@biolibs/bionet-client 0.0.0-stage → 0.1.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/README.md +77 -2
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/lab.d.ts +266 -0
- package/dist/lab.d.ts.map +1 -0
- package/dist/lab.js +372 -0
- package/dist/lab.js.map +1 -0
- package/dist/link.d.ts +83 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +228 -0
- package/dist/link.js.map +1 -0
- package/dist/source.d.ts +52 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +36 -0
- package/dist/source.js.map +1 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.d.ts.map +1 -0
- package/dist/sqlite.js +60 -0
- package/dist/sqlite.js.map +1 -0
- package/dist/store.d.ts +46 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +32 -0
- package/dist/store.js.map +1 -0
- package/package.json +48 -4
- package/src/index.ts +22 -0
- package/src/lab.ts +468 -0
- package/src/link.ts +240 -0
- package/src/source.ts +62 -0
- package/src/sqlite.ts +60 -0
- package/src/store.ts +59 -0
package/src/lab.ts
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One person's device in one lab: its key, what it holds, and everything it can do.
|
|
3
|
+
*
|
|
4
|
+
* This is a whole lab application without a window. It knows nothing of Electron, React or a
|
|
5
|
+
* browser, so the same class sits behind a desktop app, a web page or a test, and two of these and a
|
|
6
|
+
* web peer are a lab.
|
|
7
|
+
*
|
|
8
|
+
* Everything a member does becomes a signed entry in this device's own log, is kept, and is offered
|
|
9
|
+
* to the lab's web peer when there is one to offer it to. Nothing waits for the network. What the lab
|
|
10
|
+
* holds is worked out from the entries each time they change, by `mergeLog`, which is why two devices
|
|
11
|
+
* that have been apart agree the moment they have each other's entries.
|
|
12
|
+
*/
|
|
13
|
+
import { addItem, addPart, addToRoster, adjustItem, entryId, fetchInventory, foundLab, isMember, mergeLog,
|
|
14
|
+
newItemId, nextEntry, offerPart, publicInventory, recountItem, retireItem, setField, signInventory,
|
|
15
|
+
takeEntries, type EntryStatus, type ItemState, type LabState, type Operation, type Overlap,
|
|
16
|
+
type PartState, type Role, type RosterKey, type SignedEntry } from "@biolibs/bionet";
|
|
17
|
+
import { exportSigningKey, generateSigningKey, importSigningKey, keyFingerprint,
|
|
18
|
+
type SigningKey } from "@biolibs/opencloning";
|
|
19
|
+
import { PeerLink, type LinkStatus } from "./link.js";
|
|
20
|
+
import type { KeyKeeper, LabStore } from "./store.js";
|
|
21
|
+
|
|
22
|
+
/** One key on the roster, as a window shows it. */
|
|
23
|
+
export interface RosterView extends RosterKey {
|
|
24
|
+
/** The key's fingerprint, for a person to compare. */
|
|
25
|
+
fingerprint: string;
|
|
26
|
+
/** Whether it is this device's key. */
|
|
27
|
+
you: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One entry, as a window shows it. */
|
|
31
|
+
export interface EntryView {
|
|
32
|
+
id: string;
|
|
33
|
+
author: string;
|
|
34
|
+
seq: number;
|
|
35
|
+
op: Operation;
|
|
36
|
+
status: EntryStatus;
|
|
37
|
+
reason: string | null;
|
|
38
|
+
/** What the signer called themselves. A claim. */
|
|
39
|
+
signer: string | null;
|
|
40
|
+
/** When they say they signed. A claim. */
|
|
41
|
+
signedAt: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The lab, as a window shows it. */
|
|
45
|
+
export interface LabView {
|
|
46
|
+
id: string | null;
|
|
47
|
+
name: string | null;
|
|
48
|
+
/** Whether any of the lab has reached this device yet. */
|
|
49
|
+
arrived: boolean;
|
|
50
|
+
/** Whether this device's key is on the roster, so it may change the lab. */
|
|
51
|
+
member: boolean;
|
|
52
|
+
/** Whether it may change the roster as well. */
|
|
53
|
+
keeper: boolean;
|
|
54
|
+
roster: RosterView[];
|
|
55
|
+
parts: PartState[];
|
|
56
|
+
items: ItemState[];
|
|
57
|
+
overlaps: Overlap[];
|
|
58
|
+
/** How many entries are waiting on others that have not arrived. */
|
|
59
|
+
waiting: number;
|
|
60
|
+
entries: EntryView[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The connection to the lab's web peer, as a window shows it. */
|
|
64
|
+
export interface PeerView {
|
|
65
|
+
url: string | null;
|
|
66
|
+
/** The web address the lab's inventory is published at. */
|
|
67
|
+
origin: string | null;
|
|
68
|
+
/** What to send somebody who should join. */
|
|
69
|
+
invite: string | null;
|
|
70
|
+
status: LinkStatus;
|
|
71
|
+
problem: string | null;
|
|
72
|
+
/** How many changes made here the peer is not known to have. */
|
|
73
|
+
pending: number;
|
|
74
|
+
lastSynced: string | null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Everything a window needs to draw, as plain data. */
|
|
78
|
+
export interface LabSnapshot {
|
|
79
|
+
device: { key: string; fingerprint: string; person: string | null };
|
|
80
|
+
lab: LabView | null;
|
|
81
|
+
peer: PeerView;
|
|
82
|
+
/** When this device last published the lab's inventory. */
|
|
83
|
+
published: string | null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** What a device needs. */
|
|
87
|
+
export interface LabOptions {
|
|
88
|
+
/** Where to keep things. */
|
|
89
|
+
store: LabStore;
|
|
90
|
+
/** Where the device's key lives. */
|
|
91
|
+
keys: KeyKeeper;
|
|
92
|
+
/** Something to fetch the published inventory with. Defaults to the runtime's own `fetch`. */
|
|
93
|
+
fetch?: typeof globalThis.fetch;
|
|
94
|
+
/** Something to open sockets with. Defaults to the runtime's own `WebSocket`. */
|
|
95
|
+
WebSocket?: typeof globalThis.WebSocket;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** @param peer - The peer's socket address. @returns The web address it serves from. */
|
|
99
|
+
export function originOf(peer: string): string {
|
|
100
|
+
const url = new URL(peer);
|
|
101
|
+
return `${url.protocol === "ws:" ? "http:" : "https:"}//${url.host}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Read an invitation: the peer's address, then `#`, then the lab's ID.
|
|
106
|
+
*
|
|
107
|
+
* @param invite - What a keeper sent.
|
|
108
|
+
* @returns Where the lab's peer is, and which lab.
|
|
109
|
+
* @throws If it is not an invitation.
|
|
110
|
+
*/
|
|
111
|
+
export function readInvite(invite: string): { peer: string; lab: string } {
|
|
112
|
+
const [peer, lab] = invite.trim().split("#");
|
|
113
|
+
if (peer === undefined || lab === undefined || !/^[0-9a-f]{64}$/.test(lab)) {
|
|
114
|
+
throw new Error("That is not an invitation. One looks like wss://a-lab.example/sync#, followed by 64 letters and digits.");
|
|
115
|
+
}
|
|
116
|
+
const url = new URL(peer);
|
|
117
|
+
if (url.protocol !== "wss:" && url.protocol !== "ws:") throw new Error("An invitation's address starts with wss://.");
|
|
118
|
+
return { peer, lab };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const peerAddress = (peer: string | null | undefined): string | null => {
|
|
122
|
+
if (peer === null || peer === undefined || peer.trim() === "") return null;
|
|
123
|
+
const url = new URL(peer.trim());
|
|
124
|
+
if (url.protocol !== "wss:" && url.protocol !== "ws:") throw new Error("A peer's address starts with wss://.");
|
|
125
|
+
return peer.trim();
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* One device in one lab.
|
|
130
|
+
*
|
|
131
|
+
* Make one with somewhere to keep things and somewhere to keep the key, `open()` it, and it is a
|
|
132
|
+
* working lab application: it makes the device's key if there is none, works the lab out from what
|
|
133
|
+
* is held, and starts talking to the lab's peer if it has one.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { Lab, memoryKeys, memoryStore } from "@biolibs/bionet-client";
|
|
138
|
+
*
|
|
139
|
+
* const lab = await new Lab({ store: memoryStore(), keys: memoryKeys() }).open();
|
|
140
|
+
* await lab.setPerson("Ada");
|
|
141
|
+
* await lab.found({ name: "The Wren Lab" });
|
|
142
|
+
* lab.snapshot().lab?.keeper; // true
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
export class Lab {
|
|
146
|
+
private readonly store: LabStore;
|
|
147
|
+
private held: SignedEntry[] = [];
|
|
148
|
+
private state: LabState | null = null;
|
|
149
|
+
private link: PeerLink | null = null;
|
|
150
|
+
private key!: SigningKey;
|
|
151
|
+
private fingerprint = "";
|
|
152
|
+
private readonly fingerprints = new Map<string, string>();
|
|
153
|
+
private readonly listeners = new Set<() => void>();
|
|
154
|
+
private cached: LabSnapshot | null = null;
|
|
155
|
+
/** One change at a time, so two cannot both write the same place in the log. */
|
|
156
|
+
private turn: Promise<unknown> = Promise.resolve();
|
|
157
|
+
|
|
158
|
+
constructor(private readonly options: LabOptions) {
|
|
159
|
+
this.store = options.store;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Load or make the device's key, and work the lab out from what is held.
|
|
164
|
+
*
|
|
165
|
+
* @returns This, ready.
|
|
166
|
+
*/
|
|
167
|
+
async open(): Promise<this> {
|
|
168
|
+
let exported = await this.options.keys.load();
|
|
169
|
+
if (exported === null) {
|
|
170
|
+
exported = await exportSigningKey(await generateSigningKey());
|
|
171
|
+
await this.options.keys.save(exported);
|
|
172
|
+
}
|
|
173
|
+
this.key = await importSigningKey(exported);
|
|
174
|
+
this.fingerprint = await keyFingerprint(this.key.publicKey);
|
|
175
|
+
this.held = this.store.entries();
|
|
176
|
+
await this.remerge();
|
|
177
|
+
this.connect();
|
|
178
|
+
return this;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Be told whenever anything a window would draw has changed.
|
|
183
|
+
*
|
|
184
|
+
* @param listener - Called with nothing; ask `snapshot()` for what is new.
|
|
185
|
+
* @returns A function that stops the telling.
|
|
186
|
+
*/
|
|
187
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
188
|
+
this.listeners.add(listener);
|
|
189
|
+
return () => { this.listeners.delete(listener); };
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Everything a window needs to draw, as plain data. The same object is returned until something
|
|
194
|
+
* changes, so it can be compared by identity.
|
|
195
|
+
*/
|
|
196
|
+
snapshot = (): LabSnapshot => {
|
|
197
|
+
if (this.cached !== null) return this.cached;
|
|
198
|
+
const state = this.state;
|
|
199
|
+
const mine = this.key.publicKey;
|
|
200
|
+
const me = state?.roster.find((one) => one.key === mine && one.removed === null);
|
|
201
|
+
const peer = this.store.setting("peer");
|
|
202
|
+
this.cached = {
|
|
203
|
+
device: { key: mine, fingerprint: this.fingerprint, person: this.person },
|
|
204
|
+
lab: state === null ? null : {
|
|
205
|
+
id: state.lab,
|
|
206
|
+
name: state.name,
|
|
207
|
+
arrived: state.roster.length > 0,
|
|
208
|
+
member: me !== undefined,
|
|
209
|
+
keeper: me?.role === "keeper",
|
|
210
|
+
roster: state.roster.map((one) => ({ ...one, fingerprint: this.fingerprints.get(one.key) ?? "", you: one.key === mine })),
|
|
211
|
+
parts: state.parts,
|
|
212
|
+
items: state.items,
|
|
213
|
+
overlaps: state.overlaps,
|
|
214
|
+
waiting: state.waiting.length,
|
|
215
|
+
entries: state.entries.map((one) => ({
|
|
216
|
+
id: one.id, author: one.signed.entry.author, seq: one.signed.entry.seq, op: one.signed.entry.op,
|
|
217
|
+
status: one.status, reason: one.reason, signer: one.signed.signature.signer, signedAt: one.signed.signature.signed_at,
|
|
218
|
+
})),
|
|
219
|
+
},
|
|
220
|
+
peer: {
|
|
221
|
+
url: peer,
|
|
222
|
+
origin: this.origin,
|
|
223
|
+
invite: this.invite,
|
|
224
|
+
status: this.link?.status ?? "offline",
|
|
225
|
+
problem: this.link?.problem ?? null,
|
|
226
|
+
pending: this.link?.pending ?? 0,
|
|
227
|
+
lastSynced: this.link?.lastSynced ?? null,
|
|
228
|
+
},
|
|
229
|
+
published: this.store.setting("published"),
|
|
230
|
+
};
|
|
231
|
+
return this.cached;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** The lab this device is in, or `null`. */
|
|
235
|
+
get labId(): string | null { return this.store.setting("lab"); }
|
|
236
|
+
|
|
237
|
+
/** What the person at this device is called, or `null` if they have not said. */
|
|
238
|
+
get person(): string | null { return this.store.setting("person"); }
|
|
239
|
+
|
|
240
|
+
/** The web address the lab's inventory is published at. */
|
|
241
|
+
get origin(): string | null {
|
|
242
|
+
const peer = this.store.setting("peer");
|
|
243
|
+
return this.store.setting("origin") ?? (peer === null ? null : originOf(peer));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** What to send somebody who should join, or `null` if the lab has no peer to join through. */
|
|
247
|
+
get invite(): string | null {
|
|
248
|
+
const peer = this.store.setting("peer");
|
|
249
|
+
return this.labId === null || peer === null ? null : `${peer}#${this.labId}`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** @param name - What to call the person at this device. */
|
|
253
|
+
async setPerson(name: string): Promise<void> {
|
|
254
|
+
if (name.trim() === "") throw new Error("A name, so that the lab can see who made each change.");
|
|
255
|
+
this.store.set("person", name.trim().slice(0, 200));
|
|
256
|
+
this.changed();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Found a lab on this device. It works straight away, with or without a peer.
|
|
261
|
+
*
|
|
262
|
+
* @param about - What the lab is called, and its peer's address if it has one yet.
|
|
263
|
+
*/
|
|
264
|
+
async found(about: { name: string; peer?: string | null }): Promise<void> {
|
|
265
|
+
if (this.labId !== null) throw new Error("This device is already in a lab.");
|
|
266
|
+
if (this.person === null) throw new Error("Say who you are first.");
|
|
267
|
+
if (about.name.trim() === "") throw new Error("A lab needs a name.");
|
|
268
|
+
const peer = peerAddress(about.peer);
|
|
269
|
+
const founding = await foundLab(this.key, { name: about.name.trim().slice(0, 200), person: this.person });
|
|
270
|
+
const id = await entryId(founding.entry);
|
|
271
|
+
this.store.add([{ id, signed: founding }]);
|
|
272
|
+
this.held.push(founding);
|
|
273
|
+
this.store.set("lab", id);
|
|
274
|
+
this.store.set("peer", peer);
|
|
275
|
+
await this.remerge();
|
|
276
|
+
this.connect();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Join a lab somebody else founded. Nothing arrives until a keeper has added this device's key.
|
|
281
|
+
*
|
|
282
|
+
* @param invite - The invitation a keeper sent.
|
|
283
|
+
*/
|
|
284
|
+
async join(invite: string): Promise<void> {
|
|
285
|
+
if (this.labId !== null) throw new Error("This device is already in a lab.");
|
|
286
|
+
if (this.person === null) throw new Error("Say who you are first.");
|
|
287
|
+
const { peer, lab } = readInvite(invite);
|
|
288
|
+
this.store.set("lab", lab);
|
|
289
|
+
this.store.set("peer", peer);
|
|
290
|
+
await this.remerge();
|
|
291
|
+
this.connect();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** @param peer - The lab's peer, or `null` to work with none. */
|
|
295
|
+
async setPeer(peer: string | null): Promise<void> {
|
|
296
|
+
this.store.set("peer", peerAddress(peer));
|
|
297
|
+
this.connect();
|
|
298
|
+
this.changed();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** @param origin - The web address the lab publishes from, if it is not the peer's own. */
|
|
302
|
+
async setOrigin(origin: string | null): Promise<void> {
|
|
303
|
+
this.store.set("origin", origin === null || origin.trim() === "" ? null : origin.trim());
|
|
304
|
+
this.changed();
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Stop talking to the peer, until `goOnline`. The device goes on working. */
|
|
308
|
+
goOffline(): void { this.link?.stop(); }
|
|
309
|
+
|
|
310
|
+
/** Start talking to the peer again. */
|
|
311
|
+
goOnline(): void { this.link?.start(); }
|
|
312
|
+
|
|
313
|
+
/** Add a device's key to the lab. Only a keeper may. */
|
|
314
|
+
addMember(who: { key: string; person: string; role?: Role }): Promise<void> {
|
|
315
|
+
return this.write(addToRoster(who.key.trim(), who.person.trim(), who.role ?? "member"));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Add a part, by its sequence. */
|
|
319
|
+
async addPart(part: { name: string; sequence: string; circular?: boolean }): Promise<void> {
|
|
320
|
+
const bases = part.sequence.replace(/\s+/g, "");
|
|
321
|
+
// The library underneath accepts any letters as a sequence. A freezer should not: a part named
|
|
322
|
+
// by a checksum of the wrong letters is a part nobody else will ever match.
|
|
323
|
+
if (!/^[ACGTURYSWKMBDHVN]+$/i.test(bases)) {
|
|
324
|
+
throw new Error("A sequence is written in the letters for bases: A, C, G, T, and the codes for an uncertain base.");
|
|
325
|
+
}
|
|
326
|
+
return this.write(addPart({ name: part.name.trim(), sequence: bases, circular: part.circular === true }));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Add one physical item of a part. @returns The new item's ID. */
|
|
330
|
+
async addItem(item: { part: string; amount: number; unit?: string | null }): Promise<string> {
|
|
331
|
+
const id = newItemId();
|
|
332
|
+
await this.write(addItem({ item: id, part: item.part, amount: item.amount, unit: item.unit === "" ? null : item.unit ?? null }));
|
|
333
|
+
return id;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Add to or take from an item. `by` is a whole-number difference. */
|
|
337
|
+
adjust(change: { item: string; by: number }): Promise<void> { return this.write(adjustItem(change.item, change.by)); }
|
|
338
|
+
|
|
339
|
+
/** Say how much of an item is physically there. */
|
|
340
|
+
recount(count: { item: string; amount: number }): Promise<void> { return this.write(recountItem(count.item, count.amount)); }
|
|
341
|
+
|
|
342
|
+
/** Retire an item. It stays in the history. */
|
|
343
|
+
retire(which: { item: string }): Promise<void> { return this.write(retireItem(which.item)); }
|
|
344
|
+
|
|
345
|
+
/** Say whether a part is on offer to other labs. */
|
|
346
|
+
offer(offer: { part: string; available: boolean }): Promise<void> { return this.write(offerPart(offer.part, offer.available)); }
|
|
347
|
+
|
|
348
|
+
/** Set one field on a part (by checksum) or an item (by ID). */
|
|
349
|
+
setField(change: { on: "part" | "item"; id: string; field: string; value: string | number | null }): Promise<void> {
|
|
350
|
+
return this.write(setField(change.on, change.id, change.field, change.value));
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Make one change: sign it into this device's log, keep it, and offer it to the peer.
|
|
355
|
+
*
|
|
356
|
+
* The change is tried before it is kept. A log is forever, so an entry the lab would refuse — a
|
|
357
|
+
* sequence that is not one, an item that does not exist — is turned down here, with the reason,
|
|
358
|
+
* and never written.
|
|
359
|
+
*
|
|
360
|
+
* @param op - The change.
|
|
361
|
+
* @throws If this device may not change the lab, or the lab would refuse the change.
|
|
362
|
+
*/
|
|
363
|
+
write(op: Operation): Promise<void> {
|
|
364
|
+
return this.inTurn(async () => {
|
|
365
|
+
const state = this.state;
|
|
366
|
+
if (state === null || state.lab === null) throw new Error("This device is not in a lab yet.");
|
|
367
|
+
if (!isMember(state, this.key.publicKey)) {
|
|
368
|
+
throw new Error("This device's key is not on the lab's roster, so it cannot change the lab.");
|
|
369
|
+
}
|
|
370
|
+
const signed = await nextEntry(state, this.key, op, { signer: this.person });
|
|
371
|
+
const id = await entryId(signed.entry);
|
|
372
|
+
const tried = (await mergeLog([...this.held, signed], { lab: state.lab })).entries.find((one) => one.id === id);
|
|
373
|
+
if (tried?.status !== "applied") throw new Error(tried?.reason ?? "The lab would not accept that change.");
|
|
374
|
+
this.store.add([{ id, signed }]);
|
|
375
|
+
this.held.push(signed);
|
|
376
|
+
await this.remerge();
|
|
377
|
+
this.link?.push();
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Take entries that arrived from somewhere else.
|
|
383
|
+
*
|
|
384
|
+
* @param incoming - What arrived.
|
|
385
|
+
* @returns How many were kept.
|
|
386
|
+
*/
|
|
387
|
+
take(incoming: readonly unknown[]): Promise<number> {
|
|
388
|
+
return this.inTurn(async () => {
|
|
389
|
+
const lab = this.labId;
|
|
390
|
+
if (lab === null) return 0;
|
|
391
|
+
const { kept } = await takeEntries(lab, this.held, incoming);
|
|
392
|
+
if (kept.length === 0) return 0;
|
|
393
|
+
this.store.add(await Promise.all(kept.map(async (signed) => ({ id: await entryId(signed.entry), signed }))));
|
|
394
|
+
this.held.push(...kept);
|
|
395
|
+
await this.remerge();
|
|
396
|
+
return kept.length;
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Publish what the lab shows the world: sign the public inventory and hand it to the peer.
|
|
402
|
+
*
|
|
403
|
+
* The lab keeps pointing at whichever labs its published inventory already points at.
|
|
404
|
+
*
|
|
405
|
+
* @returns Whether it was published, why not if not, and how many parts it listed.
|
|
406
|
+
*/
|
|
407
|
+
async publish(): Promise<{ ok: boolean; reason: string | null; parts: number }> {
|
|
408
|
+
const origin = this.origin;
|
|
409
|
+
if (this.state === null || this.link === null || origin === null) {
|
|
410
|
+
return { ok: false, reason: "The lab has no peer to publish through.", parts: 0 };
|
|
411
|
+
}
|
|
412
|
+
let peers;
|
|
413
|
+
try {
|
|
414
|
+
peers = (await fetchInventory(origin, { timeoutMs: 6_000, ...(this.options.fetch === undefined ? {} : { fetch: this.options.fetch }) })).signed.inventory.peers;
|
|
415
|
+
} catch {
|
|
416
|
+
peers = undefined; // nothing published yet, or unreachable: publish without pointers
|
|
417
|
+
}
|
|
418
|
+
const inventory = publicInventory(this.state, { name: this.state.name ?? "A lab", origin, contact: null, note: null },
|
|
419
|
+
peers === undefined ? {} : { peers });
|
|
420
|
+
const signed = await signInventory(inventory, this.key, { signer: this.person });
|
|
421
|
+
const answer = await this.link.publish(signed);
|
|
422
|
+
if (answer.ok) {
|
|
423
|
+
this.store.set("published", inventory.published_at);
|
|
424
|
+
this.changed();
|
|
425
|
+
}
|
|
426
|
+
return { ...answer, parts: inventory.parts.length };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Stop talking to the peer and finish with the store. */
|
|
430
|
+
close(): void {
|
|
431
|
+
this.link?.stop();
|
|
432
|
+
this.link = null;
|
|
433
|
+
this.store.close();
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
private changed(): void {
|
|
437
|
+
this.cached = null;
|
|
438
|
+
for (const listener of this.listeners) listener();
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private async remerge(): Promise<void> {
|
|
442
|
+
const lab = this.labId;
|
|
443
|
+
this.state = lab === null ? null : await mergeLog(this.held, { lab });
|
|
444
|
+
for (const one of this.state?.roster ?? []) {
|
|
445
|
+
if (!this.fingerprints.has(one.key)) this.fingerprints.set(one.key, await keyFingerprint(one.key));
|
|
446
|
+
}
|
|
447
|
+
this.changed();
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
private connect(): void {
|
|
451
|
+
this.link?.stop();
|
|
452
|
+
this.link = null;
|
|
453
|
+
const lab = this.labId;
|
|
454
|
+
const url = this.store.setting("peer");
|
|
455
|
+
if (lab === null || url === null) return;
|
|
456
|
+
this.link = new PeerLink({
|
|
457
|
+
url, lab, key: this.key, held: () => this.held, take: (entries) => this.take(entries), onChange: () => this.changed(),
|
|
458
|
+
...(this.options.WebSocket === undefined ? {} : { WebSocket: this.options.WebSocket }),
|
|
459
|
+
});
|
|
460
|
+
this.link.start();
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private inTurn<T>(work: () => Promise<T>): Promise<T> {
|
|
464
|
+
const next = this.turn.then(work, work);
|
|
465
|
+
this.turn = next.catch(() => {});
|
|
466
|
+
return next;
|
|
467
|
+
}
|
|
468
|
+
}
|