@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,6 @@
1
1
  import type { BridgeHelloRequest } from "./generated/protocol.ts";
2
2
  import type { BridgeOperationDescriptor } from "./operation.ts";
3
- import { BridgeHostRouter } from "./router.ts";
3
+ import type { BridgeHostRouter } from "./router.ts";
4
4
 
5
5
  export class DirectBridgeAdapter {
6
6
  readonly #router: BridgeHostRouter;
@@ -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 BRIDGE_FIELDS: Record<string, readonly string[]> = {
6
+ export const BRIDGE_FIELDS = {
7
7
  "BridgeHostDescriptor": ["hostInstanceId", "form"],
8
8
  "BridgeConnectionStatus": ["state", "reason"],
9
9
  "DomainAuthorityDescriptor": ["domainId", "scopeId", "availability", "readAuthority", "writeAuthority", "executionAuthority", "authorityEpoch", "authoritativeRevision"],
@@ -29,4 +29,5 @@ export const BRIDGE_FIELDS: Record<string, readonly string[]> = {
29
29
  "BridgeCancellationReceipt": ["requestId", "targetRequestId", "jobId", "outcome"],
30
30
  "BridgeServiceRequest": ["action", "credentialRef"],
31
31
  "BridgeServiceTransitionReceipt": ["generation", "ownership", "action", "previous", "current", "outcome"],
32
- };
32
+ "BridgeHostError": ["code", "message", "retryable"],
33
+ } as const;
@@ -16,7 +16,7 @@ export const BRIDGE_MAXIMUM_FAILURE_MESSAGE_BYTES = 4096 as const;
16
16
  export const BRIDGE_MAXIMUM_DEDUPLICATION_ENTRIES = 65536 as const;
17
17
  export const BRIDGE_HOST_FORMS = ["direct","tauriLocal","localService","remote","localFirst"] as const;
18
18
  export const BRIDGE_CONNECTION_STATES = ["idle","connecting","negotiating","ready","degraded","reconnecting","offline","incompatible","unauthorized","failed","closed"] as const;
19
- export const BRIDGE_CONNECTION_REASONS = ["connectRequested","transportReady","negotiationAccepted","capabilityChanged","transportLost","retryScheduled","versionMismatch","authorizationRejected","hostFailure","shutdown"] as const;
19
+ export const BRIDGE_CONNECTION_REASONS = ["connectRequested","transportReady","negotiationAccepted","capabilityChanged","transportLost","retryScheduled","retryForbidden","versionMismatch","authorizationRejected","hostFailure","shutdown"] as const;
20
20
  export const BRIDGE_AUTHENTICATION_POSTURES = ["notRequired","required","authenticated","rejected"] as const;
21
21
  export const BRIDGE_DOMAIN_AVAILABILITIES = ["available","degraded","offline"] as const;
22
22
  export const BRIDGE_READ_AUTHORITIES = ["none","projection","authoritative"] as const;
@@ -80,7 +80,7 @@ form: BridgeHostForm, };
80
80
 
81
81
  export type BridgeConnectionState = "idle" | "connecting" | "negotiating" | "ready" | "degraded" | "reconnecting" | "offline" | "incompatible" | "unauthorized" | "failed" | "closed";
82
82
 
83
- export type BridgeConnectionReason = "connectRequested" | "transportReady" | "negotiationAccepted" | "capabilityChanged" | "transportLost" | "retryScheduled" | "versionMismatch" | "authorizationRejected" | "hostFailure" | "shutdown";
83
+ export type BridgeConnectionReason = "connectRequested" | "transportReady" | "negotiationAccepted" | "capabilityChanged" | "transportLost" | "retryScheduled" | "retryForbidden" | "versionMismatch" | "authorizationRejected" | "hostFailure" | "shutdown";
84
84
 
85
85
  export type BridgeConnectionStatus = { state: BridgeConnectionState, reason: BridgeConnectionReason | null, };
86
86
 
@@ -199,6 +199,10 @@ export type BridgeServiceRequest = { action: BridgeServiceAction, credentialRef:
199
199
  export type BridgeServiceGeneration = number;
200
200
 
201
201
  export type BridgeServiceTransitionReceipt = { generation: BridgeServiceGeneration, ownership: BridgeServiceOwnership, action: BridgeServiceAction, previous: BridgeServiceState, current: BridgeServiceState, outcome: BridgeServiceOutcome, };
202
+
203
+ export type BridgeHostErrorCode = "authorityUnavailable" | "invalidSession" | "unknownDomain" | "unknownRoute" | "capabilityUnavailable" | "readDenied" | "writeDenied" | "executionDenied" | "staleAuthority" | "invalidAuthority" | "invalidReply" | "payloadCodec" | "stateUnavailable" | "eventUnavailable" | "eventPublication" | "invalidRegistration";
204
+
205
+ export type BridgeHostError = { "code": BridgeHostErrorCode, "message": string, "retryable": boolean, };
202
206
  export const BRIDGE_ADMITTED_CONNECTION_REASONS: Record<
203
207
  BridgeConnectionState,
204
208
  readonly (BridgeConnectionReason | null)[]
@@ -209,7 +213,7 @@ export const BRIDGE_ADMITTED_CONNECTION_REASONS: Record<
209
213
  "ready": ["negotiationAccepted", "capabilityChanged"],
210
214
  "degraded": ["capabilityChanged", "transportLost", "hostFailure"],
211
215
  "reconnecting": ["retryScheduled", "transportLost"],
212
- "offline": ["transportLost"],
216
+ "offline": ["transportLost", "retryForbidden"],
213
217
  "incompatible": ["versionMismatch"],
214
218
  "unauthorized": ["authorizationRejected"],
215
219
  "failed": ["hostFailure"],
package/src/bridge/job.ts CHANGED
@@ -17,25 +17,15 @@ export class BridgeJobTracker {
17
17
  this.#jobId = jobId;
18
18
  }
19
19
 
20
- classifyProgress<P>(
21
- event: BridgeProgressEvent<P>,
22
- ): BridgeProgressDecision {
23
- if (
24
- event.requestId !== this.#requestId ||
25
- event.jobId !== this.#jobId
26
- ) {
20
+ classifyProgress<P>(event: BridgeProgressEvent<P>): BridgeProgressDecision {
21
+ if (event.requestId !== this.#requestId || event.jobId !== this.#jobId) {
27
22
  return "ignoreWrongCorrelation";
28
23
  }
29
24
  return this.#terminal ? "ignoreAfterTerminal" : "accept";
30
25
  }
31
26
 
32
- classifyTerminal<S, D>(
33
- event: BridgeJobTerminalEvent<S, D>,
34
- ): BridgeJobTerminalDecision {
35
- if (
36
- event.requestId !== this.#requestId ||
37
- event.jobId !== this.#jobId
38
- ) {
27
+ classifyTerminal<S, D>(event: BridgeJobTerminalEvent<S, D>): BridgeJobTerminalDecision {
28
+ if (event.requestId !== this.#requestId || event.jobId !== this.#jobId) {
39
29
  return "ignoreWrongCorrelation";
40
30
  }
41
31
  if (this.#terminal) {
@@ -1,6 +1,6 @@
1
1
  import type { BridgeHelloRequest } from "./generated/protocol.ts";
2
2
  import type { BridgeOperationDescriptor } from "./operation.ts";
3
- import { BridgeHostRouter } from "./router.ts";
3
+ import type { BridgeHostRouter } from "./router.ts";
4
4
 
5
5
  export type BridgeSerializationPhase =
6
6
  | "negotiation_request"
@@ -30,15 +30,9 @@ export class SerializedLoopbackBridgeAdapter {
30
30
  }
31
31
 
32
32
  async negotiate(request: BridgeHelloRequest): Promise<unknown> {
33
- const encodedRequest = serialize(
34
- request,
35
- "negotiation_request",
36
- );
33
+ const encodedRequest = serialize(request, "negotiation_request");
37
34
  const reply = await this.#router.negotiate(JSON.parse(encodedRequest));
38
- return deserialize(
39
- serialize(reply, "negotiation_reply"),
40
- "negotiation_reply",
41
- );
35
+ return deserialize(serialize(reply, "negotiation_reply"), "negotiation_reply");
42
36
  }
43
37
 
44
38
  async invoke<Request, Reply>(
@@ -46,21 +40,12 @@ export class SerializedLoopbackBridgeAdapter {
46
40
  request: Request,
47
41
  ): Promise<unknown> {
48
42
  const encodedRequest = serialize(request, "operation_request");
49
- const reply = await this.#router.invoke(
50
- operation.route,
51
- JSON.parse(encodedRequest),
52
- );
53
- return deserialize(
54
- serialize(reply, "operation_reply"),
55
- "operation_reply",
56
- );
43
+ const reply = await this.#router.invoke(operation.route, JSON.parse(encodedRequest));
44
+ return deserialize(serialize(reply, "operation_reply"), "operation_reply");
57
45
  }
58
46
  }
59
47
 
60
- export function serialize(
61
- value: unknown,
62
- phase: BridgeSerializationPhase,
63
- ): string {
48
+ export function serialize(value: unknown, phase: BridgeSerializationPhase): string {
64
49
  try {
65
50
  const encoded = JSON.stringify(value);
66
51
  if (encoded === undefined) {
@@ -72,10 +57,7 @@ export function serialize(
72
57
  }
73
58
  }
74
59
 
75
- export function deserialize(
76
- value: string,
77
- phase: BridgeSerializationPhase,
78
- ): unknown {
60
+ export function deserialize(value: string, phase: BridgeSerializationPhase): unknown {
79
61
  try {
80
62
  return JSON.parse(value);
81
63
  } catch (error) {
@@ -1,3 +1,4 @@
1
+ import { isRecord } from "../core/record.ts";
1
2
  import type {
2
3
  BridgeCommandDelivery,
3
4
  BridgeCommandEnvelope,
@@ -9,7 +10,7 @@ import type {
9
10
  DomainId,
10
11
  } from "./generated/protocol.ts";
11
12
  import type { BridgeCodec } from "./validation.ts";
12
- import { BridgeSession } from "./session.ts";
13
+ import type { BridgeSession } from "./session.ts";
13
14
 
14
15
  export type BridgeOperationKind = "query" | "command" | "cancellation";
15
16
 
@@ -44,52 +45,27 @@ export class BridgeDomainClient {
44
45
  ): Promise<Reply> {
45
46
  const checkedRequest = operation.request.parse(request);
46
47
  this.#assertAuthority(operation, checkedRequest);
47
- return operation.reply.parse(
48
- await this.#adapter.invoke(operation, checkedRequest),
49
- );
48
+ return operation.reply.parse(await this.#adapter.invoke(operation, checkedRequest));
50
49
  }
51
50
 
52
51
  #assertAuthority<Request, Reply>(
53
52
  operation: BridgeOperationDescriptor<Request, Reply>,
54
53
  request: Request,
55
54
  ): void {
56
- if (
57
- !this.#session.supports(
58
- operation.domainId,
59
- operation.requiredCapability,
60
- )
61
- ) {
62
- throw new BridgeAuthorityError(
63
- "capability_unavailable",
64
- operation.domainId,
65
- );
55
+ if (!this.#session.supports(operation.domainId, operation.requiredCapability)) {
56
+ throw new BridgeAuthorityError("capability_unavailable", operation.domainId);
66
57
  }
67
58
  const authority = this.#session.authority(operation.domainId);
68
- const context = (
69
- request as {
70
- readonly context?: {
71
- readonly domainId?: unknown;
72
- readonly sessionId?: unknown;
73
- };
74
- }
75
- ).context;
59
+ const envelope = isRecord(request) ? request : undefined;
60
+ const context = isRecord(envelope?.context) ? envelope.context : undefined;
76
61
  if (context?.domainId !== operation.domainId) {
77
- throw new BridgeAuthorityError(
78
- "request_domain_mismatch",
79
- operation.domainId,
80
- );
62
+ throw new BridgeAuthorityError("request_domain_mismatch", operation.domainId);
81
63
  }
82
64
  if (context.sessionId !== this.#session.receipt.sessionId) {
83
- throw new BridgeAuthorityError(
84
- "request_session_mismatch",
85
- operation.domainId,
86
- );
65
+ throw new BridgeAuthorityError("request_session_mismatch", operation.domainId);
87
66
  }
88
67
  if (authority === undefined || authority.availability === "offline") {
89
- throw new BridgeAuthorityError(
90
- "authority_unavailable",
91
- operation.domainId,
92
- );
68
+ throw new BridgeAuthorityError("authority_unavailable", operation.domainId);
93
69
  }
94
70
  if (operation.kind === "query" && authority.readAuthority === "none") {
95
71
  throw new BridgeAuthorityError("read_denied", operation.domainId);
@@ -98,15 +74,11 @@ export class BridgeDomainClient {
98
74
  if (authority.writeAuthority !== "authoritative") {
99
75
  throw new BridgeAuthorityError("write_denied", operation.domainId);
100
76
  }
101
- const envelope = request as BridgeCommandEnvelope<unknown>;
102
- if (envelope.authorityEpoch !== authority.authorityEpoch) {
77
+ if (envelope?.authorityEpoch !== authority.authorityEpoch) {
103
78
  throw new BridgeAuthorityError("stale_authority", operation.domainId);
104
79
  }
105
80
  }
106
- if (
107
- operation.kind === "cancellation" &&
108
- authority.executionAuthority !== "executor"
109
- ) {
81
+ if (operation.kind === "cancellation" && authority.executionAuthority !== "executor") {
110
82
  throw new BridgeAuthorityError("execution_denied", operation.domainId);
111
83
  }
112
84
  }
@@ -160,7 +132,5 @@ export function classifyBridgeQueryRetry<P>(
160
132
  retryClass: BridgeRetryClass,
161
133
  adapterAllowsRetry: boolean,
162
134
  ): BridgeQueryRetryDecision {
163
- return adapterAllowsRetry && retryClass !== "never"
164
- ? "retry"
165
- : "doNotRetry";
135
+ return adapterAllowsRetry && retryClass !== "never" ? "retry" : "doNotRetry";
166
136
  }
@@ -1,20 +1,11 @@
1
- import type {
2
- BridgeHelloRequest,
3
- BridgeNegotiationReceipt,
4
- } from "./generated/protocol.ts";
5
- import {
6
- parseBridgeHelloRequest,
7
- parseBridgeNegotiationReceipt,
8
- } from "./validation.ts";
1
+ import type { BridgeHelloRequest, BridgeNegotiationReceipt } from "./generated/protocol.ts";
2
+ import { parseBridgeHelloRequest, parseBridgeNegotiationReceipt } from "./validation.ts";
9
3
  import type { BridgeOperationDescriptor } from "./operation.ts";
10
4
 
11
- type BridgeOperationHandler<Request, Reply> = (
12
- request: Request,
13
- ) => Reply | Promise<Reply>;
5
+ type BridgeOperationHandler<Request, Reply> = (request: Request) => Reply | Promise<Reply>;
14
6
 
15
7
  interface RegisteredOperation {
16
- readonly descriptor: BridgeOperationDescriptor<unknown, unknown>;
17
- readonly handler: BridgeOperationHandler<unknown, unknown>;
8
+ invoke(value: unknown): Promise<unknown>;
18
9
  }
19
10
 
20
11
  export class BridgeHostRouter {
@@ -39,8 +30,10 @@ export class BridgeHostRouter {
39
30
  throw new Error(`duplicate bridge operation route: ${descriptor.route}`);
40
31
  }
41
32
  const registration: RegisteredOperation = {
42
- descriptor: descriptor as BridgeOperationDescriptor<unknown, unknown>,
43
- handler: handler as BridgeOperationHandler<unknown, unknown>,
33
+ async invoke(value) {
34
+ const request = descriptor.request.parse(value);
35
+ return descriptor.reply.parse(await handler(request));
36
+ },
44
37
  };
45
38
  this.#operations.set(descriptor.route, registration);
46
39
  return () => {
@@ -52,10 +45,7 @@ export class BridgeHostRouter {
52
45
 
53
46
  async negotiate(value: unknown): Promise<BridgeNegotiationReceipt> {
54
47
  const request = parseBridgeHelloRequest(value);
55
- return parseBridgeNegotiationReceipt(
56
- await this.#negotiate(request),
57
- request,
58
- );
48
+ return parseBridgeNegotiationReceipt(await this.#negotiate(request), request);
59
49
  }
60
50
 
61
51
  async invoke(route: string, value: unknown): Promise<unknown> {
@@ -63,9 +53,6 @@ export class BridgeHostRouter {
63
53
  if (registration === undefined) {
64
54
  throw new Error(`unknown bridge operation route: ${route}`);
65
55
  }
66
- const request = registration.descriptor.request.parse(value);
67
- return registration.descriptor.reply.parse(
68
- await registration.handler(request),
69
- );
56
+ return registration.invoke(value);
70
57
  }
71
58
  }
@@ -26,9 +26,8 @@ import {
26
26
  checkedRetryClass,
27
27
  checkedRetryLimit,
28
28
  BridgeRuntimeError,
29
- type BridgeRuntimeBackoff,
30
- type BridgeRuntimeClock,
31
29
  } from "./policy.ts";
30
+ import type { BridgeRuntimeBackoff, BridgeRuntimeClock } from "./policy.ts";
32
31
 
33
32
  export class BridgeConnectionRuntime {
34
33
  readonly #clock: BridgeRuntimeClock;
@@ -40,11 +39,7 @@ export class BridgeConnectionRuntime {
40
39
  #reconnectNotBefore: number | undefined;
41
40
  #session: BridgeSession | undefined;
42
41
 
43
- constructor(
44
- clock: BridgeRuntimeClock,
45
- backoff: BridgeRuntimeBackoff,
46
- reconnectLimit: number,
47
- ) {
42
+ constructor(clock: BridgeRuntimeClock, backoff: BridgeRuntimeBackoff, reconnectLimit: number) {
48
43
  this.#clock = clock;
49
44
  this.#backoff = backoff;
50
45
  this.#reconnectLimit = checkedRetryLimit(reconnectLimit);
@@ -69,53 +64,42 @@ export class BridgeConnectionRuntime {
69
64
  this.#reconnectNotBefore !== undefined &&
70
65
  at < this.#reconnectNotBefore
71
66
  ) {
72
- throw new BridgeRuntimeError(
73
- "retry_not_due",
74
- "reconnect backoff has not elapsed",
75
- );
67
+ throw new BridgeRuntimeError("retry_not_due", "reconnect backoff has not elapsed");
76
68
  }
77
- const receipt = this.#commitAt(
78
- "negotiating",
79
- "transportReady",
80
- at,
81
- null,
82
- );
69
+ this.#requireTransition("negotiating");
70
+ const receipt = this.#prepareAt("negotiating", "transportReady", at, null, this.#session);
83
71
  this.#reconnectNotBefore = undefined;
84
- return receipt;
72
+ return this.#apply(receipt);
85
73
  }
86
74
 
87
75
  acceptNegotiation(
88
76
  value: unknown,
89
- requirements: readonly BridgeAuthorityRequirement[],
77
+ requirements: ReadonlyArray<BridgeAuthorityRequirement>,
90
78
  request?: BridgeHelloRequest,
91
79
  ): BridgeConnectionTransitionReceipt {
92
80
  this.#requireTransition("ready");
93
- const checkedRequest = request === undefined
94
- ? undefined
95
- : parseBridgeHelloRequest(request);
81
+ const checkedRequest = request === undefined ? undefined : parseBridgeHelloRequest(request);
96
82
  const receipt = parseBridgeNegotiationReceipt(value, checkedRequest);
97
83
  assertRequiredAuthorities(receipt, requirements);
98
- this.#session = new BridgeSession(receipt);
84
+ const session = new BridgeSession(receipt);
85
+ const transition = this.#prepareAt(
86
+ "ready",
87
+ "negotiationAccepted",
88
+ checkedMonotonic(this.#clock.now()),
89
+ null,
90
+ session,
91
+ );
92
+ this.#session = session;
99
93
  this.#reconnectAttempts = 0;
100
94
  this.#reconnectNotBefore = undefined;
101
- return this.#commit("ready", "negotiationAccepted", null);
95
+ return this.#apply(transition);
102
96
  }
103
97
 
104
98
  degrade(
105
- reason: Extract<
106
- BridgeConnectionReason,
107
- "capabilityChanged" | "transportLost" | "hostFailure"
108
- >,
99
+ reason: Extract<BridgeConnectionReason, "capabilityChanged" | "transportLost" | "hostFailure">,
109
100
  ): BridgeConnectionTransitionReceipt {
110
- if (
111
- reason !== "capabilityChanged" &&
112
- reason !== "transportLost" &&
113
- reason !== "hostFailure"
114
- ) {
115
- throw new BridgeRuntimeError(
116
- "invalid_transition",
117
- "invalid degraded-state reason",
118
- );
101
+ if (reason !== "capabilityChanged" && reason !== "transportLost" && reason !== "hostFailure") {
102
+ throw new BridgeRuntimeError("invalid_transition", "invalid degraded-state reason");
119
103
  }
120
104
  return this.#transition("degraded", reason);
121
105
  }
@@ -123,32 +107,35 @@ export class BridgeConnectionRuntime {
123
107
  reconnect(retryClass: BridgeRetryClass): BridgeConnectionTransitionReceipt {
124
108
  retryClass = checkedRetryClass(retryClass);
125
109
  const attempt = this.#reconnectAttempts + 1;
126
- const admitted = retryClass !== "never" &&
127
- attempt <= this.#reconnectLimit;
110
+ const admitted = retryClass !== "never" && attempt <= this.#reconnectLimit;
128
111
  this.#requireTransition(admitted ? "reconnecting" : "offline");
129
112
  const at = checkedMonotonic(this.#clock.now());
130
- let reconnect: BridgeReconnectSchedule | null = null;
113
+ const reconnect: BridgeReconnectSchedule | null = admitted
114
+ ? {
115
+ attempt,
116
+ retryClass,
117
+ notBefore: checkedDeadline(at, this.#backoff.delay(retryClass, attempt)),
118
+ }
119
+ : null;
120
+ let reason: BridgeConnectionReason = "transportLost";
131
121
  if (admitted) {
132
- reconnect = {
133
- attempt,
134
- retryClass,
135
- notBefore: checkedDeadline(
136
- at,
137
- this.#backoff.delay(retryClass, attempt),
138
- ),
139
- };
140
- this.#reconnectAttempts = attempt;
141
- this.#reconnectNotBefore = reconnect.notBefore;
142
- } else {
143
- this.#reconnectNotBefore = undefined;
122
+ reason = "retryScheduled";
123
+ } else if (retryClass === "never") {
124
+ reason = "retryForbidden";
144
125
  }
145
- this.#session = undefined;
146
- return this.#commitAt(
126
+ const receipt = this.#prepareAt(
147
127
  admitted ? "reconnecting" : "offline",
148
- admitted ? "retryScheduled" : "transportLost",
128
+ reason,
149
129
  at,
150
130
  reconnect,
131
+ undefined,
151
132
  );
133
+ if (reconnect !== null) {
134
+ this.#reconnectAttempts = reconnect.attempt;
135
+ }
136
+ this.#reconnectNotBefore = reconnect?.notBefore;
137
+ this.#session = undefined;
138
+ return this.#apply(receipt);
152
139
  }
153
140
 
154
141
  incompatible(): BridgeConnectionTransitionReceipt {
@@ -187,16 +174,20 @@ export class BridgeConnectionRuntime {
187
174
  }
188
175
 
189
176
  #terminal(
190
- state: Extract<
191
- BridgeConnectionState,
192
- "incompatible" | "unauthorized" | "failed" | "closed"
193
- >,
177
+ state: Extract<BridgeConnectionState, "incompatible" | "unauthorized" | "failed" | "closed">,
194
178
  reason: BridgeConnectionReason,
195
179
  ): BridgeConnectionTransitionReceipt {
196
180
  this.#requireTransition(state);
181
+ const receipt = this.#prepareAt(
182
+ state,
183
+ reason,
184
+ checkedMonotonic(this.#clock.now()),
185
+ null,
186
+ undefined,
187
+ );
197
188
  this.#session = undefined;
198
189
  this.#reconnectNotBefore = undefined;
199
- return this.#commit(state, reason, null);
190
+ return this.#apply(receipt);
200
191
  }
201
192
 
202
193
  #transition(
@@ -204,42 +195,34 @@ export class BridgeConnectionRuntime {
204
195
  reason: BridgeConnectionReason,
205
196
  ): BridgeConnectionTransitionReceipt {
206
197
  this.#requireTransition(state);
207
- return this.#commit(state, reason, null);
208
- }
209
-
210
- #commit(
211
- state: BridgeConnectionState,
212
- reason: BridgeConnectionReason,
213
- reconnect: BridgeReconnectSchedule | null,
214
- ): BridgeConnectionTransitionReceipt {
215
- return this.#commitAt(
216
- state,
217
- reason,
218
- checkedMonotonic(this.#clock.now()),
219
- reconnect,
198
+ return this.#apply(
199
+ this.#prepareAt(state, reason, checkedMonotonic(this.#clock.now()), null, this.#session),
220
200
  );
221
201
  }
222
202
 
223
- #commitAt(
203
+ #prepareAt(
224
204
  state: BridgeConnectionState,
225
205
  reason: BridgeConnectionReason,
226
206
  at: number,
227
207
  reconnect: BridgeReconnectSchedule | null,
208
+ session: BridgeSession | undefined,
228
209
  ): BridgeConnectionTransitionReceipt {
229
- const previous = this.#status;
230
- const current = { state, reason } as BridgeConnectionStatus;
231
- this.#sequence = checkedIncrement(this.#sequence);
232
- this.#status = current;
233
210
  return {
234
- sequence: this.#sequence,
211
+ sequence: checkedIncrement(this.#sequence),
235
212
  at,
236
- previous,
237
- current,
238
- sessionId: this.#session?.receipt.sessionId ?? null,
213
+ previous: this.#status,
214
+ current: { state, reason },
215
+ sessionId: session?.receipt.sessionId ?? null,
239
216
  reconnect,
240
217
  };
241
218
  }
242
219
 
220
+ #apply(receipt: BridgeConnectionTransitionReceipt): BridgeConnectionTransitionReceipt {
221
+ this.#sequence = receipt.sequence;
222
+ this.#status = receipt.current;
223
+ return receipt;
224
+ }
225
+
243
226
  #requireTransition(next: BridgeConnectionState): void {
244
227
  if (!transitionAllowed(this.#status.state, next)) {
245
228
  throw new BridgeRuntimeError(
@@ -252,7 +235,7 @@ export class BridgeConnectionRuntime {
252
235
 
253
236
  function assertRequiredAuthorities(
254
237
  receipt: BridgeNegotiationReceipt,
255
- requirements: readonly BridgeAuthorityRequirement[],
238
+ requirements: ReadonlyArray<BridgeAuthorityRequirement>,
256
239
  ): void {
257
240
  for (const requirement of requirements) {
258
241
  const authority = receipt.domainAuthorities.find(
@@ -289,30 +272,19 @@ function authoritySatisfies(
289
272
  }
290
273
  }
291
274
 
292
- function transitionAllowed(
293
- current: BridgeConnectionState,
294
- next: BridgeConnectionState,
295
- ): boolean {
275
+ function transitionAllowed(current: BridgeConnectionState, next: BridgeConnectionState): boolean {
296
276
  if (next === "closed") {
297
277
  return current !== "closed";
298
278
  }
299
- const transitions: Partial<
300
- Record<BridgeConnectionState, readonly BridgeConnectionState[]>
301
- > = {
302
- idle: ["connecting"],
303
- connecting: ["negotiating", "reconnecting", "offline", "failed"],
304
- negotiating: [
305
- "ready",
306
- "reconnecting",
307
- "offline",
308
- "incompatible",
309
- "unauthorized",
310
- "failed",
311
- ],
312
- ready: ["degraded", "reconnecting", "offline", "failed"],
313
- degraded: ["ready", "reconnecting", "offline", "failed"],
314
- reconnecting: ["negotiating", "reconnecting", "offline", "failed"],
315
- offline: ["reconnecting", "failed"],
316
- };
279
+ const transitions: Partial<Record<BridgeConnectionState, ReadonlyArray<BridgeConnectionState>>> =
280
+ {
281
+ idle: ["connecting"],
282
+ connecting: ["negotiating", "reconnecting", "offline", "failed"],
283
+ negotiating: ["ready", "reconnecting", "offline", "incompatible", "unauthorized", "failed"],
284
+ ready: ["degraded", "reconnecting", "offline", "failed"],
285
+ degraded: ["ready", "reconnecting", "offline", "failed"],
286
+ reconnecting: ["negotiating", "reconnecting", "offline", "failed"],
287
+ offline: ["reconnecting", "failed"],
288
+ };
317
289
  return transitions[current]?.includes(next) ?? false;
318
290
  }