11import { Redis , type RedisOptions } from 'ioredis'
22import type { Adapter , AcquiredJob } from '../contracts/adapter.js'
33import type { JobData } from '../types/main.js'
4+ import { DEFAULT_PRIORITY } from '../constants.js'
5+ import { calculateScore } from '../utils.js'
46
57const redisKey = 'jobs'
68type RedisConfig = Redis | RedisOptions
@@ -25,6 +27,8 @@ const ACQUIRE_JOB_SCRIPT = `
2527 for i = 1, #ready_jobs do
2628 local job_data = ready_jobs[i]
2729 local job = cjson.decode(job_data)
30+ -- Score = priority * 1e13 + timestamp
31+ -- Lower score = higher priority, FIFO within same priority
2832 local priority = job.priority or 5
2933 local timestamp = tonumber(now)
3034 local score = priority * 10000000000000 + timestamp
@@ -115,6 +119,8 @@ const RETRY_JOB_SCRIPT = `
115119 if retry_at and retry_at > now then
116120 redis.call('ZADD', delayed_key, retry_at, job_data)
117121 else
122+ -- Score = priority * 1e13 + timestamp
123+ -- Lower score = higher priority, FIFO within same priority
118124 local priority = job.priority or 5
119125 local score = priority * 10000000000000 + now
120126 redis.call('ZADD', pending_key, score, job_data)
@@ -164,6 +170,8 @@ const RECOVER_STALLED_JOBS_SCRIPT = `
164170 -- Recover: increment stalledCount and put back in pending
165171 job.stalledCount = current_stalled_count + 1
166172 local job_data = cjson.encode(job)
173+ -- Score = priority * 1e13 + timestamp
174+ -- Lower score = higher priority, FIFO within same priority
167175 local priority = job.priority or 5
168176 local score = priority * 10000000000000 + now
169177 redis.call('ZADD', pending_key, score, job_data)
@@ -297,12 +305,9 @@ export class RedisAdapter implements Adapter {
297305 }
298306
299307 async pushOn ( queue : string , jobData : JobData ) : Promise < void > {
300- const priority = jobData . priority ?? 5
301-
302- // Use priority as primary score, add timestamp for FIFO order within same priority
303- // Date.now() precision is sufficient but perfect FIFO within the same millisecond is not guaranteed
308+ const priority = jobData . priority ?? DEFAULT_PRIORITY
304309 const timestamp = Date . now ( )
305- const score = priority * 1e13 + timestamp
310+ const score = calculateScore ( priority , timestamp )
306311
307312 await this . #connection. zadd ( `${ redisKey } ::${ queue } ` , score , JSON . stringify ( jobData ) )
308313 }
0 commit comments