# ovok.outbox

Canonical page: https://docs.ovok.com/web-sdk/core/namespaces/outbox

`ovok.outbox` holds the measurements the server has not accepted yet. Every [`ovok.measurements.save`](./measurements.mdx) goes into the outbox first, so a reading survives a dropped connection or a rate limit. It survives a restart only when you pass a persistent `outboxStore`; the default store is in memory. The outbox sends the newest readings first, within a request budget, whenever it can.

## What the outbox does [#what-the-outbox-does]

- **One item per unit of sending.** An item is a reading, a series that is still growing, one segment of a long recording, or a deletion. Items are stored one by one, so a long ECG is not one big write.
- **Sent items are removed.** `ovok.outbox.recentlySent()` keeps the last 50 for display.
- **States.** An item is `pending` until the server accepts it, or `rejected` when the server refuses it. A rejected item stays until you resend or discard it.
- **Triggers.** It sends after a save (within a second), every 15 seconds while items wait, when the connection returns, when the app comes to the foreground and when an account signs in.
- **Budget.** It makes at most 40 requests per 30 seconds, so a patient's own rate limit has room left. Change it with `outboxRequestBudget`.
- **One account at a time.** An item is sent only while the account that saved it is signed in.
- **Guests.** With nobody signed in, a save is kept for the guest: it says `queued`, names `Patient/guest` and is never sent until `adopt` hands it to a patient.

## Keep the outbox on the device [#keep-the-outbox-on-the-device]

By default the outbox lives in memory and is lost when the app closes. Pass a store that persists:

```ts
import { IndexedDbOutboxStore, Ovok } from '@ovok/core';

const ovok = new Ovok({
  baseUrl: 'https://api.sandbox.ovok.com',
  tenantCode: 'your-tenant',
  outboxStore: new IndexedDbOutboxStore({ name: 'my-app-outbox' }),
});
```

- `IndexedDbOutboxStore` uses the browser's IndexedDB and needs no dependency.
- `MemoryOutboxStore` is the default, for tests and servers.
- Readings queued by an older version of the SDK in `storage` move into the outbox once, and their key is deleted.
- `connectivity` and `lifecycle` tell the outbox when the network returns and when the app comes to the foreground. They default to the browser's `online` and `visibilitychange` events; pass your own in React Native.
- `logger` receives structured entries named `outbox.flushed` (counts of sent, rejected and pending items) and `outbox.paused` (the reason and the end of the pause). They never hold values.

## Show what is waiting [#show-what-is-waiting]

```ts
const snapshot = await ovok.outbox.snapshot();

console.log(snapshot.pending, snapshot.rejected, snapshot.offline, snapshot.pausedUntil);

const stop = ovok.outbox.subscribe((next) => render(next));
```

- `snapshot()` gives the counts, whether the last request could not reach the server, when a pause ends, the oldest waiting item, the last failure, the pending items by kind and the progress of each long recording as `{ id, segmentsSent, segmentsTotal }`.
- `subscribe(listener)` calls the listener with the snapshot at once and after every change.
- `items()` lists the account's items, newest first, without their payload. `recentlySent()` lists the last 50 sent.
- `pendingObservations()` returns the observations still waiting, to show beside saved readings.
- In React, [`useOutbox()`](../react.mdx) returns the snapshot and updates as it changes.

## Send, resend or discard [#send-resend-or-discard]

```ts
const { sent, rejected, pending } = await ovok.outbox.flush();

await ovok.outbox.resend();
await ovok.outbox.discard(item.id);
```

- `flush()` sends what is due now. A pause the server asked for still holds.
- `resend(ids?)` puts rejected items back to pending, the ones you name or all of them.
- `discard(id)` deletes an item that has not been sent. A reading discarded here is not saved.
- `enqueueDelete({ system, value })` queues the deletion of the observations with an identifier, for readings saved before.

## Keep a guest's readings [#keep-a-guests-readings]

An app can let people measure before they have an account. While nobody is signed in, every save goes to the guest, whose owner key is `GUEST_OWNER_KEY`. The guest's items stay on the device: `items()`, `snapshot()` and `pendingObservations()` show them, and nothing is sent.

```ts
await ovok.measurements.save({ measurement });

// After sign-up or sign-in:
const handedOver = await ovok.outbox.adopt();
```

- `adopt(patientId?)` hands every guest item to the signed-in account. It rewrites each observation's `subject` and reading identifiers to the patient, the signed-in profile by default, then sends them as usual.
- Each item keeps its id, so whatever follows an item sees it sent.
- `enqueueDelete` for a guest only drops the guest's pending saves: nothing reached the server.
- `adopt` throws `OvokValidationError` while nobody is signed in.
- A guest's readings live only in the outbox store. Deleting the app or the browser's site data loses them.

## How the outbox handles failures [#how-the-outbox-handles-failures]

One item's failure never changes another item.

| Failure | What the outbox does |
| --- | --- |
| No connection | Keeps the item, spends no attempt, tries again at the next trigger or after 30 seconds. |
| 429 | Pauses the whole outbox until `Retry-After` (not shortened), or 60 seconds without one. |
| 5xx | Pauses the whole outbox for 300 seconds, 100 more for each repeat, up to 3600. |
| 401 | Keeps the item for its account; it goes when the session is back. |
| 409 or 412 on a conditional write | Counts the item as sent: the server already has it. |
| 400, 403, 404 or 422 | Marks the item `rejected` with the failure; `resend` or `discard` it. |
| Timeout | Waits 60 seconds, doubling to 900, and marks the item `rejected` after five. |

A request of several items that fails for one of them is sent again item by item to find which. The caller of `save` gets the error of its own reading only, and a caller's own abort leaves the item queued.

## Long recordings and series [#long-recordings-and-series]

- An ECG of more than one 5-minute segment goes up one request per segment, in order, and the group observation last, linked to the segments the server saved.
- A series from `seriesObservations` carries an identifier from its source, property and start. Saving a longer version replaces the waiting one, and the server write is a `PUT` by that identifier, so one series is one observation.

## Write a store for another platform [#write-a-store-for-another-platform]

An `OutboxStore` is six async methods: `put`, `get`, `remove`, `due`, `summaries` and `count`. Prove an adapter with the shared contract:

```ts
import { outboxStoreContract } from '@ovok/core';

outboxStoreContract(() => new MyStore()).forEach(({ name, run }) => it(name, run));
```

- Every method must be atomic, so a crash leaves an item stored or not.
- `due` returns the owner's pending items whose `nextAttemptAt` has come, newest `recordedAt` first.
- `summaries` and `count` must not read the entries; they run often.

## See also [#see-also]

- [ovok.measurements](./measurements.mdx): saving readings.
- [React integration](../react.mdx): `useOutbox`.
- [Errors and retries](../errors-and-retries.mdx): the error classes the outbox sorts.
- [Outbox API reference](../reference/core/outbox.mdx): every method and type.
