Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
🚀 API lgtm (#1289)
Thibault Le Ouayd077cdb3349d
diff --git a/apps/server/src/routes/v1/monitors/index.ts b/apps/server/src/routes/v1/monitors/index.tsindex 876a9d53f..57479bb95 100644--- a/apps/server/src/routes/v1/monitors/index.ts+++ b/apps/server/src/routes/v1/monitors/index.ts@@ -9,6 +9,8 @@ import { registerPostMonitor } from "./post";import { registerPostMonitorHTTP } from "./post_http";import { registerPostMonitorTCP } from "./post_tcp";import { registerPutMonitor } from "./put";+import { registerPutHTTPMonitor } from "./put_http";+import { registerPutTCPMonitor } from "./put_tcp";import { registerGetMonitorResult } from "./results/get";import { registerRunMonitor } from "./run/post";import { registerGetMonitorSummary } from "./summary/get";@@ -25,6 +27,8 @@ registerDeleteMonitor(monitorsApi);registerPostMonitor(monitorsApi);registerPostMonitorHTTP(monitorsApi);registerPostMonitorTCP(monitorsApi);+registerPutHTTPMonitor(monitorsApi);+registerPutTCPMonitor(monitorsApi);//registerGetMonitorSummary(monitorsApi);registerTriggerMonitor(monitorsApi);diff --git a/apps/server/src/routes/v1/monitors/post_tcp.test.ts b/apps/server/src/routes/v1/monitors/post_tcp.test.tsindex a0e18335c..66173e446 100644--- a/apps/server/src/routes/v1/monitors/post_tcp.test.ts+++ b/apps/server/src/routes/v1/monitors/post_tcp.test.ts@@ -21,14 +21,6 @@ test("create a valid monitor", async () => {},active: true,public: true,- assertions: [- {- type: "status",- compare: "eq",- target: 200,- },- { type: "header", compare: "not_eq", key: "key", target: "value" },- ],}),});diff --git a/apps/server/src/routes/v1/monitors/put.test.ts b/apps/server/src/routes/v1/monitors/put.test.tsindex df274a946..23bab7ccc 100644--- a/apps/server/src/routes/v1/monitors/put.test.ts+++ b/apps/server/src/routes/v1/monitors/put.test.ts@@ -1,8 +1,9 @@import { expect, test } from "bun:test";import { app } from "@/index";+import { MonitorSchema } from "./schema";-test("Partial update the monitor", async () => {+test("update the monitor", async () => {const res = await app.request("/v1/monitor/1", {method: "PUT",headers: {@@ -13,12 +14,14 @@ test("Partial update the monitor", async () => {name: "New Name",}),});-- expect(res.status).toBe(400);+ const data = await res.json();+ const monitor = MonitorSchema.parse(data);+ expect(res.status).toBe(200);+ expect(monitor.name).toBe("New Name");});test("invalid monitor id should return 404", async () => {- const res = await app.request("/v1/page/404", {+ const res = await app.request("/v1/monitor/404", {method: "PUT",headers: {"x-openstatus-key": "1",@@ -33,7 +36,7 @@ test("invalid monitor id should return 404", async () => {});test("no auth key should return 401", async () => {- const res = await app.request("/v1/page/2", {+ const res = await app.request("/v1/monitor/2", {method: "PUT",headers: {"content-type": "application/json",diff --git a/apps/server/src/routes/v1/monitors/put.ts b/apps/server/src/routes/v1/monitors/put.tsindex 0c0fe1679..958367e31 100644--- a/apps/server/src/routes/v1/monitors/put.ts+++ b/apps/server/src/routes/v1/monitors/put.ts@@ -8,13 +8,8 @@ import { trackMiddleware } from "@/libs/middlewares";import { Events } from "@openstatus/analytics";import { serialize } from "@openstatus/assertions";import type { monitorsApi } from "./index";-import {- HTTPMonitorSchema,- MonitorSchema,- ParamsSchema,- TCPMonitorSchema,-} from "./schema";-import { getAssertionNew } from "./utils";+import { MonitorSchema, ParamsSchema } from "./schema";+import { getAssertions } from "./utils";const putRoute = createRoute({method: "put",@@ -28,7 +23,7 @@ const putRoute = createRoute({description: "The monitor to update",content: {"application/json": {- schema: HTTPMonitorSchema.or(TCPMonitorSchema),+ schema: MonitorSchema.omit({ id: true }).partial(),},},},@@ -53,7 +48,7 @@ export function registerPutMonitor(api: typeof monitorsApi) {const { id } = c.req.valid("param");const input = c.req.valid("json");- if (input.frequency && !limits.periodicity.includes(input.frequency)) {+ if (input.periodicity && !limits.periodicity.includes(input.periodicity)) {throw new OpenStatusApiError({code: "PAYMENT_REQUIRED",message: "Upgrade for more periodicity",@@ -90,77 +85,33 @@ export function registerPutMonitor(api: typeof monitorsApi) {});}- if (_monitor.jobType === "http") {- const data = HTTPMonitorSchema.parse(input);- const { request, regions, assertions, otelHeaders, ...rest } = data;-- const headers = data?.request?.headers- ? Object.entries(data?.request.headers)- : undefined;-- const otelHeadersEntries = otelHeaders- ? Object.entries(otelHeaders).map(([key, value]) => ({- key: key,- value: value,- }))- : undefined;- const headersEntries = headers- ? headers.map(([key, value]) => ({ key: key, value: value }))- : undefined;-- const assert = assertions ? getAssertionNew(assertions) : [];-- const _newMonitor = await db- .update(monitor)- .set({- ...rest,- regions: regions.join(","),- headers: headersEntries ? JSON.stringify(headersEntries) : undefined,- otelHeaders: otelHeadersEntries- ? JSON.stringify(otelHeadersEntries)- : undefined,- assertions: assert.length > 0 ? serialize(assert) : undefined,- timeout: input.timeout || 45000,- updatedAt: new Date(),- })- .where(eq(monitor.id, Number(_monitor.id)))- .returning()- .get();- const r = MonitorSchema.parse(_newMonitor);- return c.json(r, 200);+ if (input.jobType && input.jobType !== _monitor.jobType) {+ throw new OpenStatusApiError({+ code: "BAD_REQUEST",+ message:+ "Cannot change jobType. Please delete and create a new monitor instead.",+ });}- if (_monitor.jobType === "tcp") {- const data = TCPMonitorSchema.parse(input);- const { request, regions, otelHeaders, ...rest } = data;-- const otelHeadersEntries = otelHeaders- ? Object.entries(otelHeaders).map(([key, value]) => ({- key: key,- value: value,- }))- : undefined;- const _newMonitor = await db- .update(monitor)- .set({- ...rest,- regions: regions.join(","),- otelHeaders: otelHeadersEntries- ? JSON.stringify(otelHeadersEntries)- : undefined,- timeout: input.timeout || 45000,- updatedAt: new Date(),- })- .where(eq(monitor.id, Number(_monitor.id)))- .returning()- .get();- const r = MonitorSchema.parse(_newMonitor);- return c.json(r, 200);- }+ const { headers, regions, assertions, ...rest } = input;++ const assert = assertions ? getAssertions(assertions) : [];++ const _newMonitor = await db+ .update(monitor)+ .set({+ ...rest,+ regions: regions ? regions.join(",") : undefined,+ headers: input.headers ? JSON.stringify(input.headers) : undefined,+ assertions: assert.length > 0 ? serialize(assert) : undefined,+ timeout: input.timeout || 45000,+ updatedAt: new Date(),+ })+ .where(eq(monitor.id, Number(_monitor.id)))+ .returning()+ .get();- throw new OpenStatusApiError({- code: "NOT_FOUND",- message: "Something went wrong",- });+ const data = MonitorSchema.parse(_newMonitor);+ return c.json(data, 200);});}diff --git a/apps/server/src/routes/v1/monitors/put_http.test.ts b/apps/server/src/routes/v1/monitors/put_http.test.tsnew file mode 100644index 000000000..ba452e6b8--- /dev/null+++ b/apps/server/src/routes/v1/monitors/put_http.test.ts@@ -0,0 +1,131 @@+import { expect, test } from "bun:test";++import { app } from "@/index";+import { MonitorSchema } from "./schema";++test("update the monitor", async () => {+ const res = await app.request("/v1/monitor/http/1", {+ method: "PUT",+ headers: {+ "x-openstatus-key": "1",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: "New Name",+ }),+ });++ expect(res.status).toBe(400);+});++test("invalid monitor id should return 404", async () => {+ const res = await app.request("/v1/monitor/http/404", {+ method: "PUT",+ headers: {+ "x-openstatus-key": "1",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ frequency: "10m",+ name: "OpenStatus",+ description: "OpenStatus website",+ regions: ["ams", "gru"],+ request: {+ url: "https://www.openstatus.dev",+ method: "POST",+ body: '{"hello":"world"}',+ headers: { "content-type": "application/json" },+ },+ active: true,+ public: true,+ assertions: [+ {+ kind: "statusCode",+ compare: "eq",+ target: 200,+ },+ { kind: "header", compare: "not_eq", key: "key", target: "value" },+ ],+ }),+ });++ expect(res.status).toBe(404);+});++test("Update a valid monitor", async () => {+ const res = await app.request("/v1/monitor/http", {+ method: "POST",+ headers: {+ "x-openstatus-key": "1",+ "content-type": "application/json",+ },+ body: JSON.stringify({+ frequency: "10m",+ name: "OpenStatus",+ description: "OpenStatus website",+ regions: ["ams", "gru"],+ request: {+ url: "https://www.openstatus.dev",+ method: "POST",+ body: '{"hello":"world"}',+ headers: { "content-type": "application/json" },+ },+ active: true,+ public: true,+ assertions: [+ {+ kind: "statusCode",+ compare: "eq",+ target: 200,+ },+ { kind: "header", compare: "not_eq", key: "key", target: "value" },+ ],+ }),+ });++ const result = MonitorSchema.parse(await res.json());++ expect(res.status).toBe(200);++ const updated = await app.request(`/v1/monitor/http/${result.id}`, {+ method: "PUT",+ headers: {+ "x-openstatus-key": "1",+ "content-type": "application/json",+ },+ body: JSON.stringify({+ frequency: "30m",+ name: "newName",+ description: "OpenStatus website",+ regions: ["ams", "gru"],+ request: {+ url: "https://www.openstatus.dev",+ method: "POST",+ body: '{"hello":"world"}',+ headers: { "content-type": "application/json" },+ },+ active: true,+ public: true,+ }),++ // expect(r.success).toBe(true);+ });+ const r = MonitorSchema.parse(await updated.json());+ expect(r.assertions?.length).toBe(0);+ expect(r.periodicity).toBe("30m");+ expect(r.name).toBe("newName");+});++test("no auth key should return 401", async () => {+ const res = await app.request("/v1/monitor/http/2", {+ method: "PUT",+ headers: {+ "content-type": "application/json",+ },+ body: JSON.stringify({+ /* */+ }),+ });++ expect(res.status).toBe(401);+});diff --git a/apps/server/src/routes/v1/monitors/put_http.ts b/apps/server/src/routes/v1/monitors/put_http.tsnew file mode 100644index 000000000..f0607182c--- /dev/null+++ b/apps/server/src/routes/v1/monitors/put_http.ts@@ -0,0 +1,136 @@+import { createRoute } from "@hono/zod-openapi";++import { and, db, eq, isNull } from "@openstatus/db";+import { monitor } from "@openstatus/db/src/schema";++import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";+import { trackMiddleware } from "@/libs/middlewares";+import { Events } from "@openstatus/analytics";+import { serialize } from "@openstatus/assertions";+import type { monitorsApi } from "./index";+import { HTTPMonitorSchema, MonitorSchema, ParamsSchema } from "./schema";+import { getAssertionNew } from "./utils";++const putRoute = createRoute({+ method: "put",+ tags: ["monitor"],+ summary: "Update an HTTP monitor",+ path: "/http/{id}",+ middleware: [trackMiddleware(Events.UpdateMonitor)],+ request: {+ params: ParamsSchema,+ body: {+ description: "The monitor to update",+ content: {+ "application/json": {+ schema: HTTPMonitorSchema,+ },+ },+ },+ },+ responses: {+ 200: {+ content: {+ "application/json": {+ schema: MonitorSchema,+ },+ },+ description: "Update a monitor",+ },+ ...openApiErrorResponses,+ },+});++export function registerPutHTTPMonitor(api: typeof monitorsApi) {+ return api.openapi(putRoute, async (c) => {+ const workspaceId = c.get("workspace").id;+ const limits = c.get("workspace").limits;+ const { id } = c.req.valid("param");+ const input = c.req.valid("json");++ if (input.frequency && !limits.periodicity.includes(input.frequency)) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for more periodicity",+ });+ }++ if (input.regions) {+ for (const region of input.regions) {+ if (!limits.regions.includes(region)) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for more regions",+ });+ }+ }+ }++ const _monitor = await db+ .select()+ .from(monitor)+ .where(+ and(+ eq(monitor.id, Number(id)),+ isNull(monitor.deletedAt),+ eq(monitor.workspaceId, workspaceId),+ ),+ )+ .get();++ if (!_monitor) {+ throw new OpenStatusApiError({+ code: "NOT_FOUND",+ message: `Monitor ${id} not found`,+ });+ }++ if (_monitor.jobType !== "http") {+ throw new OpenStatusApiError({+ code: "NOT_FOUND",+ message: `Monitor ${id} not found`,+ });+ }++ const { request, regions, assertions, otelHeaders, ...rest } = input;++ const headers = input.request.headers+ ? Object.entries(input.request.headers)+ : undefined;++ const otelHeadersEntries = otelHeaders+ ? Object.entries(otelHeaders).map(([key, value]) => ({+ key: key,+ value: value,+ }))+ : undefined;+ const headersEntries = headers+ ? headers.map(([key, value]) => ({ key: key, value: value }))+ : undefined;+ const assert = assertions ? getAssertionNew(assertions) : [];++ const _newMonitor = await db+ .update(monitor)+ .set({+ ...rest,+ periodicity: input.frequency,+ url: input.request.url,+ method: input.request.method,+ body: input.request.body,+ regions: regions ? regions.join(",") : undefined,+ headers: headersEntries ? JSON.stringify(headersEntries) : undefined,+ otelHeaders: otelHeadersEntries+ ? JSON.stringify(otelHeadersEntries)+ : undefined,+ assertions: assert ? serialize(assert) : "",+ timeout: input.timeout || 45000,+ updatedAt: new Date(),+ })+ .where(eq(monitor.id, Number(_monitor.id)))+ .returning()+ .get();++ const data = MonitorSchema.parse(_newMonitor);+ return c.json(data, 200);+ });+}diff --git a/apps/server/src/routes/v1/monitors/put_tcp.test.ts b/apps/server/src/routes/v1/monitors/put_tcp.test.tsnew file mode 100644index 000000000..fa1c2f351--- /dev/null+++ b/apps/server/src/routes/v1/monitors/put_tcp.test.ts@@ -0,0 +1,56 @@+import { expect, test } from "bun:test";++import { app } from "@/index";++test("update the monitor", async () => {+ const res = await app.request("/v1/monitor/tcp/1", {+ method: "PUT",+ headers: {+ "x-openstatus-key": "1",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: "New Name",+ }),+ });++ expect(res.status).toBe(400);+});++test("invalid monitor id should return 404", async () => {+ const res = await app.request("/v1/monitor/tcp/404", {+ method: "PUT",+ headers: {+ "x-openstatus-key": "1",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ frequency: "10m",+ name: "OpenStatus",+ description: "OpenStatus website",+ regions: ["ams", "gru"],+ request: {+ host: "openstatus.dev",+ port: 443,+ },+ active: true,+ public: true,+ }),+ });++ expect(res.status).toBe(404);+});++test("no auth key should return 401", async () => {+ const res = await app.request("/v1/monitor/tcp/2", {+ method: "PUT",+ headers: {+ "content-type": "application/json",+ },+ body: JSON.stringify({+ /* */+ }),+ });++ expect(res.status).toBe(401);+});diff --git a/apps/server/src/routes/v1/monitors/put_tcp.ts b/apps/server/src/routes/v1/monitors/put_tcp.tsnew file mode 100644index 000000000..c608dbc5b--- /dev/null+++ b/apps/server/src/routes/v1/monitors/put_tcp.ts@@ -0,0 +1,122 @@+import { createRoute } from "@hono/zod-openapi";++import { and, db, eq, isNull } from "@openstatus/db";+import { monitor } from "@openstatus/db/src/schema";++import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";+import { trackMiddleware } from "@/libs/middlewares";+import { Events } from "@openstatus/analytics";+import type { monitorsApi } from "./index";+import { MonitorSchema, ParamsSchema, TCPMonitorSchema } from "./schema";++const putRoute = createRoute({+ method: "put",+ tags: ["monitor"],+ summary: "Update an TCP monitor",+ path: "/tcp/{id}",+ middleware: [trackMiddleware(Events.UpdateMonitor)],+ request: {+ params: ParamsSchema,+ body: {+ description: "The monitor to update",+ content: {+ "application/json": {+ schema: TCPMonitorSchema,+ },+ },+ },+ },+ responses: {+ 200: {+ content: {+ "application/json": {+ schema: MonitorSchema,+ },+ },+ description: "Update a monitor",+ },+ ...openApiErrorResponses,+ },+});++export function registerPutTCPMonitor(api: typeof monitorsApi) {+ return api.openapi(putRoute, async (c) => {+ const workspaceId = c.get("workspace").id;+ const limits = c.get("workspace").limits;+ const { id } = c.req.valid("param");+ const input = c.req.valid("json");++ if (input.frequency && !limits.periodicity.includes(input.frequency)) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for more periodicity",+ });+ }++ if (input.regions) {+ for (const region of input.regions) {+ if (!limits.regions.includes(region)) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for more regions",+ });+ }+ }+ }++ const _monitor = await db+ .select()+ .from(monitor)+ .where(+ and(+ eq(monitor.id, Number(id)),+ isNull(monitor.deletedAt),+ eq(monitor.workspaceId, workspaceId),+ ),+ )+ .get();++ if (!_monitor) {+ throw new OpenStatusApiError({+ code: "NOT_FOUND",+ message: `Monitor ${id} not found`,+ });+ }++ if (_monitor.jobType !== "tcp") {+ throw new OpenStatusApiError({+ code: "NOT_FOUND",+ message: `Monitor ${id} not found`,+ });+ }++ const { request, regions, otelHeaders, ...rest } = input;++ const otelHeadersEntries = otelHeaders+ ? Object.entries(otelHeaders).map(([key, value]) => ({+ key: key,+ value: value,+ }))+ : undefined;++ const _newMonitor = await db+ .update(monitor)+ .set({+ ...rest,+ periodicity: input.frequency,+ url: `${request.host}:${request.port}`,+ regions: regions ? regions.join(",") : undefined,+ otelHeaders: otelHeadersEntries+ ? JSON.stringify(otelHeadersEntries)+ : undefined,+ timeout: input.timeout || 45000,+ updatedAt: new Date(),+ })+ .where(eq(monitor.id, Number(_monitor.id)))+ .returning()+ .get();++ const data = MonitorSchema.parse(_newMonitor);+ return c.json(data, 200);+ });+}