|
| 1 | +import { readFile } from "fs-extra"; |
| 2 | +import { safeLoad } from "js-yaml"; |
| 3 | +import { getOctokit } from "./github"; |
| 4 | +import { join } from "path"; |
| 5 | +import { SiteHistory } from "../interfaces"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Get the number of seconds a website has been down |
| 9 | + * @param slug - Slug of the site |
| 10 | + */ |
| 11 | +const getDowntimeSecondsForSite = async (slug: string): Promise<number> => { |
| 12 | + let [owner, repo] = (process.env.GITHUB_REPOSITORY || "").split("/"); |
| 13 | + const octokit = await getOctokit(); |
| 14 | + let msDown = 0; |
| 15 | + |
| 16 | + // Get all the issues for this website |
| 17 | + const { data } = await octokit.issues.listForRepo({ |
| 18 | + owner, |
| 19 | + repo, |
| 20 | + labels: `status,${slug}`, |
| 21 | + filter: "all", |
| 22 | + per_page: 100, |
| 23 | + }); |
| 24 | + |
| 25 | + // If this issue has been closed already, calculate the difference |
| 26 | + // between when it was closed and when it was opened |
| 27 | + // If this issue is still open, calculate the time since it was opened |
| 28 | + data.forEach( |
| 29 | + (issue) => |
| 30 | + (msDown += |
| 31 | + new Date(issue.closed_at || new Date()).getTime() - new Date(issue.created_at).getTime()) |
| 32 | + ); |
| 33 | + |
| 34 | + return Math.round(msDown / 1000); |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * Get the uptime percentage for a website |
| 39 | + * @returns Percent string, e.g., 94.43% |
| 40 | + * @param slug - Slug of the site |
| 41 | + */ |
| 42 | +export const getUptimePercentForSite = async (slug: string): Promise<string> => { |
| 43 | + const site = safeLoad(await readFile(join(".", "history", `${slug}.yml`), "utf8")) as SiteHistory; |
| 44 | + // Time when we started tracking this website's downtime |
| 45 | + const startDate = new Date(site.startTime ?? new Date()); |
| 46 | + |
| 47 | + // Number of seconds we have been tracking this site |
| 48 | + const totalSeconds = (new Date().getTime() - startDate.getTime()) / 1000; |
| 49 | + |
| 50 | + // Number of seconds the site has been down |
| 51 | + const downtimeSeconds = await getDowntimeSecondsForSite(slug); |
| 52 | + |
| 53 | + // Return a percentage string |
| 54 | + return `${((downtimeSeconds / totalSeconds) * 100).toFixed(2)}%`; |
| 55 | +}; |
0 commit comments