pull/234/merge
Jake Vis 2026-11-19 10:32:31 -08:00 committed by GitHub
commit 1de2a6b5d9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 117 additions and 3 deletions

View File

@ -22,6 +22,7 @@
{
"files": [
"pages/api/data.ts",
"pages/api/push/**",
"middleware.ts"
],
"rules": {

View File

@ -4,7 +4,8 @@ import { workerConfig } from './uptime.config'
export async function middleware(request: NextRequest) {
const passwordProtection = workerConfig.passwordProtection
if (passwordProtection) {
// Heartbeats of PUSH monitors are authenticated by the token in the URL
if (passwordProtection && !request.nextUrl.pathname.startsWith('/api/push/')) {
const authHeader = request.headers.get('Authorization')
let authenticated = false
const expected = 'Basic ' + btoa(passwordProtection)

View File

@ -0,0 +1,54 @@
import { workerConfig } from '@/uptime.config'
import { NextRequest } from 'next/server'
import { getLastPush, setLastPush } from '@/worker/src/store'
export const runtime = 'edge'
// A heartbeat arriving within this many seconds of the recorded one is accepted without another D1 write
const WRITE_COOLDOWN_SECONDS = 30
const headers = {
'Content-Type': 'text/plain',
'Cache-Control': 'no-store, max-age=0, must-revalidate',
}
function timingSafeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false
let diff = 0
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
return diff === 0
}
// Heartbeat endpoint for `PUSH` monitors: /api/push/<monitor id>/<pushToken>
export default async function handler(req: NextRequest): Promise<Response> {
if (!['GET', 'POST', 'HEAD'].includes(req.method)) {
return new Response('Method not allowed\n', { status: 405, headers })
}
// An unknown monitor and a wrong token get the same answer
const notFound = () => new Response('Not found\n', { status: 404, headers })
const match = /\/api\/push\/([^/]+)\/([^/]+)$/.exec(new URL(req.url).pathname)
if (match === null) return notFound()
let id: string, token: string
try {
id = decodeURIComponent(match[1])
token = decodeURIComponent(match[2])
} catch (e) {
return notFound()
}
const monitor = workerConfig.monitors.find((m) => m.id === id && m.method === 'PUSH')
if (!monitor || !monitor.pushToken || !timingSafeEqual(monitor.pushToken, token)) {
return notFound()
}
const currentTimeSecond = Math.round(Date.now() / 1000)
const lastPush = await getLastPush(process.env as any, monitor.id)
if (lastPush === null || currentTimeSecond - lastPush >= WRITE_COOLDOWN_SECONDS) {
await setLastPush(process.env as any, monitor.id, currentTimeSecond)
}
return new Response('OK\n', { headers })
}

View File

@ -82,8 +82,9 @@ export async function getServerSideProps() {
tooltip: monitor?.tooltip,
// @ts-ignore
statusPageLink: monitor?.statusPageLink,
// PUSH monitors have no response time to show
// @ts-ignore
hideLatencyChart: monitor?.hideLatencyChart,
hideLatencyChart: monitor?.hideLatencyChart || monitor.method === 'PUSH',
}
})

View File

@ -34,6 +34,8 @@ export type MonitorTarget = {
name: string
method: string
target: string
pushToken?: string
pushGraceSeconds?: number
tooltip?: string
statusPageLink?: string
hideLatencyChart?: boolean

View File

@ -87,6 +87,22 @@ const workerConfig: WorkerConfig = {
statusPageLink: 'https://example.com',
timeout: 5000,
},
// Example PUSH (heartbeat) Monitor, for things that can't be reached from outside (cron jobs, backups, devices behind NAT...)
// The monitored service must request `https://<your status page>/api/push/<id>/<pushToken>` periodically (GET, POST or HEAD)
{
id: 'test_push_monitor',
name: 'Example PUSH Monitor',
// `method` should be `PUSH` for push monitors
method: 'PUSH',
// `target` is not used by push monitors
target: '',
// `pushToken` is the secret part of the heartbeat URL, use a long random string (letters, digits, `-` and `_`)
pushToken: 'REPLACE_WITH_A_RANDOM_STRING',
// [OPTIONAL] the monitor is down if no heartbeat is received for `pushGraceSeconds` seconds, default to 300
// heartbeats should be sent at least twice as often, the worker checks once per minute
pushGraceSeconds: 300,
tooltip: 'Nightly backup job',
},
],
// [Optional] Notification settings
notification: {

View File

@ -1,6 +1,7 @@
import { Env } from '.'
import { MonitorTarget } from '../../types/config'
import { withTimeout, fetchTimeout } from './util'
import { getLastPush } from './store'
function isIpAddress(hostname: string): boolean {
// `URL.hostname` strips brackets for IPv6, so a `:` reliably indicates an IPv6 literal here.
@ -354,11 +355,39 @@ export async function getStatus(
return status
}
export async function getPushStatus(
monitor: MonitorTarget,
env: Env
): Promise<{ ping: number; up: boolean; err: string }> {
const grace = monitor.pushGraceSeconds ?? 300
const lastPush = await getLastPush(env, monitor.id)
if (lastPush === null) {
return { ping: 0, up: false, err: 'No heartbeat received yet' }
}
if (Math.round(Date.now() / 1000) - lastPush > grace) {
// The message must stay the same during an incident, a changed message is treated as an error reason change
const lastSeen = new Date(lastPush * 1000).toISOString().slice(0, 16).replace('T', ' ')
return {
ping: 0,
up: false,
err: `No heartbeat received in ${grace} seconds (last one at ${lastSeen} UTC)`,
}
}
return { ping: 0, up: true, err: '' }
}
export async function doMonitor(monitor: MonitorTarget, defaultLocation: string, env: Env) {
let checkLocation = defaultLocation
let status
if (monitor.checkProxy) {
if (monitor.method === 'PUSH') {
// Nothing to check here, the monitored service sends heartbeats to /api/push
checkLocation = 'PUSH'
status = await getPushStatus(monitor, env)
} else if (monitor.checkProxy) {
// Initiate a check using proxy (Geo-specific monitoring)
try {
console.log(`[${monitor.id}] Calling check proxy: ${monitor.checkProxy}`)

View File

@ -19,6 +19,16 @@ export async function setToStore(env: Env, key: string, value: string): Promise<
await stmt.bind(key, value).run()
}
// Time (in seconds) of the last heartbeat received by a `PUSH` monitor, null if there is none yet
export async function getLastPush(env: Env, monitorId: string): Promise<number | null> {
const value = Number(await getFromStore(env, 'push:' + monitorId))
return value > 0 ? value : null
}
export async function setLastPush(env: Env, monitorId: string, timeSecond: number): Promise<void> {
await setToStore(env, 'push:' + monitorId, String(timeSecond))
}
export class CompactedMonitorStateWrapper {
data: MonitorStateCompacted