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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
32 changes: 32 additions & 0 deletions packages/payload-cloud/src/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,38 @@ describe('plugin', () => {
})
})
})

describe('cron jobs', () => {
test('should always set global instance identifier, even with no cron jobs or enabled: false', async () => {
const plugin = payloadCloudPlugin({
cronJobs: {
enabled: false,
},
})
const config = await plugin(createConfig())

const globalInstance = config.globals?.find(
(global) => global.slug === 'payload-cloud-instance',
)

expect(globalInstance).toBeDefined()
expect(globalInstance?.fields).toStrictEqual([
{
name: 'instance',
type: 'text',
required: true,
},
]),
expect(globalInstance?.admin?.hidden).toStrictEqual(true)

const plugin2 = payloadCloudPlugin()
const config2 = await plugin(createConfig())
const globalInstance2 = config2.globals?.find(
(global) => global.slug === 'payload-cloud-instance',
)
expect(globalInstance2).toBeDefined()
})
})
})

function assertCloudStorage(config: Config) {
Expand Down
76 changes: 76 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,79 @@ 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)',
Copy link
Member

Choose a reason for hiding this comment

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

Any specific reason we want to put every minute on the end here? What if they change the cron to no longer be every minute and this stays?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This only ends up in the DB if the user does not define any cronJob. See line 142

}
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,
},
})

await waitRandomTime()

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 waitRandomTime(): Promise<void> {
const min = 1000 // 1 second in milliseconds
const max = 5000 // 5 seconds in milliseconds
const randomTime = Math.floor(Math.random() * (max - min + 1)) + min

return new Promise((resolve) => setTimeout(resolve, randomTime))
}

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.
* @default '* * * * *' (every minute).
*
* @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)
* │ │ │ │ │
* │ │ │ │ │
* - '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.
* @default true
* @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