@inflatable-cookie/longhorn 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -7
  3. package/src/agent-control/generated/protocol.ts +228 -0
  4. package/src/agent-control/index.ts +1 -5
  5. package/src/agent-control/selection.ts +10 -8
  6. package/src/agent-control/shim.ts +149 -77
  7. package/src/bridge/generated/fields.ts +1 -1
  8. package/src/bridge/generated/protocol.ts +55 -4
  9. package/src/bridge/generated/variant-fields.ts +1 -1
  10. package/src/bridge/job.ts +49 -2
  11. package/src/bridge/runtime/connection.ts +11 -14
  12. package/src/bridge/stream/connection.ts +14 -23
  13. package/src/bridge/stream/tracker.ts +5 -0
  14. package/src/bridge/supervision.ts +102 -80
  15. package/src/bridge/validation/base.ts +7 -27
  16. package/src/bridge/validation/negotiation.ts +1 -6
  17. package/src/bridge/validation/operations.ts +2 -14
  18. package/src/commands/client.ts +16 -2
  19. package/src/commands/controller.ts +96 -58
  20. package/src/commands/generated/fields.ts +4 -4
  21. package/src/commands/generated/protocol.ts +24 -1
  22. package/src/commands/generated/variant-fields.ts +1 -1
  23. package/src/commands/keyboard.ts +4 -13
  24. package/src/commands/physical-code.ts +11 -0
  25. package/src/commands/ports.ts +2 -1
  26. package/src/commands/projectors.ts +52 -29
  27. package/src/commands/validation.ts +408 -188
  28. package/src/config/client.ts +3 -3
  29. package/src/config/generated/base.ts +22 -6
  30. package/src/config/generated/fields.ts +2 -1
  31. package/src/config/generated/label-template.ts +1 -1
  32. package/src/config/generated/labels.ts +1 -1
  33. package/src/config/generated/protocol.ts +1 -1
  34. package/src/config/generated/restore.ts +35 -12
  35. package/src/config/generated/variant-fields.ts +1 -1
  36. package/src/config/validation/commands.ts +11 -13
  37. package/src/config/validation/outcomes.ts +147 -46
  38. package/src/config/validation/primitives.ts +11 -39
  39. package/src/config/validation/projection.ts +44 -44
  40. package/src/core/connection.ts +124 -29
  41. package/src/core/controller-lifecycle.ts +144 -0
  42. package/src/core/generated/identifiers.ts +4 -0
  43. package/src/core/identifiers.ts +40 -0
  44. package/src/core/index.ts +10 -1
  45. package/src/core/json-value.ts +58 -0
  46. package/src/core/listeners.ts +35 -0
  47. package/src/core/record.ts +76 -0
  48. package/src/core/transport.ts +10 -1
  49. package/src/core/wire-copy.ts +1 -0
  50. package/src/history/client.ts +11 -7
  51. package/src/history/controller.ts +72 -74
  52. package/src/history/generated/fields.ts +2 -1
  53. package/src/history/generated/protocol.ts +8 -5
  54. package/src/history/generated/variant-fields.ts +1 -1
  55. package/src/history/ports.ts +7 -2
  56. package/src/history/validation.ts +15 -37
  57. package/src/history-tree/client.ts +15 -13
  58. package/src/history-tree/controller.ts +131 -90
  59. package/src/history-tree/generated/fields.ts +3 -1
  60. package/src/history-tree/generated/protocol.ts +43 -7
  61. package/src/history-tree/generated/variant-fields.ts +7 -1
  62. package/src/history-tree/ports.ts +9 -4
  63. package/src/history-tree/validation.ts +44 -35
  64. package/src/layout/generated/protocol.ts +2 -1
  65. package/src/layout/generated/variant-fields.ts +47 -0
  66. package/src/layout/index.ts +1 -1
  67. package/src/layout/ratio.ts +9 -2
  68. package/src/layout/validation.ts +88 -13
  69. package/src/licence/client.ts +11 -7
  70. package/src/licence/controller.ts +64 -43
  71. package/src/licence/generated/fields.ts +2 -1
  72. package/src/licence/generated/protocol.ts +8 -4
  73. package/src/licence/generated/variant-fields.ts +1 -1
  74. package/src/licence/key.ts +2 -6
  75. package/src/licence/ports.ts +7 -2
  76. package/src/licence/validation.ts +27 -20
  77. package/src/native-content/client.ts +32 -1
  78. package/src/native-content/generated/fields.ts +4 -4
  79. package/src/native-content/generated/protocol.ts +16 -5
  80. package/src/native-content/generated/variant-fields.ts +1 -1
  81. package/src/native-content/ports.ts +2 -1
  82. package/src/native-content/validation/base.ts +16 -46
  83. package/src/native-content/validation/messages.ts +3 -0
  84. package/src/notifications/client.ts +17 -39
  85. package/src/notifications/controller.ts +266 -165
  86. package/src/notifications/generated/fields.ts +2 -1
  87. package/src/notifications/generated/labels.ts +1 -1
  88. package/src/notifications/generated/protocol.ts +5 -1
  89. package/src/notifications/generated/variant-fields.ts +1 -1
  90. package/src/notifications/ports.ts +2 -1
  91. package/src/notifications/tone.ts +1 -1
  92. package/src/notifications/validation.ts +41 -51
  93. package/src/operation/bridge.ts +79 -19
  94. package/src/operation/client.ts +17 -45
  95. package/src/operation/controller.ts +38 -59
  96. package/src/operation/generated/fields.ts +2 -1
  97. package/src/operation/generated/labels.ts +1 -1
  98. package/src/operation/generated/protocol.ts +5 -1
  99. package/src/operation/generated/variant-fields.ts +1 -1
  100. package/src/operation/ports.ts +2 -1
  101. package/src/operation/validation.ts +48 -50
  102. package/src/settings/connection.ts +10 -14
  103. package/src/settings/generated/fields.ts +2 -1
  104. package/src/settings/generated/protocol.ts +5 -1
  105. package/src/settings/generated/variant-fields.ts +1 -1
  106. package/src/settings/validation/authority.ts +2 -2
  107. package/src/settings/validation/command.ts +5 -4
  108. package/src/settings/validation/primitives.ts +32 -67
  109. package/src/settings/validation/registry.ts +13 -11
  110. package/src/surface-transfer/generated/fields.ts +1 -1
  111. package/src/surface-transfer/generated/protocol.ts +3 -3
  112. package/src/surface-transfer/generated/variant-fields.ts +1 -1
  113. package/src/surface-transfer/validation.ts +76 -53
  114. package/src/surfaces/client.ts +26 -38
  115. package/src/surfaces/generated/fields.ts +1 -1
  116. package/src/surfaces/generated/protocol.ts +1 -1
  117. package/src/surfaces/generated/variant-fields.ts +1 -1
  118. package/src/surfaces/validation.ts +198 -61
  119. package/src/transfer/connection.ts +25 -39
  120. package/src/transfer/generated/fields.ts +2 -1
  121. package/src/transfer/generated/protocol.ts +9 -1
  122. package/src/transfer/generated/variant-fields.ts +1 -1
  123. package/src/transfer/index.ts +8 -1
  124. package/src/transfer/payload.ts +12 -9
  125. package/src/transfer/validation.ts +146 -60
  126. package/src/update/client.ts +43 -16
  127. package/src/update/controller.ts +187 -104
  128. package/src/update/generated/fields.ts +2 -1
  129. package/src/update/generated/protocol.ts +19 -7
  130. package/src/update/generated/variant-fields.ts +3 -2
  131. package/src/update/ports.ts +11 -7
  132. package/src/update/serialized.ts +8 -6
  133. package/src/update/validation.ts +18 -28
@@ -1,8 +1,8 @@
1
- // @generated by `effigy generate:bridge`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Rust serde types are the wire authority.
3
3
 
4
4
  export const BRIDGE_PROTOCOL_VERSION = 1 as const;
5
- export const BRIDGE_MAXIMUM_OPAQUE_ID_BYTES = 128 as const;
5
+ export const BRIDGE_DOMAIN_ID_RULE = {"maximumBytes":128,"segmentAdditional":"0123456789_-","segmentInitial":"abcdefghijklmnopqrstuvwxyz","separator":"."} as const;
6
6
  // Wire-visible bounds. The Rust constants are the authority; a
7
7
  // hand-copied literal in a validator is drift waiting to happen.
8
8
  export const BRIDGE_MAXIMUM_REQUESTED_DOMAINS = 256 as const;
@@ -33,7 +33,7 @@ export const BRIDGE_SERVICE_OWNERSHIPS = ["ownedLocal","externalLocal","external
33
33
  export const BRIDGE_SERVICE_STATES = ["absent","starting","attaching","awaitingReadiness","ready","restarting","reconnecting","stopped","failed"] as const;
34
34
  export const BRIDGE_SERVICE_ACTIONS = ["spawn","attach","checkReadiness","restart","reconnect","shutdown"] as const;
35
35
  export const BRIDGE_SERVICE_FAILURE_CODES = ["spawnFailed","attachFailed","readinessFailed","serviceExited","restartFailed","reconnectFailed","shutdownFailed"] as const;
36
- export const BRIDGE_SNAPSHOT_DECISIONS = ["accepted","acceptedResnapshotRequired","supersededSession","wrongDomain"] as const;
36
+ export const BRIDGE_SNAPSHOT_DECISIONS = ["accepted","acceptedResnapshotRequired","supersededSession","wrongDomain","staleSnapshot"] as const;
37
37
  export const BRIDGE_STREAM_DECISIONS = ["apply","ignoreDuplicate","ignoreStale","ignoreSupersededSession","ignoreWrongDomain","resnapshotGap","resnapshotNewEpoch","resnapshotRequired"] as const;
38
38
  export const BRIDGE_PROGRESS_DECISIONS = ["accept","ignoreWrongCorrelation","ignoreAfterTerminal"] as const;
39
39
  export const BRIDGE_TERMINAL_DECISIONS = ["accept","ignoreWrongCorrelation","ignoreAlreadyTerminal"] as const;
@@ -166,7 +166,7 @@ export type BridgeSnapshotEnvelope<P> = { cursor: BridgeStreamCursor, payload: P
166
166
 
167
167
  export type BridgeEventEnvelope<P> = { cursor: BridgeStreamCursor, payload: P, };
168
168
 
169
- export type BridgeSnapshotDecision = "accepted" | "acceptedResnapshotRequired" | "supersededSession" | "wrongDomain";
169
+ export type BridgeSnapshotDecision = "accepted" | "acceptedResnapshotRequired" | "supersededSession" | "wrongDomain" | "staleSnapshot";
170
170
 
171
171
  export type BridgeStreamDecision = "apply" | "ignoreDuplicate" | "ignoreStale" | "ignoreSupersededSession" | "ignoreWrongDomain" | "resnapshotGap" | "resnapshotNewEpoch" | "resnapshotRequired";
172
172
 
@@ -220,3 +220,54 @@ export const BRIDGE_ADMITTED_CONNECTION_REASONS: Record<
220
220
  "closed": ["shutdown"],
221
221
  };
222
222
 
223
+ export const BRIDGE_ADMITTED_CONNECTION_TRANSITIONS: Record<
224
+ BridgeConnectionState,
225
+ readonly BridgeConnectionState[]
226
+ > = {
227
+ "idle": ["connecting", "closed"],
228
+ "connecting": ["negotiating", "reconnecting", "offline", "failed", "closed"],
229
+ "negotiating": ["ready", "reconnecting", "offline", "incompatible", "unauthorized", "failed", "closed"],
230
+ "ready": ["degraded", "reconnecting", "offline", "failed", "closed"],
231
+ "degraded": ["ready", "reconnecting", "offline", "failed", "closed"],
232
+ "reconnecting": ["negotiating", "reconnecting", "offline", "failed", "closed"],
233
+ "offline": ["reconnecting", "failed", "closed"],
234
+ "incompatible": ["closed"],
235
+ "unauthorized": ["closed"],
236
+ "failed": ["closed"],
237
+ "closed": [],
238
+ };
239
+
240
+ export const BRIDGE_SERVICE_UNIT_OUTCOMES = ["accepted","ready","notReady","stopped"] as const;
241
+ export const BRIDGE_SERVICE_FAILURE_STATE: BridgeServiceState = "failed";
242
+ export const BRIDGE_SERVICE_INCARNATION_STATES: readonly BridgeServiceState[] = ["starting","attaching","restarting","reconnecting"];
243
+
244
+ export const BRIDGE_SERVICE_ADMISSIONS: Record<
245
+ BridgeServiceAction,
246
+ {
247
+ readonly ownerships: readonly BridgeServiceOwnership[];
248
+ readonly states: readonly BridgeServiceState[];
249
+ readonly requiresOwnedLifecycle: boolean;
250
+ }
251
+ > = {
252
+ "spawn": {"ownerships":["ownedLocal"],"states":["absent","stopped","failed"],"requiresOwnedLifecycle":true},
253
+ "attach": {"ownerships":["externalLocal","externalRemote"],"states":["absent","stopped","failed"],"requiresOwnedLifecycle":false},
254
+ "checkReadiness": {"ownerships":["ownedLocal","externalLocal","externalRemote"],"states":["starting","attaching","awaitingReadiness","restarting","reconnecting","ready"],"requiresOwnedLifecycle":false},
255
+ "restart": {"ownerships":["ownedLocal"],"states":["ready","failed"],"requiresOwnedLifecycle":true},
256
+ "reconnect": {"ownerships":["ownedLocal","externalLocal","externalRemote"],"states":["ready","failed","stopped"],"requiresOwnedLifecycle":false},
257
+ "shutdown": {"ownerships":["ownedLocal"],"states":["starting","attaching","awaitingReadiness","ready","restarting","reconnecting","failed"],"requiresOwnedLifecycle":true},
258
+ };
259
+
260
+ export const BRIDGE_SERVICE_ADMITTED_OBSERVATIONS: readonly (readonly [
261
+ BridgeServiceAction,
262
+ BridgeServiceOutcome,
263
+ BridgeServiceState,
264
+ ])[] = [
265
+ ["spawn","accepted","starting"],
266
+ ["attach","accepted","attaching"],
267
+ ["checkReadiness","ready","ready"],
268
+ ["checkReadiness","notReady","awaitingReadiness"],
269
+ ["restart","accepted","restarting"],
270
+ ["reconnect","accepted","reconnecting"],
271
+ ["shutdown","stopped","stopped"],
272
+ ];
273
+
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:bridge`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Allowed field names per tagged-union variant, from the Rust enums.
3
3
  // Keyed by type, then by discriminant. The discriminant itself is in
4
4
  // each list, because `exact()` compares every key.
package/src/bridge/job.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { isRecord } from "../core/record.ts";
1
2
  import type {
2
3
  BridgeJobId,
3
4
  BridgeJobTerminalDecision,
@@ -6,6 +7,13 @@ import type {
6
7
  BridgeProgressEvent,
7
8
  BridgeRequestId,
8
9
  } from "./generated/protocol.ts";
10
+ import { incompatible, opaqueId } from "./validation/base.ts";
11
+
12
+ /** The identifiers that tie a progress or terminal event to one job. */
13
+ interface BridgeJobCorrelation {
14
+ readonly requestId: BridgeRequestId;
15
+ readonly jobId: BridgeJobId;
16
+ }
9
17
 
10
18
  export class BridgeJobTracker {
11
19
  readonly #requestId: BridgeRequestId;
@@ -17,15 +25,45 @@ export class BridgeJobTracker {
17
25
  this.#jobId = jobId;
18
26
  }
19
27
 
28
+ /**
29
+ * Whether a raw progress or terminal event belongs to this job, read before
30
+ * any payload is decoded. An identifier that reads as another request or job
31
+ * makes the event foreign, whatever the other identifier is, so another job's
32
+ * event is refused without its payload being decoded. An event is admitted
33
+ * only when both identifiers read and match. One that names no other job and
34
+ * has an unreadable identifier throws as malformed.
35
+ */
36
+ admits(value: unknown): boolean {
37
+ if (!isRecord(value)) {
38
+ incompatible("invalid_object", value);
39
+ }
40
+ const requestId = readOpaqueId(value.requestId);
41
+ const jobId = readOpaqueId(value.jobId);
42
+ if (
43
+ (requestId !== undefined && requestId !== this.#requestId) ||
44
+ (jobId !== undefined && jobId !== this.#jobId)
45
+ ) {
46
+ return false;
47
+ }
48
+ if (requestId === undefined || jobId === undefined) {
49
+ incompatible("invalid_id", value);
50
+ }
51
+ return true;
52
+ }
53
+
54
+ #matches(event: BridgeJobCorrelation): boolean {
55
+ return event.requestId === this.#requestId && event.jobId === this.#jobId;
56
+ }
57
+
20
58
  classifyProgress<P>(event: BridgeProgressEvent<P>): BridgeProgressDecision {
21
- if (event.requestId !== this.#requestId || event.jobId !== this.#jobId) {
59
+ if (!this.#matches(event)) {
22
60
  return "ignoreWrongCorrelation";
23
61
  }
24
62
  return this.#terminal ? "ignoreAfterTerminal" : "accept";
25
63
  }
26
64
 
27
65
  classifyTerminal<S, D>(event: BridgeJobTerminalEvent<S, D>): BridgeJobTerminalDecision {
28
- if (event.requestId !== this.#requestId || event.jobId !== this.#jobId) {
66
+ if (!this.#matches(event)) {
29
67
  return "ignoreWrongCorrelation";
30
68
  }
31
69
  if (this.#terminal) {
@@ -39,3 +77,12 @@ export class BridgeJobTracker {
39
77
  return this.#terminal;
40
78
  }
41
79
  }
80
+
81
+ /** The identifier, or `undefined` when it is not a readable opaque id. */
82
+ function readOpaqueId(value: unknown): string | undefined {
83
+ try {
84
+ return opaqueId(value);
85
+ } catch {
86
+ return undefined;
87
+ }
88
+ }
@@ -18,6 +18,7 @@ import {
18
18
  parseBridgeNegotiationReceipt,
19
19
  parseBridgeStreamCursor,
20
20
  } from "../validation.ts";
21
+ import { BRIDGE_ADMITTED_CONNECTION_TRANSITIONS } from "../generated/protocol.ts";
21
22
  import { BridgeSession } from "../session.ts";
22
23
  import {
23
24
  checkedDeadline,
@@ -106,6 +107,13 @@ export class BridgeConnectionRuntime {
106
107
 
107
108
  reconnect(retryClass: BridgeRetryClass): BridgeConnectionTransitionReceipt {
108
109
  retryClass = checkedRetryClass(retryClass);
110
+ if (retryClass !== "never" && this.#status.reason === "retryForbidden") {
111
+ // A retry-forbidden status is terminal for retries, as in the Rust machine.
112
+ throw new BridgeRuntimeError(
113
+ "invalid_transition",
114
+ `cannot transition from ${this.#status.state} to reconnecting`,
115
+ );
116
+ }
109
117
  const attempt = this.#reconnectAttempts + 1;
110
118
  const admitted = retryClass !== "never" && attempt <= this.#reconnectLimit;
111
119
  this.#requireTransition(admitted ? "reconnecting" : "offline");
@@ -272,19 +280,8 @@ function authoritySatisfies(
272
280
  }
273
281
  }
274
282
 
283
+ // Generated from `BridgeConnectionState::ADMITTED_TRANSITIONS`, the same table
284
+ // the Rust machine enforces. There is no hand-written copy here.
275
285
  function transitionAllowed(current: BridgeConnectionState, next: BridgeConnectionState): boolean {
276
- if (next === "closed") {
277
- return current !== "closed";
278
- }
279
- const transitions: Partial<Record<BridgeConnectionState, ReadonlyArray<BridgeConnectionState>>> =
280
- {
281
- idle: ["connecting"],
282
- connecting: ["negotiating", "reconnecting", "offline", "failed"],
283
- negotiating: ["ready", "reconnecting", "offline", "incompatible", "unauthorized", "failed"],
284
- ready: ["degraded", "reconnecting", "offline", "failed"],
285
- degraded: ["ready", "reconnecting", "offline", "failed"],
286
- reconnecting: ["negotiating", "reconnecting", "offline", "failed"],
287
- offline: ["reconnecting", "failed"],
288
- };
289
- return transitions[current]?.includes(next) ?? false;
286
+ return BRIDGE_ADMITTED_CONNECTION_TRANSITIONS[current].includes(next);
290
287
  }
@@ -1,8 +1,5 @@
1
- import { CheckedSnapshotConnection } from "@inflatable-cookie/longhorn/core";
2
- import type {
3
- ConnectionFailure,
4
- ConnectionFailureReporter,
5
- } from "@inflatable-cookie/longhorn/core";
1
+ import { CheckedSnapshotConnection, CheckedSubscription } from "@inflatable-cookie/longhorn/core";
2
+ import type { ConnectionFailureReporter } from "@inflatable-cookie/longhorn/core";
6
3
 
7
4
  import type {
8
5
  BridgeEventEnvelope,
@@ -27,25 +24,12 @@ export interface BridgeStreamConnectionOptions<Snapshot, Event> {
27
24
  readonly onFailure?: ConnectionFailureReporter;
28
25
  }
29
26
 
30
- export class BridgeStreamConnection<Snapshot> {
31
- readonly ready: Promise<BridgeSnapshotEnvelope<Snapshot> | undefined>;
32
- readonly #connection: CheckedSnapshotConnection<BridgeSnapshotEnvelope<Snapshot>>;
33
-
27
+ export class BridgeStreamConnection<Snapshot> extends CheckedSubscription<
28
+ BridgeSnapshotEnvelope<Snapshot>,
29
+ BridgeSnapshotEnvelope<Snapshot> | undefined
30
+ > {
34
31
  constructor(connection: CheckedSnapshotConnection<BridgeSnapshotEnvelope<Snapshot>>) {
35
- this.#connection = connection;
36
- this.ready = connection.ready;
37
- }
38
-
39
- current(): BridgeSnapshotEnvelope<Snapshot> | undefined {
40
- return this.#connection.current();
41
- }
42
-
43
- failures(): ReadonlyArray<ConnectionFailure> {
44
- return this.#connection.failures();
45
- }
46
-
47
- dispose(): Promise<void> {
48
- return this.#connection.dispose();
32
+ super(connection, (snapshot) => snapshot);
49
33
  }
50
34
  }
51
35
 
@@ -62,6 +46,13 @@ export function connectBridgeStream<Snapshot, Event>(
62
46
  if (decision === "supersededSession" || decision === "wrongDomain") {
63
47
  throw new BridgeStreamAuthorityError(decision);
64
48
  }
49
+ // The reply is behind an event already seen, and the events in between
50
+ // were not applied. Nothing else will ask again if the stream goes quiet.
51
+ if (decision === "acceptedResnapshotRequired") {
52
+ connection.requestRefresh();
53
+ }
54
+ // A stale reply is returned unchanged. The tracker kept its baseline, and
55
+ // the connection's isNewer check drops the reply, so the stream stays live.
65
56
  return snapshot;
66
57
  },
67
58
  handleEvent: (value, current) => {
@@ -34,6 +34,11 @@ export class BridgeStreamTracker {
34
34
  if (cursor.domainId !== this.#domainId) {
35
35
  return "wrongDomain";
36
36
  }
37
+ // Checked before any state is written: an older snapshot must never move
38
+ // the accepted baseline back, or a redelivered event would apply twice.
39
+ if (this.#accepted !== undefined && newer(this.#accepted, cursor)) {
40
+ return "staleSnapshot";
41
+ }
37
42
  const pendingIsNewer = this.#pending !== undefined && newer(this.#pending, cursor);
38
43
  this.#accepted = cursor;
39
44
  this.#pending = undefined;
@@ -1,25 +1,55 @@
1
1
  import type {
2
2
  BridgeCredentialRef,
3
3
  BridgeServiceAction,
4
- BridgeServiceFailureCode,
5
4
  BridgeServiceOutcome,
6
5
  BridgeServiceOwnership,
7
6
  BridgeServiceRequest,
8
7
  BridgeServiceState,
9
8
  BridgeServiceTransitionReceipt,
10
9
  } from "./generated/protocol.ts";
11
- import { BRIDGE_SERVICE_OWNERSHIPS } from "./generated/protocol.ts";
10
+ import {
11
+ BRIDGE_SERVICE_ADMISSIONS,
12
+ BRIDGE_SERVICE_ADMITTED_OBSERVATIONS,
13
+ BRIDGE_SERVICE_FAILURE_CODES,
14
+ BRIDGE_SERVICE_FAILURE_STATE,
15
+ BRIDGE_SERVICE_INCARNATION_STATES,
16
+ BRIDGE_SERVICE_OWNERSHIPS,
17
+ BRIDGE_SERVICE_UNIT_OUTCOMES,
18
+ } from "./generated/protocol.ts";
12
19
  import { opaqueId } from "./validation/base.ts";
13
20
 
14
21
  export interface BridgeServiceSupervisorPort {
15
22
  perform(request: BridgeServiceRequest): Promise<unknown> | unknown;
16
23
  }
17
24
 
25
+ /**
26
+ * Monotonic service incarnation.
27
+ *
28
+ * One incarnation covers one service attempt. It advances only when a commit
29
+ * starts an attempt (spawn, attach, restart or reconnect), never for a
30
+ * readiness observation of the running attempt and never for the attempt's
31
+ * end.
32
+ */
33
+ export type BridgeServiceIncarnation = number;
34
+
35
+ /**
36
+ * One admitted supervision action bound to the incarnation that admitted it.
37
+ *
38
+ * A runtime-local token, not a wire shape: `begin` returns it and `commit`
39
+ * accepts its observation only while that incarnation is still current.
40
+ */
41
+ export interface BridgeServiceAdmission {
42
+ readonly incarnation: BridgeServiceIncarnation;
43
+ readonly action: BridgeServiceAction;
44
+ }
45
+
18
46
  export class BridgeSupervisionError extends Error {
19
47
  readonly code:
20
48
  | "lifecycle_not_owned"
49
+ | "invalid_ownership"
21
50
  | "invalid_transition"
22
51
  | "invalid_observation"
52
+ | "stale_observation"
23
53
  | "adapter_failed";
24
54
 
25
55
  constructor(code: BridgeSupervisionError["code"]) {
@@ -33,10 +63,11 @@ export class BridgeServiceRuntime {
33
63
  readonly #ownership: BridgeServiceOwnership;
34
64
  #state: BridgeServiceState = "absent";
35
65
  #generation = 0;
66
+ #incarnation = 0;
36
67
 
37
68
  constructor(ownership: BridgeServiceOwnership) {
38
69
  if (!BRIDGE_SERVICE_OWNERSHIPS.includes(ownership)) {
39
- throw new BridgeSupervisionError("invalid_transition");
70
+ throw new BridgeSupervisionError("invalid_ownership");
40
71
  }
41
72
  this.#ownership = ownership;
42
73
  }
@@ -50,7 +81,7 @@ export class BridgeServiceRuntime {
50
81
  action: BridgeServiceAction,
51
82
  credentialRef?: BridgeCredentialRef,
52
83
  ): Promise<BridgeServiceTransitionReceipt> {
53
- this.#admit(action);
84
+ const admission = this.begin(action);
54
85
  const request: BridgeServiceRequest = {
55
86
  action,
56
87
  credentialRef: credentialRef === undefined ? null : opaqueId(credentialRef),
@@ -61,15 +92,59 @@ export class BridgeServiceRuntime {
61
92
  } catch {
62
93
  throw new BridgeSupervisionError("adapter_failed");
63
94
  }
64
- return this.observe(action, rawOutcome);
95
+ return this.commit(admission, rawOutcome);
65
96
  }
66
97
 
67
- observe(action: BridgeServiceAction, value: unknown): BridgeServiceTransitionReceipt {
98
+ /**
99
+ * Admits one action whose observation arrives after the call returns.
100
+ *
101
+ * The returned admission carries the service incarnation that admitted it, so
102
+ * the observation must be committed through `commit`. A commit that starts a
103
+ * new attempt in between supersedes the admission and the delayed observation
104
+ * is rejected instead of being reported for the later service incarnation.
105
+ * Readiness observations of one attempt share its incarnation, so overlapping
106
+ * probes of that attempt all stay committable.
107
+ */
108
+ begin(action: BridgeServiceAction): BridgeServiceAdmission {
68
109
  this.#admit(action);
110
+ return { incarnation: this.#incarnation, action };
111
+ }
112
+
113
+ /**
114
+ * Commits the observation for an action admitted by `begin`.
115
+ *
116
+ * Rejects the observation when a commit started a new service attempt after
117
+ * admission, or when the action is no longer valid in the current state.
118
+ * Neither a readiness observation nor the end of an attempt changes the
119
+ * incarnation, so a probe and a shutdown admitted together both land.
120
+ */
121
+ commit(admission: BridgeServiceAdmission, value: unknown): BridgeServiceTransitionReceipt {
122
+ if (admission.incarnation !== this.#incarnation) {
123
+ throw new BridgeSupervisionError("stale_observation");
124
+ }
125
+ this.#admit(admission.action);
126
+ return this.#apply(admission.action, value);
127
+ }
128
+
129
+ /**
130
+ * Commits an adapter observation that is current when the call is made.
131
+ *
132
+ * This admits and commits in one step, so it cannot carry an observation that
133
+ * started before the call. Use `begin` and `commit` for one that completes
134
+ * later.
135
+ */
136
+ observe(action: BridgeServiceAction, value: unknown): BridgeServiceTransitionReceipt {
137
+ return this.commit(this.begin(action), value);
138
+ }
139
+
140
+ #apply(action: BridgeServiceAction, value: unknown): BridgeServiceTransitionReceipt {
69
141
  const outcome = parseOutcome(value);
70
142
  const current = transitionState(action, outcome);
71
143
  const generation = this.#generation + 1;
72
- if (!Number.isSafeInteger(generation)) {
144
+ const incarnation = BRIDGE_SERVICE_INCARNATION_STATES.includes(current)
145
+ ? this.#incarnation + 1
146
+ : this.#incarnation;
147
+ if (!Number.isSafeInteger(generation) || !Number.isSafeInteger(incarnation)) {
73
148
  throw new BridgeSupervisionError("invalid_transition");
74
149
  }
75
150
  const receipt = {
@@ -81,44 +156,18 @@ export class BridgeServiceRuntime {
81
156
  outcome,
82
157
  };
83
158
  this.#generation = generation;
159
+ this.#incarnation = incarnation;
84
160
  this.#state = current;
85
161
  return receipt;
86
162
  }
87
163
 
88
164
  #admit(action: BridgeServiceAction): void {
89
- const owned = this.#ownership === "ownedLocal";
90
- let admitted = false;
91
- switch (action) {
92
- case "spawn":
93
- admitted = owned && ["absent", "stopped", "failed"].includes(this.#state);
94
- break;
95
- case "attach":
96
- admitted = !owned && ["absent", "stopped", "failed"].includes(this.#state);
97
- break;
98
- case "checkReadiness":
99
- admitted = [
100
- "starting",
101
- "attaching",
102
- "awaitingReadiness",
103
- "restarting",
104
- "reconnecting",
105
- "ready",
106
- ].includes(this.#state);
107
- break;
108
- case "restart":
109
- admitted = owned && ["ready", "failed"].includes(this.#state);
110
- break;
111
- case "reconnect":
112
- admitted = ["ready", "failed", "stopped"].includes(this.#state);
113
- break;
114
- case "shutdown":
115
- admitted = owned && !["absent", "stopped"].includes(this.#state);
116
- break;
117
- }
118
- if (admitted) {
165
+ const rule = BRIDGE_SERVICE_ADMISSIONS[action];
166
+ const ownershipAdmitted = rule.ownerships.includes(this.#ownership);
167
+ if (ownershipAdmitted && rule.states.includes(this.#state)) {
119
168
  return;
120
169
  }
121
- if (!owned && ["spawn", "restart", "shutdown"].includes(action)) {
170
+ if (!ownershipAdmitted && rule.requiresOwnedLifecycle) {
122
171
  throw new BridgeSupervisionError("lifecycle_not_owned");
123
172
  }
124
173
  throw new BridgeSupervisionError("invalid_transition");
@@ -130,60 +179,33 @@ function transitionState(
130
179
  outcome: BridgeServiceOutcome,
131
180
  ): BridgeServiceState {
132
181
  if (typeof outcome === "object") {
133
- return "failed";
134
- }
135
- if (action === "checkReadiness" && outcome === "ready") {
136
- return "ready";
137
- }
138
- if (action === "checkReadiness" && outcome === "notReady") {
139
- return "awaitingReadiness";
182
+ return BRIDGE_SERVICE_FAILURE_STATE;
140
183
  }
141
- if (action === "shutdown" && outcome === "stopped") {
142
- return "stopped";
143
- }
144
- if (outcome === "accepted") {
145
- const accepted: Partial<Record<BridgeServiceAction, BridgeServiceState>> = {
146
- spawn: "starting",
147
- attach: "attaching",
148
- restart: "restarting",
149
- reconnect: "reconnecting",
150
- };
151
- const state = accepted[action];
152
- if (state !== undefined) {
153
- return state;
154
- }
184
+ const admitted = BRIDGE_SERVICE_ADMITTED_OBSERVATIONS.find(
185
+ ([candidate, observation]) => candidate === action && observation === outcome,
186
+ );
187
+ if (admitted === undefined) {
188
+ throw new BridgeSupervisionError("invalid_observation");
155
189
  }
156
- throw new BridgeSupervisionError("invalid_observation");
190
+ return admitted[2];
157
191
  }
158
192
 
159
193
  function parseOutcome(value: unknown): BridgeServiceOutcome {
160
- if (value === "accepted" || value === "ready" || value === "notReady" || value === "stopped") {
161
- return value;
194
+ const unit = BRIDGE_SERVICE_UNIT_OUTCOMES.find((outcome) => outcome === value);
195
+ if (unit !== undefined) {
196
+ return unit;
162
197
  }
163
198
  if (
164
199
  typeof value === "object" &&
165
200
  value !== null &&
166
201
  !Array.isArray(value) &&
167
202
  Object.keys(value).length === 1 &&
168
- "failed" in value &&
169
- isFailureCode(value.failed)
203
+ "failed" in value
170
204
  ) {
171
- return { failed: value.failed };
205
+ const failed = BRIDGE_SERVICE_FAILURE_CODES.find((code) => code === value.failed);
206
+ if (failed !== undefined) {
207
+ return { failed };
208
+ }
172
209
  }
173
210
  throw new BridgeSupervisionError("invalid_observation");
174
211
  }
175
-
176
- function isFailureCode(value: unknown): value is BridgeServiceFailureCode {
177
- return (
178
- typeof value === "string" &&
179
- [
180
- "spawnFailed",
181
- "attachFailed",
182
- "readinessFailed",
183
- "serviceExited",
184
- "restartFailed",
185
- "reconnectFailed",
186
- "shutdownFailed",
187
- ].includes(value)
188
- );
189
- }
@@ -1,5 +1,6 @@
1
- import { isRecord } from "../../core/record.ts";
2
- import { BRIDGE_MAXIMUM_OPAQUE_ID_BYTES } from "../generated/protocol.ts";
1
+ import { isOpaqueId, matchesDomainIdRule } from "../../core/identifiers.ts";
2
+ import { checkWireFields, readWireRecord } from "../../core/record.ts";
3
+ import { BRIDGE_DOMAIN_ID_RULE } from "../generated/protocol.ts";
3
4
  export type BridgeProtocolValidationCode =
4
5
  | "unsupported_protocol_version"
5
6
  | "invalid_object"
@@ -56,21 +57,8 @@ export function record(
56
57
  required: ReadonlyArray<string>,
57
58
  optional: ReadonlyArray<string> = [],
58
59
  ): Record<string, unknown> {
59
- if (!isRecord(value)) {
60
- incompatible("invalid_object", value);
61
- }
62
- const result = value;
63
- const allowed = new Set([...required, ...optional]);
64
- for (const key of Object.keys(result)) {
65
- if (!allowed.has(key)) {
66
- incompatible("unknown_field", { key, value });
67
- }
68
- }
69
- for (const key of required) {
70
- if (!(key in result)) {
71
- incompatible("missing_field", { key, value });
72
- }
73
- }
60
+ const result = readWireRecord(value, () => incompatible("invalid_object", value));
61
+ checkWireFields(result, required, (code, key) => incompatible(code, { key, value }), optional);
74
62
  return result;
75
63
  }
76
64
 
@@ -93,22 +81,14 @@ export function unique<T>(values: ReadonlyArray<T>, key: (value: T) => string):
93
81
  }
94
82
 
95
83
  export function opaqueId(value: unknown): string {
96
- if (
97
- typeof value !== "string" ||
98
- new TextEncoder().encode(value).length > BRIDGE_MAXIMUM_OPAQUE_ID_BYTES ||
99
- !/^[a-z0-9._:-]+$/.test(value)
100
- ) {
84
+ if (!isOpaqueId(value)) {
101
85
  incompatible("invalid_id", value);
102
86
  }
103
87
  return value;
104
88
  }
105
89
 
106
90
  export function domainId(value: unknown): string {
107
- if (
108
- typeof value !== "string" ||
109
- new TextEncoder().encode(value).length > BRIDGE_MAXIMUM_OPAQUE_ID_BYTES ||
110
- !/^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)*$/.test(value)
111
- ) {
91
+ if (!matchesDomainIdRule(value, BRIDGE_DOMAIN_ID_RULE)) {
112
92
  incompatible("invalid_domain_id", value);
113
93
  }
114
94
  return value;
@@ -147,12 +147,7 @@ function validConnectionReason(
147
147
  state: BridgeConnectionState,
148
148
  reason: BridgeConnectionReason | null,
149
149
  ): boolean {
150
- // Generated from `BridgeConnectionStatus::ADMITTED_REASONS`. This used to be
151
- // an eleven-arm literal here, and Card 160 recorded it as the one rule that
152
- // could not be derived because the pairing exists in no type. That was
153
- // wrong: it exists in Rust, in a `matches!` arm, which `ts-rs` cannot carry
154
- // because it is a relation between two enums rather than a type. The two
155
- // copies agreed arm for arm — by maintenance, not by construction.
150
+ // Generated from `BridgeConnectionStatus::ADMITTED_REASONS` in Rust.
156
151
  return BRIDGE_ADMITTED_CONNECTION_REASONS[state].includes(reason);
157
152
  }
158
153
 
@@ -3,7 +3,6 @@ import { BRIDGE_FIELDS } from "../generated/fields.ts";
3
3
  import {
4
4
  BRIDGE_MAXIMUM_DEDUPLICATION_ENTRIES,
5
5
  BRIDGE_MAXIMUM_FAILURE_MESSAGE_BYTES,
6
- BRIDGE_MAXIMUM_OPAQUE_ID_BYTES,
7
6
  BRIDGE_FAILURE_PHASES,
8
7
  BRIDGE_RETRY_CLASSES,
9
8
  } from "../generated/protocol.ts";
@@ -17,7 +16,7 @@ import type {
17
16
  BridgeQueryReply,
18
17
  BridgeRequestContext,
19
18
  } from "../generated/protocol.ts";
20
- import { incompatible, integer, nullable, oneOf, opaqueId, record } from "./base.ts";
19
+ import { domainId, incompatible, integer, nullable, oneOf, opaqueId, record } from "./base.ts";
21
20
  import type { BridgeCodec } from "./base.ts";
22
21
 
23
22
  export function parseBridgeRequestContext(value: unknown): BridgeRequestContext {
@@ -25,7 +24,7 @@ export function parseBridgeRequestContext(value: unknown): BridgeRequestContext
25
24
  return {
26
25
  requestId: opaqueId(source.requestId),
27
26
  sessionId: opaqueId(source.sessionId),
28
- domainId: parseDomainId(source.domainId),
27
+ domainId: domainId(source.domainId),
29
28
  };
30
29
  }
31
30
 
@@ -176,14 +175,3 @@ function variant(
176
175
  }
177
176
  return source;
178
177
  }
179
-
180
- function parseDomainId(value: unknown): string {
181
- if (
182
- typeof value !== "string" ||
183
- new TextEncoder().encode(value).length > BRIDGE_MAXIMUM_OPAQUE_ID_BYTES ||
184
- !/^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)*$/.test(value)
185
- ) {
186
- incompatible("invalid_domain_id", value);
187
- }
188
- return value;
189
- }