-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathQueueListPresenter.server.ts
More file actions
432 lines (388 loc) · 13.5 KB
/
Copy pathQueueListPresenter.server.ts
File metadata and controls
432 lines (388 loc) · 13.5 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import type { RunEngine } from "@internal/run-engine";
import type { Prisma } from "@trigger.dev/database";
import { TaskQueueType, boundedIn } from "@trigger.dev/database";
import { type PrismaClientOrTransaction } from "~/db.server";
import { type AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { clickhouseFactory } from "~/services/clickhouse/clickhouseFactoryInstance.server";
import { logger } from "~/services/logger.server";
import { determineEngineVersion } from "~/v3/engineVersion.server";
import { engine } from "~/v3/runEngine.server";
import { BasePresenter } from "./basePresenter.server";
import { toQueueItem } from "./QueueRetrievePresenter.server";
type QueueListEngine = Pick<RunEngine, "lengthOfQueues" | "currentConcurrencyOfQueues">;
export const QUEUE_LIST_DEFAULT_ITEMS_PER_PAGE = 25;
const MAX_ITEMS_PER_PAGE = 100;
export type QueueListSort = "busiest" | "queued" | "name";
/** Ranking reads recent aggregated gauges, so ordering is a stable snapshot, not a live sort. */
export const QUEUE_RANKING_WINDOW_MINUTES = 15;
const MAX_RANKED_QUEUES = 5000;
const typeToDBQueueType: Record<"task" | "custom", TaskQueueType> = {
task: TaskQueueType.VIRTUAL,
custom: TaskQueueType.NAMED,
};
const queueListSelect = {
friendlyId: true,
name: true,
orderableName: true,
concurrencyLimit: true,
concurrencyLimitBase: true,
concurrencyLimitOverriddenAt: true,
concurrencyLimitOverriddenBy: true,
concurrencyLimitOverridePercent: true,
type: true,
paused: true,
} satisfies Prisma.TaskQueueSelect;
type QueueListRow = Prisma.TaskQueueGetPayload<{ select: typeof queueListSelect }>;
// The percent source-of-truth for percent-based overrides isn't part of the shared `QueueItem`
// schema (that's a public contract), so we surface it as an extra field on the list item.
type QueueListItem = ReturnType<typeof toQueueItem> & {
concurrencyLimitOverridePercent: number | null;
};
type QueueListPagination =
| { mode: "filtered"; currentPage: number; hasMore: boolean }
| { mode: "unfiltered"; currentPage: number; totalPages: number; count: number };
// The `?: undefined` markers keep every key reachable across the union, so consumers
// can destructure before narrowing on `success`.
export type QueueListResult =
| {
success: false;
code: string;
totalQueues: number;
hasFilters: boolean;
queues?: undefined;
pagination?: undefined;
}
| {
success: true;
queues: QueueListItem[];
pagination: QueueListPagination;
totalQueues?: number;
hasFilters: boolean;
code?: undefined;
};
function formatClickhouseDateTime(date: Date): string {
return date.toISOString().slice(0, 19).replace("T", " ");
}
function buildQueueListWhere(
environmentId: string,
query: string | undefined,
type: "task" | "custom" | undefined
): Prisma.TaskQueueWhereInput {
const trimmedQuery = query?.trim();
return {
runtimeEnvironmentId: environmentId,
version: "V2",
name: trimmedQuery
? {
contains: trimmedQuery,
mode: "insensitive",
}
: undefined,
type: type ? typeToDBQueueType[type] : undefined,
};
}
export class QueueListPresenter extends BasePresenter {
private readonly perPage: number;
private readonly engineClient: QueueListEngine;
constructor(
perPage: number = QUEUE_LIST_DEFAULT_ITEMS_PER_PAGE,
prismaClient?: PrismaClientOrTransaction,
replicaClient?: PrismaClientOrTransaction,
engineClient: QueueListEngine = engine
) {
super(prismaClient, replicaClient);
this.perPage = Math.min(perPage, MAX_ITEMS_PER_PAGE);
this.engineClient = engineClient;
}
public async call({
environment,
query,
page,
type,
sort = "name",
}: {
environment: AuthenticatedEnvironment;
query?: string;
page: number;
perPage?: number;
type?: "task" | "custom";
sort?: QueueListSort;
}): Promise<QueueListResult> {
const hasFilters = Boolean(query?.trim()) || type !== undefined;
const engineVersion = await determineEngineVersion({ environment });
if (engineVersion === "V1") {
const totalQueues = await this._replica.taskQueue.count({
where: buildQueueListWhere(environment.id, query, type),
});
if (totalQueues === 0) {
const oldQueue = await this._replica.taskQueue.findFirst({
where: {
runtimeEnvironmentId: environment.id,
version: "V1",
},
});
if (oldQueue) {
return {
success: false as const,
code: "engine-version",
totalQueues: 1,
hasFilters,
};
}
}
return {
success: false as const,
code: "engine-version",
totalQueues,
hasFilters,
};
}
if (sort !== "name") {
// Ranking is additive: any failure or unsupported input falls back to name order.
try {
const ranked = await this.getRankedQueues(environment, query, page, type, sort);
if (ranked) {
return ranked;
}
} catch (error) {
logger.warn("Queue ranking unavailable, falling back to name order", { error });
}
}
if (hasFilters) {
const { queues, hasMore } = await this.getFilteredQueues(environment, query, page, type);
return {
success: true as const,
queues,
pagination: {
mode: "filtered" as const,
currentPage: page,
hasMore,
},
hasFilters,
};
}
const totalQueues = await this._replica.taskQueue.count({
where: buildQueueListWhere(environment.id, query, type),
});
return {
success: true as const,
queues: await this.getUnfilteredQueues(environment, page, type),
pagination: {
mode: "unfiltered" as const,
currentPage: page,
totalPages: Math.ceil(totalQueues / this.perPage),
count: totalQueues,
},
totalQueues,
hasFilters,
};
}
/**
* ClickHouse ranks queues by recent activity and returns the requested page of names;
* queues with no recent metrics follow in name order. Null when ranking does not apply.
*/
private async getRankedQueues(
environment: AuthenticatedEnvironment,
query: string | undefined,
page: number,
type: "task" | "custom" | undefined,
sort: Exclude<QueueListSort, "name">
) {
if (type !== undefined) {
return null;
}
const clickhouse = await clickhouseFactory.getClickhouseForOrganization(
environment.organizationId,
"queueMetrics"
);
// The window start is aligned to the minute so repeated page loads produce identical
// query text and can share ClickHouse query-cache entries.
const windowStartMs =
Math.floor((Date.now() - QUEUE_RANKING_WINDOW_MINUTES * 60 * 1000) / 60_000) * 60_000;
const rankingArgs = {
organizationId: environment.organizationId,
projectId: environment.projectId,
environmentId: environment.id,
startTime: formatClickhouseDateTime(new Date(windowStartMs)),
nameContains: query?.trim() ?? "",
};
const offset = (page - 1) * this.perPage;
// One scan returns the page and the total ranked count (window function).
const [pageError, pageRows] = await clickhouse.queueMetrics.ranking({
...rankingArgs,
byQueuedOnly: sort === "queued" ? 1 : 0,
limit: this.perPage,
offset,
});
if (pageError) {
throw pageError;
}
let ranked = pageRows?.[0]?.ranked_total ?? 0;
if (ranked === 0 && offset > 0) {
// Empty page past the ranked head: fetch the count alone for the tail slot math.
const [countError, countRows] = await clickhouse.queueMetrics.rankingCount(rankingArgs);
if (countError) {
throw countError;
}
ranked = countRows?.[0]?.ranked ?? 0;
}
if (ranked > MAX_RANKED_QUEUES) {
return null;
}
const where = buildQueueListWhere(environment.id, query, type);
const totalQueues = await this._replica.taskQueue.count({ where });
let rankedPageQueues: QueueListRow[] = [];
if ((pageRows?.length ?? 0) > 0) {
const rankedNames = (pageRows ?? []).map((row) => row.queue_name);
rankedPageQueues = await this.findQueuesByNames(where, rankedNames);
}
// Tail of the page: name-ordered queues that have no recent metrics. Slot math uses the
// ClickHouse counts so pages never overlap, even if some ranked names no longer exist.
const rankedSlots = Math.min(Math.max(ranked - offset, 0), this.perPage);
const tailNeeded = this.perPage - rankedSlots;
let tailQueues: QueueListRow[] = [];
if (tailNeeded > 0) {
let excludedNames: string[] = [];
if (ranked > 0) {
const [allError, allRows] = await clickhouse.queueMetrics.rankingNames({
...rankingArgs,
limit: MAX_RANKED_QUEUES,
});
if (allError) {
throw allError;
}
excludedNames = (allRows ?? []).map((row) => row.queue_name);
}
// AND keeps the search's name filter intact alongside the exclusion (a spread
// would overwrite one name condition with the other).
tailQueues = await this._replica.taskQueue.findMany({
where: { AND: [where, { name: { notIn: boundedIn(excludedNames) } }] },
select: queueListSelect,
orderBy: {
orderableName: "asc",
},
skip: Math.max(0, offset - ranked),
take: tailNeeded,
});
}
return {
success: true as const,
queues: await this.enrichQueues(environment, [...rankedPageQueues, ...tailQueues]),
pagination: {
mode: "unfiltered" as const,
currentPage: page,
totalPages: Math.max(1, Math.ceil(totalQueues / this.perPage)),
count: totalQueues,
},
totalQueues,
hasFilters: Boolean(query?.trim()) || type !== undefined,
};
}
private async findQueuesByNames(
where: Prisma.TaskQueueWhereInput,
names: string[]
): Promise<QueueListRow[]> {
if (names.length === 0) {
return [];
}
const queues = await this._replica.taskQueue.findMany({
where: { AND: [where, { name: { in: boundedIn(names) } }] },
select: queueListSelect,
});
const byName = new Map(queues.map((queue) => [queue.name, queue]));
return names.flatMap((name) => byName.get(name) ?? []);
}
private async getFilteredQueues(
environment: AuthenticatedEnvironment,
query: string | undefined,
page: number,
type: "task" | "custom" | undefined
) {
const queues = await this._replica.taskQueue.findMany({
where: buildQueueListWhere(environment.id, query, type),
select: queueListSelect,
orderBy: {
orderableName: "asc",
},
skip: (page - 1) * this.perPage,
take: this.perPage + 1,
});
const hasMore = queues.length > this.perPage;
return {
queues: await this.enrichQueues(environment, queues.slice(0, this.perPage)),
hasMore,
};
}
private async getUnfilteredQueues(
environment: AuthenticatedEnvironment,
page: number,
type: "task" | "custom" | undefined
) {
const queues = await this._replica.taskQueue.findMany({
where: buildQueueListWhere(environment.id, undefined, type),
select: queueListSelect,
orderBy: {
orderableName: "asc",
},
skip: (page - 1) * this.perPage,
take: this.perPage,
});
return this.enrichQueues(environment, queues);
}
private async enrichQueues(
environment: AuthenticatedEnvironment,
queues: {
friendlyId: string;
name: string;
orderableName: string | null;
concurrencyLimit: number | null;
concurrencyLimitBase: number | null;
concurrencyLimitOverriddenAt: Date | null;
concurrencyLimitOverriddenBy: string | null;
concurrencyLimitOverridePercent: Prisma.Decimal | null;
type: TaskQueueType;
paused: boolean;
}[]
): Promise<QueueListItem[]> {
const [queuedByQueue, runningByQueue] = await Promise.all([
this.engineClient.lengthOfQueues(
environment,
queues.map((q) => q.name)
),
this.engineClient.currentConcurrencyOfQueues(
environment,
queues.map((q) => q.name)
),
]);
// Manually "join" the overridden users because there is no way to implement the relationship
// in prisma without adding a foreign key constraint
const overriddenByIds = queues.map((q) => q.concurrencyLimitOverriddenBy).filter(Boolean);
const overriddenByUsers = await this._replica.user.findMany({
where: {
id: { in: boundedIn(overriddenByIds) },
},
});
const overriddenByMap = new Map(overriddenByUsers.map((u) => [u.id, u]));
return queues.map((queue) => ({
...toQueueItem({
friendlyId: queue.friendlyId,
name: queue.name,
type: queue.type,
running: runningByQueue[queue.name] ?? 0,
queued: queuedByQueue[queue.name] ?? 0,
concurrencyLimit: queue.concurrencyLimit ?? null,
concurrencyLimitBase: queue.concurrencyLimitBase ?? null,
concurrencyLimitOverriddenAt: queue.concurrencyLimitOverriddenAt ?? null,
concurrencyLimitOverriddenBy: queue.concurrencyLimitOverriddenBy
? (overriddenByMap.get(queue.concurrencyLimitOverriddenBy) ?? null)
: null,
paused: queue.paused,
}),
// Prisma returns Decimal; the client only needs a plain number (null for absolute overrides).
concurrencyLimitOverridePercent:
queue.concurrencyLimitOverridePercent !== null
? Number(queue.concurrencyLimitOverridePercent)
: null,
}));
}
}