Skip to content
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(payload-cloud): set up cron jobs on init #10106

Merged
merged 18 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/payload-cloud/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"ts-jest": "^29.1.0"
},
"peerDependencies": {
"croner": "9.0.0",
"payload": "workspace:*"
},
"publishConfig": {
Expand Down
66 changes: 66 additions & 0 deletions packages/payload-cloud/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { Config } from 'payload'

import { Cron } from 'croner'

import type { PluginOptions } from './types.js'

import { payloadCloudEmail } from './email.js'
Expand Down Expand Up @@ -93,5 +95,69 @@ export const payloadCloudPlugin =
})
}

// We set up cron jobs on init.
// We also make sure to only run on one instance using a instance identifier stored in a global.

// If you modify this defaults, make sure to update the TsDoc in the types file.
const DEFAULT_CRON = '* * * * *'
const DEFAULT_LIMIT = 10
const DEFAULT_CRON_JOB = {
cron: DEFAULT_CRON,
limit: DEFAULT_LIMIT,
queue: 'default (every minute)',
denolfe marked this conversation as resolved.
Show resolved Hide resolved
Comment on lines +103 to +108
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that cronjobs are defined in config.jobs.autoRun and not in the plugin, where this "default cron job" should be documented. I copy the internal question:

Should the default cronjob:

  1. be set always after jobs.autoRun if it returns an empty array []?
  2. be set only in Payload Cloud Plugin if jobs autoRun returns an empty array?
  3. there should not be a default cronjob.

Personally I like option 3 better.
If we go with option 2 where would it be documented in tsdoc? the payload cloud plugin will not have any option to configure cron jobs, just to enable or disable it

}
config.globals = [
...(config.globals || []),
{
slug: 'payload-cloud-instance',
admin: {
hidden: true,
},
fields: [
{
name: 'instance',
type: 'text',
required: true,
},
],
},
]
const newOnInit = async (payload) => {
if (config.onInit) {
await config.onInit(payload)
}
const instance = generateRandomString()

await payload.updateGlobal({
slug: 'payload-cloud-instance',
data: {
instance,
},
})

const cloudInstance = await payload.findGlobal({
slug: 'payload-cloud-instance',
})

const cronJobs = pluginOptions?.cronJobs?.run ?? [DEFAULT_CRON_JOB]
if (cloudInstance.instance === instance) {
cronJobs.forEach((cronConfig) => {
new Cron(cronConfig.cron ?? DEFAULT_CRON, async () => {
await payload.jobs.run({
limit: cronConfig.limit ?? DEFAULT_LIMIT,
queue: cronConfig.queue,
})
})
})
}
}

config.onInit = newOnInit

return config
}

function generateRandomString(): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
return Array.from({ length: 24 }, () => chars[Math.floor(Math.random() * chars.length)]).join('')
}
50 changes: 50 additions & 0 deletions packages/payload-cloud/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,57 @@ export interface PayloadCloudEmailOptions {
skipVerify?: boolean
}

export type CronConfig = {
/**
* The cron schedule for the job. Defaults to '* * * * *' (every minute).
GermanJablo marked this conversation as resolved.
Show resolved Hide resolved
*
* @example
* ┌───────────── minute (0 - 59)
* │ ┌───────────── hour (0 - 23)
* │ │ ┌───────────── day of the month (1 - 31)
* │ │ │ ┌───────────── month (1 - 12)
* │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
* │ │ │ │ │ OR sun, mon, tue, wed, thu, fri, sat
* │ │ │ │ │
* │ │ │ │ │
* - '0 * * * *' every hour at minute 0
* - '0 0 * * *' daily at midnight
* - '0 0 * * 0' weekly at midnight on Sundays
* - '0 0 1 * *' monthly at midnight on the 1st day of the month
* - '0/5 * * * *' every 5 minutes
*/
cron?: string
/**
* The limit for the job. This can be overridden by the user. Defaults to 10.
*/
limit?: number
/**
* The queue name for the job.
*/
queue?: string
}

export interface PluginOptions {
/**
* Jobs configuration. By default, there is a single
* cron job that runs every minute.
*/
cronJobs?: {
/**
* Enable the cron jobs defined in the `run` array,
* or the default cron job if `run` is not defined.
* Defaults to `true`.
GermanJablo marked this conversation as resolved.
Show resolved Hide resolved
* @note If you change this in a development environment,
* you will need to restart the server for the changes to take effect.
*/
enabled?: boolean
/**
* Cron jobs configuration. If not defined, a single
* cron job is created that runs every minute.
*/
run?: CronConfig[]
}

/** Payload Cloud Email
* @default true
*/
Expand Down
58 changes: 16 additions & 42 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading