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

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,26 +1,39 @@
1
1
  import type { Key } from '@astrale-os/kernel-dsl/v1';
2
- import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
2
+ import type * as protocolSchema from '@astrale-os/kernel-protocol/schema';
3
3
  import type { Call, Result } from '../client/index.js';
4
4
  import type { RequestOptions } from '../transport/index.js';
5
- import type { InstallRequest, UninstallReceipt, UninstallRequest } from './contracts.js';
5
+ import type { Installation, InstallRequest, Uninstallation, UninstallRequest } from './contracts.js';
6
+ import { type InstallationApi, type UninstallationApi } from './installation.js';
6
7
  export type SchemaCall = (call: Call, options?: RequestOptions) => Promise<Result>;
7
8
  export interface SchemaOptions extends protocolSchema.installation.introspection.Limits {
8
- readonly lifecycleTimeoutMs?: number;
9
9
  }
10
10
  export type DomainInfo = protocolSchema.installation.introspection.DomainInfo;
11
11
  export type DomainBundle = protocolSchema.installation.introspection.DomainBundle;
12
12
  export type DomainDependencies = protocolSchema.installation.introspection.DomainDependencies;
13
13
  export type InstalledRelease = protocolSchema.installation.introspection.InstalledRelease;
14
14
  export type InstalledPin = protocolSchema.installation.introspection.InstalledPin;
15
- export type InstallResult = protocolSchema.installation.InstallResult;
16
15
  export interface SchemaApi {
17
- install(request: InstallRequest, options?: RequestOptions): Promise<InstallResult>;
18
- uninstall(request: UninstallRequest, options?: RequestOptions): Promise<UninstallReceipt>;
16
+ /**
17
+ * Install Domains: start the durable Execution the install is, wait at most `waitMs` (110 s by
18
+ * default) for its outcome unless the mode is `maintenance`, and read its status. `timeoutMs`,
19
+ * when given, bounds the whole call. The answer names the Execution with its status; `result` is
20
+ * present once it completed. A rejected install is a terminal `failed` status, never a failed
21
+ * call.
22
+ */
23
+ install(request: InstallRequest, options?: RequestOptions): Promise<Installation>;
24
+ /** The install executions and repair sessions, through their `K.Execution` Methods. */
25
+ readonly installation: InstallationApi;
26
+ /**
27
+ * Uninstall Domains: start the durable Execution the uninstall is, wait at most `waitMs` (110 s
28
+ * by default) for its outcome and read its status. `result` is the receipt once it completed.
29
+ */
30
+ uninstall(request: UninstallRequest, options?: RequestOptions): Promise<Uninstallation>;
31
+ /** The uninstall executions, through their `K.Execution` Methods. */
32
+ readonly uninstallation: UninstallationApi;
19
33
  inspect(origin: Key.Origin, options?: RequestOptions): Promise<DomainInfo>;
20
34
  bundle(origin: Key.Origin, options?: RequestOptions): Promise<DomainBundle>;
21
35
  dependencies(origin: Key.Origin, options?: RequestOptions): Promise<DomainDependencies>;
22
36
  installed(options?: RequestOptions): Promise<readonly InstalledRelease[]>;
23
37
  }
24
- export declare const DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS = 110000;
25
38
  /** Bind the canonical Schema lifecycle syscalls to one caller-scoped value-call capability. */
26
39
  export declare function createSchema(call: SchemaCall, limits: SchemaOptions): SchemaApi;
@@ -1,46 +1,41 @@
1
1
  import { Path } from '@astrale-os/kernel-core/path';
2
- import { uninstallOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
2
  import { install, uninstall } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
4
- import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
5
3
  import { call as invocation } from '../client/index.js';
6
- import { acceptOutput } from './admission.js';
4
+ import { acceptWait, deadlineOf, within } from '../execution/index.js';
5
+ import { createInstallation, createUninstallation, } from './installation.js';
7
6
  import { introspect } from './introspection.js';
8
7
  const INSTALL_PATH = Path.project(install).raw;
9
8
  const UNINSTALL_PATH = Path.project(uninstall).raw;
10
- export const DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS = 110_000;
9
+ /** How long an install or uninstall waits for its outcome unless its request says otherwise. */
10
+ const DEFAULT_LIFECYCLE_WAIT_MS = 110_000;
11
11
  /** Bind the canonical Schema lifecycle syscalls to one caller-scoped value-call capability. */
12
12
  export function createSchema(call, limits) {
13
13
  if (typeof call !== 'function')
14
14
  throw new TypeError('Schema call capability is invalid.');
15
15
  const admittedLimits = admitLimits(limits);
16
+ const installation = createInstallation(call);
17
+ const uninstallation = createUninstallation(call);
16
18
  return Object.freeze({
17
19
  async install(request, options) {
18
- const result = await call(invocation(INSTALL_PATH, request), lifecycleOptions(options, admittedLimits.lifecycleTimeoutMs));
19
- if (result.kind !== 'binary') {
20
- throw new TypeError('Schema install returned a non-binary result.');
21
- }
22
- const { mediaType } = result.value;
23
- const decode = mediaType === protocolSchema.installation.MEDIA_TYPE
24
- ? protocolSchema.installation.decode
25
- : undefined;
26
- if (decode === undefined) {
27
- throw new TypeError('Schema install returned an unsupported media type.');
28
- }
29
- if (!(result.value.body instanceof Uint8Array)) {
30
- await result.value.body[Symbol.asyncIterator]().return?.();
31
- throw new TypeError('Schema install returned a streaming binary result.');
32
- }
33
- const decoded = await decode(result.value.body, installationResultLimit(admittedLimits.maximumReleaseBytes, request.domains.length));
34
- proveInstallResult(request, decoded);
35
- return decoded;
20
+ const { waitMs, ...input } = request;
21
+ const wait = lifecycleWait(waitMs);
22
+ // A maintenance session awaits Root's commands: its outcome is not the call's to wait for.
23
+ const started = await lifecycle(call, installation, INSTALL_PATH, input, input.mode === 'maintenance' ? 0 : wait, options);
24
+ return admitInstallation(request, started);
36
25
  },
26
+ installation,
37
27
  async uninstall(request, options) {
28
+ const wait = lifecycleWait(request.waitMs);
38
29
  const snapshot = snapshotUninstallRequest(request);
39
- const output = value(await call(invocation(UNINSTALL_PATH, snapshot), lifecycleOptions(options, admittedLimits.lifecycleTimeoutMs)));
40
- const receipt = acceptOutput(uninstallOutput, output);
41
- proveUninstallReceipt(snapshot, receipt);
42
- return receipt;
30
+ const started = await lifecycle(call, uninstallation, UNINSTALL_PATH, snapshot, wait, options);
31
+ const answer = { execution: started.status.id, ...started };
32
+ const { status } = started;
33
+ if (status.outcome?.kind !== 'completed')
34
+ return Object.freeze(answer);
35
+ proveUninstallReceipt(snapshot, status.outcome.value);
36
+ return Object.freeze({ ...answer, result: status.outcome.value });
43
37
  },
38
+ uninstallation,
44
39
  async inspect(origin, options) {
45
40
  return introspect(call, admittedLimits, { kind: 'inspect', origin }, options);
46
41
  },
@@ -55,6 +50,28 @@ export function createSchema(call, limits) {
55
50
  },
56
51
  });
57
52
  }
53
+ /**
54
+ * One lifecycle syscall, before the call's deadline: start the durable Execution it is, wait at
55
+ * most `waitMs` for its outcome, and read its status. Any end of the wait leaves the status to say
56
+ * where the Execution is, so the caller never loses it.
57
+ */
58
+ async function lifecycle(call, executions, path, input, waitMs, options) {
59
+ const deadline = deadlineOf(options);
60
+ const started = await call(invocation(path, input), within(deadline, options));
61
+ if (started.kind !== 'execution') {
62
+ throw new TypeError('Schema syscall did not answer with an Execution.');
63
+ }
64
+ if (waitMs > 0) {
65
+ await executions
66
+ .result(started.execution, { waitMs }, within(deadline, options))
67
+ .catch(() => undefined);
68
+ }
69
+ const status = await executions.status(started.execution, within(deadline, options));
70
+ return started.replayed === undefined ? { status } : { status, replayed: started.replayed };
71
+ }
72
+ function lifecycleWait(waitMs) {
73
+ return acceptWait({ waitMs: waitMs ?? DEFAULT_LIFECYCLE_WAIT_MS });
74
+ }
58
75
  function snapshotUninstallRequest(request) {
59
76
  return Object.freeze({
60
77
  operation: request.operation,
@@ -75,12 +92,18 @@ function proveUninstallReceipt(request, receipt) {
75
92
  function compare(left, right) {
76
93
  return left < right ? -1 : left > right ? 1 : 0;
77
94
  }
78
- function installationResultLimit(maximumDomainBytes, roots) {
79
- const perDomain = maximumDomainBytes + 4_096;
80
- if (roots > Math.floor((Number.MAX_SAFE_INTEGER - 4_096) / perDomain)) {
81
- return Number.MAX_SAFE_INTEGER;
82
- }
83
- return perDomain * roots + 4_096;
95
+ /**
96
+ * The answer of one install, proved against its request: a completed status carries the result of
97
+ * exactly this operation, admitted by its Protocol owner.
98
+ */
99
+ function admitInstallation(request, started) {
100
+ const answer = { execution: started.status.id, ...started };
101
+ const { status } = started;
102
+ if (status.outcome?.kind !== 'completed')
103
+ return Object.freeze(answer);
104
+ const result = status.outcome.value;
105
+ proveInstallResult(request, result);
106
+ return Object.freeze({ ...answer, result });
84
107
  }
85
108
  function proveInstallResult(request, result) {
86
109
  if (result.changed) {
@@ -96,28 +119,14 @@ function proveInstallResult(request, result) {
96
119
  throw new TypeError('Schema unchanged result does not match the requested Domain count.');
97
120
  }
98
121
  }
99
- function value(result) {
100
- if (result.kind !== 'value')
101
- throw new TypeError('Schema syscall returned a non-value result.');
102
- return result.value;
103
- }
104
122
  function admitLimits(input) {
105
- const lifecycleTimeoutMs = input?.lifecycleTimeoutMs ?? DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS;
106
123
  if (input === null ||
107
124
  typeof input !== 'object' ||
108
125
  !Number.isSafeInteger(input.maximumReleaseBytes) ||
109
126
  input.maximumReleaseBytes < 1 ||
110
127
  !Number.isSafeInteger(input.maximumBundleBytes) ||
111
- input.maximumBundleBytes < 1 ||
112
- !Number.isSafeInteger(lifecycleTimeoutMs) ||
113
- lifecycleTimeoutMs < 1 ||
114
- lifecycleTimeoutMs > 2_147_483_647) {
128
+ input.maximumBundleBytes < 1) {
115
129
  throw new TypeError('Schema introspection limits are invalid.');
116
130
  }
117
- return Object.freeze({ ...input, lifecycleTimeoutMs });
118
- }
119
- function lifecycleOptions(options, timeoutMs) {
120
- if (options?.timeoutMs !== undefined)
121
- return options;
122
- return Object.freeze({ ...options, timeoutMs });
131
+ return Object.freeze({ ...input });
123
132
  }
@@ -1,5 +1,6 @@
1
1
  import type { IssuerId } from '@astrale-os/kernel-core/auth';
2
2
  import type { AuthApi } from '../auth/index.js';
3
+ import type { ExecutionApi } from '../execution/index.js';
3
4
  import type { SchemaApi } from '../schema/index.js';
4
5
  import type { ContentApi } from './content/index.js';
5
6
  import type { SessionControlOptions } from './context/index.js';
@@ -36,6 +37,7 @@ export interface BoundClientSession extends GraphApi {
36
37
  readonly kernel: IssuerId;
37
38
  readonly auth: AuthApi;
38
39
  readonly schema: SchemaApi;
40
+ readonly execution: ExecutionApi;
39
41
  readonly content: ContentApi;
40
42
  dispatch: ClientSession['dispatch'];
41
43
  call: ClientSession['call'];
@@ -1,5 +1,6 @@
1
1
  import { createAuth } from '../auth/auth.js';
2
2
  import { call as createCall, } from '../client/index.js';
3
+ import { createExecution } from '../execution/index.js';
3
4
  import { createGraph } from '../graph/index.js';
4
5
  /** Capture one Session into the ordinary graph, auth, and invocation Kernel journey. */
5
6
  export function bindSession(source, controls) {
@@ -36,21 +37,43 @@ export function bindSession(source, controls) {
36
37
  const bundle = (origin, options) => schemaSource.bundle(origin, controlOptions(options, admittedControls));
37
38
  const dependencies = (origin, options) => schemaSource.dependencies(origin, controlOptions(options, admittedControls));
38
39
  const installed = (options) => schemaSource.installed(controlOptions(options, admittedControls));
40
+ const installs = schemaSource.installation;
41
+ const installation = Object.freeze({
42
+ status: (execution, options) => installs.status(execution, controlOptions(options, admittedControls)),
43
+ result: (execution, wait, options) => installs.result(execution, wait, controlOptions(options, admittedControls)),
44
+ apply: (execution, command, options) => installs.apply(execution, command, controlOptions(options, admittedControls)),
45
+ abort: (execution, attempt, options) => installs.abort(execution, attempt, controlOptions(options, admittedControls)),
46
+ cancel: (execution, input, options) => installs.cancel(execution, input, controlOptions(options, admittedControls)),
47
+ resume: (execution, options) => installs.resume(execution, controlOptions(options, admittedControls)),
48
+ delete: (execution, options) => installs.delete(execution, controlOptions(options, admittedControls)),
49
+ });
50
+ const uninstalls = schemaSource.uninstallation;
51
+ const uninstallation = Object.freeze({
52
+ status: (execution, options) => uninstalls.status(execution, controlOptions(options, admittedControls)),
53
+ result: (execution, wait, options) => uninstalls.result(execution, wait, controlOptions(options, admittedControls)),
54
+ cancel: (execution, input, options) => uninstalls.cancel(execution, input, controlOptions(options, admittedControls)),
55
+ resume: (execution, options) => uninstalls.resume(execution, controlOptions(options, admittedControls)),
56
+ delete: (execution, options) => uninstalls.delete(execution, controlOptions(options, admittedControls)),
57
+ });
39
58
  const schema = Object.freeze({
40
59
  install,
60
+ installation,
41
61
  uninstall,
62
+ uninstallation,
42
63
  inspect,
43
64
  bundle,
44
65
  dependencies,
45
66
  installed,
46
67
  });
47
68
  const graph = createGraph(call);
69
+ const execution = createExecution(dispatch);
48
70
  const auth = createAuth((target, input, options) => call(createCall(target, input), options), admit);
49
71
  return Object.freeze({
50
72
  ...graph,
51
73
  kernel: source.kernel,
52
74
  auth,
53
75
  schema,
76
+ execution,
54
77
  dispatch,
55
78
  call,
56
79
  invoke,
@@ -106,9 +129,31 @@ function capture(source, key) {
106
129
  function captureSchema(input) {
107
130
  if (input === null || typeof input !== 'object')
108
131
  invalid();
132
+ const installation = input.installation;
133
+ if (installation === null || typeof installation !== 'object')
134
+ invalid();
135
+ const uninstallation = input.uninstallation;
136
+ if (uninstallation === null || typeof uninstallation !== 'object')
137
+ invalid();
109
138
  return Object.freeze({
110
139
  install: capture(input, 'install'),
140
+ installation: Object.freeze({
141
+ status: capture(installation, 'status'),
142
+ result: capture(installation, 'result'),
143
+ apply: capture(installation, 'apply'),
144
+ abort: capture(installation, 'abort'),
145
+ cancel: capture(installation, 'cancel'),
146
+ resume: capture(installation, 'resume'),
147
+ delete: capture(installation, 'delete'),
148
+ }),
111
149
  uninstall: capture(input, 'uninstall'),
150
+ uninstallation: Object.freeze({
151
+ status: capture(uninstallation, 'status'),
152
+ result: capture(uninstallation, 'result'),
153
+ cancel: capture(uninstallation, 'cancel'),
154
+ resume: capture(uninstallation, 'resume'),
155
+ delete: capture(uninstallation, 'delete'),
156
+ }),
112
157
  inspect: capture(input, 'inspect'),
113
158
  bundle: capture(input, 'bundle'),
114
159
  dependencies: capture(input, 'dependencies'),
@@ -1,6 +1,6 @@
1
1
  import { CODES } from '@astrale-os/kernel-protocol/errors';
2
2
  import { ResponseError, TransportError } from '../../errors/index.js';
3
- import { runSessionOperation } from '../context/index.js';
3
+ import { pauseSessionOperation } from '../context/index.js';
4
4
  const MAXIMUM_ATTEMPTS = 3;
5
5
  /** Repeat one content request that failed before any of its result was delivered. */
6
6
  export async function retry(operation, request) {
@@ -12,7 +12,7 @@ export async function retry(operation, request) {
12
12
  if (!retryable(cause) || attempt + 1 === MAXIMUM_ATTEMPTS || operation.signal.aborted) {
13
13
  throw cause;
14
14
  }
15
- await runSessionOperation(operation, (signal) => delay(200 * 2 ** attempt, signal));
15
+ await pauseSessionOperation(operation, 200 * 2 ** attempt);
16
16
  }
17
17
  }
18
18
  }
@@ -24,18 +24,3 @@ function retryable(cause) {
24
24
  cause.code === CODES.DEADLINE_EXCEEDED ||
25
25
  cause.code === CODES.OUTCOME_UNKNOWN)));
26
26
  }
27
- function delay(ms, signal) {
28
- return new Promise((resolve, reject) => {
29
- if (signal.aborted)
30
- return reject(signal.reason);
31
- const timer = setTimeout(() => {
32
- signal.removeEventListener('abort', abort);
33
- resolve();
34
- }, ms);
35
- const abort = () => {
36
- clearTimeout(timer);
37
- reject(signal.reason);
38
- };
39
- signal.addEventListener('abort', abort, { once: true });
40
- });
41
- }
@@ -1,4 +1,4 @@
1
1
  export { admitControlOptions, type SessionControlOptions } from './control.js';
2
2
  export { DEFAULT_MAXIMUM_BUNDLE_BYTES, DEFAULT_MAXIMUM_RELEASE_BYTES, DEFAULT_MAXIMUM_RESPONSE_BYTES, DEFAULT_MAXIMUM_ROUTES, DEFAULT_TIMEOUT_MS, platformDuration, positive, } from './limits.js';
3
- export { createSessionOperation, remainingSessionTime, runSessionOperation, sessionTransportOptions, type SessionOperation, } from './operation.js';
3
+ export { createSessionOperation, pauseSessionOperation, remainingSessionTime, runSessionOperation, sessionTransportOptions, type SessionOperation, } from './operation.js';
4
4
  export { admitKernel, admitPolicy, allowEndpoint, kernelInvocationEndpoint, type SessionPolicy, } from './policy.js';
@@ -1,4 +1,4 @@
1
1
  export { admitControlOptions } from './control.js';
2
2
  export { DEFAULT_MAXIMUM_BUNDLE_BYTES, DEFAULT_MAXIMUM_RELEASE_BYTES, DEFAULT_MAXIMUM_RESPONSE_BYTES, DEFAULT_MAXIMUM_ROUTES, DEFAULT_TIMEOUT_MS, platformDuration, positive, } from './limits.js';
3
- export { createSessionOperation, remainingSessionTime, runSessionOperation, sessionTransportOptions, } from './operation.js';
3
+ export { createSessionOperation, pauseSessionOperation, remainingSessionTime, runSessionOperation, sessionTransportOptions, } from './operation.js';
4
4
  export { admitKernel, admitPolicy, allowEndpoint, kernelInvocationEndpoint, } from './policy.js';
@@ -20,3 +20,5 @@ export declare function sessionTransportOptions(operation: SessionOperation): {
20
20
  export declare function sessionTransportOptions(operation: SessionOperation, idempotencyKey: RequestOptions['idempotencyKey']): RequestOptions;
21
21
  /** Settle independently of a caller capability that ignores its supplied AbortSignal. */
22
22
  export declare function runSessionOperation<Result>(operation: SessionOperation, task: (signal: AbortSignal) => Result | PromiseLike<Result>): Promise<Result>;
23
+ /** Wait `ms` before another attempt, ending early with the operation's interruption. */
24
+ export declare function pauseSessionOperation(operation: SessionOperation, ms: number): Promise<void>;
@@ -54,6 +54,25 @@ export async function runSessionOperation(operation, task) {
54
54
  operation.signal.removeEventListener('abort', abort);
55
55
  });
56
56
  }
57
+ /** Wait `ms` before another attempt, ending early with the operation's interruption. */
58
+ export function pauseSessionOperation(operation, ms) {
59
+ return runSessionOperation(operation, (signal) => delay(ms, signal));
60
+ }
61
+ function delay(ms, signal) {
62
+ return new Promise((resolve, reject) => {
63
+ if (signal.aborted)
64
+ return reject(signal.reason);
65
+ const timer = setTimeout(() => {
66
+ signal.removeEventListener('abort', abort);
67
+ resolve();
68
+ }, ms);
69
+ const abort = () => {
70
+ clearTimeout(timer);
71
+ reject(signal.reason);
72
+ };
73
+ signal.addEventListener('abort', abort, { once: true });
74
+ });
75
+ }
57
76
  function requireSessionOperation(operation) {
58
77
  if (!operation.signal.aborted)
59
78
  return;
@@ -38,6 +38,8 @@ export function credentials(source) {
38
38
  let inflight;
39
39
  let controller;
40
40
  let waiting = 0;
41
+ /** A caller without a signal keeps the mint in flight alive; anticipation does not. */
42
+ let unsignalled = false;
41
43
  let anticipating = false;
42
44
  let refreshTimer;
43
45
  let expiryTimer;
@@ -76,8 +78,10 @@ export function credentials(source) {
76
78
  if (signal?.aborted === true)
77
79
  return Promise.reject(signal.reason);
78
80
  const pending = inflight ?? begin();
79
- if (signal === undefined)
81
+ if (signal === undefined) {
82
+ unsignalled = true;
80
83
  return pending;
84
+ }
81
85
  waiting += 1;
82
86
  let settled = false;
83
87
  return new Promise((complete, fail) => {
@@ -88,7 +92,7 @@ export function credentials(source) {
88
92
  waiting -= 1;
89
93
  signal.removeEventListener('abort', cancel);
90
94
  // Nobody is waiting and nobody is anticipating: the mint has no beneficiary left.
91
- if (waiting === 0 && !anticipating)
95
+ if (waiting === 0 && !anticipating && !unsignalled)
92
96
  controller?.abort(signal.reason);
93
97
  };
94
98
  const cancel = () => {
@@ -124,10 +128,17 @@ export function credentials(source) {
124
128
  publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
125
129
  const owned = new AbortController();
126
130
  controller = owned;
131
+ unsignalled = false;
127
132
  const signal = AbortSignal.any([owned.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
128
133
  const pending = (async () => {
129
134
  try {
130
- const minted = admitMinted(await renew(signal));
135
+ // A mint that throws instead of rejecting fails this attempt alike: the executor turns the
136
+ // throw into a rejection, so the attempt settles only after it yields, once `inflight`
137
+ // holds it, and the cleanup below releases it for the next acquisition.
138
+ const minting = new Promise((complete) => {
139
+ complete(renew(signal));
140
+ });
141
+ const minted = admitMinted(await minting);
131
142
  current = minted;
132
143
  attempt = 0;
133
144
  publish({ status: 'valid', credential: minted });
@@ -166,7 +177,7 @@ export function credentials(source) {
166
177
  if (!anticipating)
167
178
  return;
168
179
  if (current === undefined) {
169
- void share().catch(() => undefined);
180
+ void (inflight ?? begin()).catch(() => undefined);
170
181
  return;
171
182
  }
172
183
  // The threshold itself, with no extra lead: chained providers sharing this rule must not
@@ -189,7 +200,7 @@ export function credentials(source) {
189
200
  function armRefresh(delay) {
190
201
  refreshTimer = setTimeout(() => {
191
202
  refreshTimer = undefined;
192
- void share().catch(() => undefined);
203
+ void (inflight ?? begin()).catch(() => undefined);
193
204
  }, delay);
194
205
  }
195
206
  function armExpiry(credential) {
@@ -0,0 +1,13 @@
1
+ import type { SessionOperation } from './context/index.js';
2
+ import type { SessionRequestOptions } from './routing/index.js';
3
+ /**
4
+ * Options of one typed invocation of a durable callable: the caller's key, or one created for this
5
+ * call. The key names the Execution, so every attempt of the call reaches the same one.
6
+ */
7
+ export declare function durableOptions(options: Readonly<SessionRequestOptions>): Readonly<SessionRequestOptions>;
8
+ /**
9
+ * Send a keyed durable invocation again while its outcome is unknown: a transport failure, sent or
10
+ * not, or the Kernel's `OUTCOME_UNKNOWN`. Its key makes the Kernel answer with the Execution a lost
11
+ * attempt recorded, marked `replayed`, instead of starting another.
12
+ */
13
+ export declare function attemptDurable<Result>(operation: SessionOperation, attempt: () => Promise<Result>): Promise<Result>;
@@ -0,0 +1,45 @@
1
+ import { CODES } from '@astrale-os/kernel-protocol/errors';
2
+ import * as invocationProtocol from '@astrale-os/kernel-protocol/invocation';
3
+ import { ResponseError, TransportError } from '../errors/index.js';
4
+ import { pauseSessionOperation } from './context/index.js';
5
+ /** The first attempt of a durable invocation and at most two more, within its one deadline. */
6
+ const MAXIMUM_ATTEMPTS = 3;
7
+ const FIRST_PAUSE_MS = 200;
8
+ /**
9
+ * Options of one typed invocation of a durable callable: the caller's key, or one created for this
10
+ * call. The key names the Execution, so every attempt of the call reaches the same one.
11
+ */
12
+ export function durableOptions(options) {
13
+ if (options.idempotencyKey !== undefined)
14
+ return options;
15
+ return Object.freeze({
16
+ ...options,
17
+ idempotencyKey: invocationProtocol.acceptIdempotencyKey(crypto.randomUUID()),
18
+ });
19
+ }
20
+ /**
21
+ * Send a keyed durable invocation again while its outcome is unknown: a transport failure, sent or
22
+ * not, or the Kernel's `OUTCOME_UNKNOWN`. Its key makes the Kernel answer with the Execution a lost
23
+ * attempt recorded, marked `replayed`, instead of starting another.
24
+ */
25
+ export async function attemptDurable(operation, attempt) {
26
+ for (let attempts = 1;; attempts++) {
27
+ try {
28
+ return await attempt();
29
+ }
30
+ catch (cause) {
31
+ const pause = FIRST_PAUSE_MS * 2 ** (attempts - 1);
32
+ if (attempts === MAXIMUM_ATTEMPTS ||
33
+ !unknownOutcome(cause) ||
34
+ operation.signal.aborted ||
35
+ operation.deadline - Date.now() <= pause) {
36
+ throw cause;
37
+ }
38
+ await pauseSessionOperation(operation, pause);
39
+ }
40
+ }
41
+ }
42
+ function unknownOutcome(cause) {
43
+ return ((cause instanceof TransportError && cause.context.kind === 'invocation') ||
44
+ (cause instanceof ResponseError && cause.code === CODES.OUTCOME_UNKNOWN));
45
+ }
@@ -9,6 +9,6 @@ export type { ClientSessionOptions } from './options.js';
9
9
  export { ClientSession, connect, type ConnectOptions } from './session.js';
10
10
  export type { CallableReference, InputOfReference, InputModeOfReference, InstanceCallableReference, OutputOfReference, } from './reference.js';
11
11
  export { reference } from './reference.js';
12
- export { execution, type ExecutionOutcome, type ExecutionRef, type ExecutionState, type ExecutionStatus, } from './execution.js';
12
+ export type { DeletedExecutionStatus, ExecutionApi, ExecutionFailure, ExecutionNodeStatus, ExecutionOutcome, ExecutionRef, ExecutionState, ExecutionStatus, ExecutionTarget, ExecutionWait, } from '../execution/index.js';
13
13
  export type { ResolvedView, ViewCatalog } from './views/index.js';
14
14
  export type { DomainBinding } from '../graph/domain/index.js';
@@ -2,4 +2,3 @@ export { bindSession, } from './bound.js';
2
2
  export { credentials, } from './credential/index.js';
3
3
  export { ClientSession, connect } from './session.js';
4
4
  export { reference } from './reference.js';
5
- export { execution, } from './execution.js';
@@ -33,7 +33,6 @@ export interface ClientSessionOptions {
33
33
  readonly maximumBundleBytes?: number;
34
34
  readonly maximumResponseBytes?: number;
35
35
  readonly timeoutMs?: number;
36
- readonly schemaLifecycleTimeoutMs?: number;
37
36
  }
38
37
  /** The caller's options once admitted, defaulted and captured, ready for the Session to wire. */
39
38
  export interface SessionConfiguration {
@@ -45,7 +44,6 @@ export interface SessionConfiguration {
45
44
  readonly maximumBundleBytes: number;
46
45
  readonly maximumResponseBytes: number;
47
46
  readonly timeoutMs: number;
48
- readonly schemaLifecycleTimeoutMs: number;
49
47
  readonly websocketAvailable: boolean;
50
48
  /** Present when the Session created, and therefore closes, its own pool. */
51
49
  readonly ownedPool?: ClientPool;
@@ -1,6 +1,5 @@
1
1
  import { Client } from '../client/index.js';
2
2
  import { ClientPool } from '../pool/index.js';
3
- import { DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS } from '../schema/index.js';
4
3
  import { AutoTransport } from '../transport/auto/index.js';
5
4
  import { HttpTransport } from '../transport/http/index.js';
6
5
  import { WebSocketTransport } from '../transport/websocket/index.js';
@@ -30,7 +29,6 @@ export function acceptSessionOptions(options) {
30
29
  const maximumBundleBytes = positive(options.maximumBundleBytes ?? DEFAULT_MAXIMUM_BUNDLE_BYTES, 'maximumBundleBytes');
31
30
  const maximumResponseBytes = positive(options.maximumResponseBytes ?? DEFAULT_MAXIMUM_RESPONSE_BYTES, 'maximumResponseBytes');
32
31
  const timeoutMs = platformDuration(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, 'timeoutMs');
33
- const schemaLifecycleTimeoutMs = platformDuration(options.schemaLifecycleTimeoutMs ?? DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS, 'schemaLifecycleTimeoutMs');
34
32
  let ownedPool;
35
33
  let pool;
36
34
  if (options.pool === undefined) {
@@ -62,7 +60,6 @@ export function acceptSessionOptions(options) {
62
60
  maximumBundleBytes,
63
61
  maximumResponseBytes,
64
62
  timeoutMs,
65
- schemaLifecycleTimeoutMs,
66
63
  websocketAvailable: options.client !== undefined ||
67
64
  options.pool !== undefined ||
68
65
  options.websocket !== undefined ||
@@ -1,10 +1,12 @@
1
1
  import type { Path as PathValue, PathLike } from '@astrale-os/kernel-core/path';
2
- import type { CallableInputOf, CallableInputModeOf, CallableOutputOf, CallableResultOf, Domain, ResolvedFunction, ExecutableMethod } from '@astrale-os/kernel-dsl/v1';
2
+ import type { CallableInputOf, CallableInputModeOf, CallableOutputOf, CallableResultOf, Domain, ResolvedFunction, ExecutableMethod, ResolvedMethod } from '@astrale-os/kernel-dsl/v1';
3
3
  import type { MethodAddress } from '@astrale-os/kernel-dsl/v1/addressing';
4
4
  import type { MeaningFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprint';
5
5
  import { type Key as KeyType } from '@astrale-os/kernel-dsl/v1/addressing';
6
- import type { Binary, Input } from '../client/index.js';
7
- import type { ExecutionRef } from './execution.js';
6
+ import type { Binary, Input, Result } from '../client/index.js';
7
+ import type { ExecutionRef } from '../execution/index.js';
8
+ /** Result kind a reference expects: a durable callable answers with its Execution. */
9
+ type OutputMode = Exclude<Result['kind'], 'redirect'>;
8
10
  declare const REFERENCE_INPUT: unique symbol;
9
11
  declare const REFERENCE_INPUT_MODE: unique symbol;
10
12
  declare const REFERENCE_OUTPUT: unique symbol;
@@ -14,7 +16,7 @@ export interface CallableReference<InputValue = Input, Output = unknown, InputMo
14
16
  readonly fingerprint?: MeaningFingerprint;
15
17
  readonly callable: KeyType.Callable;
16
18
  readonly target: PathValue;
17
- readonly outputMode: 'value' | 'stream' | 'binary';
19
+ readonly outputMode: OutputMode;
18
20
  readonly [REFERENCE_INPUT]?: InputValue;
19
21
  readonly [REFERENCE_INPUT_MODE]?: InputMode;
20
22
  readonly [REFERENCE_OUTPUT]?: Output;
@@ -24,7 +26,7 @@ export interface InstanceCallableReference<InputValue = Input, Output = unknown>
24
26
  readonly origin: KeyType.Origin;
25
27
  readonly fingerprint?: MeaningFingerprint;
26
28
  readonly callable: KeyType.Callable;
27
- readonly outputMode: 'value' | 'stream' | 'binary';
29
+ readonly outputMode: OutputMode;
28
30
  }
29
31
  export type InputOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer InputValue, unknown> ? InputValue : never;
30
32
  export type OutputOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer _Input, infer Output> ? Output : never;
@@ -47,6 +49,8 @@ export declare function reference<const Callable extends ExecutableInstanceMetho
47
49
  * addresses every Kernel syscall. Loading the Session therefore never resolves the Kernel Schema.
48
50
  */
49
51
  export declare function kernelReference(method: MethodAddress): InstanceCallableReference<unknown>;
52
+ /** The result kind invoking this callable yields. */
53
+ export declare function outputModeOf(callable: ResolvedFunction | ResolvedMethod): OutputMode;
50
54
  export declare function admitReference(input: CallableReference<unknown>): CallableReference<unknown>;
51
55
  export declare function matchesCallable(target: PathValue, callable: KeyType.Callable): boolean;
52
56
  export {};
@@ -2,6 +2,7 @@ import { Path } from '@astrale-os/kernel-core/path';
2
2
  import { callableAddress, Key, MethodKey, patterns, } from '@astrale-os/kernel-dsl/v1/addressing';
3
3
  import { callableFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprint';
4
4
  const FINGERPRINT_PATTERN = /^sha256:[0-9a-f]{64}$/u;
5
+ const OUTPUT_MODES = ['value', 'stream', 'binary', 'execution'];
5
6
  export function reference(domain, callable) {
6
7
  if (Key.origin(callable.key) !== domain.origin)
7
8
  invalid();
@@ -11,7 +12,7 @@ export function reference(domain, callable) {
11
12
  origin: domain.origin,
12
13
  fingerprint: callableFingerprint(callable),
13
14
  callable: callable.key,
14
- outputMode: callable.output.mode,
15
+ outputMode: outputModeOf(callable),
15
16
  });
16
17
  if ('owner' in callable && !callable.static) {
17
18
  const bind = (receiver) => admitReference({
@@ -39,6 +40,10 @@ export function kernelReference(method) {
39
40
  const bind = (receiver) => admitReference({ ...common, target: Path.instanceMethod(Path.from(receiver), callable) });
40
41
  return Object.assign(bind, common);
41
42
  }
43
+ /** The result kind invoking this callable yields. */
44
+ export function outputModeOf(callable) {
45
+ return callable.execution?.durable === true ? 'execution' : callable.output.mode;
46
+ }
42
47
  export function admitReference(input) {
43
48
  if (input === null || typeof input !== 'object')
44
49
  invalid();
@@ -47,7 +52,7 @@ export function admitReference(input) {
47
52
  typeof input.callable !== 'string' ||
48
53
  !Key.is(input.callable) ||
49
54
  Key.origin(input.callable) !== input.origin ||
50
- !['value', 'stream', 'binary'].includes(input.outputMode) ||
55
+ !OUTPUT_MODES.includes(input.outputMode) ||
51
56
  (input.fingerprint !== undefined &&
52
57
  (typeof input.fingerprint !== 'string' || !FINGERPRINT_PATTERN.test(input.fingerprint))))
53
58
  invalid();