-
Notifications
You must be signed in to change notification settings - Fork 390
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
feat(queue): add new upsertJobScheduler method #2797
Merged
Merged
Changes from 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
1776105
feat(queue): add new upsertJobScheduler method
manast d9cb0c0
chore: fix compiling error
manast a2bc76b
test: remove irrelevant test
manast e288570
chore: update upsertJobScheduler to use Omit for stricter field valid…
manast 599bceb
feat(queue): add new upsertJobScheduler method
manast b61f5f3
chore: fix compiling error
manast 061c4a7
test: remove irrelevant test
manast e1516ff
chore: update upsertJobScheduler to use Omit for stricter field valid…
manast bd6ed2a
chore: return the actual error code in removeJob
manast fb3748c
fix: do not remove delayed jobs that belongs to a job scheduler when …
manast 96b62ab
fix: do not remove delayed jobs that belongs to a job scheduler when …
manast 0dc1b22
chore: update cleanJobsInSet in python
manast 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 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 |
---|---|---|
@@ -0,0 +1,250 @@ | ||
import { parseExpression } from 'cron-parser'; | ||
import { RedisClient, RepeatBaseOptions, RepeatOptions } from '../interfaces'; | ||
import { JobsOptions, RepeatStrategy } from '../types'; | ||
import { Job } from './job'; | ||
import { Scripts } from './scripts'; | ||
import { QueueBase } from './queue-base'; | ||
import { RedisConnection } from './redis-connection'; | ||
|
||
export interface JobSchedulerJson { | ||
key: string; // key is actually the job scheduler id | ||
name: string; | ||
id?: string | null; | ||
endDate: number | null; | ||
tz: string | null; | ||
pattern: string | null; | ||
every?: string | null; | ||
next: number; | ||
} | ||
|
||
export class JobScheduler extends QueueBase { | ||
private repeatStrategy: RepeatStrategy; | ||
|
||
constructor( | ||
name: string, | ||
opts: RepeatBaseOptions, | ||
Connection?: typeof RedisConnection, | ||
) { | ||
super(name, opts, Connection); | ||
|
||
this.repeatStrategy = | ||
(opts.settings && opts.settings.repeatStrategy) || getNextMillis; | ||
} | ||
|
||
async upsertJobScheduler<T = any, R = any, N extends string = string>( | ||
jobSchedulerId: string, | ||
repeatOpts: Omit<RepeatOptions, 'key'>, | ||
jobName: N, | ||
jobData: T, | ||
opts: Omit<JobsOptions, 'jobId' | 'repeat' | 'delay'>, | ||
{ override }: { override: boolean }, | ||
): Promise<Job<T, R, N> | undefined> { | ||
// Check if we reached the limit of the repeatable job's iterations | ||
const iterationCount = repeatOpts.count ? repeatOpts.count + 1 : 1; | ||
if ( | ||
typeof repeatOpts.limit !== 'undefined' && | ||
iterationCount > repeatOpts.limit | ||
) { | ||
return; | ||
} | ||
|
||
// Check if we reached the end date of the repeatable job | ||
let now = Date.now(); | ||
const { endDate } = repeatOpts; | ||
if (!(typeof endDate === undefined) && now > new Date(endDate!).getTime()) { | ||
return; | ||
} | ||
|
||
const prevMillis = opts.prevMillis || 0; | ||
now = prevMillis < now ? now : prevMillis; | ||
|
||
const nextMillis = await this.repeatStrategy(now, repeatOpts, jobName); | ||
const { every, pattern } = repeatOpts; | ||
|
||
const hasImmediately = Boolean( | ||
(every || pattern) && repeatOpts.immediately, | ||
); | ||
const offset = hasImmediately && every ? now - nextMillis : undefined; | ||
if (nextMillis) { | ||
if (override) { | ||
await this.scripts.addJobScheduler(jobSchedulerId, nextMillis, { | ||
name: jobName, | ||
endDate: endDate ? new Date(endDate).getTime() : undefined, | ||
tz: repeatOpts.tz, | ||
pattern, | ||
every, | ||
}); | ||
} else { | ||
await this.scripts.updateJobSchedulerNextMillis( | ||
jobSchedulerId, | ||
nextMillis, | ||
); | ||
} | ||
|
||
const { immediately, ...filteredRepeatOpts } = repeatOpts; | ||
|
||
return this.createNextJob<T, R, N>( | ||
jobName, | ||
nextMillis, | ||
jobSchedulerId, | ||
{ ...opts, repeat: { offset, ...filteredRepeatOpts } }, | ||
jobData, | ||
iterationCount, | ||
hasImmediately, | ||
); | ||
} | ||
} | ||
|
||
private async createNextJob<T = any, R = any, N extends string = string>( | ||
name: N, | ||
nextMillis: number, | ||
jobSchedulerId: string, | ||
opts: JobsOptions, | ||
data: T, | ||
currentCount: number, | ||
hasImmediately: boolean, | ||
) { | ||
// | ||
// Generate unique job id for this iteration. | ||
// | ||
const jobId = this.getSchedulerNextJobId({ | ||
jobSchedulerId: jobSchedulerId, | ||
nextMillis, | ||
}); | ||
|
||
const now = Date.now(); | ||
const delay = | ||
nextMillis + (opts.repeat.offset ? opts.repeat.offset : 0) - now; | ||
|
||
const mergedOpts = { | ||
...opts, | ||
jobId, | ||
delay: delay < 0 || hasImmediately ? 0 : delay, | ||
timestamp: now, | ||
prevMillis: nextMillis, | ||
repeatJobKey: jobSchedulerId, | ||
}; | ||
|
||
mergedOpts.repeat = { ...opts.repeat, count: currentCount }; | ||
|
||
return this.Job.create<T, R, N>(this, name, data, mergedOpts); | ||
} | ||
|
||
async removeJobScheduler(jobSchedulerId: string): Promise<number> { | ||
return this.scripts.removeJobScheduler(jobSchedulerId); | ||
} | ||
|
||
private async getSchedulerData( | ||
client: RedisClient, | ||
key: string, | ||
next?: number, | ||
): Promise<JobSchedulerJson> { | ||
const jobData = await client.hgetall(this.toKey('repeat:' + key)); | ||
|
||
if (jobData) { | ||
return { | ||
key, | ||
name: jobData.name, | ||
endDate: parseInt(jobData.endDate) || null, | ||
tz: jobData.tz || null, | ||
pattern: jobData.pattern || null, | ||
every: jobData.every || null, | ||
next, | ||
}; | ||
} | ||
|
||
return this.keyToData(key, next); | ||
} | ||
|
||
private keyToData(key: string, next?: number): JobSchedulerJson { | ||
const data = key.split(':'); | ||
const pattern = data.slice(4).join(':') || null; | ||
|
||
return { | ||
key, | ||
name: data[0], | ||
id: data[1] || null, | ||
endDate: parseInt(data[2]) || null, | ||
tz: data[3] || null, | ||
pattern, | ||
next, | ||
}; | ||
} | ||
|
||
async getJobSchedulers( | ||
start = 0, | ||
end = -1, | ||
asc = false, | ||
): Promise<JobSchedulerJson[]> { | ||
const client = await this.client; | ||
const jobSchedulersKey = this.keys.repeat; | ||
|
||
const result = asc | ||
? await client.zrange(jobSchedulersKey, start, end, 'WITHSCORES') | ||
: await client.zrevrange(jobSchedulersKey, start, end, 'WITHSCORES'); | ||
|
||
const jobs = []; | ||
for (let i = 0; i < result.length; i += 2) { | ||
jobs.push( | ||
this.getSchedulerData(client, result[i], parseInt(result[i + 1])), | ||
); | ||
} | ||
return Promise.all(jobs); | ||
} | ||
|
||
async getSchedulersCount( | ||
client: RedisClient, | ||
prefix: string, | ||
queueName: string, | ||
): Promise<number> { | ||
return client.zcard(`${prefix}:${queueName}:repeat`); | ||
} | ||
|
||
private getSchedulerNextJobId({ | ||
nextMillis, | ||
jobSchedulerId, | ||
}: { | ||
jobSchedulerId: string; | ||
nextMillis: number | string; | ||
}) { | ||
return `repeat:${jobSchedulerId}:${nextMillis}`; | ||
} | ||
} | ||
|
||
export const getNextMillis = ( | ||
millis: number, | ||
opts: RepeatOptions, | ||
): number | undefined => { | ||
const pattern = opts.pattern; | ||
if (pattern && opts.every) { | ||
throw new Error( | ||
'Both .pattern and .every options are defined for this repeatable job', | ||
); | ||
} | ||
|
||
if (opts.every) { | ||
return ( | ||
Math.floor(millis / opts.every) * opts.every + | ||
(opts.immediately ? 0 : opts.every) | ||
); | ||
} | ||
|
||
const currentDate = | ||
opts.startDate && new Date(opts.startDate) > new Date(millis) | ||
? new Date(opts.startDate) | ||
: new Date(millis); | ||
const interval = parseExpression(pattern, { | ||
...opts, | ||
currentDate, | ||
}); | ||
|
||
try { | ||
if (opts.immediately) { | ||
return new Date().getTime(); | ||
} else { | ||
return interval.next().getTime(); | ||
} | ||
} catch (e) { | ||
// Ignore error | ||
} | ||
}; |
This file contains 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
there is a current logic to add a repeatable job without an specific key, this value is generated base on the repeat options. We could preserve that functionality by generating jobSchedulerId if it's not specified
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's what I want to avoid actually. With this API the key is mandatory, and when the old API gets deprecated it will be mandatory. Forcing the user to specify a key eliminates most of the pain we had with the old API and also makes the code much simpler and robust.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
got it, let's do it