nervur 0.20.1 → 0.20.2

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 (131) hide show
  1. package/README.md +130 -8
  2. package/dist/browser/index.d.ts +35 -0
  3. package/dist/browser/index.js +188 -0
  4. package/dist/browser/worker.d.ts +12 -0
  5. package/dist/browser/worker.js +40 -0
  6. package/dist/browser.d.ts +1 -0
  7. package/dist/browser.js +7 -0
  8. package/dist/cli/command.d.ts +1 -1
  9. package/dist/cli/command.js +59 -16
  10. package/dist/cli/harbor.d.ts +9 -11
  11. package/dist/cli/harbor.js +81 -123
  12. package/dist/contract/index.d.ts +2 -1
  13. package/dist/contract/index.js +3 -7
  14. package/dist/edge/index.d.ts +57 -0
  15. package/dist/edge/index.js +306 -0
  16. package/dist/edge.d.ts +1 -0
  17. package/dist/edge.js +8 -0
  18. package/dist/folder/index.d.ts +4 -0
  19. package/dist/folder/index.js +57 -14
  20. package/dist/harbor/carrying.d.ts +17 -0
  21. package/dist/harbor/carrying.js +38 -0
  22. package/dist/harbor/catalogue.d.ts +2 -0
  23. package/dist/harbor/catalogue.js +28 -20
  24. package/dist/harbor/dock.d.ts +22 -3
  25. package/dist/harbor/dock.js +69 -13
  26. package/dist/harbor/harbor.d.ts +14 -4
  27. package/dist/harbor/harbor.js +144 -15
  28. package/dist/harbor/index.d.ts +6 -3
  29. package/dist/harbor/index.js +4 -1
  30. package/dist/harbor/package.d.ts +2 -0
  31. package/dist/harbor/package.js +15 -0
  32. package/dist/harbor/probe.d.ts +18 -0
  33. package/dist/harbor/probe.js +15 -0
  34. package/dist/harbor/registry.d.ts +1 -0
  35. package/dist/harbor/registry.js +11 -0
  36. package/dist/harbor/relay.d.ts +15 -0
  37. package/dist/harbor/relay.js +387 -0
  38. package/dist/harbor/root-line.js +4 -2
  39. package/dist/harbor/terrain.d.ts +12 -0
  40. package/dist/harbor/terrain.js +19 -0
  41. package/dist/http/index.d.ts +4 -0
  42. package/dist/http/index.js +156 -0
  43. package/dist/http/websocket.d.ts +29 -0
  44. package/dist/http/websocket.js +133 -0
  45. package/dist/index.d.ts +2 -1
  46. package/dist/index.js +8 -2
  47. package/dist/line/answer.d.ts +8 -0
  48. package/dist/line/answer.js +60 -0
  49. package/dist/line/frame.d.ts +34 -0
  50. package/dist/line/frame.js +81 -0
  51. package/dist/line/ground.d.ts +3 -0
  52. package/dist/line/ground.js +9 -0
  53. package/dist/line/index.d.ts +5 -0
  54. package/dist/line/index.js +9 -0
  55. package/dist/line/push.d.ts +7 -0
  56. package/dist/line/push.js +92 -0
  57. package/dist/line/web.d.ts +30 -0
  58. package/dist/line/web.js +181 -0
  59. package/dist/node/index.d.ts +32 -0
  60. package/dist/node/index.js +164 -0
  61. package/dist/node.d.ts +1 -0
  62. package/dist/node.js +7 -0
  63. package/dist/pointer/bodies.d.ts +2 -0
  64. package/dist/pointer/bodies.js +10 -0
  65. package/dist/pointer/world.d.ts +7 -1
  66. package/dist/pointer/world.js +6 -0
  67. package/dist/quo/address.d.ts +19 -0
  68. package/dist/quo/address.js +84 -0
  69. package/dist/quo/door.d.ts +1 -1
  70. package/dist/quo/door.js +4 -2
  71. package/dist/quo/index.d.ts +1 -0
  72. package/dist/quo/index.js +1 -0
  73. package/dist/quo/invitation.d.ts +1 -0
  74. package/dist/quo/invitation.js +9 -5
  75. package/dist/tcp/frame.d.ts +0 -4
  76. package/dist/tcp/frame.js +0 -10
  77. package/dist/tcp/index.d.ts +8 -2
  78. package/dist/tcp/index.js +123 -27
  79. package/dist/ward/index.d.ts +2 -2
  80. package/dist/ward/index.js +1 -1
  81. package/dist/ward/stance.d.ts +2 -0
  82. package/dist/ward/stance.js +3 -1
  83. package/dist/ward/ward-being.d.ts +2 -1
  84. package/dist/ward/ward-being.js +1 -1
  85. package/dist/ward/ward.d.ts +7 -0
  86. package/dist/ward/ward.js +6 -0
  87. package/package.json +21 -2
  88. package/src/browser/index.ts +207 -0
  89. package/src/browser/worker.ts +66 -0
  90. package/src/browser.ts +9 -0
  91. package/src/cli/command.ts +53 -17
  92. package/src/cli/harbor.ts +82 -116
  93. package/src/contract/index.ts +11 -8
  94. package/src/edge/index.ts +359 -0
  95. package/src/edge.ts +10 -0
  96. package/src/folder/index.ts +57 -12
  97. package/src/harbor/carrying.ts +56 -0
  98. package/src/harbor/catalogue.ts +32 -17
  99. package/src/harbor/dock.ts +88 -17
  100. package/src/harbor/harbor.ts +146 -17
  101. package/src/harbor/index.ts +6 -3
  102. package/src/harbor/package.ts +16 -0
  103. package/src/harbor/probe.ts +34 -0
  104. package/src/harbor/registry.ts +11 -0
  105. package/src/harbor/relay.ts +399 -0
  106. package/src/harbor/root-line.ts +4 -1
  107. package/src/harbor/terrain.ts +28 -2
  108. package/src/http/index.ts +150 -0
  109. package/src/http/websocket.ts +124 -0
  110. package/src/index.ts +35 -2
  111. package/src/line/answer.ts +59 -0
  112. package/src/line/frame.ts +88 -0
  113. package/src/line/ground.ts +19 -0
  114. package/src/line/index.ts +9 -0
  115. package/src/line/push.ts +112 -0
  116. package/src/line/web.ts +227 -0
  117. package/src/node/index.ts +170 -0
  118. package/src/node.ts +9 -0
  119. package/src/pointer/bodies.ts +11 -0
  120. package/src/pointer/world.ts +18 -2
  121. package/src/quo/address.ts +87 -0
  122. package/src/quo/door.ts +4 -2
  123. package/src/quo/index.ts +1 -0
  124. package/src/quo/invitation.ts +10 -6
  125. package/src/stand/stand.ts +60 -21
  126. package/src/tcp/index.ts +142 -31
  127. package/src/ward/index.ts +2 -2
  128. package/src/ward/stance.ts +6 -1
  129. package/src/ward/ward-being.ts +2 -2
  130. package/src/ward/ward.ts +16 -0
  131. package/src/tcp/frame.ts +0 -78
@@ -0,0 +1,399 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The relay: a harbor nobody dials is reached through a harbor that is,
3
+ // by relations alone. Both sides are kit faculties, opened by the root.
4
+ //
5
+ // On the reached harbor, `org.nervur.relay`:
6
+ //
7
+ // invite { id, wards } a relay client invited under `id`, its
8
+ // notes naming the ward pks it collects for
9
+ // release { id } that client let go, and every box waiting
10
+ // for its wards answered with nothing
11
+ // collect { replies?, wait? } asked by a client: the replies to the boxes
12
+ // it took last, handed to their callers, then
13
+ // the boxes waiting for its wards; with
14
+ // `wait`, it waits for one first
15
+ // bell { endpoint } asked by a client: the push endpoint rung
16
+ // when a box waits for it, or null for none
17
+ // key asked by a client: the key its device
18
+ // subscribes to pushes with
19
+ //
20
+ // A box for a ward a client collects for reaches this harbor on any
21
+ // carrier, and the caller's dial waits for its reply, or for nothing once
22
+ // `RELAY_WAIT` passes. No box is opened here. A box no waiting collect
23
+ // takes rings the client's bell once, through a `Push` faculty the relay
24
+ // lends, until the client collects again.
25
+ //
26
+ // On the harbor nobody dials, `org.nervur.relay-client`:
27
+ //
28
+ // hold { invitation, line?, every? } the relay's invitation taken; a
29
+ // line collects always, `every`
30
+ // rings on a schedule, in ms
31
+ // ring every waiting box collected, handed
32
+ // to this harbor's doors, and the
33
+ // replies returned: a doorbell
34
+ // bell { endpoint } the relay's `bell`, asked
35
+ // key the relay's `key`, asked
36
+ // drop the relay let go
37
+ //
38
+ // Its harbor's `reach` names the relay's address, so every invitation it
39
+ // gives sends callers there. Whatever hears a push on the device asks
40
+ // `ring`.
41
+ import { Faculty, isSilence, isWord, told, type Asker, type AskSpec, type BeingClass, type JsonObject } from '../being/index.ts';
42
+ import type { Clock } from '../contract/index.ts';
43
+ import { hex, isHex, unhex } from '../crypto/index.ts';
44
+ import { readInvitation } from '../quo/index.ts';
45
+ import { ownerAsk } from '../ward/index.ts';
46
+ import { CarrierFaculty, UNDIALED, type Dialed, type Ground } from './carrying.ts';
47
+
48
+ export const RELAY = 'org.nervur.relay';
49
+ export const RELAY_CLIENT = 'org.nervur.relay-client';
50
+ export const PUSH = 'org.nervur.push';
51
+ // How long a box waits for its reply: a caller's allowance, unless it
52
+ // asks for another.
53
+ export const RELAY_WAIT = 30_000;
54
+ // How long a collect with `wait` holds, inside the client's allowance.
55
+ export const RELAY_HOLD = 20_000;
56
+ // How long a line rests after a collect that reached nothing.
57
+ export const RELAY_REST = 1_000;
58
+ // The largest box a relay carries, so the collect answering it stays a
59
+ // box Quo carries.
60
+ export const RELAYED = 262_144;
61
+ // The longest push endpoint a relay keeps.
62
+ const ENDPOINT = 2_048;
63
+ // The most boxes one collect hands over.
64
+ const BATCH = 16;
65
+ const CLIENT = 'relay';
66
+ const PUSHER = 'push';
67
+
68
+ // The contract of a ring with no content: `key` answers the key a device
69
+ // subscribes with, and `ring { endpoint }` answers `rung`, `gone` where
70
+ // the push service has let the endpoint go, or an error.
71
+ export abstract class Push extends Faculty {
72
+ static override readonly kind: string = PUSH;
73
+ }
74
+
75
+ type Waiting = { n: number; ward: string; bytes: Uint8Array; answer: (reply: Uint8Array | null) => void; cancel: () => void; collector?: string };
76
+ type Collector = { wards: readonly string[]; wake: () => void };
77
+ type Reply = { n: number; box: string | null };
78
+
79
+ const text = (v: unknown): v is string => typeof v === 'string';
80
+ const wardsOf = (notes: JsonObject | undefined): string[] => (Array.isArray(notes?.relay) ? notes.relay.filter(text) : []);
81
+ const collects: AskSpec['for'] = (_: Asker, notes) => wardsOf(notes).length > 0;
82
+ const clientAsk = (description: string, input: JsonObject = {}): AskSpec => ({ description, input: { type: 'object', ...input }, for: collects });
83
+ const readReplies = (v: unknown): Reply[] | null =>
84
+ v === undefined
85
+ ? []
86
+ : Array.isArray(v) && v.every((r) => typeof r === 'object' && r !== null && Number.isInteger((r as Reply).n) && ((r as Reply).box === null || isHex((r as Reply).box, ((r as Reply).box ?? '').length / 2)))
87
+ ? (v as Reply[])
88
+ : null;
89
+ // An answer, or the error it stands for.
90
+ const answered = (out: unknown): JsonObject => (isSilence(out) ? { error: 'silence' } : isWord(out) ? { error: told(out) as string } : (out as JsonObject));
91
+
92
+ export const relayFaculty = (clock: Clock): BeingClass =>
93
+ class Relay extends CarrierFaculty {
94
+ static override readonly kind: string = RELAY;
95
+ static override cells: JsonObject = { clients: {}, bells: {} };
96
+ static override asks: Record<string, AskSpec> = {
97
+ invite: ownerAsk('a relay client, collecting for the ward pks named', { required: ['id', 'wards'] }),
98
+ release: ownerAsk('a relay client let go', { required: ['id'] }),
99
+ collect: clientAsk('the replies to the boxes taken last, then the boxes waiting'),
100
+ bell: clientAsk('the push endpoint rung when a box waits, or null', { required: ['endpoint'] }),
101
+ key: clientAsk('the key a device subscribes to pushes with'),
102
+ };
103
+
104
+ #n = 0;
105
+ readonly #waiting: Waiting[] = [];
106
+ readonly #taken = new Map<number, Waiting>();
107
+ readonly #collectors = new Set<Collector>();
108
+ // The clients rung since they last collected.
109
+ readonly #rung = new Set<string>();
110
+ #lending: Promise<string | null> | undefined;
111
+
112
+ accepts(): boolean {
113
+ return false;
114
+ }
115
+
116
+ dial(): Promise<Dialed> {
117
+ return Promise.resolve(UNDIALED);
118
+ }
119
+
120
+ get #clients(): Record<string, string[]> {
121
+ return this.cells.clients as Record<string, string[]>;
122
+ }
123
+
124
+ get #bells(): Record<string, string> {
125
+ return this.cells.bells as Record<string, string>;
126
+ }
127
+
128
+ override relays(pk: string): boolean {
129
+ return Object.values(this.#clients).some((wards) => wards.includes(pk));
130
+ }
131
+
132
+ override relay(pk: string, bytes: Uint8Array): Promise<Uint8Array | null> {
133
+ if (!this.relays(pk) || bytes.length > RELAYED) return Promise.resolve(null);
134
+ return new Promise((resolve) => {
135
+ const wait = clock.wait(RELAY_WAIT);
136
+ const box: Waiting = { n: ++this.#n, ward: pk, bytes, answer: resolve, cancel: wait.cancel };
137
+ void wait.done.then(() => this.#settle(box, null));
138
+ this.#waiting.push(box);
139
+ let woken = false;
140
+ for (const collector of this.#collectors) {
141
+ if (!collector.wards.includes(pk)) continue;
142
+ collector.wake();
143
+ woken = true;
144
+ }
145
+ if (woken) return;
146
+ for (const [id, wards] of Object.entries(this.#clients)) {
147
+ if (!wards.includes(pk) || !Object.hasOwn(this.#bells, id) || this.#rung.has(id)) continue;
148
+ this.#rung.add(id);
149
+ void this.#ring(id);
150
+ }
151
+ });
152
+ }
153
+
154
+ // Every box answered with nothing, and every collect woken.
155
+ override sleep(): Promise<void> {
156
+ for (const box of [...this.#waiting, ...this.#taken.values()]) this.#settle(box, null);
157
+ for (const collector of this.#collectors) collector.wake();
158
+ return Promise.resolve();
159
+ }
160
+
161
+ async invite(args: JsonObject): Promise<JsonObject> {
162
+ const { id, wards } = args;
163
+ if (!text(id) || !Array.isArray(wards) || wards.length === 0 || !wards.every((w) => isHex(w, 64))) return { error: 'id is text and wards a list of ward pks' };
164
+ if (Object.hasOwn(this.#clients, id)) return { error: 'that client is invited' };
165
+ const invitation = await this.stance.occupants.invite(id, { relay: wards });
166
+ if (invitation === null) return { error: 'not invited' };
167
+ this.#clients[id] = [...(wards as string[])];
168
+ return { invitation };
169
+ }
170
+
171
+ release(args: JsonObject): JsonObject {
172
+ if (!text(args.id) || !Object.hasOwn(this.#clients, args.id)) return { error: 'no such client' };
173
+ this.stance.occupants.remove(args.id);
174
+ delete this.#clients[args.id];
175
+ delete this.#bells[args.id];
176
+ this.#rung.delete(args.id);
177
+ for (const box of [...this.#waiting, ...this.#taken.values()]) if (!this.relays(box.ward)) this.#settle(box, null);
178
+ return { released: args.id };
179
+ }
180
+
181
+ async collect(args: JsonObject, asker: Asker): Promise<JsonObject> {
182
+ const replies = readReplies(args.replies);
183
+ if (replies === null) return { error: 'replies are a list of { n, box }' };
184
+ const id = asker.id!;
185
+ this.#rung.delete(id);
186
+ for (const { n, box } of replies) {
187
+ const taken = this.#taken.get(n);
188
+ if (taken?.collector === id) this.#settle(taken, box === null ? null : unhex(box));
189
+ }
190
+ const wards = wardsOf(this.notes(asker));
191
+ if (args.wait === true && !this.#waiting.some((b) => wards.includes(b.ward))) await this.#hold(wards);
192
+ const boxes = this.#waiting.filter((b) => wards.includes(b.ward)).slice(0, BATCH);
193
+ for (const box of boxes) {
194
+ this.#waiting.splice(this.#waiting.indexOf(box), 1);
195
+ box.collector = id;
196
+ this.#taken.set(box.n, box);
197
+ }
198
+ return { boxes: boxes.map(({ n, ward, bytes }) => ({ n, ward, box: hex(bytes) })) };
199
+ }
200
+
201
+ bell(args: JsonObject, asker: Asker): JsonObject {
202
+ const { endpoint } = args;
203
+ const id = asker.id!;
204
+ if (endpoint === null) {
205
+ delete this.#bells[id];
206
+ return { bell: null };
207
+ }
208
+ if (!text(endpoint) || endpoint.length > ENDPOINT || !/^https?:\/\//.test(endpoint)) return { error: 'endpoint is a web URL, or null' };
209
+ this.#bells[id] = endpoint;
210
+ return { bell: endpoint };
211
+ }
212
+
213
+ async key(): Promise<JsonObject> {
214
+ const push = await this.#push();
215
+ return push ? answered(await push.ask('key')) : { error: 'no push faculty is open' };
216
+ }
217
+
218
+ // The client's bell rung. An endpoint the push service calls gone is
219
+ // forgotten, and kept at the relay's next arrival.
220
+ async #ring(id: string): Promise<void> {
221
+ const push = await this.#push();
222
+ const endpoint = this.#bells[id];
223
+ if (!push || endpoint === undefined) return;
224
+ const out = answered(await push.ask('ring', { endpoint }));
225
+ if (out.gone === true && this.#bells[id] === endpoint) delete this.#bells[id];
226
+ }
227
+
228
+ async #push() {
229
+ if (!this.stance.standings.get(PUSHER)) {
230
+ this.#lending ??= this.stance.lend(Push, PUSHER).finally(() => (this.#lending = undefined));
231
+ await this.#lending;
232
+ }
233
+ return this.stance.standings.get(PUSHER);
234
+ }
235
+
236
+ #hold(wards: readonly string[]): Promise<void> {
237
+ return new Promise((resolve) => {
238
+ const wait = clock.wait(RELAY_HOLD);
239
+ const collector: Collector = {
240
+ wards,
241
+ wake: () => {
242
+ wait.cancel();
243
+ this.#collectors.delete(collector);
244
+ resolve();
245
+ },
246
+ };
247
+ this.#collectors.add(collector);
248
+ void wait.done.then(collector.wake);
249
+ });
250
+ }
251
+
252
+ #settle(box: Waiting, reply: Uint8Array | null): void {
253
+ box.cancel();
254
+ const at = this.#waiting.indexOf(box);
255
+ if (at >= 0) this.#waiting.splice(at, 1);
256
+ this.#taken.delete(box.n);
257
+ box.answer(reply);
258
+ }
259
+ };
260
+
261
+ export const relayClient = (ground: Ground, clock: Clock): BeingClass =>
262
+ class RelayClient extends CarrierFaculty {
263
+ static override readonly kind: string = RELAY_CLIENT;
264
+ static override asks: Record<string, AskSpec> = {
265
+ hold: ownerAsk("a relay's invitation, collected from on a line, a schedule or a ring", { required: ['invitation'] }),
266
+ ring: ownerAsk('every waiting box collected and answered now'),
267
+ bell: ownerAsk('the push endpoint the relay rings, or null', { required: ['endpoint'] }),
268
+ key: ownerAsk('the key this device subscribes to pushes with'),
269
+ drop: ownerAsk('the relay let go'),
270
+ };
271
+
272
+ #awake = false;
273
+ #replies: Reply[] = [];
274
+ // Ends every rest and schedule when the client sleeps or lets go.
275
+ #stop: () => void = () => {};
276
+
277
+ accepts(): boolean {
278
+ return false;
279
+ }
280
+
281
+ dial(): Promise<Dialed> {
282
+ return Promise.resolve(UNDIALED);
283
+ }
284
+
285
+ override awake(): Promise<void> {
286
+ if (!this.#awake) {
287
+ this.#awake = true;
288
+ this.#start();
289
+ }
290
+ return Promise.resolve();
291
+ }
292
+
293
+ override sleep(): Promise<void> {
294
+ this.#awake = false;
295
+ this.#stop();
296
+ return Promise.resolve();
297
+ }
298
+
299
+ async hold(args: JsonObject): Promise<JsonObject> {
300
+ const invitation = readInvitation(args.invitation);
301
+ const { line, every } = args;
302
+ if (invitation === null || (line !== undefined && typeof line !== 'boolean') || (every !== undefined && !(Number.isInteger(every) && (every as number) > 0))) {
303
+ return { error: 'an invitation, line a boolean and every a positive integer' };
304
+ }
305
+ if (this.stance.standings.get(CLIENT)) return { error: 'a relay is held' };
306
+ if ((await this.stance.standings.take(CLIENT, invitation)) === null) return { error: 'not taken' };
307
+ this.cells.line = line === true;
308
+ if (every !== undefined) this.cells.every = every;
309
+ this.#start();
310
+ return { held: invitation.ward };
311
+ }
312
+
313
+ async ring(): Promise<JsonObject> {
314
+ if (!this.stance.standings.get(CLIENT)) return { error: 'no relay is held' };
315
+ let carried = 0;
316
+ for (;;) {
317
+ const sent = this.#replies.length;
318
+ const got = await this.#collect(false);
319
+ if (got === null) return { error: 'the relay was not reached', carried };
320
+ carried += got;
321
+ if (got === 0 && sent === 0) return { carried };
322
+ }
323
+ }
324
+
325
+ bell(args: JsonObject): Promise<JsonObject> {
326
+ return this.#relay('bell', { endpoint: args.endpoint ?? null });
327
+ }
328
+
329
+ key(): Promise<JsonObject> {
330
+ return this.#relay('key');
331
+ }
332
+
333
+ drop(): JsonObject {
334
+ if (!this.stance.standings.remove(CLIENT)) return { error: 'no relay is held' };
335
+ delete this.cells.line;
336
+ delete this.cells.every;
337
+ this.#stop();
338
+ return { dropped: true };
339
+ }
340
+
341
+ async #relay(method: string, args: JsonObject = {}): Promise<JsonObject> {
342
+ const standing = this.stance.standings.get(CLIENT);
343
+ return standing ? answered(await standing.ask(method, args)) : { error: 'no relay is held' };
344
+ }
345
+
346
+ #start(): void {
347
+ if (!this.#awake || !this.stance.standings.get(CLIENT)) return;
348
+ this.#stop();
349
+ let stopped = false;
350
+ const rests = new Set<() => void>();
351
+ this.#stop = () => {
352
+ stopped = true;
353
+ for (const end of rests) end();
354
+ };
355
+ const rest = (ms: number): Promise<void> =>
356
+ new Promise((resolve) => {
357
+ const wait = clock.wait(ms);
358
+ const end = () => {
359
+ wait.cancel();
360
+ rests.delete(end);
361
+ resolve();
362
+ };
363
+ rests.add(end);
364
+ void wait.done.then(end);
365
+ });
366
+ const going = () => !stopped && this.stance.standings.get(CLIENT) !== undefined;
367
+ if (this.cells.line === true) {
368
+ void (async () => {
369
+ while (going()) if ((await this.#collect(true)) === null && going()) await rest(RELAY_REST);
370
+ })();
371
+ }
372
+ const every = this.cells.every as number | undefined;
373
+ if (every !== undefined) {
374
+ void (async () => {
375
+ for (await rest(every); going(); await rest(every)) await this.ring();
376
+ })();
377
+ }
378
+ }
379
+
380
+ // One collect: the replies owed go with it, and each box it brings is
381
+ // handed to this harbor's doors. The number of boxes, or null where the
382
+ // relay was not reached.
383
+ async #collect(wait: boolean): Promise<number | null> {
384
+ const standing = this.stance.standings.get(CLIENT);
385
+ if (!standing) return null;
386
+ const replies = this.#replies.splice(0);
387
+ const out = await standing.ask('collect', { replies, wait });
388
+ const boxes = !isSilence(out) && !isWord(out) && Array.isArray((out as JsonObject).boxes) ? ((out as JsonObject).boxes as JsonObject[]) : null;
389
+ if (boxes === null) {
390
+ this.#replies.unshift(...replies);
391
+ return null;
392
+ }
393
+ for (const { n, ward, box } of boxes) {
394
+ const reply = text(ward) && text(box) && isHex(box, box.length / 2) ? await ground.arrive(ward, unhex(box)) : null;
395
+ this.#replies.push({ n: n as number, box: reply === null ? null : hex(reply) });
396
+ }
397
+ return boxes.length;
398
+ }
399
+ };
@@ -28,7 +28,10 @@ export const rootLine = async (harbor: Harbor, value: unknown): Promise<JsonObje
28
28
  const request = readRootRequest(value);
29
29
  if (request === null) return { error: 'not a root request' };
30
30
  const ward = request.ward === undefined ? harbor.box : harbor.ward(request.ward);
31
- if (ward === undefined) return { error: 'no such ward' };
31
+ if (ward === undefined) {
32
+ const failed = request.ward === undefined ? undefined : harbor.failures().wards[request.ward];
33
+ return failed === undefined ? { error: 'no such ward' } : { error: 'the ward did not stand', reason: failed };
34
+ }
32
35
  const out = await ward.root(request.method, request.args);
33
36
  if (isSilence(out)) return { silence: true };
34
37
  if (isWord(out)) return { word: told(out) as string };
@@ -1,7 +1,13 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // Where a harbor runs. A terrain hands the harbor one body for each
3
- // contract the onion cannot unpack from cells.
3
+ // contract the onion cannot unpack from cells, and the carriers its
4
+ // ground speaks.
4
5
  import type { Carrier, Clock, Custody, Entropy, Loader, Memory } from '../contract/index.ts';
6
+ import type { GroundFaculty } from './carrying.ts';
7
+ import type { Harbor } from './harbor.ts';
8
+
9
+ // A faculty a harbor opens at its genesis, under a key, by kind.
10
+ export type Opening = { readonly key: string; readonly kind: string };
5
11
 
6
12
  export abstract class Terrain {
7
13
  abstract readonly entropy: Entropy;
@@ -10,6 +16,26 @@ export abstract class Terrain {
10
16
  abstract readonly memory: Memory;
11
17
  // The code the catalogue's cells name.
12
18
  abstract readonly loader: Loader;
13
- // What reaches a ward pk this harbor does not hold.
19
+ // What reaches a ward pk this harbor holds no route for.
14
20
  abstract readonly carrier: Carrier;
21
+ // The faculty classes this ground ships, its carriers among them, and
22
+ // those a new harbor opens.
23
+ readonly faculties: readonly GroundFaculty[] = [];
24
+ readonly opens: readonly Opening[] = [];
25
+ // Whether its carriers wake and listen where their cells say. A harbor
26
+ // opened for one ask and closed again dials and hears nothing.
27
+ readonly wakes: boolean = true;
28
+
29
+ // Before the harbor opens: a terrain whose ground another run holds
30
+ // refuses here. Once it stands: whatever the ground serves beside it.
31
+ // Once its carriers sleep: what that served, gone.
32
+ claim(): Promise<void> {
33
+ return Promise.resolve();
34
+ }
35
+ stand(_harbor: Harbor): Promise<void> {
36
+ return Promise.resolve();
37
+ }
38
+ release(): Promise<void> {
39
+ return Promise.resolve();
40
+ }
15
41
  }
@@ -0,0 +1,150 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // `nervur/http`: the web carrier's listener on Node's HTTP server, an entry
3
+ // that names a platform.
4
+ //
5
+ // webServe answers posts at a path, and held lines opened to that path
6
+ // with the subprotocol `quo`, for the ground it is handed
7
+ // webGround the web carrier faculty of a Node ground, able to listen
8
+ //
9
+ // A post is one ask: 200 with the reply's box, or 204 for nothing. A post
10
+ // to another path is 404, another method 405, a body that is no ask 400.
11
+ // A page of an origin the cells name, or of any origin under `*`, is
12
+ // answered as the CORS protocol says, its preflight included. A held line
13
+ // carries one frame body to a binary message; a text message, a body that
14
+ // is no frame, or bytes that break RFC 6455 close it, and nothing after
15
+ // them is read.
16
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
17
+ import type { Socket } from 'node:net';
18
+ import type { Ground, GroundFaculty } from '../harbor/index.ts';
19
+ import { MAX_BODY, MAX_POST, nothingBody, readBody, readPost, replyBody, webFaculty, type WebListen, type WebListener } from '../line/index.ts';
20
+ import { hex } from '../crypto/index.ts';
21
+ import { tcpAt } from '../quo/index.ts';
22
+ import { acceptKey, frameOf, isClientKey, OP, WsReader } from './websocket.ts';
23
+
24
+ const pathOf = (url: string | undefined): string => {
25
+ const at = (url ?? '/').indexOf('?');
26
+ return at < 0 ? (url ?? '/') : (url ?? '/').slice(0, at);
27
+ };
28
+
29
+ const originOf = (origins: readonly string[], origin: string | undefined): string | null => {
30
+ if (origin === undefined) return null;
31
+ if (origins.includes('*')) return '*';
32
+ return origins.includes(origin) ? origin : null;
33
+ };
34
+
35
+ // The bytes of a request, up to one more than `max`, as they came.
36
+ const bodyOf = (request: IncomingMessage, max: number): Promise<Uint8Array> =>
37
+ new Promise((resolve, reject) => {
38
+ const parts: Uint8Array[] = [];
39
+ let length = 0;
40
+ request.on('data', (chunk: Uint8Array) => {
41
+ if (length > max) return;
42
+ parts.push(chunk);
43
+ length += chunk.length;
44
+ });
45
+ request.on('end', () => {
46
+ const out = new Uint8Array(length);
47
+ let at = 0;
48
+ for (const part of parts) {
49
+ out.set(part, at);
50
+ at += part.length;
51
+ }
52
+ resolve(out);
53
+ });
54
+ request.on('error', reject);
55
+ });
56
+
57
+ const post = async (ground: Ground, listen: WebListen, request: IncomingMessage, response: ServerResponse): Promise<void> => {
58
+ const allowed = originOf(listen.origins, request.headers.origin);
59
+ if (allowed !== null) response.setHeader('access-control-allow-origin', allowed);
60
+ if (pathOf(request.url) !== listen.path) return void response.writeHead(404).end();
61
+ if (request.method === 'OPTIONS') {
62
+ if (allowed !== null) {
63
+ response.setHeader('access-control-allow-methods', 'POST');
64
+ response.setHeader('access-control-allow-headers', 'content-type');
65
+ }
66
+ return void response.writeHead(204).end();
67
+ }
68
+ if (request.method !== 'POST') return void response.writeHead(405, { allow: 'POST, OPTIONS' }).end();
69
+ const ask = readPost(await bodyOf(request, MAX_POST));
70
+ if (ask === null) return void response.writeHead(400).end();
71
+ let reply: Uint8Array | null = null;
72
+ try {
73
+ reply = await ground.arrive(ask.pk, ask.box);
74
+ } catch {
75
+ reply = null;
76
+ }
77
+ if (reply === null || reply.length === 0) return void response.writeHead(204).end();
78
+ response.writeHead(200, { 'content-type': 'application/octet-stream' }).end(reply);
79
+ };
80
+
81
+ const upgrade = (ground: Ground, listen: WebListen, request: IncomingMessage, socket: Socket): void => {
82
+ const key = request.headers['sec-websocket-key'];
83
+ const offered = String(request.headers['sec-websocket-protocol'] ?? '')
84
+ .split(',')
85
+ .map((p) => p.trim());
86
+ const fine = pathOf(request.url) === listen.path && request.headers['sec-websocket-version'] === '13' && isClientKey(key) && offered.includes('quo');
87
+ if (!fine) {
88
+ socket.end('HTTP/1.1 400 Bad Request\r\nconnection: close\r\ncontent-length: 0\r\n\r\n');
89
+ return;
90
+ }
91
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: ${acceptKey(key)}\r\nsec-websocket-protocol: quo\r\n\r\n`);
92
+ const reader = new WsReader(MAX_BODY);
93
+ const send = (opcode: number, payload?: Uint8Array): void => {
94
+ if (!socket.destroyed) socket.write(frameOf(opcode, payload));
95
+ };
96
+ const close = (): void => {
97
+ send(OP.close);
98
+ socket.end();
99
+ };
100
+ socket.on('data', (chunk: Uint8Array) => {
101
+ for (const event of reader.push(chunk)) {
102
+ if (event.type === 'ping') send(OP.pong, event.data);
103
+ else if (event.type !== 'binary') return close();
104
+ else {
105
+ const frame = readBody(event.data);
106
+ if (frame === null) return close();
107
+ if (frame.kind !== 'ask') continue;
108
+ void ground
109
+ .arrive(hex(frame.pk), frame.box)
110
+ .catch(() => null)
111
+ .then((reply) => send(OP.binary, reply === null ? nothingBody(frame.id) : replyBody(frame.id, reply)));
112
+ }
113
+ }
114
+ });
115
+ socket.on('error', () => socket.destroy());
116
+ };
117
+
118
+ // A listener of the web carrier for one ground.
119
+ export const webServe = (ground: Ground, listen: WebListen): Promise<WebListener> => {
120
+ const sockets = new Set<Socket>();
121
+ const server = createServer((request, response) => {
122
+ void post(ground, listen, request, response).catch(() => {
123
+ if (!response.headersSent) response.writeHead(400);
124
+ response.end();
125
+ });
126
+ });
127
+ server.on('connection', (socket) => {
128
+ sockets.add(socket);
129
+ socket.on('close', () => sockets.delete(socket));
130
+ });
131
+ server.on('upgrade', (request: IncomingMessage, socket: Socket) => upgrade(ground, listen, request, socket));
132
+ return new Promise((resolve, reject) => {
133
+ server.once('error', reject);
134
+ server.listen(listen.port, listen.host, () => {
135
+ const { address, port } = server.address() as { address: string; port: number };
136
+ const authority = tcpAt(address, port).slice('tcp://'.length);
137
+ resolve({
138
+ port,
139
+ at: [`http://${authority}${listen.path}`, `ws://${authority}${listen.path}`],
140
+ close: () => {
141
+ for (const socket of sockets) socket.destroy();
142
+ return new Promise((done) => server.close(() => done()));
143
+ },
144
+ });
145
+ });
146
+ });
147
+ };
148
+
149
+ // The web carrier of a Node ground: it dials, and listens through `webServe`.
150
+ export const webGround: GroundFaculty = webFaculty(webServe);