@astrale-os/kernel-client 1.0.0-beta.5 → 1.0.0-beta.50

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 (206) hide show
  1. package/dist/auth/authorization.d.ts +10 -5
  2. package/dist/auth/authorization.js +14 -1
  3. package/dist/auth/index.d.ts +1 -0
  4. package/dist/client/admission.js +3 -1
  5. package/dist/client/client.d.ts +70 -4
  6. package/dist/client/client.js +209 -32
  7. package/dist/client/index.d.ts +3 -3
  8. package/dist/client/index.js +2 -2
  9. package/dist/client/level.d.ts +58 -0
  10. package/dist/client/level.js +159 -0
  11. package/dist/client/request.d.ts +7 -2
  12. package/dist/client/request.js +11 -7
  13. package/dist/client/result.d.ts +14 -1
  14. package/dist/client/result.js +19 -8
  15. package/dist/client/routing-control.d.ts +11 -15
  16. package/dist/client/routing-control.js +21 -29
  17. package/dist/errors/index.d.ts +3 -0
  18. package/dist/errors/index.js +3 -0
  19. package/dist/errors/inexpressible-error.d.ts +23 -0
  20. package/dist/errors/inexpressible-error.js +26 -0
  21. package/dist/errors/query-input.d.ts +47 -0
  22. package/dist/errors/query-input.js +85 -0
  23. package/dist/errors/refusal.d.ts +12 -0
  24. package/dist/errors/refusal.js +44 -6
  25. package/dist/errors/response-too-large-error.d.ts +11 -0
  26. package/dist/errors/response-too-large-error.js +15 -0
  27. package/dist/errors/stale-route-error.d.ts +1 -1
  28. package/dist/errors/stale-route-error.js +1 -1
  29. package/dist/{schema → execution}/admission.d.ts +2 -2
  30. package/dist/{schema → execution}/admission.js +2 -2
  31. package/dist/{session/execution.d.ts → execution/contracts.d.ts} +22 -34
  32. package/dist/execution/contracts.js +1 -0
  33. package/dist/execution/deadline.d.ts +18 -0
  34. package/dist/execution/deadline.js +25 -0
  35. package/dist/execution/execution.d.ts +61 -0
  36. package/dist/execution/execution.js +132 -0
  37. package/dist/execution/index.d.ts +4 -0
  38. package/dist/execution/index.js +3 -0
  39. package/dist/graph/domain/binding.d.ts +2 -2
  40. package/dist/graph/domain/binding.js +20 -17
  41. package/dist/graph/domain/conformance.d.ts +12 -0
  42. package/dist/graph/domain/conformance.js +18 -0
  43. package/dist/graph/domain/index.d.ts +1 -0
  44. package/dist/graph/domain/index.js +1 -1
  45. package/dist/graph/domain/provenance.d.ts +0 -2
  46. package/dist/graph/domain/provenance.js +0 -4
  47. package/dist/graph/graph.d.ts +17 -3
  48. package/dist/graph/graph.js +4 -1
  49. package/dist/graph/index.d.ts +3 -3
  50. package/dist/graph/index.js +1 -1
  51. package/dist/graph/page-contract.d.ts +66 -1
  52. package/dist/graph/provenance.d.ts +4 -5
  53. package/dist/graph/provenance.js +5 -6
  54. package/dist/graph/query.d.ts +10 -4
  55. package/dist/graph/query.js +144 -5
  56. package/dist/graph/query.typecheck.d.ts +81 -0
  57. package/dist/graph/query.typecheck.js +34 -0
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.js +1 -1
  60. package/dist/schema/contracts.d.ts +54 -79
  61. package/dist/schema/index.d.ts +2 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +36 -64
  64. package/dist/schema/installation.js +67 -131
  65. package/dist/schema/schema.d.ts +10 -16
  66. package/dist/schema/schema.js +57 -34
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +36 -32
  70. package/dist/session/content/api.d.ts +20 -2
  71. package/dist/session/content/api.js +17 -7
  72. package/dist/session/content/files.d.ts +12 -0
  73. package/dist/session/content/files.js +47 -0
  74. package/dist/session/content/index.d.ts +1 -1
  75. package/dist/session/content/input.d.ts +13 -2
  76. package/dist/session/content/input.js +25 -4
  77. package/dist/session/content/retry.d.ts +5 -1
  78. package/dist/session/content/retry.js +21 -31
  79. package/dist/session/context/index.d.ts +2 -2
  80. package/dist/session/context/index.js +2 -2
  81. package/dist/session/context/operation.d.ts +2 -0
  82. package/dist/session/context/operation.js +5 -0
  83. package/dist/session/context/policy.d.ts +2 -0
  84. package/dist/session/context/policy.js +6 -3
  85. package/dist/session/credential/credentials.d.ts +2 -1
  86. package/dist/session/credential/credentials.js +62 -29
  87. package/dist/session/discovery/bundle.d.ts +13 -4
  88. package/dist/session/discovery/bundle.js +85 -36
  89. package/dist/session/discovery/discovery.d.ts +1 -1
  90. package/dist/session/discovery/discovery.js +8 -11
  91. package/dist/session/discovery/index.d.ts +1 -0
  92. package/dist/session/discovery/index.js +5 -1
  93. package/dist/session/discovery/release.d.ts +2 -0
  94. package/dist/session/discovery/release.js +34 -31
  95. package/dist/session/discovery/response.d.ts +4 -0
  96. package/dist/session/discovery/response.js +10 -6
  97. package/dist/session/discovery/snapshot.d.ts +5 -1
  98. package/dist/session/discovery/transport.d.ts +37 -3
  99. package/dist/session/discovery/transport.js +62 -1
  100. package/dist/session/durable.d.ts +13 -0
  101. package/dist/session/durable.js +39 -0
  102. package/dist/session/exchange/exchange.d.ts +3 -2
  103. package/dist/session/exchange/exchange.js +10 -7
  104. package/dist/session/exchange/index.d.ts +1 -1
  105. package/dist/session/exchange/index.js +1 -1
  106. package/dist/session/exchange/presentation.js +28 -10
  107. package/dist/session/exchange/source.d.ts +7 -7
  108. package/dist/session/exchange/source.js +26 -27
  109. package/dist/session/index.d.ts +5 -4
  110. package/dist/session/index.js +0 -1
  111. package/dist/session/options.d.ts +4 -2
  112. package/dist/session/options.js +3 -3
  113. package/dist/session/reference.d.ts +27 -6
  114. package/dist/session/reference.js +18 -3
  115. package/dist/session/retry.d.ts +12 -0
  116. package/dist/session/retry.js +23 -0
  117. package/dist/session/routing/auth.d.ts +9 -3
  118. package/dist/session/routing/auth.js +4 -3
  119. package/dist/session/routing/cache.d.ts +12 -5
  120. package/dist/session/routing/cache.js +56 -48
  121. package/dist/session/routing/dispatch.d.ts +26 -3
  122. package/dist/session/routing/dispatch.js +112 -69
  123. package/dist/session/routing/envelope.d.ts +3 -3
  124. package/dist/session/routing/index.d.ts +1 -1
  125. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  126. package/dist/session/routing/legacy/release-route.js +6 -0
  127. package/dist/session/routing/recovery.d.ts +3 -6
  128. package/dist/session/routing/recovery.js +3 -14
  129. package/dist/session/routing/request.d.ts +2 -1
  130. package/dist/session/routing/request.js +2 -1
  131. package/dist/session/routing/result.d.ts +1 -1
  132. package/dist/session/routing/result.js +5 -1
  133. package/dist/session/routing/store.js +4 -5
  134. package/dist/session/session.d.ts +31 -5
  135. package/dist/session/session.js +70 -22
  136. package/dist/session/session.typecheck.js +20 -6
  137. package/dist/session/views/index.d.ts +2 -2
  138. package/dist/session/views/index.js +2 -2
  139. package/dist/session/views/kernel.d.ts +31 -0
  140. package/dist/session/views/kernel.js +30 -0
  141. package/dist/session/views/legacy/catalog.d.ts +21 -0
  142. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  143. package/dist/session/views/legacy/index.d.ts +14 -0
  144. package/dist/session/views/legacy/index.js +14 -0
  145. package/dist/session/views/legacy/resolve.d.ts +46 -0
  146. package/dist/session/views/legacy/resolve.js +83 -0
  147. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  148. package/dist/session/views/legacy/unplaced.js +26 -0
  149. package/dist/session/views/read.d.ts +49 -0
  150. package/dist/session/views/read.js +148 -0
  151. package/dist/session/views/view.d.ts +48 -0
  152. package/dist/session/views/view.js +74 -0
  153. package/dist/store/memory.d.ts +1 -3
  154. package/dist/store/memory.js +61 -112
  155. package/dist/store/shape.d.ts +33 -12
  156. package/dist/store/shape.js +125 -16
  157. package/dist/store/store.d.ts +6 -6
  158. package/dist/store/store.js +1 -1
  159. package/dist/transport/auto/decision.d.ts +28 -14
  160. package/dist/transport/auto/decision.js +39 -32
  161. package/dist/transport/auto/fallback.d.ts +1 -1
  162. package/dist/transport/auto/fallback.js +5 -10
  163. package/dist/transport/auto/transport.d.ts +10 -3
  164. package/dist/transport/auto/transport.js +41 -32
  165. package/dist/transport/deadline.d.ts +2 -0
  166. package/dist/transport/deadline.js +18 -0
  167. package/dist/transport/failure.d.ts +28 -1
  168. package/dist/transport/failure.js +63 -1
  169. package/dist/transport/http/admission.js +8 -35
  170. package/dist/transport/http/binary-request.d.ts +44 -0
  171. package/dist/transport/http/binary-request.js +110 -0
  172. package/dist/transport/http/binary.js +3 -3
  173. package/dist/transport/http/byte-stream.d.ts +2 -1
  174. package/dist/transport/http/byte-stream.js +12 -8
  175. package/dist/transport/http/configuration.d.ts +7 -0
  176. package/dist/transport/http/configuration.js +2 -0
  177. package/dist/transport/http/index.d.ts +1 -1
  178. package/dist/transport/http/index.js +1 -1
  179. package/dist/transport/http/response.d.ts +13 -1
  180. package/dist/transport/http/response.js +22 -9
  181. package/dist/transport/http/stream.d.ts +8 -13
  182. package/dist/transport/http/stream.js +34 -81
  183. package/dist/transport/http/transport.d.ts +14 -1
  184. package/dist/transport/http/transport.js +110 -35
  185. package/dist/transport/http/unprocessed.d.ts +5 -0
  186. package/dist/transport/http/unprocessed.js +28 -0
  187. package/dist/transport/index.d.ts +2 -1
  188. package/dist/transport/index.js +2 -1
  189. package/dist/transport/level.d.ts +42 -0
  190. package/dist/transport/level.js +58 -0
  191. package/dist/transport/stream.d.ts +52 -0
  192. package/dist/transport/stream.js +101 -0
  193. package/dist/transport/transport.d.ts +33 -0
  194. package/dist/transport/unary.d.ts +9 -0
  195. package/dist/transport/unary.js +36 -0
  196. package/dist/transport/websocket/connection.d.ts +13 -4
  197. package/dist/transport/websocket/connection.js +123 -96
  198. package/dist/transport/websocket/exchange.d.ts +15 -19
  199. package/dist/transport/websocket/exchange.js +87 -183
  200. package/dist/transport/websocket/transport.d.ts +19 -1
  201. package/dist/transport/websocket/transport.js +50 -21
  202. package/package.json +9 -7
  203. package/dist/session/execution.js +0 -34
  204. package/dist/session/views/catalog.d.ts +0 -19
  205. package/dist/session/views/resolve.d.ts +0 -13
  206. package/dist/session/views/resolve.js +0 -21
@@ -1,24 +1,26 @@
1
1
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
2
- import { ProtocolError, ResponseError, TransportError } from '../../errors/index.js';
3
- import { invocationFailure } from '../failure.js';
4
- import { asError } from '../index.js';
5
- import { decodeProtocol, requireId } from './response.js';
2
+ import { ProtocolError } from '../../errors/index.js';
3
+ import { abortFailure, withInvocation } from '../failure.js';
4
+ import { FrameStream } from '../stream.js';
5
+ import { decodeProtocol, requireId, tooLarge } from './response.js';
6
+ /** The HTTP binding of one value stream: reads its length-prefixed frames as its consumer reads. */
6
7
  export class HttpStream {
7
8
  frames;
8
9
  codec;
9
10
  requestId;
10
11
  control;
11
12
  invocation;
12
- claimed = false;
13
- terminal = false;
14
- index = 0;
13
+ released = false;
15
14
  interruption;
16
15
  constructor(frames, codec, requestId, control) {
17
16
  this.frames = frames;
18
17
  this.codec = codec;
19
18
  this.requestId = requestId;
20
19
  this.control = control;
21
- const abort = () => void this.interrupt(this.abortFailure(control.signal.reason));
20
+ const abort = () => void this.interrupt(abortFailure(control, 'stream exceeded its invocation timeout.', 'stream was cancelled.', {
21
+ delivery: 'unknown',
22
+ invocation: this.invocation,
23
+ }));
22
24
  if (control.signal.aborted)
23
25
  abort();
24
26
  else
@@ -27,66 +29,42 @@ export class HttpStream {
27
29
  static async open(response, codec, requestId, maximumFrameBytes, control) {
28
30
  if (response.body === null)
29
31
  throw new ProtocolError('stream has no body.');
30
- const stream = new HttpStream(new LengthPrefixedFrames(response.body.getReader(), maximumFrameBytes), codec, requestId, control);
31
- const first = await stream.readFrame();
32
+ const binding = new HttpStream(new LengthPrefixedFrames(response.body.getReader(), maximumFrameBytes), codec, requestId, control);
33
+ const first = await binding.readFrame();
32
34
  if (first === null || first.kind !== 'stream.start') {
33
- await stream.stop('invalid stream start');
35
+ await binding.stop('invalid stream start');
34
36
  throw new ProtocolError('stream did not begin with stream.start.');
35
37
  }
36
- stream.invocation = first.invocation;
38
+ binding.invocation = first.invocation;
39
+ const stream = new FrameStream(first.invocation, {
40
+ read: () => binding.read(stream),
41
+ cancel: (reason) => binding.stop(reason),
42
+ });
37
43
  return stream;
38
44
  }
39
- [Symbol.asyncIterator]() {
40
- if (this.claimed)
41
- throw new TypeError('streams admit exactly one consumer.');
42
- this.claimed = true;
43
- return {
44
- next: () => this.next(),
45
- return: async () => {
46
- await this.cancel('stream consumer stopped');
47
- return { done: true, value: undefined };
48
- },
49
- throw: async (error) => {
50
- await this.cancel('stream consumer failed');
51
- throw error;
52
- },
53
- };
54
- }
55
- async cancel(reason = 'stream cancelled') {
56
- await this.stop(reason);
57
- }
58
- async next() {
45
+ async read(stream) {
59
46
  if (this.interruption !== undefined)
60
47
  throw this.interruption;
61
- if (this.terminal)
48
+ if (this.released)
62
49
  return { done: true, value: undefined };
63
50
  try {
64
51
  const frame = await this.readFrame();
65
52
  if (frame === null) {
66
53
  throw new ProtocolError('stream ended without a terminal frame.');
67
54
  }
68
- if (frame.kind === 'stream.item') {
69
- if (frame.index !== this.index) {
70
- throw new ProtocolError(`stream item ${frame.index} does not match expected index ${this.index}.`);
71
- }
72
- this.index += 1;
73
- return { done: false, value: frame.value };
74
- }
75
- if (frame.kind === 'stream.error') {
76
- await this.finish();
77
- throw new ResponseError(frame.error.code, frame.error.message, this.invocation, frame.error.data);
78
- }
79
- if (frame.kind !== 'stream.end') {
80
- throw new ProtocolError(`Unexpected ${frame.kind} frame inside stream.`);
81
- }
82
- if (frame.count !== this.index) {
83
- throw new ProtocolError(`stream ended with count ${frame.count}; ${this.index} items were received.`);
55
+ if (frame.kind === 'stream.start') {
56
+ throw new ProtocolError('Unexpected stream.start frame inside stream.');
84
57
  }
58
+ const step = stream.accept(frame);
59
+ if (step.kind === 'item')
60
+ return { done: false, value: step.value };
85
61
  await this.finish();
62
+ if (step.kind === 'error')
63
+ throw step.error;
86
64
  return { done: true, value: undefined };
87
65
  }
88
66
  catch (error) {
89
- const failure = this.interruption ?? retainInvocationId(error, this.invocation);
67
+ const failure = this.interruption ?? withInvocation(error, stream.invocation);
90
68
  await this.stop(failure);
91
69
  throw failure;
92
70
  }
@@ -102,52 +80,27 @@ export class HttpStream {
102
80
  return frame;
103
81
  }
104
82
  async finish() {
105
- if (this.terminal)
83
+ if (this.released)
106
84
  return;
107
85
  await this.frames.requireEnd();
108
- this.terminal = true;
86
+ this.released = true;
109
87
  this.control.close();
110
88
  }
111
89
  async interrupt(reason) {
112
- if (this.terminal || this.interruption !== undefined)
90
+ if (this.released || this.interruption !== undefined)
113
91
  return;
114
92
  this.interruption = reason;
115
93
  await this.frames.cancel(reason);
116
94
  this.control.close();
117
95
  }
118
96
  async stop(reason) {
119
- if (this.terminal)
97
+ if (this.released)
120
98
  return;
121
- this.terminal = true;
99
+ this.released = true;
122
100
  this.control.cancel(reason);
123
101
  await this.frames.cancel(reason);
124
102
  this.control.close();
125
103
  }
126
- abortFailure(reason) {
127
- if (this.control.timedOut) {
128
- return invocationFailure('stream exceeded its invocation timeout.', 'timeout', {
129
- cause: asError(reason),
130
- delivery: 'unknown',
131
- invocation: this.invocation,
132
- });
133
- }
134
- return asError(reason ?? new Error('stream was cancelled.'));
135
- }
136
- }
137
- function retainInvocationId(input, invocation) {
138
- if (input instanceof ProtocolError && input.invocation === undefined) {
139
- return new ProtocolError(input.message, { cause: input, invocation });
140
- }
141
- if (input instanceof TransportError &&
142
- input.context.kind === 'invocation' &&
143
- input.context.invocation === undefined) {
144
- return invocationFailure(input.message, input.phase, {
145
- cause: input,
146
- delivery: input.context.delivery,
147
- invocation,
148
- });
149
- }
150
- return input;
151
104
  }
152
105
  class LengthPrefixedFrames {
153
106
  reader;
@@ -165,7 +118,7 @@ class LengthPrefixedFrames {
165
118
  return null;
166
119
  const length = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(0);
167
120
  if (length > this.maximumFrameBytes) {
168
- throw new ProtocolError(`stream frame exceeds maximumResponseBytes (${this.maximumFrameBytes}).`);
121
+ throw tooLarge('stream frame', this.maximumFrameBytes);
169
122
  }
170
123
  return (await this.take(length, false));
171
124
  }
@@ -1,19 +1,32 @@
1
1
  import type { RequestOptions, Transport, TransportRequest, TransportResult } from '../index.js';
2
+ import type { BinaryBody } from './binary-request.js';
2
3
  import type { HttpTransportOptions } from './configuration.js';
4
+ /**
5
+ * Package-private binary invocation of an admitted body, which may be a one-shot stream;
6
+ * intentionally absent from the public HttpTransport facade, whose callers could not resend a
7
+ * stream a Redirect answers.
8
+ */
9
+ export declare function dispatchBinaryBody(transport: HttpTransport, input: TransportRequest, body: BinaryBody, options?: RequestOptions): Promise<TransportResult>;
3
10
  /** HTTP implementation of the universal invocation protocol. */
4
11
  export declare class HttpTransport implements Transport {
5
12
  readonly url: string;
6
13
  private readonly fetchImpl;
7
14
  private readonly headers;
8
- private readonly timeoutMs;
15
+ readonly timeoutMs: number;
9
16
  private readonly maximumRequestBytes;
10
17
  private readonly maximumResponseBytes;
18
+ private readonly levels;
19
+ /** What a request written at the current level accepts. */
20
+ private readonly accept;
11
21
  private nextId;
12
22
  constructor(options: HttpTransportOptions);
13
23
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
14
24
  /** HTTP-only binary invocation; each call may replay a re-readable Blob. */
15
25
  dispatchBinary(input: TransportRequest, body: Blob, options?: RequestOptions): Promise<TransportResult>;
26
+ /** A Blob may be replayed; a stream is read once, by this call, and must yield its length. */
27
+ private dispatchBody;
16
28
  private dispatchWith;
29
+ private send;
17
30
  private fetchResponse;
18
31
  private nextRequestId;
19
32
  }
@@ -1,10 +1,26 @@
1
1
  import * as codecs from '@astrale-os/kernel-protocol/codecs';
2
2
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
- import { ProtocolError, ResponseError, TransportError } from '../../errors/index.js';
4
- import { invocationFailure } from '../failure.js';
5
- import { asError, controlledSignal, positiveInteger, requireLive, } from '../index.js';
3
+ import { ClientError } from '../../errors/index.js';
4
+ import { invocationFailure, requestFailure } from '../failure.js';
5
+ import { controlledSignal, positiveInteger, requireLive } from '../index.js';
6
+ import { served, writtenLevel } from '../level.js';
6
7
  import { admitResponse } from './admission.js';
8
+ import { cancelUnsent, replayableBody, sendStream } from './binary-request.js';
7
9
  import { capture } from './configuration.js';
10
+ import { hostLevel } from './response.js';
11
+ import { unprocessed } from './unprocessed.js';
12
+ const bodyDispatch = new WeakMap();
13
+ /**
14
+ * Package-private binary invocation of an admitted body, which may be a one-shot stream;
15
+ * intentionally absent from the public HttpTransport facade, whose callers could not resend a
16
+ * stream a Redirect answers.
17
+ */
18
+ export async function dispatchBinaryBody(transport, input, body, options = {}) {
19
+ const dispatch = bodyDispatch.get(transport);
20
+ if (dispatch === undefined)
21
+ throw new TypeError('Binary body dispatch requires an HttpTransport.');
22
+ return dispatch(input, body, options);
23
+ }
8
24
  /** HTTP implementation of the universal invocation protocol. */
9
25
  export class HttpTransport {
10
26
  url;
@@ -13,15 +29,25 @@ export class HttpTransport {
13
29
  timeoutMs;
14
30
  maximumRequestBytes;
15
31
  maximumResponseBytes;
32
+ levels;
33
+ /** What a request written at the current level accepts. */
34
+ accept;
16
35
  nextId = 1;
17
36
  constructor(options) {
18
37
  const configuration = capture(options);
38
+ this.levels = configuration.levels;
39
+ // A build that knows no wire change states no level, as the builds released before it.
40
+ this.accept =
41
+ configuration.levels.current === 0
42
+ ? protocol.http.acceptFor(codecs.json)
43
+ : protocol.http.acceptFor(codecs.json, configuration.levels.current);
19
44
  this.url = configuration.url;
20
45
  this.fetchImpl = configuration.fetch;
21
46
  this.headers = configuration.headers;
22
47
  this.timeoutMs = configuration.timeoutMs;
23
48
  this.maximumRequestBytes = configuration.maximumRequestBytes;
24
49
  this.maximumResponseBytes = configuration.maximumResponseBytes;
50
+ bodyDispatch.set(this, (input, body, options) => this.dispatchBody(input, body, options));
25
51
  }
26
52
  async dispatch(input, options = {}) {
27
53
  return this.dispatchWith(input, options);
@@ -30,16 +56,37 @@ export class HttpTransport {
30
56
  async dispatchBinary(input, body, options = {}) {
31
57
  if (!(body instanceof Blob))
32
58
  throw new TypeError('Binary request body must be a Blob.');
59
+ return this.dispatchBody(input, replayableBody(body), options);
60
+ }
61
+ /** A Blob may be replayed; a stream is read once, by this call, and must yield its length. */
62
+ async dispatchBody(input, body, options) {
33
63
  if (options.idempotencyKey !== undefined) {
64
+ cancelUnsent(body);
34
65
  throw new TypeError('Binary requests cannot carry an idempotency key.');
35
66
  }
36
67
  return this.dispatchWith(input, options, body);
37
68
  }
38
69
  async dispatchWith(input, options, binaryBody) {
70
+ // The stream is claimed first: whatever ends this call before reading it through cancels it.
71
+ const sent = binaryBody?.kind === 'once' ? sendStream(binaryBody) : binaryBody;
72
+ try {
73
+ return await this.send(input, options, sent);
74
+ }
75
+ finally {
76
+ if (sent?.kind === 'once') {
77
+ sent.release(new ClientError('Binary request settled before its stream ended.'));
78
+ }
79
+ }
80
+ }
81
+ async send(input, options, binary) {
82
+ const streamed = binary?.kind === 'once' ? binary : undefined;
39
83
  const requestId = this.nextRequestId();
40
84
  const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
41
85
  const codec = codecs.json;
42
- const { trace: traceInput, ...invocationInput } = input;
86
+ const { trace: traceInput, level: writtenInput, ...invocationInput } = input;
87
+ // The request states the level it is written at; the Host answers at that level at most.
88
+ const written = writtenLevel(writtenInput, this.levels);
89
+ const accept = written === this.levels.current ? this.accept : protocol.http.acceptFor(codec, written);
43
90
  const trace = traceInput === undefined ? undefined : protocol.admitTrace(traceInput);
44
91
  const request = protocol.decodeRequest({
45
92
  version: protocol.VERSION,
@@ -47,63 +94,109 @@ export class HttpTransport {
47
94
  ...invocationInput,
48
95
  ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
49
96
  });
50
- const encoded = binaryBody === undefined
97
+ const encoded = binary === undefined
51
98
  ? codec.encode(request)
52
99
  : protocol.http.encodeBinaryRequestEnvelope(request);
53
100
  const control = controlledSignal(options.signal, timeoutMs);
101
+ // A failed stream aborts the request, so no Fetch sends its truncated body as complete. The
102
+ // request fails with the stream's ClientError whatever the abort reason, so it is the plain
103
+ // AbortError: workerd logs any other abort reason as an uncaught error.
104
+ streamed?.abortOnFailure(() => control.cancel());
54
105
  let handedOff = false;
55
106
  let phase = 'connect';
107
+ // The status of the response being received, which a failure to read it still reports.
108
+ let status;
56
109
  let delivery = 'not-sent';
57
110
  try {
58
111
  requireLive(control);
59
- if (binaryBody === undefined && encodedByteLength(encoded) > this.maximumRequestBytes) {
112
+ if (binary === undefined && encodedByteLength(encoded) > this.maximumRequestBytes) {
60
113
  throw invocationFailure(`request exceeds maximumRequestBytes (${this.maximumRequestBytes}).`, 'send');
61
114
  }
62
115
  phase = 'send';
63
116
  delivery = 'unknown';
64
- const response = await this.fetchResponse(codec, encoded, trace, control, binaryBody);
117
+ const response = await this.fetchResponse(codec, encoded, accept, trace, control, binary);
118
+ // A Fetch that ignores the abort may still end a failed stream body as though it were
119
+ // complete: the server then answered bytes the caller never sent, and its answer is dropped.
120
+ const failed = streamed?.failure();
121
+ if (failed !== undefined) {
122
+ response.body?.cancel().catch(() => undefined);
123
+ throw failed;
124
+ }
65
125
  phase = 'receive';
126
+ status = response.status;
66
127
  requireLive(control);
128
+ // The Host read the request, and wrote this response, at the level the request stated or
129
+ // at its own, whichever is lower.
130
+ const host = hostLevel(response);
131
+ const level = host < written ? host : written;
67
132
  const result = await admitResponse(response, requestId, {
68
133
  maximumBytes: this.maximumResponseBytes,
69
134
  control,
135
+ level,
136
+ host,
70
137
  });
71
138
  handedOff =
72
139
  result.kind === 'stream' ||
73
140
  (result.kind === 'binary' && !(result.value.body instanceof Uint8Array));
74
- return result;
141
+ return served(result, level, host);
75
142
  }
76
143
  catch (error) {
77
- throw transportFailure(error, control, options.signal, timeoutMs, this.url, phase, delivery);
144
+ // The caller's stream failed, or yielded other than its declared length: the ClientError
145
+ // naming it, with the stream's own failure as its cause, is the failure of this request.
146
+ const rejected = streamed?.failure();
147
+ if (rejected !== undefined)
148
+ throw rejected;
149
+ // A request the server refused unprocessed, even when sent again, was never delivered.
150
+ throw requestFailure(error, control, {
151
+ phase,
152
+ delivery: phase === 'send' && unprocessed(error) ? 'not-sent' : delivery,
153
+ timeout: `request timed out after ${timeoutMs}ms.`,
154
+ failure: status === undefined
155
+ ? `Failed to communicate with the server at ${this.url}.`
156
+ : `Failed to read the HTTP ${status} response of the server at ${this.url}.`,
157
+ });
78
158
  }
79
159
  finally {
80
160
  if (!handedOff)
81
161
  control.close();
82
162
  }
83
163
  }
84
- async fetchResponse(codec, encoded, trace, control, binaryBody) {
164
+ async fetchResponse(codec, encoded, accept, trace, control, binary) {
85
165
  const init = {
86
166
  method: 'POST',
87
167
  redirect: 'manual',
88
168
  credentials: 'omit',
89
169
  referrerPolicy: 'no-referrer',
90
- // Fetch owns Content-Length; the protocol carries Blob.size across Fetch runtimes.
170
+ // Fetch owns Content-Length; the protocol carries the exact length across Fetch runtimes.
91
171
  headers: {
92
172
  ...this.headers,
93
173
  ...protocol.http.encodeTraceHeaders(trace),
94
- 'content-type': binaryBody === undefined ? codec.contentType : protocol.http.BINARY_REQUEST_CONTENT_TYPE,
95
- accept: codec.contentType,
96
- ...(binaryBody === undefined
174
+ 'content-type': binary === undefined ? codec.contentType : protocol.http.BINARY_REQUEST_CONTENT_TYPE,
175
+ accept,
176
+ ...(binary === undefined
97
177
  ? {}
98
178
  : {
99
179
  [protocol.http.REQUEST_ENVELOPE_FIELD]: encoded,
100
- [protocol.http.BINARY_LENGTH_FIELD]: String(binaryBody.size),
180
+ [protocol.http.BINARY_LENGTH_FIELD]: String(binary.length),
101
181
  }),
102
182
  },
103
- body: binaryBody ?? toBody(encoded),
183
+ body: binary === undefined ? toBody(encoded) : binary.body,
184
+ // Fetch sends a stream body without buffering it only in half duplex.
185
+ ...(binary?.kind === 'once' ? { duplex: 'half' } : {}),
104
186
  signal: control.signal,
105
187
  };
106
- return this.fetchImpl(this.url, init);
188
+ try {
189
+ return await this.fetchImpl(this.url, init);
190
+ }
191
+ catch (error) {
192
+ // The server processed none of it: send it once more, on the connection that replaces the
193
+ // one that refused it, under the same timeout and signal (CLIENT-HTTP-UNPROCESSED-RESEND).
194
+ // A stream body was consumed by the refused attempt: it is never sent again.
195
+ if (!unprocessed(error) || control.signal.aborted || binary?.kind === 'once') {
196
+ throw error;
197
+ }
198
+ return this.fetchImpl(this.url, init);
199
+ }
107
200
  }
108
201
  nextRequestId() {
109
202
  const requestId = this.nextId;
@@ -120,21 +213,3 @@ function toBody(input) {
120
213
  function encodedByteLength(input) {
121
214
  return typeof input === 'string' ? new TextEncoder().encode(input).byteLength : input.byteLength;
122
215
  }
123
- function transportFailure(input, control, parent, timeoutMs, url, phase, delivery) {
124
- if (input instanceof ResponseError || input instanceof ProtocolError)
125
- return input;
126
- if (control.timedOut) {
127
- return invocationFailure(`request timed out after ${timeoutMs}ms.`, 'timeout', {
128
- cause: asError(input),
129
- delivery,
130
- });
131
- }
132
- if (parent?.aborted)
133
- return asError(parent.reason ?? input);
134
- return input instanceof TransportError
135
- ? input
136
- : invocationFailure(`Failed to communicate with the server at ${url}.`, phase, {
137
- cause: asError(input),
138
- delivery,
139
- });
140
- }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Whether a Fetch failure proves that the server never processed the request. Only the exact
3
+ * refusal above does: any other failure, or a refusal reported in other words, proves nothing.
4
+ */
5
+ export declare function unprocessed(failure: unknown): boolean;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The failure undici's Fetch reports for a request that an HTTP/2 GOAWAY with NO_ERROR refused: one
3
+ * whose stream it never opened, or opened above the GOAWAY's last stream identifier. The server
4
+ * processed none of them (RFC 9113, Section 6.8). undici sends such a request again itself only
5
+ * when its body can be replayed, which a Fetch request body, always a stream, cannot.
6
+ */
7
+ const GOAWAY_REFUSAL = Object.freeze({
8
+ code: 'UND_ERR_INFO',
9
+ message: 'HTTP/2: "GOAWAY" frame received with code 0',
10
+ });
11
+ /** Causes a Fetch failure wraps before the one that names the refusal. */
12
+ const MAXIMUM_CAUSES = 4;
13
+ /**
14
+ * Whether a Fetch failure proves that the server never processed the request. Only the exact
15
+ * refusal above does: any other failure, or a refusal reported in other words, proves nothing.
16
+ */
17
+ export function unprocessed(failure) {
18
+ let cause = failure;
19
+ for (let depth = 0; depth <= MAXIMUM_CAUSES; depth++) {
20
+ if (typeof cause !== 'object' || cause === null)
21
+ return false;
22
+ const { code, message } = cause;
23
+ if (code === GOAWAY_REFUSAL.code && message === GOAWAY_REFUSAL.message)
24
+ return true;
25
+ cause = cause.cause;
26
+ }
27
+ return false;
28
+ }
@@ -1,2 +1,3 @@
1
1
  export type { RequestOptions, DeploymentRetired, MissControl, StaleControl, Transport, TransportRequest, TransportResult, } from './transport.js';
2
- export { asError, controlledSignal, positiveInteger, requireLive, type ControlledSignal, } from './deadline.js';
2
+ export { ConnectionMoved, served, servedOf, type Served } from './level.js';
3
+ export { asError, controlledSignal, pause, positiveInteger, requireLive, type ControlledSignal, } from './deadline.js';
@@ -1 +1,2 @@
1
- export { asError, controlledSignal, positiveInteger, requireLive, } from './deadline.js';
1
+ export { ConnectionMoved, served, servedOf } from './level.js';
2
+ export { asError, controlledSignal, pause, positiveInteger, requireLive, } from './deadline.js';
@@ -0,0 +1,42 @@
1
+ import { Levels, type Level } from '@astrale-os/kernel-core/wire';
2
+ /** The wire levels of one answer: the level it is written at and the level of its Host. */
3
+ export interface Served {
4
+ /** The wire level the answer is written at: the one its request stated or the Host's, whichever is lower. */
5
+ readonly written: Level;
6
+ /** The Host's own wire level, as it told it. */
7
+ readonly host: Level;
8
+ }
9
+ /**
10
+ * `answer`, a Transport result or the error a Host answered with, as written at `written` by a Host
11
+ * at `host`. The levels are kept beside the object and never as members of it: a caller receives
12
+ * the result its call declares, and nothing else. A Transport that states no level for an answer
13
+ * says its Host told none.
14
+ */
15
+ export declare function served<Answer extends object>(answer: Answer, written: Level, host?: Level): Answer;
16
+ /**
17
+ * The wire levels a Transport stated for `answer`: level 0 for both when it stated none. A Transport
18
+ * that wraps another reads them here to restate them for the object it returns in its place.
19
+ */
20
+ export declare function servedOf(answer: object): Served;
21
+ /**
22
+ * The connection of a Transport is at another wire level than the request it was given is written
23
+ * at: it was made again, towards a Host at another level, after it told its level. Nothing was
24
+ * sent. A Client writes the request for `level` and gives it once more; no caller sees this.
25
+ */
26
+ export declare class ConnectionMoved extends Error {
27
+ /** The wire level of the connection now. */
28
+ readonly level: Level;
29
+ constructor(
30
+ /** The wire level of the connection now. */
31
+ level: Level);
32
+ }
33
+ /**
34
+ * The wire level one request is written at: the Transport's current level unless the request names
35
+ * a lower one it reads.
36
+ */
37
+ export declare function writtenLevel(input: Level | undefined, levels: Levels): Level;
38
+ /**
39
+ * The floor and the current level a Transport states, detached from their History: those of the
40
+ * Invocation History of this build when none is given.
41
+ */
42
+ export declare function captureLevels(input: Levels | undefined): Levels;
@@ -0,0 +1,58 @@
1
+ import { acceptLevel, Levels } from '@astrale-os/kernel-core/wire';
2
+ import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
+ const SILENT = Object.freeze({ written: acceptLevel(0), host: acceptLevel(0) });
4
+ const answers = new WeakMap();
5
+ /**
6
+ * `answer`, a Transport result or the error a Host answered with, as written at `written` by a Host
7
+ * at `host`. The levels are kept beside the object and never as members of it: a caller receives
8
+ * the result its call declares, and nothing else. A Transport that states no level for an answer
9
+ * says its Host told none.
10
+ */
11
+ export function served(answer, written, host = written) {
12
+ if (written !== 0 || host !== 0) {
13
+ answers.set(answer, Object.freeze({ written: acceptLevel(written), host: acceptLevel(host) }));
14
+ }
15
+ return answer;
16
+ }
17
+ /**
18
+ * The wire levels a Transport stated for `answer`: level 0 for both when it stated none. A Transport
19
+ * that wraps another reads them here to restate them for the object it returns in its place.
20
+ */
21
+ export function servedOf(answer) {
22
+ return answers.get(answer) ?? SILENT;
23
+ }
24
+ /**
25
+ * The connection of a Transport is at another wire level than the request it was given is written
26
+ * at: it was made again, towards a Host at another level, after it told its level. Nothing was
27
+ * sent. A Client writes the request for `level` and gives it once more; no caller sees this.
28
+ */
29
+ export class ConnectionMoved extends Error {
30
+ level;
31
+ constructor(
32
+ /** The wire level of the connection now. */
33
+ level) {
34
+ super(`The connection is now at wire level ${level}.`);
35
+ this.level = level;
36
+ this.name = 'ConnectionMoved';
37
+ }
38
+ }
39
+ /**
40
+ * The wire level one request is written at: the Transport's current level unless the request names
41
+ * a lower one it reads.
42
+ */
43
+ export function writtenLevel(input, levels) {
44
+ if (input === undefined)
45
+ return levels.current;
46
+ const level = acceptLevel(input);
47
+ if (!Levels.includes(levels, level)) {
48
+ throw new TypeError(`A request cannot be written at wire level ${level}: this transport speaks levels ${levels.floor} to ${levels.current}.`);
49
+ }
50
+ return level;
51
+ }
52
+ /**
53
+ * The floor and the current level a Transport states, detached from their History: those of the
54
+ * Invocation History of this build when none is given.
55
+ */
56
+ export function captureLevels(input) {
57
+ return Levels(input ?? protocol.history);
58
+ }
@@ -0,0 +1,52 @@
1
+ import type { Value } from '@astrale-os/kernel-dsl/value';
2
+ import type * as protocol from '@astrale-os/kernel-protocol/invocation';
3
+ import type { Stream } from '../client/index.js';
4
+ import type { ResponseError } from '../errors/index.js';
5
+ /** A frame that follows a stream's `stream.start`. */
6
+ export type StreamProgress = Exclude<protocol.StreamFrame, protocol.StreamStartFrame>;
7
+ /** What one accepted frame does to its stream. */
8
+ export type FrameStep = {
9
+ readonly kind: 'item';
10
+ readonly value: Value;
11
+ } | {
12
+ readonly kind: 'end';
13
+ } | {
14
+ readonly kind: 'error';
15
+ readonly error: ResponseError;
16
+ };
17
+ /** The binding that feeds one stream its frames. */
18
+ export interface FrameSource {
19
+ /**
20
+ * Answers a read the stream cannot serve from its buffer. A binding that reads on demand answers
21
+ * every read itself, its ending included; a binding that pushes items omits it.
22
+ */
23
+ readonly read?: () => Promise<IteratorResult<Value>>;
24
+ /** Stops the stream for its consumer. */
25
+ readonly cancel: (reason: string) => Promise<void>;
26
+ }
27
+ /** The frames of one stream after its `stream.start`, sequenced, and read by exactly one consumer. */
28
+ export declare class FrameStream implements Stream {
29
+ readonly invocation: protocol.InvocationId;
30
+ private readonly source;
31
+ private readonly maximumBufferedItems;
32
+ private claimed;
33
+ private index;
34
+ private readonly items;
35
+ private readonly waiters;
36
+ private ending;
37
+ constructor(invocation: protocol.InvocationId, source: FrameSource, maximumBufferedItems?: number);
38
+ [Symbol.asyncIterator](): AsyncIterator<Value>;
39
+ cancel(reason?: string): Promise<void>;
40
+ /** The step `frame` takes; an item out of index order or a wrong end count is a ProtocolError. */
41
+ accept(frame: StreamProgress): FrameStep;
42
+ /** Hands `value` to the oldest waiting read, or buffers it; false when the buffer is full. */
43
+ push(value: Value): boolean;
44
+ /** Ends the stream: its buffered items stay readable, then every read is done. */
45
+ end(): void;
46
+ /** Fails the stream: its buffered items stay readable, then every read rejects with `error`. */
47
+ fail(error: Error): void;
48
+ /** Drops the buffered items the consumer has not read. */
49
+ discard(): void;
50
+ private next;
51
+ private settle;
52
+ }