Skip to content

Instantly share code, notes, and snippets.

@max-lt
Last active December 22, 2021 21:05
Show Gist options
  • Save max-lt/60ad2fe8496399695c436eda21d8059a to your computer and use it in GitHub Desktop.
Save max-lt/60ad2fe8496399695c436eda21d8059a to your computer and use it in GitHub Desktop.
addEventListener('scheduled', event => {
event.waitUntil(
handleSchedule(event.scheduledTime)
)
})
function sendMessage(chat_id, text, options = { }) {
return fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign(options, { chat_id, text }))
});
}
function fetchWithTimeout(url, timeout = 3000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
return fetch(url, { signal: controller.signal })
.catch((err) => {
if (err instanceof DOMException) {
return ({ ok: false, status: 408, statusText: 'Request Timeout' });
}
else throw err;
})
.finally(() => clearTimeout(id));
}
// Send to Kiwidiag
function broadcast(text, options) {
return sendMessage(CHANNEL_ID, text, options);
}
function plural(n, word) {
return n + ' ' +(n > 1 ? word + 's' : word);
}
// https://stackoverflow.com/a/11486026/4111143
function fancyTimeFormat(duration) {
// Hours, minutes and seconds
const hrs = ~~(duration / 3600);
const mins = ~~((duration % 3600) / 60);
const secs = ~~duration % 60;
if (hrs > 0) {
return plural(hrs, 'hour') + ' and ' + plural(mins, 'minute');
}
if (mins > 0) {
return plural(mins, 'minute') + ' and ' + plural(secs, 'second')
}
return plural(secs, 'second');
}
async function getText(date, key, response) {
const prev = await kv.get(key);
if (response.ok) {
const downtime = fancyTimeFormat((date - prev) / 1000);
await kv.delete(key);
return prev ? `✅ ${key} is up. It was down for ${downtime}` : null;
}
else if (prev) {
return null;
}
await kv.put(key, String(date));
return `⚠️ ${key} is down: ${response.statusText} (${response.status})`;
}
async function handleSchedule(date) {
const [client, server] = await Promise.all([
fetchWithTimeout('https://kiwidiag.arq.pw/sitemap.xml'),
fetchWithTimeout('https://kiwidiag.arq.pw/api/status')
]);
const clientText = await getText(date, 'Angular', client);
const serverText = await getText(date, 'API', server);
const texts = [clientText, serverText].filter(e => !!e);
if (texts.length) {
await broadcast(texts.join('\n'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment