From faaa22b608bde44547f7eabd848aaa73b4dd842a Mon Sep 17 00:00:00 2001 From: "HomePC\\Kevin" Date: Sat, 5 Dec 2026 11:03:15 +0100 Subject: [PATCH 1/3] refactor(monitoring): retire built-in monitoring --- .../scripts/ci/worker-postgres-evidence.sh | 2 +- .github/workflows/arm64-appliance.yml | 2 +- .github/workflows/production-smokes.yml | 2 +- .github/workflows/runtime-reliability.yml | 2 +- .../Types/background-evidence.types.ts | 2 +- .../runtime-scale/Types/background.types.ts | 17 - .../runtime-scale/Types/monitoring.types.ts | 16 - .../runtime-scale/background-capture-read.ts | 59 - .../background-capture-settlement.ts | 97 -- scripts/runtime-scale/background-capture.ts | 115 -- .../background-contention-fixture.ts | 3 +- .../background-contention-run.ts | 23 +- .../runtime-scale/background-contention.ts | 8 +- scripts/runtime-scale/background-evidence.ts | 32 +- scripts/runtime-scale/background-extended.ts | 110 +- scripts/runtime-scale/background-fixture.ts | 528 +----- scripts/runtime-scale/background-network.ts | 36 - scripts/runtime-scale/background-recovery.ts | 6 - scripts/runtime-scale/background-run.ts | 150 +- .../runtime-scale/background-source.config.ts | 2 - scripts/runtime-scale/background.ts | 258 +-- .../runtime-scale/background.validation.ts | 56 - scripts/runtime-scale/monitoring-native.ts | 95 -- scripts/runtime-scale/monitoring.ts | 719 -------- web/src/config/app-requirements.config.ts | 2 +- web/src/config/background-workers.config.ts | 1 - web/src/config/host-monitoring-ui.config.ts | 4 - web/src/config/host-monitoring.config.ts | 42 +- .../Components/MonitoringCheckStrip.tsx | 62 - .../Hooks/useMonitoringChecksTableLogic.ts | 161 -- .../Types/checks-table.types.ts | 24 - .../MonitoringChecksTable/index.tsx | 51 - .../Hooks/useMonitoringDurationChartLogic.ts | 76 - .../Types/duration-chart.types.ts | 5 - .../MonitoringDurationChart/index.tsx | 15 - .../Components/MonitoringOverview.tsx | 98 -- .../Hooks/useHostMonitoringDialogLogic.ts | 413 ----- .../Types/host-monitoring-dialog.types.ts | 69 - .../features/Admin/HostMonitoring/index.tsx | 252 --- .../Components/HostAvailabilityBadge.tsx | 25 +- .../Components/ProxyHostAppMonitoringCell.tsx | 12 +- .../Components/ProxyHostMonitoringCell.tsx | 39 - .../Hooks/useProxyHostsTableColumns.ts | 22 +- .../Hooks/useProxyHostsTableLogic.ts | 33 +- .../Types/table-logic.types.ts | 8 +- .../Components/ProxyHostsTable/index.tsx | 111 +- .../Hooks/useHostMonitoringAppSummaries.ts | 29 +- .../Hooks/useHostMonitoringSummaries.ts | 120 -- .../Hooks/useProxyHostManagementLogic.ts | 19 - .../Types/host-monitoring-overview.types.ts | 23 +- .../Types/management-logic.types.ts | 3 - .../Types/proxy-host-table.types.ts | 4 +- .../Admin/ProxyHostManagement/index.tsx | 21 - .../Types/table-actions.types.ts | 1 - .../proxyHostTableActions.ts | 10 - .../Types/host-monitoring-client.types.ts | 47 - .../host-monitoring-presentation.types.ts | 13 - .../Types/host-monitoring.types.ts | 67 - .../lib/HostMonitoring/hostMonitoringCache.ts | 4 - .../HostMonitoring/hostMonitoringClient.ts | 117 +- .../HostMonitoring/hostMonitoringResponses.ts | 87 +- web/src/lib/HostMonitoring/presentation.ts | 36 - web/src/lib/HostMonitoring/state.ts | 118 -- web/src/lib/HostMonitoring/validation.ts | 60 +- web/src/lib/Language/Locales/de.json | 105 +- web/src/lib/Language/Locales/en.json | 105 +- web/src/lib/Language/Locales/es.json | 105 +- web/src/lib/Language/Locales/fr.json | 105 +- web/src/lib/Language/Locales/it.json | 105 +- web/src/lib/Language/Locales/nl.json | 105 +- web/src/lib/Language/Locales/pl.json | 105 +- web/src/lib/Language/Locales/pt.json | 105 +- web/src/routeTree.gen.ts | 66 - .../routes/api/admin/monitoring/history.ts | 8 - web/src/routes/api/admin/monitoring/policy.ts | 13 - .../routes/api/admin/monitoring/summary.ts | 8 - .../Types/host-monitoring-batch.types.ts | 11 - .../Types/host-monitoring-http.types.ts | 6 - .../Types/host-monitoring-probe.types.ts | 27 +- .../Types/host-monitoring-service.types.ts | 8 - .../Types/host-monitoring-worker.types.ts | 21 - .../Types/host-monitoring.repository.types.ts | 46 - .../host-monitoring-app-response.server.ts | 27 +- .../host-monitoring-response.server.ts | 137 -- .../HostMonitoring/host-monitoring.batch.ts | 74 - .../host-monitoring.capture.server.ts | 94 -- .../HostMonitoring/host-monitoring.capture.ts | 182 --- .../HostMonitoring/host-monitoring.errors.ts | 12 +- .../host-monitoring.execution.ts | 542 ------ .../host-monitoring.handoff.server.ts | 12 +- .../host-monitoring.observability.ts | 57 - .../HostMonitoring/host-monitoring.probe.ts | 62 - .../host-monitoring.repository.ts | 276 +--- .../HostMonitoring/host-monitoring.service.ts | 282 ---- .../HostMonitoring/host-monitoring.storage.ts | 146 +- .../host-monitoring.worker.server.ts | 204 --- .../HostMonitoring/host-monitoring.worker.ts | 285 ---- .../LegacyHandoff/worker-admission.server.ts | 8 - .../Types/notification-internal.types.ts | 10 - .../Types/notification-state.types.ts | 10 - .../host-availability.repository.ts | 70 +- .../server/Notifications/host-availability.ts | 109 +- .../server/ProxyRuntime/proxy-runtime-data.ts | 7 + .../domain-diagnostics-data.ts | 66 +- web/src/start.ts | 31 - web/src/tests/Helpers/historicalHostOutage.ts | 47 + .../HostMonitoring/checks-table.test.tsx | 194 --- .../HostMonitoring/duration-chart.test.tsx | 226 --- .../monitoring-check-strip.test.tsx | 122 -- .../HostMonitoring/monitoring-dialog.test.tsx | 873 ---------- .../proxy-hosts-ui.test.tsx | 275 +--- .../row-action-stability.test.tsx | 1 - .../hostMonitoringClient.test.ts | 266 +-- .../lib/HostMonitoring/presentation.test.ts | 59 - .../tests/lib/HostMonitoring/state.test.ts | 254 --- .../lib/HostMonitoring/validation.test.ts | 112 -- .../background-worker-report.test.ts | 4 +- .../api/route-contracts.coverage.test.ts | 12 - .../server/AppRuntime/upstream-probes.test.ts | 11 +- .../Foundation/worker-lifecycle.test.ts | 4 +- .../Foundation/worker-lock-order.db.test.ts | 229 +-- .../Foundation/worker-operation.test.ts | 23 +- .../worker-postgres-profile.db.test.ts | 166 -- .../host-monitoring-app.service.test.ts | 17 +- .../host-monitoring-cleanup-admission.test.ts | 109 -- .../host-monitoring-fence.db.test.ts | 544 ++---- .../host-monitoring-handoff.db.test.ts | 546 +++---- .../host-monitoring-observability.test.ts | 145 -- .../host-monitoring-release-batch.test.ts | 167 -- .../host-monitoring-response.test.ts | 462 ------ ...ost-monitoring-service.coverage.db.test.ts | 196 --- .../host-monitoring.batch.test.ts | 123 -- ...ost-monitoring.capture-publication.test.ts | 354 ---- .../host-monitoring.capture.test.ts | 328 ---- .../host-monitoring.probe.test.ts | 301 ---- .../host-monitoring.repository.db.test.ts | 1453 ----------------- .../host-monitoring.service.db.test.ts | 503 ------ .../host-monitoring.service.test.ts | 45 - .../host-monitoring.worker.test.ts | 844 ---------- .../server/LegacyHandoff/worker-gate.test.ts | 4 +- .../Notifications/backup-outcomes.test.ts | 9 +- .../host-availability-handover.test.ts | 5 +- .../host-availability.db.test.ts | 403 ++--- .../Notifications/host-availability.test.ts | 364 +---- .../server/Updates/upgrade-preview.test.ts | 8 +- web/src/tests/start.coverage.test.ts | 22 +- .../production-smokes-workflow.test.ts | 50 +- .../monitoring-signal.db.test.ts | 97 -- .../tooling/runtime-scale/monitoring.test.ts | 281 ---- .../runtime-reliability/harness-dns.test.ts | 11 +- .../background-capture-read.test.ts | 69 - .../background-capture-settlement.test.ts | 145 -- .../runtime-scale/background-capture.test.ts | 40 - .../background-contention-cleanup.test.ts | 10 +- .../background-contention.test.ts | 16 +- .../runtime-scale/background-evidence.test.ts | 171 +- .../runtime-scale/background-extended.test.ts | 49 - .../background-inventory.db.test.ts | 264 --- .../background-provenance.test.ts | 26 + .../runtime-scale/background-recovery.test.ts | 4 +- .../background-telemetry.test.ts | 218 --- .../runtime-scale/background.db.test.ts | 60 +- .../scripts/runtime-scale/background.test.ts | 192 +-- 163 files changed, 1286 insertions(+), 18648 deletions(-) delete mode 100644 scripts/runtime-scale/Types/monitoring.types.ts delete mode 100644 scripts/runtime-scale/background-capture-read.ts delete mode 100644 scripts/runtime-scale/background-capture-settlement.ts delete mode 100644 scripts/runtime-scale/background-capture.ts delete mode 100644 scripts/runtime-scale/background-network.ts delete mode 100644 scripts/runtime-scale/monitoring-native.ts delete mode 100644 scripts/runtime-scale/monitoring.ts delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Hooks/useMonitoringChecksTableLogic.ts delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Types/checks-table.types.ts delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/index.tsx delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Types/duration-chart.types.ts delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx delete mode 100644 web/src/features/Admin/HostMonitoring/Components/MonitoringOverview.tsx delete mode 100644 web/src/features/Admin/HostMonitoring/Hooks/useHostMonitoringDialogLogic.ts delete mode 100644 web/src/features/Admin/HostMonitoring/Types/host-monitoring-dialog.types.ts delete mode 100644 web/src/features/Admin/HostMonitoring/index.tsx rename web/src/features/Admin/{HostMonitoring => ProxyHostManagement/Components/ProxyHostsTable}/Components/HostAvailabilityBadge.tsx (54%) delete mode 100644 web/src/features/Admin/ProxyHostManagement/Components/ProxyHostsTable/Components/ProxyHostMonitoringCell.tsx delete mode 100644 web/src/features/Admin/ProxyHostManagement/Hooks/useHostMonitoringSummaries.ts delete mode 100644 web/src/lib/HostMonitoring/Types/host-monitoring-client.types.ts delete mode 100644 web/src/lib/HostMonitoring/Types/host-monitoring-presentation.types.ts delete mode 100644 web/src/lib/HostMonitoring/presentation.ts delete mode 100644 web/src/lib/HostMonitoring/state.ts delete mode 100644 web/src/routes/api/admin/monitoring/history.ts delete mode 100644 web/src/routes/api/admin/monitoring/policy.ts delete mode 100644 web/src/routes/api/admin/monitoring/summary.ts delete mode 100644 web/src/server/HostMonitoring/Types/host-monitoring-batch.types.ts delete mode 100644 web/src/server/HostMonitoring/Types/host-monitoring-http.types.ts delete mode 100644 web/src/server/HostMonitoring/Types/host-monitoring-service.types.ts delete mode 100644 web/src/server/HostMonitoring/Types/host-monitoring-worker.types.ts delete mode 100644 web/src/server/HostMonitoring/Types/host-monitoring.repository.types.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring-response.server.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.batch.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.capture.server.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.capture.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.execution.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.observability.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.probe.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.service.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.worker.server.ts delete mode 100644 web/src/server/HostMonitoring/host-monitoring.worker.ts create mode 100644 web/src/tests/Helpers/historicalHostOutage.ts delete mode 100644 web/src/tests/features/Admin/HostMonitoring/checks-table.test.tsx delete mode 100644 web/src/tests/features/Admin/HostMonitoring/duration-chart.test.tsx delete mode 100644 web/src/tests/features/Admin/HostMonitoring/monitoring-check-strip.test.tsx delete mode 100644 web/src/tests/features/Admin/HostMonitoring/monitoring-dialog.test.tsx delete mode 100644 web/src/tests/lib/HostMonitoring/presentation.test.ts delete mode 100644 web/src/tests/lib/HostMonitoring/state.test.ts delete mode 100644 web/src/tests/lib/HostMonitoring/validation.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring-cleanup-admission.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring-observability.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring-release-batch.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring-response.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring-service.coverage.db.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.batch.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.capture-publication.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.capture.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.probe.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.repository.db.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.service.db.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.service.test.ts delete mode 100644 web/src/tests/server/HostMonitoring/host-monitoring.worker.test.ts delete mode 100644 web/src/tests/tooling/runtime-scale/monitoring-signal.db.test.ts delete mode 100644 web/src/tests/tooling/runtime-scale/monitoring.test.ts delete mode 100644 web/src/tests/tooling/scripts/runtime-scale/background-capture-read.test.ts delete mode 100644 web/src/tests/tooling/scripts/runtime-scale/background-capture-settlement.test.ts delete mode 100644 web/src/tests/tooling/scripts/runtime-scale/background-capture.test.ts delete mode 100644 web/src/tests/tooling/scripts/runtime-scale/background-extended.test.ts delete mode 100644 web/src/tests/tooling/scripts/runtime-scale/background-inventory.db.test.ts delete mode 100644 web/src/tests/tooling/scripts/runtime-scale/background-telemetry.test.ts diff --git a/.github/scripts/ci/worker-postgres-evidence.sh b/.github/scripts/ci/worker-postgres-evidence.sh index b55c927b2..498ad0798 100644 --- a/.github/scripts/ci/worker-postgres-evidence.sh +++ b/.github/scripts/ci/worker-postgres-evidence.sh @@ -48,5 +48,5 @@ if [ "$mode" = profile ]; then bun --no-env-file test --max-concurrency=1 --isolate ./web/src/tests/server/Foundation/worker-postgres-profile.db.test.ts 2>&1 | tee "$reports/profile.log" else export RENTNERPROXY_POSTGRES_PROFILE=0 - bun --no-env-file test --max-concurrency=1 --isolate ./web/src/tests/server/Foundation/background-database.db.test.ts ./web/src/tests/server/Foundation/worker-lock-order.db.test.ts ./web/src/tests/server/HostMonitoring/host-monitoring.repository.db.test.ts ./web/src/tests/server/Notifications/notification-repository.db.test.ts 2>&1 | tee "$reports/regressions.log" + bun --no-env-file test --max-concurrency=1 --isolate ./web/src/tests/server/Foundation/background-database.db.test.ts ./web/src/tests/server/Foundation/worker-lock-order.db.test.ts ./web/src/tests/server/HostMonitoring/host-monitoring-fence.db.test.ts ./web/src/tests/server/HostMonitoring/host-monitoring-handoff.db.test.ts ./web/src/tests/server/Notifications/notification-repository.db.test.ts 2>&1 | tee "$reports/regressions.log" fi diff --git a/.github/workflows/arm64-appliance.yml b/.github/workflows/arm64-appliance.yml index d60c41869..8affc8f95 100644 --- a/.github/workflows/arm64-appliance.yml +++ b/.github/workflows/arm64-appliance.yml @@ -147,7 +147,7 @@ jobs: - name: Native bounded background worker correctness scenarios if: env.RUN_CHECK == 'true' - run: 'bun --no-env-file --no-orphans scripts/runtime-scale/background-run.ts --policies 100 --duration-seconds 120 --image "rentnerproxy-smoke-${RENTNERPROXY_SMOKE_RUN}:appliance" --report "$RUNNER_TEMP/background-workers.json"' + run: 'bun --no-env-file --no-orphans scripts/runtime-scale/background-run.ts --duration-seconds 120 --image "rentnerproxy-smoke-${RENTNERPROXY_SMOKE_RUN}:appliance" --report "$RUNNER_TEMP/background-workers.json"' - name: Store bounded ARM64 background report if: ${{ env.RUN_CHECK == 'true' && always() }} diff --git a/.github/workflows/production-smokes.yml b/.github/workflows/production-smokes.yml index 85c15f123..d4ad1a9a1 100644 --- a/.github/workflows/production-smokes.yml +++ b/.github/workflows/production-smokes.yml @@ -380,7 +380,7 @@ jobs: run: 'bun --no-env-file --no-orphans scripts/runtime-reliability/run.ts --profile short --image "rentnerproxy-smoke-${RENTNERPROXY_SMOKE_RUN}:appliance" --capture-resources true --report "$RUNNER_TEMP/runtime-reliability-report/report.json"' - name: Run bounded background worker correctness scenarios if: needs.changes.outputs.runtime == 'true' - run: 'bun --no-env-file --no-orphans scripts/runtime-scale/background-run.ts --policies 100 --duration-seconds 120 --image "rentnerproxy-smoke-${RENTNERPROXY_SMOKE_RUN}:appliance" --report "$RUNNER_TEMP/runtime-reliability-report/background.json"' + run: 'bun --no-env-file --no-orphans scripts/runtime-scale/background-run.ts --duration-seconds 120 --image "rentnerproxy-smoke-${RENTNERPROXY_SMOKE_RUN}:appliance" --report "$RUNNER_TEMP/runtime-reliability-report/background.json"' - name: "Remove this run's private Docker resources" if: "always() && steps.bun.outcome == 'success'" run: bun --no-env-file .github/scripts/ci/production-smoke-ci.ts cleanup diff --git a/.github/workflows/runtime-reliability.yml b/.github/workflows/runtime-reliability.yml index 41379210b..373071ea5 100644 --- a/.github/workflows/runtime-reliability.yml +++ b/.github/workflows/runtime-reliability.yml @@ -142,7 +142,7 @@ jobs: env: SEED: ${{ inputs.seed }} run: | - args=(--policies 100 --duration-seconds 120 --extended-recovery true --image "rentnerproxy-reliability-${RENTNERPROXY_SMOKE_RUN}:current" --report "$RUNNER_TEMP/runtime-reliability-report/report.json") + args=(--duration-seconds 120 --extended-recovery true --image "rentnerproxy-reliability-${RENTNERPROXY_SMOKE_RUN}:current" --report "$RUNNER_TEMP/runtime-reliability-report/report.json") if [ -n "$SEED" ]; then args+=(--seed "$SEED"); fi bun --no-env-file --no-orphans scripts/runtime-scale/background-run.ts "${args[@]}" diff --git a/scripts/runtime-scale/Types/background-evidence.types.ts b/scripts/runtime-scale/Types/background-evidence.types.ts index 3d475b7bb..b20c9c3a0 100644 --- a/scripts/runtime-scale/Types/background-evidence.types.ts +++ b/scripts/runtime-scale/Types/background-evidence.types.ts @@ -12,7 +12,7 @@ export type BackgroundRecoveryEvidence = { runId: string reportSha256: string elapsedMs: number - schedulerAdmissions: number + deferredDeliveries: number deferredIdentities: number faults: readonly string[] capacity: 'insufficient' diff --git a/scripts/runtime-scale/Types/background.types.ts b/scripts/runtime-scale/Types/background.types.ts index 967ee2189..1062e2e51 100644 --- a/scripts/runtime-scale/Types/background.types.ts +++ b/scripts/runtime-scale/Types/background.types.ts @@ -3,10 +3,7 @@ import type { backgroundSnapshotSchema } from '../background.validation.ts' import type { ResourceSample } from '../../runtime-reliability/Types/control.types.ts' export type BackgroundOptions = { - policies: 100 | 500 | 1000 seed: number - pattern: 'simultaneous' | 'staggered' - profile: 'mixed' | 'healthy' | 'slow' | 'timeout' durationSeconds: number image?: string reportPath?: string @@ -14,13 +11,6 @@ export type BackgroundOptions = { contention?: true } -export type BackgroundPolicy = { - id: string - index: number - latency: 'healthy' | 'slow' | 'timeout' | 'failure' - offsetMs: number -} - export type BackgroundSnapshot = z.output export type BackgroundResourceSample = { kind: 'continuous' | 'recovered' @@ -28,10 +18,3 @@ export type BackgroundResourceSample = { warmup: boolean sample: Omit & { phase: 'continuous' | 'recovered' } } - -export type BackgroundReceipt = { - index: number - startedAt: number - finishedAt: number | null - latency: BackgroundPolicy['latency'] -} diff --git a/scripts/runtime-scale/Types/monitoring.types.ts b/scripts/runtime-scale/Types/monitoring.types.ts deleted file mode 100644 index f5c2558bb..000000000 --- a/scripts/runtime-scale/Types/monitoring.types.ts +++ /dev/null @@ -1,16 +0,0 @@ -export interface MonitoringScaleOptions { - hosts: 100 | 500 | 1000 - periods: 2 | 3 - profile: 'mixed' | 'slow' | 'timeout' - runtime?: 'native' - timeoutMs?: 10000 - scheduler?: 'legacy' -} - -export interface MonitoringDistribution { - count: number - p95: number | null - p99: number | null - max: number | null - total: number -} diff --git a/scripts/runtime-scale/background-capture-read.ts b/scripts/runtime-scale/background-capture-read.ts deleted file mode 100644 index d98487f4c..000000000 --- a/scripts/runtime-scale/background-capture-read.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { readBackgroundCapture } from './background-capture.ts' - -/** Fixed capture-only entry: no fixture context, SQL client, business module, or arbitrary command/path is accepted. */ -export async function runBackgroundCaptureRead(args: readonly string[]) { - const [runId] = args - if ( - args.length !== 1 || - !runId || - !/^[a-f0-9]{12}$/u.test(runId) || - process.env.RENTNERPROXY_BACKGROUND_CAPTURE_RUN !== runId || - !/^[a-f0-9]{40}$/u.test(process.env.RENTNERPROXY_BACKGROUND_CAPTURE_SOURCE_SHA ?? '') - ) - throw new Error('Invalid capture read request') - return { capture: await readBackgroundCapture(runId) } -} - -/** Client and remote deadlines are independent: Docker transport loss never proves remote drain; final container cleanup retains ownership. */ -export function backgroundCaptureReadCommand( - container: string, - runId: string, - remainingMs: number, -) { - if ( - !/^[a-z0-9][a-z0-9_.-]{0,127}$/u.test(container) || - !/^[a-f0-9]{12}$/u.test(runId) || - !Number.isFinite(remainingMs) || - remainingMs <= 250 - ) - throw new Error('Invalid bounded capture command') - const remoteTimeoutMs = Math.min(1000, Math.max(1, Math.floor(remainingMs - 250))) - return { - args: [ - 'exec', - '--workdir', - '/opt/rentnerproxy/web', - container, - '/usr/bin/timeout', - '--signal=KILL', - (remoteTimeoutMs / 1000).toFixed(3) + 's', - 'gosu', - 'rentnerproxy-web', - 'bun', - '--no-env-file', - '/opt/rentnerproxy/web/background-capture-read.js', - runId, - ], - clientTimeoutMs: remainingMs, - remoteTimeoutMs, - } -} - -if (import.meta.main) { - try { - console.log(JSON.stringify(await runBackgroundCaptureRead(process.argv.slice(2)))) - } catch { - console.error('Background capture read unavailable') - process.exitCode = 1 - } -} diff --git a/scripts/runtime-scale/background-capture-settlement.ts b/scripts/runtime-scale/background-capture-settlement.ts deleted file mode 100644 index a7b76148e..000000000 --- a/scripts/runtime-scale/background-capture-settlement.ts +++ /dev/null @@ -1,97 +0,0 @@ -// oxlint-disable no-await-in-loop -- Each bounded read observes publication progress from the real web owner. -import { checkBackgroundCancellation } from './background-pause.ts' -import type { BackgroundSnapshot } from './Types/background.types.ts' - -/** Require one admission and exactly one same-attempt start for every observation already inside the workload window. */ -function coversObservedAttempts( - snapshot: BackgroundSnapshot, - expected: { runId: string; sourceSha: string }, -) { - const capture = snapshot.schedulerCapture - if ( - !capture || - capture.runId !== expected.runId || - capture.sourceSha !== expected.sourceSha || - capture.overflowed || - capture.clockRegressed || - capture.expired || - capture.publication.fd === null || - capture.publication.generation === 0 - ) - return false - return snapshot.observations.every((observation) => { - const policy = snapshot.policies.find( - (item) => - item.id === observation.policyId && item.version === observation.policyVersion, - ) - if (!policy) return false - const events = capture.events.filter( - (event) => - event.policyId === policy.id && - event.policyVersion === policy.version && - event.dueAt === policy.dueAt, - ) - const admissions = events.filter((event) => event.kind === 'admitted') - const starts = events.filter((event) => event.kind === 'started') - return ( - admissions.length === 1 && - starts.length === 1 && - admissions[0]!.attemptHash === starts[0]!.attemptHash && - admissions[0]!.at >= policy.dueAt && - starts[0]!.at >= admissions[0]!.at && - starts[0]!.monotonicMs >= admissions[0]!.monotonicMs - ) - }) -} - -/** Reread persisted capture under a bounded client wait; the caller separately bounds remote read-only execution and retains container cleanup ownership. */ -export async function settleBackgroundCapture( - initial: BackgroundSnapshot, - expected: { runId: string; sourceSha: string }, - dependencies: { - signal: AbortSignal - /** Bound the client wait by remainingMs; a separate remote timeout and final container cleanup must own remote work after transport loss. */ - read: (remainingMs: number) => Promise - now?: () => number - sleep?: (milliseconds: number) => Promise - }, - timeoutMs = 2_000, -) { - if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) - throw new Error('Capture settlement deadline must be finite and positive') - const now = dependencies.now ?? performance.now.bind(performance) - const sleep = dependencies.sleep ?? Bun.sleep - const started = now() - const budgetMs = Math.max(1, Math.min(timeoutMs, 2_000)) - const deadline = started + budgetMs - let snapshot = initial - let reads = 0 - const result = (status: 'complete' | 'deadline' | 'unavailable' | 'not-required') => ({ - snapshot, - status, - reads, - budgetMs, - elapsedMs: Math.max(0, now() - started), - }) - checkBackgroundCancellation(dependencies.signal) - if (!initial.observations.length) return result('not-required') - while (!coversObservedAttempts(snapshot, expected)) { - checkBackgroundCancellation(dependencies.signal) - const remainingMs = deadline - now() - if (remainingMs <= 250) return result('deadline') - try { - reads++ - const observed = await dependencies.read(remainingMs) - checkBackgroundCancellation(dependencies.signal) - if (now() > deadline) return result('deadline') - snapshot = { ...initial, schedulerCapture: observed.schedulerCapture } - } catch { - checkBackgroundCancellation(dependencies.signal) - return result(now() >= deadline ? 'deadline' : 'unavailable') - } - if (!coversObservedAttempts(snapshot, expected)) - await sleep(Math.min(25, Math.max(0, deadline - now()))) - } - checkBackgroundCancellation(dependencies.signal) - return result('complete') -} diff --git a/scripts/runtime-scale/background-capture.ts b/scripts/runtime-scale/background-capture.ts deleted file mode 100644 index 25ccaaaf7..000000000 --- a/scripts/runtime-scale/background-capture.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { open, stat } from 'node:fs/promises' -import { constants } from 'node:fs' -import type { BigIntStats } from 'node:fs' -import { hostMonitoringCaptureSchema } from '../../web/src/server/HostMonitoring/host-monitoring.capture.ts' -import { readRuntimeProcesses } from '../smoke/appliance-processes.ts' -import type { HostMonitoringCapture } from '../../web/src/server/HostMonitoring/host-monitoring.capture.ts' - -type Owner = { pid: number; startTicks: string; state: string } -/** Open once without following links or blocking on a FIFO, then bound every byte read from that same regular inode. */ -async function withBoundedBackgroundCapture( - path: string, - observe: (text: string, identity: BigIntStats) => Promise, -) { - const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK) - try { - const identity = await file.stat({ bigint: true }) - const maximum = 8 * 1024 * 1024 - if (!identity.isFile() || identity.size > BigInt(maximum)) return null - const fileSize = Number(identity.size) - const buffer = Buffer.alloc(Math.min(fileSize + 1, maximum + 1)) - let size = 0 - while (size < buffer.length) { - // oxlint-disable-next-line no-await-in-loop -- Read only from the opened inode under one fixed byte bound. - const { bytesRead } = await file.read(buffer, size, buffer.length - size, size) - if (!bytesRead) break - size += bytesRead - } - if (size > fileSize || size > maximum) return null - return await observe(buffer.subarray(0, size).toString('utf8'), identity) - } finally { - await file.close() - } -} - -/** Preserve the bounded raw-file helper; authority requires the separate live descriptor lease validation below. */ -export function readBoundedBackgroundCapture(path: string) { - return withBoundedBackgroundCapture(path, async (text) => text) -} - -async function ownerHoldsPublication(capture: HostMonitoringCapture, opened: BigIntStats) { - const fd = capture.publication.fd - if (fd === null || capture.publication.generation === 0) return false - try { - const held = await stat('/proc/' + capture.pid + '/fd/' + fd, { bigint: true }) - return held.isFile() && held.dev === opened.dev && held.ino === opened.ino - } catch { - return false - } -} -/** Compare both census brackets; neither PID reuse nor a child-process capture establishes serving-owner evidence. */ -export function backgroundCaptureMatchesOwner( - capture: HostMonitoringCapture, - expected: { runId: string; sourceSha: string | undefined }, - before: Owner[], - after: Owner[], - now: number, -) { - return ( - before.length === 1 && - after.length === 1 && - !['Z', 'X'].includes(before[0]!.state) && - !['Z', 'X'].includes(after[0]!.state) && - capture.runId === expected.runId && - capture.sourceSha === expected.sourceSha && - capture.pid === before[0]!.pid && - capture.processStartTicks === before[0]!.startTicks && - before[0]!.pid === after[0]!.pid && - before[0]!.startTicks === after[0]!.startTicks && - now >= capture.createdAt && - now <= capture.expiresAt - ) -} - -/** Hold the opened artifact through both lease checks; pathname cleanup failure and descriptor reuse cannot revive an obsolete inode. */ -export async function readLeasedBackgroundCapture( - path: string, - expected: { runId: string; sourceSha: string | undefined }, - owners: () => Promise = async () => - (await readRuntimeProcesses()).filter( - (owner) => owner.role === 'web' && owner.pid !== process.pid, - ), - now: () => number = Date.now, -) { - try { - const before = await owners() - const captured = await withBoundedBackgroundCapture(path, async (text, opened) => { - const capture = hostMonitoringCaptureSchema.parse(JSON.parse(text)) - if (!(await ownerHoldsPublication(capture, opened))) return null - const after = await owners() - if ( - !backgroundCaptureMatchesOwner(capture, expected, before, after, now()) || - !(await ownerHoldsPublication(capture, opened)) - ) - return null - return capture - }) - if (!captured) return null - // The held artifact has been closed too. No await may follow this final time qualification. - const qualifiedAt = now() - return qualifiedAt >= captured.createdAt && qualifiedAt <= captured.expiresAt - ? captured - : null - } catch { - return null - } -} - -/** Missing, stale, unleased or mismatched capture is unavailable; no network receipt can substitute for it. */ -export function readBackgroundCapture(runId: string) { - if (!/^[a-f0-9]{12}$/u.test(runId)) return Promise.resolve(null) - return readLeasedBackgroundCapture('/tmp/rentnerproxy-background-capture-' + runId + '.json', { - runId, - sourceSha: process.env.RENTNERPROXY_BACKGROUND_CAPTURE_SOURCE_SHA, - }) -} diff --git a/scripts/runtime-scale/background-contention-fixture.ts b/scripts/runtime-scale/background-contention-fixture.ts index c98a5e775..8572aea78 100644 --- a/scripts/runtime-scale/background-contention-fixture.ts +++ b/scripts/runtime-scale/background-contention-fixture.ts @@ -244,9 +244,8 @@ export async function backgroundContentionFixture(context: FixtureContext) { active: number lockWaiters: number idleTransactions: number - monitoringLeases: number }>( - sql`select count(*)::int as connections, count(*) filter (where state = 'active' and pid <> pg_backend_pid())::int as active, count(*) filter (where wait_event_type = 'Lock')::int as "lockWaiters", count(*) filter (where state = 'idle in transaction')::int as "idleTransactions", (select count(*)::int from rentnerproxy.host_check_policies where lease_expires_at > clock_timestamp()) as "monitoringLeases" from pg_stat_activity where datname = current_database()`, + sql`select count(*)::int as connections, count(*) filter (where state = 'active' and pid <> pg_backend_pid())::int as active, count(*) filter (where wait_event_type = 'Lock')::int as "lockWaiters", count(*) filter (where state = 'idle in transaction')::int as "idleTransactions" from pg_stat_activity where datname = current_database()`, ), ]) const { runtime, configuration, observedAt } = notificationSnapshot diff --git a/scripts/runtime-scale/background-contention-run.ts b/scripts/runtime-scale/background-contention-run.ts index 364b90643..d6e724bfe 100644 --- a/scripts/runtime-scale/background-contention-run.ts +++ b/scripts/runtime-scale/background-contention-run.ts @@ -66,10 +66,7 @@ export async function runContentionWindow( ) { const context = harness.context const extra = { - policyCount: options.policies, seed: options.seed, - duePattern: options.pattern, - backgroundProfile: options.profile, contention: true, } console.log(JSON.stringify({ predeclaredContentionContract: contentionContract })) @@ -162,7 +159,7 @@ export async function runContentionWindow( checkBackgroundCancellation(signal) started() const began = performance.now() - const begin = await context.fixture('background-start', extra) + const begin = await context.fixture('background-read', extra) checkBackgroundCancellation(signal) snapshot = backgroundSnapshotSchema.parse(begin.background) await context.waitFor( @@ -170,9 +167,15 @@ export async function runContentionWindow( checkBackgroundCancellation(signal) const value = await context.fixture('background-contention-read', extra) checkBackgroundCancellation(signal) - return contentionStateSchema.parse(value.contention).postgres.monitoringLeases > 0 + const state = contentionStateSchema.parse(value.contention) + const receiver = await control() + return ( + state.notification.inflight > 0 && + receiver.notifications.activeWebhooks + receiver.notifications.smtpConnections > + 0 + ) }, - 'Actual monitoring leases are active before arming the mixed event burst', + 'Actual notification sends are active before arming the mixed event burst', 10000, ) checkBackgroundCancellation(signal) @@ -185,7 +188,6 @@ export async function runContentionWindow( const baselineNative = await native() while (performance.now() - began < options.durationSeconds * 1000) { checkBackgroundCancellation(signal) - const captureStarted = performance.now() const envelope = await context.fixture('background-read', extra) checkBackgroundCancellation(signal) snapshot = backgroundSnapshotSchema.parse(envelope.background) @@ -233,8 +235,6 @@ export async function runContentionWindow( samples.push({ elapsedMs: performance.now() - began, criticalObservedMs: critical.value.observedAt - baselineNative.observedAt, - captureSpanMs: performance.now() - captureStarted, - leasedPolicies: state.postgres.monitoringLeases, managementMs: read.value, proxyMs: proxy.value, state, @@ -244,11 +244,6 @@ export async function runContentionWindow( web: web.value, processMemory: readMemoryObservation(resource.value), }) - if ( - snapshot.observations.length >= options.policies && - performance.now() - began >= 35000 - ) - break await Bun.sleep(100) } checkBackgroundCancellation(signal) diff --git a/scripts/runtime-scale/background-contention.ts b/scripts/runtime-scale/background-contention.ts index 21f511e88..16c6f8ee2 100644 --- a/scripts/runtime-scale/background-contention.ts +++ b/scripts/runtime-scale/background-contention.ts @@ -45,7 +45,6 @@ export const contentionStateSchema = z.strictObject({ active: count, lockWaiters: count, idleTransactions: count, - monitoringLeases: count, }), }) export const contentionReceiverSchema = z.strictObject({ @@ -79,8 +78,6 @@ export type ContentionSample = { processMemory?: ReturnType elapsedMs: number criticalObservedMs: number - captureSpanMs: number - leasedPolicies: number managementMs: number proxyMs: number state: z.output @@ -131,7 +128,6 @@ export function buildContentionReport( const management = backgroundDistribution(samples.map((item) => item.managementMs)) const proxy = backgroundDistribution(samples.map((item) => item.proxyMs)) const isMixedOverlap = (item: ContentionSample) => - item.leasedPolicies > 0 && item.state.notification.inflight > 0 && item.receiver.notifications.activeWebhooks + item.receiver.notifications.smtpConnections > 0 const overlap = samples.filter(isMixedOverlap) @@ -223,7 +219,6 @@ export function buildContentionReport( item.revisionUnchanged && item.state.notification.inflight <= 8 && item.state.notification.pending + item.state.notification.inflight <= 256 && - item.leasedPolicies <= 64 && item.state.postgres.connections <= 100, ) && management.p95! <= contentionContract.targets.managementP95Ms && @@ -242,7 +237,7 @@ export function buildContentionReport( processMemoryComplete, memoryMeasurementSemantics, }, - model: 'Actual appliance notification, monitoring and discovery workers; controlled private slow receivers and Docker events; no manual delivery driver', + model: 'Actual appliance notification and discovery workers; controlled private slow receivers and Docker events; no manual delivery driver', contract: contentionContract, samples, simultaneousSamples: overlap.length, @@ -252,7 +247,6 @@ export function buildContentionReport( }, proxy: { ...proxy, errors: proxyErrors }, progress: { - monitoringLeasesObserved: maximum((item) => item.leasedPolicies), emailAccepted: email, webhookAccepted: webhook, durableNotificationSuccesses: durable, diff --git a/scripts/runtime-scale/background-evidence.ts b/scripts/runtime-scale/background-evidence.ts index ffbb0c323..7f229635d 100644 --- a/scripts/runtime-scale/background-evidence.ts +++ b/scripts/runtime-scale/background-evidence.ts @@ -27,9 +27,6 @@ const schema = z.object({ imageIdentity: z.string().regex(/^sha256:[a-f0-9]{64}$/u), imagePlatform: z.enum(['linux/amd64', 'linux/arm64']), seed: z.number().int().nonnegative().max(0xffffffff), - policyCount: z.literal(100), - duePattern: z.literal('simultaneous'), - latencyProfile: z.literal('mixed'), extendedRecoverySelected: z.literal(true), provenance: z.object({ runId: z.string().min(1), @@ -37,9 +34,6 @@ const schema = z.object({ .object({ runId: z.string().min(1), seed: z.number().int().nonnegative(), - policyCount: z.literal(100), - pattern: z.literal('simultaneous'), - profile: z.literal('mixed'), durationSeconds: z.literal(120), contention: z.literal(false), extendedRecovery: z.literal(true), @@ -50,7 +44,7 @@ const schema = z.object({ fixture: z .object({ sourceManifest: manifest, - artifacts: z.array(z.object({ name: z.string(), sha256: digest })).length(4), + artifacts: z.array(z.object({ name: z.string(), sha256: digest })).length(3), installedArtifactsVerified: z.literal(true), }) .passthrough(), @@ -62,25 +56,6 @@ const schema = z.object({ sha256: digest, }), }), - monitoring: z.object({ - status: z.literal('met'), - attempted: z.literal(100), - schedulerAdmitted: z.literal(100), - committed: z.literal(100), - networkAccepted: z.literal(100), - schedulerCapture: z.object({ - status: z.literal('complete'), - expectedAttempts: z.literal(100), - capturedAdmissions: z.literal(100), - matchedStartedAttempts: z.literal(100), - identity: z.object({ runId: z.string().min(1), sourceSha: z.string() }), - flags: z.object({ - overflowed: z.literal(false), - expired: z.literal(false), - clockRegressed: z.literal(false), - }), - }), - }), notifications: z.object({ initiallyDeferred: z.number().int().positive().max(1024), initiallyDeferredIdentities: z.array(notificationIdentity).max(1024), @@ -125,8 +100,6 @@ export function backgroundRecoveryEvidence( requireEvidence(!/^0+$/u.test(report.targetSha) && !/^sha256:0+$/u.test(report.imageIdentity)) requireEvidence(provenance.runId === provenance.scenario.runId) requireEvidence(report.seed === provenance.scenario.seed) - requireEvidence(report.monitoring.schedulerCapture.identity.runId === provenance.runId) - requireEvidence(report.monitoring.schedulerCapture.identity.sourceSha === expected.targetSha) requireEvidence(provenance.automationSources.sha256 === expected.automationSha256) requireEvidence(provenance.automationSourceRecheck.sha256 === expected.automationSha256) requireEvidence( @@ -140,7 +113,6 @@ export function backgroundRecoveryEvidence( requireEvidence( JSON.stringify(artifactNames) === JSON.stringify([ - 'background-capture-read.js', 'background-contention-receiver.js', 'background-contention-web.js', 'reliability-fixture.js', @@ -191,7 +163,7 @@ export function backgroundRecoveryEvidence( runId: provenance.runId, reportSha256: report.reportSha256, elapsedMs: report.extendedRecovery.elapsedMs, - schedulerAdmissions: report.monitoring.schedulerAdmitted, + deferredDeliveries: notifications.deferredAdmissions.length, deferredIdentities: notifications.initiallyDeferred, faults: provenance.scenario.faults, capacity: report.summary.capacity, diff --git a/scripts/runtime-scale/background-extended.ts b/scripts/runtime-scale/background-extended.ts index b39ca4229..97598c251 100644 --- a/scripts/runtime-scale/background-extended.ts +++ b/scripts/runtime-scale/background-extended.ts @@ -7,93 +7,31 @@ import { import { requestHttp3Client } from '../smoke/http3/client.ts' import type { createHarness } from '../runtime-reliability/harness.ts' import type { FixtureResult } from '../runtime-reliability/Types/harness.types.ts' -import type { BackgroundOptions } from './Types/background.types.ts' -import { backgroundSnapshotSchema } from './background.validation.ts' -import { contentionWebSchema } from './background-contention.ts' export type ExtendedRecoveryStage = | 'certificate-prepare' | 'certificate-exercise' - | 'monitoring-start' | 'job-queue' | 'backup-restore' - | 'origin-restore' | 'job-resume' | 'job-applied' | 'runtime-sync' | 'certificate-metadata' | 'certificate-tls' - | 'monitoring-quiesce' - | 'monitoring-final-fence' | 'audit-replay' | 'budget' -/** Require actual serving-worker completion, disabled/unleased policies, and stable durable history before the final fence. */ -export async function waitForMonitoringDrain( - readWorkerRunning: () => Promise, - readSnapshot: () => Promise>, - waitFor: (check: () => Promise, message: string, timeoutMs: number) => Promise, - checkCancellation: () => void = () => {}, -) { - let previousObservations = -1 - let stableReads = 0 - await waitFor( - async () => { - checkCancellation() - const [running, snapshot] = await Promise.all([readWorkerRunning(), readSnapshot()]) - assert.ok(Number.isSafeInteger(running) && running >= 0) - const drained = - running === 0 && - snapshot.policies.every((policy) => !policy.enabled && !policy.leased) - if (drained && snapshot.observations.length === previousObservations) stableReads++ - else stableReads = 0 - previousObservations = snapshot.observations.length - return drained && stableReads >= 3 - }, - 'Actual web monitoring operations drain and durable observations stop changing', - 15000, - ) -} - -/** Read allowlisted host-monitoring running count from the authenticated web support RPC, never from the fixture process. */ -export async function readActualHostMonitoringRunning( - container: string, - docker: (args: string[], options: { timeoutMs: number }) => Promise, -) { - const raw = await docker( - [ - 'exec', - container, - 'bun', - '--no-env-file', - '/opt/rentnerproxy/web/background-contention-web.js', - ], - { timeoutMs: 7000 }, - ) - const report = contentionWebSchema.parse(JSON.parse(raw)) - assert.equal(report.source, 'authenticated actual web support RPC') - assert.ok(report.bun) - const worker = report.bun.workers.find((item) => item.id === 'host_monitoring') - assert.ok(worker) - return worker.running -} - /** Check cancellation between restore stages and verify the same queued certificate, exact activation, stale-write fences, and audit replay within ten minutes. */ export async function exerciseExtendedBackgroundRecovery( harness: Awaited>, - options: BackgroundOptions, + seed: number, paused: (operation: () => Promise) => Promise, checkCancellation: () => void = () => {}, onStage: (stage: ExtendedRecoveryStage) => void = () => {}, ) { checkCancellation() const context = harness.context - const extra = { - policyCount: options.policies, - seed: options.seed, - duePattern: options.pattern, - backgroundProfile: options.profile, - } + const extra = { seed } const started = performance.now() checkCancellation() onStage('certificate-prepare') @@ -102,10 +40,6 @@ export async function exerciseExtendedBackgroundRecovery( onStage('certificate-exercise') await exerciseCertificates(context, 0) checkCancellation() - onStage('monitoring-start') - const workload = backgroundSnapshotSchema.parse( - (await context.fixture('background-start', extra)).background, - ) onStage('job-queue') const queued = (await paused(() => context.fixture('background-job-prepare', extra))) .recovery as { jobId?: string; queuedForRestore?: boolean } @@ -114,16 +48,6 @@ export async function exerciseExtendedBackgroundRecovery( onStage('backup-restore') await harness.backupRestore() checkCancellation() - onStage('origin-restore') - await context.docker([ - 'exec', - context.container, - 'bun', - '--no-env-file', - '-e', - `await Bun.write(${JSON.stringify('/tmp/background-origin-' + context.runId)},${JSON.stringify(String(workload.origin))});await import('node:fs/promises').then(fs=>fs.chmod(${JSON.stringify('/tmp/background-origin-' + context.runId)},0o600))`, - ]) - checkCancellation() onStage('job-resume') const resumed = (await context.fixture('background-job-resume', extra)).recovery as { jobId?: string @@ -173,34 +97,6 @@ export async function exerciseExtendedBackgroundRecovery( 'Restored job activates its exact durable certificate', ) checkCancellation() - onStage('monitoring-quiesce') - const quiescent = backgroundSnapshotSchema.parse( - (await context.fixture('background-quiesce', extra)).background, - ) - checkCancellation() - await waitForMonitoringDrain( - () => - readActualHostMonitoringRunning(context.container, (args, dockerOptions) => - context.docker(args, dockerOptions), - ), - async () => - backgroundSnapshotSchema.parse( - (await context.fixture('background-read', extra)).background, - ), - context.waitFor, - checkCancellation, - ) - checkCancellation() - onStage('monitoring-final-fence') - const stable = backgroundSnapshotSchema.parse( - (await context.fixture('background-read', extra)).background, - ) - assert.ok(stable.policies.every((policy) => !policy.enabled && !policy.leased)) - assert.equal( - stable.observations.length, - quiescent.observations.length, - 'Cancelled pre-maintenance probes cannot append stale outcomes after the final fence', - ) onStage('audit-replay') const audit = (await paused(() => context.fixture('background-audit-replay', extra))).recovery checkCancellation() @@ -217,8 +113,6 @@ export async function exerciseExtendedBackgroundRecovery( activeRestore: { jobId: queued.jobId, finalStage: 'applied', - strandedMonitoringLeases: 0, - noLateMonitoringWrites: true, }, audit, } diff --git a/scripts/runtime-scale/background-fixture.ts b/scripts/runtime-scale/background-fixture.ts index 401367e01..48e53294f 100644 --- a/scripts/runtime-scale/background-fixture.ts +++ b/scripts/runtime-scale/background-fixture.ts @@ -1,476 +1,23 @@ -// oxlint-disable no-await-in-loop -- Faults mutate and then verify the exact durable claim before the next case. -import assert from 'node:assert/strict' -import { readFile, writeFile } from 'node:fs/promises' -import { randomUUID, X509Certificate, createHash } from 'node:crypto' -import { and, eq, inArray, sql } from 'drizzle-orm' -import { - hostCheckPolicies, - hostCheckObservations, - hostCheckIncidents, - hostDomains, - proxyHosts, - trustedCas, - accessPolicies, - redirectHosts, -} from '../../web/src/db/schema.ts' -import type { AuthTransaction } from '../../web/src/server/Auth/Core/Types/database.types.ts' -import { readProxyRuntimeSnapshot } from '../../web/src/server/ProxyRuntime/proxy-runtime-data.ts' -import * as repository from '../../web/src/server/HostMonitoring/host-monitoring.repository.ts' import { runFixture } from '../runtime-reliability/fixture-core.ts' -import { executeFixture } from '../runtime-reliability/fixture.ts' import type { FixtureContext } from '../runtime-reliability/Types/fixture.types.ts' -import { backgroundPolicies } from './background.ts' -import { withInFlightBackgroundHead } from './background-network.ts' +import { executeFixture } from '../runtime-reliability/fixture.ts' import { backgroundSnapshotSchema } from './background.validation.ts' import { backgroundRecoveryFixture } from './background-recovery.ts' import { backgroundContentionFixture } from './background-contention-fixture.ts' import { runBackgroundDiscovery } from './background-discovery.ts' import { runBackgroundNotifications } from './background-notifications.ts' -import { readBackgroundCapture } from './background-capture.ts' -import type { BackgroundOptions } from './Types/background.types.ts' -import { - TLS_TEST_CA, - TLS_TEST_CERTIFICATE, -} from '../../web/src/tests/server/Notifications/Types/tls-test.types.ts' - -/** Project validated fixture command fields into the fixed background workload without reading process-global configuration. */ -function options(context: Pick): BackgroundOptions { - return { - policies: context.command.policyCount, - seed: context.command.seed, - profile: context.command.backgroundProfile, - pattern: context.command.duePattern, - durationSeconds: 120, - } -} -/** Measure an authorized management read and return validated durable policy/observation evidence for the seeded fixture IDs. */ +/** Record an authenticated host-list read without depending on the retired monitoring scheduler. */ async function snapshot(context: FixtureContext) { const started = performance.now() await context.authorized(context.hosts.getProxyHostsService) - const managementReadMs = performance.now() - started - const inventory = backgroundPolicies(options(context)) - const ids = inventory.map((item) => item.id) - const [policies, observations] = await Promise.all([ - context.database - .select() - .from(hostCheckPolicies) - .where(inArray(hostCheckPolicies.proxyHostId, ids)), - context.database - .select() - .from(hostCheckObservations) - .innerJoin(hostCheckPolicies, eq(hostCheckPolicies.id, hostCheckObservations.policyId)) - .where(inArray(hostCheckPolicies.proxyHostId, ids)) - .orderBy(hostCheckObservations.checkedAt), - ]) - const origin = Number(await readFile('/tmp/background-origin-' + context.command.runId, 'utf8')) return backgroundSnapshotSchema.parse({ - origin, - managementReadMs, - schedulerCapture: await readBackgroundCapture(context.command.runId), - policies: inventory.flatMap((item) => { - const policy = policies.find((candidate) => candidate.proxyHostId === item.id) - return policy - ? [ - { - id: policy.id, - index: item.index, - dueAt: origin + item.offsetMs, - version: policy.version, - enabled: policy.enabled, - leased: policy.leaseToken !== null, - }, - ] - : [] - }), - observations: observations.map((item) => ({ - policyId: item.host_check_observations.policyId, - policyVersion: item.host_check_observations.policyVersion, - checkedAt: item.host_check_observations.checkedAt.getTime(), - status: item.host_check_observations.status, - code: item.host_check_observations.code, - })), + origin: Date.now(), + managementReadMs: performance.now() - started, }) } -/** Mutate one owned in-flight claim across stale-context faults and verify durable write fences, restoring temporary host configuration afterward. */ -export async function backgroundFences(context: Pick) { - const inventory = backgroundPolicies(options(context)) - const hostId = inventory[0]!.id - const database = context.database - const ids = inventory.map((item) => item.id) - await database - .update(hostCheckPolicies) - .set({ enabled: false, leaseToken: null, leaseExpiresAt: null }) - .where(inArray(hostCheckPolicies.proxyHostId, ids)) - const [original] = await database.select().from(proxyHosts).where(eq(proxyHosts.id, hostId)) - assert.ok(original) - const caId = Bun.randomUUIDv7(), - accessId = Bun.randomUUIDv7() - const ca = new X509Certificate(TLS_TEST_CA) - try { - await database.insert(trustedCas).values({ - id: caId, - name: 'Background fixture CA', - pem: TLS_TEST_CA, - fingerprintSha256: 'sha256:' + createHash('sha256').update(TLS_TEST_CA).digest('hex'), - subject: ca.subject, - issuer: ca.issuer, - notBefore: new Date(ca.validFrom), - notAfter: new Date(ca.validTo), - }) - await database - .insert(accessPolicies) - .values({ id: accessId, name: 'Background fixture policy', mode: 'public' }) - const cases = [] - for (const fault of [ - 'policy-version', - 'lease-expiry', - 'host-change', - 'host-disabled', - 'access-policy-change', - 'trusted-ca-change', - 'database-lock', - 'cancelled', - 'duplicate-completion', - ] as const) { - await database - .update(proxyHosts) - .set({ - enabled: true, - forwardPort: original.forwardPort, - forwardScheme: fault === 'trusted-ca-change' ? 'https' : 'http', - trustedCaId: fault === 'trusted-ca-change' ? caId : null, - accessPolicyId: fault === 'access-policy-change' ? accessId : null, - }) - .where(eq(proxyHosts.id, hostId)) - await database - .update(hostCheckPolicies) - .set({ - enabled: true, - version: randomUUID(), - nextCheckAt: new Date(0), - leaseToken: null, - leaseExpiresAt: null, - }) - .where(eq(hostCheckPolicies.proxyHostId, hostId)) - const claim = await repository.claimDueHostMonitoringPolicy() - assert.ok(claim) - assert.equal(claim.policy.proxyHostId, hostId) - const [before] = await repository.readHostMonitoringClaimContexts([claim]) - assert.ok(before) - const count = async () => - ( - await database - .select({ id: hostCheckObservations.id }) - .from(hostCheckObservations) - .where(eq(hostCheckObservations.policyId, claim.policy.id)) - ).length - const prior = await count() - const network = await withInFlightBackgroundHead(async () => { - if (fault === 'policy-version') - await database - .update(hostCheckPolicies) - .set({ version: randomUUID(), leaseToken: null, leaseExpiresAt: null }) - .where(eq(hostCheckPolicies.id, claim.policy.id)) - if (fault === 'lease-expiry') - await database - .update(hostCheckPolicies) - .set({ leaseExpiresAt: new Date(0) }) - .where(eq(hostCheckPolicies.id, claim.policy.id)) - if (fault === 'host-change') - await database - .update(proxyHosts) - .set({ forwardPort: original.forwardPort + 1 }) - .where(eq(proxyHosts.id, hostId)) - if (fault === 'host-disabled') - await database - .update(proxyHosts) - .set({ enabled: false }) - .where(eq(proxyHosts.id, hostId)) - if (fault === 'access-policy-change') - await database - .update(accessPolicies) - .set({ - mode: 'ip-restricted', - ipRules: { defaultAction: 'deny', allow: [], deny: [] }, - }) - .where(eq(accessPolicies.id, accessId)) - if (fault === 'trusted-ca-change') - await database - .update(trustedCas) - .set({ pem: TLS_TEST_CERTIFICATE }) - .where(eq(trustedCas.id, caId)) - }) - const completion = { - claim, - outcome: { - status: 'unhealthy' as const, - code: 'unexpected_status' as const, - durationMs: network.durationMs, - httpStatus: network.status, - }, - before, - signal: fault === 'cancelled' ? AbortSignal.abort() : new AbortController().signal, - } - if (fault === 'database-lock') { - const locked = Promise.withResolvers() - const holder = database.transaction(async (transaction) => { - await transaction - .select() - .from(hostCheckPolicies) - .where(eq(hostCheckPolicies.id, claim.policy.id)) - .for('update') - locked.resolve() - await Bun.sleep(2500) - }) - await Promise.race([locked.promise, holder]) - const began = performance.now() - try { - await assert.rejects(repository.completeHostMonitoringClaims([completion])) - assert.ok( - performance.now() - began < 4000, - 'Lock contention must be bounded by the worker transaction timeout', - ) - } finally { - await holder - } - } else { - const [result] = await repository.completeHostMonitoringClaims([completion]) - assert.equal(result?.status, 'fulfilled') - assert.equal( - result?.status === 'fulfilled' && result.value, - fault === 'duplicate-completion', - ) - } - if (fault === 'duplicate-completion') { - const [retry] = await repository.completeHostMonitoringClaims([completion]) - assert.ok(retry?.status === 'fulfilled' && !retry.value) - } - assert.equal( - await count(), - prior + (fault === 'duplicate-completion' ? 1 : 0), - 'Only a fresh, once-only completion changes durable observations', - ) - await repository.releaseHostMonitoringClaim(claim) - await database - .update(hostCheckPolicies) - .set({ enabled: false, leaseToken: null, leaseExpiresAt: null }) - .where(eq(hostCheckPolicies.id, claim.policy.id)) - const [final] = await database - .select() - .from(hostCheckPolicies) - .where(eq(hostCheckPolicies.id, claim.policy.id)) - assert.ok(final && !final.leaseToken && !final.leaseExpiresAt && !final.enabled) - const incidents = await database - .select({ id: hostCheckIncidents.id }) - .from(hostCheckIncidents) - .where( - and( - eq(hostCheckIncidents.policyId, claim.policy.id), - sql`${hostCheckIncidents.closedReason} is null`, - ), - ) - assert.ok(incidents.length <= 1, 'No duplicate active incidents') - cases.push({ - fault, - passed: true, - networkModel: 'controlled in-flight HEAD, real durable context/lease fences', - staleWrites: 0, - strandedLeases: 0, - observationsAdded: fault === 'duplicate-completion' ? 1 : 0, - activeIncidents: incidents.length, - }) - } - return { - cases, - extendedRecoveryRequired: ['active-certificate-restore', 'audit-cursor-replay'], - } - } finally { - await database - .update(proxyHosts) - .set({ - enabled: original.enabled, - forwardPort: original.forwardPort, - forwardScheme: original.forwardScheme, - trustedCaId: original.trustedCaId, - accessPolicyId: original.accessPolicyId, - }) - .where(eq(proxyHosts.id, hostId)) - await database.delete(trustedCas).where(eq(trustedCas.id, caId)) - await database.delete(accessPolicies).where(eq(accessPolicies.id, accessId)) - } -} - -/** Fixture-only inventory setup; the explicit 1000-policy case also owns the traffic routes. */ -export async function prepareBackgroundInventory( - context: Pick & { - database: { - transaction(operation: (transaction: AuthTransaction) => Promise): Promise - } - }, -) { - const inventory = backgroundPolicies(options(context)) - const bindings = await context.database.transaction(async (transaction) => { - assert.equal( - ( - await transaction - .select({ id: hostCheckPolicies.id }) - .from(hostCheckPolicies) - .limit(1) - ).length, - 0, - 'No preexisting monitoring policies', - ) - let rebound: { proxyId: string; policyHostId: string } | null = null - if (inventory.length === 1000) { - const { state, domain, command } = context - assert.equal( - state.runId, - command.runId, - 'Boundary fixture must match persisted run ownership', - ) - assert.equal( - state.domain, - domain, - 'Boundary fixture domain must match persisted ownership', - ) - assert.ok( - state.proxyId && state.policyHostId && state.policyId && state.redirectId, - 'Boundary fixture must be prepared', - ) - assert.notEqual( - state.proxyId, - state.policyHostId, - 'Boundary traffic owners must be distinct', - ) - const hosts = await transaction.select().from(proxyHosts).for('update') - const redirects = await transaction.select().from(redirectHosts).for('update') - const domains = await transaction.select().from(hostDomains).for('update') - const [policy] = await transaction - .select() - .from(accessPolicies) - .where(eq(accessPolicies.id, state.policyId)) - .for('update') - assert.equal( - hosts.length, - 2, - 'Only the two original fixture proxy hosts may be replaced', - ) - assert.equal(redirects.length, 1, 'Only the original fixture redirect may be disabled') - assert.equal(domains.length, 3, 'Only the three original fixture domains may exist') - assert.ok( - policy && - policy.mode === 'public' && - policy.name === 'Reliability ' + command.runId, - 'Boundary control route retains its original public policy', - ) - for (const [hostId, alias, accessPolicyId] of [ - [state.proxyId, domain, null], - [state.policyHostId, 'policy-' + domain, state.policyId], - ] as const) { - const host = hosts.find((item) => item.id === hostId) - assert.ok( - host && - host.enabled && - host.forwardScheme === 'http' && - host.forwardHost === command.upstreamHost && - host.forwardPort === command.upstreamPort && - host.certificateId === null && - !host.forceHttps && - host.upstreamPool === null && - host.trustedCaId === null && - host.upstreamTlsServerName === null && - host.accessPolicyId === accessPolicyId, - 'Only an unchanged owned fixture stub may be replaced', - ) - assert.ok( - domains.some((item) => item.proxyHostId === hostId && item.domain === alias), - 'Boundary traffic alias ownership must match', - ) - assert.ok( - !inventory.some((item) => item.id === hostId), - 'Boundary inventory identities must be fresh', - ) - } - const redirect = redirects[0]! - assert.ok( - redirect.id === state.redirectId && - redirect.enabled && - redirect.destination === 'http://' + domain + '/initial' && - redirect.statusCode === 302 && - redirect.preserveRequestUri && - redirect.certificateId === null && - domains.some( - (item) => - item.redirectHostId === redirect.id && - item.domain === 'redirect-' + domain, - ), - 'Only the unused original fixture redirect may be disabled', - ) - await transaction - .delete(proxyHosts) - .where(inArray(proxyHosts.id, [state.proxyId, state.policyHostId])) - await transaction - .update(redirectHosts) - .set({ enabled: false }) - .where(eq(redirectHosts.id, state.redirectId)) - rebound = { proxyId: inventory.at(-2)!.id, policyHostId: inventory.at(-1)!.id } - } - await transaction.insert(proxyHosts).values( - inventory.map((item) => ({ - id: item.id, - forwardScheme: 'http' as const, - forwardHost: context.command.upstreamHost, - forwardPort: context.command.upstreamPort, - ...(item.id === rebound?.policyHostId - ? { accessPolicyId: context.state.policyId } - : {}), - })), - ) - await transaction.insert(hostDomains).values( - inventory.map((item) => ({ - proxyHostId: item.id, - domain: `bg-${item.index}-${item.latency}-${context.domain}`, - })), - ) - await transaction.insert(hostCheckPolicies).values( - inventory.map((item) => ({ - proxyHostId: item.id, - id: item.id, - domain: `bg-${item.index}-${item.latency}-${context.domain}`, - enabled: false, - intervalSeconds: 60, - timeoutMs: 3000, - failureThreshold: 1, - })), - ) - if (rebound) { - await transaction.insert(hostDomains).values([ - { proxyHostId: rebound.proxyId, domain: context.domain }, - { proxyHostId: rebound.policyHostId, domain: 'policy-' + context.domain }, - ]) - const runtime = await readProxyRuntimeSnapshot(transaction) - assert.equal( - runtime.proxyHosts.length, - 1000, - 'Boundary inventory must fit the actual runtime host limit', - ) - assert.equal( - runtime.redirectHosts.length, - 0, - 'Boundary redirect must remain outside the routing budget', - ) - } - return rebound - }) - if (bindings) { - Object.assign(context.state, bindings) - await context.save() - } -} - -/** Dispatch validated background fixture phases; use the existing fixture executor for phases outside this workload. */ +/** Dispatch remaining notification, discovery, and recovery worker fixtures. */ async function execute(context: FixtureContext): Promise> { if (!context.command.phase.startsWith('background-')) return executeFixture(context) if (context.command.phase.startsWith('background-contention-')) { @@ -480,60 +27,33 @@ async function execute(context: FixtureContext): Promise desiredRevision: (await context.runtime.getProxyRuntimeSnapshotService()).revision, } } - const inventory = backgroundPolicies(options(context)) - if (context.command.phase === 'background-prepare') { - await prepareBackgroundInventory(context) - await writeFile('/tmp/background-origin-' + context.command.runId, '0', { mode: 0o600 }) - } - if (context.command.phase === 'background-start') { - const origin = Date.now() + 1000 - await writeFile('/tmp/background-origin-' + context.command.runId, String(origin), { - mode: 0o600, - }) - await context.database.transaction(async (transaction) => { - for (const item of inventory) - await transaction - .update(hostCheckPolicies) - .set({ enabled: true, nextCheckAt: new Date(origin + item.offsetMs) }) - .where(eq(hostCheckPolicies.proxyHostId, item.id)) - }) + if (context.command.phase === 'background-read' && context.command.contention) { + const [background, contention] = await Promise.all([ + snapshot(context), + backgroundContentionFixture({ + ...context, + command: { ...context.command, phase: 'background-contention-read' }, + }), + ]) + return { + background, + contention, + desiredRevision: (await context.runtime.getProxyRuntimeSnapshotService()).revision, + } } - if (context.command.phase === 'background-quiesce') - await context.database - .update(hostCheckPolicies) - .set({ enabled: false, leaseToken: null, leaseExpiresAt: null }) - .where( - inArray( - hostCheckPolicies.proxyHostId, - inventory.map((item) => item.id), - ), - ) const detail = [ 'background-job-prepare', 'background-job-resume', 'background-audit-replay', ].includes(context.command.phase) ? { recovery: await backgroundRecoveryFixture(context) } - : context.command.phase === 'background-fences' - ? { fences: await backgroundFences(context) } - : context.command.phase === 'background-discovery' - ? { discovery: await runBackgroundDiscovery(context.command.seed) } - : context.command.phase === 'background-notifications' - ? { notifications: await runBackgroundNotifications(context) } - : { background: await snapshot(context) } + : context.command.phase === 'background-discovery' + ? { discovery: await runBackgroundDiscovery(context.command.seed) } + : context.command.phase === 'background-notifications' + ? { notifications: await runBackgroundNotifications(context) } + : { background: await snapshot(context) } const desired = await context.runtime.getProxyRuntimeSnapshotService() - return { - ...detail, - ...(context.command.contention && context.command.phase === 'background-read' - ? { - contention: await backgroundContentionFixture({ - ...context, - command: { ...context.command, phase: 'background-contention-read' }, - }), - } - : {}), - desiredRevision: desired.revision, - } + return { ...detail, desiredRevision: desired.revision } } if (import.meta.main) await runFixture(execute) diff --git a/scripts/runtime-scale/background-network.ts b/scripts/runtime-scale/background-network.ts deleted file mode 100644 index 9ab51e0e5..000000000 --- a/scripts/runtime-scale/background-network.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** Hold a real loopback HEAD in flight while mutating its context, then always release the barrier and stop the owned server. */ -export async function withInFlightBackgroundHead(operation: () => Promise) { - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - const server = Bun.serve({ - hostname: '127.0.0.1', - port: 0, - async fetch() { - entered.resolve() - await release.promise - return new Response(null, { status: 503 }) - }, - }) - const start = performance.now() - const request = fetch(`http://127.0.0.1:${server.port}/`, { - method: 'HEAD', - signal: AbortSignal.timeout(3000), - }) - try { - await Promise.race([ - entered.promise, - request.then(() => { - throw new Error('Fixture HEAD completed before mutation barrier') - }), - ]) - await operation() - release.resolve() - const response = await request - await response.body?.cancel() - return { status: response.status, durationMs: Math.ceil(performance.now() - start) } - } finally { - release.resolve() - await request.catch(() => undefined) - await server.stop(true) - } -} diff --git a/scripts/runtime-scale/background-recovery.ts b/scripts/runtime-scale/background-recovery.ts index 4f9e15e12..7c883cde7 100644 --- a/scripts/runtime-scale/background-recovery.ts +++ b/scripts/runtime-scale/background-recovery.ts @@ -5,7 +5,6 @@ import { certificateEventCursor, certificateEventReceipts, certificateJobs, - hostCheckPolicies, } from '../../web/src/db/schema.ts' import { synchronizeCertificateEventsOnce } from '../../web/src/server/Admin/CertificateManagement/certificate-events.worker.ts' import type { FixtureContext } from '../runtime-reliability/Types/fixture.types.ts' @@ -99,16 +98,11 @@ export async function backgroundRecoveryFixture(context: FixtureContext) { before, 'Replaying actual controller outcomes restores the final durable cursor without duplicate receipts/audit effects', ) - const leases = await database - .select({ id: hostCheckPolicies.id }) - .from(hostCheckPolicies) - .where(sql`${hostCheckPolicies.leaseToken} is not null`) return { status: 'met', finalCursor: after.cursor, receiptIds: after.receiptIds, auditedEventCount: after.auditEventIds.length, duplicateAuditEffects: 0, - monitoringLeases: leases.length, } } diff --git a/scripts/runtime-scale/background-run.ts b/scripts/runtime-scale/background-run.ts index 31cd4ccae..573cdcb1b 100644 --- a/scripts/runtime-scale/background-run.ts +++ b/scripts/runtime-scale/background-run.ts @@ -9,7 +9,6 @@ import { recoverReliabilityComponent } from '../runtime-reliability/component-re import { postgresPauseProbe } from '../runtime-reliability/postgres-pause.ts' import { backgroundDistribution, - backgroundMonitoringReport, backgroundResourceEvidence, backgroundRecoveryBaseline, backgroundFailureDiagnostic, @@ -25,17 +24,11 @@ import { withBackgroundPause, } from './background-pause.ts' import { exerciseExtendedBackgroundRecovery } from './background-extended.ts' -import { backgroundPolicies } from './background.ts' import { - backgroundReceiptsSchema, backgroundSnapshotSchema, backgroundExtendedRecoverySchema, } from './background.validation.ts' import { stageBackgroundFixtureSources } from './background-source.ts' -import { settleBackgroundCapture } from './background-capture-settlement.ts' -import { backgroundCaptureReadCommand } from './background-capture-read.ts' -import { hostMonitoringCaptureSchema } from '../../web/src/server/HostMonitoring/host-monitoring.capture.ts' -import { z } from 'zod' import { backgroundSourceManifest, backgroundReportBinding, @@ -116,29 +109,12 @@ async function installFixture(context: ReliabilityContext) { probe, context.container + ':/opt/rentnerproxy/web/background-contention-web.js', ]) - const captureReader = join(context.temp, 'background-capture-read.js') - await context.command([ - process.execPath, - '--no-env-file', - 'build', - join(source, 'scripts/runtime-scale/background-capture-read.ts'), - '--tsconfig-override=' + join(source, 'tsconfig.json'), - '--target=bun', - '--packages=external', - '--outfile=' + captureReader, - ]) - await context.docker([ - 'cp', - captureReader, - context.container + ':/opt/rentnerproxy/web/background-capture-read.js', - ]) const sourceManifest = await backgroundSourceManifest(source) const artifacts = await Promise.all( [ ['reliability-fixture.js', bundle], ['background-contention-receiver.js', receiver], ['background-contention-web.js', probe], - ['background-capture-read.js', captureReader], ].map(async ([name, path]) => ({ name: name!, sha256: createHash('sha256') @@ -153,7 +129,7 @@ async function installFixture(context: ReliabilityContext) { 'bun', '--no-env-file', '-e', - "const names=['reliability-fixture.js','background-contention-receiver.js','background-contention-web.js','background-capture-read.js'];console.log(JSON.stringify(await Promise.all(names.map(async name=>({name,sha256:new Bun.CryptoHasher('sha256').update(await Bun.file('/opt/rentnerproxy/web/'+name).arrayBuffer()).digest('hex')})))))", + "const names=['reliability-fixture.js','background-contention-receiver.js','background-contention-web.js'];console.log(JSON.stringify(await Promise.all(names.map(async name=>({name,sha256:new Bun.CryptoHasher('sha256').update(await Bun.file('/opt/rentnerproxy/web/'+name).arrayBuffer()).digest('hex')})))))", ]), ) as unknown assert.deepEqual( @@ -255,10 +231,7 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { ) const context = harness.context const extra = { - policyCount: options.policies, seed: options.seed, - duePattern: options.pattern, - backgroundProfile: options.profile, } const resources: BackgroundResourceSample[] = [] const proxyMs: number[] = [] @@ -271,10 +244,6 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { process.on('SIGTERM', interrupt) let snapshot: BackgroundSnapshot | undefined let contention: Awaited>['report'] | undefined - let monitoring: ReturnType | undefined - let captureSettlement: - Omit>, 'snapshot'> | undefined - let fences: unknown let notifications: unknown let discovery: unknown let extendedRecovery: unknown = { @@ -305,9 +274,6 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { const scenarioIdentity = { runId: context.runId, seed: options.seed, - policyCount: options.policies, - pattern: options.pattern, - profile: options.profile, durationSeconds: options.durationSeconds, contention: options.contention === true, extendedRecovery: options.extendedRecovery === true, @@ -316,7 +282,6 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { let proxyFailures = 0 let origin = 0 let elapsedMs = 0 - let receiptsOverflowed = false /** Accept resource evidence only when before/after ownership matches, tagging warmup and recovered samples separately from continuous work. */ const sample = async (kind: BackgroundResourceSample['kind']) => { const before = await recoveryDependencies(context).snapshot() @@ -346,7 +311,7 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { slo: backgroundSlo, baseline: 'appliance-1g-2cpu-512pid-100conn', evidence: - 'real appliance worker, PostgreSQL durable observations, controller HTTP probes and controlled fixture upstream; one cadence window is a correctness regression, not a sustained capacity claim', + 'remaining notification and discovery workers, component recovery, authenticated management reads, proxy traffic and bounded resource telemetry; no sustained capacity claim', }, }), ) @@ -366,14 +331,6 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { fixtureProvenance = await installFixture(context) checkBackgroundCancellation(abort.signal) await context.synced(await context.fixture('prepare')) - checkBackgroundCancellation(abort.signal) - await context.synced(await context.fixture('background-prepare', extra)) - if (options.policies === 1000) - await context.refreshDns( - backgroundPolicies(options) - .slice(-2) - .map((item) => `bg-${item.index}-${item.latency}-${context.domain}`), - ) origin = performance.now() enter('workload') if (options.contention) { @@ -396,7 +353,7 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { proxyFailures += result.proxyErrors } else { snapshot = backgroundSnapshotSchema.parse( - (await context.fixture('background-start', extra)).background, + (await context.fixture('background-read', extra)).background, ) while (performance.now() - origin < options.durationSeconds * 1000) { checkBackgroundCancellation(abort.signal) @@ -436,63 +393,11 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { const rejected = responses.find((response) => response.status === 'rejected') if (rejected?.status === 'rejected') throw rejected.reason assert.ok(snapshot) - if ( - snapshot.observations.length >= options.policies && - performance.now() - origin >= 35000 - ) - break await Bun.sleep(500) } } elapsedMs = performance.now() - origin assert.ok(snapshot) - enter('capture-settlement') - const settled = await settleBackgroundCapture( - snapshot, - { runId: context.runId, sourceSha: harness.targetSha }, - { - signal: abort.signal, - read: async (remainingMs) => { - const command = backgroundCaptureReadCommand( - context.container, - context.runId, - remainingMs, - ) - const output = await context.docker(command.args, { - timeoutMs: command.clientTimeoutMs, - }) - const value = z - .strictObject({ capture: hostMonitoringCaptureSchema.nullable() }) - .parse(JSON.parse(output)) - return { ...snapshot!, schedulerCapture: value.capture } - }, - }, - ) - snapshot = settled.snapshot - captureSettlement = { - status: settled.status, - reads: settled.reads, - budgetMs: settled.budgetMs, - elapsedMs: settled.elapsedMs, - } - const receipts = backgroundReceiptsSchema.parse(await harness.backgroundReceipts()) - receiptsOverflowed = receipts.overflowed - monitoring = backgroundMonitoringReport(options, snapshot, receipts.receipts, elapsedMs, { - runId: context.runId, - sourceSha: harness.targetSha, - }) - const quiescent = backgroundSnapshotSchema.parse( - (await context.fixture('background-quiesce', extra)).background, - ) - const before = quiescent.observations.length - enter('fences') - fences = ( - await withPausedWeb( - context, - () => context.fixture('background-fences', extra), - abort.signal, - ) - ).fences enter('discovery') discovery = (await context.fixture('background-discovery', extra)).discovery enter('notifications') @@ -547,18 +452,6 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { }) enter('recovery-durability') await context.synced(await context.fixture('background-read', extra)) - const final = backgroundSnapshotSchema.parse( - (await context.fixture('background-read', extra)).background, - ) - assert.equal( - final.observations.length, - before + 1, - 'Recovery must retain once-only fenced completions', - ) - assert.ok( - final.policies.every((policy) => !policy.enabled && !policy.leased), - 'No disabled work is stranded or restarted', - ) const duration = performance.now() - started recovery.push({ component, @@ -590,12 +483,10 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { const pauseElapsedMs = performance.now() - pauseStarted if (options.extendedRecovery) { enter('extended-recovery') - const policy = backgroundPolicies(options)[0]! - const domain = `bg-${policy.index}-${policy.latency}-${context.domain}` extendedRecovery = await exerciseExtendedBackgroundRecovery( harness, - options, - (operation) => withPausedWeb(context, operation, abort.signal, domain), + options.seed, + (operation) => withPausedWeb(context, operation, abort.signal), () => checkBackgroundCancellation(abort.signal), (step) => enter('extended-recovery:' + step), ) @@ -656,11 +547,9 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { } const passed = !failure && - monitoring?.status === 'met' && (!options.extendedRecovery || backgroundExtendedRecoverySchema.safeParse(extendedRecovery).success) && (!options.contention || contention?.status === 'met') && - !receiptsOverflowed && resourceEvidence.status !== 'unmet' && proxyFailures === 0 && interactive.management.p99 !== null && @@ -696,31 +585,12 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { imageIdentity: harness.imageIdentity, imagePlatform, seed: options.seed, - policyCount: options.policies, - duePattern: options.pattern, - latencyProfile: options.profile, - intervalSeconds: 60, observedWorkloadMs: elapsedMs, scenarioElapsedMs: performance.now() - scenarioStarted, extendedRecoverySelected: options.extendedRecovery === true, slo: backgroundSlo, - instrumentation: { - schedulerCapture: - 'opt-in actual web owner; instrumentation overhead is included, not an uninstrumented capacity measurement', - maximumEvents: 20_000, - captureLifetimeMs: 600_000, - maximumCaptureBytes: 8 * 1024 * 1024, - writeCoalesceMs: 25, - finalCaptureSemantics: - 'Only persisted matching events qualify; an unflushed or missing last event yields insufficient evidence rather than inferred admission', - captureReadOwnership: - 'Capture-only remote Bun reader has a separate timeout --signal=KILL configured deadline of at most 1000ms from remote wrapper startup; client waits at most the remaining settlement budget. Client timeout is not remote-drain proof; final container cleanup retains ownership. No SQL/context is created by the reader.', - }, - monitoring, - captureSettlement, ...(contention ? { contention } : {}), interactive, - fences, notifications, discovery, extendedRecovery, @@ -728,7 +598,7 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { recovery, resources: { ...resourceEvidence, - scope: 'Monitoring workload and short component recovery; extended restoration has no continuous resource claim', + scope: 'Short component recovery and remaining worker activity; extended restoration has no continuous resource claim', samples: resources, }, summary: { @@ -746,13 +616,7 @@ export async function runBackgroundScenarios(options: BackgroundOptions) { const artifact = { ...report, reportSha256: backgroundReportBinding(report) } await writeFile(path, JSON.stringify(artifact, null, 2) + '\n', { mode: 0o600 }) await chmod(path, 0o600) - console.log( - 'Runtime background: ' + - (passed ? 'passed' : 'failed') + - '; policies=' + - options.policies + - '; capacity=insufficient', - ) + console.log('Runtime background: ' + (passed ? 'passed' : 'failed') + '; capacity=insufficient') return artifact } diff --git a/scripts/runtime-scale/background-source.config.ts b/scripts/runtime-scale/background-source.config.ts index c9e9bb7c1..6f5bd852c 100644 --- a/scripts/runtime-scale/background-source.config.ts +++ b/scripts/runtime-scale/background-source.config.ts @@ -1,7 +1,5 @@ export const BACKGROUND_FIXTURE_SOURCE_PATHS = [ 'scripts/runtime-scale/background-fixture.ts', - 'scripts/runtime-scale/background-capture.ts', - 'scripts/runtime-scale/background-capture-read.ts', 'scripts/runtime-scale/background-notifications.ts', 'scripts/runtime-scale/background-notification-identities.ts', 'scripts/runtime-scale/background-receivers.ts', diff --git a/scripts/runtime-scale/background.ts b/scripts/runtime-scale/background.ts index cf89f8d05..8150cf258 100644 --- a/scripts/runtime-scale/background.ts +++ b/scripts/runtime-scale/background.ts @@ -1,16 +1,9 @@ // oxlint-disable no-await-in-loop -- Ownership proof requires ordered census/readiness checks within one deadline. import { memoryResourceEvidence } from '../runtime-reliability/resource-probe.ts' -import { createHash } from 'node:crypto' import assert from 'node:assert/strict' -import { createSeededRandom, parseReliabilityOptions } from '../runtime-reliability/control.ts' +import { parseReliabilityOptions } from '../runtime-reliability/control.ts' import { resourceLimits } from '../runtime-reliability/control.config.ts' -import type { - BackgroundOptions, - BackgroundPolicy, - BackgroundReceipt, - BackgroundResourceSample, - BackgroundSnapshot, -} from './Types/background.types.ts' +import type { BackgroundOptions, BackgroundResourceSample } from './Types/background.types.ts' import type { ComponentRecoveryDependencies, ComponentRecoverySnapshot, @@ -113,35 +106,18 @@ export function assertCertificateReplayEvidence(evidence: { /** Name every selected fault explicitly; selection remains separate from completed execution evidence. */ export function backgroundFaultSelection(extendedRecovery: boolean): string[] { return [ - 'policy-version', - 'lease-expiry', - 'host-change', - 'host-disabled', - 'access-policy-change', - 'trusted-ca-change', - 'database-lock', - 'cancelled', - 'duplicate-completion', 'notification-lease-faults', 'web-stop', 'controller-stop', 'postgres-pause', 'web-pause', ...(extendedRecovery - ? [ - 'interrupted-certificate-jobs', - 'active-work-restore', - 'monitoring-final-fence', - 'audit-cursor-replay', - ] + ? ['interrupted-certificate-jobs', 'active-work-restore', 'audit-cursor-replay'] : []), ] } export const backgroundSlo = { - intervalSeconds: 60, - dueToNetworkStartP99Ms: 55000, - dueToCommitMaxMs: 60000, managementReadP99Ms: 500, ssrP99Ms: 1000, proxyP99Ms: 1000, @@ -150,7 +126,6 @@ export const backgroundSlo = { extendedRecoveryMs: 600000, minimumContinuousSamples: 8, minimumContinuousSpanMs: 30000, - minimumChecksPerSecond: { 100: 100 / 60, 500: 500 / 60, 1000: 1000 / 60 }, notifications: { attempted: 320, acknowledged: 280, @@ -161,7 +136,7 @@ export const backgroundSlo = { discovery: { events: 256, inventory: 8, reconnects: 3, recoveryMs: 45000 }, } as const -/** Accept unique flag/value pairs for fixed workload profiles and cap the cadence window at five minutes; extended recovery stays explicit. */ +/** Accept bounded recovery-worker options and cap the observation window at five minutes. */ export function parseBackgroundOptions(args: string[]): BackgroundOptions { const flags = new Map() for (let index = 0; index < args.length; index += 2) { @@ -169,10 +144,7 @@ export function parseBackgroundOptions(args: string[]): BackgroundOptions { const value = args[index + 1] if ( ![ - '--policies', '--seed', - '--pattern', - '--profile', '--duration-seconds', '--image', '--report', @@ -186,18 +158,9 @@ export function parseBackgroundOptions(args: string[]): BackgroundOptions { throw new Error('Invalid background option') flags.set(flag, value) } - const policies = flags.get('--policies') ?? '100' - const pattern = flags.get('--pattern') ?? 'simultaneous' - const profile = flags.get('--profile') ?? 'mixed' const extendedRecovery = flags.get('--extended-recovery') ?? 'false' const contention = flags.get('--contention') ?? 'false' - if ( - !['100', '500', '1000'].includes(policies) || - !['simultaneous', 'staggered'].includes(pattern) || - !['mixed', 'healthy', 'slow', 'timeout'].includes(profile) || - !['true', 'false'].includes(extendedRecovery) || - !['true', 'false'].includes(contention) - ) + if (!['true', 'false'].includes(extendedRecovery) || !['true', 'false'].includes(contention)) throw new Error('Background workload outside fixed bounds') const inherited = parseReliabilityOptions( [...flags] @@ -211,10 +174,7 @@ export function parseBackgroundOptions(args: string[]): BackgroundOptions { 'Background scenarios are bounded to five minutes; use release reliability for soaks', ) return { - policies: Number(policies) as BackgroundOptions['policies'], seed: inherited.seed, - pattern: pattern as BackgroundOptions['pattern'], - profile: profile as BackgroundOptions['profile'], durationSeconds: inherited.durationSeconds, ...(inherited.image ? { image: inherited.image } : {}), ...(inherited.reportPath ? { reportPath: inherited.reportPath } : {}), @@ -223,27 +183,6 @@ export function parseBackgroundOptions(args: string[]): BackgroundOptions { } } -/** Derive stable policy identities, latency profiles, and due offsets from the seed without depending on global randomness or wall time. */ -export function backgroundPolicies(options: BackgroundOptions): BackgroundPolicy[] { - const random = createSeededRandom(options.seed) - return Array.from({ length: options.policies }, (_, index) => { - const digest = createHash('sha256') - .update(`background:${options.seed}:${index}`) - .digest('hex') - return { - id: `${digest.slice(0, 8)}-${digest.slice(8, 12)}-4${digest.slice(13, 16)}-8${digest.slice(17, 20)}-${digest.slice(20, 32)}`, - index, - latency: - options.profile === 'mixed' - ? (['healthy', 'slow', 'timeout', 'failure'] as const)[ - Math.floor(random() * 4) - ]! - : options.profile, - offsetMs: options.pattern === 'staggered' ? Math.floor(random() * 10000) : 0, - } - }) -} - /** Compute nearest-rank tails without mutating input; reject invalid samples and represent missing evidence with null percentiles. */ export function backgroundDistribution(values: readonly number[]) { if (values.some((value) => !Number.isFinite(value) || value < 0)) @@ -335,190 +274,3 @@ export function backgroundResourceEvidence(samples: BackgroundResourceSample[]) stabilityClaimed: false, } } - -/** Compare durable once-only outcomes and network receipts with the seeded workload; missing start evidence cannot establish scheduler admission. */ -export function backgroundMonitoringReport( - options: BackgroundOptions, - snapshot: BackgroundSnapshot, - receipts: BackgroundReceipt[], - elapsedMs: number, - expectedCapture?: { runId: string; sourceSha: string }, -) { - const expected = backgroundPolicies(options) - const capture = snapshot.schedulerCapture - const captured = - !!capture && - !!expectedCapture && - capture.runId === expectedCapture.runId && - capture.sourceSha === expectedCapture.sourceSha && - capture.publication.fd !== null && - capture.publication.generation > 0 && - !capture.overflowed && - !capture.expired && - !capture.clockRegressed - const policies = snapshot.policies.map((policy) => { - const observations = snapshot.observations.filter((item) => item.policyId === policy.id) - const network = receipts.filter((item) => item.index === policy.index) - const workload = expected[policy.index]! - const expectedCode = - workload.latency === 'timeout' - ? 'upstream_timeout' - : workload.latency === 'failure' - ? 'unexpected_status' - : 'expected_status' - const first = observations[0] - const admitted = captured - ? capture.events.filter( - (event) => - event.kind === 'admitted' && - event.policyId === policy.id && - event.policyVersion === policy.version && - event.dueAt === policy.dueAt, - ) - : [] - const admission = admitted.length === 1 ? admitted[0] : undefined - const started = captured - ? capture!.events.filter( - (event) => - event.kind === 'started' && - event.policyId === policy.id && - event.policyVersion === policy.version && - event.dueAt === policy.dueAt, - ) - : [] - const adapterStart = - started.length === 1 && started[0]!.attemptHash === admission?.attemptHash - ? started[0] - : undefined - const validTiming = - admission && - adapterStart && - admission.at >= policy.dueAt && - adapterStart.at >= admission.at && - adapterStart.monotonicMs >= admission.monotonicMs - return { - id: policy.id, - index: policy.index, - expectedCode, - attempted: 1, - schedulerAdmitted: captured ? admitted.length : null, - schedulerStarted: captured ? started.length : null, - dueToAdmissionMs: - admission && admission.at >= policy.dueAt ? admission.at - policy.dueAt : null, - admissionToAdapterStartMs: validTiming - ? adapterStart.monotonicMs - admission.monotonicMs - : null, - networkAccepted: network.length, - committed: observations.length, - correctOutcome: - first?.code === expectedCode && - first.policyVersion === policy.version && - first.status === (expectedCode === 'expected_status' ? 'healthy' : 'unhealthy'), - dueToStartMs: network[0] ? Math.max(0, network[0].startedAt - policy.dueAt) : null, - dueToCommitMs: first ? Math.max(0, first.checkedAt - policy.dueAt) : null, - strandedLease: policy.leased, - } - }) - const starts = backgroundDistribution( - policies.flatMap((policy) => (policy.dueToStartMs === null ? [] : [policy.dueToStartMs])), - ) - const completions = backgroundDistribution( - policies.flatMap((policy) => (policy.dueToCommitMs === null ? [] : [policy.dueToCommitMs])), - ) - const committed = policies.reduce((sum, policy) => sum + policy.committed, 0) - const admissions = captured - ? policies.reduce((sum, policy) => sum + (policy.schedulerAdmitted ?? 0), 0) - : null - const queueLag = captured - ? backgroundDistribution( - policies.flatMap((policy) => - policy.dueToAdmissionMs === null ? [] : [policy.dueToAdmissionMs], - ), - ) - : null - const schedulerStartLag = captured - ? backgroundDistribution( - policies.flatMap((policy) => - policy.admissionToAdapterStartMs === null - ? [] - : [policy.admissionToAdapterStartMs], - ), - ) - : null - const schedulerComplete = - captured && - policies.every( - (policy) => - policy.schedulerAdmitted === 1 && - policy.schedulerStarted === 1 && - policy.dueToAdmissionMs !== null && - policy.admissionToAdapterStartMs !== null, - ) - const throughput = elapsedMs > 0 ? committed / (elapsedMs / 1000) : null - const complete = - policies.length === options.policies && - new Set(policies.map((policy) => policy.id)).size === options.policies && - new Set(policies.map((policy) => policy.index)).size === options.policies && - policies.every( - (policy) => policy.committed === 1 && policy.correctOutcome && !policy.strandedLease, - ) - return { - policies, - attempted: options.policies, - schedulerAdmitted: admissions, - schedulerAdmissionEvidence: captured - ? 'actual web owner: committed claim returned to scheduler adapter; not the SQL commit instant' - : 'unavailable or invalid capture; upstream receipts establish network acceptance only', - schedulerCapture: { - status: schedulerComplete ? 'complete' : 'insufficient', - expectedAttempts: options.policies, - capturedAdmissions: admissions, - matchedStartedAttempts: schedulerStartLag?.count ?? null, - identity: captured - ? { - runId: capture.runId, - sourceSha: capture.sourceSha, - pid: capture.pid, - processStartTicks: capture.processStartTicks, - epoch: capture.epoch, - publication: capture.publication, - } - : null, - rejected: !!capture && !captured, - flags: capture - ? { - overflowed: capture.overflowed, - expired: capture.expired, - clockRegressed: capture.clockRegressed, - } - : null, - }, - networkAccepted: receipts.length, - committed, - checksPerSecond: throughput, - queueLag, - schedulerStartLag, - timingSemantics: { - queueLag: - 'policy due wall time to actual committed-claim-return observation in web; includes SQL/admission wait, not exact database commit', - schedulerStartLag: - 'same-attempt monotonic committed-claim-return to probe adapter entry; excludes context lookup/controller/native network start', - startLag: - 'policy due wall time to independent controlled upstream HEAD receipt; never scheduler admission', - completionLag: - 'policy due wall time to persisted observation checkedAt; not exact SQL commit visibility', - }, - startLag: starts, - completionLag: completions, - status: - !complete || - starts.p99! > backgroundSlo.dueToNetworkStartP99Ms || - completions.max! > backgroundSlo.dueToCommitMaxMs || - throughput === null || - throughput < backgroundSlo.minimumChecksPerSecond[options.policies] - ? 'unmet' - : starts.count < options.policies || !schedulerComplete - ? 'insufficient' - : 'met', - } -} diff --git a/scripts/runtime-scale/background.validation.ts b/scripts/runtime-scale/background.validation.ts index 2e3b2d476..1e3c2e8bb 100644 --- a/scripts/runtime-scale/background.validation.ts +++ b/scripts/runtime-scale/background.validation.ts @@ -1,6 +1,4 @@ import { z } from 'zod' -import { hostMonitoringCaptureSchema } from '../../web/src/server/HostMonitoring/host-monitoring.capture.ts' - export const backgroundExtendedRecoverySchema = z.object({ status: z.literal('met'), elapsedMs: z.number().finite().nonnegative().max(600_000), @@ -8,8 +6,6 @@ export const backgroundExtendedRecoverySchema = z.object({ activeRestore: z.object({ jobId: z.uuid(), finalStage: z.literal('applied'), - strandedMonitoringLeases: z.literal(0), - noLateMonitoringWrites: z.literal(true), }), audit: z.object({ status: z.literal('met'), @@ -21,62 +17,10 @@ export const backgroundExtendedRecoverySchema = z.object({ .refine((ids) => new Set(ids).size === ids.length), auditedEventCount: z.number().int().positive(), duplicateAuditEffects: z.literal(0), - monitoringLeases: z.literal(0), }), }) export const backgroundSnapshotSchema = z.strictObject({ origin: z.number().finite().nonnegative(), - policies: z - .array( - z.strictObject({ - id: z.uuid(), - index: z.number().int().min(0).max(999), - dueAt: z.number().finite().nonnegative(), - enabled: z.boolean(), - leased: z.boolean(), - version: z.uuid(), - }), - ) - .max(1000), - observations: z - .array( - z.strictObject({ - policyId: z.uuid(), - policyVersion: z.uuid(), - checkedAt: z.number().finite().nonnegative(), - status: z.enum(['healthy', 'unhealthy', 'unknown']), - code: z.enum([ - 'expected_status', - 'unexpected_status', - 'upstream_unreachable', - 'upstream_timeout', - 'upstream_dns_failed', - 'tls_failed', - 'configuration_stale', - 'configuration_changed', - 'host_not_active', - 'runtime_unavailable', - 'busy', - 'invalid_response', - ]), - }), - ) - .max(10000), managementReadMs: z.number().finite().nonnegative(), - schedulerCapture: hostMonitoringCaptureSchema.nullable().optional(), -}) - -export const backgroundReceiptsSchema = z.strictObject({ - overflowed: z.boolean(), - receipts: z - .array( - z.strictObject({ - index: z.number().int().min(0).max(999), - latency: z.enum(['healthy', 'slow', 'timeout', 'failure']), - startedAt: z.number().finite().nonnegative(), - finishedAt: z.number().finite().nonnegative().nullable(), - }), - ) - .max(10000), }) diff --git a/scripts/runtime-scale/monitoring-native.ts b/scripts/runtime-scale/monitoring-native.ts deleted file mode 100644 index ab351185c..000000000 --- a/scripts/runtime-scale/monitoring-native.ts +++ /dev/null @@ -1,95 +0,0 @@ -import type { MonitoringScaleOptions } from './Types/monitoring.types.ts' -import type { ProxyRuntimeSnapshot } from '../../web/src/server/ProxyRuntime/Types/proxy-runtime.types.ts' -import { monitoringLatency, MonitoringInputError } from './monitoring.ts' - -/** Restricts native mutations to the explicitly opted-in loopback controller and synthetic fixture identity. */ -export function assertNativeMonitoringFixture( - flag: string | undefined, - controllerUrl: string | undefined, - token: string | undefined, -) { - if ( - flag !== '1' || - controllerUrl !== 'http://127.0.0.1:55441' || - token !== 'synthetic-monitoring-scale-token-392' - ) - throw new MonitoringInputError('native') -} - -/** Hosts bounded deterministic HTTP upstreams and exposes the real controller/traffic adapters for the isolated workload. */ -export async function createNativeMonitoringFixture( - options: MonitoringScaleOptions, - domains: readonly string[], -) { - assertNativeMonitoringFixture( - process.env.RENTNERPROXY_MONITORING_NATIVE_FIXTURE, - process.env.RENTNERPROXY_CONTROLLER_URL, - process.env.RENTNERPROXY_CONTROLLER_TOKEN, - ) - const [{ inspectControllerDomain }, { applyProxyRuntimeConfiguration }] = await Promise.all([ - import('../../web/src/server/Controller/domain-diagnostics.server.ts'), - import('../../web/src/server/Controller/proxy.server.ts'), - ]) - const hosts = new Map(domains.map((domain, index) => [domain, index])) - let active = 0 - const upstream = Bun.serve({ - hostname: '0.0.0.0', - port: 0, - idleTimeout: 15, - /** Serves only selected fixture domains, retaining slow HEAD requests beyond the controller's requested deadline. */ - async fetch(request) { - const index = hosts.get(request.headers.get('host') ?? '') - if ( - index !== undefined && - request.method === 'GET' && - new URL(request.url).pathname === '/traffic' - ) - return new Response('monitoring-capacity-traffic') - if (request.method !== 'HEAD' || index === undefined) - return new Response(null, { status: 404 }) - if (active >= 128) return new Response(null, { status: 503 }) - active++ - try { - const latency = monitoringLatency(options.profile, index, options.timeoutMs) - const delayMs = latency.timeout ? latency.durationMs + 500 : latency.durationMs - await new Promise((resolve) => { - const finish = () => { - clearTimeout(timer) - request.signal.removeEventListener('abort', finish) - resolve() - } - const timer = setTimeout(finish, delayMs) - request.signal.addEventListener('abort', finish, { once: true }) - if (request.signal.aborted) finish() - }) - return new Response(null, { status: 200 }) - } finally { - active-- - } - }, - }) - return { - forwardHost: 'host.docker.internal', - forwardPort: upstream.port, - inspect: inspectControllerDomain, - /** Verifies a real Caddy response independently of scheduled upstream probes. */ - async traffic() { - const response = await fetch('http://127.0.0.1:55442/traffic', { - headers: { host: domains[0]! }, - signal: AbortSignal.timeout(1000), - redirect: 'error', - }) - if ( - response.status !== 200 || - (await response.text()) !== 'monitoring-capacity-traffic' - ) - throw new Error('Isolated Caddy traffic failed during monitoring load.') - }, - /** Requires confirmed activation of the fixture snapshot before scheduling probes. */ - async apply(snapshot: ProxyRuntimeSnapshot) { - if (!(await applyProxyRuntimeConfiguration(snapshot))) - throw new Error('Isolated native monitoring configuration was not activated.') - }, - stop: () => upstream.stop(true), - } -} diff --git a/scripts/runtime-scale/monitoring.ts b/scripts/runtime-scale/monitoring.ts deleted file mode 100644 index ccfb3d929..000000000 --- a/scripts/runtime-scale/monitoring.ts +++ /dev/null @@ -1,719 +0,0 @@ -import type { MonitoringScaleOptions, MonitoringDistribution } from './Types/monitoring.types.ts' -import type { - DomainDiagnosticsControllerInput, - DomainDiagnosticsResult, -} from '../../web/src/lib/RuntimeDiagnostics/Types/domain-diagnostics.types.ts' - -const inputMessages = { - options: - 'Expected --hosts 100|500|1000 --periods 2|3 --profile mixed|slow|timeout --runtime simulated|native --timeout-ms 3000|10000 --scheduler candidate|legacy', - bounds: 'Monitoring workload outside fixed bounds', - database: 'Isolated monitoring database required', - isolation: - 'Requires RENTNERPROXY_DATABASE_INTEGRATION=1 and loopback rentnerproxy_upstream_test', - nonempty: 'Refusing nonempty monitoring/host database', - native: 'Native monitoring requires the explicitly isolated controller fixture.', -} as const - -/** Identifies fixed, safe CLI guard diagnostics without accepting caller-provided error text. */ -export class MonitoringInputError extends Error { - constructor(readonly code: keyof typeof inputMessages) { - super(inputMessages[code]) - this.name = 'MonitoringInputError' - } -} - -/** Shows recognized guard messages while hiding driver errors, connection URLs and credentials. */ -export function formatMonitoringFailure(error: unknown): string { - return error instanceof MonitoringInputError && Object.hasOwn(inputMessages, error.code) - ? inputMessages[error.code] - : 'Monitoring capacity failed; inspect isolated database/runtime availability. No credentials logged.' -} - -/** Accepts only the fixed workload, duration, timeout and scheduler profiles supported by this opt-in fixture. */ -export function parseMonitoringOptions(args: string[]): MonitoringScaleOptions { - const flags = new Map() - for (let index = 0; index < args.length; index += 2) { - const flag = args[index]! - const value = args[index + 1] - if ( - ![ - '--hosts', - '--periods', - '--profile', - '--runtime', - '--timeout-ms', - '--scheduler', - ].includes(flag) || - flags.has(flag) || - !value - ) - throw new MonitoringInputError('options') - flags.set(flag, value) - } - const hosts = flags.get('--hosts') ?? '100' - const periods = flags.get('--periods') ?? '2' - const profile = flags.get('--profile') ?? 'mixed' - const runtime = flags.get('--runtime') ?? 'simulated' - const timeoutMs = flags.get('--timeout-ms') ?? '3000' - const scheduler = flags.get('--scheduler') ?? 'candidate' - if ( - !['100', '500', '1000'].includes(hosts) || - !['2', '3'].includes(periods) || - !['mixed', 'slow', 'timeout'].includes(profile) || - !['native', 'simulated'].includes(runtime) || - !['3000', '10000'].includes(timeoutMs) || - !['legacy', 'candidate'].includes(scheduler) - ) - throw new MonitoringInputError('bounds') - return { - hosts: Number(hosts) as MonitoringScaleOptions['hosts'], - periods: Number(periods) as MonitoringScaleOptions['periods'], - profile: profile as MonitoringScaleOptions['profile'], - ...(runtime === 'native' ? { runtime: 'native' as const } : {}), - ...(timeoutMs === '10000' ? { timeoutMs: 10000 as const } : {}), - ...(scheduler === 'legacy' ? { scheduler: 'legacy' as const } : {}), - } -} - -/** Rejects unflagged or non-test database destinations before importing modules that can mutate fixture state. */ -export function assertIsolatedMonitoringDatabase( - flag: string | undefined, - value: string | undefined, -): void { - let url: URL - try { - url = new URL(value ?? '') - } catch { - throw new MonitoringInputError('database') - } - if ( - flag !== '1' || - !['postgres:', 'postgresql:'].includes(url.protocol) || - url.hostname !== '127.0.0.1' || - url.pathname !== '/rentnerproxy_upstream_test' - ) - throw new MonitoringInputError('isolation') -} - -/** Reports nearest-rank tail latency in the input's units, with null tails for an empty sample. */ -export function monitoringDistribution(values: readonly number[]): MonitoringDistribution { - const sorted = values.toSorted((left, right) => left - right) - const percentile = (fraction: number) => sorted[Math.ceil(sorted.length * fraction) - 1] ?? null - return { - count: sorted.length, - p95: percentile(0.95), - p99: percentile(0.99), - max: sorted.at(-1) ?? null, - total: values.reduce((sum, value) => sum + value, 0), - } -} - -/** Assigns deterministic healthy/timeout delays while preserving the requested timeout and interval workload. */ -export function monitoringLatency( - profile: MonitoringScaleOptions['profile'], - index: number, - timeoutMs = 3000, -) { - if (profile !== 'mixed') - return { - durationMs: profile === 'slow' ? timeoutMs * 0.8 : timeoutMs, - timeout: profile === 'timeout', - } - const durationMs = [20, 150, 1000, timeoutMs][index % 4]! - return { durationMs, timeout: index % 4 === 3 } -} - -/** Produces a protocol-valid diagnostic for the simulation profile without claiming native network execution. */ -export function simulatedMonitoringResult( - input: DomainDiagnosticsControllerInput, - durationMs: number, - timeout: boolean, -): DomainDiagnosticsResult { - const common = { durationMs: 0, addresses: [], httpStatus: null } - return { - ...input, - activeRevision: input.expectedRevision, - checkedAt: new Date().toISOString(), - observationPoint: 'appliance', - publicReachability: 'not_checked', - stages: { - configuration: { ...common, status: 'passed', code: 'configuration_active' }, - dns: { ...common, status: 'unknown', code: 'skipped' }, - upstream: { - ...common, - durationMs, - status: timeout ? 'failed' : 'passed', - code: timeout ? 'upstream_timeout' : 'upstream_responded', - httpStatus: timeout ? null : 200, - }, - tls: { ...common, status: 'not_applicable', code: 'http_upstream' }, - }, - } -} - -function sleep(ms: number) { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -/** Accepts only the exact healthy and timeout status/code pairs emitted by controlled fixture upstreams. */ -export function isMonitoringFixtureOutcome(status: string, code: string): boolean { - return ( - (status === 'healthy' && code === 'expected_status') || - (status === 'unhealthy' && code === 'upstream_timeout') - ) -} - -/** Seeds an empty isolated database, measures unchanged 60-second policies, and drains and removes its fixtures on exit. */ -export async function runMonitoringCapacity(options: MonitoringScaleOptions) { - assertIsolatedMonitoringDatabase( - process.env.RENTNERPROXY_DATABASE_INTEGRATION, - process.env.DATABASE_URL, - ) - const [ - { db, closeDatabaseForRestoreMaintenance }, - schema, - orm, - repository, - { createHostMonitoringWorker }, - { createHostMonitoringProbe }, - { createHostMonitoringBatcher }, - { HOST_MONITORING_LIMITS }, - { BACKGROUND_DATABASE_POLICY }, - { settleWorkerTasks }, - { HostMonitoringCleanupError }, - ] = await Promise.all([ - import('../../web/src/db/index.ts'), - import('../../web/src/db/schema.ts'), - import('drizzle-orm'), - import('../../web/src/server/HostMonitoring/host-monitoring.repository.ts'), - import('../../web/src/server/HostMonitoring/host-monitoring.worker.ts'), - import('../../web/src/server/HostMonitoring/host-monitoring.probe.ts'), - import('../../web/src/server/HostMonitoring/host-monitoring.batch.ts'), - import('../../web/src/config/host-monitoring.config.ts'), - import('../../web/src/config/background-resources.config.ts'), - import('../../web/src/server/Foundation/worker-lifecycle.server.ts'), - import('../../web/src/server/HostMonitoring/Types/host-monitoring-worker.types.ts'), - ]) - const { hostCheckPolicies, hostCheckObservations, proxyHosts, redirectHosts, hostDomains } = - schema - const { sql, inArray } = orm - const nativeMode = options.runtime === 'native' - const contract = { - kind: nativeMode - ? 'production monitoring pipeline with native controller, Caddy and deterministic HTTP upstreams; real isolated PostgreSQL' - : 'production TypeScript monitoring pipeline; deterministic simulated inspect; real isolated PostgreSQL', - options, - intervalSeconds: 60, - timeoutMs: options.timeoutMs ?? 3000, - scheduler: - options.scheduler === 'legacy' - ? 'serial completion-relative one-second admission model on candidate storage/runtime' - : 'candidate bounded pipeline', - concurrency: HOST_MONITORING_LIMITS.workerConcurrency, - claimBatch: HOST_MONITORING_LIMITS.claimBatchSize, - persistenceBatch: HOST_MONITORING_LIMITS.persistenceBatchSize, - pollMs: HOST_MONITORING_LIMITS.pollIntervalMs, - cooperativeStopSeconds: 240, - referenceSlo: { - exactCompletionsPerPolicyPerPeriod: 1, - dueToStartP99Ms: 55000, - dueToCompletionMaxMs: 60000, - managementReadP99Ms: 250, - nativeProxyTrafficP99Ms: 250, - queueGrowth: 0, - }, - resourceEnvelope: { - harnessRssMiB: 512, - harnessAverageCpuCores: 2, - databaseActiveConnections: 16, - databaseLockWaiters: 3, - sampledDatabaseLockWaitMs: 250, - nativeControllerCaddyCpuLimit: 2, - nativeControllerCaddyMemoryLimitMiB: 512, - databaseCpuLimit: 2, - databaseMemoryLimitMiB: 1024, - }, - limits: [ - 'Plain management list reads, no SSR/auth/UI load', - 'Claim, completion and retention transactions intentionally share configuration locks; at most three sampled waiters and 250ms sampled lock delay are allowed', - 'Harness CPU/RSS only; PostgreSQL and native controller CPU/RSS require external container sampling', - nativeMode - ? 'Actual HTTP through native controller; configured upstream name resolves through Docker; no TLS/SSR load' - : 'No actual HTTP/DNS/TLS or native controller execution; simulated diagnostic durations are explicit', - 'Reference SLOs are test acceptance targets, not previously established appliance guarantees', - ], - } - console.log(JSON.stringify({ predeclaredContract: contract })) - const hostIds: string[] = Array.from({ length: options.hosts }, () => Bun.randomUUIDv7()) - const domains = hostIds.map((id, index) => `capacity-${index}-${id}.example.test`) - let native: - | Awaited> - | undefined - const phases: Record = { - claim: [], - context: [], - probe: [], - commit: [], - retention: [], - managementRead: [], - databaseSample: [], - proxyTraffic: [], - } - const dueToStart: number[] = [], - dueToCompletion: number[] = [] - const completed = Array.from({ length: options.periods }, () => new Map()) - const queue: { - elapsedMs: number - due: number - active: number - lockWaiters: number - lockWaitMs: number - }[] = [] - const failures: string[] = [] - let origin = 0, - startedAt = 0, - peakRss = 0, - maxActive = 0, - maxLockWaiters = 0, - maxLockWaitMs = 0 - let seeded = false - const samplerController = new AbortController() - let sampler: Promise | undefined - let worker: ReturnType | undefined - let cpu = process.cpuUsage() - let legacyActive = false - let legacyNextAt = 0 - let runAborted = false - let workerDrain: Promise | undefined - /** Own the first stop checkpoint and its actual writer drain, preserving failure evidence without detached rejections. */ - function stopWorker(): Promise { - if (!worker) return Promise.resolve() - workerDrain ??= (async () => { - const checkpoint = Promise.resolve().then(() => worker!.stop()) - void checkpoint.catch(() => { - failures.push('Monitoring worker stop failed') - }) - try { - await settleWorkerTasks([checkpoint]) - } catch { - failures.push('Monitoring worker drain failed') - } - })() - return workerDrain - } - /** Stops admission once and lets the run unwind through fixture cleanup on deadlines or signals. */ - function abortRun(reason: 'budget' | 'SIGINT' | 'SIGTERM') { - if (runAborted) return - runAborted = true - failures.push( - reason === 'budget' - ? 'Monitoring capacity wall-clock budget exhausted' - : `Monitoring capacity interrupted by ${reason}`, - ) - samplerController.abort() - void stopWorker().catch(() => { - console.error('[monitoring] Worker shutdown failed') - }) - } - const budgetTimer = setTimeout(() => abortRun('budget'), 240000) - const interrupt = () => abortRun('SIGINT') - const terminate = () => abortRun('SIGTERM') - process.once('SIGINT', interrupt) - process.once('SIGTERM', terminate) - /** Records full phase latency, including failures, without changing the operation's result or error. */ - async function measure(name: string, operation: () => Promise): Promise { - const start = performance.now() - try { - return await operation() - } finally { - phases[name]!.push(performance.now() - start) - } - } - - try { - const [existingPolicies, existingHosts, existingRedirects] = await Promise.all([ - db.select({ id: hostCheckPolicies.id }).from(hostCheckPolicies).limit(1), - db.select({ id: proxyHosts.id }).from(proxyHosts).limit(1), - db.select({ id: redirectHosts.id }).from(redirectHosts).limit(1), - ]) - if (existingPolicies.length || existingHosts.length || existingRedirects.length) - throw new MonitoringInputError('nonempty') - if (nativeMode) { - const { createNativeMonitoringFixture } = await import('./monitoring-native.ts') - native = await createNativeMonitoringFixture(options, domains) - } - await db.transaction(async (transaction) => { - await transaction.insert(proxyHosts).values( - hostIds.map((id) => ({ - id, - forwardScheme: 'http' as const, - forwardHost: native?.forwardHost ?? '127.0.0.1', - forwardPort: native?.forwardPort ?? 9, - })), - ) - await transaction.insert(hostDomains).values( - hostIds.map((id, index) => ({ - proxyHostId: id, - domain: domains[index]!, - })), - ) - origin = Date.now() + 1000 - await transaction.insert(hostCheckPolicies).values( - hostIds.map((id, index) => ({ - proxyHostId: id, - domain: domains[index]!, - enabled: true, - intervalSeconds: 60, - timeoutMs: options.timeoutMs ?? 3000, - nextCheckAt: new Date(origin), - })), - ) - }) - seeded = true - if (runAborted) throw new Error('Monitoring capacity stopped during setup.') - if (native) { - const { readProxyRuntimeSnapshot } = - await import('../../web/src/server/ProxyRuntime/proxy-runtime-data.ts') - await native.apply( - await db.transaction(readProxyRuntimeSnapshot, { - isolationLevel: 'repeatable read', - accessMode: 'read only', - }), - ) - origin = Date.now() + 1000 - await db - .update(hostCheckPolicies) - .set({ nextCheckAt: new Date(origin) }) - .where(inArray(hostCheckPolicies.proxyHostId, hostIds)) - } - const latencies = new Map( - hostIds.map((id, index) => [ - id, - monitoringLatency(options.profile, index, options.timeoutMs), - ]), - ) - const readContext = createHostMonitoringBatcher< - Parameters[0][number], - Awaited>[number] - >({ - size: HOST_MONITORING_LIMITS.claimBatchSize, - delayMs: 0, - run: (claims) => - measure('context', async () => - (await repository.readHostMonitoringClaimContexts(claims)).map((value) => ({ - status: 'fulfilled' as const, - value, - })), - ), - }) - const complete = createHostMonitoringBatcher< - Parameters[0][number], - boolean - >({ - size: HOST_MONITORING_LIMITS.persistenceBatchSize, - delayMs: HOST_MONITORING_LIMITS.persistenceDelayMs, - run: (items) => - measure('commit', async () => { - const results = await repository.completeHostMonitoringClaims(items) - results.forEach((result, index) => { - const claim = items[index]!.claim - if (result.status !== 'fulfilled' || !result.value) { - failures.push('Completion rejected or fenced') - return - } - const due = claim.policy.nextCheckAt.getTime() - const period = Math.floor((due - origin) / 60000) - dueToCompletion.push(Date.now() - due) - const coverage = completed[period] - if (coverage) - coverage.set(claim.policy.id, (coverage.get(claim.policy.id) ?? 0) + 1) - else failures.push('Completion outside requested periods') - }) - return results - }), - }) - // A cancelled flight owns up to 64 claims. Send only the monitoring class's - // running allowance to SQL at once; each original token/version fence stays intact. - const release = createHostMonitoringBatcher< - Parameters[0], - boolean - >({ - size: BACKGROUND_DATABASE_POLICY.classes.monitoring.running, - delayMs: 0, - run: (claims) => - Promise.allSettled( - claims.map(async (claim) => repository.releaseHostMonitoringClaim(claim)), - ), - }) - const runClaim = createHostMonitoringProbe({ - readContext, - inspect: async (input, signal, probeOptions) => - measure('probe', async () => { - if (native) return native.inspect(input, signal, probeOptions) - const latency = latencies.get(input.hostId)! - await new Promise((resolve, reject) => { - const timer = setTimeout(() => { - signal.removeEventListener('abort', abort) - resolve() - }, latency.durationMs) - function abort() { - clearTimeout(timer) - reject(new Error('Capacity run stopped')) - } - signal.addEventListener('abort', abort, { once: true }) - if (signal.aborted) abort() - }) - return simulatedMonitoringResult(input, latency.durationMs, latency.timeout) - }), - complete: (claim, outcome, before, signal) => - complete({ claim, outcome, before, signal }), - release: async (claim) => { - try { - return await release(claim) - } catch (cause) { - throw new HostMonitoringCleanupError(cause) - } - }, - }) - worker = createHostMonitoringWorker({ - claim: (limit) => { - if (options.scheduler === 'legacy' && (legacyActive || Date.now() < legacyNextAt)) - return Promise.resolve([]) - return measure('claim', () => - repository.claimDueHostMonitoringPolicies( - options.scheduler === 'legacy' ? 1 : limit, - ), - ) - }, - runClaim: async (claim, signal) => { - dueToStart.push(Date.now() - claim.policy.nextCheckAt.getTime()) - legacyActive = true - try { - await runClaim(claim, signal) - } finally { - legacyActive = false - legacyNextAt = Date.now() + 1000 - } - }, - releaseCancelled: async (claim) => { - await release(claim) - }, - prune: () => measure('retention', repository.pruneHostMonitoringHistory), - unavailable: () => { - failures.push('Production worker reported unavailable') - }, - }) - startedAt = Date.now() - cpu = process.cpuUsage() - sampler = (async () => { - let nextDatabaseSample = 0 - while (!samplerController.signal.aborted) { - peakRss = Math.max(peakRss, process.memoryUsage().rss) - try { - if (native) { - // oxlint-disable-next-line no-await-in-loop -- Keep a single real proxy request in flight alongside management reads. - await measure('proxyTraffic', native.traffic) - } - // Plain management list read; intentionally not an SSR claim. - // oxlint-disable-next-line no-await-in-loop -- Keep a single continuous management read in flight. - await measure('managementRead', () => - db - .select({ id: proxyHosts.id, enabled: proxyHosts.enabled }) - .from(proxyHosts) - .orderBy(proxyHosts.id) - .limit(100), - ) - if (Date.now() >= nextDatabaseSample) { - // oxlint-disable-next-line no-await-in-loop -- Sample serially to avoid adding database contention. - const stats = await measure('databaseSample', () => - db.execute( - sql`select (select count(*)::int from ${hostCheckPolicies} where enabled and next_check_at <= clock_timestamp()) as due, (select count(*)::int from pg_stat_activity where datname = current_database() and state = 'active') as active, (select count(*)::int from pg_stat_activity where datname = current_database() and wait_event_type = 'Lock') as lock_waiters, (select coalesce(max(extract(epoch from (clock_timestamp() - locks.waitstart)) * 1000), 0)::float8 from pg_locks locks join pg_stat_activity activity on activity.pid = locks.pid where activity.datname = current_database() and not locks.granted) as lock_wait_ms`, - ), - ) - const row = stats[0]! - const active = Number(row.active), - lockWaiters = Number(row.lock_waiters) - maxActive = Math.max(maxActive, active) - maxLockWaiters = Math.max(maxLockWaiters, lockWaiters) - const lockWaitMs = Math.max(0, Number(row.lock_wait_ms)) - maxLockWaitMs = Math.max(maxLockWaitMs, lockWaitMs) - queue.push({ - elapsedMs: Date.now() - origin, - due: Number(row.due), - active, - lockWaiters, - lockWaitMs, - }) - nextDatabaseSample = Date.now() + 1000 - } - } catch { - failures.push('Management/database sampler failed') - } - // oxlint-disable-next-line no-await-in-loop -- Bound sampling frequency. - await sleep(200) - } - })() - worker.start() - const end = origin + (options.periods - 1) * 60000 + 59000 - while (Date.now() < end) { - if (runAborted) break - // Bounded wall clock includes a final 59-second drain, never stretches policy cadence. - // oxlint-disable-next-line no-await-in-loop -- Wait for the fixed final cadence window. - await sleep(Math.min(200, end - Date.now())) - } - await stopWorker() - samplerController.abort() - await sampler - const elapsedMs = Date.now() - startedAt - const cpuUsed = process.cpuUsage(cpu) - const averageCpuCores = (cpuUsed.user + cpuUsed.system) / (elapsedMs * 1000) - const coverage = completed.map((period, index) => ({ - period: index + 1, - policies: period.size, - completions: [...period.values()].reduce((sum, count) => sum + count, 0), - duplicates: [...period.values()].filter((count) => count !== 1).length, - })) - const boundaryQueue = Array.from( - { length: options.periods }, - (_, index) => - queue.findLast( - (sample) => - sample.elapsedMs >= index * 60000 + 55000 && - sample.elapsedMs < (index + 1) * 60000, - )?.due ?? null, - ) - const observations = await db - .select({ - status: hostCheckObservations.status, - code: hostCheckObservations.code, - count: sql`count(*)::int`, - }) - .from(hostCheckObservations) - .groupBy(hostCheckObservations.status, hostCheckObservations.code) - const observationCount = observations.reduce((sum, row) => sum + Number(row.count), 0) - const expectedTimeouts = - options.profile === 'timeout' - ? observationCount - : options.profile === 'slow' - ? 0 - : (options.hosts * options.periods) / 4 - const timeoutCount = observations - .filter((row) => row.code === 'upstream_timeout' && row.status === 'unhealthy') - .reduce((sum, row) => sum + Number(row.count), 0) - if ( - timeoutCount !== expectedTimeouts || - observations.some((row) => !isMonitoringFixtureOutcome(row.status, row.code)) - ) - failures.push('Controlled upstream outcomes differ from requested workload') - const startDistribution = monitoringDistribution(dueToStart), - completionDistribution = monitoringDistribution(dueToCompletion) - if ( - coverage.some( - (period) => - period.policies !== options.hosts || - period.duplicates || - period.completions !== options.hosts, - ) - ) - failures.push('Exact per-period policy coverage unmet') - if ( - (startDistribution.p99 ?? Infinity) > contract.referenceSlo.dueToStartP99Ms || - (completionDistribution.max ?? Infinity) > contract.referenceSlo.dueToCompletionMaxMs - ) - failures.push('Scheduling latency SLO unmet') - if ( - (monitoringDistribution(phases.managementRead!).p99 ?? Infinity) > - contract.referenceSlo.managementReadP99Ms - ) - failures.push('Plain management read SLO unmet') - if ( - native && - (monitoringDistribution(phases.proxyTraffic!).p99 ?? Infinity) > - contract.referenceSlo.nativeProxyTrafficP99Ms - ) - failures.push('Native proxy traffic latency SLO unmet') - if (boundaryQueue.some((value) => value !== 0)) - failures.push('Queue did not drain before every next period') - if ( - peakRss / 1048576 > contract.resourceEnvelope.harnessRssMiB || - averageCpuCores > contract.resourceEnvelope.harnessAverageCpuCores || - maxActive > contract.resourceEnvelope.databaseActiveConnections || - maxLockWaiters > contract.resourceEnvelope.databaseLockWaiters || - maxLockWaitMs > contract.resourceEnvelope.sampledDatabaseLockWaitMs - ) - failures.push('Resource envelope unmet') - if (observationCount !== options.hosts * options.periods) - failures.push('Persisted observation count differs from exact workload') - return { - contract, - passed: failures.length === 0, - failures: [...new Set(failures)], - elapsedMs, - coverage, - boundaryQueue, - queue, - dueToStartMs: startDistribution, - dueToCompletionMs: completionDistribution, - phaseMs: Object.fromEntries( - Object.entries(phases).map(([name, values]) => [ - name, - monitoringDistribution(values), - ]), - ), - resources: { - cpuUserMs: cpuUsed.user / 1000, - cpuSystemMs: cpuUsed.system / 1000, - averageCpuCores, - peakRssMiB: peakRss / 1048576, - maxActiveDatabaseConnections: maxActive, - maxDatabaseLockWaiters: maxLockWaiters, - sampledMaxDatabaseLockWaitMs: maxLockWaitMs, - }, - observations: observationCount, - outcomes: observations, - checksPerSecond: observationCount / (elapsedMs / 1000), - } - } finally { - clearTimeout(budgetTimer) - process.removeListener('SIGINT', interrupt) - process.removeListener('SIGTERM', terminate) - samplerController.abort() - try { - await stopWorker() - } finally { - try { - await sampler - } finally { - try { - if (seeded) await db.delete(proxyHosts).where(inArray(proxyHosts.id, hostIds)) - } finally { - try { - await native?.stop() - } finally { - await closeDatabaseForRestoreMaintenance() - } - } - } - } - } -} - -if (import.meta.main) { - if (process.argv.includes('--help')) - console.log( - 'Opt-in bounded monitoring capacity: RENTNERPROXY_DATABASE_INTEGRATION=1 DATABASE_URL= bun --no-env-file scripts/runtime-scale/monitoring.ts --hosts 100|500|1000 --periods 2|3 --profile mixed|slow|timeout --runtime simulated|native --timeout-ms 3000|10000 --scheduler candidate|legacy. Native requires the explicitly isolated controller fixture. Legacy models serial completion-relative one-second admission on candidate storage/runtime, not an old-release benchmark. Requires empty host/policy tables. Emits JSON; nonzero exit on unmet reference SLO. No full SSR measurement.', - ) - else { - try { - const result = await runMonitoringCapacity( - parseMonitoringOptions(process.argv.slice(2)), - ) - console.log(JSON.stringify(result)) - if (!result.passed) process.exitCode = 1 - } catch (error) { - console.error(formatMonitoringFailure(error)) - process.exitCode = 1 - } - } -} diff --git a/web/src/config/app-requirements.config.ts b/web/src/config/app-requirements.config.ts index 403fbbf48..b08dc3793 100644 --- a/web/src/config/app-requirements.config.ts +++ b/web/src/config/app-requirements.config.ts @@ -26,7 +26,7 @@ export const BUNDLED_INSTALLER_CONFIG = 'docker/production/apps/catalog/installe * over; older platforms then require such an app and a completed handoff before updating. */ export const BUILT_IN_FEATURE_TRANSITIONS: readonly BuiltInFeatureTransition[] = [ - { domain: 'monitoring', status: 'built-in', apps: [] }, + { domain: 'monitoring', status: 'retired', apps: ['rentnerproxy.monitoring'] }, { domain: 'docker-discovery', status: 'built-in', apps: [] }, { domain: 'load-balancer', status: 'built-in', apps: [] }, { domain: 'dns', status: 'built-in', apps: [] }, diff --git a/web/src/config/background-workers.config.ts b/web/src/config/background-workers.config.ts index 6ea52a323..2110431c6 100644 --- a/web/src/config/background-workers.config.ts +++ b/web/src/config/background-workers.config.ts @@ -5,7 +5,6 @@ export const backgroundWorkerIds = [ 'certificate_jobs', 'backup_outcomes', 'notifications', - 'host_monitoring', 'docker_discovery', 'npm_import_cleanup', 'app_runtime', diff --git a/web/src/config/host-monitoring-ui.config.ts b/web/src/config/host-monitoring-ui.config.ts index bb73fa96c..ba8bdef3f 100644 --- a/web/src/config/host-monitoring-ui.config.ts +++ b/web/src/config/host-monitoring-ui.config.ts @@ -1,9 +1,5 @@ export const HOST_MONITORING_UI = { - pollIntervalMs: 15_000, requestTimeoutMs: 10_000, responseLimitBytes: 262_144, summaryBatchLimit: 100, - historyPageLimit: 100, - historyLoadedLimit: 300, - historySlots: 40, } as const diff --git a/web/src/config/host-monitoring.config.ts b/web/src/config/host-monitoring.config.ts index b78f7248c..660c0133a 100644 --- a/web/src/config/host-monitoring.config.ts +++ b/web/src/config/host-monitoring.config.ts @@ -1,22 +1,6 @@ export const HOST_MONITORING_LIMITS = { maxPolicies: 1_000, - maxActiveClaims: 64, - workerConcurrency: 64, - claimBatchSize: 16, - persistenceBatchSize: 16, - persistenceDelayMs: 25, - pollIntervalMs: 250, - idlePollMaximumMs: 30_000, - leaseMs: 45_000, transactionTimeoutMs: 2_000, - // A global ceiling, not a minimum history promise: 1,000 policies receive at most 100 samples each after fair pruning. - maxObservations: 100_000, - maxIncidents: 10_000, - historyLimit: 100, - inputLimitBytes: 4_096, - retentionSweepMs: 60_000, - retentionDeleteLimit: 4_096, - retentionPolicyPageSize: 8, advisoryLockId: 7_421_916, } as const @@ -83,19 +67,6 @@ export const HOST_MONITORING_HANDOFF = { }, } as const -export const HOST_MONITORING_DEFAULTS = { - enabled: false, - intervalSeconds: 60, - timeoutMs: 3_000, - expectedStatus: 200, - failureThreshold: 3, - recoveryThreshold: 2, - // Time/count settings are upper bounds; the global fair-share budget may retain fewer samples. - retentionDays: 7, - sampleLimit: 1_440, - incidentLimit: 100, -} as const - /** * How the proxy host table reads host availability from the monitoring app once the app owns the * monitoring domain. Every call is bounded in count, size and time, and shared and cached briefly. @@ -111,22 +82,13 @@ export const HOST_MONITORING_APP = { failureTtlMs: 5_000, maxCachedInstallations: 8, resultLimitBytes: 1_048_576, - // The built-in freshness rule at its defaults: two intervals, one timeout and a 15 s allowance. - staleAfterMs: - HOST_MONITORING_DEFAULTS.intervalSeconds * 2_000 + - HOST_MONITORING_DEFAULTS.timeoutMs + - 15_000, + // Two default probe intervals, one timeout and a 15-second allowance. + staleAfterMs: 2 * 60_000 + 3_000 + 15_000, // Clock differences between the app and the platform below this are not "in the future". futureSkewMs: 5_000, pollIntervalMs: 20_000, } as const -export const HOST_MONITORING_WRITE_RATE_LIMIT = { - limit: 20, - windowMs: 60_000, - scope: 'host-monitoring-policy', -} as const - export const HOST_MONITORING_OUTCOME_CODES = [ 'expected_status', 'unexpected_status', diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx b/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx deleted file mode 100644 index 8c41f16c1..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import StatusStrip from '@/shared/StatusStrip/index.tsx' -import HostAvailabilityBadge from './HostAvailabilityBadge.tsx' -import type { - MonitoringDialogHandler, - MonitoringDialogState, -} from '../Types/host-monitoring-dialog.types.ts' - -export default function MonitoringCheckStrip({ - slots, - formatDate, -}: { - readonly slots: MonitoringDialogState['checkSlots'] - readonly formatDate: MonitoringDialogHandler['formatDate'] -}) { - const { t } = useTranslationStore() - return ( - - observation - ? { - id, - tone: - observation.status === 'healthy' - ? 'positive' - : observation.status === 'unhealthy' - ? 'negative' - : 'neutral', - label: `${formatDate(observation.checkedAt)} · ${t(`admin.hostMonitoring.states.${observation.status}`)}`, - tooltip: ( -
- - -
-
- {t('admin.hostMonitoring.duration')} -
-
- {observation.durationMs === null - ? '—' - : `${observation.durationMs} ms`} -
-
- {t('admin.hostMonitoring.httpStatus')} -
-
- {observation.httpStatus ?? '—'} -
-
- {t(`admin.hostMonitoring.codes.${observation.code}`)} -
- ), - } - : { id, gap: true }, - )} - /> - ) -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Hooks/useMonitoringChecksTableLogic.ts b/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Hooks/useMonitoringChecksTableLogic.ts deleted file mode 100644 index b72a555e8..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Hooks/useMonitoringChecksTableLogic.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { filterFn_equalsString, sortFn_datetime } from '@tanstack/react-table' -import type { ColumnDef, FilterFn } from '@tanstack/react-table' -import { createElement, useMemo, useState } from 'react' -import type { HostMonitoringObservationView } from '@/lib/HostMonitoring/Types/host-monitoring-client.types.ts' -import { createDateRangeFilter } from '@/lib/Table/tableFilters.ts' -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import useClientTable from '@/shared/Table/Hooks/useClientTable.ts' -import HttpStatusBadge from '@/shared/HttpStatusBadge/index.tsx' -import type { ClientTableFeatures } from '@/shared/Table/Types/client-table.types.ts' -import type { TableColumnFilterConfigs } from '@/shared/Table/Types/table.types.ts' -import HostAvailabilityBadge from '../../HostAvailabilityBadge.tsx' -import type { - MonitoringChecksTableLogicResult, - MonitoringChecksTableProps, -} from '../Types/checks-table.types.ts' - -const getRowId = (observation: HostMonitoringObservationView) => observation.id -const dateFilter = createDateRangeFilter() - -export default function useMonitoringChecksTableLogic( - observations: MonitoringChecksTableProps['observations'], -): MonitoringChecksTableLogicResult { - const { t, locale } = useTranslationStore() - const [showColumnFilters, setShowColumnFilters] = useState(false) - const data = useMemo(() => [...observations], [observations]) - const formatter = useMemo( - () => new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }), - [locale], - ) - const columns = useMemo>>( - () => [ - { - accessorKey: 'checkedAt', - header: t('admin.hostMonitoring.checkedAt'), - sortFn: sortFn_datetime, - filterFn: dateFilter, - cell: ({ row }) => - createElement( - 'time', - { - dateTime: row.original.checkedAt.toISOString(), - className: 'whitespace-nowrap', - }, - formatter.format(row.original.checkedAt), - ), - }, - { - accessorKey: 'status', - header: t('admin.hostMonitoring.status'), - filterFn: filterFn_equalsString, - cell: ({ row }) => - createElement(HostAvailabilityBadge, { availability: row.original.status }), - }, - { - id: 'durationMs', - accessorFn: (row) => row.durationMs ?? undefined, - header: t('admin.hostMonitoring.duration'), - enableColumnFilter: false, - sortUndefined: 'last', - cell: ({ row }) => - createElement( - 'span', - { className: 'whitespace-nowrap font-mono' }, - row.original.durationMs === null ? '—' : `${row.original.durationMs} ms`, - ), - }, - { - id: 'httpStatus', - accessorFn: (row) => row.httpStatus ?? undefined, - header: t('admin.hostMonitoring.httpStatus'), - sortUndefined: 'last', - filterFn: (row, _columnId, value) => - String(row.original.httpStatus ?? 'missing') === String(value), - cell: ({ row }) => - row.original.httpStatus === null - ? '—' - : createElement(HttpStatusBadge, { status: row.original.httpStatus }), - }, - { - accessorKey: 'code', - header: t('admin.hostMonitoring.outcome'), - filterFn: filterFn_equalsString, - cell: ({ row }) => t(`admin.hostMonitoring.codes.${row.original.code}`), - }, - ], - [formatter, t], - ) - const globalFilterFn = useMemo>( - () => (row, _columnId, value) => { - const search = String(value).trim().toLocaleLowerCase(locale) - const observation = row.original - return [ - formatter.format(observation.checkedAt), - t(`admin.hostMonitoring.states.${observation.status}`), - t(`admin.hostMonitoring.codes.${observation.code}`), - observation.durationMs === null ? '' : `${observation.durationMs} ms`, - observation.httpStatus ?? '', - ] - .join(' ') - .toLocaleLowerCase(locale) - .includes(search) - }, - [formatter, locale, t], - ) - const { table, state, handler } = useClientTable({ - data, - columns, - getRowId, - initialSorting: [{ id: 'checkedAt', desc: true }], - globalFilterFn, - }) - const columnFilterConfigs = useMemo( - () => ({ - checkedAt: { type: 'dateRange' }, - status: { - type: 'select', - placeholder: t('admin.hostMonitoring.all'), - options: (['healthy', 'unhealthy', 'unknown'] as const).map((value) => ({ - value, - label: t(`admin.hostMonitoring.states.${value}`), - content: createElement(HostAvailabilityBadge, { availability: value }), - })), - }, - httpStatus: { - type: 'select', - placeholder: t('admin.hostMonitoring.table.allHttpStatuses'), - options: [...new Set(data.map((row) => row.httpStatus))] - .toSorted((a, b) => (a ?? 0) - (b ?? 0)) - .map((value) => ({ - value: String(value ?? 'missing'), - content: - value === null - ? t('admin.hostMonitoring.table.missingHttpStatus') - : createElement(HttpStatusBadge, { status: value }), - label: - value === null - ? t('admin.hostMonitoring.table.missingHttpStatus') - : String(value), - })), - }, - code: { - type: 'select', - placeholder: t('admin.hostMonitoring.table.allOutcomes'), - options: [...new Set(data.map((row) => row.code))].map((value) => ({ - value, - label: t(`admin.hostMonitoring.codes.${value}`), - })), - }, - }), - [data, t], - ) - return { - table, - state: { searchInput: state.searchInput, showColumnFilters, columnFilterConfigs }, - handler: { - handleSearchInputChange: handler.handleSearchInputChange, - handleResetFilters: handler.handleResetFilters, - handleToggleColumnFilters: () => setShowColumnFilters((value) => !value), - }, - } -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Types/checks-table.types.ts b/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Types/checks-table.types.ts deleted file mode 100644 index b40a86ab3..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/Types/checks-table.types.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { HostMonitoringObservationView } from '@/lib/HostMonitoring/Types/host-monitoring-client.types.ts' -import type { ClientTable } from '@/shared/Table/Types/client-table.types.ts' -import type { TableColumnFilterConfigs } from '@/shared/Table/Types/table.types.ts' - -export interface MonitoringChecksTableProps { - readonly observations: readonly HostMonitoringObservationView[] - readonly more: boolean - readonly loadingMore: boolean - readonly onLoadMore: () => void -} - -export interface MonitoringChecksTableLogicResult { - readonly table: ClientTable - readonly state: { - readonly searchInput: string - readonly showColumnFilters: boolean - readonly columnFilterConfigs: TableColumnFilterConfigs - } - readonly handler: { - readonly handleSearchInputChange: (value: string) => void - readonly handleResetFilters: () => void - readonly handleToggleColumnFilters: () => void - } -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/index.tsx b/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/index.tsx deleted file mode 100644 index 08f3babed..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringChecksTable/index.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import DataTable from '@/shared/Table/index.tsx' -import useMonitoringChecksTableLogic from './Hooks/useMonitoringChecksTableLogic.ts' -import type { MonitoringChecksTableProps } from './Types/checks-table.types.ts' - -export default function MonitoringChecksTable(props: MonitoringChecksTableProps) { - const { state, handler, table } = useMonitoringChecksTableLogic(props.observations) - const { t } = useTranslationStore() - return ( - - {t('admin.hostMonitoring.table.loadOlder')} - - ) : null - } - /> - ) -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts deleted file mode 100644 index 624dfe152..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { useCallback, useMemo } from 'react' -import { durationSeries } from '@/lib/HostMonitoring/presentation.ts' -import type { HostMonitoringObservationView } from '@/lib/HostMonitoring/Types/host-monitoring-client.types.ts' -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import useTimeSeriesChartDefinition from '@/shared/TimeSeriesChart/Hooks/useTimeSeriesChartDefinition.ts' -import type { MonitoringDurationChartProps } from '../Types/duration-chart.types.ts' - -type DurationRow = ReturnType>[number] - -const checkedAt = (row: DurationRow) => row.checkedAt -const duration = (row: DurationRow) => row.durationMs - -export default function useMonitoringDurationChartLogic( - observations: MonitoringDurationChartProps['observations'], -) { - const { t, locale } = useTranslationStore() - const rows = useMemo(() => durationSeries(observations), [observations]) - const formats = useMemo( - () => ({ - date: new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }), - milliseconds: new Intl.NumberFormat(locale, { - style: 'unit', - unit: 'millisecond', - unitDisplay: 'short', - maximumFractionDigits: 0, - }), - }), - [locale], - ) - const formatValue = useCallback( - (value: number) => formats.milliseconds.format(value), - [formats], - ) - const tooltip = useCallback( - (row: DurationRow) => - row.durationMs === null - ? null - : { - title: formats.date.format(row.checkedAt), - rows: [ - { - label: t('admin.hostMonitoring.duration'), - value: formats.milliseconds.format(row.durationMs), - color: - row.status === 'unhealthy' - ? 'var(--theme-danger-text)' - : 'var(--color-brand-500)', - }, - { - label: t('admin.hostMonitoring.status'), - value: t(`admin.hostMonitoring.states.${row.status}`), - }, - { - label: t('admin.hostMonitoring.httpStatus'), - value: String(row.httpStatus ?? '—'), - }, - ], - }, - [formats, t], - ) - const definition = useTimeSeriesChartDefinition({ - id: 'monitoring-duration', - rows, - time: checkedAt, - value: duration, - formatValue, - tooltip, - }) - return { - state: { - definition, - title: t('admin.hostMonitoring.chart'), - description: t('admin.hostMonitoring.chartDescription'), - }, - } -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Types/duration-chart.types.ts b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Types/duration-chart.types.ts deleted file mode 100644 index f13a0476a..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Types/duration-chart.types.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { HostMonitoringObservationView } from '@/lib/HostMonitoring/Types/host-monitoring-client.types.ts' - -export interface MonitoringDurationChartProps { - readonly observations: readonly HostMonitoringObservationView[] -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx deleted file mode 100644 index bc3553086..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import TimeSeriesChart from '@/shared/TimeSeriesChart/index.tsx' -import useMonitoringDurationChartLogic from './Hooks/useMonitoringDurationChartLogic.ts' -import type { MonitoringDurationChartProps } from './Types/duration-chart.types.ts' - -export default function MonitoringDurationChart({ observations }: MonitoringDurationChartProps) { - const { state } = useMonitoringDurationChartLogic(observations) - return ( - - ) -} diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringOverview.tsx b/web/src/features/Admin/HostMonitoring/Components/MonitoringOverview.tsx deleted file mode 100644 index d7c3e18a6..000000000 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringOverview.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import { CustomSelect } from '@rentnerkev/select/select' -import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import MonitoringDurationChart from './MonitoringDurationChart/index.tsx' -import MonitoringChecksTable from './MonitoringChecksTable/index.tsx' -import MonitoringCheckStrip from './MonitoringCheckStrip.tsx' -import HostAvailabilityBadge from './HostAvailabilityBadge.tsx' -import TableFilterSelect from '@/shared/Table/Components/TableFilterSelect.tsx' -import type { - MonitoringDialogHandler, - MonitoringDialogState, -} from '../Types/host-monitoring-dialog.types.ts' - -export default function MonitoringOverview({ - state, - handler, -}: { - readonly state: MonitoringDialogState - readonly handler: MonitoringDialogHandler -}) { - const { t } = useTranslationStore() - return ( -
- {!state.policy ? ( -
-

{t('admin.hostMonitoring.noPolicy')}

- {state.canUpdate ? ( - - ) : null} -
- ) : null} -
- ({ - value, - label: t( - value === 'all' - ? 'admin.hostMonitoring.all' - : `admin.hostMonitoring.states.${value}`, - ), - content: - value === 'all' ? undefined : ( - - ), - }))} - searchable={false} - value={state.status} - onValueChange={handler.handleStatus} - /> - ({ - value, - label: t(`admin.hostMonitoring.${value}`), - }))} - value={state.period} - onValueChange={handler.handlePeriod} - /> -
- {state.historyError ? ( -
-

{t('admin.hostMonitoring.loadError')}

-
- ) : state.historyLoading ? ( - {t('admin.hostMonitoring.loading')} - ) : ( - <> - {state.observations.length > 0 ? ( - - ) : null} - - - - )} -
- ) -} diff --git a/web/src/features/Admin/HostMonitoring/Hooks/useHostMonitoringDialogLogic.ts b/web/src/features/Admin/HostMonitoring/Hooks/useHostMonitoringDialogLogic.ts deleted file mode 100644 index 4640967e9..000000000 --- a/web/src/features/Admin/HostMonitoring/Hooks/useHostMonitoringDialogLogic.ts +++ /dev/null @@ -1,413 +0,0 @@ -import useAsyncAction from '@/shared/Feedback/Hooks/useAsyncAction.ts' -import { toast } from '@rentnerkev/toasts' -import { useEffect, useId, useMemo, useRef, useState } from 'react' -import { useForm, useStore } from '@tanstack/react-form' -import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { PERMISSIONS } from '@/config/permissions.config.ts' -import { HOST_MONITORING_DEFAULTS } from '@/config/host-monitoring.config.ts' -import { HOST_MONITORING_UI } from '@/config/host-monitoring-ui.config.ts' -import { - getHostMonitoringHistory, - getHostMonitoringPolicy, - saveHostMonitoringPolicy, - HostMonitoringClientError, -} from '@/lib/HostMonitoring/hostMonitoringClient.ts' -import { hostMonitoringQueryKeys } from '@/lib/HostMonitoring/hostMonitoringCache.ts' -import { hostMonitoringSettingsSchema } from '@/lib/HostMonitoring/validation.ts' -import { monitoringCheckSlots, monitoringSince } from '@/lib/HostMonitoring/presentation.ts' -import type { - HostMonitoringHistoryQuery, - HostMonitoringSettings, -} from '@/lib/HostMonitoring/Types/host-monitoring.types.ts' -import type { MonitoringPeriod } from '@/lib/HostMonitoring/Types/host-monitoring-presentation.types.ts' -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import type { - HostMonitoringDialogProps, - MonitoringDialogHandler, - MonitoringDialogState, - MonitoringHistoryPage, - MonitoringHistoryPageParam, - MonitoringTab, -} from '../Types/host-monitoring-dialog.types.ts' - -/** An app took monitoring over, or a handoff to one is open: the built-in settings are retired. */ -function isHandedOff(error: unknown) { - return error instanceof HostMonitoringClientError && error.code === 'handed_off' -} - -function privateError(error: unknown) { - return ( - error instanceof HostMonitoringClientError && - (error.code === 'authentication_required' || error.code === 'permission_denied') - ) -} - -export default function useHostMonitoringDialogLogic(props: HostMonitoringDialogProps) { - const runAction = useAsyncAction() - const { t, locale } = useTranslationStore() - const queryClient = useQueryClient() - const id = useId() - const canView = props.permissions.includes(PERMISSIONS.PROXY_HOSTS_VIEW) - // The dialog session in which a save was refused because an app takes monitoring over. - const [refusedScope, setRefusedScope] = useState(null) - const [tab, setTab] = useState('overview') - const [status, setStatus] = useState('all') - const [period, setPeriod] = useState('recent') - const [conflict, setConflict] = useState(false) - const [ready, setReady] = useState(false) - const [accessRevoked, setAccessRevoked] = useState(false) - const baseVersion = useRef(null) - const draftOwner = useRef('') - const generation = useRef({ scope: '', version: 0, active: false }) - const authorizationRevoked = useRef(false) - const scope = JSON.stringify([ - props.open, - props.host.id, - props.host.domains, - [...new Set(props.permissions)].toSorted(), - ]) - useEffect(() => { - const currentGeneration = generation.current - if (currentGeneration.scope !== scope) currentGeneration.version += 1 - currentGeneration.scope = scope - currentGeneration.active = true - return () => { - currentGeneration.active = false - } - }, [scope]) - const domains = useMemo( - () => - props.host.domains - .filter((domain) => !domain.startsWith('*.')) - .map((domain) => ({ value: domain, label: domain })), - [props.host.domains], - ) - const enabled = props.open && canView && !accessRevoked - function fenceAuthorization(error: unknown): never { - if (privateError(error)) { - authorizationRevoked.current = true - generation.current.version += 1 - } - throw error - } - const policyQuery = useQuery({ - queryKey: hostMonitoringQueryKeys.policy(props.host.id), - queryFn: ({ signal }) => - getHostMonitoringPolicy(props.host.id, signal).catch(fenceAuthorization), - enabled, - refetchOnWindowFocus: true, - refetchOnReconnect: true, - retry: (count, error) => !privateError(error) && count < 3, - }) - const historyInput: HostMonitoringHistoryQuery = { - proxyHostId: props.host.id, - status, - limit: HOST_MONITORING_UI.historyPageLimit, - } - const historyQuery = useInfiniteQuery({ - queryKey: hostMonitoringQueryKeys.history({ ...historyInput, period }), - initialPageParam: undefined as MonitoringHistoryPageParam | undefined, - queryFn: async ({ signal, pageParam }): Promise => { - const windowSince = pageParam ? pageParam.since : monitoringSince(period, Date.now()) - const history = await getHostMonitoringHistory( - { - ...historyInput, - ...(windowSince ? { since: windowSince } : {}), - ...(pageParam ? { before: pageParam.before } : {}), - }, - signal, - ).catch(fenceAuthorization) - return { ...history, windowSince } - }, - getNextPageParam: (page, pages) => - pages.length * HOST_MONITORING_UI.historyPageLimit < - HOST_MONITORING_UI.historyLoadedLimit - ? page.nextCursor - ? { before: page.nextCursor, since: page.windowSince } - : undefined - : undefined, - enabled: enabled && !privateError(policyQuery.error), - refetchOnWindowFocus: true, - refetchOnReconnect: true, - retry: (count, error) => !privateError(error) && count < 3, - }) - // A refused save retires the settings form until the dialog closes; the next session asks - // again, as an aborted handoff returns monitoring to platform. A read reporting the handoff - // retires it too. - if (!props.open && refusedScope !== null) setRefusedScope(null) - const handedOff = - refusedScope === scope || isHandedOff(policyQuery.error) || isHandedOff(historyQuery.error) - const canUpdate = - canView && props.permissions.includes(PERMISSIONS.PROXY_HOSTS_UPDATE) && !handedOff - const forbidden = - !canView || - accessRevoked || - privateError(policyQuery.error) || - privateError(historyQuery.error) - // oxlint-disable react/set-state-in-effect -- Latch server authorization failures so focus/reconnect cannot restart private polling. - useEffect(() => { - if (privateError(policyQuery.error) || privateError(historyQuery.error)) - setAccessRevoked(true) - }, [policyQuery.error, historyQuery.error]) - // oxlint-enable react/set-state-in-effect - const policy = forbidden ? null : (policyQuery.data ?? null) - const defaultSettings = useMemo( - () => ({ ...HOST_MONITORING_DEFAULTS, domain: domains[0]?.value ?? '' }), - [domains], - ) - const [draftDefaults, setDraftDefaults] = useState(defaultSettings) - const mutation = useMutation({ - mutationFn: ({ - input, - }: { - input: Parameters[0] - generation: number - }) => saveHostMonitoringPolicy(input), - onSuccess: async (saved, attempt) => { - if (authorizationRevoked.current) return - queryClient.setQueryData( - hostMonitoringQueryKeys.policy(attempt.input.proxyHostId), - saved, - ) - const invalidation = queryClient.invalidateQueries({ - queryKey: hostMonitoringQueryKeys.all, - }) - if (attempt.generation !== generation.current.version) { - await invalidation - return - } - baseVersion.current = saved.version - setDraftDefaults(saved.settings) - form.reset(saved.settings) - setConflict(false) - if (generation.current.active) - toast.success(t('admin.hostMonitoring.saved'), { title: t('toast.titles.success') }) - await invalidation - }, - onError: (error, attempt) => { - if (attempt.generation !== generation.current.version) return - if (error instanceof HostMonitoringClientError && error.code === 'conflict') { - setConflict(true) - runAction(() => policyQuery.refetch()) - if (generation.current.active) - toast.warning(t('admin.hostMonitoring.conflict'), { - title: t('toast.titles.warning'), - }) - } else if (error instanceof HostMonitoringClientError && error.code === 'handed_off') { - setRefusedScope(scope) - form.reset() - // The table drops the built-in column once the summary reports the handoff too. - runAction(() => - queryClient.invalidateQueries({ queryKey: hostMonitoringQueryKeys.all }), - ) - if (generation.current.active) - toast.error(t('admin.hostMonitoring.handedOff'), { - title: t('toast.titles.error'), - }) - } else { - if (generation.current.active) - toast.error(t('admin.hostMonitoring.saveError'), { - title: t('toast.titles.error'), - }) - } - if (privateError(error)) { - authorizationRevoked.current = true - generation.current.version += 1 - setAccessRevoked(true) - queryClient.removeQueries({ queryKey: hostMonitoringQueryKeys.all }) - setReady(false) - } - }, - }) - const form = useForm({ - defaultValues: draftDefaults, - validators: { - onChange: ({ value }) => - hostMonitoringSettingsSchema.safeParse(value).success - ? undefined - : t('admin.hostMonitoring.invalid'), - }, - onSubmit: ({ value }) => { - if ( - !canUpdate || - forbidden || - !ready || - conflict || - mutation.isPending || - !domains.some((domain) => domain.value === value.domain) - ) - return - const parsed = hostMonitoringSettingsSchema.safeParse(value) - if (!parsed.success) { - toast.error(t('admin.hostMonitoring.invalid'), { title: t('toast.titles.error') }) - return - } - mutation.mutate({ - generation: generation.current.version, - input: { - proxyHostId: props.host.id, - expectedVersion: baseVersion.current, - settings: parsed.data, - }, - }) - }, - }) - const dirty = useStore(form.store, (snapshot) => snapshot.isDirty) - const values = useStore(form.store, (snapshot) => snapshot.values) - const valid = - hostMonitoringSettingsSchema.safeParse(values).success && - domains.some((domain) => domain.value === values.domain) - const reportedInvalidDraft = useRef(false) - useEffect(() => { - if (valid || !dirty) { - reportedInvalidDraft.current = false - return - } - if ( - !props.open || - forbidden || - !canUpdate || - !ready || - draftOwner.current !== scope || - reportedInvalidDraft.current - ) - return - reportedInvalidDraft.current = true - toast.error(t('admin.hostMonitoring.invalid'), { title: t('toast.titles.error') }) - }, [valid, dirty, props.open, forbidden, canUpdate, ready, scope, t]) - // oxlint-disable react/set-state-in-effect -- Synchronize the explicit TanStack Form draft with query versions, preserving dirty edits and erasing private values on permission loss. - useEffect(() => { - if (!props.open || forbidden) { - draftOwner.current = '' - setReady(false) - const cleared = { ...HOST_MONITORING_DEFAULTS, domain: '' } - setDraftDefaults(cleared) - form.reset(cleared) - return - } - if (!policyQuery.isSuccess) return - if (draftOwner.current === scope) { - if (dirty) { - if (!conflict && baseVersion.current !== (policyQuery.data?.version ?? null)) { - setConflict(true) - toast.warning(t('admin.hostMonitoring.conflict'), { - title: t('toast.titles.warning'), - }) - } - return - } - if (baseVersion.current === (policyQuery.data?.version ?? null)) return - } - draftOwner.current = scope - baseVersion.current = policyQuery.data?.version ?? null - const nextDefaults = policyQuery.data?.settings ?? { - ...HOST_MONITORING_DEFAULTS, - domain: props.host.domains.find((domain) => !domain.startsWith('*.')) ?? '', - } - setDraftDefaults(nextDefaults) - form.reset(nextDefaults) - setReady(true) - setConflict(false) - }, [ - props.open, - props.host.domains, - forbidden, - policyQuery.isSuccess, - policyQuery.data, - form, - dirty, - conflict, - t, - scope, - ]) - // oxlint-enable react/set-state-in-effect - const observations = useMemo( - () => - forbidden - ? [] - : (historyQuery.data?.pages - .flatMap((page) => page.observations) - .slice(0, HOST_MONITORING_UI.historyLoadedLimit) ?? []), - [forbidden, historyQuery.data], - ) - const formatter = useMemo( - () => new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }), - [locale], - ) - const checkSlots = useMemo(() => monitoringCheckSlots(observations), [observations]) - const handler: MonitoringDialogHandler = { - handleOpenChange: (open) => { - if (!mutation.isPending && (!dirty || open || forbidden)) props.onOpenChange(open) - }, - handleTab: setTab, - handleStatus: (value) => { - if ( - value === 'all' || - value === 'healthy' || - value === 'unhealthy' || - value === 'unknown' - ) - setStatus(value) - }, - handlePeriod: (value) => { - if (value === 'recent' || value === 'hour' || value === 'day' || value === 'week') { - setPeriod(value) - } - }, - handleMore: () => { - if (historyQuery.hasNextPage && !historyQuery.isFetchingNextPage) - runAction(() => historyQuery.fetchNextPage()) - }, - handleDiscard: () => { - if (mutation.isPending) return - const latest = forbidden - ? defaultSettings - : (policyQuery.data?.settings ?? defaultSettings) - baseVersion.current = forbidden ? null : (policyQuery.data?.version ?? null) - setDraftDefaults(latest) - form.reset(latest) - setConflict(false) - }, - handleSubmit: (event) => { - event.preventDefault() - event.stopPropagation() - runAction(() => form.handleSubmit()) - }, - formatDate: (date) => (date ? formatter.format(date) : '—'), - } - const state: MonitoringDialogState = { - canView: !forbidden, - canUpdate: canUpdate && !forbidden, - tab, - id, - locale, - domains, - policy, - loading: enabled && policyQuery.isPending, - error: policyQuery.isError && policyQuery.data === undefined, - historyError: historyQuery.isError && historyQuery.data === undefined, - historyLoading: historyQuery.isPending, - observations, - checkSlots, - status, - period, - more: Boolean(historyQuery.hasNextPage), - loadingMore: historyQuery.isFetchingNextPage, - pending: mutation.isPending, - dirty, - valid, - conflict, - ready, - numericFields: [ - { name: 'intervalSeconds', min: 30, max: 86_400 }, - { name: 'timeoutMs', min: 1_000, max: 10_000 }, - { name: 'expectedStatus', min: 100, max: 599 }, - { name: 'failureThreshold', min: 1, max: 20 }, - { name: 'recoveryThreshold', min: 1, max: 20 }, - { name: 'retentionDays', min: 1, max: 30 }, - { name: 'sampleLimit', min: 10, max: 10_000 }, - { name: 'incidentLimit', min: 1, max: 1_000 }, - ], - } - return { state, handler, form } -} diff --git a/web/src/features/Admin/HostMonitoring/Types/host-monitoring-dialog.types.ts b/web/src/features/Admin/HostMonitoring/Types/host-monitoring-dialog.types.ts deleted file mode 100644 index 6f9420899..000000000 --- a/web/src/features/Admin/HostMonitoring/Types/host-monitoring-dialog.types.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { ProxyHostSummary } from '@/lib/Admin/ProxyHostManagement/Types/proxy-hosts.types.ts' -import type { - HostMonitoringPolicyView, - HostMonitoringHistoryQuery, - HostMonitoringSettings, -} from '@/lib/HostMonitoring/Types/host-monitoring.types.ts' -import type { - HostMonitoringHistoryView, - HostMonitoringObservationView, -} from '@/lib/HostMonitoring/Types/host-monitoring-client.types.ts' -import type { - HostAvailability, - MonitoringCheckSlot, - MonitoringPeriod, -} from '@/lib/HostMonitoring/Types/host-monitoring-presentation.types.ts' -export interface HostAvailabilityBadgeProps { - readonly availability: HostAvailability - readonly className?: string -} -export interface HostMonitoringDialogProps { - readonly open: boolean - readonly onOpenChange: (open: boolean) => void - readonly host: ProxyHostSummary - readonly permissions: readonly string[] -} -export type MonitoringTab = 'overview' | 'settings' -export interface MonitoringHistoryPageParam { - readonly before: NonNullable - readonly since: string | undefined -} -export interface MonitoringHistoryPage extends HostMonitoringHistoryView { - readonly windowSince: string | undefined -} -type NumericMonitoringSetting = Exclude -export interface MonitoringDialogState { - readonly canView: boolean - readonly canUpdate: boolean - readonly tab: MonitoringTab - readonly id: string - readonly locale: string - readonly domains: readonly { value: string; label: string }[] - readonly policy: HostMonitoringPolicyView | null - readonly loading: boolean - readonly error: boolean - readonly historyError: boolean - readonly historyLoading: boolean - readonly observations: HostMonitoringHistoryView['observations'] - readonly checkSlots: readonly MonitoringCheckSlot[] - readonly status: HostMonitoringHistoryQuery['status'] - readonly period: MonitoringPeriod - readonly more: boolean - readonly loadingMore: boolean - readonly pending: boolean - readonly dirty: boolean - readonly valid: boolean - readonly conflict: boolean - readonly ready: boolean - readonly numericFields: readonly { name: NumericMonitoringSetting; min: number; max: number }[] -} -export interface MonitoringDialogHandler { - readonly handleOpenChange: (open: boolean) => void - readonly handleTab: (tab: MonitoringTab) => void - readonly handleStatus: (value: string | null) => void - readonly handlePeriod: (value: string | null) => void - readonly handleMore: () => void - readonly handleDiscard: () => void - readonly handleSubmit: (event: React.FormEvent) => void - readonly formatDate: (date: Date | null) => string -} diff --git a/web/src/features/Admin/HostMonitoring/index.tsx b/web/src/features/Admin/HostMonitoring/index.tsx deleted file mode 100644 index b8052c6fe..000000000 --- a/web/src/features/Admin/HostMonitoring/index.tsx +++ /dev/null @@ -1,252 +0,0 @@ -import { NumberInput } from '@rentnerkev/inputs' -import { CustomSelect } from '@rentnerkev/select/select' -import { Modal } from '@/shared/Modal/index.tsx' -import OptionToggle from '@/shared/Forms/OptionToggle.tsx' -import Tabs from '@/shared/Tabs/index.tsx' -import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import MonitoringOverview from './Components/MonitoringOverview.tsx' -import useHostMonitoringDialogLogic from './Hooks/useHostMonitoringDialogLogic.ts' -import type { HostMonitoringDialogProps } from './Types/host-monitoring-dialog.types.ts' - -export default function HostMonitoringDialog(props: HostMonitoringDialogProps) { - const { state, handler, form } = useHostMonitoringDialogLogic(props) - const { t } = useTranslationStore() - return ( - ({ - id: tab, - label: t(`admin.hostMonitoring.${tab}`), - }))} - value={state.tab} - onChange={(tab) => - handler.handleTab(tab === 'settings' ? 'settings' : 'overview') - } - /> - } - footer={ - <> - {state.dirty ? ( - <> - - {t('admin.hostMonitoring.dirty')} - - - - ) : null} - - {state.canUpdate && state.tab === 'settings' ? ( - - ) : null} - - } - > -
- {!state.canView ? ( -

- {t('admin.hostMonitoring.permissionDenied')} -

- ) : state.loading ? ( - - {t('admin.hostMonitoring.loading')} - - ) : state.error ? ( -
-

{t('admin.hostMonitoring.loadError')}

-
- ) : ( - <> - - - - )} -
-
- ) -} diff --git a/web/src/features/Admin/HostMonitoring/Components/HostAvailabilityBadge.tsx b/web/src/features/Admin/ProxyHostManagement/Components/ProxyHostsTable/Components/HostAvailabilityBadge.tsx similarity index 54% rename from web/src/features/Admin/HostMonitoring/Components/HostAvailabilityBadge.tsx rename to web/src/features/Admin/ProxyHostManagement/Components/ProxyHostsTable/Components/HostAvailabilityBadge.tsx index 8661fb49e..eef3149c6 100644 --- a/web/src/features/Admin/HostMonitoring/Components/HostAvailabilityBadge.tsx +++ b/web/src/features/Admin/ProxyHostManagement/Components/ProxyHostsTable/Components/HostAvailabilityBadge.tsx @@ -1,36 +1,19 @@ -import { - CheckCircle2, - CircleHelp, - Clock3, - LoaderCircle, - PauseCircle, - TriangleExclamationPoint, - XCircle, -} from 'lucide-react' +import { CheckCircle2, CircleHelp, Clock3, XCircle } from 'lucide-react' import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import type { HostAvailabilityBadgeProps } from '../Types/host-monitoring-dialog.types.ts' +import type { HostAvailabilityBadgeProps } from '../../../Types/host-monitoring-overview.types.ts' -export default function HostAvailabilityBadge({ - availability, - className = '', -}: HostAvailabilityBadgeProps) { +export default function HostAvailabilityBadge({ availability }: HostAvailabilityBadgeProps) { const { t } = useTranslationStore() return ( {availability === 'healthy' ? (