ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/messenger/tasks/task-1-3-1-typed-schema
TASK

Implementation

Raw JSON is just strings. A typed schema wraps the raw message in classes with explicit fields, validation, and serialization methods — making it impossible to accidentally send a malformed message.

Implement a Message class with to_json() / from_json() methods and a MessageBody class. Your node handles init, echo, and a new validate message type:

{ "type": "validate", "msg_id": 1,
  "payload": "{\"src\":\"a\",\"dest\":\"b\",\"body\":{\"type\":\"x\"}}" }
-> { "type": "validate_ok", "in_reply_to": 1,
    "valid": true, "fields": ["src", "dest", "body.type"] }

The validate handler parses the JSON string in payload and reports which top-level and nested fields are present. If the payload is not valid JSON, return valid: false with an empty fields list.

Sample Test Cases

Init and echo with typed schemaTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"echo","msg_id":2,"echo":"typed"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "echo_ok", "echo": "typed", "in_reply_to": 2, "msg_id": 1}}
Validate a well-formed payloadTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"validate","msg_id":2,"payload":"{\"src\":\"a\",\"dest\":\"b\",\"body\":{\"type\":\"x\"}}"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "validate_ok", "valid": true, "fields": ["src", "dest", "body.type"], "in_reply_to": 2, "msg_id": 1}}

Hints

Hint 1
Define a Message class with src, dest, and body fields
Hint 2
Body should have type, msg_id, and in_reply_to fields at minimum
Hint 3
Implement to_json() and from_json() methods for serialization
Hint 4
Validate field types during deserialization
Hint 5
Handle missing optional fields with sensible defaults
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

serializationdeserializationschema designtype safety
main.py
python
Model Message Format with Typed Schema - The Messenger | Build Distributed Systems