@astrale-os/kernel-client 1.0.0-beta.4 → 1.0.0-beta.40

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 (194) hide show
  1. package/dist/auth/index.d.ts +1 -0
  2. package/dist/client/admission.js +3 -1
  3. package/dist/client/client.d.ts +19 -2
  4. package/dist/client/client.js +62 -30
  5. package/dist/client/index.d.ts +3 -3
  6. package/dist/client/index.js +2 -2
  7. package/dist/client/request.d.ts +8 -2
  8. package/dist/client/request.js +28 -7
  9. package/dist/client/result.d.ts +10 -1
  10. package/dist/client/result.js +10 -4
  11. package/dist/client/routing-control.d.ts +11 -15
  12. package/dist/client/routing-control.js +21 -29
  13. package/dist/errors/index.d.ts +3 -0
  14. package/dist/errors/index.js +3 -0
  15. package/dist/errors/query-input.d.ts +47 -0
  16. package/dist/errors/query-input.js +85 -0
  17. package/dist/errors/refusal.d.ts +24 -0
  18. package/dist/errors/refusal.js +78 -0
  19. package/dist/errors/response-too-large-error.d.ts +11 -0
  20. package/dist/errors/response-too-large-error.js +15 -0
  21. package/dist/errors/stale-route-error.d.ts +1 -1
  22. package/dist/errors/stale-route-error.js +1 -1
  23. package/dist/{schema → execution}/admission.d.ts +2 -2
  24. package/dist/{schema → execution}/admission.js +3 -3
  25. package/dist/execution/contracts.d.ts +76 -0
  26. package/dist/execution/contracts.js +1 -0
  27. package/dist/execution/deadline.d.ts +18 -0
  28. package/dist/execution/deadline.js +25 -0
  29. package/dist/execution/execution.d.ts +61 -0
  30. package/dist/execution/execution.js +132 -0
  31. package/dist/execution/index.d.ts +4 -0
  32. package/dist/execution/index.js +3 -0
  33. package/dist/graph/domain/binding.d.ts +2 -2
  34. package/dist/graph/domain/binding.js +24 -17
  35. package/dist/graph/domain/conformance.d.ts +12 -0
  36. package/dist/graph/domain/conformance.js +18 -0
  37. package/dist/graph/domain/index.d.ts +1 -0
  38. package/dist/graph/domain/index.js +1 -1
  39. package/dist/graph/domain/provenance.d.ts +0 -2
  40. package/dist/graph/domain/provenance.js +0 -4
  41. package/dist/graph/graph.d.ts +17 -3
  42. package/dist/graph/graph.js +4 -1
  43. package/dist/graph/index.d.ts +3 -3
  44. package/dist/graph/index.js +1 -1
  45. package/dist/graph/page-contract.d.ts +66 -1
  46. package/dist/graph/provenance.d.ts +4 -5
  47. package/dist/graph/provenance.js +5 -6
  48. package/dist/graph/query.d.ts +10 -4
  49. package/dist/graph/query.js +149 -7
  50. package/dist/graph/query.typecheck.d.ts +79 -0
  51. package/dist/graph/query.typecheck.js +34 -0
  52. package/dist/pacer/index.d.ts +1 -1
  53. package/dist/pacer/index.js +1 -1
  54. package/dist/pacer/retry/index.d.ts +1 -0
  55. package/dist/pacer/retry/index.js +1 -0
  56. package/dist/pacer/retry/refusals.d.ts +7 -0
  57. package/dist/pacer/retry/refusals.js +10 -0
  58. package/dist/pacer/retry/retry.d.ts +2 -0
  59. package/dist/pacer/retry/retry.js +33 -1
  60. package/dist/schema/contracts.d.ts +77 -9
  61. package/dist/schema/index.d.ts +3 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +76 -0
  64. package/dist/schema/installation.js +82 -0
  65. package/dist/schema/schema.d.ts +22 -13
  66. package/dist/schema/schema.js +67 -48
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +66 -20
  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 +1 -1
  80. package/dist/session/context/index.js +1 -1
  81. package/dist/session/context/operation.d.ts +2 -0
  82. package/dist/session/context/operation.js +5 -0
  83. package/dist/session/credential/credentials.js +43 -28
  84. package/dist/session/discovery/bundle.d.ts +9 -4
  85. package/dist/session/discovery/bundle.js +28 -35
  86. package/dist/session/discovery/discovery.d.ts +1 -1
  87. package/dist/session/discovery/discovery.js +8 -11
  88. package/dist/session/discovery/release.js +18 -28
  89. package/dist/session/discovery/snapshot.d.ts +5 -1
  90. package/dist/session/discovery/transport.d.ts +35 -3
  91. package/dist/session/discovery/transport.js +40 -1
  92. package/dist/session/durable.d.ts +13 -0
  93. package/dist/session/durable.js +39 -0
  94. package/dist/session/exchange/exchange.d.ts +3 -2
  95. package/dist/session/exchange/exchange.js +10 -7
  96. package/dist/session/exchange/index.d.ts +1 -1
  97. package/dist/session/exchange/index.js +1 -1
  98. package/dist/session/exchange/presentation.js +28 -10
  99. package/dist/session/exchange/source.d.ts +7 -7
  100. package/dist/session/exchange/source.js +26 -27
  101. package/dist/session/index.d.ts +5 -4
  102. package/dist/session/index.js +0 -1
  103. package/dist/session/options.d.ts +0 -2
  104. package/dist/session/options.js +0 -3
  105. package/dist/session/reference.d.ts +27 -6
  106. package/dist/session/reference.js +18 -3
  107. package/dist/session/retry.d.ts +12 -0
  108. package/dist/session/retry.js +23 -0
  109. package/dist/session/routing/auth.d.ts +9 -3
  110. package/dist/session/routing/auth.js +4 -3
  111. package/dist/session/routing/cache.d.ts +12 -5
  112. package/dist/session/routing/cache.js +56 -48
  113. package/dist/session/routing/dispatch.d.ts +26 -3
  114. package/dist/session/routing/dispatch.js +112 -67
  115. package/dist/session/routing/envelope.d.ts +3 -3
  116. package/dist/session/routing/index.d.ts +1 -1
  117. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  118. package/dist/session/routing/legacy/release-route.js +6 -0
  119. package/dist/session/routing/recovery.d.ts +3 -6
  120. package/dist/session/routing/recovery.js +3 -14
  121. package/dist/session/routing/request.d.ts +6 -1
  122. package/dist/session/routing/request.js +13 -2
  123. package/dist/session/routing/result.d.ts +1 -1
  124. package/dist/session/routing/result.js +5 -1
  125. package/dist/session/routing/store.js +4 -5
  126. package/dist/session/session.d.ts +31 -5
  127. package/dist/session/session.js +67 -20
  128. package/dist/session/session.typecheck.js +20 -6
  129. package/dist/session/views/index.d.ts +2 -2
  130. package/dist/session/views/index.js +2 -2
  131. package/dist/session/views/kernel.d.ts +31 -0
  132. package/dist/session/views/kernel.js +30 -0
  133. package/dist/session/views/legacy/catalog.d.ts +21 -0
  134. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  135. package/dist/session/views/legacy/index.d.ts +14 -0
  136. package/dist/session/views/legacy/index.js +14 -0
  137. package/dist/session/views/legacy/resolve.d.ts +46 -0
  138. package/dist/session/views/legacy/resolve.js +83 -0
  139. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  140. package/dist/session/views/legacy/unplaced.js +26 -0
  141. package/dist/session/views/read.d.ts +49 -0
  142. package/dist/session/views/read.js +148 -0
  143. package/dist/session/views/view.d.ts +48 -0
  144. package/dist/session/views/view.js +74 -0
  145. package/dist/store/memory.d.ts +1 -3
  146. package/dist/store/memory.js +73 -105
  147. package/dist/store/shape.d.ts +33 -12
  148. package/dist/store/shape.js +125 -16
  149. package/dist/store/store.d.ts +6 -6
  150. package/dist/store/store.js +1 -1
  151. package/dist/transport/auto/decision.d.ts +26 -14
  152. package/dist/transport/auto/decision.js +35 -32
  153. package/dist/transport/auto/fallback.d.ts +1 -1
  154. package/dist/transport/auto/fallback.js +5 -10
  155. package/dist/transport/auto/transport.d.ts +0 -2
  156. package/dist/transport/auto/transport.js +24 -32
  157. package/dist/transport/deadline.d.ts +2 -0
  158. package/dist/transport/deadline.js +18 -0
  159. package/dist/transport/failure.d.ts +28 -1
  160. package/dist/transport/failure.js +63 -1
  161. package/dist/transport/http/admission.js +7 -34
  162. package/dist/transport/http/binary-request.d.ts +44 -0
  163. package/dist/transport/http/binary-request.js +110 -0
  164. package/dist/transport/http/binary.js +3 -3
  165. package/dist/transport/http/byte-stream.d.ts +2 -1
  166. package/dist/transport/http/byte-stream.js +12 -8
  167. package/dist/transport/http/index.d.ts +1 -1
  168. package/dist/transport/http/index.js +1 -1
  169. package/dist/transport/http/response.d.ts +3 -1
  170. package/dist/transport/http/response.js +7 -9
  171. package/dist/transport/http/stream.d.ts +8 -13
  172. package/dist/transport/http/stream.js +34 -81
  173. package/dist/transport/http/transport.d.ts +10 -0
  174. package/dist/transport/http/transport.js +87 -32
  175. package/dist/transport/http/unprocessed.d.ts +5 -0
  176. package/dist/transport/http/unprocessed.js +28 -0
  177. package/dist/transport/index.d.ts +1 -1
  178. package/dist/transport/index.js +1 -1
  179. package/dist/transport/stream.d.ts +52 -0
  180. package/dist/transport/stream.js +101 -0
  181. package/dist/transport/transport.d.ts +10 -0
  182. package/dist/transport/unary.d.ts +8 -0
  183. package/dist/transport/unary.js +34 -0
  184. package/dist/transport/websocket/connection.d.ts +7 -3
  185. package/dist/transport/websocket/connection.js +103 -92
  186. package/dist/transport/websocket/exchange.d.ts +12 -19
  187. package/dist/transport/websocket/exchange.js +86 -184
  188. package/dist/transport/websocket/transport.js +11 -19
  189. package/package.json +9 -7
  190. package/dist/session/execution.d.ts +0 -65
  191. package/dist/session/execution.js +0 -34
  192. package/dist/session/views/catalog.d.ts +0 -19
  193. package/dist/session/views/resolve.d.ts +0 -13
  194. package/dist/session/views/resolve.js +0 -21
@@ -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
+ }
@@ -4,6 +4,8 @@ export interface ControlledSignal {
4
4
  cancel(reason?: unknown): void;
5
5
  close(): void;
6
6
  }
7
+ /** Wait `ms`, or until `signal` aborts, which rejects with its reason. */
8
+ export declare function pause(ms: number, signal?: AbortSignal): Promise<void>;
7
9
  /** One caller signal plus one transport-owned lifetime deadline. */
8
10
  export declare function controlledSignal(parent: AbortSignal | undefined, timeoutMs: number): ControlledSignal;
9
11
  export declare function positiveInteger(input: number, label: string): number;
@@ -1,3 +1,21 @@
1
+ /** Wait `ms`, or until `signal` aborts, which rejects with its reason. */
2
+ export function pause(ms, signal) {
3
+ return new Promise((resolve, reject) => {
4
+ if (signal?.aborted) {
5
+ reject(signal.reason);
6
+ return;
7
+ }
8
+ const abort = () => {
9
+ clearTimeout(timer);
10
+ reject(signal.reason);
11
+ };
12
+ const timer = setTimeout(() => {
13
+ signal?.removeEventListener('abort', abort);
14
+ resolve();
15
+ }, ms);
16
+ signal?.addEventListener('abort', abort, { once: true });
17
+ });
18
+ }
1
19
  /** One caller signal plus one transport-owned lifetime deadline. */
2
20
  export function controlledSignal(parent, timeoutMs) {
3
21
  const controller = new AbortController();
@@ -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, ResponseTooLargeError, 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,64 @@ 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 ResponseTooLargeError && input.invocation === undefined) {
53
+ return new ResponseTooLargeError(input.message, input.maximumResponseBytes, {
54
+ cause: input,
55
+ invocation,
56
+ });
57
+ }
58
+ if (input instanceof ProtocolError && input.invocation === undefined) {
59
+ return new ProtocolError(input.message, { cause: input, invocation });
60
+ }
61
+ if (input instanceof TransportError &&
62
+ input.context.kind === 'invocation' &&
63
+ input.context.invocation === undefined) {
64
+ return invocationFailure(input.message, input.phase, {
65
+ cause: input,
66
+ delivery: input.context.delivery,
67
+ invocation,
68
+ });
69
+ }
70
+ return input;
71
+ }
@@ -1,8 +1,9 @@
1
1
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
2
2
  import * as retirement from '@astrale-os/kernel-protocol/routes';
3
- import { ProtocolError, ResponseError } from '../../errors/index.js';
3
+ import { ProtocolError } from '../../errors/index.js';
4
4
  import { invocationFailure } from '../failure.js';
5
5
  import { requireLive } from '../index.js';
6
+ import { responseError, unaryResult } from '../unary.js';
6
7
  import { decodeBinary } from './binary.js';
7
8
  import { codecForResponse, decodeProtocol, readBoundedBody, requireId, requireNoStore, } from './response.js';
8
9
  import { decodeDeploymentRetired } from './retired.js';
@@ -63,39 +64,11 @@ export async function admitResponse(response, requestId, context) {
63
64
  requireLive(control);
64
65
  const decoded = decodeProtocol('response body', () => responseCodec.decode(body));
65
66
  const envelope = decodeProtocol('response envelope', () => protocol.decodeResponse(decoded));
66
- if (envelope.requestId === null && 'error' in envelope) {
67
- throw new ResponseError(envelope.error.code, envelope.error.message, envelope.invocation, envelope.error.data);
68
- }
67
+ if (envelope.requestId === null && 'error' in envelope)
68
+ throw responseError(envelope.error, envelope.invocation);
69
69
  requireId(requestId, envelope.requestId);
70
- if ('kind' in envelope && envelope.kind === 'stale') {
71
- const stale = decodeProtocol('stale response', () => protocol.decodeStale(envelope));
72
- requireLive(control);
73
- return Object.freeze({
74
- kind: 'stale',
75
- current: stale.current,
76
- invocation: stale.invocation,
77
- });
78
- }
79
- if ('kind' in envelope && envelope.kind === 'miss') {
80
- decodeProtocol('miss response', () => protocol.decodeMiss(envelope));
81
- requireLive(control);
82
- return Object.freeze({ kind: 'miss', invocation: envelope.invocation });
83
- }
84
- if ('kind' in envelope && envelope.kind === 'redirect') {
85
- const response = decodeProtocol('redirect response', () => protocol.decodeRedirectResponse(envelope));
86
- requireLive(control);
87
- return redirectResult(response);
88
- }
89
- if ('error' in envelope) {
90
- throw new ResponseError(envelope.error.code, envelope.error.message, envelope.invocation, envelope.error.data);
91
- }
70
+ if ('error' in envelope)
71
+ throw responseError(envelope.error, envelope.invocation);
92
72
  requireLive(control);
93
- return { kind: 'value', value: envelope.result, invocation: envelope.invocation };
94
- }
95
- function redirectResult(response) {
96
- return Object.freeze({
97
- kind: 'redirect',
98
- invocation: response.invocation,
99
- redirect: response.redirect,
100
- });
73
+ return unaryResult(envelope);
101
74
  }
@@ -0,0 +1,44 @@
1
+ import { ClientError } from '../../errors/index.js';
2
+ /**
3
+ * One admitted binary request body, whose kind says whether it can be sent again: a Blob is read
4
+ * anew by every send, a stream of exactly `length` bytes is consumed by the one send that reads it.
5
+ */
6
+ export type BinaryBody = {
7
+ readonly kind: 'replayable';
8
+ readonly body: Blob;
9
+ readonly length: number;
10
+ } | {
11
+ readonly kind: 'once';
12
+ readonly body: ReadableStream<Uint8Array>;
13
+ readonly length: number;
14
+ };
15
+ /** One send of a stream body: what Fetch reads, and the caller's stream failure it met. */
16
+ export interface StreamSend {
17
+ readonly kind: 'once';
18
+ readonly length: number;
19
+ /** Counted copy of the caller's stream, ending exactly after its declared length. */
20
+ readonly body: ReadableStream<Uint8Array>;
21
+ /** The failure of the caller's stream, or of its length, when one ended the send. */
22
+ readonly failure: () => ClientError | undefined;
23
+ /**
24
+ * Abort the request when the stream fails, before its copy errors: a Fetch may otherwise end the
25
+ * failed body as though it were complete (workerd does), and the server would answer it.
26
+ */
27
+ readonly abortOnFailure: (abort: () => void) => void;
28
+ /** Cancel the caller's stream unless it was read through its end. */
29
+ readonly release: (reason: unknown) => void;
30
+ }
31
+ /** A Blob body, which every send reads again. */
32
+ export declare function replayableBody(blob: Blob): BinaryBody;
33
+ /**
34
+ * Admit one binary body. A stream is snapshotted with its declared length and must be unread: the
35
+ * request that sends it consumes it, and nothing can send it again. A stream is recognized by its
36
+ * reader, so one from another realm or a polyfill is accepted too.
37
+ */
38
+ export declare function acceptBinaryBody(input: unknown): BinaryBody;
39
+ /** Cancel a stream body that no request has started to read; a Blob needs nothing. */
40
+ export declare function cancelUnsent(body: BinaryBody | undefined): void;
41
+ /** Send a stream once: count its bytes and fail it when they differ from its declared length. */
42
+ export declare function sendStream(source: Extract<BinaryBody, {
43
+ kind: 'once';
44
+ }>): StreamSend;
@@ -0,0 +1,110 @@
1
+ import { ClientError } from '../../errors/index.js';
2
+ /** A Blob body, which every send reads again. */
3
+ export function replayableBody(blob) {
4
+ return Object.freeze({ kind: 'replayable', body: blob, length: blob.size });
5
+ }
6
+ /**
7
+ * Admit one binary body. A stream is snapshotted with its declared length and must be unread: the
8
+ * request that sends it consumes it, and nothing can send it again. A stream is recognized by its
9
+ * reader, so one from another realm or a polyfill is accepted too.
10
+ */
11
+ export function acceptBinaryBody(input) {
12
+ if (typeof Blob !== 'undefined' && input instanceof Blob)
13
+ return replayableBody(input);
14
+ if (input !== null && typeof input === 'object' && !Array.isArray(input)) {
15
+ const { body, length } = input;
16
+ if (isReadableStream(body)) {
17
+ if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) {
18
+ throw new TypeError('Binary stream length must be a non-negative safe integer.');
19
+ }
20
+ if (body.locked)
21
+ throw new TypeError('Binary stream is already being read.');
22
+ return Object.freeze({ kind: 'once', body, length });
23
+ }
24
+ }
25
+ throw new TypeError('Binary input must be a Blob, File, or byte stream with its exact length.');
26
+ }
27
+ function isReadableStream(input) {
28
+ return (input !== null &&
29
+ typeof input === 'object' &&
30
+ typeof input.getReader === 'function');
31
+ }
32
+ /** Cancel a stream body that no request has started to read; a Blob needs nothing. */
33
+ export function cancelUnsent(body) {
34
+ if (body?.kind !== 'once' || body.body.locked)
35
+ return;
36
+ body.body
37
+ .cancel(new ClientError('Binary request ended before its stream was sent.'))
38
+ .catch(() => undefined);
39
+ }
40
+ /** Send a stream once: count its bytes and fail it when they differ from its declared length. */
41
+ export function sendStream(source) {
42
+ const reader = source.body.getReader();
43
+ let sent = 0;
44
+ let finished = false;
45
+ let failure;
46
+ let abort;
47
+ const release = (reason) => {
48
+ if (finished)
49
+ return;
50
+ finished = true;
51
+ reader.cancel(reason).then(() => reader.releaseLock(), () => reader.releaseLock());
52
+ };
53
+ const stop = (controller, cause) => {
54
+ failure ??= cause;
55
+ release(cause);
56
+ abort?.();
57
+ controller.error(cause);
58
+ };
59
+ const body = new ReadableStream({
60
+ async pull(controller) {
61
+ let next;
62
+ try {
63
+ next = await reader.read();
64
+ }
65
+ catch (cause) {
66
+ if (!finished) {
67
+ stop(controller, new ClientError(`Binary request stream failed after ${sent} of its ${source.length} declared bytes.`, { cause }));
68
+ }
69
+ return;
70
+ }
71
+ // Fetch cancelled the send while this read was pending.
72
+ if (finished)
73
+ return;
74
+ if (next.done) {
75
+ if (sent !== source.length) {
76
+ stop(controller, new ClientError(`Binary request stream ended after ${sent} bytes; expected ${source.length}.`));
77
+ return;
78
+ }
79
+ finished = true;
80
+ reader.releaseLock();
81
+ controller.close();
82
+ return;
83
+ }
84
+ const chunk = next.value;
85
+ if (!(chunk instanceof Uint8Array)) {
86
+ stop(controller, new ClientError('Binary request stream yielded a non-byte chunk.'));
87
+ return;
88
+ }
89
+ sent += chunk.byteLength;
90
+ if (sent > source.length) {
91
+ stop(controller, new ClientError(`Binary request stream exceeded its declared length of ${source.length} bytes.`));
92
+ return;
93
+ }
94
+ controller.enqueue(chunk);
95
+ },
96
+ cancel: release,
97
+ }, { highWaterMark: 0 });
98
+ return Object.freeze({
99
+ kind: 'once',
100
+ length: source.length,
101
+ body,
102
+ failure: () => failure,
103
+ abortOnFailure: (next) => {
104
+ abort = next;
105
+ if (failure !== undefined)
106
+ next();
107
+ },
108
+ release,
109
+ });
110
+ }
@@ -3,7 +3,7 @@ import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
3
  import { ProtocolError } from '../../errors/index.js';
4
4
  import { requireLive } from '../index.js';
5
5
  import { HttpByteStream } from './byte-stream.js';
6
- import { binaryHeaders, decodeProtocol, readBoundedBody } from './response.js';
6
+ import { binaryHeaders, decodeProtocol, readBoundedBody, tooLarge, } from './response.js';
7
7
  /** Admit buffered or streaming binary output within the invocation's lifetime. */
8
8
  export async function decodeBinary(response, requestId, binaryId, streaming, context) {
9
9
  const { control, maximumBytes } = context;
@@ -29,14 +29,14 @@ export async function decodeBinary(response, requestId, binaryId, streaming, con
29
29
  throw new ProtocolError(`streaming binary has an invalid ${protocol.http.BINARY_LENGTH_FIELD}.`);
30
30
  }
31
31
  if (expectedBytes !== undefined && expectedBytes > maximumBytes) {
32
- throw new ProtocolError(`streaming binary exceeds maximumResponseBytes (${maximumBytes}).`);
32
+ throw tooLarge('streaming binary', maximumBytes);
33
33
  }
34
34
  requireLive(control);
35
35
  return {
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;