2020-11-08 13:56:02 +01:00
|
|
|
import config from '../../config.yaml'
|
|
|
|
|
2020-11-11 23:39:54 +01:00
|
|
|
import { setKV, getKVWithMetadata, gcMonitors, getKV } from './helpers'
|
|
|
|
|
|
|
|
function getDate() {
|
|
|
|
return new Date().toISOString().split('T')[0]
|
|
|
|
}
|
2020-11-08 13:56:02 +01:00
|
|
|
|
|
|
|
export async function processCronTrigger(event) {
|
|
|
|
for (const monitor of config.monitors) {
|
|
|
|
console.log(`Checking ${monitor.name} ...`)
|
|
|
|
|
|
|
|
const init = {
|
|
|
|
method: monitor.method || 'GET',
|
|
|
|
redirect: monitor.followRedirect ? 'follow' : 'manual',
|
|
|
|
headers: {
|
|
|
|
'User-Agent': 'cf-worker-status-page',
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2020-11-11 23:39:54 +01:00
|
|
|
const checkResponse = await fetch(monitor.url, init)
|
|
|
|
const kvState = await getKVWithMetadata('s_' + monitor.id)
|
2020-11-08 13:56:02 +01:00
|
|
|
|
|
|
|
// metadata from monitor settings
|
2020-11-11 23:39:54 +01:00
|
|
|
const newMetadata = {
|
|
|
|
operational: checkResponse.status === (monitor.expectStatus || 200),
|
2020-11-08 13:56:02 +01:00
|
|
|
id: monitor.id,
|
2020-11-11 23:39:54 +01:00
|
|
|
firstCheck: kvState.metadata ? kvState.metadata.firstCheck : getDate(),
|
2020-11-08 13:56:02 +01:00
|
|
|
}
|
|
|
|
|
2020-11-11 23:39:54 +01:00
|
|
|
// Write current status if status changed or for first time
|
2020-11-08 13:56:02 +01:00
|
|
|
if (
|
2020-11-11 23:39:54 +01:00
|
|
|
!kvState.metadata ||
|
|
|
|
kvState.metadata.operational !== newMetadata.operational
|
2020-11-08 13:56:02 +01:00
|
|
|
) {
|
2020-11-11 23:39:54 +01:00
|
|
|
console.log('Saving changed state..')
|
|
|
|
|
|
|
|
await setKV('s_' + monitor.id, null, newMetadata)
|
2020-11-08 13:56:02 +01:00
|
|
|
|
|
|
|
if (typeof SECRET_SLACK_WEBHOOK !== 'undefined') {
|
2020-11-11 23:39:54 +01:00
|
|
|
await notifySlack(monitor, newMetadata)
|
2020-11-08 13:56:02 +01:00
|
|
|
}
|
|
|
|
|
2020-11-11 23:39:54 +01:00
|
|
|
if (!newMetadata.operational) {
|
|
|
|
// try to get failed daily status first as KV read is cheaper than write
|
|
|
|
const kvFailedDayStatusKey = 'h_' + monitor.id + '_' + getDate()
|
|
|
|
const kvFailedDayStatus = await getKV(kvFailedDayStatusKey)
|
2020-11-08 13:56:02 +01:00
|
|
|
|
2020-11-11 23:39:54 +01:00
|
|
|
// write if not found
|
|
|
|
if (!kvFailedDayStatus) {
|
|
|
|
console.log('Saving new failed daily status..')
|
|
|
|
await setKV(kvFailedDayStatusKey, null)
|
|
|
|
}
|
|
|
|
}
|
2020-11-08 13:56:02 +01:00
|
|
|
}
|
|
|
|
|
2020-11-11 23:39:54 +01:00
|
|
|
// save last check timestamp
|
2020-11-08 13:56:02 +01:00
|
|
|
await setKV('lastUpdate', Date.now())
|
|
|
|
}
|
|
|
|
await gcMonitors(config)
|
|
|
|
|
|
|
|
return new Response('OK')
|
|
|
|
}
|