KScript docs
EN

Queues and jobs: KScript.Queue

Job middleware

Middleware runs around each attempt at a job. A job lists its middleware in fn middleware(), which is worked out with the job's fields, so a key can include them:

<import package="KScript.Queue" />

<job name="ImportContacts">
  <field name="user_id" type="int" />

  <fn name="middleware" value="[@without_overlapping(&quot;contacts-{.user_id}&quot;), @rate_limited('crm', limit: 10, per: 1m)]" />

  <fn name="handle">
    <echo>Importing contacts for {.user_id}</echo>
  </fn>
</job>
import KScript.Queue

job ImportContacts {
  user_id: int

  fn middleware() => [@without_overlapping("contacts-{.user_id}"), @rate_limited('crm', limit: 10, per: 1m)]

  fn handle() {
    echo "Importing contacts for {.user_id}"
  }
}

@without_overlapping(key) runs one job of this type with the same key at a time. Another one goes back on its queue for release_after (10s by default) without using up a try. If a worker stops while it holds the key, the key is freed after expires, the job's timeout by default.

@rate_limited(key, limit:, per:) lets at most limit jobs with that key start in each period, across every worker on the connection. A job over the limit goes back on its queue until the next period, without using up a try.

A middleware can also be a function. It is given next, which runs the rest of the middleware and then handle, and decides whether to call it:

<import package="KScript.Queue" />

<job name="Sync">
  <fn name="middleware" value="[fn(next) => @env('SYNC_PAUSED', 'no') == 'yes' ? null : $next()]" />

  <fn name="handle">
    <echo>Syncing</echo>
  </fn>
</job>
import KScript.Queue

job Sync {
  fn middleware() => [fn(next) => @env('SYNC_PAUSED', 'no') == 'yes' ? null : $next()]

  fn handle() {
    echo 'Syncing'
  }
}

Edit this page on GitHub