-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathqueues.server.ts
More file actions
341 lines (293 loc) · 10.7 KB
/
queues.server.ts
File metadata and controls
341 lines (293 loc) · 10.7 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
import { sanitizeQueueName } from "@trigger.dev/core/v3/isomorphic";
import { PrismaClientOrTransaction } from "@trigger.dev/database";
import { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { logger } from "~/services/logger.server";
import { findCurrentWorkerFromEnvironment } from "~/v3/models/workerDeployment.server";
import {
LockedBackgroundWorker,
QueueManager,
QueueProperties,
QueueValidationResult,
TriggerTaskRequest,
} from "../types";
import { WorkerGroupService } from "~/v3/services/worker/workerGroupService.server";
import type { RunEngine } from "~/v3/runEngine.server";
import { env } from "~/env.server";
import { tryCatch } from "@trigger.dev/core/v3";
import { ServiceValidationError } from "~/v3/services/common.server";
import { createCache, createLRUMemoryStore, DefaultStatefulContext, Namespace } from "@internal/cache";
import { singleton } from "~/utils/singleton";
// LRU cache for environment queue sizes to reduce Redis calls
const queueSizeCache = singleton("queueSizeCache", () => {
const ctx = new DefaultStatefulContext();
const memory = createLRUMemoryStore(env.QUEUE_SIZE_CACHE_MAX_SIZE, "queue-size-cache");
return createCache({
queueSize: new Namespace<number>(ctx, {
stores: [memory],
fresh: env.QUEUE_SIZE_CACHE_TTL_MS,
stale: env.QUEUE_SIZE_CACHE_TTL_MS + 1000,
}),
});
});
/**
* Extract the queue name from a queue option that may be:
* - An object with a string `name` property: { name: "queue-name" }
* - A double-wrapped object (bug case): { name: { name: "queue-name", ... } }
*
* This handles the case where the SDK accidentally double-wraps the queue
* option when it's already an object with a name property.
*/
function extractQueueName(queue: { name?: unknown } | undefined): string | undefined {
if (!queue?.name) {
return undefined;
}
// Normal case: queue.name is a string
if (typeof queue.name === "string") {
return queue.name;
}
// Double-wrapped case: queue.name is an object with its own name property
if (typeof queue.name === "object" && queue.name !== null && "name" in queue.name) {
const innerName = (queue.name as { name: unknown }).name;
if (typeof innerName === "string") {
return innerName;
}
}
return undefined;
}
export class DefaultQueueManager implements QueueManager {
constructor(
private readonly prisma: PrismaClientOrTransaction,
private readonly engine: RunEngine
) { }
async resolveQueueProperties(
request: TriggerTaskRequest,
lockedBackgroundWorker?: LockedBackgroundWorker
): Promise<QueueProperties> {
let queueName: string;
let lockedQueueId: string | undefined;
let taskTtl: string | null | undefined;
// Determine queue name based on lockToVersion and provided options
if (lockedBackgroundWorker) {
// Task is locked to a specific worker version
const specifiedQueueName = extractQueueName(request.body.options?.queue);
// Always fetch the task to get TTL (and default queue if no override)
const lockedTask = await this.prisma.backgroundWorkerTask.findFirst({
where: {
workerId: lockedBackgroundWorker.id,
runtimeEnvironmentId: request.environment.id,
slug: request.taskId,
},
include: {
queue: true,
},
});
if (!lockedTask) {
throw new ServiceValidationError(
`Task '${request.taskId}' not found on locked version '${lockedBackgroundWorker.version ?? "<unknown>"
}'.`
);
}
taskTtl = lockedTask.ttl;
if (specifiedQueueName) {
// A specific queue name is provided, validate it exists for the locked worker
const specifiedQueue = await this.prisma.taskQueue.findFirst({
where: {
name: specifiedQueueName,
runtimeEnvironmentId: request.environment.id,
workers: { some: { id: lockedBackgroundWorker.id } },
},
});
if (!specifiedQueue) {
throw new ServiceValidationError(
`Specified queue '${specifiedQueueName}' not found or not associated with locked version '${lockedBackgroundWorker.version ?? "<unknown>"
}'.`
);
}
// Use the validated queue name directly
queueName = specifiedQueue.name;
lockedQueueId = specifiedQueue.id;
} else {
if (!lockedTask.queue) {
// This case should ideally be prevented by earlier checks or schema constraints,
// but handle it defensively.
logger.error("Task found on locked version, but has no associated queue record", {
taskId: request.taskId,
workerId: lockedBackgroundWorker.id,
version: lockedBackgroundWorker.version,
});
throw new ServiceValidationError(
`Default queue configuration for task '${request.taskId}' missing on locked version '${lockedBackgroundWorker.version ?? "<unknown>"
}'.`
);
}
// Use the task's default queue name
queueName = lockedTask.queue.name;
lockedQueueId = lockedTask.queue.id;
}
} else {
// Task is not locked to a specific version, use regular logic
if (request.body.options?.lockToVersion) {
// This should only happen if the findFirst failed, indicating the version doesn't exist
throw new ServiceValidationError(
`Task locked to version '${request.body.options.lockToVersion}', but no worker found with that version.`
);
}
// Get queue name using the helper for non-locked case (handles provided name or finds default)
const taskInfo = await this.getTaskQueueInfo(request);
queueName = taskInfo.queueName;
taskTtl = taskInfo.taskTtl;
}
// Sanitize the final determined queue name once
const sanitizedQueueName = sanitizeQueueName(queueName);
// Check that the queuename is not an empty string
if (!sanitizedQueueName) {
queueName = sanitizeQueueName(`task/${request.taskId}`); // Fallback if sanitization results in empty
} else {
queueName = sanitizedQueueName;
}
return {
queueName,
lockedQueueId,
taskTtl,
};
}
async getQueueName(request: TriggerTaskRequest): Promise<string> {
const result = await this.getTaskQueueInfo(request);
return result.queueName;
}
private async getTaskQueueInfo(
request: TriggerTaskRequest
): Promise<{ queueName: string; taskTtl?: string | null }> {
const { taskId, environment, body } = request;
const { queue } = body.options ?? {};
// Use extractQueueName to handle double-wrapped queue objects
const overriddenQueueName = extractQueueName(queue);
const defaultQueueName = `task/${taskId}`;
// Find the current worker for the environment
const worker = await findCurrentWorkerFromEnvironment(environment, this.prisma);
if (!worker) {
logger.debug("Failed to get queue name: No worker found", {
taskId,
environmentId: environment.id,
});
return { queueName: overriddenQueueName ?? defaultQueueName, taskTtl: undefined };
}
const task = await this.prisma.backgroundWorkerTask.findFirst({
where: {
workerId: worker.id,
runtimeEnvironmentId: environment.id,
slug: taskId,
},
include: {
queue: true,
},
});
if (!task) {
console.log("Failed to get queue name: No task found", {
taskId,
environmentId: environment.id,
});
return { queueName: overriddenQueueName ?? defaultQueueName, taskTtl: undefined };
}
if (!task.queue) {
console.log("Failed to get queue name: No queue found", {
taskId,
environmentId: environment.id,
queueConfig: task.queueConfig,
});
return { queueName: overriddenQueueName ?? defaultQueueName, taskTtl: task.ttl };
}
return { queueName: overriddenQueueName ?? task.queue.name ?? defaultQueueName, taskTtl: task.ttl };
}
async validateQueueLimits(
environment: AuthenticatedEnvironment,
queueName: string,
itemsToAdd?: number
): Promise<QueueValidationResult> {
const queueSizeGuard = await guardQueueSizeLimitsForQueue(
this.engine,
environment,
queueName,
itemsToAdd
);
logger.debug("Queue size guard result", {
queueSizeGuard,
queueName,
environment: {
id: environment.id,
type: environment.type,
organization: environment.organization,
project: environment.project,
},
});
return {
ok: queueSizeGuard.isWithinLimits,
maximumSize: queueSizeGuard.maximumSize ?? 0,
queueSize: queueSizeGuard.queueSize ?? 0,
};
}
async getWorkerQueue(
environment: AuthenticatedEnvironment,
regionOverride?: string
): Promise<string | undefined> {
if (environment.type === "DEVELOPMENT") {
return environment.id;
}
const workerGroupService = new WorkerGroupService({
prisma: this.prisma,
engine: this.engine,
});
const [error, workerGroup] = await tryCatch(
workerGroupService.getDefaultWorkerGroupForProject({
projectId: environment.projectId,
regionOverride,
})
);
if (error) {
throw new ServiceValidationError(error.message);
}
if (!workerGroup) {
throw new ServiceValidationError("No worker group found");
}
return workerGroup.masterQueue;
}
}
export function getMaximumSizeForEnvironment(environment: AuthenticatedEnvironment): number | undefined {
if (environment.type === "DEVELOPMENT") {
return environment.organization.maximumDevQueueSize ?? env.MAXIMUM_DEV_QUEUE_SIZE;
} else {
return environment.organization.maximumDeployedQueueSize ?? env.MAXIMUM_DEPLOYED_QUEUE_SIZE;
}
}
async function guardQueueSizeLimitsForQueue(
engine: RunEngine,
environment: AuthenticatedEnvironment,
queueName: string,
itemsToAdd: number = 1
) {
const maximumSize = getMaximumSizeForEnvironment(environment);
if (typeof maximumSize === "undefined") {
return { isWithinLimits: true };
}
const queueSize = await getCachedQueueSize(engine, environment, queueName);
const projectedSize = queueSize + itemsToAdd;
return {
isWithinLimits: projectedSize <= maximumSize,
maximumSize,
queueSize,
};
}
async function getCachedQueueSize(
engine: RunEngine,
environment: AuthenticatedEnvironment,
queueName: string
): Promise<number> {
if (!env.QUEUE_SIZE_CACHE_ENABLED) {
return engine.lengthOfQueue(environment, queueName);
}
const cacheKey = `${environment.id}:${queueName}`;
const result = await queueSizeCache.queueSize.swr(cacheKey, async () => {
return engine.lengthOfQueue(environment, queueName);
});
return result.val ?? 0;
}