-
-
Notifications
You must be signed in to change notification settings - Fork 901
fix(v3): eagerly dequeue messages from a queue when that queue is added to or removed from (v4 backport) #2438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,6 +44,9 @@ import { | |
| } from "./constants.server"; | ||
| import { setInterval } from "node:timers/promises"; | ||
| import { tryCatch } from "@trigger.dev/core/utils"; | ||
| import { Worker, type WorkerConcurrencyOptions } from "@trigger.dev/redis-worker"; | ||
| import z from "zod"; | ||
| import { Logger } from "@trigger.dev/core/logger"; | ||
|
|
||
| const KEY_PREFIX = "marqs:"; | ||
|
|
||
|
|
@@ -74,6 +77,24 @@ export type MarQSOptions = { | |
| subscriber?: MessageQueueSubscriber; | ||
| sharedWorkerQueueConsumerIntervalMs?: number; | ||
| sharedWorkerQueueMaxMessageCount?: number; | ||
| eagerDequeuingEnabled?: boolean; | ||
| workerOptions: { | ||
| pollIntervalMs?: number; | ||
| immediatePollIntervalMs?: number; | ||
| shutdownTimeoutMs?: number; | ||
| concurrency?: WorkerConcurrencyOptions; | ||
| enabled?: boolean; | ||
| }; | ||
| }; | ||
|
|
||
| const workerCatalog = { | ||
| processQueueForWorkerQueue: { | ||
| schema: z.object({ | ||
| queueKey: z.string(), | ||
| parentQueueKey: z.string(), | ||
| }), | ||
| visibilityTimeoutMs: 30_000, | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
|
|
@@ -83,6 +104,7 @@ export class MarQS { | |
| private redis: Redis; | ||
| public keys: MarQSKeyProducer; | ||
| #rebalanceWorkers: Array<AsyncWorker> = []; | ||
| private worker: Worker<typeof workerCatalog>; | ||
|
|
||
| constructor(private readonly options: MarQSOptions) { | ||
| this.redis = options.redis; | ||
|
|
@@ -91,6 +113,29 @@ export class MarQS { | |
|
|
||
| this.#startRebalanceWorkers(); | ||
| this.#registerCommands(); | ||
|
|
||
| this.worker = new Worker({ | ||
| name: "marqs-worker", | ||
| redisOptions: { | ||
| ...options.redis.options, | ||
| keyPrefix: `${options.redis.options.keyPrefix}:worker`, | ||
| }, | ||
| catalog: workerCatalog, | ||
| concurrency: options.workerOptions?.concurrency, | ||
| pollIntervalMs: options.workerOptions?.pollIntervalMs ?? 1000, | ||
| immediatePollIntervalMs: options.workerOptions?.immediatePollIntervalMs ?? 100, | ||
| shutdownTimeoutMs: options.workerOptions?.shutdownTimeoutMs ?? 10_000, | ||
| logger: new Logger("MarQSWorker", "info"), | ||
| jobs: { | ||
| processQueueForWorkerQueue: async (job) => { | ||
| await this.#processQueueForWorkerQueue(job.payload.queueKey, job.payload.parentQueueKey); | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
ericallam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (options.workerOptions?.enabled) { | ||
| this.worker.start(); | ||
| } | ||
| } | ||
|
|
||
| get name() { | ||
|
|
@@ -280,6 +325,21 @@ export class MarQS { | |
| span.setAttribute("reserve_recursive_queue", reserve.recursiveQueue); | ||
| } | ||
|
|
||
| if (env.type !== "DEVELOPMENT" && this.options.eagerDequeuingEnabled) { | ||
| // This will move the message to the worker queue so it can be dequeued | ||
| await this.worker.enqueueOnce({ | ||
| id: messageQueue, // dedupe by environment, queue, and concurrency key | ||
| job: "processQueueForWorkerQueue", | ||
| payload: { | ||
| queueKey: messageQueue, | ||
| parentQueueKey: parentQueue, | ||
| }, | ||
| // Add a small delay to dedupe messages so at most one of these will processed, | ||
| // every 500ms per queue, concurrency key, and environment | ||
| availableAt: new Date(Date.now() + 500), // 500ms from now | ||
| }); | ||
| } | ||
|
Comment on lines
+327
to
+340
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Gate eager-dequeue behind worker enabled and DRY the 500ms magic number. If the worker is disabled, enqueueOnce will accumulate jobs that never run. Also, replace the hardcoded 500ms with a shared constant. Apply: - if (env.type !== "DEVELOPMENT" && this.options.eagerDequeuingEnabled) {
+ if (
+ env.type !== "DEVELOPMENT" &&
+ this.options.eagerDequeuingEnabled &&
+ this.options.workerOptions?.enabled
+ ) {
// This will move the message to the worker queue so it can be dequeued
await this.worker.enqueueOnce({
id: messageQueue, // dedupe by environment, queue, and concurrency key
job: "processQueueForWorkerQueue",
payload: {
queueKey: messageQueue,
parentQueueKey: parentQueue,
},
// Add a small delay to dedupe messages so at most one of these will processed,
// every 500ms per queue, concurrency key, and environment
- availableAt: new Date(Date.now() + 500), // 500ms from now
+ availableAt: new Date(Date.now() + EAGER_DEQUEUE_DEBOUNCE_MS),
});
}Add once near KEY_PREFIX: const EAGER_DEQUEUE_DEBOUNCE_MS = 500;🤖 Prompt for AI Agents |
||
|
|
||
| const result = await this.#callEnqueueMessage(messagePayload, reserve); | ||
|
|
||
| if (result) { | ||
|
|
@@ -870,6 +930,64 @@ export class MarQS { | |
| ); | ||
| } | ||
|
|
||
| async #processQueueForWorkerQueue(queueKey: string, parentQueueKey: string) { | ||
| return this.#trace("processQueueForWorkerQueue", async (span) => { | ||
| span.setAttributes({ | ||
| [SemanticAttributes.QUEUE]: queueKey, | ||
| [SemanticAttributes.PARENT_QUEUE]: parentQueueKey, | ||
| }); | ||
|
|
||
| const maxCount = this.options.sharedWorkerQueueMaxMessageCount ?? 10; | ||
|
|
||
| const dequeuedMessages = await this.#callDequeueMessages({ | ||
| messageQueue: queueKey, | ||
| parentQueue: parentQueueKey, | ||
| maxCount, | ||
| }); | ||
|
|
||
| if (!dequeuedMessages || dequeuedMessages.length === 0) { | ||
| return; | ||
| } | ||
|
|
||
| await this.#trace( | ||
| "addToWorkerQueue", | ||
| async (addToWorkerQueueSpan) => { | ||
| const workerQueueKey = this.keys.sharedWorkerQueueKey(); | ||
|
|
||
| addToWorkerQueueSpan.setAttributes({ | ||
| message_count: dequeuedMessages.length, | ||
| [SemanticAttributes.PARENT_QUEUE]: workerQueueKey, | ||
| }); | ||
|
|
||
| await this.redis.rpush( | ||
| workerQueueKey, | ||
| ...dequeuedMessages.map((message) => message.messageId) | ||
| ); | ||
| }, | ||
| { | ||
| kind: SpanKind.INTERNAL, | ||
| attributes: { | ||
| [SEMATTRS_MESSAGING_OPERATION]: "receive", | ||
| [SEMATTRS_MESSAGING_SYSTEM]: "marqs", | ||
| }, | ||
| } | ||
| ); | ||
|
|
||
| // If we dequeued the max count, we need to enqueue another job to dequeue the next batch | ||
| if (dequeuedMessages.length === maxCount) { | ||
| await this.worker.enqueueOnce({ | ||
| id: queueKey, | ||
| job: "processQueueForWorkerQueue", | ||
| payload: { | ||
| queueKey, | ||
| parentQueueKey, | ||
| }, | ||
| availableAt: new Date(Date.now() + 500), // 500ms from now | ||
| }); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| public async acknowledgeMessage(messageId: string, reason: string = "unknown") { | ||
| return this.#trace( | ||
| "acknowledgeMessage", | ||
|
|
@@ -901,6 +1019,20 @@ export class MarQS { | |
| messageId, | ||
| }); | ||
|
|
||
| const sharedQueueKey = this.keys.sharedQueueKey(); | ||
|
|
||
| if (this.options.eagerDequeuingEnabled && message.parentQueue === sharedQueueKey) { | ||
| await this.worker.enqueueOnce({ | ||
| id: message.queue, | ||
| job: "processQueueForWorkerQueue", | ||
| payload: { | ||
| queueKey: message.queue, | ||
| parentQueueKey: message.parentQueue, | ||
| }, | ||
| availableAt: new Date(Date.now() + 500), // 500ms from now | ||
| }); | ||
| } | ||
|
|
||
| await this.options.subscriber?.messageAcked(message); | ||
| }, | ||
| { | ||
|
|
@@ -2482,5 +2614,17 @@ function getMarQSClient() { | |
| subscriber: concurrencyTracker, | ||
| sharedWorkerQueueConsumerIntervalMs: env.MARQS_SHARED_WORKER_QUEUE_CONSUMER_INTERVAL_MS, | ||
| sharedWorkerQueueMaxMessageCount: env.MARQS_SHARED_WORKER_QUEUE_MAX_MESSAGE_COUNT, | ||
| eagerDequeuingEnabled: env.MARQS_SHARED_WORKER_QUEUE_EAGER_DEQUEUE_ENABLED === "1", | ||
| workerOptions: { | ||
| enabled: env.MARQS_WORKER_ENABLED === "1", | ||
| pollIntervalMs: env.MARQS_WORKER_POLL_INTERVAL_MS, | ||
| immediatePollIntervalMs: env.MARQS_WORKER_IMMEDIATE_POLL_INTERVAL_MS, | ||
| shutdownTimeoutMs: env.MARQS_WORKER_SHUTDOWN_TIMEOUT_MS, | ||
| concurrency: { | ||
| workers: env.MARQS_WORKER_CONCURRENCY_LIMIT, | ||
| tasksPerWorker: env.MARQS_WORKER_CONCURRENCY_TASKS_PER_WORKER, | ||
| limit: env.MARQS_WORKER_CONCURRENCY_LIMIT, | ||
| }, | ||
| }, | ||
| }); | ||
ericallam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.