refactor(server): move server crates under packages/backend and upgrade y-octo to 0.4.0

Move the server Rust workspace directly under packages/backend.
Exclude native and server from that workspace.
Move frame-audit to tools/frame-audit as a standalone crate.
Isolate packages/backend/native under the root workspace.
Upgrade y-octo to 0.4.0 in native-playground and remove the old removal workarounds.
Update CI workflows, static gates, and docs for the new paths.
This commit is contained in:
DarkSky committed 2026-11-23 15:12:26 +09:00
1 parent ec1093007c
commit b375374c7f
63 files changed
+128 -180

No files matched your search

+13 -8
View File
@@ -100,7 +100,7 @@ jobs:
name: L0 Tier A, Server Contracts & Test Harness
runs-on: ubuntu-24.04
env:
# One installed toolchain for crates/ and tools/parity-harness alike.
# One installed toolchain for packages/backend/ and tools/parity-harness alike.
RUSTUP_TOOLCHAIN: '1.98.1'
steps:
- name: Checkout repository
@@ -130,7 +130,8 @@ jobs:
uses: Swatinem/rust-cache@v2
with:
workspaces: |
crates -> target
packages/backend -> target
tools/frame-audit -> target
tools/parity-harness -> target
key: server-harness
@@ -140,10 +141,10 @@ jobs:
docker pull -q docker.io/library/redis:7-alpine@sha256:7f7d30b7fdd09467bac58198a1f166dd69789d348d4fe859cccb20e0cf287fbe &
wait
- name: Format, clippy and test crates/ (real PostgreSQL and Redis) and the parity harness
working-directory: crates
- name: Format, clippy and test packages/backend/ (real PostgreSQL and Redis) and the parity harness
working-directory: packages/backend
run: |
mkdir -p ../.artifacts/server-harness
mkdir -p ../../.artifacts/server-harness
status=passed
timings=()
step() {
@@ -157,17 +158,21 @@ jobs:
step fmt cargo fmt --all -- --check
step clippy cargo clippy --locked --workspace --all-targets -- -D warnings
step test cargo test --locked --workspace
parity=(--manifest-path ../tools/parity-harness/Cargo.toml)
audit=(--manifest-path ../../tools/frame-audit/Cargo.toml)
step audit-fmt cargo fmt "${audit[@]}" --all -- --check
step audit-clippy cargo clippy --locked "${audit[@]}" --workspace --all-targets -- -D warnings
step audit-test cargo test --locked "${audit[@]}" --workspace
parity=(--manifest-path ../../tools/parity-harness/Cargo.toml)
step parity-fmt cargo fmt "${parity[@]}" --all -- --check
step parity-clippy cargo clippy --locked "${parity[@]}" --workspace --all-targets -- -D warnings
step parity-test cargo test --locked "${parity[@]}" --workspace
cargo run --locked --quiet -p test-db-harness --bin affine-test-env -- \
run-json --out ../.artifacts/server-harness/run.json --lane server-harness --status "$status" \
run-json --out ../../.artifacts/server-harness/run.json --lane server-harness --status "$status" \
--sha "${{ github.sha }}" --run-id "${{ github.run_id }}-${{ github.run_attempt }}" \
--select frame-audit --select test-db-harness --select parity-harness \
--select server-types --select server-db --select server-spi \
--select server-http --select server-worker --select affine-server "${timings[@]}"
cat ../.artifacts/server-harness/run.json
cat ../../.artifacts/server-harness/run.json
test "$status" = passed
- name: Upload run report
+1 -1
View File
@@ -40,7 +40,7 @@ packages/frontend/apps/android/App/**
packages/frontend/apps/ios/App/**
tests/blocksuite/snapshots
tests/oracle-contracts/**
crates/server-types/assets/*.license.json
packages/backend/server-types/assets/*.license.json
blocksuite/native-playground/**
blocksuite/docs/api/**
blocksuite/docs-site/.vitepress/.temp/**
+2 -2
View File
@@ -8,8 +8,8 @@ These rules apply at repository root on the `darksky/native-playground` branch a
- **PR-less CI on push:** Push topic branches matching `darksky/np/**` (or `darksky/native-playground`) to trigger `.github/workflows/native-playground.yml` directly. `.github/workflows/build-test.yml` ignores `darksky/native-playground` pull requests so unrelated legacy jobs stay silent.
- **Review council gate:** Every topic branch requires at least **3 of 4** review council approvals before squash-landing onto `darksky/native-playground`.
- **Performance regression gate:** Any CI benchmark metric regressing by **more than 10%** against the rolling `N-3` baseline is routed to the dedicated performance guardian before landing.
- **Cargo rustflags isolation:** Root `.cargo/config.toml` injects NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`) that Cargo concatenates into nested workspaces. Always build and test `blocksuite/native-playground` and the standalone `crates/` workspace with `CARGO_ENCODED_RUSTFLAGS=""` in the environment.
- **Static gates and fast lanes:** `node scripts/ci/check-l0-tier-a.mjs` (no dependencies, under a second) guards `crates/` layering and hygiene, the `waitForTimeout` / `.skip` ratchet in `scripts/ci/l0-ratchet.json` (counts may only go down; lower the ceiling with `--update-baseline`), and workflow references. `native-playground.yml` always runs it with the frozen server contract checks (`scripts/oracle`), the `crates/` checks and the `tools/parity-harness` checks, and calls `np-web-fast.yml` (lint, typecheck, Node-only Vitest projects) only when web sources change and `np-web-build.yml` (production bundles of `@affine/web`, `@affine/mobile` and `@affine/admin`, no Electron/Playwright downloads, eight minutes per bundle) only when frontend sources change.
- **Cargo rustflags isolation:** Root `.cargo/config.toml` injects NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`) that Cargo concatenates into nested workspaces. Always build and test `blocksuite/native-playground`, `packages/backend`, `tools/frame-audit`, and `tools/parity-harness` with `CARGO_ENCODED_RUSTFLAGS=""` in the environment.
- **Static gates and fast lanes:** `node scripts/ci/check-l0-tier-a.mjs` (no dependencies, under a second) guards `packages/backend/` layering and hygiene, the `waitForTimeout` / `.skip` ratchet in `scripts/ci/l0-ratchet.json` (counts may only go down, lower the ceiling with `--update-baseline`), and workflow references. `native-playground.yml` runs it with the frozen server contract checks (`scripts/oracle`), the `packages/backend/` checks, and the `tools/parity-harness` checks. It calls `np-web-fast.yml` (lint, typecheck, Node-only Vitest projects) when web sources change, and `np-web-build.yml` (production bundles of `@affine/web`, `@affine/mobile`, and `@affine/admin`, no Electron/Playwright downloads) when frontend sources change.
## Engineering & testing principles
+2 -2
View File
@@ -6,7 +6,7 @@ This document records the active engineering invariants enforced in CI today alo
### Workspace boundaries
- `crates/ui`: Single fused internal GPU UI library (vendored once without upstream sync hooks, zero internal `proc-macro = true` crates, zero external UI-kit dependencies). It knows **nothing** about BlockSuite or AFFiNE (`scripts/check-invariants.sh` rejects `blocksuite` and `affine` inside `crates/ui`) and embeds zero fonts (fonts are registered by the application via `cx.text_system().add_fonts(...)`).
- `crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies — `scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `crates/doc/Cargo.toml`) built on `y-octo 0.3.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:<docId>`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour, keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it. When removing blocks or surface elements, `clear_value_canonically` clears nested `Map`/`Array`/`Text` entries leaf-first before `map_remove` so `y-octo 0.3.0`'s `DeleteSet::batch_add_ranges` never inserts unsorted `AHashMap` clock ranges into a vacant `OrderRange::Fragment`.
- `crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies, `scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `crates/doc/Cargo.toml`) built on `y-octo 0.4.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:<docId>`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour, keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it.
- `crates/playground`: Application layer owning the shipping `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), the tracked repository font registration (`Inter` and the four `IBM Plex Mono` faces), the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). `theme.rs` resolves colors, typography and icons from the generated `tokens/tokens.rs` / `tokens/icons.rs` (pulled in with `include!`, never copied and never reformatted) for `PlaygroundTheme::{Light, Dark}`; `block_flow/` is the Page-mode renderer; `rich_text/` is the rich paragraph engine; `editor_session/` and `clipboard/` are the page editor; `overlays/` holds the popovers and the interactive block controls; `room_client/` is live room sync; `showcase.rs` seeds the deterministic `seed_showcase_doc` workspace shown without a room (every Page-mode block, one image blob, one remote collaborator).
- `unexpected_cfgs = "deny"` is enforced workspace-wide in `Cargo.toml`; dead upstream feature gates are forbidden.
@@ -22,7 +22,7 @@ This document records the active engineering invariants enforced in CI today alo
- **Motion is pure data**: Transitions are declared once as `(from, to, curve, start_ms, duration_ms)` and evaluated as a pure function of scheduler time. Never write frame-by-frame recurrence loops or `sleep` waits.
- **Zero tester branches**: Application and layout logic never inspect `is_headless` or inline `#[cfg(any(test, feature = "harness"))]` to alter behavior (`scripts/check-invariants.sh`).
- **Four-rate replay invariance**: Stepped `PlaygroundView` transitions (the mode switch, the slash menu and the formatting toolbar opening and closing) must progress monotonically with in-flight frames and produce byte-identical terminal `FrameSnapshot` JSON at `60`, `120`, `24`, and `7` fps (`bs-harness fps-check`).
- **Callsite tracing**: Under the `harness` feature, `InteractiveElement::snapshot(...)` records post-layout bounds, `content_mask`, interactivity, focus, and `#[track_caller]` `file:line` origins into `Window::frame_snapshot()` for `sources_at(x, y)` and `bs-harness audit`. The snapshot schema and the audit rules are the repository's `crates/frame-audit` (a `serde`-only path dependency of `crates/ui`, re-exported from `ui::harness`); change them there and keep both workspaces' tests green. Non-harness release builds compile to no-op stubs.
- **Callsite tracing**: Under the `harness` feature, `InteractiveElement::snapshot(...)` records post-layout bounds, `content_mask`, interactivity, focus, and `#[track_caller]` `file:line` origins into `Window::frame_snapshot()` for `sources_at(x, y)` and `bs-harness audit`. The snapshot schema and the audit rules are the repository's `tools/frame-audit` (a `serde`-only path dependency of `crates/ui`, re-exported from `ui::harness`). Change them there and keep both workspaces' tests green. Non-harness release builds compile to no-op stubs.
- **Locked builds & rustflags isolation**: `Cargo.lock` is committed and CI runs with `--locked` and `CARGO_ENCODED_RUSTFLAGS=""` (`scripts/check-invariants.sh` verifies fresh `cargo rustc --print link-args` contains zero leaked root NAPI flags).
### Page rendering and room sync
+1 -1
View File
@@ -35,7 +35,7 @@ etagere = "0.2"
flume = { version = "0.12", default-features = false, features = ["async"] }
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", default-features = false }
foreign-types = "0.5"
frame-audit = { path = "../../crates/frame-audit" }
frame-audit = { path = "../../tools/frame-audit" }
futures = "0.3.34"
getrandom = { version = "0.3.4", features = ["wasm_js"] }
heapless = "0.9.2"
@@ -23,7 +23,7 @@ server = [
serde.workspace = true
serde_json = { workspace = true, features = ["float_roundtrip"] }
thiserror.workspace = true
y-octo = { version = "0.3.0", default-features = false, features = ["session"] }
y-octo = { version = "0.4.0", default-features = false, features = ["session"] }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
axum = { version = "0.8", features = ["ws"], optional = true }
@@ -255,40 +255,6 @@ impl PageDocSession {
}
}
/// Recursively clear all children of a Yjs container leaf-first so every underlying
/// `store.delete_item` deletes a single item (`ranges.len() == 1`), keeping
/// `DeleteSet` ranges sorted regardless of map iteration order.
pub(super) fn clear_value_canonically(&mut self, value: SessionReadValue) -> DocResult<()> {
match value {
SessionReadValue::Map(ident) => {
let target = TypeTarget::Identity(ident);
let mut entries = self.session.read_map(&target)?;
entries.sort_by(|a, b| a.0.cmp(&b.0));
for (k, v) in entries {
self.clear_value_canonically(v)?;
self.session.map_remove(&target, &k)?;
}
}
SessionReadValue::Array(ident) => {
let target = TypeTarget::Identity(ident);
let items = self.session.read_array(&target)?;
for (idx, v) in items.into_iter().enumerate().rev() {
self.clear_value_canonically(v)?;
self.session.array_remove(&target, idx as u64, 1)?;
}
}
SessionReadValue::Text(ident) => {
let target = TypeTarget::Identity(ident);
let len = self.session.read_text_len(&target)?;
if len > 0 {
self.session.text_remove(&target, 0, len)?;
}
}
_ => {}
}
Ok(())
}
pub fn guid(&self) -> &str {
self.session.guid()
}
@@ -56,14 +56,6 @@ impl PageDocSession {
Ok(commit?)
}
fn remove_block_canonically(&mut self, id: &str) -> DocResult<()> {
if let Some(val) = self.session.get_map_value(&self.blocks_target, id)? {
self.clear_value_canonically(val)?;
}
self.session.map_remove(&self.blocks_target, id)?;
Ok(())
}
pub fn delete_block_subtree(
&mut self,
parent_id: &str,
@@ -88,7 +80,7 @@ impl PageDocSession {
page.session
.array_remove(&children_target(parent_id), index, 1)?;
for id in candidates.difference(&retained) {
page.remove_block_canonically(id)?;
page.session.map_remove(&page.blocks_target, id)?;
}
Ok(())
})
@@ -202,7 +194,7 @@ impl PageDocSession {
child_values(&children),
)?;
}
page.remove_block_canonically(id)?;
page.session.map_remove(&page.blocks_target, id)?;
Ok(())
})
}
@@ -476,7 +468,7 @@ impl PageDocSession {
}
}
for id in ids {
page.remove_block_canonically(&id)?;
page.session.map_remove(&page.blocks_target, &id)?;
}
Ok(())
})
@@ -583,7 +575,7 @@ impl PageDocSession {
}
page.session
.array_remove(&children_target(&parent), slot + 1, 1)?;
page.remove_block_canonically(id)?;
page.session.map_remove(&page.blocks_target, id)?;
if !old.children.is_empty() {
if accepts_children {
page.session.array_push(
@@ -107,36 +107,16 @@ impl PageDocSession {
element_id: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.advance_time(now_ms);
let elements_value_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value"),
);
let element_id = element_id.to_string();
if self.session.tx_depth() == 0 {
return self.structural_edit(now_ms, move |page| {
if let Some(val) = page
.session
.get_map_value(&elements_value_target, &element_id)?
{
page.clear_value_canonically(val)?;
}
page.session
.map_remove(&elements_value_target, &element_id)?;
Ok(())
});
}
self.advance_time(now_ms);
if let Some(val) = self
.session
.get_map_value(&elements_value_target, &element_id)?
{
self.clear_value_canonically(val)?;
}
Ok(self
.session
.map_remove(&elements_value_target, &element_id)?)
.map_remove(&elements_value_target, element_id)?)
}
/// Update multiple fields on an existing surface element in one tracked transaction.
@@ -462,9 +442,6 @@ impl PageDocSession {
if trimmed_text.is_empty() {
return self.structural_edit(now_ms, move |page| {
for key in ["text", "labelXYWH", "labelOffset"] {
if let Some(val) = page.session.get_map_value(&elem_target, key)? {
page.clear_value_canonically(val)?;
}
let _ = page.session.map_remove(&elem_target, key);
}
Ok(())
@@ -35,7 +35,7 @@ ui = { path = "../ui" }
unicode-bidi.workspace = true
unicode-linebreak = "0.1"
unicode-segmentation.workspace = true
y-octo = { version = "0.3.0", default-features = false, features = ["session"] }
y-octo = { version = "0.4.0", default-features = false, features = ["session"] }
[dev-dependencies]
tempfile = "3"
@@ -2,7 +2,7 @@
//! structural UI audit primitives.
//!
//! The snapshot schema and the audit rules live in the renderer-independent
//! `frame-audit` crate (repository `crates/frame-audit`) and are re-exported
//! `frame-audit` crate (repository `tools/frame-audit`) and are re-exported
//! here. Full snapshot collection and auditing are active under
//! `#[cfg(any(test, feature = "harness"))]`; non-harness release builds compile
//! down to zero-cost no-op stubs so layout and view code never need inline
-41
View File
@@ -1,41 +0,0 @@
# Working in `crates/` (for agents)
`crates/` is the standalone server-side Rust workspace (`crates/Cargo.toml`, `resolver = "3"`, edition 2024, its own `Cargo.lock` and `rust-toolchain.toml`). It never joins the root `Cargo.toml` workspace, so server and test infrastructure build without the desktop and N-API media dependencies.
## Crates
- `frame-audit`: the one frame snapshot schema (`FrameSnapshot` of `DebugElementSnapshot`s with bounds, `content_mask`, opacity, interactivity, radii, `#[track_caller]` callsites, and optional evidence: roles, cursors, text metrics, baseline groups, footer slots, renderer hit-test probes) and its audit engine (`audit_frame_snapshot`, rule ids in `rules::ALL`). Depends on `serde` only. `blocksuite/native-playground/crates/ui` depends on it by path and re-exports it, so the native renderer, headless harnesses and server tooling share one schema; change it with both workspaces' tests green. Evidence rules run only on elements that opt in, and an opted-in element without the evidence its rule needs is a violation. Every rule keeps a failing case in the table in `src/tests.rs`, and snapshots without the evidence fields still load.
- `test-db-harness` (library `test_db_harness`, binary `affine-test-env`): PostgreSQL and Redis for server tests.
- PostgreSQL: an explicit `AFFINE_TEST_PG_URL` is used only when database `postgres` carries the comment `affine-test-cluster`, and every maintenance connection re-checks it before doing anything. Otherwise the machine-wide container `affine-test-env-postgres-<digest>` is reused or started (loopback random port, tmpfs data, `fsync`/`synchronous_commit`/`full_page_writes` off) and marked; it outlives the process for later runs. `PgCluster::start_docker` gives a private container removed on drop.
- Templates: `affine_tpl_<digest>` is built once per migration digest under an advisory lock, records the applied migrations in `_prisma_migrations`, and is left read-only (`IS_TEMPLATE`, `ALLOW_CONNECTIONS false`). Each test gets `test_<run>_<seq>` via `CREATE DATABASE ... TEMPLATE`.
- Leases: every clone has a row in `postgres.public.test_db_leases` with a secret owner token; heartbeat and release need the token. Cloning, heartbeat, release and the reaper serialize per database on an advisory lock (the lease row, the clone and its TTL start are made under it), and the reaper re-checks expiry and `pg_stat_activity` under it before dropping (without `FORCE`), so a database being cloned, renewed or used is never dropped. `PgCluster` and `DbLease` alike reach the cluster only through a maintenance connection that re-checks the marker.
- Redis: an explicit `AFFINE_TEST_REDIS_URL` isolated by the `test:<run>:` key prefix, or a private `redis:7-alpine` container.
- Containers carry `affine.test.env=true` and `affine.test.shared=true|false`; private ones also `affine.test.owner=<run id>`. `Container::remove_owned(id, owner)` (used by drop, and by `affine-test-env down` with the `AFFINE_TEST_OWNER` that `up` wrote) removes only a container labeled `affine.test.shared=false` and owned by that non-empty run, named by its full 64-hex id; names, prefixes, unlabeled, foreign, unmarked and shared containers are refused. Concurrent `ensure_shared` callers converge on one container: losers of the name race wait (short backoff, 60 s from their own first lookup or start, so an image pull is not counted) until it runs; a stopped leftover of ours is removed without force and replaced, and a paused or unknown-state one is kept and reported. A Docker-compatible CLI such as `podman` can be named in `AFFINE_TEST_CONTAINER_CLI`.
- `run.json`: `{ run_id, sha, lane, selected_targets, skipped_targets_with_reason, timings_ms, status }`, written by `affine-test-env run-json`.
- `server-types` (library `server_types`): pure canonical domain types (`DeploymentMode`, `ServerRole`, `LicenseTier`, `Limits`, `Rights`, `AccessGrant`, `DomainError`) and `license` (`LicenseEnvelopeV2` ECDSA P-256 verification, `Keyring` with `community-default-v1` privilege separation and `pro-v1`, bundled `default-selfhost-10s-100g.license.json`, and fail-closed `OnceLock`-cached `default_selfhost_access_grant()`). Zero transport frameworks or legacy naming aliases.
- `server-db` (library `server_db`): single `PgPool` (`min_connections = 0`, `after_connect` setting `statement_timeout`, `idle_in_transaction_session_timeout = '10s'`, `application_name = "affine:<channel>:<role>:v2"`), 4-tier bounded `Semaphore` admission (`WorkloadTier`), `with_long_query_timeout` (`SET LOCAL statement_timeout`), `dedicated_session_conn`, task-local `with_query_scope` counters, dual-track `ensure_schema_ready` (fresh-DB bundled `v0.27.5` baseline + `_prisma_migrations` seeding + `schema_baseline_0275` checkpoint; existing-DB `v0.27.5` stepping-stone gate without mutating `_prisma_migrations`), and isolated `phase_a_compat` SQL helpers.
- `server-spi` (library `server_spi`): pure canonical SPI traits (`QuotaGate`, `SessionPolicyHook` borrowing `&mut sqlx::Transaction<'_, Postgres>`, `CopilotPolicySpi`, `ServerExtension`) and the default `CommunityExtension` (10-seat / 100 GiB bundled self-host grant, fail-closed on 0-seat readonly).
- `server-http` (library `server_http`): `axum 0.8` + `async-graphql 7` transport skeleton (`Arc<AppState>` + `ArcSwap<RuntimeConfig>`, role-isolated `/healthz`, `/readyz` with 2 s PG/Redis probe timeouts, `v0.27.5` `/info`, `/graphql` with `workspace(id)` -> `WorkspaceType`), plus `legacy_compat::{quota, errors}` isolating all `v0.27.5` GraphQL quota labels and Apollo error extensions at the edge.
- `server-worker` (library `server_worker`): `SessionRedis`-compatible distributed mutex (`MutexLock:<key>` via `SET NX EX` + atomic Lua renew/unlock), `v2:` private keyspace helper, `CancellationToken`, and `WorkerSupervisor` graceful lease drain.
- `affine-server`: single-binary multi-role CLI (`--role front|graphql|worker|script|allinone`, `--port 0`, default `ensure_schema_ready()` startup gate with `--skip-schema-check`) and reusable library entrypoints (`build_server`, `serve_with_extension`, `build_app_and_serve`) accepting any `Arc<dyn ServerExtension>`.
Both images are fully qualified and pinned to multi-arch index digests in `src/pg.rs` / `src/redis.rs`, in `.github/workflows/native-playground.yml`, and in `scripts/ci/check-l0-tier-a.mjs`, which fails when they differ; change all three together.
## Rules
- Server-domain crates (`crates/server-domain*`) never depend on `legacy_compat`, `phase_a_compat`, `axum` or `async-graphql`, and nothing in `crates/` carries private keys, prompt assets or private-edition table references (`scripts/ci/check-l0-tier-a.mjs`).
- Tests use real services: `cargo test` needs Docker (or `AFFINE_TEST_CONTAINER_CLI`) or the two `AFFINE_TEST_*_URL` variables, and never skips silently. Tests share one cluster and run in parallel, so each asserts on its own databases only.
## Verification
Run inside `crates/` (its `rust-toolchain.toml` applies there) with the root NAPI link flags cleared:
```sh
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 changing `frame-audit`, also run `cargo test --locked -p ui --features harness` in `blocksuite/native-playground`.
-15
View File
@@ -1,15 +0,0 @@
[package]
description = "Renderer-independent geometry and interaction audit rules over serialized UI frame snapshots"
edition.workspace = true
license.workspace = true
name = "frame-audit"
publish.workspace = true
rust-version.workspace = true
version = "0.1.0"
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
[lints]
workspace = true
+41
View File
@@ -0,0 +1,41 @@
# Working in `packages/backend/` (for agents)
`packages/backend/` is the standalone server-side Rust workspace (`packages/backend/Cargo.toml`, `resolver = "3"`, edition 2024, with its own `Cargo.lock` and `rust-toolchain.toml`, excluding legacy `native/` and `server/`). It does not join the root `Cargo.toml` workspace, so server and test infrastructure build without desktop and N-API dependencies.
## Crates
- `tools/frame-audit`: shared frame snapshot schema (`FrameSnapshot` of `DebugElementSnapshot` with bounds, `content_mask`, opacity, interactivity, radii, `#[track_caller]` callsites, and optional evidence fields) and audit engine (`audit_frame_snapshot`, rule ids in `rules::ALL`). Depends on `serde` only. `blocksuite/native-playground/crates/ui` depends on it by path and re-exports it. Keep both workspaces' tests green when changing it.
- `test-db-harness` (library `test_db_harness`, binary `affine-test-env`): PostgreSQL and Redis harness for server tests.
- PostgreSQL: an explicit `AFFINE_TEST_PG_URL` is used only when database `postgres` carries the comment `affine-test-cluster`, and maintenance connections verify that marker before running. Otherwise the shared container `affine-test-env-postgres-<digest>` is reused or started on a random loopback port with tmpfs storage and marked. `PgCluster::start_docker` starts a private container removed on drop.
- Templates: `affine_tpl_<digest>` is built once per migration digest under an advisory lock, records applied migrations in `_prisma_migrations`, and is left read-only (`IS_TEMPLATE`, `ALLOW_CONNECTIONS false`). Each test gets `test_<run>_<seq>` via `CREATE DATABASE ... TEMPLATE`.
- Leases: every clone has a row in `postgres.public.test_db_leases` with a secret owner token required for heartbeat and release. Cloning, heartbeat, release, and reaping serialize per database on an advisory lock, and the reaper verifies expiry and `pg_stat_activity` before dropping without `FORCE`.
- Redis: uses `AFFINE_TEST_REDIS_URL` isolated by the `test:<run>:` key prefix, or a private `redis:7-alpine` container.
- Containers carry `affine.test.env=true` and `affine.test.shared=true|false`. Private containers also carry `affine.test.owner=<run id>`. `Container::remove_owned(id, owner)` removes only a private container owned by that run by its full 64-hex id. Concurrent `ensure_shared` callers converge on one container. `AFFINE_TEST_CONTAINER_CLI` can select a Docker-compatible CLI such as `podman`.
- `run.json`: `{ run_id, sha, lane, selected_targets, skipped_targets_with_reason, timings_ms, status }`, written by `affine-test-env run-json`.
- `server-types` (library `server_types`): canonical domain types (`DeploymentMode`, `ServerRole`, `LicenseTier`, `Limits`, `Rights`, `AccessGrant`, `DomainError`) and `license` (`LicenseEnvelopeV2` ECDSA P-256 verification, `Keyring` with `community-default-v1` and `pro-v1`, bundled `default-selfhost-10s-100g.license.json`, and fail-closed `OnceLock`-cached `default_selfhost_access_grant()`). No transport frameworks or legacy naming aliases.
- `server-db` (library `server_db`): single `PgPool` (`min_connections = 0`, `after_connect` setting `statement_timeout`, `idle_in_transaction_session_timeout = '10s'`, `application_name = "affine:<channel>:<role>:v2"`), 4-tier bounded `Semaphore` admission (`WorkloadTier`), `with_long_query_timeout`, `dedicated_session_conn`, task-local `with_query_scope` counters, `ensure_schema_ready` (fresh-DB bundled `v0.27.5` baseline seeding or existing-DB baseline verification without mutating `_prisma_migrations`), and isolated `phase_a_compat` compatibility storage adapters.
- `server-spi` (library `server_spi`): canonical SPI traits (`QuotaGate`, `SessionPolicyHook` borrowing `&mut sqlx::Transaction<'_, Postgres>`, `CopilotPolicySpi`, `ServerExtension`) and the default `CommunityExtension` (10-seat / 100 GiB bundled self-host grant, fail-closed on 0-seat readonly).
- `server-http` (library `server_http`): `axum 0.8` and `async-graphql 7` transport layer (`Arc<AppState>` and `ArcSwap<RuntimeConfig>`, role-isolated `/healthz`, `/readyz` with 2 s PG/Redis probe timeouts, `/info`, `/graphql` with `workspace(id)` -> `WorkspaceType`), plus `legacy_compat::{quota, errors}` isolating external GraphQL quota labels and Apollo error extensions at the edge.
- `server-worker` (library `server_worker`): `SessionRedis`-compatible distributed mutex (`MutexLock:<key>` via `SET NX EX` and atomic Lua renew/unlock), `v2:` private keyspace helper, `CancellationToken`, and `WorkerSupervisor` graceful lease drain.
- `affine-server`: single-binary multi-role CLI (`--role front|graphql|worker|script|allinone`, `--port 0`, default `ensure_schema_ready()` startup gate with `--skip-schema-check`) and reusable library entrypoints (`build_server`, `serve_with_extension`, `build_app_and_serve`) accepting any `Arc<dyn ServerExtension>`.
Both test images are pinned to multi-arch index digests in `test-db-harness/src/pg.rs` and `test-db-harness/src/redis.rs`, in `.github/workflows/native-playground.yml`, and in `scripts/ci/check-l0-tier-a.mjs`. Change all three together.
## Rules
- Server-domain crates (`packages/backend/server-domain*`) never depend on `legacy_compat`, `phase_a_compat`, `axum`, or `async-graphql`. Nothing in `packages/backend/` carries private keys, prompt assets, or private-edition table references (`scripts/ci/check-l0-tier-a.mjs`).
- Tests use real services. `cargo test` requires Docker (or `AFFINE_TEST_CONTAINER_CLI`) or both `AFFINE_TEST_*_URL` variables, 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/` (its `rust-toolchain.toml` applies there) with the root NAPI link flags cleared:
```sh
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 changing `tools/frame-audit`, also run `cargo test --locked -p ui --features harness` in `blocksuite/native-playground`.
File renamed without changes.
View File
File renamed without changes.
@@ -1,6 +1,6 @@
[workspace]
exclude = ["native", "server"]
members = [
"frame-audit",
"test-db-harness",
"server-types",
"server-db",
@@ -43,9 +43,10 @@ tower-http = { version = "0.6", features = ["cors", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
uuid = { version = "1", features = ["v4", "serde"] }
y-octo = { version = "0.4.0", features = ["large_refs"] }
affine-server = { path = "affine-server" }
frame-audit = { path = "frame-audit" }
frame-audit = { path = "../../tools/frame-audit" }
server-db = { path = "server-db" }
server-http = { path = "server-http" }
server-spi = { path = "server-spi" }
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -211,7 +211,7 @@ fn startup_schema_gate_rejects_pre_0275_database_by_default() {
};
let err = match serve_with_extension(cli, Arc::new(CommunityExtension::new()), CancellationToken::new()).await {
Ok(_) => panic!("expected stepping-stone rejection for non-empty pre-0.27.5 database"),
Ok(_) => panic!("expected baseline gate rejection for non-empty pre-0.27.5 database"),
Err(err) => err,
};
assert!(
+1
View File
@@ -4,6 +4,7 @@ license-file = "LICENSE"
name = "affine_server_native"
publish = false
version = "1.0.0"
workspace = "../../.."
[lib]
crate-type = ["cdylib"]
File renamed without changes.
File renamed without changes.
@@ -2,20 +2,19 @@ use std::{
env,
fmt::Write as _,
fs,
path::{Path, PathBuf},
path::PathBuf,
};
use sha2::{Digest, Sha256};
fn main() {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
let repo_root = manifest_dir
let backend_dir = manifest_dir
.parent()
.and_then(Path::parent)
.expect("crates/server-db must live two levels under repository root");
.expect("packages/backend/server-db must live directly under packages/backend");
let migrations_dir = repo_root.join("packages/backend/server/migrations");
let runtime_sql_path = repo_root.join("packages/backend/native/src/runtime/sql/runtime_migrations.sql");
let migrations_dir = backend_dir.join("server/migrations");
let runtime_sql_path = backend_dir.join("native/src/runtime/sql/runtime_migrations.sql");
println!("cargo:rerun-if-changed={}", migrations_dir.display());
println!("cargo:rerun-if-changed={}", runtime_sql_path.display());
@@ -48,7 +47,7 @@ fn main() {
.unwrap();
writeln!(
generated,
"pub(crate) const BUNDLED_RUNTIME_MIGRATIONS_SQL: &str = include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../packages/backend/native/src/runtime/sql/runtime_migrations.sql\"));\n"
"pub(crate) const BUNDLED_RUNTIME_MIGRATIONS_SQL: &str = include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../native/src/runtime/sql/runtime_migrations.sql\"));\n"
)
.unwrap();
writeln!(
@@ -57,7 +56,7 @@ fn main() {
)
.unwrap();
for (name, checksum) in entries {
let rel = format!("/../../packages/backend/server/migrations/{name}/migration.sql");
let rel = format!("/../server/migrations/{name}/migration.sql");
writeln!(
generated,
" BundledPrismaMigration {{\n name: {:?},\n checksum: {:?},\n sql: include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), {:?})),\n }},",
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
//! Phase A `v0.27.5` co-existence SQL helpers.
//! Compatibility storage adapters for shared database schemas.
//!
//! Kept isolated under `phase_a_compat` so canonical domain crates never depend
//! on transition-era checkpoint tables or cutover checks.
//! on shared-schema checkpoint tables or cutover checks.
use crate::DbError;
@@ -6,7 +6,7 @@
//! `BEGIN;`/`COMMIT;` so embedded transaction wrappers never commit early) +
//! runtime tables, writes the `schema_baseline_0275` checkpoint, and creates
//! `native_schema_migrations`.
//! 2. Existing non-empty DB: enforces the `v0.27.5` stepping-stone gate without
//! 2. Existing non-empty DB: enforces the `v0.27.5` baseline gate without
//! ever mutating `_prisma_migrations`, idempotently ensures runtime tables
//! and `native_schema_migrations`.
@@ -295,7 +295,7 @@ async fn ensure_schema_ready_locked(conn: &mut sqlx::PgConnection) -> Result<Sch
let is_fresh_empty = !prisma_table_exists && public_table_count == 0;
let resuming_fresh_init = !is_fresh_empty && phase_a_compat::is_schema_baseline_0275_initializing(&mut *conn).await?;
// Track A: Fresh empty database or strictly verified resume of an interrupted
// Fresh empty database or strictly verified resume of an interrupted
// `server-db` fresh bootstrap.
if is_fresh_empty || resuming_fresh_init {
let prefix_len = if is_fresh_empty {
@@ -353,8 +353,8 @@ async fn ensure_schema_ready_locked(conn: &mut sqlx::PgConnection) -> Result<Sch
});
}
// Track B: Existing non-empty database — enforce v0.27.5 stepping-stone gate
// without ever modifying `_prisma_migrations`.
// Existing non-empty database: enforce the v0.27.5 baseline gate
// without modifying `_prisma_migrations`.
let has_baseline_checkpoint = phase_a_compat::has_schema_baseline_0275_checkpoint(&mut *conn).await?;
let missing_migrations = if prisma_table_exists {
@@ -18,9 +18,7 @@ fn repo_migrations_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.join("packages/backend/server/migrations")
.join("server/migrations")
}
fn test_runtime() -> tokio::runtime::Runtime {
@@ -178,7 +176,7 @@ fn partial_pre_0275_db_fails_with_stepping_stone_required() {
)
.unwrap();
// Even if a stale `schema_baseline_0275` checkpoint row exists, missing Prisma
// migrations must still fail the stepping-stone gate.
// migrations must still fail the baseline gate.
client
.batch_execute(
r#"CREATE TABLE IF NOT EXISTS storage_reconciliation_checkpoints (
@@ -206,7 +204,7 @@ fn partial_pre_0275_db_fails_with_stepping_stone_required() {
let err = db
.ensure_schema_ready()
.await
.expect_err("partial DB must fail stepping-stone check");
.expect_err("partial DB must fail baseline gate check");
match err {
DbError::SteppingStoneRequired {
missing_migrations,
@@ -319,7 +317,7 @@ fn existing_0275_db_boots_cleanly_without_touching_prisma_migrations() {
.fetch_one(conn.as_conn())
.await
.unwrap();
assert!(runtime_table_exists, "Track B must ensure runtime tables exist");
assert!(runtime_table_exists, "existing-DB bootstrap must ensure runtime tables exist");
drop(conn);
db.pool().close().await;
});
File renamed without changes.
@@ -255,7 +255,7 @@ mod tests {
#[test]
fn graphql_sdl_fields_and_types_match_v0275_oracle_schema() {
let oracle_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/oracle-contracts/v0.27.5/schema.gql");
let oracle_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../tests/oracle-contracts/v0.27.5/schema.gql");
let oracle_sdl =
std::fs::read_to_string(&oracle_path).unwrap_or_else(|e| panic!("failed to read {}: {e}", oracle_path.display()));
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -97,9 +97,9 @@ pub fn session_redis_url(base_redis_url: &str) -> Result<(String, u8), WorkerErr
Ok((out, session_db))
}
/// Helper for `V_new` private keys inside the shared Redis logical DB.
/// Helper for private worker keys inside the shared Redis logical DB.
///
/// Every key is prefixed with `<optional_prefix>v2:` so `V_new` worker state
/// Every key is prefixed with `<optional_prefix>v2:` so worker state
/// never collides with `v0.27.5` keys.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct V2Keyspace {
File renamed without changes.
@@ -301,7 +301,7 @@ fn pg_lease_tokens_and_cluster_marker_guard_destructive_calls() {
#[test]
fn affine_server_migrations_build_prisma_compatible_template() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../packages/backend/server/migrations");
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = MigrationSet::load(&dir).unwrap();
let cluster = PgCluster::from_env_or_docker().unwrap();
let template = cluster.ensure_template(&migrations).unwrap();
+11 -8
View File
@@ -6,9 +6,9 @@
// node scripts/ci/check-l0-tier-a.mjs --update-baseline rewrite the ratchet
//
// Gates:
// 1. crates/ layering: server-domain crates never depend on compatibility
// 1. packages/backend/ layering: server-domain crates never depend on compatibility
// layers or transport frameworks.
// 2. crates/ hygiene: no private keys, commercial prompts or private-edition
// 2. packages/backend/ hygiene: no private keys, commercial prompts or private-edition
// table references in the public workspace.
// 3. Test-debt ratchet: per-file counts of `waitForTimeout(` and `.skip`
// may only go down; `*.skip.*` test files are not allowed at all.
@@ -67,9 +67,10 @@ function* walk(dir) {
const lineOf = (text, index) => text.slice(0, index).split('\n').length;
// 1 + 2. crates/ layering and hygiene -------------------------------------
// 1 + 2. packages/backend/ layering and hygiene -----------------------------
const CRATES = join(ROOT, 'crates');
const CRATES = join(ROOT, 'packages/backend');
const LEGACY_BACKEND_DIRS = new Set(['native', 'server']);
const DOMAIN_FORBIDDEN = [
'legacy_compat',
'phase_a_compat',
@@ -86,8 +87,10 @@ const HYGIENE_RULES = [
if (existsSync(CRATES)) {
for (const file of walk(CRATES)) {
const path = rel(file);
const sub = path.slice('packages/backend/'.length).split('/')[0];
if (LEGACY_BACKEND_DIRS.has(sub)) continue;
if (/(^|\/)prompts\//.test(path))
fail('crates-hygiene', `${path}: prompt assets do not belong in crates/`);
fail('crates-hygiene', `${path}: prompt assets do not belong in packages/backend/`);
if (statSync(file).size > 2 * 1024 * 1024) continue;
const text = read(file);
for (const [pattern, what] of HYGIENE_RULES) {
@@ -96,7 +99,7 @@ if (existsSync(CRATES)) {
fail('crates-hygiene', `${path}:${lineOf(text, m.index)}: ${what}`);
}
const domainCrate = /^crates\/server-domain[^/]*\//.test(path);
const domainCrate = /^packages\/backend\/server-domain[^/]*\//.test(path);
if (domainCrate && path.endsWith('/Cargo.toml')) {
const deps = text
.split(/^\[/m)
@@ -277,8 +280,8 @@ for (const name of readdirSync(WORKFLOWS).filter(f => /\.ya?ml$/.test(f))) {
// The harness starts the same pinned images the workflows pull.
const HARNESS_IMAGES = [
['crates/test-db-harness/src/pg.rs', /PG_IMAGE: &str =\s*"([^"]+)"/],
['crates/test-db-harness/src/redis.rs', /REDIS_IMAGE: &str =\s*"([^"]+)"/],
['packages/backend/test-db-harness/src/pg.rs', /PG_IMAGE: &str =\s*"([^"]+)"/],
['packages/backend/test-db-harness/src/redis.rs', /REDIS_IMAGE: &str =\s*"([^"]+)"/],
];
for (const [path, pattern] of HARNESS_IMAGES) {
if (!existsSync(join(ROOT, path))) continue;
+2 -1
View File
@@ -90,13 +90,14 @@
}
},
"skip": {
"total": 62,
"total": 63,
"files": {
"blocksuite/integration-test/src/__tests__/edgeless/turbo-renderer.spec.ts": 2,
"packages/backend/server/src/__tests__/app/selfhost.e2e.ts": 1,
"packages/backend/server/src/__tests__/copilot/copilot-provider.spec.ts": 1,
"packages/backend/server/src/__tests__/doc/renderer.spec.ts": 1,
"packages/backend/server/src/__tests__/user.e2e.ts": 1,
"packages/backend/server/src/data/__tests__/cutover-baseline.spec.ts": 1,
"packages/frontend/core/src/__tests__/ai/utils/apply-model/apply-patch-to-doc.spec.ts": 2,
"tests/affine-cloud-copilot/e2e/ai-action/change-tone.spec.ts": 1,
"tests/affine-cloud-copilot/e2e/ai-action/check-code-error.spec.ts": 1,
+20
View File
@@ -0,0 +1,20 @@
[workspace]
[package]
description = "Renderer-independent geometry and interaction audit rules over serialized UI frame snapshots"
edition = "2024"
license = "MIT"
name = "frame-audit"
publish = false
rust-version = "1.88"
version = "0.1.0"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[lints.rust]
unsafe_code = "forbid"
[lints.clippy]
all = { level = "warn", priority = -1 }
File renamed without changes.
File renamed without changes.
File renamed without changes.