Repository navigation
Expand file tree
/
Copy pathpost.ts
More file actions
228 lines (197 loc) · 6.24 KB
/
Copy pathpost.ts
File metadata and controls
228 lines (197 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { createRoute, type z } from "@hono/zod-openapi";
import { getLogger } from "@logtape/logtape";
import { env } from "@/env";
import { openApiErrorResponses } from "@/libs/errors";
import { db } from "@openstatus/db";
import { check } from "@openstatus/db/src/schema/check";
import percentile from "percentile";
import type { checkApi } from "../index";
const logger = getLogger("api-server");
import {
AggregatedResponseSchema,
AggregatedResult,
CheckPostResponseSchema,
CheckSchema,
ResponseSchema,
} from "./schema";
function isSelfHost() {
return process.env.SELF_HOST === "true";
}
function getCheckerBaseUrl() {
return (process.env.CHECKER_BASE_URL || "http://checker:8080").replace(
/\/$/,
"",
);
}
function getCheckerRegion(region: string) {
if (!isSelfHost()) {
return region;
}
return process.env.CHECKER_REGION || "ams";
}
const postRoute = createRoute({
method: "post",
tags: ["check"],
summary: "Run a single check",
path: "/http",
request: {
body: {
description: "The run request to create",
content: {
"application/json": {
schema: CheckSchema,
},
},
},
},
responses: {
200: {
content: {
"application/json": {
schema: CheckPostResponseSchema,
},
},
description: "Return a run result",
},
...openApiErrorResponses,
},
});
export function registerHTTPPostCheck(api: typeof checkApi) {
return api.openapi(postRoute, async (c) => {
const data = c.req.valid("json");
const workspaceId = c.get("workspace").id;
const input = c.req.valid("json");
const { headers, regions, runCount, aggregated, ...rest } = data;
const newCheck = await db
.insert(check)
.values({
workspaceId: workspaceId,
regions: regions.join(","),
countRequests: runCount,
...rest,
})
.returning()
.get();
const result = [];
for (let count = 0; count < input.runCount; count++) {
const currentFetch = [];
for (const region of input.regions) {
const targetRegion = getCheckerRegion(region);
const targetUrl = isSelfHost()
? `${getCheckerBaseUrl()}/ping/${targetRegion}`
: `https://openstatus-checker.fly.dev/ping/${targetRegion}`;
const r = fetch(targetUrl, {
headers: {
Authorization: `Basic ${env.CRON_SECRET}`,
"Content-Type": "application/json",
...(isSelfHost() ? {} : { "fly-prefer-region": targetRegion }),
},
method: "POST",
body: JSON.stringify({
requestId: newCheck.id,
workspaceId: workspaceId,
url: input.url,
method: input.method,
headers: input.headers?.reduce((acc, { key, value }) => {
if (!key) return acc; // key === "" is an invalid header
return {
// biome-ignore lint/performance/noAccumulatingSpread: <explanation>
...acc,
[key]: value,
};
}, {}),
body: input.body ? input.body : undefined,
}),
});
currentFetch.push(r);
}
const allResults = await Promise.allSettled(currentFetch);
result.push(...allResults);
}
const fulfilledRequest: z.infer<typeof ResponseSchema>[] = [];
const filteredResult = result.filter((r) => r.status === "fulfilled");
for await (const r of filteredResult) {
if (r.status !== "fulfilled") throw new Error("No value");
const json = await r.value.json();
const parsed = ResponseSchema.safeParse(json);
if (!parsed.success) {
logger.error("Failed to parse check response", {
check_id: newCheck.id,
workspace_id: workspaceId,
validation_errors: parsed.error,
});
throw new Error(`Failed to parse response: ${parsed.error.message}`);
}
fulfilledRequest.push(parsed.data);
}
let aggregatedResponse = null;
if (aggregated) {
const { dns, connect, tls, firstByte, transfer, latency } =
getTiming(fulfilledRequest);
aggregatedResponse = AggregatedResult.parse({
dns: getAggregate(dns),
connect: getAggregate(connect),
tls: getAggregate(tls),
firstByte: getAggregate(firstByte),
transfer: getAggregate(transfer),
latency: getAggregate(latency),
});
}
const allTimings = fulfilledRequest.map((r) => r.timing);
const lastResponse = fulfilledRequest[fulfilledRequest.length - 1];
const responseResult = CheckPostResponseSchema.parse({
id: newCheck.id,
raw: allTimings, // TODO: we should return the region here as well!
response: lastResponse,
aggregated: aggregatedResponse ? aggregatedResponse : undefined,
});
return c.json(responseResult, 200);
});
}
// This is a helper function to get the timing of the request
type ReturnGetTiming = Record<
"dns" | "connect" | "tls" | "firstByte" | "transfer" | "latency",
number[]
>;
function getTiming(data: z.infer<typeof ResponseSchema>[]): ReturnGetTiming {
return data.reduce(
(prev, curr) => {
prev.dns.push(curr.timing.dnsDone - curr.timing.dnsStart);
prev.connect.push(curr.timing.connectDone - curr.timing.connectStart);
prev.tls.push(
curr.timing.tlsHandshakeDone - curr.timing.tlsHandshakeStart,
);
prev.firstByte.push(
curr.timing.firstByteDone - curr.timing.firstByteStart,
);
prev.transfer.push(curr.timing.transferDone - curr.timing.transferStart);
prev.latency.push(curr.latency);
return prev;
},
{
dns: [],
connect: [],
tls: [],
firstByte: [],
transfer: [],
latency: [],
} as ReturnGetTiming,
);
}
function getAggregate(data: number[]) {
const parsed = AggregatedResponseSchema.safeParse({
p50: percentile(50, data),
p75: percentile(75, data),
p95: percentile(95, data),
p99: percentile(99, data),
min: Math.min(...data),
max: Math.max(...data),
});
if (!parsed.success) {
logger.error("Failed to parse aggregated response", {
validation_errors: parsed.error,
});
throw new Error(`Failed to parse response: ${parsed.error.message}`);
}
return parsed.data;
}