diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example new file mode 100644 index 0000000..482deaa --- /dev/null +++ b/apps/web/.dev.vars.example @@ -0,0 +1,4 @@ +# Copy to .dev.vars for `next dev` / `wrangler dev` (never committed). +# Optional: put the status page behind HTTP Basic auth, as `user:password`. +# Deployed, this is the Orun secret STATUS_PAGE_PASSWORD (README). +# STATUS_PAGE_PASSWORD=admin:change-me diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..96804f8 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,4 @@ +# Nothing to set for the data path: the monitor state lives in the D1 database +# bound as DB in wrangler.jsonc (the committed fixture render — wrangler keeps +# a local SQLite behind it; `pnpm db:init:local` creates the table there — and, +# on deploy, rendered from the cloudflare-d1 root's wiring document). diff --git a/apps/web/LICENSE b/apps/web/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/apps/web/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..c68049b --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,30 @@ +# apps/web — the status page and its checker, in one Worker + +[UptimeFlare](https://github.com/lyc8503/UptimeFlare) (lyc8503, Apache-2.0) +on Cloudflare Workers + Static Assets through `@opennextjs/cloudflare`. The +pages (`pages/`, `components/`, `locales/`) are upstream's, on the Next.js +pages router; `worker.ts` adds the `scheduled` handler that runs upstream's +checker (`monitor/`, upstream's `worker/src`) on the Worker's Cron Trigger. + +| What | Where | +|---|---| +| The monitors, the page's links, maintenances, notifications | `uptime.config.ts` (all options: `uptime.config.full.ts`) | +| The page's name and source link | `lib/site.ts` | +| The checker (HTTP/HTTPS/TCP checks, incidents, webhooks, the state) | `monitor/` | +| The Worker's entry: OpenNext's `fetch` + the checker's `scheduled` | `worker.ts` | +| The password gate (the optional `STATUS_PAGE_PASSWORD` secret) | `proxy.ts` | +| The JSON API and the badge | `pages/api/data.ts`, `pages/api/badge.ts` | +| Bindings, the Cron Trigger | `wrangler.template.jsonc` (+ `wiring.fixture.json` → the committed `wrangler.jsonc`) | + +```bash +pnpm run wire:fixture # render wrangler.jsonc from the fixture (committed) +pnpm db:init:local # create the monitor_state table in wrangler's local D1 +pnpm build # next build + opennextjs-cloudflare build +pnpm exec wrangler dev --test-scheduled +curl 'http://localhost:8787/__scheduled?cron=*+*+*+*+*' # run the checker once +curl http://localhost:8787/api/data # the state it wrote +``` + +`next dev` serves the pages against the same local D1 through wrangler's +platform proxy; the checker runs only under `wrangler dev`, which has a +`scheduled` event to give it. diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts new file mode 100644 index 0000000..564ad08 --- /dev/null +++ b/apps/web/cloudflare-env.d.ts @@ -0,0 +1,8 @@ +// The bindings wrangler.jsonc declares, as the Worker (and `next dev` through +// the platform proxy) sees them. Keep in step with wrangler.template.jsonc. +// The Workers runtime types (D1Database, ExportedHandler, …) come from +// @cloudflare/workers-types, as upstream's checker Worker had them. +interface CloudflareEnv { + DB: D1Database + ASSETS: Fetcher +} diff --git a/apps/web/component.yaml b/apps/web/component.yaml new file mode 100644 index 0000000..5006031 --- /dev/null +++ b/apps/web/component.yaml @@ -0,0 +1,119 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: web + description: UptimeFlare's status page and checker in one Worker (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, the checks on its Cron Trigger, per environment) +spec: + type: cloudflare-workers-assets-turbo + lifecycle: production + owner: platform + # `app`, not `web`: a domain and a component share one name space in the + # catalog, and a domain called `web` hid this component from it. + domain: app + path: apps/web + # Its own lane per environment: the Next.js build is the longest job in the + # plan, and a shared lane would wait on it. + lane: isolated + # INFRA BEFORE APP. The Worker binds the D1 database by id, and the id is + # rendered into its config during the build from the wiring document the + # cloudflare-d1 root lease-publishes after its apply. A job resolves its + # secrets when it STARTS, so on a merge to main this deploy waits for that + # environment's apply (enforced) and the document is there; a pull request + # deploys nothing, so nothing on one waits (advisory). + dependsOn: + - component: cloudflare-d1 + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + secretEnv: + WIRING_CLOUDFLARE_D1_STAGE: "secret://uptimeflare/uptimeflare/stage/WIRING_CLOUDFLARE_D1" + WIRING_CLOUDFLARE_D1_PROD: "secret://uptimeflare/uptimeflare/prod/WIRING_CLOUDFLARE_D1" + # The status page's password, `user:password`, stored per environment as the + # product's secret STATUS_PAGE_PASSWORD (README → A private status page). + # The Worker reads it at request time (proxy.ts), so the build hands it to + # the Worker as a Worker secret and no bundle contains it (buildCommand + # below). BEST-EFFORT, wire-now-seed-later: a key nobody has stored is + # skipped when the job resolves its secrets (no env var, no failure), and the + # page is public — which is how a fresh product deploys. + optionalSecretEnv: + STATUS_PAGE_PASSWORD: "secret://uptimeflare/uptimeflare/{{ .environment }}/STATUS_PAGE_PASSWORD" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/web" + wranglerConfig: wrangler.jsonc + + # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets + # directory bound via ASSETS — both deploy in one `wrangler deploy`. The + # entry here is the custom worker (fetch from the generated worker + the + # scheduled handler that runs the checks); wrangler bundles the generated + # one into it. + workerEntrypoint: worker.ts + assetsDir: .open-next/assets + + # Per-env worker name: uptimeflare-web-{dev,stage,prod}. The one Cron + # Trigger in wrangler.jsonc (every minute) is registered on each deployed + # Worker, so stage and prod each check every monitor into their own + # database. + workerName: uptimeflare-web + environmentAwareWorkerName: true + + # The account's workers.dev subdomain; exported to the smoke step as + # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # Render this environment's wrangler config, then build. stage and prod + # render from the wiring document their cloudflare-d1 apply published + # (secretEnv above, resolved before the job's first step); dev, which no + # root applies to and which only verifies, renders from the committed + # fixture. The committed wrangler.jsonc (the fixture render) is what the + # composition's verify-app-structure step finds before this runs; the + # render keeps its `main` (worker.ts) and its one `triggers.crons` entry. + # The password never reaches the build (`env -u`): the Worker reads it at + # request time. Then, when the environment has one, it goes to the Worker + # as a SECRET (tooling/wire/worker-secrets.mjs: `wrangler secret bulk`, + # the value over stdin) before the composition deploys it. Only the deploy + # lane holds a Cloudflare credential, so a verify lane builds the same and + # pushes nothing. + buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-d1 --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && env -u STATUS_PAGE_PASSWORD pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret STATUS_PAGE_PASSWORD --worker "uptimeflare-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc + + # Smoke: the CRON's effect is readable. Every minute the trigger checks + # every monitor through the scheduled handler, which writes the state — + # its `lastUpdate`, in seconds — to the D1 database; /api/data, answered + # only by the Worker reading that database, must carry an `updatedAt` no + # older than ten minutes (the state is written at least every three). A + # page that merely renders proves neither the trigger nor the binding, and + # the page's name is the owner's to change. When the environment has a + # STATUS_PAGE_PASSWORD the request carries it. The composition retries + # this with backoff (~4.5 min), usually long enough for a first deploy's + # new trigger to fire (a rerun of the failed lane covers the rest). Read + # only; the response is buffered before it is parsed. + smokeCommand: "body=$(curl -sf ${STATUS_PAGE_PASSWORD:+-u \"${STATUS_PAGE_PASSWORD}\"} \"${DEPLOYED_URL}/api/data\") && at=$(printf '%s' \"${body}\" | grep -Eo '\"updatedAt\":[0-9]+' | grep -Eo '[0-9]+$') && [ $(( $(date +%s) - at )) -lt 600 ]" + labels: + team: platform + layer: delivery + surface: web + runtime: cloudflare diff --git a/apps/web/components/DetailBar.tsx b/apps/web/components/DetailBar.tsx new file mode 100644 index 0000000..f8bb98c --- /dev/null +++ b/apps/web/components/DetailBar.tsx @@ -0,0 +1,160 @@ +import { MonitorState, MonitorTarget } from '@/types/config' +import { getColor } from '@/util/color' +import { Box, Tooltip, Modal } from '@mantine/core' +import { useResizeObserver } from '@mantine/hooks' +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +const moment = require('moment') +require('moment-precise-range-plugin') + +export default function DetailBar({ + monitor, + state, +}: { + monitor: MonitorTarget + state: MonitorState +}) { + const { t } = useTranslation('common') + const [barRef, barRect] = useResizeObserver() + const [modalOpened, setModalOpened] = useState(false) + const [modalTitle, setModalTitle] = useState('') + const [modelContent, setModelContent] = useState(
) + + const overlapLen = (x1: number, x2: number, y1: number, y2: number) => { + return Math.max(0, Math.min(x2, y2) - Math.max(x1, y1)) + } + + const uptimePercentBars = [] + + const currentTime = Math.round(Date.now() / 1000) + const montiorStartTime = state.incident[monitor.id][0].start[0] + + const todayStart = new Date() + todayStart.setHours(0, 0, 0, 0) + + for (let i = 89; i >= 0; i--) { + const dayStart = Math.round(todayStart.getTime() / 1000) - i * 86400 + const dayEnd = dayStart + 86400 + + const dayMonitorTime = overlapLen(dayStart, dayEnd, montiorStartTime, currentTime) + let dayDownTime = 0 + + let incidentReasons: string[] = [] + + for (let incident of state.incident[monitor.id]) { + const incidentStart = incident.start[0] + const incidentEnd = incident.end ?? currentTime + + const overlap = overlapLen(dayStart, dayEnd, incidentStart, incidentEnd) + dayDownTime += overlap + + // Incident history for the day + if (overlap > 0) { + for (let i = 0; i < incident.error.length; i++) { + let partStart = incident.start[i] + let partEnd = + i === incident.error.length - 1 ? incident.end ?? currentTime : incident.start[i + 1] + partStart = Math.max(partStart, dayStart) + partEnd = Math.min(partEnd, dayEnd) + + if (overlapLen(dayStart, dayEnd, partStart, partEnd) > 0) { + const startStr = new Date(partStart * 1000).toLocaleTimeString([], { + hour: '2-digit', + minute: '2-digit', + }) + const endStr = new Date(partEnd * 1000).toLocaleTimeString([], { + hour: '2-digit', + minute: '2-digit', + }) + incidentReasons.push(`[${startStr}-${endStr}] ${incident.error[i]}`) + } + } + } + } + + const dayPercent = (((dayMonitorTime - dayDownTime) / dayMonitorTime) * 100).toPrecision(4) + + uptimePercentBars.push( + +
+ {t('percent at date', { + percent: dayPercent, + date: new Date(dayStart * 1000).toLocaleDateString(), + })} +
+ {dayDownTime > 0 && ( +
+ {t('Down for', { + duration: moment.preciseDiff(moment(0), moment(dayDownTime * 1000)), + })} +
+ )} + + ) + } + > +
{ + if (dayDownTime > 0) { + setModalTitle( + t('incidents at', { + name: monitor.name, + date: new Date(dayStart * 1000).toLocaleDateString(), + }) + ) + setModelContent( + <> + {incidentReasons.map((reason, index) => ( +
{reason}
+ ))} + + ) + setModalOpened(true) + } + }} + /> + + ) + } + + return ( + <> + setModalOpened(false)} + title={modalTitle} + size={'40em'} + > + {modelContent} + + + {uptimePercentBars.slice(Math.floor(Math.max(9 * 90 - barRect.width, 0) / 9), 90)} + + + ) +} diff --git a/apps/web/components/DetailChart.tsx b/apps/web/components/DetailChart.tsx new file mode 100644 index 0000000..9d174a8 --- /dev/null +++ b/apps/web/components/DetailChart.tsx @@ -0,0 +1,102 @@ +import { Line } from 'react-chartjs-2' +import { + Chart as ChartJS, + CategoryScale, + LinearScale, + PointElement, + LineElement, + Title, + Tooltip as ChartTooltip, + Legend, + TimeScale, +} from 'chart.js' +import 'chartjs-adapter-moment' +import { MonitorState, MonitorTarget } from '@/types/config' +import { codeToCountry } from '@/util/iata' +import { useTranslation } from 'react-i18next' + +ChartJS.register( + CategoryScale, + LinearScale, + PointElement, + LineElement, + Title, + ChartTooltip, + Legend, + TimeScale +) + +export default function DetailChart({ + monitor, + state, +}: { + monitor: MonitorTarget + state: MonitorState +}) { + const { t } = useTranslation('common') + const latencyData = state.latency[monitor.id].map((point) => ({ + x: point.time * 1000, + y: point.ping, + loc: point.loc, + })) + + let data = { + datasets: [ + { + data: latencyData, + borderColor: 'rgb(112, 119, 140)', + borderWidth: 2, + radius: 0, + cubicInterpolationMode: 'monotone' as const, + tension: 0.4, + }, + ], + } + + let options = { + responsive: true, + maintainAspectRatio: false, + interaction: { + mode: 'index' as const, + intersect: false, + }, + animation: { + duration: 0, + }, + plugins: { + tooltip: { + callbacks: { + label: (item: any) => { + if (item.parsed.y) { + return `${item.parsed.y}ms (${codeToCountry(item.raw.loc)})` + } + }, + }, + }, + legend: { + display: false, + }, + title: { + display: true, + text: t('Response times'), + align: 'start' as const, + }, + }, + scales: { + x: { + type: 'time' as const, + ticks: { + source: 'auto' as const, + maxRotation: 0, + autoSkip: true, + }, + }, + }, + } + + return ( +
+ +
+ ) +} diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx new file mode 100644 index 0000000..657a260 --- /dev/null +++ b/apps/web/components/Footer.tsx @@ -0,0 +1,14 @@ +import { Divider } from '@mantine/core' +import { pageConfig } from '@/uptime.config' + +export default function Footer() { + const defaultFooter = + '

Open-source monitoring and status page powered by UptimeFlare, made with ❤ by lyc8503.

' + + return ( + <> + +
+ + ) +} diff --git a/apps/web/components/Header.tsx b/apps/web/components/Header.tsx new file mode 100644 index 0000000..bfccf32 --- /dev/null +++ b/apps/web/components/Header.tsx @@ -0,0 +1,53 @@ +import { Container, Group, Image } from '@mantine/core' +import classes from '@/styles/Header.module.css' +import { pageConfig } from '@/uptime.config' +import { PageConfigLink } from '@/types/config' +import { useTranslation } from 'react-i18next' + +export default function Header({ style }: { style?: React.CSSProperties }) { + const { t } = useTranslation('common') + const linkToElement = (link: PageConfigLink, i: number) => { + return ( + + {link.label} + + ) + } + + const links = [{ label: t('Incidents'), link: '/incidents' }, ...(pageConfig.links || [])] + + return ( +
+ +
+ + logo + +
+ + + {links?.map(linkToElement)} + + + + {links?.filter((link) => link.highlight || link.link.startsWith('/')).map(linkToElement)} + +
+
+ ) +} diff --git a/apps/web/components/MaintenanceAlert.tsx b/apps/web/components/MaintenanceAlert.tsx new file mode 100644 index 0000000..746d80e --- /dev/null +++ b/apps/web/components/MaintenanceAlert.tsx @@ -0,0 +1,95 @@ +import { Alert, List, Text, useMantineTheme } from '@mantine/core' +import { useMediaQuery } from '@mantine/hooks' +import { IconAlertTriangle } from '@tabler/icons-react' +import { MaintenanceConfig, MonitorTarget } from '@/types/config' +import { pageConfig } from '@/uptime.config' +import { useTranslation } from 'react-i18next' + +export default function MaintenanceAlert({ + maintenance, + style, + upcoming = false, +}: { + maintenance: Omit & { monitors?: (MonitorTarget | undefined)[] } + style?: React.CSSProperties + upcoming?: boolean +}) { + const { t } = useTranslation('common') + const theme = useMantineTheme() + const isDesktop = useMediaQuery(`(min-width: ${theme.breakpoints.sm})`) + + return ( + } + title={ + + {(upcoming ? t('Upcoming') : '') + (maintenance.title || t('Scheduled Maintenance'))} + + } + color={ + upcoming ? pageConfig.maintenances?.upcomingColor ?? 'gray' : maintenance.color || 'yellow' + } + withCloseButton={false} + style={{ margin: '16px auto 0 auto', ...style }} + > + {/* Date range in top right (desktop) or inline (mobile) */} +
+
+
+ {upcoming ? t('Scheduled for') : t('From')} +
+
{new Date(maintenance.start).toLocaleString()}
+
+ {upcoming ? t('Expected end') : t('To')} +
+
+ {maintenance.end + ? new Date(maintenance.end).toLocaleString() + : t('Until further notice')} +
+
+
+ + {maintenance.body} + {maintenance.monitors && maintenance.monitors.length > 0 && ( + <> + + {t('Affected components')} + + + {maintenance.monitors.map((comp, compIdx) => ( + {comp?.name ?? t('MONITOR ID NOT FOUND')} + ))} + + + )} +
+ ) +} diff --git a/apps/web/components/MonitorDetail.tsx b/apps/web/components/MonitorDetail.tsx new file mode 100644 index 0000000..0ff35bf --- /dev/null +++ b/apps/web/components/MonitorDetail.tsx @@ -0,0 +1,104 @@ +import { Text, Tooltip } from '@mantine/core' +import { MonitorState, MonitorTarget } from '@/types/config' +import { IconAlertCircle, IconAlertTriangle, IconCircleCheck } from '@tabler/icons-react' +import DetailChart from './DetailChart' +import DetailBar from './DetailBar' +import { getColor } from '@/util/color' +import { maintenances } from '@/uptime.config' +import { useTranslation } from 'react-i18next' + +export default function MonitorDetail({ + monitor, + state, +}: { + monitor: MonitorTarget + state: MonitorState +}) { + const { t } = useTranslation('common') + + if (!state.latency[monitor.id]) + return ( + <> + + {monitor.name} + + + {t('No data available')} + + + ) + + let statusIcon = + state.incident[monitor.id].slice(-1)[0].end === null ? ( + + ) : ( + + ) + + // Hide real status icon if monitor is in maintenance + const now = new Date() + const hasMaintenance = maintenances + .filter((m) => now >= new Date(m.start) && (!m.end || now <= new Date(m.end))) + .find((maintenance) => maintenance.monitors?.includes(monitor.id)) + if (hasMaintenance) + statusIcon = ( + + ) + + let totalTime = Date.now() / 1000 - state.incident[monitor.id][0].start[0] + let downTime = 0 + for (let incident of state.incident[monitor.id]) { + downTime += (incident.end ?? Date.now() / 1000) - incident.start[0] + } + + const uptimePercent = (((totalTime - downTime) / totalTime) * 100).toPrecision(4) + + // Conditionally render monitor name with or without hyperlink based on monitor.url presence + const monitorNameElement = ( + + {monitor.statusPageLink ? ( + + {statusIcon} {monitor.name} + + ) : ( + <> + {statusIcon} {monitor.name} + + )} + + ) + + return ( + <> +
+ {monitor.tooltip ? ( + {monitorNameElement} + ) : ( + monitorNameElement + )} + + + {t('Overall', { percent: uptimePercent })} + +
+ + + {!monitor.hideLatencyChart && } + + ) +} diff --git a/apps/web/components/MonitorList.tsx b/apps/web/components/MonitorList.tsx new file mode 100644 index 0000000..ab14eb2 --- /dev/null +++ b/apps/web/components/MonitorList.tsx @@ -0,0 +1,133 @@ +import { MonitorState, MonitorTarget } from '@/types/config' +import { Accordion, Card, Center, Text } from '@mantine/core' +import MonitorDetail from './MonitorDetail' +import { pageConfig } from '@/uptime.config' +import { useEffect, useState } from 'react' +import { useTranslation } from 'react-i18next' + +function countDownCount(state: MonitorState, ids: string[]) { + let downCount = 0 + for (let id of ids) { + if (state.incident[id] === undefined || state.incident[id].length === 0) { + continue + } + + if (state.incident[id].slice(-1)[0].end === null) { + downCount++ + } + } + return downCount +} + +function getStatusTextColor(state: MonitorState, ids: string[]) { + let downCount = countDownCount(state, ids) + if (downCount === 0) { + return '#059669' + } else if (downCount === ids.length) { + return '#df484a' + } else { + return '#f29030' + } +} + +export default function MonitorList({ + monitors, + state, +}: { + monitors: MonitorTarget[] + state: MonitorState +}) { + const { t } = useTranslation('common') + const group = pageConfig.group + const groupedMonitor = group && Object.keys(group).length > 0 + let content + + // Load expanded groups from localStorage + const savedExpandedGroups = localStorage.getItem('expandedGroups') + const expandedInitial = savedExpandedGroups + ? JSON.parse(savedExpandedGroups) + : Object.keys(group || {}) + const [expandedGroups, setExpandedGroups] = useState(expandedInitial) + useEffect(() => { + localStorage.setItem('expandedGroups', JSON.stringify(expandedGroups)) + }, [expandedGroups]) + + if (groupedMonitor) { + // Grouped monitors + content = ( + setExpandedGroups(values)} + > + {Object.keys(group).map((groupName) => ( + + +
+
{groupName}
+ + {group[groupName].length - countDownCount(state, group[groupName])}/ + {group[groupName].length} {t('Operational')} + +
+
+ + {monitors + .filter((monitor) => group[groupName].includes(monitor.id)) + .sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id)) + .map((monitor) => ( +
+ + + +
+ ))} +
+
+ ))} +
+ ) + } else { + // Ungrouped monitors + content = monitors.map((monitor) => ( +
+ + + +
+ )) + } + + return ( +
+ + {content} + +
+ ) +} diff --git a/apps/web/components/NoIncidents.tsx b/apps/web/components/NoIncidents.tsx new file mode 100644 index 0000000..865281b --- /dev/null +++ b/apps/web/components/NoIncidents.tsx @@ -0,0 +1,31 @@ +import { Alert, Text } from '@mantine/core' +import { IconInfoCircle } from '@tabler/icons-react' +import { useTranslation } from 'react-i18next' + +export default function NoIncidentsAlert({ style }: { style?: React.CSSProperties }) { + const { t } = useTranslation('common') + return ( + } + title={ + + {t('No incidents in this month')} + + } + color="gray" + withCloseButton={false} + style={{ + position: 'relative', + margin: '16px auto 0 auto', + ...style, + }} + > + {t('There are no incidents for this month')} + + ) +} diff --git a/apps/web/components/NoSsr.tsx b/apps/web/components/NoSsr.tsx new file mode 100644 index 0000000..d819d39 --- /dev/null +++ b/apps/web/components/NoSsr.tsx @@ -0,0 +1,12 @@ +import dynamic from 'next/dynamic' +import React from 'react' + +// React 19's types dropped PromiseLikeOfReactNode from the union upstream +// spelled out; ReactNode is that union. +const NoSsr = (props: { + children: React.ReactNode +}) => {props.children} + +export default dynamic(() => Promise.resolve(NoSsr), { + ssr: false, +}) diff --git a/apps/web/components/OverallStatus.tsx b/apps/web/components/OverallStatus.tsx new file mode 100644 index 0000000..40f57c7 --- /dev/null +++ b/apps/web/components/OverallStatus.tsx @@ -0,0 +1,137 @@ +import { MaintenanceConfig, MonitorTarget } from '@/types/config' +import { Center, Container, Title, Collapse, Button, Box } from '@mantine/core' +import { IconCircleCheck, IconAlertCircle, IconPlus, IconMinus } from '@tabler/icons-react' +import { useEffect, useState } from 'react' +import MaintenanceAlert from './MaintenanceAlert' +import { pageConfig } from '@/uptime.config' +import { useTranslation } from 'react-i18next' + +function useWindowVisibility() { + const [isVisible, setIsVisible] = useState(true) + useEffect(() => { + const handleVisibilityChange = () => setIsVisible(document.visibilityState === 'visible') + document.addEventListener('visibilitychange', handleVisibilityChange) + return () => document.removeEventListener('visibilitychange', handleVisibilityChange) + }, []) + return isVisible +} + +export default function OverallStatus({ + state, + maintenances, + monitors, +}: { + state: { overallUp: number; overallDown: number; lastUpdate: number } + maintenances: MaintenanceConfig[] + monitors: MonitorTarget[] +}) { + const { t } = useTranslation('common') + let group = pageConfig.group + let groupedMonitor = (group && Object.keys(group).length > 0) || false + + let statusString = '' + let icon = + if (state.overallUp === 0 && state.overallDown === 0) { + statusString = t('No data yet') + } else if (state.overallUp === 0) { + statusString = t('All systems not operational') + } else if (state.overallDown === 0) { + statusString = t('All systems operational') + icon = + } else { + statusString = t('Some systems not operational', { + down: state.overallDown, + total: state.overallUp + state.overallDown, + }) + } + + const [openTime] = useState(Math.round(Date.now() / 1000)) + const [currentTime, setCurrentTime] = useState(Math.round(Date.now() / 1000)) + const isWindowVisible = useWindowVisibility() + const [expandUpcoming, setExpandUpcoming] = useState(false) + + useEffect(() => { + const interval = setInterval(() => { + if (!isWindowVisible) return + if (currentTime - state.lastUpdate > 300 && currentTime - openTime > 30) { + window.location.reload() + } + setCurrentTime(Math.round(Date.now() / 1000)) + }, 1000) + return () => clearInterval(interval) + }) + + const now = new Date() + + const activeMaintenances: (Omit & { + monitors?: MonitorTarget[] + })[] = maintenances + .filter((m) => now >= new Date(m.start) && (!m.end || now <= new Date(m.end))) + .map((maintenance) => ({ + ...maintenance, + monitors: maintenance.monitors?.map( + (monitorId) => monitors.find((mon) => monitorId === mon.id)! + ), + })) + + const upcomingMaintenances: (Omit & { + monitors?: (MonitorTarget | undefined)[] + })[] = maintenances + .filter((m) => now < new Date(m.start)) + .map((maintenance) => ({ + ...maintenance, + monitors: maintenance.monitors?.map( + (monitorId) => monitors.find((mon) => monitorId === mon.id)! + ), + })) + + return ( + +
{icon}
+ + {statusString} + + + {t('Last updated on', { + date: new Date(state.lastUpdate * 1000).toLocaleString(), + seconds: currentTime - state.lastUpdate, + })} + + + {/* Upcoming Maintenance */} + {upcomingMaintenances.length > 0 && ( + <> + + {t('upcoming maintenance', { count: upcomingMaintenances.length })}{' '} + <span + style={{ textDecoration: 'underline', cursor: 'pointer' }} + onClick={() => setExpandUpcoming(!expandUpcoming)} + > + {expandUpcoming ? t('Hide') : t('Show')} + </span> + + + + {upcomingMaintenances.map((maintenance, idx) => ( + + ))} + + + )} + + {/* Active Maintenance */} + {activeMaintenances.map((maintenance, idx) => ( + + ))} +
+ ) +} diff --git a/apps/web/eslint.config.mjs b/apps/web/eslint.config.mjs new file mode 100644 index 0000000..f613ee6 --- /dev/null +++ b/apps/web/eslint.config.mjs @@ -0,0 +1,41 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +// UptimeFlare's code is kept as upstream wrote it; the rules eslint-config-next +// 16 brings that it was not written against are turned off by name, each with +// the reason, rather than rewriting the template. +export default defineConfig([ + ...nextVitals, + ...nextTs, + { + rules: { + // worker.ts imports the generated `.open-next/worker.js` the way the + // OpenNext custom-worker howto does: `@ts-ignore` with a reason, because + // the file does not exist before the build. Upstream's state code uses + // `@ts-expect-error` for Uint8Array.fromHex/toHex, which the DOM lib + // does not type yet. + "@typescript-eslint/ban-ts-comment": [ + "error", + { "ts-ignore": "allow-with-description", "ts-expect-error": false }, + ], + // Upstream types much of its state and API plumbing as `any`. + "@typescript-eslint/no-explicit-any": "off", + // …and declares with `let` what it never reassigns. + "prefer-const": "off", + // The status components read the clock while they render (the uptime + // bars and percentages are relative to now), as upstream's do; the + // whole page renders in the browser only (NoSsr), so no server and + // client render can disagree about it. + "react-hooks/purity": "off", + }, + }, + { + // DetailBar loads moment and its precise-range plugin with require(), as + // upstream does (the plugin patches moment in place). + files: ["components/DetailBar.tsx", "postcss.config.js"], + rules: { "@typescript-eslint/no-require-imports": "off" }, + }, + // .wrangler holds the bundles `wrangler dev` writes; never source. + globalIgnores([".next/**", ".open-next/**", ".wrangler/**", "next-env.d.ts", "cloudflare-env.d.ts"]), +]); diff --git a/apps/web/init.sql b/apps/web/init.sql new file mode 100644 index 0000000..90565b9 --- /dev/null +++ b/apps/web/init.sql @@ -0,0 +1,6 @@ +-- The monitor state's one table, for wrangler's LOCAL D1 (`pnpm db:init:local`): +-- upstream's init.sql under the table name monitor_state. +CREATE TABLE IF NOT EXISTS monitor_state ( + key VARCHAR(255) PRIMARY KEY, + value BLOB NOT NULL +); diff --git a/apps/web/lib/site.ts b/apps/web/lib/site.ts new file mode 100644 index 0000000..0e08526 --- /dev/null +++ b/apps/web/lib/site.ts @@ -0,0 +1,6 @@ +// The status page's own name and its source link — the two things that make a +// copy of it somebody else's. `SITE_NAME` is the page's title and heading +// (uptime.config.ts's `pageConfig.title`); `SOURCE_URL` is the GitHub link in +// its header. Change them here. +export const SITE_NAME = "My Status Page"; +export const SOURCE_URL = "https://github.com/sourceplane/uptimeflare"; diff --git a/apps/web/locales/de-DE/common.json b/apps/web/locales/de-DE/common.json new file mode 100644 index 0000000..9686989 --- /dev/null +++ b/apps/web/locales/de-DE/common.json @@ -0,0 +1,37 @@ +{ + "Incidents": "Vorfälle", + "No data yet": "Noch keine Daten", + "All systems not operational": "Nicht alle Systeme funktionsfähig", + "All systems operational": "Alle Systeme funktionsfähig", + "Some systems not operational": "Manche Systeme sind nicht funktionsfähig ({{down}} von {{total}})", + "Last updated on": "Letzte Aktualisierung: {{date}} (vor {{seconds}} Sekunden)", + "upcoming maintenance": "{{count}} anstehende Wartung", + "upcoming maintenance_plural": "{{count}} anstehende Wartungen", + "Hide": "[verstecken]", + "Show": "[zeigen]", + "Operational": "Funktionsfähig", + "No data available": "Keine Daten verfügbar, stelle sicher dass der Worker mit der letzten Config-Version deployed wurde und prüfe den Worker-Status!", + "Overall": "Gesamt: {{percent}}%", + "No Data": "Keine Daten", + "percent at date": "{{percent}}% am {{date}}", + "Down for": "Ausfall für {{duration}} (Klick für Details)", + "incidents at": "🚨 {{name}} Vorfall am {{date}}", + "Response times": "Antwortzeiten (ms)", + "Upcoming": "[Geplant] ", + "Scheduled Maintenance": "Geplante Wartung", + "Scheduled for": "Geplant für:", + "From": "Von:", + "Expected end": "Voraussichtliches Ende:", + "To": "Bis:", + "Until further notice": "Bis auf Weiteres", + "Affected components": "Betroffene Komponenten:", + "MONITOR ID NOT FOUND": "[ERR: MONITOR ID NICHT GEFUNDEN]", + "No incidents in this month": "Keine Vorfälle diesen Monat", + "There are no incidents for this month": "Es gibt keine Vorfälle diesen Monat.", + "Monitor not found": "Monitor mit ID {{id}} nicht gefunden!", + "Monitor State not defined": "Monitor-Status ist nicht definiert. Prüfe den Worker-Status und das Binding!", + "All": "Alle", + "Select monitor": "Auswählen", + "Backwards": "← Zurück", + "Forward": "Vorwärts →" +} diff --git a/apps/web/locales/en/common.json b/apps/web/locales/en/common.json new file mode 100644 index 0000000..6484ce0 --- /dev/null +++ b/apps/web/locales/en/common.json @@ -0,0 +1,37 @@ +{ + "Incidents": "Incidents", + "No data yet": "No data yet", + "All systems not operational": "All systems not operational", + "All systems operational": "All systems operational", + "Some systems not operational": "Some systems not operational ({{down}} out of {{total}})", + "Last updated on": "Last updated on: {{date}} ({{seconds}} sec ago)", + "upcoming maintenance": "{{count}} upcoming maintenance", + "upcoming maintenance_plural": "{{count}} upcoming maintenances", + "Hide": "[Hide]", + "Show": "[Show]", + "Operational": "Operational", + "No data available": "No data available, please make sure you have deployed your workers with latest config and check your worker status!", + "Overall": "Overall: {{percent}}%", + "No Data": "No Data", + "percent at date": "{{percent}}% at {{date}}", + "Down for": "Down for {{duration}} (click for detail)", + "incidents at": "🚨 {{name}} incidents at {{date}}", + "Response times": "Response times(ms)", + "Upcoming": "[Upcoming] ", + "Scheduled Maintenance": "Scheduled Maintenance", + "Scheduled for": "Scheduled for:", + "From": "From:", + "Expected end": "Expected end:", + "To": "To:", + "Until further notice": "Until further notice", + "Affected components": "Affected components:", + "MONITOR ID NOT FOUND": "[ERR: MONITOR ID NOT FOUND]", + "No incidents in this month": "No incidents in this month", + "There are no incidents for this month": "There are no incidents for this month.", + "Monitor not found": "Monitor with id {{id}} not found!", + "Monitor State not defined": "Monitor State is not defined now, please check your worker's status and binding!", + "All": "All", + "Select monitor": "Select monitor", + "Backwards": "← Backwards", + "Forward": "Forward →" +} diff --git a/apps/web/locales/fr-FR/common.json b/apps/web/locales/fr-FR/common.json new file mode 100644 index 0000000..e28074b --- /dev/null +++ b/apps/web/locales/fr-FR/common.json @@ -0,0 +1,37 @@ +{ + "Incidents": "Incidents", + "No data yet": "Aucune donnée pour le moment", + "All systems not operational": "Aucun système n'est opérationnel", + "All systems operational": "Tous les systèmes sont opérationnels", + "Some systems not operational": "Certains systèmes ne fonctionnent pas ({{down}} sur {{total}})", + "Last updated on": "Dernière actualisation : {{date}} (il y a {{seconds}} secondes)", + "upcoming maintenance": "{{count}} maintenance à venir", + "upcoming maintenance_plural": "{{count}} maintenances à venir", + "Hide": "[Masquer]", + "Show": "[Afficher]", + "Operational": "Opérationnel", + "No data available": "Aucune donnée disponible. Veuillez vous assurer d'avoir déployé vos workers avec la dernière configuration et vérifiez leur statut !", + "Overall": "Moyenne : {{percent}}%", + "No Data": "Aucune donnée", + "percent at date": "{{percent}}% le {{date}}", + "Down for": "Interruption de {{duration}} (cliquez pour plus de détails)", + "incidents at": "🚨 Incidents sur {{name}} le {{date}}", + "Response times": "Temps de réponse (ms)", + "Upcoming": "[À venir] ", + "Scheduled Maintenance": "Maintenance planifiée", + "Scheduled for": "Planifiée pour :", + "From": "De :", + "Expected end": "Fin prévue :", + "To": "À :", + "Until further notice": "Jusqu'à nouvel ordre", + "Affected components": "Composants affectés :", + "MONITOR ID NOT FOUND": "[ERR : ID DU MONITEUR INTROUVABLE]", + "No incidents in this month": "Aucun incident ce mois-ci", + "There are no incidents for this month": "Il n'y a aucun incident pour ce mois-ci.", + "Monitor not found": "Le moniteur avec l'ID {{id}} est introuvable !", + "Monitor State not defined": "L'état du moniteur n'est pas défini actuellement, veuillez vérifier le statut de votre worker et sa liaison !", + "All": "Tous", + "Select monitor": "Sélectionner un moniteur", + "Backwards": "← Précédent", + "Forward": "Suivant →" +} \ No newline at end of file diff --git a/apps/web/locales/zh-CN/common.json b/apps/web/locales/zh-CN/common.json new file mode 100644 index 0000000..52866f5 --- /dev/null +++ b/apps/web/locales/zh-CN/common.json @@ -0,0 +1,37 @@ +{ + "Incidents": "历史故障", + "No data yet": "暂无数据", + "All systems not operational": "系统均离线", + "All systems operational": "系统一切正常", + "Some systems not operational": "部分系统离线 ({{down}} / {{total}})", + "Last updated on": "最后更新于: {{date}} ({{seconds}} 秒前)", + "upcoming maintenance": "{{count}} 个即将进行的维护", + "upcoming maintenance_plural": "{{count}} 个即将进行的维护", + "Hide": "[隐藏]", + "Show": "[显示]", + "Operational": "在线", + "No data available": "暂无数据,请确保您已使用最新配置部署了 Worker 并检查 Worker 状态!", + "Overall": "总可用率: {{percent}}%", + "No Data": "暂无数据", + "percent at date": "{{percent}}% 于 {{date}}", + "Down for": "故障持续 {{duration}} (点击查看详情)", + "incidents at": "🚨 {{name}} 于 {{date}} 不可用", + "Response times": "响应时间(ms)", + "Upcoming": "[即将开始] ", + "Scheduled Maintenance": "计划维护", + "Scheduled for": "计划开始:", + "From": "开始:", + "Expected end": "预计结束:", + "To": "结束:", + "Until further notice": "直到另行通知", + "Affected components": "受影响组件:", + "MONITOR ID NOT FOUND": "[错误: 未找到监控 ID]", + "No incidents in this month": "本月无故障", + "There are no incidents for this month": "本月没有发生任何故障。", + "Monitor not found": "未找到 ID 为 {{id}} 的监控!", + "Monitor State not defined": "监控状态未定义,请检查您的 Worker 状态和绑定!", + "All": "全部", + "Select monitor": "选择监控", + "Backwards": "← 上一月", + "Forward": "下一月 →" +} diff --git a/apps/web/locales/zh-TW/common.json b/apps/web/locales/zh-TW/common.json new file mode 100644 index 0000000..e787bf4 --- /dev/null +++ b/apps/web/locales/zh-TW/common.json @@ -0,0 +1,37 @@ +{ + "Incidents": "歷來事件", + "No data yet": "沒有資料", + "All systems not operational": "所有服務都已停止運作", + "All systems operational": "所有服務皆正常運作", + "Some systems not operational": "部分服務停止運作 ({{down}} / {{total}})", + "Last updated on": "最後更新於:{{date}}({{seconds}} 秒前)", + "upcoming maintenance": "{{count}} 個即將要進行的維護", + "upcoming maintenance_plural": "{{count}} 個即將要進行的維護", + "Hide": "[隱藏]", + "Show": "[顯示]", + "Operational": "運行中", + "No data available": "沒有資料,請確保已部署最新設定的 Worker 並檢查 Worker 狀態!", + "Overall": "總運行率:{{percent}}%", + "No Data": "沒有資料", + "percent at date": "{{percent}}% 於 {{date}}", + "Down for": "事件持續 {{duration}}(點擊查看詳情)", + "incidents at": "🚨 {{name}} 於 {{date}} 停運", + "Response times": "回應時間(毫秒)", + "Upcoming": "[即將開始] ", + "Scheduled Maintenance": "預定維護", + "Scheduled for": "預定開始:", + "From": "開始:", + "Expected end": "預計結束:", + "To": "結束:", + "Until further notice": "即日起持續生效", + "Affected components": "受影響的部份:", + "MONITOR ID NOT FOUND": "[錯誤:找不到站點 ID]", + "No incidents in this month": "本月無事件", + "There are no incidents for this month": "本月沒有任何事件發生。", + "Monitor not found": "找不到 ID 為 {{id}} 的站點!", + "Monitor State not defined": "站點狀態未定義,請檢查您的 Worker 狀態與 KV 綁定!", + "All": "全部", + "Select monitor": "選取站點", + "Backwards": "← 上個月", + "Forward": "下個月 →" +} diff --git a/apps/web/monitor/index.ts b/apps/web/monitor/index.ts new file mode 100644 index 0000000..dc7b1bf --- /dev/null +++ b/apps/web/monitor/index.ts @@ -0,0 +1,256 @@ +// UptimeFlare's checker (upstream `worker/src/index.ts`), run by the Cron +// Trigger of the Worker that also serves the status page: worker.ts hands its +// `scheduled` events here. The loop is upstream's, unchanged; what differs is +// the Env (the D1 binding is DB) and the Durable Object remote checker, which +// this port leaves out (monitor.ts). +import { workerConfig } from '../uptime.config' +import { doMonitor } from './monitor' +import { formatAndNotify, getWorkerLocation } from './util' +import { CompactedMonitorStateWrapper, getFromStore, setToStore } from './store' +import pLimit from 'p-limit' + +export interface Env { + DB: D1Database +} + +const Worker = { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext): Promise { + const workerLocation = (await getWorkerLocation()) || 'ERROR' + console.log(`Running scheduled event on ${workerLocation}...`) + + // Create a wrapped MonitorState from stored compacted state + const state = new CompactedMonitorStateWrapper(await getFromStore(env, 'state')) + state.data.overallDown = 0 + state.data.overallUp = 0 + + let statusChanged = false + const currentTimeSecond = Math.round(Date.now() / 1000) + + // Parallel check multiple monitors + // Max concurrent connection is 6 limited by Cloudflare Workers, we use 5 here to be safe + type CheckResult = { id: string; location: string; status: { ping: number; up: boolean; err: string } } + let checkQueue: Promise[] = [] + let checkResult: Record = {}; + const limit = pLimit(5); + for (const monitor of workerConfig.monitors) { + checkQueue.push(limit(() => doMonitor(monitor, workerLocation, env))) + } + for (const result of await Promise.all(checkQueue)) { + checkResult[result.id] = result + } + + // Update each monitor's state based on check results + for (const monitor of workerConfig.monitors) { + console.log(`Processing monitor result: ${monitor.name} (${monitor.id})`) + + let monitorStatusChanged = false + const { location: checkLocation, status } = checkResult[monitor.id] + + // Update counters + status.up ? state.data.overallUp++ : state.data.overallDown++ + + // Update incidents + // Create a dummy incident to store the start time of the monitoring and simplify logic + if (state.incidentLen(monitor.id) === 0) { + state.appendIncident(monitor.id, { + start: [currentTimeSecond], + end: currentTimeSecond, + error: ['dummy'], + }) + } + + // Then lastIncident here must not be null + let lastIncident = state.getIncident(monitor.id, state.incidentLen(monitor.id) - 1) + + if (status.up) { + // Current status is up + // close existing incident if any + if (lastIncident.end === null) { + lastIncident.end = currentTimeSecond + // write back the modified last incident + state.setIncident(monitor.id, state.incidentLen(monitor.id) - 1, lastIncident) + + monitorStatusChanged = true + try { + if ( + // 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 + ) { + await formatAndNotify(monitor, true, lastIncident.start[0], currentTimeSecond, 'OK') + } else { + console.log( + `grace period (${workerConfig.notification?.gracePeriod}m) not met, skipping webhook UP notification for ${monitor.name}` + ) + } + + console.log('Calling config onStatusChange callback...') + await workerConfig.callbacks?.onStatusChange?.( + env, + monitor, + true, + lastIncident.start[0], + currentTimeSecond, + 'OK' + ) + } catch (e) { + console.log('Error calling callback: ') + console.log(e) + } + } + } else { + // Current status is down + // open new incident if not already open + if (lastIncident.end !== null) { + state.appendIncident(monitor.id, { + start: [currentTimeSecond], + end: null, + error: [status.err], + }) + monitorStatusChanged = true + } else if (lastIncident.end === null && lastIncident.error.slice(-1)[0] !== status.err) { + // append if the error message changes + lastIncident.start.push(currentTimeSecond) + lastIncident.error.push(status.err) + + // write back the modified last incident + state.setIncident(monitor.id, state.incidentLen(monitor.id) - 1, lastIncident) + monitorStatusChanged = true + } + + const currentIncident = state.getIncident(monitor.id, state.incidentLen(monitor.id) - 1) + try { + if ( + // monitor status changed AND... + (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) + ) { + if ( + currentIncident.start[0] !== currentTimeSecond && + workerConfig.notification?.skipErrorChangeNotification + ) { + console.log( + 'Skipping notification for following error reason change due to user config' + ) + } else { + await formatAndNotify( + monitor, + false, + currentIncident.start[0], + currentTimeSecond, + status.err + ) + } + } else { + console.log( + `Grace period (${workerConfig.notification + ?.gracePeriod}m) not met or no change (currently down for ${ + currentTimeSecond - currentIncident.start[0] + }s, changed ${monitorStatusChanged}), skipping webhook DOWN notification for ${ + monitor.name + }` + ) + } + + if (monitorStatusChanged) { + console.log('Calling config onStatusChange callback...') + await workerConfig.callbacks?.onStatusChange?.( + env, + monitor, + false, + currentIncident.start[0], + currentTimeSecond, + status.err + ) + } + } catch (e) { + console.log('Error calling callback: ') + console.log(e) + } + + try { + console.log('Calling config onIncident callback...') + await workerConfig.callbacks?.onIncident?.( + env, + monitor, + currentIncident.start[0], + currentTimeSecond, + status.err + ) + } catch (e) { + console.log('Error calling callback: ') + console.log(e) + } + } + + // append to latency data + state.appendLatency(monitor.id, { + loc: checkLocation, + ping: status.ping, + time: currentTimeSecond, + }) + + // discard old data + while (state.getFirstLatency(monitor.id).time < currentTimeSecond - 12 * 60 * 60) { + state.unshiftLatency(monitor.id) + } + + // discard old incidents + while ( + state.incidentLen(monitor.id) > 0 && + state.getIncident(monitor.id, 0).end && + state.getIncident(monitor.id, 0).end! < currentTimeSecond - 90 * 24 * 60 * 60 + ) { + state.shiftIncident(monitor.id) + } + + if ( + state.incidentLen(monitor.id) === 0 || + (state.getIncident(monitor.id, 0).start[0] > currentTimeSecond - 90 * 24 * 60 * 60 && + state.getIncident(monitor.id, 0).error[0] != 'dummy') + ) { + // put the dummy incident back + state.unshiftIncident(monitor.id, { + start: [currentTimeSecond - 90 * 24 * 60 * 60], + end: currentTimeSecond - 90 * 24 * 60 * 60, + error: ['dummy'], + }) + } + + statusChanged ||= monitorStatusChanged + } + + console.log( + `statusChanged: ${statusChanged}, lastUpdate: ${state.data.lastUpdate}, currentTime: ${currentTimeSecond}` + ) + // Update state + // Allow for a cooldown period before writing to storage + if ( + statusChanged || + currentTimeSecond - state.data.lastUpdate >= + (workerConfig.kvWriteCooldownMinutes ?? 3) * 60 - 10 // Allow for 10 seconds of clock drift + ) { + console.log('Updating state...') + state.data.lastUpdate = currentTimeSecond + await setToStore(env, 'state', state.getCompactedStateStr()) + } else { + console.log('Skipping state update due to cooldown period.') + } + }, +} + +export default Worker diff --git a/apps/web/monitor/monitor.ts b/apps/web/monitor/monitor.ts new file mode 100644 index 0000000..150c618 --- /dev/null +++ b/apps/web/monitor/monitor.ts @@ -0,0 +1,418 @@ +import type { Env } from '.' +import { MonitorTarget } from '../types/config' +import { withTimeout, fetchTimeout } from './util' + +function isIpAddress(hostname: string): boolean { + // `URL.hostname` strips brackets for IPv6, so a `:` reliably indicates an IPv6 literal here. + if (hostname.includes(':')) return true + + const parts = hostname.split('.') + if (parts.length !== 4) return false + + return parts.every((part) => { + if (!/^\d{1,3}$/.test(part)) return false + const value = Number(part) + return value >= 0 && value <= 255 + }) +} + +function getDomainOnlyIpVersionOption(hostname: string, gpUrl: URL): { ipVersion?: number } { + // Globalping only allows `measurementOptions.ipVersion` when `target` is a domain (it controls DNS resolution). + if (isIpAddress(hostname)) return {} + + // Keep the original behavior for domain targets. + return { ipVersion: Number(gpUrl.searchParams.get('ipVersion') || 4) } +} + +async function httpResponseBasicCheck( + monitor: MonitorTarget, + code: number, + bodyReader: () => Promise +): Promise { + if (monitor.expectedCodes) { + if (!monitor.expectedCodes.includes(code)) { + return `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${code}` + } + } else { + if (code < 200 || code > 299) { + return `Expected codes: 2xx, Got: ${code}` + } + } + + if (monitor.responseKeyword || monitor.responseForbiddenKeyword) { + // Only read response body if we have a keyword to check + const responseBody = await bodyReader() + + // 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)}` + ) + return "HTTP response doesn't contain the configured keyword" + } + + // 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)}` + ) + return 'HTTP response contains the configured forbidden keyword' + } + } + + return null +} + +export async function getStatusWithGlobalPing( + monitor: MonitorTarget +): Promise<{ location: string; status: { ping: number; up: boolean; err: string } }> { + // TODO: should throw when there's error with globalping API + try { + if (monitor.checkProxy === undefined) { + throw "empty check proxy for globalping, shouldn't call this method" + } + + const gpUrl = new URL(monitor.checkProxy) + if (gpUrl.protocol !== 'globalping:') { + throw 'incorrect check proxy protocol for globalping, got: ' + gpUrl.protocol + } + + const token = gpUrl.hostname + let globalPingRequest = {} + + if (monitor.method === 'TCP_PING') { + const targetUrl = new URL('https://' + monitor.target) // dummy https:// to parse hostname & port + const ipVersionOption = getDomainOnlyIpVersionOption(targetUrl.hostname, gpUrl) + globalPingRequest = { + type: 'ping', + target: targetUrl.hostname, + locations: + gpUrl.searchParams.get('magic') !== null + ? [ + { + magic: gpUrl.searchParams.get('magic'), + }, + ] + : undefined, + measurementOptions: { + port: targetUrl.port, + packets: 1, + protocol: 'tcp', // TODO: icmp? + ...ipVersionOption, + }, + } + } else { + const targetUrl = new URL(monitor.target) + const ipVersionOption = getDomainOnlyIpVersionOption(targetUrl.hostname, gpUrl) + if (monitor.body !== undefined) { + throw 'custom body not supported' + } + if (monitor.method && !['GET', 'HEAD', 'OPTIONS'].includes(monitor.method.toUpperCase())) { + throw 'only GET, HEAD, OPTIONS methods are supported' + } + globalPingRequest = { + type: 'http', + target: targetUrl.hostname, + locations: + gpUrl.searchParams.get('magic') !== null + ? [ + { + magic: gpUrl.searchParams.get('magic'), + }, + ] + : undefined, + measurementOptions: { + request: { + method: monitor.method, + path: targetUrl.pathname, + query: targetUrl.search === '' ? undefined : targetUrl.search, + headers: Object.fromEntries( + Object.entries(monitor.headers ?? {}).map(([key, value]) => [key, String(value)]) + ), // TODO: host header? + }, + port: + targetUrl.port === '' + ? targetUrl.protocol === 'http:' + ? 80 + : 443 + : Number(targetUrl.port), + protocol: targetUrl.protocol.replace(':', ''), + ...ipVersionOption, + }, + } + } + + const startTime = Date.now() + console.log(`Requesting the Global Ping API, payload: ${JSON.stringify(globalPingRequest)}`) + const measurement = await fetchTimeout('https://api.globalping.io/v1/measurements', 5000, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: 'Bearer ' + token, + }, + body: JSON.stringify(globalPingRequest), + }) + const measurementResponse = (await measurement.json()) as any + + if (measurement.status !== 202) { + throw measurementResponse.error.message + } + + const measurementId = measurementResponse.id + console.log( + `Measurement created successfully, id: ${measurementId}, time elapsed: ${ + Date.now() - startTime + }ms` + ) + + const pollStart = Date.now() + let measurementResult: any + while (true) { + if (Date.now() - pollStart > (monitor.timeout ?? 10000) + 2000) { + // 2s extra buffer + throw 'api polling timeout' + } + + measurementResult = (await ( + await fetchTimeout(`https://api.globalping.io/v1/measurements/${measurementId}`, 5000) + ).json()) as any + if (measurementResult.status !== 'in-progress') { + break + } + + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + + console.log( + `Measurement ${measurementId} finished with response: ${JSON.stringify( + measurementResult + )}, time elapsed: ${Date.now() - pollStart}ms` + ) + + if ( + measurementResult.status !== 'finished' || + measurementResult.results[0].result.status !== 'finished' + ) { + console.log( + `measurement failed with status: ${measurementResult.status}, result status: ${measurementResult.results[0].result.status}` + ) + // Truncate raw output to avoid huge error messages + throw `status [${measurementResult.status}|${ + measurementResult.results[0].result.status + }]: ${measurementResult.results?.[0].result?.rawOutput?.slice(0, 64)}` + } + + const country = measurementResult.results[0].probe.country + const city = measurementResult.results[0].probe.city + + if (monitor.method === 'TCP_PING') { + const time = Math.round(measurementResult.results[0].result.stats.avg) + return { + location: country + '/' + city, + status: { + ping: time, + up: true, + err: '', + }, + } + } else { + const time = measurementResult.results[0].result.timings.total + const code = measurementResult.results[0].result.statusCode + const body = measurementResult.results[0].result.rawBody + + let err = await httpResponseBasicCheck(monitor, code, () => body) + if (err !== null) { + console.log(`${monitor.name} didn't pass response check: ${err}`) + } + + if ( + monitor.target.toLowerCase().startsWith('https') && + !measurementResult.results[0].result.tls.authorized + ) { + console.log( + `${monitor.name} TLS certificate not trusted: ${measurementResult.results[0].result.tls.error}` + ) + err = 'TLS certificate not trusted: ' + measurementResult.results[0].result.tls.error + } + + return { + location: country + '/' + city, + status: { + ping: time, + up: err === null, + err: err ?? '', + }, + } + } + } catch (e: any) { + console.log(`Globalping ${monitor.name} errored with ${e}`) + return { + location: 'ERROR', + status: { + ping: e.toString().toLowerCase().includes('timeout') ? monitor.timeout ?? 10000 : 0, + up: false, + err: 'Globalping error: ' + e.toString(), + }, + } + } +} + +export async function getStatus( + monitor: MonitorTarget +): Promise<{ ping: number; up: boolean; err: string }> { + let status = { + ping: 0, + up: false, + err: 'Unknown', + } + + const startTime = Date.now() + + if (monitor.method === 'TCP_PING') { + // TCP port endpoint monitor + try { + 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 socket = connect({ hostname: parsed.hostname, port: Number(parsed.port) }) + + // Now we have an `opened` promise! + await withTimeout(monitor.timeout || 10000, socket.opened) + await socket.close() + + console.log(`${monitor.name} connected to ${monitor.target}`) + + status.ping = Date.now() - startTime + status.up = true + status.err = '' + } catch (e: Error | any) { + console.log(`${monitor.name} errored with ${e.name}: ${e.message}`) + if (e.message.includes('timed out')) { + status.ping = monitor.timeout || 10000 + } + status.up = false + status.err = e.name + ': ' + e.message + } + } else { + // HTTP endpoint monitor + try { + let headers = new Headers(monitor.headers as any) + if (!headers.has('user-agent')) { + headers.set('user-agent', 'UptimeFlare/1.0 (+https://github.com/lyc8503/UptimeFlare)') + } + + const response = await fetchTimeout(monitor.target, monitor.timeout || 10000, { + method: monitor.method, + headers: headers, + body: monitor.body, + cf: { + cacheTtlByStatus: { + '100-599': -1, // Don't cache any status code, from https://developers.cloudflare.com/workers/runtime-apis/request/#requestinitcfproperties + }, + }, + }) + + console.log(`${monitor.name} responded with ${response.status}`) + status.ping = Date.now() - startTime + + const err = await httpResponseBasicCheck( + monitor, + response.status, + response.text.bind(response) + ) + try { + await response.body?.cancel() + } catch (e) {} // Always try to cancel body, see issue #166 + + if (err !== null) { + console.log(`${monitor.name} didn't pass response check: ${err}`) + } + status.up = err === null + status.err = err ?? '' + } catch (e: any) { + console.log(`${monitor.name} errored with ${e.name}: ${e.message}`) + if (e.name === 'AbortError') { + status.ping = monitor.timeout || 10000 + status.up = false + status.err = `Timeout after ${status.ping}ms` + } else { + status.up = false + status.err = e.name + ': ' + e.message + } + } + } + + return status +} + +export const WORKER_PROXY_UNAVAILABLE = + 'worker:// check proxies (Durable Objects) are not available in this port' + +// `env` is kept in the signature for upstream's callers; nothing reads it +// since the remote checker (the one binding it used) is left out. +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export async function doMonitor(monitor: MonitorTarget, defaultLocation: string, env: Env) { + let checkLocation = defaultLocation + let status + + if (monitor.checkProxy) { + // Initiate a check using proxy (Geo-specific monitoring) + try { + console.log(`[${monitor.id}] Calling check proxy: ${monitor.checkProxy}`) + let resp + if (monitor.checkProxy.startsWith('worker://')) { + // Upstream runs `worker://` checks in a Durable Object placed + // by a location hint. This port has no Durable Object (no Orun + // composition places one), so the proxy is "down": with + // `checkProxyFallback` the monitor is checked locally below, without + // it the monitor reports why. + throw WORKER_PROXY_UNAVAILABLE + } else if (monitor.checkProxy.startsWith('globalping://')) { + resp = await getStatusWithGlobalPing(monitor) + } else { + resp = await ( + await fetch(monitor.checkProxy, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(monitor), + }) + ).json<{ location: string; status: { ping: number; up: boolean; err: string } }>() + } + checkLocation = resp.location + status = resp.status + } catch (err) { + console.log(`[${monitor.id}] Error calling proxy: ${err}`) + if (monitor.checkProxyFallback) { + console.log('Falling back to local check...') + status = await getStatus(monitor) + } else { + // TODO: more consistent error handling (throw or return?) + status = { + ping: 0, + up: false, + err: err === WORKER_PROXY_UNAVAILABLE ? WORKER_PROXY_UNAVAILABLE : 'Unknown check proxy error', + } + } + } + } else { + // Initiate a check from the current location + status = await getStatus(monitor) + } + + console.log(`[${monitor.id}] Check result from ${checkLocation}: up=${status.up}, ping=${status.ping}, err=${status.err}`) + + return { + location: checkLocation, + status, + id: monitor.id, + } +} diff --git a/apps/web/monitor/store.ts b/apps/web/monitor/store.ts new file mode 100644 index 0000000..0d40f30 --- /dev/null +++ b/apps/web/monitor/store.ts @@ -0,0 +1,253 @@ +import type { Env } from '.' +import { + IncidentRecord, + LatencyRecord, + MonitorState, + MonitorStateCompacted, +} from '../types/config' + +// The state lives in the DB D1 binding's `monitor_state(key, value)` table +// (upstream names the table after the project; this name survives a rebrand), +// created by the migrations before the Worker deploys. +export async function getFromStore(env: Pick, key: string): Promise { + const stmt = env.DB.prepare('SELECT value FROM monitor_state WHERE key = ?') + const result = await stmt.bind(key).first<{ value: string }>() + return result?.value || null +} + +export async function setToStore(env: Pick, key: string, value: string): Promise { + const stmt = env.DB.prepare( + 'INSERT INTO monitor_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value;' + ) + await stmt.bind(key, value).run() +} + +export class CompactedMonitorStateWrapper { + data: MonitorStateCompacted + + constructor(compactedStateStr: string | null) { + if (!compactedStateStr) { + // Initialize empty state + this.data = { + lastUpdate: 0, + overallUp: 0, + overallDown: 0, + incident: {}, + latency: {}, + } + return + } + this.data = JSON.parse(compactedStateStr) + } + + getCompactedStateStr(): string { + return JSON.stringify(this.data) + } + + // Don't use this method at server-side + uncompact(): MonitorState { + let state: MonitorState = { + lastUpdate: this.data.lastUpdate, + overallUp: this.data.overallUp, + overallDown: this.data.overallDown, + incident: {}, + latency: {}, + } + + const hex2Uint8Arr = (hex: string): Uint8Array => { + // @ts-expect-error This method is not available in Node.js 22.x, but available in Cloudflare Workers and new browsers + if (Uint8Array.fromHex) { + // @ts-expect-error + return Uint8Array.fromHex(hex) + } else { + console.warn('Uint8Array.fromHex is not available, using parseInt as fallback. Consider upgrading your browser.') + const ret = new Uint8Array(hex.length / 2) + for (let i = 0; i < hex.length; i += 2) { + ret[i / 2] = parseInt(hex.slice(i, i + 2), 16) + } + return ret + } + } + + Object.keys(this.data.incident).forEach((monitorId) => { + state.incident[monitorId] = [] + const incidents = this.data.incident[monitorId] + + if ( + incidents.start.length !== incidents.end.length || + incidents.start.length !== incidents.error.length + ) { + throw new Error( + 'Inconsistent incident data lengths, please report an issue at https://github.com/lyc8503/UptimeFlare' + ) + } + + for (let i = 0; i < incidents.start.length; i++) { + state.incident[monitorId].push({ + start: incidents.start[i], + end: incidents.end[i], + error: incidents.error[i], + }) + } + }) + + Object.keys(this.data.latency).forEach((monitorId) => { + state.latency[monitorId] = [] + const latencies = this.data.latency[monitorId] + const locUncompacted: string[] = [] + latencies.loc.c.forEach((count, index) => { + for (let i = 0; i < count; i++) { + locUncompacted.push(latencies.loc.v[index]) + } + }) + + const timeArr = new Uint32Array(hex2Uint8Arr(latencies.time).buffer) + const pingArr = new Uint16Array(hex2Uint8Arr(latencies.ping).buffer) + + if (timeArr.length !== pingArr.length || timeArr.length !== locUncompacted.length) { + throw new Error( + 'Inconsistent latency data lengths, please report an issue at https://github.com/lyc8503/UptimeFlare.' + ) + } + + for (let i = 0; i < timeArr.length; i++) { + state.latency[monitorId].push({ + time: timeArr[i], + ping: pingArr[i], + loc: locUncompacted[i], + }) + } + }) + + return state + } + + incidentLen(monitorId: string): number { + const incidents = this.data.incident[monitorId] + if (!incidents) return 0 + return incidents.start.length + } + + getIncident(monitorId: string, index: number): IncidentRecord { + const incidents = this.data.incident[monitorId] + if (!incidents || index < 0 || index >= incidents.start.length) { + throw new Error('Index out of bounds or monitor not found') + } + return { + start: incidents.start[index], + end: incidents.end[index], + error: incidents.error[index], + } + } + + setIncident(monitorId: string, index: number, incident: IncidentRecord) { + const incidents = this.data.incident[monitorId] + if (!incidents || index < 0 || index >= incidents.start.length) { + throw new Error('Index out of bounds or monitor not found') + } + incidents.start[index] = incident.start + incidents.end[index] = incident.end + incidents.error[index] = incident.error + } + + appendIncident(monitorId: string, incident: IncidentRecord) { + let incidents = this.data.incident[monitorId] + if (!incidents) { + // Initialize incident arrays + this.data.incident[monitorId] = { + start: [], + end: [], + error: [], + } + incidents = this.data.incident[monitorId] + } + incidents.start.push(incident.start) + incidents.end.push(incident.end) + incidents.error.push(incident.error) + } + + shiftIncident(monitorId: string) { + const incidents = this.data.incident[monitorId] + incidents.start.shift() + incidents.end.shift() + incidents.error.shift() + } + + unshiftIncident(monitorId: string, incident: IncidentRecord) { + const incidents = this.data.incident[monitorId] + incidents.start.unshift(incident.start) + incidents.end.unshift(incident.end) + incidents.error.unshift(incident.error) + } + + latencyLen(monitorId: string): number { + const latencies = this.data.latency[monitorId] + if (!latencies) return 0 + return latencies.ping.length / 4 // Uint16Array, 4 characters per entry in hex + } + + appendLatency(monitorId: string, record: LatencyRecord) { + let latencies = this.data.latency[monitorId] + if (!latencies) { + // Initialize latency arrays + this.data.latency[monitorId] = { + time: '', + ping: '', + loc: { + c: [], + v: [], + }, + } + latencies = this.data.latency[monitorId] + } + + // @ts-expect-error + latencies.time += new Uint8Array(new Uint32Array([record.time]).buffer).toHex() + // @ts-expect-error + latencies.ping += new Uint8Array(new Uint16Array([record.ping]).buffer).toHex() + + if (latencies.loc.v[latencies.loc.v.length - 1] !== record.loc) { + latencies.loc.c.push(1) + latencies.loc.v.push(record.loc) + } else { + latencies.loc.c[latencies.loc.c.length - 1] += 1 + } + } + + getFirstLatency(monitorId: string): LatencyRecord { + let latencies = this.data.latency[monitorId] + + return { + // @ts-expect-error + time: new Uint32Array(Uint8Array.fromHex(latencies.time.slice(0, 8)).buffer)[0], + // @ts-expect-error + ping: new Uint16Array(Uint8Array.fromHex(latencies.ping.slice(0, 4)).buffer)[0], + loc: latencies.loc.v[0], + } + } + + getLastLatency(monitorId: string): LatencyRecord { + let latencies = this.data.latency[monitorId] + + return { + // @ts-expect-error + time: new Uint32Array(Uint8Array.fromHex(latencies.time.slice(-8)).buffer)[0], + // @ts-expect-error + ping: new Uint16Array(Uint8Array.fromHex(latencies.ping.slice(-4)).buffer)[0], + loc: latencies.loc.v[latencies.loc.v.length - 1], + } + } + + unshiftLatency(monitorId: string) { + let latencies = this.data.latency[monitorId] + + latencies.time = latencies.time.slice(8) + latencies.ping = latencies.ping.slice(4) + + latencies.loc.c[0] -= 1 + if (latencies.loc.c[0] === 0) { + latencies.loc.c.shift() + latencies.loc.v.shift() + } + } +} diff --git a/apps/web/monitor/util.ts b/apps/web/monitor/util.ts new file mode 100644 index 0000000..5addbd0 --- /dev/null +++ b/apps/web/monitor/util.ts @@ -0,0 +1,201 @@ +import { MonitorTarget, WebhookConfig } from '../types/config' +import { maintenances, workerConfig } from '../uptime.config' + +async function getWorkerLocation() { + const res = await fetch('https://cloudflare.com/cdn-cgi/trace') + const text = await res.text() + + const colo = /^colo=(.*)$/m.exec(text)?.[1] + return colo +} + +const fetchTimeout = ( + url: string, + ms: number, + { signal, ...options }: RequestInit | undefined = {} +): Promise => { + const controller = new AbortController() + const promise = fetch(url, { signal: controller.signal, ...options }) + if (signal) signal.addEventListener('abort', () => controller.abort()) + const timeout = setTimeout(() => controller.abort(), ms) + return promise.finally(() => clearTimeout(timeout)) +} + +function withTimeout(millis: number, promise: Promise): Promise { + const timeout = new Promise((resolve, reject) => + setTimeout(() => reject(new Error(`Promise timed out after ${millis}ms`)), millis) + ) + + return Promise.race([promise, timeout]) +} + +function formatStatusChangeNotification( + monitor: any, + isUp: boolean, + timeIncidentStart: number, + timeNow: number, + reason: string, + timeZone: string +) { + const dateFormatter = new Intl.DateTimeFormat('en-US', { + month: 'numeric', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + hour12: false, + timeZone: timeZone, + }) + + let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60) + const timeNowFormatted = dateFormatter.format(new Date(timeNow * 1000)) + const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000)) + + if (isUp) { + return `✅ ${monitor.name} is up! \nThe service is up again after being down for ${downtimeDuration} minutes.` + } else if (timeNow == timeIncidentStart) { + return `🔴 ${ + monitor.name + } is currently down. \nService is unavailable at ${timeNowFormatted}. \nIssue: ${ + reason || 'unspecified' + }` + } else { + return `🔴 ${ + monitor.name + } is still down. \nService is unavailable since ${timeIncidentStartFormatted} (${downtimeDuration} minutes). \nIssue: ${ + reason || 'unspecified' + }` + } +} + +function templateWebhookPlayload(payload: any, message: string) { + for (const key in payload) { + if (Object.prototype.hasOwnProperty.call(payload, key)) { + if (payload[key] === '$MSG') { + payload[key] = message + } else if (typeof payload[key] === 'object' && payload[key] !== null) { + templateWebhookPlayload(payload[key], message) + } + } + } +} + +async function webhookNotify(webhook: WebhookConfig, message: string) { + if (Array.isArray(webhook)) { + for (const w of webhook) { + await webhookNotify(w, message) + } + return + } + + console.log( + 'Sending webhook notification: ' + JSON.stringify(message) + ' to webhook ' + webhook.url + ) + try { + let url = webhook.url + let method = webhook.method + let headers = new Headers(webhook.headers as any) + let payloadTemplated: { [key: string]: string | number } = JSON.parse( + JSON.stringify(webhook.payload) + ) + templateWebhookPlayload(payloadTemplated, message) + let body = undefined + + switch (webhook.payloadType) { + case 'param': + method = method ?? 'GET' + const urlTmp = new URL(url) + for (const [k, v] of Object.entries(payloadTemplated)) { + urlTmp.searchParams.append(k, v.toString()) + } + url = urlTmp.toString() + break + case 'json': + method = method ?? 'POST' + if (headers.get('content-type') === null) { + headers.set('content-type', 'application/json') + } + body = JSON.stringify(payloadTemplated) + break + case 'x-www-form-urlencoded': + method = method ?? 'POST' + if (headers.get('content-type') === null) { + headers.set('content-type', 'application/x-www-form-urlencoded') + } + body = new URLSearchParams(payloadTemplated as any).toString() + break + default: + throw 'Unrecognized payload type: ' + webhook.payloadType + } + + console.log( + `Webhook finalized parameters: ${method} ${url}, headers ${JSON.stringify( + Object.fromEntries(headers.entries()) + )}, body ${JSON.stringify(body)}` + ) + const resp = await fetchTimeout(url, webhook.timeout ?? 5000, { method, headers, body }) + + if (!resp.ok) { + console.log( + 'Error calling webhook server, code: ' + resp.status + ', response: ' + (await resp.text()) + ) + } else { + console.log('Webhook notification sent successfully, code: ' + resp.status) + } + } catch (e) { + console.log('Error calling webhook server: ' + e) + } +} + +// Auxiliary function to format notification and send it via webhook +const formatAndNotify = async ( + monitor: MonitorTarget, + isUp: boolean, + timeIncidentStart: number, + timeNow: number, + reason: string +) => { + // Skip notification if monitor is in the skip list + const skipList = workerConfig.notification?.skipNotificationIds + if (skipList && skipList.includes(monitor.id)) { + console.log(`Skipping notification for ${monitor.name} (${monitor.id} in skipNotificationIds)`) + return + } + + // Skip notification if monitor is in maintenance + const maintenanceList = maintenances + .filter( + (m) => + new Date(timeNow * 1000) >= new Date(m.start) && + (!m.end || new Date(timeNow * 1000) <= new Date(m.end)) + ) + .map((e) => e.monitors || []) + .flat() + + if (maintenanceList.includes(monitor.id)) { + console.log(`Skipping notification for ${monitor.name} (in maintenance)`) + return + } + + if (workerConfig.notification?.webhook) { + const notification = formatStatusChangeNotification( + monitor, + isUp, + timeIncidentStart, + timeNow, + reason, + workerConfig.notification?.timeZone ?? 'Etc/GMT' + ) + await webhookNotify(workerConfig.notification.webhook, notification) + } else { + console.log(`Webhook not set, skipping notification for ${monitor.name}`) + } +} + +export { + getWorkerLocation, + fetchTimeout, + withTimeout, + webhookNotify, + formatStatusChangeNotification, + formatAndNotify, +} diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs new file mode 100644 index 0000000..067eefe --- /dev/null +++ b/apps/web/next.config.mjs @@ -0,0 +1,27 @@ +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { initOpenNextCloudflareForDev } from '@opennextjs/cloudflare' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) + +// `next dev` reaches the D1 binding through wrangler's local platform proxy +// (render apps/web/wrangler.jsonc first: `pnpm run wire:fixture`). +initOpenNextCloudflareForDev() + +/** @type {import('next').NextConfig} */ +const nextConfig = { + reactStrictMode: true, + // Required by @opennextjs/cloudflare, which bundles `.next/standalone/**` + // into the Worker; traced from the monorepo root. + output: 'standalone', + outputFileTracingRoot: path.join(__dirname, '../..'), + // OpenNext bundles the Worker with the `workerd` export condition, and + // react-textarea-autosize (a Mantine dependency) points that condition at + // its edge-light build, which Next's tracing — done under Node's conditions + // — never copies into the standalone output. Trace it in by hand. + outputFileTracingIncludes: { + '/*': ['../../node_modules/.pnpm/react-textarea-autosize@*/node_modules/react-textarea-autosize/dist/*edge-light*'], + }, +} + +export default nextConfig diff --git a/apps/web/open-next.config.ts b/apps/web/open-next.config.ts new file mode 100644 index 0000000..c2ac4dc --- /dev/null +++ b/apps/web/open-next.config.ts @@ -0,0 +1,14 @@ +// OpenNext Cloudflare adapter config. +// +// Nothing is cached between requests and nothing revalidates: the page renders +// per request (only to put its Open Graph image on the request's origin; SWR +// polls the API routes from the browser), and the API routes are dynamic. The +// static-assets incremental cache is the read-only one, with no R2/KV/D1 to +// provision for it. A template that revalidates (ISR, `revalidateTag`) swaps +// this for the R2 incremental cache plus a tag cache. +import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"; +import staticAssetsIncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache"; + +export default defineCloudflareConfig({ + incrementalCache: staticAssetsIncrementalCache, +}); diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..b7c5113 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,49 @@ +{ + "name": "@app/web", + "version": "0.0.0", + "private": true, + "scripts": { + "dev": "next dev -p 3000", + "build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && opennextjs-cloudflare populateCache local", + "start": "next start -p 3000", + "preview": "opennextjs-cloudflare preview", + "db:init:local": "wrangler d1 execute DB --local --config wrangler.jsonc --file init.sql", + "typecheck": "tsc --noEmit", + "lint": "eslint .", + "wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage" + }, + "dependencies": { + "@mantine/core": "^7.17.8", + "@mantine/hooks": "^7.17.8", + "@opennextjs/cloudflare": "^1.20.11", + "@tabler/icons-react": "^2.47.0", + "chart.js": "^4.4.0", + "chartjs-adapter-moment": "^1.0.1", + "i18next": "^25.7.3", + "i18next-browser-languagedetector": "^8.2.0", + "moment": "^2.29.4", + "moment-precise-range-plugin": "^1.3.0", + "next": "16.3.8", + "p-limit": "^7.2.0", + "react": "^19.2.1", + "react-chartjs-2": "^5.2.0", + "react-dom": "^19.2.1", + "react-i18next": "^16.5.0" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@cloudflare/workers-types": "^4.20250508.0", + "@types/moment-precise-range-plugin": "^0.2.2", + "@types/node": "^22.9.0", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9.27.0", + "eslint-config-next": "16.3.8", + "postcss": "^8.4.49", + "postcss-preset-mantine": "^1.8.0", + "postcss-simple-vars": "^7.0.1", + "typescript": "^5.8.3", + "wrangler": "^4.151.0" + } +} diff --git a/apps/web/pages/_app.tsx b/apps/web/pages/_app.tsx new file mode 100644 index 0000000..84dc46a --- /dev/null +++ b/apps/web/pages/_app.tsx @@ -0,0 +1,24 @@ +import '@mantine/core/styles.css' +import type { AppProps } from 'next/app' +import Head from 'next/head' +import { MantineProvider } from '@mantine/core' +import NoSsr from '@/components/NoSsr' +import { pageConfig } from '@/uptime.config' +import '@/util/i18n' + +export default function App({ Component, pageProps }: AppProps) { + return ( + <> + {/* The title outside NoSsr, so the server-rendered page carries it too + (upstream sets it only once the page renders in the browser). */} + + {pageConfig.title} + + + + + + + + ) +} diff --git a/apps/web/pages/_document.tsx b/apps/web/pages/_document.tsx new file mode 100644 index 0000000..83374be --- /dev/null +++ b/apps/web/pages/_document.tsx @@ -0,0 +1,16 @@ +import { Html, Head, Main, NextScript } from 'next/document' +import { ColorSchemeScript } from '@mantine/core' + +export default function Document() { + return ( + + + + + +
+ + + + ) +} diff --git a/apps/web/pages/api/badge.ts b/apps/web/pages/api/badge.ts new file mode 100644 index 0000000..de6ef35 --- /dev/null +++ b/apps/web/pages/api/badge.ts @@ -0,0 +1,69 @@ +import type { NextApiRequest, NextApiResponse } from 'next' +import { getCloudflareContext } from '@opennextjs/cloudflare' +import { CompactedMonitorStateWrapper, getFromStore } from '@/monitor/store' + +// Upstream's edge route (a shields.io endpoint badge), as a Node API route. +type BadgePayload = { + schemaVersion: 1 + label: string + message: string + color: string + isError?: boolean +} + +const jsonHeaders = { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store, max-age=0, must-revalidate', +} + +function errorBadge(label: string, message: string): BadgePayload { + return { + schemaVersion: 1, + label, + message, + color: 'lightgrey', + isError: true, + } +} + +function param(req: NextApiRequest, name: string): string | null { + const v = req.query[name] + return typeof v === 'string' ? v : null +} + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + for (const [k, v] of Object.entries(jsonHeaders)) res.setHeader(k, v) + const monitorId = param(req, 'id') + const label = param(req, 'label') ?? monitorId ?? 'UptimeFlare' + try { + const upMsg = param(req, 'up') ?? 'UP' + const downMsg = param(req, 'down') ?? 'DOWN' + const colorUp = param(req, 'colorUp') ?? 'brightgreen' + const colorDown = param(req, 'colorDown') ?? 'red' + + if (!monitorId) { + return res.status(400).send(JSON.stringify(errorBadge(label, 'no-monitor'))) + } + + const { env } = await getCloudflareContext({ async: true }) + const compactedState = new CompactedMonitorStateWrapper(await getFromStore(env, 'state')) + + const lastIncident = compactedState.getIncident( + monitorId, + compactedState.incidentLen(monitorId) - 1 + ) + const isUp = lastIncident?.end !== null + + const badge: BadgePayload = { + schemaVersion: 1, + label, + message: isUp ? upMsg : downMsg, + color: isUp ? colorUp : colorDown, + } + + return res.status(200).send(JSON.stringify(badge)) + } catch (err) { + console.error('Error rendering badge API:', err) + return res.status(500).send(JSON.stringify(errorBadge('status', 'error'))) + } +} diff --git a/apps/web/pages/api/data.ts b/apps/web/pages/api/data.ts new file mode 100644 index 0000000..4f14e86 --- /dev/null +++ b/apps/web/pages/api/data.ts @@ -0,0 +1,59 @@ +import type { NextApiRequest, NextApiResponse } from 'next' +import { getCloudflareContext } from '@opennextjs/cloudflare' +import { maintenances, workerConfig } from '@/uptime.config' +import { CompactedMonitorStateWrapper, getFromStore } from '@/monitor/store' + +// Upstream's edge route, as a Node API route (OpenNext runs no edge runtime): +// the same headers, the same body, the D1 binding from the Worker's env. +const headers = { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type', +} + +export default async function handler(_req: NextApiRequest, res: NextApiResponse) { + for (const [k, v] of Object.entries(headers)) res.setHeader(k, v) + + let compactedState: CompactedMonitorStateWrapper + try { + const { env } = await getCloudflareContext({ async: true }) + compactedState = new CompactedMonitorStateWrapper(await getFromStore(env, 'state')) + } catch (e) { + // Most likely no monitor_state table: the migrations have not run. + console.error('Error reading monitor state:', e) + return res.status(500).send(JSON.stringify({ error: 'Monitor state unavailable' })) + } + + if (compactedState.data.lastUpdate === 0) { + return res.status(500).send(JSON.stringify({ error: 'No data available' })) + } + + const monitors: Record = {} + + for (const monitor of workerConfig.monitors) { + const lastIncident = compactedState.getIncident( + monitor.id, + compactedState.incidentLen(monitor.id) - 1 + ) + + const isUp = lastIncident?.end !== null + const latency = compactedState.getLastLatency(monitor.id) + monitors[monitor.id] = { + up: isUp, + latency: latency.ping, + location: latency.loc, + message: isUp ? 'OK' : lastIncident?.error[lastIncident.error.length - 1], + } + } + + const ret = { + up: compactedState.data.overallUp, + down: compactedState.data.overallDown, + updatedAt: compactedState.data.lastUpdate, + monitors, + maintenances, + } + + return res.status(200).send(JSON.stringify(ret)) +} diff --git a/apps/web/pages/incidents.tsx b/apps/web/pages/incidents.tsx new file mode 100644 index 0000000..a4fbbe1 --- /dev/null +++ b/apps/web/pages/incidents.tsx @@ -0,0 +1,143 @@ +import Head from 'next/head' + +import { Inter } from 'next/font/google' +import { MaintenanceConfig, MonitorTarget } from '@/types/config' +import { maintenances, pageConfig } from '@/uptime.config' +import Header from '@/components/Header' +import { Box, Button, Center, Container, Group, Select } from '@mantine/core' +import Footer from '@/components/Footer' +import { useEffect, useState } from 'react' +import MaintenanceAlert from '@/components/MaintenanceAlert' +import NoIncidentsAlert from '@/components/NoIncidents' +import { useTranslation } from 'react-i18next' + +const inter = Inter({ subsets: ['latin'] }) + +function getSelectedMonth() { + const hash = window.location.hash.replace('#', '') + if (!hash) { + const now = new Date() + return now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + } + return hash.split('-').splice(0, 2).join('-') +} + +function filterIncidentsByMonth( + incidents: MaintenanceConfig[], + monthStr: string, + monitors: MonitorTarget[] +): (Omit & { monitors: MonitorTarget[] })[] { + return incidents + .filter((incident) => { + const d = new Date(incident.start) + const incidentMonth = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + return incidentMonth === monthStr + }) + .map((e) => ({ + ...e, + monitors: (e.monitors || []).map((e) => monitors.find((mon) => mon.id === e)!), + })) + .sort((a, b) => (new Date(a.start) > new Date(b.start) ? -1 : 1)) +} + +function getPrevNextMonth(monthStr: string) { + const [year, month] = monthStr.split('-').map(Number) + const date = new Date(year, month - 1) + const prev = new Date(date) + prev.setMonth(prev.getMonth() - 1) + const next = new Date(date) + next.setMonth(next.getMonth() + 1) + return { + prev: prev.getFullYear() + '-' + String(prev.getMonth() + 1).padStart(2, '0'), + next: next.getFullYear() + '-' + String(next.getMonth() + 1).padStart(2, '0'), + } +} + +export default function IncidentsPage({ monitors }: { monitors: MonitorTarget[] }) { + const { t } = useTranslation('common') + const [selectedMonitor, setSelectedMonitor] = useState('') + const [selectedMonth, setSelectedMonth] = useState(getSelectedMonth()) + + useEffect(() => { + const onHashChange = () => setSelectedMonth(getSelectedMonth()) + window.addEventListener('hashchange', onHashChange) + return () => window.removeEventListener('hashchange', onHashChange) + }, []) + + const filteredIncidents = filterIncidentsByMonth(maintenances, selectedMonth, monitors) + const monitorFilteredIncidents = selectedMonitor + ? filteredIncidents.filter((i) => i.monitors.find((e) => e.id === selectedMonitor)) + : filteredIncidents + + const { prev, next } = getPrevNextMonth(selectedMonth) + + const monitorOptions = [ + { value: '', label: t('All') }, + ...monitors.map((monitor) => ({ + value: monitor.id, + label: monitor.name, + })), + ] + + return ( + <> + + {pageConfig.title} + + + +
+
+
+ + +