KScript docs
EN

KScript.Queue

Queued jobs: job declarations, dispatch, retries with backoff, failed jobs, the worker that runs them, and the schedule of tasks that run at set times.

Import it at the top of a script:

<import package="KScript.Queue" />
import KScript.Queue

KScript.Queue queues jobs for kscript worker, so its examples can't run inside the docs. Copy one into a .ks.xml file and run it with kscript.

ElementsStatements

#<event>event

Declares an event: something that happened in the app, with the fields its listeners need, typed like a <type>'s. Keep events in the project's events folder. @dispatch_event(OrderPlaced(order_id: $order.id)) tells every listener: each listener for OrderPlaced { } function, and each job declared with listens_to: OrderPlaced, which is queued.Declares an event: something that happened in the app, with the fields its listeners need, typed like a type's. Keep events in the project's events folder. @dispatch_event(OrderPlaced(order_id: $order.id)) tells every listener: each listener for OrderPlaced { } function, and each job declared with listens_to: OrderPlaced, which is queued.
Declares an app event (KScript.Queue). Write event OrderPlaced { order_id: int }, then @dispatch_event(OrderPlaced(order_id: 7)).

Holds statements.Holds statements in { }. Scripts only.

AttributeValueDescription
name requireda new variable's nameThe event's name, starting with a capital letter and saying what happened: OrderPlaced, UserSignedUp.
fieldsfieldsThe fields on one line, like fn params: order_id: int, total: number. Bigger events list them one per line.
descriptiona stringWhat happened, shown on hover.
Example
<event name="OrderPlaced">
  <field name="order_id" type="int" />
</event>
<echo>{ OrderPlaced(order_id: 7).order_id }</echo>
event OrderPlaced {
  order_id: int
}
echo OrderPlaced(order_id: 7).order_id

#<job>job

Declares a job: work to do later, on a queue, by kscript worker. Its fields are the data it needs, typed like a <type>'s; fn handle() does the work and sees the fields as variables. SendWelcome(user_id: 7)->dispatch() queues one. An error in handle is retried after its backoff until its tries run out; then fn failed(err) runs and the job is kept with the failed jobs (kscript queue failed). fn middleware() gives what runs around each attempt, such as [@without_overlapping()].Declares a job: work to do later, on a queue, by kscript worker. Its fields are the data it needs, typed like a type's; fn handle() does the work and sees the fields as variables. SendWelcome(user_id: 7)->dispatch() queues one. An error in handle is retried after its backoff until its tries run out; then fn failed(err) runs and the job is kept with the failed jobs (kscript queue failed). fn middleware() gives what runs around each attempt, such as [@without_overlapping()].
Declares a background job. Put its fields and a fn handle() { ... } method inside job SendMessage { ... }.

Holds statements.Holds statements in { }.

AttributeValueDescription
name requireda new variable's nameThe job's name, starting with a capital letter: SendWelcome, BuildReport.
queuea stringThe queue it goes on, unless the dispatch names one. Defaults to default.
connectiona stringThe connection in kscript.json's queue.connections it goes to, unless the dispatch names one. Defaults to queue.default.
triesa stringAttempts before it counts as failed. Defaults to 3.
backoffexpressionHow long to wait before each retry: one time (30s), a list ([10s, 1m, 5m], the last one repeats), or 'exponential' (2s, 4s, 8s, up to 10m; the default).
timeoutexpressionThe longest one attempt may run, such as 30s or 5m. Past it the attempt stops with a JobTimeout error. Defaults to 60s.
retry_untilexpressionHow long after it was dispatched it may still be retried, such as 1h.
unique_forexpressionWhile a job with the same fields is waiting or running, another dispatch of it is dropped, for this long at most, such as 10m.
unique_bya list of names: [a, b]The fields that make two dispatches the same for unique_for: [user_id]. Defaults to all of them.
retry_onan error typeOnly errors of these types are retried: [Timeout, Network]. Others fail the job at once.
fail_onan error typeErrors of these types fail the job at once, without more tries: [Validation, NotFound].
listens_toa stringAn event the job listens to: each @dispatch_event() of it queues the job, with its fields filled from the event's.
fieldsfieldsThe fields on one line, like fn params: user_id: int, email: email. Bigger jobs list them one per line.
descriptiona stringWhat the job does, shown on hover.
OptionValueDescription
queuea stringThe queue it goes on, unless the dispatch names one. Defaults to default.
connectiona stringThe connection in kscript.json's queue.connections it goes to, unless the dispatch names one. Defaults to queue.default.
triesa stringAttempts before it counts as failed. Defaults to 3.
backoffexpressionHow long to wait before each retry: one time (30s), a list ([10s, 1m, 5m], the last one repeats), or 'exponential' (2s, 4s, 8s, up to 10m; the default).
timeoutexpressionThe longest one attempt may run, such as 30s or 5m. Past it the attempt stops with a JobTimeout error. Defaults to 60s.
retry_untilexpressionHow long after it was dispatched it may still be retried, such as 1h.
unique_forexpressionWhile a job with the same fields is waiting or running, another dispatch of it is dropped, for this long at most, such as 10m.
unique_bya list of names: [a, b]The fields that make two dispatches the same for unique_for: [user_id]. Defaults to all of them.
retry_onan error typeOnly errors of these types are retried: [Timeout, Network]. Others fail the job at once.
fail_onan error typeErrors of these types fail the job at once, without more tries: [Validation, NotFound].
listens_toa stringAn event the job listens to: each @dispatch_event() of it queues the job, with its fields filled from the event's.
descriptiona stringWhat the job does, shown on hover.
Example
<job name="SendWelcome" queue="mail" tries="5" backoff="[10s, 1m]">
  <field name="email" type="email" />
  <fn name="handle">
    <echo>Welcome, { $email }</echo>
  </fn>
</job>
<do>SendWelcome(email: 'joan@example.com')->run()</do>
job SendWelcome(queue: 'mail', tries: 5, backoff: [10s, 1m]) {
  email: email
  fn handle() {
    echo "Welcome, { .email }"
  }
}
SendWelcome(email: 'joan@example.com')->run()

#<listener>listener

Listens for an event. Each <fn> inside takes the event and runs, in order, when @dispatch_event() dispatches it: listener for OrderPlaced { fn send_receipt(event: OrderPlaced) { } }. An error in one stops the rest and reaches the dispatch. Keep listeners in the project's listeners folder, whose scripts run the first time an event is dispatched. Work that should happen later goes in a job with listens_to: OrderPlaced instead.Listens for an event. Each fn inside takes the event and runs, in order, when @dispatch_event() dispatches it: listener for OrderPlaced { fn send_receipt(event: OrderPlaced) { } }. An error in one stops the rest and reaches the dispatch. Keep listeners in the project's listeners folder, whose scripts run the first time an event is dispatched. Work that should happen later goes in a job with listens_to: OrderPlaced instead.
Listens for an event (KScript.Queue). Write listener for OrderPlaced { fn send_receipt(event: OrderPlaced) { } }.

Holds statements.Holds statements in { }. Scripts only.

AttributeValueDescription
for requireda stringThe event it listens for.
descriptiona stringWhat the listener does, shown on hover.
Example
<event name="OrderPlaced">
  <field name="order_id" type="int" />
</event>
<listener for="OrderPlaced">
  <fn name="log_order" params="event: OrderPlaced">
    <echo>Order { $event.order_id } placed</echo>
  </fn>
</listener>
<do>@dispatch_event(OrderPlaced(order_id: 7))</do>
event OrderPlaced {
  order_id: int
}
listener for OrderPlaced {
  fn log_order(event: OrderPlaced) {
    echo "Order { $event.order_id } placed"
  }
}
@dispatch_event(OrderPlaced(order_id: 7))

#<Schedule>Schedule

The schedule file (schedule.kscript): the tasks kscript schedule work runs at their times, each a <Task> with a cron schedule or an every: time, and a job to dispatch or a function to run.The schedule file (schedule.kscript): the tasks kscript schedule work runs at their times, each a Task with a cron schedule or an every: time, and a job to dispatch or a function to run.

Holds statements.Holds statements in { }. Scripts only.

Example
<Schedule>
  <Task every="5m" run="tidy" />
</Schedule>
Schedule {
  Task(every: 5m, run: @tidy)
}

#<Task>Task

A task of the schedule: when it runs (cron or every) and what it does (job, dispatched to its queue, or run, a function called by the scheduler). Task(cron: '0 3 * * *', job: PruneSessions(), without_overlapping: true).

Self-closing.A statement on its own. Scripts only. Goes inside <Schedule>Schedule.

AttributeOptionValueDescription
crona stringWhen it runs, as a cron schedule: '0 3 * * ' (03:00 every day), '/15 9-17 * * mon-fri', @hourly, @daily.
everyexpressionHow often it runs instead, in whole minutes: 1m, 5m, 1h, 1d. Counted from midnight, so every: 15m runs at :00, :15, :30 and :45.
jobexpressionA job to dispatch each time: PruneSessions() or SendDigest(kind: 'daily'). It is built when the task is due and goes on its queue for kscript worker.
runa function: @nameA function the scheduler calls each time, with no arguments: @tidy or @reports.nightly.
namea stringThe task's name in kscript schedule list and the scheduler's output. Defaults to the job's or the function's name.
without_overlappingtrue or falseThe task is skipped while its last run is still going (a dispatched job counts until a worker finishes it). Uses the queue's locks, so it holds across processes with a file or database connection.
queuea stringThe queue its job goes on, instead of the job's own.
connectiona stringThe connection its job goes to, instead of the job's own.
descriptiona stringWhat the task is for, shown by kscript schedule list.
Example
<Schedule>
  <Task cron="0 3 * * *" run="tidy" without_overlapping="true" />
</Schedule>
Schedule {
  Task(cron: '0 3 * * *', run: @tidy, without_overlapping: true)
}

Commands

Commands are called with @, in any expression: @name(arguments).

#@batch(jobs: list) → batch

Jobs dispatched together, whose progress the queue keeps: @batch($rows->map(fn(r) => ImportRow(id: $r.id)))->then(ImportDone())->catch(ImportFailed())->dispatch(). then runs when every job succeeded, catch at the first failure, and finally when all have run. ->dispatch() returns the batch; @queue()->batch($batch.id).progress reads how far it has got.
ParameterTakes
jobs requiredlist
Example
<job name="Step" fields="n: int">
  <fn name="handle"><echo>Step { $n }</echo></fn>
</job>
<job name="Done">
  <fn name="handle"><echo>All done</echo></fn>
</job>
<let name="batch" value="@batch([Step(n: 1), Step(n: 2)])->then(Done())->dispatch()" />
<echo>{ $batch.progress }%</echo>
job Step {
  n: int
  fn handle() {
    echo "Step { .n }"
  }
}
job Done {
  fn handle() {
    echo 'All done'
  }
}
$batch = @batch([Step(n: 1), Step(n: 2)])->then(Done())->dispatch()
echo "{ $batch.progress }%"

#@chain(jobs: list) → chain

Jobs that run one after another: each starts when the one before it succeeds, and a failure stops the rest. @chain([ImportCsv(path: $f), RebuildIndex()])->dispatch().
ParameterTakes
jobs requiredlist
Example
<job name="Step" fields="n: int">
  <fn name="handle"><echo>Step { $n }</echo></fn>
</job>
<do>@chain([Step(n: 1), Step(n: 2)])->run()</do>
job Step {
  n: int
  fn handle() {
    echo "Step { .n }"
  }
}
@chain([Step(n: 1), Step(n: 2)])->run()

#@dispatch_event(event: record) → number

Tells every listener of an event: runs each listener for function with it, in order, then queues each job that listens_to it (after the transaction commits, inside one). Returns how many listeners it reached. Not @emit_event(), which sends an event to the browser.
ParameterTakes
event requiredrecord
Example
<event name="OrderPlaced">
  <field name="order_id" type="int" />
</event>
<listener for="OrderPlaced">
  <fn name="log_order" params="event: OrderPlaced">
    <echo>Order { $event.order_id } placed</echo>
  </fn>
</listener>
<echo>{ @dispatch_event(OrderPlaced(order_id: 7)) } listener</echo>
event OrderPlaced {
  order_id: int
}
listener for OrderPlaced {
  fn log_order(event: OrderPlaced) {
    echo "Order { $event.order_id } placed"
  }
}
echo "{ @dispatch_event(OrderPlaced(order_id: 7)) } listener"

#@fail_job(error?)

In a job's handle: fails the job now, without more tries. Give an error (@fail_job(Validation('Bad data'))) or a message.
Example
<job name="Check" fields="n: int">
  <fn name="handle">
    <if test="$n lt 0"><do>@fail_job('n must not be negative')</do></if>
  </fn>
</job>
<try>
  <do>Check(n: -1)->run()</do>
  <catch as="err"><echo>{ $err.message }</echo></catch>
</try>
job Check {
  n: int
  fn handle() {
    if .n < 0 {
      @fail_job('n must not be negative')
    }
  }
}
try {
  Check(n: -1)->run()
} catch err {
  echo $err.message
}

#@fake_queue() → fake_queue

For tests: from now on in this run, dispatched jobs are kept instead of queued or run. $q->pushed(SendWelcome) lists them and $q->run_all() runs them.
Example
<job name="Hello" fields="who: string">
  <fn name="handle"><echo>Hello { $who }</echo></fn>
</job>
<let name="q" value="@fake_queue()" />
<do>Hello(who: 'Joan')->dispatch()</do>
<echo>{ $q->count() } queued</echo>
<do>$q->run_all()</do>
job Hello {
  who: string
  fn handle() {
    echo "Hello { .who }"
  }
}
$q = @fake_queue()
Hello(who: 'Joan')->dispatch()
echo "{ $q->count() } queued"
$q->run_all()

#@queue(name?: string, connection?: string) → queue

A queue, to look at or empty: @queue('mail')->size(). Defaults to the default queue of the default connection.
ParameterTakes
name optionalstring
connection optionalstring

Arguments can be named: @queue(…, connection: …).

Example
<echo>{ @queue('mail', connection: 'memory')->size() } waiting</echo>
echo "{ @queue('mail', connection: 'memory')->size() } waiting"

#@rate_limited(key: string, limit: number, per: duration) → job_middleware

Job middleware, for fn middleware(): at most limit jobs with this key start in each period, across every worker: @rate_limited('mail', limit: 10, per: 1m). A job over the limit goes back on its queue until the next period, without using up a try.
ParameterTakes
key requiredstring
limit requirednumber
per requiredduration

Arguments can be named: @rate_limited(…, limit: …, per: …).

Example
<job name="Send" fields="to: string">
  <fn name="middleware" value="[@rate_limited('mail', limit: 10, per: 1m)]" />
  <fn name="handle"><echo>Sending to { $to }</echo></fn>
</job>
<do>Send(to: 'joan@example.com')->run()</do>
job Send {
  to: string
  fn middleware() => [@rate_limited('mail', limit: 10, per: 1m)]
  fn handle() {
    echo "Sending to { .to }"
  }
}
Send(to: 'joan@example.com')->run()

#@release_job(after?: duration)

In a job's handle: puts the job back on its queue without using up a try, to run again after a while: @release_job(after: 30s).
ParameterTakes
after optionalduration
Example
<job name="Poll">
  <fn name="handle">
    <do>@release_job(after: 30s)</do>
  </fn>
</job>
<do>Poll()->run()</do>
job Poll {
  fn handle() {
    @release_job(after: 30s)
  }
}
Poll()->run()

#@without_overlapping(key?: string, release_after?: duration, expires?: duration) → job_middleware

Job middleware, for fn middleware(): only one job of this type with the same key runs at a time; another goes back on its queue for release_after (10s by default) without using up a try. expires frees the key if a worker stops while holding it (the job's timeout by default).
ParameterTakes
key optionalstring
release_after optionalduration
expires optionalduration

Arguments can be named: @without_overlapping(…, release_after: …, expires: …).

Example
<job name="Import" fields="user_id: int">
  <fn name="middleware" value="[@without_overlapping(&quot;import-{$user_id}&quot;)]" />
  <fn name="handle"><echo>Importing for { $user_id }</echo></fn>
</job>
<do>Import(user_id: 7)->run()</do>
job Import {
  user_id: int
  fn middleware() => [@without_overlapping("import-{.user_id}")]
  fn handle() {
    echo "Importing for { .user_id }"
  }
}
Import(user_id: 7)->run()

Methods

On job values: ->dispatch(), ->run()

On chain values: ->dispatch(), ->run(), ->count()

On batch values: ->then(), ->catch(), ->finally(), ->dispatch()

On queue values: ->size(), ->waiting(), ->failed(), ->clear(), ->retry(), ->remove(), ->batch()

On fake_queue values: ->pushed(), ->dispatches(), ->count(), ->count_of(), ->run_all(), ->clear()