feat: move to config/base class to have fallback values on missing exports

pull/101/head
Bennet Gallein 2025-04-18 21:03:42 +02:00
parent be3aa8beda
commit 9932ea2590
No known key found for this signature in database
GPG Key ID: 54F2DF6954E8C635
9 changed files with 162 additions and 108 deletions

View File

@ -1,6 +1,6 @@
import { Container, Group, Text } from '@mantine/core' import { Container, Group, Text } from '@mantine/core'
import classes from '@/styles/Header.module.css' import classes from '@/styles/Header.module.css'
import { pageConfig } from '@/uptime.config' import { pageConfig } from '@/config'
import { PageConfigLink } from '@/types/config' import { PageConfigLink } from '@/types/config'
export default function Header() { export default function Header() {

View File

@ -1,7 +1,7 @@
import { MonitorState, MonitorTarget } from '@/uptime.types' import { MonitorState, MonitorTarget } from '@/types/uptime.types'
import { Accordion, Card, Center, Text } from '@mantine/core' import { Accordion, Card, Center, Text } from '@mantine/core'
import MonitorDetail from './MonitorDetail' import MonitorDetail from './MonitorDetail'
import { pageConfig } from '@/uptime.config'; import { pageConfig } from '@/config'
function countDownCount(state: MonitorState, ids: string[]) { function countDownCount(state: MonitorState, ids: string[]) {
let downCount = 0 let downCount = 0
@ -28,45 +28,61 @@ function getStatusTextColor(state: MonitorState, ids: string[]) {
} }
} }
export default function MonitorList({ monitors, state }: { monitors: MonitorTarget[]; state: MonitorState }) { export default function MonitorList({
monitors,
state,
}: {
monitors: MonitorTarget[]
state: MonitorState
}) {
// @ts-ignore // @ts-ignore
let group: any = pageConfig.group let group: any = pageConfig.group
let groupedMonitor = group && Object.keys(group).length > 0 let groupedMonitor = group && Object.keys(group).length > 0
let content let content
if (groupedMonitor) { if (groupedMonitor) {
// Grouped monitors // Grouped monitors
content = ( content = (
<Accordion multiple defaultValue={Object.keys(group)} variant='contained'> <Accordion multiple defaultValue={Object.keys(group)} variant="contained">
{ {Object.keys(group).map((groupName) => (
Object.keys(group).map(groupName => ( <Accordion.Item key={groupName} value={groupName}>
<Accordion.Item key={groupName} value={groupName}> <Accordion.Control>
<Accordion.Control> <div
<div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center' }}> style={{
<div>{groupName}</div> display: 'flex',
<Text fw={500} style={{ display: 'inline', paddingRight: '5px', color: getStatusTextColor(state, group[groupName])}}> justifyContent: 'space-between',
{group[groupName].length - countDownCount(state, group[groupName])} width: '100%',
/{group[groupName].length} Operational alignItems: 'center',
</Text> }}
</div> >
</Accordion.Control> <div>{groupName}</div>
<Accordion.Panel> <Text
{ fw={500}
monitors style={{
.filter(monitor => group[groupName].includes(monitor.id)) display: 'inline',
.sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id)) paddingRight: '5px',
.map(monitor => ( color: getStatusTextColor(state, group[groupName]),
<div key={monitor.id}> }}
<Card.Section ml="xs" mr="xs"> >
<MonitorDetail monitor={monitor} state={state} /> {group[groupName].length - countDownCount(state, group[groupName])}/
</Card.Section> {group[groupName].length} Operational
</div> </Text>
)) </div>
} </Accordion.Control>
</Accordion.Panel> <Accordion.Panel>
</Accordion.Item> {monitors
)) .filter((monitor) => group[groupName].includes(monitor.id))
} .sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id))
.map((monitor) => (
<div key={monitor.id}>
<Card.Section ml="xs" mr="xs">
<MonitorDetail monitor={monitor} state={state} />
</Card.Section>
</div>
))}
</Accordion.Panel>
</Accordion.Item>
))}
</Accordion> </Accordion>
) )
} else { } else {

13
config/index.ts Normal file
View File

@ -0,0 +1,13 @@
import { Maintenances, PageConfig, WorkerConfig } from '@/types/config'
import * as config from '@/uptime.config'
const pageConfig = config.pageConfig
const workerConfig = config.workerConfig
let maintenances = []
// need any because we cannot guarantee that maintenances exists
if ((config as any).maintenances) {
maintenances = (config as any).maintenances
}
export { pageConfig, workerConfig, maintenances }

View File

@ -1,7 +1,7 @@
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server' import type { NextRequest } from 'next/server'
import { workerConfig } from './uptime.config' import { workerConfig } from '@/config'
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
// @ts-ignore // @ts-ignore
const passwordProtection = workerConfig.passwordProtection const passwordProtection = workerConfig.passwordProtection
@ -12,15 +12,16 @@ export async function middleware(request: NextRequest) {
if (authHeader && authHeader.length === expected.length) { if (authHeader && authHeader.length === expected.length) {
// a simple timing-safe compare // a simple timing-safe compare
authenticated = true; authenticated = true
for (let i = 0; i < authHeader.length; i++) { for (let i = 0; i < authHeader.length; i++) {
if (authHeader[i] !== expected[i]) authenticated = false; if (authHeader[i] !== expected[i]) authenticated = false
} }
} }
if (!authenticated) { if (!authenticated) {
return NextResponse.json( return NextResponse.json(
{ code: 401, message: "Not authenticated" }, { status: 401, headers: { 'WWW-Authenticate': 'Basic' } } { code: 401, message: 'Not authenticated' },
{ status: 401, headers: { 'WWW-Authenticate': 'Basic' } }
) )
} }
} }

View File

@ -1,4 +1,4 @@
import { workerConfig } from '@/uptime.config' import { workerConfig } from '@/config'
import { MonitorState } from '@/types/uptime.types' import { MonitorState } from '@/types/uptime.types'
import { NextRequest } from 'next/server' import { NextRequest } from 'next/server'

View File

@ -1,9 +1,9 @@
import Head from 'next/head' import Head from 'next/head'
import { Inter } from 'next/font/google' import { Inter } from 'next/font/google'
import { MonitorState, MonitorTarget } from '@/uptime.types' import { MonitorState, MonitorTarget } from '@/types/uptime.types'
import { KVNamespace } from '@cloudflare/workers-types' import { KVNamespace } from '@cloudflare/workers-types'
import { pageConfig, workerConfig } from '@/uptime.config' import { pageConfig, workerConfig } from '@/config'
import OverallStatus from '@/components/OverallStatus' import OverallStatus from '@/components/OverallStatus'
import Header from '@/components/Header' import Header from '@/components/Header'
import MonitorList from '@/components/MonitorList' import MonitorList from '@/components/MonitorList'
@ -22,21 +22,17 @@ export default function Home({
tooltip?: string tooltip?: string
statusPageLink?: string statusPageLink?: string
}) { }) {
let state; let state
if (stateStr !== undefined) { if (stateStr !== undefined) {
state = JSON.parse(stateStr) as MonitorState state = JSON.parse(stateStr) as MonitorState
} }
// Specify monitorId in URL hash to view a specific monitor (can be used in iframe) // Specify monitorId in URL hash to view a specific monitor (can be used in iframe)
const monitorId = window.location.hash.substring(1); const monitorId = window.location.hash.substring(1)
if (monitorId) { if (monitorId) {
const monitor = monitors.find((monitor) => monitor.id === monitorId); const monitor = monitors.find((monitor) => monitor.id === monitorId)
if (!monitor || !state) { if (!monitor || !state) {
return ( return <Text fw={700}>Monitor with id {monitorId} not found!</Text>
<Text fw={700}>
Monitor with id {monitorId} not found!
</Text>
)
} }
return ( return (
<div style={{ maxWidth: '810px' }}> <div style={{ maxWidth: '810px' }}>
@ -70,9 +66,14 @@ export default function Home({
)} )}
<Divider mt="lg" /> <Divider mt="lg" />
<Text size="xs" mt="xs" mb="xs" style={{ <Text
textAlign: 'center' size="xs"
}}> mt="xs"
mb="xs"
style={{
textAlign: 'center',
}}
>
Open-source monitoring and status page powered by{' '} Open-source monitoring and status page powered by{' '}
<a href="https://github.com/lyc8503/UptimeFlare" target="_blank"> <a href="https://github.com/lyc8503/UptimeFlare" target="_blank">
Uptimeflare Uptimeflare

View File

@ -2,7 +2,6 @@ export type PageConfig = {
title?: string title?: string
links?: PageConfigLink[] links?: PageConfigLink[]
group?: PageConfigGroup group?: PageConfigGroup
maintenances?: Maintenances[]
} }
export type Maintenances = { export type Maintenances = {

View File

@ -1,4 +1,4 @@
import { PageConfig, WorkerConfig } from './types/config' import { Maintenances, PageConfig, WorkerConfig } from '@/types/config'
const pageConfig: PageConfig = { const pageConfig: PageConfig = {
// Title for your status page // Title for your status page
@ -119,5 +119,16 @@ const workerConfig: WorkerConfig = {
}, },
} }
const maintenances: Maintenances[] = [
// {
// title: 'Planned downtime',
// body: 'Please be patient',
// monitors: ['monitor-id-1', 'monitor-id-2'],
// start: new Date('2025-04-19 00:00:00Z'),
// end: new Date('2025-04-19 01:00:00Z'),
// color: 'red',
// },
]
// Don't forget this, otherwise compilation fails. // Don't forget this, otherwise compilation fails.
export { pageConfig, workerConfig } export { pageConfig, workerConfig, maintenances }

View File

@ -1,6 +1,6 @@
import { workerConfig } from '../../uptime.config' import { workerConfig } from '../../config'
import { formatStatusChangeNotification, getWorkerLocation, notifyWithApprise } from './util' import { formatStatusChangeNotification, getWorkerLocation, notifyWithApprise } from './util'
import { MonitorState, MonitorTarget } from '../../uptime.types' import { MonitorState, MonitorTarget } from '../../types/uptime.types'
import { getStatus } from './monitor' import { getStatus } from './monitor'
import { DurableObject } from 'cloudflare:workers' import { DurableObject } from 'cloudflare:workers'
@ -26,7 +26,9 @@ export default {
// @ts-ignore // @ts-ignore
const skipList: string[] = workerConfig.notification?.skipNotificationIds const skipList: string[] = workerConfig.notification?.skipNotificationIds
if (skipList && skipList.includes(monitor.id)) { if (skipList && skipList.includes(monitor.id)) {
console.log(`Skipping notification for ${monitor.name} (${monitor.id} in skipNotificationIds)`) console.log(
`Skipping notification for ${monitor.name} (${monitor.id} in skipNotificationIds)`
)
return return
} }
@ -46,7 +48,9 @@ export default {
notification.body notification.body
) )
} else { } else {
console.log(`Apprise API server or recipient URL not set, skipping apprise notification for ${monitor.name}`) console.log(
`Apprise API server or recipient URL not set, skipping apprise notification for ${monitor.name}`
)
} }
} }
@ -83,11 +87,11 @@ export default {
try { try {
console.log('Calling check proxy: ' + monitor.checkProxy) console.log('Calling check proxy: ' + monitor.checkProxy)
let resp let resp
if (monitor.checkProxy.startsWith("worker://")) { if (monitor.checkProxy.startsWith('worker://')) {
const doLoc = monitor.checkProxy.replace("worker://", "") const doLoc = monitor.checkProxy.replace('worker://', '')
const doId = env.REMOTE_CHECKER_DO.idFromName(doLoc) const doId = env.REMOTE_CHECKER_DO.idFromName(doLoc)
const doStub = env.REMOTE_CHECKER_DO.get(doId, { const doStub = env.REMOTE_CHECKER_DO.get(doId, {
locationHint: doLoc as DurableObjectLocationHint locationHint: doLoc as DurableObjectLocationHint,
}) })
resp = await doStub.getLocationAndStatus(monitor) resp = await doStub.getLocationAndStatus(monitor)
} else { } else {
@ -97,7 +101,7 @@ export default {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(monitor), body: JSON.stringify(monitor),
}) })
).json<{location: string; status: {ping: number; up: boolean; err: string}}>() ).json<{ location: string; status: { ping: number; up: boolean; err: string } }>()
} }
checkLocation = resp.location checkLocation = resp.location
status = resp.status status = resp.status
@ -144,17 +148,14 @@ export default {
// grace period not set OR ... // grace period not set OR ...
workerConfig.notification?.gracePeriod === undefined || 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) // 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 currentTimeSecond - lastIncident.start[0] >=
(workerConfig.notification.gracePeriod + 1) * 60 - 30
) { ) {
await formatAndNotify( await formatAndNotify(monitor, true, lastIncident.start[0], currentTimeSecond, 'OK')
monitor,
true,
lastIncident.start[0],
currentTimeSecond,
'OK'
)
} else { } else {
console.log(`grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping apprise UP notification for ${monitor.name}`) console.log(
`grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping apprise UP notification for ${monitor.name}`
)
} }
console.log('Calling config onStatusChange callback...') console.log('Calling config onStatusChange callback...')
@ -195,22 +196,20 @@ export default {
try { try {
if ( if (
// monitor status changed AND... // monitor status changed AND...
(monitorStatusChanged && ( (monitorStatusChanged &&
// grace period not set OR ... // grace period not set OR ...
workerConfig.notification?.gracePeriod === undefined || (workerConfig.notification?.gracePeriod === undefined ||
// have sent a notification for DOWN status // have sent a notification for DOWN status
currentTimeSecond - currentIncident.start[0] >= (workerConfig.notification.gracePeriod + 1) * 60 - 30 currentTimeSecond - currentIncident.start[0] >=
)) (workerConfig.notification.gracePeriod + 1) * 60 - 30)) ||
|| // grace period is set AND...
( (workerConfig.notification?.gracePeriod !== undefined &&
// grace period is set AND... // grace period is met
workerConfig.notification?.gracePeriod !== undefined && currentTimeSecond - currentIncident.start[0] >=
( workerConfig.notification.gracePeriod * 60 - 30 &&
// grace period is met currentTimeSecond - currentIncident.start[0] <
currentTimeSecond - currentIncident.start[0] >= workerConfig.notification.gracePeriod * 60 - 30 && workerConfig.notification.gracePeriod * 60 + 30)
currentTimeSecond - currentIncident.start[0] < workerConfig.notification.gracePeriod * 60 + 30 ) {
)
)) {
await formatAndNotify( await formatAndNotify(
monitor, monitor,
false, false,
@ -219,7 +218,14 @@ export default {
status.err status.err
) )
} else { } else {
console.log(`Grace period (${workerConfig.notification?.gracePeriod}m) not met (currently down for ${currentTimeSecond - currentIncident.start[0]}s, changed ${monitorStatusChanged}), skipping apprise DOWN notification for ${monitor.name}`) console.log(
`Grace period (${workerConfig.notification
?.gracePeriod}m) not met (currently down for ${
currentTimeSecond - currentIncident.start[0]
}s, changed ${monitorStatusChanged}), skipping apprise DOWN notification for ${
monitor.name
}`
)
} }
if (monitorStatusChanged) { if (monitorStatusChanged) {
@ -274,40 +280,45 @@ export default {
// discard old incidents // discard old incidents
let incidentList = state.incident[monitor.id] let incidentList = state.incident[monitor.id]
while (incidentList.length > 0 && incidentList[0].end && incidentList[0].end < currentTimeSecond - 90 * 24 * 60 * 60) { while (
incidentList.length > 0 &&
incidentList[0].end &&
incidentList[0].end < currentTimeSecond - 90 * 24 * 60 * 60
) {
incidentList.shift() incidentList.shift()
} }
if (incidentList.length == 0 || ( if (
incidentList[0].start[0] > currentTimeSecond - 90 * 24 * 60 * 60 && incidentList.length == 0 ||
incidentList[0].error[0] != 'dummy' (incidentList[0].start[0] > currentTimeSecond - 90 * 24 * 60 * 60 &&
)) { incidentList[0].error[0] != 'dummy')
) {
// put the dummy incident back // put the dummy incident back
incidentList.unshift( incidentList.unshift({
{ start: [currentTimeSecond - 90 * 24 * 60 * 60],
start: [currentTimeSecond - 90 * 24 * 60 * 60], end: currentTimeSecond - 90 * 24 * 60 * 60,
end: currentTimeSecond - 90 * 24 * 60 * 60, error: ['dummy'],
error: ['dummy'], })
}
)
} }
state.incident[monitor.id] = incidentList state.incident[monitor.id] = incidentList
statusChanged ||= monitorStatusChanged statusChanged ||= monitorStatusChanged
} }
console.log(`statusChanged: ${statusChanged}, lastUpdate: ${state.lastUpdate}, currentTime: ${currentTimeSecond}`) console.log(
`statusChanged: ${statusChanged}, lastUpdate: ${state.lastUpdate}, currentTime: ${currentTimeSecond}`
)
// Update state // Update state
// Allow for a cooldown period before writing to KV // Allow for a cooldown period before writing to KV
if ( if (
statusChanged || statusChanged ||
currentTimeSecond - state.lastUpdate >= workerConfig.kvWriteCooldownMinutes * 60 - 10 // Allow for 10 seconds of clock drift currentTimeSecond - state.lastUpdate >= workerConfig.kvWriteCooldownMinutes * 60 - 10 // Allow for 10 seconds of clock drift
) { ) {
console.log("Updating state...") console.log('Updating state...')
state.lastUpdate = currentTimeSecond state.lastUpdate = currentTimeSecond
await env.UPTIMEFLARE_STATE.put('state', JSON.stringify(state)) await env.UPTIMEFLARE_STATE.put('state', JSON.stringify(state))
} else { } else {
console.log("Skipping state update due to cooldown period.") console.log('Skipping state update due to cooldown period.')
} }
}, },
} }
@ -317,8 +328,10 @@ export class RemoteChecker extends DurableObject {
super(ctx, env) super(ctx, env)
} }
async getLocationAndStatus(monitor: MonitorTarget): Promise<{location: string; status: {ping: number; up: boolean; err: string}}> { async getLocationAndStatus(
const colo = await getWorkerLocation() as string 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}...`) console.log(`Running remote checker (DurableObject) at ${colo}...`)
const status = await getStatus(monitor) const status = await getStatus(monitor)
return { return {