misc: run prettier

This commit is contained in:
lyc8503 committed 2025-04-19 21:50:43 +08:00
1 parent 751373d5dd
commit 4bcf4173ea
22 files changed
+402 -302

No files matched your search

+62 -49
View File
@@ -26,7 +26,9 @@ export default {
// @ts-ignore
const skipList: string[] = workerConfig.notification?.skipNotificationIds
if (skipList && skipList.includes(monitor.id)) {
console.log(`Skipping notification for ${monitor.name} (${monitor.id} in skipNotificationIds)`)
console.log(
`Skipping notification for ${monitor.name} (${monitor.id} in skipNotificationIds)`
)
return
}
@@ -46,7 +48,9 @@ export default {
notification.body
)
} else {
console.log(`Apprise API server or recipient URL not set, skipping apprise notification for ${monitor.name}`)
console.log(
`Apprise API server or recipient URL not set, skipping apprise notification for ${monitor.name}`
)
}
}
@@ -83,11 +87,11 @@ export default {
try {
console.log('Calling check proxy: ' + monitor.checkProxy)
let resp
if (monitor.checkProxy.startsWith("worker://")) {
const doLoc = monitor.checkProxy.replace("worker://", "")
if (monitor.checkProxy.startsWith('worker://')) {
const doLoc = monitor.checkProxy.replace('worker://', '')
const doId = env.REMOTE_CHECKER_DO.idFromName(doLoc)
const doStub = env.REMOTE_CHECKER_DO.get(doId, {
locationHint: doLoc as DurableObjectLocationHint
locationHint: doLoc as DurableObjectLocationHint,
})
resp = await doStub.getLocationAndStatus(monitor)
} else {
@@ -97,7 +101,7 @@ export default {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(monitor),
})
).json<{location: string; status: {ping: number; up: boolean; err: string}}>()
).json<{ location: string; status: { ping: number; up: boolean; err: string } }>()
}
checkLocation = resp.location
status = resp.status
@@ -144,17 +148,14 @@ export default {
// grace period not set OR ...
workerConfig.notification?.gracePeriod === undefined ||
// only when we have sent a notification for DOWN status, we will send a notification for UP status (within 30 seconds of possible drift)
currentTimeSecond - lastIncident.start[0] >= (workerConfig.notification.gracePeriod + 1) * 60 - 30
currentTimeSecond - lastIncident.start[0] >=
(workerConfig.notification.gracePeriod + 1) * 60 - 30
) {
await formatAndNotify(
monitor,
true,
lastIncident.start[0],
currentTimeSecond,
'OK'
)
await formatAndNotify(monitor, true, lastIncident.start[0], currentTimeSecond, 'OK')
} else {
console.log(`grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping apprise UP notification for ${monitor.name}`)
console.log(
`grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping apprise UP notification for ${monitor.name}`
)
}
console.log('Calling config onStatusChange callback...')
@@ -195,22 +196,20 @@ export default {
try {
if (
// monitor status changed AND...
(monitorStatusChanged && (
(monitorStatusChanged &&
// grace period not set OR ...
workerConfig.notification?.gracePeriod === undefined ||
// have sent a notification for DOWN status
currentTimeSecond - currentIncident.start[0] >= (workerConfig.notification.gracePeriod + 1) * 60 - 30
))
||
(
// grace period is set AND...
workerConfig.notification?.gracePeriod !== undefined &&
(
// grace period is met
currentTimeSecond - currentIncident.start[0] >= workerConfig.notification.gracePeriod * 60 - 30 &&
currentTimeSecond - currentIncident.start[0] < workerConfig.notification.gracePeriod * 60 + 30
)
)) {
(workerConfig.notification?.gracePeriod === undefined ||
// have sent a notification for DOWN status
currentTimeSecond - currentIncident.start[0] >=
(workerConfig.notification.gracePeriod + 1) * 60 - 30)) ||
// grace period is set AND...
(workerConfig.notification?.gracePeriod !== undefined &&
// grace period is met
currentTimeSecond - currentIncident.start[0] >=
workerConfig.notification.gracePeriod * 60 - 30 &&
currentTimeSecond - currentIncident.start[0] <
workerConfig.notification.gracePeriod * 60 + 30)
) {
await formatAndNotify(
monitor,
false,
@@ -219,7 +218,14 @@ export default {
status.err
)
} else {
console.log(`Grace period (${workerConfig.notification?.gracePeriod}m) not met (currently down for ${currentTimeSecond - currentIncident.start[0]}s, changed ${monitorStatusChanged}), skipping apprise DOWN notification for ${monitor.name}`)
console.log(
`Grace period (${workerConfig.notification
?.gracePeriod}m) not met (currently down for ${
currentTimeSecond - currentIncident.start[0]
}s, changed ${monitorStatusChanged}), skipping apprise DOWN notification for ${
monitor.name
}`
)
}
if (monitorStatusChanged) {
@@ -274,40 +280,45 @@ export default {
// discard old incidents
let incidentList = state.incident[monitor.id]
while (incidentList.length > 0 && incidentList[0].end && incidentList[0].end < currentTimeSecond - 90 * 24 * 60 * 60) {
while (
incidentList.length > 0 &&
incidentList[0].end &&
incidentList[0].end < currentTimeSecond - 90 * 24 * 60 * 60
) {
incidentList.shift()
}
if (incidentList.length == 0 || (
incidentList[0].start[0] > currentTimeSecond - 90 * 24 * 60 * 60 &&
incidentList[0].error[0] != 'dummy'
)) {
if (
incidentList.length == 0 ||
(incidentList[0].start[0] > currentTimeSecond - 90 * 24 * 60 * 60 &&
incidentList[0].error[0] != 'dummy')
) {
// put the dummy incident back
incidentList.unshift(
{
start: [currentTimeSecond - 90 * 24 * 60 * 60],
end: currentTimeSecond - 90 * 24 * 60 * 60,
error: ['dummy'],
}
)
incidentList.unshift({
start: [currentTimeSecond - 90 * 24 * 60 * 60],
end: currentTimeSecond - 90 * 24 * 60 * 60,
error: ['dummy'],
})
}
state.incident[monitor.id] = incidentList
statusChanged ||= monitorStatusChanged
}
console.log(`statusChanged: ${statusChanged}, lastUpdate: ${state.lastUpdate}, currentTime: ${currentTimeSecond}`)
console.log(
`statusChanged: ${statusChanged}, lastUpdate: ${state.lastUpdate}, currentTime: ${currentTimeSecond}`
)
// Update state
// Allow for a cooldown period before writing to KV
if (
statusChanged ||
currentTimeSecond - state.lastUpdate >= workerConfig.kvWriteCooldownMinutes * 60 - 10 // Allow for 10 seconds of clock drift
currentTimeSecond - state.lastUpdate >= workerConfig.kvWriteCooldownMinutes * 60 - 10 // Allow for 10 seconds of clock drift
) {
console.log("Updating state...")
console.log('Updating state...')
state.lastUpdate = currentTimeSecond
await env.UPTIMEFLARE_STATE.put('state', JSON.stringify(state))
} else {
console.log("Skipping state update due to cooldown period.")
console.log('Skipping state update due to cooldown period.')
}
},
}
@@ -317,8 +328,10 @@ export class RemoteChecker extends DurableObject {
super(ctx, env)
}
async getLocationAndStatus(monitor: MonitorTarget): Promise<{location: string; status: {ping: number; up: boolean; err: string}}> {
const colo = await getWorkerLocation() as string
async getLocationAndStatus(
monitor: MonitorTarget
): Promise<{ location: string; status: { ping: number; up: boolean; err: string } }> {
const colo = (await getWorkerLocation()) as string
console.log(`Running remote checker (DurableObject) at ${colo}...`)
const status = await getStatus(monitor)
return {
+24 -10
View File
@@ -1,5 +1,5 @@
import { MonitorTarget } from "../../uptime.types";
import { withTimeout, fetchTimeout } from "./util";
import { MonitorTarget } from '../../uptime.types'
import { withTimeout, fetchTimeout } from './util'
export async function getStatus(
monitor: MonitorTarget
@@ -15,9 +15,11 @@ export async function getStatus(
if (monitor.method === 'TCP_PING') {
// TCP port endpoint monitor
try {
const connect = await import(/* webpackIgnore: true */ "cloudflare:sockets").then((sockets) => sockets.connect)
const connect = await import(/* webpackIgnore: true */ 'cloudflare:sockets').then(
(sockets) => sockets.connect
)
// This is not a real https connection, but we need to add a dummy `https://` to parse the hostname & port
const parsed = new URL("https://" + monitor.target)
const parsed = new URL('https://' + monitor.target)
const socket = connect({ hostname: parsed.hostname, port: Number(parsed.port) })
// Now we have an `opened` promise!
@@ -58,8 +60,9 @@ export async function getStatus(
if (!monitor.expectedCodes.includes(response.status)) {
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
status.up = false
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${response.status
}`
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${
response.status
}`
return status
}
} else {
@@ -77,17 +80,28 @@ export async function getStatus(
// MUST contain responseKeyword
if (monitor.responseKeyword && !responseBody.includes(monitor.responseKeyword)) {
console.log(`${monitor.name} expected keyword ${monitor.responseKeyword}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
console.log(
`${monitor.name} expected keyword ${
monitor.responseKeyword
}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
)
status.up = false
status.err = "HTTP response doesn't contain the configured keyword"
return status
}
// MUST NOT contain responseForbiddenKeyword
if (monitor.responseForbiddenKeyword && responseBody.includes(monitor.responseForbiddenKeyword)) {
console.log(`${monitor.name} forbidden keyword ${monitor.responseForbiddenKeyword}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`)
if (
monitor.responseForbiddenKeyword &&
responseBody.includes(monitor.responseForbiddenKeyword)
) {
console.log(
`${monitor.name} forbidden keyword ${
monitor.responseForbiddenKeyword
}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
)
status.up = false
status.err = "HTTP response contains the configured forbidden keyword"
status.err = 'HTTP response contains the configured forbidden keyword'
return status
}
}
+25 -6
View File
@@ -43,7 +43,7 @@ function formatStatusChangeNotification(
timeZone: timeZone,
})
let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60);
let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60)
const timeNowFormatted = dateFormatter.format(new Date(timeNow * 1000))
const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000))
@@ -60,7 +60,9 @@ function formatStatusChangeNotification(
} else {
return {
title: `🔴 ${monitor.name} is still down.`,
body: `Service is unavailable since ${timeIncidentStartFormatted} (${downtimeDuration} minutes). Issue: ${reason || 'unspecified'}`,
body: `Service is unavailable since ${timeIncidentStartFormatted} (${downtimeDuration} minutes). Issue: ${
reason || 'unspecified'
}`,
}
}
}
@@ -71,7 +73,16 @@ async function notifyWithApprise(
title: string,
body: string
) {
console.log('Sending Apprise notification: ' + title + '-' + body + ' to ' + recipientUrl + ' via ' + appriseApiServer)
console.log(
'Sending Apprise notification: ' +
title +
'-' +
body +
' to ' +
recipientUrl +
' via ' +
appriseApiServer
)
try {
const resp = await fetchTimeout(appriseApiServer, 5000, {
method: 'POST',
@@ -83,12 +94,14 @@ async function notifyWithApprise(
title,
body,
type: 'warning',
format: 'text'
format: 'text',
}),
})
if (!resp.ok) {
console.log('Error calling apprise server, code: ' + resp.status + ', response: ' + await resp.text())
console.log(
'Error calling apprise server, code: ' + resp.status + ', response: ' + (await resp.text())
)
} else {
console.log('Apprise notification sent successfully, code: ' + resp.status)
}
@@ -97,4 +110,10 @@ async function notifyWithApprise(
}
}
export { getWorkerLocation, fetchTimeout, withTimeout, notifyWithApprise, formatStatusChangeNotification }
export {
getWorkerLocation,
fetchTimeout,
withTimeout,
notifyWithApprise,
formatStatusChangeNotification,
}