@astrale-os/kernel-client 1.0.0-beta.22 → 1.0.0-beta.24

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 (60) hide show
  1. package/dist/client/client.d.ts +5 -4
  2. package/dist/client/client.js +7 -7
  3. package/dist/client/index.d.ts +1 -1
  4. package/dist/client/request.d.ts +5 -9
  5. package/dist/client/request.js +13 -16
  6. package/dist/errors/index.d.ts +1 -0
  7. package/dist/errors/index.js +1 -0
  8. package/dist/errors/query-input.d.ts +47 -0
  9. package/dist/errors/query-input.js +84 -0
  10. package/dist/execution/deadline.d.ts +10 -0
  11. package/dist/execution/deadline.js +12 -0
  12. package/dist/execution/execution.js +2 -7
  13. package/dist/execution/index.d.ts +1 -1
  14. package/dist/execution/index.js +1 -1
  15. package/dist/graph/domain/binding.d.ts +2 -2
  16. package/dist/graph/graph.d.ts +17 -3
  17. package/dist/graph/graph.js +4 -1
  18. package/dist/graph/index.d.ts +2 -2
  19. package/dist/graph/page-contract.d.ts +53 -1
  20. package/dist/graph/query.d.ts +10 -4
  21. package/dist/graph/query.js +125 -2
  22. package/dist/graph/query.typecheck.d.ts +77 -0
  23. package/dist/graph/query.typecheck.js +34 -0
  24. package/dist/schema/contracts.d.ts +21 -10
  25. package/dist/schema/index.d.ts +1 -1
  26. package/dist/schema/installation.d.ts +11 -1
  27. package/dist/schema/installation.js +45 -1
  28. package/dist/schema/schema.d.ts +4 -4
  29. package/dist/schema/schema.js +34 -24
  30. package/dist/session/bound.js +27 -31
  31. package/dist/session/content/api.js +2 -2
  32. package/dist/session/content/input.js +2 -2
  33. package/dist/session/content/retry.d.ts +2 -1
  34. package/dist/session/content/retry.js +13 -23
  35. package/dist/session/context/operation.js +2 -16
  36. package/dist/session/durable.js +13 -19
  37. package/dist/session/retry.d.ts +12 -0
  38. package/dist/session/retry.js +23 -0
  39. package/dist/session/routing/dispatch.d.ts +2 -2
  40. package/dist/session/routing/dispatch.js +12 -20
  41. package/dist/session/routing/request.d.ts +2 -1
  42. package/dist/session/routing/request.js +2 -1
  43. package/dist/store/store.d.ts +6 -6
  44. package/dist/transport/deadline.d.ts +2 -0
  45. package/dist/transport/deadline.js +18 -0
  46. package/dist/transport/http/admission.js +7 -42
  47. package/dist/transport/http/binary-request.d.ts +23 -9
  48. package/dist/transport/http/binary-request.js +12 -10
  49. package/dist/transport/http/response.d.ts +0 -1
  50. package/dist/transport/http/response.js +0 -6
  51. package/dist/transport/http/transport.d.ts +3 -2
  52. package/dist/transport/http/transport.js +16 -20
  53. package/dist/transport/index.d.ts +1 -1
  54. package/dist/transport/index.js +1 -1
  55. package/dist/transport/unary.d.ts +7 -0
  56. package/dist/transport/unary.js +34 -0
  57. package/dist/transport/websocket/connection.js +1 -7
  58. package/dist/transport/websocket/exchange.d.ts +2 -0
  59. package/dist/transport/websocket/exchange.js +13 -43
  60. package/package.json +5 -5
@@ -1,6 +1,8 @@
1
- import { QueryAST, QueryASTDecodeError, QueryResult } from '@astrale-os/kernel-core/graph/query';
1
+ import { QUERY, QueryAST, QueryASTDecodeError, QueryResult, } from '@astrale-os/kernel-core/graph/query';
2
2
  import { Path, PathError } from '@astrale-os/kernel-core/path';
3
+ import { queryOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
4
  import { query } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
5
+ import * as portable from '@astrale-os/kernel-dsl/value';
4
6
  import { call as invocation } from '../client/index.js';
5
7
  import { captureExpected } from './expectation.js';
6
8
  import { retainQueryProvenance } from './provenance.js';
@@ -17,7 +19,128 @@ export function queryNodePath(target) {
17
19
  throw new QueryASTDecodeError('/source/nodes/0', 'Invalid Node target', { cause });
18
20
  }
19
21
  }
20
- export async function queryGraph(call, input, options) {
22
+ export function queryGraph(call, input, options) {
23
+ return isQuery(input)
24
+ ? queryV7(call, input, options)
25
+ : queryLegacyAST(call, input, options);
26
+ }
27
+ /** A Query: an object naming `"query": "astrale.query/7"`. */
28
+ function isQuery(input) {
29
+ return isRecord(input) && input.query === QUERY;
30
+ }
31
+ // ─── Query v7 ───────────────────────────────────────────────────────────────────────────────
32
+ /**
33
+ * Send one Query (page "Fondations Query v7", § Wire v7) as the operation's request `{document,
34
+ * paging?, expected?}`, and admit the answer of its family. The Kernel decodes the Query against
35
+ * its Registry; the Client admits its structure only, before any I/O. A continuation is the same
36
+ * Query with `paging.after` set to a Page's cursor.
37
+ */
38
+ async function queryV7(call, input, options) {
39
+ const admitted = admitQuery(input);
40
+ const { expected, paging, ...request } = options ?? {};
41
+ const admittedPaging = admitPaging(paging);
42
+ const capturedExpected = captureExpected(expected);
43
+ const output = await call(invocation(KERNEL_QUERY_PATH, Object.freeze({
44
+ document: admitted,
45
+ ...(admittedPaging === undefined ? {} : { paging: admittedPaging }),
46
+ ...(capturedExpected === undefined ? {} : { expected: capturedExpected }),
47
+ })), options === undefined ? undefined : request);
48
+ return decodeAnswer(output, familyOf(admitted));
49
+ }
50
+ /** A detached, frozen Query of exactly one family; its names are the Kernel's to decode. */
51
+ function admitQuery(input) {
52
+ const query = snapshot(input, 'query');
53
+ if (!isRecord(query) || familyOf(query) === undefined) {
54
+ return invalid('query', 'it holds exactly one of list, exists, count');
55
+ }
56
+ return query;
57
+ }
58
+ /** A detached, frozen paging: sizes per list path, each at least 1, and a Page's cursor. */
59
+ function admitPaging(input) {
60
+ if (input === undefined)
61
+ return undefined;
62
+ const paging = snapshot(input, 'paging');
63
+ if (!isRecord(paging) || !hasOnlyKeys(paging, ['sizes', 'after'])) {
64
+ return invalid('paging', 'it is {sizes?, after?}');
65
+ }
66
+ const { sizes, after } = paging;
67
+ if (sizes !== undefined &&
68
+ (!Array.isArray(sizes) ||
69
+ !sizes.every((entry) => isRecord(entry) &&
70
+ hasExactKeys(entry, ['at', 'size']) &&
71
+ Array.isArray(entry.at) &&
72
+ entry.at.every((name) => typeof name === 'string') &&
73
+ Number.isSafeInteger(entry.size) &&
74
+ entry.size >= 1))) {
75
+ return invalid('paging', 'each size is {at: [Branch names], size: an integer of at least 1}');
76
+ }
77
+ if (after !== undefined && (typeof after !== 'string' || after.length === 0)) {
78
+ return invalid('paging', 'after is the cursor of a Page');
79
+ }
80
+ return paging;
81
+ }
82
+ /** A detached, frozen portable snapshot of one caller value. */
83
+ function snapshot(input, what) {
84
+ try {
85
+ return portable.acceptImmutable(input);
86
+ }
87
+ catch (cause) {
88
+ if (!(cause instanceof portable.BoundaryError))
89
+ throw cause;
90
+ return invalid(what, 'it is not a portable JSON value', cause);
91
+ }
92
+ }
93
+ function invalid(what, detail, cause) {
94
+ const subject = what === 'query' ? 'Graph query' : 'Graph query paging';
95
+ throw new TypeError(`${subject} is invalid: ${detail}.`, { cause });
96
+ }
97
+ /** The family a Query's root fold names; undefined unless it names exactly one. */
98
+ function familyOf(query) {
99
+ const families = ['list', 'exists', 'count'].filter((family) => family in query);
100
+ return families.length === 1 ? families[0] : undefined;
101
+ }
102
+ /**
103
+ * The Kernel's answer, admitted by the query operation's contract as a detached frozen value, of
104
+ * the family the Query asked for.
105
+ */
106
+ function decodeAnswer(input, family) {
107
+ const refuse = (cause) => {
108
+ throw new TypeError('Graph query answer is invalid.', { cause });
109
+ };
110
+ let value;
111
+ try {
112
+ value = portable.acceptImmutable(input);
113
+ }
114
+ catch (cause) {
115
+ if (!(cause instanceof portable.BoundaryError))
116
+ throw cause;
117
+ return refuse(cause);
118
+ }
119
+ if (!isRecord(value) || !(family in value) || !queryOutput.safeParse(value).success) {
120
+ return refuse();
121
+ }
122
+ const answer = value;
123
+ return 'list' in answer && !pagesClosed(answer.list) ? refuse() : answer;
124
+ }
125
+ /** Every Page, its Branches' included, carries a cursor exactly when an item follows it (W3). */
126
+ function pagesClosed(page) {
127
+ const continued = 'cursor' in page;
128
+ return page.complete !== continued && page.items.every(itemClosed);
129
+ }
130
+ function itemClosed(item) {
131
+ return ((item.source === undefined || itemClosed(item.source)) &&
132
+ (item.target === undefined || itemClosed(item.target)) &&
133
+ Object.values(item.branches).every((branch) => !('items' in branch) || pagesClosed(branch)));
134
+ }
135
+ function isRecord(input) {
136
+ return input !== null && typeof input === 'object' && !Array.isArray(input);
137
+ }
138
+ function hasOnlyKeys(input, allowed) {
139
+ return Object.keys(input).every((key) => allowed.includes(key));
140
+ }
141
+ // ─── Legacy: V6 QueryAST ────────────────────────────────────────────────────────────────────
142
+ /** The legacy path: one V6 QueryAST and its page, answered `{result, page}`. */
143
+ async function queryLegacyAST(call, input, options) {
21
144
  const ast = QueryAST.decode(input);
22
145
  const { expected, page, ...request } = options;
23
146
  const admittedPage = admitPage(page);
@@ -0,0 +1,77 @@
1
+ import type { QueryAST, QueryResultFor } from '@astrale-os/kernel-core/graph/query';
2
+ import type { GraphApi, GraphQueryV6Options } from './graph.js';
3
+ import type { QueryAnswer, QueryAnswerFor, QueryResponse } from './index.js';
4
+ type Equal<Left, Right> = (<Value>() => Value extends Left ? 1 : 2) extends <Value>() => (Value extends Right ? 1 : 2) ? true : false;
5
+ type Assert<Condition extends true> = Condition;
6
+ type ListAnswer = Extract<QueryAnswer, {
7
+ readonly list: unknown;
8
+ }>;
9
+ type ExistsAnswer = Extract<QueryAnswer, {
10
+ readonly exists: unknown;
11
+ }>;
12
+ type CountAnswer = Extract<QueryAnswer, {
13
+ readonly count: unknown;
14
+ }>;
15
+ declare const ast: QueryAST<import("@astrale-os/kernel-core/graph/query").QueryNodeSelect<{
16
+ kind: "value";
17
+ }>, never>;
18
+ declare const list: {
19
+ readonly query: "astrale.query/7";
20
+ readonly list: {
21
+ readonly nodes: readonly [`${string}:class.${string}`];
22
+ readonly orderBy: readonly [{
23
+ readonly property: `${string}:class.${string}.property.${string}`;
24
+ readonly direction: 'asc';
25
+ readonly missing: 'last';
26
+ }];
27
+ };
28
+ };
29
+ declare const exists: {
30
+ readonly query: "astrale.query/7";
31
+ readonly exists: {
32
+ readonly nodes: readonly [`${string}:class.${string}`];
33
+ };
34
+ };
35
+ declare const count: {
36
+ readonly query: "astrale.query/7";
37
+ readonly count: {
38
+ readonly nodes: readonly [`${string}:class.${string}`];
39
+ };
40
+ readonly upTo: 10;
41
+ };
42
+ declare function overloads(): Promise<readonly [QueryResponse<import("@astrale-os/kernel-core/graph/query").QueryNodeResult<{
43
+ kind: "value";
44
+ }>>, {
45
+ readonly list: import("./page-contract.js").QueryPage;
46
+ readonly facts: Extract<import("@astrale-os/kernel-core/graph/query").Answer, {
47
+ readonly list: unknown;
48
+ }>['facts'];
49
+ readonly revision: string;
50
+ readonly revised?: true;
51
+ }, {
52
+ readonly exists: boolean;
53
+ readonly undecided?: boolean;
54
+ }, {
55
+ readonly count: number;
56
+ readonly more: boolean;
57
+ readonly undecided?: import("@astrale-os/kernel-core/graph/query").Undecided;
58
+ }]>;
59
+ export type pickedByInput = Assert<Equal<Awaited<ReturnType<typeof overloads>>, readonly [QueryResponse<QueryResultFor<typeof ast>>, ListAnswer, ExistsAnswer, CountAnswer]>>;
60
+ export type answerByFamily = Assert<Equal<[
61
+ QueryAnswerFor<typeof list>,
62
+ QueryAnswerFor<typeof exists>,
63
+ QueryAnswerFor<typeof count>
64
+ ], [
65
+ ListAnswer,
66
+ ExistsAnswer,
67
+ CountAnswer
68
+ ]>>;
69
+ /** The legacy overload stays last: `Parameters` and `ReturnType` keep reading V6. */
70
+ export type legacyLast = Assert<Equal<[
71
+ Parameters<GraphApi['query']>,
72
+ Awaited<ReturnType<GraphApi['query']>>
73
+ ], [
74
+ [QueryAST, GraphQueryV6Options],
75
+ QueryResponse<QueryResultFor<QueryAST>>
76
+ ]>>;
77
+ export {};
@@ -0,0 +1,34 @@
1
+ import { Query, QUERY } from '@astrale-os/kernel-core/graph/query';
2
+ const ast = Query.from({ nodes: [task] }).select({ kind: 'nodes', projection: { kind: 'value' } });
3
+ const list = {
4
+ query: QUERY,
5
+ list: { nodes: [Task], orderBy: [{ property: title, direction: 'asc', missing: 'last' }] },
6
+ };
7
+ const exists = { query: QUERY, exists: { nodes: [Task] } };
8
+ const count = { query: QUERY, count: { nodes: [Task] }, upTo: 10 };
9
+ async function overloads() {
10
+ // A V6 QueryAST picks the legacy overload and its result; a Query the answer of its family.
11
+ const legacy = await graph.query(ast, { page: { size: 10 } });
12
+ const listed = await graph.query(list, { paging: { sizes: [{ at: [], size: 10 }] } });
13
+ const decided = await graph.query(exists);
14
+ const counted = await graph.query(count, { expected: [] });
15
+ return [legacy, listed, decided, counted];
16
+ }
17
+ async function refusals() {
18
+ // @ts-expect-error A Query takes its paging in `paging`, not V6's `page`.
19
+ await graph.query(list, { page: { size: 10 } });
20
+ // @ts-expect-error A V6 QueryAST needs its `page`; v7 `paging` is not one.
21
+ await graph.query(ast, { paging: { sizes: [{ at: [], size: 10 }] } });
22
+ // @ts-expect-error A V6 QueryAST has no default page.
23
+ await graph.query(ast);
24
+ // @ts-expect-error A Query names the v7 version.
25
+ await graph.query({ query: 'astrale.query/6', list: { nodes: [Task] } });
26
+ // @ts-expect-error A Query's root fold is list, exists or count.
27
+ await graph.query({ query: QUERY, nodes: [Task] });
28
+ // @ts-expect-error A count needs its bound.
29
+ await graph.query({ query: QUERY, count: { nodes: [Task] } });
30
+ // @ts-expect-error An input is a Query or a V6 QueryAST.
31
+ await graph.query({ ...ast, query: QUERY });
32
+ }
33
+ void overloads;
34
+ void refusals;
@@ -2,16 +2,23 @@ import type { NodeId } from '@astrale-os/kernel-core/graph/node';
2
2
  import type { installation } from '@astrale-os/kernel-core/schema';
3
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
4
  import type { schema as protocolSchema } from '@astrale-os/kernel-protocol';
5
- import type { ExecutionOutcome, ExecutionStatus, ExecutionWait } from '../execution/index.js';
5
+ import type { ExecutionOutcome, ExecutionStatus } from '../execution/index.js';
6
6
  export type OperationId = installation.OperationId;
7
7
  /** Canonical caller input accepted by the Kernel install syscall. */
8
8
  export type DomainRequest = CoreDomainRequest;
9
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.
10
+ * How long an install, an uninstall or a watch of an install waits at most, `waitMs`, in
11
+ * milliseconds: 110 s by default; `0` reads the status once and answers it. The wait is the
12
+ * Client's own: it is never sent, so it is no part of the operation's intent.
13
13
  */
14
- export type InstallRequest = InstallInput & ExecutionWait;
14
+ export interface LifecycleWait {
15
+ readonly waitMs?: number;
16
+ }
17
+ /**
18
+ * One install: its Kernel input, plus how long the Client waits for its outcome, or, in mode
19
+ * `maintenance`, until its repair session awaits Root's first command.
20
+ */
21
+ export type InstallRequest = InstallInput & LifecycleWait;
15
22
  /** Admitted terminal install receipt returned by the Kernel. */
16
23
  export type InstallReceipt = CoreInstallReceipt;
17
24
  /** The committed result of an install: its receipt, or the generations it proved unchanged. */
@@ -33,6 +40,13 @@ export type InstallOutcome = ExecutionOutcome<InstallResult>;
33
40
  * attempt report).
34
41
  */
35
42
  export type InstallStatus = ExecutionStatus<InstallResult>;
43
+ /**
44
+ * How long a watch of an install lasts at most, and, for a repair session, the index the command
45
+ * it awaits must pass, `after` (`0` by default: any).
46
+ */
47
+ export interface InstallationWatch extends LifecycleWait {
48
+ readonly after?: number;
49
+ }
36
50
  /** One admitted install answer: its Execution, its status, and its result once completed. */
37
51
  export interface Installation {
38
52
  readonly execution: NodeId;
@@ -45,11 +59,8 @@ export interface Installation {
45
59
  /** The committed result, present exactly when the status is completed. */
46
60
  readonly result?: InstallResult;
47
61
  }
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;
62
+ /** One uninstall: its Kernel input, plus how long the Client waits for its outcome. */
63
+ export type UninstallRequest = UninstallInput & LifecycleWait;
53
64
  /** Admitted terminal uninstall receipt returned by the Kernel. */
54
65
  export type UninstallReceipt = UninstallOutput;
55
66
  /** A terminal uninstall: its committed receipt, its rejection, or its cancellation. */
@@ -1,4 +1,4 @@
1
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
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';
4
+ export type { DomainRequest, InstallAttemptReport, InstallClass, InstallDetail, InstallMode, InstallOutcome, InstallResult, InstallStatus, InstallValidationOptions, Installation, InstallationWatch, InstallReceipt, InstallRequest, LifecycleWait, OperationId, Uninstallation, UninstallOutcome, UninstallReceipt, UninstallRequest, UninstallStatus, } from './contracts.js';
@@ -2,7 +2,7 @@ import type { NodeId } from '@astrale-os/kernel-core/graph/node';
2
2
  import type { InstallValidation } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
3
  import type { ExecutionCall, ExecutionWait } from '../execution/index.js';
4
4
  import type { RequestOptions } from '../transport/index.js';
5
- import type { InstallOutcome, InstallStatus, UninstallOutcome, UninstallStatus } from './contracts.js';
5
+ import type { InstallationWatch, InstallOutcome, InstallStatus, LifecycleWait, UninstallOutcome, UninstallStatus } from './contracts.js';
6
6
  /**
7
7
  * The install executions of one Instance, through the `K.Execution` Methods of each. Observing
8
8
  * and a cooperative cancel are Root's or the initiator's; signals, a forced cancel, resume and
@@ -13,6 +13,14 @@ export interface InstallationApi {
13
13
  status(execution: NodeId, options?: RequestOptions): Promise<InstallStatus>;
14
14
  /** The terminal outcome, waiting at most `waitMs` in total; `EXECUTION_PENDING` once it lapses. */
15
15
  result(execution: NodeId, wait?: ExecutionWait, options?: RequestOptions): Promise<InstallOutcome>;
16
+ /**
17
+ * Read the status until the repair session awaits a command whose index passes `after`, or the
18
+ * install ends, pauses or expires, or `waitMs` lapses, or the deadline `timeoutMs` sets is within
19
+ * the answer margin (2 s), and answer the last status read. Each read
20
+ * follows the last one after a quarter of the time the watch has lasted, at most one second and
21
+ * never less than that read took: a change is seen within a quarter of the time it took to come.
22
+ */
23
+ watch(execution: NodeId, watch?: InstallationWatch, options?: RequestOptions): Promise<InstallStatus>;
16
24
  /**
17
25
  * A waiting repair session attempts its target: the `command:<index>` signal, `index` being
18
26
  * the `detail.command` its status announces. A signal already resolved is refused.
@@ -64,3 +72,5 @@ export interface UninstallationApi {
64
72
  export declare function createInstallation(call: ExecutionCall): InstallationApi;
65
73
  /** The uninstall Methods: a completed outcome carries the receipt Core's contract admits. */
66
74
  export declare function createUninstallation(call: ExecutionCall): UninstallationApi;
75
+ /** The wait `wait` asks for, in milliseconds: its `waitMs`, or the default. */
76
+ export declare function lifecycleWait(wait: LifecycleWait | undefined): number;
@@ -1,11 +1,17 @@
1
1
  import { abortSignal, commandSignal, uninstallOutput, } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
2
2
  import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
3
- import { acceptOutput, executionMethods } from '../execution/index.js';
3
+ import { acceptOutput, acceptWait, deadlineOf, executionMethods, waitEnd, within, } from '../execution/index.js';
4
+ import { pause } from '../transport/index.js';
5
+ /** How long an install or uninstall waits for what it waits for unless its request says otherwise. */
6
+ const DEFAULT_LIFECYCLE_WAIT_MS = 110_000;
7
+ /** The longest pause between two reads of a watch: a long watch reads once a second. */
8
+ const WATCH_PAUSE_MS = 1_000;
4
9
  /** The install Methods: a completed outcome carries the result its Protocol owner admits. */
5
10
  export function createInstallation(call) {
6
11
  const { signal, ...methods } = executionMethods(call, acceptInstallResult);
7
12
  return Object.freeze({
8
13
  ...methods,
14
+ watch: (execution, watch, options) => watchInstall(methods.status, execution, watch, options),
9
15
  apply: async (execution, command, options) => signal(execution, {
10
16
  name: commandSignal(ordinal(command.index)),
11
17
  value: Object.freeze({
@@ -21,6 +27,44 @@ export function createUninstallation(call) {
21
27
  const { signal: _signal, ...methods } = executionMethods(call, acceptUninstallReceipt);
22
28
  return Object.freeze(methods);
23
29
  }
30
+ /** The watch `InstallationApi.watch` describes, over the `status` Method. */
31
+ async function watchInstall(status, execution, watch, options) {
32
+ const waitMs = lifecycleWait(watch);
33
+ const after = watch?.after ?? 0;
34
+ if (!Number.isSafeInteger(after) || after < 0) {
35
+ throw new TypeError('A watched command index is a nonnegative integer.');
36
+ }
37
+ const deadline = deadlineOf(options);
38
+ const started = Date.now();
39
+ // Each read after the first has the answer margin left before the call's deadline to come back.
40
+ const ends = waitEnd(deadline, waitMs);
41
+ for (;;) {
42
+ const read = Date.now();
43
+ const current = await status(execution, within(deadline, options));
44
+ const now = Date.now();
45
+ if (settled(current, after) || now >= ends)
46
+ return current;
47
+ // In whole milliseconds, a timer's own resolution: an instant read never reads again at once.
48
+ await pause(Math.min(WATCH_PAUSE_MS, Math.max(1, now - read, Math.ceil((now - started) / 4)), ends - now), options?.signal);
49
+ // A read starts by the end of the watch at the latest: a timer that woke past it reads no more.
50
+ if (Date.now() > ends)
51
+ return current;
52
+ }
53
+ }
54
+ /**
55
+ * Whether a watch ends at `status`: its session awaits a command past `after`, or nothing changes
56
+ * it any more without a command: it ended, paused or expired.
57
+ */
58
+ function settled(status, after) {
59
+ if (status.outcome !== undefined || status.state === 'paused' || status.state === 'expired')
60
+ return true;
61
+ const detail = status.detail;
62
+ return detail?.phase === 'awaiting' && (detail.command ?? 0) > after;
63
+ }
64
+ /** The wait `wait` asks for, in milliseconds: its `waitMs`, or the default. */
65
+ export function lifecycleWait(wait) {
66
+ return acceptWait({ waitMs: wait?.waitMs ?? DEFAULT_LIFECYCLE_WAIT_MS });
67
+ }
24
68
  function acceptInstallResult(input) {
25
69
  if (uninstallOutput.safeParse(input).success) {
26
70
  throw new TypeError('The Execution is an uninstall: read it through SchemaApi.uninstallation.');
@@ -15,10 +15,10 @@ export type InstalledPin = protocolSchema.installation.introspection.InstalledPi
15
15
  export interface SchemaApi {
16
16
  /**
17
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.
18
+ * default) for its outcome, or, in mode `maintenance`, until its repair session awaits Root's
19
+ * first command (`installation.watch`), and answer its status. `timeoutMs`, when given, bounds the
20
+ * whole call. The answer names the Execution with its status; `result` is present once it
21
+ * completed. A rejected install is a terminal `failed` status, never a failed call.
22
22
  */
23
23
  install(request: InstallRequest, options?: RequestOptions): Promise<Installation>;
24
24
  /** The install executions and repair sessions, through their `K.Execution` Methods. */
@@ -1,13 +1,11 @@
1
1
  import { Path } from '@astrale-os/kernel-core/path';
2
2
  import { install, uninstall } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
3
3
  import { call as invocation } from '../client/index.js';
4
- import { acceptWait, deadlineOf, within } from '../execution/index.js';
5
- import { createInstallation, createUninstallation, } from './installation.js';
4
+ import { deadlineOf, within } from '../execution/index.js';
5
+ import { createInstallation, createUninstallation, lifecycleWait, } from './installation.js';
6
6
  import { introspect } from './introspection.js';
7
7
  const INSTALL_PATH = Path.project(install).raw;
8
8
  const UNINSTALL_PATH = Path.project(uninstall).raw;
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
9
  /** Bind the canonical Schema lifecycle syscalls to one caller-scoped value-call capability. */
12
10
  export function createSchema(call, limits) {
13
11
  if (typeof call !== 'function')
@@ -17,17 +15,19 @@ export function createSchema(call, limits) {
17
15
  const uninstallation = createUninstallation(call);
18
16
  return Object.freeze({
19
17
  async install(request, options) {
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);
18
+ const { waitMs: _waitMs, ...input } = request;
19
+ const waitMs = lifecycleWait(request);
20
+ // A maintenance session's outcome is Root's to decide: the call waits until it awaits Root.
21
+ const wait = input.mode === 'maintenance'
22
+ ? sessionWait(installation, waitMs)
23
+ : outcomeWait(installation, waitMs);
24
+ return admitInstallation(request, await lifecycle(call, INSTALL_PATH, input, wait, options));
25
25
  },
26
26
  installation,
27
27
  async uninstall(request, options) {
28
- const wait = lifecycleWait(request.waitMs);
28
+ const wait = outcomeWait(uninstallation, lifecycleWait(request));
29
29
  const snapshot = snapshotUninstallRequest(request);
30
- const started = await lifecycle(call, uninstallation, UNINSTALL_PATH, snapshot, wait, options);
30
+ const started = await lifecycle(call, UNINSTALL_PATH, snapshot, wait, options);
31
31
  const answer = { execution: started.status.id, ...started };
32
32
  const { status } = started;
33
33
  if (status.outcome?.kind !== 'completed')
@@ -50,28 +50,38 @@ export function createSchema(call, limits) {
50
50
  },
51
51
  });
52
52
  }
53
+ /** Wait at most `waitMs` for the outcome, however that wait ends, then read the status. */
54
+ function outcomeWait(executions, waitMs) {
55
+ return async (execution, deadline, options) => {
56
+ if (waitMs > 0)
57
+ await executions
58
+ .result(execution, { waitMs }, within(deadline, options))
59
+ .catch(() => undefined);
60
+ return executions.status(execution, within(deadline, options));
61
+ };
62
+ }
63
+ /**
64
+ * Watch a repair session at most `waitMs`, until it awaits Root's first command, and answer the
65
+ * last status read; a watch that fails reads the status once.
66
+ */
67
+ function sessionWait(installation, waitMs) {
68
+ return (execution, deadline, options) => installation
69
+ .watch(execution, { waitMs }, within(deadline, options))
70
+ .catch(() => installation.status(execution, within(deadline, options)));
71
+ }
53
72
  /**
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.
73
+ * One lifecycle syscall, before the call's deadline: start the durable Execution it is and answer
74
+ * the status `wait` ends on.
57
75
  */
58
- async function lifecycle(call, executions, path, input, waitMs, options) {
76
+ async function lifecycle(call, path, input, wait, options) {
59
77
  const deadline = deadlineOf(options);
60
78
  const started = await call(invocation(path, input), within(deadline, options));
61
79
  if (started.kind !== 'execution') {
62
80
  throw new TypeError('Schema syscall did not answer with an Execution.');
63
81
  }
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));
82
+ const status = await wait(started.execution, deadline, options);
70
83
  return started.replayed === undefined ? { status } : { status, replayed: started.replayed };
71
84
  }
72
- function lifecycleWait(waitMs) {
73
- return acceptWait({ waitMs: waitMs ?? DEFAULT_LIFECYCLE_WAIT_MS });
74
- }
75
85
  function snapshotUninstallRequest(request) {
76
86
  return Object.freeze({
77
87
  operation: request.operation,
@@ -20,40 +20,41 @@ export function bindSession(source, controls) {
20
20
  const downloadSource = capture(contentSource, 'download');
21
21
  const viewsForSource = capture(source, 'viewsFor');
22
22
  const schemaSource = captureSchema(source.schema);
23
- const dispatch = ((input, options) => dispatchSource(input, requestOptions(options, admittedControls)));
23
+ const dispatch = ((input, options) => dispatchSource(input, mergeOptions(options, admittedControls)));
24
24
  const admit = (input, options) => admitSource(input, mergeOptions(options, admittedControls));
25
- const call = ((input, options) => callSource(input, requestOptions(options, admittedControls)));
26
- const invoke = ((reference, input, options) => invokeSource(reference, input, requestOptions(options, admittedControls)));
27
- const stream = (input, options) => streamSource(input, requestOptions(options, admittedControls));
28
- const binary = (input, options) => binarySource(input, requestOptions(options, admittedControls));
25
+ const call = ((input, options) => callSource(input, mergeOptions(options, admittedControls)));
26
+ const invoke = ((reference, input, options) => invokeSource(reference, input, mergeOptions(options, admittedControls)));
27
+ const stream = (input, options) => streamSource(input, mergeOptions(options, admittedControls));
28
+ const binary = (input, options) => binarySource(input, mergeOptions(options, admittedControls));
29
29
  const upload = (input, options) => uploadSource(input, mergeOptions(options, admittedControls));
30
30
  // Both forms share the bound controls; the source selects the form from its argument.
31
- const download = ((input, options) => downloadSource(input, controlOptions(options, admittedControls)));
31
+ const download = ((input, options) => downloadSource(input, mergeOptions(options, admittedControls)));
32
32
  const content = Object.freeze({ upload, download });
33
- const viewsFor = (domain, options) => viewsForSource(domain, controlOptions(options, admittedControls));
34
- const install = (request, options) => schemaSource.install(request, controlOptions(options, admittedControls));
35
- const uninstall = (request, options) => schemaSource.uninstall(request, controlOptions(options, admittedControls));
36
- const inspect = (origin, options) => schemaSource.inspect(origin, controlOptions(options, admittedControls));
37
- const bundle = (origin, options) => schemaSource.bundle(origin, controlOptions(options, admittedControls));
38
- const dependencies = (origin, options) => schemaSource.dependencies(origin, controlOptions(options, admittedControls));
39
- const installed = (options) => schemaSource.installed(controlOptions(options, admittedControls));
33
+ const viewsFor = (domain, options) => viewsForSource(domain, mergeOptions(options, admittedControls));
34
+ const install = (request, options) => schemaSource.install(request, mergeOptions(options, admittedControls));
35
+ const uninstall = (request, options) => schemaSource.uninstall(request, mergeOptions(options, admittedControls));
36
+ const inspect = (origin, options) => schemaSource.inspect(origin, mergeOptions(options, admittedControls));
37
+ const bundle = (origin, options) => schemaSource.bundle(origin, mergeOptions(options, admittedControls));
38
+ const dependencies = (origin, options) => schemaSource.dependencies(origin, mergeOptions(options, admittedControls));
39
+ const installed = (options) => schemaSource.installed(mergeOptions(options, admittedControls));
40
40
  const installs = schemaSource.installation;
41
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)),
42
+ status: (execution, options) => installs.status(execution, mergeOptions(options, admittedControls)),
43
+ result: (execution, wait, options) => installs.result(execution, wait, mergeOptions(options, admittedControls)),
44
+ watch: (execution, watch, options) => installs.watch(execution, watch, mergeOptions(options, admittedControls)),
45
+ apply: (execution, command, options) => installs.apply(execution, command, mergeOptions(options, admittedControls)),
46
+ abort: (execution, attempt, options) => installs.abort(execution, attempt, mergeOptions(options, admittedControls)),
47
+ cancel: (execution, input, options) => installs.cancel(execution, input, mergeOptions(options, admittedControls)),
48
+ resume: (execution, options) => installs.resume(execution, mergeOptions(options, admittedControls)),
49
+ delete: (execution, options) => installs.delete(execution, mergeOptions(options, admittedControls)),
49
50
  });
50
51
  const uninstalls = schemaSource.uninstallation;
51
52
  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)),
53
+ status: (execution, options) => uninstalls.status(execution, mergeOptions(options, admittedControls)),
54
+ result: (execution, wait, options) => uninstalls.result(execution, wait, mergeOptions(options, admittedControls)),
55
+ cancel: (execution, input, options) => uninstalls.cancel(execution, input, mergeOptions(options, admittedControls)),
56
+ resume: (execution, options) => uninstalls.resume(execution, mergeOptions(options, admittedControls)),
57
+ delete: (execution, options) => uninstalls.delete(execution, mergeOptions(options, admittedControls)),
57
58
  });
58
59
  const schema = Object.freeze({
59
60
  install,
@@ -102,12 +103,6 @@ function admitControls(input) {
102
103
  }
103
104
  return Object.freeze({ signal: input.signal, deadline: input.deadline });
104
105
  }
105
- function requestOptions(options, controls) {
106
- return mergeOptions(options, controls);
107
- }
108
- function controlOptions(options, controls) {
109
- return mergeOptions(options, controls);
110
- }
111
106
  function mergeOptions(options, controls) {
112
107
  if (controls === undefined)
113
108
  return options;
@@ -140,6 +135,7 @@ function captureSchema(input) {
140
135
  installation: Object.freeze({
141
136
  status: capture(installation, 'status'),
142
137
  result: capture(installation, 'result'),
138
+ watch: capture(installation, 'watch'),
143
139
  apply: capture(installation, 'apply'),
144
140
  abort: capture(installation, 'abort'),
145
141
  cancel: capture(installation, 'cancel'),
@@ -1,4 +1,4 @@
1
- import { cancelUnsent, isReplayable } from '../../transport/http/binary-request.js';
1
+ import { cancelUnsent } from '../../transport/http/binary-request.js';
2
2
  import { requireResultKind } from '../routing/index.js';
3
3
  import { downloadBatch } from './batch.js';
4
4
  import { acceptBody, acceptControls, acceptLocation, acceptMediaType } from './input.js';
@@ -13,7 +13,7 @@ export function createContentApi(dependencies) {
13
13
  const operation = dependencies.operation(acceptControls(options));
14
14
  const send = () => dependencies.dispatch(UPLOAD, { mediaType }, operation, body);
15
15
  // A stream cannot be read twice: it has one attempt.
16
- const result = await (isReplayable(body) ? retry(operation, send) : send());
16
+ const result = await (body.kind === 'replayable' ? retry(operation, send) : send());
17
17
  return decodeUploadResult(requireResultKind('value', result).value);
18
18
  }
19
19
  catch (cause) {