@inflatable-cookie/longhorn 0.5.0 → 0.6.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 (126) hide show
  1. package/package.json +1 -1
  2. package/src/agent-control/inject.ts +4 -1
  3. package/src/agent-control/selection.ts +35 -20
  4. package/src/agent-control/shim.ts +302 -144
  5. package/src/bridge/direct.ts +1 -1
  6. package/src/bridge/generated/fields.ts +3 -2
  7. package/src/bridge/generated/protocol.ts +7 -3
  8. package/src/bridge/job.ts +4 -14
  9. package/src/bridge/loopback.ts +7 -25
  10. package/src/bridge/operation.ts +13 -43
  11. package/src/bridge/router.ts +10 -23
  12. package/src/bridge/runtime/connection.ts +77 -105
  13. package/src/bridge/runtime/policy.ts +8 -28
  14. package/src/bridge/runtime/retry.ts +6 -18
  15. package/src/bridge/session.ts +4 -14
  16. package/src/bridge/stream/connection.ts +16 -38
  17. package/src/bridge/stream/source.ts +2 -6
  18. package/src/bridge/stream/tracker.ts +7 -12
  19. package/src/bridge/supervision.ts +11 -26
  20. package/src/bridge/validation/base.ts +17 -39
  21. package/src/bridge/validation/jobs.ts +11 -25
  22. package/src/bridge/validation/negotiation.ts +27 -37
  23. package/src/bridge/validation/operations.ts +28 -52
  24. package/src/bridge/validation/streams.ts +3 -10
  25. package/src/commands/client.ts +21 -26
  26. package/src/commands/controller.ts +32 -47
  27. package/src/commands/generated/fields.ts +3 -2
  28. package/src/commands/generated/protocol.ts +4 -0
  29. package/src/commands/keyboard.ts +92 -89
  30. package/src/commands/ports.ts +6 -12
  31. package/src/commands/projectors.ts +50 -48
  32. package/src/commands/validation.ts +70 -97
  33. package/src/config/client.ts +6 -19
  34. package/src/config/generated/fields.ts +2 -2
  35. package/src/config/names.ts +6 -12
  36. package/src/config/validation/commands.ts +5 -17
  37. package/src/config/validation/outcomes.ts +31 -39
  38. package/src/config/validation/primitives.ts +36 -53
  39. package/src/config/validation/projection.ts +66 -94
  40. package/src/core/connection.ts +70 -61
  41. package/src/core/record.ts +4 -0
  42. package/src/core/transport.ts +4 -15
  43. package/src/core/wire-copy.ts +6 -0
  44. package/src/history/client.ts +6 -12
  45. package/src/history/controller.ts +46 -46
  46. package/src/history/direct.ts +1 -3
  47. package/src/history/generated/fields.ts +2 -2
  48. package/src/history/ports.ts +4 -6
  49. package/src/history/serialized.ts +9 -13
  50. package/src/history/validation.ts +71 -55
  51. package/src/history-tree/client.ts +87 -11
  52. package/src/history-tree/controller.ts +313 -70
  53. package/src/history-tree/direct.ts +3 -1
  54. package/src/history-tree/generated/fields.ts +2 -2
  55. package/src/history-tree/ports.ts +3 -1
  56. package/src/history-tree/serialized.ts +39 -11
  57. package/src/history-tree/validation.ts +262 -63
  58. package/src/layout/generated/protocol.ts +2 -2
  59. package/src/layout/ratio.ts +2 -8
  60. package/src/layout/validation.ts +10 -19
  61. package/src/layout/visibility.ts +1 -2
  62. package/src/licence/client.ts +44 -7
  63. package/src/licence/controller.ts +76 -40
  64. package/src/licence/direct.ts +3 -1
  65. package/src/licence/generated/fields.ts +2 -2
  66. package/src/licence/generated/key-conformance.json +28 -0
  67. package/src/licence/generated/protocol.ts +1 -1
  68. package/src/licence/key.ts +40 -12
  69. package/src/licence/ports.ts +3 -1
  70. package/src/licence/serialized.ts +32 -9
  71. package/src/licence/validation.ts +120 -36
  72. package/src/native-content/client.ts +178 -236
  73. package/src/native-content/generated/fields.ts +2 -2
  74. package/src/native-content/ports.ts +9 -15
  75. package/src/native-content/serialized.ts +12 -19
  76. package/src/native-content/validation/base.ts +57 -50
  77. package/src/native-content/validation/messages.ts +21 -35
  78. package/src/native-content/validation/state.ts +31 -33
  79. package/src/notifications/client.ts +87 -31
  80. package/src/notifications/controller.ts +215 -61
  81. package/src/notifications/direct.ts +3 -1
  82. package/src/notifications/generated/fields.ts +2 -2
  83. package/src/notifications/ports.ts +7 -3
  84. package/src/notifications/serialized.ts +11 -9
  85. package/src/notifications/validation.ts +147 -43
  86. package/src/operation/bridge.ts +117 -50
  87. package/src/operation/client.ts +38 -24
  88. package/src/operation/controller.ts +33 -42
  89. package/src/operation/direct.ts +1 -3
  90. package/src/operation/generated/fields.ts +2 -2
  91. package/src/operation/ports.ts +10 -9
  92. package/src/operation/serialized.ts +8 -9
  93. package/src/operation/validation.ts +152 -65
  94. package/src/settings/client.ts +11 -44
  95. package/src/settings/connection.ts +26 -40
  96. package/src/settings/generated/fields.ts +3 -3
  97. package/src/settings/generated/protocol.ts +9 -4
  98. package/src/settings/names.ts +2 -4
  99. package/src/settings/registry.ts +23 -25
  100. package/src/settings/validation/authority.ts +19 -17
  101. package/src/settings/validation/command.ts +17 -37
  102. package/src/settings/validation/error.ts +2 -8
  103. package/src/settings/validation/primitives.ts +26 -42
  104. package/src/settings/validation/projection.ts +8 -24
  105. package/src/settings/validation/registry.ts +25 -73
  106. package/src/surface-transfer/client.ts +6 -18
  107. package/src/surface-transfer/generated/fields.ts +2 -2
  108. package/src/surface-transfer/validation.ts +31 -49
  109. package/src/surfaces/client.ts +12 -22
  110. package/src/surfaces/generated/fields.ts +2 -2
  111. package/src/surfaces/validation.ts +40 -49
  112. package/src/transfer/client.ts +26 -60
  113. package/src/transfer/connection.ts +12 -20
  114. package/src/transfer/generated/fields.ts +5 -5
  115. package/src/transfer/generated/protocol.ts +4 -4
  116. package/src/transfer/payload.ts +13 -31
  117. package/src/transfer/validation.ts +39 -75
  118. package/src/update/client.ts +59 -9
  119. package/src/update/controller.ts +113 -48
  120. package/src/update/direct.ts +3 -1
  121. package/src/update/generated/fields.ts +3 -3
  122. package/src/update/generated/protocol.ts +7 -3
  123. package/src/update/generated/variant-fields.ts +1 -0
  124. package/src/update/ports.ts +6 -2
  125. package/src/update/serialized.ts +34 -10
  126. package/src/update/validation.ts +115 -35
@@ -1,6 +1,8 @@
1
+ import { CheckedSnapshotConnection } from "@inflatable-cookie/longhorn/core";
1
2
  import type {
2
3
  ConnectionFailure,
3
4
  ConnectionFailureReporter,
5
+ SnapshotEventAction,
4
6
  } from "@inflatable-cookie/longhorn/core";
5
7
 
6
8
  import {
@@ -11,21 +13,22 @@ import {
11
13
  assertValidNativeContentDecisionResult,
12
14
  assertValidNativeContentDesiredUpdateRequest,
13
15
  assertValidNativeContentDesiredUpdateResult,
16
+ assertValidNativeContentSnapshot,
14
17
  assertValidNativeContentSnapshotRequest,
15
18
  assertValidNativeContentSnapshotResult,
16
19
  } from "./validation.ts";
17
- import {
18
- NATIVE_CONTENT_PROTOCOL_VERSION,
19
- type ContentSizeDecision,
20
- type ContentSizeProposal,
21
- type DesiredUpdate,
22
- type NativeContentChangedEvent,
23
- type NativeContentContentSizeDecisionResult,
24
- type NativeContentDesiredUpdateResult,
25
- type NativeContentIslandId,
26
- type NativeContentSnapshot,
20
+ import { NATIVE_CONTENT_PROTOCOL_VERSION } from "./generated/protocol.ts";
21
+ import type {
22
+ ContentSizeDecision,
23
+ ContentSizeProposal,
24
+ DesiredUpdate,
25
+ NativeContentContentSizeDecisionResult,
26
+ NativeContentDesiredUpdateResult,
27
+ NativeContentIslandId,
28
+ NativeContentProtocolRejection,
29
+ NativeContentSnapshot,
27
30
  } from "./generated/protocol.ts";
28
- import type { NativeContentPort, NativeContentUnlisten } from "./ports.ts";
31
+ import type { NativeContentPort } from "./ports.ts";
29
32
 
30
33
  const DEFAULT_MAXIMUM_PENDING_REQUESTS = 32;
31
34
 
@@ -36,7 +39,7 @@ export interface NativeContentClientOptions {
36
39
  export interface NativeContentConnection {
37
40
  readonly ready: Promise<NativeContentSnapshot>;
38
41
  current(): NativeContentSnapshot | undefined;
39
- failures(): readonly ConnectionFailure[];
42
+ failures(): ReadonlyArray<ConnectionFailure>;
40
43
  updateDesired(update: DesiredUpdate): Promise<NativeContentDesiredUpdateResult>;
41
44
  decideContentSize(
42
45
  proposal: ContentSizeProposal,
@@ -55,8 +58,7 @@ export class NativeContentClient {
55
58
  islandId: NativeContentIslandId,
56
59
  options: NativeContentClientOptions = {},
57
60
  ) {
58
- const maximum =
59
- options.maximumPendingRequests ?? DEFAULT_MAXIMUM_PENDING_REQUESTS;
61
+ const maximum = options.maximumPendingRequests ?? DEFAULT_MAXIMUM_PENDING_REQUESTS;
60
62
  if (!Number.isSafeInteger(maximum) || maximum < 1) {
61
63
  throw new RangeError("maximumPendingRequests must be a positive integer");
62
64
  }
@@ -79,21 +81,19 @@ export class NativeContentClient {
79
81
  }
80
82
  }
81
83
 
84
+ /**
85
+ * Native-content lifetime on the shared snapshot connection: listener first,
86
+ * connect for the first authoritative snapshot, then refresh on events. This
87
+ * class adds only what is native-content specific: the connect/snapshot
88
+ * requests, the event cursor rules and the bounded mutation requests.
89
+ */
82
90
  class CheckedNativeContentConnection implements NativeContentConnection {
83
91
  readonly ready: Promise<NativeContentSnapshot>;
84
92
  readonly #port: NativeContentPort;
85
93
  readonly #islandId: NativeContentIslandId;
86
94
  readonly #maximumPendingRequests: number;
87
- readonly #listener: ((snapshot: NativeContentSnapshot) => void) | undefined;
88
- readonly #onFailure: ConnectionFailureReporter | undefined;
89
- readonly #failures: ConnectionFailure[] = [];
95
+ readonly #connection: CheckedSnapshotConnection<NativeContentSnapshot>;
90
96
  readonly #pending = new Set<string>();
91
- readonly #queuedEvents: NativeContentChangedEvent[] = [];
92
- #snapshot: NativeContentSnapshot | undefined;
93
- #unlisten: NativeContentUnlisten | undefined;
94
- #cleanup: Promise<void> | undefined;
95
- #pump: Promise<void> | undefined;
96
- #refreshPending = false;
97
97
  #disposed = false;
98
98
 
99
99
  constructor(
@@ -106,39 +106,51 @@ class CheckedNativeContentConnection implements NativeContentConnection {
106
106
  this.#port = port;
107
107
  this.#islandId = islandId;
108
108
  this.#maximumPendingRequests = maximumPendingRequests;
109
- this.#listener = listener;
110
- this.#onFailure = onFailure;
111
- this.ready = this.#start();
109
+ this.#connection = new CheckedSnapshotConnection<NativeContentSnapshot>({
110
+ listen: async (receive) => (port.listen === undefined ? () => {} : port.listen(receive)),
111
+ loadSnapshot: () => this.#loadSnapshot(),
112
+ validateSnapshot: parseSnapshot,
113
+ handleEvent: (payload, current) => eventAction(payload, current, islandId),
114
+ isNewer: isNewerSessionSnapshot,
115
+ onSnapshot: listener,
116
+ onFailure,
117
+ disposedBeforeReadyError: () => new NativeContentConnectionDisposedError(),
118
+ });
119
+ this.ready = this.#connection.ready.then((snapshot) => {
120
+ if (snapshot === undefined) {
121
+ throw new NativeContentConnectionUnavailableError();
122
+ }
123
+ return snapshot;
124
+ });
112
125
  }
113
126
 
114
127
  current(): NativeContentSnapshot | undefined {
115
- return this.#snapshot;
128
+ return this.#connection.current();
116
129
  }
117
130
 
118
- failures(): readonly ConnectionFailure[] {
119
- return [...this.#failures];
131
+ failures(): ReadonlyArray<ConnectionFailure> {
132
+ return this.#connection.failures();
120
133
  }
121
134
 
122
- async updateDesired(
123
- update: DesiredUpdate,
124
- ): Promise<NativeContentDesiredUpdateResult> {
135
+ async updateDesired(update: DesiredUpdate): Promise<NativeContentDesiredUpdateResult> {
125
136
  const current = await this.#requireCurrent();
126
137
  const requestId = this.#beginRequest();
127
- const session = sessionCursor(current);
128
- const request = {
129
- protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
130
- request_id: requestId,
131
- island_id: this.#islandId,
132
- client_epoch: current.cursor.client_epoch,
133
- expected_desired_revision: current.cursor.desired_revision,
134
- update,
135
- };
136
- assertValidNativeContentDesiredUpdateRequest(request);
137
138
  try {
139
+ const request = {
140
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
141
+ request_id: requestId,
142
+ island_id: this.#islandId,
143
+ client_epoch: current.cursor.client_epoch,
144
+ expected_desired_revision: current.cursor.desired_revision,
145
+ update,
146
+ };
147
+ assertValidNativeContentDesiredUpdateRequest(request);
138
148
  const value = await this.#port.updateDesired(request);
139
149
  assertValidNativeContentDesiredUpdateResult(value);
140
150
  assertCorrelation(value.request_id, requestId);
141
- if (value.status === "committed") this.#offer(value.snapshot, session);
151
+ if (value.status === "committed") {
152
+ this.#connection.offer(value.snapshot);
153
+ }
142
154
  return value;
143
155
  } finally {
144
156
  this.#pending.delete(requestId);
@@ -151,21 +163,22 @@ class CheckedNativeContentConnection implements NativeContentConnection {
151
163
  ): Promise<NativeContentContentSizeDecisionResult> {
152
164
  const current = await this.#requireCurrent();
153
165
  const requestId = this.#beginRequest();
154
- const session = sessionCursor(current);
155
- const request = {
156
- protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
157
- request_id: requestId,
158
- island_id: this.#islandId,
159
- client_epoch: current.cursor.client_epoch,
160
- proposal,
161
- decision,
162
- };
163
- assertValidNativeContentDecisionRequest(request);
164
166
  try {
167
+ const request = {
168
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
169
+ request_id: requestId,
170
+ island_id: this.#islandId,
171
+ client_epoch: current.cursor.client_epoch,
172
+ proposal,
173
+ decision,
174
+ };
175
+ assertValidNativeContentDecisionRequest(request);
165
176
  const value = await this.#port.decideContentSize(request);
166
177
  assertValidNativeContentDecisionResult(value);
167
178
  assertCorrelation(value.request_id, requestId);
168
- if (value.status === "decided") this.#offer(value.snapshot, session);
179
+ if (value.status === "decided") {
180
+ this.#connection.offer(value.snapshot);
181
+ }
169
182
  return value;
170
183
  } finally {
171
184
  this.#pending.delete(requestId);
@@ -175,170 +188,75 @@ class CheckedNativeContentConnection implements NativeContentConnection {
175
188
  async dispose(): Promise<void> {
176
189
  this.#disposed = true;
177
190
  this.#pending.clear();
178
- await this.#closeListener();
179
191
  try {
180
- await this.ready;
181
- } catch {
182
- // Registration/start failures are already retained in failures().
183
- }
184
- await this.#closeListener();
185
- }
186
-
187
- async #start(): Promise<NativeContentSnapshot> {
188
- try {
189
- this.#unlisten =
190
- this.#port.listen === undefined
191
- ? () => {}
192
- : await this.#port.listen((value) => this.#handleEvent(value));
192
+ await this.#connection.dispose();
193
193
  } catch (error) {
194
- this.#recordFailure("registration", error);
195
- throw error;
196
- }
197
-
198
- if (this.#disposed) {
199
- await this.#closeListener();
200
- throw new NativeContentConnectionDisposedError();
201
- }
202
-
203
- try {
204
- const requestId = this.#port.nextRequestId();
205
- const request = {
206
- protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
207
- request_id: requestId,
208
- island_id: this.#islandId,
209
- };
210
- assertValidNativeContentConnectRequest(request);
211
- const value = await this.#port.connect(request);
212
- assertValidNativeContentConnectResult(value);
213
- assertCorrelation(value.request_id, requestId);
214
- if (value.status === "rejected") {
215
- throw new NativeContentRequestRejectedError(value.rejection);
216
- }
217
- if (this.#disposed) {
218
- await this.#closeListener();
219
- throw new NativeContentConnectionDisposedError();
194
+ // A failed start is already retained in failures(). Disposing the
195
+ // connection is not a second failure, so only a teardown error rejects.
196
+ const reported = this.#connection
197
+ .failures()
198
+ .some((failure) => failure.phase !== "unlisten" && failure.error === error);
199
+ if (!reported) {
200
+ throw error;
220
201
  }
221
- this.#install(value.snapshot);
222
- for (const event of this.#queuedEvents.splice(0)) this.#acceptEvent(event);
223
- await this.#synchronize();
224
- const current = this.#snapshot;
225
- if (current === undefined) throw new Error("native-content connect returned no snapshot");
226
- return current;
227
- } catch (error) {
228
- this.#recordFailure("snapshot", error);
229
- await this.#closeAfterFailure();
230
- throw error;
231
202
  }
232
203
  }
233
204
 
234
- #handleEvent(value: unknown): void {
235
- if (this.#disposed || this.#failures.length > 0) return;
236
- try {
237
- assertValidNativeContentChangedEvent(value);
238
- if (value.cursor.island_id !== this.#islandId) return;
239
- if (this.#snapshot === undefined) {
240
- this.#queuedEvents.push(value);
241
- return;
242
- }
243
- this.#acceptEvent(value);
244
- } catch (error) {
245
- this.#recordFailure("event", error);
246
- void this.#closeAfterFailure();
247
- }
205
+ async #loadSnapshot(): Promise<unknown> {
206
+ const current = this.#connection.current();
207
+ return current === undefined ? this.#connect() : this.#refresh(current);
248
208
  }
249
209
 
250
- #acceptEvent(event: NativeContentChangedEvent): void {
251
- const current = this.#snapshot;
252
- if (current === undefined) return;
253
- const currentCursor = current.cursor;
254
- if (event.cursor.authority_epoch < currentCursor.authority_epoch) return;
255
- if (
256
- event.cursor.authority_epoch > currentCursor.authority_epoch ||
257
- event.cursor.client_epoch > currentCursor.client_epoch
258
- ) {
259
- throw new NativeContentSessionReplacedError();
260
- }
261
- if (event.cursor.client_epoch < currentCursor.client_epoch) return;
262
- if (
263
- event.cursor.desired_revision <= currentCursor.desired_revision &&
264
- event.cursor.observed_revision <= currentCursor.observed_revision
265
- ) {
266
- return;
267
- }
268
- this.#refreshPending = true;
269
- void this.#synchronize().catch((error) => {
270
- this.#recordFailure("snapshot", error);
271
- void this.#closeAfterFailure();
272
- });
273
- }
274
-
275
- #synchronize(): Promise<void> {
276
- if (this.#disposed || this.#failures.length > 0 || !this.#refreshPending) {
277
- return Promise.resolve();
278
- }
279
- this.#pump ??= this.#runPump().finally(() => {
280
- this.#pump = undefined;
281
- });
282
- return this.#pump;
283
- }
284
-
285
- async #runPump(): Promise<void> {
286
- while (this.#refreshPending && !this.#disposed && this.#failures.length === 0) {
287
- this.#refreshPending = false;
288
- const current = this.#snapshot;
289
- if (current === undefined) return;
290
- const requestId = this.#port.nextRequestId();
291
- const request = {
292
- protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
293
- request_id: requestId,
294
- island_id: this.#islandId,
295
- client_epoch: current.cursor.client_epoch,
296
- };
297
- assertValidNativeContentSnapshotRequest(request);
298
- const value = await this.#port.snapshot(request);
299
- assertValidNativeContentSnapshotResult(value);
300
- assertCorrelation(value.request_id, requestId);
301
- if (value.status === "rejected") {
302
- throw new NativeContentRequestRejectedError(value.rejection);
303
- }
304
- this.#offer(value.snapshot, sessionCursor(current));
210
+ async #connect(): Promise<unknown> {
211
+ const requestId = this.#port.nextRequestId();
212
+ const request = {
213
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
214
+ request_id: requestId,
215
+ island_id: this.#islandId,
216
+ };
217
+ assertValidNativeContentConnectRequest(request);
218
+ const value = await this.#port.connect(request);
219
+ assertValidNativeContentConnectResult(value);
220
+ assertCorrelation(value.request_id, requestId);
221
+ if (value.status === "rejected") {
222
+ throw new NativeContentRequestRejectedError(value.rejection);
305
223
  }
224
+ return value.snapshot;
306
225
  }
307
226
 
308
- #offer(snapshot: NativeContentSnapshot, session: SessionCursor): void {
309
- if (this.#disposed) return;
310
- const current = this.#snapshot;
311
- if (current === undefined) return;
312
- if (
313
- current.cursor.authority_epoch !== session.authorityEpoch ||
314
- current.cursor.client_epoch !== session.clientEpoch ||
315
- snapshot.cursor.authority_epoch !== session.authorityEpoch ||
316
- snapshot.cursor.client_epoch !== session.clientEpoch
317
- ) {
318
- return;
227
+ async #refresh(current: NativeContentSnapshot): Promise<unknown> {
228
+ const requestId = this.#port.nextRequestId();
229
+ const request = {
230
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
231
+ request_id: requestId,
232
+ island_id: this.#islandId,
233
+ client_epoch: current.cursor.client_epoch,
234
+ };
235
+ assertValidNativeContentSnapshotRequest(request);
236
+ const value = await this.#port.snapshot(request);
237
+ assertValidNativeContentSnapshotResult(value);
238
+ assertCorrelation(value.request_id, requestId);
239
+ if (value.status === "rejected") {
240
+ throw new NativeContentRequestRejectedError(value.rejection);
319
241
  }
320
- if (!isNewerSnapshot(snapshot, current)) return;
321
- this.#install(snapshot);
322
- }
323
-
324
- #install(snapshot: NativeContentSnapshot): void {
325
- this.#snapshot = snapshot;
326
- this.#listener?.(snapshot);
242
+ return value.snapshot;
327
243
  }
328
244
 
329
245
  async #requireCurrent(): Promise<NativeContentSnapshot> {
330
246
  await this.ready;
331
- if (this.#disposed) throw new NativeContentConnectionDisposedError();
332
- const current = this.#snapshot;
333
- if (current === undefined) throw new NativeContentConnectionUnavailableError();
247
+ if (this.#disposed) {
248
+ throw new NativeContentConnectionDisposedError();
249
+ }
250
+ const current = this.#connection.current();
251
+ if (current === undefined) {
252
+ throw new NativeContentConnectionUnavailableError();
253
+ }
334
254
  return current;
335
255
  }
336
256
 
337
257
  #beginRequest(): string {
338
258
  if (this.#pending.size >= this.#maximumPendingRequests) {
339
- throw new NativeContentPendingRequestLimitError(
340
- this.#maximumPendingRequests,
341
- );
259
+ throw new NativeContentPendingRequestLimitError(this.#maximumPendingRequests);
342
260
  }
343
261
  const requestId = this.#port.nextRequestId();
344
262
  if (this.#pending.has(requestId)) {
@@ -347,53 +265,84 @@ class CheckedNativeContentConnection implements NativeContentConnection {
347
265
  this.#pending.add(requestId);
348
266
  return requestId;
349
267
  }
268
+ }
350
269
 
351
- #recordFailure(phase: ConnectionFailure["phase"], error: unknown): void {
352
- if (this.#failures.some((failure) => failure.phase === phase && failure.error === error)) return;
353
- const failure = { phase, error };
354
- this.#failures.push(failure);
355
- this.#onFailure?.(failure);
356
- }
270
+ function parseSnapshot(value: unknown): NativeContentSnapshot {
271
+ assertValidNativeContentSnapshot(value);
272
+ return value;
273
+ }
357
274
 
358
- async #closeAfterFailure(): Promise<void> {
359
- try {
360
- await this.#closeListener();
361
- } catch (error) {
362
- this.#recordFailure("unlisten", error);
363
- }
275
+ function eventAction(
276
+ payload: unknown,
277
+ current: NativeContentSnapshot | undefined,
278
+ islandId: NativeContentIslandId,
279
+ ): SnapshotEventAction {
280
+ assertValidNativeContentChangedEvent(payload);
281
+ const event = payload.cursor;
282
+ if (event.island_id !== islandId) {
283
+ return { kind: "ignore" };
364
284
  }
365
-
366
- #closeListener(): Promise<void> {
367
- if (this.#cleanup !== undefined) return this.#cleanup;
368
- const unlisten = this.#unlisten;
369
- if (unlisten === undefined) return Promise.resolve();
370
- this.#unlisten = undefined;
371
- this.#cleanup = Promise.resolve().then(() => unlisten());
372
- return this.#cleanup;
285
+ if (current === undefined) {
286
+ return { kind: "refresh" };
373
287
  }
374
- }
375
288
 
376
- interface SessionCursor {
377
- readonly authorityEpoch: number;
378
- readonly clientEpoch: number;
289
+ const currentCursor = current.cursor;
290
+ if (event.authority_epoch < currentCursor.authority_epoch) {
291
+ return { kind: "ignore" };
292
+ }
293
+ if (
294
+ event.authority_epoch > currentCursor.authority_epoch ||
295
+ event.client_epoch > currentCursor.client_epoch
296
+ ) {
297
+ throw new NativeContentSessionReplacedError();
298
+ }
299
+ if (event.client_epoch < currentCursor.client_epoch) {
300
+ return { kind: "ignore" };
301
+ }
302
+ if (
303
+ event.desired_revision <= currentCursor.desired_revision &&
304
+ event.observed_revision <= currentCursor.observed_revision
305
+ ) {
306
+ return { kind: "ignore" };
307
+ }
308
+ return { kind: "refresh" };
379
309
  }
380
310
 
381
- function sessionCursor(snapshot: NativeContentSnapshot): SessionCursor {
382
- return {
383
- authorityEpoch: snapshot.cursor.authority_epoch,
384
- clientEpoch: snapshot.cursor.client_epoch,
385
- };
311
+ /**
312
+ * A snapshot only replaces the current one within the same authority and
313
+ * client epoch. A different session cannot arrive by refresh or by request
314
+ * result: an authority or client epoch change is a session replacement, which
315
+ * the event path reports as a failure.
316
+ */
317
+ function isNewerSessionSnapshot(
318
+ candidate: NativeContentSnapshot,
319
+ current: NativeContentSnapshot | undefined,
320
+ ): boolean {
321
+ if (current === undefined) {
322
+ return true;
323
+ }
324
+ if (
325
+ candidate.cursor.authority_epoch !== current.cursor.authority_epoch ||
326
+ candidate.cursor.client_epoch !== current.cursor.client_epoch
327
+ ) {
328
+ return false;
329
+ }
330
+ return isNewerNativeContentSnapshot(candidate, current);
386
331
  }
387
332
 
388
333
  export function isNewerNativeContentSnapshot(
389
334
  candidate: NativeContentSnapshot,
390
335
  current: NativeContentSnapshot | undefined,
391
336
  ): boolean {
392
- if (current === undefined) return true;
337
+ if (current === undefined) {
338
+ return true;
339
+ }
393
340
  if (candidate.cursor.authority_epoch !== current.cursor.authority_epoch) {
394
341
  return candidate.cursor.authority_epoch > current.cursor.authority_epoch;
395
342
  }
396
- if (candidate.cursor.client_epoch !== current.cursor.client_epoch) return false;
343
+ if (candidate.cursor.client_epoch !== current.cursor.client_epoch) {
344
+ return false;
345
+ }
397
346
  if (
398
347
  candidate.cursor.desired_revision < current.cursor.desired_revision ||
399
348
  candidate.cursor.observed_revision < current.cursor.observed_revision
@@ -406,13 +355,6 @@ export function isNewerNativeContentSnapshot(
406
355
  );
407
356
  }
408
357
 
409
- function isNewerSnapshot(
410
- candidate: NativeContentSnapshot,
411
- current: NativeContentSnapshot,
412
- ): boolean {
413
- return isNewerNativeContentSnapshot(candidate, current);
414
- }
415
-
416
358
  function assertCorrelation(received: string, expected: string): void {
417
359
  if (received !== expected) {
418
360
  throw new NativeContentResponseCorrelationError(expected, received);
@@ -432,7 +374,7 @@ export class NativeContentResponseCorrelationError extends Error {
432
374
  }
433
375
 
434
376
  export class NativeContentRequestRejectedError extends Error {
435
- constructor(readonly rejection: import("./generated/protocol.ts").NativeContentProtocolRejection) {
377
+ constructor(readonly rejection: NativeContentProtocolRejection) {
436
378
  super(rejection.message);
437
379
  this.name = "NativeContentRequestRejectedError";
438
380
  }
@@ -3,7 +3,7 @@
3
3
  // A `record()` given one of these rejects unknown and missing keys —
4
4
  // contract 010's Boundary Validation Target.
5
5
 
6
- export const NATIVE_CONTENT_FIELDS: Record<string, readonly string[]> = {
6
+ export const NATIVE_CONTENT_FIELDS = {
7
7
  "ClientPoint": ["x", "y"],
8
8
  "ClientSize": ["width", "height"],
9
9
  "ClientRect": ["origin", "size"],
@@ -29,4 +29,4 @@ export const NATIVE_CONTENT_FIELDS: Record<string, readonly string[]> = {
29
29
  "NativeContentDesiredUpdateRequest": ["protocol_version", "request_id", "island_id", "client_epoch", "expected_desired_revision", "update"],
30
30
  "NativeContentContentSizeDecisionRequest": ["protocol_version", "request_id", "island_id", "client_epoch", "proposal", "decision"],
31
31
  "NativeContentChangedEvent": ["protocol_version", "cursor", "change"],
32
- };
32
+ } as const;
@@ -17,30 +17,24 @@ export interface NativeContentPort {
17
17
  connect(request: NativeContentConnectRequest): Promise<unknown>;
18
18
  snapshot(request: NativeContentSnapshotRequest): Promise<unknown>;
19
19
  updateDesired(request: NativeContentDesiredUpdateRequest): Promise<unknown>;
20
- decideContentSize(
21
- request: NativeContentContentSizeDecisionRequest,
22
- ): Promise<unknown>;
23
- listen?(
24
- listener: (event: unknown) => void,
25
- ): NativeContentUnlisten | Promise<NativeContentUnlisten>;
20
+ decideContentSize(request: NativeContentContentSizeDecisionRequest): Promise<unknown>;
21
+ listen?:
22
+ | ((
23
+ listener: (event: unknown) => void,
24
+ ) => NativeContentUnlisten | Promise<NativeContentUnlisten>)
25
+ | undefined;
26
26
  nextRequestId(): NativeContentRequestId;
27
27
  }
28
28
 
29
29
  export interface CheckedNativeContentPort {
30
- connect(
31
- request: NativeContentConnectRequest,
32
- ): Promise<NativeContentConnectResult>;
33
- snapshot(
34
- request: NativeContentSnapshotRequest,
35
- ): Promise<NativeContentSnapshotResult>;
30
+ connect(request: NativeContentConnectRequest): Promise<NativeContentConnectResult>;
31
+ snapshot(request: NativeContentSnapshotRequest): Promise<NativeContentSnapshotResult>;
36
32
  updateDesired(
37
33
  request: NativeContentDesiredUpdateRequest,
38
34
  ): Promise<NativeContentDesiredUpdateResult>;
39
35
  decideContentSize(
40
36
  request: NativeContentContentSizeDecisionRequest,
41
37
  ): Promise<NativeContentContentSizeDecisionResult>;
42
- listen?(
43
- listener: (event: NativeContentChangedEvent) => void,
44
- ): Promise<NativeContentUnlisten>;
38
+ listen?(listener: (event: NativeContentChangedEvent) => void): Promise<NativeContentUnlisten>;
45
39
  nextRequestId(): NativeContentRequestId;
46
40
  }
@@ -1,3 +1,4 @@
1
+ import { wireCopy } from "../core/wire-copy.ts";
1
2
  import type {
2
3
  NativeContentConnectRequest,
3
4
  NativeContentContentSizeDecisionRequest,
@@ -14,37 +15,29 @@ export class SerializedNativeContentPort implements NativeContentPort {
14
15
  }
15
16
 
16
17
  async connect(request: NativeContentConnectRequest): Promise<unknown> {
17
- return clone(await this.#inner.connect(clone(request)));
18
+ return wireCopy(await this.#inner.connect(wireCopy(request)));
18
19
  }
19
20
 
20
21
  async snapshot(request: NativeContentSnapshotRequest): Promise<unknown> {
21
- return clone(await this.#inner.snapshot(clone(request)));
22
+ return wireCopy(await this.#inner.snapshot(wireCopy(request)));
22
23
  }
23
24
 
24
- async updateDesired(
25
- request: NativeContentDesiredUpdateRequest,
26
- ): Promise<unknown> {
27
- return clone(await this.#inner.updateDesired(clone(request)));
25
+ async updateDesired(request: NativeContentDesiredUpdateRequest): Promise<unknown> {
26
+ return wireCopy(await this.#inner.updateDesired(wireCopy(request)));
28
27
  }
29
28
 
30
- async decideContentSize(
31
- request: NativeContentContentSizeDecisionRequest,
32
- ): Promise<unknown> {
33
- return clone(await this.#inner.decideContentSize(clone(request)));
29
+ async decideContentSize(request: NativeContentContentSizeDecisionRequest): Promise<unknown> {
30
+ return wireCopy(await this.#inner.decideContentSize(wireCopy(request)));
34
31
  }
35
32
 
36
- async listen(
37
- listener: (event: unknown) => void,
38
- ): Promise<NativeContentUnlisten> {
39
- if (this.#inner.listen === undefined) return () => {};
40
- return this.#inner.listen((event) => listener(clone(event)));
33
+ async listen(listener: (event: unknown) => void): Promise<NativeContentUnlisten> {
34
+ if (this.#inner.listen === undefined) {
35
+ return () => {};
36
+ }
37
+ return this.#inner.listen((event) => listener(wireCopy(event)));
41
38
  }
42
39
 
43
40
  nextRequestId(): string {
44
41
  return this.#inner.nextRequestId();
45
42
  }
46
43
  }
47
-
48
- function clone<Value>(value: Value): Value {
49
- return JSON.parse(JSON.stringify(value)) as Value;
50
- }