@biolibs/bionet 1.1.0 → 1.2.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/src/merge.ts ADDED
@@ -0,0 +1,605 @@
1
+ /**
2
+ * What a lab holds, worked out from every key's log together.
3
+ *
4
+ * Nothing here is stored state. Give `mergeLog` the entries and it returns the lab: who is on the
5
+ * roster, which parts and items there are, how much of each. Give it the same entries in any order,
6
+ * on any machine, and it returns the same lab — that is the whole point, because two people who have
7
+ * been offline for a week have to agree the moment their laptops meet, without either being in charge.
8
+ *
9
+ * The rules it applies were each chosen for what goes wrong without them:
10
+ *
11
+ * - **Order comes from what an entry had seen**, never from a clock. A change counts as later than
12
+ * another only if its author held the other when they made it.
13
+ * - **Amounts are differences.** Two people each using a tube while offline are two uses, not one
14
+ * overwriting the other. A recount says what is physically there and replaces only the adjustments
15
+ * its author had seen. Amounts are whole numbers of the item's unit, so that they have one spelling
16
+ * to sign and add up exactly; a lab that needs finer than a microlitre counts in something smaller.
17
+ * - **A removal names a cutoff.** The entry that removes a key says the last entry of that key's log
18
+ * the lab accepts, so somebody removed cannot add to the lab afterwards by claiming not to have
19
+ * heard. What they wrote past the cutoff is kept, set aside, and shown.
20
+ * - **When two changes truly overlap, the lower entry ID wins**, and the overlap is reported. It is
21
+ * the same choice on every machine and nobody can arrange it in advance.
22
+ * - **Between keepers, the one who has been a keeper longer is heard first.**
23
+ *
24
+ * It refuses quietly. An entry that is not allowed is still placed, with its status and the reason,
25
+ * because the people in the lab need to see what was turned away and why.
26
+ */
27
+ import { Dseqrecord } from "@biolibs/dseqrecord";
28
+ import type { SignOptions, SigningKey } from "@biolibs/opencloning";
29
+ import { entryId, readEntry, verifyEntry, writeEntry, type Operation, type Role,
30
+ type SignedEntry } from "./log.js";
31
+ import { INVENTORY_VERSION, type InventoryDocument, type InventoryPart, type LabModel,
32
+ type PeerModel } from "./model.js";
33
+
34
+ /** The longest sequence one part may have. */
35
+ export const LONGEST_SEQUENCE = 500_000;
36
+
37
+ /** One key on the roster, now or once. */
38
+ export interface RosterKey {
39
+ /** The key, 32 bytes in base64url. */
40
+ key: string;
41
+ /** Whose device it is. A claim made by whoever added it. */
42
+ person: string;
43
+ /** What it may do. */
44
+ role: Role;
45
+ /** Whether this is the key that founded the lab. */
46
+ founder: boolean;
47
+ /** The entry that put it on the roster. */
48
+ added: string;
49
+ /** If it was removed: by which entry, and the last `seq` of its log the lab accepts. */
50
+ removed: { by: string; cutoff: number } | null;
51
+ }
52
+
53
+ /** One part the lab knows of. */
54
+ export interface PartState {
55
+ /** Its checksum, which is its identity. */
56
+ checksum: string;
57
+ /** Its bases. */
58
+ sequence: string;
59
+ /** Whether it is a circle. */
60
+ circular: boolean;
61
+ /** How long it is. */
62
+ length: number;
63
+ /** What the lab calls it. */
64
+ name: string;
65
+ /** Whether it is on offer to other labs. Nothing is until somebody says so. */
66
+ offered: boolean;
67
+ /** Anything else set on it. */
68
+ fields: Record<string, string | number | null>;
69
+ /** The entry that added it. */
70
+ added: string;
71
+ }
72
+
73
+ /** One physical item: a tube, a prep. */
74
+ export interface ItemState {
75
+ /** Its ID. */
76
+ item: string;
77
+ /** The checksum of the part it is an item of. */
78
+ part: string;
79
+ /** What one of its amount is, if anybody said: a tube, a microlitre. */
80
+ unit: string | null;
81
+ /** How much there is, by the log. Always a whole number of the unit. */
82
+ amount: number;
83
+ /** Whether it has been retired. */
84
+ retired: boolean;
85
+ /** Whether the log has lost track: the amount went below zero, or two recounts overlapped. */
86
+ needsRecount: boolean;
87
+ /** Anything else set on it. */
88
+ fields: Record<string, string | number | null>;
89
+ /** The entry that added it. */
90
+ added: string;
91
+ }
92
+
93
+ /** What became of one entry. */
94
+ export type EntryStatus = "applied" | "set aside" | "refused" | "not understood";
95
+
96
+ /** One entry, in the order the merge settled on, with what became of it. */
97
+ export interface Placed {
98
+ /** Its ID. */
99
+ id: string;
100
+ /** The entry. */
101
+ signed: SignedEntry;
102
+ /** Whether it counted. */
103
+ status: EntryStatus;
104
+ /** Why not, if not. */
105
+ reason: string | null;
106
+ }
107
+
108
+ /** An entry that could not be placed, or was not looked at further. */
109
+ export interface Unplaced {
110
+ /** What arrived. */
111
+ signed: unknown;
112
+ /** Why it is not in the lab. */
113
+ reason: string;
114
+ }
115
+
116
+ /** Two changes made without knowledge of each other, where only one could stand. */
117
+ export interface Overlap {
118
+ /** What they were both about. */
119
+ what: string;
120
+ /** The entry that stood. */
121
+ kept: string;
122
+ /** The entry that did not. */
123
+ dropped: string;
124
+ }
125
+
126
+ /** A lab, as its logs describe it. */
127
+ export interface LabState {
128
+ /** The lab's ID, or `null` if no founding entry was among the entries. */
129
+ lab: string | null;
130
+ /** What its founder called it. */
131
+ name: string | null;
132
+ /** Every key that is or was on the roster. */
133
+ roster: RosterKey[];
134
+ /** Every part. */
135
+ parts: PartState[];
136
+ /** Every item. */
137
+ items: ItemState[];
138
+ /** Every entry that could be placed, in order, with what became of it. */
139
+ entries: Placed[];
140
+ /** Entries that are waiting on others that have not arrived. */
141
+ waiting: Unplaced[];
142
+ /** Entries that were thrown out before they were placed: unreadable, badly signed, another lab's. */
143
+ discarded: Unplaced[];
144
+ /** Changes that overlapped. */
145
+ overlaps: Overlap[];
146
+ /** The latest placed entry in each key's log. */
147
+ heads: Record<string, { seq: number; id: string }>;
148
+ /** For each key, how far into every log its latest entry had seen. */
149
+ knows: Record<string, Record<string, number>>;
150
+ }
151
+
152
+ /** An entry inside the merge. */
153
+ interface Node {
154
+ id: string;
155
+ signed: SignedEntry;
156
+ author: string;
157
+ seq: number;
158
+ op: Operation;
159
+ /** How far into each log this entry had seen, itself included. Set when it is placed. */
160
+ vc: Map<string, number>;
161
+ }
162
+
163
+ const KEY = /^[A-Za-z0-9_-]{43}$/;
164
+ const ITEM_ID = /^[A-Za-z0-9_-]{1,80}$/;
165
+ const FIELD = /^[a-z][a-z0-9_]{0,59}$/;
166
+ const RESERVED = new Set(["amount", "part", "item", "checksum", "sequence", "circular", "length", "offered", "retired"]);
167
+
168
+ const text = (value: unknown, most: number): value is string =>
169
+ typeof value === "string" && value.length > 0 && value.length <= most;
170
+ /** An amount is a whole number of the item's unit: only whole numbers have one agreed spelling to sign. */
171
+ const amountOf = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value);
172
+ const role = (value: unknown): value is Role => value === "member" || value === "keeper";
173
+
174
+ /** Whether `later` was written by somebody who held `earlier`. */
175
+ const hadSeen = (later: Node, earlier: Node): boolean => (later.vc.get(earlier.author) ?? -1) >= earlier.seq;
176
+
177
+ /**
178
+ * Work a lab out from its entries.
179
+ *
180
+ * @param entries - Every entry held, from every key, in any order. Duplicates are harmless.
181
+ * @param options - `lab` says which lab to build, when entries from more than one may be present.
182
+ * @returns The lab. It is the same for the same set of entries, whatever order they came in.
183
+ * @throws If the entries found more than one lab and `options.lab` does not say which is meant.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { adjustItem, mergeLog, nextEntry } from "@biolibs/bionet";
188
+ *
189
+ * const lab = await mergeLog(everyEntryHeld);
190
+ * lab.items.find((one) => one.item === tube)?.amount; // 9
191
+ *
192
+ * const used = await nextEntry(lab, key, adjustItem(tube, -1));
193
+ * (await mergeLog([...everyEntryHeld, used])).items.find((one) => one.item === tube)?.amount; // 8
194
+ * ```
195
+ */
196
+ export async function mergeLog(entries: readonly unknown[], options: { lab?: string } = {}): Promise<LabState> {
197
+ const state: LabState = { lab: options.lab ?? null, name: null, roster: [], parts: [], items: [], entries: [],
198
+ waiting: [], discarded: [], overlaps: [], heads: {}, knows: {} };
199
+
200
+ // Read and check every entry on its own, before any of them is believed about the others.
201
+ const nodes = new Map<string, Node>();
202
+ for (const value of entries) {
203
+ let signed: SignedEntry;
204
+ try {
205
+ signed = readEntry(value);
206
+ } catch (cause) {
207
+ state.discarded.push({ signed: value, reason: cause instanceof Error ? cause.message : String(cause) });
208
+ continue;
209
+ }
210
+ const id = await entryId(signed.entry);
211
+ if (nodes.has(id)) continue;
212
+ const check = await verifyEntry(signed);
213
+ if (!check.ok) {
214
+ state.discarded.push({ signed, reason: check.problem ?? "Its signature does not hold." });
215
+ continue;
216
+ }
217
+ nodes.set(id, { id, signed, author: signed.entry.author, seq: signed.entry.seq, op: signed.entry.op, vc: new Map() });
218
+ }
219
+
220
+ // Which lab. A founding entry is the only kind with no lab, and its ID is the lab's.
221
+ const foundings = [...nodes.values()].filter((node) => node.signed.entry.lab === null);
222
+ if (options.lab === undefined && foundings.length > 1) {
223
+ throw new Error("These entries found more than one lab. Say which lab is meant.");
224
+ }
225
+ const founding = options.lab === undefined ? foundings[0] : foundings.find((node) => node.id === options.lab);
226
+ if (founding === undefined) {
227
+ for (const node of nodes.values()) state.waiting.push({ signed: node.signed, reason: "The lab's founding entry has not arrived." });
228
+ return state;
229
+ }
230
+ state.lab = founding.id;
231
+
232
+ // One chain per key: each entry must follow the one before it, and a key may say only one thing
233
+ // at each place in its log.
234
+ const byAuthor = new Map<string, Map<number, Node[]>>();
235
+ for (const node of nodes.values()) {
236
+ if (node !== founding && node.signed.entry.lab !== state.lab) {
237
+ state.discarded.push({ signed: node.signed, reason: "It was written for another lab." });
238
+ continue;
239
+ }
240
+ const log = byAuthor.get(node.author) ?? new Map<number, Node[]>();
241
+ log.set(node.seq, [...(log.get(node.seq) ?? []), node]);
242
+ byAuthor.set(node.author, log);
243
+ }
244
+ const chains = new Map<string, Node[]>();
245
+ const chained = new Map<string, Node>();
246
+ for (const [author, log] of byAuthor) {
247
+ const chain: Node[] = [];
248
+ for (let seq = 0; log.has(seq); seq++) {
249
+ const before = chain[seq - 1];
250
+ const here = log.get(seq)!;
251
+ const follows = here.filter((node) => node.signed.entry.prev === (before?.id ?? null))
252
+ .sort((a, b) => (a === founding ? -1 : b === founding ? 1 : a.id < b.id ? -1 : 1));
253
+ for (const node of here) {
254
+ if (!follows.includes(node)) state.discarded.push({ signed: node.signed, reason: "It does not follow the entry before it in its own log." });
255
+ }
256
+ for (const node of follows.slice(1)) {
257
+ state.discarded.push({ signed: node.signed, reason: "It is a second entry at the same place in its key's log." });
258
+ }
259
+ if (follows.length === 0) break;
260
+ chain.push(follows[0]!);
261
+ chained.set(follows[0]!.id, follows[0]!);
262
+ }
263
+ for (const [seq, here] of log) {
264
+ if (seq >= chain.length) {
265
+ for (const node of here) {
266
+ if (!state.discarded.some((one) => one.signed === node.signed)) {
267
+ state.waiting.push({ signed: node.signed, reason: "An earlier entry in the same log has not arrived." });
268
+ }
269
+ }
270
+ }
271
+ }
272
+ chains.set(author, chain);
273
+ }
274
+
275
+ // Place the entries, and settle the roster while doing it. Whether an entry counts can depend on
276
+ // a removal placed after it, so this is repeated with the cutoffs it found until they stop changing.
277
+ let cuts = new Map<string, number>();
278
+ let walked = walk(founding, chains, chained, cuts);
279
+ for (let round = 0; round < 8 && !sameCuts(cuts, walked.cuts); round++) {
280
+ cuts = walked.cuts;
281
+ walked = walk(founding, chains, chained, cuts);
282
+ }
283
+
284
+ state.name = text(founding.op["name"], 200) ? founding.op["name"] : null;
285
+ state.roster = [...walked.roster.values()];
286
+ state.entries = walked.placed;
287
+ for (const [author, chain] of chains) {
288
+ const last = chain.filter((node) => walked.reached.has(node.id)).at(-1);
289
+ if (last !== undefined) {
290
+ state.heads[author] = { seq: last.seq, id: last.id };
291
+ state.knows[author] = Object.fromEntries(last.vc);
292
+ }
293
+ for (const node of chain) {
294
+ if (!walked.reached.has(node.id)) {
295
+ state.waiting.push({ signed: node.signed, reason: "It had seen an entry that has not arrived." });
296
+ }
297
+ }
298
+ }
299
+
300
+ fold(state, walked.placed, chained);
301
+ return state;
302
+ }
303
+
304
+ /** Whether two sets of cutoffs are the same. */
305
+ function sameCuts(a: Map<string, number>, b: Map<string, number>): boolean {
306
+ return a.size === b.size && [...a].every(([key, cutoff]) => b.get(key) === cutoff);
307
+ }
308
+
309
+ /**
310
+ * Put the chained entries in an order every machine agrees on, and settle the roster on the way.
311
+ *
312
+ * An entry is ready once the entry before it and everything it had seen are placed. Of the ready
313
+ * ones, a roster change by a keeper goes first, the longest-standing keeper before the others; after
314
+ * those, the lowest entry ID.
315
+ */
316
+ function walk(founding: Node, chains: Map<string, Node[]>, chained: Map<string, Node>, cuts: Map<string, number>): {
317
+ placed: Placed[]; roster: Map<string, RosterKey>; cuts: Map<string, number>; reached: Set<string>;
318
+ } {
319
+ const placed: Placed[] = [];
320
+ const roster = new Map<string, RosterKey>();
321
+ const found = new Map<string, number>();
322
+ const reached = new Set<string>();
323
+ const at = new Map<string, number>();
324
+ const since = new Map<string, number>(); // when each key became a keeper, as a count
325
+ const isKeeper = (key: string): boolean => roster.get(key)?.role === "keeper";
326
+ const liveKeepers = (): number => [...roster.values()].filter((one) => one.role === "keeper" && one.removed === null).length;
327
+
328
+ const ready = (): Node[] => {
329
+ const out: Node[] = [];
330
+ for (const [author, chain] of chains) {
331
+ const node = chain[at.get(author) ?? 0];
332
+ if (node === undefined) continue;
333
+ const seen = Object.entries(node.signed.entry.seen);
334
+ if (seen.every(([key, id]) => reached.has(id) && chained.get(id)?.author === key)) out.push(node);
335
+ }
336
+ return out;
337
+ };
338
+ const rank = (node: Node): number =>
339
+ node.op.type.startsWith("roster.") && isKeeper(node.author) ? (since.get(node.author) ?? 0) : Number.MAX_SAFE_INTEGER;
340
+
341
+ for (let next = ready(); next.length > 0; next = ready()) {
342
+ next.sort((a, b) => rank(a) - rank(b) || (a.id < b.id ? -1 : 1));
343
+ const node = next[0]!;
344
+ at.set(node.author, (at.get(node.author) ?? 0) + 1);
345
+ reached.add(node.id);
346
+
347
+ // What this entry had seen: what the one before it had, what it names, and itself.
348
+ const before = chains.get(node.author)![node.seq - 1];
349
+ node.vc = new Map(before?.vc ?? []);
350
+ for (const id of Object.values(node.signed.entry.seen)) {
351
+ for (const [key, seq] of chained.get(id)!.vc) node.vc.set(key, Math.max(node.vc.get(key) ?? -1, seq));
352
+ }
353
+ node.vc.set(node.author, node.seq);
354
+
355
+ const say = (status: EntryStatus, reason: string | null = null): void => {
356
+ placed.push({ id: node.id, signed: node.signed, status, reason });
357
+ };
358
+ const op = node.op;
359
+
360
+ if (node === founding) {
361
+ roster.set(node.author, { key: node.author, person: text(op["person"], 200) ? op["person"] : "",
362
+ role: "keeper", founder: true, added: node.id, removed: null });
363
+ since.set(node.author, since.size);
364
+ say("applied");
365
+ continue;
366
+ }
367
+ const author = roster.get(node.author);
368
+ if (author === undefined) { say("refused", "Its key is not on the lab's roster."); continue; }
369
+ if (!hadSeen(node, chained.get(author.added)!)) { say("refused", "It was written before its key had seen itself added to the roster."); continue; }
370
+ const cut = cuts.get(node.author);
371
+ if (cut !== undefined && node.seq > cut) { say("set aside", "It comes after the point at which its key was removed."); continue; }
372
+
373
+ if (!op.type.startsWith("roster.")) {
374
+ say("applied"); // whether the change itself makes sense is settled when the inventory is folded
375
+ continue;
376
+ }
377
+ if (author.role !== "keeper") { say("refused", "Only a keeper may change the roster."); continue; }
378
+
379
+ if (op.type === "roster.add") {
380
+ if (!(typeof op["key"] === "string" && KEY.test(op["key"])) || !text(op["person"], 200) || !role(op["role"])) {
381
+ say("refused", "It does not say which key to add, whose it is, or as what.");
382
+ } else if (roster.has(op["key"])) {
383
+ say("refused", "That key is already on the roster, or was removed from it.");
384
+ } else {
385
+ roster.set(op["key"], { key: op["key"], person: op["person"], role: op["role"], founder: false, added: node.id, removed: null });
386
+ if (op["role"] === "keeper") since.set(op["key"], since.size);
387
+ say("applied");
388
+ }
389
+ } else if (op.type === "roster.remove") {
390
+ const target = typeof op["key"] === "string" ? roster.get(op["key"]) : undefined;
391
+ const cutoff = op["cutoff"];
392
+ if (target === undefined) {
393
+ say("refused", "The key it removes is not on the roster.");
394
+ } else if (typeof cutoff !== "number" || !Number.isInteger(cutoff) || cutoff < -1) {
395
+ say("refused", "It does not say where in that key's log to stop.");
396
+ } else if (cutoff > (node.vc.get(target.key) ?? -1)) {
397
+ say("refused", "Its cutoff is past what its author had seen of that key's log.");
398
+ } else if (target.removed === null && target.role === "keeper" && liveKeepers() === 1) {
399
+ say("refused", "A lab cannot be left without a keeper.");
400
+ } else {
401
+ const stop = Math.min(cutoff, found.get(target.key) ?? cutoff);
402
+ found.set(target.key, stop);
403
+ target.removed = { by: target.removed?.by ?? node.id, cutoff: stop };
404
+ say("applied");
405
+ }
406
+ } else if (op.type === "roster.role") {
407
+ const target = typeof op["key"] === "string" ? roster.get(op["key"]) : undefined;
408
+ if (target === undefined || target.removed !== null || !role(op["role"])) {
409
+ say("refused", "It does not name a key on the roster and a role to give it.");
410
+ } else if (target.role === "keeper" && op["role"] === "member" && liveKeepers() === 1) {
411
+ say("refused", "A lab cannot be left without a keeper.");
412
+ } else {
413
+ if (op["role"] === "keeper" && target.role !== "keeper") since.set(target.key, since.size);
414
+ target.role = op["role"];
415
+ say("applied");
416
+ }
417
+ } else {
418
+ say("not understood", "This version does not know that kind of roster change.");
419
+ }
420
+ }
421
+ return { placed, roster, cuts: found, reached };
422
+ }
423
+
424
+ /** A value that the latest writer wins, with the entry that set it. */
425
+ interface Register { node: Node; value: unknown }
426
+
427
+ /** Apply the inventory changes, in the order the walk settled on. */
428
+ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): void {
429
+ const parts = new Map<string, { part: PartState; set: Map<string, Register> }>();
430
+ const items = new Map<string, {
431
+ item: ItemState; set: Map<string, Register>;
432
+ base: { node: Node; amount: number; recount: boolean }; adjusted: { node: Node; by: number }[]; overlapped: boolean;
433
+ }>();
434
+
435
+ /** Set a value, unless a change that had not been seen and has a lower ID already set it. */
436
+ const write = (set: Map<string, Register>, field: string, node: Node, value: unknown, what: string): void => {
437
+ const held = set.get(field);
438
+ if (held === undefined || hadSeen(node, held.node)) { set.set(field, { node, value }); return; }
439
+ const wins = node.id < held.node.id;
440
+ state.overlaps.push({ what, kept: wins ? node.id : held.node.id, dropped: wins ? held.node.id : node.id });
441
+ if (wins) set.set(field, { node, value });
442
+ };
443
+
444
+ for (const one of placed) {
445
+ if (one.status !== "applied") continue;
446
+ const node = chained.get(one.id)!;
447
+ const op = node.op;
448
+ if (op.type.startsWith("roster.")) continue;
449
+ const refuse = (reason: string): void => { one.status = "refused"; one.reason = reason; };
450
+
451
+ if (op.type === "part.add") {
452
+ if (!text(op["sequence"], LONGEST_SEQUENCE) || !text(op["name"], 200) || typeof op["circular"] !== "boolean") {
453
+ refuse("It does not carry a sequence, a name and whether the part is a circle.");
454
+ continue;
455
+ }
456
+ // Both the molecule and its checksum are worked out inside the guard: an entry from another
457
+ // machine must never be able to stop the merge, only to be refused by it.
458
+ let record: Dseqrecord;
459
+ let checksum: string;
460
+ try {
461
+ record = new Dseqrecord(op["sequence"], op["circular"]);
462
+ checksum = record.seguid();
463
+ } catch {
464
+ refuse("What it carries is not a sequence.");
465
+ continue;
466
+ }
467
+ if (!parts.has(checksum)) {
468
+ parts.set(checksum, {
469
+ part: { checksum, sequence: op["sequence"], circular: op["circular"], length: record.length,
470
+ name: op["name"], offered: false, fields: {}, added: node.id },
471
+ set: new Map([["name", { node, value: op["name"] }]]),
472
+ });
473
+ }
474
+ } else if (op.type === "part.offer") {
475
+ const held = typeof op["part"] === "string" ? parts.get(op["part"]) : undefined;
476
+ if (held === undefined || typeof op["available"] !== "boolean") { refuse("It does not name a part the lab has, and whether to offer it."); continue; }
477
+ write(held.set, "offered", node, op["available"], `whether ${held.part.name} is on offer`);
478
+ } else if (op.type === "item.add") {
479
+ if (!(typeof op["item"] === "string" && ITEM_ID.test(op["item"])) || !amountOf(op["amount"]) || op["amount"] < 0
480
+ || !(op["unit"] === null || text(op["unit"], 20))) {
481
+ refuse("It does not carry an item ID, a whole starting amount and a unit.");
482
+ } else if (items.has(op["item"])) {
483
+ refuse("An item with that ID already exists.");
484
+ } else if (typeof op["part"] !== "string" || !parts.has(op["part"])) {
485
+ refuse("The part it is an item of is not one the lab has.");
486
+ } else {
487
+ items.set(op["item"], {
488
+ item: { item: op["item"], part: op["part"], unit: op["unit"], amount: 0, retired: false, needsRecount: false, fields: {}, added: node.id },
489
+ set: new Map(), base: { node, amount: op["amount"], recount: false }, adjusted: [], overlapped: false,
490
+ });
491
+ }
492
+ } else if (op.type === "item.adjust" || op.type === "item.recount" || op.type === "item.retire") {
493
+ const held = typeof op["item"] === "string" ? items.get(op["item"]) : undefined;
494
+ if (held === undefined) { refuse("The item it changes is not one the lab has."); continue; }
495
+ if (op.type === "item.adjust") {
496
+ if (!amountOf(op["by"]) || op["by"] === 0) { refuse("It does not say by how many whole units."); continue; }
497
+ held.adjusted.push({ node, by: op["by"] });
498
+ } else if (op.type === "item.recount") {
499
+ if (!amountOf(op["amount"]) || op["amount"] < 0) { refuse("It does not say how many whole units are there."); continue; }
500
+ if (!held.base.recount || hadSeen(node, held.base.node)) {
501
+ held.base = { node, amount: op["amount"], recount: true };
502
+ held.overlapped = false;
503
+ } else {
504
+ // Two people counted without knowing of each other. One count stands, and the item is flagged.
505
+ const wins = node.id < held.base.node.id;
506
+ state.overlaps.push({ what: `the count of item ${held.item.item}`, kept: wins ? node.id : held.base.node.id,
507
+ dropped: wins ? held.base.node.id : node.id });
508
+ if (wins) held.base = { node, amount: op["amount"], recount: true };
509
+ held.overlapped = true;
510
+ }
511
+ } else {
512
+ held.item.retired = true;
513
+ }
514
+ } else if (op.type === "field.set") {
515
+ const field = op["field"];
516
+ const value = op["value"];
517
+ const target = op["on"] === "part" && typeof op["id"] === "string" ? parts.get(op["id"])
518
+ : op["on"] === "item" && typeof op["id"] === "string" ? items.get(op["id"]) : undefined;
519
+ if (target === undefined) { refuse("It does not name a part or an item the lab has."); continue; }
520
+ if (typeof field !== "string" || !FIELD.test(field) || RESERVED.has(field)) { refuse("It does not name a field that can be set."); continue; }
521
+ if (!(value === null || amountOf(value) || (typeof value === "string" && value.length <= 2_000))) { refuse("Its value is not text, a whole number or nothing."); continue; }
522
+ if (field === "name" && op["on"] === "part" && !text(value, 200)) { refuse("A part's name has to be some text."); continue; }
523
+ write(target.set, field, node, value, `${field} of ${op["on"]} ${String(op["id"]).slice(0, 12)}`);
524
+ } else {
525
+ one.status = "not understood";
526
+ one.reason = "This version does not know that kind of change.";
527
+ }
528
+ }
529
+
530
+ for (const { part, set } of parts.values()) {
531
+ for (const [field, held] of set) {
532
+ if (field === "name") part.name = held.value as string;
533
+ else if (field === "offered") part.offered = held.value as boolean;
534
+ else part.fields[field] = held.value as string | number | null;
535
+ }
536
+ state.parts.push(part);
537
+ }
538
+ for (const { item, set, base, adjusted, overlapped } of items.values()) {
539
+ // A recount replaces the adjustments its author had seen. Everything else still counts.
540
+ const since = adjusted.filter((one) => !hadSeen(base.node, one.node)).reduce((sum, one) => sum + one.by, 0);
541
+ item.amount = base.amount + since;
542
+ item.needsRecount = item.amount < 0 || overlapped;
543
+ for (const [field, held] of set) item.fields[field] = held.value as string | number | null;
544
+ state.items.push(item);
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Write the next entry in a key's log, given the lab as it stands.
550
+ *
551
+ * It works out the three things an entry has to say about its place: which lab, what came before it
552
+ * in this key's log, and which other logs have moved on since this key last wrote.
553
+ *
554
+ * @param state - The lab, from `mergeLog` over everything held.
555
+ * @param key - The device's key.
556
+ * @param op - The change.
557
+ * @param options - A name to sign under, and when.
558
+ * @returns The signed entry, to be added to what is held and sent to the others.
559
+ * @throws If `state` has no lab.
560
+ */
561
+ export async function nextEntry(state: LabState, key: SigningKey, op: Operation,
562
+ options: SignOptions = {}): Promise<SignedEntry> {
563
+ if (state.lab === null) throw new Error("There is no lab here to write to.");
564
+ const head = state.heads[key.publicKey];
565
+ const prev = head === undefined ? null : state.entries.find((one) => one.id === head.id)!.signed;
566
+ const known = state.knows[key.publicKey] ?? {};
567
+ const seen: Record<string, string> = {};
568
+ for (const [author, theirs] of Object.entries(state.heads)) {
569
+ if (author !== key.publicKey && (known[author] ?? -1) < theirs.seq) seen[author] = theirs.id;
570
+ }
571
+ return writeEntry(key, { lab: state.lab, prev, seen }, op, options);
572
+ }
573
+
574
+ /**
575
+ * What a lab shows the world: the parts it has in stock, and whether each is on offer.
576
+ *
577
+ * The logs hold everything — every tube, every amount, who took what. None of that leaves. A part is
578
+ * listed if some item of it that has not been retired has anything left, it is on offer only if a
579
+ * member said so, and the only note that travels is one written to be public (`public_note`).
580
+ *
581
+ * @param state - The lab.
582
+ * @param lab - Who is publishing, and from where.
583
+ * @param options - Other labs to point at, and when to say it was published.
584
+ * @returns An inventory, ready for a member to sign with `signInventory`.
585
+ */
586
+ export function publicInventory(state: LabState, lab: LabModel,
587
+ options: { peers?: readonly PeerModel[]; publishedAt?: string } = {}): InventoryDocument {
588
+ const inStock = new Set(state.items.filter((item) => !item.retired && item.amount > 0).map((item) => item.part));
589
+ const parts: InventoryPart[] = state.parts.filter((part) => inStock.has(part.checksum)).map((part, at) => ({
590
+ id: String(at + 1),
591
+ name: part.name,
592
+ checksum: part.checksum,
593
+ length: part.length,
594
+ circular: part.circular,
595
+ available: part.offered,
596
+ note: typeof part.fields["public_note"] === "string" ? part.fields["public_note"] : null,
597
+ }));
598
+ return {
599
+ bionet_inventory_version: INVENTORY_VERSION,
600
+ lab,
601
+ parts,
602
+ ...(options.peers === undefined ? {} : { peers: [...options.peers] }),
603
+ published_at: options.publishedAt ?? new Date().toISOString(),
604
+ };
605
+ }