# Write a station that processes workpieces

A station that does work on each workpiece loops over its `input` bin in `execute` and calls `processWorkpiece` for each one. `processWorkpiece` does the bin moves from [Bins](/docs/method/bins) for you: it copies the workpiece to `doing/`, runs your code on the copy, then moves it to `output/` or `failed/`.

## The station

From the factory template's example line, `EX1` counts the words in each workpiece. Its handler is `src/stations/EX1__count_words/station.js`:

```js
import { defineStation, attachReport, attachWorkpieces, bin, listWorkpieces, processWorkpiece, countWords, renderLocal } from '@assemblyline/lib-factory';
import { z } from 'zod';
import fs from 'node:fs';
import path from 'node:path';

export default defineStation({
  code: 'EX1',
  configSchema: z.object({
    batch_size: z.number().int().positive().default(10).describe('Most workpieces taken from input per run'),
  }),

  execute: async (config, context) => {
    const { work_record } = context;
    const workpieces = {};
    const results = [];

    for (const workpiece_id of listWorkpieces(bin('EX1', 'input')).slice(0, config.batch_size)) {
      const run = await processWorkpiece({
        station: 'EX1',
        workpiece_id,
        work_record_id: work_record.id,
        body: async (wp_doing) => {
          const text = fs.readFileSync(path.join(wp_doing, 'document.txt'), 'utf8');
          const words = countWords(text);
          if (words === 0) throw new Error('Empty document: nothing to count');
          fs.writeFileSync(path.join(wp_doing, 'result.json'), JSON.stringify({ words }, null, 2));
          return words;
        },
      });

      workpieces[workpiece_id] = run.status === 'ok' ? 'done' : 'failed';
      results.push(run.status === 'ok' ? { workpiece_id, words: run.value } : { workpiece_id, error: run.error.message });
    }

    await attachWorkpieces(work_record.id, workpieces);
    await attachReport(work_record.id, renderLocal(import.meta.url, './report.md', { results }));

    const failed_count = results.filter((r) => r.error).length;
    return { done_count: results.length - failed_count, failed_count };
  },
});
```

- **`listWorkpieces(bin('EX1', 'input'))`** returns the workpieces waiting in the bin, sorted by name. It is the same test the conveyor uses, so it skips loose files and folders without a `pointer.json`.
- **`.slice(0, config.batch_size)`** caps the run. Every station takes a batch, never all of `input/`; the rest wait for the next run: see [Batches and concurrency](/docs/method/batches).
- **`processWorkpiece`** never throws. It returns `{ status: 'ok', value }` or `{ status: 'failed', error }`, so one bad workpiece doesn't stop the rest.
- **`attachWorkpieces`** reports each workpiece's outcome, `done` or `failed`, to the run's work record.
- **`attachReport`** attaches the run's summary: see [Report a run](/docs/guides/report-a-run).

## The body

The `body` function is your code for one workpiece. It gets `wp_doing`, the path of the copy in `doing/`.

| Rule | Why |
|---|---|
| Read and write only under `wp_doing` | The original in `input/` has to stay untouched, so a failure can keep it for a retry |
| Throw to fail | A thrown error sends the workpiece to `failed/`. Returning a value, even `false`, sends it to `output/`. |
| Return a JSON-serialisable value | It comes back as `run.value`, for your report and the run's output |

Put details on the error you throw. They are saved in the workpiece's `error.json`: see [Find out why a workpiece failed](/docs/guides/handle-failures).

## Log an event before an outside action

`processWorkpiece` writes `station_started`, `station_complete` and `station_failed` to the workpiece's `log.jsonl`. Before your body does something outside the factory, such as posting to an API, sending an email or moving a file to a shared folder, add an event of your own. If the action fails or the process dies, the log shows how far the workpiece got:

```js
logEvent(wp_doing, 'IN2', work_record.id, 'posting_to_ledger');
await ledger.post(entry);
```

`logEvent` never throws; a failed write only prints a warning.

## Run several at once

For choosing the numbers, see [Batches and concurrency](/docs/method/batches).

The loop above runs the batch one workpiece at a time. To run several at once, use `pooled` to set how many run together:

```js
const pending = listWorkpieces(bin('IN1', 'input')).slice(0, config.batch_size);
const results = await pooled(pending, config.concurrency, async (workpiece_id) => {
  const run = await processWorkpiece({ station: 'IN1', workpiece_id, work_record_id: work_record.id, body });
  return { workpiece_id, run };
});
```

## Several stages in one body

When the work on a workpiece has several stages (extract, then validate, then file), make them functions called one after another inside the one body. Split them into separate stations, joined by conveyors, only when each stage needs to run, retry or be watched on its own: see [One job per station](/docs/method/one-job-per-station).

Work the whole run needs once, such as syncing a list of accounts, goes in `execute` before the loop, and the body uses the result.

## A line head creates workpieces

The first station on a line has no `input/` and doesn't call `processWorkpiece`. It creates each workpiece straight in its own `output/`. From the template's `EX0`:

```js
const wp = path.join(bin('EX0', 'output'), workpiece_id);
fs.mkdirSync(wp, { recursive: true });
fs.copyFileSync(path.join(config.source_dir, file), path.join(wp, 'document.txt'));
fs.writeFileSync(path.join(wp, 'pointer.json'), JSON.stringify({ workpiece_id, source_file: file, seeded_at: new Date().toISOString() }, null, 2));
logEvent(wp, 'EX0', work_record.id, 'workpiece_created');
```

The line head reports each workpiece it created as `done` with `attachWorkpieces`. It also keeps a [registry](/docs/method/line-head-registry) of what it has already created (the template appends to `intake-registry.jsonl`), so the next run doesn't create the same workpiece twice. When the workpiece id comes from the source, write the workpiece first and the registry entry second: a crash between the two creates the workpiece again on the next run instead of losing it.

## When not to use `processWorkpiece`

| The station | Do this instead |
|---|---|
| Creates workpieces (a line head) | Create the folder in `bin(station, 'output')`, as above |
| Only moves workpieces | Don't write a station: give the next station a `conveyor`. See [Connect stations](/docs/guides/connect-stations) |
| Reads finished work without changing it (a summary over `done`) | Read `bin(station, 'done')` directly |

Every function used here is listed in the [lib-factory README](https://github.com/assemblyline-sh/lib-factory#exports).

For the handler around the body (its folder, its config schema, what `execute` receives and returns), see [Write a station](/docs/guides/write-a-station).
