Tooling

Job Queue

Run work in the background of the game server with server.queue - retries, backoff, delays and failed jobs, in memory or in the database.

Every game server has a job queue, server.queue in the game's code and ctx.queue in a plugin. Put slow or unreliable work on it, such as calling another service or sending mail, so a tick never waits for it. A job that throws is tried again, and kept among the failed jobs once it ran out of tries.

The queue is part of @mavonengine/core, so there is nothing to install. Its jobs are kept in memory, or in the database when the project has a database plugin such as @mavonengine/sqlite, where they survive a restart.

Writing a job

A job is a class that extends Job and implements handle():

import Job from '@mavonengine/core/Queue/Job'

export class GrantReward extends Job<{ player: string, coins: number }> {
  static jobName = 'grant-reward'
  tries = 3
  backoffMs = [1000, 5000]

  async handle() {
    await addCoins(this.data.player, this.data.coins)
  }

  failed(error: Error) {
    // Called once, when the last try threw
  }
}
FieldDefault
static jobNamethe class nameThe name the job is stored and looked up by. Set it, so renaming the class or a bundler renaming it doesn't leave queued jobs without a class. In a plugin, put the plugin's name in it, like chat:expire-mute
queuedefaultThe queue it goes on
tries1How often it is tried before it counts as failed
backoffMs0How long to wait before trying again, in ms: one number for every retry, or one per retry with the last repeating, like [1000, 10_000, 60_000]

data is stored as JSON and the job is built again from it with new GrantReward(data) when it runs, also after a restart. Keep it to what JSON keeps: ids, not entities or connections.

handle() gets the run's context: id (the same over its retries), queue and attempt, 1 on the first try. A throw or a rejection is a failed try.

Dispatching

const id = await server.queue.dispatch(new GrantReward({ player: account.id, coins: 10 }))

server.queue.dispatch(new GrantReward(data), { delayMs: 60_000 }) // in a minute
server.queue.dispatch(new GrantReward(data), { queue: 'rewards' })

await server.queue.dispatchSync(new GrantReward(data)) // now, in this call
  • dispatch() resolves with the job's id once it is stored, not once it ran.
  • Jobs can be dispatched before start(). They start running once it is done.
  • dispatchSync() runs the job in the call, without the queue: no retries, and a throw is passed on.

In a plugin

Register the plugin's job classes in setup(). A job the process dispatches registers its class itself, but a job queued before a restart only runs once its class is registered:

export default defineServerPlugin({
  setup(ctx) {
    ctx.queue.register(ExpireMute)
  },
  http(app, ctx) {
    app.post('/api/my-plugin/mute', ctx.requireAdmin, async (req, res) => {
      await ctx.queue.dispatch(new ExpireMute({ id: req.body.id }), { delayMs: req.body.minutes * 60_000 })
      res.status(202).end()
    })
  },
})

Jobs whose class isn't registered wait on the queue. Two different classes with the same jobName throw.

Failed jobs

const failed = await server.queue.failed(50) // the latest first
await server.queue.retry(failed[0].id) // back on its queue, with its tries again
await server.queue.forget(failed[0].id)

A failed job has its id, queue, name, payload, attempts, failedAt and the error of its last try, with the stack. await server.queue.size('default') counts the jobs that haven't finished on a queue, delayed and running ones included; without a name, on all queues.

Options

Set as queue in the server's options:

const server = new MyServer(logger, physicsWorld, {
  plugins: { root: projectRoot },
  queue: { concurrency: 4, queues: ['high', 'default'] },
})
OptionDefault
driverdatabase with a database plugin, else memoryWhere jobs are kept. database uses the tables core_jobs and core_failed_jobs
worktrueRun jobs in this process. Turn it off on a server that only dispatches
concurrency1How many jobs run at the same time
queuesevery queueThe queues to work, the first first: with ['high', 'default'], a job on default only runs while high has none due. Without it, the job due longest runs first
pollIntervalMs1000How often an idle worker looks for due jobs
retryAfterMs90000A job still running after this long is taken to be abandoned, for example because its server was killed, and runs again. Keep it above the longest a job takes
  • With a database: the queue's migration runs when the server starts, without holding the start up; jobs dispatched meanwhile move over. When the migration fails, the queue stays in memory and the log says so.
  • In memory: jobs are lost when the server stops.
  • Stopping: server.stop() stops taking jobs and waits for the running ones before it closes the database, see Stopping.

Watching it

The dashboard's Overview tab graphs the queue: jobs queued, processed and failed, and how many run. The metrics have it as queue, with the driver, whether this server works the queue and a history of samples.