Skip to content

Commit

Permalink
🐛 headers and checker (#877)
Browse files Browse the repository at this point in the history
  • Loading branch information
thibaultleouay authored Jun 15, 2024
1 parent d59c4ea commit 30c7961
Show file tree
Hide file tree
Showing 29 changed files with 152 additions and 104 deletions.
34 changes: 31 additions & 3 deletions apps/checker/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@ import (

type statusCode int

// We should export it
type PingResponse struct {
RequestId int64 `json:"requestId,omitempty"`
WorkspaceId int64 `json:"workspaceId,omitempty"`
Status int `json:"status,omitempty"`
Latency int64 `json:"latency"`
Body string `json:"body,omitempty"`
Headers string `json:"headers,omitempty"`
Time int64 `json:"time"`
Timing checker.Timing `json:"timing"`
Region string `json:"region"`
}

func (s statusCode) IsSuccessful() bool {
return s >= 200 && s < 300
}
Expand Down Expand Up @@ -263,10 +276,25 @@ func main() {

r.Region = flyRegion

headersAsString, err := json.Marshal(r.Headers)
if err != nil {
return nil
}

tbData := PingResponse{
RequestId: req.RequestId,
WorkspaceId: req.WorkspaceId,
Status: r.Status,
Latency: r.Latency,
Body: r.Body,
Headers: string(headersAsString),
Time: r.Time,
Timing: r.Timing,
Region: r.Region,
}

res = r
res.RequestId = req.RequestId
res.WorkspaceId = req.WorkspaceId
if err := tinybirdClient.SendEvent(ctx, res, dataSourceName); err != nil {
if err := tinybirdClient.SendEvent(ctx, tbData, dataSourceName); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
}
return nil
Expand Down
4 changes: 3 additions & 1 deletion apps/checker/request/request.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package request

import "encoding/json"
import (
"encoding/json"
)

type AssertionType string

Expand Down
20 changes: 10 additions & 10 deletions apps/server/src/v1/check/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,40 +107,40 @@ export function registerPostCheck(api: typeof checkAPI) {
if (aggregated) {
// This is ugly
const dnsArray = fulfilledRequest.map(
(r) => r.timing.dnsDone - r.timing.dnsStart,
(r) => r.timing.dnsDone - r.timing.dnsStart
);
const connectArray = fulfilledRequest.map(
(r) => r.timing.connectDone - r.timing.connectStart,
(r) => r.timing.connectDone - r.timing.connectStart
);
const tlsArray = fulfilledRequest.map(
(r) => r.timing.tlsHandshakeDone - r.timing.tlsHandshakeStart,
(r) => r.timing.tlsHandshakeDone - r.timing.tlsHandshakeStart
);
const firstArray = fulfilledRequest.map(
(r) => r.timing.firstByteDone - r.timing.firstByteStart,
(r) => r.timing.firstByteDone - r.timing.firstByteStart
);
const transferArray = fulfilledRequest.map(
(r) => r.timing.transferDone - r.timing.transferStart,
(r) => r.timing.transferDone - r.timing.transferStart
);
const latencyArray = fulfilledRequest.map((r) => r.latency);

const dnsPercentile = percentile([50, 75, 95, 99], dnsArray) as number[];
const connectPercentile = percentile(
[50, 75, 95, 99],
connectArray,
connectArray
) as number[];
const tlsPercentile = percentile([50, 75, 95, 99], tlsArray) as number[];
const firstPercentile = percentile(
[50, 75, 95, 99],
firstArray,
firstArray
) as number[];

const transferPercentile = percentile(
[50, 75, 95, 99],
transferArray,
transferArray
) as number[];
const latencyPercentile = percentile(
[50, 75, 95, 99],
latencyArray,
latencyArray
) as number[];

const aggregatedDNS = AggregatedResponseSchema.parse({
Expand Down Expand Up @@ -212,6 +212,6 @@ export function registerPostCheck(api: typeof checkAPI) {
aggregated: aggregatedResponse ? aggregatedResponse : undefined,
});

return c.json(responseResult);
return c.json(responseResult, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/incidents/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ export function registerGetIncident(app: typeof incidentsApi) {
.where(
and(
eq(incidentTable.workspaceId, Number(workspaceId)),
eq(incidentTable.id, Number(id)),
),
eq(incidentTable.id, Number(id))
)
)
.get();

Expand All @@ -51,6 +51,6 @@ export function registerGetIncident(app: typeof incidentsApi) {

const data = IncidentSchema.parse(_incident);

return c.json(data);
return c.json(data, 200);
});
}
2 changes: 1 addition & 1 deletion apps/server/src/v1/incidents/get_all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ export function registerGetAllIncidents(app: typeof incidentsApi) {
}

const returnValues = z.array(IncidentSchema).parse(_incidents); // TODO: think of using safeParse with SchemaError.fromZod
return c.json(returnValues);
return c.json(returnValues, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/incidents/put.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export function registerPutIncident(app: typeof incidentsApi) {
.where(
and(
eq(incidentTable.id, Number(id)),
eq(incidentTable.workspaceId, Number(workspaceId)),
),
eq(incidentTable.workspaceId, Number(workspaceId))
)
)
.get();

Expand All @@ -81,6 +81,6 @@ export function registerPutIncident(app: typeof incidentsApi) {

const data = IncidentSchema.parse(_newIncident);

return c.json(data);
return c.json(data, 200);
});
}
15 changes: 15 additions & 0 deletions apps/server/src/v1/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { expect, test } from "bun:test";

import { api } from "./index";

test("Middleware error should return json", async () => {
const res = await api.request("/status_report/1", {});

const json = await res.json();
expect(res.status).toBe(401);
expect(json).toMatchObject({
code: "UNAUTHORIZED",
message: "Unauthorized",
docs: "https://docs.openstatus.dev/api-references/errors/code/UNAUTHORIZED",
});
});
14 changes: 8 additions & 6 deletions apps/server/src/v1/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,24 @@ import { db, eq } from "@openstatus/db";
import { workspace } from "@openstatus/db/src/schema";
import { getPlanConfig } from "@openstatus/plans";
import type { Variables } from "./index";
import { HTTPException } from "hono/http-exception";

export async function middleware(
c: Context<{ Variables: Variables }, "/*">,
next: Next,
next: Next
) {
const key = c.req.header("x-openstatus-key");
if (!key) return c.text("Unauthorized", 401);
if (!key) throw new HTTPException(401, { message: "Unauthorized" });

const { error, result } =
process.env.NODE_ENV === "production"
? await verifyKey(key)
: { result: { valid: true, ownerId: "1" }, error: null };

if (error) return c.text("Internal Server Error", 500);
if (!result.valid) return c.text("Unauthorized", 401);
if (!result.ownerId) return c.text("Unauthorized", 401);
if (error) throw new HTTPException(500, { message: error.message });
if (!result.valid) throw new HTTPException(401, { message: "Unauthorized" });
if (!result.ownerId)
throw new HTTPException(401, { message: "Unauthorized" });

const _workspace = await db
.select()
Expand All @@ -30,7 +32,7 @@ export async function middleware(

if (!_workspace) {
console.error("Workspace not found");
return c.text("Unauthorized", 401);
throw new HTTPException(401, { message: "Unauthorized" });
}

c.set("workspacePlan", getPlanConfig(_workspace.plan));
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/v1/monitors/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ export function registerDeleteMonitor(app: typeof monitorsApi) {

// FIXME: Remove all relations of the monitor from all notifications, pages,....

return c.json({});
return c.json({}, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/monitors/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ export function registerGetMonitor(api: typeof monitorsApi) {
and(
eq(monitor.id, Number(id)),
eq(monitor.workspaceId, Number(workspaceId)),
isNull(monitor.deletedAt),
),
isNull(monitor.deletedAt)
)
)
.get();

Expand All @@ -52,6 +52,6 @@ export function registerGetMonitor(api: typeof monitorsApi) {

const data = MonitorSchema.parse(_monitor);

return c.json(data);
return c.json(data, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/monitors/get_all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export function registerGetAllMonitors(app: typeof monitorsApi) {
.where(
and(
eq(monitor.workspaceId, Number(workspaceId)),
isNull(monitor.deletedAt),
),
isNull(monitor.deletedAt)
)
)
.all();

Expand All @@ -48,6 +48,6 @@ export function registerGetAllMonitors(app: typeof monitorsApi) {

const data = z.array(MonitorSchema).parse(_monitors);

return c.json(data);
return c.json(data, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/monitors/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ export function registerPostMonitor(api: typeof monitorsApi) {
.where(
and(
eq(monitor.workspaceId, Number(workspaceId)),
isNull(monitor.deletedAt),
),
isNull(monitor.deletedAt)
)
)
.all()
)[0].count;
Expand Down Expand Up @@ -97,6 +97,6 @@ export function registerPostMonitor(api: typeof monitorsApi) {

const data = MonitorSchema.parse(_newMonitor);

return c.json(data);
return c.json(data, 200);
});
}
2 changes: 1 addition & 1 deletion apps/server/src/v1/monitors/put.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,6 @@ export function registerPutMonitor(api: typeof monitorsApi) {

const data = MonitorSchema.parse(_newMonitor);

return c.json(data);
return c.json(data, 200);
});
}
15 changes: 8 additions & 7 deletions apps/server/src/v1/monitors/summary/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ export function registerGetMonitorSummary(api: typeof monitorsApi) {
and(
eq(monitor.id, Number(id)),
eq(monitor.workspaceId, Number(workspaceId)),
isNull(monitor.deletedAt),
),
isNull(monitor.deletedAt)
)
)
.get();

Expand All @@ -75,13 +75,11 @@ export function registerGetMonitorSummary(api: typeof monitorsApi) {
}

const cache = await redis.get<z.infer<typeof dailyStatsSchemaArray>>(
`${id}-daily-stats`,
`${id}-daily-stats`
);
if (cache) {
console.log("fetching from cache");
return c.json({
data: cache,
});
return c.json({ data: cache }, 200);
}

// FIXME: we should use the OSTinybird client
Expand All @@ -90,8 +88,11 @@ export function registerGetMonitorSummary(api: typeof monitorsApi) {
monitorId: id,
});

if (res === undefined) {
throw new HTTPException(404, { message: "Not Found" });
}
await redis.set(`${id}-daily-stats`, res, { ex: 600 });

return c.json({ data: res });
return c.json({ data: res }, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/notifications/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ export function registerGetNotification(api: typeof notificationsApi) {
.where(
and(
eq(page.workspaceId, Number(workspaceId)),
eq(notification.id, Number(id)),
),
eq(notification.id, Number(id))
)
)
.get();

Expand All @@ -66,6 +66,6 @@ export function registerGetNotification(api: typeof notificationsApi) {
monitors,
});

return c.json(data);
return c.json(data, 200);
});
}
2 changes: 1 addition & 1 deletion apps/server/src/v1/notifications/get_all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,6 @@ export function registerGetAllNotifications(app: typeof notificationsApi) {
data.push(p);
}

return c.json(data);
return c.json(data, 200);
});
}
6 changes: 3 additions & 3 deletions apps/server/src/v1/notifications/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ export function registerPostNotification(api: typeof notificationsApi) {
and(
inArray(monitor.id, monitors),
eq(monitor.workspaceId, Number(workspaceId)),
isNull(monitor.deletedAt),
),
isNull(monitor.deletedAt)
)
)
.all();

Expand Down Expand Up @@ -113,6 +113,6 @@ export function registerPostNotification(api: typeof notificationsApi) {
monitors,
payload: _payload,
});
return c.json(data);
return c.json(data, 200);
});
}
Loading

0 comments on commit 30c7961

Please sign in to comment.