Skip to Content
Motoko

The client and its transports

The client owns what is the same whatever carries it: each followed session's view, folded from its events in order; its cursor, the one right after the last event it folded; its status; and the calls, with their parsed results and typed errors. A transport owns its wire format and its reconnects, and does two things:

interface MotokoTransport {
  call<M extends CallMethod>(method: M, params: CallParams<M>, signal: AbortSignal): Promise<unknown>;
  follow(sessionId: string, from: () => Cursor | undefined, listener: FollowListener): () => void;
}
interface FollowListener {
  live(): void;                      // the follow is on, from from(); again after each drop
  event(item: StreamItem): void;     // { cursor, event }
  ended(error: MotokoError): void;   // the server stopped following; nothing more comes
  dropped(): void;                   // the connection dropped; the transport follows again from from()
}

call resolves with the result as the server answered it, which the client parses, or rejects with a MotokoError, or with what the app's own code it runs throws before sending, such as httpTransport's headers and paths; once signal aborts (the client closed), it rejects with connection_closed and is not sent if it was not yet. follow asks from() for the client's cursor each time it connects, so a reconnect resumes after the last event the client folded, not the last one the transport saw. follow may throw only before it has told the listener anything: the client's follow then throws that error, and the session's next follower starts it afresh. Once it has told the listener something, a follow it cannot keep ends with ended(error). Any other carrier (Electron IPC, a test double) is a transport of the app's own.

Over a WebSocket

webSocketTransport speaks Motoko's socket protocol, whose frames @chia1104/motoko-wire/socket defines and the Cloudflare README describes: a call is a motoko:call frame answered by motoko:result or motoko:error, a follow is a subscribe call, and the server streams motoko:event frames and a motoko:ended. Frames whose type does not start with motoko: are the app's, and the transport leaves them alone.

A call made while the socket is closed is sent once it opens; one sent on a connection that closes before its reply rejects with connection_closed. A new connection follows nothing, so on every open each follow subscribes again, from the client's cursor. The transport drops a session's events until the server confirms its subscribe, so a follow started again on the same socket never mixes with the one it replaced. A follow the server ended is neither subscribed again nor unsubscribed.

Over HTTP

httpTransport makes each call a POST {baseUrl}/call with a JSON { method, params }, and answers with its { result } or rejects with its { error }. An answer that is not the handler's (the app's own refusal in resolve, a proxy's error page) rejects with forbidden for a 401 or 403, and with internal otherwise.

A follow is a GET {baseUrl}/sessions/:sessionId/events, its server-sent events read through fetch's streaming body rather than EventSource, so it sends headers (an Authorization header, say) as a call does. A headers function is the app's code: what it throws rejects a call as it is, before anything is sent, and a follow tries again after the backoff below. The transport reads the stream as the SSE spec does: lines that end in CRLF, LF or CR, comments, data over several lines, and an ended event that ends the follow. It leaves id and retry alone: the cursor is in each event's data, and the client keeps its own.

When the stream ends without ended, or the server cannot be reached, the transport follows again after a backoff (half a second at first, doubling up to 30 seconds, with jitter), sending Last-Event-ID with the client's cursor, so the server resumes after the last event the client folded. A server that cannot serve the follow now is tried again the same way: a 408, a 429, or any 5xx, such as a proxy's 502 during a deploy or a 503 lease_held while the instance's home fails over. Any other answer before the stream starts is the server's answer to the follow: a cursor it cannot honour (400 invalid_cursor), a caller it does not let (401, 403), a session that is gone (404). The follow ends with that error and is not tried again.

An app that serves Motoko from routes of its own, its controllers rather than motokoHandler, says where each request goes with paths, below baseUrl: a call's path from the call, so one carries what its params say, and a session's events' path. Each starts with /, with what it takes from the call encoded. A path function is the app's code, so what it throws rejects the call, or throws from follow, as it is, and a path that does not start with / does so as a TypeError. Either way nothing is sent, so it is not a connection_closed to retry. The requests and the answers stay the handler's: a call's JSON { method, params } answered { result } or { error } with its status, and a follow's event stream, which node's sessionEventStream and statusOf give the app's routes (see node's The app's own routes):

const transport = httpTransport({
  baseUrl: "/api",
  paths: {
    call: ({ method, params }) =>
      method === "submit" ? `/chats/${encodeURIComponent(params.sessionId)}/messages` : `/calls/${method}`,
    events: (sessionId) => `/chats/${encodeURIComponent(sessionId)}/events`,
  },
});