@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,4 +1,5 @@
1
- import { isRecord } from "../core/record.ts";
1
+ import { isOpaqueId } from "../core/identifiers.ts";
2
+ import { checkWireFields, readWireRecord, wireVariantFields } from "../core/record.ts";
2
3
  import {
3
4
  NOTIFICATION_VARIANT_FIELDS,
4
5
  NOTIFICATION_VARIANT_FIELDS_DISCRIMINANTS,
@@ -8,6 +9,9 @@ import {
8
9
  NOTIFICATION_CHANGED_KINDS,
9
10
  NOTIFICATION_MUTATION_KINDS,
10
11
  NOTIFICATION_MUTATION_STATUSES,
12
+ NOTIFICATION_CLEAR_TARGET_KINDS,
13
+ NOTIFICATION_RECEIPT_KINDS,
14
+ NOTIFICATION_REMOVAL_REASONS,
11
15
  NOTIFICATION_PROTOCOL_VERSION,
12
16
  NOTIFICATION_READ_STATES,
13
17
  NOTIFICATION_REJECTION_CODES,
@@ -39,7 +43,7 @@ export function assertValidNotificationSnapshotQuery(
39
43
  ): asserts value is NotificationSnapshotQuery {
40
44
  const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationSnapshotQuery);
41
45
  protocol(object.protocolVersion, "$.protocolVersion");
42
- text(object.requestId, "$.requestId");
46
+ opaqueId(object.requestId, "$.requestId");
43
47
  natural(object.offset, "$.offset");
44
48
  natural(object.limit, "$.limit");
45
49
  }
@@ -48,7 +52,7 @@ export function assertValidNotificationSnapshotResponse(
48
52
  value: unknown,
49
53
  ): asserts value is NotificationSnapshotResponse {
50
54
  const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationSnapshotResponse);
51
- text(object.requestId, "$.requestId");
55
+ opaqueId(object.requestId, "$.requestId");
52
56
  assertValidNotificationSnapshot(object.snapshot);
53
57
  }
54
58
 
@@ -79,13 +83,13 @@ export function assertValidNotificationMutationCommand(
79
83
  const object = record(value, "$");
80
84
  member(object.kind, NOTIFICATION_MUTATION_KINDS, "$.kind");
81
85
  protocol(object.protocolVersion, "$.protocolVersion");
82
- text(object.requestId, "$.requestId");
86
+ opaqueId(object.requestId, "$.requestId");
83
87
  authority(object.authority, "$.authority");
84
88
  natural(object.expectedLedgerRevision, "$.expectedLedgerRevision");
85
89
  switch (object.kind) {
86
90
  case "add":
87
91
  exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
88
- text(object.notificationId, "$.notificationId");
92
+ opaqueId(object.notificationId, "$.notificationId");
89
93
  draft(object.draft, "$.draft");
90
94
  break;
91
95
  case "replace":
@@ -96,12 +100,12 @@ export function assertValidNotificationMutationCommand(
96
100
  case "markSeen":
97
101
  case "dismiss":
98
102
  exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
99
- text(object.notificationId, "$.notificationId");
103
+ opaqueId(object.notificationId, "$.notificationId");
100
104
  break;
101
105
  case "clear": {
102
106
  exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
103
107
  const target = record(object.target, "$.target");
104
- member(target.kind, ["all", "records"] as const, "$.target.kind");
108
+ member(target.kind, NOTIFICATION_CLEAR_TARGET_KINDS, "$.target.kind");
105
109
  exactKeys(
106
110
  target,
107
111
  "$.target",
@@ -109,7 +113,7 @@ export function assertValidNotificationMutationCommand(
109
113
  );
110
114
  if (target.kind === "records") {
111
115
  array(target.notificationIds, "$.target.notificationIds").forEach((id, index) =>
112
- text(id, `$.target.notificationIds[${index}]`),
116
+ opaqueId(id, `$.target.notificationIds[${index}]`),
113
117
  );
114
118
  }
115
119
  break;
@@ -126,7 +130,7 @@ export function assertValidNotificationMutationResult(
126
130
  ): asserts value is NotificationMutationResult {
127
131
  const object = record(value, "$");
128
132
  member(object.status, NOTIFICATION_MUTATION_STATUSES, "$.status");
129
- text(object.requestId, "$.requestId");
133
+ opaqueId(object.requestId, "$.requestId");
130
134
  assertValidNotificationSnapshot(object.snapshot);
131
135
  if (object.status === "committed") {
132
136
  exactKeys(object, "$", variantKeys("NotificationMutationResult", object, "$"));
@@ -149,19 +153,19 @@ export function assertValidNotificationChangedEvent(
149
153
  ): asserts value is NotificationChangedEvent {
150
154
  const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationChangedEvent);
151
155
  protocol(object.protocolVersion, "$.protocolVersion");
152
- text(object.requestId, "$.requestId");
156
+ opaqueId(object.requestId, "$.requestId");
153
157
  authority(object.authority, "$.authority");
154
158
  natural(object.previousLedgerRevision, "$.previousLedgerRevision");
155
159
  natural(object.committedLedgerRevision, "$.committedLedgerRevision");
156
160
  array(object.affectedNotificationIds, "$.affectedNotificationIds").forEach((id, index) =>
157
- text(id, `$.affectedNotificationIds[${index}]`),
161
+ opaqueId(id, `$.affectedNotificationIds[${index}]`),
158
162
  );
159
163
  member(object.kind, NOTIFICATION_CHANGED_KINDS, "$.kind");
160
164
  }
161
165
 
162
166
  function authority(value: unknown, path: string): void {
163
167
  const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationAuthorityProjection);
164
- text(object.authorityId, `${path}.authorityId`);
168
+ opaqueId(object.authorityId, `${path}.authorityId`);
165
169
  positive(object.authorityEpoch, `${path}.authorityEpoch`);
166
170
  }
167
171
 
@@ -173,22 +177,22 @@ function limits(value: unknown, path: string): void {
173
177
 
174
178
  function draft(value: unknown, path: string): void {
175
179
  const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationDraftProjection);
176
- text(object.sourceId, `${path}.sourceId`);
180
+ opaqueId(object.sourceId, `${path}.sourceId`);
177
181
  member(object.severity, NOTIFICATION_SEVERITIES, `${path}.severity`);
178
182
  text(object.title, `${path}.title`);
179
183
  text(object.summary, `${path}.summary`);
180
- nullableText(object.causeId, `${path}.causeId`);
184
+ nullableOpaqueId(object.causeId, `${path}.causeId`);
181
185
  array(object.actions, `${path}.actions`).forEach((action, index) => {
182
186
  const item = exact(
183
187
  action,
184
188
  `${path}.actions[${index}]`,
185
189
  NOTIFICATIONS_FIELDS.NotificationActionProjection,
186
190
  );
187
- text(item.referenceId, `${path}.actions[${index}].referenceId`);
191
+ opaqueId(item.referenceId, `${path}.actions[${index}].referenceId`);
188
192
  text(item.label, `${path}.actions[${index}].label`);
189
193
  });
190
- nullableText(object.replacementKey, `${path}.replacementKey`);
191
- nullableText(object.producerToken, `${path}.producerToken`);
194
+ nullableOpaqueId(object.replacementKey, `${path}.replacementKey`);
195
+ nullableOpaqueId(object.producerToken, `${path}.producerToken`);
192
196
  member(object.retentionClass, NOTIFICATION_RETENTION_CLASSES, `${path}.retentionClass`);
193
197
  if (object.presentationTimeUnixMs !== null) {
194
198
  integer(object.presentationTimeUnixMs, `${path}.presentationTimeUnixMs`);
@@ -200,7 +204,7 @@ function recordProjection(
200
204
  path: string,
201
205
  ): asserts value is NotificationRecordProjection {
202
206
  const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationRecordProjection);
203
- text(object.notificationId, `${path}.notificationId`);
207
+ opaqueId(object.notificationId, `${path}.notificationId`);
204
208
  draft(object.draft, `${path}.draft`);
205
209
  positive(object.sequence, `${path}.sequence`);
206
210
  positive(object.lastChangedLedgerRevision, `${path}.lastChangedLedgerRevision`);
@@ -210,11 +214,7 @@ function recordProjection(
210
214
 
211
215
  function receipt(value: unknown, path: string): void {
212
216
  const object = record(value, path);
213
- member(
214
- object.kind,
215
- ["added", "replaced", "seen", "removed", "retentionChanged"] as const,
216
- `${path}.kind`,
217
- );
217
+ member(object.kind, NOTIFICATION_RECEIPT_KINDS, `${path}.kind`);
218
218
  natural(object.previousLedgerRevision, `${path}.previousLedgerRevision`);
219
219
  natural(object.committedLedgerRevision, `${path}.committedLedgerRevision`);
220
220
  if (object.kind === "added" || object.kind === "replaced") {
@@ -243,7 +243,7 @@ function removals(value: unknown, path: string): void {
243
243
  NOTIFICATIONS_FIELDS.NotificationRemovalProjection,
244
244
  );
245
245
  recordProjection(item.record, `${path}[${index}].record`);
246
- member(item.reason, ["dismissed", "cleared", "pruned"] as const, `${path}[${index}].reason`);
246
+ member(item.reason, NOTIFICATION_REMOVAL_REASONS, `${path}[${index}].reason`);
247
247
  });
248
248
  }
249
249
 
@@ -254,10 +254,8 @@ function protocol(value: unknown, path: string): void {
254
254
  }
255
255
 
256
256
  function record(value: unknown, path: string): Record<string, unknown> {
257
- if (!isRecord(value)) {
258
- fail(path, "expected object");
259
- }
260
- return value;
257
+ const result = readWireRecord(value, () => fail(path, "expected object"));
258
+ return result;
261
259
  }
262
260
 
263
261
  function exact(value: unknown, path: string, keys: ReadonlyArray<string>): Record<string, unknown> {
@@ -271,11 +269,7 @@ function exactKeys(
271
269
  path: string,
272
270
  keys: ReadonlyArray<string>,
273
271
  ): void {
274
- const actual = Object.keys(object).sort();
275
- const expected = [...keys].sort();
276
- if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
277
- fail(path, `expected keys ${expected.join(", ")}`);
278
- }
272
+ checkWireFields(object, keys, () => fail(path, `expected keys ${[...keys].sort().join(", ")}`));
279
273
  }
280
274
 
281
275
  function array(value: unknown, path: string): Array<unknown> {
@@ -290,9 +284,14 @@ function text(value: unknown, path: string): void {
290
284
  fail(path, "expected nonempty string");
291
285
  }
292
286
  }
293
- function nullableText(value: unknown, path: string): void {
287
+ function opaqueId(value: unknown, path: string): void {
288
+ if (!isOpaqueId(value)) {
289
+ fail(path, "expected bounded lowercase opaque id");
290
+ }
291
+ }
292
+ function nullableOpaqueId(value: unknown, path: string): void {
294
293
  if (value !== null) {
295
- text(value, path);
294
+ opaqueId(value, path);
296
295
  }
297
296
  }
298
297
  function boolean(value: unknown, path: string): void {
@@ -326,25 +325,16 @@ function fail(path: string, message: string): never {
326
325
  throw new NotificationProtocolValidationError(path, message);
327
326
  }
328
327
 
329
- /**
330
- * Allowed keys for one tagged-union variant, from the generated map, with the
331
- * discriminant's name read from the map too.
332
- *
333
- * A missing entry means the generator failed to read the union: every caller
334
- * checks the discriminant above this call.
335
- */
336
328
  function variantKeys(
337
329
  type: string,
338
330
  object: Record<string, unknown>,
339
331
  path: string,
340
332
  ): ReadonlyArray<string> {
341
- const discriminant = object[NOTIFICATION_VARIANT_FIELDS_DISCRIMINANTS[type] ?? "kind"];
342
- const keys =
343
- typeof discriminant === "string"
344
- ? NOTIFICATION_VARIANT_FIELDS[type]?.[discriminant]
345
- : undefined;
346
- if (keys === undefined) {
347
- fail(path, `no generated fields for ${type}.${String(discriminant)}`);
348
- }
349
- return keys;
333
+ return wireVariantFields(
334
+ NOTIFICATION_VARIANT_FIELDS,
335
+ NOTIFICATION_VARIANT_FIELDS_DISCRIMINANTS,
336
+ type,
337
+ object,
338
+ (discriminant) => fail(path, `no generated fields for ${type}.${String(discriminant)}`),
339
+ );
350
340
  }
@@ -3,6 +3,7 @@ import {
3
3
  bridgeCodec,
4
4
  parseBridgeCommandEnvelope,
5
5
  parseBridgeCommandReply,
6
+ parseBridgeJobTerminalEvent,
6
7
  parseBridgeQueryEnvelope,
7
8
  parseBridgeQueryReply,
8
9
  } from "@inflatable-cookie/longhorn/bridge";
@@ -10,6 +11,7 @@ import type {
10
11
  BridgeCommandEnvelope,
11
12
  BridgeCommandReply,
12
13
  BridgeDomainClient,
14
+ BridgeFailure,
13
15
  BridgeJobId,
14
16
  BridgeJobTerminalEvent,
15
17
  BridgeOperationDescriptor,
@@ -51,6 +53,40 @@ export interface BridgeOperationPortOptions {
51
53
  readonly nextOperationRequestId: () => string;
52
54
  }
53
55
 
56
+ export type BridgeOperationFailure =
57
+ | {
58
+ readonly kind: "rejected" | "indeterminate";
59
+ readonly requestId: BridgeRequestId;
60
+ readonly failure: BridgeFailure<null>;
61
+ }
62
+ | {
63
+ readonly kind: "miscorrelated";
64
+ readonly requestId: BridgeRequestId;
65
+ readonly receivedRequestId: BridgeRequestId;
66
+ }
67
+ | {
68
+ readonly kind: "failed";
69
+ readonly requestId: BridgeRequestId;
70
+ readonly jobId: BridgeJobId;
71
+ readonly failure: BridgeFailure<null>;
72
+ }
73
+ | {
74
+ readonly kind: "cancelled";
75
+ readonly requestId: BridgeRequestId;
76
+ readonly jobId: BridgeJobId;
77
+ };
78
+
79
+ export class BridgeOperationError extends Error {
80
+ constructor(readonly outcome: BridgeOperationFailure) {
81
+ super(
82
+ "failure" in outcome
83
+ ? `operation bridge ${outcome.kind}: ${outcome.failure.message}`
84
+ : `operation bridge ${outcome.kind}`,
85
+ );
86
+ this.name = "BridgeOperationError";
87
+ }
88
+ }
89
+
54
90
  export function createBridgeOperationPort(options: BridgeOperationPortOptions): OperationPort {
55
91
  return {
56
92
  snapshot: (query) => executeQuery(options, query),
@@ -64,10 +100,7 @@ async function executeQuery(options: BridgeOperationPortOptions, query: Operatio
64
100
  const context = nextContext(options);
65
101
  const descriptor = queryDescriptor(options.domainId);
66
102
  const reply = await options.client.execute(descriptor, { context, payload: query });
67
- if (reply.requestId !== context.requestId || !("success" in reply.outcome)) {
68
- throw new Error("operation bridge query was rejected or miscorrelated");
69
- }
70
- return reply.outcome.success;
103
+ return queryResult(context.requestId, reply);
71
104
  }
72
105
 
73
106
  async function executeCommand(
@@ -88,10 +121,20 @@ async function executeCommand(
88
121
  idempotencyKey: context.requestId,
89
122
  payload: command,
90
123
  });
91
- if (reply.requestId !== context.requestId || !("applied" in reply.outcome)) {
92
- throw new Error("operation bridge command was rejected, indeterminate, or miscorrelated");
124
+ const { requestId } = context;
125
+ checkCorrelation(requestId, reply.requestId);
126
+ const { outcome } = reply;
127
+ if ("rejected" in outcome) {
128
+ throw new BridgeOperationError({ kind: "rejected", requestId, failure: outcome.rejected });
93
129
  }
94
- return reply.outcome.applied;
130
+ if ("indeterminate" in outcome) {
131
+ throw new BridgeOperationError({
132
+ kind: "indeterminate",
133
+ requestId,
134
+ failure: outcome.indeterminate,
135
+ });
136
+ }
137
+ return outcome.applied;
95
138
  }
96
139
 
97
140
  async function executeCancellation(
@@ -101,12 +144,27 @@ async function executeCancellation(
101
144
  const context = nextContext(options);
102
145
  const descriptor = cancellationDescriptor(options.domainId);
103
146
  const reply = await options.client.execute(descriptor, { context, payload: command });
104
- if (reply.requestId !== context.requestId || !("success" in reply.outcome)) {
105
- throw new Error("operation bridge cancellation was rejected or miscorrelated");
147
+ return queryResult(context.requestId, reply);
148
+ }
149
+
150
+ function queryResult<Result>(requestId: BridgeRequestId, reply: BridgeQueryReply<Result, null>) {
151
+ checkCorrelation(requestId, reply.requestId);
152
+ if ("rejected" in reply.outcome) {
153
+ throw new BridgeOperationError({
154
+ kind: "rejected",
155
+ requestId,
156
+ failure: reply.outcome.rejected,
157
+ });
106
158
  }
107
159
  return reply.outcome.success;
108
160
  }
109
161
 
162
+ function checkCorrelation(requestId: BridgeRequestId, receivedRequestId: BridgeRequestId): void {
163
+ if (receivedRequestId !== requestId) {
164
+ throw new BridgeOperationError({ kind: "miscorrelated", requestId, receivedRequestId });
165
+ }
166
+ }
167
+
110
168
  function nextContext(options: BridgeOperationPortOptions): BridgeRequestContext {
111
169
  return {
112
170
  requestId: options.nextBridgeRequestId(),
@@ -214,22 +272,24 @@ export class BridgeOperationJobCorrelation {
214
272
  return event.progress.operationId === this.#operationId ? event.progress : undefined;
215
273
  }
216
274
 
275
+ /** Returns a correlated success or throws for a correlated failed or cancelled job. */
217
276
  acceptTerminal(
218
277
  event: BridgeJobTerminalEvent<OperationChangedEvent, null>,
219
278
  ): OperationChangedEvent | undefined {
220
279
  if (this.#tracker.classifyTerminal(event) !== "accept") {
221
280
  return undefined;
222
281
  }
223
- if (
224
- typeof event.outcome !== "object" ||
225
- event.outcome === null ||
226
- !("succeeded" in event.outcome)
227
- ) {
228
- return undefined;
282
+ const { requestId, jobId, outcome } = parseBridgeJobTerminalEvent(
283
+ event,
284
+ codec(assertValidOperationChangedEvent),
285
+ noDetails,
286
+ );
287
+ if (outcome === "cancelled") {
288
+ throw new BridgeOperationError({ kind: "cancelled", requestId, jobId });
289
+ }
290
+ if ("failed" in outcome) {
291
+ throw new BridgeOperationError({ kind: "failed", requestId, jobId, failure: outcome.failed });
229
292
  }
230
- assertValidOperationChangedEvent(event.outcome.succeeded);
231
- return event.outcome.succeeded.operationId === this.#operationId
232
- ? event.outcome.succeeded
233
- : undefined;
293
+ return outcome.succeeded.operationId === this.#operationId ? outcome.succeeded : undefined;
234
294
  }
235
295
  }
@@ -1,4 +1,4 @@
1
- import { CheckedSnapshotConnection } from "@inflatable-cookie/longhorn/core";
1
+ import { CheckedSnapshotConnection, CheckedSubscription } from "@inflatable-cookie/longhorn/core";
2
2
  import type {
3
3
  ConnectionFailure,
4
4
  ConnectionFailureReporter,
@@ -10,6 +10,7 @@ import {
10
10
  assertValidOperationChangedEvent,
11
11
  assertValidOperationMutationCommand,
12
12
  assertValidOperationMutationResult,
13
+ assertValidOperationSnapshot,
13
14
  assertValidOperationSnapshotResponse,
14
15
  } from "./validation.ts";
15
16
  import { OPERATION_PROTOCOL_VERSION } from "./generated/protocol.ts";
@@ -72,7 +73,19 @@ export class OperationClient {
72
73
  listener: (snapshot: OperationSnapshot) => void,
73
74
  onFailure?: ConnectionFailureReporter,
74
75
  ): OperationSubscription {
75
- return new CheckedOperationSubscription(this, this.#port, listener, onFailure);
76
+ const port = this.#port;
77
+ return new CheckedSubscription(
78
+ new CheckedSnapshotConnection({
79
+ listen: async (receive) => (port.listen === undefined ? () => {} : port.listen(receive)),
80
+ loadSnapshot: async () => (await this.snapshot()).snapshot,
81
+ validateSnapshot: parseSnapshot,
82
+ handleEvent: operationEventAction,
83
+ isNewer: isNewerOperationSnapshot,
84
+ onSnapshot: listener,
85
+ onFailure,
86
+ }),
87
+ () => {},
88
+ );
76
89
  }
77
90
  }
78
91
 
@@ -94,50 +107,9 @@ function assertResponseCorrelation(received: string, expected: string): void {
94
107
  }
95
108
  }
96
109
 
97
- class CheckedOperationSubscription implements OperationSubscription {
98
- readonly ready: Promise<void>;
99
- readonly #connection: CheckedSnapshotConnection<OperationSnapshot>;
100
-
101
- constructor(
102
- client: OperationClient,
103
- port: OperationPort,
104
- listener: (snapshot: OperationSnapshot) => void,
105
- onFailure?: ConnectionFailureReporter,
106
- ) {
107
- this.#connection = new CheckedSnapshotConnection({
108
- listen: async (receive) => {
109
- if (port.listen === undefined) {
110
- return () => {};
111
- }
112
- return port.listen(receive);
113
- },
114
- loadSnapshot: async () => (await client.snapshot()).snapshot,
115
- validateSnapshot: parseSnapshot,
116
- handleEvent: operationEventAction,
117
- isNewer: isNewerOperationSnapshot,
118
- onSnapshot: listener,
119
- onFailure,
120
- });
121
- this.ready = this.#connection.ready.then(() => undefined);
122
- }
123
-
124
- current(): OperationSnapshot | undefined {
125
- return this.#connection.current();
126
- }
127
-
128
- failures(): ReadonlyArray<ConnectionFailure> {
129
- return this.#connection.failures();
130
- }
131
-
132
- dispose(): Promise<void> {
133
- return this.#connection.dispose();
134
- }
135
- }
136
-
137
110
  function parseSnapshot(value: unknown): OperationSnapshot {
138
- const response = { requestId: "request:validation", snapshot: value };
139
- assertValidOperationSnapshotResponse(response);
140
- return response.snapshot;
111
+ assertValidOperationSnapshot(value);
112
+ return value;
141
113
  }
142
114
 
143
115
  export function operationEventAction(
@@ -1,5 +1,5 @@
1
+ import { ControllerLifecycle } from "../core/controller-lifecycle.ts";
1
2
  import { isNewerOperationSnapshot, OperationClient } from "./client.ts";
2
- import type { OperationSubscription } from "./client.ts";
3
3
  import { OPERATION_PROTOCOL_VERSION } from "./generated/protocol.ts";
4
4
  import type {
5
5
  OperationCancellationResult,
@@ -47,9 +47,7 @@ export class OperationController {
47
47
  #selectedOperationId: OperationId | undefined;
48
48
  #commandRejection: OperationCommandRejection | undefined;
49
49
  #commandFailure: OperationCommandFailure | undefined;
50
- #subscription: OperationSubscription | undefined;
51
- #started = false;
52
- #lifecycleRevision = 0;
50
+ readonly #lifecycle = new ControllerLifecycle();
53
51
  #commandRevision = 0;
54
52
 
55
53
  constructor(options: OperationControllerOptions) {
@@ -57,7 +55,7 @@ export class OperationController {
57
55
  }
58
56
 
59
57
  get status(): OperationControllerStatus {
60
- return this.#status;
58
+ return this.#lifecycle.eventFailure ?? this.#status;
61
59
  }
62
60
 
63
61
  get snapshot(): OperationSnapshot | undefined {
@@ -100,55 +98,40 @@ export class OperationController {
100
98
  return () => this.#observers.delete(observer);
101
99
  }
102
100
 
103
- async start(): Promise<void> {
104
- if (this.#started) {
105
- return;
106
- }
107
- this.#started = true;
108
- const lifecycleRevision = ++this.#lifecycleRevision;
109
- this.#setStatus({ kind: "loading" });
110
-
111
- const subscription = this.#client.subscribe(
112
- (snapshot) => {
113
- if (this.#isCurrentLifecycle(lifecycleRevision)) {
114
- this.#install(snapshot);
115
- }
116
- },
117
- ({ error }) => {
118
- if (this.#isCurrentLifecycle(lifecycleRevision)) {
119
- this.#setStatus({ kind: "failed", error });
120
- }
101
+ start(): Promise<void> {
102
+ return this.#lifecycle.start({
103
+ loading: () => this.#setStatus({ kind: "loading" }),
104
+ connect: ({ isCurrent, reportFailure, watch }) => {
105
+ const subscription = this.#client.subscribe((snapshot) => {
106
+ if (isCurrent()) {
107
+ this.#install(snapshot);
108
+ }
109
+ }, reportFailure);
110
+ return watch(subscription, () => this.#setStatus({ kind: "ready" }));
121
111
  },
122
- );
123
- this.#subscription = subscription;
112
+ failed: (error) => this.#setStatus({ kind: "failed", error }),
113
+ });
114
+ }
124
115
 
125
- try {
126
- await subscription.ready;
127
- if (this.#isCurrentLifecycle(lifecycleRevision)) {
128
- this.#setStatus({ kind: "ready" });
129
- }
130
- } catch (error) {
131
- if (this.#isCurrentLifecycle(lifecycleRevision)) {
132
- this.#setStatus({ kind: "failed", error });
133
- }
134
- }
116
+ /** Replaces the current subscription, including after a reported failure. */
117
+ restart(): Promise<void> {
118
+ return this.#lifecycle.restart(
119
+ this.status,
120
+ () => this.stop(),
121
+ () => this.start(),
122
+ );
135
123
  }
136
124
 
137
- async stop(): Promise<void> {
138
- this.#started = false;
139
- this.#lifecycleRevision += 1;
140
- this.#commandRevision += 1;
141
- const subscription = this.#subscription;
142
- this.#subscription = undefined;
143
- this.#snapshot = undefined;
144
- this.#selectedOperationId = undefined;
145
- this.#pending.clear();
146
- this.#commandRejection = undefined;
147
- this.#commandFailure = undefined;
148
- this.#setStatus({ kind: "idle" });
149
- if (subscription !== undefined) {
150
- await subscription.dispose();
151
- }
125
+ stop(): Promise<void> {
126
+ return this.#lifecycle.stop(() => {
127
+ this.#commandRevision += 1;
128
+ this.#snapshot = undefined;
129
+ this.#selectedOperationId = undefined;
130
+ this.#pending.clear();
131
+ this.#commandRejection = undefined;
132
+ this.#commandFailure = undefined;
133
+ this.#setStatus({ kind: "idle" });
134
+ });
152
135
  }
153
136
 
154
137
  select(operationId: OperationId | undefined): void {
@@ -204,7 +187,7 @@ export class OperationController {
204
187
  if (this.#hasPending(pending.operationId, pending.kind)) {
205
188
  throw new OperationControllerCommandPendingError(pending.operationId, pending.kind);
206
189
  }
207
- const lifecycleRevision = this.#lifecycleRevision;
190
+ const lifecycleRevision = this.#lifecycle.revision;
208
191
  const commandRevision = ++this.#commandRevision;
209
192
  this.#pending.set(pending.requestId, pending);
210
193
  this.#commandFailure = undefined;
@@ -213,7 +196,7 @@ export class OperationController {
213
196
 
214
197
  try {
215
198
  const result = await run();
216
- if (this.#isCurrentLifecycle(lifecycleRevision)) {
199
+ if (this.#lifecycle.isCurrent(lifecycleRevision)) {
217
200
  this.#install(result.snapshot);
218
201
  if (commandRevision === this.#commandRevision && result.status === "rejected") {
219
202
  this.#commandRejection = { ...pending, rejection: result.rejection };
@@ -222,14 +205,14 @@ export class OperationController {
222
205
  return result;
223
206
  } catch (error) {
224
207
  if (
225
- this.#isCurrentLifecycle(lifecycleRevision) &&
208
+ this.#lifecycle.isCurrent(lifecycleRevision) &&
226
209
  commandRevision === this.#commandRevision
227
210
  ) {
228
211
  this.#commandFailure = { ...pending, error };
229
212
  }
230
213
  throw error;
231
214
  } finally {
232
- if (this.#isCurrentLifecycle(lifecycleRevision)) {
215
+ if (this.#lifecycle.isCurrent(lifecycleRevision)) {
233
216
  this.#pending.delete(pending.requestId);
234
217
  this.#notify();
235
218
  }
@@ -237,7 +220,7 @@ export class OperationController {
237
220
  }
238
221
 
239
222
  #requireAvailableEntry(operationId: OperationId): OperationEntryProjection {
240
- if (!this.#started || this.#snapshot === undefined) {
223
+ if (!this.#lifecycle.active || this.#snapshot === undefined) {
241
224
  throw new OperationControllerUnavailableError();
242
225
  }
243
226
  const operation = this.#entry(operationId);
@@ -271,10 +254,6 @@ export class OperationController {
271
254
  this.#notify();
272
255
  }
273
256
 
274
- #isCurrentLifecycle(revision: number): boolean {
275
- return this.#started && revision === this.#lifecycleRevision;
276
- }
277
-
278
257
  #setStatus(status: OperationControllerStatus): void {
279
258
  this.#status = status;
280
259
  this.#notify();
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:operation`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Allowed field names per protocol type, from the Rust structs.
3
3
  // A `record()` given one of these rejects unknown and missing keys —
4
4
  // contract 010's Boundary Validation Target.
@@ -17,4 +17,5 @@ export const OPERATION_FIELDS = {
17
17
  "OperationRejection": ["code", "detail", "refreshRequired"],
18
18
  "OperationCancellationReceiptProjection": ["operationId", "outcome", "previousState", "committedState", "previousOperationRevision", "committedOperationRevision", "previousCatalogueRevision", "committedCatalogueRevision", "evicted"],
19
19
  "OperationChangedEvent": ["protocolVersion", "requestId", "authority", "previousCatalogueRevision", "committedCatalogueRevision", "operationId", "kind"],
20
+ "OperationHostError": ["code", "message", "retryable"],
20
21
  } as const;
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:operation`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Wording lives in Rust, on the enum that owns it. A label edited here is
3
3
  // a label that disagrees with the native surface.
4
4