TASK
Implementation
Implement line-delimited framing where messages end with \r\n. This is the approach used by Redis RESP, HTTP/1.1 headers, and SMTP.
The challenge: TCP doesn't guarantee that a full line arrives in one read. You must buffer partial reads correctly.
Implement handlers:
Request: {"type": "line_encode", "msg_id": 1, "message": "PING"}
Response: {"type": "line_encode_ok", "in_reply_to": 1, "encoded": "PING\r\n", "bytes": 6}
Request: {"type": "line_decode", "msg_id": 2, "buffer": "PING\r\nPONG\r\n"}
Response: {"type": "line_decode_ok", "in_reply_to": 2, "messages": ["PING", "PONG"], "remaining": ""}
Request: {"type": "line_decode", "msg_id": 3, "buffer": "PING\r\nPON"}
Response: {"type": "line_decode_ok", "in_reply_to": 3, "messages": ["PING"], "remaining": "PON"}Sample Test Cases
Encode a line 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":"line_encode","msg_id":2,"message":"PING"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "line_encode_ok", "in_reply_to": 2, "encoded": "PING\r\n", "bytes": 6, "msg_id": 1}}
Decode multiple complete linesTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"line_decode","msg_id":2,"buffer":"GET key1\r\nSET key2 val\r\n"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "line_decode_ok", "in_reply_to": 2, "messages": ["GET key1", "SET key2 val"], "remaining": "", "msg_id": 1}}
Hints
Hint 1▾
Messages are terminated by \r\n (CRLF)
Hint 2▾
Buffer incoming bytes until you find a complete \r\n
Hint 3▾
Handle the case where \r\n is split across two TCP reads
Hint 4▾
This is similar to how Redis RESP protocol works
Hint 5▾
Return an error for messages that exceed a maximum length limit
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
line-delimitedRESP protocolCRLFpartial readsbuffer management
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()