Repository navigation
Expand file tree
/
Copy pathport-settings.ts
More file actions
53 lines (47 loc) · 2.24 KB
/
Copy pathport-settings.ts
File metadata and controls
53 lines (47 loc) · 2.24 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
// What the lab keeps of a port only while something is in it, as its VLAN, its cost in the spanning tree and the
// conditions of its cable are, and how the switches are told of it after every change.
import { heldPorts, samePort, type Wiring } from "./topology.ts";
import type { Effect, LabState, PortRef, SwitchName } from "./types.ts";
/** One kind of setting, read from what the lab keeps of each port that has one. */
export interface PortSetting<Held, Value> {
readonly value: (held: Held) => Value;
/** What a port with no setting has, as a new port does. */
readonly none: Value;
readonly same: (a: Value, b: Value) => boolean;
readonly effect: (port: PortRef, value: Value) => Effect;
}
type Held = Wiring & Pick<LabState, "switches">;
/** Whether a NIC's cable or one from another port is in the port, on a switch that is there. */
export function isHeld(state: Held, port: PortRef): boolean {
return state.switches.includes(port.switch) && heldPorts(state, port.switch).some((held) => held.port === port.port);
}
/** Those of the settings whose port something is in. */
export function heldSettings<T extends { readonly port: PortRef }>(state: Held, settings: readonly T[]): readonly T[] {
return settings.filter(({ port }) => isHeld(state, port));
}
/**
* What the switches are told when a port's settings go from `was` to `now`. A port that has none now is as a new
* one again, unless its switch is gone with it, and a port whose setting differs from what it had is told the new one.
*/
export function settlePortSetting<T extends { readonly port: PortRef }, Value>(
setting: PortSetting<T, Value>,
was: readonly T[],
now: readonly T[],
switches: readonly SwitchName[],
): Effect[] {
const at = (list: readonly T[], port: PortRef): Value => {
const held = list.find((other) => samePort(other.port, port));
return held ? setting.value(held) : setting.none;
};
const effects: Effect[] = [];
for (const { port } of was) {
if (switches.includes(port.switch) && !now.some((held) => samePort(held.port, port))) {
effects.push(setting.effect(port, setting.none));
}
}
for (const held of now) {
const value = setting.value(held);
if (!setting.same(at(was, held.port), value)) effects.push(setting.effect(held.port, value));
}
return effects;
}