# Sessions, enrolments and interruptions

## From enrolment to results

1. Create the user (`POST /users`) and **enrol** them in a protocol (`POST /user-protocols`). An enrolment has no capture yet, and the same person can be enrolled in the same protocol more than once.
2. Ask which **position** is next (`GET /user-protocols/{userProtocolId}`). Its `protocol.interpreted` says whether the protocol is interpreted: with `false`, as in Measurement, captures produce indicators only, the stream announces `results.ready` instead of `constellation.complete`, and `POST /analyze` answers `409 PROTOCOL_NOT_ANALYSED`. `GET /catalog/protocols` and `GET /catalog/protocol_group` carry it too. Today only the test environment's Engine returns `interpreted`.
3. Send the first batch of that position: Engine opens a **session** for it. There is no session id to keep: the pair `userProtocolId` + `protocolMechanicId` identifies it.
4. When every step has its batches and its `Final`, the session completes and its results appear.

Each position has at most one open session and one completed session. To measure the same position again, enrol again.

## Abandoned and restarted captures

- A session that receives no batch for a few minutes is **abandoned** (the threshold is a setting of the environment), and the live stream says so with `session.abandoned`.
- A late batch then answers `409 SESSION_ABANDONED`. Restart from `step: 1` with `kpnfile.order: 1`. The message tells you the threshold of the environment where this example was captured:

```json
{
  "status": 409,
  "body": {
    "code": 409,
    "reason": "SESSION_ABANDONED",
    "message": "Session abandoned after 300s of inactivity. This mechanic must be restarted from the beginning.",
    "restartRequired": true,
    "expected": {
      "step": 1,
      "kpnfile": {
        "order": 1,
        "status": "Partial"
      }
    }
  }
}
```

- Each attempt carries its `captureId`. A restart batch (`step: 1`, `kpnfile.order: 1`) with a **new** `captureId` closes the attempt that was open and starts this one; any other batch with a `captureId` other than the open attempt's answers `409 SESSION_ABANDONED`: it is a late batch of an attempt you already replaced.
- A position that already has a completed capture answers `409 POSITION_ALREADY_COMPLETED` to any new batch:

```json
{
  "status": 409,
  "body": {
    "code": 409,
    "reason": "POSITION_ALREADY_COMPLETED",
    "message": "This mechanic already has a completed session."
  }
}
```

- To give up a capture on purpose: `POST /user-protocols/{userProtocolId}/{protocolMechanicId}/cancel`. It is idempotent: with nothing open it answers `200` with `cancelled: false` and `reason: "no_open_session"`. With `?captureId=` it closes the open capture only if it is that one; if another capture is open, it touches nothing and answers `200` with `cancelled: false` and `reason: "other_capture_open"`. Without `captureId`, whatever is open is closed; with a capture token (`POST /token/capture`), leaving `captureId` out uses the token's, so only that capture can be closed. `cancelled: false` with `reason: null` means the capture closed by itself at that same moment (it timed out or finished): there is nothing left to cancel. Today only the test environment's Engine takes `captureId`.
- While another attempt holds the position (a capture in progress, or a recording waiting to be sent), a new one answers `409 POSITION_RESERVED`. Recording now and sending the frames later (`captureId`, `deferred` and `capturedAt` in `POST …/context`) is described in the [API reference](/docs/reference/). The end notice of a recording that was already cancelled, or rejected as out of order (`recordingEndedAt` without `capturedAt`), answers `409 CAPTURE_CANCELLED`: nothing is reserved, so do not retry.
- `GET /user-protocols/{userProtocolId}/{protocolMechanicId}/sessions` lists the attempts at a position, oldest first, with their `status` and `captureId`. `deferred: true` marks a recording held to be processed later, and `receivingPackets: true` an attempt that has received at least one batch: a deferred attempt with `receivingPackets: false` is a reservation still waiting for its frames. They are the same two fields as the `holder` of a `409 POSITION_RESERVED`. Today only the test environment's Engine returns them.

## When a position is not available

Engine declares the position clocks (see [Protocols](/docs/concepts/protocols/#positions-and-their-clocks)) and checks them when a session is opened, never in the middle of one. Whether a failed check rejects the capture or is only logged depends on the environment; when it rejects, the answer is a `409`:

| `reason` | What to do |
| --- | --- |
| `MECHANIC_NOT_YET_AVAILABLE` | Retry at `earliestAt` |
| `MECHANIC_EXPIRED` | That window has closed for good: continue with `goTo` |
| `MUST_START_AT_FIRST_POSITION` | Start with the position in `goTo` |

`rule` names the clock (`date_window`, `time_of_day`, `spacing`, `start_order`, `start_weekday`): use it for logs, not for branching. `spacing` can also come from the minimum spacing Engine keeps between two captures of the same protocol, even when the position declares none.

**When does a position open?** In `GET /user-protocols/{userProtocolId}` each pending session carries a `window`. With `hasTiming: true` and a time-slot or spacing clock, `from` and `to` can arrive `null`, and there is no `earliestAt` as in the `409`. The data to compute it is there: `window.prevCaptureAt` (when the previous capture started) and `window.requiredGapSeconds` (the spacing Engine asks). The position opens at `prevCaptureAt` plus `requiredGapSeconds`; when either is `null` there is no spacing to wait for.

**Without computing it.** In the test environment's Engine, `nextSessions` of `GET /user-protocols/{userProtocolId}/health` and of `GET /users/{externalId}/status` gives each pending session a `window.earliestAt`: the same time as the `earliestAt` of the `409 MECHANIC_NOT_YET_AVAILABLE`, and `null` when it can be captured now or never again. In the same answers, `lastCompletedAt` says when the last completed capture started (when it was recorded, for a recording), not when it finished.

**No data, or still processing?** `GET /results/{userProtocolId}/{protocolMechanicId}` returns the same thing in both cases: `200` with `rawResults` and `aggResults` empty, because the position has no session yet or its capture has not completed. To tell them apart, read `GET …/sessions` of the position: `sessions: []` means nothing has been sent; an attempt with its `status` means it is on its way. `GET /users/{externalId}/status` gives the state of the whole protocol (`capturing`, `awaiting_processing`…).

## Interruptions and microinterventions

After a completed capture, a context may offer a **microintervention**: a short mechanic, such as a breathing exercise, that is not a position of the protocol. The offer is an **interruption**, anchored to the capture that triggered it.

1. You learn about it from the live stream (`interruption.offered`) or with `GET /user-protocols/{userProtocolId}/interruptions?status=offered`.
2. `GET /interruptions/{interruptionId}` returns what to show: steps and instructions, in the same shape as a position.
3. Capture it with `POST /interruptions/{interruptionId}/process-kpn-emo`. An offer that is not started expires.
4. `GET /results/interruption/{interruptionId}` returns the results of the capture that triggered the offer, under `origen` (the API spells this key in Spanish), and of the microintervention, under `micro` (`null` if it was not done).
5. To give up a microintervention in progress: `POST /interruptions/{interruptionId}/cancel`. It is idempotent: with nothing open it answers `200` with `cancelled: false`.

From an offer, rely on `interruptionId`, `origin` and `message`. `observedValues`, `trigger` and `kpnWindow` are internal: do not rely on them. Whether a context offers microinterventions depends on your organization's contexts.

> The SDK does not handle microinterventions yet: use the HTTP API. An offer cannot be declined: if you do not start it, it expires.
