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.
|
A more advanced, serverless, and free uptime monitoring & status page solution, powered by Cloudflare Workers, complete with a user-friendly interface.
|
||||||
|
|
||||||
## ⭐Features
|
## ⭐Features
|
||||||
|
|
||||||
- Open-source, easy to deploy (in under 10 minutes, no local tools required), and free
|
- Open-source, easy to deploy (in under 10 minutes, no local tools required), and free
|
||||||
- Monitoring capabilities
|
- Monitoring capabilities
|
||||||
- Up to 50 checks at 1-minute intervals
|
- Up to 50 checks at 1-minute intervals
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@
|
||||||
一个由 Cloudflare Workers 驱动的功能丰富、Serverless 且免费的 Uptime 监控及状态页面。
|
一个由 Cloudflare Workers 驱动的功能丰富、Serverless 且免费的 Uptime 监控及状态页面。
|
||||||
|
|
||||||
## ⭐功能
|
## ⭐功能
|
||||||
|
|
||||||
- 开源,易于部署(全程无需本地工具,耗时不到 10 分钟),且完全免费
|
- 开源,易于部署(全程无需本地工具,耗时不到 10 分钟),且完全免费
|
||||||
- 监控功能
|
- 监控功能
|
||||||
- 最多支持 50 个 1 分钟精度的检查
|
- 最多支持 50 个 1 分钟精度的检查
|
||||||
|
|
|
||||||
|
|
@ -50,13 +50,20 @@ export default function DetailBar({
|
||||||
if (overlap > 0) {
|
if (overlap > 0) {
|
||||||
for (let i = 0; i < incident.error.length; i++) {
|
for (let i = 0; i < incident.error.length; i++) {
|
||||||
let partStart = incident.start[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)
|
partStart = Math.max(partStart, dayStart)
|
||||||
partEnd = Math.min(partEnd, dayEnd)
|
partEnd = Math.min(partEnd, dayEnd)
|
||||||
|
|
||||||
if (overlapLen(dayStart, dayEnd, partStart, partEnd) > 0) {
|
if (overlapLen(dayStart, dayEnd, partStart, partEnd) > 0) {
|
||||||
const startStr = new Date(partStart * 1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
|
const startStr = new Date(partStart * 1000).toLocaleTimeString([], {
|
||||||
const endStr = new Date(partEnd * 1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
|
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]}`)
|
incidentReasons.push(`[${startStr}-${endStr}] ${incident.error[i]}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -77,7 +84,10 @@ export default function DetailBar({
|
||||||
<>
|
<>
|
||||||
<div>{dayPercent + '% at ' + new Date(dayStart * 1000).toLocaleDateString()}</div>
|
<div>{dayPercent + '% at ' + new Date(dayStart * 1000).toLocaleDateString()}</div>
|
||||||
{dayDownTime > 0 && (
|
{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={() => {
|
onClick={() => {
|
||||||
if (dayDownTime > 0) {
|
if (dayDownTime > 0) {
|
||||||
setModalTitle(`🚨 ${monitor.name} incidents at ${new Date(dayStart * 1000).toLocaleDateString()}`)
|
setModalTitle(
|
||||||
|
`🚨 ${monitor.name} incidents at ${new Date(dayStart * 1000).toLocaleDateString()}`
|
||||||
|
)
|
||||||
setModelContent(
|
setModelContent(
|
||||||
<>
|
<>
|
||||||
{incidentReasons.map((reason, index) => (<div key={index}>{reason}</div>))}
|
{incidentReasons.map((reason, index) => (
|
||||||
|
<div key={index}>{reason}</div>
|
||||||
|
))}
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
setModalOpened(true)
|
setModalOpened(true)
|
||||||
|
|
@ -110,7 +124,12 @@ export default function DetailBar({
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Modal opened={modalOpened} onClose={() => setModalOpened(false)} title={modalTitle} size={'40em'}>
|
<Modal
|
||||||
|
opened={modalOpened}
|
||||||
|
onClose={() => setModalOpened(false)}
|
||||||
|
title={modalTitle}
|
||||||
|
size={'40em'}
|
||||||
|
>
|
||||||
{modelContent}
|
{modelContent}
|
||||||
</Modal>
|
</Modal>
|
||||||
<Box
|
<Box
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,11 @@ export default function MonitorDetail({
|
||||||
const monitorNameElement = (
|
const monitorNameElement = (
|
||||||
<Text mt="sm" fw={700} style={{ display: 'inline-flex', alignItems: 'center' }}>
|
<Text mt="sm" fw={700} style={{ display: 'inline-flex', alignItems: 'center' }}>
|
||||||
{monitor.statusPageLink ? (
|
{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}
|
{statusIcon} {monitor.name}
|
||||||
</a>
|
</a>
|
||||||
) : (
|
) : (
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { MonitorState, MonitorTarget } from '@/uptime.types'
|
import { MonitorState, MonitorTarget } from '@/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 '@/uptime.config'
|
||||||
|
|
||||||
function countDownCount(state: MonitorState, ids: string[]) {
|
function countDownCount(state: MonitorState, ids: string[]) {
|
||||||
let downCount = 0
|
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
|
// @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
|
||||||
|
|
@ -37,36 +43,46 @@ export default function MonitorList({ monitors, state }: { monitors: MonitorTarg
|
||||||
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 {
|
||||||
|
|
|
||||||
|
|
@ -1,24 +1,24 @@
|
||||||
import { Center, Title } from '@mantine/core'
|
import { Center, Title } from '@mantine/core'
|
||||||
import { IconCircleCheck, IconAlertCircle } from '@tabler/icons-react'
|
import { IconCircleCheck, IconAlertCircle } from '@tabler/icons-react'
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
function useWindowVisibility() {
|
function useWindowVisibility() {
|
||||||
const [isVisible, setIsVisible] = useState(true);
|
const [isVisible, setIsVisible] = useState(true)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleVisibilityChange = () => {
|
const handleVisibilityChange = () => {
|
||||||
console.log('visibility change', document.visibilityState);
|
console.log('visibility change', document.visibilityState)
|
||||||
setIsVisible(document.visibilityState === 'visible');
|
setIsVisible(document.visibilityState === 'visible')
|
||||||
};
|
}
|
||||||
|
|
||||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
document.addEventListener('visibilitychange', handleVisibilityChange)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||||
};
|
}
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
return isVisible;
|
return isVisible
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function OverallStatus({
|
export default function OverallStatus({
|
||||||
|
|
@ -36,12 +36,14 @@ export default function OverallStatus({
|
||||||
statusString = 'All systems operational'
|
statusString = 'All systems operational'
|
||||||
icon = <IconCircleCheck style={{ width: 64, height: 64, color: '#059669' }} />
|
icon = <IconCircleCheck style={{ width: 64, height: 64, color: '#059669' }} />
|
||||||
} else {
|
} 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 [openTime] = useState(Math.round(Date.now() / 1000))
|
||||||
const [currentTime, setCurrentTime] = useState(Math.round(Date.now() / 1000))
|
const [currentTime, setCurrentTime] = useState(Math.round(Date.now() / 1000))
|
||||||
const isWindowVisible = useWindowVisibility();
|
const isWindowVisible = useWindowVisibility()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const interval = setInterval(() => {
|
const interval = setInterval(() => {
|
||||||
|
|
@ -66,7 +68,9 @@ export default function OverallStatus({
|
||||||
</Title>
|
</Title>
|
||||||
<Title mt="sm" style={{ textAlign: 'center', color: '#70778c' }} order={5}>
|
<Title mt="sm" style={{ textAlign: 'center', color: '#70778c' }} order={5}>
|
||||||
Last updated on:{' '}
|
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>
|
</Title>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
declare global {
|
declare global {
|
||||||
namespace NodeJS {
|
namespace NodeJS {
|
||||||
interface ProcessEnv {
|
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) {
|
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' } }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/** @type {import('next').NextConfig} */
|
/** @type {import('next').NextConfig} */
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
reactStrictMode: true
|
reactStrictMode: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = nextConfig
|
module.exports = nextConfig
|
||||||
|
|
@ -11,8 +11,8 @@ if (process.env.NODE_ENV === 'development') {
|
||||||
bindings: {
|
bindings: {
|
||||||
UPTIMEFLARE_STATE: {
|
UPTIMEFLARE_STATE: {
|
||||||
type: 'kv',
|
type: 'kv',
|
||||||
id: 'UPTIMEFLARE_STATE'
|
id: 'UPTIMEFLARE_STATE',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,10 @@
|
||||||
import { workerConfig } from "@/uptime.config"
|
import { workerConfig } from '@/uptime.config'
|
||||||
import { MonitorState } from "@/uptime.types"
|
import { MonitorState } from '@/uptime.types'
|
||||||
import { NextRequest } from "next/server"
|
import { NextRequest } from 'next/server'
|
||||||
|
|
||||||
export const runtime = 'edge'
|
export const runtime = 'edge'
|
||||||
|
|
||||||
export default async function handler(req: NextRequest): Promise<Response> {
|
export default async function handler(req: NextRequest): Promise<Response> {
|
||||||
|
|
||||||
const { UPTIMEFLARE_STATE } = process.env as unknown as {
|
const { UPTIMEFLARE_STATE } = process.env as unknown as {
|
||||||
UPTIMEFLARE_STATE: KVNamespace
|
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' }), {
|
return new Response(JSON.stringify({ error: 'No data available' }), {
|
||||||
status: 500,
|
status: 500,
|
||||||
headers: {
|
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 = {}
|
let monitors: any = {}
|
||||||
|
|
||||||
|
|
@ -29,7 +28,7 @@ export default async function handler(req: NextRequest): Promise<Response> {
|
||||||
up: isUp,
|
up: isUp,
|
||||||
latency: state.latency[monitor.id].recent.slice(-1)[0].ping,
|
latency: state.latency[monitor.id].recent.slice(-1)[0].ping,
|
||||||
location: state.latency[monitor.id].recent.slice(-1)[0].loc,
|
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,
|
up: state.overallUp,
|
||||||
down: state.overallDown,
|
down: state.overallDown,
|
||||||
updatedAt: state.lastUpdate,
|
updatedAt: state.lastUpdate,
|
||||||
monitors: monitors
|
monitors: monitors,
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Response(JSON.stringify(ret), {
|
return new Response(JSON.stringify(ret), {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json',
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -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
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// This is a Node.js implementation of status monitoring
|
// This is a Node.js implementation of status monitoring
|
||||||
|
|
||||||
const location = ''
|
const location = ''
|
||||||
const defaultTimeout = 5000 // 5 seconds, a lower default for deployments on platforms like Vercel
|
const defaultTimeout = 5000 // 5 seconds, a lower default for deployments on platforms like Vercel
|
||||||
|
|
||||||
const express = require('express')
|
const express = require('express')
|
||||||
const net = require('net')
|
const net = require('net')
|
||||||
|
|
@ -39,31 +39,30 @@ async function getStatus(monitor) {
|
||||||
try {
|
try {
|
||||||
// This is not a real https connection, but we need to add a dummy `https://` to parse the hostname & port
|
// This is not a real https connection, but we need to add a dummy `https://` to parse the hostname & port
|
||||||
// TODO: ipv6 buggy
|
// TODO: ipv6 buggy
|
||||||
const parsed = new URL("https://" + monitor.target)
|
const parsed = new URL('https://' + monitor.target)
|
||||||
host = parsed.hostname
|
host = parsed.hostname
|
||||||
port = parsed.port
|
port = parsed.port
|
||||||
|
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
const socket = net.createConnection({ host: host, port: Number(port) })
|
const socket = net.createConnection({ host: host, port: Number(port) })
|
||||||
|
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
socket.destroy()
|
socket.destroy()
|
||||||
reject(new Error(`Timeout after ${monitor.timeout || defaultTimeout}ms`))
|
reject(new Error(`Timeout after ${monitor.timeout || defaultTimeout}ms`))
|
||||||
}, monitor.timeout || defaultTimeout)
|
}, monitor.timeout || defaultTimeout)
|
||||||
|
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
clearTimeout(timer)
|
clearTimeout(timer)
|
||||||
socket.end()
|
socket.end()
|
||||||
resolve(null)
|
resolve(null)
|
||||||
})
|
})
|
||||||
|
|
||||||
socket.on('error', (err) => {
|
socket.on('error', (err) => {
|
||||||
clearTimeout(timer)
|
clearTimeout(timer)
|
||||||
socket.destroy()
|
socket.destroy()
|
||||||
reject(err)
|
reject(err)
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
status.up = true
|
status.up = true
|
||||||
status.err = ''
|
status.err = ''
|
||||||
|
|
@ -90,8 +89,9 @@ async function getStatus(monitor) {
|
||||||
if (!monitor.expectedCodes.includes(response.status)) {
|
if (!monitor.expectedCodes.includes(response.status)) {
|
||||||
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
||||||
status.up = false
|
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
|
return status
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -109,17 +109,28 @@ async function getStatus(monitor) {
|
||||||
|
|
||||||
// MUST contain responseKeyword
|
// MUST contain responseKeyword
|
||||||
if (monitor.responseKeyword && !responseBody.includes(monitor.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.up = false
|
||||||
status.err = "HTTP response doesn't contain the configured keyword"
|
status.err = "HTTP response doesn't contain the configured keyword"
|
||||||
return status
|
return status
|
||||||
}
|
}
|
||||||
|
|
||||||
// MUST NOT contain responseForbiddenKeyword
|
// MUST NOT contain responseForbiddenKeyword
|
||||||
if (monitor.responseForbiddenKeyword && responseBody.includes(monitor.responseForbiddenKeyword)) {
|
if (
|
||||||
console.log(`${monitor.name} forbidden keyword ${monitor.responseForbiddenKeyword}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
|
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.up = false
|
||||||
status.err = "HTTP response contains the configured forbidden keyword"
|
status.err = 'HTTP response contains the configured forbidden keyword'
|
||||||
return status
|
return status
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -142,19 +153,17 @@ async function getStatus(monitor) {
|
||||||
return status
|
return status
|
||||||
}
|
}
|
||||||
|
|
||||||
app.use(express.json());
|
app.use(express.json())
|
||||||
|
|
||||||
app.post('/', async (req, res) => {
|
app.post('/', async (req, res) => {
|
||||||
res.json(
|
res.json({
|
||||||
{
|
location: await getWorkerLocation(),
|
||||||
location: await getWorkerLocation(),
|
status: await getStatus(req.body),
|
||||||
status: await getStatus(req.body),
|
})
|
||||||
}
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
app.listen(port, () => {
|
app.listen(port, () => {
|
||||||
console.log(`App listening on port ${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 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)
|
// If specified, monitors will be grouped and ordered, not-listed monitors will be invisble (but still monitored)
|
||||||
group: {
|
group: {
|
||||||
"🌐 Public (example group name)": ['foo_monitor', 'bar_monitor', 'more monitor ids...'],
|
'🌐 Public (example group name)': ['foo_monitor', 'bar_monitor', 'more monitor ids...'],
|
||||||
"🔐 Private": ['test_tcp_monitor'],
|
'🔐 Private': ['test_tcp_monitor'],
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -77,12 +77,12 @@ const workerConfig = {
|
||||||
notification: {
|
notification: {
|
||||||
// [Optional] apprise API server URL
|
// [Optional] apprise API server URL
|
||||||
// if not specified, no notification will be sent
|
// 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
|
// [Optional] recipient URL for apprise, refer to https://github.com/caronc/apprise
|
||||||
// if not specified, no notification will be sent
|
// 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"
|
// [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
|
// [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
|
// 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
|
// 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
|
// This callback will be called when there's a status change for any monitor
|
||||||
// Write any Typescript code here
|
// Write any Typescript code here
|
||||||
|
|
||||||
// This will not follow the grace period settings and will be called immediately when the status changes
|
// 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
|
// You need to handle the grace period manually if you want to implement it
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { MonitorTarget } from "../../uptime.types";
|
import { MonitorTarget } from '../../uptime.types'
|
||||||
import { withTimeout, fetchTimeout } from "./util";
|
import { withTimeout, fetchTimeout } from './util'
|
||||||
|
|
||||||
export async function getStatus(
|
export async function getStatus(
|
||||||
monitor: MonitorTarget
|
monitor: MonitorTarget
|
||||||
|
|
@ -15,9 +15,11 @@ export async function getStatus(
|
||||||
if (monitor.method === 'TCP_PING') {
|
if (monitor.method === 'TCP_PING') {
|
||||||
// TCP port endpoint monitor
|
// TCP port endpoint monitor
|
||||||
try {
|
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
|
// 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) })
|
const socket = connect({ hostname: parsed.hostname, port: Number(parsed.port) })
|
||||||
|
|
||||||
// Now we have an `opened` promise!
|
// Now we have an `opened` promise!
|
||||||
|
|
@ -58,8 +60,9 @@ export async function getStatus(
|
||||||
if (!monitor.expectedCodes.includes(response.status)) {
|
if (!monitor.expectedCodes.includes(response.status)) {
|
||||||
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
||||||
status.up = false
|
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
|
return status
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -77,17 +80,28 @@ export async function getStatus(
|
||||||
|
|
||||||
// MUST contain responseKeyword
|
// MUST contain responseKeyword
|
||||||
if (monitor.responseKeyword && !responseBody.includes(monitor.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.up = false
|
||||||
status.err = "HTTP response doesn't contain the configured keyword"
|
status.err = "HTTP response doesn't contain the configured keyword"
|
||||||
return status
|
return status
|
||||||
}
|
}
|
||||||
|
|
||||||
// MUST NOT contain responseForbiddenKeyword
|
// MUST NOT contain responseForbiddenKeyword
|
||||||
if (monitor.responseForbiddenKeyword && responseBody.includes(monitor.responseForbiddenKeyword)) {
|
if (
|
||||||
console.log(`${monitor.name} forbidden keyword ${monitor.responseForbiddenKeyword}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
|
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.up = false
|
||||||
status.err = "HTTP response contains the configured forbidden keyword"
|
status.err = 'HTTP response contains the configured forbidden keyword'
|
||||||
return status
|
return status
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ function formatStatusChangeNotification(
|
||||||
timeZone: timeZone,
|
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 timeNowFormatted = dateFormatter.format(new Date(timeNow * 1000))
|
||||||
const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000))
|
const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000))
|
||||||
|
|
||||||
|
|
@ -60,7 +60,9 @@ function formatStatusChangeNotification(
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
title: `🔴 ${monitor.name} is still down.`,
|
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,
|
title: string,
|
||||||
body: 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 {
|
try {
|
||||||
const resp = await fetchTimeout(appriseApiServer, 5000, {
|
const resp = await fetchTimeout(appriseApiServer, 5000, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|
@ -83,12 +94,14 @@ async function notifyWithApprise(
|
||||||
title,
|
title,
|
||||||
body,
|
body,
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
format: 'text'
|
format: 'text',
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!resp.ok) {
|
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 {
|
} else {
|
||||||
console.log('Apprise notification sent successfully, code: ' + resp.status)
|
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,
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,105 +1,105 @@
|
||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||||
|
|
||||||
/* Projects */
|
/* Projects */
|
||||||
// "incremental": true, /* Enable incremental compilation */
|
// "incremental": true, /* Enable incremental compilation */
|
||||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
|
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
|
||||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
|
||||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
/* Language and Environment */
|
/* Language and Environment */
|
||||||
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
||||||
"lib": [
|
"lib": [
|
||||||
"es2021"
|
"es2021"
|
||||||
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
|
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
|
||||||
"jsx": "react" /* Specify what JSX code is generated. */,
|
"jsx": "react" /* Specify what JSX code is generated. */,
|
||||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
|
||||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
|
||||||
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
|
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
|
||||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
|
||||||
/* Modules */
|
/* Modules */
|
||||||
"module": "es2022" /* Specify what module code is generated. */,
|
"module": "es2022" /* Specify what module code is generated. */,
|
||||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
||||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
|
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
|
||||||
"types": [
|
"types": [
|
||||||
"@cloudflare/workers-types"
|
"@cloudflare/workers-types"
|
||||||
] /* Specify type package names to be included without being referenced in a source file. */,
|
] /* Specify type package names to be included without being referenced in a source file. */,
|
||||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
"resolveJsonModule": true /* Enable importing .json files */,
|
"resolveJsonModule": true /* Enable importing .json files */,
|
||||||
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
|
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
/* JavaScript Support */
|
/* JavaScript Support */
|
||||||
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
|
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
|
||||||
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
|
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
|
||||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
|
||||||
|
|
||||||
/* Emit */
|
/* Emit */
|
||||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
|
||||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||||
// "removeComments": true, /* Disable emitting comments. */
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
"noEmit": true /* Disable emitting files from a compilation. */,
|
"noEmit": true /* Disable emitting files from a compilation. */,
|
||||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
|
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
|
||||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
|
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
|
||||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
|
||||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
|
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
|
||||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||||
|
|
||||||
/* Interop Constraints */
|
/* Interop Constraints */
|
||||||
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
|
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
|
||||||
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
|
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
|
||||||
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
|
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
|
||||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
||||||
|
|
||||||
/* Type Checking */
|
/* Type Checking */
|
||||||
"strict": true /* Enable all strict type-checking options. */,
|
"strict": true /* Enable all strict type-checking options. */,
|
||||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
|
||||||
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
|
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
|
||||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
|
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
|
||||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
|
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
|
||||||
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
|
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
|
||||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
|
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
|
||||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
|
||||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
||||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
|
||||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
|
||||||
/* Completeness */
|
/* Completeness */
|
||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue