# Documents

Distributed document store.

This store is built on top of the base store. This store allows for type-safe document storage and retrieval accross peers. 

As of now, go through the [tests](./src//__tests__/index.integration.test.ts) for documentation on how to use the module.

## Remote query authorization

`index.canSearch(request, from)` authorizes remote `SearchRequest`,
`SearchRequestIndexed`, `IterationRequest`, and `CollectNextRequest` requests.
It receives the actual decoded request (including indexed replication intent)
and the authenticated requester's public key. Returning `false` produces
`NoAccess` before query processing; `index.canRead` separately filters individual
results after admission. Iterator-close messages retain their ownership check
and can still clean up an admitted iterator after search permission is denied.

Indexed requests previously bypassed `canSearch`. Policies that exhaustively
check request classes must now handle `SearchRequestIndexed` explicitly;
ordinary callbacks using shared request fields remain source-compatible.
Persisted data and wire formats are unchanged. These checks authorize query
responses, not all replication or direct block access, and do not by themselves
provide store confidentiality.

With `remote: { throwOnMissing: true }`, a responding peer's `NoAccess` rejects
`get()`, `search()`, `iterate().next()` and `iterate().all()` with the exported
`AccessDeniedError`. Its `peers: string[]` holds the first denying responder
processed and need not list every denying peer. The RPC may wait for other
requested peers before processing those responses. This also applies when
permission is revoked before a continuation request. Healthy responses from
other peers do not turn an observed denial into success. An error processing a
later page, received from a peer or read from the local index, also rejects
instead of ending that source's rows early.

This also covers the queries that a replicator joining later triggers, for
`get(id, { waitFor })` and for iterators with a keep-open `remote.wait`, and
pages that a peer pushes to an iterator with push `updates`, such as a predicted
`NoAccess`. A denial, missing response or page-processing error there rejects
`get()`, or rejects the iterator's next read and every read after it until
`close()`, with `done()` returning `false` until then. When `remote.from` or
`remote.reach.discover` is set, a joining replicator outside them is still
asked, as without the option, and its failures on any page are only logged.
Omitting the option or setting it to `false` preserves best-effort behavior.

Public response callbacks still run and their errors propagate unchanged.
`search()` and `.all()` close their iterators on failure; manual iteration still
requires `close()` in `finally`. Already returned pages are not rolled back, and
with `replicate: true`, rows from responders processed before the denial may
already be stored locally. This query-level denial handling does not report
`canRead`-filtered rows or establish cursor-loss detection, old-peer
strict-protocol support, or a complete listing/snapshot guarantee. Wire formats
are unchanged.

## Waiting for a remote query candidate

To gate the first query on a non-self cover candidate and reject when the wait
expires, use the existing blocking policy:

```typescript
const iterator = store.docs.index.iterate({}, {
	remote: {
		wait: {
			behavior: "block",
			until: "any",
			timeout: 5_000,
			onTimeout: "error",
		},
	},
});
try {
	const results = await iterator.next(100);
} finally {
	await iterator.close();
}
```

The blocking wait and its deadline start when `iterate()` creates the iterator,
not at the first `next()`. The wait listens for replication changes; it does not
poll. Its positive timeout bounds the readiness phase, including the initial
cover lookup, not the whole query. Closing the iterator or aborting its top-level
`signal` cancels the wait. A lookup already in progress may finish later; its late
result is ignored.
With `behavior: "block"`, a zero timeout leaves the wait untimed.

This is only candidate discovery: a non-self `getCover` result is not proof of
reachability, complete query coverage, authorization, catch-up, or persistence.
It can include peers with synchronization in flight. Persisted delivery receipts
remain the durability proof. Defaults are unchanged: `remote.wait: true` uses
`"keep-open"`, not this blocking gate; an omitted `onTimeout` proceeds on timeout.

## Query timing diagnostics

The existing `Documents.open({ type, sync: { profile } })` callback also receives
bounded `documents.query.*` and `rpc.request.*` events. With no callback, tracing
is disabled. These events are advisory and do not change query coverage,
authorization, timeouts, or persisted delivery requirements.

Each query has an opaque process-local `traceId`; forwarded RPC events include
their own `details.requestTraceId`. Query events time local lookup, cover
selection, and result introduction. RPC events distinguish key/seal setup from
actual publishing, accepted responses, and the response deadline. Setup precedes
the RPC response timer. A publish completion does not prove remote arrival;
a deadline can return partial results that Documents tolerates. Inspect both
RPC outcome/reason and the query terminal's `missingGroups`.

Traces emit at most 256 detail events plus one reserved terminal, with version,
elapsed time, emitted count and dropped count. Documents samples the first 16
selected targets; RPC independently samples the first 16 accepted targeted
responders. These sets may differ, exposing up to 32 distinct peer identities
per query. `directPeerPresent` is local map-presence evidence, not a claim of
reachability, subscriber readiness, authority, or receipt eligibility. Query
keys, document contents and request bytes are not emitted. Peer identifiers are
still operational metadata: control access to stored traces.

Observers must remain cheap; slow synchronous callbacks can perturb measurements.
These query/RPC emitters contain callback exceptions and async rejections without
awaiting observers, and suppress late events after the terminal. Keep any external
collector bounded too. The precommit immutable lookup is separate from persisted
receipt settlement, so its time must not be attributed to receipt latency.

## Put timing diagnostics

The same `sync.profile` callback receives one bounded trace for each single
`put` call. All events of a trace share a `traceId` that starts with
`documents.put:`. A trace ends with exactly one `documents.put.settle` event
after the call succeeds or fails, including any requested persisted delivery.
A put that gets as far as choosing its write path also reports
`documents.put.prepare` and `documents.put.path`, whose `details.path` is
`"prepared"` or `"compatibility"`. A put that fails before that reports only
the phases it reached. Options rejected when the put starts, such as persisted
delivery with `target: "none"`, leave only `documents.put.settle`. A failed
preparation (for example a missing or invalid id, or an oversized document) or
a failed lookup of the existing document leaves `documents.put.prepare` and
`documents.put.settle`.

Only `"compatibility"` puts also time their detailed phases:
`documents.put.authorize`, `entry.create.payload`, `entry.create.signable`,
`entry.create.sign`, `entry.create.authorize`, `entry.create.storage`,
`log.append.createEntry`, `log.append.entryIndex`, `documents.put.projection`
and `sharedLog.append.localProcessing`. A put takes this path when the store
has a `canPerform` callback (other than a `policy` helper that allows the
document up front), `immutable` documents, `strictHistory`, `mode: "compat"`
or a document type that is itself a `Program`. A put also takes it when it
sets an option the prepared path does not handle, such as `checkRemote`,
`signers`, custom `meta`, or an explicit `target` other than `"none"`; an
explicit `"replicators"` stays on the prepared path only with persisted
delivery. Other puts take the default `"prepared"` path and report no detailed
phases, whether they commit natively or through the JavaScript fallback. Use
`details.path` to tell which path a put took.

Durations are inclusive and overlap; do not sum them. For example,
`log.append.createEntry` includes every `entry.create.*` span, and
`entry.create.authorize` includes `documents.put.authorize`.
`entry.create.storage` combines serialization, CID calculation and block
storage, not an isolated fsync. `documents.put.authorize` covers the store's
write check: the existing-document lookup (for `immutable` documents, a
local-then-remote lookup that reports its own query trace), the
`strictHistory` check, document decoding for a custom `id` function or a
`canPerform` callback, and the `canPerform` callback itself, with any previous
entries a `policy` helper needs. `log.append.entryIndex` includes trusted
commit-evidence capture; `documents.put.projection` covers document projection
and change dispatch; `sharedLog.append.localProcessing` includes
coordinate/planning work and ordinary delivery. Phase `outcome: "success"`
means the phase returned, not that permission was granted or a durable receipt
exists. Only the normal write/receipt contract provides durability evidence.

Put tracing follows the current `sync.profile` of the `sync` object passed to
`open`: each `put` reads it when it starts. Removing the callback after open
stops `documents.put:` traces for later puts, while a put already in progress
finishes its trace. Query traces, including the lookups a put makes for
`immutable` documents or `checkRemote`, keep the callback captured at open
until the store closes. Without a callback, puts create no trace and add no
phase clock reads. A store opened with `mode: "native"` (strict native mode)
still rejects `sync.profile` at open and never traces puts.

These traces use the same 256-detail-event bound and isolated observer delivery
as query traces, with no document IDs, contents, hashes or raw errors. Keep
observers cheap and filter on the `traceId` prefix when relying on this
isolation: older uncorrelated `sync.profile` events have their existing
behavior. No write options or storage/wire formats change.

## Durable remote delivery

Document puts can opt in to waiting for crash-safe persistence on current remote
replica owners:

```typescript
await store.docs.putMany(documents, {
	unique: true,
	delivery: {
		reliability: "persisted",
		minAcks: 2,
		timeout: 120_000,
	},
});
```

`minAcks` counts distinct remote owners; it does not increase the store's
configured replication degree. A successful return proves persistence at the
receipt instant, not permanent custody or Byzantine correctness. The local
commit happens first, so a later delivery failure reports the exact committed
hashes in a `PersistedDeliveryError` with `retrySafe === false`.

Persisted delivery supports `put`, independent distinct-key `putMany`, and a
single `del` operation. For a delete, the receipt covers the exact `CUT`
tombstone entry. It does not wait for remote document-index or change-event
side effects, prove permanent tombstone retention, or compact prior history.

## Required local batching and failure accounting

Callers that cannot accept a sequential `put` fallback can opt in explicitly:

```typescript
import { DocumentBatchCommitError } from "@peerbit/document";

try {
	const result = await store.docs.putMany(documents, {
		batching: "required",
		unique: true,
		target: "none",
	});
	// result.entries has the same order as the captured input documents.
} catch (error) {
	if (!(error instanceof DocumentBatchCommitError)) throw error;
	console.log(error.localCommit, error.committedItems, error.cause);
}
```

Required mode captures the input array, document encodings, keys, and supported
append options at invocation. It rejects unsupported document modes/options and
duplicate keys before append, and never falls back to sequential document puts.
The default behavior is unchanged. This requires the existing independent batch
append path, not an all-or-none storage transaction or a particular number of
fsync calls. Backend durability configuration still applies.

`DocumentBatchCommitError.committedItems` is an immutable array of `{ index, hash }`
pairs: indexes refer to the captured input array, not a later mutated array.
The local outcome is separate from projection and remote delivery:

- `not-started`: no local append was handed off; `retrySafe` is true for replaying
  the local append only, not for application/policy callback side effects.
- `committed`: the complete ordered local append is confirmed. Do not replay it;
  projection, change-event, or remote-receipt work may still have failed. Inspect
  `cause` to determine the failed phase.
- `indeterminate`: native preparation/append may have changed state without a
  complete success acknowledgment, or native durable persistence failed.
  `recoveryRequired` is true and automatic replay is unsafe. An empty evidence
  array does **not** mean nothing committed. Exact indexes are exposed only when
  the complete ordered batch is known.

`recoveryRequired` describes an unresolved local append outcome: false does not
mean a failed document projection needs no repair. Required batching can also be
combined with persisted delivery (omit `target: "none"` in that case). A remote
receipt failure retains local commit evidence and the `PersistedDeliveryError`
as `cause`; only successful persisted delivery proves the requested remote
durability. No transaction atomicity or permanent custody is implied.



Example 
```typescript 
import { field, option, serialize, variant } from "@dao-xyz/borsh";
import { Program } from "@peerbit/program";
import { Peerbit } from "peerbit";
import {
	Documents,
	DocumentIndex,
	SearchRequest,
	StringMatch,
	StringMatchMethod,
	Results,
} from "@peerbit/document";


@variant("document")
class Document {
    @field({ type: "string" })
    id: string;

    @field({ type: option("string") })
    name?: string;

    @field({ type: option("u64") })
    number?: bigint;

    constructor(opts?: Document) {
        if (opts) {
            Object.assign(this, opts);
        }
    }
}

@variant("test_documents")
class TestStore extends Program {
    @field({ type: Documents })
    docs: Documents<Document>;

    constructor(properties?: { docs: Documents<Document> }) {
        super();
        if (properties) {
            this.docs = properties.docs;
        }
    }
    async open(): Promise<void> {
        await this.docs.open({ 
			type: Document, 
			index: {
				fields: (obj) => obj // here you can filter and transform what fields you want to index
			}})
    }
}

// later 

const peer = await Peerbit.create ({libp2p: your_libp2p_instance})
const store = peer.open(new TestStore());
console.log(store.address) /// this address can be opened by another peer 


// insert
let doc = new Document({
    id: "1",
    name: "hello world",
    number: 1n,
});
let doc2 = new Document({
    id: "2",
    name: "hello world",
    number: 2n,
});

let doc3 = new Document({
    id: "3",
    name: "foo",
    number: 3n,
});

await store.docs.put(doc);
await store.docs.put(doc2);
await store.docs.put(doc3);


// search for documents from another peer
const peer2 = await Peerbit.create ({libp2: another_libp2p_instance})
const store2 = peer2.open(store.address);

let responses: Document[] = await store2.docs.index.search(
    new SearchRequest({
        query: [
          new StringMatch({
                key: "name",
                value: "ello",
				method: StringMatchMethod.contains
            }),
        ],
    })
);
expect(responses]).to.have.length(2);
expect(responses.map((x) => x.value.id)).to.deep.equal(["1", "2"]);
```
