@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
@@ -2,5 +2,5 @@ export { Client, dispatchTrace, type ClientOptions } from './client.js';
2
2
  export { acceptCall } from './admission.js';
3
3
  export type { AuthenticatedClient, RemoteCredential } from './credential.js';
4
4
  export { call, type Call, type ClientDispatchOptions, type ClientDispatchOptionsWithBody, } from './request.js';
5
- export type { Binary, BinaryResponse, Input, RedirectResult, Result, Stream, StreamResult, ValueResult, } from './result.js';
5
+ export type { Binary, BinaryResponse, ExecutionResult, Input, RedirectResult, Result, Stream, StreamResult, ValueResult, } from './result.js';
6
6
  export { isAdmittedDeploymentRetiredError, isAdmittedMissError, isAdmittedStaleRouteError, } from './routing-control.js';
@@ -25,6 +25,7 @@ export interface AdmittedRequest {
25
25
  readonly delegate?: protocol.Delegate;
26
26
  readonly routing?: protocol.Routing;
27
27
  readonly schema?: protocol.SchemaTarget;
28
+ readonly maintenance?: protocol.Maintenance;
28
29
  readonly options: RequestOptions;
29
30
  readonly body?: Blob;
30
31
  }
@@ -10,11 +10,13 @@ export function admitRequest(input, options, lifecycle) {
10
10
  const delegate = admitDelegate(options?.delegate);
11
11
  const routing = admitRouting(options?.routing);
12
12
  const schema = admitSchemaTarget(options?.schema);
13
+ const maintenance = admitMaintenance(options?.maintenance);
13
14
  return Object.freeze({
14
15
  call,
15
16
  ...(delegate === undefined ? {} : { delegate }),
16
17
  ...(routing === undefined ? {} : { routing }),
17
18
  ...(schema === undefined ? {} : { schema }),
19
+ ...(maintenance === undefined ? {} : { maintenance }),
18
20
  ...(admitted.body === undefined ? {} : { body: admitted.body }),
19
21
  options: admittedOptions,
20
22
  });
@@ -28,6 +30,9 @@ export function invocation(request, credential, trace) {
28
30
  if (request.schema !== undefined) {
29
31
  throw new TypeError('Destination Client requests cannot carry a Schema target.');
30
32
  }
33
+ if (request.maintenance !== undefined) {
34
+ throw new TypeError('Destination Client requests cannot carry a maintenance guard.');
35
+ }
31
36
  }
32
37
  else if ((credential === undefined) !== (request.delegate === undefined)) {
33
38
  throw new TypeError('Source Client credentials and delegation requests must occur together.');
@@ -38,6 +43,7 @@ export function invocation(request, credential, trace) {
38
43
  ...(request.delegate === undefined ? {} : { delegate: request.delegate }),
39
44
  ...(request.routing === undefined ? {} : { routing: request.routing }),
40
45
  ...(request.schema === undefined ? {} : { schema: request.schema }),
46
+ ...(request.maintenance === undefined ? {} : { maintenance: request.maintenance }),
41
47
  ...(admittedTrace === undefined ? {} : { trace: admittedTrace }),
42
48
  });
43
49
  }
@@ -54,6 +60,7 @@ function admitRequestOptions(input) {
54
60
  'delegate',
55
61
  'routing',
56
62
  'schema',
63
+ 'maintenance',
57
64
  'body',
58
65
  ].includes(String(field)))) {
59
66
  throw new TypeError('Client request options contain unsupported fields.');
@@ -118,6 +125,16 @@ function admitSchemaTarget(input) {
118
125
  throw new TypeError('Client Schema target is invalid.', { cause });
119
126
  }
120
127
  }
128
+ function admitMaintenance(input) {
129
+ if (input === undefined)
130
+ return undefined;
131
+ try {
132
+ return invocationProtocol.acceptMaintenance(input);
133
+ }
134
+ catch (cause) {
135
+ throw new TypeError('Client maintenance guard is invalid.', { cause });
136
+ }
137
+ }
121
138
  function lifecycleOptions(input, lifecycle) {
122
139
  const signal = input?.signal === undefined ? lifecycle : AbortSignal.any([input.signal, lifecycle]);
123
140
  return Object.freeze({
@@ -23,12 +23,21 @@ export type StreamResult = Correlated<Extract<Callable, {
23
23
  export type BinaryResponse = Correlated<Extract<Callable, {
24
24
  readonly kind: 'binary';
25
25
  }>>;
26
+ /**
27
+ * A durable call's answer. `replayed` is absent when the Host does not say whether the call
28
+ * replayed its Execution.
29
+ */
30
+ export type ExecutionResult = Correlated<Omit<Extract<Callable, {
31
+ readonly kind: 'execution';
32
+ }>, 'replayed'> & {
33
+ readonly replayed?: boolean;
34
+ }>;
26
35
  export interface RedirectResult {
27
36
  readonly kind: 'redirect';
28
37
  readonly redirect: protocol.Redirection;
29
38
  readonly invocation: protocol.InvocationId;
30
39
  }
31
- export type Result = ValueResult | StreamResult | BinaryResponse | RedirectResult;
40
+ export type Result = ValueResult | StreamResult | BinaryResponse | ExecutionResult | RedirectResult;
32
41
  export declare function requireValue(result: Promise<Result>): Promise<ValueResult>;
33
42
  export declare function requireStream(result: Promise<Result>): Promise<StreamResult>;
34
43
  export declare function requireBinary(result: Promise<Result>): Promise<BinaryResponse>;
@@ -8,7 +8,7 @@ export async function requireValue(result) {
8
8
  export async function requireStream(result) {
9
9
  const settled = await result;
10
10
  if (settled.kind !== 'stream')
11
- mismatch('stream', settled.kind);
11
+ mismatch('stream', settled);
12
12
  return settled;
13
13
  }
14
14
  export async function requireBinary(result) {
@@ -17,8 +17,14 @@ export async function requireBinary(result) {
17
17
  return rejectMismatch('binary', settled);
18
18
  return settled;
19
19
  }
20
- function mismatch(expected, received) {
21
- throw new ClientError(`Function returned ${received}; ${expected} was required.`);
20
+ function mismatch(expected, result) {
21
+ throw new ClientError(`${returned(result)}; ${expected} was required.`);
22
+ }
23
+ /** What the call did; a started Execution is named so its caller never starts it again. */
24
+ function returned(result) {
25
+ return result.kind === 'execution'
26
+ ? `Function started Execution ${result.execution}`
27
+ : `Function returned ${result.kind}`;
22
28
  }
23
29
  async function rejectMismatch(expected, result) {
24
30
  if (result.kind === 'stream') {
@@ -27,5 +33,5 @@ async function rejectMismatch(expected, result) {
27
33
  if (result.kind === 'binary' && !(result.value.body instanceof Uint8Array)) {
28
34
  await result.value.body[Symbol.asyncIterator]().return?.();
29
35
  }
30
- mismatch(expected, result.kind);
36
+ mismatch(expected, result);
31
37
  }
@@ -2,6 +2,7 @@ export * from './client-error.js';
2
2
  export * from './exchange-error.js';
3
3
  export * from './miss-error.js';
4
4
  export * from './protocol-error.js';
5
+ export * from './refusal.js';
5
6
  export * from './response-error.js';
6
7
  export * from './session-error.js';
7
8
  export * from './stale-route-error.js';
@@ -2,6 +2,7 @@ export * from './client-error.js';
2
2
  export * from './exchange-error.js';
3
3
  export * from './miss-error.js';
4
4
  export * from './protocol-error.js';
5
+ export * from './refusal.js';
5
6
  export * from './response-error.js';
6
7
  export * from './session-error.js';
7
8
  export * from './stale-route-error.js';
@@ -0,0 +1,19 @@
1
+ import { ResponseError } from './response-error.js';
2
+ /** Return the delay a refused invocation prescribes before it is sent again, and nothing else. */
3
+ export declare function retryAfterOf(error: unknown): number | undefined;
4
+ /** Whether the Instance refused the invocation because a maintenance session admits only root. */
5
+ export declare function isMaintenance(error: unknown): error is ResponseError;
6
+ /**
7
+ * Whether the Kernel refused a request whose maintenance guard names a session that does not own
8
+ * the Instance: it ended, or another one owns it. Nothing ran; resending it unchanged cannot succeed.
9
+ */
10
+ export declare function isMaintenanceSessionStale(error: unknown): error is ResponseError;
11
+ /** Whether a sealed conflict ran nothing because the graph snapshot advanced; resend it at once. */
12
+ export declare function isSnapshotStale(error: unknown): error is ResponseError;
13
+ /**
14
+ * Whether the Kernel refused a request because the client was built against a Domain meaning this
15
+ * Instance does not serve: the revision a Query or a Mutation expects of a Domain, or the meaning
16
+ * of a callable. Nothing ran; resending it unchanged cannot succeed, so the client is rebuilt or
17
+ * reloaded against what the Instance serves.
18
+ */
19
+ export declare function isExpectationMismatch(error: unknown): error is ResponseError;
@@ -0,0 +1,63 @@
1
+ import * as errors from '@astrale-os/kernel-protocol/errors';
2
+ import { CALLABLE_FINGERPRINT_MISMATCH } from '@astrale-os/kernel-protocol/invocation';
3
+ import { ResponseError } from './response-error.js';
4
+ /**
5
+ * Sealed conflicts whose plan met a checkpoint advanced past its pinned snapshot, an Authority
6
+ * evaluation's included (POLICY_SNAPSHOT_MISMATCH).
7
+ */
8
+ const SNAPSHOT_STALE_REASONS = new Set([
9
+ 'SNAPSHOT_STALE',
10
+ 'QUERY_SNAPSHOT_STALE',
11
+ 'MUTATION_SNAPSHOT_STALE',
12
+ 'POLICY_SNAPSHOT_MISMATCH',
13
+ ]);
14
+ /** Conflicts whose request expects a Domain meaning this Instance does not serve. */
15
+ const EXPECTATION_MISMATCH_REASONS = new Set([
16
+ 'QUERY_EXPECTATION_MISMATCH',
17
+ 'MUTATION_EXPECTATION_MISMATCH',
18
+ CALLABLE_FINGERPRINT_MISMATCH,
19
+ ]);
20
+ /** Return the delay a refused invocation prescribes before it is sent again, and nothing else. */
21
+ export function retryAfterOf(error) {
22
+ if (!(error instanceof ResponseError))
23
+ return undefined;
24
+ return errors.retryAfterOf({
25
+ code: error.code,
26
+ message: error.message,
27
+ ...(error.data === undefined ? {} : { data: error.data }),
28
+ });
29
+ }
30
+ /** Whether the Instance refused the invocation because a maintenance session admits only root. */
31
+ export function isMaintenance(error) {
32
+ return (error instanceof ResponseError &&
33
+ error.reason?.code === errors.RETRY_REASONS.INSTANCE_MAINTENANCE &&
34
+ retryAfterOf(error) !== undefined);
35
+ }
36
+ /**
37
+ * Whether the Kernel refused a request whose maintenance guard names a session that does not own
38
+ * the Instance: it ended, or another one owns it. Nothing ran; resending it unchanged cannot succeed.
39
+ */
40
+ export function isMaintenanceSessionStale(error) {
41
+ return (error instanceof ResponseError &&
42
+ error.code === errors.CODES.CONFLICT &&
43
+ error.reason?.code === 'MAINTENANCE_SESSION_STALE');
44
+ }
45
+ /** Whether a sealed conflict ran nothing because the graph snapshot advanced; resend it at once. */
46
+ export function isSnapshotStale(error) {
47
+ return (error instanceof ResponseError &&
48
+ error.code === errors.CODES.CONFLICT &&
49
+ error.reason !== undefined &&
50
+ SNAPSHOT_STALE_REASONS.has(error.reason.code));
51
+ }
52
+ /**
53
+ * Whether the Kernel refused a request because the client was built against a Domain meaning this
54
+ * Instance does not serve: the revision a Query or a Mutation expects of a Domain, or the meaning
55
+ * of a callable. Nothing ran; resending it unchanged cannot succeed, so the client is rebuilt or
56
+ * reloaded against what the Instance serves.
57
+ */
58
+ export function isExpectationMismatch(error) {
59
+ return (error instanceof ResponseError &&
60
+ error.code === errors.CODES.CONFLICT &&
61
+ error.reason !== undefined &&
62
+ EXPECTATION_MISMATCH_REASONS.has(error.reason.code));
63
+ }
@@ -7,6 +7,6 @@ interface OutputContract {
7
7
  readonly success: false;
8
8
  };
9
9
  }
10
- /** Admit one value result through its Core-owned syscall contract. */
11
- export declare function acceptOutput<T>(contract: OutputContract, input: unknown): T;
10
+ /** Admit one value an Execution Method answered through its Core-owned contract. */
11
+ export declare function acceptOutput<T>(contract: OutputContract, input: unknown, what: string): T;
12
12
  export {};
@@ -1,10 +1,10 @@
1
1
  import * as portable from '@astrale-os/kernel-dsl/value';
2
- /** Admit one value result through its Core-owned syscall contract. */
3
- export function acceptOutput(contract, input) {
2
+ /** Admit one value an Execution Method answered through its Core-owned contract. */
3
+ export function acceptOutput(contract, input, what) {
4
4
  const value = portable.accept(input);
5
5
  const parsed = contract.safeParse(value);
6
6
  if (!parsed.success)
7
- throw new TypeError('Kernel returned an invalid Schema result.');
7
+ throw new TypeError(`Kernel returned an invalid ${what}.`);
8
8
  return freeze(parsed.data);
9
9
  }
10
10
  function freeze(input) {
@@ -0,0 +1,76 @@
1
+ import type { NodeId } from '@astrale-os/kernel-core/graph/node';
2
+ import type { SystemExecutionDetail } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
+ import type { Value } from '@astrale-os/kernel-dsl/value';
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
+ /**
12
+ * Present on the reference a durable call answered when its Host says: false when that call
13
+ * created the Execution, true when its idempotency key already named it.
14
+ */
15
+ readonly replayed?: boolean;
16
+ readonly [EXECUTION_OUTPUT]?: Output;
17
+ }
18
+ /** An Execution, by its reference or by its NodeId. */
19
+ export type ExecutionTarget<Output = unknown> = ExecutionRef<Output> | NodeId;
20
+ /** The public failure an Execution ended with, such as `DATA_MIGRATION_REQUIRED`. */
21
+ export interface ExecutionFailure {
22
+ readonly code: string;
23
+ readonly message: string;
24
+ readonly family?: string;
25
+ readonly details?: Value;
26
+ }
27
+ /** A terminal Execution: its completed value, its failure, or its cancellation. */
28
+ export type ExecutionOutcome<Output = unknown> = {
29
+ readonly kind: 'completed';
30
+ readonly value: Output;
31
+ } | {
32
+ readonly kind: 'failed';
33
+ readonly error: ExecutionFailure;
34
+ } | {
35
+ readonly kind: 'cancelled';
36
+ };
37
+ export type ExecutionState = 'pending' | 'running' | 'waiting' | 'paused' | 'completed' | 'failed' | 'cancelled' | 'expired';
38
+ /**
39
+ * The status of an Execution: its node's, or what Root reads of a system execution whose node was
40
+ * deleted.
41
+ */
42
+ export type ExecutionStatus<Output = unknown> = ExecutionNodeStatus<Output> | DeletedExecutionStatus<Output>;
43
+ /** The status of an Execution whose node exists, with the engine state of its run. */
44
+ export interface ExecutionNodeStatus<Output = unknown> {
45
+ readonly id: NodeId;
46
+ readonly function: NodeId;
47
+ readonly version: `sha256:${string}`;
48
+ readonly state: ExecutionState;
49
+ readonly createdAt: string;
50
+ /** A system execution's step, progress and session state, as Core shapes it. */
51
+ readonly detail?: SystemExecutionDetail;
52
+ /** Present exactly once the Execution is terminal. */
53
+ readonly outcome?: ExecutionOutcome<Output>;
54
+ }
55
+ /**
56
+ * What Root alone reads of a system execution whose node was deleted: the outcome its lifecycle
57
+ * record keeps, under the explicit state `deleted`, never a live state.
58
+ */
59
+ export interface DeletedExecutionStatus<Output = unknown> {
60
+ readonly id: NodeId;
61
+ readonly state: 'deleted';
62
+ readonly outcome: ExecutionOutcome<Output>;
63
+ /** Absent: the node that recorded them is deleted. */
64
+ readonly function?: never;
65
+ readonly version?: never;
66
+ readonly createdAt?: never;
67
+ readonly detail?: never;
68
+ }
69
+ /**
70
+ * How long a call waits for the terminal outcome, in total, across as many `Execution.result`
71
+ * requests as it takes. Absent or `0`, the call answers what the Execution holds now.
72
+ */
73
+ export interface ExecutionWait {
74
+ readonly waitMs?: number;
75
+ }
76
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { RequestOptions } from '../transport/index.js';
2
+ /**
3
+ * The absolute deadline of one Client call, whatever number of Kernel requests it sends: its
4
+ * `timeoutMs` from now when given, otherwise none (`Infinity`), each request then taking its default.
5
+ */
6
+ export declare function deadlineOf(options: RequestOptions | undefined): number;
7
+ /** The options of the call's next request: the time left before its deadline, at least 1 ms. */
8
+ export declare function within(deadline: number, options: RequestOptions | undefined): RequestOptions | undefined;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The absolute deadline of one Client call, whatever number of Kernel requests it sends: its
3
+ * `timeoutMs` from now when given, otherwise none (`Infinity`), each request then taking its default.
4
+ */
5
+ export function deadlineOf(options) {
6
+ return options?.timeoutMs === undefined ? Infinity : Date.now() + options.timeoutMs;
7
+ }
8
+ /** The options of the call's next request: the time left before its deadline, at least 1 ms. */
9
+ export function within(deadline, options) {
10
+ if (deadline === Infinity)
11
+ return options;
12
+ return { ...options, timeoutMs: Math.max(1, deadline - Date.now()) };
13
+ }
@@ -0,0 +1,57 @@
1
+ import type { Value } from '@astrale-os/kernel-dsl/value';
2
+ import type { Call, Result } from '../client/index.js';
3
+ import type { RequestOptions } from '../transport/index.js';
4
+ import type { ExecutionOutcome, ExecutionStatus, ExecutionTarget, ExecutionWait } from './contracts.js';
5
+ /** The value-call capability the `K.Execution` Methods are sent through. */
6
+ export type ExecutionCall = (call: Call, options?: RequestOptions) => Promise<Result>;
7
+ /**
8
+ * The `K.Execution` Methods of any Execution. Observing and a cooperative cancel are the Domain's
9
+ * or the initiator's; signals, a forced cancel, resume and delete are the owner Domain's (Root's
10
+ * for an install). A completed value is typed by the reference alone.
11
+ */
12
+ export interface ExecutionApi {
13
+ status<Output>(execution: ExecutionTarget<Output>, options?: RequestOptions): Promise<ExecutionStatus<Output>>;
14
+ /**
15
+ * The terminal outcome, waiting at most `waitMs` for it in total; the Kernel's
16
+ * `EXECUTION_PENDING` once that wait lapses. Ending the wait never ends the Execution.
17
+ */
18
+ result<Output>(execution: ExecutionTarget<Output>, wait?: ExecutionWait, options?: RequestOptions): Promise<ExecutionOutcome<Output>>;
19
+ /** Resolve the named durable promise once. */
20
+ signal(execution: ExecutionTarget, signal: {
21
+ readonly name: string;
22
+ readonly value: Value;
23
+ }, options?: RequestOptions): Promise<void>;
24
+ /** A cooperative cancel; `force` kills the run without compensation. */
25
+ cancel<Output>(execution: ExecutionTarget<Output>, input?: {
26
+ readonly force?: boolean;
27
+ }, options?: RequestOptions): Promise<ExecutionStatus<Output>>;
28
+ /** Resume a paused Execution; a running one is unchanged. */
29
+ resume<Output>(execution: ExecutionTarget<Output>, options?: RequestOptions): Promise<ExecutionStatus<Output>>;
30
+ /** Delete the Execution, then kill and purge its run. */
31
+ delete(execution: ExecutionTarget, options?: RequestOptions): Promise<void>;
32
+ }
33
+ /** The `K.Execution` Methods of one kind of Execution, its completed value admitted as `Completed`. */
34
+ export interface ExecutionMethods<Completed> {
35
+ status(execution: ExecutionTarget, options?: RequestOptions): Promise<ExecutionStatus<Completed>>;
36
+ result(execution: ExecutionTarget, wait?: ExecutionWait, options?: RequestOptions): Promise<ExecutionOutcome<Completed>>;
37
+ signal(execution: ExecutionTarget, signal: {
38
+ readonly name: string;
39
+ readonly value: unknown;
40
+ }, options?: RequestOptions): Promise<void>;
41
+ cancel(execution: ExecutionTarget, input?: {
42
+ readonly force?: boolean;
43
+ }, options?: RequestOptions): Promise<ExecutionStatus<Completed>>;
44
+ resume(execution: ExecutionTarget, options?: RequestOptions): Promise<ExecutionStatus<Completed>>;
45
+ delete(execution: ExecutionTarget, options?: RequestOptions): Promise<void>;
46
+ }
47
+ /** Bind the `K.Execution` Methods to one call capability. */
48
+ export declare function createExecution(call: ExecutionCall): ExecutionApi;
49
+ /**
50
+ * The `K.Execution` Methods over one call capability, a completed value admitted by `accept`.
51
+ * Status and outcome are admitted against their Core contracts. The effect-free reads, `status`
52
+ * and `result`, are sent again through the pacer after a TransportError or a refusal that carries
53
+ * a retry delay, within the call's deadline; the other Methods are sent once.
54
+ */
55
+ export declare function executionMethods<Completed>(call: ExecutionCall, accept: (value: unknown) => Completed): ExecutionMethods<Completed>;
56
+ /** The wait an `ExecutionWait` asks for, in milliseconds. */
57
+ export declare function acceptWait(wait: ExecutionWait | undefined): number;
@@ -0,0 +1,137 @@
1
+ import { Path } from '@astrale-os/kernel-core/path';
2
+ import { executionOutcome, executionStatus, } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
+ import { execution as methods } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
4
+ import { MethodKey } from '@astrale-os/kernel-dsl/v1/addressing';
5
+ import { call as invocation } from '../client/index.js';
6
+ import { ResponseError, TransportError } from '../errors/index.js';
7
+ import { RETRY_REFUSALS, retry } from '../pacer/index.js';
8
+ import { acceptOutput } from './admission.js';
9
+ import { deadlineOf, within } from './deadline.js';
10
+ /** Attempts of one effect-free Execution read; the call's deadline bounds them too. */
11
+ const READ_ATTEMPTS = 8;
12
+ /** A pending answer sooner than this did not wait: the Kernel answers now, so waiting ends. */
13
+ const LAPSED_WAIT_MS = 1_000;
14
+ /** No wait is sent again with less time left than this. */
15
+ const MINIMUM_WAIT_MS = 1_000;
16
+ /**
17
+ * The time a wait leaves its answer to come back. The Kernel bounds a wait by its own request
18
+ * deadline, never by this call's: the client ends each wait this long before its request times out.
19
+ */
20
+ const ANSWER_MARGIN_MS = 2_000;
21
+ /** Bind the `K.Execution` Methods to one call capability. */
22
+ export function createExecution(call) {
23
+ // A completed value is the handler output, which only the reference types.
24
+ return executionMethods(call, (value) => value);
25
+ }
26
+ /**
27
+ * The `K.Execution` Methods over one call capability, a completed value admitted by `accept`.
28
+ * Status and outcome are admitted against their Core contracts. The effect-free reads, `status`
29
+ * and `result`, are sent again through the pacer after a TransportError or a refusal that carries
30
+ * a retry delay, within the call's deadline; the other Methods are sent once.
31
+ */
32
+ export function executionMethods(call, accept) {
33
+ const send = async (id, method, input, options) => {
34
+ const target = Path.instanceMethod(Path.id(id), MethodKey.of(method.owner, method.name));
35
+ const result = await call(invocation(target, input), options);
36
+ if (result.kind !== 'value')
37
+ throw new TypeError('Execution Method returned a non-value result.');
38
+ return result.value;
39
+ };
40
+ const read = (deadline, options, work) => retry(() => work(within(deadline, options)), {
41
+ maxAttempts: READ_ATTEMPTS,
42
+ shouldRetry: (error, attempt) => Date.now() < deadline &&
43
+ (error instanceof TransportError || RETRY_REFUSALS.shouldRetry(error, attempt)),
44
+ retryAfter: RETRY_REFUSALS.retryAfter,
45
+ });
46
+ const outcomeOf = (input) => {
47
+ const outcome = acceptOutput(executionOutcome, input, 'Execution outcome');
48
+ if (outcome.kind !== 'completed')
49
+ return outcome;
50
+ return Object.freeze({ kind: 'completed', value: accept(outcome.value) });
51
+ };
52
+ const statusOf = (id, input) => {
53
+ const admitted = acceptOutput(executionStatus, input, 'Execution status');
54
+ if (admitted.id !== id)
55
+ throw new TypeError('Kernel returned the status of another Execution.');
56
+ const outcome = admitted.outcome === undefined ? undefined : outcomeOf(admitted.outcome);
57
+ // A deleted Execution carries the outcome its lifecycle record keeps, whatever its kind.
58
+ if (admitted.state === 'deleted')
59
+ return Object.freeze({ id, state: 'deleted', outcome: outcome });
60
+ if ((admitted.state === 'completed') !== (outcome?.kind === 'completed')) {
61
+ throw new TypeError('Execution status and outcome disagree.');
62
+ }
63
+ const { outcome: _outcome, ...rest } = admitted;
64
+ return Object.freeze({ ...rest, ...(outcome === undefined ? {} : { outcome }) });
65
+ };
66
+ return Object.freeze({
67
+ async status(target, options) {
68
+ const id = idOf(target);
69
+ return read(deadlineOf(options), options, async (attempt) => statusOf(id, await send(id, methods.status, {}, attempt)));
70
+ },
71
+ /**
72
+ * Each request waits for the time left, ending early enough for its answer to come back before
73
+ * the call's deadline, and lives as long as its wait and that answer. A wait that lapsed after
74
+ * waiting is sent again while time is left; any other end of the wait is the caller's.
75
+ */
76
+ async result(target, wait, options) {
77
+ const id = idOf(target);
78
+ const deadline = deadlineOf(options);
79
+ const end = Math.min(Date.now() + acceptWait(wait), deadline - ANSWER_MARGIN_MS);
80
+ for (;;) {
81
+ const sent = Date.now();
82
+ try {
83
+ return await read(deadline, options, async (attempt) => {
84
+ const waitMs = Math.max(0, end - Date.now());
85
+ return outcomeOf(await send(id, methods.result, { waitMs }, waitRequest(waitMs, attempt)));
86
+ });
87
+ }
88
+ catch (error) {
89
+ const lapsed = isPending(error) && Date.now() - sent >= LAPSED_WAIT_MS;
90
+ if (!lapsed || end - Date.now() < MINIMUM_WAIT_MS)
91
+ throw error;
92
+ }
93
+ }
94
+ },
95
+ async signal(target, signal, options) {
96
+ // The call admits the value as portable before it is sent.
97
+ const input = { name: signal.name, value: signal.value };
98
+ await send(idOf(target), methods.signal, input, options);
99
+ },
100
+ async cancel(target, input = {}, options) {
101
+ const id = idOf(target);
102
+ return statusOf(id, await send(id, methods.cancel, { ...input }, options));
103
+ },
104
+ async resume(target, options) {
105
+ const id = idOf(target);
106
+ return statusOf(id, await send(id, methods.resume, {}, options));
107
+ },
108
+ async delete(target, options) {
109
+ await send(idOf(target), methods.delete, {}, options);
110
+ },
111
+ });
112
+ }
113
+ /**
114
+ * The request of one wait: it lives as long as the wait and the time its answer takes to come
115
+ * back, which a wait ending that long before the call's deadline keeps within it. A request that
116
+ * does not wait keeps the call's options.
117
+ */
118
+ function waitRequest(waitMs, options) {
119
+ return waitMs === 0 ? options : { ...options, timeoutMs: waitMs + ANSWER_MARGIN_MS };
120
+ }
121
+ /** The wait an `ExecutionWait` asks for, in milliseconds. */
122
+ export function acceptWait(wait) {
123
+ const waitMs = wait?.waitMs ?? 0;
124
+ if (!Number.isSafeInteger(waitMs) || waitMs < 0) {
125
+ throw new TypeError('An Execution wait is a nonnegative integer of milliseconds.');
126
+ }
127
+ return waitMs;
128
+ }
129
+ function idOf(target) {
130
+ const id = typeof target === 'string' ? target : target?.id;
131
+ if (typeof id !== 'string')
132
+ throw new TypeError('An Execution is named by its reference or NodeId.');
133
+ return id;
134
+ }
135
+ function isPending(error) {
136
+ return error instanceof ResponseError && error.reason?.code === 'EXECUTION_PENDING';
137
+ }
@@ -0,0 +1,4 @@
1
+ export type { DeletedExecutionStatus, ExecutionFailure, ExecutionNodeStatus, ExecutionOutcome, ExecutionRef, ExecutionState, ExecutionStatus, ExecutionTarget, ExecutionWait, } from './contracts.js';
2
+ export { acceptWait, createExecution, executionMethods, type ExecutionApi, type ExecutionCall, type ExecutionMethods, } from './execution.js';
3
+ export { acceptOutput } from './admission.js';
4
+ export { deadlineOf, within } from './deadline.js';
@@ -0,0 +1,3 @@
1
+ export { acceptWait, createExecution, executionMethods, } from './execution.js';
2
+ export { acceptOutput } from './admission.js';
3
+ export { deadlineOf, within } from './deadline.js';