Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The ecosystem · jobs and cron

Work that runs later, and again until it is done

Work that shouldn't hold up a request (a welcome mail, a nightly cleanup, a call to a slow service) becomes a job: a row in your app's database (Postgres or SQLite), run in the background by workers, and tried again, a little later each time, until it succeeds. A schedule queues a job when its time comes. Send email from a job (packages/email), so an unreachable mail server is tried again.

packages/jobs is a plugin written in Roc, on what the server platform gives any plugin: the database and its notifications, background loops, and isolated calls (plugins).

Installing it#

Name the package in your app's header and list its plugin in App.program (this app also names packages/admin, for the jobs page):

app [program] { admin: "…/packages/admin/main.roc", jobs: "…/packages/jobs/main.roc", pf: platform "…/server/platform/main.roc" }
test/e2e/app/main.roc, in part
import jobs.Cron
import jobs.Job
import Generated/App
import Jobs
…
program = App.program({
	init!: |started| Ok({ started: started }),
	…
	# The jobs plugin (packages/jobs): the kinds of job the app's modules define, and a schedule. The
	# jobs page (packages/admin) is a route of the app's, for members only (routes/(staff)/).
	plugins: [
		Job.plugin({ jobs: App.jobs, crons: [Cron.every("0 3 * * *", Jobs.welcome, { member: "everyone" })] }),
	],
})

Job.plugin takes one record; only jobs is required:

FieldDefaultWhat it is
jobs(required)the kinds of job the workers run: App.jobs, every kind your modules define, found by rocx generate (and every build)
cronsnonethe schedules, each a Cron.every(…) (below)
workers4how many jobs run at once
retry_ms1000the wait before a failed job's second attempt, doubled for each attempt after
on_failed!nothing morecalled with a job that failed for good, after it is logged: its kind, id, attempts and error (for an error tracker, packages/posthog's PostHog.job_failed!)
keep_done_msa weekhow long a done job is kept after it finished, then swept (below)
keep_failed_ms30 daysthe same for a failed or canceled job
sweep_msan hourhow often finished jobs are swept, besides at start

The plugin adds the queue's table, rocx_jobs (migration jobs/0001_jobs), the workers, the schedules' loop and the sweep. At start it checks every schedule and queues again the jobs a stop cut short. Without the plugin, queueing a job is an error that says to list it. An app on SQLite (the default, data/app.db) always has its database. On Postgres with no DATABASE_URL, the server doesn't start, and says why; under --dev and --debug it starts with a warning, the plugin runs nothing, and queueing returns the database's error.

A job#

A kind of job has a name and a function that does the work. The function gets your app's context (what its init! made) and the job's input, any type Roc can write as JSON. It answers Ok({}) when the work is done, or Err(why), and the job runs again later.

server/test/app/main.roc, in part
## Writes what it was told to the job log.
note_job : Job.Kind(_, { run : Str, said : Str })
note_job = Job.define(
	"note",
	|_context, { run, said }|
		match Db.run!("insert into job_log (kind, said) values ('note', $1)", [Text("${run} ${said}")]) {
			Ok(_) => Ok({})
			Err(DbErr(why)) => Err(why)
		},
)

Define kinds at the top of a module's block, as here: rocx generate (and every build) finds every Job.define and Job.define_with there and lists them in App.jobs. A program written by hand lists Job.handler(kind) for each kind instead.

Queueing one#

server/test/app/main.roc, in part
("POST", "/jobs/note") =>
	match Job.enqueue!(note_job, { run, said: Server.text_of(request) }, {}) {
		Ok({}) => text(202, "queued")
		Err(JobErr(why)) => text(500, why)
	}
("POST", "/jobs/later") =>
	match Job.enqueue!(note_job, { run, said: "later" }, { when: At(Time.now_millis!({}) + 400) }) {

Job.enqueue!(kind, input, {}) queues a job to run when a worker is free. { when: At(ms) } holds it until that moment, in milliseconds since the epoch, as Time.now_millis! gives it (a past moment means now). when defaults to Now. The input is stored as JSON and read back as the kind's input type. Options have defaults: a call names only what it changes, and new options won't break it.

Queued inside Db.transaction!, a job is a row in the transaction: it runs only if the transaction commits (transactions). Job's errors are open unions ([JobErr(Str), ..others]), like Db's. So one transaction's body can use ? on its statements, its jobs and your own errors together, and its caller matches JobErr beside DbErr.

On a schedule#

Cron.every("0 3 * * *", nightly, {})       # five fields, UTC: at 03:00 each day
Cron.every("* * * * * *", tick_job, {})    # six begin with seconds: every second

A schedule in crons queues its job, with its input, each time it comes round. Cron syntax: five fields (minute hour day month weekday), or six with seconds first, always UTC. A field is *, a number, a range (1-5), a step (*/15) or a list of them (1,15,30). Months and weekdays may be named (JAN, MON).

Each scheduled job is keyed by its schedule and due second, so a restart never queues it twice, and a failed run is retried like any job. A schedule the parser (Roc too) can't read, or whose job the plugin doesn't run, stops the server at start, saying why.

Attempts, time limits and keys#

server/test/app/Samples.roc, in part
## A reminder: tried once, within a minute (`Job.define`'s are tried five times, with no limit).
reminder : Job.Kind(_, { member : Str })
reminder = Job.define_with("reminder", { attempts: 1, timeout_ms: 60_000 }, |_context, { member }| if (member.is_empty()) Err("no one to remind") else Ok({}))

## A member's reminder, a day from now: one at a time, keyed by the member, so a second is
## `Exists`, and nothing is queued.
remind_tomorrow! : Str => Try([Queued, Exists], [JobErr(Str)])
remind_tomorrow! = |member| Job.enqueue_keyed!(reminder, { member: member }, { when: At(Time.now_millis!({}) + 86_400_000), key: "reminder:${member}" })

## Not tomorrow after all: canceled, or moved to an hour from now. Each says how many it changed.
forget_reminder! : Str => Try(U64, [JobErr(Str)])
forget_reminder! = |member| Job.cancel!("reminder:${member}")

remind_sooner! : Str => Try(U64, [JobErr(Str)])
remind_sooner! = |member| Job.move!("reminder:${member}", At(Time.now_millis!({}) + 3_600_000))

How jobs run#

Reading the queue#

server/test/app/Samples.roc, in part
## The last twenty reminders that failed, and why: what an app's own page of jobs might list.
failed_reminders! : {} => Try(List(Str), [JobErr(Str)])
failed_reminders! = |{}| {
	rows = Job.list!({ state: "failed", kind: "reminder", before_id: 0, limit: 20 })?
	Ok(
		rows.map(
			|row|
				match row.last_error {
					Some(why) => "${row.id.to_str()}: ${why}"
					Null => row.id.to_str()
				},
		),
	)
}

Job.list!({ state, kind, before_id, limit }) reads jobs, newest first; "" and 0 mean any. Each is a Job.Row: id, kind, input (as JSON), state (queued, running, done, failed or canceled), attempts and max_attempts, key, last error, and times in milliseconds. Everything else the jobs page uses is there for your pages too:

The jobs page#

server/test/app/main.roc, in part
admins_only : Middleware(Str, Str)
admins_only = Middleware.make(|request, context, next!| if (Server.header(request, "x-admin") == Ok("yes")) next!(request, context) else Server.refused(403, "admins only"))

# … in its routes
# The jobs page (packages/admin), on a route of the app's (D-116), behind a guard of its own, with
# a link back to the app.
(_, "/admin/jobs") => Middleware.run!(admins_only, request, context, |passed, _| JobsPage.respond!(passed, { mount: "/admin/jobs", back: { label: "Acme Tests", href: "/" } }))

packages/admin draws a page of the queue on a route of yours, for your admins only. Call JobsPage.respond!(request, { mount }) from a respond!, which answers every method, in a folder whose middleware knows who is an admin. mount is the route's path. The page needs the jobs plugin. back is a link to your app's own pages, first in the sidebar (none by default). At the sidebar's foot, Back to the app goes to the page of yours you came from, or to /.

routes/(admin)/admin/jobs/+server.roc
import admin.JobsPage

# routes/(admin)/+middleware.roc guards it, as every route in (admin)/: middleware = Middlewares.admin
respond! = |{ request, .. }| JobsPage.respond!(request, { mount: "/admin/jobs" })

Not yet#