Understanding CPDS #
CPDS is one person's data server. An application asks it to store a record, CPDS checks permission, and a successful write becomes durable, signed state that another application can read or synchronize. You do not need to understand the cryptography or every Rust feature before following that request.
Read this guide in order the first time. Then use the source map to jump to the question you are working on. The examples describe the current implementation, not a promise that CPDS implements the complete AT Protocol PDS specification. Operating commands are in README; design tradeoffs are in architecture.md; missing production features are tracked in production-plan.md.
1. The vocabulary you will see #
Use this as a lookup table; you do not need to memorize it before reading code.
| Term | Meaning in this repository |
|---|---|
| PDS | Personal Data Server: the process hosting an identity and its data. |
| DID | The identity identifier, such as did:web:alice.test. It is not a password. |
| Handle | A human-readable name such as alice.test, resolved to a DID. Its current validity is separate from account status. |
| Record | A structured value, usually shown as JSON, stored under a collection and record key. |
| Collection / NSID | The record's type namespace, for example app.bsky.feed.post. A record's $type must match it. |
| Record key / rkey | A record's name inside a collection. Generated keys use TIDs; explicit keys need not be timestamps. |
| AT URI | A record address: at://<did>/<collection>/<rkey>. It identifies a location, not a particular version of its contents. |
| CID | A content identifier containing a format and cryptographic hash. Changing the encoded bytes changes their CID. A CID is not an access token. |
| DAG-CBOR | The deterministic binary representation used for records and signed structures. JSON $link and $bytes forms become native binary links and bytes. |
| MST | Merkle Search Tree: ATrium's content-addressed tree mapping record paths to record CIDs. Its root summarizes the public repository state. |
| Commit / head | A signed description of a repository revision / the currently selected commit. It is unrelated to a Git or Jujutsu commit. |
| Revision / TID | A sortable timestamp identifier. CPDS keeps new public repository revisions above the persisted previous revision, including after restart. |
| CAR | Content Addressed aRchive: roots plus CID-labelled blocks, used to transfer repository data and proofs. |
| XRPC / Lexicon | AT Protocol's HTTP method surface / the schemas naming its inputs, outputs, and errors. ATrium supplies many generated Rust models. |
| Cursor | A continuation position for a list or stream. A record key, a repository-list cursor, and a firehose sequence are not interchangeable. |
| Outbox | SQLite rows recording committed public sync events so clients can replay after a disconnect or restart. |
A useful distinction is address versus content versus permission. An AT URI names a record; a CID names particular encoded content; a token authorizes an action. None substitutes for either of the others.
2. The source map #
There are two Cargo packages. The root cpds package builds both a library
(src/lib.rs) and the executable (src/main.rs). cpds-protocol is a library
under crates/. They share a lockfile and workspace lint policy.
This map is an index, not a list of files to read at once. Start with main.rs
and AppState::assemble, then follow one request through the files it actually
calls. Leave the remaining features until that path makes sense.
| Question | Start here |
|---|---|
| What happens when I run it? | src/main.rs: command selection, startup gates, listener. |
| Where do settings come from? | src/config.rs and config/origin.rs: defaults, production requirements, URL policy; config/relay.rs retains origin parity tests. |
| Who constructs the services? | src/lib.rs: AppState::assemble. |
| Which URL calls which function? | http/mod.rs and space/routes.rs: registration; space/http.rs groups the feature's HTTP adapters. |
| How is a request checked or logged? | http/auth.rs, http/error.rs, http/security.rs, http/observability.rs, http/rate_limit.rs, rate_limits.rs. |
| What are the values passed between layers? | domain/: account, record, blob, OAuth, identity, and event types; syntax.rs: ATrium-backed syntax checks. |
| What makes record bytes valid and canonical? | cpds-protocol/src/lib.rs. |
| How does a public record change? | repository/records.rs: reads and write planning; repository/commit.rs: staged MST changes and signed commit. |
| Where are account status and public discovery? | repository/accounts.rs, http/server.rs. |
| How do exports and events work? | repository/export.rs, repository/car.rs, repository/stream.rs, http/subscription.rs. |
| Where do blob bytes and metadata go? | repository/blobs.rs, blob_store/, database/blob.rs. |
| Who owns SQL and migrations? | database/; record commit transactions in database/repo.rs, the ATrium block overlay in database/blockstore.rs, schema history in database/schema.rs. |
| How does login work? | oauth/, http/oauth.rs, database/oauth.rs. |
| How is identity resolved? | identity.rs: resolution; identity/http.rs: shared outbound transport policy; domain/identity.rs: document rules. |
| What belongs only to Spaces? | space/mod.rs: lifecycle, membership, and notification metadata; space/authorization.rs: grants/policy; space/records.rs: record/recovery service; SQL in space/database/repository.rs, metadata.rs, and auth.rs. |
| What checks and cleans storage? | repository/maintenance.rs, http/runtime.rs. |
| How do backup and operator actions work? | backup.rs, private_fs.rs, relay.rs, and the command branches in main.rs. |
| What remains outside those features? | clock.rs: monotonic TIDs; events.rs: optional in-process observers; error.rs: shared error vocabulary. |
Several files contain impl RepositoryService. They add methods to the same
type, not separate services. repository/mod.rs
declares those modules and constructs that type. Likewise, SQL methods can live
in feature files while operating on the same Database connection.
database/query.rs delegates fallible row iteration
to rusqlite, while Database::query_one uses its single-row decoder. Optional
lookups keep missing rows distinct from decoding failures. Raw tuples use
rusqlite's TryFrom<&Row>; the small sql_row! constructor handles explicitly
indexed struct fields. Both read SQL fields in order before domain validation.
Constraint mapping uses rusqlite's own error-code accessor: only a top-level
SQLite constraint becomes a conflict; conversion errors retain their original
database error and cause, even when that cause contains a constraint error.
Stored record and blob CIDs then use the native CID parser through the shared
error-context adapter; record JSON parsing still follows CID parsing.
Repository block lookup uses the same optional-query helper, then verifies the
content address after releasing the connection lock.
Block addressing checks the repository codec and hash algorithm before using
the protocol package's shared SHA-256 constructor; rejected writes never enter
the transaction-local overlay.
Outbox sequence extrema use the single-row helper with their existing aggregate
queries; an empty outbox still yields zero for the latest sequence and no earliest
sequence.
Outbox pages finish reading all SQL rows before decoding payloads, whereas
incremental block exports validate as they stream. Database::transaction commits only when its
callback succeeds; an error leaves the transaction to roll back. The actual SQL, validation order,
and feature-specific rules remain in the persistence modules.
Schema upgrades follow an ordered list of version thresholds, SQL batches, and
optional immediate blob-index backfills. Each step stays inside the existing
upgrade transaction; a failed backfill prevents later migrations and rolls back
earlier changes. The version-9 outbox repair remains in that same sequence.
All three database open methods share one connection constructor. It passes the
existing initialization flag to the schema implementation: normal and in-memory
opens can initialize storage; an existing-only open cannot initialize an empty
file and still uses read/write-only SQLite open flags.
Space HTTP has the same organization principle: credentials,
management, records,
sync, and notifications
keep related wire types beside their handlers. The small facade reexports the
route functions; it does not add another service layer.
One-string output objects use the existing JSON value representation. Their
typed list containers retain field order and optional-cursor omission; inputs
and nested structured outputs remain typed. Constructing these tiny JSON objects
adds a map/key allocation and string clone, but preserves exact response bytes.
http/request.rs names recurring native Axum extractor
tuples. A handler still destructures its state, headers, URI, and parsed payload;
the alias only shares the types. Extraction order and handler authentication
remain explicit, with no custom extraction implementation.
Public record reads share one generated ATrium output because both single and
list reads always include a CID. Latest-commit responses reuse the same generated
commit metadata as write responses. Wire fields and validation order remain the
same even where these internal Rust return types are shared.
Error::xrpc constructs named protocol errors for both public and Space paths;
it replaces duplicate local constructors without changing their names or
messages. Authentication errors remain a separate variant, and each caller
retains the condition and evaluation order that chooses an error.
Numeric Retry-After headers use the HTTP library's integer conversion, preserving
the existing decimal header bytes and response without a string-parse round trip.
Framework-error normalization checks the content-type prefix directly in its
short-circuit guard; successful and already-JSON responses remain untouched.
Outgoing responses use generated OutputData directly when an outer ATrium
Object would contain no extension fields. Nested objects and extension data
remain in their original representations.
The protocol encoder selects present $link and $bytes values before invoking
their decoders; those helpers return a decoded value, not another optional layer.
Type and blob checks still precede special forms, and special forms precede
ordinary child traversal. Blob validation borrows the JSON map through Serde's
native deserializer instead of cloning the entire object.
Repository listings retain the already-decoded ListedRepoHead rows until HTTP
assembles the generated response; only the existing public fields are emitted.
The collection-filtered listing validates its collection before sharing the
same cursor parsing, head query, and next-cursor construction as the full list.
Missing-blob inventories likewise retain their existing CID/record-URI pairs.
Neither path needs a second summary representation or another mapping pass.
When representations are identical, layers share them: Space record, operation,
blob-list, and space-discovery queries reach their services directly, as do Space
creation, update, and notification-registration inputs. Member and writer listings share
the concrete SpacePageQuery while keeping their separate authorization rules.
Notification registration and removal pass that same input through persistence;
credential checks still precede the unchanged SQL and expiry handling.
That query reaches both database listings directly. The storage boundary applies
the existing default/clamp and converts its bounded limit to SQLite's i64;
SQL ordering and row decoding remain unchanged.
Single-record reads and deletes also share RecordQuery with their services;
query and JSON parsing retain the same four string fields and rejection rules.
Reads pass that query through persistence after authorization, collection/key
validation, and repository existence checks. SpaceRef uses native FromStr
parsing at the existing validation points and preserves the original URI bytes,
so the lookup needs no reconstructed URI or second field mapping.
Single deletes also pass this query through after ownership, write policy, and
key validation; TID generation still precedes the unchanged delete transaction.
Blob inventory and Space discovery likewise pass their query values through;
persistence applies their existing endpoint defaults and bounds before querying.
The unbounded record inventory used by recovery remains a separate path.
The parsed writer notice also serializes directly to the existing four-field
notification JSON, after its hash is decoded and the writer is recorded.
Writer listings share SpaceWriter<Hash>: persistence keeps raw bytes, and HTTP
projects the hash to LexBytes after selecting the cursor. This keeps the same
eager encoding and JSON field order without a second three-field response model.
Latest-commit and batch-write responses use native single-key maps containing
typed SignedCommit and AppliedWrite values. This removes private wrapper
types at the cost of one outer map allocation, without converting nested values
to generic JSON or changing their field order.
Space record listings likewise build their four wire fields directly in the
existing post-cursor mapping, preserving the exclude-values behavior.
RepoOpsPage also serves
as the operation-list response; HTTP still applies exclude-values before
serializing it. Public and Space record views use
RecordView. Space HTTP and service writes share RecordInput<Text, Key>:
HTTP owns its strings and optional key, while services borrow text and require
the key for put/update. The record value remains owned in both cases. There is
no second six-field input model. Authorization and URI rules remain separate.
Public record reads compare native CIDs after full lookup and decoding, then
construct the same RecordView only when the optional CID filter matches.
The database's find_record returns an optional record directly. Write planning
keeps absence as data; public get/delete require a record and return NotFound.
Both paths still receive database and decoding failures unchanged.
find_blob likewise preserves absence as an optional metadata result. Reference
validation and byte reads turn absence into their distinct existing public errors;
availability/deletion filters and stored-metadata decoding remain in persistence.
Space and operation serializers explicitly omit internal metadata.
LifecycleEvent in database/repo.rs constructs and inserts identity/account outbox payloads;
the calling transaction still owns state changes, retention, and rollback.
That same typed next event selects the account handle/status compare-and-set.
The expected value is persisted text; the next status remains an AccountStatus.
A no-op or conflict returns before commit, so trigger side effects roll back too.
The service uses the same event to share bounded lifecycle retries. Handle
validation remains before lookup; status idempotence remains before user policy,
and only the matching handle/status conflict is retried. Operator and user
permissions remain distinct, with their existing public return types.
Validated public operations reuse ATrium RepoOpData through the event stream;
the durable JSON payload remains a separate representation with its existing
string CIDs and null fields. The commit transaction constructs durable outbox
operations directly alongside borrowed records, retaining each SQL insertion's
original position in the transaction.
Record displays only its AT URI, never its value or CID. Views and batch output
use its native to_string() directly. Maintenance and legacy
backfill diagnostics use that formatter through lazy error context, so successful
paths do not construct a diagnostic URI. Private snapshot and blob writes use
native file-creation options; their permission, synchronization, and cleanup
ordering remains explicit at the storage boundary.
Private snapshot helpers return their final native I/O result through the existing
error conversion, without reconstructing a redundant success result.
Each synchronous/asynchronous directory-sync function guards its I/O with
cfg!(unix): Unix retains open-then-sync and other platforms return without I/O.
Filesystem opening and publication own their directory preparation directly;
readiness owns its write/sync probe and still awaits cleanup before returning
the probe result. These operations need no single-caller forwarding methods.
Blob deletion and temporary-file cleanup share the same unlink-then-parent-sync
operation. Cleanup is still awaited before choosing which error to return.
Temporary-name recognition chains UTF-8 conversion and the last pending-marker
split before checking the readiness/CID prefix and sixteen ASCII hex bytes.
Generated blob paths always contain an owner hash and CID beneath the root,
so their parent is nonempty even when the configured root is relative.
clock::format_utc_datetime shares the existing whole-second timestamp text for
repository events and Space notice expiry. Callers retain their distinct range
error context and any subsequent Lexicon validation. Notification registration
formats the expiry directly after persistence, without a forwarding wrapper.
clock::now supplies whole Unix seconds to persistence, Space credentials,
registration, backup, and blob collection. Reads remain at their original call
sites; the helper does not cache time. OAuth's duration-before-timestamp arithmetic
and the TID clock's nanosecond reading remain separate.
The in-memory blob adapter
uses its existing derived Default directly; no separate constructor is needed.
TID encoding collects the thirteen alphabet digits directly from the unchanged
64-bit clock value; clock advancement, saturation, and decoding remain separate.
Syntax validators share a small adapter around ATrium's native FromStr parsers.
Each caller keeps its exact error label; borrowed validators return the original
text. Datetime minimum checks and language duplicate checks remain separate.
Space service-endpoint resolution keeps the first parsed DID for lookup instead
of parsing it again; local comparisons still use its unchanged original text.
Space references check their prefix and four-segment shape before validating
the DID, collection, and record key in that order.
Language validation parses with ATrium first, then classifies subtag byte shapes
for CPDS's existing duplicate checks. Singleton extensions and longer variants
cannot collide in the shared set of case-folded subtags.
Identity resolution concatenates binary DNS TXT chunks before parsing the DID.
Local document validation and network handle verification share the exact,
case-sensitive at://{handle} alias-membership check. This predicate does not
parse or normalize the handle; each caller retains its earlier checks and errors.
did:web URL construction borrows unescaped segments and owns only decoded
ones; every segment is still decoded before path and outbound-URL validation.
Splitting on the colon always produces at least one segment, so the decoded
host and remaining path can be borrowed directly; empty segments still fail
the subsequent validation. Outbound URL policy matches host kind, deployment
mode, and scheme together, retaining HTTPS domains and local-only loopback IPs.
Space CAR sections use unsigned-varint, already present through ATrium, for
length-prefix encoding. CPDS still owns the whole-section size check before any
output mutation. Headers and CID-prefixed blocks pass their byte slices directly
to the same section writer, without a separate forwarding block helper.
A stable native tuple-key sort orders record paths by byte
length, then UTF-8 bytes, retaining the input order of duplicate paths.
Public and relay configuration use the same validated HttpOrigin value.
Its parse_public and config-private parse_relay constructors retain their
setting-specific errors, component-check order, and production HTTPS rules.
Display, hostname formatting, and endpoint construction share the same URL
representation; endpoint construction still clones the URL and sets its path.
This intentionally replaces the former public PublicOrigin and RelayOrigin
Rust types and their derived Debug names, without compatibility aliases.
The Settings reader also owns relay, account, and OAuth-client parsing. These
methods use the same source and deployment mode; configuration still reads
settings in field order and stops at the first failure.
Deployment mode is selected at that boundary: absent or exact local uses local
mode, exact production enables production checks, and all other strings fail
before any further setting is read.
Why only one extracted library? #
Both public repositories and Spaces need exactly the same record encoding, but
neither should import the other feature's service implementation. The protocol
package expresses that shared rule and tests it without assembling CPDS.
Its byte-addressing helpers, sha256_cid and dag_cbor_cid, return a CID
directly: SHA-256 always supplies 32 bytes to a 64-byte-capacity multihash.
record_cid remains fallible because it validates and encodes the record and
enforces the size limit before hashing.
Storage and HTTP are not separate packages because they are not independent products here. Most organization needs a module, not a new public API or trait. Keep real change points—blob storage, OAuth client lookup, event delivery, identity resolution—explicit; do not invent a generic repository framework to make unrelated protocols look identical. ATrium already supplies standard protocol machinery, so CPDS composes it instead of keeping a second MST or signature implementation.
3. Follow startup before following a request #
Read main, then AppState::assemble. main passes the operating-system
argument iterator directly to operation_from; there is no separate
command-parsing wrapper. Normal startup:
- Initializes logging and parses the command and configuration.
- Opens or creates SQLite and applies migrations. Opens the filesystem blob
store.
CPDS_DATABASEdefaults tocpds.sqlite3; bytes default toblobs/. There is no database server to install and no separate migration command. Schema version 9 preserves older records and event sequence numbers while repairing legacy upgrades and indexing OAuth credential expiry cleanup. - Assembles one configured account, the signing services, identity resolver, OAuth registry, adapters, and request/stream limits.
- In production, verifies the configured handle and DID in both directions. Local startup uses its derived development identity without network lookup.
- Checks adapters, collects eligible orphan blobs, verifies durable public repository state, reconciles the configured handle, and collects eligible old repository blocks.
- Binds the TCP listener, logs
cpds is listening, and starts serving with periodic maintenance. Ctrl-C/SIGTERM triggers bounded draining and a WAL checkpoint.
That is why a process can be doing startup work before it prints the listening
message. /health means HTTP is alive; /ready additionally checks dependencies
and the durable event store. Neither repeats the entire signed-graph proof on
each request.
The final database readiness probe uses rusqlite's native query_row_and_then
with SELECT 1, retaining its first-row requirement and database error mapping.
Stream handlers subscribe directly to the existing Tokio watch sender. Shutdown
publishes sticky true on that sender after the shutdown future resolves and
before request drain; AppState adds no forwarding methods around the channel.
Handle revalidation returns confirmed validity separately from resolver errors. A transient failure leaves the previous validity flag intact; confirmed changes drive the existing recovery/invalidation events without changing account status. The identity service retains its configured deployment mode directly for both the local-handle shortcut and outbound policy. Concrete DNS and DID resolution live in its network interface implementation; no forwarding methods are needed. Identity HTTP dispatch likewise owns its request loop directly inside the existing timeout, retaining its HTTPS/redirect policy and bounded body reads.
The other commands deliberately branch away from serving. verify proves
existing storage, backup captures it, set-account-status changes hosting
policy offline, and request-crawl asks configured relays to discover the PDS
without opening storage. Do not use a fresh empty database to "repair" an
unexpectedly missing production database.
The command parser combines optional Unicode conversion and status parsing before
producing the same fixed configuration error. Crawl and serve return their native
results directly; their startup checks and logging still happen in the same order.
Relay request futures borrow the client, configured origin, and hostname through
the awaited batch. They need no per-relay clones; retries, logging, bounded delays,
and collecting every failure remain unchanged.
4. Follow one public write #
Use createRecord first; study applyWrites after that.
JSON request + bearer token
→ HTTP adapter: parse generated input and authenticate
→ records: check owner, identifiers, record shape, blob references, swaps
→ commit: stage record blocks and ATrium MST changes; sign final head
→ SQLite transaction: blocks + head + indexes + operations + sync event
→ commit succeeds
→ optional EventSink notification; HTTP returns record/commit identifiers
The HTTP handler is not supposed to decide how to build an MST or write SQL. The protocol encoder is not supposed to decide which account may write. SQLite must recheck race-sensitive conditions inside the transaction, not merely trust an earlier HTTP check.
swapRecord and swapCommit mean "perform this only if the version I saw is
still current." They prevent silent lost updates. A generated record key and a
repository revision both use the TID clock, but they serve different purposes.
applyWrites preserves an enum distinguishing create, update, and delete. The
planner walks operations in order, so a later operation sees earlier changes
in the same batch. It then commits the batch once. Failure must leave no partial
record changes, no new head, and no public event advertising uncommitted data.
The committed RecordMutation values also supply the HTTP results, so the
planner does not maintain a second result vector alongside its mutations.
Single writes return (record, commit) and batches return (commit, mutations).
HTTP names those fields directly without a separate service-result wrapper.
Commit metadata uses ATrium's native CommitMetaData: the generated revision
is validated before staging, borrowed during signing, and returned with the
native root CID after durable publication and notification. This intentionally
replaces the string-only CommitView Rust type and its Debug representation.
HTTP no longer reparses these already-valid commit values; record CID validation
remains first in single-write output conversion. Stored repository heads still
carry raw revision text, which latest-commit HTTP validates at its existing
boundary. Nested wire objects and the cid-then-rev field order are unchanged.
The selected MST operation is awaited before one shared error conversion; a
failure still returns immediately before the next operation or publication.
The per-key cache is consumed and replaced for each planned operation. A cached
deletion is distinct from a key that has not been read, so later operations
cannot accidentally reload the pre-batch record from SQLite.
Public and Space batches share the owned command enum, exposed as RecordBatchWrite
and WriteRequest respectively. Public HTTP still converts its generated ATrium
inputs at the same boundary; Space JSON retains its own union tags. Their
authorization, planning, and commit rules remain separate.
Space checks Create/Update variants directly at the batch validation guard; a
single-use enum accessor is unnecessary. The size check remains first, and
strict-validation rejection still precedes per-write authorization.
There are two related representations of a public record: the convenient SQL index/value and the canonical content-addressed repository block. They are not two independent truths. One commit updates both, and startup verification checks their exact agreement. Historical schema migrations are therefore not dead code merely because new databases start at the latest schema. Opening a signed repository takes its root CID and expected revision directly, without building a temporary database-head value. It still opens the graph, checks the revision, and then verifies the signature, in that order. The block overlay eagerly verifies that reachable blocks exist, then lends its matching staged entries to the event-CID collector. That caller copies only CIDs, not block bytes. The separate staged-write handoff and its ordering are unchanged.
5. Follow reads, blobs, and exports #
An ordinary getRecord resolves a hosted active repository, validates the path,
and reads its current SQL record. An optional requested CID must match that
record. listRecords applies its own bounded ordering and cursor rules; do not
reuse another endpoint's cursor parser just because both cursors are strings.
Its service returns the records/cursor pair directly, matching the other listing
methods. HTTP converts each record before assembling the unchanged response;
there is no second page wrapper.
A blob is a separate byte object, not a large JSON record:
- Upload validates size and MIME syntax, computes its raw-byte CID, and reserves owner metadata in SQLite.
- The blob adapter publishes the bytes; the filesystem adapter verifies their CID and durably renames a private temporary file.
- SQLite marks the upload available. A record can now reference the owner's matching CID, MIME type, and size.
- Public
getBlobserves it only while a current public record references it. A Space-only reference does not make it public.
Strict write validation and tolerant reference discovery share only iteration over JSON children. A valid typed blob ends strict traversal at that object; discovery still visits its children, and their legacy/error rules stay separate. ATrium decodes each blob from a borrowed JSON value, avoiding an initial deep clone while still returning owned metadata. Strict recursive traversal uses native fallible iteration, preserving child order, partial collection, and the first error; it does not scan past a failed child.
Optional blob cursors use native Option/Result composition: absent cursors
remain absent, parsed CIDs are canonicalized before SQL, and each inventory
retains its own malformed-cursor error context.
Deleting a reference does not immediately delete the file. The collector checks both public and Space reference indexes, waits through the configured grace period, durably claims an orphan, and deletes its bytes. Claims make interrupted cleanup resumable and prevent a new record from attaching to a claimed object.
Exports answer different questions. getRepo returns a full or retained-history
incremental CAR; sync getRecord returns a signed proof for one record;
getBlocks returns requested blocks only if reachable from that repository.
They do not expose every block that happens to exist in the shared database.
ATrium reopens these locally generated archives in tests; there is no public
remote-CAR import endpoint.
The same crate-internal sync_head supplies exports and the latest-commit HTTP
handler. HTTP projects its CID/revision into the wire converter directly; there
is no separate service method that merely wraps that head.
6. Follow OAuth without confusing its tokens #
Read tests/oauth_flow.rs alongside the service. The
test is a small executable client, including deliberate failure and replay.
- An app supplies its registered client ID, exact redirect URI, scope, state, and S256 PKCE challenge. The challenge is a hash of a secret verifier the app keeps for the next step.
- The account approves with its password. CPDS checks the password using Argon2 and returns a five-minute, one-time authorization code to that redirect.
- The app exchanges the code with its verifier and the same client/redirect. SQLite inserts a hashed access token and consumes the code atomically.
- The app uses the returned one-hour opaque bearer token. CPDS hashes the presented token, finds its account/client/scope, and applies endpoint policy.
The authorization page escapes attributes with native string replacements, replacing ampersands first so generated entities are not escaped a second time. Its HTML and attribute bytes remain unchanged. Authorization returns the code and redirect URL as a pair. HTTP retains both through response construction and uses the URL for the unchanged redirect header. PKCE validation returns its native result after all earlier request checks. Registered redirect matching uses the URL list's native membership operation; URL equality and client-before-redirect-before-scope-before-PKCE error order stay unchanged. Discovery metadata retains owned native URLs through response serialization. URL serialization supplies the same canonical strings without converting the already-owned endpoint URLs into additional String allocations.
The account password, authorization code, and access token are different
credentials. state is returned for the client to check; it is not a substitute
for PKCE. A failed token insert must leave the code usable for a retry, while a
successful exchange must make replay fail. Consumed codes are deleted in that
same transaction; expired credentials are rejected at the expiration second and
cleaned up during issuance/redemption. The unit fault-injection test in
oauth/mod.rs checks that transaction boundary directly.
Code redemption decodes all five stored string columns before checking request
bindings, then returns only the DID and scope its service needs. This keeps
SQL-type failures ahead of binding mismatches without another stored-code model.
The authorization page and approval form share AuthorizationRequest; their
endpoint-specific fields and validation remain in HTTP. Parser failures still
pass through the common public-error normalizer. The authorization handler checks
response type, then challenge method, before client/redirect/PKCE validation;
no single-use conversion wrapper is needed. The token endpoint passes its
parsed TokenForm directly to the service: HTTP rejects unsupported grant types
first, and the service then checks PKCE before generating credentials or redeeming
the code. The issued TokenGrant is also
the token response, with its bearer type and the DID serialized as sub.
Authorization-code persistence also consumes the existing request. Its defaulted
URI parameter keeps AuthorizationRequest URL-validated in HTTP and the service,
while raw string URIs remain representable for the database boundary. Client and
redirect text are borrowed before acquiring the transaction; state is not stored.
PKCE challenge derivation owns its verifier guard and reuses OAuth's existing
SHA-256/base64url hash. Length and character rules still run before hashing.
This is the implemented OAuth core, not the complete AT Protocol OAuth profile.
PAR, OAuth DPoP, refresh/revocation lifecycle, and dynamic profile-complete client
registration must not be inferred from the presence of /oauth/token.
7. Add Spaces only after public records make sense #
A Space identifies an authority, a type, and a key. Within it, each writer has their own repository. Space records live in separate tables from public records; the public record endpoints and public firehose do not reveal them.
The domain-owned RecordQuery carries the same four raw key strings through
HTTP parsing, single deletes, batch-delete planning, and the SQL delete helper.
It removes repeated unpacking without validating earlier or changing ownership.
Batch deletion still rejects a missing record and rolls back earlier writes;
single deletion remains idempotent. The batch result still emits only its delete
type tag, never the internal key fields.
OAuth Space grants constrain authority/type, collection, read/write action, and management capability. The read authorization enum distinguishes an OAuth grant from a credential for one Space. A public CID does not bypass these checks. HTTP owns this enum and services borrow it directly, without a second borrowed representation. Each read still performs its own checks, including snapshot authorization when operation listing reaches that boundary. Record capabilities carry their required collection alongside the action; read and management capabilities do not take an irrelevant optional collection. Policy field reads use immutable JSON indexing followed by the expected type check, so absent fields and wrong types still follow the existing rejection path. Space metadata reads use that same enum while preserving each credential's own checks; a credential read does not inherit OAuth scope or membership rules. Blob reads consult the selected Space repository's reference index after authorization, so they are not limited to scanning the first page of records.
Delegation tokens are exchanged once for Space credentials bound to a DPoP
public key. DPoP is a signed proof of possession: a request proof binds its
method and URL, and ath binds it to the presented credential. Replay storage
rejects reused proofs. Client attestations, managing-app checks, and service
notification tokens are additional boundaries, not interchangeable credentials.
Credential verification returns the exact verified Space string directly;
HTTP applies its Space rate check before passing that scope to the service.
Authorization-header parsing is one native optional-value pipeline: first
header, valid text, exact scheme, one ASCII space, then nonempty payload. It
neither trims tokens nor falls back to a later header, and preserves the borrowed
payload or the same authentication error.
Delegation exchange returns its validated SpaceClaims. HTTP immediately takes
the issuer and subject from those claims, without a second delegation model;
unused claim fields are dropped before any subsequent asynchronous operation.
All three minted token kinds use one signer that builds the ES256K header from
the token type and optional key ID. Each caller still creates its own claims,
with the same time reads and random identifier generation before serialization.
JWT decoding borrows the original header.payload text for signature checking.
It checks the three-segment shape before decoding header, claims, and signature
in that order; no reconstructed signing-input string is needed.
Service-token verification returns the issuer/audience pair directly. HTTP names
both values and checks the issuer's service rate limit before notification policy.
Credential issuance reuses the existing public/member read-policy decision after
checking application access and the owner's bypass. Managing-app delegation and
its configuration errors remain separate, and only non-owner member-list policy
consults the membership table on this path.
That lookup uses SQLite's native first-row existence check, with the same query
and connection lock rather than an optional unit-valued row.
Public and Space commits are deliberately different. Public repositories use signed MST roots; the alpha Space format combines an order-independent set hash (LtHash), fresh binding material, a signature, and a MAC. A Space CAR has a signed view and record index as two roots. Record values still use the same canonical codec as public records. One read transaction obtains a matching revision and record snapshot, with a 64 MiB stored-JSON bound before loading records and a separate 64 MiB encoded CAR bound. Metadata-only recovery omits values, not permission checks.
SpaceService holds ATrium's Secp256k1Keypair directly. commit::sign composes
the Space-specific set hash, fresh randomness, context, signature, HKDF, and MAC;
there is no second key-holder wrapper. Key import still occurs during service
construction with its Space-specific configuration error context.
Recovery and commit-only callers share signed_snapshot; callers needing only
the signed commit select it from the returned commit/records pair. Even those
callers still authorize, load the bounded snapshot, and sign it before discarding
the records. The commit-only HTTP wire wrapper remains unchanged.
The recovery handler passes that pair directly to the existing CAR serializer,
without another service forwarding method.
Space record mutation helpers recheck account activity inside their transaction, before reading or changing records. Batch writes call those helpers in order, so each item observes the current transactional account state and any failure rolls back the complete batch. Strict batch deletes and idempotent single deletes retain their separate missing-record behavior.
Space writer notifications and the public durable firehose are also different.
Space metadata persistence receives the existing update/notice inputs after
service validation. It stores only the notice's space, repository, revision,
and hash; authentication remains the service's responsibility. At the storage
boundary, None means no change and Some(Value::Null) stores JSON null.
Writer listings and notification registration share the credential-match,
local-authority, and stored-Space checks. Registration and unregistration first
check the hosted account's active status; writer listing keeps its existing
policy without that account-status check.
Stored notification destinations travel as (service, endpoint) pairs. The
database decodes both strings in that order, and delivery destructures the pair
into named references without another registration output model.
Space notification delivery is best-effort with one two-second budget per batch
and at most four concurrent recipients. Incoming deletion notices do
not remove a retained local replica because CPDS does not keep one. Read the
alpha feature as its own bounded protocol, not as finished general federation.
8. Follow durability and recovery #
A public record transaction appends durable events before acknowledging success.
The initial sequence contains identity, account, and commit events. The optional
EventSink runs afterward; failure there is logged, not returned as a failed
write that might tempt a client to create the record again. The whole optional
event batch shares a two-second delivery deadline. These deadlines do not make
notifications durable or eliminate uncertain client outcomes after a disconnect.
subscribeRepos rebuilds ATrium wire messages from that durable history and
sends DAG-CBOR WebSocket frames. The consumer saves its last processed sequence.
If it reconnects within retention, it can replay. If it falls behind retention,
OutdatedCursor means it must resynchronize from a repository export. Retained
events constrain garbage collection: blocks needed for replay must remain.
Stream errors select their public name/message before one shared timed send.
Internal failures are still logged and sanitized before encoding; XRPC errors
retain their own names and messages, with the same frame bytes and deadline.
HTTP JSON and stream CBOR share the two-field ErrorBody<Message> representation.
HTTP still owns its String and streams borrow their message; each keeps its
original serializer, field order, error context, and response/frame construction.
A backup must preserve the database and blob files as one consistent pair.
CPDS verifies storage, holds an SQLite write barrier, takes a native database
snapshot, copies CID-verified blobs, and writes a non-secret manifest into a
new private directory. The barrier can delay writes; backup is not a free
background copy. The signing key and password configuration need separate
protection. verify checks restored storage without opening a listener and
refuses a missing or uninitialized database.
Account hosting status is separate from identity and storage. Deactivation can
be reversed by the account; the offline operator command controls host states.
deleted means access suppression here, not secure erasure. Never describe
that operation as destroying all account data.
AccountStatus owns the existing account and repository error mappings and
active-state checks. Callers retain responsibility for looking up the right
account and choosing the appropriate policy before changing or exposing data.
The database returns a hosted identity as (Account, AccountStatus), with named
destructuring in its callers. It reads DID and handle before parsing the stored
status. This replaces the former HostedAccount Rust wrapper and its named
Debug representation; protocol output and account-policy checks are unchanged.
9. Enough Rust to read this code #
| Syntax or concept | How to read it here |
|---|---|
struct |
A named set of fields. Record holds a DID, collection, key, CID, and value. It need not be a class with inheritance. |
enum / match |
One of several valid alternatives. RecordBatchWrite prevents a delete from accidentally carrying a required create payload. |
impl Type |
Functions belonging to that type. Multiple files can contain implementations of the same service. |
Result<T> and ? |
Either a successful value or an error. ? returns an error to the caller early; it does not swallow it. |
Option<T> |
A value may be absent. None is not automatically an error: a list can legitimately have no next cursor. |
&T / &mut T |
Borrow a value for reading / exclusive mutation instead of transferring ownership. |
String / &str |
Owned text / a borrowed view of text. .clone() copies owned data unless the type explicitly shares it. |
Arc<T> |
Shared ownership across tasks. Cloning an Arc shares the same object; it does not duplicate the database. |
Mutex<T> |
Exclusive access to shared mutable state. CPDS's database lock protects one SQLite connection. A lock is not a database transaction. |
async, .await |
Work that can yield while waiting. Synchronous SQLite, hashing, or CPU work does not become nonblocking just because its caller is async. |
trait / dyn Trait |
An interface / a runtime-selected implementation. Arc<dyn BlobStore> lets tests use memory and the executable use files. |
impl Serialize |
A concrete but hidden return type supporting serialization. The protocol crate avoids exposing a second public data-model enum. |
pub, pub(crate), private |
Visible to consumers, only within this crate, or within the module's privacy boundary. Module splits need not make APIs public. |
#[derive(...)], Serde |
Generated routine behavior such as serialization. Wire annotations still matter: field names and omitted values are protocol contracts. |
#[cfg(test)] |
Code compiled for that target's unit tests, not ordinary server execution. Files in tests/ are separate integration-test crates. |
Do not read every unwrap() the same way. An assertion in a test describes the
expected setup/result; an unchecked operation on an untrusted production value
needs a very different justification. Likewise, converting every struct into a
trait does not automatically make code more testable—real SQLite often proves
transaction behavior better than a mocked database.
The shared Error type receives its HTTP response implementation in
http/error.rs; no extra error wrapper is needed. ErrorContext::context adds
a diagnostic and chooses the existing error category without losing the
underlying failure text.
10. Learn by running one small test at a time #
Run from the repository root. Tests create isolated memory or temporary storage; these exercises do not use your running PDS database. Cargo may need to download locked dependencies on its first build. Read the named test, predict the result, then run it. The assertion following a call tells you what the author promises.
Exercise A: identical records have identical addresses #
Read the protocol fixture tests and look at one JSON/CBOR/CID fixture triple.
Why would encoding $bytes as an ordinary string change the CID?
cargo test --locked -p cpds-protocol
Exercise B: a batch is one transaction #
Find the create/update/delete sequence and the deliberately failing batch in
record_flow.rs. Which checks prove the state did not partially change?
cargo test --locked -p cpds --test record_flow public_apply_writes_is_atomic_ordered_and_emits_one_commit
Exercise C: uploading is not publishing #
Read the public blob test before running it. Predict the response immediately after upload and after a public record references the returned blob.
cargo test --locked -p cpds --test record_flow blobs_become_public_only_when_referenced_by_a_public_record
Exercise D: a failed login exchange can be retried safely #
Follow the SQL trigger that rejects token storage. Why must the code remain unused? Then compare that failure with replay after a successful exchange.
cargo test --locked -p cpds --lib failed_token_storage_does_not_consume_the_authorization_code
cargo test --locked -p cpds --test oauth_flow
Exercise E: the same interface works with files and memory #
Read contract in blob_store_contract.rs and both adapter implementations.
Find behavior a filesystem needs that an in-memory map does not.
cargo test --locked -p cpds --test blob_store_contract
cargo test --locked -p cpds --test backup_restore
Exercise F: permission and encoding both survive a Space export #
Read the selected Space blob-reference test and the two-root CAR test. The former tests who can read; the latter checks what bytes are being exported.
cargo test --locked -p cpds --test space_flow list_blobs_only_exposes_references_in_the_selected_space_repo
cargo test --locked -p cpds --test space_flow get_repo_returns_two_root_verifiable_car_layouts
Exercise G: reconnect after missing events #
Finally read the fake-relay scenario. It receives an actual crawl request, resolves the served identity, repairs an expired cursor, and verifies the next live commit. This exercise requires loopback networking and child processes.
cargo test --locked -p cpds --test subscribe_repos_flow fake_relay_crawls_resolves_identity_repairs_gap_and_resumes_live
11. How to choose a test and make a change #
| What changes? | Evidence to run/read |
|---|---|
| Pure record encoding | Protocol unit tests plus pinned fixtures under tests/fixtures. |
| A service invariant or SQL race | repository/tests/ groups account, blob, export, maintenance, record, and stream cases; SQL tests stay beside their adapters. These use real SQLite, rollback/failure injection, and restart checks. |
| An HTTP contract | record_flow, oauth_flow, sync_flow, space_flow, account_lifecycle, and http_* integration suites through the shared router harness. |
| An adapter | blob_store_contract, readiness tests, and the adapter's own tests. |
| Socket/process behavior | subscribe_repos_flow, relay_crawl, runtime unit tests, and Unix-only process_lifecycle. |
| Compatibility with AT Protocol | atrium_api_interop, atrium_repo_interop, crypto_interop, protocol/syntax fixtures, and composed export/stream tests. |
The shared harness does real OAuth and real SQL. It replaces infrastructure, not the business rules being tested. A green pure test does not prove a process will bind, a green socket test does not prove real DNS or TLS deployment, and fixture parity does not prove complete federation.
For an ordinary change:
- Find the route or command, service rule, persistence boundary, and existing behavioral test. Read only the additional layers needed to explain it.
- Add a regression for the observable failure before changing behavior.
- Prefer an existing type, helper, or mature dependency. Put new code where its reason to change already lives. Extract a module before proposing a crate.
- Verify failure and success, including rollback, visibility, and replay when relevant. Remove the superseded implementation rather than keeping two paths.
- Run the workspace gates and review the diff, keeping unrelated work intact.
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo test --workspace --all-targets --locked
cargo deny --locked check
--workspace matters: plain cargo test selects the root package and will not
run the extracted protocol package's tests. The full suite needs permission to
open local sockets and launch processes. CI is configured for Rust 1.88 on
Linux; passing a local run is not evidence that CI, another platform, or a live
deployment has run.
You have the central model when you can explain who authorizes a change, what must commit together, what can be recomputed or replayed, and which test proves each claim. The rest of the repository becomes a set of concrete examples of those four questions, rather than a vocabulary test.