@astrale-os/kernel-client 1.0.0-beta.25 → 1.0.0-beta.27

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 (73) hide show
  1. package/dist/client/admission.js +3 -1
  2. package/dist/client/client.d.ts +16 -3
  3. package/dist/client/client.js +36 -15
  4. package/dist/client/index.d.ts +2 -2
  5. package/dist/client/index.js +1 -1
  6. package/dist/client/routing-control.d.ts +11 -15
  7. package/dist/client/routing-control.js +21 -29
  8. package/dist/errors/query-input.js +2 -1
  9. package/dist/errors/stale-route-error.d.ts +1 -1
  10. package/dist/errors/stale-route-error.js +1 -1
  11. package/dist/graph/page-contract.d.ts +8 -3
  12. package/dist/graph/query.js +10 -4
  13. package/dist/graph/query.typecheck.js +1 -1
  14. package/dist/session/admission.js +4 -2
  15. package/dist/session/credential/credentials.js +32 -28
  16. package/dist/session/discovery/bundle.d.ts +9 -4
  17. package/dist/session/discovery/bundle.js +28 -35
  18. package/dist/session/discovery/discovery.d.ts +1 -1
  19. package/dist/session/discovery/discovery.js +7 -10
  20. package/dist/session/discovery/release.js +18 -28
  21. package/dist/session/discovery/transport.d.ts +35 -3
  22. package/dist/session/discovery/transport.js +40 -1
  23. package/dist/session/exchange/exchange.d.ts +3 -2
  24. package/dist/session/exchange/exchange.js +10 -7
  25. package/dist/session/exchange/index.d.ts +1 -1
  26. package/dist/session/exchange/index.js +1 -1
  27. package/dist/session/exchange/presentation.js +28 -10
  28. package/dist/session/exchange/source.d.ts +7 -7
  29. package/dist/session/exchange/source.js +26 -27
  30. package/dist/session/routing/auth.d.ts +9 -3
  31. package/dist/session/routing/auth.js +4 -3
  32. package/dist/session/routing/cache.d.ts +12 -5
  33. package/dist/session/routing/cache.js +56 -48
  34. package/dist/session/routing/dispatch.d.ts +2 -1
  35. package/dist/session/routing/dispatch.js +83 -61
  36. package/dist/session/routing/index.d.ts +1 -1
  37. package/dist/session/routing/recovery.d.ts +3 -6
  38. package/dist/session/routing/recovery.js +3 -14
  39. package/dist/session/routing/store.js +4 -5
  40. package/dist/session/views/kernel.d.ts +31 -0
  41. package/dist/session/views/kernel.js +30 -0
  42. package/dist/session/views/read.js +5 -10
  43. package/dist/session/views/view.js +1 -6
  44. package/dist/store/memory.d.ts +1 -3
  45. package/dist/store/memory.js +61 -112
  46. package/dist/store/shape.d.ts +33 -12
  47. package/dist/store/shape.js +125 -16
  48. package/dist/store/store.js +1 -1
  49. package/dist/transport/auto/decision.d.ts +26 -14
  50. package/dist/transport/auto/decision.js +35 -32
  51. package/dist/transport/auto/fallback.d.ts +1 -1
  52. package/dist/transport/auto/fallback.js +5 -10
  53. package/dist/transport/auto/transport.d.ts +0 -2
  54. package/dist/transport/auto/transport.js +24 -32
  55. package/dist/transport/failure.d.ts +28 -1
  56. package/dist/transport/failure.js +57 -1
  57. package/dist/transport/http/admission.js +2 -2
  58. package/dist/transport/http/binary.js +1 -1
  59. package/dist/transport/http/byte-stream.d.ts +2 -1
  60. package/dist/transport/http/byte-stream.js +10 -7
  61. package/dist/transport/http/stream.d.ts +8 -13
  62. package/dist/transport/http/stream.js +32 -79
  63. package/dist/transport/http/transport.js +11 -22
  64. package/dist/transport/stream.d.ts +52 -0
  65. package/dist/transport/stream.js +101 -0
  66. package/dist/transport/unary.d.ts +3 -2
  67. package/dist/transport/unary.js +3 -3
  68. package/dist/transport/websocket/connection.d.ts +7 -3
  69. package/dist/transport/websocket/connection.js +102 -85
  70. package/dist/transport/websocket/exchange.d.ts +10 -19
  71. package/dist/transport/websocket/exchange.js +72 -153
  72. package/dist/transport/websocket/transport.js +11 -19
  73. package/package.json +6 -5
@@ -1,48 +1,51 @@
1
+ const UNDECIDED = Object.freeze({ kind: 'undecided' });
2
+ const CLOSED = Object.freeze({ kind: 'closed' });
1
3
  /** Serializes the one initial transport decision without retaining invocation values. */
2
4
  export class AutoDecision {
3
- selected;
4
- pending;
5
- closed = false;
5
+ state = UNDECIDED;
6
+ get closed() {
7
+ return this.state.kind === 'closed';
8
+ }
9
+ /** Claim the probe when undecided; otherwise report the state to follow. */
6
10
  begin() {
7
- if (this.closed)
8
- return { kind: 'wait', selection: Promise.resolve(undefined) };
9
- if (this.selected)
10
- return { kind: 'selected', selection: this.selected };
11
- if (this.pending)
12
- return { kind: 'wait', selection: this.pending.promise };
13
- let resolve;
14
- const promise = new Promise((settle) => {
15
- resolve = settle;
11
+ if (this.state.kind !== 'undecided')
12
+ return this.state;
13
+ let settle;
14
+ const settled = new Promise((resolve) => {
15
+ settle = resolve;
16
16
  });
17
- this.pending = { promise, resolve };
17
+ this.state = { kind: 'probing', settled, settle };
18
18
  return { kind: 'probe' };
19
19
  }
20
- select(selection) {
21
- if (this.closed || this.selected)
22
- return;
23
- this.selected = selection;
24
- this.pending?.resolve(selection);
25
- this.pending = undefined;
20
+ /** The probe proved WebSocket usable. */
21
+ selectWebSocket() {
22
+ if (this.state.kind === 'probing')
23
+ this.move({ kind: 'chosen', via: 'websocket' });
26
24
  }
27
25
  /** Permanently degrade a prior or pending WebSocket selection to HTTP. */
28
26
  demote() {
29
- if (this.closed || this.selected === 'http')
27
+ if (this.state.kind === 'closed')
28
+ return;
29
+ if (this.state.kind === 'chosen' && this.state.via === 'http')
30
30
  return;
31
- this.selected = 'http';
32
- this.pending?.resolve('http');
33
- this.pending = undefined;
31
+ this.move({ kind: 'chosen', via: 'http' });
34
32
  }
33
+ /** The probe proved nothing; the next caller probes again. */
35
34
  release() {
36
- if (this.closed || this.selected)
37
- return;
38
- this.pending?.resolve(undefined);
39
- this.pending = undefined;
35
+ if (this.state.kind === 'probing')
36
+ this.move(UNDECIDED);
40
37
  }
38
+ /** Returns whether this call closed the decision. */
41
39
  close() {
42
- if (this.closed)
43
- return;
44
- this.closed = true;
45
- this.pending?.resolve(undefined);
46
- this.pending = undefined;
40
+ if (this.state.kind === 'closed')
41
+ return false;
42
+ this.move(CLOSED);
43
+ return true;
44
+ }
45
+ move(next) {
46
+ const previous = this.state;
47
+ this.state = next;
48
+ if (previous.kind === 'probing')
49
+ previous.settle(next);
47
50
  }
48
51
  }
@@ -10,7 +10,7 @@ export declare class InvocationBudget {
10
10
  options(): RequestOptions;
11
11
  get cancelled(): boolean;
12
12
  get idempotency(): 'supplied' | 'absent';
13
- wait(decision: Promise<'websocket' | 'http' | undefined>): Promise<'websocket' | 'http' | undefined>;
13
+ wait<T>(decision: Promise<T>): Promise<T>;
14
14
  private remaining;
15
15
  }
16
16
  export declare function mayFallback(error: unknown): error is TransportError;
@@ -1,6 +1,6 @@
1
1
  import { targetPath } from '@astrale-os/kernel-core/callable';
2
2
  import { TransportError } from '../../errors/index.js';
3
- import { invocationFailure } from '../failure.js';
3
+ import { abortError, timeoutFailure } from '../failure.js';
4
4
  import { positiveInteger } from '../index.js';
5
5
  const MAXIMUM_TIMEOUT_MS = 2_147_483_647;
6
6
  /** One invocation-owned total timeout budget shared by selection and fallback. */
@@ -30,14 +30,14 @@ export class InvocationBudget {
30
30
  }
31
31
  async wait(decision) {
32
32
  if (this.input?.signal?.aborted)
33
- throw abortReason(this.input.signal);
33
+ throw abortError(this.input.signal.reason, new Error('request was cancelled'));
34
34
  const remaining = this.remaining();
35
35
  let timer;
36
36
  let abort;
37
37
  const interrupted = new Promise((_resolve, reject) => {
38
- timer = setTimeout(() => reject(invocationFailure('Automatic transport decision exceeded its timeout.', 'timeout')), remaining);
38
+ timer = setTimeout(() => reject(timeoutFailure('Automatic transport decision exceeded its timeout.')), remaining);
39
39
  if (this.input?.signal) {
40
- abort = () => reject(abortReason(this.input.signal));
40
+ abort = () => reject(abortError(this.input.signal.reason, new Error('request was cancelled')));
41
41
  this.input.signal.addEventListener('abort', abort, { once: true });
42
42
  }
43
43
  });
@@ -54,7 +54,7 @@ export class InvocationBudget {
54
54
  remaining() {
55
55
  const remaining = Math.min(MAXIMUM_TIMEOUT_MS, this.timeoutMs - (Date.now() - this.started));
56
56
  if (remaining < 1) {
57
- throw invocationFailure('Automatic transport invocation exceeded its timeout.', 'timeout');
57
+ throw timeoutFailure('Automatic transport invocation exceeded its timeout.');
58
58
  }
59
59
  return remaining;
60
60
  }
@@ -69,8 +69,3 @@ export function mayFallback(error) {
69
69
  export function warningTarget(input) {
70
70
  return targetPath(input.call.target);
71
71
  }
72
- function abortReason(signal) {
73
- return signal.reason instanceof Error
74
- ? signal.reason
75
- : new Error(signal.reason === undefined ? 'request was cancelled' : String(signal.reason));
76
- }
@@ -25,12 +25,10 @@ export declare class AutoTransport implements Transport {
25
25
  private readonly decision;
26
26
  private readonly timeoutMs;
27
27
  private readonly onWarning;
28
- private closed;
29
28
  constructor(options: AutoTransportOptions);
30
29
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
31
30
  private dispatchWithBudget;
32
31
  close(): void;
33
- private determine;
34
32
  private tryWebsocket;
35
33
  private requireOpen;
36
34
  }
@@ -14,7 +14,6 @@ export class AutoTransport {
14
14
  decision = new AutoDecision();
15
15
  timeoutMs;
16
16
  onWarning;
17
- closed = false;
18
17
  constructor(options) {
19
18
  if (options === null || typeof options !== 'object') {
20
19
  throw new TypeError('AutoTransport options must be an object.');
@@ -63,44 +62,37 @@ export class AutoTransport {
63
62
  return this.dispatchWithBudget(input, budget);
64
63
  }
65
64
  async dispatchWithBudget(input, budget) {
66
- const ticket = this.decision.begin();
67
- if (ticket.kind === 'selected') {
68
- return ticket.selection === 'websocket'
69
- ? this.tryWebsocket(input, budget, false)
70
- : this.http.dispatch(input, budget.options());
71
- }
72
- if (ticket.kind === 'wait') {
73
- const selection = await budget.wait(ticket.selection);
65
+ let ticket = this.decision.begin();
66
+ while (ticket.kind === 'probing') {
67
+ const settled = await budget.wait(ticket.settled);
74
68
  this.requireOpen();
75
- if (!selection)
76
- return this.dispatchWithBudget(input, budget);
77
- return selection === 'websocket'
78
- ? this.tryWebsocket(input, budget, false)
79
- : this.http.dispatch(input, budget.options());
69
+ ticket = settled.kind === 'undecided' ? this.decision.begin() : settled;
70
+ }
71
+ switch (ticket.kind) {
72
+ case 'closed':
73
+ throw closedFailure();
74
+ case 'probe':
75
+ return this.tryWebsocket(input, budget);
76
+ case 'chosen':
77
+ return ticket.via === 'websocket'
78
+ ? this.tryWebsocket(input, budget)
79
+ : this.http.dispatch(input, budget.options());
80
80
  }
81
- return this.determine(input, budget);
82
81
  }
83
82
  close() {
84
- if (this.closed)
83
+ if (!this.decision.close())
85
84
  return;
86
- this.closed = true;
87
- this.decision.close();
88
85
  this.websocket.close();
89
86
  }
90
- async determine(input, budget) {
91
- return this.tryWebsocket(input, budget, true);
92
- }
93
- async tryWebsocket(input, budget, probing) {
87
+ async tryWebsocket(input, budget) {
94
88
  try {
95
89
  const result = await this.websocket.dispatch(input, budget.options());
96
- if (probing)
97
- this.decision.select('websocket');
90
+ this.decision.selectWebSocket();
98
91
  return result;
99
92
  }
100
93
  catch (error) {
101
94
  if (budget.cancelled) {
102
- if (probing)
103
- this.decision.release();
95
+ this.decision.release();
104
96
  throw error;
105
97
  }
106
98
  if (error instanceof TransportError &&
@@ -110,9 +102,7 @@ export class AutoTransport {
110
102
  throw error;
111
103
  }
112
104
  if (!mayFallback(error)) {
113
- if (probing) {
114
- this.decision.select('websocket');
115
- }
105
+ this.decision.selectWebSocket();
116
106
  throw error;
117
107
  }
118
108
  const idempotency = budget.idempotency;
@@ -131,8 +121,10 @@ export class AutoTransport {
131
121
  }
132
122
  }
133
123
  requireOpen() {
134
- if (!this.closed)
135
- return;
136
- throw invocationFailure('AutoTransport is closed.', 'closed');
124
+ if (this.decision.closed)
125
+ throw closedFailure();
137
126
  }
138
127
  }
128
+ function closedFailure() {
129
+ return invocationFailure('AutoTransport is closed.', 'closed');
130
+ }
@@ -1,7 +1,34 @@
1
- import { TransportError, type InvocationTransportErrorOptions } from '../errors/index.js';
1
+ import type * as protocol from '@astrale-os/kernel-protocol/invocation';
2
+ import type { ControlledSignal } from './deadline.js';
3
+ import { ProtocolError, TransportError, type InvocationTransportErrorOptions } from '../errors/index.js';
2
4
  type InvocationFailureEvidence = Omit<InvocationTransportErrorOptions, 'delivery' | 'phase'> & {
3
5
  readonly delivery?: InvocationTransportErrorOptions['delivery'];
4
6
  };
7
+ /** Where a request stood when it stopped, and what its binding calls a failure there. */
8
+ export interface RequestStop {
9
+ readonly phase: 'connect' | 'send' | 'receive';
10
+ readonly delivery: InvocationTransportErrorOptions['delivery'];
11
+ /** The message of the failure the request's deadline is. */
12
+ readonly timeout: string;
13
+ /** The message of a failure to communicate. */
14
+ readonly failure: string;
15
+ }
5
16
  /** Create invocation transport evidence with the common not-sent default. */
6
17
  export declare function invocationFailure(message: string, phase: InvocationTransportErrorOptions['phase'], evidence?: InvocationFailureEvidence): TransportError;
18
+ /** The failure of an invocation its deadline ended. */
19
+ export declare function timeoutFailure(message: string, evidence?: InvocationFailureEvidence): TransportError;
20
+ /** The error a cancelled request fails with: its abort reason, or `otherwise` when it gave none. */
21
+ export declare function abortError(reason: unknown, otherwise: unknown): Error;
22
+ /**
23
+ * The error a request ends with when its control aborts: `timeout` when its deadline fired,
24
+ * otherwise its caller's abort reason, or `cancelled` when the abort gave none.
25
+ */
26
+ export declare function abortFailure(control: ControlledSignal, timeout: string, cancelled: string, evidence?: Omit<InvocationFailureEvidence, 'cause'>): Error;
27
+ /**
28
+ * The public error of a request that threw `input`: a Kernel answer or protocol breach as it is,
29
+ * then its deadline, then its caller's cancellation, then a transport failure where it stood.
30
+ */
31
+ export declare function requestFailure(input: unknown, control: ControlledSignal, stop: RequestStop): unknown;
32
+ /** `input` naming `invocation`, when it is a protocol or invocation failure that names none. */
33
+ export declare function withInvocation<T>(input: T, invocation: protocol.InvocationId | undefined): T | ProtocolError | TransportError;
7
34
  export {};
@@ -1,4 +1,5 @@
1
- import { TransportError } from '../errors/index.js';
1
+ import { ProtocolError, ResponseError, TransportError, } from '../errors/index.js';
2
+ import { asError } from './deadline.js';
2
3
  /** Create invocation transport evidence with the common not-sent default. */
3
4
  export function invocationFailure(message, phase, evidence = {}) {
4
5
  return TransportError.invocation(message, {
@@ -7,3 +8,58 @@ export function invocationFailure(message, phase, evidence = {}) {
7
8
  delivery: evidence.delivery ?? 'not-sent',
8
9
  });
9
10
  }
11
+ /** The failure of an invocation its deadline ended. */
12
+ export function timeoutFailure(message, evidence = {}) {
13
+ return invocationFailure(message, 'timeout', evidence);
14
+ }
15
+ /** The error a cancelled request fails with: its abort reason, or `otherwise` when it gave none. */
16
+ export function abortError(reason, otherwise) {
17
+ return asError(reason ?? otherwise);
18
+ }
19
+ /**
20
+ * The error a request ends with when its control aborts: `timeout` when its deadline fired,
21
+ * otherwise its caller's abort reason, or `cancelled` when the abort gave none.
22
+ */
23
+ export function abortFailure(control, timeout, cancelled, evidence = {}) {
24
+ const reason = control.signal.reason;
25
+ if (control.timedOut)
26
+ return timeoutFailure(timeout, { ...evidence, cause: asError(reason) });
27
+ return abortError(reason, new Error(cancelled));
28
+ }
29
+ /**
30
+ * The public error of a request that threw `input`: a Kernel answer or protocol breach as it is,
31
+ * then its deadline, then its caller's cancellation, then a transport failure where it stood.
32
+ */
33
+ export function requestFailure(input, control, stop) {
34
+ if (input instanceof ResponseError || input instanceof ProtocolError)
35
+ return input;
36
+ if (control.timedOut) {
37
+ return timeoutFailure(stop.timeout, { cause: asError(input), delivery: stop.delivery });
38
+ }
39
+ if (control.signal.aborted)
40
+ return abortError(control.signal.reason, input);
41
+ if (input instanceof TransportError)
42
+ return input;
43
+ return invocationFailure(stop.failure, stop.phase, {
44
+ cause: asError(input),
45
+ delivery: stop.delivery,
46
+ });
47
+ }
48
+ /** `input` naming `invocation`, when it is a protocol or invocation failure that names none. */
49
+ export function withInvocation(input, invocation) {
50
+ if (invocation === undefined)
51
+ return input;
52
+ if (input instanceof ProtocolError && input.invocation === undefined) {
53
+ return new ProtocolError(input.message, { cause: input, invocation });
54
+ }
55
+ if (input instanceof TransportError &&
56
+ input.context.kind === 'invocation' &&
57
+ input.context.invocation === undefined) {
58
+ return invocationFailure(input.message, input.phase, {
59
+ cause: input,
60
+ delivery: input.context.delivery,
61
+ invocation,
62
+ });
63
+ }
64
+ return input;
65
+ }
@@ -65,10 +65,10 @@ export async function admitResponse(response, requestId, context) {
65
65
  const decoded = decodeProtocol('response body', () => responseCodec.decode(body));
66
66
  const envelope = decodeProtocol('response envelope', () => protocol.decodeResponse(decoded));
67
67
  if (envelope.requestId === null && 'error' in envelope)
68
- throw responseError(envelope);
68
+ throw responseError(envelope.error, envelope.invocation);
69
69
  requireId(requestId, envelope.requestId);
70
70
  if ('error' in envelope)
71
- throw responseError(envelope);
71
+ throw responseError(envelope.error, envelope.invocation);
72
72
  requireLive(control);
73
73
  return unaryResult(envelope);
74
74
  }
@@ -36,7 +36,7 @@ export async function decodeBinary(response, requestId, binaryId, streaming, con
36
36
  kind: 'binary',
37
37
  invocation,
38
38
  value: {
39
- body: new HttpByteStream(response.body, maximumBytes, control, expectedBytes),
39
+ body: new HttpByteStream(response.body, maximumBytes, control, invocation, expectedBytes),
40
40
  // The byte stream enforces this exact count through its final read.
41
41
  ...(expectedBytes === undefined ? {} : { length: expectedBytes }),
42
42
  mediaType,
@@ -1,3 +1,4 @@
1
+ import type * as protocol from '@astrale-os/kernel-protocol/invocation';
1
2
  import type { ControlledSignal } from '../index.js';
2
3
  /** Single-consumer HTTP byte stream preserving invocation lifetime and backpressure. */
3
4
  export declare class HttpByteStream implements AsyncIterable<Uint8Array> {
@@ -9,7 +10,7 @@ export declare class HttpByteStream implements AsyncIterable<Uint8Array> {
9
10
  private terminal;
10
11
  private bytes;
11
12
  private interruption;
12
- constructor(body: ReadableStream<Uint8Array>, maximumBytes: number, control: ControlledSignal, expectedBytes?: number | undefined);
13
+ constructor(body: ReadableStream<Uint8Array>, maximumBytes: number, control: ControlledSignal, invocation: protocol.InvocationId, expectedBytes?: number | undefined);
13
14
  [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
14
15
  cancel(reason?: unknown): Promise<void>;
15
16
  private next;
@@ -1,5 +1,5 @@
1
1
  import { ProtocolError } from '../../errors/index.js';
2
- import { asError } from '../index.js';
2
+ import { abortFailure } from '../failure.js';
3
3
  /** Single-consumer HTTP byte stream preserving invocation lifetime and backpressure. */
4
4
  export class HttpByteStream {
5
5
  maximumBytes;
@@ -10,12 +10,12 @@ export class HttpByteStream {
10
10
  terminal = false;
11
11
  bytes = 0;
12
12
  interruption;
13
- constructor(body, maximumBytes, control, expectedBytes) {
13
+ constructor(body, maximumBytes, control, invocation, expectedBytes) {
14
14
  this.maximumBytes = maximumBytes;
15
15
  this.control = control;
16
16
  this.expectedBytes = expectedBytes;
17
17
  this.reader = body.getReader();
18
- const abort = () => void this.interrupt(control.signal.reason);
18
+ const abort = () => void this.interrupt(abortFailure(control, 'streaming binary exceeded its invocation timeout.', 'streaming binary was cancelled.', { delivery: 'unknown', invocation }));
19
19
  if (control.signal.aborted)
20
20
  abort();
21
21
  else
@@ -72,14 +72,17 @@ export class HttpByteStream {
72
72
  return { done: false, value: new Uint8Array(next.value) };
73
73
  }
74
74
  catch (error) {
75
- await this.cancel(error);
76
- throw error;
75
+ // A Fetch body errors a pending read with its signal's raw reason; the interruption is the
76
+ // public failure that abort maps to.
77
+ const failure = this.interruption ?? error;
78
+ await this.cancel(failure);
79
+ throw failure;
77
80
  }
78
81
  }
79
- async interrupt(reason) {
82
+ async interrupt(failure) {
80
83
  if (this.terminal || this.interruption !== undefined)
81
84
  return;
82
- this.interruption = asError(reason ?? new Error('streaming binary was cancelled.'));
85
+ this.interruption = failure;
83
86
  await this.cancelReader(this.interruption);
84
87
  this.control.close();
85
88
  }
@@ -1,26 +1,21 @@
1
- import type { Value } from '@astrale-os/kernel-dsl/value';
2
1
  import type * as codecs from '@astrale-os/kernel-protocol/codecs';
3
2
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
4
- import type { Stream } from '../../client/index.js';
5
- import { type ControlledSignal } from '../index.js';
6
- export declare class HttpStream implements Stream {
3
+ import type { ControlledSignal } from '../index.js';
4
+ import { FrameStream } from '../stream.js';
5
+ /** The HTTP binding of one value stream: reads its length-prefixed frames as its consumer reads. */
6
+ export declare class HttpStream {
7
7
  private readonly frames;
8
8
  private readonly codec;
9
9
  private readonly requestId;
10
10
  private readonly control;
11
- invocation: protocol.InvocationId;
12
- private claimed;
13
- private terminal;
14
- private index;
11
+ private invocation;
12
+ private released;
15
13
  private interruption;
16
14
  private constructor();
17
- static open(response: Response, codec: codecs.Codec, requestId: protocol.RequestId, maximumFrameBytes: number, control: ControlledSignal): Promise<HttpStream>;
18
- [Symbol.asyncIterator](): AsyncIterator<Value>;
19
- cancel(reason?: string): Promise<void>;
20
- private next;
15
+ static open(response: Response, codec: codecs.Codec, requestId: protocol.RequestId, maximumFrameBytes: number, control: ControlledSignal): Promise<FrameStream>;
16
+ private read;
21
17
  private readFrame;
22
18
  private finish;
23
19
  private interrupt;
24
20
  private stop;
25
- private abortFailure;
26
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';
2
+ import { ProtocolError } from '../../errors/index.js';
3
+ import { abortFailure, withInvocation } from '../failure.js';
4
+ import { FrameStream } from '../stream.js';
5
5
  import { decodeProtocol, requireId } 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;