forked from mtusi2026/mtusi2026lab7
58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import { type ReplicaBaseline, type ReplicaService } from "./failover-proof";
|
|
export type ReplicaState = {
|
|
id: string;
|
|
running: boolean;
|
|
project: string;
|
|
service: string;
|
|
started: string;
|
|
};
|
|
export function createReplicaSnapshot(ports: {
|
|
inspect: (service: ReplicaService) => Promise<ReplicaState>;
|
|
command: (args: string[]) => Promise<string>;
|
|
}) {
|
|
if (
|
|
typeof ports?.inspect !== "function" ||
|
|
typeof ports.command !== "function"
|
|
)
|
|
throw Error("REPLICA_SNAPSHOT_PORTS_REQUIRED");
|
|
return async (): Promise<ReplicaBaseline> => {
|
|
const baseline = {} as ReplicaBaseline;
|
|
for (const service of ["api1", "api2"] as const) {
|
|
const before = await ports.inspect(service);
|
|
if (
|
|
!before.running ||
|
|
before.project !== "mtuci-vp7-security" ||
|
|
before.service !== service ||
|
|
!/^[a-f0-9]{64}$/.test(before.id)
|
|
)
|
|
throw Error("FAILOVER_BASELINE_NOT_OWN_RUNNING_REPLICA");
|
|
const alias = (
|
|
await ports.command([
|
|
"docker",
|
|
"exec",
|
|
before.id,
|
|
"/bin/cat",
|
|
"/tmp/messenger-instance-id",
|
|
])
|
|
).trim();
|
|
if (
|
|
!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(
|
|
alias,
|
|
)
|
|
)
|
|
throw Error("INVALID_REPLICA_ALIAS");
|
|
const after = await ports.inspect(service);
|
|
if (
|
|
!after.running ||
|
|
after.id !== before.id ||
|
|
after.started !== before.started ||
|
|
after.project !== before.project ||
|
|
after.service !== before.service
|
|
)
|
|
throw Error("FAILOVER_REPLICA_CHANGED_DURING_READ");
|
|
baseline[service] = { container: before.id, alias };
|
|
}
|
|
return baseline;
|
|
};
|
|
}
|