-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathpostgresRunsRepository.server.ts
More file actions
348 lines (299 loc) · 10.4 KB
/
postgresRunsRepository.server.ts
File metadata and controls
348 lines (299 loc) · 10.4 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import { RunId } from "@trigger.dev/core/v3/isomorphic";
import { Prisma } from "@trigger.dev/database";
import { sqlDatabaseSchema } from "~/db.server";
import {
type FilterRunsOptions,
type IRunsRepository,
type ListRunsOptions,
type ListedRun,
type RunListInputOptions,
type RunsRepositoryOptions,
type TagListOptions,
convertRunListInputOptionsToFilterRunsOptions,
} from "./runsRepository.server";
export class PostgresRunsRepository implements IRunsRepository {
constructor(private readonly options: RunsRepositoryOptions) {}
get name() {
return "postgres";
}
async listRunIds(options: ListRunsOptions) {
const filterOptions = await convertRunListInputOptionsToFilterRunsOptions(
options,
this.options.prisma
);
const query = this.#buildRunIdsQuery(filterOptions, options.page);
const runs = await this.options.prisma.$queryRaw<{ id: string }[]>(query);
return runs.map((run) => run.id);
}
async listFriendlyRunIds(options: ListRunsOptions) {
const filterOptions = await convertRunListInputOptionsToFilterRunsOptions(
options,
this.options.prisma
);
const query = this.#buildFriendlyRunIdsQuery(filterOptions, options.page);
const runs = await this.options.prisma.$queryRaw<{ friendlyId: string }[]>(query);
return runs.map((run) => run.friendlyId);
}
async listRuns(options: ListRunsOptions) {
const filterOptions = await convertRunListInputOptionsToFilterRunsOptions(
options,
this.options.prisma
);
const query = this.#buildRunsQuery(filterOptions, options.page);
const runs = await this.options.prisma.$queryRaw<ListedRun[]>(query);
// If there are more runs than the page size, we need to fetch the next page
const hasMore = runs.length > options.page.size;
let nextCursor: string | null = null;
let previousCursor: string | null = null;
// Get cursors for next and previous pages
const direction = options.page.direction ?? "forward";
switch (direction) {
case "forward": {
previousCursor = options.page.cursor ? runs.at(0)?.id ?? null : null;
if (hasMore) {
// The next cursor should be the last run ID from this page
nextCursor = runs[options.page.size - 1]?.id ?? null;
}
break;
}
case "backward": {
const reversedRuns = [...runs].reverse();
if (hasMore) {
previousCursor = reversedRuns.at(1)?.id ?? null;
nextCursor = reversedRuns.at(options.page.size)?.id ?? null;
} else {
// Use the last item (oldest run) as the forward cursor.
// We can't use a fixed index (pageSize - 1) because the result set
// may have fewer items than pageSize (e.g., when new runs were created
// while the user was browsing, shifting page boundaries).
nextCursor = reversedRuns.at(reversedRuns.length - 1)?.id ?? null;
}
break;
}
}
const runsToReturn =
options.page.direction === "backward" && hasMore
? runs.slice(1, options.page.size + 1)
: runs.slice(0, options.page.size);
// ClickHouse is slightly delayed, so we're going to do in-memory status filtering too
let filteredRuns = runsToReturn;
if (options.statuses && options.statuses.length > 0) {
filteredRuns = runsToReturn.filter((run) => options.statuses!.includes(run.status));
}
return {
runs: filteredRuns,
pagination: {
nextCursor,
previousCursor,
},
};
}
async countRuns(options: RunListInputOptions) {
const filterOptions = await convertRunListInputOptionsToFilterRunsOptions(
options,
this.options.prisma
);
const query = this.#buildCountQuery(filterOptions);
const result = await this.options.prisma.$queryRaw<{ count: bigint }[]>(query);
if (result.length === 0) {
throw new Error("No count rows returned");
}
return Number(result[0].count);
}
async listTags({ projectId, query, offset, limit }: TagListOptions) {
const tags = await this.options.prisma.taskRunTag.findMany({
select: {
name: true,
},
where: {
projectId,
name: query
? {
startsWith: query,
mode: "insensitive",
}
: undefined,
},
orderBy: {
id: "desc",
},
take: limit + 1,
skip: offset,
});
return {
tags: tags.map((tag) => tag.name),
};
}
#buildRunIdsQuery(
filterOptions: FilterRunsOptions,
page: { size: number; cursor?: string; direction?: "forward" | "backward" }
) {
const whereConditions = this.#buildWhereConditions(filterOptions, page.cursor, page.direction);
return Prisma.sql`
SELECT tr.id
FROM ${sqlDatabaseSchema}."TaskRun" tr
WHERE ${whereConditions}
ORDER BY ${page.direction === "backward" ? Prisma.sql`tr.id ASC` : Prisma.sql`tr.id DESC`}
LIMIT ${page.size + 1}
`;
}
#buildFriendlyRunIdsQuery(
filterOptions: FilterRunsOptions,
page: { size: number; cursor?: string; direction?: "forward" | "backward" }
) {
const whereConditions = this.#buildWhereConditions(filterOptions, page.cursor, page.direction);
return Prisma.sql`
SELECT tr."friendlyId"
FROM ${sqlDatabaseSchema}."TaskRun" tr
WHERE ${whereConditions}
ORDER BY ${page.direction === "backward" ? Prisma.sql`tr.id ASC` : Prisma.sql`tr.id DESC`}
LIMIT ${page.size + 1}
`;
}
#buildRunsQuery(
filterOptions: FilterRunsOptions,
page: { size: number; cursor?: string; direction?: "forward" | "backward" }
) {
const whereConditions = this.#buildWhereConditions(filterOptions, page.cursor, page.direction);
return Prisma.sql`
SELECT
tr.id,
tr."friendlyId",
tr."taskIdentifier",
tr."taskVersion",
tr."runtimeEnvironmentId",
tr.status,
tr."createdAt",
tr."startedAt",
tr."lockedAt",
tr."delayUntil",
tr."updatedAt",
tr."completedAt",
tr."isTest",
tr."spanId",
tr."idempotencyKey",
tr."ttl",
tr."expiredAt",
tr."costInCents",
tr."baseCostInCents",
tr."usageDurationMs",
tr."runTags",
tr."depth",
tr."rootTaskRunId",
tr."batchId",
tr."metadata",
tr."metadataType",
tr."machinePreset",
tr."queue"
FROM ${sqlDatabaseSchema}."TaskRun" tr
WHERE ${whereConditions}
ORDER BY ${page.direction === "backward" ? Prisma.sql`tr.id ASC` : Prisma.sql`tr.id DESC`}
LIMIT ${page.size + 1}
`;
}
#buildCountQuery(filterOptions: FilterRunsOptions) {
const whereConditions = this.#buildWhereConditions(filterOptions);
return Prisma.sql`
SELECT COUNT(*) as count
FROM ${sqlDatabaseSchema}."TaskRun" tr
WHERE ${whereConditions}
`;
}
#buildWhereConditions(
filterOptions: FilterRunsOptions,
cursor?: string,
direction?: "forward" | "backward"
) {
const conditions: Prisma.Sql[] = [];
// Environment filter
conditions.push(Prisma.sql`tr."runtimeEnvironmentId" = ${filterOptions.environmentId}`);
// Cursor pagination
if (cursor) {
if (direction === "forward" || !direction) {
conditions.push(Prisma.sql`tr.id < ${cursor}`);
} else {
conditions.push(Prisma.sql`tr.id > ${cursor}`);
}
}
// Task filters
if (filterOptions.tasks && filterOptions.tasks.length > 0) {
conditions.push(Prisma.sql`tr."taskIdentifier" IN (${Prisma.join(filterOptions.tasks)})`);
}
// Version filters
if (filterOptions.versions && filterOptions.versions.length > 0) {
conditions.push(Prisma.sql`tr."taskVersion" IN (${Prisma.join(filterOptions.versions)})`);
}
// Status filters
if (filterOptions.statuses && filterOptions.statuses.length > 0) {
conditions.push(
Prisma.sql`tr.status = ANY(ARRAY[${Prisma.join(
filterOptions.statuses
)}]::"TaskRunStatus"[])`
);
}
// Tag filters
if (filterOptions.tags && filterOptions.tags.length > 0) {
conditions.push(
Prisma.sql`tr."runTags" && ARRAY[${Prisma.join(filterOptions.tags)}]::text[]`
);
}
// Schedule filter
if (filterOptions.scheduleId) {
conditions.push(Prisma.sql`tr."scheduleId" = ${filterOptions.scheduleId}`);
}
// Time period filter
if (filterOptions.period) {
conditions.push(
Prisma.sql`tr."createdAt" >= NOW() - INTERVAL '1 millisecond' * ${filterOptions.period}`
);
}
// From date filter
if (filterOptions.from) {
conditions.push(
Prisma.sql`tr."createdAt" >= ${new Date(filterOptions.from).toISOString()}::timestamp`
);
}
// To date filter
if (filterOptions.to) {
const toDate = new Date(filterOptions.to);
const now = new Date();
const clampedDate = toDate > now ? now : toDate;
conditions.push(Prisma.sql`tr."createdAt" <= ${clampedDate.toISOString()}::timestamp`);
}
// Test filter
if (typeof filterOptions.isTest === "boolean") {
conditions.push(Prisma.sql`tr."isTest" = ${filterOptions.isTest}`);
}
// Root only filter
if (filterOptions.rootOnly) {
conditions.push(Prisma.sql`tr."rootTaskRunId" IS NULL`);
}
// Batch filter
if (filterOptions.batchId) {
conditions.push(Prisma.sql`tr."batchId" = ${filterOptions.batchId}`);
}
// Bulk action filter
if (filterOptions.bulkId) {
conditions.push(
Prisma.sql`tr."bulkActionGroupIds" && ARRAY[${filterOptions.bulkId}]::text[]`
);
}
// Run ID filter
if (filterOptions.runId && filterOptions.runId.length > 0) {
const friendlyIds = filterOptions.runId.map((runId) => RunId.toFriendlyId(runId));
conditions.push(Prisma.sql`tr."friendlyId" IN (${Prisma.join(friendlyIds)})`);
}
// Queue filter
if (filterOptions.queues && filterOptions.queues.length > 0) {
conditions.push(Prisma.sql`tr."queue" IN (${Prisma.join(filterOptions.queues)})`);
}
// Machine preset filter
if (filterOptions.machines && filterOptions.machines.length > 0) {
conditions.push(Prisma.sql`tr."machinePreset" IN (${Prisma.join(filterOptions.machines)})`);
}
// Combine all conditions with AND
return conditions.reduce((acc, condition) =>
acc === null ? condition : Prisma.sql`${acc} AND ${condition}`
);
}
}