@biolibs/bionet 1.2.1 → 1.3.1

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 CHANGED
@@ -26,7 +26,7 @@
26
26
  */
27
27
  import { Dseqrecord } from "@biolibs/dseqrecord";
28
28
  import type { SignOptions, SigningKey } from "@biolibs/opencloning";
29
- import { entryId, readEntry, verifyEntry, writeEntry, type Operation, type Role,
29
+ import { entryId, readEntry, verifyEntry, writeEntry, type Operation, type Role, type RunInput, type StandingMm,
30
30
  type SignedEntry } from "./log.js";
31
31
  import { INVENTORY_VERSION, type InventoryDocument, type InventoryPart, type LabModel,
32
32
  type PeerModel } from "./model.js";
@@ -84,12 +84,75 @@ export interface ItemState {
84
84
  retired: boolean;
85
85
  /** Whether the log has lost track: the amount went below zero, or two recounts overlapped. */
86
86
  needsRecount: boolean;
87
+ /** The run that made it, if one did. */
88
+ from: string | null;
89
+ /** Where it is, if anybody has said: the place, and the position if the place is a box. */
90
+ where: { place: string; slot: { row: number; column: number } | null } | null;
87
91
  /** Anything else set on it. */
88
92
  fields: Record<string, string | number | null>;
89
93
  /** The entry that added it. */
90
94
  added: string;
91
95
  }
92
96
 
97
+ /** One place: a room, a freezer, a shelf, a box. */
98
+ export interface PlaceState {
99
+ /** Its ID. */
100
+ place: string;
101
+ /** What kind of place it is. Anything a lab calls one; the usual ones are drawn knowingly. */
102
+ kind: string;
103
+ /** What the lab calls it. */
104
+ name: string;
105
+ /** The place it is in, or `null` if it is in nothing. */
106
+ parent: string | null;
107
+ /** Its positions, if it is a box. Fixed when it is added. */
108
+ grid: { rows: number; columns: number } | null;
109
+ /** Where it stands and how big it is, if anybody has said. */
110
+ standing: StandingMm | null;
111
+ /** Whether it has been retired. */
112
+ retired: boolean;
113
+ /**
114
+ * Whether moves made apart left it inside itself. Such a place is shown as being in nothing
115
+ * until somebody moves it.
116
+ */
117
+ adrift: boolean;
118
+ /** Anything else set on it. */
119
+ fields: Record<string, string | number | null>;
120
+ /** The entry that added it. */
121
+ added: string;
122
+ }
123
+
124
+ /** Something done at the bench, as the lab records it. */
125
+ export interface RunState {
126
+ /** Its ID. */
127
+ run: string;
128
+ /** What kind of run it was: `pcr`. */
129
+ kind: string;
130
+ /** The place it was done at, or `null`. */
131
+ instrument: string | null;
132
+ /** What went in, and how much of each was used. */
133
+ inputs: RunInput[];
134
+ /** The items it made, and the part each is an item of. */
135
+ outputs: { item: string; part: string }[];
136
+ /** How it was set up. */
137
+ settings: Record<string, string | number>;
138
+ /** Whether it worked. */
139
+ outcome: "worked" | "failed";
140
+ /** Anything said about it. */
141
+ note: string | null;
142
+ /** The entry that recorded it. */
143
+ added: string;
144
+ }
145
+
146
+ /** One position of one box that the log says holds more than one item. */
147
+ export interface Crowded {
148
+ /** The box. */
149
+ place: string;
150
+ /** The position. */
151
+ slot: { row: number; column: number };
152
+ /** The items the log has there. */
153
+ items: string[];
154
+ }
155
+
93
156
  /** What became of one entry. */
94
157
  export type EntryStatus = "applied" | "set aside" | "refused" | "not understood";
95
158
 
@@ -135,6 +198,12 @@ export interface LabState {
135
198
  parts: PartState[];
136
199
  /** Every item. */
137
200
  items: ItemState[];
201
+ /** Every place. */
202
+ places: PlaceState[];
203
+ /** Positions the log says hold more than one item. Somebody has to go and look. */
204
+ crowded: Crowded[];
205
+ /** Everything done at the bench that was recorded, in the order the merge settled on. */
206
+ runs: RunState[];
138
207
  /** Every entry that could be placed, in order, with what became of it. */
139
208
  entries: Placed[];
140
209
  /** Entries that are waiting on others that have not arrived. */
@@ -168,6 +237,73 @@ const RESERVED = new Set(["amount", "part", "item", "checksum", "sequence", "cir
168
237
  const text = (value: unknown, most: number): value is string =>
169
238
  typeof value === "string" && value.length > 0 && value.length <= most;
170
239
  /** An amount is a whole number of the item's unit: only whole numbers have one agreed spelling to sign. */
240
+ /** Fields of a place that are changed by their own operations, not by `field.set`. */
241
+ const PLACE_RESERVED = new Set(["place", "kind", "parent", "grid", "standing", "retired", "adrift"]);
242
+
243
+ /** The most positions a box may have along one side, and the farthest a place may stand or reach, in millimetres. */
244
+ const MOST_SIDE = 100;
245
+ const FARTHEST = 1_000_000;
246
+
247
+ const isGrid = (value: unknown): value is { rows: number; columns: number } => {
248
+ const grid = value as { rows?: unknown; columns?: unknown } | null;
249
+ return typeof grid === "object" && grid !== null && [grid.rows, grid.columns].every((side) => Number.isSafeInteger(side) && (side as number) >= 1 && (side as number) <= MOST_SIDE);
250
+ };
251
+
252
+ const isSlot = (value: unknown): value is { row: number; column: number } => {
253
+ const slot = value as { row?: unknown; column?: unknown } | null;
254
+ return typeof slot === "object" && slot !== null && [slot.row, slot.column].every((at) => Number.isSafeInteger(at) && (at as number) >= 0);
255
+ };
256
+
257
+ const isStanding = (value: unknown): value is StandingMm => {
258
+ const standing = value as Partial<StandingMm> | null;
259
+ const three = (list: unknown, least: number): boolean =>
260
+ Array.isArray(list) && list.length === 3 && list.every((one) => Number.isSafeInteger(one) && one >= least && one <= FARTHEST);
261
+ return typeof standing === "object" && standing !== null && three(standing.at, -FARTHEST) && three(standing.size, 1)
262
+ && [0, 90, 180, 270].includes(standing.turn as number);
263
+ };
264
+
265
+ /** The most items that may go into one run or come out of it, and the most settings it may carry. */
266
+ const MOST_IN_A_RUN = 50;
267
+
268
+ /**
269
+ * Why a run cannot be recorded, or `null` if it can.
270
+ *
271
+ * Everything is checked before anything is changed: an entry from another machine may be refused,
272
+ * and must never leave a run half applied.
273
+ */
274
+ function runProblem(op: Operation, items: ReadonlyMap<string, unknown>, places: ReadonlyMap<string, unknown>, runs: ReadonlySet<string>): string | null {
275
+ if (!(typeof op["run"] === "string" && ITEM_ID.test(op["run"])) || !text(op["kind"], 40)) return "It does not carry a run ID and what kind of run it was.";
276
+ if (runs.has(op["run"])) return "A run with that ID already exists.";
277
+ if (!(op["instrument"] === null || (typeof op["instrument"] === "string" && places.has(op["instrument"])))) return "The place it was done at is not one the lab has.";
278
+ if (op["outcome"] !== "worked" && op["outcome"] !== "failed") return "It does not say whether it worked.";
279
+ if (!(op["note"] === null || text(op["note"], 2_000))) return "Its note is not some text.";
280
+ const settings = op["settings"];
281
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings) || Object.keys(settings).length > MOST_IN_A_RUN
282
+ || !Object.entries(settings).every(([name, value]) => FIELD.test(name) && (amountOf(value) || (typeof value === "string" && value.length <= 200)))) {
283
+ return "Its settings are not whole numbers and short text, by name.";
284
+ }
285
+ const inputs = op["inputs"];
286
+ if (!Array.isArray(inputs) || inputs.length > MOST_IN_A_RUN) return "It does not list what went in.";
287
+ for (const input of inputs as Partial<RunInput>[]) {
288
+ if (typeof input !== "object" || input === null || !amountOf(input.amount) || input.amount < 0 || !text(input.role, 40)) return "It does not say how many whole units of each thing went in, and as what.";
289
+ if (typeof input.item !== "string" || !items.has(input.item)) return "Something it says went in is not an item the lab has.";
290
+ }
291
+ const outputs = op["outputs"];
292
+ if (!Array.isArray(outputs) || outputs.length > MOST_IN_A_RUN) return "It does not list what came out.";
293
+ if (op["outcome"] === "failed" && outputs.length > 0) return "A run that did not work made nothing.";
294
+ const seen = new Set<string>();
295
+ for (const output of outputs as Record<string, unknown>[]) {
296
+ if (typeof output !== "object" || output === null || !(typeof output["item"] === "string" && ITEM_ID.test(output["item"]))
297
+ || !text(output["sequence"], LONGEST_SEQUENCE) || typeof output["circular"] !== "boolean" || !text(output["name"], 200)
298
+ || !amountOf(output["amount"]) || output["amount"] < 0 || !(output["unit"] === null || text(output["unit"], 20))) {
299
+ return "It does not give each thing that came out an item ID, a sequence, a name, a whole amount and a unit.";
300
+ }
301
+ if (items.has(output["item"]) || seen.has(output["item"])) return "An item with that ID already exists.";
302
+ seen.add(output["item"]);
303
+ }
304
+ return null;
305
+ }
306
+
171
307
  const amountOf = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value);
172
308
  const role = (value: unknown): value is Role => value === "member" || value === "keeper";
173
309
 
@@ -194,7 +330,7 @@ const hadSeen = (later: Node, earlier: Node): boolean => (later.vc.get(earlier.a
194
330
  * ```
195
331
  */
196
332
  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: [],
333
+ const state: LabState = { lab: options.lab ?? null, name: null, roster: [], parts: [], items: [], places: [], crowded: [], runs: [], entries: [],
198
334
  waiting: [], discarded: [], overlaps: [], heads: {}, knows: {} };
199
335
 
200
336
  // Read and check every entry on its own, before any of them is believed about the others.
@@ -441,6 +577,10 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
441
577
  if (wins) set.set(field, { node, value });
442
578
  };
443
579
 
580
+ const places = new Map<string, { place: PlaceState; set: Map<string, Register> }>();
581
+ /** Where each item was last put. */
582
+ const put = new Map<string, Map<string, Register>>();
583
+
444
584
  for (const one of placed) {
445
585
  if (one.status !== "applied") continue;
446
586
  const node = chained.get(one.id)!;
@@ -485,7 +625,7 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
485
625
  refuse("The part it is an item of is not one the lab has.");
486
626
  } else {
487
627
  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 },
628
+ item: { item: op["item"], part: op["part"], unit: op["unit"], amount: 0, retired: false, needsRecount: false, from: null, where: null, fields: {}, added: node.id },
489
629
  set: new Map(), base: { node, amount: op["amount"], recount: false }, adjusted: [], overlapped: false,
490
630
  });
491
631
  }
@@ -511,12 +651,101 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
511
651
  } else {
512
652
  held.item.retired = true;
513
653
  }
654
+ } else if (op.type === "place.add") {
655
+ const grid = op["grid"];
656
+ if (!(typeof op["place"] === "string" && ITEM_ID.test(op["place"])) || !text(op["kind"], 40) || !text(op["name"], 200)
657
+ || !(grid === null || isGrid(grid))) {
658
+ refuse("It does not carry a place ID, a kind, a name, and positions that are whole numbers.");
659
+ } else if (places.has(op["place"])) {
660
+ refuse("A place with that ID already exists.");
661
+ } else if (!(op["parent"] === null || (typeof op["parent"] === "string" && places.has(op["parent"])))) {
662
+ refuse("The place it is in is not one the lab has.");
663
+ } else {
664
+ places.set(op["place"], {
665
+ place: { place: op["place"], kind: op["kind"], name: op["name"], parent: null, grid: grid === null ? null : { rows: grid.rows, columns: grid.columns },
666
+ standing: null, retired: false, adrift: false, fields: {}, added: node.id },
667
+ set: new Map<string, Register>([["name", { node, value: op["name"] }], ["parent", { node, value: op["parent"] }]]),
668
+ });
669
+ }
670
+ } else if (op.type === "place.move" || op.type === "place.stand" || op.type === "place.retire") {
671
+ const held = typeof op["place"] === "string" ? places.get(op["place"]) : undefined;
672
+ if (held === undefined) { refuse("The place it changes is not one the lab has."); continue; }
673
+ if (op.type === "place.move") {
674
+ const parent = op["parent"];
675
+ if (!(parent === null || (typeof parent === "string" && places.has(parent)))) { refuse("The place it moves to is not one the lab has."); continue; }
676
+ if (parent === op["place"]) { refuse("A place cannot be inside itself."); continue; }
677
+ write(held.set, "parent", node, parent, `where ${held.place.name} is`);
678
+ } else if (op.type === "place.stand") {
679
+ const standing = op["standing"];
680
+ if (!(standing === null || isStanding(standing))) { refuse("It does not say where the place stands and how big it is, in whole millimetres."); continue; }
681
+ write(held.set, "standing", node, standing, `where ${held.place.name} stands`);
682
+ } else {
683
+ held.place.retired = true;
684
+ }
685
+ } else if (op.type === "item.put") {
686
+ const item = typeof op["item"] === "string" ? items.get(op["item"]) : undefined;
687
+ if (item === undefined) { refuse("The item it puts somewhere is not one the lab has."); continue; }
688
+ const place = op["place"];
689
+ const slot = op["slot"];
690
+ if (place === null) {
691
+ if (slot !== null) { refuse("An item that is nowhere is at no position."); continue; }
692
+ } else {
693
+ const into = typeof place === "string" ? places.get(place) : undefined;
694
+ if (into === undefined) { refuse("The place it puts the item in is not one the lab has."); continue; }
695
+ if (slot !== null && !(isSlot(slot) && into.place.grid !== null && slot.row < into.place.grid.rows && slot.column < into.place.grid.columns)) {
696
+ refuse("The position it names is not one that place has.");
697
+ continue;
698
+ }
699
+ }
700
+ if (!put.has(item.item.item)) put.set(item.item.item, new Map());
701
+ write(put.get(item.item.item)!, "where", node, place === null ? null : { place, slot: slot === null ? null : { row: (slot as { row: number }).row, column: (slot as { column: number }).column } },
702
+ `where item ${item.item.item.slice(0, 12)} is`);
703
+ } else if (op.type === "run.record") {
704
+ const problem = runProblem(op, items, places, new Set(state.runs.map((run) => run.run)));
705
+ if (problem !== null) { refuse(problem); continue; }
706
+ const inputs = op["inputs"] as RunInput[];
707
+ const outputs = op["outputs"] as { item: string; sequence: string; circular: boolean; name: string; amount: number; unit: string | null }[];
708
+ // What comes out is worked out before anything is changed, so that a run is recorded whole or not at all.
709
+ const made: { output: (typeof outputs)[number]; record: Dseqrecord; checksum: string }[] = [];
710
+ try {
711
+ for (const output of outputs) {
712
+ const record = new Dseqrecord(output.sequence, output.circular);
713
+ made.push({ output, record, checksum: record.seguid() });
714
+ }
715
+ } catch {
716
+ refuse("Something it says came out is not a sequence.");
717
+ continue;
718
+ }
719
+ for (const input of inputs) if (input.amount > 0) items.get(input.item)!.adjusted.push({ node, by: -input.amount });
720
+ for (const { output, record, checksum } of made) {
721
+ if (!parts.has(checksum)) {
722
+ parts.set(checksum, {
723
+ part: { checksum, sequence: output.sequence, circular: output.circular, length: record.length, name: output.name, offered: false, fields: {}, added: node.id },
724
+ set: new Map([["name", { node, value: output.name }]]),
725
+ });
726
+ }
727
+ items.set(output.item, {
728
+ item: { item: output.item, part: checksum, unit: output.unit, amount: 0, retired: false, needsRecount: false, from: op["run"] as string,
729
+ where: null, fields: {}, added: node.id },
730
+ set: new Map(), base: { node, amount: output.amount, recount: false }, adjusted: [], overlapped: false,
731
+ });
732
+ }
733
+ state.runs.push({
734
+ run: op["run"] as string, kind: op["kind"] as string, instrument: op["instrument"] as string | null,
735
+ inputs: inputs.map((input) => ({ item: input.item, amount: input.amount, role: input.role })),
736
+ outputs: made.map(({ output, checksum }) => ({ item: output.item, part: checksum })),
737
+ settings: { ...(op["settings"] as Record<string, string | number>) }, outcome: op["outcome"] as "worked" | "failed",
738
+ note: op["note"] as string | null, added: node.id,
739
+ });
514
740
  } else if (op.type === "field.set") {
515
741
  const field = op["field"];
516
742
  const value = op["value"];
517
743
  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; }
744
+ : op["on"] === "item" && typeof op["id"] === "string" ? items.get(op["id"])
745
+ : op["on"] === "place" && typeof op["id"] === "string" ? places.get(op["id"]) : undefined;
746
+ if (target === undefined) { refuse("It does not name a part, an item or a place the lab has."); continue; }
747
+ if (op["on"] === "place" && typeof field === "string" && PLACE_RESERVED.has(field)) { refuse("It does not name a field that can be set."); continue; }
748
+ if (field === "name" && op["on"] === "place" && !text(value, 200)) { refuse("A place's name has to be some text."); continue; }
520
749
  if (typeof field !== "string" || !FIELD.test(field) || RESERVED.has(field)) { refuse("It does not name a field that can be set."); continue; }
521
750
  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
751
  if (field === "name" && op["on"] === "part" && !text(value, 200)) { refuse("A part's name has to be some text."); continue; }
@@ -541,8 +770,38 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
541
770
  item.amount = base.amount + since;
542
771
  item.needsRecount = item.amount < 0 || overlapped;
543
772
  for (const [field, held] of set) item.fields[field] = held.value as string | number | null;
773
+ item.where = (put.get(item.item)?.get("where")?.value ?? null) as ItemState["where"];
544
774
  state.items.push(item);
545
775
  }
776
+ for (const { place, set } of places.values()) {
777
+ for (const [field, held] of set) {
778
+ if (field === "name") place.name = held.value as string;
779
+ else if (field === "parent") place.parent = held.value as string | null;
780
+ else if (field === "standing") place.standing = held.value as StandingMm | null;
781
+ else place.fields[field] = held.value as string | number | null;
782
+ }
783
+ state.places.push(place);
784
+ }
785
+ // Two people apart can each move a place into the other. Neither move is wrong alone, so neither
786
+ // is refused: every place caught in the loop is shown as being in nothing, and says so.
787
+ for (const { place } of places.values()) {
788
+ const passed = new Set<string>();
789
+ for (let up = place.parent; up !== null && !passed.has(up); up = places.get(up)!.place.parent) {
790
+ if (up === place.place) { place.adrift = true; break; }
791
+ passed.add(up);
792
+ }
793
+ }
794
+ for (const { place } of places.values()) if (place.adrift) place.parent = null;
795
+ // Two tubes cannot stand in one position, but two people apart can each say theirs does.
796
+ const stood = new Map<string, Crowded>();
797
+ for (const item of state.items) {
798
+ if (item.retired || item.where === null || item.where.slot === null) continue;
799
+ const key = `${item.where.place} ${item.where.slot.row} ${item.where.slot.column}`;
800
+ const held = stood.get(key) ?? { place: item.where.place, slot: item.where.slot, items: [] };
801
+ held.items.push(item.item);
802
+ stood.set(key, held);
803
+ }
804
+ state.crowded = [...stood.values()].filter((one) => one.items.length > 1);
546
805
  }
547
806
 
548
807
  /**