Repository navigation
Description
Motivation
#12198 moves pnpr's hosted store (published packages + static content) into an S3-compatible object store (S3 / Cloudflare R2 / MinIO / …). That removes the biggest blocker to running pnpr as multiple stateless replicas, but it isn't sufficient on its own: pnpr still keeps other state on local disk that a horizontally-scaled or serverless runtime won't preserve or share.
This issue tracks making the remaining state pluggable so pnpr can run as a stateless, horizontally-scalable service (the realistic near-term target is container-serverless with autoscaling — Cloud Run / Fly / Container Apps / Fargate scale-to-zero; true FaaS is a larger lift, see below).
Organizing principle: every per-instance disk dependency becomes a config-selected backend, defaulting to today's local behavior, following the pattern pnpm/pnpm#12198 established (build the client once at config-load time into an Arc<dyn …> handle so request handlers stay infallible).
Two backend "kinds"
Everything pnpr keeps locally is one of:
- Blob (content / objects) — already abstracted by
object_store; reuse theS3Storefrom feat(pnpr): store hosted packages in an S3-compatible object store pnpm#12198. - Record (relational / KV state) — narrow async traits, default impl = today's SQLite/file, plus a networked impl.
Components
| Component | Today (code) | Kind | Externalize via |
|---|---|---|---|
| Hosted store | storage.rs HostedStore {Fs|S3} |
Blob | ✅ done (#12198) |
| Proxy cache | storage.rs cached: Store (fs-only) |
Blob | Generalize to {Fs|S3}, reuse S3Store |
Accelerator CAS (pnpr-store) |
install_accelerator.rs store_dir |
Blob | Content-addressed → S3 maps directly |
| Auth: users + tokens | auth.rs UserStore / TokenStore |
Record | ✅ done (#12206) — UserBackend/TokenBackend traits + libsql/Turso impl |
| Grant table | install_accelerator/grant_table.rs |
Record | Trait + networked-SQLite impl |
| Public-packages | install_accelerator/public_packages.rs |
Record | Trait + networked-SQLite impl |
| Verdict cache | install_accelerator/verdict_cache.rs |
Record (pure cache) | Leave ephemeral, or externalize |
Blob side (cache + accelerator CAS)
Reuses pnpm/pnpm#12198. Two fs-isms to handle in the proxy cache:
- TTL freshness —
Store::read_fresh_packumentreads file mtime; the S3 variant usesObjectMeta.last_modified(object_store exposes it). tee_to_cache(streaming.rs) writes incrementally to a local file then renames. S3 can't append, so stage to local tmp and upload on stream completion (multipart for large tarballs) — same stage-then-upload shape the publish path already uses.
No new external service — cheapest large win.
Record side (auth + grants)
Narrow async traits, keeping current impls as defaults:
trait UserBackend { async fn get(..); async fn upsert_or_login(..); async fn count(); }
trait TokenBackend { async fn issue(..); async fn lookup(..); async fn list(..); async fn revoke(..); }
trait GrantBackend { async fn is_granted(..); async fn record(..); async fn clear_package(..); }Impls: InMemory, LocalSqlite (today, rusqlite), and a networked SQLite impl. Selected by config, built into Arc<dyn …> at load time. (Multiple impls behind dyn → async-trait.)
DB choice: SQLite-compatible, not Postgres
pnpr is already built on SQLite (rusqlite backs tokens, grants, public-packages, verdict cache), so the schemas and queries already exist. Standardizing on SQLite-compatible services keeps the SQL and makes an all-Cloudflare stack coherent: R2 (blobs) + D1 (records) + compute.
Important nuance: "SQLite" ≠ "rusqlite" once networked. rusqlite opens a local file; a networked SQLite service needs a different driver. Keep the SQL, swap the driver:
| Option | Reach it via | Works with current stack? |
|---|---|---|
| Cloudflare D1 | Workers binding, or REST API (SQL over HTTP) | REST API: yes (Cloud Run/Lambda). Workers binding: only inside a Worker. |
| Turso / libSQL | libsql crate (network + embedded replicas) |
Yes — any tokio runtime |
| LiteFS (Fly) | FUSE-replicated file, rusqlite unchanged, single writer |
Yes |
| rqlite | Raft + HTTP | Yes |
Caveats:
- D1 is happiest inside a Worker, and Workers can't run the current
tokio/axum/rusqlitestack (WASM rewrite). From Cloud Run/Lambda you'd use D1's REST API (per-query HTTP). - Auth/token lookup is on the hot path (≈ every request). A pure-HTTP-to-D1 backend taxes every call. Mitigate with a short-TTL in-process token cache or Turso embedded replicas (local-fast reads).
- Eventual consistency on replicas — fine for grants/public-packages (grant table is already best-effort, clear-on-discovery); the one to watch is token-revocation lag. A config knob (replica vs primary read for auth) covers it.
Recommendation: abstract behind the record-backend trait; default LocalSqlite. For the container-serverless target reachable today, Turso/libSQL is the pragmatic pick (works with the current stack; embedded replicas solve the hot-path auth read). D1 is the north-star for the Workers/edge path, gated on the larger stack rewrite.
Config shape (each block absent ⇒ local default)
storage: ./storage
s3: { bucket: pkgs, ... } # hosted blobs (done)
cache:
s3: { bucket: cache, ... } # proxy-cache blobs (phase 2)
accelerator:
store:
s3: { bucket: accel, ... } # accelerator CAS (phase 2)
backend:
libsql:
url: ${PNPR_LIBSQL_URL}
auth_token: ${PNPR_LIBSQL_TOKEN}
# or: d1: { account_id, database_id, api_token }Phased rollout
- Hosted → S3 — ✅ done (#12198).
- Proxy cache + accelerator CAS → S3 — reuses
object_store, no new external service. After this the only local state left is the SQLite record stores. Biggest bang, lowest risk — proposed next step. - Auth (users + tokens) → networked SQLite — ✅ done (#12206).
UserBackend/TokenBackendasync traits; local (htpasswd + SQLite) / in-memory / libsql/Turso impls selected by abackend.libsql:block. Embedded-replica read acceleration (replicaPath/syncIntervalSecs) for the hot-path token lookup; strict atomic registration cap. - Grants + public-packages → networked SQLite; leave verdict-cache ephemeral (pure cache, degrades to lower hit-rate).
- Deployment glue — Cloud Run needs ~a Dockerfile + readiness probe; Lambda needs
lambda_http+ response-streaming handling; Workers is a separate, larger effort.
Cross-cutting caveat (independent of where bytes live)
With N replicas, the read-modify-write flows are the real distributed-systems risk, not storage:
- Publish merges the incoming manifest into the existing packument (
publish.rs::merge_manifest); partial-unpublish rewrites it. Two replicas publishing the same package concurrently = last-write-wins on the packument object → a lost version. - Single-instance half ✅ done (#12206): a striped per-package lock serializes the read-modify-write packument flows (publish, dist-tag, partial-unpublish) on one instance. Cross-replica still pending: S3 conditional writes (
If-Match/ ETag) or a DB-level conditional update. pnpm clients usually serialize per package, but a shared registry shouldn't rely on that.
Also: keep cold-start cost down — the install accelerator is already lazily built via OnceLock; keep that laziness and use a small connection pool.
Written by an agent (Claude Code, claude-opus-4-8).
Activity
feat(pnpr): config-selectable networked-SQLite auth backend + per-pac…
feat(pnpr): config-selectable networked-SQLite auth backend (#12199 p…
zkochan commentedon Jun 5, 2026
Phase 3 (Auth → networked SQLite) landed in pnpm/pnpm#12206 (merged to
mainas70554b8).Delivered:
UserBackend/TokenBackendasync traits; record stores built once at startup intoArc<dyn …>handles. Three impls, config-selected: local (htpasswd + SQLite), in-memory, and networked libsql/Turso (LibsqlAuth) — both records in one shared DB so replicas see a consistent set of users + tokens. Selected via a top-levelbackend.libsql:block.replicaPath+syncIntervalSecs) so the hot-path token lookup reads a local synced file instead of a network round-trip; the interval bounds revocation lag.Remaining for a fully stateless multi-replica deployment:
object_store, no new service).If-Match/ETag CAS (the cross-replica half of the cross-cutting caveat).So the records side reachable today (R2 blobs + Turso auth + compute) works for auth + hosted blobs; phases 2/4 close the rest.
Written by an agent (Claude Code, claude-opus-4-8).
chore(git): merge main into clippy pedantic branch
style(pnpr): comply with clippy::pedantic in merged auth backend code
chore(rust/clippy): pedantic, nursery, and some (#12209)
zkochan commentedon Sep 6, 2026
One multi-replica race got smaller in pnpm/pnpm#14608, which is worth recording here since this issue owns the stateless-deployment story.
When several instances share one hosted store, two publishes of the same
name@versionwith different bytes race for the same immutable blob key. The loser used to answer201while the store served the winner's bytes. Every publish path now reports it: the version is left out of the registry document and the publisher gets409. That coversPUT /:pkg, the npm batch,-/stageapproval,cargo publish,twine upload, and the cross-ecosystem batch.This does not close the conditional-write half this issue tracks. A packument write still races on read-modify-write, and the fix there is still
If-Match/ETagon the document itself. What changed is that the blob half of the race is no longer silent.Written by an agent (Claude Code, claude-opus-5).
fix(pnpr): approve a staged publish once across replicas (#14665)
zkochan commentedon Sep 7, 2026
Status after pnpm/pnpm#14665, with a re-audit of the component table above — three of its rows have moved since it was written.
The cross-cutting caveat is closed
Every read-modify-write on the shared hosted store is now compare-and-set:
dist-tag, partial unpublish and journal roll-forward write underIf-Matchon the object's ETag and retry on top of the winner (fix(pnpr): prevent stale hosted packument writes pnpm#12832).pnpr/crates/pnpr/tests/multi_replica.rsnow drives two routers over one object store the way a load balancer spreads requests over two containers, and covers concurrent publishes of one package, cross-replica staging, double approval, and a rejection racing an approval.One window stays open by design: between an approval's claim recheck and its commit. It cannot be closed with an ownership token, because the staged record and the package document are two objects with no transaction between them. What is left is bounded — two approvals of one stage replay the same held bytes onto the same immutable blob slot. Closing it needs a lock with a fencing token in a record backend, which is the phase-4 track below.
Corrections to the component table
resolver/verdict_cache.rs, local SQLite, a pure cache).pnpr/docker/Dockerfile) and/-/pingis always served as a health check, so Cloud Run needs no new work. Lambda response streaming and Workers are still open.<cache>/pnpr-store, a pnpm store directory under the cache root — still local.What actually remains
pnpr-pipeline-runs) are filesystem-only, and unlike the caches they are not regenerable. Behind a load balancer a run posted to one replica is invisible from every other, so the pipeline UI shows a different history depending on which replica answers. They are append-only, so create-only object writes are enough. This is the one remaining item that changes what a user sees.ObjectMeta.last_modifiedon the object store) andtee_to_cachewrites-then-renames, which needs the stage-then-upload shape the publish path already uses.storagepath, so that path has to outlive its restarts. Documented in the pnpr README's new "Running several replicas" section.So "three replicas behind a load balancer" is a supported deployment now for the npm, Cargo, Python and OCI surfaces, given an S3-compatible store that honors
If-Match/If-None-Matchand a sharedbackend:database for accounts. The pipeline UI is the exception.Written by an agent (Claude Code, claude-opus-5).
feat(pnpr): keep pipeline run records with the hosted packages (#14668)
zkochan commentedon Sep 8, 2026
Phase 2 (proxy cache + accelerator CAS to S3): not worth doing as specified
Sized after pnpm/pnpm#14668. The phase reads as the cheapest win in the table above, but the numbers do not support that any more, so it should not be picked up as written.
It closes no gap. The proxy cache and the accelerator store are disposable. A replica that starts cold refetches from upstream and warms up; nothing is lost and nothing races. That is unlike the run records in pnpm/pnpm#14668, which were testimony a replica could not rebuild.
It would slow the install path. Nothing memoizes in front of the proxy cache: a proxied packument request reads it on every request. On local disk that read is around 0.1 ms; through an object store it is a 10-20 ms round trip, on every hit, during installs. Trading upstream fetches (TTL-bounded, occasional) for an object-store round trip per request is a bad trade for the surface pnpr exists to make fast.
The accelerator store is the wrong place for it.
<cache>/pnpr-storeis a pnpmStoreDirdriven by pacquet's fetcher, which the resolver walks per package while it resolves a lockfile. Putting an object store under it puts network latency inside that loop. Performance is the priority in the install accelerator, and this would spend it. It is also pacquet's store, not pnpr's, so the change does not belong on this side.What would pay, if anything here does. The tarball half of the proxy cache: large, immutable, fetched once, and worth sharing across replicas. That path currently hands callers an
fs::Fileso it can serveRangeandIf-Range, so it needs the range-serving rework first. Worth filing on its own merits rather than as "phase 2".And the shape that would make a shared cache safe for the hot path is two tiers — local disk in front of the shared bucket, with the shared tier consulted on a local miss. That is a real design with its own invalidation questions, not a backend swap.
Suggest striking the proxy-cache and accelerator-CAS rows from the phased rollout, and keeping the two-tier cache as a separate idea for whenever a deployment shape actually asks for it.
Written by an agent (Claude Code, claude-opus-5).
fix(pnpr): approve a staged publish once across replicas (pnpm#14665)
feat(pnpr): keep pipeline run records with the hosted packages (pnpm#…
zkochan commentedon Nov 7, 2026
Closing: what this issue tracks has shipped, been dropped, or been replaced by a newer design. State on
main(863382fa585):If-Matchon package documentspnpr gcfenced against in-flight commits (pnpm/pnpm#17717). Upload sessions and a few small records still use conditional object writes./-/pingcover Cloud Run. pnpr also runs on Cloudflare Containers behind a Worker (pnpr/docs/cloudflare.md). Lambda response streaming was never needed, so it isn't tracked.One idea from this thread could still be useful if a deployment asks for it: a two-tier tarball cache (local disk in front of a shared bucket) for the large, immutable half of the proxy cache. It needs the range-serving rework first, and it would be its own task.
Written by an agent (Claude Code, claude-opus-5-5).