misc: run prettier
parent
751373d5dd
commit
4bcf4173ea
|
|
@ -8,6 +8,7 @@
|
|||
A more advanced, serverless, and free uptime monitoring & status page solution, powered by Cloudflare Workers, complete with a user-friendly interface.
|
||||
|
||||
## ⭐Features
|
||||
|
||||
- Open-source, easy to deploy (in under 10 minutes, no local tools required), and free
|
||||
- Monitoring capabilities
|
||||
- Up to 50 checks at 1-minute intervals
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
一个由 Cloudflare Workers 驱动的功能丰富、Serverless 且免费的 Uptime 监控及状态页面。
|
||||
|
||||
## ⭐功能
|
||||
|
||||
- 开源,易于部署(全程无需本地工具,耗时不到 10 分钟),且完全免费
|
||||
- 监控功能
|
||||
- 最多支持 50 个 1 分钟精度的检查
|
||||
|
|
|
|||
|
|
@ -50,13 +50,20 @@ export default function DetailBar({
|
|||
if (overlap > 0) {
|
||||
for (let i = 0; i < incident.error.length; i++) {
|
||||
let partStart = incident.start[i]
|
||||
let partEnd = i === incident.error.length - 1 ? (incident.end ?? currentTime) : incident.start[i + 1]
|
||||
let partEnd =
|
||||
i === incident.error.length - 1 ? incident.end ?? currentTime : incident.start[i + 1]
|
||||
partStart = Math.max(partStart, dayStart)
|
||||
partEnd = Math.min(partEnd, dayEnd)
|
||||
|
||||
if (overlapLen(dayStart, dayEnd, partStart, partEnd) > 0) {
|
||||
const startStr = new Date(partStart * 1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
|
||||
const endStr = new Date(partEnd * 1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
|
||||
const startStr = new Date(partStart * 1000).toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
const endStr = new Date(partEnd * 1000).toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
incidentReasons.push(`[${startStr}-${endStr}] ${incident.error[i]}`)
|
||||
}
|
||||
}
|
||||
|
|
@ -77,7 +84,10 @@ export default function DetailBar({
|
|||
<>
|
||||
<div>{dayPercent + '% at ' + new Date(dayStart * 1000).toLocaleDateString()}</div>
|
||||
{dayDownTime > 0 && (
|
||||
<div>{`Down for ${moment.preciseDiff(moment(0), moment(dayDownTime * 1000))} (click for detail)`}</div>
|
||||
<div>{`Down for ${moment.preciseDiff(
|
||||
moment(0),
|
||||
moment(dayDownTime * 1000)
|
||||
)} (click for detail)`}</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
|
@ -94,10 +104,14 @@ export default function DetailBar({
|
|||
}}
|
||||
onClick={() => {
|
||||
if (dayDownTime > 0) {
|
||||
setModalTitle(`🚨 ${monitor.name} incidents at ${new Date(dayStart * 1000).toLocaleDateString()}`)
|
||||
setModalTitle(
|
||||
`🚨 ${monitor.name} incidents at ${new Date(dayStart * 1000).toLocaleDateString()}`
|
||||
)
|
||||
setModelContent(
|
||||
<>
|
||||
{incidentReasons.map((reason, index) => (<div key={index}>{reason}</div>))}
|
||||
{incidentReasons.map((reason, index) => (
|
||||
<div key={index}>{reason}</div>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
setModalOpened(true)
|
||||
|
|
@ -110,7 +124,12 @@ export default function DetailBar({
|
|||
|
||||
return (
|
||||
<>
|
||||
<Modal opened={modalOpened} onClose={() => setModalOpened(false)} title={modalTitle} size={'40em'}>
|
||||
<Modal
|
||||
opened={modalOpened}
|
||||
onClose={() => setModalOpened(false)}
|
||||
title={modalTitle}
|
||||
size={'40em'}
|
||||
>
|
||||
{modelContent}
|
||||
</Modal>
|
||||
<Box
|
||||
|
|
|
|||
|
|
@ -44,7 +44,11 @@ export default function MonitorDetail({
|
|||
const monitorNameElement = (
|
||||
<Text mt="sm" fw={700} style={{ display: 'inline-flex', alignItems: 'center' }}>
|
||||
{monitor.statusPageLink ? (
|
||||
<a href={monitor.statusPageLink} target="_blank" style={{ display: 'inline-flex', alignItems: 'center', color: 'inherit' }}>
|
||||
<a
|
||||
href={monitor.statusPageLink}
|
||||
target="_blank"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', color: 'inherit' }}
|
||||
>
|
||||
{statusIcon} {monitor.name}
|
||||
</a>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { MonitorState, MonitorTarget } from '@/uptime.types'
|
||||
import { Accordion, Card, Center, Text } from '@mantine/core'
|
||||
import MonitorDetail from './MonitorDetail'
|
||||
import { pageConfig } from '@/uptime.config';
|
||||
import { pageConfig } from '@/uptime.config'
|
||||
|
||||
function countDownCount(state: MonitorState, ids: string[]) {
|
||||
let downCount = 0
|
||||
|
|
@ -28,7 +28,13 @@ 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
|
||||
let group: any = pageConfig.group
|
||||
let groupedMonitor = group && Object.keys(group).length > 0
|
||||
|
|
@ -37,36 +43,46 @@ export default function MonitorList({ monitors, state }: { monitors: MonitorTarg
|
|||
if (groupedMonitor) {
|
||||
// Grouped monitors
|
||||
content = (
|
||||
<Accordion multiple defaultValue={Object.keys(group)} variant='contained'>
|
||||
{
|
||||
Object.keys(group).map(groupName => (
|
||||
<Accordion multiple defaultValue={Object.keys(group)} variant="contained">
|
||||
{Object.keys(group).map((groupName) => (
|
||||
<Accordion.Item key={groupName} value={groupName}>
|
||||
<Accordion.Control>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
width: '100%',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div>{groupName}</div>
|
||||
<Text fw={500} style={{ display: 'inline', paddingRight: '5px', color: getStatusTextColor(state, group[groupName])}}>
|
||||
{group[groupName].length - countDownCount(state, group[groupName])}
|
||||
/{group[groupName].length} Operational
|
||||
<Text
|
||||
fw={500}
|
||||
style={{
|
||||
display: 'inline',
|
||||
paddingRight: '5px',
|
||||
color: getStatusTextColor(state, group[groupName]),
|
||||
}}
|
||||
>
|
||||
{group[groupName].length - countDownCount(state, group[groupName])}/
|
||||
{group[groupName].length} Operational
|
||||
</Text>
|
||||
</div>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
{
|
||||
monitors
|
||||
.filter(monitor => group[groupName].includes(monitor.id))
|
||||
{monitors
|
||||
.filter((monitor) => group[groupName].includes(monitor.id))
|
||||
.sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id))
|
||||
.map(monitor => (
|
||||
.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>
|
||||
)
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,24 +1,24 @@
|
|||
import { Center, Title } from '@mantine/core'
|
||||
import { IconCircleCheck, IconAlertCircle } from '@tabler/icons-react'
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
function useWindowVisibility() {
|
||||
const [isVisible, setIsVisible] = useState(true);
|
||||
const [isVisible, setIsVisible] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
console.log('visibility change', document.visibilityState);
|
||||
setIsVisible(document.visibilityState === 'visible');
|
||||
};
|
||||
console.log('visibility change', document.visibilityState)
|
||||
setIsVisible(document.visibilityState === 'visible')
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange)
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, []);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return isVisible;
|
||||
return isVisible
|
||||
}
|
||||
|
||||
export default function OverallStatus({
|
||||
|
|
@ -36,12 +36,14 @@ export default function OverallStatus({
|
|||
statusString = 'All systems operational'
|
||||
icon = <IconCircleCheck style={{ width: 64, height: 64, color: '#059669' }} />
|
||||
} else {
|
||||
statusString = `Some systems not operational (${state.overallDown} out of ${state.overallUp + state.overallDown})`
|
||||
statusString = `Some systems not operational (${state.overallDown} out of ${
|
||||
state.overallUp + state.overallDown
|
||||
})`
|
||||
}
|
||||
|
||||
const [openTime] = useState(Math.round(Date.now() / 1000))
|
||||
const [currentTime, setCurrentTime] = useState(Math.round(Date.now() / 1000))
|
||||
const isWindowVisible = useWindowVisibility();
|
||||
const isWindowVisible = useWindowVisibility()
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
|
|
@ -66,7 +68,9 @@ export default function OverallStatus({
|
|||
</Title>
|
||||
<Title mt="sm" style={{ textAlign: 'center', color: '#70778c' }} order={5}>
|
||||
Last updated on:{' '}
|
||||
{`${new Date(state.lastUpdate * 1000).toLocaleString()} (${currentTime - state.lastUpdate} sec ago)`}
|
||||
{`${new Date(state.lastUpdate * 1000).toLocaleString()} (${
|
||||
currentTime - state.lastUpdate
|
||||
} sec ago)`}
|
||||
</Title>
|
||||
</>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
declare global {
|
||||
namespace NodeJS {
|
||||
interface ProcessEnv {
|
||||
UPTIMEFLARE_STATE: KVNamespace;
|
||||
UPTIMEFLARE_STATE: KVNamespace
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
export {}
|
||||
|
|
|
|||
|
|
@ -12,15 +12,16 @@ export async function middleware(request: NextRequest) {
|
|||
|
||||
if (authHeader && authHeader.length === expected.length) {
|
||||
// a simple timing-safe compare
|
||||
authenticated = true;
|
||||
authenticated = true
|
||||
for (let i = 0; i < authHeader.length; i++) {
|
||||
if (authHeader[i] !== expected[i]) authenticated = false;
|
||||
if (authHeader[i] !== expected[i]) authenticated = false
|
||||
}
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
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' } }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true
|
||||
reactStrictMode: true,
|
||||
}
|
||||
|
||||
module.exports = nextConfig
|
||||
|
|
@ -11,8 +11,8 @@ if (process.env.NODE_ENV === 'development') {
|
|||
bindings: {
|
||||
UPTIMEFLARE_STATE: {
|
||||
type: 'kv',
|
||||
id: 'UPTIMEFLARE_STATE'
|
||||
}
|
||||
}
|
||||
id: 'UPTIMEFLARE_STATE',
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import { workerConfig } from "@/uptime.config"
|
||||
import { MonitorState } from "@/uptime.types"
|
||||
import { NextRequest } from "next/server"
|
||||
import { workerConfig } from '@/uptime.config'
|
||||
import { MonitorState } from '@/uptime.types'
|
||||
import { NextRequest } from 'next/server'
|
||||
|
||||
export const runtime = 'edge'
|
||||
|
||||
export default async function handler(req: NextRequest): Promise<Response> {
|
||||
|
||||
const { UPTIMEFLARE_STATE } = process.env as unknown as {
|
||||
UPTIMEFLARE_STATE: KVNamespace
|
||||
}
|
||||
|
|
@ -15,11 +14,11 @@ export default async function handler(req: NextRequest): Promise<Response> {
|
|||
return new Response(JSON.stringify({ error: 'No data available' }), {
|
||||
status: 500,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
}
|
||||
const state = (JSON.parse(stateStr)) as unknown as MonitorState
|
||||
const state = JSON.parse(stateStr) as unknown as MonitorState
|
||||
|
||||
let monitors: any = {}
|
||||
|
||||
|
|
@ -29,7 +28,7 @@ export default async function handler(req: NextRequest): Promise<Response> {
|
|||
up: isUp,
|
||||
latency: state.latency[monitor.id].recent.slice(-1)[0].ping,
|
||||
location: state.latency[monitor.id].recent.slice(-1)[0].loc,
|
||||
message: isUp ? "OK" : state.incident[monitor.id].slice(-1)[0].error.slice(-1)[0]
|
||||
message: isUp ? 'OK' : state.incident[monitor.id].slice(-1)[0].error.slice(-1)[0],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -37,12 +36,12 @@ export default async function handler(req: NextRequest): Promise<Response> {
|
|||
up: state.overallUp,
|
||||
down: state.overallDown,
|
||||
updatedAt: state.lastUpdate,
|
||||
monitors: monitors
|
||||
monitors: monitors,
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify(ret), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -22,21 +22,17 @@ export default function Home({
|
|||
tooltip?: string
|
||||
statusPageLink?: string
|
||||
}) {
|
||||
let state;
|
||||
let state
|
||||
if (stateStr !== undefined) {
|
||||
state = JSON.parse(stateStr) as MonitorState
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const monitor = monitors.find((monitor) => monitor.id === monitorId);
|
||||
const monitor = monitors.find((monitor) => monitor.id === monitorId)
|
||||
if (!monitor || !state) {
|
||||
return (
|
||||
<Text fw={700}>
|
||||
Monitor with id {monitorId} not found!
|
||||
</Text>
|
||||
)
|
||||
return <Text fw={700}>Monitor with id {monitorId} not found!</Text>
|
||||
}
|
||||
return (
|
||||
<div style={{ maxWidth: '810px' }}>
|
||||
|
|
@ -70,9 +66,14 @@ export default function Home({
|
|||
)}
|
||||
|
||||
<Divider mt="lg" />
|
||||
<Text size="xs" mt="xs" mb="xs" style={{
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
<Text
|
||||
size="xs"
|
||||
mt="xs"
|
||||
mb="xs"
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
Open-source monitoring and status page powered by{' '}
|
||||
<a href="https://github.com/lyc8503/UptimeFlare" target="_blank">
|
||||
Uptimeflare
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ async function getStatus(monitor) {
|
|||
try {
|
||||
// This is not a real https connection, but we need to add a dummy `https://` to parse the hostname & port
|
||||
// TODO: ipv6 buggy
|
||||
const parsed = new URL("https://" + monitor.target)
|
||||
const parsed = new URL('https://' + monitor.target)
|
||||
host = parsed.hostname
|
||||
port = parsed.port
|
||||
|
||||
|
|
@ -62,8 +62,7 @@ async function getStatus(monitor) {
|
|||
socket.destroy()
|
||||
reject(err)
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
status.up = true
|
||||
status.err = ''
|
||||
|
|
@ -90,7 +89,8 @@ async function getStatus(monitor) {
|
|||
if (!monitor.expectedCodes.includes(response.status)) {
|
||||
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
||||
status.up = false
|
||||
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${response.status
|
||||
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${
|
||||
response.status
|
||||
}`
|
||||
return status
|
||||
}
|
||||
|
|
@ -109,17 +109,28 @@ async function getStatus(monitor) {
|
|||
|
||||
// MUST contain responseKeyword
|
||||
if (monitor.responseKeyword && !responseBody.includes(monitor.responseKeyword)) {
|
||||
console.log(`${monitor.name} expected keyword ${monitor.responseKeyword}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
|
||||
console.log(
|
||||
`${monitor.name} expected keyword ${
|
||||
monitor.responseKeyword
|
||||
}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
status.up = false
|
||||
status.err = "HTTP response doesn't contain the configured keyword"
|
||||
return status
|
||||
}
|
||||
|
||||
// MUST NOT contain responseForbiddenKeyword
|
||||
if (monitor.responseForbiddenKeyword && responseBody.includes(monitor.responseForbiddenKeyword)) {
|
||||
console.log(`${monitor.name} forbidden keyword ${monitor.responseForbiddenKeyword}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
|
||||
if (
|
||||
monitor.responseForbiddenKeyword &&
|
||||
responseBody.includes(monitor.responseForbiddenKeyword)
|
||||
) {
|
||||
console.log(
|
||||
`${monitor.name} forbidden keyword ${
|
||||
monitor.responseForbiddenKeyword
|
||||
}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
status.up = false
|
||||
status.err = "HTTP response contains the configured forbidden keyword"
|
||||
status.err = 'HTTP response contains the configured forbidden keyword'
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
|
@ -142,19 +153,17 @@ async function getStatus(monitor) {
|
|||
return status
|
||||
}
|
||||
|
||||
app.use(express.json());
|
||||
app.use(express.json())
|
||||
|
||||
app.post('/', async (req, res) => {
|
||||
res.json(
|
||||
{
|
||||
res.json({
|
||||
location: await getWorkerLocation(),
|
||||
status: await getStatus(req.body),
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`App listening on port ${port}`)
|
||||
})
|
||||
|
||||
module.exports = app;
|
||||
module.exports = app
|
||||
|
|
|
|||
|
|
@ -11,8 +11,8 @@ const pageConfig = {
|
|||
// If not specified, all monitors will be shown in a single list
|
||||
// If specified, monitors will be grouped and ordered, not-listed monitors will be invisble (but still monitored)
|
||||
group: {
|
||||
"🌐 Public (example group name)": ['foo_monitor', 'bar_monitor', 'more monitor ids...'],
|
||||
"🔐 Private": ['test_tcp_monitor'],
|
||||
'🌐 Public (example group name)': ['foo_monitor', 'bar_monitor', 'more monitor ids...'],
|
||||
'🔐 Private': ['test_tcp_monitor'],
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -77,12 +77,12 @@ const workerConfig = {
|
|||
notification: {
|
||||
// [Optional] apprise API server URL
|
||||
// if not specified, no notification will be sent
|
||||
appriseApiServer: "https://apprise.example.com/notify",
|
||||
appriseApiServer: 'https://apprise.example.com/notify',
|
||||
// [Optional] recipient URL for apprise, refer to https://github.com/caronc/apprise
|
||||
// if not specified, no notification will be sent
|
||||
recipientUrl: "tgram://bottoken/ChatID",
|
||||
recipientUrl: 'tgram://bottoken/ChatID',
|
||||
// [Optional] timezone used in notification messages, default to "Etc/GMT"
|
||||
timeZone: "Asia/Shanghai",
|
||||
timeZone: 'Asia/Shanghai',
|
||||
// [Optional] grace period in minutes before sending a notification
|
||||
// notification will be sent only if the monitor is down for N continuous checks after the initial failure
|
||||
// if not specified, notification will be sent immediately
|
||||
|
|
@ -101,7 +101,6 @@ const workerConfig = {
|
|||
) => {
|
||||
// This callback will be called when there's a status change for any monitor
|
||||
// Write any Typescript code here
|
||||
|
||||
// This will not follow the grace period settings and will be called immediately when the status changes
|
||||
// You need to handle the grace period manually if you want to implement it
|
||||
},
|
||||
|
|
|
|||
|
|
@ -26,7 +26,9 @@ export default {
|
|||
// @ts-ignore
|
||||
const skipList: string[] = workerConfig.notification?.skipNotificationIds
|
||||
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
|
||||
}
|
||||
|
||||
|
|
@ -46,7 +48,9 @@ export default {
|
|||
notification.body
|
||||
)
|
||||
} 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 {
|
||||
console.log('Calling check proxy: ' + monitor.checkProxy)
|
||||
let resp
|
||||
if (monitor.checkProxy.startsWith("worker://")) {
|
||||
const doLoc = monitor.checkProxy.replace("worker://", "")
|
||||
if (monitor.checkProxy.startsWith('worker://')) {
|
||||
const doLoc = monitor.checkProxy.replace('worker://', '')
|
||||
const doId = env.REMOTE_CHECKER_DO.idFromName(doLoc)
|
||||
const doStub = env.REMOTE_CHECKER_DO.get(doId, {
|
||||
locationHint: doLoc as DurableObjectLocationHint
|
||||
locationHint: doLoc as DurableObjectLocationHint,
|
||||
})
|
||||
resp = await doStub.getLocationAndStatus(monitor)
|
||||
} else {
|
||||
|
|
@ -97,7 +101,7 @@ export default {
|
|||
headers: { 'Content-Type': 'application/json' },
|
||||
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
|
||||
status = resp.status
|
||||
|
|
@ -144,17 +148,14 @@ export default {
|
|||
// 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
|
||||
currentTimeSecond - lastIncident.start[0] >=
|
||||
(workerConfig.notification.gracePeriod + 1) * 60 - 30
|
||||
) {
|
||||
await formatAndNotify(
|
||||
monitor,
|
||||
true,
|
||||
lastIncident.start[0],
|
||||
currentTimeSecond,
|
||||
'OK'
|
||||
)
|
||||
await formatAndNotify(monitor, true, lastIncident.start[0], currentTimeSecond, 'OK')
|
||||
} 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...')
|
||||
|
|
@ -195,22 +196,20 @@ export default {
|
|||
try {
|
||||
if (
|
||||
// monitor status changed AND...
|
||||
(monitorStatusChanged && (
|
||||
(monitorStatusChanged &&
|
||||
// grace period not set OR ...
|
||||
workerConfig.notification?.gracePeriod === undefined ||
|
||||
(workerConfig.notification?.gracePeriod === undefined ||
|
||||
// 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 &&
|
||||
(
|
||||
(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
|
||||
)
|
||||
)) {
|
||||
currentTimeSecond - currentIncident.start[0] >=
|
||||
workerConfig.notification.gracePeriod * 60 - 30 &&
|
||||
currentTimeSecond - currentIncident.start[0] <
|
||||
workerConfig.notification.gracePeriod * 60 + 30)
|
||||
) {
|
||||
await formatAndNotify(
|
||||
monitor,
|
||||
false,
|
||||
|
|
@ -219,7 +218,14 @@ export default {
|
|||
status.err
|
||||
)
|
||||
} 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) {
|
||||
|
|
@ -274,40 +280,45 @@ export default {
|
|||
|
||||
// discard old incidents
|
||||
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()
|
||||
}
|
||||
|
||||
if (incidentList.length == 0 || (
|
||||
incidentList[0].start[0] > currentTimeSecond - 90 * 24 * 60 * 60 &&
|
||||
incidentList[0].error[0] != 'dummy'
|
||||
)) {
|
||||
if (
|
||||
incidentList.length == 0 ||
|
||||
(incidentList[0].start[0] > currentTimeSecond - 90 * 24 * 60 * 60 &&
|
||||
incidentList[0].error[0] != 'dummy')
|
||||
) {
|
||||
// put the dummy incident back
|
||||
incidentList.unshift(
|
||||
{
|
||||
incidentList.unshift({
|
||||
start: [currentTimeSecond - 90 * 24 * 60 * 60],
|
||||
end: currentTimeSecond - 90 * 24 * 60 * 60,
|
||||
error: ['dummy'],
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
state.incident[monitor.id] = incidentList
|
||||
|
||||
statusChanged ||= monitorStatusChanged
|
||||
}
|
||||
|
||||
console.log(`statusChanged: ${statusChanged}, lastUpdate: ${state.lastUpdate}, currentTime: ${currentTimeSecond}`)
|
||||
console.log(
|
||||
`statusChanged: ${statusChanged}, lastUpdate: ${state.lastUpdate}, currentTime: ${currentTimeSecond}`
|
||||
)
|
||||
// Update state
|
||||
// Allow for a cooldown period before writing to KV
|
||||
if (
|
||||
statusChanged ||
|
||||
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
|
||||
await env.UPTIMEFLARE_STATE.put('state', JSON.stringify(state))
|
||||
} 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)
|
||||
}
|
||||
|
||||
async getLocationAndStatus(monitor: MonitorTarget): Promise<{location: string; status: {ping: number; up: boolean; err: string}}> {
|
||||
const colo = await getWorkerLocation() as string
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { MonitorTarget } from "../../uptime.types";
|
||||
import { withTimeout, fetchTimeout } from "./util";
|
||||
import { MonitorTarget } from '../../uptime.types'
|
||||
import { withTimeout, fetchTimeout } from './util'
|
||||
|
||||
export async function getStatus(
|
||||
monitor: MonitorTarget
|
||||
|
|
@ -15,9 +15,11 @@ export async function getStatus(
|
|||
if (monitor.method === 'TCP_PING') {
|
||||
// TCP port endpoint monitor
|
||||
try {
|
||||
const connect = await import(/* webpackIgnore: true */ "cloudflare:sockets").then((sockets) => sockets.connect)
|
||||
const connect = await import(/* webpackIgnore: true */ 'cloudflare:sockets').then(
|
||||
(sockets) => sockets.connect
|
||||
)
|
||||
// This is not a real https connection, but we need to add a dummy `https://` to parse the hostname & port
|
||||
const parsed = new URL("https://" + monitor.target)
|
||||
const parsed = new URL('https://' + monitor.target)
|
||||
const socket = connect({ hostname: parsed.hostname, port: Number(parsed.port) })
|
||||
|
||||
// Now we have an `opened` promise!
|
||||
|
|
@ -58,7 +60,8 @@ export async function getStatus(
|
|||
if (!monitor.expectedCodes.includes(response.status)) {
|
||||
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
||||
status.up = false
|
||||
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${response.status
|
||||
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${
|
||||
response.status
|
||||
}`
|
||||
return status
|
||||
}
|
||||
|
|
@ -77,17 +80,28 @@ export async function getStatus(
|
|||
|
||||
// MUST contain responseKeyword
|
||||
if (monitor.responseKeyword && !responseBody.includes(monitor.responseKeyword)) {
|
||||
console.log(`${monitor.name} expected keyword ${monitor.responseKeyword}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
|
||||
console.log(
|
||||
`${monitor.name} expected keyword ${
|
||||
monitor.responseKeyword
|
||||
}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
status.up = false
|
||||
status.err = "HTTP response doesn't contain the configured keyword"
|
||||
return status
|
||||
}
|
||||
|
||||
// MUST NOT contain responseForbiddenKeyword
|
||||
if (monitor.responseForbiddenKeyword && responseBody.includes(monitor.responseForbiddenKeyword)) {
|
||||
console.log(`${monitor.name} forbidden keyword ${monitor.responseForbiddenKeyword}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
|
||||
if (
|
||||
monitor.responseForbiddenKeyword &&
|
||||
responseBody.includes(monitor.responseForbiddenKeyword)
|
||||
) {
|
||||
console.log(
|
||||
`${monitor.name} forbidden keyword ${
|
||||
monitor.responseForbiddenKeyword
|
||||
}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
status.up = false
|
||||
status.err = "HTTP response contains the configured forbidden keyword"
|
||||
status.err = 'HTTP response contains the configured forbidden keyword'
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ function formatStatusChangeNotification(
|
|||
timeZone: timeZone,
|
||||
})
|
||||
|
||||
let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60);
|
||||
let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60)
|
||||
const timeNowFormatted = dateFormatter.format(new Date(timeNow * 1000))
|
||||
const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000))
|
||||
|
||||
|
|
@ -60,7 +60,9 @@ function formatStatusChangeNotification(
|
|||
} else {
|
||||
return {
|
||||
title: `🔴 ${monitor.name} is still down.`,
|
||||
body: `Service is unavailable since ${timeIncidentStartFormatted} (${downtimeDuration} minutes). Issue: ${reason || 'unspecified'}`,
|
||||
body: `Service is unavailable since ${timeIncidentStartFormatted} (${downtimeDuration} minutes). Issue: ${
|
||||
reason || 'unspecified'
|
||||
}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -71,7 +73,16 @@ async function notifyWithApprise(
|
|||
title: string,
|
||||
body: string
|
||||
) {
|
||||
console.log('Sending Apprise notification: ' + title + '-' + body + ' to ' + recipientUrl + ' via ' + appriseApiServer)
|
||||
console.log(
|
||||
'Sending Apprise notification: ' +
|
||||
title +
|
||||
'-' +
|
||||
body +
|
||||
' to ' +
|
||||
recipientUrl +
|
||||
' via ' +
|
||||
appriseApiServer
|
||||
)
|
||||
try {
|
||||
const resp = await fetchTimeout(appriseApiServer, 5000, {
|
||||
method: 'POST',
|
||||
|
|
@ -83,12 +94,14 @@ async function notifyWithApprise(
|
|||
title,
|
||||
body,
|
||||
type: 'warning',
|
||||
format: 'text'
|
||||
format: 'text',
|
||||
}),
|
||||
})
|
||||
|
||||
if (!resp.ok) {
|
||||
console.log('Error calling apprise server, code: ' + resp.status + ', response: ' + await resp.text())
|
||||
console.log(
|
||||
'Error calling apprise server, code: ' + resp.status + ', response: ' + (await resp.text())
|
||||
)
|
||||
} else {
|
||||
console.log('Apprise notification sent successfully, code: ' + resp.status)
|
||||
}
|
||||
|
|
@ -97,4 +110,10 @@ async function notifyWithApprise(
|
|||
}
|
||||
}
|
||||
|
||||
export { getWorkerLocation, fetchTimeout, withTimeout, notifyWithApprise, formatStatusChangeNotification }
|
||||
export {
|
||||
getWorkerLocation,
|
||||
fetchTimeout,
|
||||
withTimeout,
|
||||
notifyWithApprise,
|
||||
formatStatusChangeNotification,
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue