TASK
Implementation
Implement a protocol versioning scheme. The sender includes a protocol_version in the header. The receiver handles backward compatibility for older versions.
Protocol versions:
- v1:
{version: 1, key: string, value: string} - v2:
{version: 2, key: string, value: string|int, timestamp_ms: number, tags: string[]}
When receiving a v1 message, upgrade it to v2 with defaults: timestamp_ms = 0, tags = [].
Implement handlers:
Request: {"type": "proto_send_v1", "msg_id": 1, "key": "name", "value": "Alice"}
Response: {"type": "proto_send_v1_ok", "in_reply_to": 1, "wire_version": 1}
Request: {"type": "proto_send_v2", "msg_id": 2, "key": "age", "value": 30, "timestamp_ms": 1700000000, "tags": ["user"]}
Response: {"type": "proto_send_v2_ok", "in_reply_to": 2, "wire_version": 2}
Request: {"type": "proto_receive", "msg_id": 3, "wire_version": 1, "key": "name", "value": "Alice"}
Response: {"type": "proto_receive_ok", "in_reply_to": 3, "parsed_version": 2, "key": "name", "value": "Alice", "timestamp_ms": 0, "tags": []}Sample Test Cases
Send v1 messageTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"proto_send_v1","msg_id":2,"key":"name","value":"Alice"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "proto_send_v1_ok", "in_reply_to": 2, "wire_version": 1, "msg_id": 1}}
Receive v1 message upgraded to v2Timeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"proto_receive","msg_id":2,"wire_version":1,"key":"name","value":"Alice"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "proto_receive_ok", "in_reply_to": 2, "parsed_version": 2, "key": "name", "value": "Alice", "timestamp_ms": 0, "tags": [], "msg_id": 1}}
Hints
Hint 1▾
Include a protocol_version field in the message header
Hint 2▾
Version 1: basic key-value with string values only
Hint 3▾
Version 2: adds integer values and a timestamp field
Hint 4▾
The receiver must handle both v1 and v2 messages
Hint 5▾
Use sensible defaults for missing fields when upgrading v1 to v2
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
protocol versioningbackward compatibilitywire formatmigration
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
import sys
import json
def main():
# Your implementation here
for line in sys.stdin:
msg = json.loads(line)
print(json.dumps(msg), flush=True)
if __name__ == "__main__":
main()