-
-
Notifications
You must be signed in to change notification settings - Fork 656
Expand file tree
/
Copy path_cron.ts
More file actions
290 lines (263 loc) · 8.09 KB
/
_cron.ts
File metadata and controls
290 lines (263 loc) · 8.09 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import { CloudTasksClient } from "@google-cloud/tasks";
import type { google } from "@google-cloud/tasks/build/protos/protos";
import { z } from "zod";
import { and, db, eq, gte, isNotNull, lte, notInArray } from "@openstatus/db";
import type { MonitorStatus } from "@openstatus/db/src/schema";
import {
maintenance,
monitor,
monitorStatusTable,
selectMonitorSchema,
selectMonitorStatusSchema,
} from "@openstatus/db/src/schema";
import {
maintenancesToPageComponents,
pageComponent,
} from "@openstatus/db/src/schema/page_components";
import { env } from "@/env";
import type { Region } from "@openstatus/db/src/schema/constants";
import { regionDict } from "@openstatus/regions";
import {
type httpPayloadSchema,
type tpcPayloadSchema,
transformHeaders,
} from "@openstatus/utils";
const periodicityAvailable = selectMonitorSchema.pick({ periodicity: true });
// FIXME: do coerce in zod instead
const DEFAULT_URL = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
// We can't secure cron endpoint by vercel thus we should make sure they are called by the generated url
export const isAuthorizedDomain = (url: string) => {
return url.includes(DEFAULT_URL);
};
export const cron = async ({
periodicity,
}: z.infer<typeof periodicityAvailable>) => {
const client = new CloudTasksClient({
projectId: env.GCP_PROJECT_ID,
credentials: {
client_email: process.env.GCP_CLIENT_EMAIL,
private_key: env.GCP_PRIVATE_KEY.replaceAll("\\n", "\n"),
},
});
const parent = client.queuePath(
env.GCP_PROJECT_ID,
env.GCP_LOCATION,
periodicity,
);
const timestamp = Date.now();
const currentMaintenance = db
.select({ id: maintenance.id })
.from(maintenance)
.where(
and(lte(maintenance.from, new Date()), gte(maintenance.to, new Date())),
)
.as("currentMaintenance");
const currentMaintenanceMonitors = db
.select({ id: pageComponent.monitorId })
.from(maintenancesToPageComponents)
.innerJoin(
currentMaintenance,
eq(maintenancesToPageComponents.maintenanceId, currentMaintenance.id),
)
.innerJoin(
pageComponent,
eq(maintenancesToPageComponents.pageComponentId, pageComponent.id),
)
.where(isNotNull(pageComponent.monitorId));
const result = await db
.select()
.from(monitor)
.where(
and(
eq(monitor.periodicity, periodicity),
eq(monitor.active, true),
notInArray(monitor.id, currentMaintenanceMonitors),
),
)
.all();
console.log(`Start cron for ${periodicity}`);
const monitors = z.array(selectMonitorSchema).safeParse(result);
const allResult = [];
if (!monitors.success) {
console.error(
`Error while fetching the monitors ${monitors.error.issues.map((issue) => issue.message).join(", ")}`,
);
throw new Error("Error while fetching the monitors");
}
for (const row of monitors.data) {
// const selectedRegions = row.regions.length > 0 ? row.regions : ["ams"];
const result = await db
.select()
.from(monitorStatusTable)
.where(eq(monitorStatusTable.monitorId, row.id))
.all();
const monitorStatus = z.array(selectMonitorStatusSchema).safeParse(result);
if (!monitorStatus.success) {
console.error(
`Error while fetching the monitor status ${monitorStatus.error.issues.map((issue) => issue.message).join(", ")}`,
);
continue;
}
for (const region of row.regions) {
const status =
monitorStatus.data.find((m) => region === m.region)?.status || "active";
const r = regionDict[region as keyof typeof regionDict];
if (!r) {
console.error(`Invalid region ${region}`);
continue;
}
if (r.deprecated) {
// Let's uncomment this when we are ready to remove deprecated regions
// We should not use deprecated regions anymore
console.error(`Deprecated region ${region}`);
continue;
}
const response = createCronTask({
row,
timestamp,
client,
parent,
status,
region,
});
allResult.push(response);
if (periodicity === "30s") {
// we schedule another task in 30s
const scheduledAt = timestamp + 30 * 1000;
const response = createCronTask({
row,
timestamp: scheduledAt,
client,
parent,
status,
region,
});
allResult.push(response);
}
}
}
const allRequests = await Promise.allSettled(allResult);
const success = allRequests.filter((r) => r.status === "fulfilled").length;
const failed = allRequests.filter((r) => r.status === "rejected").length;
console.log(
`End cron for ${periodicity} with ${allResult.length} jobs with ${success} success and ${failed} failed`,
);
};
// timestamp needs to be in ms
const createCronTask = async ({
row,
timestamp,
client,
parent,
status,
region,
}: {
row: z.infer<typeof selectMonitorSchema>;
timestamp: number;
client: CloudTasksClient;
parent: string;
status: MonitorStatus;
region: Region;
}) => {
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: "cron",
otelConfig: row.otelEndpoint
? {
endpoint: row.otelEndpoint,
headers: transformHeaders(row.otelHeaders),
}
: undefined,
retry: row.retry || 3,
followRedirects: row.followRedirects || true,
};
}
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: "cron",
retry: row.retry || 3,
otelConfig: row.otelEndpoint
? {
endpoint: row.otelEndpoint,
headers: transformHeaders(row.otelHeaders),
}
: undefined,
};
}
if (!payload) {
throw new Error("Invalid jobType");
}
const regionInfo = regionDict[region];
let regionHeader = {};
if (regionInfo.provider === "fly") {
regionHeader = { "fly-prefer-region": region };
}
if (regionInfo.provider === "koyeb") {
regionHeader = { "X-KOYEB-REGION-OVERRIDE": region.replace("koyeb_", "") };
}
if (regionInfo.provider === "railway") {
regionHeader = { "railway-region": region.replace("railway_", "") };
}
const newTask: google.cloud.tasks.v2beta3.ITask = {
httpRequest: {
headers: {
"Content-Type": "application/json", // Set content type to ensure compatibility your application's request parsing
...regionHeader,
Authorization: `Basic ${env.CRON_SECRET}`,
},
httpMethod: "POST",
url: generateUrl({ row, region }),
body: Buffer.from(JSON.stringify(payload)).toString("base64"),
},
scheduleTime: {
seconds: timestamp / 1000,
},
};
const request = { parent: parent, task: newTask };
return client.createTask(request);
};
function generateUrl({
row,
region,
}: {
row: z.infer<typeof selectMonitorSchema>;
region: Region;
}) {
const regionInfo = regionDict[region];
switch (regionInfo.provider) {
case "fly":
return `https://openstatus-checker.fly.dev/checker/${row.jobType}?monitor_id=${row.id}`;
case "koyeb":
return `https://openstatus-checker.koyeb.app/checker/${row.jobType}?monitor_id=${row.id}`;
case "railway":
return `https://railway-proxy-production-9cb1.up.railway.app/checker/${row.jobType}?monitor_id=${row.id}`;
default:
throw new Error("Invalid jobType");
}
}