# Station context

`execute(config, ctx)` gets `ctx`, the context of one run. Every call on it is bound to that run, so none takes the work record's id.

| Member | Type | What it is |
|---|---|---|
| `ctx.work_record.id` | string | The run's work record id. In a local run it starts with `local-wr-`. |
| `ctx.station.code` | string | The code of the station being run |
| `ctx.org_id` | string | The organisation the run belongs to; `local` in a local run |
| `ctx.attachReport(content)` | `Promise<boolean>` | Attach the run's report |
| `ctx.attachDocument(title, content)` | `Promise<boolean>` | Attach a supporting document |
| `ctx.attachFile(title, filepath)` | `Promise<boolean>` | Attach a file from disk |
| `ctx.eachWorkpiece(fn)` | `Promise<{ results, counts }>` | Work through a batch of the station's `input/` |
| `ctx.seed(options, fn)` | `Promise<SeedResult>` | Create a workpiece in a line head's `output/` |
| `ctx.cursor.get()`, `ctx.cursor.set(value)` | | A line head's bookmark in its source |

For types in station code: `@param {import('@assemblyline/lib-factory').StationContext} ctx`.

## The attach calls

| Call | Takes | Attaches | Local copy, in `.factory/work_records/<id>/` |
|---|---|---|---|
| `attachReport(content)` | markdown | The run's report | `report.md` |
| `attachDocument(title, content)` | a title and markdown | A supporting document | `<title>.md`, with every character other than letters, digits, `-` and `_` replaced by `_` |
| `attachFile(title, filepath)` | a title and a path | A file: `.xlsx`, `.xls`, `.pdf`, `.csv`, `.png`, `.jpg` or `.jpeg`, up to 10 MB | A copy under the file's own name |

- **They never throw.** A failed call prints the error to the session's log and returns `false`; a successful one returns `true`.
- **The local copy is written on every run.** A local run writes only the copy and returns `true`.

How to use them: [Report a run](/docs/guides/report-a-run).

## `ctx.eachWorkpiece(fn)`

Takes up to `config.batch_size` workpieces from the station's `input/`, in name order, and runs `fn(wp)` on each with up to `config.concurrency` at once. Each runs on a copy in `doing/`. When the batch is done, it reports every finished or failed workpiece to the run, once.

| Config key | Rule |
|---|---|
| `batch_size` | A positive integer, declared in `configSchema`. Without it, `eachWorkpiece` throws. |
| `concurrency` | A positive integer, declared in `configSchema`. Without it, `eachWorkpiece` throws. |

`fn` gets `wp`, the [workpiece](/docs/reference/workpiece). What it does decides where the workpiece goes:

| `fn` | The workpiece | Its input | Reported as |
|---|---|---|---|
| returns nothing, or an object with no `sub_bin` or `wait` | `output/` | `done/` | `done` |
| returns `{ sub_bin: 'approved' }` | `output/approved/` | `done/` | `done` |
| returns `{ wait: '<reason>' }` | stays in `input/`, untouched | | not reported |
| throws | `failed/`, the original from `input/`, with `error.json` and `error.txt` | | `failed` |
| throws a `StopError` | stays in `input/`; the batch stops | | not reported |

- A `sub_bin` is letters, digits, `_` and `-`. A `wait` is a non-empty string. Any other value fails the workpiece.
- After a `StopError`, no workpiece starts; those already running finish and are reported, then `eachWorkpiece` throws the `StopError` and the run fails as retryable.

It returns `{ results, counts }`:

| Field | Holds |
|---|---|
| `results` | One row per workpiece, in batch order: what `fn` returned, plus `workpiece_id` and `status: 'done'` or `'waiting'`; or `{ workpiece_id, status: 'failed', error }`, the error's message |
| `counts` | `{ done, failed, waiting, sub_bins }`; `sub_bins` counts the done workpieces by sub-bin: `{ approved: 3 }` |

How to use it: [Write a station that processes workpieces](/docs/guides/process-workpieces).

## `ctx.seed(options, fn)`

A line head creates one workpiece. The lib keeps the station's [intake registry](/docs/method/line-head-registry) and writes `pointer.json`; `fn` fills the folder.

| Option | Type | What it does |
|---|---|---|
| `dedup_key` | non-empty string | What makes this item the same one (a message id, a file path). A key already in the registry returns `seen` without calling `fn`. Without it, nothing is recorded and the item is seeded on every call. |
| `workpiece_id` | string | The workpiece's id, chosen by the station |
| `workpiece_prefix` | string | The lib numbers the id `<prefix>-<N>`, one past the highest `N` in the registry. Needs `dedup_key`. |
| `pointer` | object | More fields for `pointer.json`. Never in the registry. Read after `fn` returns, so `fn` may add to it. |

Give exactly one of `workpiece_id` and `workpiece_prefix`. The id is a folder name: not empty, no `/` or `\`, not starting with `.`. A call that breaks these rules throws.

`fn(wp)` gets a [workpiece](/docs/reference/workpiece) whose `wp.dir` is a hidden folder, `output/.<id>/`, and `wp.id` is the new id:

| `fn` | Result |
|---|---|
| returns nothing | The lib writes `pointer.json`, logs `workpiece_created`, renames the folder into `output/`, then records `{ workpiece_id, dedup_key, seeded_at }` in the registry |
| returns `{ skip: '<reason>' }` | The folder is dropped. With a `dedup_key`, the key is recorded with the reason and `workpiece_id: null`, so the item is never judged again. No number is used. |
| throws | The folder is dropped and nothing is recorded: the next run tries the item again |
| throws a `StopError` | The folder is dropped and `seed` throws it; the run fails as retryable |
| writes `pointer.json` itself | The seed fails: pass its fields as `pointer` |

It returns one of:

| `status` | Fields | When |
|---|---|---|
| `seeded` | `workpiece_id` | The workpiece is in `output/` |
| `skipped` | `reason` | `fn` returned `{ skip }` |
| `seen` | | The `dedup_key` is in the registry, or a workpiece with that id and `dedup_key` is already in `output/` (the lib then records it) |
| `failed` | `error` | `fn` threw, or another workpiece with that id is already in `output/` |
| `limit` | | `max_seed_per_run` workpieces were already seeded in this run; `fn` isn't called |

- **`max_seed_per_run`** caps the workpieces seeded in one run. Declare it in the station's `configSchema` as a positive integer: a key the schema doesn't name is dropped before `execute` runs. Skipped and seen items don't count.
- **Seeds run one at a time,** in call order, even when called without `await`.
- **When `execute` ends,** even with a throw, the run reports every seeded workpiece as `done` and logs `[IN0] N seeded, M skipped, K seen, F failed`.

How to use it: [A line head creates workpieces](/docs/guides/process-workpieces#a-line-head-creates-workpieces).

## `ctx.cursor`

A line head's place in its source, such as a timestamp or a page token, kept in `.factory/stations/<CODE>/cursor.json`.

| Call | Returns or does |
|---|---|
| `get()` | The value set in this run, else the saved value, else `null` |
| `set(value)` | Holds `value` (any JSON value but `undefined`) to save when the run ends. Saved only when `execute` didn't throw and no seed failed. |

A line head with a cursor gives every seed a `dedup_key`, so items read again after a run that didn't save return `seen`.
