@astrale-os/kernel-client 1.0.0-beta.22 → 1.0.0-beta.24

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 (60) hide show
  1. package/dist/client/client.d.ts +5 -4
  2. package/dist/client/client.js +7 -7
  3. package/dist/client/index.d.ts +1 -1
  4. package/dist/client/request.d.ts +5 -9
  5. package/dist/client/request.js +13 -16
  6. package/dist/errors/index.d.ts +1 -0
  7. package/dist/errors/index.js +1 -0
  8. package/dist/errors/query-input.d.ts +47 -0
  9. package/dist/errors/query-input.js +84 -0
  10. package/dist/execution/deadline.d.ts +10 -0
  11. package/dist/execution/deadline.js +12 -0
  12. package/dist/execution/execution.js +2 -7
  13. package/dist/execution/index.d.ts +1 -1
  14. package/dist/execution/index.js +1 -1
  15. package/dist/graph/domain/binding.d.ts +2 -2
  16. package/dist/graph/graph.d.ts +17 -3
  17. package/dist/graph/graph.js +4 -1
  18. package/dist/graph/index.d.ts +2 -2
  19. package/dist/graph/page-contract.d.ts +53 -1
  20. package/dist/graph/query.d.ts +10 -4
  21. package/dist/graph/query.js +125 -2
  22. package/dist/graph/query.typecheck.d.ts +77 -0
  23. package/dist/graph/query.typecheck.js +34 -0
  24. package/dist/schema/contracts.d.ts +21 -10
  25. package/dist/schema/index.d.ts +1 -1
  26. package/dist/schema/installation.d.ts +11 -1
  27. package/dist/schema/installation.js +45 -1
  28. package/dist/schema/schema.d.ts +4 -4
  29. package/dist/schema/schema.js +34 -24
  30. package/dist/session/bound.js +27 -31
  31. package/dist/session/content/api.js +2 -2
  32. package/dist/session/content/input.js +2 -2
  33. package/dist/session/content/retry.d.ts +2 -1
  34. package/dist/session/content/retry.js +13 -23
  35. package/dist/session/context/operation.js +2 -16
  36. package/dist/session/durable.js +13 -19
  37. package/dist/session/retry.d.ts +12 -0
  38. package/dist/session/retry.js +23 -0
  39. package/dist/session/routing/dispatch.d.ts +2 -2
  40. package/dist/session/routing/dispatch.js +12 -20
  41. package/dist/session/routing/request.d.ts +2 -1
  42. package/dist/session/routing/request.js +2 -1
  43. package/dist/store/store.d.ts +6 -6
  44. package/dist/transport/deadline.d.ts +2 -0
  45. package/dist/transport/deadline.js +18 -0
  46. package/dist/transport/http/admission.js +7 -42
  47. package/dist/transport/http/binary-request.d.ts +23 -9
  48. package/dist/transport/http/binary-request.js +12 -10
  49. package/dist/transport/http/response.d.ts +0 -1
  50. package/dist/transport/http/response.js +0 -6
  51. package/dist/transport/http/transport.d.ts +3 -2
  52. package/dist/transport/http/transport.js +16 -20
  53. package/dist/transport/index.d.ts +1 -1
  54. package/dist/transport/index.js +1 -1
  55. package/dist/transport/unary.d.ts +7 -0
  56. package/dist/transport/unary.js +34 -0
  57. package/dist/transport/websocket/connection.js +1 -7
  58. package/dist/transport/websocket/exchange.d.ts +2 -0
  59. package/dist/transport/websocket/exchange.js +13 -43
  60. package/package.json +5 -5
@@ -1,7 +1,7 @@
1
1
  import { NodeId } from '@astrale-os/kernel-core/graph/node';
2
2
  import { PropertyKey } from '@astrale-os/kernel-dsl/v1/addressing';
3
3
  import * as artifact from '@astrale-os/kernel-protocol/artifact';
4
- import { acceptBinaryBody } from '../../transport/http/binary-request.js';
4
+ import { acceptBinaryBody, replayableBody } from '../../transport/http/binary-request.js';
5
5
  import { admitControlOptions } from '../context/index.js';
6
6
  const CONTENT_TIMEOUT_MS = 30 * 60 * 1_000;
7
7
  export function acceptLocation(input) {
@@ -20,7 +20,7 @@ export function acceptBody(input) {
20
20
  const bytes = input.buffer instanceof ArrayBuffer
21
21
  ? input
22
22
  : new Uint8Array(input);
23
- return new Blob([bytes]);
23
+ return replayableBody(new Blob([bytes]));
24
24
  }
25
25
  try {
26
26
  return acceptBinaryBody(input);
@@ -1,6 +1,7 @@
1
1
  import type { SessionOperation } from '../context/index.js';
2
2
  /**
3
3
  * Repeat one content request that failed before any of its result was delivered: after a pause of
4
- * about 200 ms, then 400 ms, or of about the delay a refusal prescribes when it is longer.
4
+ * at least 100 ms, then 200 ms, or of the delay a refusal prescribes when it is longer, each
5
+ * lengthened by a random share of up to as much again.
5
6
  */
6
7
  export declare function retry<Result>(operation: SessionOperation, request: () => Promise<Result>): Promise<Result>;
@@ -1,34 +1,24 @@
1
1
  import { CODES } from '@astrale-os/kernel-protocol/errors';
2
2
  import { ResponseError, retryAfterOf, TransportError } from '../../errors/index.js';
3
- import { pauseSessionOperation } from '../context/index.js';
4
- const MAXIMUM_ATTEMPTS = 3;
3
+ import { retrySessionRequest } from '../retry.js';
5
4
  /**
6
5
  * Repeat one content request that failed before any of its result was delivered: after a pause of
7
- * about 200 ms, then 400 ms, or of about the delay a refusal prescribes when it is longer.
6
+ * at least 100 ms, then 200 ms, or of the delay a refusal prescribes when it is longer, each
7
+ * lengthened by a random share of up to as much again.
8
8
  */
9
- export async function retry(operation, request) {
10
- for (let attempt = 0;; attempt++) {
11
- try {
12
- return await request();
13
- }
14
- catch (cause) {
15
- const after = retryAfterOf(cause);
16
- if ((after === undefined && !retryable(cause)) ||
17
- attempt + 1 === MAXIMUM_ATTEMPTS ||
18
- operation.signal.aborted) {
19
- throw cause;
20
- }
21
- await pauseSessionOperation(operation, pause(attempt, after));
22
- }
23
- }
9
+ export function retry(operation, request) {
10
+ return retrySessionRequest(operation, pause, request);
24
11
  }
25
12
  /**
26
- * The pause before attempt `attempt + 1`: at least 100 ms doubled at each attempt, or the delay
27
- * `after` a refusal prescribes when it is longer, and up to as much again drawn at random, so that
28
- * clients refused together do not all come back at once.
13
+ * The pause after failed attempt `failed`: at least 100 ms doubled at each attempt, or the delay a
14
+ * refusal prescribes when it is longer, and up to as much again drawn at random, so that clients
15
+ * refused together do not all come back at once.
29
16
  */
30
- function pause(attempt, after) {
31
- const least = Math.max(after ?? 0, 100 * 2 ** attempt);
17
+ function pause(cause, failed) {
18
+ const after = retryAfterOf(cause);
19
+ if (after === undefined && !retryable(cause))
20
+ return undefined;
21
+ const least = Math.max(after ?? 0, 100 * 2 ** (failed - 1));
32
22
  return least + Math.random() * least;
33
23
  }
34
24
  function retryable(cause) {
@@ -1,4 +1,5 @@
1
1
  import { SessionError } from '../../errors/index.js';
2
+ import { pause } from '../../transport/index.js';
2
3
  /** Create one total wall-clock budget for a complete public Client Session operation. */
3
4
  export function createSessionOperation(lifecycle, input, defaultTimeoutMs) {
4
5
  const timeoutMs = input?.timeoutMs ?? defaultTimeoutMs;
@@ -56,22 +57,7 @@ export async function runSessionOperation(operation, task) {
56
57
  }
57
58
  /** Wait `ms` before another attempt, ending early with the operation's interruption. */
58
59
  export function pauseSessionOperation(operation, ms) {
59
- return runSessionOperation(operation, (signal) => delay(ms, signal));
60
- }
61
- function delay(ms, signal) {
62
- return new Promise((resolve, reject) => {
63
- if (signal.aborted)
64
- return reject(signal.reason);
65
- const timer = setTimeout(() => {
66
- signal.removeEventListener('abort', abort);
67
- resolve();
68
- }, ms);
69
- const abort = () => {
70
- clearTimeout(timer);
71
- reject(signal.reason);
72
- };
73
- signal.addEventListener('abort', abort, { once: true });
74
- });
60
+ return runSessionOperation(operation, (signal) => pause(ms, signal));
75
61
  }
76
62
  function requireSessionOperation(operation) {
77
63
  if (!operation.signal.aborted)
@@ -1,9 +1,7 @@
1
1
  import { CODES } from '@astrale-os/kernel-protocol/errors';
2
2
  import * as invocationProtocol from '@astrale-os/kernel-protocol/invocation';
3
3
  import { ResponseError, TransportError } from '../errors/index.js';
4
- import { pauseSessionOperation } from './context/index.js';
5
- /** The first attempt of a durable invocation and at most two more, within its one deadline. */
6
- const MAXIMUM_ATTEMPTS = 3;
4
+ import { retrySessionRequest } from './retry.js';
7
5
  const FIRST_PAUSE_MS = 200;
8
6
  /**
9
7
  * Options of one typed invocation of a durable callable: the caller's key, or one created for this
@@ -22,22 +20,18 @@ export function durableOptions(options) {
22
20
  * not, or the Kernel's `OUTCOME_UNKNOWN`. Its key makes the Kernel answer with the Execution a lost
23
21
  * attempt recorded, marked `replayed`, instead of starting another.
24
22
  */
25
- export async function attemptDurable(operation, attempt) {
26
- for (let attempts = 1;; attempts++) {
27
- try {
28
- return await attempt();
29
- }
30
- catch (cause) {
31
- const pause = FIRST_PAUSE_MS * 2 ** (attempts - 1);
32
- if (attempts === MAXIMUM_ATTEMPTS ||
33
- !unknownOutcome(cause) ||
34
- operation.signal.aborted ||
35
- operation.deadline - Date.now() <= pause) {
36
- throw cause;
37
- }
38
- await pauseSessionOperation(operation, pause);
39
- }
40
- }
23
+ export function attemptDurable(operation, attempt) {
24
+ return retrySessionRequest(operation, pause, attempt);
25
+ }
26
+ /**
27
+ * The pause after failed attempt `failed`: 200 ms doubled at each attempt, unless the outcome is
28
+ * known or the call's deadline would pass first.
29
+ */
30
+ function pause(cause, failed, operation) {
31
+ if (!unknownOutcome(cause))
32
+ return undefined;
33
+ const ms = FIRST_PAUSE_MS * 2 ** (failed - 1);
34
+ return operation.deadline - Date.now() <= ms ? undefined : ms;
41
35
  }
42
36
  function unknownOutcome(cause) {
43
37
  return ((cause instanceof TransportError && cause.context.kind === 'invocation') ||
@@ -0,0 +1,12 @@
1
+ import type { SessionOperation } from './context/index.js';
2
+ /**
3
+ * The pause before another attempt of a request whose attempt `failed` (counted from 1) threw
4
+ * `cause`, or `undefined` when that failure must not be retried.
5
+ */
6
+ export type RetryPause = (cause: unknown, failed: number, operation: SessionOperation) => number | undefined;
7
+ /**
8
+ * Attempt `request` until it settles, its operation is interrupted, it has been attempted
9
+ * {@link MAXIMUM_ATTEMPTS} times, or `pause` declines its failure, pausing through the operation
10
+ * between attempts. A request that is not retried throws its last cause.
11
+ */
12
+ export declare function retrySessionRequest<Result>(operation: SessionOperation, pause: RetryPause, request: () => Promise<Result>): Promise<Result>;
@@ -0,0 +1,23 @@
1
+ import { pauseSessionOperation } from './context/index.js';
2
+ /** The first attempt of a session request and at most two more. */
3
+ const MAXIMUM_ATTEMPTS = 3;
4
+ /**
5
+ * Attempt `request` until it settles, its operation is interrupted, it has been attempted
6
+ * {@link MAXIMUM_ATTEMPTS} times, or `pause` declines its failure, pausing through the operation
7
+ * between attempts. A request that is not retried throws its last cause.
8
+ */
9
+ export async function retrySessionRequest(operation, pause, request) {
10
+ for (let failed = 1;; failed++) {
11
+ try {
12
+ return await request();
13
+ }
14
+ catch (cause) {
15
+ if (failed === MAXIMUM_ATTEMPTS || operation.signal.aborted)
16
+ throw cause;
17
+ const ms = pause(cause, failed, operation);
18
+ if (ms === undefined)
19
+ throw cause;
20
+ await pauseSessionOperation(operation, ms);
21
+ }
22
+ }
23
+ }
@@ -27,8 +27,8 @@ export interface SessionDispatcherOptions {
27
27
  };
28
28
  }
29
29
  /**
30
- * A streaming call is forced over HTTP and may carry a binary body. A Blob is read again by every
31
- * send; a stream is consumed by the first one.
30
+ * A streaming call is forced over HTTP and may carry an admitted binary body, whose kind says
31
+ * whether it can be sent again: a Blob is read anew by every send, a stream only by the first.
32
32
  */
33
33
  export interface Streaming {
34
34
  readonly body?: BinaryBody;
@@ -1,7 +1,6 @@
1
1
  import { Key } from '@astrale-os/kernel-dsl/v1/addressing';
2
2
  import { acceptCall, Client, dispatchInternal } from '../../client/index.js';
3
3
  import { ClientError } from '../../errors/index.js';
4
- import { isReplayable } from '../../transport/http/binary-request.js';
5
4
  import { runSessionOperation, remainingSessionTime, sessionTransportOptions, allowEndpoint, } from '../context/index.js';
6
5
  import { resolveAuth } from './auth.js';
7
6
  import { selectEnvelope, selectEnvelopeTarget } from './envelope.js';
@@ -73,7 +72,7 @@ export class SessionDispatcher {
73
72
  ...(routing === undefined ? {} : { routing }),
74
73
  // The guard is the source Kernel's: a routed destination request never carries it.
75
74
  ...(options.maintenance === undefined ? {} : { maintenance: options.maintenance }),
76
- }));
75
+ }, streaming?.body));
77
76
  }
78
77
  async followSource(result, state, options, operation, streaming) {
79
78
  if (result.kind !== 'redirect')
@@ -115,7 +114,7 @@ export class SessionDispatcher {
115
114
  ...transportOptions(operation, options, streaming),
116
115
  routing: learned.route.via,
117
116
  };
118
- const result = await runSessionOperation(operation, () => send(client, learned.credential, call, request, trace));
117
+ const result = await runSessionOperation(operation, () => send(client, learned.credential, call, request, streaming?.body, trace));
119
118
  if (result.kind === 'redirect') {
120
119
  throw new ClientError('A destination redirect is invalid; only the source Kernel may redirect.');
121
120
  }
@@ -147,11 +146,11 @@ export class SessionDispatcher {
147
146
  function transportOptions(operation, options, streaming) {
148
147
  return streaming?.body === undefined
149
148
  ? sessionTransportOptions(operation, options.idempotencyKey)
150
- : { ...sessionTransportOptions(operation), body: streaming.body };
149
+ : sessionTransportOptions(operation);
151
150
  }
152
151
  /** A stream body was consumed by the send that just answered: it is never sent again. */
153
152
  function requireResendable(streaming, step, cause) {
154
- if (streaming?.body === undefined || isReplayable(streaming.body))
153
+ if (streaming?.body?.kind !== 'once')
155
154
  return;
156
155
  throw new ClientError(`A call with a streamed binary body is sent once and cannot ${step}; send it again with a new stream.`, cause === undefined ? undefined : { cause });
157
156
  }
@@ -170,21 +169,14 @@ function requireTargetRelease(route, target) {
170
169
  }
171
170
  }
172
171
  /**
173
- * Send one call, presenting the Trace only on the attempt that carries it. A stream body goes
174
- * through the package-private path too: the public Client refuses one, because only this routing
175
- * refuses to resend it.
172
+ * Send one call, presenting the Trace only on the attempt that carries it. A call with a body goes
173
+ * through the package-private path, which sends the admitted body: the public Client refuses a
174
+ * stream, because only this routing refuses to resend it. A body-carrying call is always sent by a
175
+ * Client this routing created.
176
176
  */
177
- function send(client, credential, call, options, trace) {
178
- if (trace !== undefined || !publicOptions(options)) {
179
- return dispatchInternal(client, credential, call, options, trace);
177
+ function send(client, credential, call, options, body, trace) {
178
+ if (trace !== undefined || body !== undefined) {
179
+ return dispatchInternal(client, credential, call, options, trace, body);
180
180
  }
181
- const sender = credential === undefined ? client : client.as(credential);
182
- // Both branches are needed: each narrows `options` to one `Client.dispatch` overload.
183
- return options.body === undefined
184
- ? sender.dispatch(call, options)
185
- : sender.dispatch(call, options);
186
- }
187
- /** Whether the public Client takes these options: no body, or a re-readable Blob. */
188
- function publicOptions(options) {
189
- return options.body === undefined || isReplayable(options.body);
181
+ return (credential === undefined ? client : client.as(credential)).dispatch(call, options);
190
182
  }
@@ -1,4 +1,5 @@
1
1
  import type * as invocation from '@astrale-os/kernel-protocol/invocation';
2
+ import type { BinaryBody } from '../../transport/http/binary-request.js';
2
3
  import type { SessionControlOptions } from '../context/index.js';
3
4
  export type SessionEnvelopeTransport = 'auto' | 'http' | 'websocket';
4
5
  export interface SessionRequestOptions extends SessionControlOptions {
@@ -15,7 +16,7 @@ export type SessionRequestOptionsWithBody = Omit<SessionRequestOptions, 'body' |
15
16
  };
16
17
  export declare function admitInvocationOptions(input: SessionRequestOptions | SessionRequestOptionsWithBody | undefined): {
17
18
  readonly options: Readonly<SessionRequestOptions>;
18
- readonly body?: Blob;
19
+ readonly body?: BinaryBody;
19
20
  };
20
21
  export declare function admitRequestOptions(input?: SessionRequestOptions): Readonly<SessionRequestOptions>;
21
22
  export declare function admitEnvelopeTransport(input: SessionEnvelopeTransport): SessionEnvelopeTransport;
@@ -1,4 +1,5 @@
1
1
  import * as invocationProtocol from '@astrale-os/kernel-protocol/invocation';
2
+ import { replayableBody } from '../../transport/http/binary-request.js';
2
3
  import { admitControlOptions } from '../context/index.js';
3
4
  export function admitInvocationOptions(input) {
4
5
  if (input === undefined)
@@ -15,7 +16,7 @@ export function admitInvocationOptions(input) {
15
16
  if (options.idempotencyKey !== undefined) {
16
17
  throw new TypeError('Binary requests cannot carry an idempotency key.');
17
18
  }
18
- return Object.freeze({ options: admitRequestOptions(options), body });
19
+ return Object.freeze({ options: admitRequestOptions(options), body: replayableBody(body) });
19
20
  }
20
21
  export function admitRequestOptions(input = {}) {
21
22
  if (input === null || typeof input !== 'object' || Array.isArray(input)) {
@@ -1,10 +1,10 @@
1
1
  import type { MutationAST, MutationInput, MutationResult } from '@astrale-os/kernel-core/graph/mutate';
2
2
  import type { QueryAST, QueryResultFor } from '@astrale-os/kernel-core/graph/query';
3
3
  import type { QueryResponse } from '../graph/index.js';
4
- import type { GraphApi, GraphMutationOptions, GraphQueryOptions, MutationAuthor } from '../graph/index.js';
4
+ import type { GraphApi, GraphMutationOptions, GraphQueryV6Options, MutationAuthor } from '../graph/index.js';
5
5
  export type StoreQuery = QueryAST;
6
6
  export type StoreQueryResponse<Query extends StoreQuery = StoreQuery> = QueryResponse<QueryResultFor<Query>>;
7
- export interface StoreReadOptions extends GraphQueryOptions {
7
+ export interface StoreReadOptions extends GraphQueryV6Options {
8
8
  readonly freshness?: 'cached' | 'refresh';
9
9
  }
10
10
  export interface StoreMutationOptions extends GraphMutationOptions {
@@ -50,15 +50,15 @@ export declare class GraphStore {
50
50
  private closed;
51
51
  constructor(options: StoreOptions);
52
52
  read<Query extends StoreQuery>(query: Query, options: StoreReadOptions): Promise<StoreQueryResponse<Query>>;
53
- peek<Query extends StoreQuery>(query: Query, options: GraphQueryOptions): StoreQueryResponse<Query> | undefined;
53
+ peek<Query extends StoreQuery>(query: Query, options: GraphQueryV6Options): StoreQueryResponse<Query> | undefined;
54
54
  preload<Query extends StoreQuery>(query: Query, options: StoreReadOptions): Promise<void>;
55
- subscribe<Query extends StoreQuery>(query: Query, listener: () => void, options: GraphQueryOptions): () => void;
56
- getSnapshot<Query extends StoreQuery>(query: Query, options: GraphQueryOptions): StoreSnapshot<Query>;
55
+ subscribe<Query extends StoreQuery>(query: Query, listener: () => void, options: GraphQueryV6Options): () => void;
56
+ getSnapshot<Query extends StoreQuery>(query: Query, options: GraphQueryV6Options): StoreSnapshot<Query>;
57
57
  observe<Query extends StoreQuery>(query: Query, listener: (snapshot: StoreSnapshot<Query>) => void, options: StoreReadOptions): () => void;
58
58
  mutate(author: MutationAuthor, options?: StoreMutationOptions): Promise<MutationResult>;
59
59
  mutate(input: MutationAST | MutationInput, options?: StoreMutationOptions): Promise<MutationResult>;
60
60
  invalidate(): void;
61
- invalidate(query: StoreQuery, options: GraphQueryOptions): void;
61
+ invalidate(query: StoreQuery, options: GraphQueryV6Options): void;
62
62
  sweep(): void;
63
63
  close(): void;
64
64
  private admit;
@@ -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,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,47 +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);
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);
92
72
  requireLive(control);
93
- if ('execution' in envelope) {
94
- return {
95
- kind: 'execution',
96
- execution: envelope.execution,
97
- ...(envelope.replayed === undefined ? {} : { replayed: envelope.replayed }),
98
- invocation: envelope.invocation,
99
- };
100
- }
101
- return { kind: 'value', value: envelope.result, invocation: envelope.invocation };
102
- }
103
- function redirectResult(response) {
104
- return Object.freeze({
105
- kind: 'redirect',
106
- invocation: response.invocation,
107
- redirect: response.redirect,
108
- });
73
+ return unaryResult(envelope);
109
74
  }
@@ -1,9 +1,21 @@
1
- import type { BinaryRequestBody } from '@astrale-os/kernel-core/callable';
2
1
  import { ClientError } from '../../errors/index.js';
3
- /** A binary request body: a re-readable Blob, or a one-shot stream of exactly `length` bytes. */
4
- export type BinaryBody = Blob | BinaryRequestBody;
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
+ };
5
15
  /** One send of a stream body: what Fetch reads, and the caller's stream failure it met. */
6
16
  export interface StreamSend {
17
+ readonly kind: 'once';
18
+ readonly length: number;
7
19
  /** Counted copy of the caller's stream, ending exactly after its declared length. */
8
20
  readonly body: ReadableStream<Uint8Array>;
9
21
  /** The failure of the caller's stream, or of its length, when one ended the send. */
@@ -16,15 +28,17 @@ export interface StreamSend {
16
28
  /** Cancel the caller's stream unless it was read through its end. */
17
29
  readonly release: (reason: unknown) => void;
18
30
  }
31
+ /** A Blob body, which every send reads again. */
32
+ export declare function replayableBody(blob: Blob): BinaryBody;
19
33
  /**
20
- * Capture one binary body. A stream is snapshotted with its declared length and must be unread:
21
- * the request that sends it consumes it, and nothing can send it again. A stream is recognized by
22
- * its reader, so one from another realm or a polyfill is accepted too.
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.
23
37
  */
24
38
  export declare function acceptBinaryBody(input: unknown): BinaryBody;
25
- /** Whether a body can be sent again: a Blob is read anew, a stream is consumed by one send. */
26
- export declare function isReplayable(body: BinaryBody): body is Blob;
27
39
  /** Cancel a stream body that no request has started to read; a Blob needs nothing. */
28
40
  export declare function cancelUnsent(body: BinaryBody | undefined): void;
29
41
  /** Send a stream once: count its bytes and fail it when they differ from its declared length. */
30
- export declare function sendStream(source: BinaryRequestBody): StreamSend;
42
+ export declare function sendStream(source: Extract<BinaryBody, {
43
+ kind: 'once';
44
+ }>): StreamSend;
@@ -1,12 +1,16 @@
1
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
+ }
2
6
  /**
3
- * Capture one binary body. A stream is snapshotted with its declared length and must be unread:
4
- * the request that sends it consumes it, and nothing can send it again. A stream is recognized by
5
- * its reader, so one from another realm or a polyfill is accepted too.
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.
6
10
  */
7
11
  export function acceptBinaryBody(input) {
8
12
  if (typeof Blob !== 'undefined' && input instanceof Blob)
9
- return input;
13
+ return replayableBody(input);
10
14
  if (input !== null && typeof input === 'object' && !Array.isArray(input)) {
11
15
  const { body, length } = input;
12
16
  if (isReadableStream(body)) {
@@ -15,7 +19,7 @@ export function acceptBinaryBody(input) {
15
19
  }
16
20
  if (body.locked)
17
21
  throw new TypeError('Binary stream is already being read.');
18
- return Object.freeze({ body, length });
22
+ return Object.freeze({ kind: 'once', body, length });
19
23
  }
20
24
  }
21
25
  throw new TypeError('Binary input must be a Blob, File, or byte stream with its exact length.');
@@ -25,13 +29,9 @@ function isReadableStream(input) {
25
29
  typeof input === 'object' &&
26
30
  typeof input.getReader === 'function');
27
31
  }
28
- /** Whether a body can be sent again: a Blob is read anew, a stream is consumed by one send. */
29
- export function isReplayable(body) {
30
- return typeof Blob !== 'undefined' && body instanceof Blob;
31
- }
32
32
  /** Cancel a stream body that no request has started to read; a Blob needs nothing. */
33
33
  export function cancelUnsent(body) {
34
- if (body === undefined || isReplayable(body) || body.body.locked)
34
+ if (body?.kind !== 'once' || body.body.locked)
35
35
  return;
36
36
  body.body
37
37
  .cancel(new ClientError('Binary request ended before its stream was sent.'))
@@ -96,6 +96,8 @@ export function sendStream(source) {
96
96
  cancel: release,
97
97
  }, { highWaterMark: 0 });
98
98
  return Object.freeze({
99
+ kind: 'once',
100
+ length: source.length,
99
101
  body,
100
102
  failure: () => failure,
101
103
  abortOnFailure: (next) => {
@@ -10,6 +10,5 @@ export declare function codecForResponse(contentType: string | null): codecs.Cod
10
10
  export declare function readBoundedBody(response: Response, maximumBytes: number, signal: AbortSignal): Promise<Uint8Array>;
11
11
  export declare function requireId(expected: protocol.RequestId, received: protocol.RequestId): void;
12
12
  export declare function decodeProtocol<T>(label: string, decode: () => T): T;
13
- export declare function normalizeMediaType(input: string | null): string | undefined;
14
13
  export declare function binaryHeaders(input: Headers, names: readonly string[]): Readonly<Record<string, string>>;
15
14
  export declare function requireNoStore(response: Response): void;
@@ -56,12 +56,6 @@ export function decodeProtocol(label, decode) {
56
56
  throw new ProtocolError(`server returned an invalid ${label}.`, { cause: asError(error) });
57
57
  }
58
58
  }
59
- export function normalizeMediaType(input) {
60
- if (input === null)
61
- return undefined;
62
- const value = input.split(';', 1)[0]?.trim().toLowerCase();
63
- return value === '' ? undefined : value;
64
- }
65
59
  export function binaryHeaders(input, names) {
66
60
  const output = {};
67
61
  for (const name of names) {
@@ -2,8 +2,9 @@ import type { RequestOptions, Transport, TransportRequest, TransportResult } fro
2
2
  import type { BinaryBody } from './binary-request.js';
3
3
  import type { HttpTransportOptions } from './configuration.js';
4
4
  /**
5
- * Package-private binary invocation whose body may be a one-shot stream; intentionally absent from
6
- * the public HttpTransport facade, whose callers could not resend a stream a Redirect answers.
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.
7
8
  */
8
9
  export declare function dispatchBinaryBody(transport: HttpTransport, input: TransportRequest, body: BinaryBody, options?: RequestOptions): Promise<TransportResult>;
9
10
  /** HTTP implementation of the universal invocation protocol. */