@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,31 +1,29 @@
1
- import { ClassKey } from '@astrale-os/kernel-dsl/v1/addressing';
2
1
  import { isDomain } from '@astrale-os/kernel-dsl/v1/domain';
3
2
  import { provenanceOfGraphValue, provenanceOfResponse } from '../provenance.js';
3
+ import { definedClass, validateDefinedProperties } from './conformance.js';
4
4
  import { selectedEdges, selectedNodes } from './page.js';
5
5
  import { projectEdge, projectNode } from './project.js';
6
- import { provenanceOfProjectedValue, sameClosure } from './provenance.js';
6
+ import { provenanceOfProjectedValue } from './provenance.js';
7
7
  export function createDomainBinding(domain, graph, call) {
8
8
  if (!isDomain(domain))
9
9
  throw new TypeError('Domain binding requires an admitted DSL Domain.');
10
10
  const wrapNode = (selected, node) => {
11
11
  requireOwnedClass(domain, selected);
12
- const provenance = requireProvenance(domain, node);
12
+ const provenance = requireProvenance(node);
13
13
  const exact = requireExactClass(domain, node.class, 'node');
14
14
  if (!exact.satisfies(selected))
15
15
  throw new TypeError(`${exact.key} does not satisfy ${selected.key}.`);
16
- const diagnostics = exact.validateProperties(node.props);
17
- if (diagnostics.length > 0)
16
+ if (validateDefinedProperties(exact, node.props).length > 0)
18
17
  throw new TypeError(`Node ${node.id} has invalid exact Properties.`);
19
18
  return projectNode(selected, node, provenance, call);
20
19
  };
21
20
  const wrapEdge = (selected, edge) => {
22
21
  requireOwnedClass(domain, selected);
23
- const provenance = requireProvenance(domain, edge);
22
+ const provenance = requireProvenance(edge);
24
23
  const exact = requireExactClass(domain, edge.class, 'edge');
25
24
  if (!exact.satisfies(selected))
26
25
  throw new TypeError(`${exact.key} does not satisfy ${selected.key}.`);
27
- const diagnostics = exact.validateProperties(edge.props);
28
- if (diagnostics.length > 0)
26
+ if (validateDefinedProperties(exact, edge.props).length > 0)
29
27
  throw new TypeError('Edge has invalid exact Properties.');
30
28
  return projectEdge(selected, edge, provenance);
31
29
  };
@@ -34,9 +32,14 @@ export function createDomainBinding(domain, graph, call) {
34
32
  graph,
35
33
  async query(query, options) {
36
34
  const selected = selectedSourceClass(domain, query);
37
- const response = await graph.query(query, { ...options, expected: domain.closure });
35
+ // The Kernel answers in its active Schema; projection checks each value against `domain`.
36
+ const response = await graph.query(query, options);
37
+ // A repair-session read may hold facts the bound Domain refutes: it is never typed by it.
38
+ if (response.certification === 'uncertified') {
39
+ throw new TypeError('An uncertified Query response cannot be bound to its Domain.');
40
+ }
38
41
  const provenance = provenanceOfResponse(response);
39
- if (provenance === undefined || !sameClosure(provenance.closure, domain.closure)) {
42
+ if (provenance === undefined) {
40
43
  throw new TypeError('Authenticated query provenance was not retained.');
41
44
  }
42
45
  const next = response.page.next === undefined
@@ -46,7 +49,9 @@ export function createDomainBinding(domain, graph, call) {
46
49
  page: { ...options.page, after: response.page.next },
47
50
  });
48
51
  if (selected.kind === 'node') {
49
- const nodes = selectedNodes(response).map((node) => wrapNode(selected, node));
52
+ const nodes = selectedNodes(response)
53
+ .filter((node) => definedClass(domain, node.class) !== undefined)
54
+ .map((node) => wrapNode(selected, node));
50
55
  return Object.freeze({
51
56
  nodes: Object.freeze(nodes),
52
57
  raw: response,
@@ -54,7 +59,9 @@ export function createDomainBinding(domain, graph, call) {
54
59
  refine: (value, target) => refineNode(domain, call, value, target, provenance),
55
60
  });
56
61
  }
57
- const edges = selectedEdges(response).map((edge) => wrapEdge(selected, edge));
62
+ const edges = selectedEdges(response)
63
+ .filter((edge) => definedClass(domain, edge.class) !== undefined)
64
+ .map((edge) => wrapEdge(selected, edge));
58
65
  return Object.freeze({
59
66
  edges: Object.freeze(edges),
60
67
  raw: response,
@@ -107,16 +114,16 @@ function requireOwnedClass(domain, selected) {
107
114
  throw new TypeError('Selected Class does not belong to the bound Domain closure.');
108
115
  }
109
116
  }
110
- function requireProvenance(domain, value) {
117
+ function requireProvenance(value) {
111
118
  const provenance = provenanceOfGraphValue(value);
112
- if (provenance === undefined || !sameClosure(provenance.closure, domain.closure)) {
113
- throw new TypeError('Graph value lacks matching authenticated query provenance.');
119
+ if (provenance === undefined) {
120
+ throw new TypeError('Graph value lacks authenticated query provenance.');
114
121
  }
115
122
  return provenance;
116
123
  }
117
124
  function requireExactClass(domain, key, kind) {
118
- const exact = domain.definition(ClassKey.ref(ClassKey(key)));
119
- if (exact?.ref.kind !== 'class' || exact.kind !== kind || exact.abstract) {
125
+ const exact = definedClass(domain, key);
126
+ if (exact?.kind !== kind || exact.abstract) {
120
127
  throw new TypeError(`Exact ${kind} Class ${key} is not active and concrete.`);
121
128
  }
122
129
  return exact;
@@ -0,0 +1,12 @@
1
+ import type { Domain } from '@astrale-os/kernel-dsl/v1/domain';
2
+ import type { AnyResolvedClass, Diagnostic } from '@astrale-os/kernel-dsl/v1/language';
3
+ /**
4
+ * The Class `domain` defines under `key`, or `undefined` when that Class was added after `domain`
5
+ * was built. The Kernel answers in its active Schema, so a result may hold values of such a Class.
6
+ */
7
+ export declare function definedClass(domain: Domain, key: string): AnyResolvedClass | undefined;
8
+ /**
9
+ * What in `props` breaks `exact`: a Property it defines holding an invalid value, or a required one
10
+ * absent. A Property `exact` does not define passes: the active Schema may add it.
11
+ */
12
+ export declare function validateDefinedProperties(exact: AnyResolvedClass, props: unknown): readonly Diagnostic[];
@@ -0,0 +1,18 @@
1
+ import { ClassKey } from '@astrale-os/kernel-dsl/v1/addressing';
2
+ /**
3
+ * The Class `domain` defines under `key`, or `undefined` when that Class was added after `domain`
4
+ * was built. The Kernel answers in its active Schema, so a result may hold values of such a Class.
5
+ */
6
+ export function definedClass(domain, key) {
7
+ const definition = domain.definition(ClassKey.ref(ClassKey(key)));
8
+ return definition?.ref.kind === 'class' ? definition : undefined;
9
+ }
10
+ /**
11
+ * What in `props` breaks `exact`: a Property it defines holding an invalid value, or a required one
12
+ * absent. A Property `exact` does not define passes: the active Schema may add it.
13
+ */
14
+ export function validateDefinedProperties(exact, props) {
15
+ return exact
16
+ .validateProperties(props)
17
+ .filter((diagnostic) => diagnostic.code !== 'DOMAIN_PROPERTY_UNKNOWN');
18
+ }
@@ -1,3 +1,4 @@
1
1
  export type { DomainBinding, DomainQueryOptions } from './binding.js';
2
+ export { definedClass, validateDefinedProperties } from './conformance.js';
2
3
  export type { BoundEdge, BoundGraphValue, BoundNode, BoundNodeFor } from './model.js';
3
4
  export type { BoundEdgePage, BoundNodePage, BoundQueryPage } from './page.js';
@@ -1 +1 @@
1
- export {};
1
+ export { definedClass, validateDefinedProperties } from './conformance.js';
@@ -1,6 +1,4 @@
1
- import type { Domain } from '@astrale-os/kernel-dsl/v1/domain';
2
1
  import type { QueryProvenance } from '../provenance.js';
3
2
  export declare function retainProjectedProvenance(value: object, provenance: QueryProvenance): void;
4
3
  export declare function provenanceOfProjectedValue(value: object): QueryProvenance | undefined;
5
- export declare function sameClosure(left: Domain['closure'], right: Domain['closure']): boolean;
6
4
  export type { QueryProvenance };
@@ -5,7 +5,3 @@ export function retainProjectedProvenance(value, provenance) {
5
5
  export function provenanceOfProjectedValue(value) {
6
6
  return projectedValues.get(value);
7
7
  }
8
- export function sameClosure(left, right) {
9
- return (left.length === right.length &&
10
- left.every((identity, index) => identity.origin === right[index]?.origin && identity.revision === right[index]?.revision));
11
- }
@@ -1,6 +1,6 @@
1
1
  export { createGraph, type GraphApi, type GraphCall, type GraphMutationOptions, type GraphQueryOptions, type MutationAuthor, } from './graph.js';
2
2
  export type { QueryPageRequest, QueryResponse } from './page-contract.js';
3
- export { type BoundEdge, type BoundEdgePage, type BoundGraphValue, type BoundNode, type BoundNodeFor, type BoundNodePage, type BoundQueryPage, type DomainBinding, type DomainQueryOptions, } from './domain/index.js';
3
+ export { type BoundEdge, type BoundEdgePage, type BoundGraphValue, type BoundNode, type BoundNodeFor, type BoundNodePage, type BoundQueryPage, type DomainBinding, type DomainQueryOptions, definedClass, validateDefinedProperties, } from './domain/index.js';
4
4
  export { NodeUnavailableError } from './errors.js';
5
5
  export type { NeighborsOptions, NodePage } from './page/index.js';
6
6
  export { LocalAlias, type GraphSpec } from '@astrale-os/kernel-core/graph/graph';
@@ -1,5 +1,5 @@
1
1
  export { createGraph, } from './graph.js';
2
- export {} from './domain/index.js';
2
+ export { definedClass, validateDefinedProperties, } from './domain/index.js';
3
3
  export { NodeUnavailableError } from './errors.js';
4
4
  export { LocalAlias } from '@astrale-os/kernel-core/graph/graph';
5
5
  export { MutationAST, MutationResult, } from '@astrale-os/kernel-core/graph/mutate';
@@ -10,4 +10,10 @@ export interface QueryResponse<Result extends QueryResult = QueryResult> {
10
10
  readonly page: {
11
11
  readonly next?: string;
12
12
  };
13
+ /**
14
+ * Present only for a repair-session read made without conformance admission: its facts may
15
+ * violate the active schema, so it is raw Core data only. The Store keeps it out of its shared
16
+ * cache and a Domain binding refuses to type it.
17
+ */
18
+ readonly certification?: 'uncertified';
13
19
  }
@@ -1,14 +1,13 @@
1
1
  import type { Edge } from '@astrale-os/kernel-core/graph/edge';
2
2
  import type { Node } from '@astrale-os/kernel-core/graph/node';
3
- import type { DomainDependency } from '@astrale-os/kernel-dsl/v1/schema';
4
3
  import type { QueryResponse } from './page-contract.js';
4
+ /** A certified Query response this client received from the Kernel; `page` identifies it. */
5
5
  export interface QueryProvenance {
6
- readonly closure: readonly DomainDependency[];
7
6
  readonly page: object;
8
7
  }
9
- /** Retain authenticated query provenance without adding serialized response metadata. */
10
- export declare function retainQueryProvenance(response: QueryResponse, closure: readonly DomainDependency[]): QueryResponse;
11
- /** Reattach the exact authenticated closure when Store materialization replaces response objects. */
8
+ /** Retain the provenance of a certified Query response without adding serialized metadata. */
9
+ export declare function retainQueryProvenance(response: QueryResponse): QueryResponse;
10
+ /** Reattach provenance when Store materialization replaces response objects. */
12
11
  export declare function retainDerivedQueryProvenance(source: QueryResponse, derived: QueryResponse): QueryResponse;
13
12
  export declare function provenanceOfGraphValue(value: Node | Edge): QueryProvenance | undefined;
14
13
  export declare function provenanceOfResponse(value: QueryResponse): QueryProvenance | undefined;
@@ -1,8 +1,8 @@
1
1
  const graphValues = new WeakMap();
2
2
  const responses = new WeakMap();
3
- /** Retain authenticated query provenance without adding serialized response metadata. */
4
- export function retainQueryProvenance(response, closure) {
5
- const provenance = Object.freeze({ closure, page: Object.freeze({}) });
3
+ /** Retain the provenance of a certified Query response without adding serialized metadata. */
4
+ export function retainQueryProvenance(response) {
5
+ const provenance = Object.freeze({ page: Object.freeze({}) });
6
6
  responses.set(response, provenance);
7
7
  const { result } = response;
8
8
  if (result.kind === 'graph') {
@@ -29,10 +29,9 @@ export function retainQueryProvenance(response, closure) {
29
29
  }
30
30
  return response;
31
31
  }
32
- /** Reattach the exact authenticated closure when Store materialization replaces response objects. */
32
+ /** Reattach provenance when Store materialization replaces response objects. */
33
33
  export function retainDerivedQueryProvenance(source, derived) {
34
- const provenance = responses.get(source);
35
- return provenance === undefined ? derived : retainQueryProvenance(derived, provenance.closure);
34
+ return responses.has(source) ? retainQueryProvenance(derived) : derived;
36
35
  }
37
36
  export function provenanceOfGraphValue(value) {
38
37
  return graphValues.get(value);
@@ -28,9 +28,10 @@ export async function queryGraph(call, input, options) {
28
28
  page: admittedPage,
29
29
  })), request);
30
30
  const response = decodeResponse(output);
31
- return capturedExpected === undefined
32
- ? response
33
- : retainQueryProvenance(response, capturedExpected);
31
+ // A repair-session read may hold facts the Domain refutes: it carries no provenance.
32
+ return response.certification === undefined
33
+ ? retainQueryProvenance(response)
34
+ : response;
34
35
  }
35
36
  function admitPage(input) {
36
37
  if (input === null || typeof input !== 'object' || Array.isArray(input)) {
@@ -52,9 +53,13 @@ function decodeResponse(input) {
52
53
  throw new TypeError('Graph query response is invalid.');
53
54
  }
54
55
  const value = input;
55
- if (!hasExactKeys(value, ['result', 'page'])) {
56
+ const uncertified = value.certification !== undefined;
57
+ if (!hasExactKeys(value, uncertified ? ['result', 'page', 'certification'] : ['result', 'page'])) {
56
58
  throw new TypeError('Graph query response is invalid.');
57
59
  }
60
+ if (uncertified && value.certification !== 'uncertified') {
61
+ throw new TypeError('Graph query response certification is invalid.');
62
+ }
58
63
  const pageInput = value.page;
59
64
  if (pageInput === null || typeof pageInput !== 'object' || Array.isArray(pageInput)) {
60
65
  throw new TypeError('Graph query response page is invalid.');
@@ -69,7 +74,11 @@ function decodeResponse(input) {
69
74
  }
70
75
  const result = QueryResult.decode(value.result);
71
76
  const page = Object.freeze(pageValue.next === undefined ? {} : { next: pageValue.next });
72
- return Object.freeze({ result, page });
77
+ return Object.freeze({
78
+ result,
79
+ page,
80
+ ...(uncertified ? { certification: 'uncertified' } : {}),
81
+ });
73
82
  }
74
83
  function hasExactKeys(input, expected) {
75
84
  const keys = Object.keys(input);
@@ -1,4 +1,4 @@
1
- export { retry, type RetryOptions } from './retry/index.js';
1
+ export { RETRY_REFUSALS, retry, type RetryOptions } from './retry/index.js';
2
2
  export { createQueue, type QueueOptions } from './queue/index.js';
3
3
  export { createBatcher, type BatchOptions } from './batcher/index.js';
4
4
  export { createRateLimiter, type RateLimitOptions } from './limiter/index.js';
@@ -1,4 +1,4 @@
1
- export { retry } from './retry/index.js';
1
+ export { RETRY_REFUSALS, retry } from './retry/index.js';
2
2
  export { createQueue } from './queue/index.js';
3
3
  export { createBatcher } from './batcher/index.js';
4
4
  export { createRateLimiter } from './limiter/index.js';
@@ -1 +1,2 @@
1
+ export { RETRY_REFUSALS } from './refusals.js';
1
2
  export { retry, type RetryOptions } from './retry.js';
@@ -1 +1,2 @@
1
+ export { RETRY_REFUSALS } from './refusals.js';
1
2
  export { retry } from './retry.js';
@@ -0,0 +1,7 @@
1
+ import type { RetryOptions } from './retry.js';
2
+ /**
3
+ * Opt-in policy for refusals proven to have run nothing. A back-pressure, draining or maintenance
4
+ * refusal is resent no earlier than its prescribed delay; a stale-snapshot conflict is resent after
5
+ * ordinary backoff. Every other failure ends the retry.
6
+ */
7
+ export declare const RETRY_REFUSALS: Readonly<Required<Pick<RetryOptions, 'shouldRetry' | 'retryAfter'>>>;
@@ -0,0 +1,10 @@
1
+ import { isSnapshotStale, retryAfterOf } from '../../errors/index.js';
2
+ /**
3
+ * Opt-in policy for refusals proven to have run nothing. A back-pressure, draining or maintenance
4
+ * refusal is resent no earlier than its prescribed delay; a stale-snapshot conflict is resent after
5
+ * ordinary backoff. Every other failure ends the retry.
6
+ */
7
+ export const RETRY_REFUSALS = Object.freeze({
8
+ shouldRetry: (error) => retryAfterOf(error) !== undefined || isSnapshotStale(error),
9
+ retryAfter: (error) => retryAfterOf(error),
10
+ });
@@ -4,6 +4,8 @@ export interface RetryOptions {
4
4
  readonly maxWait?: number;
5
5
  readonly jitter?: number;
6
6
  readonly shouldRetry?: (error: Error, attempt: number) => boolean;
7
+ /** Least delay in milliseconds a failure prescribes before the next attempt; backoff still applies. */
8
+ readonly retryAfter?: (error: Error, attempt: number) => number | undefined;
7
9
  }
8
10
  /** Retry with bounded exponential backoff and never swallow the final failure. */
9
11
  export declare function retry<Result>(operation: () => Promise<Result>, options?: RetryOptions): Promise<Result>;
@@ -10,6 +10,9 @@ export async function retry(operation, options = {}) {
10
10
  if (options.shouldRetry !== undefined && typeof options.shouldRetry !== 'function') {
11
11
  throw new TypeError('Retry classifier is invalid.');
12
12
  }
13
+ if (options.retryAfter !== undefined && typeof options.retryAfter !== 'function') {
14
+ throw new TypeError('Retry delay classifier is invalid.');
15
+ }
13
16
  const attempts = positive(options.maxAttempts ?? DEFAULT_RETRY_ATTEMPTS, 'maxAttempts');
14
17
  const baseWait = nonNegative(options.baseWait ?? DEFAULT_RETRY_BASE_WAIT_MS, 'baseWait');
15
18
  const maxWait = nonNegative(options.maxWait ?? DEFAULT_RETRY_MAX_WAIT_MS, 'maxWait');
@@ -19,7 +22,11 @@ export async function retry(operation, options = {}) {
19
22
  }
20
23
  let succeeded = false;
21
24
  let failure;
25
+ // Earliest instant the last failure allows the next attempt; backoff has already waited part of it.
26
+ let notBefore = 0;
27
+ let invalidDelay;
22
28
  const retryer = new AsyncRetryer(async () => {
29
+ await waitUntil(notBefore);
23
30
  try {
24
31
  const result = await operation();
25
32
  succeeded = true;
@@ -29,6 +36,15 @@ export async function retry(operation, options = {}) {
29
36
  catch (error) {
30
37
  succeeded = false;
31
38
  failure = error;
39
+ if (error instanceof Error && options.retryAfter !== undefined) {
40
+ const delay = options.retryAfter(error, retryer.store.state.currentAttempt);
41
+ if (delay !== undefined && (!Number.isFinite(delay) || delay < 0)) {
42
+ invalidDelay = new TypeError('retryAfter must return a finite non-negative number.');
43
+ }
44
+ else {
45
+ notBefore = delay === undefined ? 0 : Date.now() + delay;
46
+ }
47
+ }
32
48
  throw error;
33
49
  }
34
50
  }, {
@@ -39,13 +55,23 @@ export async function retry(operation, options = {}) {
39
55
  maxAttempts: (current) => {
40
56
  const error = current.store.state.lastError;
41
57
  const attempt = current.store.state.currentAttempt;
58
+ if (invalidDelay !== undefined)
59
+ return attempt;
42
60
  if (error !== undefined && options.shouldRetry?.(error, attempt) === false)
43
61
  return attempt;
44
62
  return attempts;
45
63
  },
46
64
  throwOnError: 'last',
47
65
  });
48
- const result = await retryer.execute();
66
+ let result;
67
+ try {
68
+ result = await retryer.execute();
69
+ }
70
+ catch (error) {
71
+ throw invalidDelay ?? error;
72
+ }
73
+ if (invalidDelay !== undefined)
74
+ throw invalidDelay;
49
75
  if (!succeeded) {
50
76
  if (failure !== undefined)
51
77
  throw failure;
@@ -53,3 +79,9 @@ export async function retry(operation, options = {}) {
53
79
  }
54
80
  return result;
55
81
  }
82
+ /** Timers may fire early against the wall clock, so wait again until the instant has passed. */
83
+ async function waitUntil(instant) {
84
+ for (let remaining = instant - Date.now(); remaining > 0; remaining = instant - Date.now()) {
85
+ await new Promise((resolve) => setTimeout(resolve, remaining));
86
+ }
87
+ }
@@ -1,12 +1,69 @@
1
+ import type { NodeId } from '@astrale-os/kernel-core/graph/node';
1
2
  import type { installation } from '@astrale-os/kernel-core/schema';
2
- import type { DomainRequest as CoreDomainRequest, InstallInput, InstallReceipt as CoreInstallReceipt, UninstallInput, UninstallOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
+ import type { AttemptReport, DomainRequest as CoreDomainRequest, InstallClass as CoreInstallClass, InstallInput, InstallMode as CoreInstallMode, InstallReceipt as CoreInstallReceipt, SystemExecutionDetail, UninstallInput, UninstallOutput, ValidationOptions } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
4
+ import type { schema as protocolSchema } from '@astrale-os/kernel-protocol';
5
+ import type { ExecutionOutcome, ExecutionStatus, ExecutionWait } from '../execution/index.js';
3
6
  export type OperationId = installation.OperationId;
4
7
  /** Canonical caller input accepted by the Kernel install syscall. */
5
8
  export type DomainRequest = CoreDomainRequest;
6
- export type InstallRequest = InstallInput;
9
+ /**
10
+ * One install: its Kernel input, plus `waitMs`, how long the Client waits for its outcome (110 s
11
+ * by default; `0` answers at once). `waitMs` is the Client's own: it is never sent, so it is no
12
+ * part of the operation's intent.
13
+ */
14
+ export type InstallRequest = InstallInput & ExecutionWait;
7
15
  /** Admitted terminal install receipt returned by the Kernel. */
8
16
  export type InstallReceipt = CoreInstallReceipt;
9
- /** Canonical caller input accepted by the Kernel uninstall syscall. */
10
- export type UninstallRequest = UninstallInput;
17
+ /** The committed result of an install: its receipt, or the generations it proved unchanged. */
18
+ export type InstallResult = protocolSchema.installation.InstallResult;
19
+ /** What an install does to the stored data: nothing, applied at once, or revalidated first. */
20
+ export type InstallClass = CoreInstallClass;
21
+ export type InstallMode = CoreInstallMode;
22
+ /** The validation options of an install, defaults filled in. */
23
+ export type InstallValidationOptions = ValidationOptions;
24
+ /** The last attempt of a repair session that ended without activating, with its report. */
25
+ export type InstallAttemptReport = AttemptReport;
26
+ /** What an install or session shows beside its engine state, as Core shapes it. */
27
+ export type InstallDetail = SystemExecutionDetail;
28
+ /** A terminal install: its committed result, its rejection, or its cancellation. */
29
+ export type InstallOutcome = ExecutionOutcome<InstallResult>;
30
+ /**
31
+ * The status of one install or repair session: the engine `state` the CLI decides on, and the
32
+ * Core `detail` (phase, class, progress, the next command index, the running attempt and the last
33
+ * attempt report).
34
+ */
35
+ export type InstallStatus = ExecutionStatus<InstallResult>;
36
+ /** One admitted install answer: its Execution, its status, and its result once completed. */
37
+ export interface Installation {
38
+ readonly execution: NodeId;
39
+ /**
40
+ * True when the operation id already named this Execution, so the call replayed it and changed
41
+ * nothing; false when this call started it; absent when the Host does not say.
42
+ */
43
+ readonly replayed?: boolean;
44
+ readonly status: InstallStatus;
45
+ /** The committed result, present exactly when the status is completed. */
46
+ readonly result?: InstallResult;
47
+ }
48
+ /**
49
+ * One uninstall: its Kernel input, plus `waitMs`, how long the Client waits for its outcome, as
50
+ * for an install, and never sent.
51
+ */
52
+ export type UninstallRequest = UninstallInput & ExecutionWait;
11
53
  /** Admitted terminal uninstall receipt returned by the Kernel. */
12
54
  export type UninstallReceipt = UninstallOutput;
55
+ /** A terminal uninstall: its committed receipt, its rejection, or its cancellation. */
56
+ export type UninstallOutcome = ExecutionOutcome<UninstallReceipt>;
57
+ /** The status of one uninstall. */
58
+ export type UninstallStatus = ExecutionStatus<UninstallReceipt>;
59
+ /** One admitted uninstall answer: its Execution, its status, and its receipt once completed. */
60
+ export interface Uninstallation {
61
+ readonly execution: NodeId;
62
+ /**
63
+ * True when the operation id already named this Execution; false when this call started it;
64
+ * absent when the Host does not say.
65
+ */
66
+ readonly replayed?: boolean;
67
+ readonly status: UninstallStatus;
68
+ readonly result?: UninstallReceipt;
69
+ }
@@ -1,3 +1,4 @@
1
- export { createSchema, DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS, type SchemaApi, type SchemaCall, type SchemaOptions, type DomainBundle, type DomainDependencies, type DomainInfo, type InstalledPin, type InstalledRelease, type InstallResult, } from './schema.js';
1
+ export { createSchema, type SchemaApi, type SchemaCall, type SchemaOptions, type DomainBundle, type DomainDependencies, type DomainInfo, type InstalledPin, type InstalledRelease, } from './schema.js';
2
2
  export { acceptOperationId, createOperationId } from './operation.js';
3
- export type { DomainRequest, InstallReceipt, InstallRequest, OperationId, UninstallReceipt, UninstallRequest, } from './contracts.js';
3
+ export type { InstallationApi, UninstallationApi } from './installation.js';
4
+ export type { DomainRequest, InstallAttemptReport, InstallClass, InstallDetail, InstallMode, InstallOutcome, InstallResult, InstallStatus, InstallValidationOptions, Installation, InstallReceipt, InstallRequest, OperationId, Uninstallation, UninstallOutcome, UninstallReceipt, UninstallRequest, UninstallStatus, } from './contracts.js';
@@ -1,2 +1,2 @@
1
- export { createSchema, DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS, } from './schema.js';
1
+ export { createSchema, } from './schema.js';
2
2
  export { acceptOperationId, createOperationId } from './operation.js';
@@ -0,0 +1,66 @@
1
+ import type { NodeId } from '@astrale-os/kernel-core/graph/node';
2
+ import type { InstallValidation } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
+ import type { ExecutionCall, ExecutionWait } from '../execution/index.js';
4
+ import type { RequestOptions } from '../transport/index.js';
5
+ import type { InstallOutcome, InstallStatus, UninstallOutcome, UninstallStatus } from './contracts.js';
6
+ /**
7
+ * The install executions of one Instance, through the `K.Execution` Methods of each. Observing
8
+ * and a cooperative cancel are Root's or the initiator's; signals, a forced cancel, resume and
9
+ * delete are Root's.
10
+ */
11
+ export interface InstallationApi {
12
+ /** The status of one install or repair session. */
13
+ status(execution: NodeId, options?: RequestOptions): Promise<InstallStatus>;
14
+ /** The terminal outcome, waiting at most `waitMs` in total; `EXECUTION_PENDING` once it lapses. */
15
+ result(execution: NodeId, wait?: ExecutionWait, options?: RequestOptions): Promise<InstallOutcome>;
16
+ /**
17
+ * A waiting repair session attempts its target: the `command:<index>` signal, `index` being
18
+ * the `detail.command` its status announces. A signal already resolved is refused.
19
+ */
20
+ apply(execution: NodeId, command: {
21
+ readonly index: number;
22
+ readonly validation?: InstallValidation;
23
+ }, options?: RequestOptions): Promise<void>;
24
+ /**
25
+ * Stop the attempt a repair session runs, `detail.attempt.number`, through its `abort:<attempt>`
26
+ * signal; the session waits again.
27
+ */
28
+ abort(execution: NodeId, attempt: number, options?: RequestOptions): Promise<void>;
29
+ /**
30
+ * A cooperative cancel ends an install before its point of no return with nothing changed, and
31
+ * has a repair session attempt its source schema. `force` kills the run; a live session refuses
32
+ * it `EXECUTION_EXIT_REFUSED`: cancel it cooperatively or apply it.
33
+ */
34
+ cancel(execution: NodeId, input?: {
35
+ readonly force?: boolean;
36
+ }, options?: RequestOptions): Promise<InstallStatus>;
37
+ /** Resume a paused install or session; a running one is unchanged. */
38
+ resume(execution: NodeId, options?: RequestOptions): Promise<InstallStatus>;
39
+ /**
40
+ * Delete the Execution, then kill and purge its run; a live session refuses it
41
+ * `EXECUTION_EXIT_REFUSED`: cancel or apply it first.
42
+ */
43
+ delete(execution: NodeId, options?: RequestOptions): Promise<void>;
44
+ }
45
+ /**
46
+ * The uninstall executions of one Instance, through the same `K.Execution` Methods: a completed
47
+ * outcome carries the uninstall receipt. An uninstall has no repair session, so no signal.
48
+ */
49
+ export interface UninstallationApi {
50
+ /** The status of one uninstall. */
51
+ status(execution: NodeId, options?: RequestOptions): Promise<UninstallStatus>;
52
+ /** The terminal outcome, waiting at most `waitMs` in total; `EXECUTION_PENDING` once it lapses. */
53
+ result(execution: NodeId, wait?: ExecutionWait, options?: RequestOptions): Promise<UninstallOutcome>;
54
+ /** A cooperative cancel ends it before its point of no return; `force` kills the run. */
55
+ cancel(execution: NodeId, input?: {
56
+ readonly force?: boolean;
57
+ }, options?: RequestOptions): Promise<UninstallStatus>;
58
+ /** Resume a paused uninstall; a running one is unchanged. */
59
+ resume(execution: NodeId, options?: RequestOptions): Promise<UninstallStatus>;
60
+ /** Delete the Execution, then kill and purge its run. */
61
+ delete(execution: NodeId, options?: RequestOptions): Promise<void>;
62
+ }
63
+ /** The install Methods: a completed outcome carries the result its Protocol owner admits. */
64
+ export declare function createInstallation(call: ExecutionCall): InstallationApi;
65
+ /** The uninstall Methods: a completed outcome carries the receipt Core's contract admits. */
66
+ export declare function createUninstallation(call: ExecutionCall): UninstallationApi;
@@ -0,0 +1,38 @@
1
+ import { abortSignal, commandSignal, uninstallOutput, } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
2
+ import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
3
+ import { acceptOutput, executionMethods } from '../execution/index.js';
4
+ /** The install Methods: a completed outcome carries the result its Protocol owner admits. */
5
+ export function createInstallation(call) {
6
+ const { signal, ...methods } = executionMethods(call, acceptInstallResult);
7
+ return Object.freeze({
8
+ ...methods,
9
+ apply: async (execution, command, options) => signal(execution, {
10
+ name: commandSignal(ordinal(command.index)),
11
+ value: Object.freeze({
12
+ kind: 'apply',
13
+ ...(command.validation === undefined ? {} : { validation: command.validation }),
14
+ }),
15
+ }, options),
16
+ abort: async (execution, attempt, options) => signal(execution, { name: abortSignal(ordinal(attempt)), value: Object.freeze({ kind: 'abort' }) }, options),
17
+ });
18
+ }
19
+ /** The uninstall Methods: a completed outcome carries the receipt Core's contract admits. */
20
+ export function createUninstallation(call) {
21
+ const { signal: _signal, ...methods } = executionMethods(call, acceptUninstallReceipt);
22
+ return Object.freeze(methods);
23
+ }
24
+ function acceptInstallResult(input) {
25
+ if (uninstallOutput.safeParse(input).success) {
26
+ throw new TypeError('The Execution is an uninstall: read it through SchemaApi.uninstallation.');
27
+ }
28
+ return protocolSchema.installation.acceptResult(input);
29
+ }
30
+ function acceptUninstallReceipt(input) {
31
+ return acceptOutput(uninstallOutput, input, 'uninstall receipt');
32
+ }
33
+ function ordinal(input) {
34
+ if (!Number.isSafeInteger(input) || input < 1) {
35
+ throw new TypeError('A session signal index is a positive integer.');
36
+ }
37
+ return input;
38
+ }