> For the complete documentation index, see [llms.txt](https://www.health-samurai.io/docs/interbox/llms.txt).
> Use it to discover all available pages before guessing URLs.

---
# Your first pipeline

This tutorial reads the pipeline in the [`interbox-workspace`](https://github.com/HealthSamurai/interbox-workspace)
template, then changes it so messages are delivered in the order of their own
timestamps. It starts from the stack running as in the [Quick start](quick-start.md).

## How a workspace is laid out

```text
src/
  index.ts             # imports ./pipelines, re-exports ChainRegistry for the engine
  mappers/
    v2-to-fhir/…        # your mapping steps
  pipelines/
    index.ts           # imports every pipeline module
    hl7-to-aidbox/index.ts
```

The entry imports the pipeline modules, which declare their pipelines as a side
effect, and hands the engine the registry they were declared into:

```ts
// src/index.ts
import "./pipelines";
export { ChainRegistry } from "@health-samurai/interbox/chain";
```

The engine reads your pipelines from this export, not from its own copy of the
SDK, because the bundle carries its own. A workspace that declares external
systems with `defineSystem` also exports `SystemRegistry` from
`@health-samurai/interbox` (see [Systems](../concepts/systems.md)).

## The pipeline

```ts
// src/pipelines/hl7-to-aidbox/index.ts
import { env } from "@health-samurai/interbox";
import { aidbox, fhirItems, skipUnchanged } from "@health-samurai/interbox/aidbox";
import { mllpSource, pipeline, postgresStore } from "@health-samurai/interbox/chain";
import { hl7v2Parser } from "@health-samurai/interbox/hl7v2";
import { v2ToFhir } from "../../mappers/v2-to-fhir/index.ts";

pipeline("hl7-to-aidbox")
  .source(mllpSource({ host: env("MLLP_HOST"), port: env("MLLP_PORT") }))
  .step((raws) => raws.withSearchText((raw) => raw))
  .store(postgresStore({ codec: "text" }), {
    index: { message_type: "btree", event_type: "btree", patient_id: "btree" },
    search: "trgm",
  })
  .step(hl7v2Parser())
  .step(v2ToFhir)
  .step(fhirItems())
  .step(skipUnchanged())
  .sender(
    aidbox({
      url: env("AIDBOX_URL"),
      auth: { kind: "basic", user: env("AIDBOX_CLIENT_ID", "root"), password: env("AIDBOX_CLIENT_SECRET") },
    }),
  );
```

Read it top to bottom:

1. `mllpSource` listens for MLLP frames. Each frame is one input.
2. The step before the store makes the raw message the unit's searchable
   text, so the dashboard's search finds it from the moment it arrives.
3. `.store()` stores each message as text and creates its unit, status
   `received`. Only then does the source answer `AA`. `index` declares the
   attributes the dashboard filters on, and `search: "trgm"` indexes the
   searchable text.
4. `hl7v2Parser()` parses the stored text. A message it cannot parse ends
   its unit at `error` with `parse/not_hl7` or `parse/missing_msh`. It records
   `message_type`, `event_type`, `patient_id` and a few more attributes on the
   unit.
5. `v2ToFhir` is your mapping step: each message becomes the FHIR resources
   it describes, one item each.
6. `fhirItems()` gives each resource the key (`Type/id`), references and
   content hash the Aidbox sender needs, and `skipUnchanged()` drops a
   resource identical to the version already queued or delivered.
7. `aidbox()` sends the items to Aidbox. When the last item of a unit is
   delivered, the unit becomes `sent`.

The store comes right after the source, before the parser, so the raw message
is what is kept. A Retry after you fix a parsing problem then parses the
original again.

The mapping step lives with your other mapping code, in `src/mappers/v2-to-fhir/`. The
template's own `v2ToFhir` handles more message types; this reduced version shows the shape
of a mapping step:

```ts
// a reduced src/mappers/v2-to-fhir/index.ts
import { domainError } from "@health-samurai/interbox";
import { defineStep, type Batch } from "@health-samurai/interbox/chain";
import type { Patient, Resource } from "@health-samurai/interbox/fhir";
import { findSegment, getComponent, type HL7v2Message } from "@health-samurai/interbox/hl7v2";

function patientOf(msg: HL7v2Message): Patient {
  const pid = findSegment(msg, "PID");
  const id = getComponent(pid?.fields[3]);
  if (id === undefined) throw domainError("field", "missing", "PID-3 is empty");
  return { resourceType: "Patient", id, name: [{ family: getComponent(pid?.fields[5], 1) }] };
}

export const v2ToFhir = defineStep("v2-to-fhir", (msgs: Batch<HL7v2Message>) =>
  msgs.flatMap((msg): Resource[] => [patientOf(msg)]),
);
```

A step takes a `Batch` of rows and returns the `Batch` its methods made.
`flatMap` turns each message into its resources. A `domainError` ends the
message's unit at `error` with the kind `field/missing`. Any other throw is
treated as transient, and the unit is tried again. See [Steps and batches](../reference/steps.md#batch)
for the methods of a `Batch`, and [Steps, store and senders](../concepts/stages.md)
for what a step's context offers.

Every part is referenced by value, so the types are checked at compile time:
each step's input is the previous step's output, a store's codec refuses a row
type it cannot hold, and `aidbox()` accepts only the output of `fhirItems()`.
Deployment values (`MLLP_HOST`, `AIDBOX_URL`, secrets) come from `env()`. The
engine resolves them from its own environment, not when the pipeline is
declared: the source's when the workspace loads and the source starts, Aidbox's
as each send starts (see [Env and config](../guides/env-and-config.md)).

## Change the delivery order

Without a step that sets the unit's event time, versions of one resource are
delivered in the order their messages arrived. To order them by the message's
own time, MSH-7, add a step after the parser with `fromMsh7` from
`@health-samurai/interbox/hl7v2`, naming the sending system's time zone for the
times that carry no offset. In `src/pipelines/hl7-to-aidbox/index.ts`, import it next to
`hl7v2Parser`:

```ts
import { fromMsh7, hl7v2Parser } from "@health-samurai/interbox/hl7v2";
```

Then add the step after the parser:

```ts
  .step(hl7v2Parser())
  .step((msgs) => msgs.withOrder((msg) => fromMsh7(msg, "America/New_York")))
  .step(v2ToFhir)
```

## See the change in the running engine

Save the file. The template's `docker-compose.yaml` runs the engine against your
working tree, and its workspace service watches the tree (`INTERBOX_WORKSPACE_POLL_MS`,
2s in that file). It bundles `src/index.ts` itself, so there is no build step
of your own, and the engine swaps its workers to the new build without restarting
`interbox`. A build that fails leaves the running pipelines as they were, and the
dashboard shows why it failed.

To check the change, send a message and open its unit from the **Pipelines** page. The
unit's **Order at** field now shows the message's MSH-7 time instead of the time the unit
was created.

A deployment sets the workspace source differently: it follows a branch of a remote
repository. See [The workspace](../deploy/workspace.md) for the source, the modes, how
updates reach a running engine and what happens when two people edit the same file, and
[The workspace service](../deploy/deployment.md#the-workspace-service) for the service itself.
