-
-
Notifications
You must be signed in to change notification settings - Fork 685
/
Copy pathv2.server.ts
326 lines (267 loc) · 8.91 KB
/
v2.server.ts
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
import { trace } from "@opentelemetry/api";
import { RetryOptions, calculateNextRetryDelay } from "@trigger.dev/core/v3";
import { ConcurrencyLimitGroup, Job, JobVersion } from "@trigger.dev/database";
import { z } from "zod";
import { env } from "~/env.server";
import { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { logger } from "~/services/logger.server";
import { PerformRunExecutionV3Service } from "~/services/runs/performRunExecutionV3.server";
import { singleton } from "~/utils/singleton";
import { generateFriendlyId } from "../friendlyIdentifiers";
import { MarQS } from "./index.server";
import { MarQSShortKeyProducer } from "./marqsKeyProducer.server";
import { RequeueV2Message } from "./requeueV2Message.server";
import {
NoopWeightedChoiceStrategy,
SimpleWeightedChoiceStrategy,
} from "./simpleWeightedPriorityStrategy.server";
import { VisibilityTimeoutStrategy } from "./types";
const KEY_PREFIX = "marqsv2:";
const SHARED_QUEUE_NAME = "sharedQueue";
export class V2VisibilityTimeout implements VisibilityTimeoutStrategy {
async heartbeat(messageId: string, timeoutInMs: number): Promise<void> {
RequeueV2Message.enqueue(messageId, new Date(Date.now() + timeoutInMs));
}
async cancelHeartbeat(messageId: string): Promise<void> {
RequeueV2Message.dequeue(messageId);
}
}
export class MarQSV2KeyProducer extends MarQSShortKeyProducer {
constructor(prefix: string) {
super(prefix);
}
envSharedQueueKey(env: AuthenticatedEnvironment) {
return SHARED_QUEUE_NAME;
}
sharedQueueKey(): string {
return SHARED_QUEUE_NAME;
}
}
export const marqsv2 = singleton("marqsv2", getMarQSClient);
function getMarQSClient() {
if (env.V2_MARQS_ENABLED === "0") {
return;
}
if (!env.REDIS_HOST || !env.REDIS_PORT) {
throw new Error(
"Could not initialize marqsv2 because process.env.REDIS_HOST and process.env.REDIS_PORT are required to be set. Trigger.dev v2 will not work without this."
);
}
const redisOptions = {
keyPrefix: KEY_PREFIX,
port: env.REDIS_PORT,
host: env.REDIS_HOST,
username: env.REDIS_USERNAME,
password: env.REDIS_PASSWORD,
enableAutoPipelining: true,
// Force support for both IPv6 and IPv4, by default ioredis sets this to 4,
// only allowing IPv4 connections:
// https://github.com/redis/ioredis/issues/1576
family: 0,
...(env.REDIS_TLS_DISABLED === "true" ? {} : { tls: {} }),
};
return new MarQS({
verbose: env.V2_MARQS_VERBOSE === "1",
name: "marqsv2",
tracer: trace.getTracer("marqsv2"),
visibilityTimeoutStrategy: new V2VisibilityTimeout(),
keysProducer: new MarQSV2KeyProducer(KEY_PREFIX),
queuePriorityStrategy: new SimpleWeightedChoiceStrategy({
queueSelectionCount: env.V2_MARQS_QUEUE_SELECTION_COUNT,
}),
envQueuePriorityStrategy: new NoopWeightedChoiceStrategy(), // We don't use this in v2, since all queues go through the shared queue
workers: 0,
redis: redisOptions,
defaultEnvConcurrency: env.V2_MARQS_DEFAULT_ENV_CONCURRENCY, // this is so we aren't limited by the environment concurrency
defaultOrgConcurrency: env.DEFAULT_ORG_EXECUTION_CONCURRENCY_LIMIT,
visibilityTimeoutInMs: env.V2_MARQS_VISIBILITY_TIMEOUT_MS, // 15 minutes
enableRebalancing: false,
});
}
export type V2QueueConsumerOptions = {
pollInterval?: number;
retryOptions?: RetryOptions;
};
const MessageBody = z.object({
version: z.literal("v1").default("v1"),
runId: z.string(),
attempt: z.number().default(1),
});
export class V2QueueConsumer {
private _enabled = false;
private _pollInterval: number;
private _retryOptions: RetryOptions = {
maxAttempts: 3,
factor: 2,
minTimeoutInMs: 1000,
maxTimeoutInMs: 60000,
randomize: true,
};
private _id: string;
constructor(private _options: V2QueueConsumerOptions = {}) {
this._pollInterval = this._options.pollInterval || 1000;
this._retryOptions = {
...this._retryOptions,
...this._options.retryOptions,
};
this._id = generateFriendlyId("v2-consumer", 6);
}
async start(startDelay: number = 0) {
if (this._enabled) {
return;
}
this._enabled = true;
// Only putting this here once does not actually delay the start of the consumer (for some reason)
await new Promise((resolve) => setTimeout(resolve, startDelay));
await new Promise((resolve) => setTimeout(resolve, startDelay));
logger.debug(`[marqsv2] Starting V2QueueConsumer`, {
startDelay,
});
return this.#doWork().catch(console.error);
}
async stop() {
if (!this._enabled) {
return;
}
logger.debug("[marqsv2] Stopping V2QueueConsumer");
this._enabled = false;
}
async #doWork() {
if (!this._enabled) {
return;
}
await this.#doWorkInternal();
}
async #doWorkInternal() {
const message = await marqsv2?.dequeueMessageInSharedQueue(this._id);
if (!message) {
setTimeout(() => this.#doWork(), this._pollInterval);
return;
}
const messageBody = MessageBody.safeParse(message.data);
if (!messageBody.success) {
logger.error("[marqsv2] Failed to parse message", {
queueMessage: message.data,
error: messageBody.error,
});
await marqsv2?.acknowledgeMessage(message.messageId);
setTimeout(() => this.#doWork(), this._pollInterval);
return;
}
logger.debug("[V2QueueConsumer] Received message", {
messageData: messageBody.data,
});
try {
const service = new PerformRunExecutionV3Service();
await service.call({
id: messageBody.data.runId,
reason: "EXECUTE_JOB",
isRetry: false,
lastAttempt: false,
});
} catch (error) {
logger.error("[marqsv2] Failed to execute job", {
runId: messageBody.data.runId,
error,
});
const attempt = messageBody.data.attempt + 1;
const retryDelay = calculateNextRetryDelay(this._retryOptions, attempt);
if (!retryDelay) {
logger.error("[marqsv2] Job failed after max attempts", {
runId: messageBody.data.runId,
attempt,
});
await marqsv2?.acknowledgeMessage(message.messageId);
} else {
await marqsv2?.nackMessage(message.messageId, Date.now() + retryDelay, {
attempt,
});
}
} finally {
setTimeout(() => this.#doWork(), this._pollInterval);
}
}
}
interface V2QueueConsumerPoolOptions {
poolSize: number;
pollInterval: number;
}
class V2QueueConsumerPool {
#consumers: V2QueueConsumer[];
#shuttingDown: boolean = false;
constructor(private opts: V2QueueConsumerPoolOptions) {
this.#consumers = Array(opts.poolSize)
.fill(null)
.map((_, i) => new V2QueueConsumer({ pollInterval: opts.pollInterval }));
process.on("SIGTERM", this.#handleSignal.bind(this));
process.on("SIGINT", this.#handleSignal.bind(this));
}
async start() {
await Promise.allSettled(
this.#consumers.map((consumer, i) =>
consumer.start(i * (this.opts.pollInterval / this.opts.poolSize))
)
);
}
async stop() {
await Promise.allSettled(this.#consumers.map((consumer) => consumer.stop()));
}
async #handleSignal(signal: string) {
if (this.#shuttingDown) {
return;
}
this.#shuttingDown = true;
logger.debug(`[V2QueueConsumerPool] Received ${signal}, shutting down...`);
this.stop().finally(() => {
logger.debug("V2QueueConsumerPool shutdown");
});
}
}
export const v2QueueConsumerPool = singleton("v2QueueConsumerPool", initalizePool);
async function initalizePool() {
if (env.V2_MARQS_ENABLED === "0") {
return;
}
if (env.V2_MARQS_CONSUMER_POOL_ENABLED === "0") {
return;
}
console.log(
`🎱 Initializing V2QueueConsumerPool (poolSize=${env.V2_MARQS_CONSUMER_POOL_SIZE}, pollInterval=${env.V2_MARQS_CONSUMER_POLL_INTERVAL_MS})`
);
const pool = new V2QueueConsumerPool({
poolSize: env.V2_MARQS_CONSUMER_POOL_SIZE,
pollInterval: env.V2_MARQS_CONSUMER_POLL_INTERVAL_MS,
});
await pool.start();
return pool;
}
export async function putConcurrencyLimitGroup(
concurrencyLimitGroup: ConcurrencyLimitGroup,
env: AuthenticatedEnvironment
): Promise<void> {
logger.debug(`[marqsv2] Updating concurrency limit group`, {
concurrencyLimitGroup,
environment: env,
});
await marqsv2?.updateQueueConcurrencyLimits(
env,
`group/${concurrencyLimitGroup.name}`,
concurrencyLimitGroup.concurrencyLimit
);
}
export async function putJobConcurrencyLimit(
job: Job,
version: JobVersion,
env: AuthenticatedEnvironment
): Promise<void> {
logger.debug(`[marqsv2] Updating job concurrency limit`, {
job,
version,
environment: env,
});
if (typeof version.concurrencyLimit === "number" && version.concurrencyLimit > 0) {
await marqsv2?.updateQueueConcurrencyLimits(env, `job/${job.slug}`, version.concurrencyLimit);
} else {
await marqsv2?.removeQueueConcurrencyLimits(env, `job/${job.slug}`);
}
}