# Jobs and routes

> Work on the server in the background, by interval, by the clock or once later, in slices that carry on; and JSON routes of your own for signed-in members.

Page: https://songstress.app/docs/develop/jobs-and-routes/

The server entry does work nobody is waiting on as **jobs**, shown in Activity while they run, and answers your own
programs on **routes**: JSON, for a member signed in to the server. Both came with API 0.1.11, so ask for
`"songstress": "^0.1.11"`, or start with `--template full`, whose `daily` part has one of each.

## A day closed at midnight, answered on a route [#a-day-closed-at-midnight-answered-on-a-route]

```json title="songstress.json"
"engines": { "songstress": "^0.1.11" },
"entry": { "server": "dist/server.js" },
"hooks": { "server": ["onInstall", "onScrobble"] },
"permissions": {
  "listening.read": { "reason": "Hear that a song was played, to count today's plays." },
  "storage": { "reason": "Keep the plays of each of the last 30 days." },
  "jobs": { "reason": "Close each day by itself, in the background." },
  "routes": { "reason": "Answer the last days to your own programs." }
},
"contributes": {
  "jobs": [{ "id": "close-day", "title": "Close the day", "at": "00:00" }],
  "routes": [{ "id": "plays", "method": "GET", "path": "/plays" }]
}
```

```ts title="src/daily.ts"
import { songstress } from 'songstress/server'

/** How many closed days are kept. */
const DAYS = 30

// Once, when the extension is installed: the day the counting starts.
songstress.hooks.onInstall(async (event) => {
  await songstress.storage.set('since', event.at.slice(0, 10))
})

// Today's count is the extension's own, not a member's: no userId.
songstress.hooks.onScrobble(async () => {
  await songstress.storage.set('today', ((await songstress.storage.get<number>('today')) ?? 0) + 1)
})

// At midnight by the server's clock, the server runs this by itself.
songstress.jobs.register('close-day', async (run) => {
  const today = (await songstress.storage.get<number>('today')) ?? 0
  const days = (await songstress.storage.get<number[]>('days')) ?? []
  await songstress.storage.set('days', [today, ...days].slice(0, DAYS))
  await songstress.storage.set('today', 0)
  run.progress(1, 1, today === 1 ? '1 play' : `${today} plays`)
})

// GET /plays under the extension's own prefix.
songstress.routes.register('plays', async () => ({
  body: {
    since: (await songstress.storage.get<string>('since')) ?? null,
    today: (await songstress.storage.get<number>('today')) ?? 0,
    days: (await songstress.storage.get<number[]>('days')) ?? [],
  },
}))
```

## Jobs [#jobs]

A job is work on the server, shown in Activity while it runs. Declare it, and give it `every` (`15m`, `6h`, `1d`) or
`at` (`03:00`, the server's own clock), never both, to run by itself; without either, a job runs only when your code
starts it.

A job runs in slices. Each run is one call of its handler, with the host's deadline of 30 seconds: it does part of the
work, keeps its place in `storage`, and calls `run.again(after?)` to run again once this run ends well, with the same
input and for the same member. `jobs.start(id, input, { after, userId })` queues a run: `after` waits first (a week at
most), and `userId` names the member who asked, whose Activity then shows it. A job already waiting or running isn't
queued twice. One run at a time for each extension; a job that keeps failing runs later and later, and after ten
failures in a row stops running by itself and the admins are told. Runs waiting outlive a restart of the server.
Jobs run, and `at`, `after`, `userId` and `run.again` work, from API 0.1.11: `"songstress": "^0.1.11"`.

Work the server runs in the background, on a schedule or when code asks, shown in Activity.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The job's name. Code registers its handler under it. |
| `title` | `string` | The job as Activity shows it. |
| `every?` | `string \| undefined` | How often the job runs by itself: a number and m, h or d (15m, 6h, 1d). Left out with at, the job runs only when code starts it. |
| `at?` | `string \| undefined` | The time of day the job runs by itself, by the server's own clock: HH:MM, 24-hour (03:00). A job has every or at, never both. Left out with every, the job runs only when code starts it. |

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

songstress.jobs.register('sync', async (run) => {
  const pages = 10
  for (let page = 1; page <= pages; page++) {
    run.progress(page, pages, `Page ${page} of ${pages}`)
  }
})

// Once more in ten minutes, for the member who asked.
const runId = await songstress.jobs.start('sync', { full: true }, { after: '10m', userId: 'ana' })
```

Jobs (the manifest's `contributes.jobs`), each shown in Activity while it
runs. Server entry; permission `jobs`.

| Field | Type | Description |
|---|---|---|
| `register` | `(id: string, handler: JobHandler) => Disposable` | Registers the handler of a declared job. |
| `start` | `(id: string, input?: unknown, options?: JobStartOptions) => Promise<string>` | Queues a run of one of the extension's jobs, with `input` (JSON, 8 KiB at most) for its handler; resolves to the run's id. A job already waiting or running is not queued twice: its run's id is the answer. |

`register`, for example:

```ts
import { songstress } from 'songstress/server'

songstress.jobs.register('mark-live', async (run) => {
  const { songs } = await songstress.library.search('live', { types: ['song'], limit: 100 })
  for (const [done, song] of songs.entries()) {
    await songstress.storage.set(`live:${song.id}`, true)
    run.progress(done + 1, songs.length, song.title)
  }
})
```

`start`, for example:

```ts
import { songstress } from 'songstress/server'

songstress.commands.register('mark-live-now', async () => {
  const runId = await songstress.jobs.start('mark-live')
  return { action: { type: 'toast', message: `Started (${runId})` } }
})
```

A run is handed:

One run of a job.

| Field | Type | Description |
|---|---|---|
| `runId` | `string` | The run's id, as Activity knows it. |
| `input?` | `JsonValue \| undefined` | What `jobs.start` was given; undefined for a run on the job's own schedule. |
| `userId?` | `string \| undefined` | The member who started it, when one did. |
| `progress` | `(done: number, total?: number, note?: string) => void` | Tells Activity how far the run is: `done` of `total`, and a few words. |
| `again` | `(after?: string) => void` | Runs the job again once this run ends well, with the same input and for the same member: the next slice of long work, which goes on from where this one kept its place in storage. `after` waits first: a number and `s`, `m` or `h` (`30s`, `10m`), a day at most; at once when left out. A run that throws, or that a person cancels in Activity, is not run again. Called twice in one run, the last call counts. |

`progress`, for example:

```ts
import { songstress } from 'songstress/server'

songstress.jobs.register('mark-live', async (run) => {
  run.progress(0, 100, 'Starting')
})
```

`again`, for example:

```ts
import { songstress } from 'songstress/server'

songstress.jobs.register('index-all', async (run) => {
  const from = (await songstress.storage.get<number>('index-from')) ?? 0
  const { songs } = await songstress.library.search('', { types: ['song'], limit: 100 })
  const slice = songs.slice(from, from + 20)
  for (const song of slice) await songstress.storage.set(`indexed:${song.id}`, true)
  await songstress.storage.set('index-from', from + slice.length)
  if (slice.length === 20) run.again()
})
```

## Routes [#routes]

JSON routes for signed-in callers, under a prefix that belongs to your extension. Two routes may not answer the same
method and path (`ROUTE_DUPLICATE`). Songstress serves them from API 0.1.11 (`"songstress": "^0.1.11"`) at
`/api/songstress/extensions/v1/routes/<your id>/<path>`, to a member signed in to that server: `request.userId` is the
member the session names, never one the caller says. A request's body is JSON, 256 KiB at most; the answer is JSON,
512 KiB at most, never cached, with a status of 200 to 299 or 400 to 599 (any other, a redirect too, is answered 502).
A handler has 15 seconds, and four requests run at once for one extension, two of them for one member at most:
the next is answered 429.

An HTTP route under the extension's own prefix on the server.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The route's name. Code registers its handler under it. |
| `method` | `"DELETE" \| "GET" \| "PATCH" \| "POST" \| "PUT"` | The HTTP method. |
| `path` | `string` | The path under the extension's own prefix: segments of lowercase letters, digits, dots, hyphens and underscores, or :name for a part the handler reads (/charts/:period). |

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

songstress.routes.register('chart', async (request) => {
  const top = (await songstress.storage.get<string[]>(`chart/${request.params.period}`, { userId: request.userId })) ?? []
  return { status: 200, body: { top } }
})
```

A handler is handed the request, and answers:

A request to one of the extension's routes.

| Field | Type | Description |
|---|---|---|
| `method` | `"DELETE" \| "GET" \| "PATCH" \| "POST" \| "PUT"` | The method the route was called with, one the manifest declares for it. |
| `params` | `Record<string, string>` | The `:name` parts of the route's path. |
| `query` | `Record<string, string>` | The query string's values, by name. |
| `body?` | `JsonValue \| undefined` | The request's JSON body, when it has one. |
| `userId` | `string` | The signed-in member who asked. A route is never open to the world. |

What a route answers: JSON, and nothing else.

| Field | Type | Description |
|---|---|---|
| `status?` | `number \| undefined` | Left out, 200. |
| `body?` | `unknown` | JSON. |

## Long work, in slices [#long-work-in-slices]

A run has 30 seconds. Work longer than that keeps its place in `storage` and asks to go on:

```ts title="src/import.ts"
import { songstress } from 'songstress/server'

songstress.jobs.register('import', async (run) => {
  const page = (await songstress.storage.get<number>('import/page')) ?? 1
  // … fetch and keep one page of the import …
  run.progress(page, 40, `Page ${page} of 40`)
  if (page < 40) {
    await songstress.storage.set('import/page', page + 1)
    run.again()
  } else {
    await songstress.storage.delete('import/page')
  }
})
```

## Where a person sees them [#where-a-person-sees-them]

Every run of a job is in Activity, in the places every job of Songstress's is: quiet in the timeline unless a person
started it (`jobs.start(…, { userId })`) or it failed, and cancellable there. A route is your programs' own: nothing
of Songstress's draws it. To show a member what a job did, set a [badge](/docs/develop/sidebar/#set-a-badge) or a
[status](/docs/develop/status-and-context/#status-from-code), refresh a page (`ui.refresh`), or post to your client
code (`ui.post`, see [Live](/docs/develop/interface/#live)).

## Test them [#test-them]

`host.runJob(id, { input, userId })` runs a job once and hands back each progress it reported, `host.started` lists
each run `jobs.start` queued, and `host.request(route, { params, query, body, userId })` calls a route as a signed-in
member. See [Test and debug](/docs/develop/testing/#test-against-the-mock-host).
