# Sync

AnchorDB is a local database first. Sync is an optional layer on top: it sends the changes made on the
phone to your server, and brings the server's changes back. This page explains what it does and how
to turn it on.

Without a `sync` block, none of this exists: no queue, no network code, no extra metadata.

## What it does for you

| You would otherwise build | What AnchorDB does |
| --- | --- |
| A queue of changes to send ("outbox") | Every write also records a **mutation** in a durable queue, in the same storage write, so a crash cannot lose it. |
| Retrying when the network is down | Failed sends go back in the queue with exponential backoff. Nothing is dropped. |
| Not sending the same change twice | Each mutation has an id; the server remembers its answer for each one, so a retry after a timeout cannot apply a change twice. |
| "Which edit is newer?" | Every write is stamped with a **hybrid logical clock** (HLC): roughly wall-clock time, but it never goes backwards and it corrects itself from the server's clock. |
| A version per record | Every document carries the server version it was last synced at. A change made against an old version is a **conflict**. |
| Remembering deletes | With sync on, a delete leaves a marker (a tombstone) until the server has been told, then it is removed. |
| Downloading everything every time | Pull is **incremental**: the server returns changes since a cursor, and the cursor is saved after each page, so an interrupted pull resumes where it stopped. |
| Clock skew between phone and server | Each response carries the server's time; the client keeps an offset and stamps with it. |

## Turning it on

```ts
import { createAnchorDB } from "anchordb-react";
import { attachSync } from "anchordb";

export const db = createAnchorDB({
  name: "expense-tracker",
  sync: {
    endpoint: "https://api.example.com/anchor/v1",
    auth: { getToken: async () => await getAccessToken() },
    conflictResolution: { strategy: "last-write-wins" },
  },
});

const sync = await attachSync(db);

// Push the queue, then pull what changed. Call it when the app starts, when the network comes back,
// and on pull-to-refresh.
await db.sync.now();
```

Your app code does not change. `Expense.create(...)`, `updateOne`, `deleteMany` and so on all queue
their changes on their own, and so do writes inside `db.transaction()` — they are queued only if the
transaction commits.

## When it runs

`db.sync.now()` syncs whenever you call it: on pull-to-refresh, say. Since 1.5.0 sync can also run
on its own:

```ts
sync: {
  endpoint,
  autoSync: true,      // a short while after writes (autoSyncDelayMs, default 2 s)
  intervalMs: 60_000,  // and every minute while the app is in the foreground
}
```

Tell it about the network and the app's state, and it syncs as soon as either comes back:

```ts
NetInfo.addEventListener((s) => s.isConnected && db.sync.online());
useAppStateSync(db, AppState); // anchordb-react: foreground() / background()
```

- After a failure it waits before trying again: 2 s, then twice as long each time up to 5 minutes,
  with some randomness so phones don't all retry at once. `online()` skips the wait.
- An expired token (`auth:expired`) stops automatic sync. Refresh the token and call
  `db.sync.now()` to start it again.
- In the background the timer is paused.

## Shared data

By default each document belongs to the user who created it, and only they sync it. For data that
several users share, such as a household's Home book, name its scope with `scopeOf`:

```ts
sync: {
  endpoint,
  scopeOf: (collection, doc) => (doc.bookId ? `book:${doc.bookId}` : undefined), // undefined: the user's own
  pullScopes: () => [currentBookScope], // optional: pull only the book on screen
}
```

The server decides who belongs to each book (see the
[sync-server README](https://www.npmjs.com/package/anchordb-sync-server#shared-books)). The phone
keeps up with it:

- A user removed from a book loses that book's documents from the phone on the next pull.
- A document moved to another book disappears from the old book's other members.
- A new member receives the whole book.

Turning sync on later is safe: on the first `attachSync`, documents written before sync existed are
queued as new, so nothing stays stranded on the phone.

## Conflicts

A conflict is when the same document changed on the phone and on the server since the last sync. You
choose how it is settled with `conflictResolution.strategy`:

| Strategy | Result |
| --- | --- |
| `last-write-wins` (default) | The newer change wins, by HLC time. Ties go to the server. |
| `server-wins` | The server's version is kept; the phone's change is dropped. |
| `client-wins` | The phone's version is pushed again over the server's. |
| `field-level` | A three-way merge: fields only one side changed are both kept; fields both changed go by `fieldPolicy` (`lww`, `server` or `client`). |
| `custom` | Your function: `resolver: ({ local, remote, base }) => resolvedDocument`. |

To tell the user that their change lost:

```ts
db.on("conflict", ({ collection, documentId, winner }) => {
  if (winner === "remote") toast(`${collection} was changed elsewhere; kept the other version`);
});
```

A change the server rejects for good — a duplicate key, a validation failure — is **parked** as
failed instead of retried forever. Anchor Lens shows parked mutations, and `retryMutation` sends one
again.

## Status and events

```ts
db.sync.status();          // "idle" | "syncing" | "offline" | "error" | "paused" | "disabled"
await db.sync.pending();   // changes waiting to be sent
```

Events: `sync:start`, `sync:progress`, `sync:complete`, `sync:error`, `queue:changed`, `conflict`,
`duplicate-key`, and `auth:expired` (a 401/403 pauses sync rather than discarding anything; refresh
the token and call `db.sync.now()` again). In React, `useSyncStatus(db)` gives `{ status, pending }`.

## The server side

Use `anchordb-sync-server`. It speaks the protocol for you, with Express, Next.js and NestJS
adapters, and stores in memory or in MongoDB through Mongoose:

```ts
import express from "express";
import mongoose from "mongoose";
import { createAnchorRouter } from "anchordb-sync-server";
import { MongooseStore } from "anchordb-sync-server/mongoose";

const app = express();
app.use(express.json());
app.use("/anchor/v1", createAnchorRouter(express.Router, { store: new MongooseStore({ mongoose }) }));
```

The server keeps the version counters, the change sequence pull cursors point into, and the
remembered answers that make retries safe. It never picks a conflict winner: it returns its document,
and the strategy on the phone decides.

**Give it an `authenticate` function** whenever more than one person uses the app. Each user then
syncs only their own documents. Without it, every caller shares every document. Before 1.4.1 the
server ignored the identity even when `authenticate` was set; the
[sync-server README](https://www.npmjs.com/package/anchordb-sync-server#users) explains the upgrade.

What the phone does about it:

- If the server answers a change with **404**, the document isn't the user's (or no longer exists).
  The change is parked, and the phone deletes its copy, unless it was a new document.
- If the document was **deleted on the user's other phone**, that's a conflict, and your strategy
  decides. With `last-write-wins`, a newer edit brings the document back.
- When the server's **epoch** changes, the phone deletes its synced copy and pulls again, keeping
  unsent changes, and emits `sync:reset`.

## The protocol, for any other backend

Two JSON endpoints, both `POST`:

- **`{endpoint}/sync/push`** — `{ protocolVersion, clientId, sentAt, changes: Mutation[] }`. Each
  mutation has `mutationId`, `collection`, `documentId`, `operation` (`insert`, `update`, `replace` or
  `delete`), `payload` (the whole document, or null for a delete), `baseVersion` and `hlc`. The reply has
  one result per change, in order: `accepted` (with the new `version`), `rejected` (with a `reason`;
  `code: 11000` for a duplicate key, `404` for a document that doesn't exist or isn't the user's), or
  `conflict` (with the server's `document` and `version`; `document: null, deleted: true` when it was
  deleted). The answer for a `(clientId, mutationId)` must be remembered per user and replayed on a
  retry.
- **`{endpoint}/sync/pull`** — `{ protocolVersion, clientId, cursor, limit }`. The reply is
  `{ changes, nextCursor, hasMore, serverTime, epoch? }`, each change being `{ collection, documentId,
  document (null if deleted), version, deleted, updatedAt, scope? }`.

`protocolVersion` is 2 since anchordb 1.4.1. Push replies carry `epoch` too.

Documents travel as plain JSON, with `_id` as a 24-character hex string and dates as ISO-8601 UTC
strings, so a Mongoose model can take them as they are. The full types are in `anchordb`'s exports:
`PushRequest`, `PushResponse`, `PullRequest`, `PullResponse`, `Mutation`, `RemoteChange`.

## Not yet

- The server keeps delete markers indefinitely. Clearing old ones safely needs a protocol change, so
  that a phone that has not synced since then knows to download everything again.
