@kolu/surface-map reference
A dynamic keyed map of remote surfaces: one entry surface, typed once, keyed at
runtime, served as one. @kolu/surface-map depends only on @kolu/surface, and
its API lives on three public subpaths, the declaration, the server and the
client, plus two leaves.
Declaring, serving and connecting a map
Three calls build the map, back it with data, and consume it.
| Export | Subpath | What it is |
|---|---|---|
defineSurfaceMap({ key, entry, codec, failure, connection?, entriesClient?, name?, siblings? }) | . | Builds a SurfaceMap from a key schema, an entry surface and a key codec. |
SurfaceMap | . | The declared value: the wire group, the tag prefix and the membership spec. |
serveSurfaceMap(map, registry) | /server | Backs the map with a MapRegistry; returns { group, handlers, dispose }. |
connectSurfaceMap(map, transport, opts?) | /client | Consumes the map; returns a SurfaceMapClient with the Solid useEntry. |
ConnectSurfaceMapOptions<Key> | /client | The optional third argument of connectSurfaceMap. |
testMembershipId() | /testing | Mints a branded MembershipId for fixtures. |
EvidenceLine / EvidenceLineSchema / FailureEvidence / FailureEvidenceSchema | /evidence | The failure-evidence vocabulary, also re-exported from .. |
defineSurfaceMap({ key, entry, codec, failure, connection?, entriesClient?, name?, siblings? })
Builds a map from a key schema, an entry surface and the key’s codec. It returns
a SurfaceMap.
| Option | Meaning |
|---|---|
key | The key schema. Its decoded type is Key, which can be any validated value. |
entry | The entry Surface<ES> that every key serves. |
codec | The key’s string codec. |
failure | Required. The schema for the domain failure value. |
connection? | The schema for the fine per-entry connection payload (SR9). |
entriesClient? | The client error policy for the membership collection (SR11). |
name? | The sibling key the map is mounted under in a combined surface. |
siblings? | Nested sibling surfaces, served per key. See Nested siblings. |
- The
keyschema need not be a branded string. kolu’sHostKeyis a discriminated-sum object. failurefixes the domain failure value, andFailureis inferred from it, with no explicit type args.connectionis carried on the live arms, validated but never enumerated, likefailure.nameis kolu’s"padi"or drishti’s"hosts". It decides the map’s owntagPrefixat declaration time and drives the client’s transport slice, so no stringly key is written at any connection site.entriesClientis the app-typed client error policy (ClientCollectionPolicy<EP>), threaded ontoentriesSpec.client, so a map-membership subscription failure reaches the app’sconnectSurfaceMaponClientError. ItsEPis inferred from the value and defaults tonever, so a policy-free map keepsentriesSpec.clientunfillable.- The membership collection has no per-key origin, so its interpreter fires origin-free.
- There is no matching
evidenceoption. Failure evidence is a fixed structural type this package owns, not a domain value to parameterize.
const HostKeySchema = Schema.String;
const identityCodec: KeyCodec<string> = { encode: (k) => k, decode: (s) => s };
// The domain failure schema validates the value a failed entry publishes — a
// failed member cannot exist without one (there is no fabricated fallback cause).
const hostFailureSchema = Schema.Struct({ reason: Schema.String });
type HostFailure = typeof hostFailureSchema.Type;
const hostMap = defineSurfaceMap({
key: HostKeySchema,
entry,
codec: identityCodec,
failure: hostFailureSchema,
});
SurfaceMap
The declared value:
{ keySchema, entry, group, tagPrefix, name?, entriesSpec, codec, siblings }.
groupis the key-folded wire group: oneRpcper entry-member verb, with a canonical-stringmapKeyfolded into its payload, plus the two unfoldedentriesmembership members.- A host that serves this map merges that group into its own. There is no second “fragment” value to splice and nothing to cast, because a tag carries its own route.
tagPrefixis"surface/"for a root-served map and"surface/<name>/"for a named one. Both the server’s handler keys and the client’s re-tagging read it off the value, so there is one authority.entriesSpecis the membership collection’s wire spec, always string-keyed.- The domain failure schema is the
failureargument given todefineSurfaceMap, embedded inentriesSpec.schemaand theentries.getsuccess schema, so there is no separatefailureSchemafield.
serveSurfaceMap(map, registry)
Backs the map with a MapRegistry. It returns
{ group, handlers, dispose }.
- It stamps a fresh
membershipIdwhen a key enters membership, drops it when the key leaves, and publishes it on thewarming,connectedandfailedarms alike. - Its
statusOfseam states a fault’s emptyevidenceonce, exactly as it already supplies the fault’skindandmembershipId. - It delivers a removal and a same-key re-add as two non-coalesced membership events.
connectSurfaceMap(map, transport, opts?)
Consumes the map and returns a SurfaceMapClient.
transportmust be the branded parent handle (for exampleconn.transportfromconnectSurfaces) or an in-processdirectDispatch. Any other wire dispatch throws.- The scoping key derives from
map.name: there is nosiblingKeyargument, the key comes from the declaration. - A named map is re-tagged onto
surface/<name>/…after the half-open guard, so it inherits the parent’s watchdog. A nameless map is served at the transport root and not re-tagged. - Scoping is a tag rewrite over the resolved dispatch, never a re-wrap of the transport value, so no step can strip the half-open brand.
- Pass
optswhenever the entry surface carries a policy: a declared policy with no interpreter throws at construction.
ConnectSurfaceMapOptions<Key>
The optional third argument of connectSurfaceMap. Its
onClientError?: (policy, err, origin?: { key: Key }) => void is the app’s client
error interpreter, the keyed-map counterpart to connectSurfaces’
onClientError (see the
core reference).
- A map is where a
{ key }origin exists, so this interpreter carries one, unlike the origin-free base interpreter. - A per-key entry member’s declared
client.onErrorfires withorigin = { key }, injected by the per-key client builder, which holds the decoded key. - The membership
entriescollection has no per-key origin, so it fires withoriginomitted. - An origin-requiring policy arm is therefore only reachable where the key
exists, and the base
buildSurfaceClientstays origin-agnostic.
testMembershipId()
Mints a branded MembershipId for fixtures. It is the test-only subpath, and
tests use it rather than a literal.
EvidenceLine / EvidenceLineSchema / FailureEvidence / FailureEvidenceSchema
The failure-evidence vocabulary. It sits on the schema-only /evidence leaf and
is re-exported from ., so a consumer that must not pull the group builder into
its bundle imports the leaf.
FailureEvidence = readonly { source: "local" | "remote"; line: string }[]: the retained output tail of the episode that failed.EvidenceLine.sourcesays where the line came from."local"is the serving process’s own output (provisioning, lifecycle chatter),"remote"is the far end’s forwarded output.- The source is a field, never an in-band
[local]prefix a reader would have to parse back off the string. FailureEvidenceSchemaandEvidenceLineSchemaare module consts, not functions of a domain schema.@kolu/surface-remote’sLogEntryisEvidenceLineand itsLogEntrySchemaisEvidenceLineSchema, so that package’sConnectionInfoSchema.logvalidates the same line vocabulary rather than a re-declared twin.- Evidence reaches the map’s wire through the one door
entryStatusSchemaowns. @kolu/surface-remote’sSessionState.logis structurally exactlyFailureEvidence, so the producer passes its retained tail straight through, with no injection and no second evidence pipe.
Nested siblings
An entry may carry whole sibling surfaces beside the entry surface: a second daemon the entry’s own socket already serves, re-served through the map and addressed per key.
siblings: { odu: oduSurface }makes every member of that surface reachable asentry(host).odu.streams.checkout.use(…), typed from odu’s own spec.- A map whose
siblingsis absent mints not one extra tag. - A sibling is declared as a whole
Surface, not as a spec fragment, because it is a different program’s contract with its own release cadence and version. - Why: Why a sibling is a whole surface.
| Entry | What it covers |
|---|---|
| The sibling tag grammar | How a sibling’s wire tags nest, one segment deep, and where the re-tag derives from. |
| What a sibling face carries | The six subtrees a sibling face is, and what stays the entry’s. |
| Sibling names that are refused | The two keys refused at declaration, and the reserved name that is not. |
The sibling tag grammar
The grammar is one segment of nesting, no more.
| Member | Tag |
|---|---|
An entry member of a map mounted as padi | surface/padi/<member>/<verb> |
| A sibling member of that map | surface/padi/<sibling>/<member>/<verb> |
| The same sibling member upstream, on the entry’s own socket | surface/<sibling>/<member>/<verb> |
- Upstream, that daemon is a plain sibling of its host surface, so the map hop is a re-tag between the two.
- The re-tag derives from the framework’s one sibling rule applied twice
(
mapSiblingTagPrefix), rather than string surgery. - Both halves of the rewrite live in the solid-free
./define, beside the walk that mints the tags, so the contract, the server and the client cannot drift.
What a sibling face carries
Everything else about a sibling member is an entry member’s: it folds the same
mapKey into its payload, routes to that key’s own session, and rides the same
membership gates.
- A sibling face is the six bound subtrees (
cells,collections,streams,events,procedures,rpc) and nothing more. stateandclockstay the entry’s. Membership and the clock offset are facts of the key, and a surface served under that entry has no second membership of its own.- Under
useEntrya sibling’s subscriptions re-key by exactly the entry’s rule ({enc, membershipId}). - The per-key clients, the entry’s and each sibling’s, are cached and disposed as one value, never as a parallel cache that could outlive the entry’s.
Sibling names that are refused
Two names are refused at declaration, where the name is the defect.
- A sibling key that is not a legal tag segment, by the same check
composeSurfaceContractsapplies at the same seam. - A sibling key that collides with an entry face member (
ENTRY_FACE_MEMBERS:cells,streams,state, and the rest), which would shadow the entry’s own subtree and hand a consumer the sibling where it asked for the entry. - The reserved
entriesname is not refused for a sibling’s member. A sibling’s members live one segment below the map’s membership collection, so a sibling that publishes its ownentriescollection cannot shadow the map’s.
The client
SurfaceMapClient exposes the membership authority, transport liveness, the key
codec, and two lenses onto an entry.
| Member | Returns |
|---|---|
entries | ReadOnlyBoundCollection<Key, EntryStatus> — the single membership authority. |
live | Accessor<boolean> — resolved transport liveness for the membership strip. |
codec | KeyCodec<Key> — the one key-identity authority. |
entry(key) | Entry<ES> — the pure point lens (no owner, no I/O, total). |
useEntry(keyAccessor) | Entry<ES> — the Solid lens; throws ownerless. |
dispose() | Tears the client down. |
scopedByEntry(client, active, build) | Per-key state retained across switches, from /client. |
watchByEntry(client, cell, items, onRaise) | Per-member attention, watched eagerly, from /client. |
entries
ReadOnlyBoundCollection<Key, EntryStatus>, the single membership authority. It
is read-only: the map server is the sole writer, so there is no client upsert
or delete.
Its value type is ObservedEntryStatus:
every value it hands out has already been through floorOnLiveness.
live
Accessor<boolean>: resolved transport liveness, for the membership strip.
entry(key)
Entry<ES>, the pure point lens. It takes no owner, does no I/O, and is total.
It is a partial application of the key: a per-key SurfaceClient<ES>, cached by
the entry’s {encodedKey, membershipId} identity, so two views of one live member
share one upstream subscription. The lens itself stays owner-free, and an
imperative call reads the pending identity and routes identically by encoded key.
An Entry<ES> carries cells / collections / streams / events /
procedures (the same bound hooks a single surface has), one named face per
declared nested sibling (entry.odu.…, see
Nested siblings), plus:
| Member | Returns |
|---|---|
procedures | The entry’s declared procedures, bound and typed from the spec. |
rpc | The raw member face (rpc.surface.<member>.<verb>), typed unknown per leaf. |
clock.toLocal(remoteMs) | A host-stamped epoch in the local clock: number | null. |
state() | EntryState — a total fold over entries, never nullable. |
useEntry(keyAccessor)
Entry<ES>, the Solid lens. It throws when called outside a reactive owner.
- It re-keys its reactive subscription whenever the entry’s
{encodedKey, membershipId}identity changes. - An active-key switch (the encoded key changes) disposes the old key’s subscriptions, and the new key’s populate synchronously.
- A same-key membership re-add or authority restart (a new
membershipIdfor the same encoded key) re-keys too. - It canonicalizes its accessor’s key by its encoded string, so a same-key re-decode of the same membership reads as a no-op, never a re-key.
- The
{encodedKey, membershipId}re-key is the reactive.use()lifetimeuseEntrydrives.
const entries = app.entries.use(); // the ONE membership authority (the chips)
const hosts = entries.keys(); // each chip's key
const status = (host: string) => app.entry(host).state().kind; // warming/connected/failed
const active = app.useEntry(activeHost); // re-keys on switch; old subs dispose
const load = active.cells.load.use();
const processes = active.collections.processes.use();
dispose()
Tears the client down.
entry(key).procedures
The entry’s declared procedures, bound and typed from the entry spec:
entry.procedures.<ns>.<verb>(input).
- It is a narrow mapped type over the entry spec’s
procedures, so it types straight from the declaration with no cast. It also dodges the union-budget overflow (TS2590) that a second precise mapped type over an abstract entry spec would trip. - The key-injecting dispatch folds
{ mapKey }into every call and rewrites the tag onto the map’s own prefix, so the caller never passes the key. - A procedure’s declared error schema (
ProcedureSpec.error) rides the folded member, so a tagged error raised behind the map’s keyed proxy arrives at the outer client with its_tagand data intact. The map hop never demotes a declared error to a defect. - A call on an absent key is a typed rejection (
MapKeyUnknown), the one-shot twin of a sub’s typed stream-end.
entry(key).rpc
The raw member face, rpc.surface.<member>.<verb>. It is the addressing-layer
escape hatch only, and stays typed unknown per leaf.
- A declared procedure never needs it.
- The map folds no reserved
system/*member, so per-entry liveness rides theentriesauthority instead, and reaching asystem/*member throughentry.rpcfails at the map hop.
// Every declared procedure rides `entry.procedures.<ns>.<verb>`, bound and typed
// straight from the declaration — NO cast. (`entry.rpc` is the STRUCTURAL member
// face, reserved for the `system.*` members plus the escape hatch.) The
// key-injecting dispatch folds `{ mapKey }` into every call, so the caller never
// passes the key.
const kill = (
active: Entry<typeof entry.spec>,
pid: number,
): Effect.Effect<{ ok: boolean }, unknown> =>
active.procedures.proc.kill({ pid });
entry(key).clock.toLocal(remoteMs)
Reprojects a host-stamped timestamp into the local clock through the entry’s
measured offset: remoteMs − offset. It returns number | null.
- It returns
null, never a silent identity, whenever the entry has no measured offset:warming,failed,unobservableandnot-a-member. - A
connectedentry whoseclockOffsetis stillnullalso readsnull, since the link is live but the offset is not yet probed. Readiness is decoupled from the offset. - The
number | nulltype forces the caller to render a pending ”—” rather than fall back to the raw remote value. - It reads only
.kind, never.failure, and folds the membership collection, so it re-answers as the entry connects.
entry(key).state()
EntryState = ObservedEntryStatus | { kind: "not-a-member" }: a total fold over
entries, never nullable. See Entry status.
scopedByEntry(client, active, build)
Per-key client state, retained across key switches. It is the retained-owner dual
of useEntry, and watchByEntry is its eager twin. Where useEntry disposes the
old key’s world on every switch (right for cheap wire subscriptions), this keeps
the focused tile, the camera or a per-host view posture, so switching hosts
restores the world you left.
scopedByEntry(client, active, build) → { active(): T | undefined, get(key): T | undefined }
active: Accessor<K | null>is app policy.nullmeans nothing is selected (drishti’s fleet grid; kolu never).build(key, ctx)runs once per key on its first activation, and its return value is that key’s owned world.ctx.isActiveis anAccessor<boolean>, so the active-only discipline (WebGL release and re-acquire, centre-on-active) lives inside the owner.- Lifetime is
entriesmembership, not the wire. An owner is built lazily, so a never-visited background host costs nothing. It is retained across every switch-away, and disposed the instant its key leavesentries. - A removed-then-re-added host is a fresh member: lazy again, never resurrected.
active()returns the active key’s world, orundefinedfor both anullactive and an active key that is not a current member (a removal race, where a dev-modeconsole.warnnames the vanished key).get(key)is a background peek at any key’s world (W5 attention rollups) that never creates an owner. It returnsundefinedwhen the key was never activated or is not a member.- It throws when called outside a reactive owner, because it holds a
keyArrayof per-key roots that must be disposed with the app. - Keys are folded to their canonical wire string through
client.codec, not compared by===: two logically-equal keys from independent decodes need not be reference-equal. - It is built over
@solid-primitives/keyed’skeyArray, keyed by membership.
// Per-host CLIENT state whose lifetime is `entries` MEMBERSHIP — the retained
// dual of `useEntry`'s dispose-on-switch. An owner is built LAZILY on a key's
// first activation, RETAINED across every switch-away, and DISPOSED the instant
// its key leaves `entries` (a removed-then-re-added host is a FRESH member).
const scopes = scopedByEntry(app, activeHost, (host, ctx) => ({
tiles: new Map<number, string>(), // this host's OWN state — plain, per-host
focusedPid: createSignal<number | null>(null),
isFocused: ctx.isActive, // active-only discipline lives INSIDE the owner
label: host, // the key is in scope for whatever the owner builds
}));
scopes.active(); // the ACTIVE host's world: `T | undefined` (null / vanished)
scopes.get("web-01"); // a background peek at ANY key — never CREATES an owner
watchByEntry(client, cell, items, onRaise)
Per-member attention, watched eagerly. It shares scopedByEntry’s membership
kernel (codec identity, the entries view, retained-per-key roots disposed on
membership exit), but every member gets a root the moment it joins, because a
background host is the one you need to hear from.
watchByEntry(client, cell, items, onRaise) → { get(key): { kind: "live" | "stale"; value } | undefined }
cell(entry)selects the per-entry cell to watch (e => e.cells.urgency): a get-onlyWatchableCell<A>whose.use()yields the current value and the rawSubscription, whoseupdatedcarries the change pairs.items(value)extracts stablePropertyKeyids from the cell value (v => v.awaitingIds). Stability is the app’s one obligation, and it is what makes “same item, not a new one” decidable.- Ids are
string/number/symbol, never objects. The set-diff compares by value, so object ids rebuilt fresh per frame would compare by reference and re-raise every frame. An object-iditemsis a compile error. onRaise(key, raised, value)fires for newly-raised ids. Raise detection is a pure set-diff over the framework’supdated{ prev, next }pairs:items(next) ∖ items(prev).- The change-iff-fired law upstream (see
Subscription.updated) is what makes a plain set-diff trustworthy: no hand-held previous frame, no frame classification, no per-window memory.
Reading a watched member
get(key)is a point read:{ kind: "live" | "stale"; value }, orundefinedwhen the key is not a member or has no frame yet. A mirror stays silent until the authority speaks (see @kolu/surface-remote).livemeans our link to the host is up and connected, and this cell’s own subscription is neither errored nor ended.- An errored or ended cell reads
stale, so its last value dims rather than lying live and a consumer never counts frozen data.stalealso holds the last value under a down link. - There is no
total(): aggregation is app policy, so the watcher hands facts and each app folds. kolu sums awaiting terminals across live hosts, and drishti counts hosts in trouble. - It throws when called outside a reactive owner, because it holds a
keyArrayof per-key roots that must be disposed with the app.
Entry status
The per-entry status types. EntryStatus is what the wire carries; the rest are
what a client reads.
| Export | Subpath | What it is |
|---|---|---|
EntryStatus<Failure, Conn> | . | The published per-entry status: warming, connected or failed. |
MembershipId | . | The branded, never-reused identity of one membership episode. |
EntryState<Failure, Conn> / ObservedEntryStatus<Failure, Conn> | . | The total client read, and what a client can honestly say. |
UnobservableEntry | . | The client-only arm, minted by the liveness floor. |
FailureRecord<Failure> | . | A failure and its evidence as one value. |
isSettling(state) | . | True for warming and unobservable. |
EntryStatus<Failure, Conn>
The status the map publishes for one key.
// `Conn` (SR9): the fine per-entry connection payload, carried on the LIVE arms and
// parameterized like `Failure` — the map validates it against its own `connection`
// schema, never enumerating it. It is the ONE authority the coarse `kind` (the dot) and
// the fine word both derive from; optional, so a connection-less map omits it. The
// `failed` arm carries none at all — see the note on that arm below.
type EntryStatus<Failure = unknown, Conn = unknown> =
// `membershipId`: opaque, never-reused per-add identity — a BRANDED `MembershipId`
// (an empty/fabricated bare string is a compile error), minted only by
// `serveSurfaceMap` / the wire decode. Clients key cached owners on
// `{encodedKey, membershipId}`, so a same-key re-add / authority restart rebuilds.
| { kind: "warming"; membershipId: MembershipId; connection?: Conn }
| {
kind: "connected";
membershipId: MembershipId;
clockOffset: number | null; // own-clock offset; null = not-yet-measured
connection?: Conn;
}
// No `connection` on this arm — deliberately. The failed entry's live word would be
// the same frame `evidence` was pinned from, so `connection?.log` here was a second,
// floorable copy of the tail. Removing the field makes that read a compile error.
| {
kind: "failed";
membershipId: MembershipId;
failure: Failure; // schema-valid domain failure
evidence: FailureEvidence; // the retained output tail that EVIDENCES it
};
- Absence from
entriesis “not a member”. There is noabsentarm, because a collection already expresses absence by not carrying the key. Client reads stay total through an explicit{ kind: "not-a-member" }value, which the wire never carries. - Every arm carries a
membershipId. Failureis a type parameter. It defaults tounknownand is inferred from the map’sfailureschema, so a domain instantiatesEntryStatus<PadiEntryFailure>at its own map and.failurenarrows there. The package carries the discriminant, never the enumeration.- The framework fixes only the shape, not the fields.
failureis whatever the map’sfailureschema (WireSchema<Failure>) accepts: a bare string, a code-only object or a discriminated union are all valid. - The package fixes only that
failureis a sibling field on thefailedarm, never a secondkind, validated by that schema.
The projection contract
Status is a projection of the resolved session’s state, never a second writer.
| Session state | Published arm |
|---|---|
copying / connecting | warming |
connected | connected |
A disconnected carrying a standing domain failure, or a terminal failed | failed |
A plain transient disconnected, with no specific failure | warming |
warming means in motion, and self-heals: an unreachable box retrying at backoff
is warming, not failed. failed means it needs intervention.
Conn, the fine connection payload
Conn (SR9) is carried on the warming and connected arms. It is optional and
inferred from the map’s connection schema, exactly like Failure.
- The package carries
state.connectionand validates it against that schema, never enumerating what a domain’s connection states are. - It is the one authority both the coarse dot (
kind) and the fine word derive from.serveHostMapproduces both from the sameSessionStateframe in one projection. - A consumer reads the word off the same entry it reads the dot from
(
state().connection), never a second subscription. - A map with no
connectionschema simply omits the field. - The
failedarm carries noconnectionat all. - Why: Why the connection word and the dot have one source.
The failed arm
It carries a schema-valid domain failure value, validated by the map’s own
failure schema, not a loose object. It also carries that failure’s evidence,
and the evidence is required.
- padi’s
PadiEntryFailureis aSchema.UnionofSchema.Structs discriminated on a structuralcauseliteral, each arm carrying its humanreason. Thecontract-skew-refusedarm additionally carries a typedrunning/expectedversion pair. - A consumer therefore reads
state.failure.causeandstate.failure.reason(and.running/.expectedon the skew arm) with full narrowing. - The
reasonfield is padi’s own convention, a human string never parsed for control flow, not a framework guarantee. A domain whose schema carries noreasonis equally well-formed. - A failed status without
evidencefailsentryStatusSchema, so “a reason without its evidence” cannot be decoded off the wire. - The failure and its evidence together are a
FailureRecord<Failure>. floorOnLivenesstakes the live arms offconnectionentirely over a dead link while passing the failure record through, so evidence survives the floor with the reason it belongs to.entry.connection?.logon a failed entry does not compile.[]is a real value with one meaning, that the failure genuinely produced no output. It is minted only by the seam that knows, never as a fallback for “we could not see it”.- Why the pairing is a shape rather than a convention is the explanation page’s job.
MembershipId
The identity of one membership episode. It is a branded MembershipId, not a
bare string:
Schema.String.check(Schema.isMinLength(1)).pipe(Schema.brand("MembershipId")).
serveSurfaceMapstamps an opaque, never-reusedcrypto.randomUUID()when a key enters membership, drops it when the key leaves, and publishes it on thewarming/connected/failedarms alike.- The client keys every cached per-key owner on
{encodedKey, membershipId}, so a same-key remove and re-add rebuilds subscriptions, with no hand-rolled generation rearm. - An authority restart does the same: the id map is per-server-instance, so every member gets a fresh id and none is reused across a restart.
- It is framework identity, not something a display consumer reads. Display
consumers switch on
kindand readfailureorclockOffset. - An empty
""or a client-fabricated id is a compile error, because an opaque never-reused identity is unspellable by a consumer (P4). - It is produced two ways:
serveSurfaceMap’s mint (decodeMembershipId(crypto.randomUUID()), the one sanctioned decode, which throws on an empty string) and the wireentryStatusSchemadecode, the one boundary a status is decoded through. - The brand is erased at runtime (the value is the plain string), so keying and serialization are unchanged.
- Tests mint one through the
testMembershipId()helper on the@kolu/surface-map/testingsubpath, never a literal. - The transient pre-frame gap (a key seen in the membership keyset before its
first status frame) uses the single sanctioned
PENDING_MEMBERSHIP_IDmarker, which is display-only and never keyed against.
EntryState and ObservedEntryStatus
EntryState<Failure, Conn> = ObservedEntryStatus<Failure, Conn> | { kind: "not-a-member" },
and ObservedEntryStatus<Failure, Conn> = EntryStatus<Failure, Conn> | UnobservableEntry.
- Both live in the solid-free contract module, so a node consumer re-exports them type-only.
EntryStatusis the published (wire) type.ObservedEntryStatusis what a client can honestly say, and it is the value type of the client’sentriescollection. Every value that collection hands out has already been throughfloorOnLiveness.
UnobservableEntry
The client-only arm, minted by the liveness floor:
{ kind: "unobservable"; membershipId: MembershipId; published: "warming" | "connected" }.
It means our link to the publisher is dead.
- It is an arm rather than a flag on
warming, so every.exhaustive()must say what it does while blind. - A consumer that times an entry (a deadline, an escalation, a “failed to start” verdict) therefore cannot mistake our own outage for a real, self-healing campaign (kolu#2129).
- It carries no
clockOffsetand noconnection, so nothing green is paintable and no frozen live word can keep narrating.membershipIdrides through, since the floor is about liveness, not identity. publishedhas nofailedinhabitant: a post-mortem does not go stale like a live claim, sofailedpasses the floor untouched.- It has no wire schema. It is a projection of the consumer’s own transport, so
entryStatusSchemahas no arm to encode it into and a floored value can never be republished. - The floor applies to both
entry(key).state()and theentriesprojection.
FailureRecord<Failure>
{ failure, evidence }: the reason and its evidence as one named value.
EntryConnectionState’sfailedarm is one.- Its
disconnectedarm carries an optionalrefuse: FailureRecord. Present is a standing refuse, which publishes asfailed; absent is a transient drop, which publishes aswarming. - Because the pair is one value rather than two correlated fields, a reason
without its evidence is unspellable, and
state.refuse !== undefinednarrows it with no hand-written predicate. - Evidence is a fixed structural type the package owns, not a third type parameter: see the evidence vocabulary.
isSettling(state)
isSettling(state): boolean is the spin-only consumer’s one call, true for
warming and unobservable. It is exported from ., so splitting the arm costs
a spinner nothing. Anything that puts a clock on an entry must still narrow the
union itself.
The server seam
What a host implements to back a map, and the errors a folded member declares.
| Export | Subpath | What it is |
|---|---|---|
MapRegistry<K> | /server | The membership and resolution seam serveSurfaceMap reads. |
EntrySession / EntryFault | /server | What resolve(key) returns: a kind-tagged sum. |
MapRejectionSchema | . | The map’s declared rejection vocabulary. |
MapRegistry<K>
interface MapRegistry<K, Prov = "copying", Failure = unknown, Conn = unknown> {
members(): K[];
subscribe(onChange: () => void): () => void; // fires only AFTER members()/has() reflect the change
has(key: K): boolean;
resolve(key: K): // a kind-tagged sum, provably disjoint
| EntrySession<Prov, Failure, Conn> // { kind: "session", dispatch, state, connection? }
| EntryFault<Failure>; // { kind: "fault", failure }
}
- The registry is the one writer of membership.
entriesis that truth published, and status is derived from each resolved session’s state. members()andhas()answer from one consistent snapshot.- A departure and a same-key re-add are separate, non-coalesced transitions. When
a key leaves and its spelling returns, the registry publishes the removal and
the re-add as two distinct membership events, and the returning member carries
a fresh
membershipId. - A coalesced re-add would let a client-side adapter retain the departed member’s
old
membershipId, and with it the stale per-key subscription, defeating the{encodedKey, membershipId}rebuild.serveSurfaceMapdelivers them non-coalesced, and a hand-rolledMapRegistrymust too. - A call carries its key in every frame. An unknown key is a typed rejection
(unary:
MapKeyUnknown) or an immediate typed end (stream), because membership loss mid-stream is ordinary and only a one-shot call cannot end gracefully. - A key that leaves membership mid-stream ends its subs before the session is destroyed, so no socket-error frame follows a typed end.
EntrySession / EntryFault
resolve returns EntrySession ({ kind: "session", dispatch, state, connection? })
or EntryFault ({ kind: "fault", failure }, a schema-valid domain value). The
sum is kind-tagged, so a consumer switches on the tag rather than on field
presence.
dispatchis the erasedSurfaceDispatchthe map forwards member calls to, by tag. Whatever minted it (a wire link,directDispatch, a mirror) the map never learns.- The connection state’s
failedarm requires a domainfailure: “failed with no failure” is unconstructible at the type, not caught by a runtime throw. - The serving adapter (
serveHostMap) fails loud at its own classification seam rather than falling back to a framework"other"cause. EntryFaultcarries no evidence. A fault has no session, hence no retained output tail, so a hand-rolled registry mints{ kind: "fault", failure }and nothing else.
MapRejectionSchema
The map’s declared rejection vocabulary: the union of MapKeyNonCanonical,
MapKeyUnknown and MapEntryFailed.
- The classes live in
@kolu/surface/errors, not here. A map entry’s call crosses the same re-serving parent hop as every other surface error, so both ends must have been built from one schema for the_tagand its data to survive serialize, deserialize and re-serialize. - The union is declared on every folded member, streaming ones included. A non-canonical wire key is a real rejection on any verb, and a stream whose error channel did not declare it would flatten it into a defect.
Transport deaths a folded member declares
A folded member also declares the transport deaths its forward relays. The map
raises none of them itself: unaryHandler and forwardStream hand the call
straight to session.dispatch, so whatever the entry’s own link fails with
becomes that member’s failure.
| Error | Raised when |
|---|---|
SurfaceStdioTransportClosed | The leg’s subprocess or socket is gone, such as a daemon behind the entry respawning. |
SurfaceRelayTransportLost | A re-serve’s middle hop drops. |
- Both are on every folded member’s error channel, alongside
MapRejectionSchemaand alongside the entry’s own declared error when it has one. Declared, they let a caller tell a respawning daemon from a terminal fault. SurfaceTransportRetiredis deliberately absent. It is the browser socket’s own 4001 retirement, raised by the consumer’s link, and never carried up through a forward.
The fold envelope
Every procedure folds as { mapKey, input }: one wire shape for any input.
- Field constants:
MAP_KEY_FIELD = "mapKey",INPUT_FIELD = "input". An entry input that itself carries amapKeyfield cannot collide with the folded key, because it rides nested underinput. - A void-input member carries no
inputfield at all. The envelope schema isSchema.Struct({ mapKey }), notSchema.Struct({ mapKey, input: Schema.Void }). - Relying on JSON dropping an
undefinedvalue and on the decoder accepting the missing key is fragile. Omitting the field makes “void = no input key” the one representation on both encode and decode. - The envelope is a wrap, not a spread merge. Its decoded type is
{ mapKey: string, input: <decoded member input> }, the same decoded sideSurfaceDispatchcarries, so folding is a plain value wrap with no second encode or decode to keep in step. - The codec functions
fold(mapKey, input),unfoldInput(wire)andunfoldKeyField(wire)reference these constants, so the envelope shape lives in exactly one place. Misroute-by-collision is unconstructible, not merely unlikely.
KeyCodec<K>
interface KeyCodec<K> { encode(key: K): string; decode(wire: string): K; }
Bridges Key to the canonical wire string every channel name, dedup key and
membership entry is keyed on.
- For a plain-string key it is the identity pair. kolu’s
HostKeypasses its own encode and decode. decodeis paired with a decode throughkeySchemaand need not validate on its own.encodeis a bare cheap call on the hottest paths: a per-key cache lookup, the membership fold, and the per-tick republish.- The server re-derives and re-validates the real
Kfrom the wire string throughcodec.decode, then akeySchemadecode. - The connected
SurfaceMapClientre-exposes this codec as itscodecmember, the one key-identity authority on the client. It encodes and decodes the canonical wire string. scopedByEntry, and any consumer keying its own per-entry structure off membership, folds a key through it rather than trusting===reference identity, which the client cannot guarantee across independent decodes of the same logical key.
// `codec` — the ONE key-identity authority: the canonical wire string every
// channel name, dedup key, and membership entry is keyed on. `scopedByEntry`
// folds each key through it rather than trusting `===` reference identity.
const wire: string = app.codec.encode("web-01"); // K → wire string
const key: string = app.codec.decode(wire); // wire string → K
For why the wire is shaped this way, see Entry contracts; to serve a map, see How to serve a map.