@astrale-os/kernel-client 1.0.0-beta.3 → 1.0.0-beta.30

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 (192) hide show
  1. package/dist/auth/index.d.ts +1 -0
  2. package/dist/client/admission.js +3 -1
  3. package/dist/client/client.d.ts +19 -2
  4. package/dist/client/client.js +62 -30
  5. package/dist/client/index.d.ts +3 -3
  6. package/dist/client/index.js +2 -2
  7. package/dist/client/request.d.ts +8 -2
  8. package/dist/client/request.js +28 -7
  9. package/dist/client/result.d.ts +10 -1
  10. package/dist/client/result.js +10 -4
  11. package/dist/client/routing-control.d.ts +11 -15
  12. package/dist/client/routing-control.js +21 -29
  13. package/dist/errors/index.d.ts +3 -0
  14. package/dist/errors/index.js +3 -0
  15. package/dist/errors/query-input.d.ts +47 -0
  16. package/dist/errors/query-input.js +85 -0
  17. package/dist/errors/refusal.d.ts +19 -0
  18. package/dist/errors/refusal.js +63 -0
  19. package/dist/errors/response-too-large-error.d.ts +11 -0
  20. package/dist/errors/response-too-large-error.js +15 -0
  21. package/dist/errors/stale-route-error.d.ts +1 -1
  22. package/dist/errors/stale-route-error.js +1 -1
  23. package/dist/{schema → execution}/admission.d.ts +2 -2
  24. package/dist/{schema → execution}/admission.js +3 -3
  25. package/dist/execution/contracts.d.ts +76 -0
  26. package/dist/execution/contracts.js +1 -0
  27. package/dist/execution/deadline.d.ts +18 -0
  28. package/dist/execution/deadline.js +25 -0
  29. package/dist/execution/execution.d.ts +61 -0
  30. package/dist/execution/execution.js +132 -0
  31. package/dist/execution/index.d.ts +4 -0
  32. package/dist/execution/index.js +3 -0
  33. package/dist/graph/domain/binding.d.ts +2 -2
  34. package/dist/graph/domain/binding.js +24 -17
  35. package/dist/graph/domain/conformance.d.ts +12 -0
  36. package/dist/graph/domain/conformance.js +18 -0
  37. package/dist/graph/domain/index.d.ts +1 -0
  38. package/dist/graph/domain/index.js +1 -1
  39. package/dist/graph/domain/provenance.d.ts +0 -2
  40. package/dist/graph/domain/provenance.js +0 -4
  41. package/dist/graph/graph.d.ts +17 -3
  42. package/dist/graph/graph.js +4 -1
  43. package/dist/graph/index.d.ts +3 -3
  44. package/dist/graph/index.js +1 -1
  45. package/dist/graph/page-contract.d.ts +64 -1
  46. package/dist/graph/provenance.d.ts +4 -5
  47. package/dist/graph/provenance.js +5 -6
  48. package/dist/graph/query.d.ts +10 -4
  49. package/dist/graph/query.js +145 -7
  50. package/dist/graph/query.typecheck.d.ts +77 -0
  51. package/dist/graph/query.typecheck.js +34 -0
  52. package/dist/pacer/index.d.ts +1 -1
  53. package/dist/pacer/index.js +1 -1
  54. package/dist/pacer/retry/index.d.ts +1 -0
  55. package/dist/pacer/retry/index.js +1 -0
  56. package/dist/pacer/retry/refusals.d.ts +7 -0
  57. package/dist/pacer/retry/refusals.js +10 -0
  58. package/dist/pacer/retry/retry.d.ts +2 -0
  59. package/dist/pacer/retry/retry.js +33 -1
  60. package/dist/schema/contracts.d.ts +77 -9
  61. package/dist/schema/index.d.ts +3 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +76 -0
  64. package/dist/schema/installation.js +82 -0
  65. package/dist/schema/schema.d.ts +22 -13
  66. package/dist/schema/schema.js +67 -48
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +66 -20
  70. package/dist/session/content/api.d.ts +10 -2
  71. package/dist/session/content/api.js +13 -4
  72. package/dist/session/content/index.d.ts +1 -1
  73. package/dist/session/content/input.d.ts +6 -1
  74. package/dist/session/content/input.js +12 -4
  75. package/dist/session/content/retry.d.ts +5 -1
  76. package/dist/session/content/retry.js +21 -31
  77. package/dist/session/context/index.d.ts +1 -1
  78. package/dist/session/context/index.js +1 -1
  79. package/dist/session/context/operation.d.ts +2 -0
  80. package/dist/session/context/operation.js +5 -0
  81. package/dist/session/credential/credentials.js +43 -28
  82. package/dist/session/discovery/bundle.d.ts +9 -4
  83. package/dist/session/discovery/bundle.js +28 -35
  84. package/dist/session/discovery/discovery.d.ts +1 -1
  85. package/dist/session/discovery/discovery.js +8 -11
  86. package/dist/session/discovery/release.js +18 -28
  87. package/dist/session/discovery/snapshot.d.ts +5 -1
  88. package/dist/session/discovery/transport.d.ts +35 -3
  89. package/dist/session/discovery/transport.js +40 -1
  90. package/dist/session/durable.d.ts +13 -0
  91. package/dist/session/durable.js +39 -0
  92. package/dist/session/exchange/exchange.d.ts +3 -2
  93. package/dist/session/exchange/exchange.js +10 -7
  94. package/dist/session/exchange/index.d.ts +1 -1
  95. package/dist/session/exchange/index.js +1 -1
  96. package/dist/session/exchange/presentation.js +28 -10
  97. package/dist/session/exchange/source.d.ts +7 -7
  98. package/dist/session/exchange/source.js +26 -27
  99. package/dist/session/index.d.ts +4 -3
  100. package/dist/session/index.js +0 -1
  101. package/dist/session/options.d.ts +0 -2
  102. package/dist/session/options.js +0 -3
  103. package/dist/session/reference.d.ts +9 -5
  104. package/dist/session/reference.js +7 -2
  105. package/dist/session/retry.d.ts +12 -0
  106. package/dist/session/retry.js +23 -0
  107. package/dist/session/routing/auth.d.ts +9 -3
  108. package/dist/session/routing/auth.js +4 -3
  109. package/dist/session/routing/cache.d.ts +12 -5
  110. package/dist/session/routing/cache.js +56 -48
  111. package/dist/session/routing/dispatch.d.ts +26 -3
  112. package/dist/session/routing/dispatch.js +112 -67
  113. package/dist/session/routing/envelope.d.ts +3 -3
  114. package/dist/session/routing/index.d.ts +1 -1
  115. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  116. package/dist/session/routing/legacy/release-route.js +6 -0
  117. package/dist/session/routing/recovery.d.ts +3 -6
  118. package/dist/session/routing/recovery.js +3 -14
  119. package/dist/session/routing/request.d.ts +6 -1
  120. package/dist/session/routing/request.js +13 -2
  121. package/dist/session/routing/result.d.ts +1 -1
  122. package/dist/session/routing/result.js +5 -1
  123. package/dist/session/routing/store.js +4 -5
  124. package/dist/session/session.d.ts +31 -5
  125. package/dist/session/session.js +60 -19
  126. package/dist/session/session.typecheck.js +20 -6
  127. package/dist/session/views/index.d.ts +2 -2
  128. package/dist/session/views/index.js +2 -2
  129. package/dist/session/views/kernel.d.ts +31 -0
  130. package/dist/session/views/kernel.js +30 -0
  131. package/dist/session/views/legacy/catalog.d.ts +21 -0
  132. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  133. package/dist/session/views/legacy/index.d.ts +14 -0
  134. package/dist/session/views/legacy/index.js +14 -0
  135. package/dist/session/views/legacy/resolve.d.ts +46 -0
  136. package/dist/session/views/legacy/resolve.js +83 -0
  137. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  138. package/dist/session/views/legacy/unplaced.js +26 -0
  139. package/dist/session/views/read.d.ts +49 -0
  140. package/dist/session/views/read.js +148 -0
  141. package/dist/session/views/view.d.ts +48 -0
  142. package/dist/session/views/view.js +74 -0
  143. package/dist/store/memory.d.ts +1 -3
  144. package/dist/store/memory.js +73 -105
  145. package/dist/store/shape.d.ts +33 -12
  146. package/dist/store/shape.js +125 -16
  147. package/dist/store/store.d.ts +6 -6
  148. package/dist/store/store.js +1 -1
  149. package/dist/transport/auto/decision.d.ts +26 -14
  150. package/dist/transport/auto/decision.js +35 -32
  151. package/dist/transport/auto/fallback.d.ts +1 -1
  152. package/dist/transport/auto/fallback.js +5 -10
  153. package/dist/transport/auto/transport.d.ts +0 -2
  154. package/dist/transport/auto/transport.js +24 -32
  155. package/dist/transport/deadline.d.ts +2 -0
  156. package/dist/transport/deadline.js +18 -0
  157. package/dist/transport/failure.d.ts +28 -1
  158. package/dist/transport/failure.js +63 -1
  159. package/dist/transport/http/admission.js +7 -34
  160. package/dist/transport/http/binary-request.d.ts +44 -0
  161. package/dist/transport/http/binary-request.js +110 -0
  162. package/dist/transport/http/binary.js +3 -3
  163. package/dist/transport/http/byte-stream.d.ts +2 -1
  164. package/dist/transport/http/byte-stream.js +12 -8
  165. package/dist/transport/http/index.d.ts +1 -1
  166. package/dist/transport/http/index.js +1 -1
  167. package/dist/transport/http/response.d.ts +3 -1
  168. package/dist/transport/http/response.js +7 -9
  169. package/dist/transport/http/stream.d.ts +8 -13
  170. package/dist/transport/http/stream.js +34 -81
  171. package/dist/transport/http/transport.d.ts +10 -0
  172. package/dist/transport/http/transport.js +87 -32
  173. package/dist/transport/http/unprocessed.d.ts +5 -0
  174. package/dist/transport/http/unprocessed.js +28 -0
  175. package/dist/transport/index.d.ts +1 -1
  176. package/dist/transport/index.js +1 -1
  177. package/dist/transport/stream.d.ts +52 -0
  178. package/dist/transport/stream.js +101 -0
  179. package/dist/transport/transport.d.ts +10 -0
  180. package/dist/transport/unary.d.ts +8 -0
  181. package/dist/transport/unary.js +34 -0
  182. package/dist/transport/websocket/connection.d.ts +7 -3
  183. package/dist/transport/websocket/connection.js +103 -92
  184. package/dist/transport/websocket/exchange.d.ts +12 -19
  185. package/dist/transport/websocket/exchange.js +86 -184
  186. package/dist/transport/websocket/transport.js +11 -19
  187. package/package.json +7 -5
  188. package/dist/session/execution.d.ts +0 -65
  189. package/dist/session/execution.js +0 -34
  190. package/dist/session/views/catalog.d.ts +0 -19
  191. package/dist/session/views/resolve.d.ts +0 -13
  192. package/dist/session/views/resolve.js +0 -21
@@ -5,25 +5,46 @@ import type { QueryPageRequest } from '../graph/index.js';
5
5
  import type { FactReferences } from './entity-index.js';
6
6
  import type { StoreQueryResponse, StoreSnapshot } from './store.js';
7
7
  type ShapeState = StoreSnapshot['state'];
8
+ /** A confirmed server response with the facts it references and the response displayed from it. */
9
+ export interface QueryAnswer {
10
+ readonly confirmed: StoreQueryResponse;
11
+ readonly references: FactReferences;
12
+ readonly response: StoreQueryResponse;
13
+ readonly refreshedAt: number;
14
+ }
15
+ /** One cached query: its answer, snapshot, observers, in-flight read and retention clock. */
8
16
  export declare class QueryShape {
17
+ #private;
9
18
  readonly key: string;
10
19
  readonly ast: QueryAST;
11
20
  readonly page: QueryPageRequest;
12
21
  readonly expected: readonly DomainDependency[] | undefined;
13
- readonly listeners: Set<() => void>;
14
- state: ShapeState;
15
- confirmed?: StoreQueryResponse;
16
- response?: StoreQueryResponse;
17
- references?: FactReferences;
18
- inflight?: Promise<StoreQueryResponse>;
19
- invalidation: number;
20
- releasedAt?: number;
21
- accessedAt: number;
22
- refreshedAt?: number;
23
- snapshot: StoreSnapshot;
24
- constructor(key: string, ast: QueryAST, page: QueryPageRequest, expected: readonly DomainDependency[] | undefined, now: number);
22
+ constructor(key: string, ast: QueryAST, page: QueryPageRequest, expected: readonly DomainDependency[] | undefined, now: number, report: (error: unknown) => void);
23
+ get snapshot(): StoreSnapshot;
24
+ get state(): ShapeState;
25
+ get answer(): QueryAnswer | undefined;
26
+ get inflight(): Promise<StoreQueryResponse> | undefined;
27
+ get invalidation(): number;
28
+ get accessedAt(): number;
25
29
  get observed(): boolean;
30
+ /** When the shape became unobserved and idle, or undefined while it is observed or reading. */
31
+ idleSince(): number | undefined;
26
32
  referencesAny(nodes: ReadonlySet<NodeId>, edges: ReadonlySet<string>): boolean;
33
+ touch(now: number): void;
34
+ listen(listener: () => void, now: number): void;
35
+ /** Removes a listener; the caller releases the shape once it is no longer observed. */
36
+ unlisten(listener: () => void): void;
37
+ release(now: number): void;
38
+ begin(read: Promise<StoreQueryResponse>): void;
39
+ /** Ends `read` if it is still the shape's read and reports whether it was. */
40
+ finish(read: Promise<StoreQueryResponse>): boolean;
41
+ invalidate(): void;
42
+ /** Records a newly confirmed answer, then publishes `state`. */
43
+ settle(answer: QueryAnswer, state: ShapeState): void;
44
+ /** Replaces the displayed answer without a new server confirmation, then publishes `state`. */
45
+ show(answer: QueryAnswer, state: ShapeState): void;
46
+ publish(state: ShapeState, error?: unknown): void;
47
+ close(): void;
27
48
  }
28
49
  export declare const COLD_SNAPSHOT: StoreSnapshot;
29
50
  export {};
@@ -1,32 +1,141 @@
1
+ /** One cached query: its answer, snapshot, observers, in-flight read and retention clock. */
1
2
  export class QueryShape {
2
3
  key;
3
4
  ast;
4
5
  page;
5
6
  expected;
6
- listeners = new Set();
7
- state = 'cold';
8
- confirmed;
9
- response;
10
- references;
11
- inflight;
12
- invalidation = 0;
13
- releasedAt;
14
- accessedAt;
15
- refreshedAt;
16
- snapshot = COLD_SNAPSHOT;
17
- constructor(key, ast, page, expected, now) {
7
+ #listeners = new Set();
8
+ #report;
9
+ #snapshot = COLD_SNAPSHOT;
10
+ #answer;
11
+ #inflight;
12
+ #invalidation = 0;
13
+ #accessedAt;
14
+ #releasedAt;
15
+ constructor(key, ast, page, expected, now, report) {
18
16
  this.key = key;
19
17
  this.ast = ast;
20
18
  this.page = page;
21
19
  this.expected = expected;
22
- this.accessedAt = now;
20
+ this.#accessedAt = now;
21
+ this.#releasedAt = now;
22
+ this.#report = report;
23
+ }
24
+ get snapshot() {
25
+ return this.#snapshot;
26
+ }
27
+ get state() {
28
+ return this.#snapshot.state;
29
+ }
30
+ get answer() {
31
+ return this.#answer;
32
+ }
33
+ get inflight() {
34
+ return this.#inflight;
35
+ }
36
+ get invalidation() {
37
+ return this.#invalidation;
38
+ }
39
+ get accessedAt() {
40
+ return this.#accessedAt;
23
41
  }
24
42
  get observed() {
25
- return this.listeners.size > 0;
43
+ return this.#listeners.size > 0;
44
+ }
45
+ /** When the shape became unobserved and idle, or undefined while it is observed or reading. */
46
+ idleSince() {
47
+ return this.observed || this.#inflight !== undefined ? undefined : this.#releasedAt;
26
48
  }
27
49
  referencesAny(nodes, edges) {
28
- return (this.references?.nodes.some((id) => nodes.has(id)) === true ||
29
- this.references?.edges.some((key) => edges.has(key)) === true);
50
+ const references = this.#answer?.references;
51
+ return (references?.nodes.some((id) => nodes.has(id)) === true ||
52
+ references?.edges.some((key) => edges.has(key)) === true);
53
+ }
54
+ touch(now) {
55
+ this.#accessedAt = now;
56
+ if (!this.observed)
57
+ this.#releasedAt = now;
58
+ }
59
+ listen(listener, now) {
60
+ this.#listeners.add(listener);
61
+ this.#accessedAt = now;
62
+ this.#releasedAt = undefined;
63
+ }
64
+ /** Removes a listener; the caller releases the shape once it is no longer observed. */
65
+ unlisten(listener) {
66
+ this.#listeners.delete(listener);
67
+ }
68
+ release(now) {
69
+ this.#releasedAt = now;
70
+ }
71
+ begin(read) {
72
+ this.#inflight = read;
73
+ }
74
+ /** Ends `read` if it is still the shape's read and reports whether it was. */
75
+ finish(read) {
76
+ if (this.#inflight !== read)
77
+ return false;
78
+ this.#inflight = undefined;
79
+ return true;
80
+ }
81
+ invalidate() {
82
+ this.#invalidation += 1;
83
+ }
84
+ /** Records a newly confirmed answer, then publishes `state`. */
85
+ settle(answer, state) {
86
+ this.#answer = answer;
87
+ this.touch(answer.refreshedAt);
88
+ this.publish(state);
89
+ }
90
+ /** Replaces the displayed answer without a new server confirmation, then publishes `state`. */
91
+ show(answer, state) {
92
+ this.#answer = answer;
93
+ this.publish(state);
94
+ }
95
+ publish(state, error) {
96
+ const next = snapshotFor(state, this.#answer?.response, error);
97
+ if (sameSnapshot(this.#snapshot, next))
98
+ return;
99
+ this.#snapshot = next;
100
+ for (const listener of Array.from(this.#listeners)) {
101
+ try {
102
+ listener();
103
+ }
104
+ catch (error) {
105
+ this.#report(error);
106
+ }
107
+ }
108
+ }
109
+ close() {
110
+ this.#listeners.clear();
111
+ this.#inflight?.catch(() => undefined);
30
112
  }
31
113
  }
32
114
  export const COLD_SNAPSHOT = Object.freeze({ state: 'cold' });
115
+ function snapshotFor(state, response, error) {
116
+ switch (state) {
117
+ case 'cold':
118
+ return Object.freeze({ state });
119
+ case 'loading':
120
+ return Object.freeze({ state });
121
+ case 'failed':
122
+ return Object.freeze({ state, error, ...(response === undefined ? {} : { response }) });
123
+ case 'ready':
124
+ case 'stale':
125
+ case 'refreshing':
126
+ case 'optimistic':
127
+ if (response === undefined)
128
+ throw new TypeError(`Store ${state} snapshot requires a response.`);
129
+ return Object.freeze({ state, response });
130
+ }
131
+ }
132
+ function sameSnapshot(left, right) {
133
+ if (left.state !== right.state)
134
+ return false;
135
+ if ('response' in left || 'response' in right) {
136
+ if (!('response' in left) || !('response' in right) || left.response !== right.response) {
137
+ return false;
138
+ }
139
+ }
140
+ return left.state !== 'failed' || right.state !== 'failed' || left.error === right.error;
141
+ }
@@ -1,10 +1,10 @@
1
1
  import type { MutationAST, MutationInput, MutationResult } from '@astrale-os/kernel-core/graph/mutate';
2
2
  import type { QueryAST, QueryResultFor } from '@astrale-os/kernel-core/graph/query';
3
3
  import type { QueryResponse } from '../graph/index.js';
4
- import type { GraphApi, GraphMutationOptions, GraphQueryOptions, MutationAuthor } from '../graph/index.js';
4
+ import type { GraphApi, GraphMutationOptions, GraphQueryV6Options, MutationAuthor } from '../graph/index.js';
5
5
  export type StoreQuery = QueryAST;
6
6
  export type StoreQueryResponse<Query extends StoreQuery = StoreQuery> = QueryResponse<QueryResultFor<Query>>;
7
- export interface StoreReadOptions extends GraphQueryOptions {
7
+ export interface StoreReadOptions extends GraphQueryV6Options {
8
8
  readonly freshness?: 'cached' | 'refresh';
9
9
  }
10
10
  export interface StoreMutationOptions extends GraphMutationOptions {
@@ -50,15 +50,15 @@ export declare class GraphStore {
50
50
  private closed;
51
51
  constructor(options: StoreOptions);
52
52
  read<Query extends StoreQuery>(query: Query, options: StoreReadOptions): Promise<StoreQueryResponse<Query>>;
53
- peek<Query extends StoreQuery>(query: Query, options: GraphQueryOptions): StoreQueryResponse<Query> | undefined;
53
+ peek<Query extends StoreQuery>(query: Query, options: GraphQueryV6Options): StoreQueryResponse<Query> | undefined;
54
54
  preload<Query extends StoreQuery>(query: Query, options: StoreReadOptions): Promise<void>;
55
- subscribe<Query extends StoreQuery>(query: Query, listener: () => void, options: GraphQueryOptions): () => void;
56
- getSnapshot<Query extends StoreQuery>(query: Query, options: GraphQueryOptions): StoreSnapshot<Query>;
55
+ subscribe<Query extends StoreQuery>(query: Query, listener: () => void, options: GraphQueryV6Options): () => void;
56
+ getSnapshot<Query extends StoreQuery>(query: Query, options: GraphQueryV6Options): StoreSnapshot<Query>;
57
57
  observe<Query extends StoreQuery>(query: Query, listener: (snapshot: StoreSnapshot<Query>) => void, options: StoreReadOptions): () => void;
58
58
  mutate(author: MutationAuthor, options?: StoreMutationOptions): Promise<MutationResult>;
59
59
  mutate(input: MutationAST | MutationInput, options?: StoreMutationOptions): Promise<MutationResult>;
60
60
  invalidate(): void;
61
- invalidate(query: StoreQuery, options: GraphQueryOptions): void;
61
+ invalidate(query: StoreQuery, options: GraphQueryV6Options): void;
62
62
  sweep(): void;
63
63
  close(): void;
64
64
  private admit;
@@ -56,7 +56,7 @@ export class GraphStore {
56
56
  }
57
57
  peek(query, options) {
58
58
  const { key } = this.identity(query, options);
59
- return this.memory.get(key)?.response;
59
+ return this.memory.get(key)?.answer?.response;
60
60
  }
61
61
  async preload(query, options) {
62
62
  await this.read(query, options);
@@ -1,23 +1,35 @@
1
- type AutoSelection = 'websocket' | 'http';
2
- type AutoDecisionTicket = {
3
- readonly kind: 'selected';
4
- readonly selection: AutoSelection;
1
+ export type AutoVia = 'websocket' | 'http';
2
+ /** A state the Auto transport choice can rest in. */
3
+ export type AutoSettled = {
4
+ readonly kind: 'undecided';
5
5
  } | {
6
- readonly kind: 'wait';
7
- readonly selection: Promise<AutoSelection | undefined>;
6
+ readonly kind: 'chosen';
7
+ readonly via: AutoVia;
8
8
  } | {
9
- readonly kind: 'probe';
9
+ readonly kind: 'closed';
10
10
  };
11
+ /** What `begin` grants: the probe itself, or the state the caller must follow. */
12
+ export type AutoTicket = {
13
+ readonly kind: 'probe';
14
+ } | {
15
+ readonly kind: 'probing';
16
+ readonly settled: Promise<AutoSettled>;
17
+ } | Exclude<AutoSettled, {
18
+ kind: 'undecided';
19
+ }>;
11
20
  /** Serializes the one initial transport decision without retaining invocation values. */
12
21
  export declare class AutoDecision {
13
- private selected;
14
- private pending;
15
- private closed;
16
- begin(): AutoDecisionTicket;
17
- select(selection: AutoSelection): void;
22
+ private state;
23
+ get closed(): boolean;
24
+ /** Claim the probe when undecided; otherwise report the state to follow. */
25
+ begin(): AutoTicket;
26
+ /** The probe proved WebSocket usable. */
27
+ selectWebSocket(): void;
18
28
  /** Permanently degrade a prior or pending WebSocket selection to HTTP. */
19
29
  demote(): void;
30
+ /** The probe proved nothing; the next caller probes again. */
20
31
  release(): void;
21
- close(): void;
32
+ /** Returns whether this call closed the decision. */
33
+ close(): boolean;
34
+ private move;
22
35
  }
23
- export {};
@@ -1,48 +1,51 @@
1
+ const UNDECIDED = Object.freeze({ kind: 'undecided' });
2
+ const CLOSED = Object.freeze({ kind: 'closed' });
1
3
  /** Serializes the one initial transport decision without retaining invocation values. */
2
4
  export class AutoDecision {
3
- selected;
4
- pending;
5
- closed = false;
5
+ state = UNDECIDED;
6
+ get closed() {
7
+ return this.state.kind === 'closed';
8
+ }
9
+ /** Claim the probe when undecided; otherwise report the state to follow. */
6
10
  begin() {
7
- if (this.closed)
8
- return { kind: 'wait', selection: Promise.resolve(undefined) };
9
- if (this.selected)
10
- return { kind: 'selected', selection: this.selected };
11
- if (this.pending)
12
- return { kind: 'wait', selection: this.pending.promise };
13
- let resolve;
14
- const promise = new Promise((settle) => {
15
- resolve = settle;
11
+ if (this.state.kind !== 'undecided')
12
+ return this.state;
13
+ let settle;
14
+ const settled = new Promise((resolve) => {
15
+ settle = resolve;
16
16
  });
17
- this.pending = { promise, resolve };
17
+ this.state = { kind: 'probing', settled, settle };
18
18
  return { kind: 'probe' };
19
19
  }
20
- select(selection) {
21
- if (this.closed || this.selected)
22
- return;
23
- this.selected = selection;
24
- this.pending?.resolve(selection);
25
- this.pending = undefined;
20
+ /** The probe proved WebSocket usable. */
21
+ selectWebSocket() {
22
+ if (this.state.kind === 'probing')
23
+ this.move({ kind: 'chosen', via: 'websocket' });
26
24
  }
27
25
  /** Permanently degrade a prior or pending WebSocket selection to HTTP. */
28
26
  demote() {
29
- if (this.closed || this.selected === 'http')
27
+ if (this.state.kind === 'closed')
28
+ return;
29
+ if (this.state.kind === 'chosen' && this.state.via === 'http')
30
30
  return;
31
- this.selected = 'http';
32
- this.pending?.resolve('http');
33
- this.pending = undefined;
31
+ this.move({ kind: 'chosen', via: 'http' });
34
32
  }
33
+ /** The probe proved nothing; the next caller probes again. */
35
34
  release() {
36
- if (this.closed || this.selected)
37
- return;
38
- this.pending?.resolve(undefined);
39
- this.pending = undefined;
35
+ if (this.state.kind === 'probing')
36
+ this.move(UNDECIDED);
40
37
  }
38
+ /** Returns whether this call closed the decision. */
41
39
  close() {
42
- if (this.closed)
43
- return;
44
- this.closed = true;
45
- this.pending?.resolve(undefined);
46
- this.pending = undefined;
40
+ if (this.state.kind === 'closed')
41
+ return false;
42
+ this.move(CLOSED);
43
+ return true;
44
+ }
45
+ move(next) {
46
+ const previous = this.state;
47
+ this.state = next;
48
+ if (previous.kind === 'probing')
49
+ previous.settle(next);
47
50
  }
48
51
  }
@@ -10,7 +10,7 @@ export declare class InvocationBudget {
10
10
  options(): RequestOptions;
11
11
  get cancelled(): boolean;
12
12
  get idempotency(): 'supplied' | 'absent';
13
- wait(decision: Promise<'websocket' | 'http' | undefined>): Promise<'websocket' | 'http' | undefined>;
13
+ wait<T>(decision: Promise<T>): Promise<T>;
14
14
  private remaining;
15
15
  }
16
16
  export declare function mayFallback(error: unknown): error is TransportError;
@@ -1,6 +1,6 @@
1
1
  import { targetPath } from '@astrale-os/kernel-core/callable';
2
2
  import { TransportError } from '../../errors/index.js';
3
- import { invocationFailure } from '../failure.js';
3
+ import { abortError, timeoutFailure } from '../failure.js';
4
4
  import { positiveInteger } from '../index.js';
5
5
  const MAXIMUM_TIMEOUT_MS = 2_147_483_647;
6
6
  /** One invocation-owned total timeout budget shared by selection and fallback. */
@@ -30,14 +30,14 @@ export class InvocationBudget {
30
30
  }
31
31
  async wait(decision) {
32
32
  if (this.input?.signal?.aborted)
33
- throw abortReason(this.input.signal);
33
+ throw abortError(this.input.signal.reason, new Error('request was cancelled'));
34
34
  const remaining = this.remaining();
35
35
  let timer;
36
36
  let abort;
37
37
  const interrupted = new Promise((_resolve, reject) => {
38
- timer = setTimeout(() => reject(invocationFailure('Automatic transport decision exceeded its timeout.', 'timeout')), remaining);
38
+ timer = setTimeout(() => reject(timeoutFailure('Automatic transport decision exceeded its timeout.')), remaining);
39
39
  if (this.input?.signal) {
40
- abort = () => reject(abortReason(this.input.signal));
40
+ abort = () => reject(abortError(this.input.signal.reason, new Error('request was cancelled')));
41
41
  this.input.signal.addEventListener('abort', abort, { once: true });
42
42
  }
43
43
  });
@@ -54,7 +54,7 @@ export class InvocationBudget {
54
54
  remaining() {
55
55
  const remaining = Math.min(MAXIMUM_TIMEOUT_MS, this.timeoutMs - (Date.now() - this.started));
56
56
  if (remaining < 1) {
57
- throw invocationFailure('Automatic transport invocation exceeded its timeout.', 'timeout');
57
+ throw timeoutFailure('Automatic transport invocation exceeded its timeout.');
58
58
  }
59
59
  return remaining;
60
60
  }
@@ -69,8 +69,3 @@ export function mayFallback(error) {
69
69
  export function warningTarget(input) {
70
70
  return targetPath(input.call.target);
71
71
  }
72
- function abortReason(signal) {
73
- return signal.reason instanceof Error
74
- ? signal.reason
75
- : new Error(signal.reason === undefined ? 'request was cancelled' : String(signal.reason));
76
- }
@@ -25,12 +25,10 @@ export declare class AutoTransport implements Transport {
25
25
  private readonly decision;
26
26
  private readonly timeoutMs;
27
27
  private readonly onWarning;
28
- private closed;
29
28
  constructor(options: AutoTransportOptions);
30
29
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
31
30
  private dispatchWithBudget;
32
31
  close(): void;
33
- private determine;
34
32
  private tryWebsocket;
35
33
  private requireOpen;
36
34
  }
@@ -14,7 +14,6 @@ export class AutoTransport {
14
14
  decision = new AutoDecision();
15
15
  timeoutMs;
16
16
  onWarning;
17
- closed = false;
18
17
  constructor(options) {
19
18
  if (options === null || typeof options !== 'object') {
20
19
  throw new TypeError('AutoTransport options must be an object.');
@@ -63,44 +62,37 @@ export class AutoTransport {
63
62
  return this.dispatchWithBudget(input, budget);
64
63
  }
65
64
  async dispatchWithBudget(input, budget) {
66
- const ticket = this.decision.begin();
67
- if (ticket.kind === 'selected') {
68
- return ticket.selection === 'websocket'
69
- ? this.tryWebsocket(input, budget, false)
70
- : this.http.dispatch(input, budget.options());
71
- }
72
- if (ticket.kind === 'wait') {
73
- const selection = await budget.wait(ticket.selection);
65
+ let ticket = this.decision.begin();
66
+ while (ticket.kind === 'probing') {
67
+ const settled = await budget.wait(ticket.settled);
74
68
  this.requireOpen();
75
- if (!selection)
76
- return this.dispatchWithBudget(input, budget);
77
- return selection === 'websocket'
78
- ? this.tryWebsocket(input, budget, false)
79
- : this.http.dispatch(input, budget.options());
69
+ ticket = settled.kind === 'undecided' ? this.decision.begin() : settled;
70
+ }
71
+ switch (ticket.kind) {
72
+ case 'closed':
73
+ throw closedFailure();
74
+ case 'probe':
75
+ return this.tryWebsocket(input, budget);
76
+ case 'chosen':
77
+ return ticket.via === 'websocket'
78
+ ? this.tryWebsocket(input, budget)
79
+ : this.http.dispatch(input, budget.options());
80
80
  }
81
- return this.determine(input, budget);
82
81
  }
83
82
  close() {
84
- if (this.closed)
83
+ if (!this.decision.close())
85
84
  return;
86
- this.closed = true;
87
- this.decision.close();
88
85
  this.websocket.close();
89
86
  }
90
- async determine(input, budget) {
91
- return this.tryWebsocket(input, budget, true);
92
- }
93
- async tryWebsocket(input, budget, probing) {
87
+ async tryWebsocket(input, budget) {
94
88
  try {
95
89
  const result = await this.websocket.dispatch(input, budget.options());
96
- if (probing)
97
- this.decision.select('websocket');
90
+ this.decision.selectWebSocket();
98
91
  return result;
99
92
  }
100
93
  catch (error) {
101
94
  if (budget.cancelled) {
102
- if (probing)
103
- this.decision.release();
95
+ this.decision.release();
104
96
  throw error;
105
97
  }
106
98
  if (error instanceof TransportError &&
@@ -110,9 +102,7 @@ export class AutoTransport {
110
102
  throw error;
111
103
  }
112
104
  if (!mayFallback(error)) {
113
- if (probing) {
114
- this.decision.select('websocket');
115
- }
105
+ this.decision.selectWebSocket();
116
106
  throw error;
117
107
  }
118
108
  const idempotency = budget.idempotency;
@@ -131,8 +121,10 @@ export class AutoTransport {
131
121
  }
132
122
  }
133
123
  requireOpen() {
134
- if (!this.closed)
135
- return;
136
- throw invocationFailure('AutoTransport is closed.', 'closed');
124
+ if (this.decision.closed)
125
+ throw closedFailure();
137
126
  }
138
127
  }
128
+ function closedFailure() {
129
+ return invocationFailure('AutoTransport is closed.', 'closed');
130
+ }
@@ -4,6 +4,8 @@ export interface ControlledSignal {
4
4
  cancel(reason?: unknown): void;
5
5
  close(): void;
6
6
  }
7
+ /** Wait `ms`, or until `signal` aborts, which rejects with its reason. */
8
+ export declare function pause(ms: number, signal?: AbortSignal): Promise<void>;
7
9
  /** One caller signal plus one transport-owned lifetime deadline. */
8
10
  export declare function controlledSignal(parent: AbortSignal | undefined, timeoutMs: number): ControlledSignal;
9
11
  export declare function positiveInteger(input: number, label: string): number;
@@ -1,3 +1,21 @@
1
+ /** Wait `ms`, or until `signal` aborts, which rejects with its reason. */
2
+ export function pause(ms, signal) {
3
+ return new Promise((resolve, reject) => {
4
+ if (signal?.aborted) {
5
+ reject(signal.reason);
6
+ return;
7
+ }
8
+ const abort = () => {
9
+ clearTimeout(timer);
10
+ reject(signal.reason);
11
+ };
12
+ const timer = setTimeout(() => {
13
+ signal?.removeEventListener('abort', abort);
14
+ resolve();
15
+ }, ms);
16
+ signal?.addEventListener('abort', abort, { once: true });
17
+ });
18
+ }
1
19
  /** One caller signal plus one transport-owned lifetime deadline. */
2
20
  export function controlledSignal(parent, timeoutMs) {
3
21
  const controller = new AbortController();
@@ -1,7 +1,34 @@
1
- import { TransportError, type InvocationTransportErrorOptions } from '../errors/index.js';
1
+ import type * as protocol from '@astrale-os/kernel-protocol/invocation';
2
+ import type { ControlledSignal } from './deadline.js';
3
+ import { ProtocolError, TransportError, type InvocationTransportErrorOptions } from '../errors/index.js';
2
4
  type InvocationFailureEvidence = Omit<InvocationTransportErrorOptions, 'delivery' | 'phase'> & {
3
5
  readonly delivery?: InvocationTransportErrorOptions['delivery'];
4
6
  };
7
+ /** Where a request stood when it stopped, and what its binding calls a failure there. */
8
+ export interface RequestStop {
9
+ readonly phase: 'connect' | 'send' | 'receive';
10
+ readonly delivery: InvocationTransportErrorOptions['delivery'];
11
+ /** The message of the failure the request's deadline is. */
12
+ readonly timeout: string;
13
+ /** The message of a failure to communicate. */
14
+ readonly failure: string;
15
+ }
5
16
  /** Create invocation transport evidence with the common not-sent default. */
6
17
  export declare function invocationFailure(message: string, phase: InvocationTransportErrorOptions['phase'], evidence?: InvocationFailureEvidence): TransportError;
18
+ /** The failure of an invocation its deadline ended. */
19
+ export declare function timeoutFailure(message: string, evidence?: InvocationFailureEvidence): TransportError;
20
+ /** The error a cancelled request fails with: its abort reason, or `otherwise` when it gave none. */
21
+ export declare function abortError(reason: unknown, otherwise: unknown): Error;
22
+ /**
23
+ * The error a request ends with when its control aborts: `timeout` when its deadline fired,
24
+ * otherwise its caller's abort reason, or `cancelled` when the abort gave none.
25
+ */
26
+ export declare function abortFailure(control: ControlledSignal, timeout: string, cancelled: string, evidence?: Omit<InvocationFailureEvidence, 'cause'>): Error;
27
+ /**
28
+ * The public error of a request that threw `input`: a Kernel answer or protocol breach as it is,
29
+ * then its deadline, then its caller's cancellation, then a transport failure where it stood.
30
+ */
31
+ export declare function requestFailure(input: unknown, control: ControlledSignal, stop: RequestStop): unknown;
32
+ /** `input` naming `invocation`, when it is a protocol or invocation failure that names none. */
33
+ export declare function withInvocation<T>(input: T, invocation: protocol.InvocationId | undefined): T | ProtocolError | TransportError;
7
34
  export {};