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 style={{ display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center' }}>
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
width: '100%',
|
||||||
|
alignItems: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
<div>{groupName}</div>
|
<div>{groupName}</div>
|
||||||
<Text fw={500} style={{ display: 'inline', paddingRight: '5px', color: getStatusTextColor(state, group[groupName])}}>
|
<Text
|
||||||
{group[groupName].length - countDownCount(state, group[groupName])}
|
fw={500}
|
||||||
/{group[groupName].length} Operational
|
style={{
|
||||||
|
display: 'inline',
|
||||||
|
paddingRight: '5px',
|
||||||
|
color: getStatusTextColor(state, group[groupName]),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{group[groupName].length - countDownCount(state, group[groupName])}/
|
||||||
|
{group[groupName].length} Operational
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
</Accordion.Control>
|
</Accordion.Control>
|
||||||
<Accordion.Panel>
|
<Accordion.Panel>
|
||||||
{
|
{monitors
|
||||||
monitors
|
.filter((monitor) => group[groupName].includes(monitor.id))
|
||||||
.filter(monitor => group[groupName].includes(monitor.id))
|
|
||||||
.sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id))
|
.sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id))
|
||||||
.map(monitor => (
|
.map((monitor) => (
|
||||||
<div key={monitor.id}>
|
<div key={monitor.id}>
|
||||||
<Card.Section ml="xs" mr="xs">
|
<Card.Section ml="xs" mr="xs">
|
||||||
<MonitorDetail monitor={monitor} state={state} />
|
<MonitorDetail monitor={monitor} state={state} />
|
||||||
</Card.Section>
|
</Card.Section>
|
||||||
</div>
|
</div>
|
||||||
))
|
))}
|
||||||
}
|
|
||||||
</Accordion.Panel>
|
</Accordion.Panel>
|
||||||
</Accordion.Item>
|
</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
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ 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
|
||||||
|
|
||||||
|
|
@ -62,8 +62,7 @@ async function getStatus(monitor) {
|
||||||
socket.destroy()
|
socket.destroy()
|
||||||
reject(err)
|
reject(err)
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
status.up = true
|
status.up = true
|
||||||
status.err = ''
|
status.err = ''
|
||||||
|
|
@ -90,7 +89,8 @@ 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
|
||||||
}
|
}
|
||||||
|
|
@ -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...
|
// grace period is set AND...
|
||||||
workerConfig.notification?.gracePeriod !== undefined &&
|
(workerConfig.notification?.gracePeriod !== undefined &&
|
||||||
(
|
|
||||||
// grace period is met
|
// grace period is met
|
||||||
currentTimeSecond - currentIncident.start[0] >= workerConfig.notification.gracePeriod * 60 - 30 &&
|
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,7 +60,8 @@ 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
|
||||||
}
|
}
|
||||||
|
|
@ -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,
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue