@astrale-os/kernel-client 1.0.0-beta.5 → 1.0.0-beta.50

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 (206) hide show
  1. package/dist/auth/authorization.d.ts +10 -5
  2. package/dist/auth/authorization.js +14 -1
  3. package/dist/auth/index.d.ts +1 -0
  4. package/dist/client/admission.js +3 -1
  5. package/dist/client/client.d.ts +70 -4
  6. package/dist/client/client.js +209 -32
  7. package/dist/client/index.d.ts +3 -3
  8. package/dist/client/index.js +2 -2
  9. package/dist/client/level.d.ts +58 -0
  10. package/dist/client/level.js +159 -0
  11. package/dist/client/request.d.ts +7 -2
  12. package/dist/client/request.js +11 -7
  13. package/dist/client/result.d.ts +14 -1
  14. package/dist/client/result.js +19 -8
  15. package/dist/client/routing-control.d.ts +11 -15
  16. package/dist/client/routing-control.js +21 -29
  17. package/dist/errors/index.d.ts +3 -0
  18. package/dist/errors/index.js +3 -0
  19. package/dist/errors/inexpressible-error.d.ts +23 -0
  20. package/dist/errors/inexpressible-error.js +26 -0
  21. package/dist/errors/query-input.d.ts +47 -0
  22. package/dist/errors/query-input.js +85 -0
  23. package/dist/errors/refusal.d.ts +12 -0
  24. package/dist/errors/refusal.js +44 -6
  25. package/dist/errors/response-too-large-error.d.ts +11 -0
  26. package/dist/errors/response-too-large-error.js +15 -0
  27. package/dist/errors/stale-route-error.d.ts +1 -1
  28. package/dist/errors/stale-route-error.js +1 -1
  29. package/dist/{schema → execution}/admission.d.ts +2 -2
  30. package/dist/{schema → execution}/admission.js +2 -2
  31. package/dist/{session/execution.d.ts → execution/contracts.d.ts} +22 -34
  32. package/dist/execution/contracts.js +1 -0
  33. package/dist/execution/deadline.d.ts +18 -0
  34. package/dist/execution/deadline.js +25 -0
  35. package/dist/execution/execution.d.ts +61 -0
  36. package/dist/execution/execution.js +132 -0
  37. package/dist/execution/index.d.ts +4 -0
  38. package/dist/execution/index.js +3 -0
  39. package/dist/graph/domain/binding.d.ts +2 -2
  40. package/dist/graph/domain/binding.js +20 -17
  41. package/dist/graph/domain/conformance.d.ts +12 -0
  42. package/dist/graph/domain/conformance.js +18 -0
  43. package/dist/graph/domain/index.d.ts +1 -0
  44. package/dist/graph/domain/index.js +1 -1
  45. package/dist/graph/domain/provenance.d.ts +0 -2
  46. package/dist/graph/domain/provenance.js +0 -4
  47. package/dist/graph/graph.d.ts +17 -3
  48. package/dist/graph/graph.js +4 -1
  49. package/dist/graph/index.d.ts +3 -3
  50. package/dist/graph/index.js +1 -1
  51. package/dist/graph/page-contract.d.ts +66 -1
  52. package/dist/graph/provenance.d.ts +4 -5
  53. package/dist/graph/provenance.js +5 -6
  54. package/dist/graph/query.d.ts +10 -4
  55. package/dist/graph/query.js +144 -5
  56. package/dist/graph/query.typecheck.d.ts +81 -0
  57. package/dist/graph/query.typecheck.js +34 -0
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.js +1 -1
  60. package/dist/schema/contracts.d.ts +54 -79
  61. package/dist/schema/index.d.ts +2 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +36 -64
  64. package/dist/schema/installation.js +67 -131
  65. package/dist/schema/schema.d.ts +10 -16
  66. package/dist/schema/schema.js +57 -34
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +36 -32
  70. package/dist/session/content/api.d.ts +20 -2
  71. package/dist/session/content/api.js +17 -7
  72. package/dist/session/content/files.d.ts +12 -0
  73. package/dist/session/content/files.js +47 -0
  74. package/dist/session/content/index.d.ts +1 -1
  75. package/dist/session/content/input.d.ts +13 -2
  76. package/dist/session/content/input.js +25 -4
  77. package/dist/session/content/retry.d.ts +5 -1
  78. package/dist/session/content/retry.js +21 -31
  79. package/dist/session/context/index.d.ts +2 -2
  80. package/dist/session/context/index.js +2 -2
  81. package/dist/session/context/operation.d.ts +2 -0
  82. package/dist/session/context/operation.js +5 -0
  83. package/dist/session/context/policy.d.ts +2 -0
  84. package/dist/session/context/policy.js +6 -3
  85. package/dist/session/credential/credentials.d.ts +2 -1
  86. package/dist/session/credential/credentials.js +62 -29
  87. package/dist/session/discovery/bundle.d.ts +13 -4
  88. package/dist/session/discovery/bundle.js +85 -36
  89. package/dist/session/discovery/discovery.d.ts +1 -1
  90. package/dist/session/discovery/discovery.js +8 -11
  91. package/dist/session/discovery/index.d.ts +1 -0
  92. package/dist/session/discovery/index.js +5 -1
  93. package/dist/session/discovery/release.d.ts +2 -0
  94. package/dist/session/discovery/release.js +34 -31
  95. package/dist/session/discovery/response.d.ts +4 -0
  96. package/dist/session/discovery/response.js +10 -6
  97. package/dist/session/discovery/snapshot.d.ts +5 -1
  98. package/dist/session/discovery/transport.d.ts +37 -3
  99. package/dist/session/discovery/transport.js +62 -1
  100. package/dist/session/durable.d.ts +13 -0
  101. package/dist/session/durable.js +39 -0
  102. package/dist/session/exchange/exchange.d.ts +3 -2
  103. package/dist/session/exchange/exchange.js +10 -7
  104. package/dist/session/exchange/index.d.ts +1 -1
  105. package/dist/session/exchange/index.js +1 -1
  106. package/dist/session/exchange/presentation.js +28 -10
  107. package/dist/session/exchange/source.d.ts +7 -7
  108. package/dist/session/exchange/source.js +26 -27
  109. package/dist/session/index.d.ts +5 -4
  110. package/dist/session/index.js +0 -1
  111. package/dist/session/options.d.ts +4 -2
  112. package/dist/session/options.js +3 -3
  113. package/dist/session/reference.d.ts +27 -6
  114. package/dist/session/reference.js +18 -3
  115. package/dist/session/retry.d.ts +12 -0
  116. package/dist/session/retry.js +23 -0
  117. package/dist/session/routing/auth.d.ts +9 -3
  118. package/dist/session/routing/auth.js +4 -3
  119. package/dist/session/routing/cache.d.ts +12 -5
  120. package/dist/session/routing/cache.js +56 -48
  121. package/dist/session/routing/dispatch.d.ts +26 -3
  122. package/dist/session/routing/dispatch.js +112 -69
  123. package/dist/session/routing/envelope.d.ts +3 -3
  124. package/dist/session/routing/index.d.ts +1 -1
  125. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  126. package/dist/session/routing/legacy/release-route.js +6 -0
  127. package/dist/session/routing/recovery.d.ts +3 -6
  128. package/dist/session/routing/recovery.js +3 -14
  129. package/dist/session/routing/request.d.ts +2 -1
  130. package/dist/session/routing/request.js +2 -1
  131. package/dist/session/routing/result.d.ts +1 -1
  132. package/dist/session/routing/result.js +5 -1
  133. package/dist/session/routing/store.js +4 -5
  134. package/dist/session/session.d.ts +31 -5
  135. package/dist/session/session.js +70 -22
  136. package/dist/session/session.typecheck.js +20 -6
  137. package/dist/session/views/index.d.ts +2 -2
  138. package/dist/session/views/index.js +2 -2
  139. package/dist/session/views/kernel.d.ts +31 -0
  140. package/dist/session/views/kernel.js +30 -0
  141. package/dist/session/views/legacy/catalog.d.ts +21 -0
  142. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  143. package/dist/session/views/legacy/index.d.ts +14 -0
  144. package/dist/session/views/legacy/index.js +14 -0
  145. package/dist/session/views/legacy/resolve.d.ts +46 -0
  146. package/dist/session/views/legacy/resolve.js +83 -0
  147. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  148. package/dist/session/views/legacy/unplaced.js +26 -0
  149. package/dist/session/views/read.d.ts +49 -0
  150. package/dist/session/views/read.js +148 -0
  151. package/dist/session/views/view.d.ts +48 -0
  152. package/dist/session/views/view.js +74 -0
  153. package/dist/store/memory.d.ts +1 -3
  154. package/dist/store/memory.js +61 -112
  155. package/dist/store/shape.d.ts +33 -12
  156. package/dist/store/shape.js +125 -16
  157. package/dist/store/store.d.ts +6 -6
  158. package/dist/store/store.js +1 -1
  159. package/dist/transport/auto/decision.d.ts +28 -14
  160. package/dist/transport/auto/decision.js +39 -32
  161. package/dist/transport/auto/fallback.d.ts +1 -1
  162. package/dist/transport/auto/fallback.js +5 -10
  163. package/dist/transport/auto/transport.d.ts +10 -3
  164. package/dist/transport/auto/transport.js +41 -32
  165. package/dist/transport/deadline.d.ts +2 -0
  166. package/dist/transport/deadline.js +18 -0
  167. package/dist/transport/failure.d.ts +28 -1
  168. package/dist/transport/failure.js +63 -1
  169. package/dist/transport/http/admission.js +8 -35
  170. package/dist/transport/http/binary-request.d.ts +44 -0
  171. package/dist/transport/http/binary-request.js +110 -0
  172. package/dist/transport/http/binary.js +3 -3
  173. package/dist/transport/http/byte-stream.d.ts +2 -1
  174. package/dist/transport/http/byte-stream.js +12 -8
  175. package/dist/transport/http/configuration.d.ts +7 -0
  176. package/dist/transport/http/configuration.js +2 -0
  177. package/dist/transport/http/index.d.ts +1 -1
  178. package/dist/transport/http/index.js +1 -1
  179. package/dist/transport/http/response.d.ts +13 -1
  180. package/dist/transport/http/response.js +22 -9
  181. package/dist/transport/http/stream.d.ts +8 -13
  182. package/dist/transport/http/stream.js +34 -81
  183. package/dist/transport/http/transport.d.ts +14 -1
  184. package/dist/transport/http/transport.js +110 -35
  185. package/dist/transport/http/unprocessed.d.ts +5 -0
  186. package/dist/transport/http/unprocessed.js +28 -0
  187. package/dist/transport/index.d.ts +2 -1
  188. package/dist/transport/index.js +2 -1
  189. package/dist/transport/level.d.ts +42 -0
  190. package/dist/transport/level.js +58 -0
  191. package/dist/transport/stream.d.ts +52 -0
  192. package/dist/transport/stream.js +101 -0
  193. package/dist/transport/transport.d.ts +33 -0
  194. package/dist/transport/unary.d.ts +9 -0
  195. package/dist/transport/unary.js +36 -0
  196. package/dist/transport/websocket/connection.d.ts +13 -4
  197. package/dist/transport/websocket/connection.js +123 -96
  198. package/dist/transport/websocket/exchange.d.ts +15 -19
  199. package/dist/transport/websocket/exchange.js +87 -183
  200. package/dist/transport/websocket/transport.d.ts +19 -1
  201. package/dist/transport/websocket/transport.js +50 -21
  202. package/package.json +9 -7
  203. package/dist/session/execution.js +0 -34
  204. package/dist/session/views/catalog.d.ts +0 -19
  205. package/dist/session/views/resolve.d.ts +0 -13
  206. package/dist/session/views/resolve.js +0 -21
@@ -1,7 +1,10 @@
1
1
  import * as errors from '@astrale-os/kernel-protocol/errors';
2
2
  import { ProtocolError, ResponseError } from '../../errors/index.js';
3
- import { invocationFailure } from '../failure.js';
3
+ import { abortFailure, invocationFailure, withInvocation } from '../failure.js';
4
4
  import { asError } from '../index.js';
5
+ import { served } from '../level.js';
6
+ import { FrameStream } from '../stream.js';
7
+ import { responseError, unaryResult } from '../unary.js';
5
8
  /** One correlated invocation within a multiplexed WebSocket connection. */
6
9
  export class WebSocketExchange {
7
10
  owner;
@@ -12,14 +15,7 @@ export class WebSocketExchange {
12
15
  resolveResult;
13
16
  rejectResult;
14
17
  abort;
15
- state = 'response';
16
- claimed = false;
17
- index = 0;
18
- values = [];
19
- waiters = [];
20
- terminal;
21
- sent = false;
22
- invocation;
18
+ phase = { kind: 'unsent' };
23
19
  constructor(owner, requestId, control, maximumBufferedItems) {
24
20
  this.owner = owner;
25
21
  this.requestId = requestId;
@@ -29,12 +25,15 @@ export class WebSocketExchange {
29
25
  this.resolveResult = resolve;
30
26
  this.rejectResult = reject;
31
27
  });
32
- this.abort = () => this.cancelLocally(this.abortFailure());
28
+ this.abort = () => this.fail(abortFailure(control, 'WebSocket invocation exceeded its timeout.', 'WebSocket invocation was cancelled.', {
29
+ delivery: this.phase.kind === 'unsent' ? 'not-sent' : 'unknown',
30
+ invocation: this.invocation,
31
+ }), { kind: 'cancel' });
33
32
  if (!control.signal.aborted)
34
33
  control.signal.addEventListener('abort', this.abort, { once: true });
35
34
  }
36
35
  start(send, encoded) {
37
- if (this.state === 'finished')
36
+ if (this.phase.kind === 'finished')
38
37
  return this.result;
39
38
  if (this.control.signal.aborted) {
40
39
  this.abort();
@@ -42,63 +41,44 @@ export class WebSocketExchange {
42
41
  }
43
42
  try {
44
43
  send(encoded);
45
- this.sent = true;
44
+ // A socket may fail the exchange while it sends.
45
+ if (this.phase.kind === 'unsent')
46
+ this.phase = { kind: 'sent' };
46
47
  }
47
48
  catch (error) {
48
49
  this.fail(invocationFailure('Failed to send the WebSocket invocation.', 'send', {
49
50
  cause: asError(error),
50
- }), 1011);
51
+ }), { kind: 'close', code: 1011 });
51
52
  }
52
53
  return this.result;
53
54
  }
54
55
  receive(input) {
55
56
  try {
56
- if (this.state === 'response') {
57
+ const phase = this.phase;
58
+ if (phase.kind === 'unsent' || phase.kind === 'sent') {
57
59
  this.receiveResponse(input);
58
60
  return;
59
61
  }
60
- if (this.state !== 'stream' || isKind(input, 'binary')) {
62
+ if (phase.kind !== 'stream' || !isStreamFrame(input)) {
61
63
  throw new ProtocolError('server sent an unexpected WebSocket response.');
62
64
  }
63
- this.receiveStreamFrame(input);
65
+ this.receiveStreamFrame(phase.stream, input);
64
66
  }
65
67
  catch (error) {
66
- const failure = protocolFailure(error, this.invocation);
67
- this.fail(failure, failure instanceof WebSocketPolicyError ? 1008 : 1002);
68
+ this.fail(protocolFailure(error, this.invocation), { kind: 'close', code: 1002 });
68
69
  }
69
70
  }
70
71
  connectionFailed(error) {
71
- this.fail(this.sent
72
- ? invocationFailure(error.message, 'receive', {
72
+ this.fail(this.phase.kind === 'unsent'
73
+ ? error
74
+ : invocationFailure(error.message, 'receive', {
73
75
  cause: error,
74
76
  delivery: 'unknown',
75
77
  ...(this.invocation === undefined ? {} : { invocation: this.invocation }),
76
- })
77
- : error);
78
+ }), { kind: 'close', code: 1002 });
78
79
  }
79
- [Symbol.asyncIterator]() {
80
- if (this.claimed)
81
- throw new TypeError('streams admit exactly one consumer.');
82
- this.claimed = true;
83
- return {
84
- next: () => this.next(),
85
- return: async () => {
86
- await this.cancel('stream consumer stopped');
87
- return { done: true, value: undefined };
88
- },
89
- throw: async (error) => {
90
- await this.cancel('stream consumer failed');
91
- throw error;
92
- },
93
- };
94
- }
95
- async cancel(_reason = 'stream cancelled') {
96
- if (this.state === 'finished')
97
- return;
98
- this.values.length = 0;
99
- this.terminal = true;
100
- this.finishCancelled();
101
- this.flushTerminal();
80
+ get invocation() {
81
+ return this.phase.kind === 'stream' ? this.phase.stream.invocation : undefined;
102
82
  }
103
83
  receiveResponse(input) {
104
84
  if (isKind(input, 'binary')) {
@@ -115,184 +95,108 @@ export class WebSocketExchange {
115
95
  });
116
96
  return;
117
97
  }
118
- if (isKind(input, 'stream.start')) {
119
- const start = input;
120
- requireId(this.requestId, start.requestId);
121
- if (start.kind !== 'stream.start')
98
+ if (isStreamFrame(input)) {
99
+ requireId(this.requestId, input.requestId);
100
+ if (input.kind !== 'stream.start') {
122
101
  throw new ProtocolError('stream did not begin with stream.start.');
123
- this.state = 'stream';
124
- this.invocation = start.invocation;
125
- this.resolveResult({ kind: 'stream', stream: this, invocation: start.invocation });
126
- return;
127
- }
128
- if (isKind(input, 'redirect')) {
129
- const response = input;
130
- requireId(this.requestId, response.requestId);
131
- this.complete({
132
- kind: 'redirect',
133
- invocation: response.invocation,
134
- redirect: response.redirect,
135
- });
136
- return;
137
- }
138
- if (isKind(input, 'stale')) {
139
- const stale = input;
140
- requireId(this.requestId, stale.requestId);
141
- this.complete(Object.freeze({ kind: 'stale', current: stale.current, invocation: stale.invocation }));
142
- return;
143
- }
144
- if (isKind(input, 'miss')) {
145
- const miss = input;
146
- requireId(this.requestId, miss.requestId);
147
- this.complete(Object.freeze({ kind: 'miss', invocation: miss.invocation }));
102
+ }
103
+ const stream = new FrameStream(input.invocation, { cancel: async () => this.cancel() }, this.maximumBufferedItems);
104
+ this.phase = { kind: 'stream', stream };
105
+ this.resolveResult(served({ kind: 'stream', stream, invocation: input.invocation }, this.owner.level));
148
106
  return;
149
107
  }
150
108
  const response = input;
151
109
  requireId(this.requestId, response.requestId);
152
110
  if ('error' in response) {
153
- this.reject(new ResponseError(response.error.code, response.error.message, response.invocation, response.error.data));
154
- return;
111
+ this.reject(responseError(response.error, response.invocation, this.owner.level));
155
112
  }
156
- this.complete({ kind: 'value', value: response.result, invocation: response.invocation });
113
+ else
114
+ this.complete(unaryResult(response));
157
115
  }
158
- receiveStreamFrame(frame) {
116
+ receiveStreamFrame(stream, frame) {
159
117
  requireId(this.requestId, frame.requestId);
160
118
  if (frame.kind === 'stream.start') {
161
119
  throw new ProtocolError('server sent a duplicate stream.start frame.');
162
120
  }
163
- if (frame.kind === 'stream.item') {
164
- if (frame.index !== this.index) {
165
- throw new ProtocolError(`stream item ${frame.index} does not match expected index ${this.index}.`);
166
- }
167
- this.index += 1;
168
- const waiter = this.waiters.shift();
169
- if (waiter !== undefined)
170
- waiter.resolve({ done: false, value: frame.value });
171
- else {
172
- if (this.values.length >= this.maximumBufferedItems) {
173
- throw new WebSocketPolicyError(`stream exceeds maximumBufferedStreamItems (${this.maximumBufferedItems}).`);
174
- }
175
- this.values.push(frame.value);
121
+ const step = stream.accept(frame);
122
+ if (step.kind === 'item') {
123
+ if (!stream.push(step.value)) {
124
+ const overflow = new ProtocolError(`stream exceeds maximumBufferedStreamItems (${this.maximumBufferedItems}).`);
125
+ this.fail(protocolFailure(overflow, this.invocation), { kind: 'close', code: 1008 });
176
126
  }
177
127
  return;
178
128
  }
179
- if (frame.kind === 'stream.end' && frame.count !== this.index) {
180
- throw new ProtocolError(`stream ended with count ${frame.count}; ${this.index} items were received.`);
181
- }
182
- this.terminal =
183
- frame.kind === 'stream.error'
184
- ? new ResponseError(frame.error.code, frame.error.message, this.invocation, frame.error.data)
185
- : true;
186
- this.finish(true);
187
- this.flushTerminal();
129
+ this.finish({ kind: 'reuse' });
130
+ if (step.kind === 'error')
131
+ stream.fail(step.error);
132
+ else
133
+ stream.end();
188
134
  }
189
- next() {
190
- const value = this.values.shift();
191
- if (value !== undefined)
192
- return Promise.resolve({ done: false, value });
193
- if (this.terminal === true)
194
- return Promise.resolve({ done: true, value: undefined });
195
- if (this.terminal instanceof Error)
196
- return Promise.reject(this.terminal);
197
- return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
135
+ /** The consumer's cancellation: drops what it has not read and tells the server. */
136
+ cancel() {
137
+ const phase = this.phase;
138
+ if (phase.kind !== 'stream')
139
+ return;
140
+ phase.stream.discard();
141
+ this.finish({ kind: 'cancel' });
142
+ phase.stream.end();
198
143
  }
199
144
  complete(result) {
200
- this.finish(true);
201
- this.resolveResult(result);
145
+ this.finish({ kind: 'reuse' });
146
+ this.resolveResult(served(result, this.owner.level));
202
147
  }
203
148
  reject(error) {
204
- this.finish(true);
149
+ this.finish({ kind: 'reuse' });
205
150
  this.rejectResult(error);
206
151
  }
207
- fail(error, closeCode = 1002) {
208
- if (this.state === 'finished')
152
+ /** Fails the pending result or the stream; a cancelled exchange drops what was not read. */
153
+ fail(error, release) {
154
+ const phase = this.phase;
155
+ if (phase.kind === 'finished')
209
156
  return;
210
- if (this.state === 'response')
157
+ if (phase.kind !== 'stream')
211
158
  this.rejectResult(error);
212
159
  else {
213
- this.terminal = error;
214
- this.flushTerminal();
160
+ if (release.kind === 'cancel')
161
+ phase.stream.discard();
162
+ phase.stream.fail(error);
215
163
  }
216
- this.finish(false, closeCode);
164
+ this.finish(release);
217
165
  }
218
- cancelLocally(error) {
219
- if (this.state === 'finished')
166
+ finish(release) {
167
+ if (this.phase.kind === 'finished')
220
168
  return;
221
- if (this.state === 'response')
222
- this.rejectResult(error);
223
- else {
224
- this.values.length = 0;
225
- this.terminal = error;
226
- this.flushTerminal();
227
- }
228
- this.finishCancelled();
229
- }
230
- finish(reusable, closeCode) {
231
- if (this.state === 'finished')
232
- return;
233
- this.state = 'finished';
169
+ this.phase = { kind: 'finished' };
234
170
  this.control.signal.removeEventListener('abort', this.abort);
235
171
  this.control.close();
236
- this.owner.finish(this, reusable, closeCode);
237
- }
238
- finishCancelled() {
239
- if (this.state === 'finished')
240
- return;
241
- this.state = 'finished';
242
- this.control.signal.removeEventListener('abort', this.abort);
243
- this.control.close();
244
- this.owner.cancel(this, this.requestId);
245
- }
246
- flushTerminal() {
247
- if (this.terminal === undefined)
248
- return;
249
- for (const waiter of this.waiters.splice(0)) {
250
- if (this.terminal === true)
251
- waiter.resolve({ done: true, value: undefined });
252
- else
253
- waiter.reject(this.terminal);
254
- }
255
- }
256
- abortFailure() {
257
- if (this.control.timedOut) {
258
- return invocationFailure('WebSocket invocation exceeded its timeout.', 'timeout', {
259
- cause: asError(this.control.signal.reason),
260
- delivery: this.sent ? 'unknown' : 'not-sent',
261
- ...(this.invocation === undefined ? {} : { invocation: this.invocation }),
262
- });
263
- }
264
- return asError(this.control.signal.reason ?? new Error('WebSocket invocation was cancelled.'));
172
+ if (release.kind === 'cancel')
173
+ this.owner.cancel(this, this.requestId);
174
+ else if (release.kind === 'close')
175
+ this.owner.finish(this, release.code);
176
+ else
177
+ this.owner.finish(this);
265
178
  }
266
179
  }
267
- class WebSocketPolicyError extends ProtocolError {
268
- }
180
+ /** The error of a frame the exchange cannot accept, naming the invocation it belongs to. */
269
181
  function protocolFailure(input, invocation) {
270
- if (input instanceof ResponseError)
271
- return input;
272
- if (input instanceof WebSocketPolicyError) {
273
- return input.invocation !== undefined || invocation === undefined
274
- ? input
275
- : new WebSocketPolicyError(input.message, { cause: input, invocation });
276
- }
277
- if (input instanceof ProtocolError) {
278
- return input.invocation !== undefined || invocation === undefined
279
- ? input
280
- : new ProtocolError(input.message, { cause: input, invocation });
182
+ if (input instanceof ResponseError || input instanceof ProtocolError) {
183
+ return withInvocation(input, invocation);
281
184
  }
282
- if (input instanceof errors.ProtocolError) {
283
- return new ProtocolError(input.message, { cause: input, invocation });
284
- }
285
- return new ProtocolError('server returned an invalid WebSocket frame.', {
286
- cause: asError(input),
287
- invocation,
288
- });
185
+ return new ProtocolError(input instanceof errors.ProtocolError
186
+ ? input.message
187
+ : 'server returned an invalid WebSocket frame.', { cause: asError(input), invocation });
289
188
  }
290
189
  function requireId(expected, received) {
291
190
  if (received !== expected) {
292
191
  throw new ProtocolError(`response requestId ${JSON.stringify(received)} does not match request requestId ${JSON.stringify(expected)}.`);
293
192
  }
294
193
  }
295
- function isKind(input, kind) {
194
+ /** Only stream frames may follow `stream.start`; a unary response would end the stream unchecked. */
195
+ function isStreamFrame(input) {
196
+ return 'kind' in input && typeof input.kind === 'string' && input.kind.startsWith('stream.');
197
+ }
198
+ /** Whether `input` is a plain object whose `kind` is `kind`. */
199
+ export function isKind(input, kind) {
296
200
  return (typeof input === 'object' &&
297
201
  input !== null &&
298
202
  !Array.isArray(input) &&
@@ -1,3 +1,5 @@
1
+ import type { Level } from '@astrale-os/kernel-core/wire';
2
+ import * as protocol from '@astrale-os/kernel-protocol/invocation';
1
3
  import type { RequestOptions, Transport, TransportRequest, TransportResult } from '../index.js';
2
4
  /** Web-compatible WebSocket constructor used by the built-in WebSocket transport. */
3
5
  export type WebSocketConstructor = new (url: string | URL, protocols?: string | string[]) => WebSocket;
@@ -16,18 +18,24 @@ export interface WebSocketTransportOptions {
16
18
  readonly maximumActiveInvocations?: number;
17
19
  /** Maximum decoded items retained while a stream consumer is slower than the socket. */
18
20
  readonly maximumBufferedStreamItems?: number;
21
+ /**
22
+ * The wire History whose levels the transport offers, its current level first; absent, the
23
+ * Invocation History of this build.
24
+ */
25
+ readonly levels?: protocol.Levels;
19
26
  }
20
27
  /** WebSocket implementation of the universal invocation protocol. */
21
28
  export declare class WebSocketTransport implements Transport {
22
29
  readonly url: string;
23
30
  private readonly connectionUrl;
24
31
  private readonly WebSocketConstructor;
25
- private readonly timeoutMs;
32
+ readonly timeoutMs: number;
26
33
  private readonly maximumRequestBytes;
27
34
  private readonly maximumResponseBytes;
28
35
  private readonly maximumBufferedBytes;
29
36
  private readonly maximumActiveInvocations;
30
37
  private readonly maximumBufferedStreamItems;
38
+ private readonly levels;
31
39
  private readonly connections;
32
40
  private readonly connectionOwner;
33
41
  private connection;
@@ -35,8 +43,18 @@ export declare class WebSocketTransport implements Transport {
35
43
  private nextId;
36
44
  constructor(options: WebSocketTransportOptions);
37
45
  dispatch(input: TransportRequest, options?: RequestOptions): Promise<TransportResult>;
46
+ /**
47
+ * The wire level of the connection, which its subprotocol fixed for every message: it connects
48
+ * when no connection is open, within the deadline of `options`.
49
+ */
50
+ fixed(options?: RequestOptions): Promise<Level>;
38
51
  /** Close the multiplexed connection, reject active exchanges, and reject future dispatches. */
39
52
  close(): void;
53
+ /**
54
+ * What a call fails with when connecting, or writing to the connection, threw `error`: a failure
55
+ * to connect, which sent nothing, unless the connection and its exchange already judged it.
56
+ */
57
+ private failure;
40
58
  private connectionClosed;
41
59
  private acquire;
42
60
  private nextRequestId;
@@ -1,8 +1,9 @@
1
1
  import * as codecs from '@astrale-os/kernel-protocol/codecs';
2
2
  import * as protocol from '@astrale-os/kernel-protocol/invocation';
3
- import { ProtocolError, ResponseError, TransportError } from '../../errors/index.js';
4
- import { invocationFailure } from '../failure.js';
3
+ import { TransportError } from '../../errors/index.js';
4
+ import { invocationFailure, requestFailure } from '../failure.js';
5
5
  import { asError, controlledSignal, positiveInteger, requireLive } from '../index.js';
6
+ import { captureLevels, ConnectionMoved, writtenLevel } from '../level.js';
6
7
  import { WebSocketConnection } from './connection.js';
7
8
  const DEFAULT_TIMEOUT_MS = 30_000;
8
9
  const DEFAULT_MAXIMUM_REQUEST_BYTES = 16 * 1024 * 1024;
@@ -21,6 +22,7 @@ export class WebSocketTransport {
21
22
  maximumBufferedBytes;
22
23
  maximumActiveInvocations;
23
24
  maximumBufferedStreamItems;
25
+ levels;
24
26
  connections = new Set();
25
27
  connectionOwner = Object.freeze({
26
28
  closed: (connection) => this.connectionClosed(connection),
@@ -41,6 +43,7 @@ export class WebSocketTransport {
41
43
  this.maximumBufferedBytes = positiveInteger(options.maximumBufferedBytes ?? DEFAULT_MAXIMUM_BUFFERED_BYTES, 'maximumBufferedBytes');
42
44
  this.maximumActiveInvocations = positiveInteger(options.maximumActiveInvocations ?? DEFAULT_MAXIMUM_ACTIVE_INVOCATIONS, 'maximumActiveInvocations');
43
45
  this.maximumBufferedStreamItems = positiveInteger(options.maximumBufferedStreamItems ?? DEFAULT_MAXIMUM_BUFFERED_STREAM_ITEMS, 'maximumBufferedStreamItems');
46
+ this.levels = captureLevels(options.levels);
44
47
  }
45
48
  async dispatch(input, options = {}) {
46
49
  if (this.stopped) {
@@ -48,10 +51,12 @@ export class WebSocketTransport {
48
51
  }
49
52
  const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
50
53
  const codec = codecs.json;
54
+ const { level, ...invocationInput } = input;
55
+ const written = writtenLevel(level, this.levels);
51
56
  const request = protocol.decodeRequest({
52
57
  version: protocol.VERSION,
53
58
  requestId: this.nextRequestId(),
54
- ...input,
59
+ ...invocationInput,
55
60
  ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
56
61
  });
57
62
  const control = controlledSignal(options.signal, timeoutMs);
@@ -60,17 +65,42 @@ export class WebSocketTransport {
60
65
  requireLive(control);
61
66
  const connection = await this.acquire(control, codec);
62
67
  requireLive(control);
68
+ // The subprotocol fixed the level of every message. The request was written for the level
69
+ // this Transport told: a connection made again at another level does not carry it.
70
+ if (connection.level !== written)
71
+ throw new ConnectionMoved(connection.level);
63
72
  owned = true;
64
73
  return await connection.dispatch(request, control, this.maximumBufferedStreamItems);
65
74
  }
66
75
  catch (error) {
67
- throw transportFailure(error, control, options.signal, timeoutMs, this.url);
76
+ throw this.failure(error, control, timeoutMs);
68
77
  }
69
78
  finally {
70
79
  if (!owned)
71
80
  control.close();
72
81
  }
73
82
  }
83
+ /**
84
+ * The wire level of the connection, which its subprotocol fixed for every message: it connects
85
+ * when no connection is open, within the deadline of `options`.
86
+ */
87
+ async fixed(options = {}) {
88
+ if (this.stopped) {
89
+ throw invocationFailure('WebSocketTransport is closed.', 'closed');
90
+ }
91
+ const timeoutMs = positiveInteger(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
92
+ const control = controlledSignal(options.signal, timeoutMs);
93
+ try {
94
+ requireLive(control);
95
+ return (await this.acquire(control, codecs.json)).level;
96
+ }
97
+ catch (error) {
98
+ throw this.failure(error, control, timeoutMs);
99
+ }
100
+ finally {
101
+ control.close();
102
+ }
103
+ }
74
104
  /** Close the multiplexed connection, reject active exchanges, and reject future dispatches. */
75
105
  close() {
76
106
  if (this.stopped)
@@ -81,6 +111,21 @@ export class WebSocketTransport {
81
111
  for (const connection of this.connections)
82
112
  connection.shutdown(failure);
83
113
  }
114
+ /**
115
+ * What a call fails with when connecting, or writing to the connection, threw `error`: a failure
116
+ * to connect, which sent nothing, unless the connection and its exchange already judged it.
117
+ */
118
+ failure(error, control, timeoutMs) {
119
+ // The connection and its exchange already judged their own failures, deadline included.
120
+ if (error instanceof TransportError || error instanceof ConnectionMoved)
121
+ return error;
122
+ return requestFailure(error, control, {
123
+ phase: 'connect',
124
+ delivery: 'not-sent',
125
+ timeout: `WebSocket invocation timed out after ${timeoutMs}ms.`,
126
+ failure: `Failed to communicate with the server at ${this.url}.`,
127
+ });
128
+ }
84
129
  connectionClosed(connection) {
85
130
  this.connections.delete(connection);
86
131
  if (this.connection === connection)
@@ -89,7 +134,7 @@ export class WebSocketTransport {
89
134
  async acquire(control, codec) {
90
135
  let connection = this.connection;
91
136
  if (connection === undefined || !connection.isAvailable) {
92
- connection = new WebSocketConnection(this.connectionOwner, this.WebSocketConstructor, this.connectionUrl, codec, this.maximumRequestBytes, this.maximumResponseBytes, this.maximumBufferedBytes, this.maximumActiveInvocations);
137
+ connection = new WebSocketConnection(this.connectionOwner, this.WebSocketConstructor, this.connectionUrl, codec, this.maximumRequestBytes, this.maximumResponseBytes, this.maximumBufferedBytes, this.maximumActiveInvocations, this.levels);
93
138
  this.connection = connection;
94
139
  this.connections.add(connection);
95
140
  }
@@ -131,19 +176,3 @@ function admitWebSocket(input) {
131
176
  }
132
177
  return implementation;
133
178
  }
134
- function transportFailure(input, control, parent, timeoutMs, url) {
135
- if (input instanceof ResponseError || input instanceof ProtocolError)
136
- return input;
137
- if (input instanceof TransportError)
138
- return input;
139
- if (control.timedOut) {
140
- return invocationFailure(`WebSocket invocation timed out after ${timeoutMs}ms.`, 'timeout', {
141
- cause: asError(input),
142
- });
143
- }
144
- if (parent?.aborted)
145
- return asError(parent.reason ?? input);
146
- return invocationFailure(`Failed to communicate with the server at ${url}.`, 'connect', {
147
- cause: asError(input),
148
- });
149
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-client",
3
- "version": "1.0.0-beta.5",
3
+ "version": "1.0.0-beta.50",
4
4
  "description": "Universal Client — protocol-first, transport-agnostic",
5
5
  "keywords": [
6
6
  "astrale",
@@ -65,17 +65,19 @@
65
65
  "access": "public"
66
66
  },
67
67
  "dependencies": {
68
- "@astrale-os/kernel-core": "1.0.0-beta.5",
69
- "@astrale-os/kernel-dsl": "1.0.0-beta.3",
70
- "@astrale-os/kernel-protocol": "1.0.0-beta.5",
68
+ "@astrale-os/kernel-core": "1.0.0-beta.47",
69
+ "@astrale-os/kernel-dsl": "1.0.0-beta.34",
70
+ "@astrale-os/kernel-protocol": "1.0.0-beta.47",
71
71
  "@tanstack/pacer": "0.20.1"
72
72
  },
73
73
  "devDependencies": {
74
- "@astrale-os/kernel-server": "1.0.0-beta.5",
74
+ "@astrale-os/kernel-server": "1.0.0-beta.47",
75
75
  "@astrale/typescript-config": "npm:@jsr/astrale__typescript-config@~1.1.0",
76
- "@types/node": "^22.0.0",
76
+ "@types/node": "^24.10.0",
77
+ "esbuild": "0.28.1",
77
78
  "typescript": "7.0.2",
78
- "vitest": "^5.0.1"
79
+ "undici": "8.12.2",
80
+ "vitest": "^5.0.5"
79
81
  },
80
82
  "scripts": {
81
83
  "build": "tsc",
@@ -1,34 +0,0 @@
1
- import { Path } from '@astrale-os/kernel-core/path';
2
- import { execution as methods } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
3
- import { kernelReference } from './reference.js';
4
- const bound = {
5
- status: kernelReference(methods.status),
6
- result: kernelReference(methods.result),
7
- cancel: kernelReference(methods.cancel),
8
- signal: kernelReference(methods.signal),
9
- resume: kernelReference(methods.resume),
10
- delete: kernelReference(methods.delete),
11
- };
12
- function receiver(execution) {
13
- return Path.id(typeof execution === 'string' ? execution : execution.id);
14
- }
15
- /**
16
- * Typed references to the methods of one Execution, for `session.invoke`:
17
- *
18
- * ```ts
19
- * const run = await session.invoke(remind(invoice), { days: 3 })
20
- * const outcome = await session.invoke(execution.result(run), { waitMs: 10_000 })
21
- * ```
22
- */
23
- export const execution = Object.freeze({
24
- status: (target) => bound.status(receiver(target)),
25
- /** Outcome once terminal; fails `EXECUTION_PENDING` when `waitMs` elapses first. */
26
- result: (target) => bound.result(receiver(target)),
27
- /** Cooperative cancellation; `force` kills without compensation (owner Domain only). */
28
- cancel: (target) => bound.cancel(receiver(target)),
29
- /** Resolve a named durable promise once (owner Domain only). */
30
- signal: (target) => bound.signal(receiver(target)),
31
- resume: (target) => bound.resume(receiver(target)),
32
- /** Forget the Execution and stop its run (owner Domain only). */
33
- delete: (target) => bound.delete(receiver(target)),
34
- });
@@ -1,19 +0,0 @@
1
- import type { Key, bundle } from '@astrale-os/kernel-dsl/v1';
2
- import type { DomainRelease } from '@astrale-os/kernel-protocol/release';
3
- import { type ResolvedView } from '@astrale-os/kernel-core/schema/kernel/syscalls/view-resolution';
4
- export type { ResolvedView } from '@astrale-os/kernel-core/schema/kernel/syscalls/view-resolution';
5
- import type { SessionPolicy } from '../context/index.js';
6
- /** One verified View declaration joined with its owning Release and provenance. */
7
- /** Immutable canonical-key-ordered inventory of Views resolved under one Session revision. */
8
- export interface ViewCatalog {
9
- readonly entrypoint?: ResolvedView;
10
- readonly views: readonly ResolvedView[];
11
- }
12
- /** Join each root Domain View to its exact release binding. */
13
- export declare function rootViewCatalog(release: DomainRelease, artifact: bundle.Bundle, policy: Readonly<SessionPolicy>): ViewCatalog;
14
- export declare function catalogFromKeys(root: ViewCatalog, keys: readonly Key.View[]): ViewCatalog;
15
- /**
16
- * Re-admit one Runtime-resolved Domain View catalog at the Client trust boundary. Only Views that
17
- * the requested Domain declares for itself are kept.
18
- */
19
- export declare function domainViewCatalog(input: unknown, domain: Key.Origin, policy: Readonly<SessionPolicy>): ViewCatalog;
@@ -1,13 +0,0 @@
1
- import type { PathLike } from '@astrale-os/kernel-core/path';
2
- import type { Key } from '@astrale-os/kernel-dsl/v1';
3
- import type { Call, Input } from '../../client/index.js';
4
- import type { SessionOperation } from '../context/index.js';
5
- import type { ViewCatalog } from './catalog.js';
6
- export type ViewInvoker = (call: Call, operation: SessionOperation) => Promise<Input>;
7
- export type ViewCatalogAdmission = (input: unknown, domain: Key.Origin) => ViewCatalog;
8
- /**
9
- * Resolve the per-Domain View catalog through the canonical source Kernel call, then admit its
10
- * installed Release evidence. Every View targets its owning Domain, so only an exact Domain
11
- * Path `/:<origin>` is meaningful; any other Path is refused before the call.
12
- */
13
- export declare function resolveViewsFor(invoke: ViewInvoker, admitCatalog: ViewCatalogAdmission, domain: PathLike, operation: SessionOperation): Promise<ViewCatalog>;