@astrale-os/kernel-client 1.0.0-beta.45 → 1.0.0-beta.47

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 (44) hide show
  1. package/dist/auth/authorization.d.ts +8 -3
  2. package/dist/auth/authorization.js +10 -1
  3. package/dist/client/client.d.ts +51 -2
  4. package/dist/client/client.js +158 -13
  5. package/dist/client/level.d.ts +58 -0
  6. package/dist/client/level.js +159 -0
  7. package/dist/client/result.d.ts +4 -0
  8. package/dist/client/result.js +10 -5
  9. package/dist/errors/index.d.ts +1 -0
  10. package/dist/errors/index.js +1 -0
  11. package/dist/errors/inexpressible-error.d.ts +23 -0
  12. package/dist/errors/inexpressible-error.js +26 -0
  13. package/dist/graph/page-contract.d.ts +9 -3
  14. package/dist/graph/query.js +6 -1
  15. package/dist/graph/query.typecheck.d.ts +3 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/session/credential/credentials.d.ts +2 -1
  19. package/dist/session/credential/credentials.js +24 -6
  20. package/dist/transport/auto/decision.d.ts +2 -0
  21. package/dist/transport/auto/decision.js +4 -0
  22. package/dist/transport/auto/transport.d.ts +10 -1
  23. package/dist/transport/auto/transport.js +17 -0
  24. package/dist/transport/http/admission.js +3 -3
  25. package/dist/transport/http/configuration.d.ts +7 -0
  26. package/dist/transport/http/configuration.js +2 -0
  27. package/dist/transport/http/response.d.ts +10 -0
  28. package/dist/transport/http/response.js +15 -0
  29. package/dist/transport/http/transport.d.ts +4 -1
  30. package/dist/transport/http/transport.js +25 -5
  31. package/dist/transport/index.d.ts +1 -0
  32. package/dist/transport/index.js +1 -0
  33. package/dist/transport/level.d.ts +42 -0
  34. package/dist/transport/level.js +58 -0
  35. package/dist/transport/transport.d.ts +33 -0
  36. package/dist/transport/unary.d.ts +2 -1
  37. package/dist/transport/unary.js +4 -2
  38. package/dist/transport/websocket/connection.d.ts +6 -1
  39. package/dist/transport/websocket/connection.js +21 -5
  40. package/dist/transport/websocket/exchange.d.ts +3 -0
  41. package/dist/transport/websocket/exchange.js +6 -4
  42. package/dist/transport/websocket/transport.d.ts +19 -1
  43. package/dist/transport/websocket/transport.js +48 -11
  44. package/package.json +5 -5
@@ -1,6 +1,7 @@
1
1
  import type { EdgeKey, EdgeSlug } from '@astrale-os/kernel-core/graph/edge';
2
2
  import type { FactId } from '@astrale-os/kernel-core/graph/formula';
3
3
  import type { Answer, QueryResult, Undecided, wire } from '@astrale-os/kernel-core/graph/query';
4
+ import type { RevisionToken } from '@astrale-os/kernel-core/graph/revision';
4
5
  import type { ClassKey } from '@astrale-os/kernel-dsl/v1/addressing';
5
6
  /** Caller-selected bounds and continuation for one graph query page. */
6
7
  export interface QueryPageRequest {
@@ -49,8 +50,11 @@ export interface QueryItem {
49
50
  }
50
51
  /**
51
52
  * What a Query answers, by its family: a list's Page, the table of the facts it renders as values
52
- * (an Edge's entry with the slug the Edge stores, when it has one), the revision it was read at and
53
- * whether its cursor came from another (W6); an `exists`; or a `count`.
53
+ * (an Edge's entry with the slug the Edge stores, when it has one, and each entry of a stored Node
54
+ * or Edge the caller reads with its `revision` and its write count, `writes`, unless the Host does
55
+ * not state them), the schema revision it was read under (`schema`) and whether its cursor came
56
+ * from another (W6); an `exists`; or a `count`. A Host below wire level 1 states neither on any
57
+ * entry: that case ends when the floor passes level 1.
54
58
  */
55
59
  export type QueryAnswer = {
56
60
  readonly list: QueryPage;
@@ -58,8 +62,10 @@ export type QueryAnswer = {
58
62
  readonly list: unknown;
59
63
  }>['facts'][number] & {
60
64
  readonly slug?: EdgeSlug;
65
+ readonly revision?: RevisionToken;
66
+ readonly writes?: number;
61
67
  })[];
62
- readonly revision: string;
68
+ readonly schema: string;
63
69
  readonly revised?: true;
64
70
  } | Exclude<Answer, {
65
71
  readonly list: unknown;
@@ -1,4 +1,5 @@
1
1
  import { QUERY, QueryAST, QueryASTDecodeError, QueryResult, } from '@astrale-os/kernel-core/graph/query';
2
+ import { isRevisionToken } from '@astrale-os/kernel-core/graph/revision';
2
3
  import { Path, PathError } from '@astrale-os/kernel-core/path';
3
4
  import { queryOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
4
5
  import { query } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
@@ -126,7 +127,11 @@ function decodeAnswer(input, family) {
126
127
  return answer;
127
128
  // Only an Edge carries a slug.
128
129
  const slugs = answer.facts.every(({ fact, slug }) => slug === undefined || typeof fact !== 'string');
129
- return slugs && pagesClosed(answer.list) ? answer : refuse();
130
+ // A revision and a write count come together, or the Kernel states neither.
131
+ const revisions = answer.facts.every(({ revision, writes }) => revision === undefined
132
+ ? writes === undefined
133
+ : writes !== undefined && isRevisionToken(revision));
134
+ return slugs && revisions && pagesClosed(answer.list) ? answer : refuse();
130
135
  }
131
136
  /**
132
137
  * Every Page, its Branches' included, carries a cursor exactly when an item follows it (W3), and
@@ -47,8 +47,10 @@ declare function overloads(): Promise<readonly [QueryResponse<import("@astrale-o
47
47
  readonly list: unknown;
48
48
  }>['facts'][number] & {
49
49
  readonly slug?: import("@astrale-os/kernel-core/graph/edge").EdgeSlug;
50
+ readonly revision?: import("@astrale-os/kernel-core/graph/revision").RevisionToken;
51
+ readonly writes?: number;
50
52
  })[];
51
- readonly revision: string;
53
+ readonly schema: string;
52
54
  readonly revised?: true;
53
55
  }, {
54
56
  readonly exists: boolean;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { Target, targetPath } from '@astrale-os/kernel-core/callable';
2
2
  export { Client, call, type AuthenticatedClient, type Call, type ClientDispatchOptions, type ClientDispatchOptionsWithBody, type ClientOptions, type Binary, type BinaryResponse, type Input, type RemoteCredential, type Result, type Stream, type StreamResult, type ValueResult, } from './client/index.js';
3
3
  export * from './errors/index.js';
4
- export { type RequestOptions, type DeploymentRetired, type MissControl, type StaleControl, type Transport, type TransportRequest, type TransportResult, } from './transport/index.js';
4
+ export { type RequestOptions, type DeploymentRetired, type MissControl, ConnectionMoved, served, servedOf, type Served, type StaleControl, type Transport, type TransportRequest, type TransportResult, } from './transport/index.js';
5
5
  export { HttpTransport, type Fetch, type HttpTransportOptions } from './transport/http/index.js';
6
6
  export { WebSocketTransport, type WebSocketConstructor, type WebSocketTransportOptions, } from './transport/websocket/index.js';
7
7
  export { AutoTransport, formatClientWarning, type AutoTransportOptions, type ClientWarning, } from './transport/auto/index.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { Target, targetPath } from '@astrale-os/kernel-core/callable';
2
2
  export { Client, call, } from './client/index.js';
3
3
  export * from './errors/index.js';
4
- export {} from './transport/index.js';
4
+ export { ConnectionMoved, served, servedOf, } from './transport/index.js';
5
5
  export { HttpTransport } from './transport/http/index.js';
6
6
  export { WebSocketTransport, } from './transport/websocket/index.js';
7
7
  export { AutoTransport, formatClientWarning, } from './transport/auto/index.js';
@@ -24,7 +24,8 @@ export type CredentialsState = {
24
24
  };
25
25
  /**
26
26
  * Acquire one fresh credential: a compact JWT, whose `exp` claim is its expiry, or an explicit
27
- * credential and expiry. The supplied signal is owned by Credentials.
27
+ * credential and expiry. The supplied signal is owned by Credentials: the attempt fails once it
28
+ * aborts, at the mint budget at the latest, whether or not the mint observes it.
28
29
  */
29
30
  export type CredentialsMint = (signal: AbortSignal) => string | SessionCredential | PromiseLike<string | SessionCredential>;
30
31
  export interface CredentialsOptions {
@@ -131,18 +131,28 @@ export function credentials(source) {
131
131
  return { promise: Promise.reject(error), controller };
132
132
  }
133
133
  const renew = mint;
134
- const current = held();
135
- publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
136
134
  unsignalled = false;
137
- const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
135
+ const signal = controller.signal;
136
+ // The budget is a timer of this owner's clock, cleared once the attempt settles.
137
+ const deadline = setTimeout(() => {
138
+ controller.abort(new DOMException('Session credential mint timed out.', 'TimeoutError'));
139
+ }, MINT_TIMEOUT_MS);
140
+ let abandon;
138
141
  const promise = (async () => {
139
142
  try {
140
143
  // A mint that throws instead of rejecting fails this attempt alike: the executor turns the
141
144
  // throw into a rejection, so the attempt settles only after it yields, once `minting`
142
- // holds it, and the cleanup below releases it for the next acquisition.
143
- const returned = new Promise((complete) => {
145
+ // holds it, and the cleanup below releases it for the next acquisition. The budget is
146
+ // this owner's, not the mint's: the attempt fails once its signal aborts, whether or not
147
+ // the mint observes it, so an answer that never comes cannot hold `minting` forever.
148
+ const answer = new Promise((complete) => {
144
149
  complete(renew(signal));
145
150
  });
151
+ const returned = new Promise((complete, fail) => {
152
+ abandon = () => fail(signal.reason);
153
+ signal.addEventListener('abort', abandon, { once: true });
154
+ answer.then(complete, fail);
155
+ });
146
156
  const minted = admitMinted(await returned);
147
157
  attempt = 0;
148
158
  publish({ status: 'valid', credential: minted });
@@ -155,10 +165,16 @@ export function credentials(source) {
155
165
  throw error;
156
166
  }
157
167
  finally {
168
+ clearTimeout(deadline);
169
+ if (abandon !== undefined)
170
+ signal.removeEventListener('abort', abandon);
158
171
  minting = undefined;
159
172
  }
160
173
  })();
161
174
  minting = { promise, controller };
175
+ // Published once the mint is held: an observer that acquires now joins it. It settles later.
176
+ const current = held();
177
+ publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
162
178
  // A rejection reaches every waiter; keep an unattached one from surfacing as unhandled.
163
179
  promise.catch(() => undefined);
164
180
  return minting;
@@ -213,7 +229,9 @@ export function credentials(source) {
213
229
  clearTimeout(expiryTimer);
214
230
  expiryTimer = setTimeout(() => {
215
231
  expiryTimer = undefined;
216
- if (!anticipating || held() !== credential)
232
+ // A mint in flight settles within its budget and reports the outcome itself: expiry is
233
+ // published only while no attempt is pending, so `expired` always means a retry can start.
234
+ if (!anticipating || held() !== credential || minting !== undefined)
217
235
  return;
218
236
  publish({ status: 'expired', error: new ClientError('Session credential expired.') });
219
237
  }, clamp(credential.expiresAt - Date.now()));
@@ -21,6 +21,8 @@ export type AutoTicket = {
21
21
  export declare class AutoDecision {
22
22
  private state;
23
23
  get closed(): boolean;
24
+ /** The route every request follows, once one is chosen. */
25
+ get route(): 'websocket' | 'http' | undefined;
24
26
  /** Claim the probe when undecided; otherwise report the state to follow. */
25
27
  begin(): AutoTicket;
26
28
  /** The probe proved WebSocket usable. */
@@ -6,6 +6,10 @@ export class AutoDecision {
6
6
  get closed() {
7
7
  return this.state.kind === 'closed';
8
8
  }
9
+ /** The route every request follows, once one is chosen. */
10
+ get route() {
11
+ return this.state.kind === 'chosen' ? this.state.via : undefined;
12
+ }
9
13
  /** Claim the probe when undecided; otherwise report the state to follow. */
10
14
  begin() {
11
15
  if (this.state.kind !== 'undecided')
@@ -1,3 +1,5 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
2
+ import type * as protocol from '@astrale-os/kernel-protocol/invocation';
1
3
  import type { Fetch } from '../http/index.js';
2
4
  import type { RequestOptions, Transport, TransportRequest, TransportResult } from '../index.js';
3
5
  import type { WebSocketConstructor } from '../websocket/index.js';
@@ -17,16 +19,23 @@ export interface AutoTransportOptions {
17
19
  readonly maximumActiveInvocations?: number;
18
20
  readonly maximumBufferedStreamItems?: number;
19
21
  readonly onWarning?: (warning: ClientWarning) => void;
22
+ /** The wire History both bindings state; absent, the Invocation History of this build. */
23
+ readonly levels?: protocol.Levels;
20
24
  }
21
25
  /** Sticky WebSocket-first Transport with one delivery-aware HTTP fallback decision. */
22
26
  export declare class AutoTransport implements Transport {
23
27
  private readonly websocket;
24
28
  private readonly http;
25
29
  private readonly decision;
26
- private readonly timeoutMs;
30
+ readonly timeoutMs: number;
27
31
  private readonly onWarning;
28
32
  constructor(options: AutoTransportOptions);
29
33
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
34
+ /**
35
+ * The level of the WebSocket connection once WebSocket is the chosen route; none over HTTP, and
36
+ * none before the route is chosen: the first request probes it.
37
+ */
38
+ fixed(options?: RequestOptions): Promise<Level | undefined>;
30
39
  private dispatchWithBudget;
31
40
  close(): void;
32
41
  private tryWebsocket;
@@ -34,6 +34,7 @@ export class AutoTransport {
34
34
  ...(options.maximumResponseBytes === undefined
35
35
  ? {}
36
36
  : { maximumResponseBytes: options.maximumResponseBytes }),
37
+ ...(options.levels === undefined ? {} : { levels: options.levels }),
37
38
  });
38
39
  this.websocket = new WebSocketTransport({
39
40
  url: options.endpoints.websocket,
@@ -54,6 +55,7 @@ export class AutoTransport {
54
55
  ...(options.maximumBufferedStreamItems === undefined
55
56
  ? {}
56
57
  : { maximumBufferedStreamItems: options.maximumBufferedStreamItems }),
58
+ ...(options.levels === undefined ? {} : { levels: options.levels }),
57
59
  });
58
60
  }
59
61
  async dispatch(input, options) {
@@ -61,6 +63,21 @@ export class AutoTransport {
61
63
  const budget = new InvocationBudget(options, this.timeoutMs);
62
64
  return this.dispatchWithBudget(input, budget);
63
65
  }
66
+ /**
67
+ * The level of the WebSocket connection once WebSocket is the chosen route; none over HTTP, and
68
+ * none before the route is chosen: the first request probes it.
69
+ */
70
+ async fixed(options) {
71
+ if (this.decision.route !== 'websocket')
72
+ return undefined;
73
+ try {
74
+ return await this.websocket.fixed(options);
75
+ }
76
+ catch {
77
+ // The dispatch that follows meets the same failure and reports it.
78
+ return undefined;
79
+ }
80
+ }
64
81
  async dispatchWithBudget(input, budget) {
65
82
  let ticket = this.decision.begin();
66
83
  while (ticket.kind === 'probing') {
@@ -10,7 +10,7 @@ import { decodeDeploymentRetired } from './retired.js';
10
10
  import { HttpStream } from './stream.js';
11
11
  /** Admit exactly one response representation, preserving reserved-control precedence. */
12
12
  export async function admitResponse(response, requestId, context) {
13
- const { control, maximumBytes } = context;
13
+ const { control, maximumBytes, level, host } = context;
14
14
  if (response.status >= 300 && response.status < 400) {
15
15
  throw new ProtocolError('server returned a network redirect.');
16
16
  }
@@ -65,10 +65,10 @@ export async function admitResponse(response, requestId, context) {
65
65
  const decoded = decodeProtocol('response body', () => responseCodec.decode(body));
66
66
  const envelope = decodeProtocol('response envelope', () => protocol.decodeResponse(decoded));
67
67
  if (envelope.requestId === null && 'error' in envelope)
68
- throw responseError(envelope.error, envelope.invocation);
68
+ throw responseError(envelope.error, envelope.invocation, level, host);
69
69
  requireId(requestId, envelope.requestId);
70
70
  if ('error' in envelope)
71
- throw responseError(envelope.error, envelope.invocation);
71
+ throw responseError(envelope.error, envelope.invocation, level, host);
72
72
  requireLive(control);
73
73
  return unaryResult(envelope);
74
74
  }
@@ -1,3 +1,4 @@
1
+ import * as protocol from '@astrale-os/kernel-protocol/invocation';
1
2
  /** Web Fetch capability used by the built-in HTTP transport. */
2
3
  export type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
3
4
  export interface HttpTransportOptions {
@@ -10,6 +11,11 @@ export interface HttpTransportOptions {
10
11
  readonly maximumRequestBytes?: number;
11
12
  /** Maximum unary, binary, or individual stream-frame body size. */
12
13
  readonly maximumResponseBytes?: number;
14
+ /**
15
+ * The wire History whose current level the transport states and whose floor bounds what it
16
+ * reads; absent, the Invocation History of this build.
17
+ */
18
+ readonly levels?: protocol.Levels;
13
19
  }
14
20
  /** Captured transport configuration, admitted once before any invocation. */
15
21
  export interface Configuration {
@@ -19,6 +25,7 @@ export interface Configuration {
19
25
  readonly timeoutMs: number;
20
26
  readonly maximumRequestBytes: number;
21
27
  readonly maximumResponseBytes: number;
28
+ readonly levels: protocol.Levels;
22
29
  }
23
30
  /** Admit static options and detach the caller's request headers. */
24
31
  export declare function capture(options: HttpTransportOptions): Configuration;
@@ -1,5 +1,6 @@
1
1
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
2
2
  import { asError, positiveInteger } from '../index.js';
3
+ import { captureLevels } from '../level.js';
3
4
  const DEFAULT_TIMEOUT_MS = 30_000;
4
5
  const DEFAULT_MAXIMUM_REQUEST_BYTES = 16 * 1024 * 1024;
5
6
  const DEFAULT_MAXIMUM_RESPONSE_BYTES = 16 * 1024 * 1024;
@@ -15,6 +16,7 @@ export function capture(options) {
15
16
  timeoutMs: positiveInteger(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, 'timeoutMs'),
16
17
  maximumRequestBytes: positiveInteger(options.maximumRequestBytes ?? DEFAULT_MAXIMUM_REQUEST_BYTES, 'maximumRequestBytes'),
17
18
  maximumResponseBytes: positiveInteger(options.maximumResponseBytes ?? DEFAULT_MAXIMUM_RESPONSE_BYTES, 'maximumResponseBytes'),
19
+ levels: captureLevels(options.levels),
18
20
  };
19
21
  }
20
22
  function normalizeUrl(input) {
@@ -1,3 +1,4 @@
1
+ import { type Level } from '@astrale-os/kernel-core/wire';
1
2
  import * as codecs from '@astrale-os/kernel-protocol/codecs';
2
3
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
4
  import { ResponseTooLargeError } from '../../errors/index.js';
@@ -6,7 +7,16 @@ import { type ControlledSignal } from '../index.js';
6
7
  export interface ResponseContext {
7
8
  readonly maximumBytes: number;
8
9
  readonly control: ControlledSignal;
10
+ /** The wire level the response is written at. */
11
+ readonly level: Level;
12
+ /** The Host's own wire level. */
13
+ readonly host: Level;
9
14
  }
15
+ /**
16
+ * The wire level the Host of a response tells: level 0 when it tells none. A Host tells its level
17
+ * only to a request that stated one.
18
+ */
19
+ export declare function hostLevel(response: Response): Level;
10
20
  export declare function codecForResponse(contentType: string | null): codecs.Codec | undefined;
11
21
  export declare function readBoundedBody(response: Response, maximumBytes: number, signal: AbortSignal): Promise<Uint8Array>;
12
22
  /** The failure of an answer that passed the client's `maximumResponseBytes`. */
@@ -1,7 +1,22 @@
1
+ import { acceptLevel } from '@astrale-os/kernel-core/wire';
1
2
  import * as codecs from '@astrale-os/kernel-protocol/codecs';
2
3
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
4
  import { ProtocolError, ResponseError, ResponseTooLargeError } from '../../errors/index.js';
4
5
  import { asError } from '../index.js';
6
+ /**
7
+ * The wire level the Host of a response tells: level 0 when it tells none. A Host tells its level
8
+ * only to a request that stated one.
9
+ */
10
+ export function hostLevel(response) {
11
+ const field = response.headers.get(protocol.http.LEVEL_FIELD);
12
+ if (field === null)
13
+ return acceptLevel(0);
14
+ const level = protocol.http.decodeLevel(field);
15
+ if (level === undefined) {
16
+ throw new ProtocolError(`server told an invalid wire level ${JSON.stringify(field)}.`);
17
+ }
18
+ return level;
19
+ }
5
20
  export function codecForResponse(contentType) {
6
21
  return protocol.http.codecForContentType(contentType, [codecs.json]);
7
22
  }
@@ -12,9 +12,12 @@ export declare class HttpTransport implements Transport {
12
12
  readonly url: string;
13
13
  private readonly fetchImpl;
14
14
  private readonly headers;
15
- private readonly timeoutMs;
15
+ readonly timeoutMs: number;
16
16
  private readonly maximumRequestBytes;
17
17
  private readonly maximumResponseBytes;
18
+ private readonly levels;
19
+ /** What a request written at the current level accepts. */
20
+ private readonly accept;
18
21
  private nextId;
19
22
  constructor(options: HttpTransportOptions);
20
23
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
@@ -3,9 +3,11 @@ import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
3
  import { ClientError } from '../../errors/index.js';
4
4
  import { invocationFailure, requestFailure } from '../failure.js';
5
5
  import { controlledSignal, positiveInteger, requireLive } from '../index.js';
6
+ import { served, writtenLevel } from '../level.js';
6
7
  import { admitResponse } from './admission.js';
7
8
  import { cancelUnsent, replayableBody, sendStream } from './binary-request.js';
8
9
  import { capture } from './configuration.js';
10
+ import { hostLevel } from './response.js';
9
11
  import { unprocessed } from './unprocessed.js';
10
12
  const bodyDispatch = new WeakMap();
11
13
  /**
@@ -27,9 +29,18 @@ export class HttpTransport {
27
29
  timeoutMs;
28
30
  maximumRequestBytes;
29
31
  maximumResponseBytes;
32
+ levels;
33
+ /** What a request written at the current level accepts. */
34
+ accept;
30
35
  nextId = 1;
31
36
  constructor(options) {
32
37
  const configuration = capture(options);
38
+ this.levels = configuration.levels;
39
+ // A build that knows no wire change states no level, as the builds released before it.
40
+ this.accept =
41
+ configuration.levels.current === 0
42
+ ? protocol.http.acceptFor(codecs.json)
43
+ : protocol.http.acceptFor(codecs.json, configuration.levels.current);
33
44
  this.url = configuration.url;
34
45
  this.fetchImpl = configuration.fetch;
35
46
  this.headers = configuration.headers;
@@ -72,7 +83,10 @@ export class HttpTransport {
72
83
  const requestId = this.nextRequestId();
73
84
  const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
74
85
  const codec = codecs.json;
75
- const { trace: traceInput, ...invocationInput } = input;
86
+ const { trace: traceInput, level: writtenInput, ...invocationInput } = input;
87
+ // The request states the level it is written at; the Host answers at that level at most.
88
+ const written = writtenLevel(writtenInput, this.levels);
89
+ const accept = written === this.levels.current ? this.accept : protocol.http.acceptFor(codec, written);
76
90
  const trace = traceInput === undefined ? undefined : protocol.admitTrace(traceInput);
77
91
  const request = protocol.decodeRequest({
78
92
  version: protocol.VERSION,
@@ -100,7 +114,7 @@ export class HttpTransport {
100
114
  }
101
115
  phase = 'send';
102
116
  delivery = 'unknown';
103
- const response = await this.fetchResponse(codec, encoded, trace, control, binary);
117
+ const response = await this.fetchResponse(codec, encoded, accept, trace, control, binary);
104
118
  // A Fetch that ignores the abort may still end a failed stream body as though it were
105
119
  // complete: the server then answered bytes the caller never sent, and its answer is dropped.
106
120
  const failed = streamed?.failure();
@@ -111,14 +125,20 @@ export class HttpTransport {
111
125
  phase = 'receive';
112
126
  status = response.status;
113
127
  requireLive(control);
128
+ // The Host read the request, and wrote this response, at the level the request stated or
129
+ // at its own, whichever is lower.
130
+ const host = hostLevel(response);
131
+ const level = host < written ? host : written;
114
132
  const result = await admitResponse(response, requestId, {
115
133
  maximumBytes: this.maximumResponseBytes,
116
134
  control,
135
+ level,
136
+ host,
117
137
  });
118
138
  handedOff =
119
139
  result.kind === 'stream' ||
120
140
  (result.kind === 'binary' && !(result.value.body instanceof Uint8Array));
121
- return result;
141
+ return served(result, level, host);
122
142
  }
123
143
  catch (error) {
124
144
  // The caller's stream failed, or yielded other than its declared length: the ClientError
@@ -141,7 +161,7 @@ export class HttpTransport {
141
161
  control.close();
142
162
  }
143
163
  }
144
- async fetchResponse(codec, encoded, trace, control, binary) {
164
+ async fetchResponse(codec, encoded, accept, trace, control, binary) {
145
165
  const init = {
146
166
  method: 'POST',
147
167
  redirect: 'manual',
@@ -152,7 +172,7 @@ export class HttpTransport {
152
172
  ...this.headers,
153
173
  ...protocol.http.encodeTraceHeaders(trace),
154
174
  'content-type': binary === undefined ? codec.contentType : protocol.http.BINARY_REQUEST_CONTENT_TYPE,
155
- accept: codec.contentType,
175
+ accept,
156
176
  ...(binary === undefined
157
177
  ? {}
158
178
  : {
@@ -1,2 +1,3 @@
1
1
  export type { RequestOptions, DeploymentRetired, MissControl, StaleControl, Transport, TransportRequest, TransportResult, } from './transport.js';
2
+ export { ConnectionMoved, served, servedOf, type Served } from './level.js';
2
3
  export { asError, controlledSignal, pause, positiveInteger, requireLive, type ControlledSignal, } from './deadline.js';
@@ -1 +1,2 @@
1
+ export { ConnectionMoved, served, servedOf } from './level.js';
1
2
  export { asError, controlledSignal, pause, positiveInteger, requireLive, } from './deadline.js';
@@ -0,0 +1,42 @@
1
+ import { Levels, type Level } from '@astrale-os/kernel-core/wire';
2
+ /** The wire levels of one answer: the level it is written at and the level of its Host. */
3
+ export interface Served {
4
+ /** The wire level the answer is written at: the one its request stated or the Host's, whichever is lower. */
5
+ readonly written: Level;
6
+ /** The Host's own wire level, as it told it. */
7
+ readonly host: Level;
8
+ }
9
+ /**
10
+ * `answer`, a Transport result or the error a Host answered with, as written at `written` by a Host
11
+ * at `host`. The levels are kept beside the object and never as members of it: a caller receives
12
+ * the result its call declares, and nothing else. A Transport that states no level for an answer
13
+ * says its Host told none.
14
+ */
15
+ export declare function served<Answer extends object>(answer: Answer, written: Level, host?: Level): Answer;
16
+ /**
17
+ * The wire levels a Transport stated for `answer`: level 0 for both when it stated none. A Transport
18
+ * that wraps another reads them here to restate them for the object it returns in its place.
19
+ */
20
+ export declare function servedOf(answer: object): Served;
21
+ /**
22
+ * The connection of a Transport is at another wire level than the request it was given is written
23
+ * at: it was made again, towards a Host at another level, after it told its level. Nothing was
24
+ * sent. A Client writes the request for `level` and gives it once more; no caller sees this.
25
+ */
26
+ export declare class ConnectionMoved extends Error {
27
+ /** The wire level of the connection now. */
28
+ readonly level: Level;
29
+ constructor(
30
+ /** The wire level of the connection now. */
31
+ level: Level);
32
+ }
33
+ /**
34
+ * The wire level one request is written at: the Transport's current level unless the request names
35
+ * a lower one it reads.
36
+ */
37
+ export declare function writtenLevel(input: Level | undefined, levels: Levels): Level;
38
+ /**
39
+ * The floor and the current level a Transport states, detached from their History: those of the
40
+ * Invocation History of this build when none is given.
41
+ */
42
+ export declare function captureLevels(input: Levels | undefined): Levels;
@@ -0,0 +1,58 @@
1
+ import { acceptLevel, Levels } from '@astrale-os/kernel-core/wire';
2
+ import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
+ const SILENT = Object.freeze({ written: acceptLevel(0), host: acceptLevel(0) });
4
+ const answers = new WeakMap();
5
+ /**
6
+ * `answer`, a Transport result or the error a Host answered with, as written at `written` by a Host
7
+ * at `host`. The levels are kept beside the object and never as members of it: a caller receives
8
+ * the result its call declares, and nothing else. A Transport that states no level for an answer
9
+ * says its Host told none.
10
+ */
11
+ export function served(answer, written, host = written) {
12
+ if (written !== 0 || host !== 0) {
13
+ answers.set(answer, Object.freeze({ written: acceptLevel(written), host: acceptLevel(host) }));
14
+ }
15
+ return answer;
16
+ }
17
+ /**
18
+ * The wire levels a Transport stated for `answer`: level 0 for both when it stated none. A Transport
19
+ * that wraps another reads them here to restate them for the object it returns in its place.
20
+ */
21
+ export function servedOf(answer) {
22
+ return answers.get(answer) ?? SILENT;
23
+ }
24
+ /**
25
+ * The connection of a Transport is at another wire level than the request it was given is written
26
+ * at: it was made again, towards a Host at another level, after it told its level. Nothing was
27
+ * sent. A Client writes the request for `level` and gives it once more; no caller sees this.
28
+ */
29
+ export class ConnectionMoved extends Error {
30
+ level;
31
+ constructor(
32
+ /** The wire level of the connection now. */
33
+ level) {
34
+ super(`The connection is now at wire level ${level}.`);
35
+ this.level = level;
36
+ this.name = 'ConnectionMoved';
37
+ }
38
+ }
39
+ /**
40
+ * The wire level one request is written at: the Transport's current level unless the request names
41
+ * a lower one it reads.
42
+ */
43
+ export function writtenLevel(input, levels) {
44
+ if (input === undefined)
45
+ return levels.current;
46
+ const level = acceptLevel(input);
47
+ if (!Levels.includes(levels, level)) {
48
+ throw new TypeError(`A request cannot be written at wire level ${level}: this transport speaks levels ${levels.floor} to ${levels.current}.`);
49
+ }
50
+ return level;
51
+ }
52
+ /**
53
+ * The floor and the current level a Transport states, detached from their History: those of the
54
+ * Invocation History of this build when none is given.
55
+ */
56
+ export function captureLevels(input) {
57
+ return Levels(input ?? protocol.history);
58
+ }
@@ -1,3 +1,4 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
1
2
  import type { invocation as protocol, routes } from '@astrale-os/kernel-protocol';
2
3
  import type { Result } from '../client/result.js';
3
4
  export interface RequestOptions {
@@ -24,6 +25,11 @@ export interface TransportRequest {
24
25
  readonly schema?: protocol.SchemaTarget;
25
26
  /** Source-Kernel maintenance session guard; omitted after routing. */
26
27
  readonly maintenance?: protocol.Maintenance;
28
+ /**
29
+ * The wire level `call` is written at, which the Transport states to the Host in place of its
30
+ * current one; absent, the current level. It is never a member of the envelope.
31
+ */
32
+ readonly level?: Level;
27
33
  }
28
34
  /** Correlated reserved control decoded independently from application results and errors. */
29
35
  export interface StaleControl {
@@ -44,9 +50,36 @@ export interface DeploymentRetired extends routes.DeploymentRetired {
44
50
  readonly invocation: protocol.InvocationId;
45
51
  }
46
52
  export type TransportResult = Result | StaleControl | MissControl | DeploymentRetired;
53
+ /**
54
+ * The embedding-environment adapter of a Client. What it tells of wire levels is its whole
55
+ * contract with its Client, and every part of it is exported:
56
+ *
57
+ * - it states to the Host the level a request names (`TransportRequest.level`);
58
+ * - it states the levels of each result it returns and each error a Host answered with beside
59
+ * that object, with `served`; an answer no level is stated for is read as the answer of a Host
60
+ * at level 0, which told none;
61
+ * - when its connection fixes one level, it tells it with `fixed`, and throws `ConnectionMoved`
62
+ * when the connection is at another level than the request it is given is written at.
63
+ *
64
+ * A Transport that wraps another keeps that contract. The levels are kept beside an answer and
65
+ * never as members of it, so one that returns or throws another object than the one it was given, a
66
+ * copy included, restates them: `served(copy, servedOf(answer).written, servedOf(answer).host)`.
67
+ * It lets `ConnectionMoved` through, and passes `fixed` and `timeoutMs` on.
68
+ */
47
69
  export interface Transport {
48
70
  /** Primary embedding-environment adapter for a complete invocation boundary. */
49
71
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
72
+ /**
73
+ * The wire level every request of this Transport's connection is written at, when its connection
74
+ * fixes one for every message; it connects when it has to. A Client asks before it writes a
75
+ * request, and writes it for that level. Absent, or `undefined`: each request states its own.
76
+ */
77
+ readonly fixed?: (options?: RequestOptions) => Promise<Level | undefined>;
78
+ /**
79
+ * The deadline of one dispatch whose options name none, in milliseconds. A Client that gives a
80
+ * request to the Transport a second time gives it what is left of the first deadline.
81
+ */
82
+ readonly timeoutMs?: number;
50
83
  /** Optional owned-resource shutdown used by Client.close(). */
51
84
  readonly close?: () => void;
52
85
  }
@@ -1,8 +1,9 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
1
2
  import type { ErrorPayload } from '@astrale-os/kernel-protocol/errors';
2
3
  import type * as protocol from '@astrale-os/kernel-protocol/invocation';
3
4
  import type { TransportResult } from './transport.js';
4
5
  import { ResponseError } from '../errors/index.js';
5
6
  /** The application error one decoded error response or `stream.error` frame of `invocation` carries. */
6
- export declare function responseError(error: ErrorPayload, invocation: protocol.InvocationId): ResponseError;
7
+ export declare function responseError(error: ErrorPayload, invocation: protocol.InvocationId, level?: Level, host?: Level | undefined): ResponseError;
7
8
  /** The Transport result of one decoded unary response that carries no application error. */
8
9
  export declare function unaryResult(response: Exclude<protocol.Response, protocol.ErrorResponse>): TransportResult;