Repository navigation
Expand file tree
/
Copy pathworkspace.ts
More file actions
559 lines (521 loc) · 22.4 KB
/
Copy pathworkspace.ts
File metadata and controls
559 lines (521 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import {
addressStr,
defaultAddress,
defaultName,
isAddressFault,
MAX_NICS,
MAX_NODE,
parseAddress,
parseDefaultName,
} from "../net/index.ts";
import { cableEffects } from "./cables.ts";
import { CONDITION_PARTS, conditionsOf, hasConditions, isConditionsFault } from "./conditions.ts";
import { FIRST_SETS, MAX_EXTRA_DISKS, parseGiB } from "./disks.ts";
import { identity, isNameFault, parseCheckpointName, parseMachineName, parseSwitchName } from "./identity.ts";
import { addressClash, type BootNode, bootMachines } from "./machines.ts";
import { addPanes, focusPane, keyboardHolder, parkPane, toggleMaximise } from "./panes.ts";
import { keysOf } from "./record.ts";
import { parseCost, parsePriority } from "./stp.ts";
import { addressed, machineList, plugsOf, samePort } from "./topology.ts";
import {
type AgentState,
type Checkpoint,
type ConditionPart,
type Conditions,
DEFAULT_SWITCH,
DISK_SIZES,
type DiskSets,
type Disks,
HUES,
type Identity,
type LabState,
MAX_CPUS,
MAX_MACHINES,
MAX_MEM_MIB,
MAX_SWITCHES,
type MachineSpec,
type NicRef,
type NicSpec,
NO_CONDITIONS,
type Plug,
PORTS,
type PortCost,
type PortRef,
type PortVlan,
type Step,
type SwitchCable,
type SwitchName,
type VlanId,
type VlanPort,
} from "./types.ts";
import { settleSwitches } from "./update.ts";
import { parseVlanId, vlanList } from "./vlans.ts";
/** The slices that the saved workspace is made from. Typed so that saveWorkspace can read nothing else. */
const SAVED = [
"nextN",
"machines",
"rail",
"switches",
"switchCables",
"portVlans",
"stp",
"priorities",
"portCosts",
"panes",
"keyboard",
] as const;
type Saved = Pick<LabState, (typeof SAVED)[number]> & { readonly agent: Pick<AgentState, "policies" | "paused"> };
export function saveWorkspace(state: Saved): string {
const nodes = machineList(state)
.filter((m) => m.life.phase !== "removing")
.map((m) => {
const plugs = plugsOf(m.life);
return {
n: m.n,
name: m.name,
hue: m.hue,
...m.spec,
nics: m.spec.nics.map((nic, k) => {
const plug = plugs[k];
return {
net: nic.net,
address: nic.address ? addressStr(nic.address) : null,
port: plug?.kind === "port" ? plug.port : null,
cut: plug?.kind === "port" && plug.link === "cut",
conditions: (plug?.kind === "port" && plug.conditions) || NO_CONDITIONS,
};
}),
failure: m.life.phase === "failed" ? m.life.reason : undefined,
sets: m.sets,
// A restore that a reload cuts short is done again from the start, and one that is not in here never was.
restore: m.life.phase === "restoring" ? m.life.from.set : undefined,
// A stop that a reload cuts short ends as it was going to.
off: m.life.phase === "off" || (m.life.phase === "stopping" && m.life.next === "off") ? true : undefined,
};
});
return JSON.stringify({
version: VERSION,
nextN: state.nextN,
switches: state.switches,
cables: state.switchCables.map(({ ends, link, conditions = NO_CONDITIONS }) => ({
ends,
cut: link === "cut",
conditions,
})),
vlans: state.portVlans.map(({ port, vlan }) =>
vlan.mode === "access"
? { port, vlan: vlan.vlan }
: { port, trunk: { allowed: vlan.allowed, native: vlan.native } },
),
stp: state.stp,
priorities: state.priorities,
costs: state.portCosts,
nodes,
order: state.panes.order,
parked: state.panes.order.filter((n) => (state.panes.maximised?.before ?? state.panes.parked)[n] === "user"),
maximised: state.panes.maximised?.machine,
focus: keyboardHolder(state.keyboard),
policies: state.agent.policies,
paused: state.agent.paused,
});
}
/** saveWorkspace, made again only once a slice that it saves has changed, so a tick of the clock costs nothing. */
export function workspaceSaver(): (state: LabState) => string {
let last: { readonly state: Saved; readonly text: string } | null = null;
return (state) => {
const before = last?.state;
const same =
before !== undefined &&
SAVED.every((key) => before[key] === state[key]) &&
before.agent.policies === state.agent.policies &&
before.agent.paused === state.agent.paused;
if (last && same) return last.text;
last = { state, text: saveWorkspace(state) };
return last.text;
};
}
const record = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
/** Refuses the saved lab, and says where in it the value is that the lab cannot have: `nodes[2].nics[0].port`. */
function invalid(at: string): never {
throw new Error(`The saved Unlab workspace could not be read (${at}). Its disks and settings have been kept.`);
}
/** The index of the first item that an earlier one matches, or -1 when none does. */
const repeated = <T>(list: readonly T[], same: (a: T, b: T) => boolean): number =>
list.findIndex((item, i) => list.findIndex((other) => same(other, item)) !== i);
interface SavedNic {
readonly spec: NicSpec;
readonly plug: Plug;
}
function readSwitches(saved: unknown, at: string): LabState["switches"] {
if (!Array.isArray(saved) || saved.length > MAX_SWITCHES) return invalid(at);
const [first, ...others] = saved.map((saved: unknown, i) => {
const name = typeof saved === "string" ? parseSwitchName(saved) : invalid(`${at}[${i}]`);
return isNameFault(name) ? invalid(`${at}[${i}]`) : name;
});
const twice = repeated(saved, Object.is);
if (twice >= 0) return invalid(`${at}[${twice}]`);
return first === DEFAULT_SWITCH ? [DEFAULT_SWITCH, ...others] : invalid(`${at}[0]`);
}
function readSwitch(saved: unknown, switches: LabState["switches"], at: string): SwitchName {
return switches.find((name) => name === saved) ?? invalid(at);
}
function readPort(saved: unknown, switches: LabState["switches"], at: string): PortRef | null {
if (saved === null) return null;
if (!record(saved)) return invalid(at);
return {
switch: readSwitch(saved.switch, switches, `${at}.switch`),
port: PORTS.find((port) => port === saved.port) ?? invalid(`${at}.port`),
};
}
/** A cable's conditions, each part a number in its range. In the lab, a cable with none has no such field. */
function readConditions(saved: unknown, at: string): { readonly conditions?: Conditions } {
if (!record(saved)) return invalid(at);
const values: Partial<Record<ConditionPart, number>> = {};
for (const [key, value] of Object.entries(saved)) {
const part = CONDITION_PARTS.find((part) => part === key);
if (!part || typeof value !== "number") return invalid(`${at}.${key}`);
values[part] = value;
}
const conditions = conditionsOf(values);
if (isConditionsFault(conditions))
return invalid(conditions.kind === "out-of-range" ? `${at}.${conditions.part}` : at);
return hasConditions(conditions) ? { conditions } : {};
}
function readCable(saved: unknown, switches: LabState["switches"], at: string): SwitchCable {
if (!record(saved)) return invalid(at);
if (typeof saved.cut !== "boolean") return invalid(`${at}.cut`);
if (!Array.isArray(saved.ends) || saved.ends.length !== 2) return invalid(`${at}.ends`);
const ends = saved.ends as readonly unknown[];
const end = (i: 0 | 1) => readPort(ends[i], switches, `${at}.ends[${i}]`) ?? invalid(`${at}.ends[${i}]`);
return {
ends: [end(0), end(1)],
link: saved.cut ? "cut" : "up",
...readConditions(saved.conditions, `${at}.conditions`),
};
}
function readCables(saved: unknown, switches: LabState["switches"], at: string): readonly SwitchCable[] {
return Array.isArray(saved)
? saved.map((cable: unknown, i) => readCable(cable, switches, `${at}[${i}]`))
: invalid(at);
}
/** The switches that take part in the spanning tree, each once, in the order of the lab's switches. */
function readStp(saved: unknown, switches: LabState["switches"], at: string): readonly SwitchName[] {
if (!Array.isArray(saved)) return invalid(at);
const twice = repeated(saved, Object.is);
if (twice >= 0) return invalid(`${at}[${twice}]`);
const names = saved.map((name: unknown, i) => readSwitch(name, switches, `${at}[${i}]`));
return switches.filter((name) => names.includes(name));
}
/** Each switch's priority, of those that have one set. */
function readPriorities(saved: unknown, switches: LabState["switches"], at: string): LabState["priorities"] {
if (!record(saved)) return invalid(at);
return Object.fromEntries(
Object.entries(saved).map(([name, priority]) => [
readSwitch(name, switches, `${at}.${name}`),
(typeof priority === "number" ? parsePriority(String(priority)) : null) ?? invalid(`${at}.${name}`),
]),
);
}
/** Settings of ports, one for each port at most. */
function onePerPort<T extends { readonly port: PortRef }>(settings: readonly T[], at: string): readonly T[] {
const twice = repeated(settings, (a, b) => samePort(a.port, b.port));
return twice >= 0 ? invalid(`${at}[${twice}].port`) : settings;
}
function readCosts(saved: unknown, switches: LabState["switches"], at: string): readonly PortCost[] {
if (!Array.isArray(saved)) return invalid(at);
const costs = saved.map((held: unknown, i): PortCost => {
if (!record(held)) return invalid(`${at}[${i}]`);
const cost = (typeof held.cost === "number" ? parseCost(String(held.cost)) : null) ?? invalid(`${at}[${i}].cost`);
return { port: readPort(held.port, switches, `${at}[${i}].port`) ?? invalid(`${at}[${i}].port`), cost };
});
return onePerPort(costs, at);
}
function readVlanId(saved: unknown, at: string): VlanId {
return (typeof saved === "number" ? parseVlanId(String(saved)) : null) ?? invalid(at);
}
function readPortVlan(saved: Record<string, unknown>, at: string): PortVlan {
if (saved.trunk === undefined) return { mode: "access", vlan: readVlanId(saved.vlan, `${at}.vlan`) };
const { trunk } = saved;
if (!record(trunk)) return invalid(`${at}.trunk`);
const { allowed } = trunk;
if (allowed !== "all" && !Array.isArray(allowed)) return invalid(`${at}.trunk.allowed`);
return {
mode: "trunk",
allowed:
allowed === "all"
? "all"
: vlanList(allowed.map((id: unknown, i) => readVlanId(id, `${at}.trunk.allowed[${i}]`))),
native: readVlanId(trunk.native, `${at}.trunk.native`),
};
}
function readVlans(saved: unknown, switches: LabState["switches"], at: string): readonly VlanPort[] {
if (!Array.isArray(saved)) return invalid(at);
const vlans = saved.map((held: unknown, i): VlanPort => {
if (!record(held)) return invalid(`${at}[${i}]`);
const port = readPort(held.port, switches, `${at}[${i}].port`) ?? invalid(`${at}[${i}].port`);
return { port, vlan: readPortVlan(held, `${at}[${i}]`) };
});
return onePerPort(vlans, at);
}
function readNic(saved: unknown, switches: LabState["switches"], at: string): SavedNic {
if (!record(saved)) return invalid(at);
if (typeof saved.cut !== "boolean") return invalid(`${at}.cut`);
const port = readPort(saved.port, switches, `${at}.port`);
const net = saved.net === "none" ? "none" : readSwitch(saved.net, switches, `${at}.net`);
return {
spec: {
// A NIC that was plugged in after it was spawned on none used to be saved as on none.
net: port?.switch ?? net,
address: readAddress(saved.address, `${at}.address`),
},
plug: port
? { kind: "port", port, link: saved.cut ? "cut" : "up", ...readConditions(saved.conditions, `${at}.conditions`) }
: { kind: "none" },
};
}
function readAddress(saved: unknown, at: string): NicSpec["address"] {
if (saved === null) return null;
const address = typeof saved === "string" ? parseAddress(saved) : invalid(at);
return isAddressFault(address) ? invalid(at) : address;
}
function readNics(saved: unknown, switches: LabState["switches"], at: string): readonly SavedNic[] {
if (!Array.isArray(saved) || saved.length < 1 || saved.length > MAX_NICS) return invalid(at);
return saved.map((nic: unknown, k) => readNic(nic, switches, `${at}[${k}]`));
}
function readDisks(saved: unknown, at: string): Disks {
if (!record(saved)) return invalid(at);
if (!Array.isArray(saved.extra) || saved.extra.length > MAX_EXTRA_DISKS) return invalid(`${at}.extra`);
return {
root: DISK_SIZES.find((size) => size === saved.root) ?? invalid(`${at}.root`),
extra: saved.extra.map((size, i) => parseGiB(size) ?? invalid(`${at}.extra[${i}]`)),
};
}
const isCount = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
function readCheckpoint(saved: unknown, at: string): Checkpoint {
if (!record(saved)) return invalid(at);
const name = (typeof saved.name === "string" ? parseCheckpointName(saved.name) : null) ?? invalid(`${at}.name`);
const { set, bytes } = saved;
if (!isCount(set)) return invalid(`${at}.set`);
return isCount(bytes) ? { name, set, bytes } : invalid(`${at}.bytes`);
}
/** The live set and each checkpoint's are different sets, each below the next, and no two checkpoints share a name. */
function readSets(saved: unknown, at: string): DiskSets {
if (!record(saved)) return invalid(at);
const { live, next } = saved;
if (!isCount(live)) return invalid(`${at}.live`);
if (!isCount(next)) return invalid(`${at}.next`);
if (!Array.isArray(saved.checkpoints)) return invalid(`${at}.checkpoints`);
const checkpoints = saved.checkpoints.map((checkpoint: unknown, i) =>
readCheckpoint(checkpoint, `${at}.checkpoints[${i}]`),
);
if (live >= next) return invalid(`${at}.live`);
const clash = checkpoints.findIndex(
({ name, set }, i) =>
set === live ||
set >= next ||
checkpoints.some((other, j) => j < i && (other.set === set || other.name === name)),
);
return clash >= 0 ? invalid(`${at}.checkpoints[${clash}]`) : { live, next, checkpoints };
}
function readRestore(saved: unknown, { checkpoints }: DiskSets, at: string): Checkpoint | undefined {
return saved === undefined ? undefined : (checkpoints.find(({ set }) => set === saved) ?? invalid(at));
}
interface SavedNode extends Readonly<Record<string, unknown>> {
readonly n: number;
}
interface SavedLab extends Readonly<Record<string, unknown>> {
readonly nodes: readonly SavedNode[];
}
/** What each machine is as the next version saves it. A field of the version before that the next has not is gone. */
const eachNode =
(change: (node: SavedNode, at: string) => SavedNode) =>
(lab: SavedLab): SavedLab => ({ ...lab, nodes: lab.nodes.map((node, i) => change(node, `nodes[${i}]`)) });
function savedNics({ nics }: SavedNode, at: string): readonly Readonly<Record<string, unknown>>[] {
if (!Array.isArray(nics)) return invalid(`${at}.nics`);
return nics.map((nic: unknown, k) => (record(nic) ? nic : invalid(`${at}.nics[${k}]`)));
}
/** Each takes a lab from one version to the next, the first from version 1. */
const UPGRADES: readonly ((lab: SavedLab) => SavedLab)[] = [
// A machine had one NIC, saved in the machine itself.
eachNode(({ net, port, cut, ...node }) => ({ ...node, nics: [{ net, port, cut }] })),
// It had no addresses, and no choice of gateway.
eachNode((node, at) => {
const [eth0, ...rest] = savedNics(node, at);
if (!eth0) return invalid(`${at}.nics`);
const address = addressStr(defaultAddress(node.n));
return {
...node,
gateway: eth0.net === DEFAULT_SWITCH,
nics: [{ ...eth0, address }, ...rest.map((nic) => ({ ...nic, address: null }))],
};
}),
// It had no name.
eachNode((node) => ({ ...node, name: defaultName(node.n) })),
// It had no extra disks.
eachNode(({ diskGiB, ...node }) => ({ ...node, disks: { root: diskGiB ?? "4", extra: [] } })),
// It had no checkpoints.
eachNode((node) => ({ ...node, sets: FIRST_SETS })),
// A port was a number on the only switch.
(lab) => ({
...eachNode((node, at) => ({
...node,
nics: savedNics(node, at).map(({ port, ...nic }) => ({
...nic,
port: port === null ? null : { switch: DEFAULT_SWITCH, port },
})),
}))(lab),
switches: [DEFAULT_SWITCH],
}),
// No cable went from one switch to another.
(lab) => ({ ...lab, cables: [] }),
// Every port was in VLAN 1.
(lab) => ({ ...lab, vlans: [] }),
// No cable had conditions.
(lab) => ({
...eachNode((node, at) => ({ ...node, nics: savedNics(node, at).map((nic) => ({ ...nic, conditions: {} })) }))(lab),
cables: Array.isArray(lab.cables)
? lab.cables.map((cable: unknown, i) => (record(cable) ? { ...cable, conditions: {} } : invalid(`cables[${i}]`)))
: invalid("cables"),
}),
// No switch took part in a spanning tree.
(lab) => ({ ...lab, stp: [] }),
// Every switch had the same priority, and every port the same cost.
(lab) => ({ ...lab, priorities: {}, costs: [] }),
];
const VERSION = UPGRADES.length + 1;
/** The lab as this version would have saved it. */
function readLab(raw: string): SavedLab {
let saved: unknown;
try {
saved = JSON.parse(raw);
} catch {
return invalid("not JSON");
}
if (!record(saved)) return invalid("not a lab");
const { version } = saved;
if (!isCount(version) || version < 1 || version > VERSION) return invalid("version");
if (!Array.isArray(saved.nodes) || saved.nodes.length > MAX_MACHINES) return invalid("nodes");
const nodes = saved.nodes.map((node: unknown, i): SavedNode => {
if (!record(node)) return invalid(`nodes[${i}]`);
return typeof node.n === "number" ? { ...node, n: node.n } : invalid(`nodes[${i}].n`);
});
return UPGRADES.slice(version - 1).reduce<SavedLab>((lab, upgrade) => upgrade(lab), { ...saved, nodes });
}
/** `node<n>` names machine n and no other, as it does when the lab gives it out. */
function readIdentity(n: number, saved: unknown, at: string): Identity {
const name = (typeof saved === "string" ? parseMachineName(saved) : null) ?? invalid(at);
return [n, null].includes(parseDefaultName(name)) ? identity(n, name) : invalid(at);
}
/** What one machine was, as `planSpawn` would have let it be. */
function readNode(m: SavedNode, at: string, switches: LabState["switches"], taken: PortRef[]): BootNode {
const id = readIdentity(m.n, m.name, `${at}.name`);
if (switches.some((name) => name === id.name)) return invalid(`${at}.name`);
const cpus = m.cpus ?? 1;
if (typeof cpus !== "number" || !Number.isInteger(cpus) || cpus < 1 || cpus > MAX_CPUS) return invalid(`${at}.cpus`);
const { memMiB } = m;
if (typeof memMiB !== "number" || !Number.isSafeInteger(memMiB) || memMiB < 1 || memMiB > MAX_MEM_MIB) {
return invalid(`${at}.memMiB`);
}
if (typeof m.image !== "string") return invalid(`${at}.image`);
if (typeof m.gateway !== "boolean") return invalid(`${at}.gateway`);
const hue = HUES.find((h) => h === m.hue) ?? invalid(`${at}.hue`);
const nics = readNics(m.nics, switches, `${at}.nics`);
for (const [k, { plug }] of nics.entries()) {
if (plug.kind === "none") continue;
if (taken.some((other) => samePort(other, plug.port))) return invalid(`${at}.nics[${k}].port`);
taken.push(plug.port);
}
const sets = readSets(m.sets, `${at}.sets`);
return {
identity: id,
failure: typeof m.failure === "string" ? m.failure : undefined,
off: m.off === true,
sets,
restore: readRestore(m.restore, sets, `${at}.restore`),
hue,
spec: {
image: m.image,
memMiB,
disks: readDisks(m.disks, `${at}.disks`),
cpus,
gateway: m.gateway,
nics: nics.map((nic) => nic.spec),
},
plugs: nics.map((nic) => nic.plug),
};
}
/** The NIC whose address the machine cannot have, as `planSpawn` would have said, or -1 when it can have them all. */
function clashingNic(spec: MachineSpec, held: ReadonlyMap<number, NicRef>): number {
const clash = addressClash(spec, held);
if (!clash) return -1;
if (clash.kind === "address-overlap") return clash.nics[1];
return spec.nics.findIndex(({ address }) => address?.ip === clash.address.ip);
}
/** Before panels parked one at a time, one `dock` was open or collapsed. */
export function restoreWorkspace(base: LabState, raw: string | null): Step {
if (raw === null) return { state: base, effects: [] };
const saved = readLab(raw);
const switches = readSwitches(saved.switches, "switches");
const switchCables = readCables(saved.cables, switches, "cables");
const vlans = readVlans(saved.vlans, switches, "vlans");
const stp = readStp(saved.stp, switches, "stp");
const priorities = readPriorities(saved.priorities, switches, "priorities");
const costs = readCosts(saved.costs, switches, "costs");
const taken: PortRef[] = switchCables.flatMap(({ ends }) => ends);
const twice = repeated(taken, samePort);
if (twice >= 0) return invalid(`cables[${Math.floor(twice / 2)}].ends[${twice % 2}]`);
const nodes: BootNode[] = [];
const addresses = new Map<number, NicRef>();
for (const [i, m] of saved.nodes.entries()) {
const at = `nodes[${i}]`;
const node = readNode(m, at, switches, taken);
const { identity: id, spec } = node;
if (nodes.some((other) => other.identity.n === id.n)) return invalid(`${at}.n`);
if (nodes.some((other) => other.identity.name === id.name)) return invalid(`${at}.name`);
const nic = clashingNic(spec, addresses);
if (nic >= 0) return invalid(`${at}.nics[${nic}].address`);
for (const { nic, address } of addressed(spec)) addresses.set(address.ip, { machine: id.name, nic });
nodes.push(node);
}
const { nextN } = saved;
if (
typeof nextN !== "number" ||
!Number.isInteger(nextN) ||
nextN > MAX_NODE + 1 ||
nextN <= Math.max(0, ...nodes.map((n) => n.identity.n))
)
return invalid("nextN");
const wired: LabState = { ...base, switches, switchCables, stp, priorities, portVlans: vlans, portCosts: costs };
const booted = bootMachines(wired, nodes, nextN, 0);
// Settled as any change is, from a lab that has none of it. A machine that failed holds no port, so the one it held
// is in VLAN 1 and costs 20000.
const settled = settleSwitches(base, booted.state);
const { state } = settled;
// The spanning tree and what each port carries and how it treats frames first, so no cable carries a frame before
// its switches have agreed on it. Then the cables, so a machine's first frame crosses them.
const effects = [...settled.effects, ...cableEffects(state), ...booted.effects];
const order = Array.isArray(saved.order) ? saved.order : [];
const sorted = [...state.rail].sort((a, b) => order.indexOf(a) - order.indexOf(b));
let panes = addPanes(base.panes, sorted);
for (const n of state.rail) if (Array.isArray(saved.parked) && saved.parked.includes(n)) panes = parkPane(panes, n);
const focus =
state.rail.find((n) => n === saved.focus && panes.parked[n] !== "user") ??
panes.order.find((n) => !panes.parked[n]);
if (focus) panes = focusPane(panes, focus);
if (focus && saved.maximised === focus) panes = toggleMaximise(panes, focus);
const policies = { ...base.agent.policies };
if (record(saved.policies))
for (const key of keysOf(policies)) {
const p = saved.policies[key];
if (p === "ask" || p === "off" || p === "run") policies[key] = p;
}
return {
effects,
state: {
...state,
panes,
keyboard: focus ? { kind: "pane", machine: focus } : { kind: "none" },
agent: { ...base.agent, policies, paused: saved.paused === true },
},
};
}