@inflatable-cookie/longhorn 0.1.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 (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -0
  3. package/package.json +205 -0
  4. package/src/agent-control/index.ts +20 -0
  5. package/src/agent-control/inject.ts +4 -0
  6. package/src/agent-control/shim.ts +722 -0
  7. package/src/bridge/direct.ts +22 -0
  8. package/src/bridge/generated/fields.ts +32 -0
  9. package/src/bridge/generated/protocol.ts +218 -0
  10. package/src/bridge/generated/variant-fields.ts +10 -0
  11. package/src/bridge/index.ts +15 -0
  12. package/src/bridge/job.ts +51 -0
  13. package/src/bridge/loopback.ts +84 -0
  14. package/src/bridge/operation.ts +166 -0
  15. package/src/bridge/router.ts +71 -0
  16. package/src/bridge/runtime/connection.ts +318 -0
  17. package/src/bridge/runtime/policy.ts +89 -0
  18. package/src/bridge/runtime/retry.ts +60 -0
  19. package/src/bridge/runtime.ts +3 -0
  20. package/src/bridge/session.ts +67 -0
  21. package/src/bridge/stream/connection.ts +146 -0
  22. package/src/bridge/stream/source.ts +61 -0
  23. package/src/bridge/stream/tracker.ts +109 -0
  24. package/src/bridge/stream.ts +6 -0
  25. package/src/bridge/supervision.ts +204 -0
  26. package/src/bridge/validation/base.ts +164 -0
  27. package/src/bridge/validation/jobs.ts +105 -0
  28. package/src/bridge/validation/negotiation.ts +242 -0
  29. package/src/bridge/validation/operations.ts +213 -0
  30. package/src/bridge/validation/streams.ts +47 -0
  31. package/src/bridge/validation.ts +5 -0
  32. package/src/commands/client.ts +124 -0
  33. package/src/commands/controller.ts +411 -0
  34. package/src/commands/generated/fields.ts +43 -0
  35. package/src/commands/generated/protocol.ts +876 -0
  36. package/src/commands/generated/variant-fields.ts +88 -0
  37. package/src/commands/index.ts +13 -0
  38. package/src/commands/keyboard.ts +361 -0
  39. package/src/commands/ports.ts +82 -0
  40. package/src/commands/projectors.ts +306 -0
  41. package/src/commands/validation.ts +444 -0
  42. package/src/config/client.ts +215 -0
  43. package/src/config/generated/base.ts +714 -0
  44. package/src/config/generated/fields.ts +54 -0
  45. package/src/config/generated/label-template.ts +14 -0
  46. package/src/config/generated/labels.ts +30 -0
  47. package/src/config/generated/protocol.ts +3 -0
  48. package/src/config/generated/restore.ts +658 -0
  49. package/src/config/generated/variant-fields.ts +129 -0
  50. package/src/config/index.ts +12 -0
  51. package/src/config/names.ts +19 -0
  52. package/src/config/validation/commands.ts +155 -0
  53. package/src/config/validation/outcomes.ts +243 -0
  54. package/src/config/validation/primitives.ts +174 -0
  55. package/src/config/validation/projection.ts +351 -0
  56. package/src/config/validation.ts +7 -0
  57. package/src/core/connection.ts +252 -0
  58. package/src/core/index.ts +2 -0
  59. package/src/core/transport.ts +24 -0
  60. package/src/history/client.ts +65 -0
  61. package/src/history/controller.ts +385 -0
  62. package/src/history/direct.ts +21 -0
  63. package/src/history/generated/fields.ts +18 -0
  64. package/src/history/generated/protocol.ts +389 -0
  65. package/src/history/generated/variant-fields.ts +27 -0
  66. package/src/history/index.ts +13 -0
  67. package/src/history/ports.ts +31 -0
  68. package/src/history/serialized.ts +38 -0
  69. package/src/history/validation.ts +334 -0
  70. package/src/history-tree/client.ts +16 -0
  71. package/src/history-tree/controller.ts +199 -0
  72. package/src/history-tree/direct.ts +3 -0
  73. package/src/history-tree/generated/fields.ts +26 -0
  74. package/src/history-tree/generated/protocol.ts +711 -0
  75. package/src/history-tree/generated/variant-fields.ts +39 -0
  76. package/src/history-tree/index.ts +13 -0
  77. package/src/history-tree/ports.ts +43 -0
  78. package/src/history-tree/serialized.ts +15 -0
  79. package/src/history-tree/validation.ts +269 -0
  80. package/src/layout/generated/protocol.ts +289 -0
  81. package/src/layout/index.ts +4 -0
  82. package/src/layout/ratio.ts +22 -0
  83. package/src/layout/validation.ts +110 -0
  84. package/src/layout/visibility.ts +30 -0
  85. package/src/licence/client.ts +32 -0
  86. package/src/licence/controller.ts +301 -0
  87. package/src/licence/direct.ts +3 -0
  88. package/src/licence/generated/fields.ts +17 -0
  89. package/src/licence/generated/key-conformance.json +42 -0
  90. package/src/licence/generated/protocol.ts +249 -0
  91. package/src/licence/generated/variant-fields.ts +34 -0
  92. package/src/licence/index.ts +14 -0
  93. package/src/licence/key.ts +125 -0
  94. package/src/licence/ports.ts +39 -0
  95. package/src/licence/serialized.ts +13 -0
  96. package/src/licence/validation.ts +226 -0
  97. package/src/native-content/client.ts +474 -0
  98. package/src/native-content/direct.ts +16 -0
  99. package/src/native-content/generated/fields.ts +32 -0
  100. package/src/native-content/generated/protocol.ts +498 -0
  101. package/src/native-content/generated/variant-fields.ts +77 -0
  102. package/src/native-content/index.ts +12 -0
  103. package/src/native-content/ports.ts +46 -0
  104. package/src/native-content/serialized.ts +50 -0
  105. package/src/native-content/validation/base.ts +194 -0
  106. package/src/native-content/validation/messages.ts +192 -0
  107. package/src/native-content/validation/state.ts +404 -0
  108. package/src/native-content/validation.ts +7 -0
  109. package/src/notifications/client.ts +106 -0
  110. package/src/notifications/controller.ts +240 -0
  111. package/src/notifications/direct.ts +12 -0
  112. package/src/notifications/generated/fields.ts +19 -0
  113. package/src/notifications/generated/labels.ts +20 -0
  114. package/src/notifications/generated/protocol.ts +522 -0
  115. package/src/notifications/generated/variant-fields.ts +37 -0
  116. package/src/notifications/index.ts +16 -0
  117. package/src/notifications/ports.ts +22 -0
  118. package/src/notifications/serialized.ts +27 -0
  119. package/src/notifications/toast.ts +41 -0
  120. package/src/notifications/tone.ts +27 -0
  121. package/src/notifications/validation.ts +246 -0
  122. package/src/operation/bridge.ts +168 -0
  123. package/src/operation/client.ts +167 -0
  124. package/src/operation/controller.ts +321 -0
  125. package/src/operation/direct.ts +15 -0
  126. package/src/operation/generated/fields.ts +20 -0
  127. package/src/operation/generated/labels.ts +15 -0
  128. package/src/operation/generated/protocol.ts +762 -0
  129. package/src/operation/generated/variant-fields.ts +60 -0
  130. package/src/operation/index.ts +14 -0
  131. package/src/operation/ports.ts +29 -0
  132. package/src/operation/serialized.ts +39 -0
  133. package/src/operation/validation.ts +479 -0
  134. package/src/settings/client.ts +142 -0
  135. package/src/settings/connection.ts +246 -0
  136. package/src/settings/generated/fields.ts +34 -0
  137. package/src/settings/generated/protocol.ts +668 -0
  138. package/src/settings/generated/variant-fields.ts +26 -0
  139. package/src/settings/index.ts +12 -0
  140. package/src/settings/names.ts +8 -0
  141. package/src/settings/registry.ts +141 -0
  142. package/src/settings/validation/authority.ts +66 -0
  143. package/src/settings/validation/command.ts +165 -0
  144. package/src/settings/validation/error.ts +33 -0
  145. package/src/settings/validation/primitives.ts +203 -0
  146. package/src/settings/validation/projection.ts +50 -0
  147. package/src/settings/validation/registry.ts +170 -0
  148. package/src/settings/validation.ts +4 -0
  149. package/src/surface-transfer/client.ts +54 -0
  150. package/src/surface-transfer/generated/fields.ts +12 -0
  151. package/src/surface-transfer/generated/protocol.ts +61 -0
  152. package/src/surface-transfer/generated/variant-fields.ts +30 -0
  153. package/src/surface-transfer/index.ts +9 -0
  154. package/src/surface-transfer/validation.ts +209 -0
  155. package/src/surfaces/client.ts +140 -0
  156. package/src/surfaces/generated/fields.ts +19 -0
  157. package/src/surfaces/generated/protocol.ts +217 -0
  158. package/src/surfaces/generated/variant-fields.ts +42 -0
  159. package/src/surfaces/index.ts +9 -0
  160. package/src/surfaces/validation.ts +199 -0
  161. package/src/transfer/client.ts +133 -0
  162. package/src/transfer/connection.ts +87 -0
  163. package/src/transfer/generated/fields.ts +23 -0
  164. package/src/transfer/generated/protocol.ts +171 -0
  165. package/src/transfer/generated/variant-fields.ts +45 -0
  166. package/src/transfer/index.ts +11 -0
  167. package/src/transfer/payload.ts +71 -0
  168. package/src/transfer/validation.ts +282 -0
  169. package/src/update/client.ts +29 -0
  170. package/src/update/controller.ts +255 -0
  171. package/src/update/direct.ts +3 -0
  172. package/src/update/generated/fields.ts +14 -0
  173. package/src/update/generated/protocol.ts +238 -0
  174. package/src/update/generated/variant-fields.ts +44 -0
  175. package/src/update/index.ts +14 -0
  176. package/src/update/ports.ts +36 -0
  177. package/src/update/serialized.ts +12 -0
  178. package/src/update/validation.ts +191 -0
@@ -0,0 +1,246 @@
1
+ import {
2
+ NOTIFICATION_VARIANT_FIELDS,
3
+ NOTIFICATION_VARIANT_FIELDS_DISCRIMINANTS,
4
+ } from "./generated/variant-fields.ts";
5
+ import { NOTIFICATIONS_FIELDS } from "./generated/fields.ts";
6
+ import {
7
+ NOTIFICATION_CHANGED_KINDS,
8
+ NOTIFICATION_MUTATION_KINDS,
9
+ NOTIFICATION_MUTATION_STATUSES,
10
+ NOTIFICATION_PROTOCOL_VERSION,
11
+ NOTIFICATION_READ_STATES,
12
+ NOTIFICATION_REJECTION_CODES,
13
+ NOTIFICATION_RETENTION_CLASSES,
14
+ NOTIFICATION_SEVERITIES,
15
+ type NotificationChangedEvent,
16
+ type NotificationMutationCommand,
17
+ type NotificationMutationResult,
18
+ type NotificationRecordProjection,
19
+ type NotificationSnapshot,
20
+ type NotificationSnapshotQuery,
21
+ type NotificationSnapshotResponse,
22
+ } from "./generated/protocol.ts";
23
+
24
+ export class NotificationProtocolValidationError extends Error {
25
+ constructor(readonly path: string, message: string) {
26
+ super(`incompatible notification protocol at ${path}: ${message}`);
27
+ this.name = "NotificationProtocolValidationError";
28
+ }
29
+ }
30
+
31
+ export function assertValidNotificationSnapshotQuery(value: unknown): asserts value is NotificationSnapshotQuery {
32
+ const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationSnapshotQuery);
33
+ protocol(object.protocolVersion, "$.protocolVersion");
34
+ text(object.requestId, "$.requestId");
35
+ natural(object.offset, "$.offset");
36
+ natural(object.limit, "$.limit");
37
+ }
38
+
39
+ export function assertValidNotificationSnapshotResponse(value: unknown): asserts value is NotificationSnapshotResponse {
40
+ const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationSnapshotResponse);
41
+ text(object.requestId, "$.requestId");
42
+ assertValidNotificationSnapshot(object.snapshot);
43
+ }
44
+
45
+ export function assertValidNotificationSnapshot(value: unknown): asserts value is NotificationSnapshot {
46
+ const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationSnapshot);
47
+ protocol(object.protocolVersion, "$.protocolVersion");
48
+ authority(object.authority, "$.authority");
49
+ natural(object.ledgerRevision, "$.ledgerRevision");
50
+ limits(object.limits, "$.limits");
51
+ natural(object.retainedCount, "$.retainedCount");
52
+ natural(object.unseenCount, "$.unseenCount");
53
+ natural(object.retainedEncodedWeight, "$.retainedEncodedWeight");
54
+ natural(object.prunedCount, "$.prunedCount");
55
+ const page = exact(object.page, "$.page", NOTIFICATIONS_FIELDS.NotificationPageProjection);
56
+ natural(page.offset, "$.page.offset");
57
+ natural(page.totalCount, "$.page.totalCount");
58
+ boolean(page.hasMore, "$.page.hasMore");
59
+ array(page.records, "$.page.records").forEach((item, index) => recordProjection(item, `$.page.records[${index}]`));
60
+ }
61
+
62
+ export function assertValidNotificationMutationCommand(value: unknown): asserts value is NotificationMutationCommand {
63
+ const object = record(value, "$");
64
+ member(object.kind, NOTIFICATION_MUTATION_KINDS, "$.kind");
65
+ protocol(object.protocolVersion, "$.protocolVersion");
66
+ text(object.requestId, "$.requestId");
67
+ authority(object.authority, "$.authority");
68
+ natural(object.expectedLedgerRevision, "$.expectedLedgerRevision");
69
+ switch (object.kind) {
70
+ case "add":
71
+ exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
72
+ text(object.notificationId, "$.notificationId");
73
+ draft(object.draft, "$.draft");
74
+ break;
75
+ case "replace":
76
+ exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
77
+ draft(object.draft, "$.draft");
78
+ boolean(object.markUnseen, "$.markUnseen");
79
+ break;
80
+ case "markSeen":
81
+ case "dismiss":
82
+ exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
83
+ text(object.notificationId, "$.notificationId");
84
+ break;
85
+ case "clear": {
86
+ exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
87
+ const target = record(object.target, "$.target");
88
+ member(target.kind, ["all", "records"] as const, "$.target.kind");
89
+ exactKeys(target, "$.target", variantKeys("NotificationClearTargetProjection", target, "$.target"));
90
+ if (target.kind === "records") array(target.notificationIds, "$.target.notificationIds").forEach((id, index) => text(id, `$.target.notificationIds[${index}]`));
91
+ break;
92
+ }
93
+ case "changeRetention":
94
+ exactKeys(object, "$", variantKeys("NotificationMutationCommand", object, "$"));
95
+ limits(object.limits, "$.limits");
96
+ break;
97
+ }
98
+ }
99
+
100
+ export function assertValidNotificationMutationResult(value: unknown): asserts value is NotificationMutationResult {
101
+ const object = record(value, "$");
102
+ member(object.status, NOTIFICATION_MUTATION_STATUSES, "$.status");
103
+ text(object.requestId, "$.requestId");
104
+ assertValidNotificationSnapshot(object.snapshot);
105
+ if (object.status === "committed") {
106
+ exactKeys(object, "$", variantKeys("NotificationMutationResult", object, "$"));
107
+ receipt(object.receipt, "$.receipt");
108
+ } else {
109
+ exactKeys(object, "$", variantKeys("NotificationMutationResult", object, "$"));
110
+ const rejection = exact(object.rejection, "$.rejection", NOTIFICATIONS_FIELDS.NotificationRejection);
111
+ member(rejection.code, NOTIFICATION_REJECTION_CODES, "$.rejection.code");
112
+ text(rejection.detail, "$.rejection.detail");
113
+ boolean(rejection.refreshRequired, "$.rejection.refreshRequired");
114
+ }
115
+ }
116
+
117
+ export function assertValidNotificationChangedEvent(value: unknown): asserts value is NotificationChangedEvent {
118
+ const object = exact(value, "$", NOTIFICATIONS_FIELDS.NotificationChangedEvent);
119
+ protocol(object.protocolVersion, "$.protocolVersion");
120
+ text(object.requestId, "$.requestId");
121
+ authority(object.authority, "$.authority");
122
+ natural(object.previousLedgerRevision, "$.previousLedgerRevision");
123
+ natural(object.committedLedgerRevision, "$.committedLedgerRevision");
124
+ array(object.affectedNotificationIds, "$.affectedNotificationIds").forEach((id, index) => text(id, `$.affectedNotificationIds[${index}]`));
125
+ member(object.kind, NOTIFICATION_CHANGED_KINDS, "$.kind");
126
+ }
127
+
128
+ function authority(value: unknown, path: string): void {
129
+ const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationAuthorityProjection);
130
+ text(object.authorityId, `${path}.authorityId`);
131
+ positive(object.authorityEpoch, `${path}.authorityEpoch`);
132
+ }
133
+
134
+ function limits(value: unknown, path: string): void {
135
+ const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationLedgerLimitsProjection);
136
+ natural(object.maximumNotifications, `${path}.maximumNotifications`);
137
+ natural(object.maximumEncodedWeight, `${path}.maximumEncodedWeight`);
138
+ }
139
+
140
+ function draft(value: unknown, path: string): void {
141
+ const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationDraftProjection);
142
+ text(object.sourceId, `${path}.sourceId`);
143
+ member(object.severity, NOTIFICATION_SEVERITIES, `${path}.severity`);
144
+ text(object.title, `${path}.title`);
145
+ text(object.summary, `${path}.summary`);
146
+ nullableText(object.causeId, `${path}.causeId`);
147
+ array(object.actions, `${path}.actions`).forEach((action, index) => {
148
+ const item = exact(action, `${path}.actions[${index}]`, NOTIFICATIONS_FIELDS.NotificationActionProjection);
149
+ text(item.referenceId, `${path}.actions[${index}].referenceId`);
150
+ text(item.label, `${path}.actions[${index}].label`);
151
+ });
152
+ nullableText(object.replacementKey, `${path}.replacementKey`);
153
+ nullableText(object.producerToken, `${path}.producerToken`);
154
+ member(object.retentionClass, NOTIFICATION_RETENTION_CLASSES, `${path}.retentionClass`);
155
+ if (object.presentationTimeUnixMs !== null) integer(object.presentationTimeUnixMs, `${path}.presentationTimeUnixMs`);
156
+ }
157
+
158
+ function recordProjection(value: unknown, path: string): asserts value is NotificationRecordProjection {
159
+ const object = exact(value, path, NOTIFICATIONS_FIELDS.NotificationRecordProjection);
160
+ text(object.notificationId, `${path}.notificationId`);
161
+ draft(object.draft, `${path}.draft`);
162
+ positive(object.sequence, `${path}.sequence`);
163
+ positive(object.lastChangedLedgerRevision, `${path}.lastChangedLedgerRevision`);
164
+ member(object.readState, NOTIFICATION_READ_STATES, `${path}.readState`);
165
+ natural(object.encodedMetadataWeight, `${path}.encodedMetadataWeight`);
166
+ }
167
+
168
+ function receipt(value: unknown, path: string): void {
169
+ const object = record(value, path);
170
+ member(object.kind, ["added", "replaced", "seen", "removed", "retentionChanged"] as const, `${path}.kind`);
171
+ natural(object.previousLedgerRevision, `${path}.previousLedgerRevision`);
172
+ natural(object.committedLedgerRevision, `${path}.committedLedgerRevision`);
173
+ if (object.kind === "added" || object.kind === "replaced") {
174
+ exactKeys(object, path, variantKeys("NotificationMutationReceiptProjection", object, path));
175
+ recordProjection(object.record, `${path}.record`);
176
+ removals(object.pruned, `${path}.pruned`);
177
+ } else if (object.kind === "seen") {
178
+ exactKeys(object, path, variantKeys("NotificationMutationReceiptProjection", object, path));
179
+ recordProjection(object.record, `${path}.record`);
180
+ } else if (object.kind === "removed") {
181
+ exactKeys(object, path, variantKeys("NotificationMutationReceiptProjection", object, path));
182
+ removals(object.removals, `${path}.removals`);
183
+ } else {
184
+ exactKeys(object, path, variantKeys("NotificationMutationReceiptProjection", object, path));
185
+ limits(object.previousLimits, `${path}.previousLimits`);
186
+ limits(object.committedLimits, `${path}.committedLimits`);
187
+ removals(object.removals, `${path}.removals`);
188
+ }
189
+ }
190
+
191
+ function removals(value: unknown, path: string): void {
192
+ array(value, path).forEach((removal, index) => {
193
+ const item = exact(removal, `${path}[${index}]`, NOTIFICATIONS_FIELDS.NotificationRemovalProjection);
194
+ recordProjection(item.record, `${path}[${index}].record`);
195
+ member(item.reason, ["dismissed", "cleared", "pruned"] as const, `${path}[${index}].reason`);
196
+ });
197
+ }
198
+
199
+ function protocol(value: unknown, path: string): void {
200
+ if (value !== NOTIFICATION_PROTOCOL_VERSION) fail(path, `expected protocol ${NOTIFICATION_PROTOCOL_VERSION}`);
201
+ }
202
+
203
+ function record(value: unknown, path: string): Record<string, unknown> {
204
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail(path, "expected object");
205
+ return value as Record<string, unknown>;
206
+ }
207
+
208
+ function exact(value: unknown, path: string, keys: readonly string[]): Record<string, unknown> {
209
+ const object = record(value, path);
210
+ exactKeys(object, path, keys);
211
+ return object;
212
+ }
213
+
214
+ function exactKeys(object: Record<string, unknown>, path: string, keys: readonly string[]): void {
215
+ const actual = Object.keys(object).sort();
216
+ const expected = [...keys].sort();
217
+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) fail(path, `expected keys ${expected.join(", ")}`);
218
+ }
219
+
220
+ function array(value: unknown, path: string): unknown[] {
221
+ if (!Array.isArray(value)) fail(path, "expected array");
222
+ return value;
223
+ }
224
+
225
+ function text(value: unknown, path: string): void { if (typeof value !== "string" || value.length === 0) fail(path, "expected nonempty string"); }
226
+ function nullableText(value: unknown, path: string): void { if (value !== null) text(value, path); }
227
+ function boolean(value: unknown, path: string): void { if (typeof value !== "boolean") fail(path, "expected boolean"); }
228
+ function integer(value: unknown, path: string): void { if (typeof value !== "number" || !Number.isSafeInteger(value)) fail(path, "expected safe integer"); }
229
+ function natural(value: unknown, path: string): void { integer(value, path); if ((value as number) < 0) fail(path, "expected nonnegative integer"); }
230
+ function positive(value: unknown, path: string): void { natural(value, path); if ((value as number) === 0) fail(path, "expected positive integer"); }
231
+ function member(value: unknown, members: readonly string[], path: string): void { if (typeof value !== "string" || !members.includes(value)) fail(path, `expected one of ${members.join(", ")}`); }
232
+ function fail(path: string, message: string): never { throw new NotificationProtocolValidationError(path, message); }
233
+
234
+ /**
235
+ * Allowed keys for one tagged-union variant, from the generated map, with the
236
+ * discriminant's name read from the map too.
237
+ *
238
+ * A missing entry means the generator failed to read the union: every caller
239
+ * checks the discriminant above this call.
240
+ */
241
+ function variantKeys(type: string, object: Record<string, unknown>, path: string): readonly string[] {
242
+ const discriminant = object[NOTIFICATION_VARIANT_FIELDS_DISCRIMINANTS[type] ?? "kind"];
243
+ const keys = NOTIFICATION_VARIANT_FIELDS[type]?.[discriminant as string];
244
+ if (keys === undefined) fail(path, `no generated fields for ${type}.${String(discriminant)}`);
245
+ return keys;
246
+ }
@@ -0,0 +1,168 @@
1
+ import {
2
+ BridgeJobTracker,
3
+ type BridgeCommandEnvelope,
4
+ type BridgeCommandReply,
5
+ type BridgeDomainClient,
6
+ type BridgeJobId,
7
+ type BridgeJobTerminalEvent,
8
+ type BridgeOperationDescriptor,
9
+ type BridgeProgressEvent,
10
+ type BridgeQueryEnvelope,
11
+ type BridgeQueryReply,
12
+ type BridgeRequestContext,
13
+ type BridgeRequestId,
14
+ type DomainId,
15
+ } from "@inflatable-cookie/longhorn/bridge";
16
+
17
+ import {
18
+ assertValidOperationCancellationCommand,
19
+ assertValidOperationCancellationResult,
20
+ assertValidOperationChangedEvent,
21
+ assertValidOperationMutationCommand,
22
+ assertValidOperationMutationResult,
23
+ assertValidOperationSnapshotQuery,
24
+ assertValidOperationSnapshotResponse,
25
+ } from "./validation.ts";
26
+ import type {
27
+ OperationCancellationCommand,
28
+ OperationCancellationResult,
29
+ OperationChangedEvent,
30
+ OperationId,
31
+ OperationMutationCommand,
32
+ OperationMutationResult,
33
+ OperationSnapshotQuery,
34
+ OperationSnapshotResponse,
35
+ } from "./generated/protocol.ts";
36
+ import type { OperationPort } from "./ports.ts";
37
+
38
+ export interface BridgeOperationPortOptions {
39
+ readonly client: BridgeDomainClient;
40
+ readonly domainId: DomainId;
41
+ readonly sessionId: string;
42
+ readonly authorityEpoch: number;
43
+ readonly nextBridgeRequestId: () => BridgeRequestId;
44
+ readonly nextOperationRequestId: () => string;
45
+ }
46
+
47
+ export function createBridgeOperationPort(options: BridgeOperationPortOptions): OperationPort {
48
+ return {
49
+ snapshot: (query) => executeQuery(options, query),
50
+ mutate: (command) => executeCommand(options, command),
51
+ cancel: (command) => executeCancellation(options, command),
52
+ nextRequestId: options.nextOperationRequestId,
53
+ };
54
+ }
55
+
56
+ async function executeQuery(options: BridgeOperationPortOptions, query: OperationSnapshotQuery) {
57
+ const context = nextContext(options);
58
+ const descriptor = queryDescriptor(options.domainId);
59
+ const reply = await options.client.execute(descriptor, { context, payload: query });
60
+ if (reply.requestId !== context.requestId || !("success" in reply.outcome)) {
61
+ throw new Error("operation bridge query was rejected or miscorrelated");
62
+ }
63
+ return reply.outcome.success;
64
+ }
65
+
66
+ async function executeCommand(options: BridgeOperationPortOptions, command: OperationMutationCommand) {
67
+ const context = nextContext(options);
68
+ const descriptor = commandDescriptor(options.domainId);
69
+ const reply = await options.client.execute(descriptor, {
70
+ context,
71
+ authorityEpoch: options.authorityEpoch,
72
+ expectedRevision: command.kind === "register" || command.kind === "changeRetention" || command.kind === "teardown"
73
+ ? command.expectedCatalogueRevision
74
+ : null,
75
+ idempotencyKey: context.requestId,
76
+ payload: command,
77
+ });
78
+ if (reply.requestId !== context.requestId || !("applied" in reply.outcome)) {
79
+ throw new Error("operation bridge command was rejected, indeterminate, or miscorrelated");
80
+ }
81
+ return reply.outcome.applied;
82
+ }
83
+
84
+ async function executeCancellation(options: BridgeOperationPortOptions, command: OperationCancellationCommand) {
85
+ const context = nextContext(options);
86
+ const descriptor = cancellationDescriptor(options.domainId);
87
+ const reply = await options.client.execute(descriptor, { context, payload: command });
88
+ if (reply.requestId !== context.requestId || !("success" in reply.outcome)) {
89
+ throw new Error("operation bridge cancellation was rejected or miscorrelated");
90
+ }
91
+ return reply.outcome.success;
92
+ }
93
+
94
+ function nextContext(options: BridgeOperationPortOptions): BridgeRequestContext {
95
+ return { requestId: options.nextBridgeRequestId(), sessionId: options.sessionId, domainId: options.domainId };
96
+ }
97
+
98
+ function codec<Value>(assertValue: (value: unknown) => void) {
99
+ return { parse(value: unknown): Value { assertValue(value); return value as Value; } };
100
+ }
101
+
102
+ function queryDescriptor(domainId: DomainId): BridgeOperationDescriptor<BridgeQueryEnvelope<OperationSnapshotQuery>, BridgeQueryReply<OperationSnapshotResponse, null>> {
103
+ return {
104
+ route: "longhorn.operation.snapshot", domainId, kind: "query",
105
+ requiredCapability: "longhorn.operation.read",
106
+ request: codec((value) => {
107
+ const payload = (value as BridgeQueryEnvelope<unknown>).payload;
108
+ assertValidOperationSnapshotQuery(payload);
109
+ }),
110
+ reply: codec((value) => {
111
+ const outcome = (value as BridgeQueryReply<unknown, null>).outcome;
112
+ if ("success" in outcome) assertValidOperationSnapshotResponse(outcome.success);
113
+ }),
114
+ };
115
+ }
116
+
117
+ function commandDescriptor(domainId: DomainId): BridgeOperationDescriptor<BridgeCommandEnvelope<OperationMutationCommand>, BridgeCommandReply<OperationMutationResult, null>> {
118
+ return {
119
+ route: "longhorn.operation.mutate", domainId, kind: "command",
120
+ requiredCapability: "longhorn.operation.manage",
121
+ request: codec((value) => assertValidOperationMutationCommand((value as BridgeCommandEnvelope<unknown>).payload)),
122
+ reply: codec((value) => {
123
+ const outcome = (value as BridgeCommandReply<unknown, null>).outcome;
124
+ if ("applied" in outcome) assertValidOperationMutationResult(outcome.applied);
125
+ }),
126
+ };
127
+ }
128
+
129
+ function cancellationDescriptor(domainId: DomainId): BridgeOperationDescriptor<BridgeQueryEnvelope<OperationCancellationCommand>, BridgeQueryReply<OperationCancellationResult, null>> {
130
+ return {
131
+ route: "longhorn.operation.cancel", domainId, kind: "cancellation",
132
+ requiredCapability: "longhorn.operation.cancel",
133
+ request: codec((value) => assertValidOperationCancellationCommand((value as BridgeQueryEnvelope<unknown>).payload)),
134
+ reply: codec((value) => {
135
+ const outcome = (value as BridgeQueryReply<unknown, null>).outcome;
136
+ if ("success" in outcome) assertValidOperationCancellationResult(outcome.success);
137
+ }),
138
+ };
139
+ }
140
+
141
+ export interface BridgeOperationCorrelation {
142
+ readonly bridgeRequestId: BridgeRequestId;
143
+ readonly bridgeJobId: BridgeJobId;
144
+ readonly operationId: OperationId;
145
+ }
146
+
147
+ export class BridgeOperationJobCorrelation {
148
+ readonly #tracker: BridgeJobTracker;
149
+ readonly #operationId: OperationId;
150
+
151
+ constructor(correlation: BridgeOperationCorrelation) {
152
+ this.#tracker = new BridgeJobTracker(correlation.bridgeRequestId, correlation.bridgeJobId);
153
+ this.#operationId = correlation.operationId;
154
+ }
155
+
156
+ acceptProgress(event: BridgeProgressEvent<OperationChangedEvent>): OperationChangedEvent | undefined {
157
+ if (this.#tracker.classifyProgress(event) !== "accept") return undefined;
158
+ assertValidOperationChangedEvent(event.progress);
159
+ return event.progress.operationId === this.#operationId ? event.progress : undefined;
160
+ }
161
+
162
+ acceptTerminal(event: BridgeJobTerminalEvent<OperationChangedEvent, null>): OperationChangedEvent | undefined {
163
+ if (this.#tracker.classifyTerminal(event) !== "accept") return undefined;
164
+ if (typeof event.outcome !== "object" || event.outcome === null || !("succeeded" in event.outcome)) return undefined;
165
+ assertValidOperationChangedEvent(event.outcome.succeeded);
166
+ return event.outcome.succeeded.operationId === this.#operationId ? event.outcome.succeeded : undefined;
167
+ }
168
+ }
@@ -0,0 +1,167 @@
1
+ import {
2
+ CheckedSnapshotConnection,
3
+ type ConnectionFailure,
4
+ type ConnectionFailureReporter,
5
+ } from "@inflatable-cookie/longhorn/core";
6
+
7
+ import {
8
+ assertValidOperationCancellationCommand,
9
+ assertValidOperationCancellationResult,
10
+ assertValidOperationChangedEvent,
11
+ assertValidOperationMutationCommand,
12
+ assertValidOperationMutationResult,
13
+ assertValidOperationSnapshotResponse,
14
+ } from "./validation.ts";
15
+ import {
16
+ OPERATION_PROTOCOL_VERSION,
17
+ type OperationCancellationCommand,
18
+ type OperationCancellationResult,
19
+ type OperationChangedEvent,
20
+ type OperationMutationCommand,
21
+ type OperationMutationResult,
22
+ type OperationSnapshot,
23
+ type OperationSnapshotResponse,
24
+ } from "./generated/protocol.ts";
25
+ import type { OperationPort } from "./ports.ts";
26
+
27
+ export interface OperationSubscription {
28
+ readonly ready: Promise<void>;
29
+ current(): OperationSnapshot | undefined;
30
+ failures(): readonly ConnectionFailure[];
31
+ dispose(): Promise<void>;
32
+ }
33
+
34
+ export class OperationClient {
35
+ readonly #port: OperationPort;
36
+
37
+ constructor(port: OperationPort) {
38
+ this.#port = port;
39
+ }
40
+
41
+ nextRequestId(): string {
42
+ return this.#port.nextRequestId();
43
+ }
44
+
45
+ async snapshot(): Promise<OperationSnapshotResponse> {
46
+ const requestId = this.#port.nextRequestId();
47
+ const value = await this.#port.snapshot({
48
+ protocolVersion: OPERATION_PROTOCOL_VERSION,
49
+ requestId,
50
+ });
51
+ assertValidOperationSnapshotResponse(value);
52
+ assertResponseCorrelation(value.requestId, requestId);
53
+ return value;
54
+ }
55
+
56
+ async mutate(command: OperationMutationCommand): Promise<OperationMutationResult> {
57
+ assertValidOperationMutationCommand(command);
58
+ const value = await this.#port.mutate(command);
59
+ assertValidOperationMutationResult(value);
60
+ assertResponseCorrelation(value.requestId, command.requestId);
61
+ return value;
62
+ }
63
+
64
+ async cancel(command: OperationCancellationCommand): Promise<OperationCancellationResult> {
65
+ assertValidOperationCancellationCommand(command);
66
+ const value = await this.#port.cancel(command);
67
+ assertValidOperationCancellationResult(value);
68
+ assertResponseCorrelation(value.requestId, command.requestId);
69
+ return value;
70
+ }
71
+
72
+ subscribe(
73
+ listener: (snapshot: OperationSnapshot) => void,
74
+ onFailure?: ConnectionFailureReporter,
75
+ ): OperationSubscription {
76
+ return new CheckedOperationSubscription(this, this.#port, listener, onFailure);
77
+ }
78
+ }
79
+
80
+ export class OperationResponseCorrelationError extends Error {
81
+ constructor(readonly expectedRequestId: string, readonly receivedRequestId: string) {
82
+ super(`operation response correlation mismatch: expected ${expectedRequestId}; received ${receivedRequestId}`);
83
+ this.name = "OperationResponseCorrelationError";
84
+ }
85
+ }
86
+
87
+ function assertResponseCorrelation(received: string, expected: string): void {
88
+ if (received !== expected) throw new OperationResponseCorrelationError(expected, received);
89
+ }
90
+
91
+ class CheckedOperationSubscription implements OperationSubscription {
92
+ readonly ready: Promise<void>;
93
+ readonly #connection: CheckedSnapshotConnection<OperationSnapshot>;
94
+
95
+ constructor(
96
+ client: OperationClient,
97
+ port: OperationPort,
98
+ listener: (snapshot: OperationSnapshot) => void,
99
+ onFailure?: ConnectionFailureReporter,
100
+ ) {
101
+ this.#connection = new CheckedSnapshotConnection({
102
+ listen: async (receive) => {
103
+ if (port.listen === undefined) return () => {};
104
+ return port.listen(receive);
105
+ },
106
+ loadSnapshot: async () => (await client.snapshot()).snapshot,
107
+ validateSnapshot: parseSnapshot,
108
+ handleEvent: operationEventAction,
109
+ isNewer: isNewerOperationSnapshot,
110
+ onSnapshot: listener,
111
+ onFailure,
112
+ });
113
+ this.ready = this.#connection.ready.then(() => undefined);
114
+ }
115
+
116
+ current(): OperationSnapshot | undefined {
117
+ return this.#connection.current();
118
+ }
119
+
120
+ failures(): readonly ConnectionFailure[] {
121
+ return this.#connection.failures();
122
+ }
123
+
124
+ dispose(): Promise<void> {
125
+ return this.#connection.dispose();
126
+ }
127
+ }
128
+
129
+ function parseSnapshot(value: unknown): OperationSnapshot {
130
+ const response = { requestId: "request:validation", snapshot: value };
131
+ assertValidOperationSnapshotResponse(response);
132
+ return value as OperationSnapshot;
133
+ }
134
+
135
+ export function operationEventAction(
136
+ value: unknown,
137
+ current: OperationSnapshot | undefined,
138
+ ): { kind: "ignore" } | { kind: "refresh" } {
139
+ assertValidOperationChangedEvent(value);
140
+ const event = value as OperationChangedEvent;
141
+ if (current === undefined) return { kind: "refresh" };
142
+ if (event.authority.authorityId !== current.authority.authorityId) {
143
+ return { kind: "ignore" };
144
+ }
145
+ if (event.authority.authorityEpoch < current.authority.authorityEpoch) {
146
+ return { kind: "ignore" };
147
+ }
148
+ if (
149
+ event.authority.authorityEpoch === current.authority.authorityEpoch &&
150
+ event.committedCatalogueRevision <= current.catalogueRevision
151
+ ) {
152
+ return { kind: "ignore" };
153
+ }
154
+ return { kind: "refresh" };
155
+ }
156
+
157
+ export function isNewerOperationSnapshot(
158
+ candidate: OperationSnapshot,
159
+ current: OperationSnapshot | undefined,
160
+ ): boolean {
161
+ if (current === undefined) return true;
162
+ if (candidate.authority.authorityId !== current.authority.authorityId) return false;
163
+ if (candidate.authority.authorityEpoch !== current.authority.authorityEpoch) {
164
+ return candidate.authority.authorityEpoch > current.authority.authorityEpoch;
165
+ }
166
+ return candidate.catalogueRevision > current.catalogueRevision;
167
+ }