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

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 (37) hide show
  1. package/dist/client/client.d.ts +51 -2
  2. package/dist/client/client.js +158 -13
  3. package/dist/client/level.d.ts +58 -0
  4. package/dist/client/level.js +159 -0
  5. package/dist/client/result.d.ts +4 -0
  6. package/dist/client/result.js +10 -5
  7. package/dist/errors/index.d.ts +1 -0
  8. package/dist/errors/index.js +1 -0
  9. package/dist/errors/inexpressible-error.d.ts +23 -0
  10. package/dist/errors/inexpressible-error.js +26 -0
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/transport/auto/decision.d.ts +2 -0
  14. package/dist/transport/auto/decision.js +4 -0
  15. package/dist/transport/auto/transport.d.ts +10 -1
  16. package/dist/transport/auto/transport.js +17 -0
  17. package/dist/transport/http/admission.js +3 -3
  18. package/dist/transport/http/configuration.d.ts +7 -0
  19. package/dist/transport/http/configuration.js +2 -0
  20. package/dist/transport/http/response.d.ts +10 -0
  21. package/dist/transport/http/response.js +15 -0
  22. package/dist/transport/http/transport.d.ts +4 -1
  23. package/dist/transport/http/transport.js +25 -5
  24. package/dist/transport/index.d.ts +1 -0
  25. package/dist/transport/index.js +1 -0
  26. package/dist/transport/level.d.ts +42 -0
  27. package/dist/transport/level.js +58 -0
  28. package/dist/transport/transport.d.ts +33 -0
  29. package/dist/transport/unary.d.ts +2 -1
  30. package/dist/transport/unary.js +4 -2
  31. package/dist/transport/websocket/connection.d.ts +6 -1
  32. package/dist/transport/websocket/connection.js +21 -5
  33. package/dist/transport/websocket/exchange.d.ts +3 -0
  34. package/dist/transport/websocket/exchange.js +6 -4
  35. package/dist/transport/websocket/transport.d.ts +19 -1
  36. package/dist/transport/websocket/transport.js +48 -11
  37. package/package.json +5 -5
@@ -1,4 +1,5 @@
1
- import type { invocation as protocol } from '@astrale-os/kernel-protocol';
1
+ import type { History, Level } from '@astrale-os/kernel-core/wire';
2
+ import { invocation as protocol } from '@astrale-os/kernel-protocol';
2
3
  import type { BinaryBody } from '../transport/http/binary-request.js';
3
4
  import type { Transport } from '../transport/index.js';
4
5
  import type { AuthenticatedClient, RemoteCredential } from './credential.js';
@@ -6,8 +7,14 @@ import type { Call, ClientDispatchOptions, ClientDispatchOptionsWithBody } from
6
7
  import type { BinaryResponse, Result, StreamResult, ValueResult } from './result.js';
7
8
  import type { RoutingControl } from './routing-control.js';
8
9
  import { type HttpTransportOptions } from '../transport/http/index.js';
9
- export type ClientOptions = HttpTransportOptions | {
10
+ export type ClientOptions = (HttpTransportOptions | {
10
11
  readonly transport: Transport;
12
+ }) & {
13
+ /**
14
+ * The wire History this Client converts under: it lowers a request for a Host behind it and
15
+ * raises what such a Host answers. Absent, the Invocation History of this build.
16
+ */
17
+ readonly levels?: History;
11
18
  };
12
19
  /** One package-private send: the Trace of a redirect continuation and an admitted body, if any. */
13
20
  export interface InternalDispatch {
@@ -28,6 +35,15 @@ export declare function dispatchInternal(client: Client, dispatch: InternalDispa
28
35
  export declare class Client implements AuthenticatedClient {
29
36
  private readonly transport;
30
37
  private readonly lifecycle;
38
+ private readonly levels;
39
+ /** The wire level of the Host, as its last response told it. */
40
+ private heard;
41
+ /**
42
+ * The level of a Host heard below the floor of this build. It is set once and nothing clears it:
43
+ * a call in flight may still be answered by another Host of the fleet, and this Client sends
44
+ * nothing more whatever that answer tells.
45
+ */
46
+ private below;
31
47
  private closed;
32
48
  constructor(options: ClientOptions);
33
49
  dispatch(call: Call, options?: ClientDispatchOptions): Promise<Result>;
@@ -37,8 +53,41 @@ export declare class Client implements AuthenticatedClient {
37
53
  stream(call: Call, options?: ClientDispatchOptions): Promise<StreamResult>;
38
54
  binary(call: Call, options?: ClientDispatchOptions): Promise<BinaryResponse>;
39
55
  as(credential: RemoteCredential): AuthenticatedClient;
56
+ /**
57
+ * The wire level of the Host as its last response told it, an error it answered included, and
58
+ * at most this build's; undefined before any. Below this build's level, the Host does not state
59
+ * what later changes added. A Client that heard a Host below its floor sends nothing more,
60
+ * whatever a later answer makes of this level.
61
+ */
62
+ level(): Level | undefined;
40
63
  close(): void;
41
64
  /** The public path: routing control is reported as the error every Client raises for it. */
42
65
  private dispatchWith;
43
66
  private dispatchRouted;
67
+ /**
68
+ * Send one envelope written for the level its Host reads. A Transport whose connection fixes a
69
+ * level tells it first, and the request is written for it before anything is sent. Otherwise the
70
+ * level last heard is a hint, the Host judges, and the request is written once more, at most,
71
+ * when a Host below refused it at admission, before any effect, and its level expresses it. A
72
+ * body that cannot be read twice is never sent again. Every entry of the Transport for one call
73
+ * shares one deadline.
74
+ */
75
+ private send;
76
+ /**
77
+ * Take the level a Host told, or the one a connection is fixed at. One below the floor of this
78
+ * build is kept for good: no later answer makes this Client send again.
79
+ */
80
+ private hear;
81
+ /**
82
+ * `envelope` as it is written for its Host: for the level of a connection that fixes one, else for
83
+ * the level last heard. A connection fixed below the floor of this build is given nothing.
84
+ */
85
+ private write;
86
+ /**
87
+ * The options of a later entry of the Transport for one call: what is left of the deadline its
88
+ * first entry started, which is the caller's or, when the caller names none, the Transport's.
89
+ * When nothing is left the request is not given to the Transport: the call timed out, with
90
+ * `cause` as what answered its earlier entry and `delivery` as whether that entry was sent.
91
+ */
92
+ private remaining;
44
93
  }
@@ -1,9 +1,12 @@
1
- import { ClientError } from '../errors/index.js';
1
+ import { invocation as protocol } from '@astrale-os/kernel-protocol';
2
+ import { ClientError, InexpressibleError, TransportError } from '../errors/index.js';
2
3
  import { cancelUnsent } from '../transport/http/binary-request.js';
3
4
  import { dispatchBinaryBody, HttpTransport, } from '../transport/http/index.js';
5
+ import { ConnectionMoved, servedOf } from '../transport/level.js';
4
6
  import { authenticated, resolveCredential } from './credential.js';
7
+ import { afterRefusal, belowFloor, connectionLevel, heardFrom, heardFromFailure, levelWithin, raised, written, writtenAt, } from './level.js';
5
8
  import { admitRequest, invocation } from './request.js';
6
- import { requireBinary, requireStream, requireValue } from './result.js';
9
+ import { release, requireBinary, requireStream, requireValue } from './result.js';
7
10
  import { isRoutingControl, raisedRoutingControl, routingControlError } from './routing-control.js';
8
11
  const controlledDispatch = new WeakMap();
9
12
  /**
@@ -40,11 +43,21 @@ async function dispatchPublic(client, { credential, call, options }) {
40
43
  export class Client {
41
44
  transport;
42
45
  lifecycle = new AbortController();
46
+ levels;
47
+ /** The wire level of the Host, as its last response told it. */
48
+ heard;
49
+ /**
50
+ * The level of a Host heard below the floor of this build. It is set once and nothing clears it:
51
+ * a call in flight may still be answered by another Host of the fleet, and this Client sends
52
+ * nothing more whatever that answer tells.
53
+ */
54
+ below;
43
55
  closed = false;
44
56
  constructor(options) {
45
57
  if (options === null || typeof options !== 'object') {
46
58
  throw new TypeError('Client options must be an object.');
47
59
  }
60
+ this.levels = options.levels ?? protocol.history;
48
61
  this.transport = Object.hasOwn(options, 'transport')
49
62
  ? admitTransport(options.transport)
50
63
  : new HttpTransport(options);
@@ -65,6 +78,15 @@ export class Client {
65
78
  as(credential) {
66
79
  return authenticated((bound, request, options) => this.dispatchWith(bound, request, options), credential);
67
80
  }
81
+ /**
82
+ * The wire level of the Host as its last response told it, an error it answered included, and
83
+ * at most this build's; undefined before any. Below this build's level, the Host does not state
84
+ * what later changes added. A Client that heard a Host below its floor sends nothing more,
85
+ * whatever a later answer makes of this level.
86
+ */
87
+ level() {
88
+ return this.heard;
89
+ }
68
90
  close() {
69
91
  if (this.closed)
70
92
  return;
@@ -84,30 +106,144 @@ export class Client {
84
106
  if (this.closed)
85
107
  throw new ClientError('Client is closed.');
86
108
  const request = admitRequest(input, options, this.lifecycle.signal, body);
109
+ const levels = this.levels;
87
110
  let result;
88
111
  try {
89
112
  const resolved = credential === undefined
90
113
  ? undefined
91
114
  : await resolveCredential(credential, request.options.signal);
92
115
  requireRequestLive(request.options.signal);
93
- const envelope = invocation(request, resolved, trace);
94
- if (request.body === undefined) {
95
- result = await this.transport.dispatch(envelope, request.options);
96
- }
97
- else {
116
+ result = await this.send(request, invocation(request, resolved, trace));
117
+ }
118
+ catch (cause) {
119
+ // A stream body this request never started to send is cancelled with it.
120
+ cancelUnsent(request.body);
121
+ throw cause;
122
+ }
123
+ // Each response is read at the level it is written at, never at a remembered one.
124
+ const answer = servedOf(result);
125
+ this.hear(heardFrom(levels, answer));
126
+ if (answer.written < levels.floor) {
127
+ // What the call did stays done. Its answer is not read, and what it handed off is released.
128
+ this.below ??= answer.written;
129
+ await release(result, 'The server answers below the wire floor of this client.');
130
+ throw belowFloor(levels, answer.host, true);
131
+ }
132
+ const level = levelWithin(levels, answer);
133
+ if (level === levels.current || result.kind !== 'value')
134
+ return result;
135
+ const value = raised(levels, level, request.call, result.value);
136
+ return value === result.value ? result : Object.freeze({ ...result, value });
137
+ }
138
+ /**
139
+ * Send one envelope written for the level its Host reads. A Transport whose connection fixes a
140
+ * level tells it first, and the request is written for it before anything is sent. Otherwise the
141
+ * level last heard is a hint, the Host judges, and the request is written once more, at most,
142
+ * when a Host below refused it at admission, before any effect, and its level expresses it. A
143
+ * body that cannot be read twice is never sent again. Every entry of the Transport for one call
144
+ * shares one deadline.
145
+ */
146
+ async send(request, envelope) {
147
+ const levels = this.levels;
148
+ // A Host heard below the floor is sent nothing, and its Transport is not asked to connect.
149
+ if (this.below !== undefined)
150
+ throw belowFloor(levels, this.below, false);
151
+ const started = Date.now();
152
+ const told = await this.transport.fixed?.(request.options);
153
+ const fixed = told === undefined ? undefined : connectionLevel(levels, told);
154
+ let sent = this.write(envelope, fixed);
155
+ // Connecting is part of the call, whether or not the connection fixes a level: its first entry
156
+ // runs within what is left of its deadline. A Transport that is asked nothing spent none of it.
157
+ let options = this.transport.fixed === undefined
158
+ ? request.options
159
+ : this.remaining(request.options, started, 'not-sent');
160
+ let moved = false;
161
+ let again = false;
162
+ for (;;) {
163
+ try {
164
+ if (request.body === undefined) {
165
+ return await this.transport.dispatch(sent, options);
166
+ }
98
167
  const transport = this.transport;
99
168
  if (!(transport instanceof HttpTransport)) {
100
169
  throw new TypeError('Binary dispatch requires HTTP transport.');
101
170
  }
102
- result = await dispatchBinaryBody(transport, envelope, request.body, request.options);
171
+ return await dispatchBinaryBody(transport, sent, request.body, options);
172
+ }
173
+ catch (cause) {
174
+ if (cause instanceof ConnectionMoved) {
175
+ // The connection was made again at another level after it told its own: nothing was
176
+ // sent. The request is written for the level it is at now, once.
177
+ if (moved) {
178
+ throw TransportError.invocation('The connection changed wire level again before the request was sent.', { phase: 'send', delivery: 'not-sent', cause });
179
+ }
180
+ moved = true;
181
+ sent = this.write(envelope, connectionLevel(levels, cause.level));
182
+ options = this.remaining(request.options, started, 'not-sent', cause);
183
+ }
184
+ else {
185
+ const host = heardFromFailure(levels, cause);
186
+ if (host !== undefined)
187
+ this.hear(host);
188
+ const next = afterRefusal(levels, envelope, sent, cause);
189
+ if (next === undefined)
190
+ throw cause;
191
+ if (next instanceof InexpressibleError)
192
+ throw next;
193
+ if (again || fixed !== undefined || moved || request.body?.kind === 'once')
194
+ throw cause;
195
+ again = true;
196
+ sent = next;
197
+ // The request crossed the wire once and its Host refused it: that refusal is the cause
198
+ // of a call whose deadline leaves no time to send it again.
199
+ options = this.remaining(request.options, started, 'unknown', cause);
200
+ }
103
201
  }
104
202
  }
105
- catch (cause) {
106
- // A stream body this request never started to send is cancelled with it.
107
- cancelUnsent(request.body);
108
- throw cause;
203
+ }
204
+ /**
205
+ * Take the level a Host told, or the one a connection is fixed at. One below the floor of this
206
+ * build is kept for good: no later answer makes this Client send again.
207
+ */
208
+ hear(level) {
209
+ this.heard = level;
210
+ if (level < this.levels.floor)
211
+ this.below ??= level;
212
+ }
213
+ /**
214
+ * `envelope` as it is written for its Host: for the level of a connection that fixes one, else for
215
+ * the level last heard. A connection fixed below the floor of this build is given nothing.
216
+ */
217
+ write(envelope, fixed) {
218
+ const levels = this.levels;
219
+ if (fixed === undefined)
220
+ return written(levels, this.heard, envelope);
221
+ this.hear(fixed);
222
+ if (fixed < levels.floor)
223
+ throw belowFloor(levels, fixed, false);
224
+ return writtenAt(levels, fixed, envelope);
225
+ }
226
+ /**
227
+ * The options of a later entry of the Transport for one call: what is left of the deadline its
228
+ * first entry started, which is the caller's or, when the caller names none, the Transport's.
229
+ * When nothing is left the request is not given to the Transport: the call timed out, with
230
+ * `cause` as what answered its earlier entry and `delivery` as whether that entry was sent.
231
+ */
232
+ remaining(options, started, delivery, cause) {
233
+ const deadline = options.timeoutMs ?? this.transport.timeoutMs;
234
+ if (deadline === undefined)
235
+ return options;
236
+ const elapsed = Date.now() - started;
237
+ if (elapsed <= 0)
238
+ return options;
239
+ if (elapsed >= deadline) {
240
+ throw TransportError.invocation(`request timed out after ${deadline}ms.`, {
241
+ phase: 'timeout',
242
+ delivery,
243
+ ...(cause === undefined ? {} : { cause }),
244
+ });
109
245
  }
110
- return result;
246
+ return { ...options, timeoutMs: deadline - elapsed };
111
247
  }
112
248
  }
113
249
  function requireRequestLive(signal) {
@@ -130,8 +266,17 @@ function admitTransport(input) {
130
266
  if (close !== undefined && typeof close !== 'function') {
131
267
  throw new TypeError('Client transport close capability is invalid.');
132
268
  }
269
+ const fixed = input.fixed;
270
+ if (fixed !== undefined && typeof fixed !== 'function') {
271
+ throw new TypeError('Client transport fixed capability is invalid.');
272
+ }
273
+ const timeoutMs = input.timeoutMs;
133
274
  return Object.freeze({
134
275
  dispatch: dispatch.bind(input),
276
+ ...(fixed === undefined ? {} : { fixed: fixed.bind(input) }),
277
+ ...(typeof timeoutMs === 'number' && Number.isSafeInteger(timeoutMs) && timeoutMs > 0
278
+ ? { timeoutMs }
279
+ : {}),
135
280
  ...(close === undefined ? {} : { close: close.bind(input) }),
136
281
  });
137
282
  }
@@ -0,0 +1,58 @@
1
+ import type { Value } from '@astrale-os/kernel-dsl/value';
2
+ import type * as protocol from '@astrale-os/kernel-protocol/invocation';
3
+ import { type History, type Level } from '@astrale-os/kernel-core/wire';
4
+ import type { TransportRequest } from '../transport/index.js';
5
+ import { InexpressibleError, ProtocolError } from '../errors/index.js';
6
+ import { type Served } from '../transport/level.js';
7
+ /**
8
+ * The request as it is sent to a Host last heard at `heard`: written for that level, and stating
9
+ * it, when the level reads the call differently; the same request otherwise, which states this
10
+ * build's level and so asks the Host again for its own. A call that level cannot express is sent as
11
+ * this build writes it: a level heard earlier is no proof of what the Host reads now, and a Host
12
+ * below refuses the call before any effect.
13
+ */
14
+ export declare function written(levels: History, heard: Level | undefined, request: TransportRequest): TransportRequest;
15
+ /**
16
+ * The request as it is sent on a connection fixed at `level`: written for that level and stating
17
+ * it. Throws `InexpressibleError`, before anything is sent, when that level cannot express the call.
18
+ */
19
+ export declare function writtenAt(levels: History, level: Level, request: TransportRequest): TransportRequest;
20
+ /**
21
+ * The wire level a Transport tells for its connection, as one this build writes at. A Transport is
22
+ * an injected capability: a value that is no wire level, or a level above this build's, is its
23
+ * defect, and nothing is sent. A level below the floor is a Host this build does not speak with,
24
+ * which its Client refuses (`belowFloor`).
25
+ */
26
+ export declare function connectionLevel(levels: History, told: unknown): Level;
27
+ /**
28
+ * The refusal of a Host below the floor of this build: it reads, and answers, a wire level this
29
+ * build converts neither to nor from.
30
+ */
31
+ export declare function belowFloor(levels: History, host: Level, sent: boolean): ProtocolError;
32
+ /**
33
+ * The wire level one answer is written at, as one this build reads. An answer written above this
34
+ * build's level is the protocol breach of a peer that names a level no request stated.
35
+ */
36
+ export declare function levelWithin(levels: History, answer: Served): Level;
37
+ /**
38
+ * The wire level of the Host that answered, as far as this build writes: what it told, and at most
39
+ * this build's own. A level below the floor is kept as it is: this build sends that Host nothing
40
+ * more.
41
+ */
42
+ export declare function heardFrom(levels: History, answer: Served): Level;
43
+ /**
44
+ * The value of a call's result as this build reads it, raised from the level it is written at. A
45
+ * value that level does not admit is the protocol breach of the Host that wrote it.
46
+ */
47
+ export declare function raised(levels: History, level: Level, call: protocol.Call, value: Value): Value;
48
+ /**
49
+ * What follows once `cause` answered `sent`: when a Host below refused `sent` at admission,
50
+ * `request` written for its level, or the `InexpressibleError`, with that refusal as its cause, when
51
+ * that level cannot express it; `undefined` for every other answer, which a call fails with as it is.
52
+ */
53
+ export declare function afterRefusal(levels: History, request: TransportRequest, sent: TransportRequest, cause: unknown): TransportRequest | InexpressibleError | undefined;
54
+ /**
55
+ * The wire level of the Host a failed call heard: the one the Host's own answer told. A failure
56
+ * that is no answer of a Host, a response that is no Invocation envelope included, tells none.
57
+ */
58
+ export declare function heardFromFailure(levels: History, cause: unknown): Level | undefined;
@@ -0,0 +1,159 @@
1
+ import { contractOf, targetCallable } from '@astrale-os/kernel-core/callable';
2
+ import { acceptLevel, Inexpressible, Unread, } from '@astrale-os/kernel-core/wire';
3
+ import * as errors from '@astrale-os/kernel-protocol/errors';
4
+ import { InexpressibleError, ProtocolError, ResponseError, TransportError, } from '../errors/index.js';
5
+ import { servedOf } from '../transport/level.js';
6
+ /**
7
+ * The wire contract a call's target names: that of the callable it spells, by the function a Host
8
+ * names the contract of the callable it resolved with. A target that spells none, and a callable
9
+ * no change names, are read the same at every level.
10
+ */
11
+ function contractOfTarget(target) {
12
+ const callable = targetCallable(target);
13
+ return callable === undefined ? undefined : contractOf(callable);
14
+ }
15
+ /**
16
+ * The request as it is sent to a Host last heard at `heard`: written for that level, and stating
17
+ * it, when the level reads the call differently; the same request otherwise, which states this
18
+ * build's level and so asks the Host again for its own. A call that level cannot express is sent as
19
+ * this build writes it: a level heard earlier is no proof of what the Host reads now, and a Host
20
+ * below refuses the call before any effect.
21
+ */
22
+ export function written(levels, heard, request) {
23
+ if (heard === undefined || heard === levels.current)
24
+ return request;
25
+ const input = lowered(levels, heard, request);
26
+ if (input instanceof Inexpressible || input === request.call.input)
27
+ return request;
28
+ return rewritten(request, input, heard);
29
+ }
30
+ /**
31
+ * The request as it is sent on a connection fixed at `level`: written for that level and stating
32
+ * it. Throws `InexpressibleError`, before anything is sent, when that level cannot express the call.
33
+ */
34
+ export function writtenAt(levels, level, request) {
35
+ if (level === levels.current)
36
+ return request;
37
+ const input = lowered(levels, level, request);
38
+ if (input instanceof Inexpressible) {
39
+ throw new InexpressibleError(input.change, input.level, level);
40
+ }
41
+ return rewritten(request, input, level);
42
+ }
43
+ /** The input of `request` as `level` reads it: the same input when its target names no contract. */
44
+ function lowered(levels, level, request) {
45
+ const contract = contractOfTarget(request.call.target);
46
+ return contract === undefined
47
+ ? request.call.input
48
+ : levels.request.lower(contract, level, request.call.input);
49
+ }
50
+ function rewritten(request, input, level) {
51
+ return Object.freeze({
52
+ ...request,
53
+ call: Object.freeze({ target: request.call.target, input }),
54
+ level,
55
+ });
56
+ }
57
+ /**
58
+ * The wire level a Transport tells for its connection, as one this build writes at. A Transport is
59
+ * an injected capability: a value that is no wire level, or a level above this build's, is its
60
+ * defect, and nothing is sent. A level below the floor is a Host this build does not speak with,
61
+ * which its Client refuses (`belowFloor`).
62
+ */
63
+ export function connectionLevel(levels, told) {
64
+ let level;
65
+ try {
66
+ level = acceptLevel(told);
67
+ }
68
+ catch (cause) {
69
+ throw TransportError.invocation('The transport told a connection level that is no wire level.', {
70
+ phase: 'connect',
71
+ delivery: 'not-sent',
72
+ cause,
73
+ });
74
+ }
75
+ if (level > levels.current) {
76
+ throw TransportError.invocation(`The transport told a connection at wire level ${level}; this client writes levels ` +
77
+ `${levels.floor} to ${levels.current}.`, { phase: 'connect', delivery: 'not-sent' });
78
+ }
79
+ return level;
80
+ }
81
+ /**
82
+ * The refusal of a Host below the floor of this build: it reads, and answers, a wire level this
83
+ * build converts neither to nor from.
84
+ */
85
+ export function belowFloor(levels, host, sent) {
86
+ return new ProtocolError(`server speaks wire level ${host}; this client reads levels ${levels.floor} to ${levels.current}` +
87
+ (sent ? '.' : ', and sent nothing.'));
88
+ }
89
+ /**
90
+ * The wire level one answer is written at, as one this build reads. An answer written above this
91
+ * build's level is the protocol breach of a peer that names a level no request stated.
92
+ */
93
+ export function levelWithin(levels, answer) {
94
+ if (answer.written > levels.current) {
95
+ throw new ProtocolError(`server answers at wire level ${answer.written}; this client reads levels ${levels.floor} to ${levels.current}.`);
96
+ }
97
+ return answer.written;
98
+ }
99
+ /**
100
+ * The wire level of the Host that answered, as far as this build writes: what it told, and at most
101
+ * this build's own. A level below the floor is kept as it is: this build sends that Host nothing
102
+ * more.
103
+ */
104
+ export function heardFrom(levels, answer) {
105
+ return answer.host > levels.current ? levels.current : answer.host;
106
+ }
107
+ /**
108
+ * The value of a call's result as this build reads it, raised from the level it is written at. A
109
+ * value that level does not admit is the protocol breach of the Host that wrote it.
110
+ */
111
+ export function raised(levels, level, call, value) {
112
+ const contract = contractOfTarget(call.target);
113
+ if (contract === undefined)
114
+ return value;
115
+ const read = levels.response.raise(contract, level, value);
116
+ if (read instanceof Unread) {
117
+ throw new ProtocolError(`server answered a value its wire level ${read.level} does not admit (${read.change}).`);
118
+ }
119
+ return read;
120
+ }
121
+ /**
122
+ * The level a Host below read `sent` at, when it refused it at admission: the Host answered that the
123
+ * input is invalid, at a level below the one `sent` is written at, whose shape does not admit it. A
124
+ * Host admits exactly the shape of its level before it runs anything, so nothing ran.
125
+ */
126
+ function unreadAt(levels, sent, cause) {
127
+ if (!(cause instanceof ResponseError) || cause.code !== errors.CODES.VALIDATION_ERROR) {
128
+ return undefined;
129
+ }
130
+ const level = servedOf(cause).written;
131
+ if (level >= (sent.level ?? levels.current) || level < levels.floor)
132
+ return undefined;
133
+ const contract = contractOfTarget(sent.call.target);
134
+ if (contract === undefined || levels.request.reads(contract, level, sent.call.input)) {
135
+ return undefined;
136
+ }
137
+ return level;
138
+ }
139
+ /**
140
+ * What follows once `cause` answered `sent`: when a Host below refused `sent` at admission,
141
+ * `request` written for its level, or the `InexpressibleError`, with that refusal as its cause, when
142
+ * that level cannot express it; `undefined` for every other answer, which a call fails with as it is.
143
+ */
144
+ export function afterRefusal(levels, request, sent, cause) {
145
+ const level = unreadAt(levels, sent, cause);
146
+ if (level === undefined)
147
+ return undefined;
148
+ const input = lowered(levels, level, request);
149
+ return input instanceof Inexpressible
150
+ ? new InexpressibleError(input.change, input.level, level, { cause })
151
+ : rewritten(request, input, level);
152
+ }
153
+ /**
154
+ * The wire level of the Host a failed call heard: the one the Host's own answer told. A failure
155
+ * that is no answer of a Host, a response that is no Invocation envelope included, tells none.
156
+ */
157
+ export function heardFromFailure(levels, cause) {
158
+ return cause instanceof ResponseError ? heardFrom(levels, servedOf(cause)) : undefined;
159
+ }
@@ -41,4 +41,8 @@ export type Result = ValueResult | StreamResult | BinaryResponse | ExecutionResu
41
41
  export declare function requireValue(result: Promise<Result>): Promise<ValueResult>;
42
42
  export declare function requireStream(result: Promise<Result>): Promise<StreamResult>;
43
43
  export declare function requireBinary(result: Promise<Result>): Promise<BinaryResponse>;
44
+ /** Release what a result its caller will not receive handed off: its stream, or its binary body. */
45
+ export declare function release(result: {
46
+ readonly kind: string;
47
+ }, reason: string): Promise<void>;
44
48
  export {};
@@ -27,11 +27,16 @@ function returned(result) {
27
27
  : `Function returned ${result.kind}`;
28
28
  }
29
29
  async function rejectMismatch(expected, result) {
30
- if (result.kind === 'stream') {
31
- await result.stream.cancel(`Expected ${expected} Function result.`).catch(() => undefined);
30
+ await release(result, `Expected ${expected} Function result.`);
31
+ mismatch(expected, result);
32
+ }
33
+ /** Release what a result its caller will not receive handed off: its stream, or its binary body. */
34
+ export async function release(result, reason) {
35
+ const held = result;
36
+ if (held.kind === 'stream') {
37
+ await held.stream.cancel(reason).catch(() => undefined);
32
38
  }
33
- if (result.kind === 'binary' && !(result.value.body instanceof Uint8Array)) {
34
- await result.value.body[Symbol.asyncIterator]().return?.();
39
+ if (held.kind === 'binary' && !(held.value.body instanceof Uint8Array)) {
40
+ await held.value.body[Symbol.asyncIterator]().return?.();
35
41
  }
36
- mismatch(expected, result);
37
42
  }
@@ -1,5 +1,6 @@
1
1
  export * from './client-error.js';
2
2
  export * from './exchange-error.js';
3
+ export * from './inexpressible-error.js';
3
4
  export * from './miss-error.js';
4
5
  export * from './protocol-error.js';
5
6
  export * from './query-input.js';
@@ -1,5 +1,6 @@
1
1
  export * from './client-error.js';
2
2
  export * from './exchange-error.js';
3
+ export * from './inexpressible-error.js';
3
4
  export * from './miss-error.js';
4
5
  export * from './protocol-error.js';
5
6
  export * from './query-input.js';
@@ -0,0 +1,23 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
2
+ import { ClientError } from './client-error.js';
3
+ /**
4
+ * A request the Host cannot express: it uses what a wire change above the Host's level introduced.
5
+ * The Client raises it in place of the refusal of a Host below, which is then its `cause`, and
6
+ * before sending on a connection fixed at a lower level. The Host ran nothing either way.
7
+ */
8
+ export declare class InexpressibleError extends ClientError {
9
+ /** The wire change that introduced what the request uses. */
10
+ readonly change: string;
11
+ /** The lowest wire level that expresses the request. */
12
+ readonly requiredLevel: Level;
13
+ /** The wire level the Host reads requests at. */
14
+ readonly hostLevel: Level;
15
+ readonly code: 4002;
16
+ constructor(
17
+ /** The wire change that introduced what the request uses. */
18
+ change: string,
19
+ /** The lowest wire level that expresses the request. */
20
+ requiredLevel: Level,
21
+ /** The wire level the Host reads requests at. */
22
+ hostLevel: Level, options?: ErrorOptions);
23
+ }
@@ -0,0 +1,26 @@
1
+ import * as errors from '@astrale-os/kernel-protocol/errors';
2
+ import { ClientError } from './client-error.js';
3
+ /**
4
+ * A request the Host cannot express: it uses what a wire change above the Host's level introduced.
5
+ * The Client raises it in place of the refusal of a Host below, which is then its `cause`, and
6
+ * before sending on a connection fixed at a lower level. The Host ran nothing either way.
7
+ */
8
+ export class InexpressibleError extends ClientError {
9
+ change;
10
+ requiredLevel;
11
+ hostLevel;
12
+ code = errors.CODES.UNSUPPORTED;
13
+ constructor(
14
+ /** The wire change that introduced what the request uses. */
15
+ change,
16
+ /** The lowest wire level that expresses the request. */
17
+ requiredLevel,
18
+ /** The wire level the Host reads requests at. */
19
+ hostLevel, options) {
20
+ super(`The server reads wire level ${hostLevel} and cannot express this request, which needs level ${requiredLevel} (${change}).`, options);
21
+ this.change = change;
22
+ this.requiredLevel = requiredLevel;
23
+ this.hostLevel = hostLevel;
24
+ this.name = 'InexpressibleError';
25
+ }
26
+ }
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';
@@ -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. */