Skip to content

Commit

Permalink
🐛 Fix upptime/upptime#838 login for time difference
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Aug 21, 2023
1 parent ab12345 commit 54100ae
Showing 1 changed file with 80 additions and 62 deletions.
142 changes: 80 additions & 62 deletions src/update.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,44 @@
import slugify from "@sindresorhus/slugify";
import dayjs from "dayjs";
import WebSocket from 'ws';
import { mkdirp, readFile, writeFile } from "fs-extra";
import { load } from "js-yaml";
import { join } from "path";
import WebSocket from "ws";
import { getConfig } from "./helpers/config";
import { getSecret } from "./helpers/secrets";
import { replaceEnvironmentVariables } from "./helpers/environment";
import { commit, lastCommit, push } from "./helpers/git";
import { getOctokit } from "./helpers/github";
import { shouldContinue } from "./helpers/init-check";
import { sendNotification } from "./helpers/notifme";
import { ping } from "./helpers/ping";
import { curl } from "./helpers/request";
import { getOwnerRepo } from "./helpers/secrets";
import { getOwnerRepo, getSecret } from "./helpers/secrets";
import { SiteHistory } from "./interfaces";
import { generateSummary } from "./summary";

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/**
* Get a human-readable time difference between from now
* @param startTime - Starting time
* @returns Human-readable time difference, e.g. "2 days, 3 hours, 5 minutes"
*/
function getHumanReadableTimeDifference(startTime: Date): string {
const now = new Date();
const deltaMilliseconds = now.getTime() - startTime.getTime();
const seconds = Math.floor(deltaMilliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);

if (days > 0) {
return `${days} days, ${hours % 24} hours, ${minutes % 60} minutes`;
} else if (hours > 0) {
return `${hours} hours, ${minutes % 60} minutes`;
} else if (minutes > 0) {
return `${minutes} minutes`;
} else {
return `${seconds} seconds`;
}
const diffDays = dayjs().diff(dayjs(startTime), "day");
const diffHours = dayjs().subtract(diffDays, "day").diff(dayjs(startTime), "hour");
const diffMinutes = dayjs()
.subtract(diffDays, "day")
.subtract(diffHours, "hour")
.diff(dayjs(startTime), "minute");
const result: string[] = [];
if (diffDays > 0) result.push(`${diffDays.toLocaleString()} ${diffDays > 1 ? "days" : "day"}`);
if (diffHours > 0)
result.push(`${diffHours.toLocaleString()} ${diffHours > 1 ? "hours" : "hour"}`);
if (diffMinutes > 0)
result.push(`${diffMinutes.toLocaleString()} ${diffMinutes > 1 ? "minutes" : "minute"}`);
return result.join(", ");
}


export const update = async (shouldCommit = false) => {
if (!(await shouldContinue())) return;
await mkdirp("history");
Expand Down Expand Up @@ -135,7 +135,7 @@ export const update = async (shouldCommit = false) => {
) as SiteHistory;
currentStatus = siteHistory.status || "unknown";
startTime = new Date(siteHistory.startTime || new Date());
} catch (error) { }
} catch (error) {}
console.log("Current status", site.slug || slugify(site.name), currentStatus, startTime);

/**
Expand All @@ -157,8 +157,12 @@ export const update = async (shouldCommit = false) => {
attempts: 5,
port: Number(replaceEnvironmentVariables(site.port ? String(site.port) : "")),
});
if (tcpResult.results.every(result => Object.prototype.toString.call((result as any).err) === "[object Error]"))
throw Error('all attempts failed');
if (
tcpResult.results.every(
(result) => Object.prototype.toString.call((result as any).err) === "[object Error]"
)
)
throw Error("all attempts failed");
console.log("Got result", tcpResult);
let responseTime = (tcpResult.avg || 0).toFixed(0);
if (parseInt(responseTime) > (site.maxResponseTime || 60000)) status = "degraded";
Expand All @@ -172,51 +176,50 @@ export const update = async (shouldCommit = false) => {
return { result: { httpCode: 0 }, responseTime: (0).toFixed(0), status: "down" };
}
} else if (site.check === "ws") {
console.log("Using websocket check instead of curl")
console.log("Using websocket check instead of curl");
let success = false;
let status: "up" | "down" | "degraded" = "up";
let responseTime = "0";
// promise to await:
const connect = () => {
return new Promise(function (resolve, reject) {
const ws = new WebSocket(replaceEnvironmentVariables(site.url));
ws.on('open', function open() {
ws.on("open", function open() {
if (site.body) {
ws.send(site.body);
} else {
ws.send("");
}
ws.on('message', function message(data) {
ws.on("message", function message(data) {
if (data) {
success = true
success = true;
}
})
});
ws.close();
ws.on('close', function close() {
console.log('Websocket disconnected');
ws.on("close", function close() {
console.log("Websocket disconnected");
});
resolve(ws)
resolve(ws);
});
ws.on('error', function error(error: any) {
reject(error)
ws.on("error", function error(error: any) {
reject(error);
});
})
}
});
};
try {
const connection = await connect()
if (connection) success = true
const connection = await connect();
if (connection) success = true;
if (success) {
status = "up";
} else {
status = "down";
};
}
return {
result: { httpCode: 200 },
responseTime,
status,
};
}
catch (error) {
} catch (error) {
console.log("ERROR Got pinging error from async call", error);
return { result: { httpCode: 0 }, responseTime: (0).toFixed(0), status: "down" };
}
Expand Down Expand Up @@ -323,8 +326,8 @@ generator: Upptime <https://github.com/upptime/upptime>
status === "up"
? config.commitPrefixStatusUp || "🟩"
: status === "degraded"
? config.commitPrefixStatusDegraded || "🟨"
: config.commitPrefixStatusDown || "🟥"
? config.commitPrefixStatusDegraded || "🟨"
: config.commitPrefixStatusDown || "🟥"
)
.replace("$SITE_NAME", site.name)
.replace("$SITE_URL", site.url)
Expand Down Expand Up @@ -376,12 +379,13 @@ generator: Upptime <https://github.com/upptime/upptime>
body: `In [\`${lastCommitSha.substr(
0,
7
)}\`](https://github.com/${owner}/${repo}/commit/${lastCommitSha}), ${site.name} (${site.url
}) ${status === "down" ? "was **down**" : "experienced **degraded performance**"}:
)}\`](https://github.com/${owner}/${repo}/commit/${lastCommitSha}), ${site.name} (${
site.url
}) ${status === "down" ? "was **down**" : "experienced **degraded performance**"}:
- HTTP code: ${result.httpCode}
- Response time: ${responseTime} ms
`,
labels: ["status", slug, ...site.tags || []],
labels: ["status", slug, ...(site.tags || [])],
});
const assignees = [...(config.assignees || []), ...(site.assignees || [])];
await octokit.issues.addAssignees({
Expand All @@ -397,17 +401,22 @@ generator: Upptime <https://github.com/upptime/upptime>
});
console.log("Opened and locked a new issue");
try {
const downmsg = await getSecret("NOTIFICATIONS_DOWN_MESSAGE") ? (getSecret("NOTIFICATIONS_DOWN_MESSAGE") || "")
.replace("$SITE_NAME", site.name)
.replace("$SITE_URL", `(${site.url})`)
.replace("$ISSUE_URL", `${newIssue.data.html_url}`)
.replace("$RESPONSE_CODE", result.httpCode.toString())
: `$EMOJI ${site.name} (${site.url}) is $STATUS : ${newIssue.data.html_url}`
const downmsg = (await getSecret("NOTIFICATIONS_DOWN_MESSAGE"))
? (getSecret("NOTIFICATIONS_DOWN_MESSAGE") || "")
.replace("$SITE_NAME", site.name)
.replace("$SITE_URL", `(${site.url})`)
.replace("$ISSUE_URL", `${newIssue.data.html_url}`)
.replace("$RESPONSE_CODE", result.httpCode.toString())
: `$EMOJI ${site.name} (${site.url}) is $STATUS : ${newIssue.data.html_url}`;

await sendNotification(
status === "down"
? `${downmsg.replace("$STATUS", "**down**").replace("$EMOJI", `${config.commitPrefixStatusDown || "🟥"}`)}`
: `${downmsg.replace("$STATUS", "experiencing **degraded performance**").replace("$EMOJI", `${config.commitPrefixStatusDegraded || "🟨"}`)}`
? `${downmsg
.replace("$STATUS", "**down**")
.replace("$EMOJI", `${config.commitPrefixStatusDown || "🟥"}`)}`
: `${downmsg
.replace("$STATUS", "experiencing **degraded performance**")
.replace("$EMOJI", `${config.commitPrefixStatusDegraded || "🟨"}`)}`
);
} catch (error) {
console.log(error);
Expand All @@ -422,7 +431,7 @@ generator: Upptime <https://github.com/upptime/upptime>
repo,
issue_number: issues.data[0].number,
});
await octokit.issues.createComment({
await octokit.issues.createComment({
owner,
repo,
issue_number: issues.data[0].number,
Expand Down Expand Up @@ -451,15 +460,24 @@ generator: Upptime <https://github.com/upptime/upptime>
});
console.log("Closed issue");
try {
const upmsg = await getSecret("NOTIFICATIONS_UP_MESSAGE") ? (getSecret("NOTIFICATIONS_UP_MESSAGE") || "")
.replace("$SITE_NAME", site.name)
.replace("$SITE_URL", `(${site.url})`)
: `$EMOJI ${site.name} (${site.url}) $STATUS`
const upmsg = (await getSecret("NOTIFICATIONS_UP_MESSAGE"))
? (getSecret("NOTIFICATIONS_UP_MESSAGE") || "")
.replace("$SITE_NAME", site.name)
.replace("$SITE_URL", `(${site.url})`)
: `$EMOJI ${site.name} (${site.url}) $STATUS`;

await sendNotification(upmsg.replace("$EMOJI", `${config.commitPrefixStatusUp || "🟩"}`).replace("$STATUS", `${issues.data[0].title.includes("degraded")
? "performance has improved"
: "is back up"
}`));
await sendNotification(
upmsg
.replace("$EMOJI", `${config.commitPrefixStatusUp || "🟩"}`)
.replace(
"$STATUS",
`${
issues.data[0].title.includes("degraded")
? "performance has improved"
: "is back up"
}`
)
);
} catch (error) {
console.log(error);
}
Expand Down

0 comments on commit 54100ae

Please sign in to comment.