Skip to content

Open-source status page, incident response and uptime monitoring

Update cli endpoint (#1073)

Thibault Le Ouayd6334213dd03
diff --git a/apps/checker/handlers/checker.go b/apps/checker/handlers/checker.go
index 40807e5ae..647022736 100644
--- a/apps/checker/handlers/checker.go
+++ b/apps/checker/handlers/checker.go
@@ -88,6 +88,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
}
var called int
+ var result checker.Response
op := func() error {
called++
@@ -174,6 +175,9 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
return fmt.Errorf("unable to ping: %v with status %v", res, res.Status)
}
+ result = res
+ result.Region = h.Region
+
// it's in error if not successful
if isSuccessfull {
data.Error = 0
@@ -181,6 +185,7 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
data.Body = ""
} else {
data.Error = 1
+ result.Error = "Error"
}
data.Assertions = assertionAsString
@@ -302,5 +307,5 @@ func (h Handler) HTTPCheckerHandler(c *gin.Context) {
}
- c.JSON(http.StatusOK, gin.H{"message": "ok"})
+ c.JSON(http.StatusOK, result)
}
diff --git a/apps/checker/handlers/tcp.go b/apps/checker/handlers/tcp.go
index 4d238224b..670d75ee8 100644
--- a/apps/checker/handlers/tcp.go
+++ b/apps/checker/handlers/tcp.go
@@ -95,6 +95,7 @@ func (h Handler) TCPHandler(c *gin.Context) {
}
var called int
+ var response TCPResponse
op := func() error {
called++
@@ -125,6 +126,16 @@ func (h Handler) TCPHandler(c *gin.Context) {
URI: req.URL,
}
+ response = TCPResponse{
+ Timestamp: res.TCPStart,
+ Timing: checker.TCPResponseTiming{
+ TCPStart: res.TCPStart,
+ TCPDone: res.TCPDone,
+ },
+ Latency: latency,
+ Region: h.Region,
+ }
+
if req.Status == "active" && req.DegradedAfter > 0 && latency > req.DegradedAfter {
checker.UpdateStatus(ctx, checker.UpdateData{
MonitorId: req.MonitorID,
@@ -196,7 +207,7 @@ func (h Handler) TCPHandler(c *gin.Context) {
}
}
- c.JSON(http.StatusOK, gin.H{"message": "ok"})
+ c.JSON(http.StatusOK, response)
}
func (h Handler) TCPHandlerRegion(c *gin.Context) {
diff --git a/apps/server/src/v1/monitors/results/get.ts b/apps/server/src/v1/monitors/results/get.ts
index 78b7ebe13..2efb42026 100644
--- a/apps/server/src/v1/monitors/results/get.ts
+++ b/apps/server/src/v1/monitors/results/get.ts
@@ -9,23 +9,10 @@ import { HTTPException } from "hono/http-exception";
import { env } from "../../../env";
import { openApiErrorResponses } from "../../../libs/errors/openapi-error-responses";
import type { monitorsApi } from "../index";
-import { ParamsSchema } from "../schema";
+import { ParamsSchema, ResultRun } from "../schema";
const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-const timingSchema = z.object({
- dnsStart: z.number(),
- dnsDone: z.number(),
- connectStart: z.number(),
- connectDone: z.number(),
- tlsHandshakeStart: z.number(),
- tlsHandshakeDone: z.number(),
- firstByteStart: z.number(),
- firstByteDone: z.number(),
- transferStart: z.number(),
- transferDone: z.number(),
-});
-
const getMonitorStats = createRoute({
method: "get",
tags: ["monitor"],
@@ -42,29 +29,7 @@ const getMonitorStats = createRoute({
200: {
content: {
"application/json": {
- schema: z.array(
- z.object({
- latency: z.number().int(), // in ms
- statusCode: z.number().int().nullable().default(null),
- monitorId: z.string().default(""),
- url: z.string().url().optional(),
- error: z
- .number()
- .default(0)
- .transform((val) => val !== 0),
- region: z.enum(flyRegions),
- timestamp: z.number().int().optional(),
- message: z.string().nullable().optional(),
- timing: z
- .preprocess((val) => {
- if (!val) return null;
- const value = timingSchema.safeParse(JSON.parse(String(val)));
- if (value.success) return value.data;
- return null;
- }, timingSchema.nullable())
- .optional(),
- }),
- ),
+ schema: z.array(ResultRun),
},
},
description: "All the metrics for the monitor",
diff --git a/apps/server/src/v1/monitors/run/post.ts b/apps/server/src/v1/monitors/run/post.ts
new file mode 100644
index 000000000..412401186
--- /dev/null
+++ b/apps/server/src/v1/monitors/run/post.ts
@@ -0,0 +1,196 @@
+import { createRoute, z } from "@hono/zod-openapi";
+import { and, eq, gte, isNull, sql } from "@openstatus/db";
+import { db } from "@openstatus/db/src/db";
+import { monitorRun } from "@openstatus/db/src/schema";
+import { monitorStatusTable } from "@openstatus/db/src/schema/monitor_status/monitor_status";
+import { selectMonitorStatusSchema } from "@openstatus/db/src/schema/monitor_status/validation";
+import { monitor } from "@openstatus/db/src/schema/monitors/monitor";
+import { selectMonitorSchema } from "@openstatus/db/src/schema/monitors/validation";
+import { getLimit } from "@openstatus/db/src/schema/plan/utils";
+import type { httpPayloadSchema, tpcPayloadSchema } from "@openstatus/utils";
+import { HTTPException } from "hono/http-exception";
+import type { monitorsApi } from "..";
+import { env } from "../../../env";
+import { openApiErrorResponses } from "../../../libs/errors/openapi-error-responses";
+import { HTTPTriggerResult, ParamsSchema } from "../schema";
+
+const triggerMonitor = createRoute({
+ method: "post",
+ tags: ["monitor"],
+ description: "Run a monitor check",
+ path: "/:id/run",
+ request: {
+ params: ParamsSchema,
+ },
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: z.array(HTTPTriggerResult),
+ },
+ },
+ description: "All the historical metrics",
+ },
+ ...openApiErrorResponses,
+ },
+});
+
+export function registerTriggerMonitor(api: typeof monitorsApi) {
+ return api.openapi(triggerMonitor, async (c) => {
+ const workspaceId = c.get("workspaceId");
+ const { id } = c.req.valid("param");
+ const limits = c.get("limits");
+
+ const lastMonth = new Date().setMonth(new Date().getMonth() - 1);
+
+ const count = (
+ await db
+ .select({ count: sql<number>`count(*)` })
+ .from(monitorRun)
+ .where(
+ and(
+ eq(monitorRun.workspaceId, Number(workspaceId)),
+ gte(monitorRun.createdAt, new Date(lastMonth)),
+ ),
+ )
+ .all()
+ )[0].count;
+
+ if (count >= getLimit(limits, "synthetic-checks")) {
+ throw new HTTPException(403, {
+ message: "Upgrade for more checks",
+ });
+ }
+
+ const monitorData = await db
+ .select()
+ .from(monitor)
+ .where(
+ and(
+ eq(monitor.id, Number(id)),
+ eq(monitor.workspaceId, Number(workspaceId)),
+ isNull(monitor.deletedAt),
+ ),
+ )
+ .get();
+
+ if (!monitorData) {
+ throw new HTTPException(404, { message: "Not Found" });
+ }
+
+ const parseMonitor = selectMonitorSchema.safeParse(monitorData);
+
+ if (!parseMonitor.success) {
+ throw new HTTPException(400, { message: "Something went wrong" });
+ }
+
+ const row = parseMonitor.data;
+
+ // Maybe later overwrite the region
+
+ const monitorStatusData = await db
+ .select()
+ .from(monitorStatusTable)
+ .where(eq(monitorStatusTable.monitorId, monitorData.id))
+ .all();
+
+ const monitorStatus = z
+ .array(selectMonitorStatusSchema)
+ .safeParse(monitorStatusData);
+ if (!monitorStatus.success) {
+ throw new HTTPException(400, { message: "Something went wrong" });
+ }
+
+ const timestamp = Date.now();
+
+ const newRun = await db
+ .insert(monitorRun)
+ .values({
+ monitorId: row.id,
+ workspaceId: row.workspaceId,
+ runnedAt: new Date(timestamp),
+ })
+ .returning();
+
+ if (!newRun[0]) {
+ throw new HTTPException(400, { message: "Something went wrong" });
+ }
+
+ const allResult = [];
+ for (const region of parseMonitor.data.regions) {
+ const status =
+ monitorStatus.data.find((m) => region === m.region)?.status || "active";
+ // Trigger the monitor
+
+ let payload:
+ | z.infer<typeof httpPayloadSchema>
+ | z.infer<typeof tpcPayloadSchema>
+ | null = null;
+ //
+ if (row.jobType === "http") {
+ payload = {
+ workspaceId: String(row.workspaceId),
+ monitorId: String(row.id),
+ url: row.url,
+ method: row.method || "GET",
+ cronTimestamp: timestamp,
+ body: row.body,
+ headers: row.headers,
+ status: status,
+ assertions: row.assertions ? JSON.parse(row.assertions) : null,
+ degradedAfter: row.degradedAfter,
+ timeout: row.timeout,
+ trigger: "api",
+ };
+ }
+ if (row.jobType === "tcp") {
+ payload = {
+ workspaceId: String(row.workspaceId),
+ monitorId: String(row.id),
+ uri: row.url,
+ status: status,
+ assertions: row.assertions ? JSON.parse(row.assertions) : null,
+ cronTimestamp: timestamp,
+ degradedAfter: row.degradedAfter,
+ timeout: row.timeout,
+ trigger: "api",
+ };
+ }
+
+ if (!payload) {
+ throw new Error("Invalid jobType");
+ }
+ const url = generateUrl({ row });
+ const result = fetch(url, {
+ headers: {
+ "Content-Type": "application/json",
+ "fly-prefer-region": region, // Specify the region you want the request to be sent to
+ Authorization: `Basic ${env.CRON_SECRET}`,
+ },
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ allResult.push(result);
+ }
+
+ const result = await Promise.all(allResult);
+ const data = z.array(HTTPTriggerResult).safeParse(result);
+
+ if (!data.success) {
+ throw new HTTPException(400, { message: "Something went wrong" });
+ }
+
+ return c.json(data.data, 200);
+ });
+}
+
+function generateUrl({ row }: { row: z.infer<typeof selectMonitorSchema> }) {
+ switch (row.jobType) {
+ case "http":
+ return `https://openstatus-checker.fly.dev/checker/http?monitor_id=${row.id}&trigger=api`;
+ case "tcp":
+ return `https://openstatus-checker.fly.dev/checker/tcp?monitor_id=${row.id}&trigger=api`;
+ default:
+ throw new Error("Invalid jobType");
+ }
+}
diff --git a/apps/server/src/v1/monitors/schema.ts b/apps/server/src/v1/monitors/schema.ts
index 7a1bf15ae..c8a9bb017 100644
--- a/apps/server/src/v1/monitors/schema.ts
+++ b/apps/server/src/v1/monitors/schema.ts
@@ -219,3 +219,48 @@ export const MonitorSchema = z
});
export type MonitorSchema = z.infer<typeof MonitorSchema>;
+
+const timingSchema = z.object({
+ dnsStart: z.number(),
+ dnsDone: z.number(),
+ connectStart: z.number(),
+ connectDone: z.number(),
+ tlsHandshakeStart: z.number(),
+ tlsHandshakeDone: z.number(),
+ firstByteStart: z.number(),
+ firstByteDone: z.number(),
+ transferStart: z.number(),
+ transferDone: z.number(),
+});
+
+export const HTTPTriggerResult = z.object({
+ status: z.number(),
+ latency: z.number(),
+ headers: z.record(z.string()),
+ timestamp: z.number(),
+ timing: timingSchema,
+ body: z.string().optional().nullable(),
+ error: z.string().optional().nullable(),
+});
+
+export const ResultRun = z.object({
+ latency: z.number().int(), // in ms
+ statusCode: z.number().int().nullable().default(null),
+ monitorId: z.string().default(""),
+ url: z.string().url().optional(),
+ error: z
+ .number()
+ .default(0)
+ .transform((val) => val !== 0),
+ region: z.enum(flyRegions),
+ timestamp: z.number().int().optional(),
+ message: z.string().nullable().optional(),
+ timing: z
+ .preprocess((val) => {
+ if (!val) return null;
+ const value = timingSchema.safeParse(JSON.parse(String(val)));
+ if (value.success) return value.data;
+ return null;
+ }, timingSchema.nullable())
+ .optional(),
+});