Elixir
An Elixir embedding of NorthTalk, backed by the Zig Core’s wasm32-wasi reactor in Wasmex. It speaks the Message Layer and needs neither Go nor a sidecar. #963 tracks the rest of the application-facing API.
It supports Elixir 1.17 or later on OTP 27 or later, with Wasmex 0.15.1. To change this package, start with the task map.
cd impl/zig && zig build -Dtarget=wasm32-wasi --prefix ../../.cache/zig-wasicd ../elixirmix deps.getmix test # uses .cache/zig-wasi/bin/talk.wasmexamples/shop is a runnable OTP application and the getting-started guide: Elixir calls a Handler, which calls Elixir and Erlang functions, and a deferred Operation is settled later by another process.
Using it
Section titled “Using it”An Instance Owner is one process holding one reactor instance. It conducts every exchange with that instance, and can drive several Script Groups.
children = [{NorthTalk, name: MyApp.Talk}]
group = NorthTalk.new_group!(MyApp.Talk, "tenant-1", [])"pricing" = NorthTalk.load!(group, "pricing", "on total a, b\n return a + b\nend total\n", []){:ok, %NorthTalk.Result{value: value, report: report}} = NorthTalk.request(group, "pricing", "total", [1, Decimal.new("2.50")])-
Results: each call returns
{:ok, _}or{:error, error}, whereerroris aNorthTalk.HostError,NorthTalk.LoadErrororNorthTalk.ScriptError. The!variants raise it instead.deliver/4returns once the message is accepted.request/5returns once its Run ends, with therun endreport and its Fuel. -
Driving: by default the owner Pumps a Group after each delivery, one Fuel Slice per Pump. Each slice is a separate message to the owner, so other work interleaves. It Pumps again at the Group’s next deadline. With
drive: :manual, the caller callspump/2with its own Clock readings. -
Values: see
NorthTalk.Value. Numbers are integers orDecimals, and floats are refused. Text is a UTF-8 binary, normalised to NFC, and Bytes areNorthTalk.Bytes. A map is aNorthTalk.Map, in order; a plain map with at most one key is accepted on input (ADR 0092). Quantities, ranges, Paths, Instants, Civil Dates, Patterns and Host Objects areNorthTalk.*structs (a Path isNorthTalk.Path, built withNorthTalk.Path.new/1, ADR 0184), andDateTime,DateandNaiveDateTimeare accepted on input. Decoding refuses any form the encoder wouldn’t write, and never creates atoms. -
Combined request and Pump:
request_pump/5andcall_pump/4admit a message or Function call and Pump its Group once, in one exchange, under either drive. They use the binaryrequest-pump-fields-v1envelope (the contract), and are refused withinvalid valuebefore admission when the reactor doesn’t offer it. An admission refusal is{:error, error}, with no Pump. Otherwise the call returns{:ok, %NorthTalk.Pumped{pending: pending, pump: outcome}}, whereoutcomeispump/2’s result, or{:error, error}when the Pump was refused and the request is left queued.await/2waits for the pending request’s result asrequest/5would, and can be called again. A timeout is aHostErrorwith codetimeout, and the Run carries on.release_pending/1discards the result and fails awaiters withpending released, but doesn’t cancel the request.close_group/1releases a Group’s handles. Withbinary_callbacks: trueonstart_link/1(orconfig :north_talk, binary_callbacks: true), the owner also requestscallbacks-fields-v1when offered, so op, prop, effect and release needs and results use binary frames even during a JSON exchange. Other needs stay JSON. It is off by default, since it measures slightly slower than JSON for immediate callbacks (#1316). Older reactors fall back automatically.{:ok, %NorthTalk.Pumped{pending: pending}} = NorthTalk.request_pump(group, "pricing", "total", [items]){:ok, %NorthTalk.Result{value: total}} = NorthTalk.await(pending):ok = NorthTalk.release_pending(pending) -
Function Values a Script returns, or passes to a callback, are
NorthTalk.Functionhandles bound to their Group and owner.call/4calls one through its Group asrequest/5sends a message, and one can be passed back into the same Group. A handle is held untilrelease/1, or untilclose_group/1or the owner closes; there are no finalisers. Using one after that, or through another Group, is aHostError:function released,group closed,instance closedorwrong group.close_group/1acts on the Host’s side only, since the Core has no message that frees a Group.{:ok, %NorthTalk.Result{value: add2}} = NorthTalk.request(group, "pricing", "adder", [2]){:ok, %NorthTalk.Result{value: 5}} = NorthTalk.call(group, add2, [3]):ok = NorthTalk.release(add2) -
Capabilities: a module that uses
NorthTalk.Capabilitydeclares Operations, each answered by a function of the same name.define_capability/2gives it to an owner,grant/3grants some or all of its Operations with a binding, andload/4takes the Grants under the names the Script uses. Calls dispatch through the Script’s Grant, so Operations of the same name in different Capabilities never collide.defmodule MyApp.Stock douse NorthTalk.Capability, name: "stock"operation "count", args: ["text"], result: "number", cost: 1def count([sku], call), do: {:ok, MyApp.Stock.count(call.binding, sku)}operation "reserve", mode: :suspending, args: ["text"], result: "text", cost: 5def reserve([sku], call), do: {:defer, MyApp.Orders.reserve_later(sku)}end:ok = NorthTalk.define_capability!(MyApp.Talk, MyApp.Stock)grant = NorthTalk.grant!(MyApp.Talk, MyApp.Stock, binding: "warehouse-1")NorthTalk.load!(group, "orders", source, grants: %{"stock" => grant})# later, when the reservation is made::ok = NorthTalk.answer(MyApp.Talk, ref, "R-1001") -
Callbacks run in monitored Tasks, never in the owner. The owner waits up to the Capability’s
:timeout, 5 s by default, for an immediate or fire-and-forget callback, so one must not call its own owner. A suspending callback runs while the owner carries on; it returns{:ok, value}or{:error, failure}, or{:defer, ref}to settle later. Its call has no timeout of its own: it ends when settled, or when the Core abandons it at itsmax_pending, the Script’s wait limit or the end of its Run, which kills its Task or forgets its ref. A suspending callback may call the owner, but must not wait for a Run that needs its own call settled. A raise, an exit, a timeout or an unexpected result is a Host failure: the Script raiseshost error. -
Lifecycle hooks: an Operation may open or close a Capability Scope (
scope:) or be Segment-bound (segment_bound: true). A Capability with Segment-bound Operations defineseffect/2, its Segment participant’sbegin,commitandrollbackhooks, returning:ok,:failedor:unknown. Anything else, a raise or a timeout isunknown, which stops the Group witheffect state unknown.release/1, the Grant release hook, runs when a Script’s Grant stops being effective, with reason:stop,:reload,:revokeor:disable; what it returns is ignored. Hooks run in Tasks, like callbacks, and the Core’s order holds: a scope left open is abandoned by an automatic call (call.automatic), then the participant commits or rolls back, then Grants are released, all before the reply or report that follows. -
Musical clock: a Host whose Scripts keep musical time makes its clock with
NorthTalk.Capability.musical_clock/2, from awaitfunction and its:cost, defines it withdefine_capability/2, and passes a Grant of it tonew_group/3andrestore/4asmusical_clock:(the musical clock, ADR 0166). Every Script of that Group holds it under the reserved namemusical-clock, whichload/4refuses fromgrants:, and a restore re-binds a savedmusical-clockGrant to the new Group’s clock, never throughgrants:.wait 8 barscallswaitwith8 baras aNorthTalk.Quantity, a suspending call with nomax_pending, and the function answers it once that many bars have passed on the Host’s Transport. Without a clock, such a wait raisesno musical time. -
Host Objects: a
NorthTalk.ObjectKinddeclares properties, each a Shape, agetand optionally aset, with their costs, and optionally an Object Collection (count,at,find) that Scripts read aselement s of o.define_object_kind/2gives it to an owner, once;object/5makes a Host Object of it in a Group, with an id unique for its Kind there and anativeterm the owner passes to every callback, and returns itsNorthTalk.Objecthandle.object_by_id/3,set_parent/3anddispose/2act on a Group’s Objects. A handle is thetoofdeliver/4orrequest/5, andload/4takesowner:, making the Script the Object’s Owning Script, andobjects:. Callbacks run in Tasks under the Kind’s:timeout, as an immediate Operation’s do; since Elixir terms don’t change in place,nativeusually names where the state lives, such as an Agent or an entity id. The owner asks forobject-elements-v1when the reactor offers it. Objects belong to their Group, so another Group’s handle iswrong group. A Request to an Object climbs its Message Path: the owner asks forclimb-v1, waits past each Run that passes the message on, and fails the Request with aNorthTalk.ScriptErrorof outcome"unhandled"when no Handler takes it.broadcast/3sends a message to every Script that wants it, and returns its Broadcast id.decide/4anddecide_broadcast/3ask by a Decision and return aNorthTalk.Pending;await/2gives aNorthTalk.Verdict,:allowed,:vetoedor:undecided, with itsvetoes(script,run,reason) andundecidedentries, once thedecidedreport seals it.door =NorthTalk.ObjectKind.new("door",props: %{"isLocked" => [shape: "boolean", get: &MyApp.Doors.locked?/1, set: &MyApp.Doors.set_locked/2]}):ok = NorthTalk.define_object_kind!(MyApp.Talk, door)front = NorthTalk.object!(group, door, "front", entity_id)NorthTalk.load!(group, "front-door", source, owner: front){:ok, _} = NorthTalk.request(group, front, "knock", []) -
Changing code:
reload/4stops and reloads a Script, carrying its Script Variables over unlessvariables: :reset;replace_library/3does so for every Script importing a Library, all or nothing;extend/3adds names without stopping anything.stop/3stops a Script. A Run discarded by any of them fails its waiting request with aNorthTalk.ScriptErrorof outcome"discarded". -
Save and restore:
save/1returns a Group’s bytes, refused witheffects pendingwhile a scope or participant is live.restore/4makes a new Group from them in this or another owner, rebinding each Script’s Grants throughgrants:; a Grant not given restores revoked, andresolve_object:restores each saved Host Object live from its Kind and id, or disposed. Each pending call in theNorthTalk.Restoredis settled withsettle/3: an answer, a failure,:reissue, which calls its callback again, or{:adopt, ref}, settled later byanswer/3orfail/3. An automatic owner first Pumps a restored Group once every pending call is settled; any still unsettled at the first Pump fails withcall lost. Saves are per Core: only a Zig Core reads one. Grant bindings, callbacks and waiting requests are not saved, so:reports_togets the outcome of a Run that was waited on. -
Supervised groups:
NorthTalk.Groupsgives each long-lived Script Group, such as a tenant or room, its own owner and reactor instance, found by a key.start_group/4runs the application’sinit.(owner, key)in a process of its own, so loading or restoring holds up no other group, and returns once the Group is ready;lookup/2finds it only then. A failed or timed-out initialization stops everything it started. Any owner exit, a trap included, restarts the group and runsinitagain against a fresh instance, so the application chooses fresh state or its last save. Each group has its own restart budget, 3 in 5 s by default; one that exhausts it stops alone and:notifyis told. Old handles are never redirected: a call through one after a restart exits with:noproc, so reacquire the Group withlookup/2.stop_group/2releases the instance without a restart.children = [{NorthTalk.Groups, name: MyApp.Rooms, notify: MyApp.RoomWatcher}]init = fn owner, key ->with {:ok, group} <- NorthTalk.new_group(owner, key),{:ok, _} <- NorthTalk.load(group, "room", source),do: {:ok, group}end{:ok, group} = NorthTalk.Groups.start_group(MyApp.Rooms, "room-1", init){:ok, group} = NorthTalk.Groups.lookup(MyApp.Rooms, "room-1"):ok = NorthTalk.Groups.stop_group(MyApp.Rooms, "room-1") -
Lost instances: if the reactor is lost other than by a trap or a timeout (Limits and faults), such as by a malformed reply, the owner fails every waiting request with
instance lostand stops, so its supervisor can restart it.
Not offered
Section titled “Not offered”This Host speaks only part of the Message Layer:
- Function Values come with the full value set in #993. They hold only a token, so nothing about them is durable on the Host’s side.
- Standard Capabilities are not offered, except
http’sfetch(NorthTalk.HTTP).http’s server Operations aren’t offered. Thesqlitefactory isn’t offered through the Message Layer by any Host. - Revoke, cancellation, inspection, Fingerprints, Store Notification checkpoints, metering and the Host Manifest have no Elixir API yet.
The reactor
Section titled “The reactor”NorthTalk.Artifact.path/0 looks for the reactor in this order:
- The
NORTH_TALK_WASMenvironment variable. config :north_talk, wasm_path: ....- The package’s
priv/talk.wasm.
The package pins one reactor release by tag and SHA-256 in artifact.ex. mix compile fetches it into priv/ and verifies it, unless an override is set, so a consumer needs neither Go nor Zig. The Elixir reactor workflow publishes a release when a reactor-v* tag is pushed, and its digest is then pinned here. CI fails when the Zig Core’s save format differs from the pinned @save_format: a PR that changes it sets the new format, tags that commit, and pins the release in the same PR.
The compiled module is cached in :persistent_term per SHA-256. Before an owner makes any Group, hello must report the save format this package reads and its required features, or the owner refuses to start with incompatible core.
The test configuration points at the repository’s .cache/ build.
Limits and faults
Section titled “Limits and faults”- Limits:
:memory_capbounds guest linear memory,:timeoutbounds each reactor call, and:limitssets the Script limits eachload/4starts from, which its ownlimits:may override.load/4withforbid_suspension: truerefuses any possible Suspension Point in the Script ascan't suspend here, for a Host that keeps every wait in its own storage; Reload, extend, Library replacement and restore keep it (ADR 0178).NorthTalk.memory/1reports linear memory apart from the BEAM’s own. A Group out of memory under the cap fails its waiting requests without of memory. - Traps and timeouts poison the instance: the owner fails every waiting request with
instance trappedand stops with{:shutdown, :trapped}. Effects are never retried. To carry on, start a new owner andrestore/4a save kept from before. Other owners are unaffected.
Measurements
Section titled “Measurements”On an Apple M5 at aa32a4d8, through NorthTalk with the pinned reactor, from the benchmark Host’s api section:
| Path | p50 | p99 |
|---|---|---|
request/5 of an empty Handler |
112 µs | 143 µs |
| One immediate callback, inside a Run | 64 µs | 90 µs |
request/5 waiting on a deferred Operation |
320 µs | 395 µs |
The callback envelope comparison for #1315 found immediate integer callbacks 16–22% slower in fields mode. Garbage collection in the owner caused that. The #1316 re-measurement cuts the codec’s allocation to near JSON’s. It leaves immediate callbacks 1.5–2.6% slower in fields mode and property refusals about 2% faster, so JSON stays the default.
Each owner holds about 2.1 MiB of guest linear memory and 0.2 MiB of process heap after one Request. The raw-frame transport figures are in the same report: the owner and its callback Tasks add to them.
Layout
Section titled “Layout”| Path | Contents |
|---|---|
lib/north_talk.ex |
The public API. |
examples/shop/ |
The OTP example and getting-started guide. |
lib/north_talk/groups.ex |
Supervised groups: one owner per Script Group, a ready lookup by key, and a restart budget per group. |
lib/north_talk/owner.ex |
The Instance Owner: exchanges, needs, Pumps and waiting requests. |
lib/north_talk/http.ex |
The http Standard factory’s fetch: the origin binding and a buffered HTTP/1.1 and HTTPS client. |
lib/north_talk/capability.ex |
Capabilities, Grants, and the NorthTalk.Call, NorthTalk.Effect and NorthTalk.Release a callback or hook gets. |
lib/north_talk/object_kind.ex |
Object Kinds: properties, Object Collections and their declarations. |
lib/north_talk/group.ex |
Group and Library handles, a Decision’s NorthTalk.Verdict, a restore’s NorthTalk.Restored and NorthTalk.PendingCalls, and a combined call’s NorthTalk.Pumped and NorthTalk.Pending. |
lib/north_talk/binary.ex |
The Request/Pump, settlement and callback binary fields envelopes, converted to and from the JSON form the owner reads. Tags and fields come from the generated envelope catalogue; reshaping stays in the codec. |
lib/north_talk/generated/envelope.ex |
Envelope tags, ordered field kinds, Reports and feature names generated from spec/data/envelope.toml. |
lib/north_talk/value.ex |
Value conversion. |
lib/north_talk/types.ex |
The value structs, and NorthTalk.Function handles. |
lib/north_talk/transport.ex |
The transport behaviour: one frame in, one frame out. |
lib/north_talk/transport/wasi.ex |
The reactor in Wasmex: compiling, instantiating, guest linear memory and talk_buffer/talk_send. |
lib/north_talk/artifact.ex |
The pinned reactor release, where the reactor is found, and what this Host requires of it. |
lib/mix/tasks/compile.north_talk_reactor.ex |
The compile step that fetches and verifies the pinned reactor. |
The Elixir benchmark Host measures this transport.