@astrale-os/kernel-client 1.0.0-beta.21 → 1.0.0-beta.22
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.
- package/dist/client/client.d.ts +6 -3
- package/dist/client/client.js +31 -20
- package/dist/client/index.d.ts +2 -2
- package/dist/client/index.js +1 -1
- package/dist/client/request.d.ts +11 -2
- package/dist/client/request.js +12 -5
- package/dist/session/content/api.d.ts +10 -2
- package/dist/session/content/api.js +13 -4
- package/dist/session/content/index.d.ts +1 -1
- package/dist/session/content/input.d.ts +6 -1
- package/dist/session/content/input.js +11 -3
- package/dist/session/content/retry.d.ts +4 -1
- package/dist/session/content/retry.js +19 -4
- package/dist/session/index.d.ts +1 -1
- package/dist/session/routing/dispatch.d.ts +7 -3
- package/dist/session/routing/dispatch.js +22 -4
- package/dist/session/session.typecheck.js +15 -2
- package/dist/transport/http/binary-request.d.ts +30 -0
- package/dist/transport/http/binary-request.js +108 -0
- package/dist/transport/http/index.d.ts +1 -1
- package/dist/transport/http/index.js +1 -1
- package/dist/transport/http/transport.d.ts +9 -0
- package/dist/transport/http/transport.js +75 -17
- package/package.json +5 -5
package/dist/client/client.d.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import type { invocation as protocol } from '@astrale-os/kernel-protocol';
|
|
2
2
|
import type { Transport } from '../transport/index.js';
|
|
3
3
|
import type { AuthenticatedClient, RemoteCredential } from './credential.js';
|
|
4
|
-
import type { Call, ClientDispatchOptions, ClientDispatchOptionsWithBody } from './request.js';
|
|
4
|
+
import type { Call, ClientDispatchOptions, ClientDispatchOptionsWithBody, ClientDispatchOptionsWithStream } from './request.js';
|
|
5
5
|
import type { BinaryResponse, Result, StreamResult, ValueResult } from './result.js';
|
|
6
6
|
import { type HttpTransportOptions } from '../transport/http/index.js';
|
|
7
7
|
export type ClientOptions = HttpTransportOptions | {
|
|
8
8
|
readonly transport: Transport;
|
|
9
9
|
};
|
|
10
|
-
/**
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Package-private Session routing path: it presents a redirect continuation's Trace and may send a
|
|
12
|
+
* one-shot stream body. Intentionally absent from the public Client facade.
|
|
13
|
+
*/
|
|
14
|
+
export declare function dispatchInternal(client: Client, credential: RemoteCredential | undefined, call: Call, options: ClientDispatchOptions | ClientDispatchOptionsWithStream | undefined, trace?: protocol.Trace): Promise<Result>;
|
|
12
15
|
/** Pure client for the universal remote Function invocation boundary. */
|
|
13
16
|
export declare class Client implements AuthenticatedClient {
|
|
14
17
|
private readonly transport;
|
package/dist/client/client.js
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { ClientError } from '../errors/index.js';
|
|
2
|
-
import {
|
|
2
|
+
import { cancelUnsent } from '../transport/http/binary-request.js';
|
|
3
|
+
import { dispatchBinaryBody, HttpTransport, } from '../transport/http/index.js';
|
|
3
4
|
import { authenticated, resolveCredential } from './credential.js';
|
|
4
5
|
import { admitRequest, invocation } from './request.js';
|
|
5
6
|
import { requireBinary, requireStream, requireValue } from './result.js';
|
|
6
7
|
import { admittedDeploymentRetiredError, admittedMissError, admittedStaleRouteError, } from './routing-control.js';
|
|
7
8
|
const controlledDispatch = new WeakMap();
|
|
8
|
-
/**
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Package-private Session routing path: it presents a redirect continuation's Trace and may send a
|
|
11
|
+
* one-shot stream body. Intentionally absent from the public Client facade.
|
|
12
|
+
*/
|
|
13
|
+
export function dispatchInternal(client, credential, call, options, trace) {
|
|
10
14
|
const dispatch = controlledDispatch.get(client);
|
|
11
15
|
if (dispatch === undefined)
|
|
12
|
-
throw new TypeError('
|
|
16
|
+
throw new TypeError('Internal dispatch requires an owned Client.');
|
|
13
17
|
return dispatch(credential, call, options, trace);
|
|
14
18
|
}
|
|
15
19
|
/** Pure client for the universal remote Function invocation boundary. */
|
|
@@ -24,7 +28,7 @@ export class Client {
|
|
|
24
28
|
this.transport = Object.hasOwn(options, 'transport')
|
|
25
29
|
? admitTransport(options.transport)
|
|
26
30
|
: new HttpTransport(options);
|
|
27
|
-
controlledDispatch.set(this, (credential, call, requestOptions, trace) => this.dispatchWith(credential, call, requestOptions, trace));
|
|
31
|
+
controlledDispatch.set(this, (credential, call, requestOptions, trace) => this.dispatchWith(credential, call, requestOptions, trace, true));
|
|
28
32
|
}
|
|
29
33
|
dispatch(call, options) {
|
|
30
34
|
return this.dispatchWith(undefined, call, options);
|
|
@@ -49,25 +53,32 @@ export class Client {
|
|
|
49
53
|
this.lifecycle.abort(failure);
|
|
50
54
|
this.transport.close?.();
|
|
51
55
|
}
|
|
52
|
-
async dispatchWith(credential, input, options, trace) {
|
|
56
|
+
async dispatchWith(credential, input, options, trace, streams = false) {
|
|
53
57
|
if (this.closed)
|
|
54
58
|
throw new ClientError('Client is closed.');
|
|
55
|
-
const request = admitRequest(input, options, this.lifecycle.signal);
|
|
56
|
-
const resolved = credential === undefined
|
|
57
|
-
? undefined
|
|
58
|
-
: await resolveCredential(credential, request.options.signal);
|
|
59
|
-
requireRequestLive(request.options.signal);
|
|
60
|
-
const envelope = invocation(request, resolved, trace);
|
|
59
|
+
const request = admitRequest(input, options, this.lifecycle.signal, streams);
|
|
61
60
|
let result;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
61
|
+
try {
|
|
62
|
+
const resolved = credential === undefined
|
|
63
|
+
? undefined
|
|
64
|
+
: await resolveCredential(credential, request.options.signal);
|
|
65
|
+
requireRequestLive(request.options.signal);
|
|
66
|
+
const envelope = invocation(request, resolved, trace);
|
|
67
|
+
if (request.body === undefined) {
|
|
68
|
+
result = await this.transport.dispatch(envelope, request.options);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
const transport = this.transport;
|
|
72
|
+
if (!(transport instanceof HttpTransport)) {
|
|
73
|
+
throw new TypeError('Binary dispatch requires HTTP transport.');
|
|
74
|
+
}
|
|
75
|
+
result = await dispatchBinaryBody(transport, envelope, request.body, request.options);
|
|
69
76
|
}
|
|
70
|
-
|
|
77
|
+
}
|
|
78
|
+
catch (cause) {
|
|
79
|
+
// A stream body this request never started to send is cancelled with it.
|
|
80
|
+
cancelUnsent(request.body);
|
|
81
|
+
throw cause;
|
|
71
82
|
}
|
|
72
83
|
if (result.kind === 'stale')
|
|
73
84
|
throw admittedStaleRouteError(result.current, result.invocation);
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { Client,
|
|
1
|
+
export { Client, dispatchInternal, type ClientOptions } from './client.js';
|
|
2
2
|
export { acceptCall } from './admission.js';
|
|
3
3
|
export type { AuthenticatedClient, RemoteCredential } from './credential.js';
|
|
4
|
-
export { call, type Call, type ClientDispatchOptions, type ClientDispatchOptionsWithBody, } from './request.js';
|
|
4
|
+
export { call, type Call, type ClientDispatchOptions, type ClientDispatchOptionsWithBody, type ClientDispatchOptionsWithStream, } from './request.js';
|
|
5
5
|
export type { Binary, BinaryResponse, ExecutionResult, Input, RedirectResult, Result, Stream, StreamResult, ValueResult, } from './result.js';
|
|
6
6
|
export { isAdmittedDeploymentRetiredError, isAdmittedMissError, isAdmittedStaleRouteError, } from './routing-control.js';
|
package/dist/client/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Client,
|
|
1
|
+
export { Client, dispatchInternal } from './client.js';
|
|
2
2
|
export { acceptCall } from './admission.js';
|
|
3
3
|
export { call, } from './request.js';
|
|
4
4
|
export { isAdmittedDeploymentRetiredError, isAdmittedMissError, isAdmittedStaleRouteError, } from './routing-control.js';
|
package/dist/client/request.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Target } from '@astrale-os/kernel-core/callable';
|
|
2
2
|
import type { PathLike } from '@astrale-os/kernel-core/path';
|
|
3
3
|
import type * as protocol from '@astrale-os/kernel-protocol/invocation';
|
|
4
|
+
import type { BinaryBody } from '../transport/http/binary-request.js';
|
|
4
5
|
import type { RequestOptions, TransportRequest } from '../transport/index.js';
|
|
5
6
|
import type { Input } from './result.js';
|
|
6
7
|
/** One portable call before Path canonicalization, correlation, and credential binding. */
|
|
@@ -20,6 +21,13 @@ export type ClientDispatchOptionsWithBody = Omit<ClientDispatchOptions, 'body' |
|
|
|
20
21
|
readonly body: Blob;
|
|
21
22
|
readonly idempotencyKey?: never;
|
|
22
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* Package-private: the body may also be a stream of exactly `length` bytes that one request
|
|
26
|
+
* consumes. Only Session routing sends one, because only it refuses a Redirect it cannot follow.
|
|
27
|
+
*/
|
|
28
|
+
export type ClientDispatchOptionsWithStream = Omit<ClientDispatchOptionsWithBody, 'body'> & {
|
|
29
|
+
readonly body: BinaryBody;
|
|
30
|
+
};
|
|
23
31
|
export interface AdmittedRequest {
|
|
24
32
|
readonly call: protocol.Call;
|
|
25
33
|
readonly delegate?: protocol.Delegate;
|
|
@@ -27,8 +35,9 @@ export interface AdmittedRequest {
|
|
|
27
35
|
readonly schema?: protocol.SchemaTarget;
|
|
28
36
|
readonly maintenance?: protocol.Maintenance;
|
|
29
37
|
readonly options: RequestOptions;
|
|
30
|
-
readonly body?:
|
|
38
|
+
readonly body?: BinaryBody;
|
|
31
39
|
}
|
|
32
40
|
export declare function call(target: PathLike | Target, input: Input): Call;
|
|
33
|
-
|
|
41
|
+
/** Admit one request; `streams` admits a stream body, which only the package-private path sends. */
|
|
42
|
+
export declare function admitRequest(input: Call, options: ClientDispatchOptions | ClientDispatchOptionsWithStream | undefined, lifecycle: AbortSignal, streams: boolean): AdmittedRequest;
|
|
34
43
|
export declare function invocation(request: AdmittedRequest, credential?: string, trace?: protocol.Trace): TransportRequest;
|
package/dist/client/request.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import * as invocationProtocol from '@astrale-os/kernel-protocol/invocation';
|
|
2
|
+
import { acceptBinaryBody } from '../transport/http/binary-request.js';
|
|
2
3
|
import { acceptCall } from './admission.js';
|
|
3
4
|
export function call(target, input) {
|
|
4
5
|
return Object.freeze({ target, input });
|
|
5
6
|
}
|
|
6
|
-
|
|
7
|
+
/** Admit one request; `streams` admits a stream body, which only the package-private path sends. */
|
|
8
|
+
export function admitRequest(input, options, lifecycle, streams) {
|
|
7
9
|
const call = acceptCall(input);
|
|
8
|
-
const admitted = admitRequestOptions(options);
|
|
10
|
+
const admitted = admitRequestOptions(options, streams);
|
|
9
11
|
const admittedOptions = lifecycleOptions(admitted.options, lifecycle);
|
|
10
12
|
const delegate = admitDelegate(options?.delegate);
|
|
11
13
|
const routing = admitRouting(options?.routing);
|
|
@@ -47,7 +49,7 @@ export function invocation(request, credential, trace) {
|
|
|
47
49
|
...(admittedTrace === undefined ? {} : { trace: admittedTrace }),
|
|
48
50
|
});
|
|
49
51
|
}
|
|
50
|
-
function admitRequestOptions(input) {
|
|
52
|
+
function admitRequestOptions(input, streams) {
|
|
51
53
|
if (input === undefined)
|
|
52
54
|
return {};
|
|
53
55
|
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
|
|
@@ -75,10 +77,15 @@ function admitRequestOptions(input) {
|
|
|
75
77
|
let body;
|
|
76
78
|
if (hasBody) {
|
|
77
79
|
const candidate = input.body;
|
|
78
|
-
if (
|
|
80
|
+
if (streams) {
|
|
81
|
+
body = acceptBinaryBody(candidate);
|
|
82
|
+
}
|
|
83
|
+
else if (candidate instanceof Blob) {
|
|
84
|
+
body = candidate;
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
79
87
|
throw new TypeError('Binary input must be a Blob or File.');
|
|
80
88
|
}
|
|
81
|
-
body = candidate;
|
|
82
89
|
}
|
|
83
90
|
if (body !== undefined && input.idempotencyKey !== undefined) {
|
|
84
91
|
throw new TypeError('Binary requests cannot carry an idempotency key.');
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import type { BinaryRequestBody } from '@astrale-os/kernel-core/callable';
|
|
1
2
|
import type { Path } from '@astrale-os/kernel-core/path';
|
|
2
3
|
import type { schema } from '@astrale-os/kernel-dsl/v1';
|
|
3
4
|
import type { Ref } from '@astrale-os/kernel-protocol/artifact';
|
|
4
5
|
import type { Binary, Input, Result } from '../../client/index.js';
|
|
6
|
+
import type { BinaryBody } from '../../transport/http/binary-request.js';
|
|
5
7
|
import type { SessionControlOptions, SessionOperation } from '../context/index.js';
|
|
6
8
|
export interface ContentLocation {
|
|
7
9
|
readonly node: string;
|
|
@@ -27,8 +29,14 @@ export type ContentDownload = {
|
|
|
27
29
|
readonly outcome: 'rejected';
|
|
28
30
|
readonly code: ContentRejection;
|
|
29
31
|
};
|
|
32
|
+
/**
|
|
33
|
+
* The bytes one upload stores. A Blob, File, or Uint8Array is read again by every attempt. A stream
|
|
34
|
+
* must yield exactly `length` bytes; the upload consumes it in one attempt, and cancels it if it
|
|
35
|
+
* fails before reading it through its end. A Domain's own binary input has this shape.
|
|
36
|
+
*/
|
|
37
|
+
export type ContentSource = Blob | Uint8Array | BinaryRequestBody;
|
|
30
38
|
export interface ContentApi {
|
|
31
|
-
upload(source:
|
|
39
|
+
upload(source: ContentSource, options: ContentUploadOptions): Promise<ContentUploadResult>;
|
|
32
40
|
download(location: ContentLocation, options?: SessionControlOptions): Promise<Binary>;
|
|
33
41
|
/**
|
|
34
42
|
* One outcome per location, in order, within one time budget for the whole list. Consume each
|
|
@@ -39,7 +47,7 @@ export interface ContentApi {
|
|
|
39
47
|
/** What the Session lends the content transfer: its time budgets and its routed dispatch. */
|
|
40
48
|
export interface ContentDependencies {
|
|
41
49
|
readonly operation: (options: SessionControlOptions) => SessionOperation;
|
|
42
|
-
readonly dispatch: (target: Path, input: Input, operation: SessionOperation, body?:
|
|
50
|
+
readonly dispatch: (target: Path, input: Input, operation: SessionOperation, body?: BinaryBody) => Promise<Result>;
|
|
43
51
|
}
|
|
44
52
|
/** Transfer immutable content over the authenticated Session routing conversation. */
|
|
45
53
|
export declare function createContentApi(dependencies: ContentDependencies): ContentApi;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { cancelUnsent, isReplayable } from '../../transport/http/binary-request.js';
|
|
1
2
|
import { requireResultKind } from '../routing/index.js';
|
|
2
3
|
import { downloadBatch } from './batch.js';
|
|
3
4
|
import { acceptBody, acceptControls, acceptLocation, acceptMediaType } from './input.js';
|
|
@@ -7,10 +8,18 @@ import { DOWNLOAD, UPLOAD, decodeDownload, decodeUploadResult } from './wire.js'
|
|
|
7
8
|
export function createContentApi(dependencies) {
|
|
8
9
|
async function upload(source, options) {
|
|
9
10
|
const body = acceptBody(source);
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
try {
|
|
12
|
+
const mediaType = acceptMediaType(options?.mediaType);
|
|
13
|
+
const operation = dependencies.operation(acceptControls(options));
|
|
14
|
+
const send = () => dependencies.dispatch(UPLOAD, { mediaType }, operation, body);
|
|
15
|
+
// A stream cannot be read twice: it has one attempt.
|
|
16
|
+
const result = await (isReplayable(body) ? retry(operation, send) : send());
|
|
17
|
+
return decodeUploadResult(requireResultKind('value', result).value);
|
|
18
|
+
}
|
|
19
|
+
catch (cause) {
|
|
20
|
+
cancelUnsent(body);
|
|
21
|
+
throw cause;
|
|
22
|
+
}
|
|
14
23
|
}
|
|
15
24
|
function download(input, options) {
|
|
16
25
|
if (Array.isArray(input)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { createContentApi, type ContentApi, type ContentDownload, type ContentLocation, type ContentRejection, type ContentUploadOptions, type ContentUploadResult, } from './api.js';
|
|
1
|
+
export { createContentApi, type ContentApi, type ContentDownload, type ContentLocation, type ContentRejection, type ContentSource, type ContentUploadOptions, type ContentUploadResult, } from './api.js';
|
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import type { BinaryBody } from '../../transport/http/binary-request.js';
|
|
1
2
|
import type { SessionControlOptions } from '../context/index.js';
|
|
2
3
|
import type { ContentLocation } from './api.js';
|
|
3
4
|
/** One canonical content location, as a download request carries it. */
|
|
4
5
|
export type Slot = Readonly<Record<'node' | 'property', string>>;
|
|
5
6
|
export declare function acceptLocation(input: ContentLocation): Slot;
|
|
6
|
-
|
|
7
|
+
/**
|
|
8
|
+
* The bytes of one upload: a Blob, an owned snapshot of a Uint8Array, or a byte stream with its
|
|
9
|
+
* exact length, which the upload consumes.
|
|
10
|
+
*/
|
|
11
|
+
export declare function acceptBody(input: unknown): BinaryBody;
|
|
7
12
|
export declare function acceptMediaType(input: unknown): string;
|
|
8
13
|
/** The caller's controls, with the content transfer's own default time budget. */
|
|
9
14
|
export declare function acceptControls(input: SessionControlOptions | undefined): SessionControlOptions;
|
|
@@ -1,6 +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
5
|
import { admitControlOptions } from '../context/index.js';
|
|
5
6
|
const CONTENT_TIMEOUT_MS = 30 * 60 * 1_000;
|
|
6
7
|
export function acceptLocation(input) {
|
|
@@ -9,9 +10,11 @@ export function acceptLocation(input) {
|
|
|
9
10
|
}
|
|
10
11
|
return Object.freeze({ node: NodeId(input.node), property: PropertyKey(input.property) });
|
|
11
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* The bytes of one upload: a Blob, an owned snapshot of a Uint8Array, or a byte stream with its
|
|
15
|
+
* exact length, which the upload consumes.
|
|
16
|
+
*/
|
|
12
17
|
export function acceptBody(input) {
|
|
13
|
-
if (typeof Blob !== 'undefined' && input instanceof Blob)
|
|
14
|
-
return input;
|
|
15
18
|
if (input instanceof Uint8Array) {
|
|
16
19
|
// Blob snapshots an ArrayBuffer view; a SharedArrayBuffer view needs an owned copy.
|
|
17
20
|
const bytes = input.buffer instanceof ArrayBuffer
|
|
@@ -19,7 +22,12 @@ export function acceptBody(input) {
|
|
|
19
22
|
: new Uint8Array(input);
|
|
20
23
|
return new Blob([bytes]);
|
|
21
24
|
}
|
|
22
|
-
|
|
25
|
+
try {
|
|
26
|
+
return acceptBinaryBody(input);
|
|
27
|
+
}
|
|
28
|
+
catch (cause) {
|
|
29
|
+
throw new TypeError('Content upload source must be a Blob, File, Uint8Array, or { body: ReadableStream, length }.', { cause });
|
|
30
|
+
}
|
|
23
31
|
}
|
|
24
32
|
export function acceptMediaType(input) {
|
|
25
33
|
if (typeof input !== 'string')
|
|
@@ -1,3 +1,6 @@
|
|
|
1
1
|
import type { SessionOperation } from '../context/index.js';
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
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.
|
|
5
|
+
*/
|
|
3
6
|
export declare function retry<Result>(operation: SessionOperation, request: () => Promise<Result>): Promise<Result>;
|
|
@@ -1,21 +1,36 @@
|
|
|
1
1
|
import { CODES } from '@astrale-os/kernel-protocol/errors';
|
|
2
|
-
import { ResponseError, TransportError } from '../../errors/index.js';
|
|
2
|
+
import { ResponseError, retryAfterOf, TransportError } from '../../errors/index.js';
|
|
3
3
|
import { pauseSessionOperation } from '../context/index.js';
|
|
4
4
|
const MAXIMUM_ATTEMPTS = 3;
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* 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.
|
|
8
|
+
*/
|
|
6
9
|
export async function retry(operation, request) {
|
|
7
10
|
for (let attempt = 0;; attempt++) {
|
|
8
11
|
try {
|
|
9
12
|
return await request();
|
|
10
13
|
}
|
|
11
14
|
catch (cause) {
|
|
12
|
-
|
|
15
|
+
const after = retryAfterOf(cause);
|
|
16
|
+
if ((after === undefined && !retryable(cause)) ||
|
|
17
|
+
attempt + 1 === MAXIMUM_ATTEMPTS ||
|
|
18
|
+
operation.signal.aborted) {
|
|
13
19
|
throw cause;
|
|
14
20
|
}
|
|
15
|
-
await pauseSessionOperation(operation,
|
|
21
|
+
await pauseSessionOperation(operation, pause(attempt, after));
|
|
16
22
|
}
|
|
17
23
|
}
|
|
18
24
|
}
|
|
25
|
+
/**
|
|
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.
|
|
29
|
+
*/
|
|
30
|
+
function pause(attempt, after) {
|
|
31
|
+
const least = Math.max(after ?? 0, 100 * 2 ** attempt);
|
|
32
|
+
return least + Math.random() * least;
|
|
33
|
+
}
|
|
19
34
|
function retryable(cause) {
|
|
20
35
|
return ((cause instanceof TransportError && cause.context.kind === 'invocation') ||
|
|
21
36
|
(cause instanceof ResponseError &&
|
package/dist/session/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type { SessionControlOptions, SessionPolicy } from './context/index.js';
|
|
2
|
-
export type { ContentApi, ContentDownload, ContentLocation, ContentRejection, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
|
|
2
|
+
export type { ContentApi, ContentDownload, ContentLocation, ContentRejection, ContentSource, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
|
|
3
3
|
export { bindSession, type BoundClientSession, type BoundSessionControls, type BoundSessionSource, } from './bound.js';
|
|
4
4
|
export { credentials, type Credentials, type CredentialsMint, type CredentialsOptions, type CredentialsState, type SessionCredential, } from './credential/index.js';
|
|
5
5
|
export type { IntrinsicRelease, SessionSnapshot } from './discovery/index.js';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { IssuerId } from '@astrale-os/kernel-core/auth/issuer';
|
|
2
2
|
import type * as invocation from '@astrale-os/kernel-protocol/invocation';
|
|
3
3
|
import type { Result } from '../../client/index.js';
|
|
4
|
+
import type { BinaryBody } from '../../transport/http/binary-request.js';
|
|
4
5
|
import type { Fetch } from '../../transport/http/index.js';
|
|
5
6
|
import type { SessionOperation, SessionPolicy } from '../context/index.js';
|
|
6
7
|
import type { AuthExchange, SessionAuth, EffectiveAuth } from './auth.js';
|
|
@@ -25,9 +26,12 @@ export interface SessionDispatcherOptions {
|
|
|
25
26
|
readonly timeoutMs: number;
|
|
26
27
|
};
|
|
27
28
|
}
|
|
28
|
-
/**
|
|
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.
|
|
32
|
+
*/
|
|
29
33
|
export interface Streaming {
|
|
30
|
-
readonly body?:
|
|
34
|
+
readonly body?: BinaryBody;
|
|
31
35
|
}
|
|
32
36
|
/** One Call with the authority it presents on every dispatch, and the route partition it selects. */
|
|
33
37
|
export interface ResolvedCall {
|
|
@@ -41,7 +45,7 @@ export declare class SessionDispatcher {
|
|
|
41
45
|
constructor(state: SessionDispatcherOptions);
|
|
42
46
|
dispatch(input: Parameters<typeof acceptCall>[0], options: SessionRequestOptions, operation: SessionOperation): Promise<Result>;
|
|
43
47
|
/** Reuse Session authority and route recovery while forcing HTTP for streaming calls. */
|
|
44
|
-
dispatchHttp(input: Parameters<typeof acceptCall>[0], options: SessionRequestOptions, operation: SessionOperation, body?:
|
|
48
|
+
dispatchHttp(input: Parameters<typeof acceptCall>[0], options: SessionRequestOptions, operation: SessionOperation, body?: BinaryBody): Promise<Result>;
|
|
45
49
|
/** Resolve the Session authority of one Call: each dispatch of the result presents it. */
|
|
46
50
|
resolve(input: Parameters<typeof acceptCall>[0], operation: SessionOperation): Promise<ResolvedCall>;
|
|
47
51
|
/**
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Key } from '@astrale-os/kernel-dsl/v1/addressing';
|
|
2
|
-
import { acceptCall, Client,
|
|
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';
|
|
4
5
|
import { runSessionOperation, remainingSessionTime, sessionTransportOptions, allowEndpoint, } from '../context/index.js';
|
|
5
6
|
import { resolveAuth } from './auth.js';
|
|
6
7
|
import { selectEnvelope, selectEnvelopeTarget } from './envelope.js';
|
|
@@ -77,6 +78,7 @@ export class SessionDispatcher {
|
|
|
77
78
|
async followSource(result, state, options, operation, streaming) {
|
|
78
79
|
if (result.kind !== 'redirect')
|
|
79
80
|
return result;
|
|
81
|
+
requireResendable(streaming, 'follow a Redirect');
|
|
80
82
|
const redirect = result.redirect;
|
|
81
83
|
if (redirect.route.via.issuer !== state.source) {
|
|
82
84
|
throw new ClientError('Redirect issuer differs from the session-pinned source Kernel identity.');
|
|
@@ -99,6 +101,7 @@ export class SessionDispatcher {
|
|
|
99
101
|
this.state.cache.delete(state.cacheKey);
|
|
100
102
|
if (!operation.claimRecovery())
|
|
101
103
|
throw cause;
|
|
104
|
+
requireResendable(streaming, 'recover its route', cause);
|
|
102
105
|
const routing = recoveryRefresh(control, learned);
|
|
103
106
|
const refreshed = await this.dispatchSource(state, routing, options, operation, streaming);
|
|
104
107
|
return this.followSource(refreshed, state, options, operation, streaming);
|
|
@@ -146,6 +149,12 @@ function transportOptions(operation, options, streaming) {
|
|
|
146
149
|
? sessionTransportOptions(operation, options.idempotencyKey)
|
|
147
150
|
: { ...sessionTransportOptions(operation), body: streaming.body };
|
|
148
151
|
}
|
|
152
|
+
/** A stream body was consumed by the send that just answered: it is never sent again. */
|
|
153
|
+
function requireResendable(streaming, step, cause) {
|
|
154
|
+
if (streaming?.body === undefined || isReplayable(streaming.body))
|
|
155
|
+
return;
|
|
156
|
+
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
|
+
}
|
|
149
158
|
function requireLearnedRoute(learned, source, target) {
|
|
150
159
|
if (learned.route.via.issuer !== source) {
|
|
151
160
|
throw new ClientError('Learned route issuer differs from the session-pinned source Kernel.');
|
|
@@ -160,13 +169,22 @@ function requireTargetRelease(route, target) {
|
|
|
160
169
|
throw new ClientError('Resolved route does not match the Target origin.');
|
|
161
170
|
}
|
|
162
171
|
}
|
|
163
|
-
/**
|
|
172
|
+
/**
|
|
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.
|
|
176
|
+
*/
|
|
164
177
|
function send(client, credential, call, options, trace) {
|
|
165
|
-
if (trace !== undefined)
|
|
166
|
-
return
|
|
178
|
+
if (trace !== undefined || !publicOptions(options)) {
|
|
179
|
+
return dispatchInternal(client, credential, call, options, trace);
|
|
180
|
+
}
|
|
167
181
|
const sender = credential === undefined ? client : client.as(credential);
|
|
168
182
|
// Both branches are needed: each narrows `options` to one `Client.dispatch` overload.
|
|
169
183
|
return options.body === undefined
|
|
170
184
|
? sender.dispatch(call, options)
|
|
171
185
|
: sender.dispatch(call, options);
|
|
172
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);
|
|
190
|
+
}
|
|
@@ -110,6 +110,10 @@ const boundBlobReceipt = boundSession.content
|
|
|
110
110
|
.then(({ receipt }) => receipt);
|
|
111
111
|
void blobReceipt;
|
|
112
112
|
void boundBlobReceipt;
|
|
113
|
+
void session.content.upload(received, { mediaType: 'image/png' });
|
|
114
|
+
void boundSession.content.upload({ body: new ReadableStream(), length: 0 }, { mediaType: 'image/png' });
|
|
115
|
+
// @ts-expect-error A stream upload declares its exact length.
|
|
116
|
+
void session.content.upload({ body: new ReadableStream() }, { mediaType: 'image/png' });
|
|
113
117
|
void session.invoke(registerReference, registration);
|
|
114
118
|
void boundSession.invoke(staticRegisterReference, registration);
|
|
115
119
|
void session.invoke(renameReference, renameRequest);
|
|
@@ -121,6 +125,12 @@ void client.dispatch(rawBinaryCall, { body: new Blob() });
|
|
|
121
125
|
void client.as('credential').call(rawBinaryCall, { body: new Blob() });
|
|
122
126
|
// @ts-expect-error Binary Functions require a byte source.
|
|
123
127
|
void session.invoke(binaryUploadReference, { mediaType: 'image/png' });
|
|
128
|
+
// @ts-expect-error A Session invocation sends a re-readable Blob: it may follow a Redirect.
|
|
129
|
+
void session.invoke(binaryUploadReference, { mediaType: 'image/png' }, { body: received });
|
|
130
|
+
// @ts-expect-error A raw Client sends a re-readable Blob: it cannot resend a stream a Redirect answers.
|
|
131
|
+
void client.dispatch(rawBinaryCall, { body: received });
|
|
132
|
+
// @ts-expect-error The public HTTP transport sends a re-readable Blob too.
|
|
133
|
+
void httpTransport.dispatchBinary(rawEnvelope, received);
|
|
124
134
|
// @ts-expect-error Value Functions reject binary bodies.
|
|
125
135
|
void session.invoke(registerReference, registration, { body: new Blob() });
|
|
126
136
|
// @ts-expect-error Bound binary Functions require a byte source.
|
|
@@ -207,5 +217,8 @@ void session.invoke(dynamicReference, dynamicInput, { expect: undefined });
|
|
|
207
217
|
const unsupportedClientOptions = { expect: undefined };
|
|
208
218
|
void unsupportedClientOptions;
|
|
209
219
|
// @ts-expect-error Internal metadata dispatch is absent from the public package facade.
|
|
210
|
-
import {
|
|
211
|
-
void
|
|
220
|
+
import { dispatchInternal } from '../index.js';
|
|
221
|
+
void dispatchInternal;
|
|
222
|
+
// @ts-expect-error The stream-capable HTTP binary path is absent from the public package facade.
|
|
223
|
+
import { dispatchBinaryBody } from '../index.js';
|
|
224
|
+
void dispatchBinaryBody;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { BinaryRequestBody } from '@astrale-os/kernel-core/callable';
|
|
2
|
+
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;
|
|
5
|
+
/** One send of a stream body: what Fetch reads, and the caller's stream failure it met. */
|
|
6
|
+
export interface StreamSend {
|
|
7
|
+
/** Counted copy of the caller's stream, ending exactly after its declared length. */
|
|
8
|
+
readonly body: ReadableStream<Uint8Array>;
|
|
9
|
+
/** The failure of the caller's stream, or of its length, when one ended the send. */
|
|
10
|
+
readonly failure: () => ClientError | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Abort the request when the stream fails, before its copy errors: a Fetch may otherwise end the
|
|
13
|
+
* failed body as though it were complete (workerd does), and the server would answer it.
|
|
14
|
+
*/
|
|
15
|
+
readonly abortOnFailure: (abort: () => void) => void;
|
|
16
|
+
/** Cancel the caller's stream unless it was read through its end. */
|
|
17
|
+
readonly release: (reason: unknown) => void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
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.
|
|
23
|
+
*/
|
|
24
|
+
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
|
+
/** Cancel a stream body that no request has started to read; a Blob needs nothing. */
|
|
28
|
+
export declare function cancelUnsent(body: BinaryBody | undefined): void;
|
|
29
|
+
/** 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;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { ClientError } from '../../errors/index.js';
|
|
2
|
+
/**
|
|
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.
|
|
6
|
+
*/
|
|
7
|
+
export function acceptBinaryBody(input) {
|
|
8
|
+
if (typeof Blob !== 'undefined' && input instanceof Blob)
|
|
9
|
+
return input;
|
|
10
|
+
if (input !== null && typeof input === 'object' && !Array.isArray(input)) {
|
|
11
|
+
const { body, length } = input;
|
|
12
|
+
if (isReadableStream(body)) {
|
|
13
|
+
if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) {
|
|
14
|
+
throw new TypeError('Binary stream length must be a non-negative safe integer.');
|
|
15
|
+
}
|
|
16
|
+
if (body.locked)
|
|
17
|
+
throw new TypeError('Binary stream is already being read.');
|
|
18
|
+
return Object.freeze({ body, length });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
throw new TypeError('Binary input must be a Blob, File, or byte stream with its exact length.');
|
|
22
|
+
}
|
|
23
|
+
function isReadableStream(input) {
|
|
24
|
+
return (input !== null &&
|
|
25
|
+
typeof input === 'object' &&
|
|
26
|
+
typeof input.getReader === 'function');
|
|
27
|
+
}
|
|
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
|
+
/** Cancel a stream body that no request has started to read; a Blob needs nothing. */
|
|
33
|
+
export function cancelUnsent(body) {
|
|
34
|
+
if (body === undefined || isReplayable(body) || 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
|
+
body,
|
|
100
|
+
failure: () => failure,
|
|
101
|
+
abortOnFailure: (next) => {
|
|
102
|
+
abort = next;
|
|
103
|
+
if (failure !== undefined)
|
|
104
|
+
next();
|
|
105
|
+
},
|
|
106
|
+
release,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { HttpTransport } from './transport.js';
|
|
1
|
+
export { dispatchBinaryBody, HttpTransport } from './transport.js';
|
|
2
2
|
export type { Fetch, HttpTransportOptions } from './configuration.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { HttpTransport } from './transport.js';
|
|
1
|
+
export { dispatchBinaryBody, HttpTransport } from './transport.js';
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { RequestOptions, Transport, TransportRequest, TransportResult } from '../index.js';
|
|
2
|
+
import type { BinaryBody } from './binary-request.js';
|
|
2
3
|
import type { HttpTransportOptions } from './configuration.js';
|
|
4
|
+
/**
|
|
5
|
+
* Package-private binary invocation 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.
|
|
7
|
+
*/
|
|
8
|
+
export declare function dispatchBinaryBody(transport: HttpTransport, input: TransportRequest, body: BinaryBody, options?: RequestOptions): Promise<TransportResult>;
|
|
3
9
|
/** HTTP implementation of the universal invocation protocol. */
|
|
4
10
|
export declare class HttpTransport implements Transport {
|
|
5
11
|
readonly url: string;
|
|
@@ -13,7 +19,10 @@ export declare class HttpTransport implements Transport {
|
|
|
13
19
|
dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
|
|
14
20
|
/** HTTP-only binary invocation; each call may replay a re-readable Blob. */
|
|
15
21
|
dispatchBinary(input: TransportRequest, body: Blob, options?: RequestOptions): Promise<TransportResult>;
|
|
22
|
+
/** A Blob may be replayed; a stream is read once, by this call, and must yield its length. */
|
|
23
|
+
private dispatchBody;
|
|
16
24
|
private dispatchWith;
|
|
25
|
+
private send;
|
|
17
26
|
private fetchResponse;
|
|
18
27
|
private nextRequestId;
|
|
19
28
|
}
|
|
@@ -1,11 +1,23 @@
|
|
|
1
1
|
import * as codecs from '@astrale-os/kernel-protocol/codecs';
|
|
2
2
|
import * as protocol from '@astrale-os/kernel-protocol/invocation';
|
|
3
|
-
import { ProtocolError, ResponseError, TransportError } from '../../errors/index.js';
|
|
3
|
+
import { ClientError, ProtocolError, ResponseError, TransportError } from '../../errors/index.js';
|
|
4
4
|
import { invocationFailure } from '../failure.js';
|
|
5
5
|
import { asError, controlledSignal, positiveInteger, requireLive, } from '../index.js';
|
|
6
6
|
import { admitResponse } from './admission.js';
|
|
7
|
+
import { acceptBinaryBody, cancelUnsent, isReplayable, sendStream } from './binary-request.js';
|
|
7
8
|
import { capture } from './configuration.js';
|
|
8
9
|
import { unprocessed } from './unprocessed.js';
|
|
10
|
+
const bodyDispatch = new WeakMap();
|
|
11
|
+
/**
|
|
12
|
+
* Package-private binary invocation whose body may be a one-shot stream; intentionally absent from
|
|
13
|
+
* the public HttpTransport facade, whose callers could not resend a stream a Redirect answers.
|
|
14
|
+
*/
|
|
15
|
+
export async function dispatchBinaryBody(transport, input, body, options = {}) {
|
|
16
|
+
const dispatch = bodyDispatch.get(transport);
|
|
17
|
+
if (dispatch === undefined)
|
|
18
|
+
throw new TypeError('Binary body dispatch requires an HttpTransport.');
|
|
19
|
+
return dispatch(input, body, options);
|
|
20
|
+
}
|
|
9
21
|
/** HTTP implementation of the universal invocation protocol. */
|
|
10
22
|
export class HttpTransport {
|
|
11
23
|
url;
|
|
@@ -23,6 +35,7 @@ export class HttpTransport {
|
|
|
23
35
|
this.timeoutMs = configuration.timeoutMs;
|
|
24
36
|
this.maximumRequestBytes = configuration.maximumRequestBytes;
|
|
25
37
|
this.maximumResponseBytes = configuration.maximumResponseBytes;
|
|
38
|
+
bodyDispatch.set(this, (input, body, options) => this.dispatchBody(input, acceptBinaryBody(body), options));
|
|
26
39
|
}
|
|
27
40
|
async dispatch(input, options = {}) {
|
|
28
41
|
return this.dispatchWith(input, options);
|
|
@@ -31,12 +44,35 @@ export class HttpTransport {
|
|
|
31
44
|
async dispatchBinary(input, body, options = {}) {
|
|
32
45
|
if (!(body instanceof Blob))
|
|
33
46
|
throw new TypeError('Binary request body must be a Blob.');
|
|
47
|
+
return this.dispatchBody(input, body, options);
|
|
48
|
+
}
|
|
49
|
+
/** A Blob may be replayed; a stream is read once, by this call, and must yield its length. */
|
|
50
|
+
async dispatchBody(input, body, options) {
|
|
34
51
|
if (options.idempotencyKey !== undefined) {
|
|
52
|
+
cancelUnsent(body);
|
|
35
53
|
throw new TypeError('Binary requests cannot carry an idempotency key.');
|
|
36
54
|
}
|
|
37
55
|
return this.dispatchWith(input, options, body);
|
|
38
56
|
}
|
|
39
57
|
async dispatchWith(input, options, binaryBody) {
|
|
58
|
+
let sent;
|
|
59
|
+
let streamed;
|
|
60
|
+
if (binaryBody !== undefined && isReplayable(binaryBody)) {
|
|
61
|
+
sent = { length: binaryBody.size, body: binaryBody, once: false };
|
|
62
|
+
}
|
|
63
|
+
else if (binaryBody !== undefined) {
|
|
64
|
+
// The stream is claimed first: whatever ends this call before reading it through cancels it.
|
|
65
|
+
streamed = sendStream(binaryBody);
|
|
66
|
+
sent = { length: binaryBody.length, body: streamed.body, once: true };
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
return await this.send(input, options, sent, streamed);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
streamed?.release(new ClientError('Binary request settled before its stream ended.'));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async send(input, options, binary, streamed) {
|
|
40
76
|
const requestId = this.nextRequestId();
|
|
41
77
|
const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
|
|
42
78
|
const codec = codecs.json;
|
|
@@ -48,22 +84,36 @@ export class HttpTransport {
|
|
|
48
84
|
...invocationInput,
|
|
49
85
|
...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
|
|
50
86
|
});
|
|
51
|
-
const encoded =
|
|
87
|
+
const encoded = binary === undefined
|
|
52
88
|
? codec.encode(request)
|
|
53
89
|
: protocol.http.encodeBinaryRequestEnvelope(request);
|
|
54
90
|
const control = controlledSignal(options.signal, timeoutMs);
|
|
91
|
+
// A failed stream aborts the request, so no Fetch sends its truncated body as complete. The
|
|
92
|
+
// request fails with the stream's ClientError whatever the abort reason, so it is the plain
|
|
93
|
+
// AbortError: workerd logs any other abort reason as an uncaught error.
|
|
94
|
+
streamed?.abortOnFailure(() => control.cancel());
|
|
55
95
|
let handedOff = false;
|
|
56
96
|
let phase = 'connect';
|
|
97
|
+
// The status of the response being received, which a failure to read it still reports.
|
|
98
|
+
let status;
|
|
57
99
|
let delivery = 'not-sent';
|
|
58
100
|
try {
|
|
59
101
|
requireLive(control);
|
|
60
|
-
if (
|
|
102
|
+
if (binary === undefined && encodedByteLength(encoded) > this.maximumRequestBytes) {
|
|
61
103
|
throw invocationFailure(`request exceeds maximumRequestBytes (${this.maximumRequestBytes}).`, 'send');
|
|
62
104
|
}
|
|
63
105
|
phase = 'send';
|
|
64
106
|
delivery = 'unknown';
|
|
65
|
-
const response = await this.fetchResponse(codec, encoded, trace, control,
|
|
107
|
+
const response = await this.fetchResponse(codec, encoded, trace, control, binary);
|
|
108
|
+
// A Fetch that ignores the abort may still end a failed stream body as though it were
|
|
109
|
+
// complete: the server then answered bytes the caller never sent, and its answer is dropped.
|
|
110
|
+
const failed = streamed?.failure();
|
|
111
|
+
if (failed !== undefined) {
|
|
112
|
+
response.body?.cancel().catch(() => undefined);
|
|
113
|
+
throw failed;
|
|
114
|
+
}
|
|
66
115
|
phase = 'receive';
|
|
116
|
+
status = response.status;
|
|
67
117
|
requireLive(control);
|
|
68
118
|
const result = await admitResponse(response, requestId, {
|
|
69
119
|
maximumBytes: this.maximumResponseBytes,
|
|
@@ -75,35 +125,42 @@ export class HttpTransport {
|
|
|
75
125
|
return result;
|
|
76
126
|
}
|
|
77
127
|
catch (error) {
|
|
128
|
+
// The caller's stream failed, or yielded other than its declared length: the ClientError
|
|
129
|
+
// naming it, with the stream's own failure as its cause, is the failure of this request.
|
|
130
|
+
const rejected = streamed?.failure();
|
|
131
|
+
if (rejected !== undefined)
|
|
132
|
+
throw rejected;
|
|
78
133
|
// A request the server refused unprocessed, even when sent again, was never delivered.
|
|
79
134
|
const proven = phase === 'send' && unprocessed(error) ? 'not-sent' : delivery;
|
|
80
|
-
throw transportFailure(error, control, options.signal, timeoutMs, this.url, phase, proven);
|
|
135
|
+
throw transportFailure(error, control, options.signal, timeoutMs, this.url, phase, proven, status);
|
|
81
136
|
}
|
|
82
137
|
finally {
|
|
83
138
|
if (!handedOff)
|
|
84
139
|
control.close();
|
|
85
140
|
}
|
|
86
141
|
}
|
|
87
|
-
async fetchResponse(codec, encoded, trace, control,
|
|
142
|
+
async fetchResponse(codec, encoded, trace, control, binary) {
|
|
88
143
|
const init = {
|
|
89
144
|
method: 'POST',
|
|
90
145
|
redirect: 'manual',
|
|
91
146
|
credentials: 'omit',
|
|
92
147
|
referrerPolicy: 'no-referrer',
|
|
93
|
-
// Fetch owns Content-Length; the protocol carries
|
|
148
|
+
// Fetch owns Content-Length; the protocol carries the exact length across Fetch runtimes.
|
|
94
149
|
headers: {
|
|
95
150
|
...this.headers,
|
|
96
151
|
...protocol.http.encodeTraceHeaders(trace),
|
|
97
|
-
'content-type':
|
|
152
|
+
'content-type': binary === undefined ? codec.contentType : protocol.http.BINARY_REQUEST_CONTENT_TYPE,
|
|
98
153
|
accept: codec.contentType,
|
|
99
|
-
...(
|
|
154
|
+
...(binary === undefined
|
|
100
155
|
? {}
|
|
101
156
|
: {
|
|
102
157
|
[protocol.http.REQUEST_ENVELOPE_FIELD]: encoded,
|
|
103
|
-
[protocol.http.BINARY_LENGTH_FIELD]: String(
|
|
158
|
+
[protocol.http.BINARY_LENGTH_FIELD]: String(binary.length),
|
|
104
159
|
}),
|
|
105
160
|
},
|
|
106
|
-
body:
|
|
161
|
+
body: binary === undefined ? toBody(encoded) : binary.body,
|
|
162
|
+
// Fetch sends a stream body without buffering it only in half duplex.
|
|
163
|
+
...(binary?.once === true ? { duplex: 'half' } : {}),
|
|
107
164
|
signal: control.signal,
|
|
108
165
|
};
|
|
109
166
|
try {
|
|
@@ -112,8 +169,10 @@ export class HttpTransport {
|
|
|
112
169
|
catch (error) {
|
|
113
170
|
// The server processed none of it: send it once more, on the connection that replaces the
|
|
114
171
|
// one that refused it, under the same timeout and signal (CLIENT-HTTP-UNPROCESSED-RESEND).
|
|
115
|
-
|
|
172
|
+
// A stream body was consumed by the refused attempt: it is never sent again.
|
|
173
|
+
if (!unprocessed(error) || control.signal.aborted || binary?.once === true) {
|
|
116
174
|
throw error;
|
|
175
|
+
}
|
|
117
176
|
return this.fetchImpl(this.url, init);
|
|
118
177
|
}
|
|
119
178
|
}
|
|
@@ -132,7 +191,7 @@ function toBody(input) {
|
|
|
132
191
|
function encodedByteLength(input) {
|
|
133
192
|
return typeof input === 'string' ? new TextEncoder().encode(input).byteLength : input.byteLength;
|
|
134
193
|
}
|
|
135
|
-
function transportFailure(input, control, parent, timeoutMs, url, phase, delivery) {
|
|
194
|
+
function transportFailure(input, control, parent, timeoutMs, url, phase, delivery, status) {
|
|
136
195
|
if (input instanceof ResponseError || input instanceof ProtocolError)
|
|
137
196
|
return input;
|
|
138
197
|
if (control.timedOut) {
|
|
@@ -145,8 +204,7 @@ function transportFailure(input, control, parent, timeoutMs, url, phase, deliver
|
|
|
145
204
|
return asError(parent.reason ?? input);
|
|
146
205
|
return input instanceof TransportError
|
|
147
206
|
? input
|
|
148
|
-
: invocationFailure(
|
|
149
|
-
|
|
150
|
-
delivery
|
|
151
|
-
});
|
|
207
|
+
: invocationFailure(status === undefined
|
|
208
|
+
? `Failed to communicate with the server at ${url}.`
|
|
209
|
+
: `Failed to read the HTTP ${status} response of the server at ${url}.`, phase, { cause: asError(input), delivery });
|
|
152
210
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astrale-os/kernel-client",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.22",
|
|
4
4
|
"description": "Universal Client — protocol-first, transport-agnostic",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"astrale",
|
|
@@ -65,13 +65,13 @@
|
|
|
65
65
|
"access": "public"
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"@astrale-os/kernel-core": "1.0.0-beta.
|
|
69
|
-
"@astrale-os/kernel-dsl": "1.0.0-beta.
|
|
70
|
-
"@astrale-os/kernel-protocol": "1.0.0-beta.
|
|
68
|
+
"@astrale-os/kernel-core": "1.0.0-beta.19",
|
|
69
|
+
"@astrale-os/kernel-dsl": "1.0.0-beta.12",
|
|
70
|
+
"@astrale-os/kernel-protocol": "1.0.0-beta.19",
|
|
71
71
|
"@tanstack/pacer": "0.20.1"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
|
-
"@astrale-os/kernel-server": "1.0.0-beta.
|
|
74
|
+
"@astrale-os/kernel-server": "1.0.0-beta.19",
|
|
75
75
|
"@astrale/typescript-config": "npm:@jsr/astrale__typescript-config@~1.1.0",
|
|
76
76
|
"@types/node": "^22.0.0",
|
|
77
77
|
"typescript": "7.0.2",
|