13 KiB
Working in packages/backend/ (for agents)
packages/backend/ is the standalone server-side Rust workspace.
It uses packages/backend/Cargo.toml, resolver = "3", edition 2024, and its own Cargo.lock and rust-toolchain.toml.
It excludes native/ and server/ and does not join the root Cargo.toml workspace.
Crates
-
tools/frame-audit: shared frame snapshot schema (FrameSnapshot,DebugElementSnapshot) and audit engine (audit_frame_snapshot,rules::ALL). It depends onserdeonly.packages/ui/uidepends on it by path and re-exports it. Keep both workspaces' tests green when you change it. -
test-db-harness(librarytest_db_harness, binaryaffine-test-env): PostgreSQL and Redis harness for server tests.-
PostgreSQL:
AFFINE_TEST_PG_URLworks only when databasepostgrescarries the commentaffine-test-cluster. Otherwise the harness reuses or startsaffine-test-env-postgres-<digest>on a random loopback port with tmpfs storage.PgCluster::start_dockerstarts a private container and removes it on drop. -
Templates: the harness builds
affine_tpl_<digest>once per migration digest under an advisory lock and marks it read-only. Each test leasestest_<run>_<seq>viaCREATE DATABASE ... TEMPLATE. -
Leases: every clone stores a row in
postgres.public.test_db_leaseswith a secret owner token. Cloning, heartbeat, release, and reaping serialize per database on an advisory lock. The reaper checks expiry andpg_stat_activitybefore it drops a database withoutFORCE. -
Redis: tests use
AFFINE_TEST_REDIS_URLwith atest:<run>:prefix, or start a privateredis:7-alpinecontainer. -
Containers carry
affine.test.env=trueandaffine.test.shared=true|false, plusaffine.test.owner=<run id>on private containers.Container::remove_owned(id, owner)removes only a private container that matches that owner and full 64-hex id.AFFINE_TEST_CONTAINER_CLIselects a Docker-compatible CLI such aspodman. -
run.json:affine-test-env run-jsonwrites{ run_id, sha, lane, selected_targets, skipped_targets_with_reason, timings_ms, status }.
-
-
server-types(libraryserver_types): canonical domain types (DeploymentMode,ServerRole,LicenseTier,BillingSubject,Limits,Rights,AccessGrant,DomainError). It also holdslicense(LicenseEnvelopeV2P-256 verification,Keyring, bundleddefault-selfhost-10s-100g.license.json, anddefault_selfhost_access_grant()). -
server-db(libraryserver_db): singlePgPoolwithmin_connections = 0,statement_timeout,idle_in_transaction_session_timeout = '10s', andapplication_name = "affine:<channel>:<role>:v2". It exportsWorkloadTieradmission,with_long_query_timeout,dedicated_session_conn,with_query_scope,ensure_schema_ready,SessionRepository, andphase_a_compat::sessions::PhaseASessionRepository. -
server-spi(libraryserver_spi): SPI traits (QuotaGate,SessionPolicyHook,CopilotPolicySpi,CopilotRuntimeSpi,RateLimitPolicy,BillingSpi,DomainDispositionHandler,ServerExtension),RequestSource,CommunityRateLimitPolicy,CommunityBillingSpi,CommunityCopilotRuntime, andCommunityExtension. -
server-domain(libraryserver_domain): pure domain services (AuthService,UserService,WorkspaceService,AdminService,DocSharingService,DocHistoryService,CommentService,NotificationService,SelfhostLicenseService,AppConfigService,CalendarService,McpCredentialService,DefaultDomainDispositionHandler,safe_fetch, andacl) plusEventBusPublisher,InvalidationPublisher, andInvalidationHintV1.AuthServicehandles HS256 access tokens,aff_rt_v1refresh rotation, recovery, grace, preflight, login OAuth/OIDC preflight and callback (atomicruntime_statesclaim before lock-freesafe_fetchtoken exchange), single-transaction security challenges (runtime_states+mail_deliveries), session signing key rotation/deletion, PostgreSQL-backed Hashcash and Turnstile captcha verification, and session cleanup.AdminServiceaggregates admin workspace listings, dashboard metrics, shared links, and mail deliveries;UserServicehandles admin user CRUD, batch import, and recreate-for-ban transactions;AppConfigServiceserves redactedappConfigMetadata, dry-runvalidateAppConfig, and dynamic OAuth/Captcha capability flags.CalendarServicemanages Google Calendar OAuth (SessionRedisCALENDAR_OAUTH_STATE:<UUID>), CalDAV discovery/sync oversafe_fetch+xmlparser, 12B IV + 12B tag AES-256-GCM credential encryption, and pool-safe polling without holding PostgreSQL connections across external HTTP requests.McpCredentialServicemanagesaff_mcp_v1.<id>.<secret>workspace credentials with family-levelFOR UPDATErotation locking (24h grace), family-wide revocation, andy-octodocument read/write operations underworkspace-doc-updateadvisory locks.acldefines workspace and document permissions and classifies reserved documents.server-domainhas nolegacy_compat,phase_a_compat,axum, orasync-graphqldependencies. -
server-mail(libraryserver_mail): 30 compiledv0.27.5HTML email templates,SmtpMailer(lettre+rustls), andprocess_ready_mail_deliveries. The worker filters direct-render rows, releases unsupported leases cleanly, reaps expired rows, redacts PII in errors, and anonymizes terminal rows. -
server-blob(libraryserver_blob):BlobStorageBackend(LocalFsBlobStorage,S3BlobStorage,AssetpackBlobStorage),DynamicBlobStorage(ArcSwaphot reload with active multipart protection),BlobServiceoverpublic.blobs, multipart upload lifecycle (init_blob_upload,get_blob_upload_part_url,proxy_upload_object,proxy_upload_part,complete_blob_upload,abort_blob_upload), storage reconciliation (cleanup_expired_reservations,reconcile_storage_orphansviastorage_reconciliation_checkpoints), andrefs(y-octosource-scoped blob reference extraction and cursor-paginated readable manifests). Writes and deletes holdStorageObjectLocksession advisory locks outside thePgPooland never hold a database transaction during object storage I/O.list_blobs_authorized,delete_blob_authorized, andrelease_deleted_blobs_authorizedrequireOwneror commercial-grantAdminplus!users.disabledin one transaction.put_blobreserves underworkspaces ... FOR UPDATE, checksQuotaGate::resolve_workspace_grant, writes the object, and completes its reservation. Storage failures surface only asUnavailable("blob storage unavailable"). -
server-sync(libraryserver_sync): pure-Rust Engine.IO v4 / Socket.IO v4 sync gateway mounted at/socket.io/. It validates, merges, and diffsy-octoCRDTs over PostgreSQL underpg_advisory_xact_lock, delegates reserved-doc classification and doc-role resolution toserver_domain::acl, and serves realtime rooms (workspace.access,workspace.config,doc.share-state,doc.grants,comment.changed,comment.changes,user.settings,notification.count). WithSessionRedisactive, userspace writes holdMutexLock:userspace:<user_id>:<doc_id>across the PostgreSQL transaction and release it via Lua. Empty-table creates useON CONFLICT DO NOTHINGwith a merge fallback, and commits check theSessionRedislease fence. Unmodifiedv0.27.5instances skip pre-commit lock checks after a 60s stall, so patchcanaryseparately for legacy fencing. It isolateslegacy_compat::errorsand bridges Redisaffine:eventbus:v1and invalidation events. -
server-search(libraryserver_search): pure-Rust search runtime (embedded,elasticsearch, andmanticoresearch) with nonapioraffine_doc_loaderdependency. It extracts document titles, blocks, and canvas elements directly withy-octo. It renews the 90ssearch_projection_lockless_v2lease every 15s and serializes generations onsearch-projection-lifecyclewith anxid8fence. It fences orphan GC per workspace onsearch-projection-ws:<workspace_id>. -
server-http(libraryserver_http):axum 0.8andasync-graphql 7transport layer with/healthz,/readyz,/info, and/graphql(including workspacesearch,aggregate,searchDocs,workspaceRolePermissions,DocType.{analytics, lastAccessedMembers}, multipart blob upload mutationscreateBlobUpload,completeBlobUpload,abortBlobUpload,WorkspaceType.blobUploadPartUrl, admin console user, workspace, dashboard, shared-link, mail-delivery, and app-config metadata/validation queries and mutations, auth security challenges, signing key rotation,UserType.token, andQuery.error). Auth REST routes cover cookie/bearer sign-in (with@UseNamedGuard('captcha')),GET /api/auth/captcha, login OAuth (POST /api/oauth/preflightwith version guard,POST /api/oauth/callbackwithout version guard), Open-App (/api/auth/open-app/sign-in-code,/api/auth/open-app/sign-in), and native sessions (/api/auth/session/exchange,/api/auth/session/refresh,/api/auth/session/revoke,/api/auth/sessions,/api/auth/sessions/revoke-all,/api/auth/sessions/:id). Storage REST routes cover avatars (/api/avatars/:id), public docs (/api/workspaces/:id/public-docs/:docId,/root-doc), doc histories (/api/workspaces/:id/docs/:guid/histories/:timestamp), comment attachments (/api/workspaces/:id/docs/:docId/comment-attachments/:key), source-scoped blobs (/api/workspaces/:id/blobs/v1/:name,blob-manifest/v1,readable-blob-manifest/v1, doc snapshot read), and HMAC-signed upload proxy routes (PUT /api/storage/upload,PUT /api/storage/multipart). Calendar and Workspace MCP routes cover/api/calendar/oauth/{preflight,callback},/api/calendar/webhook/google,/api/workspaces/:id/mcp(stateless JSON-RPC 2.0), and their corresponding GraphQL resolvers. Web and helper routes cover self-hosted worker proxy (OPTIONS/GET /api/worker/image-proxy,OPTIONS/POST /api/worker/link-previewviasafe_fetchwith strict CORS origin allowlisting, bounded media caps, andencoding_rsdecoding),doc_renderer(GET /workspace/{*path}for MarkdownDoc.Readauthz and HTML OG metadata withX-Robots-Tag: noindex), static web andcanarymobile shell hosting (?shell=,affine_shellcookie,302/index.htmlredirects,ETag/304/HEAD, strict 404 on/wasm/and asset prefixes,sign-in.htmlpriority), and telemetry collection (OPTIONS/POST /api/telemetry/collectwith cleaner rules, SHA-256 in-memory dedupe, and optional GA4 forwarding). Blob management mutations requireOwneror commercial-grantAdmin.legacy_compat::{quota, errors}isolates external GraphQL quota labels and Apollo error extensions. -
server-worker(libraryserver_worker):SessionRedis-compatible mutex (MutexLock:<key>with atomic Lua lock, renew, fence, and release using millisecondPXTTL),v2:keyspace helper,CancellationToken,run_with_distributed_lock,spawn_locked_periodic_task,WorkerSupervisor, andmaintenanceperiodic background workers (workspace lifecycle migrations, notification expiry, mail disabled-recipient skip and anonymization,runtime_states/runtime_gates/runtime_leasescleanup, and workspace admin stats refresh and recalibration). -
affine-server: single-binary multi-role CLI (--role front|graphql|worker|script|allinone,SERVER_FLAVOR,--static-dir,--port 0,ensure_schema_ready(),spawn_mail_delivery_worker, expired-session cleanup worker, periodic maintenance workers, avatar storage,/socket.io/). It exportsbuild_server,serve_with_extension,serve_with_extension_and_init, andbuild_app_and_servefor anyArc<dyn ServerExtension>.
Pin both test images to multi-arch index digests in test-db-harness/src/pg.rs, test-db-harness/src/redis.rs, .github/workflows/native-playground.yml, and scripts/ci/check-l0-tier-a.mjs.
Change all four places together.
Rules
-
Server-domain crates (
packages/backend/server-domain*) never depend onlegacy_compat,phase_a_compat,axum, orasync-graphql. Nothing inpackages/backend/carries private keys, prompt assets, or private-edition table references (scripts/ci/check-l0-tier-a.mjs). -
Tests use real services.
cargo testrequires Docker (orAFFINE_TEST_CONTAINER_CLI) or bothAFFINE_TEST_*_URLvariables, and never skips silently. Tests share one cluster and run in parallel, so each asserts on its own databases only.
Verification
Run inside packages/backend/ with the root NAPI link flags cleared:
export CARGO_ENCODED_RUSTFLAGS=""
node ../../scripts/ci/check-l0-tier-a.mjs
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
After you change tools/frame-audit, also run cargo test --locked -p ui --features harness in packages/frontend.