Merge pull request #16 from k55f97/feat/ops-hardening-q100-q101-q102
fix(status): alert channel + probe-drift detection + least-privilege deploy workflowpull/216/head
commit
2f3f30116c
|
|
@ -5,6 +5,17 @@ on:
|
|||
branches: ['main']
|
||||
workflow_dispatch:
|
||||
|
||||
# Least privilege, pinned in the workflow instead of inherited from the repo's
|
||||
# `default_workflow_permissions` setting. This job carries CLOUDFLARE_API_TOKEN
|
||||
# and runs `terraform apply`; if that setting is ever flipped to
|
||||
# read-and-write — or a new repo is derived from this one — the ambient
|
||||
# GITHUB_TOKEN would silently gain write access to the repository inside
|
||||
# exactly that run. `contents: read` is all `actions/checkout` needs; nothing
|
||||
# in this workflow or in deploy/*.py touches the GitHub API.
|
||||
# Top-level, not per-job, so a job added later inherits the restriction.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -106,6 +117,12 @@ jobs:
|
|||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
TF_VAR_CLOUDFLARE_ACCOUNT_ID: ${{ steps.fetch_account_id.outputs.account_id }}
|
||||
D1_ID: ${{ env.D1_ID }}
|
||||
# Alert channel (worker/src/pushover.ts). If these repository secrets
|
||||
# are unset the apply still succeeds, the bindings are simply omitted,
|
||||
# and the worker logs "[ALERT-CHANNEL-BROKEN] … missing Worker
|
||||
# secret(s) …" for every alert it could not deliver.
|
||||
TF_VAR_PUSHOVER_TOKEN: ${{ secrets.PUSHOVER_TOKEN }}
|
||||
TF_VAR_PUSHOVER_USER: ${{ secrets.PUSHOVER_USER }}
|
||||
|
||||
# Currently Terraform Cloudflare provider doesn't support direct upload, use wrangler to upload instead.
|
||||
- name: Upload pages
|
||||
|
|
|
|||
36
deploy.tf
36
deploy.tf
|
|
@ -21,6 +21,24 @@ variable "enable_do_migration" {
|
|||
default = false
|
||||
}
|
||||
|
||||
# Pushover alert channel (worker/src/pushover.ts). Read from the environment as
|
||||
# $TF_VAR_PUSHOVER_TOKEN / $TF_VAR_PUSHOVER_USER, which deploy.yml fills from
|
||||
# the GitHub repository secrets of the same name. Defaulted to "" so a fork or
|
||||
# a first-time deploy without the secrets still applies cleanly — the worker
|
||||
# then logs "[ALERT-CHANNEL-BROKEN] … missing Worker secret(s) …" on every
|
||||
# alert it had to drop, instead of failing silently.
|
||||
variable "PUSHOVER_TOKEN" {
|
||||
type = string
|
||||
sensitive = true
|
||||
default = ""
|
||||
}
|
||||
|
||||
variable "PUSHOVER_USER" {
|
||||
type = string
|
||||
sensitive = true
|
||||
default = ""
|
||||
}
|
||||
|
||||
resource "cloudflare_d1_database" "uptimeflare_d1" {
|
||||
account_id = var.CLOUDFLARE_ACCOUNT_ID
|
||||
name = "uptimeflare_d1"
|
||||
|
|
@ -51,7 +69,10 @@ resource "cloudflare_workers_script" "uptimeflare_worker" {
|
|||
new_sqlite_classes = ["RemoteChecker"]
|
||||
} : null
|
||||
|
||||
bindings = [{
|
||||
# `bindings` is authoritative: whatever is NOT listed here is removed from the
|
||||
# worker on the next apply. So the Pushover secrets must be bound here — a
|
||||
# `wrangler secret put` would survive exactly until the next deploy.
|
||||
bindings = concat([{
|
||||
name = "REMOTE_CHECKER_DO"
|
||||
class_name = "RemoteChecker"
|
||||
type = "durable_object_namespace"
|
||||
|
|
@ -59,7 +80,18 @@ resource "cloudflare_workers_script" "uptimeflare_worker" {
|
|||
name = "UPTIMEFLARE_D1"
|
||||
type = "d1"
|
||||
id = cloudflare_d1_database.uptimeflare_d1.id
|
||||
}]
|
||||
}],
|
||||
# Only bound when both are actually supplied; Cloudflare rejects an empty
|
||||
# secret_text, and a half-configured channel would be worse than none.
|
||||
var.PUSHOVER_TOKEN != "" && var.PUSHOVER_USER != "" ? [{
|
||||
name = "PUSHOVER_TOKEN"
|
||||
type = "secret_text"
|
||||
text = var.PUSHOVER_TOKEN
|
||||
}, {
|
||||
name = "PUSHOVER_USER"
|
||||
type = "secret_text"
|
||||
text = var.PUSHOVER_USER
|
||||
}] : [])
|
||||
}
|
||||
|
||||
resource "cloudflare_workers_cron_trigger" "uptimeflare_worker_cron" {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,188 @@
|
|||
/**
|
||||
* Red/green proof for the probe-drift detection (worker/src/probe.ts).
|
||||
*
|
||||
* npx tsx scripts/check-probe-drift.ts
|
||||
*
|
||||
* Three cases side by side, all driving the REAL `doMonitor` fallback branch
|
||||
* (worker/src/monitor.ts:397-407) against the REAL `website_enam` monitor from
|
||||
* uptime.config.ts — the Durable Object is replaced, nothing else is:
|
||||
*
|
||||
* A) PERMANENTLY DEAD PROXY — the stub throws from run 4 on. Detection MUST
|
||||
* fire, exactly once, after PROBE_DRIFT_RUNS dead runs.
|
||||
* B) SINGLE BLIP — one run out of 40 throws. Detection MUST NOT fire, or the
|
||||
* silence has only been traded for alarm fatigue.
|
||||
* C) CONTROL for the design choice — same dead proxy as A, but the cron
|
||||
* worker happens to run inside the target region. The naive "map the
|
||||
* recorded colo back to a region" test is blind here; this one is not.
|
||||
*
|
||||
* Exits non-zero if any expectation is violated.
|
||||
*/
|
||||
import { doMonitor } from '../worker/src/monitor'
|
||||
import { evaluateProbe, PROBE_DRIFT_RUNS, PROBE_DRIFT_SECONDS } from '../worker/src/probe'
|
||||
import { workerConfig } from '../uptime.config'
|
||||
import { codeToCountry } from '../util/iata'
|
||||
import type { MonitorStateCompacted, MonitorTarget } from '../types/config'
|
||||
|
||||
const monitor = workerConfig.monitors.find((m) => m.id === 'website_enam') as MonitorTarget
|
||||
if (!monitor?.checkProxy) throw new Error('website_enam or its checkProxy is gone')
|
||||
|
||||
const LOCAL_COLO = 'LHR' // the cron colo, as measured live on 2026-07-31
|
||||
const PROBE_COLO = 'EWR' // what the enam Durable Object answered live
|
||||
|
||||
/** Env whose Durable Object namespace is dead on the runs the predicate picks. */
|
||||
function envWithDeadRuns(isDead: (n: number) => boolean, run: { n: number }): any {
|
||||
return {
|
||||
REMOTE_CHECKER_DO: {
|
||||
idFromName(_name: string) {
|
||||
if (isDead(run.n)) {
|
||||
throw new Error('Network connection lost.') // what a dead DO looks like
|
||||
}
|
||||
return 'id'
|
||||
},
|
||||
get(_id: any, _opts: any) {
|
||||
return {
|
||||
async getLocationAndStatus() {
|
||||
return { location: PROBE_COLO, status: { ping: 24, up: true, err: '' } }
|
||||
},
|
||||
async kill() {},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function scenario(
|
||||
label: string,
|
||||
isDead: (n: number) => boolean,
|
||||
totalRuns: number,
|
||||
localColo: string = LOCAL_COLO
|
||||
) {
|
||||
const state: MonitorStateCompacted = {
|
||||
lastUpdate: 0,
|
||||
overallUp: 0,
|
||||
overallDown: 0,
|
||||
incident: {},
|
||||
latency: {},
|
||||
}
|
||||
const run = { n: 0 }
|
||||
const t0 = 1785457187 // live `updatedAt` from status.openshopgraph.org
|
||||
const alerts: string[] = []
|
||||
const locs: string[] = []
|
||||
let firstDegradedRun: number | null = null
|
||||
let fallbackRuns = 0
|
||||
let deadRunsBeforeDetection = 0
|
||||
let naiveLooksCorrect = 0
|
||||
let allUp = true
|
||||
|
||||
// Count how often the real fallback branch logged, as evidence that the
|
||||
// production code path — not a stand-in — produced these results.
|
||||
const realLog = console.log
|
||||
let fallbackLogLines = 0
|
||||
console.log = (...args: any[]) => {
|
||||
if (String(args[0]).startsWith('Falling back to local check')) fallbackLogLines++
|
||||
}
|
||||
|
||||
for (let n = 1; n <= totalRuns; n++) {
|
||||
run.n = n
|
||||
const now = t0 + n * 60 // cron is every minute
|
||||
const result = await doMonitor(monitor, localColo, envWithDeadRuns(isDead, run))
|
||||
const verdict = evaluateProbe(state, monitor.id, result.fromConfiguredRegion, now)
|
||||
locs.push(result.location)
|
||||
// The naive alternative: reconstruct the region from the recorded colo, the
|
||||
// only thing the pre-change state knows. "enam" == a United States colo.
|
||||
if (codeToCountry(result.location).startsWith('United States')) naiveLooksCorrect++
|
||||
allUp &&= result.status.up
|
||||
if (!result.fromConfiguredRegion) fallbackRuns++
|
||||
if (verdict.degraded && firstDegradedRun === null) {
|
||||
firstDegradedRun = n
|
||||
deadRunsBeforeDetection = fallbackRuns
|
||||
}
|
||||
if (verdict.crossed) alerts.push(`run ${n}: DRIFT (stale ${verdict.staleFor}s)`)
|
||||
if (verdict.recovered) alerts.push(`run ${n}: RECOVERED`)
|
||||
}
|
||||
console.log = realLog
|
||||
|
||||
const uniqueLocs = locs.filter((l, i) => locs.indexOf(l) === i)
|
||||
console.log(`\n=== ${label} ===`)
|
||||
console.log(
|
||||
` runs : ${totalRuns} (cron 1/min), threshold ${PROBE_DRIFT_RUNS} runs / ${PROBE_DRIFT_SECONDS}s`
|
||||
)
|
||||
console.log(` real fallback branch : taken ${fallbackLogLines}/${totalRuns} runs (monitor.ts:395)`)
|
||||
console.log(` page showed location : ${uniqueLocs.join(', ')}`)
|
||||
console.log(` monitor stayed UP : ${allUp}`)
|
||||
console.log(` first degraded run : ${firstDegradedRun ?? 'never'}`)
|
||||
console.log(` dead runs at detect : ${firstDegradedRun ? deadRunsBeforeDetection : '-'}`)
|
||||
console.log(` alerts : ${alerts.length ? alerts.join(' | ') : 'none'}`)
|
||||
console.log(
|
||||
` naive geo test says OK: ${naiveLooksCorrect}/${totalRuns} runs looked like the configured region`
|
||||
)
|
||||
return {
|
||||
alerts,
|
||||
firstDegradedRun,
|
||||
uniqueLocs,
|
||||
allUp,
|
||||
fallbackRuns,
|
||||
deadRunsBeforeDetection,
|
||||
naiveLooksCorrect,
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let ok = true
|
||||
const check = (cond: boolean, msg: string) => {
|
||||
console.log(` ${cond ? 'PASS' : 'FAIL'} ${msg}`)
|
||||
ok &&= cond
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- A: dead --
|
||||
// Healthy for 3 runs, then the Durable Object never answers again.
|
||||
const dead = await scenario('A) Durable Object permanently dead from run 4', (n) => n >= 4, 40)
|
||||
check(dead.allUp, 'monitor stays UP throughout — the fallback keeps the page honest, as designed')
|
||||
check(
|
||||
dead.uniqueLocs.join() === `${PROBE_COLO},${LOCAL_COLO}`,
|
||||
`page showed ${PROBE_COLO} then silently ${LOCAL_COLO} forever, with no other signal (the bug)`
|
||||
)
|
||||
check(
|
||||
dead.deadRunsBeforeDetection === PROBE_DRIFT_RUNS,
|
||||
`detection fires after exactly ${PROBE_DRIFT_RUNS} dead runs, got ${dead.deadRunsBeforeDetection}`
|
||||
)
|
||||
check(dead.alerts.length === 1, `exactly one alert over 40 runs, got ${dead.alerts.length}`)
|
||||
|
||||
// ---------------------------------------------------------------- B: blip --
|
||||
const blip = await scenario(
|
||||
'B) single dropped run (run 5), probe otherwise healthy',
|
||||
(n) => n === 5,
|
||||
40
|
||||
)
|
||||
check(blip.fallbackRuns === 1, `exactly one fallback run, got ${blip.fallbackRuns}`)
|
||||
check(blip.firstDegradedRun === null, `single blip never degrades, got ${blip.firstDegradedRun}`)
|
||||
check(blip.alerts.length === 0, `single blip raises no alert, got ${blip.alerts.length}`)
|
||||
check(
|
||||
blip.uniqueLocs.includes(PROBE_COLO) && blip.uniqueLocs.includes(LOCAL_COLO),
|
||||
'blip run really took the fallback branch'
|
||||
)
|
||||
|
||||
// ------------------------------------------------- C: control for the design
|
||||
// Same permanently dead probe, but the CRON worker happens to be scheduled in
|
||||
// IAD — inside enam, the very region being checked. The naive "map the colo
|
||||
// back to a region" test sees United States on every run and stays silent.
|
||||
const blind = await scenario(
|
||||
'C) control — dead probe, but the cron worker sits in the target region (IAD)',
|
||||
(n) => n >= 4,
|
||||
40,
|
||||
'IAD'
|
||||
)
|
||||
check(
|
||||
blind.naiveLooksCorrect === 40,
|
||||
`naive geo test is blind here: it saw the configured region on ${blind.naiveLooksCorrect}/40 runs`
|
||||
)
|
||||
check(
|
||||
blind.alerts.length === 1 && blind.deadRunsBeforeDetection === PROBE_DRIFT_RUNS,
|
||||
'the implemented detection still fires — it asks the proxy, not the map'
|
||||
)
|
||||
|
||||
console.log(`\n${ok ? 'GREEN' : 'RED'}`)
|
||||
if (!ok) process.exitCode = 1
|
||||
}
|
||||
|
||||
main()
|
||||
|
|
@ -152,4 +152,23 @@ export type MonitorStateCompacted = {
|
|||
time: string // Hex encoded Uint32Array
|
||||
}
|
||||
>
|
||||
|
||||
// Probe health per monitor — unix seconds of the most recent run whose check
|
||||
// actually came back from the monitor's CONFIGURED region (`checkProxy`).
|
||||
//
|
||||
// Why this exists: with `checkProxyFallback: true` a probe outage is silent.
|
||||
// monitor.ts falls back to a local re-check, `checkLocation` keeps the local
|
||||
// colo, and the page stays honest — it names the place it really measured.
|
||||
// Nothing anywhere says the configured region has stopped answering, so a
|
||||
// permanently dead Durable Object degrades a two-region page to a one-region
|
||||
// page without a single signal. This field is that signal.
|
||||
//
|
||||
// A timestamp, deliberately not a run counter: the state is only written when
|
||||
// something changed or after `kvWriteCooldownMinutes` (index.ts:239-249), so
|
||||
// an increment-per-run counter would silently lose the runs in between. A
|
||||
// timestamp is idempotent and survives skipped writes.
|
||||
//
|
||||
// Optional: states written before this change simply don't have it, and the
|
||||
// clock starts on the first run after the deploy.
|
||||
probeOkAt?: Record<string, number> // monitor id -> unix seconds
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,14 +110,22 @@ const workerConfig: WorkerConfig = {
|
|||
// ---------------------------------------------------------------------
|
||||
],
|
||||
notification: {
|
||||
// Wire Pushover here (same account as ops/minimax-usage.sh) — needs the
|
||||
// owner's Pushover token/user key; do not commit real keys, use the
|
||||
// full-config option of reading from env if desired.
|
||||
// webhook: {
|
||||
// url: 'https://api.pushover.net/1/messages.json',
|
||||
// payloadType: 'x-www-form-urlencoded',
|
||||
// payload: { token: 'APP_TOKEN', user: 'USER_KEY', message: '$MSG' },
|
||||
// },
|
||||
// ALERT CHANNEL — Pushover, wired in worker/src/pushover.ts.
|
||||
//
|
||||
// `webhook` stays UNSET here on purpose and is not a gap: the upstream
|
||||
// webhook path (worker/src/util.ts:83) reads its credentials out of THIS
|
||||
// committed object, and this repository is public, so a Pushover app token
|
||||
// and user key cannot live here. The fork sends the identical formatted
|
||||
// message from Worker SECRET bindings instead (PUSHOVER_TOKEN /
|
||||
// PUSHOVER_USER, see worker/src/index.ts Env and deploy.tf).
|
||||
//
|
||||
// Everything below still applies to it: it is dispatched by the same
|
||||
// `formatAndNotify`, so skipNotificationIds, maintenance windows and the
|
||||
// grace period gate Pushover exactly as they gated the webhook.
|
||||
//
|
||||
// If the secrets are not set, the channel is FAIL-CLOSED AND LOUD: every
|
||||
// dropped alert logs `[ALERT-CHANNEL-BROKEN] … missing Worker secret(s) …`
|
||||
// as an error, so an outage nobody could be told about is itself visible.
|
||||
timeZone: 'Europe/Berlin',
|
||||
// Avoid flapping alerts: notify only after 3 consecutive failed checks.
|
||||
gracePeriod: 3,
|
||||
|
|
|
|||
|
|
@ -2,13 +2,26 @@ import { DurableObject } from 'cloudflare:workers'
|
|||
import { MonitorTarget } from '../../types/config'
|
||||
import { workerConfig } from '../../uptime.config'
|
||||
import { doMonitor, getStatus } from './monitor'
|
||||
import { formatAndNotify, getWorkerLocation } from './util'
|
||||
import { formatAndNotify, getWorkerLocation, webhookNotify } from './util'
|
||||
import { pushoverNotify } from './pushover'
|
||||
import { CompactedMonitorStateWrapper, getFromStore, setToStore } from './store'
|
||||
import {
|
||||
evaluateProbe,
|
||||
formatProbeDriftNotification,
|
||||
formatProbeRecoveryNotification,
|
||||
PROBE_DRIFT_RUNS,
|
||||
} from './probe'
|
||||
import pLimit from 'p-limit'
|
||||
|
||||
export interface Env {
|
||||
REMOTE_CHECKER_DO: DurableObjectNamespace<RemoteChecker>
|
||||
UPTIMEFLARE_D1: D1Database
|
||||
// Pushover alert channel (worker/src/pushover.ts). Bound as Worker SECRETS
|
||||
// by deploy.tf from the GitHub repository secrets of the same name — never
|
||||
// committed, this repository is public. Optional in the type on purpose:
|
||||
// when they are absent the run must still work and must SAY they are absent.
|
||||
PUSHOVER_TOKEN?: string
|
||||
PUSHOVER_USER?: string
|
||||
}
|
||||
|
||||
const Worker = {
|
||||
|
|
@ -26,7 +39,12 @@ const Worker = {
|
|||
|
||||
// Parallel check multiple monitors
|
||||
// Max concurrent connection is 6 limited by Cloudflare Workers, we use 5 here to be safe
|
||||
type CheckResult = { id: string; location: string; status: { ping: number; up: boolean; err: string } }
|
||||
type CheckResult = {
|
||||
id: string
|
||||
location: string
|
||||
status: { ping: number; up: boolean; err: string }
|
||||
fromConfiguredRegion: boolean
|
||||
}
|
||||
let checkQueue: Promise<CheckResult>[] = []
|
||||
let checkResult: Record<string, CheckResult> = {};
|
||||
const limit = pLimit(5);
|
||||
|
|
@ -77,7 +95,14 @@ const Worker = {
|
|||
currentTimeSecond - lastIncident.start[0] >=
|
||||
(workerConfig.notification.gracePeriod + 1) * 60 - 30
|
||||
) {
|
||||
await formatAndNotify(monitor, true, lastIncident.start[0], currentTimeSecond, 'OK')
|
||||
await formatAndNotify(
|
||||
env,
|
||||
monitor,
|
||||
true,
|
||||
lastIncident.start[0],
|
||||
currentTimeSecond,
|
||||
'OK'
|
||||
)
|
||||
} else {
|
||||
console.log(
|
||||
`grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping webhook UP notification for ${monitor.name}`
|
||||
|
|
@ -145,6 +170,7 @@ const Worker = {
|
|||
)
|
||||
} else {
|
||||
await formatAndNotify(
|
||||
env,
|
||||
monitor,
|
||||
false,
|
||||
currentIncident.start[0],
|
||||
|
|
@ -194,6 +220,64 @@ const Worker = {
|
|||
}
|
||||
}
|
||||
|
||||
// --- probe drift: is this monitor still measuring from its own region? --
|
||||
// Independent of up/down on purpose. A monitor can be perfectly green and
|
||||
// still have stopped being the second vantage point it is named after.
|
||||
const probe = evaluateProbe(
|
||||
state.data,
|
||||
monitor.id,
|
||||
checkResult[monitor.id].fromConfiguredRegion,
|
||||
currentTimeSecond
|
||||
)
|
||||
if (monitor.checkProxy && probe.degraded) {
|
||||
// Logged every run while degraded: `wrangler tail` is the channel that
|
||||
// works even with no webhook configured.
|
||||
console.log(
|
||||
`[probe-drift] ${monitor.id}: configured region ${monitor.checkProxy} has not ` +
|
||||
`answered for ${probe.staleFor}s (>= ${PROBE_DRIFT_RUNS} runs); measuring from ` +
|
||||
`${checkLocation} instead`
|
||||
)
|
||||
}
|
||||
if (monitor.checkProxy && (probe.crossed || probe.recovered)) {
|
||||
// Notified once per transition, not per run — the point of N is to not
|
||||
// trade silence for alarm fatigue.
|
||||
const message = probe.crossed
|
||||
? formatProbeDriftNotification(
|
||||
monitor.name,
|
||||
monitor.checkProxy,
|
||||
checkLocation,
|
||||
probe.staleFor
|
||||
)
|
||||
: formatProbeRecoveryNotification(monitor.name, monitor.checkProxy)
|
||||
console.log(message)
|
||||
if (workerConfig.notification?.webhook) {
|
||||
try {
|
||||
await webhookNotify(workerConfig.notification.webhook, message)
|
||||
} catch (e) {
|
||||
console.log('Error sending probe drift notification: ' + e)
|
||||
}
|
||||
}
|
||||
// MERGE RESOLUTION (probe-drift x alert-channel): the webhook above is
|
||||
// the only channel the probe-drift change could use when it was written,
|
||||
// and `notification.webhook` is unset for good — its credentials would
|
||||
// have to be committed into this PUBLIC repo (uptime.config.ts). Left
|
||||
// alone, the two changes would have combined into a finding that never
|
||||
// reaches anyone. It is therefore sent over the same Pushover channel as
|
||||
// an outage, but labelled as neither UP nor DOWN and at normal priority:
|
||||
// a moved vantage point is an operations fact, not a user-visible
|
||||
// outage, and must not bypass quiet hours the way a real outage does.
|
||||
await pushoverNotify(
|
||||
env,
|
||||
message,
|
||||
true,
|
||||
monitor.name,
|
||||
undefined,
|
||||
probe.crossed ? 'check region degraded' : 'check region recovered'
|
||||
)
|
||||
// Force the state write so `probeOkAt` and the alert cannot drift apart.
|
||||
statusChanged = true
|
||||
}
|
||||
|
||||
// append to latency data
|
||||
state.appendLatency(monitor.id, {
|
||||
loc: checkLocation,
|
||||
|
|
|
|||
|
|
@ -358,6 +358,12 @@ export async function doMonitor(monitor: MonitorTarget, defaultLocation: string,
|
|||
let checkLocation = defaultLocation
|
||||
let status
|
||||
|
||||
// Did this run actually measure from the region the monitor is configured for?
|
||||
// A monitor without `checkProxy` is configured for "wherever the cron runs",
|
||||
// so the local colo IS its configured region and it is true by definition.
|
||||
// With a `checkProxy` it only becomes true when the proxy really answered.
|
||||
let fromConfiguredRegion = monitor.checkProxy === undefined
|
||||
|
||||
if (monitor.checkProxy) {
|
||||
// Initiate a check using proxy (Geo-specific monitoring)
|
||||
try {
|
||||
|
|
@ -389,9 +395,14 @@ export async function doMonitor(monitor: MonitorTarget, defaultLocation: string,
|
|||
}
|
||||
checkLocation = resp.location
|
||||
status = resp.status
|
||||
fromConfiguredRegion = true
|
||||
} catch (err) {
|
||||
console.log(`[${monitor.id}] Error calling proxy: ${err}`)
|
||||
if (monitor.checkProxyFallback) {
|
||||
// `fromConfiguredRegion` stays false: the target was measured, but NOT
|
||||
// from `monitor.checkProxy`. `checkLocation` keeps `defaultLocation`,
|
||||
// i.e. the local colo — which is the honest answer for the page and at
|
||||
// the same time the whole reason this branch is invisible.
|
||||
console.log('Falling back to local check...')
|
||||
status = await getStatus(monitor)
|
||||
} else {
|
||||
|
|
@ -410,5 +421,6 @@ export async function doMonitor(monitor: MonitorTarget, defaultLocation: string,
|
|||
location: checkLocation,
|
||||
status,
|
||||
id: monitor.id,
|
||||
fromConfiguredRegion,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,119 @@
|
|||
import { MonitorStateCompacted } from '../../types/config'
|
||||
|
||||
/**
|
||||
* Detection for the silent self-healing described in uptime.config.ts:80-85.
|
||||
*
|
||||
* `checkProxyFallback: true` is the right setting — a probe outage must not be
|
||||
* published as a service outage. But it makes the probe outage itself invisible:
|
||||
* monitor.ts falls back to a local re-check, the page reports the local colo
|
||||
* (truthfully), and nothing states that the configured region has stopped
|
||||
* answering. A Durable Object that never comes back therefore turns a
|
||||
* two-region page into a one-region page in complete silence.
|
||||
*
|
||||
* This module is the missing comparison: configured region (`checkProxy`)
|
||||
* against the region the run actually came from (`fromConfiguredRegion`,
|
||||
* monitor.ts).
|
||||
*
|
||||
* WHY NOT COMPARE THE COLO GEOGRAPHICALLY. The obvious reading of "target
|
||||
* region vs actual region" is to map the recorded colo (e.g. "EWR") to a
|
||||
* region and compare it against the hint ("enam"). That test is strictly
|
||||
* weaker and would have a real blind spot: `checkLocation` on the fallback
|
||||
* path is the CRON worker's colo, and the cron worker can be scheduled
|
||||
* anywhere — including inside the very region being checked. A dead enam probe
|
||||
* whose fallback happens to run in a US colo would look perfect. (Measured
|
||||
* 2026-07-31: cron colo LHR, probe colo EWR — today it would happen to show,
|
||||
* tomorrow it need not.) It would also need a ~200-entry country->region table
|
||||
* whose gaps produce false positives. The proxy call either answered or it did
|
||||
* not; that is the exact signal, so it is the one used here.
|
||||
*/
|
||||
|
||||
// Consecutive runs from outside the configured region before this is a finding.
|
||||
// Cron is `* * * * *` (deploy.tf:64-69), so N runs ~ N minutes.
|
||||
//
|
||||
// WHY 15:
|
||||
// * Noise floor: a Durable Object relocation or cold start costs one or two
|
||||
// runs. N=1 or N=3 would page for every blip — new alarm fatigue, which is
|
||||
// worse than the silence it replaces.
|
||||
// * Not the service grace period: `notification.gracePeriod` is 3 because a
|
||||
// user-visible outage is urgent. A probe that moved is an operations fact,
|
||||
// not a user-visible outage; it may be found 15 minutes later.
|
||||
// * Above the write cooldown: state is written at most every
|
||||
// `kvWriteCooldownMinutes` (3). At 5x that, a skipped state write can never
|
||||
// manufacture a streak.
|
||||
export const PROBE_DRIFT_RUNS = 15
|
||||
export const PROBE_DRIFT_SECONDS = PROBE_DRIFT_RUNS * 60
|
||||
|
||||
export type ProbeVerdict = {
|
||||
/** Seconds since the configured region last answered for this monitor. */
|
||||
staleFor: number
|
||||
/** Currently measuring from outside the configured region for >= N runs. */
|
||||
degraded: boolean
|
||||
/** This run is the one that crossed the threshold (fire the alert once). */
|
||||
crossed: boolean
|
||||
/** The configured region answered again after a degraded stretch. */
|
||||
recovered: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds one check result into `state.probeOkAt` and returns the verdict.
|
||||
* Mutates `state.probeOkAt` — that is the point, the field has to be persisted.
|
||||
*
|
||||
* @param monitorId id of the monitor just checked
|
||||
* @param fromConfiguredRegion did the run come from `monitor.checkProxy`?
|
||||
* @param now unix seconds of this run
|
||||
*/
|
||||
export function evaluateProbe(
|
||||
state: MonitorStateCompacted,
|
||||
monitorId: string,
|
||||
fromConfiguredRegion: boolean,
|
||||
now: number
|
||||
): ProbeVerdict {
|
||||
const probeOkAt = (state.probeOkAt ??= {})
|
||||
|
||||
// First time we see this monitor (fresh state, or first run after deploy):
|
||||
// start the clock now, so a monitor cannot be born already degraded.
|
||||
const previousOkAt = probeOkAt[monitorId] ?? now
|
||||
const staleFor = Math.max(0, now - previousOkAt)
|
||||
|
||||
if (fromConfiguredRegion) {
|
||||
probeOkAt[monitorId] = now
|
||||
return {
|
||||
staleFor: 0,
|
||||
degraded: false,
|
||||
crossed: false,
|
||||
recovered: staleFor >= PROBE_DRIFT_SECONDS,
|
||||
}
|
||||
}
|
||||
|
||||
probeOkAt[monitorId] = previousOkAt
|
||||
return {
|
||||
staleFor,
|
||||
degraded: staleFor >= PROBE_DRIFT_SECONDS,
|
||||
// Fire once, on the run that crosses. The +-30s window is the idiom already
|
||||
// used for the grace period in index.ts:129-137 and absorbs clock drift;
|
||||
// with a 60s cron exactly one run falls inside it.
|
||||
crossed: staleFor >= PROBE_DRIFT_SECONDS - 30 && staleFor < PROBE_DRIFT_SECONDS + 30,
|
||||
recovered: false,
|
||||
}
|
||||
}
|
||||
|
||||
export function formatProbeDriftNotification(
|
||||
monitorName: string,
|
||||
configuredRegion: string,
|
||||
measuredFrom: string,
|
||||
staleFor: number
|
||||
): string {
|
||||
return (
|
||||
`\u{1F4CD} ${monitorName}: check region "${configuredRegion}" has not answered for ` +
|
||||
`${Math.round(staleFor / 60)} minutes. Checks are falling back to ${measuredFrom}, ` +
|
||||
`so this monitor is no longer an independent vantage point. ` +
|
||||
`Service status itself is unaffected.`
|
||||
)
|
||||
}
|
||||
|
||||
export function formatProbeRecoveryNotification(
|
||||
monitorName: string,
|
||||
configuredRegion: string
|
||||
): string {
|
||||
return `\u{2705} ${monitorName}: check region "${configuredRegion}" is answering again.`
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
// Pushover alert channel for the status worker.
|
||||
//
|
||||
// WHY THIS FILE EXISTS
|
||||
// The fork ships exactly one built-in notification path, `notification.webhook`
|
||||
// in uptime.config.ts (dispatched by worker/src/util.ts:82 `webhookNotify`).
|
||||
// That path takes its credentials from the *committed* config object, so wiring
|
||||
// Pushover through it would put the app token and the user key into a PUBLIC
|
||||
// git repository. It stayed commented out for that reason — which meant every
|
||||
// outage, including an outage of the check regions themselves, notified nobody.
|
||||
//
|
||||
// This module sends the same formatted message to Pushover, but reads the two
|
||||
// credentials from Worker *secret bindings* (env), so nothing secret is ever
|
||||
// committed. It is deliberately FAIL-CLOSED AND LOUD: if a credential is
|
||||
// missing the run does not silently skip, it logs an error that names exactly
|
||||
// what is missing and what the operator has to do.
|
||||
//
|
||||
// Same account/endpoint as the Mac mini's existing alert path
|
||||
// (`~/osg/ops/minimax-usage.sh`, credentials in `~/osg/shared/.env` under the
|
||||
// keys PUSHOVER_TOKEN / PUSHOVER_USER). Pushover's API is a plain HTTPS POST
|
||||
// with a form body and needs no SDK, no account beyond the existing one and no
|
||||
// egress that a Cloudflare Worker cannot do.
|
||||
|
||||
/** Secret bindings this channel needs. Optional on purpose: absence is a state
|
||||
* we must detect and report, not a compile error. */
|
||||
export type PushoverEnv = {
|
||||
PUSHOVER_TOKEN?: string
|
||||
PUSHOVER_USER?: string
|
||||
}
|
||||
|
||||
const PUSHOVER_API = 'https://api.pushover.net/1/messages.json'
|
||||
|
||||
/** Marker every failure of the alert channel itself carries, so it can be
|
||||
* grepped in `wrangler tail` / Workers Logs without knowing this file. */
|
||||
export const ALERT_CHANNEL_BROKEN = '[ALERT-CHANNEL-BROKEN]'
|
||||
|
||||
/**
|
||||
* Send one status-change message to Pushover.
|
||||
*
|
||||
* Never throws: a broken alert channel must not abort the monitoring run that
|
||||
* produced the alert. Every failure path logs with `console.error` so it shows
|
||||
* up as an error in Workers Logs (observability is on, deploy.tf:38-45).
|
||||
*/
|
||||
export async function pushoverNotify(
|
||||
env: PushoverEnv | undefined,
|
||||
message: string,
|
||||
isUp: boolean,
|
||||
monitorName: string,
|
||||
timeoutMs = 8000,
|
||||
// Label for events that are neither an outage nor a recovery — currently the
|
||||
// probe-drift finding from worker/src/probe.ts, which is an operations fact
|
||||
// about our own vantage point, not about the monitored service. Omitted for
|
||||
// the normal status change, which keeps the UP/DOWN wording unchanged.
|
||||
eventLabel?: string
|
||||
): Promise<boolean> {
|
||||
const label = eventLabel ?? (isUp ? 'UP' : 'DOWN')
|
||||
const token = env?.PUSHOVER_TOKEN?.trim()
|
||||
const user = env?.PUSHOVER_USER?.trim()
|
||||
|
||||
const missing: string[] = []
|
||||
if (!token) missing.push('PUSHOVER_TOKEN')
|
||||
if (!user) missing.push('PUSHOVER_USER')
|
||||
if (missing.length > 0) {
|
||||
// FAIL-CLOSED: no credential -> no alert. Say so loudly instead of
|
||||
// returning quietly, otherwise this looks exactly like "all is well".
|
||||
console.error(
|
||||
`${ALERT_CHANNEL_BROKEN} Pushover alert for "${monitorName}" (${label}) was NOT sent: missing Worker secret(s) ${missing.join(
|
||||
' and '
|
||||
)}. Nobody is being notified about outages. Fix: set the GitHub repository secret(s) ` +
|
||||
`${missing.join(' and ')} on k55f97/osg-status; deploy.yml passes them as TF_VAR_* and ` +
|
||||
`deploy.tf binds them as Worker secrets. Message that was dropped: ${message}`
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
// priority 1 = bypass quiet hours for a real outage, 0 = normal for recovery.
|
||||
const body = new URLSearchParams({
|
||||
token: token as string,
|
||||
user: user as string,
|
||||
title: `OpenShopGraph Status: ${monitorName} ${eventLabel ?? (isUp ? 'recovered' : 'DOWN')}`,
|
||||
message,
|
||||
priority: isUp ? '0' : '1',
|
||||
})
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
try {
|
||||
const resp = await fetch(PUSHOVER_API, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
signal: controller.signal,
|
||||
})
|
||||
// Response body is small JSON and carries the error reason on 4xx; it never
|
||||
// echoes the credentials back, so it is safe to log. The request body is
|
||||
// NOT logged — it contains the token and the user key.
|
||||
const text = await resp.text()
|
||||
if (!resp.ok) {
|
||||
console.error(
|
||||
`${ALERT_CHANNEL_BROKEN} Pushover rejected the alert for "${monitorName}": HTTP ${resp.status} ${text}`
|
||||
)
|
||||
return false
|
||||
}
|
||||
console.log(`Pushover alert sent for "${monitorName}" (${label}): ${text}`)
|
||||
return true
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`${ALERT_CHANNEL_BROKEN} Pushover alert for "${monitorName}" could not be delivered: ${e}`
|
||||
)
|
||||
return false
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { MonitorTarget, WebhookConfig } from '../../types/config'
|
||||
import { maintenances, workerConfig } from '../../uptime.config'
|
||||
import { pushoverNotify, PushoverEnv } from './pushover'
|
||||
|
||||
async function getWorkerLocation() {
|
||||
const res = await fetch('https://cloudflare.com/cdn-cgi/trace')
|
||||
|
|
@ -148,6 +149,11 @@ async function webhookNotify(webhook: WebhookConfig, message: string) {
|
|||
|
||||
// Auxiliary function to format notification and send it via webhook
|
||||
const formatAndNotify = async (
|
||||
// `env` carries the Worker secret bindings for credential-based channels
|
||||
// (Pushover). It is optional so that callers/tests without an env still
|
||||
// compile; a missing env is treated as "credential missing" and is reported
|
||||
// loudly by pushoverNotify rather than silently skipped.
|
||||
env: PushoverEnv | undefined,
|
||||
monitor: MonitorTarget,
|
||||
isUp: boolean,
|
||||
timeIncidentStart: number,
|
||||
|
|
@ -176,19 +182,26 @@ const formatAndNotify = async (
|
|||
return
|
||||
}
|
||||
|
||||
const notification = formatStatusChangeNotification(
|
||||
monitor,
|
||||
isUp,
|
||||
timeIncidentStart,
|
||||
timeNow,
|
||||
reason,
|
||||
workerConfig.notification?.timeZone ?? 'Etc/GMT'
|
||||
)
|
||||
|
||||
// Channel 1 (upstream): generic webhook, credentials would live in the
|
||||
// committed config — unusable for this PUBLIC repo, so normally unset.
|
||||
if (workerConfig.notification?.webhook) {
|
||||
const notification = formatStatusChangeNotification(
|
||||
monitor,
|
||||
isUp,
|
||||
timeIncidentStart,
|
||||
timeNow,
|
||||
reason,
|
||||
workerConfig.notification?.timeZone ?? 'Etc/GMT'
|
||||
)
|
||||
await webhookNotify(workerConfig.notification.webhook, notification)
|
||||
} else {
|
||||
console.log(`Webhook not set, skipping notification for ${monitor.name}`)
|
||||
}
|
||||
|
||||
// Channel 2 (fork): Pushover with credentials from Worker secret bindings.
|
||||
// Always attempted. If the secrets are missing this does NOT fall through
|
||||
// quietly — it logs an error naming the missing secret, so an unnotifiable
|
||||
// outage is itself visible in the logs.
|
||||
await pushoverNotify(env, notification, isUp, monitor.name)
|
||||
}
|
||||
|
||||
export {
|
||||
|
|
|
|||
Loading…
Reference in New Issue