3/27
Part 1 of 7 · Messages instead of callsLearn and do

A message is a call cut in two

On one machine, a call waits for its answer. Across machines, nothing waits. send(to_id, message) puts the message in the network's queue and returns at once. Later, maybe much later, the network calls receive(from_id, message) on the other machine. That is the sendAsyncMessage and receiveMessage pair from the report.

Here is a machine that tells the time to whoever asks:

# (to, message) for each send
outbox = []

def record(to: int, message: tuple) -> None:
    outbox.append((to, message))

class Clock:
    """Answers the time to whoever asks."""

    def __init__(self, node_id: int, send) -> None:
        self.node_id, self.send = node_id, send

    def receive(self, from_id: int, message: tuple) -> None:
        if message == ("time?",):
            self.send(from_id, ("time", 12))

clock = Clock(8, record)
print(clock.receive(2, ("time?",)))
print(outbox)
None
[(2, ('time', 12))]

Two things changed from a call:

  • The answer goes out through send, addressed to from_id. A handler's return value goes nowhere, because the network calls receive and throws away what it returns. That is why the first line prints None.
  • The machine learns who asked from from_id. Nobody told it in advance.

record is a fake send. It writes each message down instead of delivering it. That's how you test one handler with no network at all: call receive yourself and read what it tried to send.

Each message here is a tuple whose first item names its kind: ("ask",) asks for a count, and ("answer", n) carries one. In an interview you can pick any format, as long as you say it out loud before you write the handlers. The tests here expect these two.

The editor holds Leaf, a machine with no children, and the same record. Write Leaf.receive: when an ask arrives, it sends an answer with its count, 1, back to the machine that asked.