@astrale-os/kernel-client 1.0.0-beta.2 → 1.0.0-beta.21

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 (82) hide show
  1. package/dist/client/index.d.ts +1 -1
  2. package/dist/client/request.d.ts +1 -0
  3. package/dist/client/request.js +17 -0
  4. package/dist/client/result.d.ts +10 -1
  5. package/dist/client/result.js +10 -4
  6. package/dist/errors/index.d.ts +1 -0
  7. package/dist/errors/index.js +1 -0
  8. package/dist/errors/refusal.d.ts +19 -0
  9. package/dist/errors/refusal.js +63 -0
  10. package/dist/{schema → execution}/admission.d.ts +2 -2
  11. package/dist/{schema → execution}/admission.js +3 -3
  12. package/dist/execution/contracts.d.ts +76 -0
  13. package/dist/execution/contracts.js +1 -0
  14. package/dist/execution/deadline.d.ts +8 -0
  15. package/dist/execution/deadline.js +13 -0
  16. package/dist/execution/execution.d.ts +57 -0
  17. package/dist/execution/execution.js +137 -0
  18. package/dist/execution/index.d.ts +4 -0
  19. package/dist/execution/index.js +3 -0
  20. package/dist/graph/domain/binding.js +24 -17
  21. package/dist/graph/domain/conformance.d.ts +12 -0
  22. package/dist/graph/domain/conformance.js +18 -0
  23. package/dist/graph/domain/index.d.ts +1 -0
  24. package/dist/graph/domain/index.js +1 -1
  25. package/dist/graph/domain/provenance.d.ts +0 -2
  26. package/dist/graph/domain/provenance.js +0 -4
  27. package/dist/graph/index.d.ts +1 -1
  28. package/dist/graph/index.js +1 -1
  29. package/dist/graph/page-contract.d.ts +6 -0
  30. package/dist/graph/provenance.d.ts +4 -5
  31. package/dist/graph/provenance.js +5 -6
  32. package/dist/graph/query.js +14 -5
  33. package/dist/pacer/index.d.ts +1 -1
  34. package/dist/pacer/index.js +1 -1
  35. package/dist/pacer/retry/index.d.ts +1 -0
  36. package/dist/pacer/retry/index.js +1 -0
  37. package/dist/pacer/retry/refusals.d.ts +7 -0
  38. package/dist/pacer/retry/refusals.js +10 -0
  39. package/dist/pacer/retry/retry.d.ts +2 -0
  40. package/dist/pacer/retry/retry.js +33 -1
  41. package/dist/schema/contracts.d.ts +61 -4
  42. package/dist/schema/index.d.ts +3 -2
  43. package/dist/schema/index.js +1 -1
  44. package/dist/schema/installation.d.ts +66 -0
  45. package/dist/schema/installation.js +38 -0
  46. package/dist/schema/schema.d.ts +20 -7
  47. package/dist/schema/schema.js +57 -48
  48. package/dist/session/bound.d.ts +2 -0
  49. package/dist/session/bound.js +45 -0
  50. package/dist/session/content/retry.js +2 -17
  51. package/dist/session/context/index.d.ts +1 -1
  52. package/dist/session/context/index.js +1 -1
  53. package/dist/session/context/operation.d.ts +2 -0
  54. package/dist/session/context/operation.js +19 -0
  55. package/dist/session/credential/credentials.js +16 -5
  56. package/dist/session/durable.d.ts +13 -0
  57. package/dist/session/durable.js +45 -0
  58. package/dist/session/index.d.ts +1 -1
  59. package/dist/session/index.js +0 -1
  60. package/dist/session/options.d.ts +0 -2
  61. package/dist/session/options.js +0 -3
  62. package/dist/session/reference.d.ts +9 -5
  63. package/dist/session/reference.js +7 -2
  64. package/dist/session/routing/dispatch.d.ts +20 -2
  65. package/dist/session/routing/dispatch.js +14 -4
  66. package/dist/session/routing/request.d.ts +4 -0
  67. package/dist/session/routing/request.js +11 -1
  68. package/dist/session/routing/result.d.ts +1 -1
  69. package/dist/session/routing/result.js +5 -1
  70. package/dist/session/session.d.ts +7 -0
  71. package/dist/session/session.js +29 -12
  72. package/dist/session/session.typecheck.js +5 -4
  73. package/dist/store/memory.js +20 -1
  74. package/dist/transport/http/admission.js +8 -0
  75. package/dist/transport/http/transport.js +14 -2
  76. package/dist/transport/http/unprocessed.d.ts +5 -0
  77. package/dist/transport/http/unprocessed.js +28 -0
  78. package/dist/transport/transport.d.ts +10 -0
  79. package/dist/transport/websocket/exchange.js +14 -1
  80. package/package.json +6 -5
  81. package/dist/session/execution.d.ts +0 -65
  82. package/dist/session/execution.js +0 -34
@@ -1,8 +1,9 @@
1
1
  import type { IssuerId } from '@astrale-os/kernel-core/auth/issuer';
2
+ import type * as invocation from '@astrale-os/kernel-protocol/invocation';
2
3
  import type { Result } from '../../client/index.js';
3
4
  import type { Fetch } from '../../transport/http/index.js';
4
5
  import type { SessionOperation, SessionPolicy } from '../context/index.js';
5
- import type { AuthExchange, SessionAuth } from './auth.js';
6
+ import type { AuthExchange, SessionAuth, EffectiveAuth } from './auth.js';
6
7
  import type { RouteCache } from './cache.js';
7
8
  import type { ClientPoolCapability } from './envelope.js';
8
9
  import type { SessionEnvelopeTransport, SessionRequestOptions } from './request.js';
@@ -24,13 +25,30 @@ export interface SessionDispatcherOptions {
24
25
  readonly timeoutMs: number;
25
26
  };
26
27
  }
28
+ /** A streaming call is forced over HTTP and may carry a binary body. */
29
+ export interface Streaming {
30
+ readonly body?: Blob;
31
+ }
32
+ /** One Call with the authority it presents on every dispatch, and the route partition it selects. */
33
+ export interface ResolvedCall {
34
+ readonly call: invocation.Call;
35
+ readonly auth: EffectiveAuth;
36
+ readonly source: IssuerId;
37
+ readonly cacheKey: string;
38
+ }
27
39
  export declare class SessionDispatcher {
28
40
  private readonly state;
29
41
  constructor(state: SessionDispatcherOptions);
30
42
  dispatch(input: Parameters<typeof acceptCall>[0], options: SessionRequestOptions, operation: SessionOperation): Promise<Result>;
31
43
  /** Reuse Session authority and route recovery while forcing HTTP for streaming calls. */
32
44
  dispatchHttp(input: Parameters<typeof acceptCall>[0], options: SessionRequestOptions, operation: SessionOperation, body?: Blob): Promise<Result>;
33
- private dispatchWith;
45
+ /** Resolve the Session authority of one Call: each dispatch of the result presents it. */
46
+ resolve(input: Parameters<typeof acceptCall>[0], operation: SessionOperation): Promise<ResolvedCall>;
47
+ /**
48
+ * Dispatch a resolved Call. Sending it again presents the same principal and caller, which an
49
+ * idempotency key needs to name the same Execution.
50
+ */
51
+ dispatchResolved(dispatch: ResolvedCall, options: SessionRequestOptions, operation: SessionOperation, streaming?: Streaming): Promise<Result>;
34
52
  /** The cached route for this partition, evicted when it no longer passes delivery checks. */
35
53
  private warmRoute;
36
54
  private dispatchSource;
@@ -11,13 +11,14 @@ export class SessionDispatcher {
11
11
  this.state = state;
12
12
  }
13
13
  async dispatch(input, options, operation) {
14
- return this.dispatchWith(input, options, operation);
14
+ return this.dispatchResolved(await this.resolve(input, operation), options, operation);
15
15
  }
16
16
  /** Reuse Session authority and route recovery while forcing HTTP for streaming calls. */
17
17
  async dispatchHttp(input, options, operation, body) {
18
- return this.dispatchWith(input, options, operation, { body });
18
+ return this.dispatchResolved(await this.resolve(input, operation), options, operation, { body });
19
19
  }
20
- async dispatchWith(input, options, operation, streaming) {
20
+ /** Resolve the Session authority of one Call: each dispatch of the result presents it. */
21
+ async resolve(input, operation) {
21
22
  this.state.requireOpen();
22
23
  const call = acceptCall(input);
23
24
  // Authority is resolved before warm lookup so changed credentials or delegation cannot reuse a
@@ -28,7 +29,14 @@ export class SessionDispatcher {
28
29
  : await this.state.exchange.resolve(call, resolved, operation);
29
30
  const source = this.state.kernel;
30
31
  const cacheKey = await runSessionOperation(operation, () => this.state.cache.key(source, call, auth));
31
- const dispatch = Object.freeze({ call, auth, source, cacheKey });
32
+ return Object.freeze({ call, auth, source, cacheKey });
33
+ }
34
+ /**
35
+ * Dispatch a resolved Call. Sending it again presents the same principal and caller, which an
36
+ * idempotency key needs to name the same Execution.
37
+ */
38
+ async dispatchResolved(dispatch, options, operation, streaming) {
39
+ this.state.requireOpen();
32
40
  const learned = await this.warmRoute(dispatch, operation, streaming);
33
41
  if (learned !== undefined) {
34
42
  return this.dispatchDestinationWithRecovery(learned, dispatch, options, operation, undefined, streaming);
@@ -62,6 +70,8 @@ export class SessionDispatcher {
62
70
  ...transportOptions(operation, options, streaming),
63
71
  ...(state.auth.delegate === undefined ? {} : { delegate: state.auth.delegate }),
64
72
  ...(routing === undefined ? {} : { routing }),
73
+ // The guard is the source Kernel's: a routed destination request never carries it.
74
+ ...(options.maintenance === undefined ? {} : { maintenance: options.maintenance }),
65
75
  }));
66
76
  }
67
77
  async followSource(result, state, options, operation, streaming) {
@@ -3,6 +3,10 @@ import type { SessionControlOptions } from '../context/index.js';
3
3
  export type SessionEnvelopeTransport = 'auto' | 'http' | 'websocket';
4
4
  export interface SessionRequestOptions extends SessionControlOptions {
5
5
  readonly idempotencyKey?: invocation.IdempotencyKey;
6
+ /** Sent to the source Kernel only; a routed destination never receives it. */
7
+ readonly maintenance?: {
8
+ readonly session: string;
9
+ };
6
10
  readonly body?: never;
7
11
  }
8
12
  export type SessionRequestOptionsWithBody = Omit<SessionRequestOptions, 'body' | 'idempotencyKey'> & {
@@ -23,17 +23,27 @@ export function admitRequestOptions(input = {}) {
23
23
  }
24
24
  const control = admitControlOptions(input);
25
25
  const fields = Reflect.ownKeys(input);
26
- if (fields.some((field) => !['signal', 'timeoutMs', 'idempotencyKey'].includes(String(field)))) {
26
+ if (fields.some((field) => !['signal', 'timeoutMs', 'idempotencyKey', 'maintenance'].includes(String(field)))) {
27
27
  throw new TypeError('Session request options contain unsupported fields.');
28
28
  }
29
29
  const idempotencyKey = input.idempotencyKey === undefined
30
30
  ? undefined
31
31
  : invocationProtocol.acceptIdempotencyKey(input.idempotencyKey, 'request.idempotencyKey');
32
+ const maintenance = input.maintenance === undefined ? undefined : admitMaintenance(input.maintenance);
32
33
  return Object.freeze({
33
34
  ...control,
34
35
  ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
36
+ ...(maintenance === undefined ? {} : { maintenance }),
35
37
  });
36
38
  }
39
+ function admitMaintenance(input) {
40
+ try {
41
+ return invocationProtocol.acceptMaintenance(input);
42
+ }
43
+ catch (cause) {
44
+ throw new TypeError('Session maintenance guard is invalid.', { cause });
45
+ }
46
+ }
37
47
  export function admitEnvelopeTransport(input) {
38
48
  if (input !== 'auto' && input !== 'http' && input !== 'websocket') {
39
49
  throw new TypeError('Session envelope transport is invalid.');
@@ -1,5 +1,5 @@
1
1
  import type { Result } from '../../client/index.js';
2
2
  /** Narrow a Result to the kind a sugar requires, releasing a live body before rejecting it. */
3
- export declare function requireResultKind<Kind extends 'value' | 'stream' | 'binary'>(expected: Kind, result: Result): Extract<Result, {
3
+ export declare function requireResultKind<Kind extends Exclude<Result['kind'], 'redirect'>>(expected: Kind, result: Result): Extract<Result, {
4
4
  kind: Kind;
5
5
  }>;
@@ -8,5 +8,9 @@ export function requireResultKind(expected, result) {
8
8
  if (result.kind === 'binary' && !(result.value.body instanceof Uint8Array)) {
9
9
  void result.value.body[Symbol.asyncIterator]().return?.();
10
10
  }
11
- throw new ClientError(`Function returned ${result.kind}; ${expected} was required.`);
11
+ // A started Execution is named so its caller never starts it again.
12
+ const returned = result.kind === 'execution'
13
+ ? `Function started Execution ${result.execution}`
14
+ : `Function returned ${result.kind}`;
15
+ throw new ClientError(`${returned}; ${expected} was required.`);
12
16
  }
@@ -3,6 +3,7 @@ import type { PathLike } from '@astrale-os/kernel-core/path';
3
3
  import type { Domain } from '@astrale-os/kernel-dsl/v1/domain';
4
4
  import type { AuthApi } from '../auth/index.js';
5
5
  import type { Call, Input, Result } from '../client/index.js';
6
+ import type { ExecutionApi } from '../execution/index.js';
6
7
  import type { DomainBinding, GraphApi } from '../graph/index.js';
7
8
  import type { SchemaApi } from '../schema/index.js';
8
9
  import type { ContentApi } from './content/index.js';
@@ -22,6 +23,8 @@ export type ConnectOptions = Omit<ClientSessionOptions, 'kernel' | 'policy'> & {
22
23
  export declare class ClientSession {
23
24
  readonly kernel: IssuerId;
24
25
  readonly schema: SchemaApi;
26
+ /** The `K.Execution` Methods of any Execution, a durable call's or an install's. */
27
+ readonly execution: ExecutionApi;
25
28
  readonly graph: GraphApi;
26
29
  readonly auth: AuthApi;
27
30
  readonly content: ContentApi;
@@ -58,6 +61,10 @@ export declare class ClientSession {
58
61
  dispatch(call: Call, options: SessionRequestOptionsWithBody): Promise<Result>;
59
62
  call(call: Call, options?: SessionRequestOptions): Promise<Input>;
60
63
  call(call: Call, options: SessionRequestOptionsWithBody): Promise<Input>;
64
+ /**
65
+ * Invoke one typed reference. A durable callable's call is keyed, by the caller's key or by one
66
+ * created for this call, and sent again with that key while its outcome is unknown.
67
+ */
61
68
  invoke<const Reference extends CallableReference<unknown>>(reference: InputModeOfReference<Reference> extends 'binary' ? never : Reference, input: InputOfReference<Reference>, options?: SessionRequestOptions): Promise<OutputOfReference<Reference>>;
62
69
  invoke<const Reference extends CallableReference<unknown, unknown, 'binary'>>(reference: Reference, input: InputOfReference<Reference>, options: SessionRequestOptionsWithBody): Promise<OutputOfReference<Reference>>;
63
70
  private dispatchWith;
@@ -3,6 +3,7 @@ import { callableFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprin
3
3
  import { createAuth } from '../auth/auth.js';
4
4
  import { acceptCall } from '../client/index.js';
5
5
  import { SessionError } from '../errors/index.js';
6
+ import { createExecution } from '../execution/index.js';
6
7
  import { createDomainBinding } from '../graph/domain/binding.js';
7
8
  import { createGraph } from '../graph/index.js';
8
9
  import { createSchema } from '../schema/index.js';
@@ -10,9 +11,10 @@ import { admitFunction } from './admission.js';
10
11
  import { createContentApi } from './content/index.js';
11
12
  import { admitControlOptions, allowEndpoint, createSessionOperation } from './context/index.js';
12
13
  import { createSessionDiscovery } from './discovery/index.js';
14
+ import { attemptDurable, durableOptions } from './durable.js';
13
15
  import { acquireDomainCredential, admitExchangeRequest, createSessionExchange, } from './exchange/index.js';
14
16
  import { acceptSessionOptions } from './options.js';
15
- import { admitReference } from './reference.js';
17
+ import { admitReference, outputModeOf } from './reference.js';
16
18
  import { admitInvocationOptions, requireResultKind, SessionDispatcher } from './routing/index.js';
17
19
  import { domainViewCatalog, resolveViewsFor } from './views/index.js';
18
20
  const DEFAULT_SESSION_POLICY = Object.freeze({ maximumRouteAgeMs: 60_000 });
@@ -20,6 +22,8 @@ const DEFAULT_SESSION_POLICY = Object.freeze({ maximumRouteAgeMs: 60_000 });
20
22
  export class ClientSession {
21
23
  kernel;
22
24
  schema;
25
+ /** The `K.Execution` Methods of any Execution, a durable call's or an install's. */
26
+ execution;
23
27
  graph;
24
28
  auth;
25
29
  content;
@@ -92,8 +96,8 @@ export class ClientSession {
92
96
  this.schema = createSchema((request, options) => this.dispatch(request, options), {
93
97
  maximumReleaseBytes,
94
98
  maximumBundleBytes,
95
- lifecycleTimeoutMs: settled.schemaLifecycleTimeoutMs,
96
99
  });
100
+ this.execution = createExecution((request, options) => this.dispatch(request, options));
97
101
  this.graph = createGraph((call, options) => this.call(call, options));
98
102
  this.auth = createAuth((target, input, options) => this.call({ target, input }, options), (call, options) => {
99
103
  const operation = this.operation(admitControlOptions(options));
@@ -157,16 +161,29 @@ export class ClientSession {
157
161
  }),
158
162
  input,
159
163
  };
160
- const operation = this.operation(admitted.options);
161
- const result = await (admitted.body === undefined && admittedReference.outputMode !== 'binary'
162
- ? this.dispatcher.dispatch(call, admitted.options, operation)
163
- : this.dispatcher.dispatchHttp(call, admitted.options, operation, admitted.body));
164
+ // A durable call is keyed, so an attempt whose outcome is unknown can be sent again.
165
+ const durable = admittedReference.outputMode === 'execution';
166
+ const requested = durable ? durableOptions(admitted.options) : admitted.options;
167
+ const operation = this.operation(requested);
168
+ const streaming = admitted.body === undefined && admittedReference.outputMode !== 'binary'
169
+ ? undefined
170
+ : { body: admitted.body };
171
+ // Resolved once: every attempt presents the principal and caller its key names an Execution with.
172
+ const resolved = await this.dispatcher.resolve(call, operation);
173
+ const attempt = () => this.dispatcher.dispatchResolved(resolved, requested, operation, streaming);
174
+ const result = await (durable ? attemptDurable(operation, attempt) : attempt());
164
175
  const narrowed = requireResultKind(admittedReference.outputMode, result);
165
- return narrowed.kind === 'value'
166
- ? narrowed.value
167
- : narrowed.kind === 'stream'
168
- ? narrowed.stream
169
- : narrowed.value;
176
+ switch (narrowed.kind) {
177
+ case 'stream':
178
+ return narrowed.stream;
179
+ case 'execution':
180
+ return Object.freeze({
181
+ id: narrowed.execution,
182
+ ...(narrowed.replayed === undefined ? {} : { replayed: narrowed.replayed }),
183
+ });
184
+ default:
185
+ return narrowed.value;
186
+ }
170
187
  }
171
188
  dispatchWith(call, options, requireHttp = false) {
172
189
  const admitted = admitInvocationOptions(options);
@@ -209,7 +226,7 @@ export class ClientSession {
209
226
  fingerprint: callableFingerprint(method),
210
227
  callable: method.key,
211
228
  target: Path.instanceMethod(Path.id(node.id), method.key),
212
- outputMode: method.output.mode,
229
+ outputMode: outputModeOf(method),
213
230
  }, input);
214
231
  }
215
232
  operation(options) {
@@ -4,7 +4,7 @@ import { K, KernelSchema } from '@astrale-os/kernel-core/schema';
4
4
  import { defineSchema, func, method, nodeClass, schema, valueSchema, } from '@astrale-os/kernel-dsl/v1';
5
5
  import { isBinaryInput } from '@astrale-os/kernel-dsl/v1/language';
6
6
  import { call } from '../client/index.js';
7
- import { ClientSession, credentials, execution, reference } from './index.js';
7
+ import { ClientSession, credentials, reference } from './index.js';
8
8
  void new ClientSession(options);
9
9
  void auth;
10
10
  void control;
@@ -189,12 +189,13 @@ const durableDomain = schema.resolve(defineSchema('client.durable.typecheck', {
189
189
  }));
190
190
  const remindReference = reference(durableDomain, durableDomain.classes.Invoice.methods.remind)(Path.id(NodeId('invoice-1')));
191
191
  const durableReturnsExecution = true;
192
+ const outcome = session.execution.result(run, { waitMs: 1_000 });
192
193
  const outcomeIsTyped = true;
194
+ const status = session.execution.status(run);
193
195
  const statusIsTyped = true;
194
- void session.invoke(execution.result(run), { waitMs: 1_000 });
195
- void session.invoke(execution.signal(run), { name: 'approval', value: { by: 'billing' } });
196
+ void session.execution.signal(run, { name: 'approval', value: { by: 'billing' } });
196
197
  // @ts-expect-error Force is the only cancellation option.
197
- void session.invoke(execution.cancel(run), { waitMs: 1_000 });
198
+ void session.execution.cancel(run, { waitMs: 1_000 });
198
199
  void durableReturnsExecution;
199
200
  void outcomeIsTyped;
200
201
  void statusIsTyped;
@@ -4,6 +4,10 @@ import { retainDerivedQueryProvenance } from '../graph/provenance.js';
4
4
  import { EntityIndex } from './entity-index.js';
5
5
  import { OptimisticOverlay } from './optimistic.js';
6
6
  import { COLD_SNAPSHOT, QueryShape } from './shape.js';
7
+ const NO_REFERENCES = Object.freeze({
8
+ nodes: Object.freeze([]),
9
+ edges: Object.freeze([]),
10
+ });
7
11
  export class GraphMemory {
8
12
  options;
9
13
  entities = new EntityIndex();
@@ -60,6 +64,17 @@ export class GraphMemory {
60
64
  this.publish(shape, prior === undefined ? 'cold' : this.overlay.hasAny() ? 'optimistic' : 'stale');
61
65
  return result;
62
66
  }
67
+ // An uncertified read may hold facts the active schema refutes: it stays raw on its own
68
+ // shape and never enters, or is derived from, the shared entity cache.
69
+ if (result.certification === 'uncertified') {
70
+ shape.references = NO_REFERENCES;
71
+ shape.confirmed = result;
72
+ shape.response = result;
73
+ shape.refreshedAt = this.options.now();
74
+ this.touch(shape, shape.refreshedAt);
75
+ this.publish(shape, 'ready');
76
+ return shape.response;
77
+ }
63
78
  const integration = this.entities.integrate(result.result);
64
79
  shape.references = integration.references;
65
80
  shape.confirmed = result;
@@ -127,7 +142,7 @@ export class GraphMemory {
127
142
  }
128
143
  optimistic() {
129
144
  for (const shape of this.shapes.values()) {
130
- if (shape.response === undefined)
145
+ if (shape.response === undefined || shape.confirmed?.certification === 'uncertified')
131
146
  continue;
132
147
  shape.response = this.materialize(shape.confirmed, shape.references);
133
148
  this.publish(shape, 'optimistic');
@@ -195,9 +210,13 @@ export class GraphMemory {
195
210
  this.pending.shift()?.reject(error);
196
211
  }
197
212
  materialize(template, references) {
213
+ // Optimistic overlays and cache refreshes never rewrite an uncertified read.
214
+ if (template.certification === 'uncertified')
215
+ return template;
198
216
  const response = Object.freeze({
199
217
  result: this.materializeResult(template.result, references),
200
218
  page: template.page,
219
+ ...(template.certification === undefined ? {} : { certification: template.certification }),
201
220
  });
202
221
  return retainDerivedQueryProvenance(template, response);
203
222
  }
@@ -90,6 +90,14 @@ export async function admitResponse(response, requestId, context) {
90
90
  throw new ResponseError(envelope.error.code, envelope.error.message, envelope.invocation, envelope.error.data);
91
91
  }
92
92
  requireLive(control);
93
+ if ('execution' in envelope) {
94
+ return {
95
+ kind: 'execution',
96
+ execution: envelope.execution,
97
+ ...(envelope.replayed === undefined ? {} : { replayed: envelope.replayed }),
98
+ invocation: envelope.invocation,
99
+ };
100
+ }
93
101
  return { kind: 'value', value: envelope.result, invocation: envelope.invocation };
94
102
  }
95
103
  function redirectResult(response) {
@@ -5,6 +5,7 @@ import { invocationFailure } from '../failure.js';
5
5
  import { asError, controlledSignal, positiveInteger, requireLive, } from '../index.js';
6
6
  import { admitResponse } from './admission.js';
7
7
  import { capture } from './configuration.js';
8
+ import { unprocessed } from './unprocessed.js';
8
9
  /** HTTP implementation of the universal invocation protocol. */
9
10
  export class HttpTransport {
10
11
  url;
@@ -74,7 +75,9 @@ export class HttpTransport {
74
75
  return result;
75
76
  }
76
77
  catch (error) {
77
- throw transportFailure(error, control, options.signal, timeoutMs, this.url, phase, delivery);
78
+ // A request the server refused unprocessed, even when sent again, was never delivered.
79
+ const proven = phase === 'send' && unprocessed(error) ? 'not-sent' : delivery;
80
+ throw transportFailure(error, control, options.signal, timeoutMs, this.url, phase, proven);
78
81
  }
79
82
  finally {
80
83
  if (!handedOff)
@@ -103,7 +106,16 @@ export class HttpTransport {
103
106
  body: binaryBody ?? toBody(encoded),
104
107
  signal: control.signal,
105
108
  };
106
- return this.fetchImpl(this.url, init);
109
+ try {
110
+ return await this.fetchImpl(this.url, init);
111
+ }
112
+ catch (error) {
113
+ // The server processed none of it: send it once more, on the connection that replaces the
114
+ // one that refused it, under the same timeout and signal (CLIENT-HTTP-UNPROCESSED-RESEND).
115
+ if (!unprocessed(error) || control.signal.aborted)
116
+ throw error;
117
+ return this.fetchImpl(this.url, init);
118
+ }
107
119
  }
108
120
  nextRequestId() {
109
121
  const requestId = this.nextId;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Whether a Fetch failure proves that the server never processed the request. Only the exact
3
+ * refusal above does: any other failure, or a refusal reported in other words, proves nothing.
4
+ */
5
+ export declare function unprocessed(failure: unknown): boolean;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The failure undici's Fetch reports for a request that an HTTP/2 GOAWAY with NO_ERROR refused: one
3
+ * whose stream it never opened, or opened above the GOAWAY's last stream identifier. The server
4
+ * processed none of them (RFC 9113, Section 6.8). undici sends such a request again itself only
5
+ * when its body can be replayed, which a Fetch request body, always a stream, cannot.
6
+ */
7
+ const GOAWAY_REFUSAL = Object.freeze({
8
+ code: 'UND_ERR_INFO',
9
+ message: 'HTTP/2: "GOAWAY" frame received with code 0',
10
+ });
11
+ /** Causes a Fetch failure wraps before the one that names the refusal. */
12
+ const MAXIMUM_CAUSES = 4;
13
+ /**
14
+ * Whether a Fetch failure proves that the server never processed the request. Only the exact
15
+ * refusal above does: any other failure, or a refusal reported in other words, proves nothing.
16
+ */
17
+ export function unprocessed(failure) {
18
+ let cause = failure;
19
+ for (let depth = 0; depth <= MAXIMUM_CAUSES; depth++) {
20
+ if (typeof cause !== 'object' || cause === null)
21
+ return false;
22
+ const { code, message } = cause;
23
+ if (code === GOAWAY_REFUSAL.code && message === GOAWAY_REFUSAL.message)
24
+ return true;
25
+ cause = cause.cause;
26
+ }
27
+ return false;
28
+ }
@@ -4,6 +4,14 @@ export interface RequestOptions {
4
4
  readonly signal?: AbortSignal;
5
5
  readonly timeoutMs?: number;
6
6
  readonly idempotencyKey?: protocol.IdempotencyKey;
7
+ /**
8
+ * The maintenance session a root request expects to act within, by its install execution id. It
9
+ * grants nothing: the Kernel refuses the request `MAINTENANCE_SESSION_STALE` unless that session
10
+ * is the Instance's live one. The Client carries it in the source request, never to a destination.
11
+ */
12
+ readonly maintenance?: {
13
+ readonly session: string;
14
+ };
7
15
  }
8
16
  export interface TransportRequest {
9
17
  readonly call: protocol.Call;
@@ -14,6 +22,8 @@ export interface TransportRequest {
14
22
  readonly routing?: protocol.Routing;
15
23
  /** Source-Kernel Schema Registration precondition; omitted after routing. */
16
24
  readonly schema?: protocol.SchemaTarget;
25
+ /** Source-Kernel maintenance session guard; omitted after routing. */
26
+ readonly maintenance?: protocol.Maintenance;
17
27
  }
18
28
  /** Correlated reserved control decoded independently from application results and errors. */
19
29
  export interface StaleControl {
@@ -57,7 +57,7 @@ export class WebSocketExchange {
57
57
  this.receiveResponse(input);
58
58
  return;
59
59
  }
60
- if (this.state !== 'stream' || isKind(input, 'binary')) {
60
+ if (this.state !== 'stream' || !isStreamFrame(input)) {
61
61
  throw new ProtocolError('server sent an unexpected WebSocket response.');
62
62
  }
63
63
  this.receiveStreamFrame(input);
@@ -153,6 +153,15 @@ export class WebSocketExchange {
153
153
  this.reject(new ResponseError(response.error.code, response.error.message, response.invocation, response.error.data));
154
154
  return;
155
155
  }
156
+ if ('execution' in response) {
157
+ this.complete({
158
+ kind: 'execution',
159
+ execution: response.execution,
160
+ ...(response.replayed === undefined ? {} : { replayed: response.replayed }),
161
+ invocation: response.invocation,
162
+ });
163
+ return;
164
+ }
156
165
  this.complete({ kind: 'value', value: response.result, invocation: response.invocation });
157
166
  }
158
167
  receiveStreamFrame(frame) {
@@ -292,6 +301,10 @@ function requireId(expected, received) {
292
301
  throw new ProtocolError(`response requestId ${JSON.stringify(received)} does not match request requestId ${JSON.stringify(expected)}.`);
293
302
  }
294
303
  }
304
+ /** Only stream frames may follow `stream.start`; a unary response would end the stream unchecked. */
305
+ function isStreamFrame(input) {
306
+ return 'kind' in input && typeof input.kind === 'string' && input.kind.startsWith('stream.');
307
+ }
295
308
  function isKind(input, kind) {
296
309
  return (typeof input === 'object' &&
297
310
  input !== null &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-client",
3
- "version": "1.0.0-beta.2",
3
+ "version": "1.0.0-beta.21",
4
4
  "description": "Universal Client — protocol-first, transport-agnostic",
5
5
  "keywords": [
6
6
  "astrale",
@@ -65,16 +65,17 @@
65
65
  "access": "public"
66
66
  },
67
67
  "dependencies": {
68
- "@astrale-os/kernel-core": "1.0.0-beta.2",
69
- "@astrale-os/kernel-dsl": "1.0.0-beta.2",
70
- "@astrale-os/kernel-protocol": "1.0.0-beta.2",
68
+ "@astrale-os/kernel-core": "1.0.0-beta.18",
69
+ "@astrale-os/kernel-dsl": "1.0.0-beta.11",
70
+ "@astrale-os/kernel-protocol": "1.0.0-beta.18",
71
71
  "@tanstack/pacer": "0.20.1"
72
72
  },
73
73
  "devDependencies": {
74
- "@astrale-os/kernel-server": "1.0.0-beta.2",
74
+ "@astrale-os/kernel-server": "1.0.0-beta.18",
75
75
  "@astrale/typescript-config": "npm:@jsr/astrale__typescript-config@~1.1.0",
76
76
  "@types/node": "^22.0.0",
77
77
  "typescript": "7.0.2",
78
+ "undici": "8.10.0",
78
79
  "vitest": "^5.0.1"
79
80
  },
80
81
  "scripts": {
@@ -1,65 +0,0 @@
1
- import type { NodeId } from '@astrale-os/kernel-core/graph/node';
2
- import type { Value } from '@astrale-os/kernel-dsl/value';
3
- import type { CallableReference } from './reference.js';
4
- declare const EXECUTION_OUTPUT: unique symbol;
5
- /**
6
- * Immediate value of a durable call: the `K.Execution` it created or recovered. `Output` is the
7
- * handler output of the called declaration, carried only by the type.
8
- */
9
- export interface ExecutionRef<Output = unknown> {
10
- readonly id: NodeId;
11
- readonly [EXECUTION_OUTPUT]?: Output;
12
- }
13
- export type ExecutionOutcome<Output = unknown> = {
14
- readonly kind: 'completed';
15
- readonly value: Output;
16
- } | {
17
- readonly kind: 'failed';
18
- readonly error: {
19
- readonly code: string;
20
- readonly message: string;
21
- readonly family?: string;
22
- readonly details?: Value;
23
- };
24
- } | {
25
- readonly kind: 'cancelled';
26
- };
27
- export type ExecutionState = 'pending' | 'running' | 'waiting' | 'paused' | 'completed' | 'failed' | 'cancelled' | 'expired';
28
- export interface ExecutionStatus<Output = unknown> {
29
- readonly id: NodeId;
30
- readonly function: NodeId;
31
- readonly version: `sha256:${string}`;
32
- readonly state: ExecutionState;
33
- readonly createdAt: string;
34
- readonly outcome?: ExecutionOutcome<Output>;
35
- }
36
- type Empty = Readonly<Record<string, never>>;
37
- type ExecutionLike<Output> = ExecutionRef<Output> | NodeId;
38
- /**
39
- * Typed references to the methods of one Execution, for `session.invoke`:
40
- *
41
- * ```ts
42
- * const run = await session.invoke(remind(invoice), { days: 3 })
43
- * const outcome = await session.invoke(execution.result(run), { waitMs: 10_000 })
44
- * ```
45
- */
46
- export declare const execution: Readonly<{
47
- status: <Output>(target: ExecutionLike<Output>) => CallableReference<Empty, ExecutionStatus<Output>>;
48
- /** Outcome once terminal; fails `EXECUTION_PENDING` when `waitMs` elapses first. */
49
- result: <Output>(target: ExecutionLike<Output>) => CallableReference<{
50
- readonly waitMs?: number;
51
- }, ExecutionOutcome<Output>>;
52
- /** Cooperative cancellation; `force` kills without compensation (owner Domain only). */
53
- cancel: <Output>(target: ExecutionLike<Output>) => CallableReference<{
54
- readonly force?: boolean;
55
- }, ExecutionStatus<Output>>;
56
- /** Resolve a named durable promise once (owner Domain only). */
57
- signal: (target: ExecutionLike<unknown>) => CallableReference<{
58
- readonly name: string;
59
- readonly value: Value;
60
- }, Empty>;
61
- resume: <Output>(target: ExecutionLike<Output>) => CallableReference<Empty, ExecutionStatus<Output>>;
62
- /** Forget the Execution and stop its run (owner Domain only). */
63
- delete: (target: ExecutionLike<unknown>) => CallableReference<Empty, Empty>;
64
- }>;
65
- export {};
@@ -1,34 +0,0 @@
1
- import { Path } from '@astrale-os/kernel-core/path';
2
- import { execution as methods } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
3
- import { kernelReference } from './reference.js';
4
- const bound = {
5
- status: kernelReference(methods.status),
6
- result: kernelReference(methods.result),
7
- cancel: kernelReference(methods.cancel),
8
- signal: kernelReference(methods.signal),
9
- resume: kernelReference(methods.resume),
10
- delete: kernelReference(methods.delete),
11
- };
12
- function receiver(execution) {
13
- return Path.id(typeof execution === 'string' ? execution : execution.id);
14
- }
15
- /**
16
- * Typed references to the methods of one Execution, for `session.invoke`:
17
- *
18
- * ```ts
19
- * const run = await session.invoke(remind(invoice), { days: 3 })
20
- * const outcome = await session.invoke(execution.result(run), { waitMs: 10_000 })
21
- * ```
22
- */
23
- export const execution = Object.freeze({
24
- status: (target) => bound.status(receiver(target)),
25
- /** Outcome once terminal; fails `EXECUTION_PENDING` when `waitMs` elapses first. */
26
- result: (target) => bound.result(receiver(target)),
27
- /** Cooperative cancellation; `force` kills without compensation (owner Domain only). */
28
- cancel: (target) => bound.cancel(receiver(target)),
29
- /** Resolve a named durable promise once (owner Domain only). */
30
- signal: (target) => bound.signal(receiver(target)),
31
- resume: (target) => bound.resume(receiver(target)),
32
- /** Forget the Execution and stop its run (owner Domain only). */
33
- delete: (target) => bound.delete(receiver(target)),
34
- });