README.md

Folio #

A local-first database for AT Protocol data. Embed Folio on any client (native or web) to get a local database that functions offline, syncs optimistically, and creates a fast, low-friction user experience.

The public repository API loads collections on first read, then reads and edits locally. Synchronization refreshes only loaded collections and publishes edits:

let client = folio::Client::new(did, store, transport);
let mut repo = client.get_pub_repo();
let record = repo.get(&key).await?; // first read loads this collection at a coherent checkpoint
let records = repo.list(&key.collection).await?; // uses the local cache
repo.put(&key, updated_record.clone()).await?;
assert_eq!(repo.get(&key).await?, Some(updated_record));
repo.sync().await?;

Repository methods return folio::Result<T> with a concrete folio::Error. Match grouped failures such as Error::Record(RecordError::TypeMismatch) or Error::Sync(SyncError::Conflict(key)); XRPC variants retain their endpoint's typed error. Store and transport variants retain host errors through std::error::Error::source(). Native error sources require Send + Sync; Wasm keeps JavaScript error sources local. Adapters and their futures can still be local.

sync() leaves divergent edits saved for review. Set a conflict policy for a sync pass to prefer the server or the pending local value:

repo.sync_with(|_| Ok(folio::Resolution::Remote)).await?;
repo.sync_with(|_| Ok(folio::Resolution::Local)).await?;

A custom callback receives the key and base/local/remote values and can return Resolution::Replace(value) to merge or delete. It runs only when the server changed from the edit's base and differs from the desired value. All decisions are saved together before publication. Local preference means the pending edit wins when synced; timestamp-based last-write-wins needs an application-defined ordering, including deletion and tie-breaking rules.

For manual review, use repo.conflicts().await?, then repo.resolve(&conflict.key, conflict.revision, folio::Resolution::Local).await? (or Remote / Replace(value)). Reload a stale review before resolving it. Sync sends at most 200 edits per transaction and acknowledges each receipt before the next. A later failure preserves that progress and keeps remaining edits. Lost responses require a fresh pull; Folio does not automatically retry writes.

Native clients with thread-safe adapters work in ordinary Tokio tasks. client.with_transport(other_transport) shares the store and discovery cache, which also supports per-operation host request capabilities.

Blob bytes live separately from records. Native repositories expose put_blob and get_blob; browser clients expose putBlob and getBlob for durable local saves and cached downloads. Sync uploads referenced bytes before publishing records. See the image save and preview example.

Authentication belongs to the supplied transport. The current memory store is not durable, and synchronization trusts the PDS rather than verifying repository signatures and Merkle proofs.

folio-transport-http provides a native authenticated HTTP transport. Construction and repository selection are synchronous and make no network requests. The client discovers the account's PDS when needed; the transport authenticates on its first request. Session refresh remains with the host application.

client.get_priv_repo(space_uri)? selects the account's repository in a Space. Space reads, edits, and sync are not implemented yet.

The runnable E2E example shows login, lazy loading, local reads and edits, sync, and deletion using only Folio's public APIs:

cargo run -p folio --example e2e --locked

It uses the same root .env credentials and creates, updates, and deletes one uniquely keyed public record.

The live E2E test is ignored by default. It uses ATPROTO_HANDLE, ATPROTO_DID, and ATPROTO_PASSWORD from the ignored root .env. It creates one uniquely keyed record in the account's existing public repository, checks local reads and remote writes, and deletes the record through Folio before finishing:

cargo test -p folio --test e2e --locked -- --ignored --nocapture

Browser packages #

Use devenv shell for Rust (including wasm32-unknown-unknown), Bun, and wasm-pack. Run these commands from the repository root:

devenv tasks run folio:build     # Wasm, frozen Bun install, JS + declarations
devenv tasks run folio:check     # build + TypeScript
devenv tasks run folio:test      # build + TypeScript + Bun integration tests
devenv tasks run folio:rust-test # Rust tests; the live-account test stays ignored
devenv tasks run folio:pack      # tarballs in target/packages
devenv tasks run folio:smoke     # isolated Astro/React app: types, bundle, auth, blobs, Wasm
devenv test                     # format, Clippy, Rust, Bun, and package smoke checks
devenv up browser               # interactive fixture, run separately from tests

The Bun workspace contains @folio/client, @folio/react-query, and the optional @folio/at-astro integration. Generated Wasm and JavaScript are ignored; rebuilding is required after a fresh checkout. The installable client includes its Wasm loader, binary, and TypeScript declarations. No task publishes a package or contacts a live ATProto account.

Configure browser conflict policy when opening the client:

import { oauthFetch, Folio } from "@folio/client";

const folio = await Folio.open({
  did: session.did,
  fetch: oauthFetch(session),
  resolveConflict: "remote",
});

Use "local" to prefer pending edits, or a synchronous callback returning "remote", "local", or { replace: value } (null deletes). Omitting the option keeps manual review. See the client API.

Use @atproto/oauth-client-browser to obtain the session; the client API shows login and metadata setup. For an Astro app using at-astro, add folio() from @folio/at-astro to its integrations and import Folio from @folio/at-astro/client. The adapter supplies the authenticated publication/blob routes and fetch function automatically.

The React Query adapter provides connectFolio, schema-based folioListOptions and folioRecordOptions, and folioMutationOptions. Connect before mounting queries, pass generated Lexicon modules to infer and validate records, save with useMutation(folioMutationOptions(mutationFn)), and call folio.sync() separately to publish. Query invalidation reads cached data.

devenv up browser starts the verification fixture; devenv processes logs browser shows its URL. Use devenv down to stop it, then start it again after edits to rebuild. Save offline, reload to recover the edit, and synchronize to its in-process mock PDS. It makes no live-account requests. An offline application shell remains application-owned.