UptimeFlare/worker/src/index.ts

364 lines
13 KiB
TypeScript

import { DurableObject } from 'cloudflare:workers'
import { MonitorTarget } from '../../types/config'
import { workerConfig } from '../../uptime.config'
import { doMonitor, getStatus } from './monitor'
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 = {
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void> {
const workerLocation = (await getWorkerLocation()) || 'ERROR'
console.log(`Running scheduled event on ${workerLocation}...`)
// Create a wrapped MonitorState from stored compacted state
const state = new CompactedMonitorStateWrapper(await getFromStore(env, 'state'))
state.data.overallDown = 0
state.data.overallUp = 0
let statusChanged = false
const currentTimeSecond = Math.round(Date.now() / 1000)
// 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 }
fromConfiguredRegion: boolean
}
let checkQueue: Promise<CheckResult>[] = []
let checkResult: Record<string, CheckResult> = {};
const limit = pLimit(5);
for (const monitor of workerConfig.monitors) {
checkQueue.push(limit(() => doMonitor(monitor, workerLocation, env)))
}
for (const result of await Promise.all(checkQueue)) {
checkResult[result.id] = result
}
// Update each monitor's state based on check results
for (const monitor of workerConfig.monitors) {
console.log(`Processing monitor result: ${monitor.name} (${monitor.id})`)
let monitorStatusChanged = false
const { location: checkLocation, status } = checkResult[monitor.id]
// Update counters
status.up ? state.data.overallUp++ : state.data.overallDown++
// Update incidents
// Create a dummy incident to store the start time of the monitoring and simplify logic
if (state.incidentLen(monitor.id) === 0) {
state.appendIncident(monitor.id, {
start: [currentTimeSecond],
end: currentTimeSecond,
error: ['dummy'],
})
}
// Then lastIncident here must not be null
let lastIncident = state.getIncident(monitor.id, state.incidentLen(monitor.id) - 1)
if (status.up) {
// Current status is up
// close existing incident if any
if (lastIncident.end === null) {
lastIncident.end = currentTimeSecond
// write back the modified last incident
state.setIncident(monitor.id, state.incidentLen(monitor.id) - 1, lastIncident)
monitorStatusChanged = true
try {
if (
// grace period not set OR ...
workerConfig.notification?.gracePeriod === undefined ||
// only when we have sent a notification for DOWN status, we will send a notification for UP status (within 30 seconds of possible drift)
currentTimeSecond - lastIncident.start[0] >=
(workerConfig.notification.gracePeriod + 1) * 60 - 30
) {
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}`
)
}
console.log('Calling config onStatusChange callback...')
await workerConfig.callbacks?.onStatusChange?.(
env,
monitor,
true,
lastIncident.start[0],
currentTimeSecond,
'OK'
)
} catch (e) {
console.log('Error calling callback: ')
console.log(e)
}
}
} else {
// Current status is down
// open new incident if not already open
if (lastIncident.end !== null) {
state.appendIncident(monitor.id, {
start: [currentTimeSecond],
end: null,
error: [status.err],
})
monitorStatusChanged = true
} else if (lastIncident.end === null && lastIncident.error.slice(-1)[0] !== status.err) {
// append if the error message changes
lastIncident.start.push(currentTimeSecond)
lastIncident.error.push(status.err)
// write back the modified last incident
state.setIncident(monitor.id, state.incidentLen(monitor.id) - 1, lastIncident)
monitorStatusChanged = true
}
const currentIncident = state.getIncident(monitor.id, state.incidentLen(monitor.id) - 1)
try {
if (
// monitor status changed AND...
(monitorStatusChanged &&
// grace period not set OR ...
(workerConfig.notification?.gracePeriod === undefined ||
// have sent a notification for DOWN status
currentTimeSecond - currentIncident.start[0] >=
(workerConfig.notification.gracePeriod + 1) * 60 - 30)) ||
// grace period is set AND...
(workerConfig.notification?.gracePeriod !== undefined &&
// grace period is met
currentTimeSecond - currentIncident.start[0] >=
workerConfig.notification.gracePeriod * 60 - 30 &&
currentTimeSecond - currentIncident.start[0] <
workerConfig.notification.gracePeriod * 60 + 30)
) {
if (
currentIncident.start[0] !== currentTimeSecond &&
workerConfig.notification?.skipErrorChangeNotification
) {
console.log(
'Skipping notification for following error reason change due to user config'
)
} else {
await formatAndNotify(
env,
monitor,
false,
currentIncident.start[0],
currentTimeSecond,
status.err
)
}
} else {
console.log(
`Grace period (${workerConfig.notification
?.gracePeriod}m) not met or no change (currently down for ${
currentTimeSecond - currentIncident.start[0]
}s, changed ${monitorStatusChanged}), skipping webhook DOWN notification for ${
monitor.name
}`
)
}
if (monitorStatusChanged) {
console.log('Calling config onStatusChange callback...')
await workerConfig.callbacks?.onStatusChange?.(
env,
monitor,
false,
currentIncident.start[0],
currentTimeSecond,
status.err
)
}
} catch (e) {
console.log('Error calling callback: ')
console.log(e)
}
try {
console.log('Calling config onIncident callback...')
await workerConfig.callbacks?.onIncident?.(
env,
monitor,
currentIncident.start[0],
currentTimeSecond,
status.err
)
} catch (e) {
console.log('Error calling callback: ')
console.log(e)
}
}
// --- 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,
ping: status.ping,
time: currentTimeSecond,
})
// discard old data
while (state.getFirstLatency(monitor.id).time < currentTimeSecond - 12 * 60 * 60) {
state.unshiftLatency(monitor.id)
}
// discard old incidents
while (
state.incidentLen(monitor.id) > 0 &&
state.getIncident(monitor.id, 0).end &&
state.getIncident(monitor.id, 0).end! < currentTimeSecond - 90 * 24 * 60 * 60
) {
state.shiftIncident(monitor.id)
}
if (
state.incidentLen(monitor.id) === 0 ||
(state.getIncident(monitor.id, 0).start[0] > currentTimeSecond - 90 * 24 * 60 * 60 &&
state.getIncident(monitor.id, 0).error[0] != 'dummy')
) {
// put the dummy incident back
state.unshiftIncident(monitor.id, {
start: [currentTimeSecond - 90 * 24 * 60 * 60],
end: currentTimeSecond - 90 * 24 * 60 * 60,
error: ['dummy'],
})
}
statusChanged ||= monitorStatusChanged
}
console.log(
`statusChanged: ${statusChanged}, lastUpdate: ${state.data.lastUpdate}, currentTime: ${currentTimeSecond}`
)
// Update state
// Allow for a cooldown period before writing to storage
if (
statusChanged ||
currentTimeSecond - state.data.lastUpdate >=
(workerConfig.kvWriteCooldownMinutes ?? 3) * 60 - 10 // Allow for 10 seconds of clock drift
) {
console.log('Updating state...')
state.data.lastUpdate = currentTimeSecond
await setToStore(env, 'state', state.getCompactedStateStr())
} else {
console.log('Skipping state update due to cooldown period.')
}
},
}
export default Worker
export class RemoteChecker extends DurableObject {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env)
}
async getLocationAndStatus(
monitor: MonitorTarget
): Promise<{ location: string; status: { ping: number; up: boolean; err: string } }> {
const colo = (await getWorkerLocation()) as string
console.log(`Running remote checker (DurableObject) at ${colo}...`)
const status = await getStatus(monitor)
return {
location: colo,
status: status,
}
}
async kill() {
// Throwing an error in `blockConcurrencyWhile` will terminate the Durable Object instance
// https://developers.cloudflare.com/durable-objects/api/state/#blockconcurrencywhile
this.ctx.blockConcurrencyWhile(async () => {
throw 'killed'
})
}
}