@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,7 +1,9 @@
1
1
  import { ResponseError } from '../errors/index.js';
2
+ import { served } from './level.js';
2
3
  /** The application error one decoded error response or `stream.error` frame of `invocation` carries. */
3
- export function responseError(error, invocation) {
4
- return new ResponseError(error.code, error.message, invocation, error.data);
4
+ export function responseError(error, invocation, level, host = level) {
5
+ const answered = new ResponseError(error.code, error.message, invocation, error.data);
6
+ return level === undefined ? answered : served(answered, level, host);
5
7
  }
6
8
  /** The Transport result of one decoded unary response that carries no application error. */
7
9
  export function unaryResult(response) {
@@ -1,4 +1,5 @@
1
1
  import type * as codecs from '@astrale-os/kernel-protocol/codecs';
2
+ import { type Level } from '@astrale-os/kernel-core/wire';
2
3
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
4
  import type { ControlledSignal } from '../index.js';
4
5
  import type { TransportResult } from '../index.js';
@@ -15,18 +16,22 @@ export declare class WebSocketConnection implements ExchangeOwner {
15
16
  private readonly maximumResponseBytes;
16
17
  private readonly maximumBufferedBytes;
17
18
  private readonly maximumActiveInvocations;
19
+ private readonly levels;
18
20
  private readonly socket;
19
21
  private readonly ready;
20
22
  private resolveReady;
21
23
  private rejectReady;
22
24
  private opened;
23
25
  private closedState;
26
+ private selected;
24
27
  private readonly active;
25
28
  private readonly cancelled;
26
29
  private incoming;
27
- constructor(owner: ConnectionOwner, WebSocketConstructor: WebSocketConstructor, url: string, codec: codecs.Codec, maximumRequestBytes: number, maximumResponseBytes: number, maximumBufferedBytes: number, maximumActiveInvocations: number);
30
+ constructor(owner: ConnectionOwner, WebSocketConstructor: WebSocketConstructor, url: string, codec: codecs.Codec, maximumRequestBytes: number, maximumResponseBytes: number, maximumBufferedBytes: number, maximumActiveInvocations: number, levels: protocol.Levels);
28
31
  get isOpen(): boolean;
29
32
  get isAvailable(): boolean;
33
+ /** The wire level the Host selected for every message of this connection. */
34
+ get level(): Level;
30
35
  connect(control: ControlledSignal): Promise<void>;
31
36
  dispatch(request: protocol.Request, control: ControlledSignal, maximumBufferedItems: number): Promise<TransportResult>;
32
37
  finish(exchange: WebSocketExchange, close?: ExchangeClose): void;
@@ -1,3 +1,4 @@
1
+ import { Levels } from '@astrale-os/kernel-core/wire';
1
2
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
2
3
  import { ProtocolError } from '../../errors/index.js';
3
4
  import { invocationFailure } from '../failure.js';
@@ -12,27 +13,32 @@ export class WebSocketConnection {
12
13
  maximumResponseBytes;
13
14
  maximumBufferedBytes;
14
15
  maximumActiveInvocations;
16
+ levels;
15
17
  socket;
16
18
  ready;
17
19
  resolveReady;
18
20
  rejectReady;
19
21
  opened = false;
20
22
  closedState = false;
23
+ selected;
21
24
  active = new Map();
22
25
  cancelled = new Set();
23
26
  incoming = Promise.resolve();
24
- constructor(owner, WebSocketConstructor, url, codec, maximumRequestBytes, maximumResponseBytes, maximumBufferedBytes, maximumActiveInvocations) {
27
+ constructor(owner, WebSocketConstructor, url, codec, maximumRequestBytes, maximumResponseBytes, maximumBufferedBytes, maximumActiveInvocations, levels) {
25
28
  this.owner = owner;
26
29
  this.codec = codec;
27
30
  this.maximumRequestBytes = maximumRequestBytes;
28
31
  this.maximumResponseBytes = maximumResponseBytes;
29
32
  this.maximumBufferedBytes = maximumBufferedBytes;
30
33
  this.maximumActiveInvocations = maximumActiveInvocations;
34
+ this.levels = levels;
31
35
  this.ready = new Promise((resolve, reject) => {
32
36
  this.resolveReady = resolve;
33
37
  this.rejectReady = reject;
34
38
  });
35
- this.socket = new WebSocketConstructor(url, protocol.websocket.subprotocolFor(codec));
39
+ // A client at level 0 offers the one plain token, as it always has.
40
+ const offer = protocol.websocket.offerFor(codec, levels);
41
+ this.socket = new WebSocketConstructor(url, offer.length === 1 ? offer[0] : [...offer]);
36
42
  this.socket.binaryType = 'arraybuffer';
37
43
  this.socket.addEventListener('open', () => this.onOpen(), { once: true });
38
44
  this.socket.addEventListener('message', (event) => this.onMessage(event));
@@ -45,6 +51,12 @@ export class WebSocketConnection {
45
51
  get isAvailable() {
46
52
  return !this.closedState;
47
53
  }
54
+ /** The wire level the Host selected for every message of this connection. */
55
+ get level() {
56
+ if (this.selected === undefined)
57
+ throw new TypeError('WebSocket connection is not open.');
58
+ return this.selected;
59
+ }
48
60
  async connect(control) {
49
61
  requireLive(control);
50
62
  let abort;
@@ -149,15 +161,19 @@ export class WebSocketConnection {
149
161
  onOpen() {
150
162
  if (this.closedState)
151
163
  return;
152
- const expected = protocol.websocket.subprotocolFor(this.codec);
153
- if (this.socket.protocol !== expected) {
164
+ // The Host selects one of the offered tokens: a level this client reads.
165
+ // A Workers socket that selected none reports `null`.
166
+ const level = protocol.websocket.subprotocolLevel(this.socket.protocol ?? '', this.codec);
167
+ if (level === undefined || !Levels.includes(this.levels, level)) {
168
+ const expected = protocol.websocket.offerFor(this.codec, this.levels);
154
169
  this.end({
155
170
  code: 1002,
156
171
  reason: 'Subprotocol mismatch',
157
- error: invocationFailure(`server selected WebSocket subprotocol ${JSON.stringify(this.socket.protocol)}; expected ${JSON.stringify(expected)}.`, 'connect'),
172
+ error: invocationFailure(`server selected WebSocket subprotocol ${JSON.stringify(this.socket.protocol)}; expected ${expected.map((token) => JSON.stringify(token)).join(' or ')}.`, 'connect'),
158
173
  });
159
174
  return;
160
175
  }
176
+ this.selected = level;
161
177
  this.opened = true;
162
178
  this.resolveReady();
163
179
  }
@@ -1,3 +1,4 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
1
2
  import type * as protocol from '@astrale-os/kernel-protocol/invocation';
2
3
  import type { ControlledSignal } from '../index.js';
3
4
  import type { TransportResult } from '../index.js';
@@ -7,6 +8,8 @@ export interface ExchangeOwner {
7
8
  /** Frees the exchange's slot; `close` ends the connection, which is otherwise reusable. */
8
9
  finish(exchange: WebSocketExchange, close?: ExchangeClose): void;
9
10
  cancel(exchange: WebSocketExchange, requestId: protocol.RequestId): void;
11
+ /** The wire level the selected subprotocol fixed for the connection. */
12
+ readonly level: Level;
10
13
  }
11
14
  export type WebSocketInbound = protocol.BinaryResponse | protocol.RedirectResponse | protocol.Stale | protocol.Miss | protocol.Response | protocol.StreamFrame;
12
15
  /** One correlated invocation within a multiplexed WebSocket connection. */
@@ -2,6 +2,7 @@ import * as errors from '@astrale-os/kernel-protocol/errors';
2
2
  import { ProtocolError, ResponseError } from '../../errors/index.js';
3
3
  import { abortFailure, invocationFailure, withInvocation } from '../failure.js';
4
4
  import { asError } from '../index.js';
5
+ import { served } from '../level.js';
5
6
  import { FrameStream } from '../stream.js';
6
7
  import { responseError, unaryResult } from '../unary.js';
7
8
  /** One correlated invocation within a multiplexed WebSocket connection. */
@@ -101,13 +102,14 @@ export class WebSocketExchange {
101
102
  }
102
103
  const stream = new FrameStream(input.invocation, { cancel: async () => this.cancel() }, this.maximumBufferedItems);
103
104
  this.phase = { kind: 'stream', stream };
104
- this.resolveResult({ kind: 'stream', stream, invocation: input.invocation });
105
+ this.resolveResult(served({ kind: 'stream', stream, invocation: input.invocation }, this.owner.level));
105
106
  return;
106
107
  }
107
108
  const response = input;
108
109
  requireId(this.requestId, response.requestId);
109
- if ('error' in response)
110
- this.reject(responseError(response.error, response.invocation));
110
+ if ('error' in response) {
111
+ this.reject(responseError(response.error, response.invocation, this.owner.level));
112
+ }
111
113
  else
112
114
  this.complete(unaryResult(response));
113
115
  }
@@ -141,7 +143,7 @@ export class WebSocketExchange {
141
143
  }
142
144
  complete(result) {
143
145
  this.finish({ kind: 'reuse' });
144
- this.resolveResult(result);
146
+ this.resolveResult(served(result, this.owner.level));
145
147
  }
146
148
  reject(error) {
147
149
  this.finish({ kind: 'reuse' });
@@ -1,3 +1,5 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
2
+ import * as protocol from '@astrale-os/kernel-protocol/invocation';
1
3
  import type { RequestOptions, Transport, TransportRequest, TransportResult } from '../index.js';
2
4
  /** Web-compatible WebSocket constructor used by the built-in WebSocket transport. */
3
5
  export type WebSocketConstructor = new (url: string | URL, protocols?: string | string[]) => WebSocket;
@@ -16,18 +18,24 @@ export interface WebSocketTransportOptions {
16
18
  readonly maximumActiveInvocations?: number;
17
19
  /** Maximum decoded items retained while a stream consumer is slower than the socket. */
18
20
  readonly maximumBufferedStreamItems?: number;
21
+ /**
22
+ * The wire History whose levels the transport offers, its current level first; absent, the
23
+ * Invocation History of this build.
24
+ */
25
+ readonly levels?: protocol.Levels;
19
26
  }
20
27
  /** WebSocket implementation of the universal invocation protocol. */
21
28
  export declare class WebSocketTransport implements Transport {
22
29
  readonly url: string;
23
30
  private readonly connectionUrl;
24
31
  private readonly WebSocketConstructor;
25
- private readonly timeoutMs;
32
+ readonly timeoutMs: number;
26
33
  private readonly maximumRequestBytes;
27
34
  private readonly maximumResponseBytes;
28
35
  private readonly maximumBufferedBytes;
29
36
  private readonly maximumActiveInvocations;
30
37
  private readonly maximumBufferedStreamItems;
38
+ private readonly levels;
31
39
  private readonly connections;
32
40
  private readonly connectionOwner;
33
41
  private connection;
@@ -35,8 +43,18 @@ export declare class WebSocketTransport implements Transport {
35
43
  private nextId;
36
44
  constructor(options: WebSocketTransportOptions);
37
45
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
46
+ /**
47
+ * The wire level of the connection, which its subprotocol fixed for every message: it connects
48
+ * when no connection is open, within the deadline of `options`.
49
+ */
50
+ fixed(options?: RequestOptions): Promise<Level>;
38
51
  /** Close the multiplexed connection, reject active exchanges, and reject future dispatches. */
39
52
  close(): void;
53
+ /**
54
+ * What a call fails with when connecting, or writing to the connection, threw `error`: a failure
55
+ * to connect, which sent nothing, unless the connection and its exchange already judged it.
56
+ */
57
+ private failure;
40
58
  private connectionClosed;
41
59
  private acquire;
42
60
  private nextRequestId;
@@ -3,6 +3,7 @@ import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
3
  import { TransportError } from '../../errors/index.js';
4
4
  import { invocationFailure, requestFailure } from '../failure.js';
5
5
  import { asError, controlledSignal, positiveInteger, requireLive } from '../index.js';
6
+ import { captureLevels, ConnectionMoved, writtenLevel } from '../level.js';
6
7
  import { WebSocketConnection } from './connection.js';
7
8
  const DEFAULT_TIMEOUT_MS = 30_000;
8
9
  const DEFAULT_MAXIMUM_REQUEST_BYTES = 16 * 1024 * 1024;
@@ -21,6 +22,7 @@ export class WebSocketTransport {
21
22
  maximumBufferedBytes;
22
23
  maximumActiveInvocations;
23
24
  maximumBufferedStreamItems;
25
+ levels;
24
26
  connections = new Set();
25
27
  connectionOwner = Object.freeze({
26
28
  closed: (connection) => this.connectionClosed(connection),
@@ -41,6 +43,7 @@ export class WebSocketTransport {
41
43
  this.maximumBufferedBytes = positiveInteger(options.maximumBufferedBytes ?? DEFAULT_MAXIMUM_BUFFERED_BYTES, 'maximumBufferedBytes');
42
44
  this.maximumActiveInvocations = positiveInteger(options.maximumActiveInvocations ?? DEFAULT_MAXIMUM_ACTIVE_INVOCATIONS, 'maximumActiveInvocations');
43
45
  this.maximumBufferedStreamItems = positiveInteger(options.maximumBufferedStreamItems ?? DEFAULT_MAXIMUM_BUFFERED_STREAM_ITEMS, 'maximumBufferedStreamItems');
46
+ this.levels = captureLevels(options.levels);
44
47
  }
45
48
  async dispatch(input, options = {}) {
46
49
  if (this.stopped) {
@@ -48,10 +51,12 @@ export class WebSocketTransport {
48
51
  }
49
52
  const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
50
53
  const codec = codecs.json;
54
+ const { level, ...invocationInput } = input;
55
+ const written = writtenLevel(level, this.levels);
51
56
  const request = protocol.decodeRequest({
52
57
  version: protocol.VERSION,
53
58
  requestId: this.nextRequestId(),
54
- ...input,
59
+ ...invocationInput,
55
60
  ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
56
61
  });
57
62
  const control = controlledSignal(options.signal, timeoutMs);
@@ -60,25 +65,42 @@ export class WebSocketTransport {
60
65
  requireLive(control);
61
66
  const connection = await this.acquire(control, codec);
62
67
  requireLive(control);
68
+ // The subprotocol fixed the level of every message. The request was written for the level
69
+ // this Transport told: a connection made again at another level does not carry it.
70
+ if (connection.level !== written)
71
+ throw new ConnectionMoved(connection.level);
63
72
  owned = true;
64
73
  return await connection.dispatch(request, control, this.maximumBufferedStreamItems);
65
74
  }
66
75
  catch (error) {
67
- // The connection and its exchange already judged their own failures, deadline included.
68
- if (error instanceof TransportError)
69
- throw error;
70
- throw requestFailure(error, control, {
71
- phase: 'connect',
72
- delivery: 'not-sent',
73
- timeout: `WebSocket invocation timed out after ${timeoutMs}ms.`,
74
- failure: `Failed to communicate with the server at ${this.url}.`,
75
- });
76
+ throw this.failure(error, control, timeoutMs);
76
77
  }
77
78
  finally {
78
79
  if (!owned)
79
80
  control.close();
80
81
  }
81
82
  }
83
+ /**
84
+ * The wire level of the connection, which its subprotocol fixed for every message: it connects
85
+ * when no connection is open, within the deadline of `options`.
86
+ */
87
+ async fixed(options = {}) {
88
+ if (this.stopped) {
89
+ throw invocationFailure('WebSocketTransport is closed.', 'closed');
90
+ }
91
+ const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
92
+ const control = controlledSignal(options.signal, timeoutMs);
93
+ try {
94
+ requireLive(control);
95
+ return (await this.acquire(control, codecs.json)).level;
96
+ }
97
+ catch (error) {
98
+ throw this.failure(error, control, timeoutMs);
99
+ }
100
+ finally {
101
+ control.close();
102
+ }
103
+ }
82
104
  /** Close the multiplexed connection, reject active exchanges, and reject future dispatches. */
83
105
  close() {
84
106
  if (this.stopped)
@@ -89,6 +111,21 @@ export class WebSocketTransport {
89
111
  for (const connection of this.connections)
90
112
  connection.shutdown(failure);
91
113
  }
114
+ /**
115
+ * What a call fails with when connecting, or writing to the connection, threw `error`: a failure
116
+ * to connect, which sent nothing, unless the connection and its exchange already judged it.
117
+ */
118
+ failure(error, control, timeoutMs) {
119
+ // The connection and its exchange already judged their own failures, deadline included.
120
+ if (error instanceof TransportError || error instanceof ConnectionMoved)
121
+ return error;
122
+ return requestFailure(error, control, {
123
+ phase: 'connect',
124
+ delivery: 'not-sent',
125
+ timeout: `WebSocket invocation timed out after ${timeoutMs}ms.`,
126
+ failure: `Failed to communicate with the server at ${this.url}.`,
127
+ });
128
+ }
92
129
  connectionClosed(connection) {
93
130
  this.connections.delete(connection);
94
131
  if (this.connection === connection)
@@ -97,7 +134,7 @@ export class WebSocketTransport {
97
134
  async acquire(control, codec) {
98
135
  let connection = this.connection;
99
136
  if (connection === undefined || !connection.isAvailable) {
100
- connection = new WebSocketConnection(this.connectionOwner, this.WebSocketConstructor, this.connectionUrl, codec, this.maximumRequestBytes, this.maximumResponseBytes, this.maximumBufferedBytes, this.maximumActiveInvocations);
137
+ connection = new WebSocketConnection(this.connectionOwner, this.WebSocketConstructor, this.connectionUrl, codec, this.maximumRequestBytes, this.maximumResponseBytes, this.maximumBufferedBytes, this.maximumActiveInvocations, this.levels);
101
138
  this.connection = connection;
102
139
  this.connections.add(connection);
103
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-client",
3
- "version": "1.0.0-beta.45",
3
+ "version": "1.0.0-beta.47",
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.42",
69
- "@astrale-os/kernel-dsl": "1.0.0-beta.30",
70
- "@astrale-os/kernel-protocol": "1.0.0-beta.42",
68
+ "@astrale-os/kernel-core": "1.0.0-beta.44",
69
+ "@astrale-os/kernel-dsl": "1.0.0-beta.32",
70
+ "@astrale-os/kernel-protocol": "1.0.0-beta.44",
71
71
  "@tanstack/pacer": "0.20.1"
72
72
  },
73
73
  "devDependencies": {
74
- "@astrale-os/kernel-server": "1.0.0-beta.42",
74
+ "@astrale-os/kernel-server": "1.0.0-beta.44",
75
75
  "@astrale/typescript-config": "npm:@jsr/astrale__typescript-config@~1.1.0",
76
76
  "@types/node": "^24.10.0",
77
77
  "esbuild": "0.28.1",