Engine Protocol
The app never links the C++ core. It starts shapelogic_engine as a child
process and talks to it over the process’s standard input and output. The
command line tool and the contract tests drive the same engine, and any
language that can write a line of JSON can too.
The protocol is settled in two decision records,
docs/decisions/0003-engine-process-json-rpc.md and
docs/decisions/0012-engine-protocol.md. The method reference is
docs/API.md, generated from the schema in api/.
Messages
Section titled “Messages”Each line on the engine’s stdin is one JSON-RPC 2.0 request. Each line on its stdout is one reply or one notification. Logs go to stderr.
{"jsonrpc":"2.0","id":7,"method":"solve.start","params":{"problem":"p1","options":{"solver":"classic","disassemble":true}}}{"jsonrpc":"2.0","id":7,"result":{"revision":42}}{"jsonrpc":"2.0","method":"document.changed","params":{"revision":42,"what":["problems","solutions"],"shapes":[],"problems":["p1"]}}- Parameters are always by name, in an object. A missing, mistyped or
unknown field is refused, as the schema says (
additionalProperties: falseeverywhere). - Items are named by ids that survive reordering: shapes
s7, colorsc2, problemsp1, solutionssol42, rod setsr1, playback handlespb1, explorersax1andmx1. - A request without an
idis a notification: it runs and gets no reply. - Errors carry JSON-RPC’s code, a message and
data.errc, one of the core’s error kinds:not_found,invalid_argument,invalid_state,unsupported,io_error,parse_error,internaland so on. Every method’s schema entry lists the errors it can return. - Limits: a line of at most 64 MiB, nested at most 64 deep; batches (arrays) are refused. A malformed line is answered, never fatal.
The first call is always engine.hello with the protocol the client speaks
(this version: 1). The engine answers with its name, version and the
protocol it will speak, or refuses one it does not know.
Binary frames
Section titled “Binary frames”Meshes and pose tracks are not JSON. The engine announces a frame with a notification, then writes exactly that many raw bytes, then the reply that refers to the frame:
{"jsonrpc":"2.0","method":"frame","params":{"frame":3,"bytes":245760}}<245760 raw bytes>{"jsonrpc":"2.0","id":9,"result":{"frame":3, ...}}A frame holds typed arrays at offsets that are multiples of four; the reply
describes them. On the app’s side framing.ts splits stdout into lines and
frames, and frames.ts gives typed-array views over the bytes without
copying. The renderer never parses a frame by hand.
Events
Section titled “Events”Events are notifications the engine sends on its own.
| Event | When |
|---|---|
document.changed |
after a call that changed the document, and when background work ended; carries the new revision, what changed (shapes, colors, problems, solutions, notes, rodSets) and which ids |
solve.state |
a problem’s solve moved to another state |
solve.progress |
at most four times a second while a solve runs, and once when a run ends |
solve.solutionsAdded |
the problem’s saved list changed; carries solutionsVersion so a client knows whether to page again |
solve.error |
a run ended in error, with the failure |
solution.analyseProgress, solution.analyseEnded |
an analysis of saved assemblies |
The engine’s main thread finds out about background work by polling: the
run loop in engine/engine.cpp waits for a line for 50 ms while a solve
runs (500 ms otherwise), then calls pollEvents in engine/events.cpp,
which asks each watched problem’s session for its state and progress.
The rules
Section titled “The rules”- Requests run one at a time, in order. The main thread of the engine
runs every request and alone touches the document. Solves run on
threads of their own and are read through
readProblem(). - A reply comes before the events it caused. After
solve.startreturns{revision}, thedocument.changedfor that revision follows, then the poll’ssolve.stateandsolve.progress. A frame comes before the reply that refers to it. - The revision never goes back. Every change of the document is a new
revision. A new document counts on from the old one. The app waits for
a mutating call’s revision before it acts on what the call made
(
Store.whenRevision,Edits.mutate). - A run’s end is its revision. The last
solve.stateof a run (finished,paused,errororidle) comes before thedocument.changedthat takes the run’s results in. The app treats the run as over only at thatdocument.changed. invalid_statemeans “pause first”. While a solve is active, the shapes it reads and the lists of shapes, colors and problems are frozen. The app shows the refusal as “Pause the solve first” and never retries.- The engine is the truth. The app never computes what the engine can
answer: cells, fits, counts, meshes and sort orders are all read from
it.
solution.pagesorts and pages the solutions; the app holds only a mirror, refreshed bydocument.changed.
From schema to code
Section titled “From schema to code”The schema in api/*.json is the single source. api/README.md describes
the files and the subset of JSON Schema they use. Adding a method takes
five steps:
- Its entry in the area’s schema file.
- The handler in
engine/methods_<area>.cpp, registered in that file’sadd…Methodsfunction. - A call in
tests/contract/test_engine.py; the coverage check fails for a method never called with success. python3 api/gen_api_md.pyto regeneratedocs/API.md.just app-gento regenerate the app’s types inweb/src/engine/api.generated.ts.
Trying it by hand
Section titled “Trying it by hand”The engine reads stdin, so a shell can drive it:
just build releaseprintf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"engine.hello","params":{"protocol":1}}' \ '{"jsonrpc":"2.0","id":2,"method":"document.open","params":{"path":"tests/data/puzzles/PelikanBurr.xmpuzzle"}}' \ '{"jsonrpc":"2.0","id":3,"method":"problem.fit","params":{"problem":"p1"}}' \ | build/release/engine/shapelogic_enginetests/contract/engine_client.py is a small Python client that does the
same with replies matched to requests; the contract tests are built on it.
How the app crosses the process boundary
Section titled “How the app crosses the process boundary”In the app there is one more hop: the window’s page is sandboxed and
cannot start processes. The main process owns the engine (EngineHost),
and the page talks to it over Electron’s IPC:
renderer page preload main process engineEngineProxy.call ──sl:call──▶ window.sl.send ──ipc──▶ serveEngine.receive ──▶ EngineClient.call ──stdin──▶ ◀sl:message─ onMessage ◀─ipc── post(reply/event) ◀── OrderedInbox ◀─stdout──serveEngine in web/src/engine/serve.ts checks that the method is one
of the schema’s, refuses a call naming a file the window was never handed
(path-grants.ts), and forwards the rest. Replies, events and the engine’s
status come back on one ordered channel, so the page sees the same order
the engine produced.