@niwa-labs/client 0.0.0-stage → 0.0.0
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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/package.json +11 -4
- package/src/client-types.ts +80 -0
- package/src/client.ts +949 -0
- package/src/holder.ts +58 -0
- package/src/home.ts +11 -0
- package/src/index.ts +10 -0
- package/src/live.ts +141 -0
- package/src/observation.ts +181 -0
- package/src/pause.ts +30 -0
- package/src/token.ts +38 -0
- package/src/wire.ts +315 -0
- package/src/working-directory.ts +28 -0
- package/test/connection-leak.test.ts +17 -0
- package/test/fixtures/owner-token-of.ts +5 -0
- package/test/helpers.ts +54 -0
- package/test/line-decoder.test.ts +37 -0
- package/test/live-cancel.test.ts +24 -0
- package/test/live-feed.test.ts +49 -0
- package/test/no-sqlite.test.ts +79 -0
- package/test/owner-token.test.ts +31 -0
- package/test/query-refused.test.ts +20 -0
- package/test/retry-pause.test.ts +19 -0
- package/test/write-failure.test.ts +54 -0
- package/tsconfig.json +6 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,949 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* client.ts — the client side of the niwa wire (see wire.ts for the framing).
|
|
3
|
+
*
|
|
4
|
+
* The call connection carries `emit`, `call`, `trace` and `causes` as request/response pairs
|
|
5
|
+
* keyed by a numeric id; it is reopened on the next call when the host went away. Every
|
|
6
|
+
* subscription has its own socket, where the host streams `{ id, record }`. A subscription
|
|
7
|
+
* keeps the seq of the last record it queued and resubscribes from exactly there after a
|
|
8
|
+
* drop, so the consumer sees no gap and no duplicate.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { z } from "zod";
|
|
12
|
+
|
|
13
|
+
import { expandHome } from "./home.ts";
|
|
14
|
+
import { MAX_QUEUED_FRAMES, channelName, frameFor } from "./live.ts";
|
|
15
|
+
import { RetryPause } from "./pause.ts";
|
|
16
|
+
import { RecordRefused, RecordQuerySchema, resolveQuery, seq, targetName } from "@niwa-labs/core";
|
|
17
|
+
import type {
|
|
18
|
+
ActionTarget,
|
|
19
|
+
CallOptions,
|
|
20
|
+
Action,
|
|
21
|
+
ActionName,
|
|
22
|
+
ClientId,
|
|
23
|
+
Description,
|
|
24
|
+
EmitOptions,
|
|
25
|
+
EmitBatch,
|
|
26
|
+
LiveFrame,
|
|
27
|
+
RecordReadQuery,
|
|
28
|
+
RecordQuery,
|
|
29
|
+
ResolvedQuery,
|
|
30
|
+
RecordId,
|
|
31
|
+
RecordType,
|
|
32
|
+
RecordTypeName,
|
|
33
|
+
Seq,
|
|
34
|
+
StoredRecord,
|
|
35
|
+
StreamId,
|
|
36
|
+
TracedRecord,
|
|
37
|
+
Token,
|
|
38
|
+
} from "@niwa-labs/core";
|
|
39
|
+
import type { LiveSubscription, NiwaApi, RecordFeed } from "./client-types.ts";
|
|
40
|
+
import {
|
|
41
|
+
clientMessageSchema,
|
|
42
|
+
decodeHostMessage,
|
|
43
|
+
descriptionSchema,
|
|
44
|
+
encode,
|
|
45
|
+
lineDecoder,
|
|
46
|
+
socketPath,
|
|
47
|
+
storedRecordSchema,
|
|
48
|
+
tracedRecordSchema,
|
|
49
|
+
type HostMessage,
|
|
50
|
+
} from "./wire.ts";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Records a subscription holds for a consumer that reads slowly. Past this the socket is
|
|
54
|
+
* dropped; the cursor stays at the last queued record, so nothing is lost, and the
|
|
55
|
+
* subscription reconnects once the consumer has drained the queue to half of it.
|
|
56
|
+
*/
|
|
57
|
+
const MAX_QUEUED_RECORDS = 1024;
|
|
58
|
+
|
|
59
|
+
/** An error reported by the host: `code` is the host's error class name (`UnknownType`, …). */
|
|
60
|
+
export class HostError extends Error {
|
|
61
|
+
readonly code: string | undefined;
|
|
62
|
+
/** Set when a grant refused the call: whose grant, and the rule it lacks. */
|
|
63
|
+
readonly denied: { readonly grant: string; readonly missing: string; readonly record?: string } | undefined;
|
|
64
|
+
|
|
65
|
+
constructor(message: string, code?: string, denied?: HostError["denied"]) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.name = "HostError";
|
|
68
|
+
this.code = code;
|
|
69
|
+
this.denied = denied;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const CLOSED_MESSAGE = "the connection to the niwa host is closed";
|
|
74
|
+
|
|
75
|
+
function asError(error: unknown): Error {
|
|
76
|
+
return error instanceof Error ? error : new HostError(String(error));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
type ClientMessageInput = z.input<typeof clientMessageSchema>;
|
|
80
|
+
|
|
81
|
+
/** Read what the host returned with a schema, or refuse it. */
|
|
82
|
+
function parseReturned<S extends z.ZodType>(schema: S, value: unknown, what: string): z.output<S> {
|
|
83
|
+
const parsed = schema.safeParse(value);
|
|
84
|
+
if (!parsed.success) throw new HostError(`the host did not return ${what}`);
|
|
85
|
+
return parsed.data;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseList<S extends z.ZodType>(schema: S, value: unknown, what: string): Array<z.output<S>> {
|
|
89
|
+
if (!Array.isArray(value)) throw new HostError(`the host did not return ${what}`);
|
|
90
|
+
return value.map((entry) => parseReturned(schema, entry, what));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A query as the wire carries it: plain lists. */
|
|
94
|
+
function onWire(query: ResolvedQuery): { types?: string[]; filter?: Record<string, never>; stream?: string; from?: number } {
|
|
95
|
+
return {
|
|
96
|
+
...(query.types === undefined ? {} : { types: [...query.types] }),
|
|
97
|
+
...(query.filter === undefined ? {} : { filter: query.filter as Record<string, never> }),
|
|
98
|
+
...(query.stream === undefined ? {} : { stream: query.stream }),
|
|
99
|
+
...(query.from === undefined ? {} : { from: query.from }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Refuse a query the wire does not accept, with the reason. */
|
|
104
|
+
function checkQuery(query: ResolvedQuery): void {
|
|
105
|
+
const parsed = RecordQuerySchema.safeParse(onWire(query));
|
|
106
|
+
if (parsed.success) return;
|
|
107
|
+
const why = parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
|
|
108
|
+
throw new HostError(`the query is not one the wire accepts: ${why}`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface PendingCall {
|
|
112
|
+
resolve(value: unknown): void;
|
|
113
|
+
reject(error: Error): void;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface ConnectionOptions {
|
|
117
|
+
readonly home: string;
|
|
118
|
+
readonly client: ClientId;
|
|
119
|
+
/** The token the connection shows in `hello`; without one it is a plain client. */
|
|
120
|
+
readonly token: Token | undefined;
|
|
121
|
+
/** Called for every record of a subscription opened on this connection. */
|
|
122
|
+
readonly onRecord?: (record: StoredRecord) => void;
|
|
123
|
+
/** Called for every live frame of a live subscription opened on this connection. */
|
|
124
|
+
readonly onFrame?: (frame: LiveFrame) => void;
|
|
125
|
+
/**
|
|
126
|
+
* Called when the connection dies for good: the host refused it, or sent something this
|
|
127
|
+
* client cannot read. A plain drop is not fatal — a subscription reconnects from it.
|
|
128
|
+
*/
|
|
129
|
+
readonly onFatal?: (error: Error) => void;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** One socket to the host: it owns the request ids, the pending replies and the decoder. */
|
|
133
|
+
class WireConnection {
|
|
134
|
+
private readonly options: ConnectionOptions;
|
|
135
|
+
private readonly decoder: (chunk: Uint8Array | string) => void;
|
|
136
|
+
private readonly pending = new Map<number, PendingCall>();
|
|
137
|
+
/** Ids of subscriptions: a refusal of one of these is fatal, not a failed call. */
|
|
138
|
+
private readonly subscriptionIds = new Set<number>();
|
|
139
|
+
private readonly encoder = new TextEncoder();
|
|
140
|
+
private readonly helloId = 1;
|
|
141
|
+
private readonly donePromise: Promise<void>;
|
|
142
|
+
private resolveDone: () => void = () => undefined;
|
|
143
|
+
private socket: Bun.Socket | null = null;
|
|
144
|
+
/** Bytes the full socket did not take yet; counted in bytes, never cut inside a character. */
|
|
145
|
+
private outgoing: Uint8Array = new Uint8Array(0);
|
|
146
|
+
private nextId = this.helloId + 1;
|
|
147
|
+
private isClosed = false;
|
|
148
|
+
/** Why the connection is not usable, when the host named a reason. */
|
|
149
|
+
private lastError: Error | null = null;
|
|
150
|
+
|
|
151
|
+
constructor(options: ConnectionOptions) {
|
|
152
|
+
this.options = options;
|
|
153
|
+
this.decoder = lineDecoder((message) => this.handleMessage(message), {
|
|
154
|
+
// A line this client cannot frame or parse is half-understood: end the connection.
|
|
155
|
+
onError: (error) => this.die(error, true),
|
|
156
|
+
});
|
|
157
|
+
this.donePromise = new Promise<void>((resolve) => {
|
|
158
|
+
this.resolveDone = resolve;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Resolves when the connection is gone (closed by us or by the host). */
|
|
163
|
+
get done(): Promise<void> {
|
|
164
|
+
return this.donePromise;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
get isOpen(): boolean {
|
|
168
|
+
return !this.isClosed;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Open the socket and say hello. Rejects when the host is not reachable. */
|
|
172
|
+
async open(): Promise<void> {
|
|
173
|
+
const socket = await Bun.connect({
|
|
174
|
+
unix: socketPath(expandHome(this.options.home)),
|
|
175
|
+
socket: {
|
|
176
|
+
data: (_socket, chunk) => {
|
|
177
|
+
this.decoder(chunk);
|
|
178
|
+
},
|
|
179
|
+
close: () => {
|
|
180
|
+
this.die();
|
|
181
|
+
},
|
|
182
|
+
error: (_socket, error) => {
|
|
183
|
+
this.die(error);
|
|
184
|
+
},
|
|
185
|
+
end: () => {
|
|
186
|
+
this.die();
|
|
187
|
+
},
|
|
188
|
+
drain: () => {
|
|
189
|
+
if (!this.flush()) this.die();
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
if (this.isClosed) {
|
|
194
|
+
socket.end();
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
this.socket = socket;
|
|
198
|
+
try {
|
|
199
|
+
this.send({
|
|
200
|
+
id: this.helloId,
|
|
201
|
+
op: "hello",
|
|
202
|
+
client: this.options.client,
|
|
203
|
+
...(this.options.token === undefined ? {} : { token: this.options.token }),
|
|
204
|
+
});
|
|
205
|
+
} catch (error) {
|
|
206
|
+
// A hello that cannot be built or written leaves a connection nobody holds: close it.
|
|
207
|
+
this.die();
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** One request/response exchange: `build` gets a fresh request id; the reply is matched by it. */
|
|
213
|
+
request(build: (id: number) => ClientMessageInput): Promise<unknown> {
|
|
214
|
+
if (this.isClosed) return Promise.reject(this.closedError());
|
|
215
|
+
const id = this.nextId++;
|
|
216
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
217
|
+
this.pending.set(id, { resolve, reject });
|
|
218
|
+
try {
|
|
219
|
+
this.send(build(id));
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.pending.delete(id);
|
|
222
|
+
reject(asError(error));
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Subscribe to the records that answer a query: the history after its position, then the live ones. Resolves when the host
|
|
229
|
+
* accepted the subscription, before any record; a refusal ends the connection and rejects.
|
|
230
|
+
*/
|
|
231
|
+
subscribe(query: ResolvedQuery): Promise<void> {
|
|
232
|
+
const id = this.nextId++;
|
|
233
|
+
this.subscriptionIds.add(id);
|
|
234
|
+
return new Promise<void>((resolve, reject) => {
|
|
235
|
+
this.pending.set(id, { resolve: () => resolve(), reject });
|
|
236
|
+
try {
|
|
237
|
+
this.send({ id, op: "since", query: onWire(query) });
|
|
238
|
+
} catch (error) {
|
|
239
|
+
this.pending.delete(id);
|
|
240
|
+
reject(asError(error));
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Subscribe to the live frames of a channel. Resolves when the host answered: it registered
|
|
247
|
+
* the listener before it did, so a frame sent after this is received. Rejects when the
|
|
248
|
+
* connection ended or the host refused first.
|
|
249
|
+
*/
|
|
250
|
+
subscribeLive(channel: string): Promise<void> {
|
|
251
|
+
const id = this.nextId++;
|
|
252
|
+
this.subscriptionIds.add(id);
|
|
253
|
+
return new Promise<void>((resolve, reject) => {
|
|
254
|
+
this.pending.set(id, { resolve: () => resolve(), reject });
|
|
255
|
+
try {
|
|
256
|
+
this.send({ id, op: "live.subscribe", channel });
|
|
257
|
+
} catch (error) {
|
|
258
|
+
this.pending.delete(id);
|
|
259
|
+
reject(asError(error));
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Close the connection. Pending calls reject. */
|
|
265
|
+
close(): void {
|
|
266
|
+
this.die();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The wire's own client schema checks every message, so a message built wrong is caught here. */
|
|
270
|
+
private send(input: ClientMessageInput): void {
|
|
271
|
+
if (this.socket === null) throw this.closedError();
|
|
272
|
+
let message: z.output<typeof clientMessageSchema>;
|
|
273
|
+
try {
|
|
274
|
+
message = clientMessageSchema.parse(input);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
throw new HostError(`the client built a message the wire does not accept: ${asError(error).message}`);
|
|
277
|
+
}
|
|
278
|
+
const bytes = this.encoder.encode(encode(message));
|
|
279
|
+
const joined = new Uint8Array(this.outgoing.length + bytes.length);
|
|
280
|
+
joined.set(this.outgoing, 0);
|
|
281
|
+
joined.set(bytes, this.outgoing.length);
|
|
282
|
+
this.outgoing = joined;
|
|
283
|
+
if (!this.flush()) {
|
|
284
|
+
// A write that failed leaves bytes of a request nobody will answer: the connection ends with
|
|
285
|
+
// them, and every request on it fails, so none starts after its caller was told it failed.
|
|
286
|
+
this.die();
|
|
287
|
+
throw this.closedError();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Write as much of the waiting bytes as the socket takes; false when the socket is gone. */
|
|
292
|
+
private flush(): boolean {
|
|
293
|
+
const socket = this.socket;
|
|
294
|
+
if (socket === null) return true;
|
|
295
|
+
try {
|
|
296
|
+
while (this.outgoing.length > 0) {
|
|
297
|
+
const written = socket.write(this.outgoing);
|
|
298
|
+
if (written < 0) return false;
|
|
299
|
+
if (written === 0) return true; // full: the rest waits for the drain
|
|
300
|
+
this.outgoing = this.outgoing.subarray(written);
|
|
301
|
+
}
|
|
302
|
+
return true;
|
|
303
|
+
} catch {
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private handleMessage(message: unknown): void {
|
|
309
|
+
if (this.isClosed) return; // the rest of a chunk that was read after the connection ended
|
|
310
|
+
let decoded: HostMessage;
|
|
311
|
+
try {
|
|
312
|
+
decoded = decodeHostMessage(message);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
this.die(asError(error), true);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if ("record" in decoded) {
|
|
319
|
+
this.options.onRecord?.(decoded.record);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if ("frame" in decoded) {
|
|
324
|
+
this.options.onFrame?.({ channel: decoded.frame.channel, data: decoded.frame.data });
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const pending = this.pending.get(decoded.id);
|
|
329
|
+
if (decoded.ok) {
|
|
330
|
+
this.pending.delete(decoded.id);
|
|
331
|
+
pending?.resolve(decoded.value);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const error = decoded.refusal
|
|
335
|
+
? new RecordRefused(decoded.refusal.code, decoded.refusal.reason, decoded.refusal.entity, decoded.refusal.recordType, decoded.refusal.audit, false)
|
|
336
|
+
: new HostError(decoded.error, decoded.code, decoded.denied);
|
|
337
|
+
if (decoded.id === this.helloId || this.subscriptionIds.has(decoded.id)) {
|
|
338
|
+
// The host will not talk to this client, or refused the subscription: retrying would spin.
|
|
339
|
+
this.die(error, true);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
this.pending.delete(decoded.id);
|
|
343
|
+
pending?.reject(error);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The connection ends: every pending call is rejected at once, so nobody waits on a corpse. */
|
|
347
|
+
private die(error?: Error, fatal = false): void {
|
|
348
|
+
if (this.isClosed) return;
|
|
349
|
+
this.isClosed = true;
|
|
350
|
+
if (error !== undefined) this.lastError = error;
|
|
351
|
+
const reason = this.closedError();
|
|
352
|
+
for (const pending of this.pending.values()) pending.reject(reason);
|
|
353
|
+
this.pending.clear();
|
|
354
|
+
const socket = this.socket;
|
|
355
|
+
this.socket = null;
|
|
356
|
+
this.outgoing = new Uint8Array(0);
|
|
357
|
+
try {
|
|
358
|
+
socket?.end();
|
|
359
|
+
} catch {
|
|
360
|
+
// The socket is already gone.
|
|
361
|
+
}
|
|
362
|
+
this.resolveDone();
|
|
363
|
+
if (fatal && error !== undefined) this.options.onFatal?.(error);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private closedError(): Error {
|
|
367
|
+
return this.lastError ?? new HostError(CLOSED_MESSAGE);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
interface SubscriptionOptions {
|
|
372
|
+
readonly home: string;
|
|
373
|
+
readonly client: ClientId;
|
|
374
|
+
readonly token: Token | undefined;
|
|
375
|
+
/** The records the consumer asked for; the cursor starts at the query's position. */
|
|
376
|
+
readonly query: ResolvedQuery;
|
|
377
|
+
/** Called once when the subscription is over (closed or failed). */
|
|
378
|
+
readonly onDone: () => void;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* A live view of the journal. It owns the cursor — the last seq that was queued — and on a
|
|
383
|
+
* drop reconnects and resubscribes from it, which makes the stream gapless and duplicate-free.
|
|
384
|
+
*/
|
|
385
|
+
class RecordSubscription {
|
|
386
|
+
private readonly options: SubscriptionOptions;
|
|
387
|
+
private readonly queue: StoredRecord[] = [];
|
|
388
|
+
private readonly waiters: Array<() => void> = [];
|
|
389
|
+
private cursor: Seq;
|
|
390
|
+
private connection: WireConnection | null = null;
|
|
391
|
+
private runner: Promise<void> | null = null;
|
|
392
|
+
private failure: Error | null = null;
|
|
393
|
+
private isClosed = false;
|
|
394
|
+
private finished = false;
|
|
395
|
+
/** Set while the connection is held off because the queue is full. */
|
|
396
|
+
private resume: (() => void) | null = null;
|
|
397
|
+
/** The wait before the next attempt; a close ends it at once. */
|
|
398
|
+
private readonly pause = new RetryPause();
|
|
399
|
+
private readonly accepted: Promise<void>;
|
|
400
|
+
private markReady: () => void = () => undefined;
|
|
401
|
+
private refuseReady: (error: Error) => void = () => undefined;
|
|
402
|
+
|
|
403
|
+
constructor(options: SubscriptionOptions) {
|
|
404
|
+
this.options = options;
|
|
405
|
+
this.cursor = options.query.from ?? seq(0);
|
|
406
|
+
this.accepted = new Promise<void>((resolve, reject) => {
|
|
407
|
+
this.markReady = resolve;
|
|
408
|
+
this.refuseReady = reject;
|
|
409
|
+
});
|
|
410
|
+
// A subscription nobody waits on for readiness must not report its refusal as unhandled.
|
|
411
|
+
this.accepted.catch(() => undefined);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Return closes the socket even if a next call is waiting for a commit. */
|
|
415
|
+
iterate(): RecordFeed & AsyncIterableIterator<StoredRecord> {
|
|
416
|
+
const records = this.readRecords();
|
|
417
|
+
const subscription = this;
|
|
418
|
+
return {
|
|
419
|
+
[Symbol.asyncIterator]() { return this; },
|
|
420
|
+
next: () => records.next(),
|
|
421
|
+
return: () => {
|
|
422
|
+
this.close();
|
|
423
|
+
return records.return();
|
|
424
|
+
},
|
|
425
|
+
get ready() {
|
|
426
|
+
subscription.start();
|
|
427
|
+
return subscription.accepted;
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Open the subscription if it is not open: reading a record or asking whether it is ready does. */
|
|
433
|
+
private start(): void {
|
|
434
|
+
if (!this.isClosed) this.runner ??= this.run();
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** The records, in order, until the subscription closes. */
|
|
438
|
+
private async *readRecords(): AsyncGenerator<StoredRecord, void, undefined> {
|
|
439
|
+
if (this.isClosed) return;
|
|
440
|
+
this.start();
|
|
441
|
+
try {
|
|
442
|
+
for (;;) {
|
|
443
|
+
const record = this.queue.shift();
|
|
444
|
+
if (record !== undefined) {
|
|
445
|
+
if (this.queue.length < MAX_QUEUED_RECORDS / 2) this.release();
|
|
446
|
+
yield record;
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
if (this.failure !== null) throw this.failure;
|
|
450
|
+
if (this.isClosed) return;
|
|
451
|
+
await new Promise<void>((resolve) => this.waiters.push(resolve));
|
|
452
|
+
}
|
|
453
|
+
} finally {
|
|
454
|
+
this.close();
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Stop the subscription: the iterator ends and the socket is closed. */
|
|
459
|
+
close(): void {
|
|
460
|
+
if (this.isClosed) return;
|
|
461
|
+
this.isClosed = true;
|
|
462
|
+
this.closeConnection();
|
|
463
|
+
this.pause.cancel();
|
|
464
|
+
this.refuseReady(this.failure ?? new HostError(CLOSED_MESSAGE));
|
|
465
|
+
this.release();
|
|
466
|
+
this.wake();
|
|
467
|
+
this.finish();
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private async run(): Promise<void> {
|
|
471
|
+
try {
|
|
472
|
+
await this.loop();
|
|
473
|
+
} catch (error) {
|
|
474
|
+
this.fail(asError(error));
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Keep one connection alive: every drop leads to a fresh one, resubscribed from the cursor. */
|
|
479
|
+
private async loop(): Promise<void> {
|
|
480
|
+
while (!this.isClosed) {
|
|
481
|
+
const connection = await this.open();
|
|
482
|
+
if (this.isClosed) {
|
|
483
|
+
connection?.close();
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
if (connection !== null) {
|
|
487
|
+
this.connection = connection;
|
|
488
|
+
try {
|
|
489
|
+
// A reconnect asks for the same query from where the stream got to: no gap, no duplicate.
|
|
490
|
+
await connection.subscribe({ ...this.options.query, from: this.cursor });
|
|
491
|
+
this.markReady();
|
|
492
|
+
await connection.done;
|
|
493
|
+
} catch {
|
|
494
|
+
// The write failed: the socket is gone; the next round reconnects.
|
|
495
|
+
}
|
|
496
|
+
this.closeConnection();
|
|
497
|
+
if (this.queue.length >= MAX_QUEUED_RECORDS && !(await this.waitForRoom())) return;
|
|
498
|
+
}
|
|
499
|
+
if (!(await this.waitBeforeRetry())) return;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Open a subscription socket; null when the host is not reachable. */
|
|
504
|
+
private async open(): Promise<WireConnection | null> {
|
|
505
|
+
const connection = new WireConnection({
|
|
506
|
+
home: this.options.home,
|
|
507
|
+
client: this.options.client,
|
|
508
|
+
token: this.options.token,
|
|
509
|
+
onRecord: (record) => {
|
|
510
|
+
this.onRecord(record);
|
|
511
|
+
},
|
|
512
|
+
onFatal: (error) => {
|
|
513
|
+
this.fail(error);
|
|
514
|
+
},
|
|
515
|
+
});
|
|
516
|
+
try {
|
|
517
|
+
await connection.open();
|
|
518
|
+
return connection;
|
|
519
|
+
} catch {
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Wait before the next attempt; false when the subscription was closed. */
|
|
525
|
+
private async waitBeforeRetry(): Promise<boolean> {
|
|
526
|
+
if (this.isClosed) return false;
|
|
527
|
+
await this.pause.wait();
|
|
528
|
+
return !this.isClosed;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** Wait until the consumer has drained the queue; false when the subscription was closed. */
|
|
532
|
+
private async waitForRoom(): Promise<boolean> {
|
|
533
|
+
if (this.isClosed) return false;
|
|
534
|
+
await new Promise<void>((resolve) => {
|
|
535
|
+
this.resume = resolve;
|
|
536
|
+
});
|
|
537
|
+
return !this.isClosed;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
private release(): void {
|
|
541
|
+
const resume = this.resume;
|
|
542
|
+
this.resume = null;
|
|
543
|
+
resume?.();
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
private onRecord(record: StoredRecord): void {
|
|
547
|
+
if (this.isClosed) return;
|
|
548
|
+
// The cursor only moves forward: a record at or below it was delivered already — the
|
|
549
|
+
// host resumes after the cursor, so a boundary record can arrive twice.
|
|
550
|
+
if (record.seq <= this.cursor) return;
|
|
551
|
+
if (this.queue.length >= MAX_QUEUED_RECORDS) {
|
|
552
|
+
// The consumer is too slow. The record is not queued and the cursor does not move, so
|
|
553
|
+
// the resubscribe after the drain starts exactly here.
|
|
554
|
+
this.closeConnection();
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
this.cursor = record.seq;
|
|
558
|
+
this.queue.push(record);
|
|
559
|
+
this.wake();
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
private fail(error: Error): void {
|
|
563
|
+
if (this.failure !== null) return;
|
|
564
|
+
this.failure = error;
|
|
565
|
+
this.close();
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Tell the owner once that this subscription is over, so it is not kept in its set. */
|
|
569
|
+
private finish(): void {
|
|
570
|
+
if (this.finished) return;
|
|
571
|
+
this.finished = true;
|
|
572
|
+
this.options.onDone();
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
private closeConnection(): void {
|
|
576
|
+
const connection = this.connection;
|
|
577
|
+
this.connection = null;
|
|
578
|
+
connection?.close();
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
private wake(): void {
|
|
582
|
+
for (const resolve of this.waiters.splice(0)) resolve();
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
interface ChannelSubscriptionOptions {
|
|
587
|
+
readonly home: string;
|
|
588
|
+
readonly client: ClientId;
|
|
589
|
+
readonly token: Token | undefined;
|
|
590
|
+
readonly channel: string;
|
|
591
|
+
/** Called once when the subscription is over (closed or failed). */
|
|
592
|
+
readonly onDone: () => void;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* A view of one channel over one socket. A live frame is not a record: there is no cursor and
|
|
597
|
+
* no history, and the frames sent while the socket was down are missed. A drop is not fatal; the
|
|
598
|
+
* subscription reconnects and listens again.
|
|
599
|
+
*
|
|
600
|
+
* The socket opens when the subscription is made, not when it is first read, and `ready` says when
|
|
601
|
+
* the host has registered the listener.
|
|
602
|
+
*/
|
|
603
|
+
class ChannelSubscription {
|
|
604
|
+
private readonly options: ChannelSubscriptionOptions;
|
|
605
|
+
private readonly queue: LiveFrame[] = [];
|
|
606
|
+
private readonly waiters: Array<() => void> = [];
|
|
607
|
+
private connection: WireConnection | null = null;
|
|
608
|
+
private failure: Error | null = null;
|
|
609
|
+
private isClosed = false;
|
|
610
|
+
private finished = false;
|
|
611
|
+
private readonly pause = new RetryPause();
|
|
612
|
+
readonly ready: Promise<void>;
|
|
613
|
+
private markReady: () => void = () => undefined;
|
|
614
|
+
private refuseReady: (error: Error) => void = () => undefined;
|
|
615
|
+
|
|
616
|
+
constructor(options: ChannelSubscriptionOptions) {
|
|
617
|
+
this.options = options;
|
|
618
|
+
this.ready = new Promise<void>((resolve, reject) => {
|
|
619
|
+
this.markReady = resolve;
|
|
620
|
+
this.refuseReady = reject;
|
|
621
|
+
});
|
|
622
|
+
// A subscription nobody waits on for readiness must not report its refusal as unhandled.
|
|
623
|
+
this.ready.catch(() => undefined);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Open the socket and keep it open until the subscription is closed. */
|
|
627
|
+
start(): void {
|
|
628
|
+
void this.run();
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Return closes the socket even if a next call is waiting on a quiet channel. */
|
|
632
|
+
iterate(): LiveSubscription {
|
|
633
|
+
const frames = this.readFrames();
|
|
634
|
+
return {
|
|
635
|
+
[Symbol.asyncIterator]() { return this; },
|
|
636
|
+
next: () => frames.next(),
|
|
637
|
+
return: () => {
|
|
638
|
+
this.close();
|
|
639
|
+
return frames.return();
|
|
640
|
+
},
|
|
641
|
+
ready: this.ready,
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** The frames, in order, until the subscription closes. */
|
|
646
|
+
private async *readFrames(): AsyncGenerator<LiveFrame, void, undefined> {
|
|
647
|
+
try {
|
|
648
|
+
for (;;) {
|
|
649
|
+
const frame = this.queue.shift();
|
|
650
|
+
if (frame !== undefined) {
|
|
651
|
+
yield frame;
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
if (this.failure !== null) throw this.failure;
|
|
655
|
+
if (this.isClosed) return;
|
|
656
|
+
await new Promise<void>((resolve) => this.waiters.push(resolve));
|
|
657
|
+
}
|
|
658
|
+
} finally {
|
|
659
|
+
this.close();
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** Stop the subscription: the iterator ends and the socket is closed. */
|
|
664
|
+
close(): void {
|
|
665
|
+
if (this.isClosed) return;
|
|
666
|
+
this.isClosed = true;
|
|
667
|
+
this.closeConnection();
|
|
668
|
+
this.pause.cancel();
|
|
669
|
+
this.refuseReady(this.failure ?? new HostError(CLOSED_MESSAGE));
|
|
670
|
+
this.wake();
|
|
671
|
+
this.finish();
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
private async run(): Promise<void> {
|
|
675
|
+
try {
|
|
676
|
+
await this.loop();
|
|
677
|
+
} catch (error) {
|
|
678
|
+
this.fail(asError(error));
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** Keep one connection alive: every drop leads to a fresh one. */
|
|
683
|
+
private async loop(): Promise<void> {
|
|
684
|
+
while (!this.isClosed) {
|
|
685
|
+
const connection = await this.open();
|
|
686
|
+
if (this.isClosed) {
|
|
687
|
+
connection?.close();
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (connection !== null) {
|
|
691
|
+
this.connection = connection;
|
|
692
|
+
try {
|
|
693
|
+
await connection.subscribeLive(this.options.channel);
|
|
694
|
+
this.markReady();
|
|
695
|
+
await connection.done;
|
|
696
|
+
} catch {
|
|
697
|
+
// The write failed or the connection ended before the host answered: the next round reconnects.
|
|
698
|
+
}
|
|
699
|
+
this.closeConnection();
|
|
700
|
+
}
|
|
701
|
+
if (!(await this.waitBeforeRetry())) return;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** Open a socket; null when the host is not reachable. */
|
|
706
|
+
private async open(): Promise<WireConnection | null> {
|
|
707
|
+
const connection = new WireConnection({
|
|
708
|
+
home: this.options.home,
|
|
709
|
+
client: this.options.client,
|
|
710
|
+
token: this.options.token,
|
|
711
|
+
onFrame: (frame) => {
|
|
712
|
+
this.onFrame(frame);
|
|
713
|
+
},
|
|
714
|
+
onFatal: (error) => {
|
|
715
|
+
this.fail(error);
|
|
716
|
+
},
|
|
717
|
+
});
|
|
718
|
+
try {
|
|
719
|
+
await connection.open();
|
|
720
|
+
return connection;
|
|
721
|
+
} catch {
|
|
722
|
+
return null;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** Wait before the next attempt; false when the subscription was closed. */
|
|
727
|
+
private async waitBeforeRetry(): Promise<boolean> {
|
|
728
|
+
if (this.isClosed) return false;
|
|
729
|
+
await this.pause.wait();
|
|
730
|
+
return !this.isClosed;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
private onFrame(frame: LiveFrame): void {
|
|
734
|
+
if (this.isClosed) return;
|
|
735
|
+
if (this.queue.length >= MAX_QUEUED_FRAMES) this.queue.shift(); // a slow reader loses the oldest frames
|
|
736
|
+
this.queue.push(frame);
|
|
737
|
+
this.wake();
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
private fail(error: Error): void {
|
|
741
|
+
if (this.failure !== null) return;
|
|
742
|
+
this.failure = error;
|
|
743
|
+
this.close();
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
private finish(): void {
|
|
747
|
+
if (this.finished) return;
|
|
748
|
+
this.finished = true;
|
|
749
|
+
this.options.onDone();
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
private closeConnection(): void {
|
|
753
|
+
const connection = this.connection;
|
|
754
|
+
this.connection = null;
|
|
755
|
+
connection?.close();
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
private wake(): void {
|
|
759
|
+
for (const resolve of this.waiters.splice(0)) resolve();
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
class Client implements NiwaApi {
|
|
764
|
+
readonly records: NiwaApi["records"];
|
|
765
|
+
|
|
766
|
+
readonly live: {
|
|
767
|
+
send(channel: string, frame: LiveFrame): Promise<void>;
|
|
768
|
+
subscribe(channel: string): LiveSubscription;
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
private readonly home: string;
|
|
772
|
+
private readonly client: ClientId;
|
|
773
|
+
private readonly token: Token | undefined;
|
|
774
|
+
private link: Promise<WireConnection>;
|
|
775
|
+
private readonly subscriptions = new Set<RecordSubscription>();
|
|
776
|
+
private readonly liveSubscriptions = new Set<ChannelSubscription>();
|
|
777
|
+
private isClosed = false;
|
|
778
|
+
|
|
779
|
+
constructor(home: string, client: ClientId, token: Token | undefined, connection: WireConnection) {
|
|
780
|
+
this.home = home;
|
|
781
|
+
this.client = client;
|
|
782
|
+
this.token = token;
|
|
783
|
+
this.link = Promise.resolve(connection);
|
|
784
|
+
this.records = {
|
|
785
|
+
since: (query?: RecordQuery<any>): RecordFeed => {
|
|
786
|
+
if (this.isClosed) throw new HostError(CLOSED_MESSAGE);
|
|
787
|
+
// A query the wire refuses is the caller's mistake: it is told now, not retried as a dropped socket.
|
|
788
|
+
const resolved = resolveQuery(query);
|
|
789
|
+
checkQuery(resolved);
|
|
790
|
+
const subscription = new RecordSubscription({
|
|
791
|
+
home: this.home,
|
|
792
|
+
client: this.client,
|
|
793
|
+
token: this.token,
|
|
794
|
+
query: resolved,
|
|
795
|
+
onDone: () => {
|
|
796
|
+
this.subscriptions.delete(subscription);
|
|
797
|
+
},
|
|
798
|
+
});
|
|
799
|
+
this.subscriptions.add(subscription);
|
|
800
|
+
return subscription.iterate();
|
|
801
|
+
},
|
|
802
|
+
read: async (query?: RecordReadQuery<any>): Promise<StoredRecord[]> => {
|
|
803
|
+
const resolved = resolveQuery(query);
|
|
804
|
+
const value = await this.request((id) => ({
|
|
805
|
+
id,
|
|
806
|
+
op: "read",
|
|
807
|
+
query: onWire(resolved),
|
|
808
|
+
...(query?.limit === undefined ? {} : { limit: query.limit }),
|
|
809
|
+
}));
|
|
810
|
+
return parseList(storedRecordSchema, value, "the records it was asked for");
|
|
811
|
+
},
|
|
812
|
+
};
|
|
813
|
+
this.live = {
|
|
814
|
+
send: async (channel: string, frame: LiveFrame): Promise<void> => {
|
|
815
|
+
const name = channelName(channel);
|
|
816
|
+
const data = frameFor(name, frame).data;
|
|
817
|
+
await this.request((id) => ({ id, op: "live.send", channel: name, data }));
|
|
818
|
+
},
|
|
819
|
+
subscribe: (channel: string): LiveSubscription => {
|
|
820
|
+
if (this.isClosed) throw new HostError(CLOSED_MESSAGE);
|
|
821
|
+
const name = channelName(channel);
|
|
822
|
+
const subscription = new ChannelSubscription({
|
|
823
|
+
home: this.home,
|
|
824
|
+
client: this.client,
|
|
825
|
+
token: this.token,
|
|
826
|
+
channel: name,
|
|
827
|
+
onDone: () => {
|
|
828
|
+
this.liveSubscriptions.delete(subscription);
|
|
829
|
+
},
|
|
830
|
+
});
|
|
831
|
+
this.liveSubscriptions.add(subscription);
|
|
832
|
+
subscription.start();
|
|
833
|
+
return subscription.iterate();
|
|
834
|
+
},
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Write an external input: it starts its own chain in the host's journal. With an explicit
|
|
840
|
+
* id the write is idempotent: the same content returns the committed record, different
|
|
841
|
+
* content is an integrity error.
|
|
842
|
+
*/
|
|
843
|
+
async emit<T>(type: RecordType<T>, data: T, opts?: EmitOptions): Promise<StoredRecord> {
|
|
844
|
+
const value = await this.request((id) => ({
|
|
845
|
+
id,
|
|
846
|
+
op: "emit",
|
|
847
|
+
type: type.name,
|
|
848
|
+
data,
|
|
849
|
+
...(opts?.id === undefined ? {} : { record: opts.id }),
|
|
850
|
+
...(opts?.links === undefined ? {} : { links: opts.links }),
|
|
851
|
+
}));
|
|
852
|
+
return parseReturned(storedRecordSchema, value, "the record it wrote");
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
async emitAll<const T extends readonly RecordType<any>[]>(entries: EmitBatch<T, EmitOptions>): Promise<StoredRecord[]> {
|
|
856
|
+
const value = await this.request(id => ({
|
|
857
|
+
id, op: "emitAll",
|
|
858
|
+
entries: entries.map(({type, data, opts}) => ({type: type.name, data, record: opts?.id, links: opts?.links})),
|
|
859
|
+
}));
|
|
860
|
+
return parseList(storedRecordSchema, value, "the records it wrote");
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Call an action by typed reference, by value or by name, outside any invocation: only its name is sent.
|
|
865
|
+
*
|
|
866
|
+
* The input is what the action's schema accepts, not what it produces: a branded or transformed
|
|
867
|
+
* field is sent as it is written down, and the host's schema does the rest.
|
|
868
|
+
*
|
|
869
|
+
* An `operation` id names the call for a retry after a lost connection. The host knows the caller
|
|
870
|
+
* again only by its token, so a client without one is refused an operation id before the action runs.
|
|
871
|
+
*/
|
|
872
|
+
async call<I, O, In = I>(action: ActionTarget<I, O, In>, input: NoInfer<In>, opts?: CallOptions): Promise<O> {
|
|
873
|
+
const name = targetName(action);
|
|
874
|
+
const reason = opts?.reason;
|
|
875
|
+
const operation = opts?.operation;
|
|
876
|
+
return (await this.request((id) => ({
|
|
877
|
+
id,
|
|
878
|
+
op: "call",
|
|
879
|
+
action: name,
|
|
880
|
+
input,
|
|
881
|
+
...(reason === undefined ? {} : { reason }),
|
|
882
|
+
...(operation === undefined ? {} : { operation }),
|
|
883
|
+
}))) as O;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** What niwa is: its actions and its record types, with their schemas. */
|
|
887
|
+
async describe(): Promise<Description> {
|
|
888
|
+
const value = await this.request((id) => ({ id, op: "describe" }));
|
|
889
|
+
return parseReturned(descriptionSchema, value, "the description");
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** Everything that grew from a record: down through causes and links. */
|
|
893
|
+
async trace(record: RecordId): Promise<TracedRecord[]> {
|
|
894
|
+
const value = await this.request((id) => ({ id, op: "trace", record }));
|
|
895
|
+
return parseList(tracedRecordSchema, value, "the trace it was asked for");
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** What a record depends on: up through its cause and its links. */
|
|
899
|
+
async causes(record: RecordId): Promise<StoredRecord[]> {
|
|
900
|
+
const value = await this.request((id) => ({ id, op: "causes", record }));
|
|
901
|
+
return parseList(storedRecordSchema, value, "the records it was asked for");
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** Close every connection. Pending calls reject; subscriptions end. */
|
|
905
|
+
async close(): Promise<void> {
|
|
906
|
+
if (this.isClosed) return;
|
|
907
|
+
this.isClosed = true;
|
|
908
|
+
for (const subscription of [...this.subscriptions]) subscription.close();
|
|
909
|
+
for (const subscription of [...this.liveSubscriptions]) subscription.close();
|
|
910
|
+
(await this.link.catch(() => undefined))?.close();
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
private async request(build: (id: number) => ClientMessageInput): Promise<unknown> {
|
|
914
|
+
return (await this.connection()).request(build);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** The call connection; a host that went away and came back gets a fresh one on the next call. */
|
|
918
|
+
private async connection(): Promise<WireConnection> {
|
|
919
|
+
if (this.isClosed) throw new HostError(CLOSED_MESSAGE);
|
|
920
|
+
const known = this.link;
|
|
921
|
+
const current = await known.catch(() => undefined);
|
|
922
|
+
if (current?.isOpen) return current;
|
|
923
|
+
if (this.link === known) this.link = openConnection(this.home, this.client, this.token);
|
|
924
|
+
const fresh = await this.link;
|
|
925
|
+
if (this.isClosed) {
|
|
926
|
+
fresh.close();
|
|
927
|
+
throw new HostError(CLOSED_MESSAGE);
|
|
928
|
+
}
|
|
929
|
+
return fresh;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
async function openConnection(home: string, client: ClientId, token: Token | undefined): Promise<WireConnection> {
|
|
934
|
+
const connection = new WireConnection({ home, client, token });
|
|
935
|
+
await connection.open();
|
|
936
|
+
return connection;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* Connect to a niwa host. The host must be running and listening on the socket of that
|
|
941
|
+
* home; the returned promise rejects when it is not reachable.
|
|
942
|
+
*
|
|
943
|
+
* Who the connection is comes from `token` alone: `id` is only
|
|
944
|
+
* a name for people. Without a token, or with one the host does not know, it is a plain client.
|
|
945
|
+
*/
|
|
946
|
+
export async function connect(opts: { home: string; id?: string; token?: Token }): Promise<NiwaApi> {
|
|
947
|
+
const client = (opts.id ?? `client-${crypto.randomUUID()}`) as ClientId;
|
|
948
|
+
return new Client(opts.home, client, opts.token, await openConnection(opts.home, client, opts.token));
|
|
949
|
+
}
|