1
import { type Static, type TSchema, Type } from "typebox";2
import { Value } from "typebox/value";3
import { DescriptionSchema } from "./contract.ts";4
import { CHORD_ERROR_CODES, ChordError } from "./errors.ts";6
// JSON frames between two hosts (or a host and a client). Ids are chosen by the side that creates the hold, call or7
// subscription; every frame type has one direction, so ids never collide:8
// consumer → provider: hold, release, call, cancel, sub, unsub, resync9
// provider → consumer: shape, gone, result, state10
// State is addressed by (hold id, member): a hold implies the state of its variant, sent as units (a shape followed by11
// a snapshot of each member the consumer lacks; see Connection).12
// both: hello, ping, pong, bye, root_end, ack; parent → child: invalidate, prepare, commit, abort, retire;13
// child → parent: vote14
//15
// Each frame is declared once, as the schema every received frame is checked against (`isFrame`); the types are derived16
// from it. Payloads (hold inputs, call args, results, snapshots) stay `unknown`: they are validated where they are17
// used, against the contract. State ops are checked op by op by the delta decoder.19
/**20
* The link protocol version, announced in `hello`. Peers of different versions do not talk: the side that notices21
* closes the link with reason `protocol-version <its version>`, so the other side learns it too22
* (`LinkOptions.onProtocolMismatch`).23
*/24
export const PROTOCOL_VERSION = 4;26
const Id = Type.Integer({ minimum: 1 });27
const Name = Type.String({ minLength: 1 });28
const Reload = Type.Integer({ minimum: 1 });29
/** Arrays a sender may pass as readonly. */30
const List = <T extends TSchema>(item: T) => Type.Immutable(Type.Array(item));32
const RootRefSchema = Type.Object({ rootId: Name, codeVersion: Type.Integer({ minimum: 1 }) });33
export type RootRef = Static<typeof RootRefSchema>;35
const WireErrorSchema = Type.Object({36
code: Type.Enum(CHORD_ERROR_CODES),37
message: Type.String(),38
reason: Type.Optional(Type.String()),39
});40
export type WireError = Static<typeof WireErrorSchema>;42
const WireReloadOptionsSchema = Type.Object({43
remove: Type.Optional(List(Type.String())),44
gateDeadline: Type.Optional(Type.Number()),45
retireDeadline: Type.Optional(Type.Number()),46
});47
export type WireReloadOptions = Static<typeof WireReloadOptionsSchema>;49
/** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */50
const WireReloadReportSchema = Type.Object({51
codeVersion: Type.Integer(),52
previous: Type.Integer(),53
changed: List(Type.String()),54
removed: List(Type.String()),55
prepared: List(Type.String()),56
gated: List(Type.String()),57
});58
export type WireReloadReport = Static<typeof WireReloadReportSchema>;60
const FrameSchema = Type.Union([61
Type.Object({62
t: Type.Literal("hello"),63
/** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */64
protocol: Type.Optional(Type.Integer({ minimum: 1 })),65
name: Name,66
kind: Type.Union([Type.Literal("host"), Type.Literal("client")]),67
codeVersion: Type.Integer({ minimum: 0 }),68
/** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */69
acks: Type.Optional(Type.Boolean()),70
}),71
/** Every frame received so far except `ack` frames, counted from the link's start, once processed. */72
Type.Object({ t: Type.Literal("ack"), n: Type.Integer({ minimum: 1 }) }),73
Type.Object({74
t: Type.Literal("hold"),75
id: Id,76
/**77
* Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after78
* checking it against both; the target refuses an input its own contract places elsewhere.79
*/80
at: Name,81
/** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */82
token: DescriptionSchema,83
/** Normalized with the consumer's contract. */84
input: Type.Unknown(),85
/** A forwarded principal. Honored only on frames from the parent link. */86
principal: Type.Optional(Type.Unknown()),87
/**88
* The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored89
* only on frames from the parent link; present means the hold is a client's (not a reload participant).90
*/91
origin: Type.Optional(Name),92
/** False: no state for this hold until `sub` (a method-only binding). */93
state: Type.Optional(Type.Literal(false)),94
/** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */95
again: Type.Optional(Type.Literal(true)),96
}),97
Type.Object({ t: Type.Literal("release"), id: Id }),98
Type.Object({99
t: Type.Literal("shape"),100
id: Id,101
variant: Type.Optional(Type.String()),102
members: List(Type.String()),103
contract: Type.String(),104
/** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */105
state: List(Name),106
}),107
Type.Object({ t: Type.Literal("gone"), id: Id, error: WireErrorSchema }),108
Type.Object({109
t: Type.Literal("call"),110
id: Id,111
hold: Id,112
member: Name,113
args: Type.Optional(Type.Unknown()),114
/** Absent: the receiving host starts a root (browsers never carry roots). */115
root: Type.Optional(RootRefSchema),116
}),117
Type.Object({118
t: Type.Literal("result"),119
id: Id,120
value: Type.Optional(Type.Unknown()),121
error: Type.Optional(WireErrorSchema),122
}),123
Type.Object({ t: Type.Literal("cancel"), id: Id }),124
/** Starts the state of a hold opened with `state: false` (answered with a unit). */125
Type.Object({ t: Type.Literal("sub"), hold: Id }),126
/** Stops the state of a hold. */127
Type.Object({ t: Type.Literal("unsub"), hold: Id }),128
/** Sends member `m` again as a reset (a relay that had to drop what waited for it). */129
Type.Object({ t: Type.Literal("resync"), hold: Id, m: Name }),130
Type.Object({131
t: Type.Literal("state"),132
hold: Id,133
m: Name,134
/** `snap`/`reset` without `value`: the value is `undefined`. */135
as: Type.Union([Type.Literal("snap"), Type.Literal("reset"), Type.Literal("ops"), Type.Literal("error")]),136
value: Type.Optional(Type.Unknown()),137
/** Encoded with the stream's delta encoder; the decoder validates each op. */138
ops: Type.Optional(List(List(Type.Unknown()))),139
error: Type.Optional(WireErrorSchema),140
}),141
Type.Object({ t: Type.Literal("ping"), n: Type.Integer() }),142
Type.Object({ t: Type.Literal("pong"), n: Type.Integer() }),143
/** Ends the link (consumed by the link itself). `reason: "protocol-version <n>"`: the sender speaks version n. */144
Type.Object({ t: Type.Literal("bye"), reason: Type.Optional(Type.String()) }),145
/** The root ended at its origin: its leases on objects end (sent on every link the root's calls used). */146
Type.Object({ t: Type.Literal("root_end"), rootId: Name }),147
Type.Object({ t: Type.Literal("invalidate"), pattern: Type.Record(Type.String(), Type.Unknown()) }),148
Type.Object({149
t: Type.Literal("prepare"),150
reload: Reload,151
codeVersion: Type.Integer({ minimum: 1 }),152
plugins: List(Type.String()),153
options: WireReloadOptionsSchema,154
}),155
Type.Object({156
t: Type.Literal("vote"),157
reload: Reload,158
error: Type.Optional(WireErrorSchema),159
report: Type.Optional(WireReloadReportSchema),160
}),161
Type.Object({ t: Type.Literal("commit"), reload: Reload }),162
/** The parent dropped `codeVersion`: roots of it may still come from there no longer. */163
Type.Object({ t: Type.Literal("retire"), codeVersion: Type.Integer({ minimum: 1 }) }),164
Type.Object({ t: Type.Literal("abort"), reload: Reload }),165
]);166
export type Frame = Static<typeof FrameSchema>;168
/** A frame that passes validation; anything else is a protocol violation. */169
export const isFrame = (value: unknown): value is Frame => Value.Check(FrameSchema, value);171
export function toWireError(error: unknown): WireError {172
if (error instanceof ChordError) {173
return error.reason === undefined174
? { code: error.code, message: error.message }175
: { code: error.code, message: error.message, reason: error.reason };176
}177
return { code: "unavailable", message: error instanceof Error ? error.message : String(error) };178
}180
export const fromWireError = (error: WireError): ChordError =>181
new ChordError(error.code, error.message.replace(/^[a-z_]+(\/[a-z_]+)?: /, ""), { reason: error.reason });