-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtaskEventStore.server.ts
More file actions
327 lines (308 loc) · 9.42 KB
/
taskEventStore.server.ts
File metadata and controls
327 lines (308 loc) · 9.42 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// TaskEventStore.ts
import { Prisma, TaskEvent } from "@trigger.dev/database";
import type { PrismaClient, PrismaReplicaClient } from "~/db.server";
import { env } from "~/env.server";
export type CommonTaskEvent = Omit<TaskEvent, "id">;
export type TraceEvent = Pick<
TaskEvent,
| "spanId"
| "parentId"
| "runId"
| "idempotencyKey"
| "message"
| "style"
| "startTime"
| "duration"
| "isError"
| "isPartial"
| "isCancelled"
| "level"
| "events"
| "environmentType"
| "kind"
>;
export type DetailedTraceEvent = Pick<
TaskEvent,
| "spanId"
| "parentId"
| "runId"
| "idempotencyKey"
| "message"
| "style"
| "startTime"
| "duration"
| "isError"
| "isPartial"
| "isCancelled"
| "level"
| "events"
| "environmentType"
| "kind"
| "taskSlug"
| "taskPath"
| "workerVersion"
| "queueName"
| "machinePreset"
| "properties"
| "output"
>;
export type TaskEventStoreTable = "taskEvent" | "taskEventPartitioned";
export function getTaskEventStoreTableForRun(run: {
taskEventStore?: string;
}): TaskEventStoreTable {
return run.taskEventStore === "taskEventPartitioned" ? "taskEventPartitioned" : "taskEvent";
}
export function getTaskEventStore(): TaskEventStoreTable {
return env.TASK_EVENT_PARTITIONING_ENABLED === "1" ? "taskEventPartitioned" : "taskEvent";
}
export class TaskEventStore {
constructor(private db: PrismaClient, private readReplica: PrismaReplicaClient) {}
/**
* Insert one record.
*/
async create(table: TaskEventStoreTable, data: Prisma.TaskEventCreateInput) {
if (table === "taskEventPartitioned") {
return await this.db.taskEventPartitioned.create({ data });
} else {
return await this.db.taskEvent.create({ data });
}
}
/**
* Insert many records.
*/
async createMany(table: TaskEventStoreTable, data: Prisma.TaskEventCreateManyInput[]) {
if (table === "taskEventPartitioned") {
return await this.db.taskEventPartitioned.createMany({ data });
} else {
return await this.db.taskEvent.createMany({ data });
}
}
/**
* Query records. When partitioning is enabled and a startCreatedAt is provided,
* the store will add a condition on createdAt (from startCreatedAt up to endCreatedAt,
* which defaults to now).
*
* @param where The base Prisma where filter.
* @param startCreatedAt The start of the createdAt range.
* @param endCreatedAt Optional end of the createdAt range (defaults to now).
* @param select Optional select clause.
*/
async findMany<TSelect extends Prisma.TaskEventSelect>(
table: TaskEventStoreTable,
where: Prisma.TaskEventWhereInput,
startCreatedAt: Date,
endCreatedAt?: Date,
select?: TSelect,
orderBy?: Prisma.TaskEventOrderByWithRelationInput,
options?: { includeDebugLogs?: boolean; limit?: number }
): Promise<Prisma.TaskEventGetPayload<{ select: TSelect }>[]> {
let finalWhere: Prisma.TaskEventWhereInput = where;
if (table === "taskEventPartitioned") {
// Add buffer to start and end of the range to make sure we include all events in the range.
const end = endCreatedAt
? new Date(endCreatedAt.getTime() + env.TASK_EVENT_PARTITIONED_WINDOW_IN_SECONDS * 1000)
: new Date();
const startCreatedAtWithBuffer = new Date(
startCreatedAt.getTime() - env.TASK_EVENT_PARTITIONED_WINDOW_IN_SECONDS * 1000
);
finalWhere = {
AND: [
where,
{
createdAt: {
gte: startCreatedAtWithBuffer,
lt: end,
},
},
],
};
}
const filterDebug =
options?.includeDebugLogs === false || options?.includeDebugLogs === undefined;
if (table === "taskEventPartitioned") {
return (await this.readReplica.taskEventPartitioned.findMany({
where: {
...(finalWhere as Prisma.TaskEventPartitionedWhereInput),
...(filterDebug ? { kind: { not: "LOG" } } : {}),
},
select,
orderBy,
take: options?.limit,
})) as Prisma.TaskEventGetPayload<{ select: TSelect }>[];
} else {
// When partitioning is not enabled, we ignore the createdAt range.
return (await this.readReplica.taskEvent.findMany({
where: {
...(finalWhere as Prisma.TaskEventWhereInput),
...(filterDebug ? { kind: { not: "LOG" } } : {}),
},
select,
orderBy,
take: options?.limit,
})) as Prisma.TaskEventGetPayload<{ select: TSelect }>[];
}
}
async findTraceEvents(
table: TaskEventStoreTable,
traceId: string,
startCreatedAt: Date,
endCreatedAt?: Date,
options?: { includeDebugLogs?: boolean }
) {
const filterDebug =
options?.includeDebugLogs === false || options?.includeDebugLogs === undefined;
if (table === "taskEventPartitioned") {
const createdAtBufferInMillis = env.TASK_EVENT_PARTITIONED_WINDOW_IN_SECONDS * 1000;
const startCreatedAtWithBuffer = new Date(startCreatedAt.getTime() - createdAtBufferInMillis);
const $endCreatedAt = endCreatedAt ?? new Date();
const endCreatedAtWithBuffer = new Date($endCreatedAt.getTime() + createdAtBufferInMillis);
return await this.readReplica.$queryRaw<TraceEvent[]>`
SELECT
"spanId",
"parentId",
"runId",
"idempotencyKey",
LEFT(message, 256) as message,
style,
"startTime",
duration,
"isError",
"isPartial",
"isCancelled",
level,
events,
"environmentType",
"kind"
FROM "TaskEventPartitioned"
WHERE
"traceId" = ${traceId}
AND "createdAt" >= ${startCreatedAtWithBuffer.toISOString()}::timestamp
AND "createdAt" < ${endCreatedAtWithBuffer.toISOString()}::timestamp
${
filterDebug
? Prisma.sql`AND \"kind\" <> CAST('LOG'::text AS "public"."TaskEventKind")`
: Prisma.empty
}
ORDER BY "startTime" ASC
LIMIT ${env.MAXIMUM_TRACE_SUMMARY_VIEW_COUNT}
`;
} else {
return await this.readReplica.$queryRaw<TraceEvent[]>`
SELECT
id,
"spanId",
"parentId",
"runId",
"idempotencyKey",
LEFT(message, 256) as message,
style,
"startTime",
duration,
"isError",
"isPartial",
"isCancelled",
level,
events,
"environmentType",
"kind"
FROM "TaskEvent"
WHERE "traceId" = ${traceId}
${
filterDebug
? Prisma.sql`AND \"kind\" <> CAST('LOG'::text AS "public"."TaskEventKind")`
: Prisma.empty
}
ORDER BY "startTime" ASC
LIMIT ${env.MAXIMUM_TRACE_SUMMARY_VIEW_COUNT}
`;
}
}
async findDetailedTraceEvents(
table: TaskEventStoreTable,
traceId: string,
startCreatedAt: Date,
endCreatedAt?: Date,
options?: { includeDebugLogs?: boolean }
) {
const filterDebug =
options?.includeDebugLogs === false || options?.includeDebugLogs === undefined;
if (table === "taskEventPartitioned") {
const createdAtBufferInMillis = env.TASK_EVENT_PARTITIONED_WINDOW_IN_SECONDS * 1000;
const startCreatedAtWithBuffer = new Date(startCreatedAt.getTime() - createdAtBufferInMillis);
const $endCreatedAt = endCreatedAt ?? new Date();
const endCreatedAtWithBuffer = new Date($endCreatedAt.getTime() + createdAtBufferInMillis);
return await this.readReplica.$queryRaw<DetailedTraceEvent[]>`
SELECT
"spanId",
"parentId",
"runId",
"idempotencyKey",
message,
style,
"startTime",
duration,
"isError",
"isPartial",
"isCancelled",
level,
events,
"environmentType",
"kind",
"taskSlug",
"taskPath",
"workerVersion",
"queueName",
"machinePreset",
properties,
output
FROM "TaskEventPartitioned"
WHERE
"traceId" = ${traceId}
AND "createdAt" >= ${startCreatedAtWithBuffer.toISOString()}::timestamp
AND "createdAt" < ${endCreatedAtWithBuffer.toISOString()}::timestamp
${
filterDebug
? Prisma.sql`AND \"kind\" <> CAST('LOG'::text AS "public"."TaskEventKind")`
: Prisma.empty
}
ORDER BY "startTime" ASC
LIMIT ${env.MAXIMUM_TRACE_DETAILED_SUMMARY_VIEW_COUNT}
`;
} else {
return await this.readReplica.$queryRaw<DetailedTraceEvent[]>`
SELECT
"spanId",
"parentId",
"runId",
"idempotencyKey",
message,
style,
"startTime",
duration,
"isError",
"isPartial",
"isCancelled",
level,
events,
"environmentType",
"kind",
"taskSlug",
"taskPath",
"workerVersion",
"queueName",
"machinePreset",
properties,
output
FROM "TaskEvent"
WHERE "traceId" = ${traceId}
${
filterDebug
? Prisma.sql`AND \"kind\" <> CAST('LOG'::text AS "public"."TaskEventKind")`
: Prisma.empty
}
ORDER BY "startTime" ASC
LIMIT ${env.MAXIMUM_TRACE_DETAILED_SUMMARY_VIEW_COUNT}
`;
}
}
}