pull/221/merge
Romulo Gatto 2026-10-21 12:27:31 +00:00 committed by GitHub
commit 601ecac50f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 871 additions and 73 deletions

View File

@ -8,7 +8,13 @@ import { useTranslation } from 'react-i18next'
function countDownCount(state: MonitorState, ids: string[]) {
let downCount = 0
for (let id of ids) {
if (state.incident[id] === undefined || state.incident[id].length === 0) {
if (
state.incident[id] === undefined ||
state.incident[id].length === 0 ||
state.latency[id] === undefined ||
state.latency[id].length === 0
) {
downCount++
continue
}

View File

@ -7,7 +7,8 @@
"preview": "npx @cloudflare/next-on-pages && wrangler pages dev .vercel/output/static",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"test": "node --experimental-strip-types --test tests/*.test.mjs"
},
"dependencies": {
"@cloudflare/workers-types": "^4.20250410.0",

View File

@ -49,6 +49,18 @@ export default async function handler(req: NextRequest): Promise<Response> {
await getFromStore(process.env as any, 'state')
)
if (!compactedState.hasMonitorData(monitorId)) {
return new Response(
JSON.stringify({
schemaVersion: 1,
label,
message: downMsg,
color: colorDown,
} satisfies BadgePayload),
{ headers: jsonHeaders }
)
}
const lastIncident = compactedState.getIncident(
monitorId,
compactedState.incidentLen(monitorId) - 1

View File

@ -26,6 +26,16 @@ export default async function handler(req: NextRequest): Promise<Response> {
let monitors: any = {}
for (let monitor of workerConfig.monitors) {
if (!compactedState.hasMonitorData(monitor.id)) {
monitors[monitor.id] = {
up: false,
latency: null,
location: null,
message: 'No data available',
}
continue
}
const lastIncident = compactedState.getIncident(
monitor.id,
compactedState.incidentLen(monitor.id) - 1

View File

@ -0,0 +1,308 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { selectMonitorBatch } from '../worker/src/batch.ts'
import {
allWebhookDeliveriesSucceeded,
shouldSendDownNotification,
} from '../worker/src/notification.ts'
import { shouldPersistState } from '../worker/src/persistence.ts'
import {
CompactedMonitorStateWrapper,
setToStoreIfUnchanged,
} from '../worker/src/store.ts'
const monitors = Array.from({ length: 20 }, (_, index) => ({ id: `monitor-${index + 1}` }))
function addLatencyState(state, monitorId) {
state.data.latency[monitorId] = {
time: '00000000',
ping: '0000',
loc: { c: [1], v: ['TEST'] },
}
}
test('checks every monitor when batching is not configured', () => {
const selection = selectMonitorBatch(monitors, undefined, 0)
assert.equal(selection.batched, false)
assert.equal(selection.batchIndex, 0)
assert.equal(selection.batchCount, 1)
assert.deepEqual(selection.monitors, monitors)
})
test('invalid batch sizes preserve all-monitor behavior', () => {
for (const batchSize of [0, -1, 1.5, Number.NaN, 20, 21]) {
const selection = selectMonitorBatch(monitors, batchSize, 0)
assert.equal(selection.batched, false)
assert.deepEqual(selection.monitors, monitors)
}
})
test('selects deterministic round-robin batches for the default every-minute schedule', () => {
const first = selectMonitorBatch(monitors, 5, 0)
const second = selectMonitorBatch(monitors, 5, 60_000)
const third = selectMonitorBatch(monitors, 5, 2 * 60_000)
const fourth = selectMonitorBatch(monitors, 5, 3 * 60_000)
const wrapped = selectMonitorBatch(monitors, 5, 4 * 60_000)
assert.deepEqual(first.monitors.map(({ id }) => id), [
'monitor-1',
'monitor-2',
'monitor-3',
'monitor-4',
'monitor-5',
])
assert.deepEqual(second.monitors.map(({ id }) => id), [
'monitor-6',
'monitor-7',
'monitor-8',
'monitor-9',
'monitor-10',
])
assert.equal(third.batchIndex, 2)
assert.equal(fourth.batchIndex, 3)
assert.deepEqual(fourth.monitors.map(({ id }) => id), [
'monitor-16',
'monitor-17',
'monitor-18',
'monitor-19',
'monitor-20',
])
assert.deepEqual(wrapped.monitors, first.monitors)
})
test('retries and delayed retries select the original scheduled batch', () => {
const original = selectMonitorBatch(monitors, 5, 60_000)
selectMonitorBatch(monitors, 5, 2 * 60_000)
const delayedRetry = selectMonitorBatch(monitors, 5, 60_000)
assert.deepEqual(delayedRetry, original)
})
test('allows a smaller final batch when monitors do not divide evenly', () => {
const selection = selectMonitorBatch(monitors.slice(0, 12), 5, 2 * 60_000)
assert.equal(selection.batchCount, 3)
assert.equal(selection.batchIndex, 2)
assert.deepEqual(selection.monitors.map(({ id }) => id), ['monitor-11', 'monitor-12'])
})
test('recalculates global counters conservatively when monitor state is missing', () => {
const state = new CompactedMonitorStateWrapper(null)
state.appendIncident('up', { start: [1], end: 2, error: ['dummy'] })
state.appendIncident('down', { start: [3], end: null, error: ['timeout'] })
state.appendIncident('removed', { start: [4], end: null, error: ['removed'] })
addLatencyState(state, 'up')
addLatencyState(state, 'down')
state.recalculateOverallStatus(['up', 'down', 'unknown'])
assert.equal(state.data.overallUp, 1)
assert.equal(state.data.overallDown, 2)
assert.equal(state.hasMonitorData('unknown'), false)
})
test('incident-only state remains unavailable until a complete check', () => {
const state = new CompactedMonitorStateWrapper(null)
state.appendIncident('checked', { start: [1], end: 1, error: ['dummy'] })
state.recalculateOverallStatus(['checked'])
assert.equal(state.hasMonitorData('checked'), false)
assert.equal(state.data.overallUp, 0)
assert.equal(state.data.overallDown, 1)
addLatencyState(state, 'checked')
state.recalculateOverallStatus(['checked'])
assert.equal(state.hasMonitorData('checked'), true)
assert.equal(state.data.overallUp, 1)
assert.equal(state.data.overallDown, 0)
})
test('sends delayed DOWN on the first check at or after grace period and only once', () => {
const base = {
incidentStart: 0,
gracePeriodMinutes: 2,
skipErrorChangeNotification: false,
}
assert.equal(
shouldSendDownNotification({
...base,
currentTime: 0,
notifiedIncidentStart: undefined,
monitorStatusChanged: true,
}),
false
)
assert.equal(
shouldSendDownNotification({
...base,
currentTime: 119,
notifiedIncidentStart: undefined,
monitorStatusChanged: false,
}),
false
)
assert.equal(
shouldSendDownNotification({
...base,
currentTime: 120,
notifiedIncidentStart: undefined,
monitorStatusChanged: false,
}),
true
)
assert.equal(
shouldSendDownNotification({
...base,
currentTime: 480,
notifiedIncidentStart: 0,
monitorStatusChanged: false,
}),
false
)
})
test('allows configured error-reason notifications after the initial DOWN', () => {
const base = {
currentTime: 240,
incidentStart: 0,
notifiedIncidentStart: 0,
gracePeriodMinutes: 2,
monitorStatusChanged: true,
}
assert.equal(
shouldSendDownNotification({ ...base, skipErrorChangeNotification: false }),
true
)
assert.equal(
shouldSendDownNotification({ ...base, skipErrorChangeNotification: true }),
false
)
})
test('persists DOWN, recovery, and error-change notification state', () => {
const state = new CompactedMonitorStateWrapper(null)
state.markDownNotificationSent('monitor-1', 123)
state.setPendingRecovery('monitor-1', 123, 456)
state.setPendingErrorChange('monitor-1', 123, 400, 'connection reset')
const restored = new CompactedMonitorStateWrapper(state.getCompactedStateStr())
assert.equal(restored.wasDownNotificationSent('monitor-1', 123), true)
assert.deepEqual(restored.getPendingRecovery('monitor-1'), {
incidentStart: 123,
recoveredAt: 456,
})
assert.deepEqual(restored.getPendingErrorChange('monitor-1'), {
incidentStart: 123,
changedAt: 400,
reason: 'connection reset',
})
restored.clearPendingRecovery('monitor-1')
restored.clearPendingErrorChange('monitor-1')
restored.clearDownNotificationSent('monitor-1', 123)
assert.equal(restored.getPendingRecovery('monitor-1'), undefined)
assert.equal(restored.getPendingErrorChange('monitor-1'), undefined)
assert.equal(restored.wasDownNotificationSent('monitor-1', 123), false)
})
test('rebases monitor-scoped state without discarding another batch', () => {
const firstBatch = new CompactedMonitorStateWrapper(null)
firstBatch.appendIncident('monitor-1', { start: [1], end: 1, error: ['dummy'] })
addLatencyState(firstBatch, 'monitor-1')
firstBatch.setMonitorLastUpdate('monitor-1', 10)
const secondBatch = new CompactedMonitorStateWrapper(null)
secondBatch.appendIncident('monitor-2', { start: [2], end: null, error: ['timeout'] })
addLatencyState(secondBatch, 'monitor-2')
secondBatch.setMonitorLastUpdate('monitor-2', 11)
const merged = new CompactedMonitorStateWrapper(firstBatch.getCompactedStateStr())
assert.equal(merged.copyMonitorStateFrom(secondBatch, 'monitor-2'), true)
assert.equal(merged.hasMonitorData('monitor-1'), true)
assert.equal(merged.hasMonitorData('monitor-2'), true)
const stale = new CompactedMonitorStateWrapper(firstBatch.getCompactedStateStr())
stale.setMonitorLastUpdate('monitor-1', 9)
assert.equal(merged.copyMonitorStateFrom(stale, 'monitor-1'), false)
assert.equal(merged.data.monitorLastUpdate['monitor-1'], 10)
const equalVersion = new CompactedMonitorStateWrapper(firstBatch.getCompactedStateStr())
equalVersion.setIncident('monitor-1', 0, {
start: [1],
end: null,
error: ['stale timeout'],
})
assert.equal(merged.copyMonitorStateFrom(equalVersion, 'monitor-1'), false)
assert.equal(merged.getIncident('monitor-1', 0).end, 1)
})
test('preserves a delivered DOWN when a newer concurrent check already recovered', () => {
const base = new CompactedMonitorStateWrapper(null)
base.appendIncident('monitor-1', { start: [100], end: null, error: ['timeout'] })
addLatencyState(base, 'monitor-1')
base.setMonitorLastUpdate('monitor-1', 10)
const deliveredDown = new CompactedMonitorStateWrapper(base.getCompactedStateStr())
deliveredDown.markDownNotificationSent('monitor-1', 100)
const recovered = new CompactedMonitorStateWrapper(base.getCompactedStateStr())
recovered.setIncident('monitor-1', 0, { start: [100], end: 200, error: ['timeout'] })
recovered.setMonitorLastUpdate('monitor-1', 20)
assert.equal(recovered.copyMonitorStateFrom(deliveredDown, 'monitor-1'), true)
assert.equal(recovered.getIncident('monitor-1', 0).end, 200)
assert.equal(recovered.wasDownNotificationSent('monitor-1', 100), true)
assert.deepEqual(recovered.getPendingRecovery('monitor-1'), {
incidentStart: 100,
recoveredAt: 200,
})
})
test('D1 compare-and-set rejects a stale whole-state write', async () => {
const db = {
value: 'initial',
prepare(sql) {
return {
bind: (...args) => ({
run: async () => {
if (sql.startsWith('UPDATE') && db.value === args[2]) {
db.value = args[0]
return { meta: { changes: 1 } }
}
return { meta: { changes: 0 } }
},
}),
}
},
}
const env = { UPTIMEFLARE_D1: db }
assert.equal(await setToStoreIfUnchanged(env, 'state', 'batch-a', 'initial'), true)
assert.equal(await setToStoreIfUnchanged(env, 'state', 'batch-b', 'initial'), false)
assert.equal(db.value, 'batch-a')
})
test('notification marker changes bypass the non-batched write cooldown', () => {
assert.equal(
shouldPersistState({
batched: false,
statusChanged: false,
notificationStateChanged: true,
currentTime: 61,
lastUpdate: 60,
cooldownMinutes: 3,
}),
true
)
})
test('webhook arrays are acknowledged only when every destination succeeds', () => {
assert.equal(allWebhookDeliveriesSucceeded([]), false)
assert.equal(allWebhookDeliveriesSucceeded([true, false]), false)
assert.equal(allWebhookDeliveriesSucceeded([true, true]), true)
})

View File

@ -49,6 +49,7 @@ export type MonitorTarget = {
export type WorkerConfig<TEnv = Env> = {
kvWriteCooldownMinutes?: number
monitorBatchSize?: number
passwordProtection?: string
monitors: MonitorTarget[]
notification?: Notification
@ -125,6 +126,24 @@ export type MonitorStateCompacted = {
lastUpdate: number
overallUp: number
overallDown: number
notifiedIncidentStart?: Record<string, number>
pendingRecovery?: Record<
string,
{
incidentStart: number
recoveredAt: number
}
>
pendingErrorChange?: Record<
string,
{
incidentStart: number
changedAt: number
reason: string
}
>
notificationLastUpdate?: Record<string, number>
monitorLastUpdate?: Record<string, number>
// incident in stored in columnar format
incident: Record<

View File

@ -33,6 +33,11 @@ const pageConfig: PageConfig = {
const workerConfig: WorkerConfig = {
// [Optional] Write KV at most every N minutes unless the status changed, default to 3
kvWriteCooldownMinutes: 3,
// [Optional] Check this many monitors per scheduled invocation in deterministic round-robin batches.
// Omit to check every monitor on every invocation. Must be a positive integer smaller than the monitor count.
// With the default every-minute Cron Trigger, 20 monitors and a batch size of 5 checks each monitor every 4 minutes.
// Batched checks persist every invocation (ignoring kvWriteCooldownMinutes), and lastUpdate means the latest batch update.
// monitorBatchSize: 5,
// Enable HTTP Basic auth for status page & API by uncommenting the line below, format `<USERNAME>:<PASSWORD>`
// passwordProtection: 'username:password',
// Define all your monitors here

46
worker/src/batch.ts Normal file
View File

@ -0,0 +1,46 @@
export type MonitorBatch<T> = {
monitors: T[]
batchIndex: number
batchCount: number
batched: boolean
}
/**
* Select a deterministic round-robin monitor batch for the default
* every-minute Cron Trigger. Retries keep the same scheduled timestamp and
* therefore select the same batch without a mutable cursor.
*/
export function selectMonitorBatch<T>(
monitors: T[],
configuredBatchSize: number | undefined,
scheduledTime: number
): MonitorBatch<T> {
if (
configuredBatchSize === undefined ||
!Number.isInteger(configuredBatchSize) ||
configuredBatchSize <= 0 ||
configuredBatchSize >= monitors.length
) {
return {
monitors,
batchIndex: 0,
batchCount: 1,
batched: false,
}
}
const batchSize = configuredBatchSize
const batchCount = Math.ceil(monitors.length / batchSize)
const scheduledMinute = Number.isFinite(scheduledTime)
? Math.floor(scheduledTime / 60_000)
: 0
const batchIndex = ((scheduledMinute % batchCount) + batchCount) % batchCount
const start = batchIndex * batchSize
return {
monitors: monitors.slice(start, start + batchSize),
batchIndex,
batchCount,
batched: true,
}
}

View File

@ -3,7 +3,10 @@ import { MonitorTarget } from '../../types/config'
import { workerConfig } from '../../uptime.config'
import { doMonitor, getStatus } from './monitor'
import { formatAndNotify, getWorkerLocation } from './util'
import { CompactedMonitorStateWrapper, getFromStore, setToStore } from './store'
import { CompactedMonitorStateWrapper, getFromStore, setToStoreIfUnchanged } from './store'
import { selectMonitorBatch } from './batch'
import { shouldSendDownNotification } from './notification'
import { shouldPersistState } from './persistence'
import pLimit from 'p-limit'
export interface Env {
@ -11,17 +14,66 @@ export interface Env {
UPTIMEFLARE_D1: D1Database
}
async function persistStateWithRetry(
env: Env,
initialStoredValue: string | null,
processedState: CompactedMonitorStateWrapper,
processedMonitorIds: string[],
currentTimeSecond: number
) {
let expectedValue = initialStoredValue
let candidate = processedState
for (let attempt = 1; attempt <= 5; attempt++) {
candidate.recalculateOverallStatus(workerConfig.monitors.map((monitor) => monitor.id))
candidate.data.lastUpdate = Math.max(candidate.data.lastUpdate, currentTimeSecond)
if (
await setToStoreIfUnchanged(
env,
'state',
candidate.getCompactedStateStr(),
expectedValue
)
) {
return
}
console.log(`State changed concurrently; rebasing selected batch (attempt ${attempt}/5)...`)
const latestValue = await getFromStore(env, 'state')
const latestState = new CompactedMonitorStateWrapper(latestValue)
for (const monitorId of processedMonitorIds) {
latestState.copyMonitorStateFrom(processedState, monitorId)
}
expectedValue = latestValue
candidate = latestState
}
throw new Error('Unable to persist monitor state after 5 concurrent update attempts')
}
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
const initialStoredState = await getFromStore(env, 'state')
const state = new CompactedMonitorStateWrapper(initialStoredState)
const monitorBatch = selectMonitorBatch(
workerConfig.monitors,
workerConfig.monitorBatchSize,
event.scheduledTime
)
console.log(
`Checking monitor batch ${monitorBatch.batchIndex + 1}/${monitorBatch.batchCount}: ${monitorBatch.monitors
.map((monitor) => monitor.id)
.join(', ')}`
)
let statusChanged = false
let notificationStateChanged = false
const currentTimeSecond = Math.round(Date.now() / 1000)
// Parallel check multiple monitors
@ -30,7 +82,7 @@ const Worker = {
let checkQueue: Promise<CheckResult>[] = []
let checkResult: Record<string, CheckResult> = {};
const limit = pLimit(5);
for (const monitor of workerConfig.monitors) {
for (const monitor of monitorBatch.monitors) {
checkQueue.push(limit(() => doMonitor(monitor, workerLocation, env)))
}
for (const result of await Promise.all(checkQueue)) {
@ -38,14 +90,55 @@ const Worker = {
}
// Update each monitor's state based on check results
for (const monitor of workerConfig.monitors) {
for (const monitor of monitorBatch.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++
// Retry recovery delivery independently from the current status. A
// failed webhook remains pending until every configured destination
// accepts it.
const pendingRecovery = state.getPendingRecovery(monitor.id)
if (pendingRecovery) {
try {
const recoverySent = await formatAndNotify(
monitor,
true,
pendingRecovery.incidentStart,
pendingRecovery.recoveredAt,
'OK'
)
if (recoverySent) {
state.clearPendingRecovery(monitor.id)
state.clearDownNotificationSent(monitor.id, pendingRecovery.incidentStart)
notificationStateChanged = true
}
} catch (e) {
console.log(`Error retrying recovery notification for ${monitor.id}:`)
console.log(e)
}
}
const pendingErrorChange = state.getPendingErrorChange(monitor.id)
if (pendingErrorChange) {
try {
const errorChangeSent = await formatAndNotify(
monitor,
false,
pendingErrorChange.incidentStart,
currentTimeSecond,
pendingErrorChange.reason
)
if (errorChangeSent) {
state.clearPendingErrorChange(monitor.id)
notificationStateChanged = true
}
} catch (e) {
console.log(`Error retrying error-change notification for ${monitor.id}:`)
console.log(e)
}
}
// Update incidents
// Create a dummy incident to store the start time of the monitoring and simplify logic
@ -70,17 +163,23 @@ const Worker = {
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(monitor, true, lastIncident.start[0], currentTimeSecond, 'OK')
if (state.wasDownNotificationSent(monitor.id, lastIncident.start[0])) {
state.setPendingRecovery(monitor.id, lastIncident.start[0], currentTimeSecond)
notificationStateChanged = true
const recoverySent = await formatAndNotify(
monitor,
true,
lastIncident.start[0],
currentTimeSecond,
'OK'
)
if (recoverySent) {
state.clearPendingRecovery(monitor.id)
state.clearDownNotificationSent(monitor.id, lastIncident.start[0])
}
} else {
console.log(
`grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping webhook UP notification for ${monitor.name}`
`Skipping webhook UP notification for ${monitor.name}: no DOWN notification was sent`
)
}
@ -121,45 +220,54 @@ const Worker = {
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)
shouldSendDownNotification({
currentTime: currentTimeSecond,
incidentStart: currentIncident.start[0],
notifiedIncidentStart: state.data.notifiedIncidentStart?.[monitor.id],
gracePeriodMinutes: workerConfig.notification?.gracePeriod,
monitorStatusChanged,
skipErrorChangeNotification:
workerConfig.notification?.skipErrorChangeNotification ?? false,
})
) {
if (
currentIncident.start[0] !== currentTimeSecond &&
workerConfig.notification?.skipErrorChangeNotification
) {
console.log(
'Skipping notification for following error reason change due to user config'
)
} else {
await formatAndNotify(
monitor,
false,
const isFollowupErrorChange =
state.wasDownNotificationSent(monitor.id, currentIncident.start[0]) &&
monitorStatusChanged &&
currentIncident.start[0] !== currentTimeSecond
if (isFollowupErrorChange) {
state.setPendingErrorChange(
monitor.id,
currentIncident.start[0],
currentTimeSecond,
status.err
)
notificationStateChanged = true
}
const notificationSent = await formatAndNotify(
monitor,
false,
currentIncident.start[0],
currentTimeSecond,
status.err
)
if (notificationSent) {
if (!state.wasDownNotificationSent(monitor.id, currentIncident.start[0])) {
notificationStateChanged = true
}
state.markDownNotificationSent(monitor.id, currentIncident.start[0])
if (isFollowupErrorChange) {
state.clearPendingErrorChange(monitor.id)
}
}
} else {
console.log(
`Grace period (${workerConfig.notification
?.gracePeriod}m) not met or no change (currently down for ${
`DOWN notification not due for ${monitor.name} (down for ${
currentTimeSecond - currentIncident.start[0]
}s, changed ${monitorStatusChanged}), skipping webhook DOWN notification for ${
monitor.name
}`
}s, changed ${monitorStatusChanged}, already sent ${state.wasDownNotificationSent(
monitor.id,
currentIncident.start[0]
)})`
)
}
@ -228,22 +336,40 @@ const Worker = {
})
}
state.setMonitorLastUpdate(monitor.id, Date.now())
statusChanged ||= monitorStatusChanged
}
// Monitors outside this invocation's batch retain their incident and
// latency history. Recalculate global counters from every monitor with
// persisted state. Monitors that have not been checked yet count as
// unavailable so the status page never presents unknown state as healthy.
state.recalculateOverallStatus(workerConfig.monitors.map((monitor) => monitor.id))
console.log(
`statusChanged: ${statusChanged}, lastUpdate: ${state.data.lastUpdate}, currentTime: ${currentTimeSecond}`
)
// Update state
// Allow for a cooldown period before writing to storage
// Batched checks must persist every selected batch so its results are not
// lost. Non-batched checks retain the configured cooldown.
if (
statusChanged ||
currentTimeSecond - state.data.lastUpdate >=
(workerConfig.kvWriteCooldownMinutes ?? 3) * 60 - 10 // Allow for 10 seconds of clock drift
shouldPersistState({
batched: monitorBatch.batched,
statusChanged,
notificationStateChanged,
currentTime: currentTimeSecond,
lastUpdate: state.data.lastUpdate,
cooldownMinutes: workerConfig.kvWriteCooldownMinutes,
})
) {
console.log('Updating state...')
state.data.lastUpdate = currentTimeSecond
await setToStore(env, 'state', state.getCompactedStateStr())
await persistStateWithRetry(
env,
initialStoredState,
state,
monitorBatch.monitors.map((monitor) => monitor.id),
currentTimeSecond
)
} else {
console.log('Skipping state update due to cooldown period.')
}

View File

@ -0,0 +1,33 @@
export type DownNotificationDecision = {
currentTime: number
incidentStart: number
notifiedIncidentStart: number | undefined
gracePeriodMinutes: number | undefined
monitorStatusChanged: boolean
skipErrorChangeNotification: boolean | undefined
}
export function allWebhookDeliveriesSucceeded(results: boolean[]): boolean {
return results.length > 0 && results.every(Boolean)
}
export function shouldSendDownNotification({
currentTime,
incidentStart,
notifiedIncidentStart,
gracePeriodMinutes,
monitorStatusChanged,
skipErrorChangeNotification,
}: DownNotificationDecision): boolean {
const isFollowupErrorChange = monitorStatusChanged && incidentStart !== currentTime
if (notifiedIncidentStart === incidentStart) {
return isFollowupErrorChange && !skipErrorChangeNotification
}
const gracePeriodSeconds = (gracePeriodMinutes ?? 0) * 60
if (currentTime - incidentStart < gracePeriodSeconds) return false
if (isFollowupErrorChange && skipErrorChangeNotification) return false
return true
}

24
worker/src/persistence.ts Normal file
View File

@ -0,0 +1,24 @@
export type PersistenceDecision = {
batched: boolean
statusChanged: boolean
notificationStateChanged: boolean
currentTime: number
lastUpdate: number
cooldownMinutes: number | undefined
}
export function shouldPersistState({
batched,
statusChanged,
notificationStateChanged,
currentTime,
lastUpdate,
cooldownMinutes,
}: PersistenceDecision): boolean {
return (
batched ||
statusChanged ||
notificationStateChanged ||
currentTime - lastUpdate >= (cooldownMinutes ?? 3) * 60 - 10
)
}

View File

@ -1,5 +1,5 @@
import { Env } from '.'
import {
import type { Env } from '.'
import type {
IncidentRecord,
LatencyRecord,
MonitorState,
@ -12,11 +12,27 @@ export async function getFromStore(env: Env, key: string): Promise<string | null
return result?.value || null
}
export async function setToStore(env: Env, key: string, value: string): Promise<void> {
const stmt = env.UPTIMEFLARE_D1.prepare(
'INSERT INTO uptimeflare (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value;'
export async function setToStoreIfUnchanged(
env: Env,
key: string,
value: string,
expectedValue: string | null
): Promise<boolean> {
if (expectedValue === null) {
const result = await env.UPTIMEFLARE_D1.prepare(
'INSERT INTO uptimeflare (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING;'
)
.bind(key, value)
.run()
return (result.meta.changes ?? 0) > 0
}
const result = await env.UPTIMEFLARE_D1.prepare(
'UPDATE uptimeflare SET value = ? WHERE key = ? AND value = ?;'
)
await stmt.bind(key, value).run()
.bind(value, key, expectedValue)
.run()
return (result.meta.changes ?? 0) > 0
}
export class CompactedMonitorStateWrapper {
@ -29,12 +45,22 @@ export class CompactedMonitorStateWrapper {
lastUpdate: 0,
overallUp: 0,
overallDown: 0,
notifiedIncidentStart: {},
pendingRecovery: {},
pendingErrorChange: {},
notificationLastUpdate: {},
monitorLastUpdate: {},
incident: {},
latency: {},
}
return
}
this.data = JSON.parse(compactedStateStr)
this.data.notifiedIncidentStart ??= {}
this.data.pendingRecovery ??= {}
this.data.pendingErrorChange ??= {}
this.data.notificationLastUpdate ??= {}
this.data.monitorLastUpdate ??= {}
}
getCompactedStateStr(): string {
@ -183,6 +209,157 @@ export class CompactedMonitorStateWrapper {
return latencies.ping.length / 4 // Uint16Array, 4 characters per entry in hex
}
hasMonitorData(monitorId: string): boolean {
return this.incidentLen(monitorId) > 0 && this.latencyLen(monitorId) > 0
}
private touchNotificationState(monitorId: string) {
this.data.notificationLastUpdate ??= {}
this.data.notificationLastUpdate[monitorId] = Math.max(
Date.now(),
(this.data.notificationLastUpdate[monitorId] ?? 0) + 1
)
}
wasDownNotificationSent(monitorId: string, incidentStart: number): boolean {
return this.data.notifiedIncidentStart?.[monitorId] === incidentStart
}
markDownNotificationSent(monitorId: string, incidentStart: number) {
this.data.notifiedIncidentStart ??= {}
this.data.notifiedIncidentStart[monitorId] = incidentStart
this.touchNotificationState(monitorId)
}
clearDownNotificationSent(monitorId: string, incidentStart?: number) {
if (
(incidentStart === undefined ||
this.data.notifiedIncidentStart?.[monitorId] === incidentStart) &&
this.data.notifiedIncidentStart?.[monitorId] !== undefined
) {
delete this.data.notifiedIncidentStart[monitorId]
this.touchNotificationState(monitorId)
}
}
getPendingRecovery(monitorId: string) {
return this.data.pendingRecovery?.[monitorId]
}
setPendingRecovery(monitorId: string, incidentStart: number, recoveredAt: number) {
this.data.pendingRecovery ??= {}
this.data.pendingRecovery[monitorId] = { incidentStart, recoveredAt }
this.touchNotificationState(monitorId)
}
clearPendingRecovery(monitorId: string) {
if (this.data.pendingRecovery?.[monitorId] !== undefined) {
delete this.data.pendingRecovery[monitorId]
this.touchNotificationState(monitorId)
}
}
getPendingErrorChange(monitorId: string) {
return this.data.pendingErrorChange?.[monitorId]
}
setPendingErrorChange(
monitorId: string,
incidentStart: number,
changedAt: number,
reason: string
) {
this.data.pendingErrorChange ??= {}
this.data.pendingErrorChange[monitorId] = { incidentStart, changedAt, reason }
this.touchNotificationState(monitorId)
}
clearPendingErrorChange(monitorId: string) {
if (this.data.pendingErrorChange?.[monitorId] !== undefined) {
delete this.data.pendingErrorChange[monitorId]
this.touchNotificationState(monitorId)
}
}
setMonitorLastUpdate(monitorId: string, checkedAt: number) {
this.data.monitorLastUpdate ??= {}
this.data.monitorLastUpdate[monitorId] = checkedAt
}
copyMonitorStateFrom(source: CompactedMonitorStateWrapper, monitorId: string): boolean {
let copied = false
const sourceUpdate = source.data.monitorLastUpdate?.[monitorId] ?? 0
const currentUpdate = this.data.monitorLastUpdate?.[monitorId] ?? 0
if (sourceUpdate > currentUpdate) {
if (source.data.incident[monitorId]) {
this.data.incident[monitorId] = source.data.incident[monitorId]
} else {
delete this.data.incident[monitorId]
}
if (source.data.latency[monitorId]) {
this.data.latency[monitorId] = source.data.latency[monitorId]
} else {
delete this.data.latency[monitorId]
}
this.data.monitorLastUpdate ??= {}
this.data.monitorLastUpdate[monitorId] = sourceUpdate
copied = true
}
// Notification delivery is an external side effect and therefore has its
// own version. Preserve it even when a newer concurrent health check wins.
const sourceNotificationUpdate = source.data.notificationLastUpdate?.[monitorId] ?? 0
const currentNotificationUpdate = this.data.notificationLastUpdate?.[monitorId] ?? 0
if (sourceNotificationUpdate > currentNotificationUpdate) {
this.data.notifiedIncidentStart ??= {}
if (source.data.notifiedIncidentStart?.[monitorId] !== undefined) {
this.data.notifiedIncidentStart[monitorId] =
source.data.notifiedIncidentStart[monitorId]
} else {
delete this.data.notifiedIncidentStart[monitorId]
}
this.data.pendingRecovery ??= {}
if (source.data.pendingRecovery?.[monitorId] !== undefined) {
this.data.pendingRecovery[monitorId] = source.data.pendingRecovery[monitorId]
} else {
delete this.data.pendingRecovery[monitorId]
}
this.data.pendingErrorChange ??= {}
if (source.data.pendingErrorChange?.[monitorId] !== undefined) {
this.data.pendingErrorChange[monitorId] = source.data.pendingErrorChange[monitorId]
} else {
delete this.data.pendingErrorChange[monitorId]
}
this.data.notificationLastUpdate ??= {}
this.data.notificationLastUpdate[monitorId] = sourceNotificationUpdate
// A concurrent newer check may already have closed the incident before
// it observed the successfully delivered DOWN. Queue the matching UP.
const notifiedStart = this.data.notifiedIncidentStart[monitorId]
if (notifiedStart !== undefined && !this.data.pendingRecovery[monitorId]) {
for (let index = this.incidentLen(monitorId) - 1; index >= 0; index--) {
const incident = this.getIncident(monitorId, index)
if (incident.start[0] === notifiedStart && incident.end !== null) {
this.data.pendingRecovery[monitorId] = {
incidentStart: notifiedStart,
recoveredAt: incident.end,
}
break
}
}
}
copied = true
}
return copied
}
appendLatency(monitorId: string, record: LatencyRecord) {
let latencies = this.data.latency[monitorId]
if (!latencies) {
@ -235,6 +412,28 @@ export class CompactedMonitorStateWrapper {
}
}
recalculateOverallStatus(monitorIds: string[]) {
this.data.overallUp = 0
this.data.overallDown = 0
for (const monitorId of monitorIds) {
if (!this.hasMonitorData(monitorId)) {
// Unknown or partially migrated monitors must not be presented as
// operational while their first complete check has not run yet.
this.data.overallDown++
continue
}
const incidentCount = this.incidentLen(monitorId)
const lastIncident = this.getIncident(monitorId, incidentCount - 1)
if (lastIncident.end === null) {
this.data.overallDown++
} else {
this.data.overallUp++
}
}
}
unshiftLatency(monitorId: string) {
let latencies = this.data.latency[monitorId]

View File

@ -1,5 +1,6 @@
import { MonitorTarget, WebhookConfig } from '../../types/config'
import { maintenances, workerConfig } from '../../uptime.config'
import { allWebhookDeliveriesSucceeded } from './notification'
async function getWorkerLocation() {
const res = await fetch('https://cloudflare.com/cdn-cgi/trace')
@ -79,12 +80,13 @@ function templateWebhookPlayload(payload: any, message: string) {
}
}
async function webhookNotify(webhook: WebhookConfig, message: string) {
async function webhookNotify(webhook: WebhookConfig, message: string): Promise<boolean> {
if (Array.isArray(webhook)) {
const results: boolean[] = []
for (const w of webhook) {
await webhookNotify(w, message)
results.push(await webhookNotify(w, message))
}
return
return allWebhookDeliveriesSucceeded(results)
}
console.log(
@ -138,11 +140,14 @@ async function webhookNotify(webhook: WebhookConfig, message: string) {
console.log(
'Error calling webhook server, code: ' + resp.status + ', response: ' + (await resp.text())
)
} else {
console.log('Webhook notification sent successfully, code: ' + resp.status)
return false
}
console.log('Webhook notification sent successfully, code: ' + resp.status)
return true
} catch (e) {
console.log('Error calling webhook server: ' + e)
return false
}
}
@ -153,27 +158,30 @@ const formatAndNotify = async (
timeIncidentStart: number,
timeNow: number,
reason: string
) => {
): Promise<boolean> => {
// Skip notification if monitor is in the skip list
const skipList = workerConfig.notification?.skipNotificationIds
if (skipList && skipList.includes(monitor.id)) {
console.log(`Skipping notification for ${monitor.name} (${monitor.id} in skipNotificationIds)`)
return
return false
}
// Skip notification if monitor is in maintenance
// Skip notification if monitor is currently in maintenance. Keep timeNow for
// the notification's event timestamp, but do not let a historical recovery
// timestamp make retries remain in an already-finished maintenance window.
const maintenanceNow = new Date()
const maintenanceList = maintenances
.filter(
(m) =>
new Date(timeNow * 1000) >= new Date(m.start) &&
(!m.end || new Date(timeNow * 1000) <= new Date(m.end))
maintenanceNow >= new Date(m.start) &&
(!m.end || maintenanceNow <= new Date(m.end))
)
.map((e) => e.monitors || [])
.flat()
if (maintenanceList.includes(monitor.id)) {
console.log(`Skipping notification for ${monitor.name} (in maintenance)`)
return
return false
}
if (workerConfig.notification?.webhook) {
@ -185,9 +193,10 @@ const formatAndNotify = async (
reason,
workerConfig.notification?.timeZone ?? 'Etc/GMT'
)
await webhookNotify(workerConfig.notification.webhook, notification)
return webhookNotify(workerConfig.notification.webhook, notification)
} else {
console.log(`Webhook not set, skipping notification for ${monitor.name}`)
return false
}
}