export class SpeedTestServerNotFound extends Error { constructor() { super("Server not found") } } export interface SpeedProbeEndpoints { id: string; srcServerId: number; dstServerId: number } export class SpeedRunPersistenceUnknown extends Error { constructor(public readonly runId: string, cause?: unknown) { super(`Сетевой тест завершён, сохранение результата не подтверждено. Проверьте историю по runId ${runId} перед повтором`, { cause }) } } export interface SpeedProbeContext extends SpeedProbeEndpoints { srcInterface: string; dstInterface: string; protocol: "tcp" | "udp"; direction: "both" | "transmit" | "receive"; durationSec: number } export class SpeedProbeContextChanged extends Error { constructor(message = "Параметры speed-пробы изменились. Обновите список проб перед запуском") { super(message) } } export class SpeedProbeEndpointsChanged extends SpeedProbeContextChanged { constructor() { super("Пара устройств speed-пробы изменилась. Обновите список проб перед запуском") } } export function matchesSpeedProbeEndpoints(row: unknown, target: SpeedProbeEndpoints): boolean { if (!row || typeof row !== "object") return false const probe = row as Partial return probe.id === target.id && probe.srcServerId === target.srcServerId && probe.dstServerId === target.dstServerId } export function assertSpeedProbeEndpoints(row: unknown, target: SpeedProbeEndpoints): void { if (!matchesSpeedProbeEndpoints(row, target)) throw new SpeedProbeEndpointsChanged() } export function matchesSpeedProbeContext(row: unknown, target: SpeedProbeContext): boolean { if (!matchesSpeedProbeEndpoints(row, target)) return false const probe = row as Partial return probe.srcInterface === target.srcInterface && probe.dstInterface === target.dstInterface && probe.protocol === target.protocol && probe.direction === target.direction && probe.durationSec === target.durationSec } export function assertSpeedProbeContext(row: unknown, target: SpeedProbeContext): void { assertSpeedProbeEndpoints(row, target) if (!matchesSpeedProbeContext(row, target)) throw new SpeedProbeContextChanged() } /** Changed/deleted probes retain their snapshot; history keeps the actual run without a stale association. */ export async function persistSpeedRun(target: T | null, deps: { transaction: (work: (context: C) => Promise) => Promise updateProbe: (context: C, target: T) => Promise insertRun: (context: C, associatedProbeId: string | null) => Promise }): Promise { await deps.transaction(async context => { const associated = target ? await deps.updateProbe(context, target) : false await deps.insertRun(context, associated && target ? target.id : null) }) }