Skip to content

Open-source status page, incident response and uptime monitoring

Chore/improve server file structure (#342)

Maximilian Kaske290223d6a557
diff --git a/apps/docs/pages/rest-api/openapi.mdx b/apps/docs/pages/rest-api/openapi.mdx
index dc8938057..7100cba52 100644
--- a/apps/docs/pages/rest-api/openapi.mdx
+++ b/apps/docs/pages/rest-api/openapi.mdx
@@ -3,7 +3,7 @@ import { Callout } from "nextra/components";
import { useData } from "nextra/data";
export const getStaticProps = async ({ params }) => {
- const res = await fetch("https://api.openstatus.dev/openapi");
+ const res = await fetch("https://api.openstatus.dev/v1/openapi");
const spec = await res.json();
return {
props: {
diff --git a/apps/server/.env.example b/apps/server/.env.example
index e6898ad0c..89dc76823 100644
--- a/apps/server/.env.example
+++ b/apps/server/.env.example
@@ -1,4 +1,7 @@
DATABASE_URL=http://127.0.0.1:8080
DATABASE_AUTH_TOKEN=
NODE_ENV=production
-UNKEY_TOKEN=
\ No newline at end of file
+UNKEY_TOKEN=
+TINY_BIRD_API_KEY=
+UPSTASH_REDIS_REST_URL=
+UPSTASH_REDIS_REST_TOKEN=
\ No newline at end of file
diff --git a/apps/server/package.json b/apps/server/package.json
index 85f8f60c5..cbeb690c8 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -13,6 +13,7 @@
"zod": "3.21.4",
"@openstatus/db": "workspace:*",
"@openstatus/tinybird": "workspace:*",
+ "@openstatus/upstash": "workspace:*",
"@unkey/api": "0.6.22",
"hono": "3.6.1"
},
diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts
index 26a3bc50a..f55fc94b7 100644
--- a/apps/server/src/index.ts
+++ b/apps/server/src/index.ts
@@ -1,40 +1,35 @@
-import { OpenAPIHono } from "@hono/zod-openapi";
+import { Hono } from "hono";
-import { incidentApi } from "./incident";
-import { middleware } from "./middleware";
-import { monitorApi } from "./monitor";
+import { publicRoute } from "./public";
+import { api } from "./v1";
import { VercelIngest } from "./vercel";
-export type Variables = {
- workspaceId: string;
-};
+const app = new Hono();
/**
- * Base Path "/v1" for our api
+ * Vercel Integration
*/
-const app = new OpenAPIHono<{ Variables: Variables }>();
-app.doc("/openapi", {
- openapi: "3.0.0",
- info: {
- version: "1.0.0",
- title: "OpenStatus API",
- },
-});
-app.get("/ping", (c) => c.text("pong"));
-
-// Where we ingest data from Vercel
app.post("/integration/vercel", VercelIngest);
+
+/**
+ * Public Routes
+ */
+app.route("/public", publicRoute);
+
/**
- * Authentification Middleware
+ * Ping Pong
*/
+app.get("/ping", (c) => c.text("pong"));
-app.use("/v1/*", middleware);
-app.route("/v1/monitor", monitorApi);
-app.route("/v1/incident", incidentApi);
+/**
+ * API Routes v1
+ */
+app.route("/v1", api);
if (process.env.NODE_ENV === "development") {
app.showRoutes();
}
+
console.log("Starting server on port 3000");
export default app;
diff --git a/apps/server/src/public/index.ts b/apps/server/src/public/index.ts
new file mode 100644
index 000000000..62297d5c7
--- /dev/null
+++ b/apps/server/src/public/index.ts
@@ -0,0 +1,7 @@
+import { Hono } from "hono";
+
+import { status } from "./status";
+
+export const publicRoute = new Hono();
+
+publicRoute.route("/status", status);
diff --git a/apps/server/src/public/status.ts b/apps/server/src/public/status.ts
new file mode 100644
index 000000000..0707615fc
--- /dev/null
+++ b/apps/server/src/public/status.ts
@@ -0,0 +1,84 @@
+import { Hono } from "hono";
+
+import { db, eq } from "@openstatus/db";
+import { monitor, monitorsToPages, page } from "@openstatus/db/src/schema";
+import { getMonitorList, Tinybird } from "@openstatus/tinybird";
+import { Redis } from "@openstatus/upstash";
+
+// TODO: include ratelimiting
+
+const tb = new Tinybird({ token: process.env.TINY_BIRD_API_KEY || "" });
+const redis = Redis.fromEnv();
+
+enum Status {
+ Operational = "operational",
+ DegradedPerformance = "degraded_performance",
+ PartialOutage = "partial_outage",
+ MajorOutage = "major_outage",
+ UnderMaintenance = "under_maintenance",
+ Unknown = "unknown",
+}
+
+export const status = new Hono();
+
+status.get("/:slug", async (c) => {
+ const { slug } = c.req.param();
+
+ const cache = await redis.get(slug);
+ if (cache) return c.json({ status: cache });
+
+ // { monitors, pages, monitors_to_pages }
+ const monitorData = await db
+ .select()
+ .from(monitorsToPages)
+ .leftJoin(monitor, eq(monitorsToPages.monitorId, monitor.id))
+ .leftJoin(page, eq(monitorsToPages.pageId, page.id))
+ .where(eq(page.slug, slug))
+ .all();
+
+ // { data: [{ ok, count }] }
+ const lastMonitorPings = await Promise.allSettled(
+ monitorData.map(async ({ monitors_to_pages }) => {
+ return await getMonitorList(tb)({
+ monitorId: String(monitors_to_pages.monitorId),
+ limit: 3, // limits the grouped cronTimestamps
+ });
+ }),
+ );
+
+ // { ok, count }
+ const data = lastMonitorPings.reduce(
+ (prev, curr) => {
+ if (curr.status === "fulfilled") {
+ const { ok, count } = curr.value.data.reduce(
+ (p, c) => {
+ p.ok += c.ok;
+ p.count += c.count;
+ return p;
+ },
+ { ok: 0, count: 0 },
+ );
+ prev.ok += ok;
+ prev.count += count;
+ }
+ return prev;
+ },
+ { ok: 0, count: 0 },
+ );
+
+ const ratio = data.ok / data.count;
+
+ const status = getStatus(ratio);
+ await redis.set(slug, status, { ex: 30 });
+
+ return c.json({ status });
+});
+
+function getStatus(ratio: number) {
+ if (isNaN(ratio)) return Status.Unknown;
+ if (ratio >= 0.98) return Status.Operational;
+ if (ratio >= 0.6) return Status.DegradedPerformance;
+ if (ratio >= 0.3) return Status.PartialOutage;
+ if (ratio >= 0) return Status.MajorOutage;
+ return Status.Unknown;
+}
diff --git a/apps/server/src/incident.ts b/apps/server/src/v1/incident.ts
similarity index 99%
rename from apps/server/src/incident.ts
rename to apps/server/src/v1/incident.ts
index d6250d66d..28f58a8a6 100644
--- a/apps/server/src/incident.ts
+++ b/apps/server/src/v1/incident.ts
@@ -7,7 +7,7 @@ import {
incidentUpdate,
} from "@openstatus/db/src/schema";
-import type { Variables } from ".";
+import type { Variables } from "./index";
import { ErrorSchema } from "./shared";
const incidentApi = new OpenAPIHono<{ Variables: Variables }>();
diff --git a/apps/server/src/v1/index.ts b/apps/server/src/v1/index.ts
new file mode 100644
index 000000000..8385b8654
--- /dev/null
+++ b/apps/server/src/v1/index.ts
@@ -0,0 +1,27 @@
+import { OpenAPIHono } from "@hono/zod-openapi";
+
+import { incidentApi } from "./incident";
+import { middleware } from "./middleware";
+import { monitorApi } from "./monitor";
+
+export type Variables = {
+ workspaceId: string;
+};
+
+export const api = new OpenAPIHono<{ Variables: Variables }>();
+
+api.doc("/openapi", {
+ openapi: "3.0.0",
+ info: {
+ version: "1.0.0",
+ title: "OpenStatus API",
+ },
+});
+
+/**
+ * Authentification Middleware
+ */
+api.use("/*", middleware);
+
+api.route("/monitor", monitorApi);
+api.route("/incident", incidentApi);
diff --git a/apps/server/src/middleware.ts b/apps/server/src/v1/middleware.ts
similarity index 93%
rename from apps/server/src/middleware.ts
rename to apps/server/src/v1/middleware.ts
index 0c03afcc2..9b966237c 100644
--- a/apps/server/src/middleware.ts
+++ b/apps/server/src/v1/middleware.ts
@@ -8,7 +8,7 @@ export async function middleware(
workspaceId: string;
};
},
- "/v1/*",
+ "/*",
{}
>,
next: Next,
@@ -24,6 +24,7 @@ export async function middleware(
if (!result.valid) return c.text("Unauthorized", 401);
c.set("workspaceId", `${result.ownerId}`);
} else {
+ // REMINDER: localhost only
c.set("workspaceId", "1");
}
await next();
diff --git a/apps/server/src/monitor.ts b/apps/server/src/v1/monitor.ts
similarity index 99%
rename from apps/server/src/monitor.ts
rename to apps/server/src/v1/monitor.ts
index ce25536eb..6d12e5de0 100644
--- a/apps/server/src/monitor.ts
+++ b/apps/server/src/v1/monitor.ts
@@ -8,7 +8,7 @@ import {
periodicity,
} from "@openstatus/db/src/schema/monitor";
-import type { Variables } from ".";
+import type { Variables } from "./index";
import { ErrorSchema } from "./shared";
const ParamsSchema = z.object({
@@ -393,6 +393,7 @@ const deleteRoute = createRoute({
},
},
});
+
monitorApi.openapi(deleteRoute, async (c) => {
const workspaceId = Number(c.get("workspaceId"));
const { id } = c.req.valid("param");
diff --git a/apps/server/src/shared.ts b/apps/server/src/v1/shared.ts
similarity index 100%
rename from apps/server/src/shared.ts
rename to apps/server/src/v1/shared.ts
diff --git a/bun.lockb b/bun.lockb
index 99899b14c..e9501184a 100755
Binary files a/bun.lockb and b/bun.lockb differ
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ef777a216..66a0ad14c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -81,6 +81,9 @@ importers:
'@openstatus/tinybird':
specifier: workspace:*
version: link:../../packages/tinybird
+ '@openstatus/upstash':
+ specifier: workspace:*
+ version: link:../../packages/upstash
'@unkey/api':
specifier: 0.6.22
version: 0.6.22