feat(crates): add server-types and server-db foundations

This commit is contained in:
still.fail station committed 2026-11-23 06:30:38 +09:00
1 parent 50ee19df4f
commit ee1463d7d0
15 files changed
+4315 -23

No files matched your search

+2
View File
@@ -12,6 +12,8 @@
- Redis: an explicit `AFFINE_TEST_REDIS_URL` isolated by the `test:<run>:` key prefix, or a private `redis:7-alpine` container. - 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, 10 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`. - 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, 10 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`. - `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.
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. 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.
+1682 -18
View File
File diff suppressed because it is too large. Load diff
+18 -5
View File
@@ -1,5 +1,5 @@
[workspace] [workspace]
members = ["frame-audit", "test-db-harness"] members = ["frame-audit", "test-db-harness", "server-types", "server-db"]
resolver = "3" resolver = "3"
[workspace.package] [workspace.package]
@@ -9,10 +9,23 @@ publish = false
rust-version = "1.88" rust-version = "1.88"
[workspace.dependencies] [workspace.dependencies]
postgres = "0.19" base64 = "0.22"
serde = { version = "1", features = ["derive"] } chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
serde_json = "1" futures-util = "0.3"
sha2 = "0.10" p256 = { version = "0.13", features = ["ecdsa", "pem"] }
postgres = "0.19"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json"] }
thiserror = "2"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "sync", "time", "process"] }
uuid = { version = "1", features = ["v4", "serde"] }
frame-audit = { path = "frame-audit" }
server-db = { path = "server-db" }
server-types = { path = "server-types" }
test-db-harness = { path = "test-db-harness" }
[workspace.lints.rust] [workspace.lints.rust]
unsafe_code = "forbid" unsafe_code = "forbid"
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "server-db"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish.workspace = true
rust-version.workspace = true
[dependencies]
chrono.workspace = true
futures-util.workspace = true
serde.workspace = true
server-types.workspace = true
sha2.workspace = true
sqlx.workspace = true
thiserror.workspace = true
tokio.workspace = true
[build-dependencies]
sha2.workspace = true
[dev-dependencies]
postgres.workspace = true
test-db-harness.workspace = true
uuid.workspace = true
[lints]
workspace = true
+81
View File
@@ -0,0 +1,81 @@
use std::{
env,
fmt::Write as _,
fs,
path::{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
.parent()
.and_then(Path::parent)
.expect("crates/server-db must live two levels under repository root");
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");
println!("cargo:rerun-if-changed={}", migrations_dir.display());
println!("cargo:rerun-if-changed={}", runtime_sql_path.display());
let mut entries = Vec::new();
for entry in fs::read_dir(&migrations_dir).expect("read packages/backend/server/migrations") {
let entry = entry.expect("read migration dir entry");
let sql_path = entry.path().join("migration.sql");
if !entry.file_type().expect("file_type").is_dir() || !sql_path.is_file() {
continue;
}
println!("cargo:rerun-if-changed={}", sql_path.display());
let name = entry.file_name().to_string_lossy().into_owned();
let bytes = fs::read(&sql_path).expect("read migration.sql");
let checksum = hex_sha256(&bytes);
entries.push((name, checksum));
}
entries.sort_by(|a, b| a.0.cmp(&b.0));
assert!(
!entries.is_empty(),
"expected Prisma migrations under {}",
migrations_dir.display()
);
let mut generated = String::new();
writeln!(
generated,
"pub(crate) struct BundledPrismaMigration {{\n pub name: &'static str,\n pub checksum: &'static str,\n pub sql: &'static str,\n}}\n"
)
.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"
)
.unwrap();
writeln!(
generated,
"pub(crate) const BUNDLED_PRISMA_MIGRATIONS: &[BundledPrismaMigration] = &["
)
.unwrap();
for (name, checksum) in entries {
let rel = format!("/../../packages/backend/server/migrations/{name}/migration.sql");
writeln!(
generated,
" BundledPrismaMigration {{\n name: {:?},\n checksum: {:?},\n sql: include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), {:?})),\n }},",
name, checksum, rel
)
.unwrap();
}
writeln!(generated, "];").unwrap();
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
fs::write(out_dir.join("bundled_migrations.rs"), generated).expect("write bundled_migrations.rs");
}
fn hex_sha256(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut out = String::with_capacity(digest.len() * 2);
for b in digest {
let _ = write!(out, "{b:02x}");
}
out
}
+18
View File
@@ -0,0 +1,18 @@
//! Error types for `server-db`.
#[derive(Debug, thiserror::Error)]
pub enum DbError {
#[error("database error: {0}")]
Sqlx(#[from] sqlx::Error),
#[error("invalid database configuration: {0}")]
InvalidConfig(String),
#[error("database admission semaphore closed")]
PoolClosed,
#[error("{message}")]
SteppingStoneRequired {
missing_migrations: Vec<String>,
message: String,
},
#[error("schema readiness check failed: {0}")]
SchemaCheck(String),
}
+357
View File
@@ -0,0 +1,357 @@
//! Single-pool PostgreSQL layer with 4-tier bounded semaphore admission,
//! per-connection timeouts, task-local query counters, and dual-track `v0.27.5`
//! schema readiness.
pub mod error;
pub mod metrics;
pub mod phase_a_compat;
pub mod schema;
use std::{
future::Future,
ops::{Deref, DerefMut},
pin::Pin,
str::FromStr,
sync::Arc,
};
use futures_util::{future::BoxFuture, stream::BoxStream};
use server_types::ServerRole;
use sqlx::{
Connection as _, Describe, Either, Execute, Executor as _, PgConnection, PgPool, Postgres, Transaction,
pool::PoolConnection,
postgres::{PgConnectOptions, PgPoolOptions, PgQueryResult, PgRow, PgStatement, PgTypeInfo},
};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
pub use crate::{
error::DbError,
metrics::{QueryCountersSnapshot, current_query_counters, record_query, with_query_scope},
schema::{SchemaReadiness, bundled_0275_migration_manifest},
};
pub const DEFAULT_STATEMENT_TIMEOUT_MS: u64 = 5_000;
pub const IDLE_IN_TRANSACTION_SESSION_TIMEOUT: &str = "10s";
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum WorkloadTier {
InteractiveRead,
InteractiveWrite,
WebhookReceipt,
LongQuery,
}
impl WorkloadTier {
const fn index(self) -> usize {
match self {
Self::InteractiveRead => 0,
Self::InteractiveWrite => 1,
Self::WebhookReceipt => 2,
Self::LongQuery => 3,
}
}
}
#[derive(Clone, Debug)]
pub struct DbConfig {
pub database_url: String,
pub channel: String,
pub role: ServerRole,
pub max_connections: u32,
pub statement_timeout_ms: u64,
pub tier_permits: [usize; 4],
}
impl DbConfig {
pub fn new(database_url: impl Into<String>) -> Self {
Self {
database_url: database_url.into(),
channel: "stable".to_owned(),
role: ServerRole::Allinone,
max_connections: 20,
statement_timeout_ms: DEFAULT_STATEMENT_TIMEOUT_MS,
tier_permits: [12, 8, 4, 2],
}
}
pub fn application_name(&self) -> String {
format!("affine:{}:{}:v2", self.channel, self.role.as_str())
}
}
struct ServerDbInner {
pool: PgPool,
connect_options: PgConnectOptions,
tier_semaphores: [Arc<Semaphore>; 4],
}
#[derive(Clone)]
pub struct ServerDb {
inner: Arc<ServerDbInner>,
}
/// Pooled connection paired with its workload-tier admission permit.
///
/// Field order ensures the connection returns to the pool before the semaphore
/// permit is released.
#[derive(Debug)]
pub struct TieredConn {
conn: PoolConnection<Postgres>,
_permit: OwnedSemaphorePermit,
}
impl TieredConn {
pub fn as_conn(&mut self) -> &mut PgConnection {
&mut self.conn
}
}
impl Deref for TieredConn {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.conn
}
}
impl DerefMut for TieredConn {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.conn
}
}
impl<'c> sqlx::Executor<'c> for &'c mut TieredConn {
type Database = Postgres;
fn fetch_many<'e, 'q: 'e, E>(self, query: E) -> BoxStream<'e, Result<Either<PgQueryResult, PgRow>, sqlx::Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
metrics::record_query();
(&mut *self.conn).fetch_many(query)
}
fn fetch_optional<'e, 'q: 'e, E>(self, query: E) -> BoxFuture<'e, Result<Option<PgRow>, sqlx::Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
metrics::record_query();
(&mut *self.conn).fetch_optional(query)
}
fn prepare_with<'e, 'q: 'e>(
self,
sql: &'q str,
parameters: &'e [PgTypeInfo],
) -> BoxFuture<'e, Result<PgStatement<'q>, sqlx::Error>>
where
'c: 'e,
{
(&mut *self.conn).prepare_with(sql, parameters)
}
fn describe<'e, 'q: 'e>(self, sql: &'q str) -> BoxFuture<'e, Result<Describe<Self::Database>, sqlx::Error>>
where
'c: 'e,
{
(&mut *self.conn).describe(sql)
}
}
/// Active transaction paired with its workload-tier admission permit.
///
/// Field order ensures the transaction finishes before the semaphore permit is
/// released.
#[derive(Debug)]
pub struct TieredTx<'a> {
tx: Transaction<'a, Postgres>,
_permit: OwnedSemaphorePermit,
}
impl<'a> TieredTx<'a> {
pub fn tx_mut(&mut self) -> &mut Transaction<'a, Postgres> {
&mut self.tx
}
pub async fn commit(self) -> Result<(), DbError> {
self.tx.commit().await?;
Ok(())
}
pub async fn rollback(self) -> Result<(), DbError> {
self.tx.rollback().await?;
Ok(())
}
}
impl Deref for TieredTx<'_> {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.tx
}
}
impl DerefMut for TieredTx<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.tx
}
}
impl<'c> sqlx::Executor<'c> for &'c mut TieredTx<'_> {
type Database = Postgres;
fn fetch_many<'e, 'q: 'e, E>(self, query: E) -> BoxStream<'e, Result<Either<PgQueryResult, PgRow>, sqlx::Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
metrics::record_query();
(&mut *self.tx).fetch_many(query)
}
fn fetch_optional<'e, 'q: 'e, E>(self, query: E) -> BoxFuture<'e, Result<Option<PgRow>, sqlx::Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
metrics::record_query();
(&mut *self.tx).fetch_optional(query)
}
fn prepare_with<'e, 'q: 'e>(
self,
sql: &'q str,
parameters: &'e [PgTypeInfo],
) -> BoxFuture<'e, Result<PgStatement<'q>, sqlx::Error>>
where
'c: 'e,
{
(&mut *self.tx).prepare_with(sql, parameters)
}
fn describe<'e, 'q: 'e>(self, sql: &'q str) -> BoxFuture<'e, Result<Describe<Self::Database>, sqlx::Error>>
where
'c: 'e,
{
(&mut *self.tx).describe(sql)
}
}
impl ServerDb {
pub async fn connect(config: DbConfig) -> Result<Self, DbError> {
if config.max_connections == 0 {
return Err(DbError::InvalidConfig("max_connections must be > 0".to_owned()));
}
if config.statement_timeout_ms == 0 {
return Err(DbError::InvalidConfig("statement_timeout_ms must be > 0".to_owned()));
}
if config.tier_permits.contains(&0) {
return Err(DbError::InvalidConfig(
"every WorkloadTier permit budget must be > 0".to_owned(),
));
}
let app_name = config.application_name();
let connect_options = PgConnectOptions::from_str(&config.database_url)?.application_name(&app_name);
let statement_timeout_ms = config.statement_timeout_ms;
let pool = PgPoolOptions::new()
.min_connections(0)
.max_connections(config.max_connections)
.after_connect(move |conn, _meta| {
Box::pin(async move {
let setup = format!(
"SET statement_timeout = '{statement_timeout_ms}ms'; \
SET idle_in_transaction_session_timeout = '{IDLE_IN_TRANSACTION_SESSION_TIMEOUT}';"
);
conn.execute(setup.as_str()).await?;
Ok(())
})
})
.connect_with(connect_options.clone())
.await?;
let tier_semaphores = config.tier_permits.map(|permits| Arc::new(Semaphore::new(permits)));
Ok(Self {
inner: Arc::new(ServerDbInner {
pool,
connect_options,
tier_semaphores,
}),
})
}
pub fn pool(&self) -> &PgPool {
&self.inner.pool
}
pub async fn acquire_tiered(&self, tier: WorkloadTier) -> Result<TieredConn, DbError> {
let permit = Arc::clone(&self.inner.tier_semaphores[tier.index()])
.acquire_owned()
.await
.map_err(|_| DbError::PoolClosed)?;
let conn = self.inner.pool.acquire().await?;
metrics::record_pool_acquire();
Ok(TieredConn { conn, _permit: permit })
}
pub async fn begin_tiered(&self, tier: WorkloadTier) -> Result<TieredTx<'_>, DbError> {
let permit = Arc::clone(&self.inner.tier_semaphores[tier.index()])
.acquire_owned()
.await
.map_err(|_| DbError::PoolClosed)?;
let tx = self.inner.pool.begin().await?;
metrics::record_pool_acquire();
metrics::record_transaction();
Ok(TieredTx { tx, _permit: permit })
}
/// Acquires a [`WorkloadTier::LongQuery`] permit, opens a transaction, sets
/// `LOCAL statement_timeout = '<timeout_ms>ms'`, and runs `f` with a
/// [`TieredTx`] whose `sqlx::Executor` automatically increments
/// [`QueryCountersSnapshot::queries`]. The internal `set_config` call does
/// not increment the business query counter. Commits when `f` returns `Ok`,
/// or rolls back on error.
pub async fn with_long_query_timeout<F, T>(&self, timeout_ms: u64, f: F) -> Result<T, DbError>
where
F: for<'a, 'b> FnOnce(&'a mut TieredTx<'b>) -> Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + 'a>>,
{
if timeout_ms == 0 {
return Err(DbError::InvalidConfig("long query timeout_ms must be > 0".to_owned()));
}
let mut tiered = self.begin_tiered(WorkloadTier::LongQuery).await?;
let timeout_value = format!("{timeout_ms}ms");
sqlx::query("SELECT set_config('statement_timeout', $1, true)")
.bind(&timeout_value)
.execute(&mut **tiered.tx_mut())
.await?;
let result = f(&mut tiered).await;
match result {
Ok(value) => {
tiered.commit().await?;
Ok(value)
}
Err(err) => {
let _ = tiered.rollback().await;
Err(err)
}
}
}
/// Opens an unpooled PostgreSQL connection suitable for session-level
/// advisory locks or `LISTEN`/`NOTIFY`.
pub async fn dedicated_session_conn(&self) -> Result<PgConnection, DbError> {
let conn = PgConnection::connect_with(&self.inner.connect_options).await?;
Ok(conn)
}
/// Ensures the database is at the required `v0.27.5` schema baseline and
/// creates `native_schema_migrations`.
pub async fn ensure_schema_ready(&self) -> Result<SchemaReadiness, DbError> {
schema::ensure_schema_ready_impl(self).await
}
}
+86
View File
@@ -0,0 +1,86 @@
//! Task-local query scope counters for deterministic DB budget assertions.
use std::{
future::Future,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct QueryCountersSnapshot {
pub queries: u64,
pub transactions: u64,
pub pool_acquires: u64,
}
impl QueryCountersSnapshot {
/// Asserts that all counters stay within the given ceilings.
pub fn assert_within(&self, max_queries: u64, max_transactions: u64, max_pool_acquires: u64) -> Result<(), String> {
if self.queries > max_queries || self.transactions > max_transactions || self.pool_acquires > max_pool_acquires {
return Err(format!(
"query budget exceeded: queries={}/{max_queries}, transactions={}/{max_transactions}, pool_acquires={}/{max_pool_acquires}",
self.queries, self.transactions, self.pool_acquires
));
}
Ok(())
}
}
#[derive(Default)]
struct QueryScopeCounters {
queries: AtomicU64,
transactions: AtomicU64,
pool_acquires: AtomicU64,
}
impl QueryScopeCounters {
fn snapshot(&self) -> QueryCountersSnapshot {
QueryCountersSnapshot {
queries: self.queries.load(Ordering::Relaxed),
transactions: self.transactions.load(Ordering::Relaxed),
pool_acquires: self.pool_acquires.load(Ordering::Relaxed),
}
}
}
tokio::task_local! {
static QUERY_SCOPE: Arc<QueryScopeCounters>;
}
/// Runs `fut` inside an isolated task-local query counting scope and returns
/// its output along with the final [`QueryCountersSnapshot`].
pub async fn with_query_scope<F: Future>(fut: F) -> (F::Output, QueryCountersSnapshot) {
let counters = Arc::new(QueryScopeCounters::default());
let out = QUERY_SCOPE.scope(Arc::clone(&counters), fut).await;
(out, counters.snapshot())
}
/// Increments the active task-local `queries` counter if inside a scope.
pub fn record_query() {
let _ = QUERY_SCOPE.try_with(|c| {
c.queries.fetch_add(1, Ordering::Relaxed);
});
}
/// Increments the active task-local `transactions` counter if inside a scope.
pub(crate) fn record_transaction() {
let _ = QUERY_SCOPE.try_with(|c| {
c.transactions.fetch_add(1, Ordering::Relaxed);
});
}
/// Increments the active task-local `pool_acquires` counter if inside a scope.
pub(crate) fn record_pool_acquire() {
let _ = QUERY_SCOPE.try_with(|c| {
c.pool_acquires.fetch_add(1, Ordering::Relaxed);
});
}
/// Returns a snapshot of the active task-local scope counters, if any.
pub fn current_query_counters() -> Option<QueryCountersSnapshot> {
QUERY_SCOPE.try_with(|c| c.snapshot()).ok()
}
+111
View File
@@ -0,0 +1,111 @@
//! Phase A `v0.27.5` co-existence SQL helpers.
//!
//! Kept isolated under `phase_a_compat` so canonical domain crates never depend
//! on transition-era checkpoint tables or cutover checks.
use crate::DbError;
pub const FRESH_BOOTSTRAP_ORIGIN: &str = "server_db_fresh_0275";
/// Returns `true` if `storage_reconciliation_checkpoints` exists and contains
/// the completed `schema_baseline_0275` global marker.
pub async fn has_schema_baseline_0275_checkpoint(conn: &mut sqlx::PgConnection) -> Result<bool, DbError> {
let table_exists: bool =
sqlx::query_scalar("SELECT to_regclass('public.storage_reconciliation_checkpoints') IS NOT NULL")
.fetch_one(&mut *conn)
.await?;
if !table_exists {
return Ok(false);
}
let matched: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1
FROM storage_reconciliation_checkpoints
WHERE kind = 'schema_baseline_0275'
AND scope = 'global'
AND status = 'completed'
)",
)
.fetch_one(&mut *conn)
.await?;
Ok(matched)
}
/// Returns `true` if a fresh-DB `schema_baseline_0275` initialization created
/// by `server-db` is currently in progress (`status = 'initializing'` with
/// `metadata->>'bootstrapOrigin' = 'server_db_fresh_0275'`).
pub async fn is_schema_baseline_0275_initializing(conn: &mut sqlx::PgConnection) -> Result<bool, DbError> {
let has_metadata_col: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'storage_reconciliation_checkpoints'
AND column_name = 'metadata'
)",
)
.fetch_one(&mut *conn)
.await?;
if !has_metadata_col {
return Ok(false);
}
let matched: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1
FROM storage_reconciliation_checkpoints
WHERE kind = 'schema_baseline_0275'
AND scope = 'global'
AND status = 'initializing'
AND metadata->>'bootstrapOrigin' = $1
)",
)
.bind(FRESH_BOOTSTRAP_ORIGIN)
.fetch_one(&mut *conn)
.await?;
Ok(matched)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CutoverInvariantCounts {
pub ownerless_workspaces: i32,
pub active_unsigned_selfhost_entitlements: i32,
}
/// Evaluates the exact `v0.27.5` `CutoverCommand` validation query against the
/// database, returning invariant violation counts (both must be `0`).
pub async fn check_cutover_invariants(
conn: &mut sqlx::PgConnection,
selfhosted: bool,
) -> Result<CutoverInvariantCounts, DbError> {
let deployment = if selfhosted { "selfhosted" } else { "cloud" };
let (ownerless_workspaces, active_unsigned_selfhost_entitlements): (i32, i32) = sqlx::query_as(
"SELECT
(
SELECT count(*)::int
FROM workspaces workspace
WHERE NOT EXISTS (
SELECT 1
FROM workspace_members member
WHERE member.workspace_id = workspace.id
AND member.role = 'owner'
AND member.state = 'active'
)
),
(
SELECT count(*)::int
FROM entitlements
WHERE $1 = 'selfhosted'
AND source = 'selfhost_license'
AND signed_payload IS NULL
AND status IN ('active', 'grace')
)",
)
.bind(deployment)
.fetch_one(&mut *conn)
.await?;
Ok(CutoverInvariantCounts {
ownerless_workspaces,
active_unsigned_selfhost_entitlements,
})
}
+514
View File
@@ -0,0 +1,514 @@
//! Dual-track schema readiness engine (`ensure_schema_ready`):
//!
//! 1. Fresh empty DB (or resuming an interrupted `server-db` fresh init):
//! applies the bundled `v0.27.5` baseline migrations (each in an atomic
//! transaction paired with its `_prisma_migrations` row, stripping top-level
//! `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
//! ever mutating `_prisma_migrations`, idempotently ensures runtime tables
//! and `native_schema_migrations`.
use std::collections::{HashMap, HashSet};
use sqlx::{Connection as _, Executor as _};
use crate::{DbError, ServerDb, phase_a_compat};
include!(concat!(env!("OUT_DIR"), "/bundled_migrations.rs"));
const SCHEMA_READY_ADVISORY_LOCK: i64 = 0x4146_4649_4e45_0275;
const CREATE_PRISMA_MIGRATIONS_TABLE_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS "_prisma_migrations" (
"id" VARCHAR(36) PRIMARY KEY NOT NULL,
"checksum" VARCHAR(64) NOT NULL,
"finished_at" TIMESTAMPTZ,
"migration_name" VARCHAR(255) NOT NULL,
"logs" TEXT,
"rolled_back_at" TIMESTAMPTZ,
"started_at" TIMESTAMPTZ NOT NULL DEFAULT now(),
"applied_steps_count" INTEGER NOT NULL DEFAULT 0
)
"#;
const CREATE_CHECKPOINTS_TABLE_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS storage_reconciliation_checkpoints (
kind TEXT NOT NULL,
scope TEXT NOT NULL,
status TEXT NOT NULL,
cursor JSONB NOT NULL DEFAULT '{}',
last_key TEXT,
last_sid INTEGER,
completed_at TIMESTAMPTZ(3),
updated_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
metadata JSONB NOT NULL DEFAULT '{}',
PRIMARY KEY (kind, scope)
)
"#;
const CREATE_NATIVE_SCHEMA_MIGRATIONS_TABLE_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS native_schema_migrations (
component TEXT NOT NULL,
version INTEGER NOT NULL,
checksum TEXT NOT NULL,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (component, version)
)
"#;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SchemaReadiness {
InitializedFresh0275 { applied_migrations: usize },
ReadyExisting0275 { verified_migrations: usize },
}
/// Returns the ordered list of bundled `v0.27.5` Prisma `(migration_name, sha256_checksum)` pairs.
pub fn bundled_0275_migration_manifest() -> Vec<(&'static str, &'static str)> {
BUNDLED_PRISMA_MIGRATIONS.iter().map(|m| (m.name, m.checksum)).collect()
}
/// Strips standalone top-level transaction control statements (`BEGIN`,
/// `BEGIN TRANSACTION`, `BEGIN WORK`, `COMMIT`, `COMMIT TRANSACTION`,
/// `COMMIT WORK`, `END`, `END TRANSACTION`, `END WORK`) while preserving
/// everything inside single-quoted strings, double-quoted identifiers,
/// dollar-quoted PL/pgSQL blocks (`$$ ... $$`, `$tag$ ... $tag$`), and comments.
pub fn strip_top_level_tx_control(sql: &str) -> String {
let bytes = sql.as_bytes();
let len = bytes.len();
let mut out = String::with_capacity(len);
let mut stmt_start = 0usize;
let mut i = 0usize;
while i < len {
match bytes[i] {
b'\'' => {
i += 1;
while i < len {
if bytes[i] == b'\'' {
i += 1;
if i < len && bytes[i] == b'\'' {
i += 1;
} else {
break;
}
} else {
i += 1;
}
}
}
b'"' => {
i += 1;
while i < len {
if bytes[i] == b'"' {
i += 1;
if i < len && bytes[i] == b'"' {
i += 1;
} else {
break;
}
} else {
i += 1;
}
}
}
b'-' if i + 1 < len && bytes[i + 1] == b'-' => {
i += 2;
while i < len && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if i + 1 < len && bytes[i + 1] == b'*' => {
i = skip_block_comment(bytes, i);
}
b'$' => {
if let Some((tag_end, tag)) = parse_dollar_tag(bytes, i) {
i = tag_end;
while i < len {
if bytes[i] == b'$' && bytes[i..].starts_with(tag) {
i += tag.len();
break;
}
i += 1;
}
} else {
i += 1;
}
}
b';' => {
let stmt = &sql[stmt_start..=i];
if !is_top_level_tx_control(stmt) {
out.push_str(stmt);
}
i += 1;
stmt_start = i;
}
_ => {
i += 1;
}
}
}
if stmt_start < len {
let tail = &sql[stmt_start..];
if !is_top_level_tx_control(tail) {
out.push_str(tail);
}
}
out
}
fn skip_block_comment(bytes: &[u8], start: usize) -> usize {
let len = bytes.len();
let mut i = start + 2;
let mut depth = 1usize;
while i < len && depth > 0 {
if bytes[i] == b'/' && i + 1 < len && bytes[i + 1] == b'*' {
depth += 1;
i += 2;
} else if bytes[i] == b'*' && i + 1 < len && bytes[i + 1] == b'/' {
depth -= 1;
i += 2;
} else {
i += 1;
}
}
i
}
fn parse_dollar_tag(bytes: &[u8], start: usize) -> Option<(usize, &[u8])> {
let len = bytes.len();
if start >= len || bytes[start] != b'$' {
return None;
}
let mut j = start + 1;
if j < len && bytes[j] == b'$' {
return Some((j + 1, &bytes[start..=j]));
}
if j < len && (bytes[j].is_ascii_alphabetic() || bytes[j] == b'_') {
j += 1;
while j < len && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
j += 1;
}
if j < len && bytes[j] == b'$' {
return Some((j + 1, &bytes[start..=j]));
}
}
None
}
fn is_top_level_tx_control(stmt: &str) -> bool {
let bytes = stmt.as_bytes();
let len = bytes.len();
let mut i = 0usize;
let mut tokens: Vec<String> = Vec::new();
while i < len {
match bytes[i] {
b if b.is_ascii_whitespace() || b == b';' => i += 1,
b'-' if i + 1 < len && bytes[i + 1] == b'-' => {
i += 2;
while i < len && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if i + 1 < len && bytes[i + 1] == b'*' => {
i = skip_block_comment(bytes, i);
}
b if b.is_ascii_alphabetic() => {
let start = i;
while i < len && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
i += 1;
}
tokens.push(stmt[start..i].to_ascii_uppercase());
if tokens.len() > 2 {
return false;
}
}
_ => return false,
}
}
match tokens.as_slice() {
[a] => matches!(a.as_str(), "BEGIN" | "COMMIT" | "END"),
[a, b] => matches!(a.as_str(), "BEGIN" | "COMMIT" | "END") && matches!(b.as_str(), "TRANSACTION" | "WORK"),
_ => false,
}
}
/// Executes a single migration script inside an existing PostgreSQL transaction
/// after stripping standalone top-level `BEGIN;`/`COMMIT;` wrappers, then
/// inserts its exact `_prisma_migrations` row using the unmodified `checksum`.
pub async fn apply_migration_sql_and_record_in_tx(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
migration_name: &str,
checksum: &str,
raw_sql: &str,
) -> Result<(), DbError> {
let sanitized = strip_top_level_tx_control(raw_sql);
if !sanitized.trim().is_empty() {
sqlx::raw_sql(&sanitized)
.execute(&mut **tx)
.await
.map_err(|e| DbError::SchemaCheck(format!("failed applying bundled migration {migration_name}: {e}")))?;
}
sqlx::query(
r#"INSERT INTO "_prisma_migrations" (id, checksum, finished_at, migration_name, started_at, applied_steps_count)
VALUES (gen_random_uuid()::text, $1, now(), $2, now(), 1)"#,
)
.bind(checksum)
.bind(migration_name)
.execute(&mut **tx)
.await?;
Ok(())
}
pub(crate) async fn ensure_schema_ready_impl(db: &ServerDb) -> Result<SchemaReadiness, DbError> {
let mut conn = db.dedicated_session_conn().await?;
// Allow enough time for full fresh-DB baseline DDL on slower hosts.
sqlx::query("SET statement_timeout = '120s'").execute(&mut conn).await?;
sqlx::query("SELECT pg_advisory_lock($1)")
.bind(SCHEMA_READY_ADVISORY_LOCK)
.execute(&mut conn)
.await?;
let outcome = ensure_schema_ready_locked(&mut conn).await;
let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
.bind(SCHEMA_READY_ADVISORY_LOCK)
.execute(&mut conn)
.await;
outcome
}
async fn ensure_schema_ready_locked(conn: &mut sqlx::PgConnection) -> Result<SchemaReadiness, DbError> {
let prisma_table_exists: bool = sqlx::query_scalar("SELECT to_regclass('public._prisma_migrations') IS NOT NULL")
.fetch_one(&mut *conn)
.await?;
let public_table_count: i64 =
sqlx::query_scalar("SELECT count(*)::bigint FROM pg_tables WHERE schemaname = 'public'")
.fetch_one(&mut *conn)
.await?;
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
// `server-db` fresh bootstrap.
if is_fresh_empty || resuming_fresh_init {
let prefix_len = if is_fresh_empty {
let mut bootstrap_tx = conn.begin().await?;
bootstrap_tx.execute(CREATE_PRISMA_MIGRATIONS_TABLE_SQL).await?;
bootstrap_tx.execute(CREATE_CHECKPOINTS_TABLE_SQL).await?;
sqlx::query(
r#"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, metadata, updated_at)
VALUES (
'schema_baseline_0275',
'global',
'initializing',
jsonb_build_object('bootstrapOrigin', $1::text),
now()
)
ON CONFLICT (kind, scope) DO NOTHING"#,
)
.bind(phase_a_compat::FRESH_BOOTSTRAP_ORIGIN)
.execute(&mut *bootstrap_tx)
.await?;
bootstrap_tx.commit().await?;
0usize
} else {
verify_resumable_prefix(&mut *conn).await?
};
for migration in &BUNDLED_PRISMA_MIGRATIONS[prefix_len..] {
let mut tx = conn.begin().await?;
apply_migration_sql_and_record_in_tx(&mut tx, migration.name, migration.checksum, migration.sql).await?;
tx.commit().await?;
}
let mut finalize_tx = conn.begin().await?;
sqlx::raw_sql(BUNDLED_RUNTIME_MIGRATIONS_SQL)
.execute(&mut *finalize_tx)
.await
.map_err(|e| DbError::SchemaCheck(format!("failed applying runtime migrations: {e}")))?;
sqlx::query(
r#"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, completed_at, updated_at)
VALUES ('schema_baseline_0275', 'global', 'completed', now(), now())
ON CONFLICT (kind, scope) DO UPDATE
SET status = EXCLUDED.status,
completed_at = COALESCE(storage_reconciliation_checkpoints.completed_at, EXCLUDED.completed_at),
updated_at = now()"#,
)
.execute(&mut *finalize_tx)
.await?;
finalize_tx.execute(CREATE_NATIVE_SCHEMA_MIGRATIONS_TABLE_SQL).await?;
finalize_tx.commit().await?;
return Ok(SchemaReadiness::InitializedFresh0275 {
applied_migrations: BUNDLED_PRISMA_MIGRATIONS.len(),
});
}
// Track B: Existing non-empty database — enforce v0.27.5 stepping-stone gate
// without ever 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 {
let applied: Vec<String> = sqlx::query_scalar(
r#"SELECT migration_name
FROM "_prisma_migrations"
WHERE finished_at IS NOT NULL AND rolled_back_at IS NULL"#,
)
.fetch_all(&mut *conn)
.await?;
let applied_set: HashSet<&str> = applied.iter().map(String::as_str).collect();
BUNDLED_PRISMA_MIGRATIONS
.iter()
.filter(|m| !applied_set.contains(m.name))
.map(|m| m.name.to_owned())
.collect::<Vec<_>>()
} else {
BUNDLED_PRISMA_MIGRATIONS
.iter()
.map(|m| m.name.to_owned())
.collect::<Vec<_>>()
};
let stepping_stone_failed = !prisma_table_exists || !missing_migrations.is_empty() || !has_baseline_checkpoint;
if stepping_stone_failed {
let reason = if !prisma_table_exists || !missing_migrations.is_empty() {
let sample = missing_migrations
.iter()
.take(5)
.cloned()
.collect::<Vec<_>>()
.join(", ");
format!("{} migration(s) missing, e.g. {sample}", missing_migrations.len())
} else {
"missing completed schema_baseline_0275 cutover checkpoint".to_owned()
};
let message = format!(
"database is not at the required v0.27.5 schema baseline ({reason}). \
Upgrade this database through AFFiNE v0.27.5 (run v0.27.5 predeploy migrations and cutover) before starting the native server."
);
return Err(DbError::SteppingStoneRequired {
missing_migrations,
message,
});
}
let mut tx = conn.begin().await?;
sqlx::raw_sql(BUNDLED_RUNTIME_MIGRATIONS_SQL)
.execute(&mut *tx)
.await
.map_err(|e| DbError::SchemaCheck(format!("failed ensuring runtime migrations on existing DB: {e}")))?;
tx.execute(CREATE_NATIVE_SCHEMA_MIGRATIONS_TABLE_SQL).await?;
tx.commit().await?;
Ok(SchemaReadiness::ReadyExisting0275 {
verified_migrations: BUNDLED_PRISMA_MIGRATIONS.len(),
})
}
/// Validates that `_prisma_migrations` on a resuming fresh-bootstrap database
/// contains an exact, contiguous prefix of `BUNDLED_PRISMA_MIGRATIONS` with
/// 100% matching names and SHA-256 checksums, returning the prefix length.
async fn verify_resumable_prefix(conn: &mut sqlx::PgConnection) -> Result<usize, DbError> {
let prisma_table_exists: bool = sqlx::query_scalar("SELECT to_regclass('public._prisma_migrations') IS NOT NULL")
.fetch_one(&mut *conn)
.await?;
if !prisma_table_exists {
return Err(DbError::SchemaCheck(
"resumable fresh bootstrap checkpoint found, but _prisma_migrations table is missing".to_owned(),
));
}
let rows: Vec<(String, String, bool, bool)> = sqlx::query_as(
r#"SELECT migration_name, checksum, finished_at IS NOT NULL, rolled_back_at IS NOT NULL
FROM "_prisma_migrations""#,
)
.fetch_all(&mut *conn)
.await?;
let mut seen: HashMap<String, String> = HashMap::with_capacity(rows.len());
for (name, checksum, finished, rolled_back) in rows {
if !finished || rolled_back {
return Err(DbError::SchemaCheck(format!(
"cannot resume fresh bootstrap: migration {name} is unfinished or rolled back"
)));
}
if seen.insert(name.clone(), checksum).is_some() {
return Err(DbError::SchemaCheck(format!(
"cannot resume fresh bootstrap: duplicate _prisma_migrations entry for {name}"
)));
}
}
if seen.len() > BUNDLED_PRISMA_MIGRATIONS.len() {
return Err(DbError::SchemaCheck(format!(
"cannot resume fresh bootstrap: found {} migrations, more than bundled {}",
seen.len(),
BUNDLED_PRISMA_MIGRATIONS.len()
)));
}
let prefix_len = seen.len();
for expected in &BUNDLED_PRISMA_MIGRATIONS[..prefix_len] {
match seen.get(expected.name) {
Some(actual_checksum) if actual_checksum == expected.checksum => {}
Some(actual_checksum) => {
return Err(DbError::SchemaCheck(format!(
"cannot resume fresh bootstrap: checksum mismatch for {} (expected {}, got {actual_checksum})",
expected.name, expected.checksum
)));
}
None => {
return Err(DbError::SchemaCheck(format!(
"cannot resume fresh bootstrap: _prisma_migrations is not a contiguous prefix (missing {})",
expected.name
)));
}
}
}
Ok(prefix_len)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strip_top_level_tx_control_removes_wrappers_and_preserves_plpgsql() {
let input = "\
-- header comment
BEGIN;
CREATE TABLE demo (id INT);
DO $$
BEGIN
IF TRUE THEN
PERFORM 1;
END IF;
END
$$;
CREATE FUNCTION demo_fn() RETURNS void LANGUAGE plpgsql AS $fn$
BEGIN
RETURN;
END;
$fn$;
/* trailing comment */ COMMIT TRANSACTION;
END;
";
let stripped = strip_top_level_tx_control(input);
assert!(!stripped.contains("COMMIT TRANSACTION"));
assert!(stripped.contains("CREATE TABLE demo (id INT);"));
assert!(stripped.contains("DO $$\nBEGIN"));
assert!(stripped.contains("END\n$$;"));
assert!(stripped.contains("AS $fn$\nBEGIN\n RETURN;\nEND;\n$fn$;"));
}
}
+563
View File
@@ -0,0 +1,563 @@
use std::{
path::PathBuf,
time::{Duration, Instant},
};
use postgres::{Client, NoTls};
use server_db::{
DbConfig, DbError, SchemaReadiness, ServerDb, WorkloadTier, bundled_0275_migration_manifest, phase_a_compat,
with_query_scope,
};
use server_types::ServerRole;
use test_db_harness::{
migrations::MigrationSet,
pg::{DEFAULT_LEASE_TTL, PgCluster},
};
fn repo_migrations_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.join("packages/backend/server/migrations")
}
fn test_runtime() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.expect("build tokio runtime")
}
/// Creates a brand-new completely empty database inside the marked test cluster
/// and drops it automatically on drop.
struct EmptyDbGuard {
admin_url: String,
db_name: String,
url: String,
}
impl EmptyDbGuard {
fn create(cluster: &PgCluster, prefix: &str) -> Self {
let suffix = uuid::Uuid::new_v4().simple().to_string();
let db_name = format!("test_{prefix}_{}", &suffix[..12]);
let mut admin = Client::connect(cluster.admin_url(), NoTls).expect("connect test admin");
admin
.batch_execute(&format!("CREATE DATABASE \"{db_name}\""))
.expect("create empty test database");
let url = cluster.url_for(&db_name);
Self {
admin_url: cluster.admin_url().to_owned(),
db_name,
url,
}
}
}
impl Drop for EmptyDbGuard {
fn drop(&mut self) {
if let Ok(mut admin) = Client::connect(&self.admin_url, NoTls) {
let _ = admin.batch_execute(&format!("DROP DATABASE IF EXISTS \"{}\" WITH (FORCE)", self.db_name));
}
}
}
#[test]
fn fresh_empty_db_initializes_0275_baseline_and_is_idempotent() {
let cluster = PgCluster::from_env_or_docker().expect("test PG16 cluster");
let empty = EmptyDbGuard::create(&cluster, "fresh0275");
let disk_set = MigrationSet::load(&repo_migrations_dir()).unwrap();
let rt = test_runtime();
rt.block_on(async {
let db = ServerDb::connect(DbConfig::new(&empty.url))
.await
.expect("connect ServerDb");
let expected_manifest = bundled_0275_migration_manifest();
assert!(!expected_manifest.is_empty());
let first = db.ensure_schema_ready().await.expect("fresh DB init");
assert_eq!(
first,
SchemaReadiness::InitializedFresh0275 {
applied_migrations: expected_manifest.len()
}
);
// Verify core tables + _prisma_migrations exact SHA-256 checksums + checkpoint + native ledger.
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
for table in [
"users",
"workspaces",
"workspace_members",
"entitlements",
"snapshots",
"_prisma_migrations",
"storage_reconciliation_checkpoints",
"native_schema_migrations",
] {
let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL")
.bind(format!("public.{table}"))
.fetch_one(conn.as_conn())
.await
.unwrap();
assert!(exists, "expected table {table} to exist after fresh init");
}
let prisma_rows: Vec<(String, String, i32)> = sqlx::query_as(
r#"SELECT migration_name, checksum, applied_steps_count
FROM "_prisma_migrations"
WHERE finished_at IS NOT NULL AND rolled_back_at IS NULL
ORDER BY migration_name"#,
)
.fetch_all(conn.as_conn())
.await
.unwrap();
assert_eq!(prisma_rows.len(), disk_set.migrations.len());
for ((name, checksum, steps), expected) in prisma_rows.iter().zip(disk_set.migrations.iter()) {
assert_eq!(name, &expected.name);
assert_eq!(checksum, &expected.checksum);
assert_eq!(*steps, 1);
}
assert!(
phase_a_compat::has_schema_baseline_0275_checkpoint(conn.as_conn())
.await
.unwrap()
);
let cutover = phase_a_compat::check_cutover_invariants(conn.as_conn(), true)
.await
.unwrap();
assert_eq!(cutover.ownerless_workspaces, 0);
assert_eq!(cutover.active_unsigned_selfhost_entitlements, 0);
let before_rerun: Vec<(String, String, String)> =
sqlx::query_as(r#"SELECT id, migration_name, checksum FROM "_prisma_migrations" ORDER BY migration_name"#)
.fetch_all(conn.as_conn())
.await
.unwrap();
drop(conn);
// Second run must be an idempotent no-op with zero changes to `_prisma_migrations`.
let second = db.ensure_schema_ready().await.expect("second ensure_schema_ready");
assert_eq!(
second,
SchemaReadiness::ReadyExisting0275 {
verified_migrations: expected_manifest.len()
}
);
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let after_rerun: Vec<(String, String, String)> =
sqlx::query_as(r#"SELECT id, migration_name, checksum FROM "_prisma_migrations" ORDER BY migration_name"#)
.fetch_all(conn.as_conn())
.await
.unwrap();
assert_eq!(before_rerun, after_rerun);
drop(conn);
db.pool().close().await;
});
}
#[test]
fn partial_pre_0275_db_fails_with_stepping_stone_required() {
let cluster = PgCluster::from_env_or_docker().expect("test PG16 cluster");
let disk_set = MigrationSet::load(&repo_migrations_dir()).unwrap();
let template = cluster.ensure_template(&disk_set).unwrap();
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).unwrap();
let last_migration = disk_set.migrations.last().unwrap().name.clone();
{
let mut client = Client::connect(lease.url(), NoTls).unwrap();
client
.execute(
r#"DELETE FROM "_prisma_migrations" WHERE migration_name = $1"#,
&[&last_migration],
)
.unwrap();
// Even if a stale `schema_baseline_0275` checkpoint row exists, missing Prisma
// migrations must still fail the stepping-stone gate.
client
.batch_execute(
r#"CREATE TABLE IF NOT EXISTS storage_reconciliation_checkpoints (
kind TEXT NOT NULL,
scope TEXT NOT NULL,
status TEXT NOT NULL,
cursor JSONB NOT NULL DEFAULT '{}',
last_key TEXT,
last_sid INTEGER,
completed_at TIMESTAMPTZ(3),
updated_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
metadata JSONB NOT NULL DEFAULT '{}',
PRIMARY KEY (kind, scope)
);
INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, completed_at)
VALUES ('schema_baseline_0275', 'global', 'completed', now())
ON CONFLICT (kind, scope) DO UPDATE SET status = 'completed';"#,
)
.unwrap();
}
let rt = test_runtime();
rt.block_on(async {
let db = ServerDb::connect(DbConfig::new(lease.url())).await.unwrap();
let err = db
.ensure_schema_ready()
.await
.expect_err("partial DB must fail stepping-stone check");
match err {
DbError::SteppingStoneRequired {
missing_migrations,
message,
} => {
assert!(
message.contains("v0.27.5"),
"error message must instruct v0.27.5 upgrade, got: {message}"
);
assert_eq!(missing_migrations, vec![last_migration]);
}
other => panic!("expected SteppingStoneRequired, got {other:?}"),
}
db.pool().close().await;
});
}
#[test]
fn existing_0275_db_boots_cleanly_without_touching_prisma_migrations() {
let cluster = PgCluster::from_env_or_docker().expect("test PG16 cluster");
let disk_set = MigrationSet::load(&repo_migrations_dir()).unwrap();
let template = cluster.ensure_template(&disk_set).unwrap();
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).unwrap();
let rt = test_runtime();
rt.block_on(async {
let db = ServerDb::connect(DbConfig::new(lease.url())).await.unwrap();
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let before: Vec<(String, String, String, i32)> = sqlx::query_as(
r#"SELECT id, migration_name, checksum, applied_steps_count
FROM "_prisma_migrations"
ORDER BY migration_name"#,
)
.fetch_all(conn.as_conn())
.await
.unwrap();
drop(conn);
// All Prisma migrations present, but `schema_baseline_0275` cutover checkpoint
// missing: must be blocked with SteppingStoneRequired.
let err = db
.ensure_schema_ready()
.await
.expect_err("existing DB without schema_baseline_0275 cutover checkpoint must fail");
match err {
DbError::SteppingStoneRequired {
missing_migrations,
message,
} => {
assert!(missing_migrations.is_empty());
assert!(message.contains("v0.27.5"), "unexpected message: {message}");
}
other => panic!("expected SteppingStoneRequired, got {other:?}"),
}
// Simulate v0.27.5 cutover writing the completed `schema_baseline_0275` marker.
{
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveWrite).await.unwrap();
sqlx::raw_sql(
r#"CREATE TABLE IF NOT EXISTS storage_reconciliation_checkpoints (
kind TEXT NOT NULL,
scope TEXT NOT NULL,
status TEXT NOT NULL,
cursor JSONB NOT NULL DEFAULT '{}',
last_key TEXT,
last_sid INTEGER,
completed_at TIMESTAMPTZ(3),
updated_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
metadata JSONB NOT NULL DEFAULT '{}',
PRIMARY KEY (kind, scope)
);
INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, completed_at)
VALUES ('schema_baseline_0275', 'global', 'completed', now())
ON CONFLICT (kind, scope) DO UPDATE SET status = 'completed';"#,
)
.execute(conn.as_conn())
.await
.unwrap();
}
let readiness = db.ensure_schema_ready().await.unwrap();
assert_eq!(
readiness,
SchemaReadiness::ReadyExisting0275 {
verified_migrations: disk_set.migrations.len()
}
);
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let after: Vec<(String, String, String, i32)> = sqlx::query_as(
r#"SELECT id, migration_name, checksum, applied_steps_count
FROM "_prisma_migrations"
ORDER BY migration_name"#,
)
.fetch_all(conn.as_conn())
.await
.unwrap();
assert_eq!(
before, after,
"_prisma_migrations must never be modified on existing DB"
);
let ledger_exists: bool = sqlx::query_scalar("SELECT to_regclass('public.native_schema_migrations') IS NOT NULL")
.fetch_one(conn.as_conn())
.await
.unwrap();
assert!(ledger_exists);
let runtime_table_exists: bool =
sqlx::query_scalar("SELECT to_regclass('public.storage_reconciliation_checkpoints') IS NOT NULL")
.fetch_one(conn.as_conn())
.await
.unwrap();
assert!(runtime_table_exists, "Track B must ensure runtime tables exist");
drop(conn);
db.pool().close().await;
});
}
#[test]
fn embedded_begin_commit_migration_rolls_back_atomically_and_retries_cleanly() {
let cluster = PgCluster::from_env_or_docker().expect("test PG16 cluster");
let empty = EmptyDbGuard::create(&cluster, "txatom");
let rt = test_runtime();
rt.block_on(async {
let db = ServerDb::connect(DbConfig::new(&empty.url)).await.unwrap();
let mut conn = db.dedicated_session_conn().await.unwrap();
sqlx::raw_sql(
r#"CREATE TABLE "_prisma_migrations" (
"id" VARCHAR(36) PRIMARY KEY NOT NULL,
"checksum" VARCHAR(64) NOT NULL,
"finished_at" TIMESTAMPTZ,
"migration_name" VARCHAR(255) NOT NULL,
"logs" TEXT,
"rolled_back_at" TIMESTAMPTZ,
"started_at" TIMESTAMPTZ NOT NULL DEFAULT now(),
"applied_steps_count" INTEGER NOT NULL DEFAULT 0
)"#,
)
.execute(&mut conn)
.await
.unwrap();
let migration_sql = "\
BEGIN;
CREATE TABLE atomic_tx_probe (id INT PRIMARY KEY);
COMMIT;
";
let checksum = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
// Simulate a failure after DDL runs (before transaction commit): if embedded
// `COMMIT;` were not stripped, `atomic_tx_probe` would survive rollback.
{
use sqlx::Connection as _;
let mut tx = conn.begin().await.unwrap();
server_db::schema::apply_migration_sql_and_record_in_tx(
&mut tx,
"20261107092000_atomic_probe",
checksum,
migration_sql,
)
.await
.unwrap();
tx.rollback().await.unwrap();
}
let table_survived: bool = sqlx::query_scalar("SELECT to_regclass('public.atomic_tx_probe') IS NOT NULL")
.fetch_one(&mut conn)
.await
.unwrap();
assert!(
!table_survived,
"DDL inside embedded BEGIN/COMMIT must roll back completely when outer tx rolls back"
);
let ledger_rows: i64 = sqlx::query_scalar(r#"SELECT count(*) FROM "_prisma_migrations""#)
.fetch_one(&mut conn)
.await
.unwrap();
assert_eq!(ledger_rows, 0);
// Retry cleanly and commit: both DDL and `_prisma_migrations` row commit together.
{
use sqlx::Connection as _;
let mut tx = conn.begin().await.unwrap();
server_db::schema::apply_migration_sql_and_record_in_tx(
&mut tx,
"20261107092000_atomic_probe",
checksum,
migration_sql,
)
.await
.unwrap();
tx.commit().await.unwrap();
}
let table_exists: bool = sqlx::query_scalar("SELECT to_regclass('public.atomic_tx_probe') IS NOT NULL")
.fetch_one(&mut conn)
.await
.unwrap();
assert!(table_exists);
let ledger_rows: i64 = sqlx::query_scalar(r#"SELECT count(*) FROM "_prisma_migrations""#)
.fetch_one(&mut conn)
.await
.unwrap();
assert_eq!(ledger_rows, 1);
drop(conn);
db.pool().close().await;
});
}
#[test]
fn tiered_semaphores_timeouts_and_query_scope_counters() {
let cluster = PgCluster::from_env_or_docker().expect("test PG16 cluster");
let empty = EmptyDbGuard::create(&cluster, "runtime");
let rt = test_runtime();
rt.block_on(async {
let mut cfg = DbConfig::new(&empty.url);
cfg.channel = "canary".to_owned();
cfg.role = ServerRole::Graphql;
cfg.max_connections = 6;
cfg.statement_timeout_ms = 200;
cfg.tier_permits = [1, 1, 1, 1];
let db = ServerDb::connect(cfg).await.unwrap();
// 1. Verify per-connection session parameters (`application_name`, `statement_timeout`, `idle_in_transaction_session_timeout`).
{
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let (app_name, stmt_timeout, idle_tx_timeout): (String, String, String) = sqlx::query_as(
"SELECT current_setting('application_name'), \
current_setting('statement_timeout'), \
current_setting('idle_in_transaction_session_timeout')",
)
.fetch_one(conn.as_conn())
.await
.unwrap();
assert_eq!(app_name, "affine:canary:graphql:v2");
assert_eq!(stmt_timeout, "200ms");
assert_eq!(idle_tx_timeout, "10s");
}
// 2. Verify 4-tier Semaphore backpressure: holding InteractiveRead blocks a second
// InteractiveRead until released, while InteractiveWrite proceeds immediately.
{
let held_read = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let write_conn = tokio::time::timeout(
Duration::from_millis(500),
db.acquire_tiered(WorkloadTier::InteractiveWrite),
)
.await
.expect("InteractiveWrite must not be blocked by InteractiveRead permit exhaustion")
.unwrap();
drop(write_conn);
let db_clone = db.clone();
let waiter = tokio::spawn(async move {
let started = Instant::now();
let _conn = db_clone.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
started.elapsed()
});
tokio::time::sleep(Duration::from_millis(120)).await;
drop(held_read);
let waited = waiter.await.unwrap();
assert!(
waited >= Duration::from_millis(100),
"second InteractiveRead should wait for permit release, waited {waited:?}"
);
}
// 3. Verify statement_timeout actually aborts slow pg_sleep with SQLSTATE 57014.
{
let mut conn = db.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let err = sqlx::query("SELECT pg_sleep(1.5)")
.execute(conn.as_conn())
.await
.expect_err("pg_sleep(1.5) must be canceled by 200ms statement_timeout");
assert_eq!(
err.as_database_error().and_then(|d| d.code()).as_deref(),
Some("57014"),
"expected query_canceled (57014), got {err}"
);
}
// 4. Verify with_long_query_timeout locally relaxes statement_timeout inside the transaction
// and automatically counts business queries inside `with_query_scope`.
let (long_ok, long_snap) = with_query_scope(async {
db.with_long_query_timeout(2_500, |tx| {
Box::pin(async move {
sqlx::query("SELECT pg_sleep(0.35)").execute(&mut *tx).await?;
let val: i32 = sqlx::query_scalar("SELECT 42").fetch_one(&mut *tx).await?;
Ok(val)
})
})
.await
.expect("with_long_query_timeout must allow 350ms query")
})
.await;
assert_eq!(long_ok, 42);
assert_eq!(long_snap.pool_acquires, 1);
assert_eq!(long_snap.transactions, 1);
assert_eq!(long_snap.queries, 2);
// Confirm pooled connections still enforce the default 200ms timeout afterward.
{
let mut conn = db.acquire_tiered(WorkloadTier::LongQuery).await.unwrap();
let stmt_timeout: String = sqlx::query_scalar("SHOW statement_timeout")
.fetch_one(conn.as_conn())
.await
.unwrap();
assert_eq!(stmt_timeout, "200ms");
}
// 5. Verify with_query_scope automatic query counting & isolation across concurrent tasks.
let db_a = db.clone();
let db_b = db.clone();
let (res_a, res_b) = tokio::join!(
tokio::spawn(async move {
with_query_scope(async move {
let mut c = db_a.acquire_tiered(WorkloadTier::InteractiveRead).await.unwrap();
let _: i32 = sqlx::query_scalar("SELECT 1").fetch_one(&mut c).await.unwrap();
let _: i32 = sqlx::query_scalar("SELECT 2").fetch_one(&mut c).await.unwrap();
})
.await
.1
}),
tokio::spawn(async move {
with_query_scope(async move {
let mut tx = db_b.begin_tiered(WorkloadTier::InteractiveWrite).await.unwrap();
let _: i32 = sqlx::query_scalar("SELECT 3").fetch_one(&mut tx).await.unwrap();
tx.commit().await.unwrap();
})
.await
.1
}),
);
let snap_a = res_a.unwrap();
let snap_b = res_b.unwrap();
assert_eq!(snap_a.pool_acquires, 1);
assert_eq!(snap_a.transactions, 0);
assert_eq!(snap_a.queries, 2);
assert!(snap_a.assert_within(2, 0, 1).is_ok());
assert_eq!(snap_b.pool_acquires, 1);
assert_eq!(snap_b.transactions, 1);
assert_eq!(snap_b.queries, 1);
assert!(snap_b.assert_within(1, 1, 1).is_ok());
assert!(snap_b.assert_within(0, 1, 1).is_err());
db.pool().close().await;
});
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "server-types"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish.workspace = true
rust-version.workspace = true
[dependencies]
base64.workspace = true
chrono.workspace = true
p256.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[lints]
workspace = true
@@ -0,0 +1 @@
{"claims":{"formatVersion":2,"kid":"community-default-v1","licenseId":"affine-community-default-10s-100g-v1","audience":"affine-selfhost","scope":{"kind":"instance_default","workspaceId":null},"tier":"selfhost_default","limits":{"blobLimitBytes":104857600,"storageQuotaBytes":107374182400,"seatLimit":10,"seatQuotaBytes":null,"historyPeriodSeconds":2592000,"copilotActionLimit":10},"rights":{"commercial":false,"copilotByok":false,"unlimitedCopilot":false},"recurring":null,"issuedAt":"2026-01-01T00:00:00Z","notBefore":"2026-01-01T00:00:00Z","expiresAt":null},"signature":"MEQCIGFfGob5G8dBDn2N51mSzqNaobnPVRghKzUOuX85kk3qAiBw6YK4/X184JRFMACGI/ZoUourIJHJw46qjFqckEY/cQ=="}
+162
View File
@@ -0,0 +1,162 @@
//! Pure canonical domain types and self-hosted license verification for the
//! AFFiNE server workspace.
//!
//! This crate contains no transport frameworks (`axum`, `async-graphql`) and no
//! legacy compatibility aliases.
pub mod license;
use std::{fmt, str::FromStr};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DeploymentMode {
Selfhosted,
Cloud,
}
impl DeploymentMode {
pub const fn as_str(self) -> &'static str {
match self {
Self::Selfhosted => "selfhosted",
Self::Cloud => "cloud",
}
}
}
impl fmt::Display for DeploymentMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServerRole {
Front,
Graphql,
Worker,
Script,
Allinone,
}
impl ServerRole {
pub const fn as_str(self) -> &'static str {
match self {
Self::Front => "front",
Self::Graphql => "graphql",
Self::Worker => "worker",
Self::Script => "script",
Self::Allinone => "allinone",
}
}
}
impl fmt::Display for ServerRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for ServerRole {
type Err = DomainError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"front" => Ok(Self::Front),
"graphql" => Ok(Self::Graphql),
"worker" => Ok(Self::Worker),
"script" => Ok(Self::Script),
"allinone" => Ok(Self::Allinone),
other => Err(DomainError::Validation(format!("unknown server role: {other}"))),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LicenseTier {
CloudFree,
CloudAi,
CloudPro,
CloudTeam,
SelfhostDefault,
SelfhostTeam,
SelfhostEnterprise,
}
impl LicenseTier {
pub const fn as_str(self) -> &'static str {
match self {
Self::CloudFree => "cloud_free",
Self::CloudAi => "cloud_ai",
Self::CloudPro => "cloud_pro",
Self::CloudTeam => "cloud_team",
Self::SelfhostDefault => "selfhost_default",
Self::SelfhostTeam => "selfhost_team",
Self::SelfhostEnterprise => "selfhost_enterprise",
}
}
}
impl fmt::Display for LicenseTier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Limits {
pub blob_limit_bytes: i64,
pub storage_quota_bytes: i64,
pub seat_limit: i32,
pub seat_quota_bytes: Option<i64>,
pub history_period_seconds: i64,
pub copilot_action_limit: Option<i32>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Rights {
pub commercial: bool,
pub copilot_byok: bool,
pub unlimited_copilot: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccessGrant {
pub tier: LicenseTier,
pub seat_quantity: Option<i32>,
pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
pub limits: Limits,
pub rights: Rights,
pub diagnostics: Vec<String>,
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum DomainError {
#[error("unauthorized: {0}")]
Unauthorized(String),
#[error("forbidden: {0}")]
Forbidden(String),
#[error("not found: {0}")]
NotFound(String),
#[error("conflict: {0}")]
Conflict(String),
#[error("quota exceeded ({kind}): {message}")]
QuotaExceeded { kind: &'static str, message: String },
#[error("validation failed: {0}")]
Validation(String),
#[error("precondition failed: {0}")]
PreconditionFailed(String),
#[error("rate limited: {0}")]
RateLimited(String),
#[error("unavailable: {0}")]
Unavailable(String),
#[error("internal error: {0}")]
Internal(String),
}
+674
View File
@@ -0,0 +1,674 @@
//! Canonical `LicenseEnvelopeV2` verification, keyring privilege separation,
//! and bundled default self-hosted grant.
use std::{collections::BTreeMap, sync::OnceLock};
use base64::Engine as _;
use chrono::{DateTime, Utc};
use p256::{
ecdsa::{DerSignature, VerifyingKey, signature::Verifier as _},
pkcs8::DecodePublicKey as _,
};
use serde::{Deserialize, Serialize};
use crate::{AccessGrant, LicenseTier, Limits, Rights};
pub const COMMUNITY_DEFAULT_KID: &str = "community-default-v1";
pub const PRO_KID: &str = "pro-v1";
pub const LICENSE_AUDIENCE_SELFHOST: &str = "affine-selfhost";
pub const MAX_SEAT_LIMIT: i32 = 100_000;
/// Public key for the bundled non-commercial default self-hosted license.
pub const COMMUNITY_DEFAULT_PUBLIC_KEY: &str = "\
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEq3h5nA0kv+Jw1YQmQP+/G0r51oAV
y7eHpKl0eg1/KbtBUZMmOtyo3/dKGl7mPAl/3BdLTcepmArQdirXALJ5Iw==
-----END PUBLIC KEY-----";
/// Pre-signed bundled default self-hosted license (10 seats / 100 GiB / 100 MiB blob / 30d history / 10 copilot actions).
pub const DEFAULT_SELFHOST_LICENSE_BYTES: &[u8] = include_bytes!("../assets/default-selfhost-10s-100g.license.json");
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct LicenseScopeV2 {
pub kind: String,
pub workspace_id: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct LicenseLimitsV2 {
pub blob_limit_bytes: i64,
pub storage_quota_bytes: i64,
pub seat_limit: i32,
pub seat_quota_bytes: Option<i64>,
pub history_period_seconds: i64,
pub copilot_action_limit: Option<i32>,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct LicenseRightsV2 {
pub commercial: bool,
pub copilot_byok: bool,
pub unlimited_copilot: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct LicenseClaimsV2 {
pub format_version: u32,
pub kid: String,
pub license_id: String,
pub audience: String,
pub scope: LicenseScopeV2,
pub tier: String,
pub limits: LicenseLimitsV2,
pub rights: LicenseRightsV2,
pub recurring: Option<String>,
pub issued_at: String,
pub not_before: String,
pub expires_at: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct LicenseEnvelopeV2 {
pub claims: LicenseClaimsV2,
pub signature: String,
}
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum LicenseV2Error {
#[error("invalid license JSON: {0}")]
InvalidJson(String),
#[error("unsupported license format version: {0}")]
UnsupportedFormatVersion(u32),
#[error("unknown license key id: {0}")]
UnknownKeyId(String),
#[error("invalid public key for {kid}: {reason}")]
InvalidPublicKey { kid: String, reason: String },
#[error("invalid license signature: {0}")]
InvalidSignature(String),
#[error("invalid license claims: {0}")]
InvalidClaims(String),
#[error("license workspace scope mismatch: expected {expected:?}, got {actual:?}")]
ScopeMismatch {
expected: Option<String>,
actual: Option<String>,
},
#[error("license not yet valid: not_before={not_before}, now={now}")]
NotYetValid {
not_before: DateTime<Utc>,
now: DateTime<Utc>,
},
#[error("license expired: expires_at={expires_at}, now={now}")]
Expired {
expires_at: DateTime<Utc>,
now: DateTime<Utc>,
},
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VerifiedLicenseV2 {
pub claims: LicenseClaimsV2,
pub tier: LicenseTier,
pub issued_at: DateTime<Utc>,
pub not_before: DateTime<Utc>,
pub expires_at: Option<DateTime<Utc>>,
}
impl VerifiedLicenseV2 {
pub fn to_access_grant(&self) -> AccessGrant {
let copilot_action_limit = if self.claims.rights.unlimited_copilot {
None
} else {
self.claims.limits.copilot_action_limit
};
AccessGrant {
tier: self.tier,
seat_quantity: Some(self.claims.limits.seat_limit),
expires_at: self.expires_at,
limits: Limits {
blob_limit_bytes: self.claims.limits.blob_limit_bytes,
storage_quota_bytes: self.claims.limits.storage_quota_bytes,
seat_limit: self.claims.limits.seat_limit,
seat_quota_bytes: self.claims.limits.seat_quota_bytes,
history_period_seconds: self.claims.limits.history_period_seconds,
copilot_action_limit,
},
rights: Rights {
commercial: self.claims.rights.commercial,
copilot_byok: self.claims.rights.copilot_byok,
unlimited_copilot: self.claims.rights.unlimited_copilot,
},
diagnostics: Vec::new(),
}
}
pub fn into_access_grant(self) -> AccessGrant {
self.to_access_grant()
}
}
#[derive(Clone, Debug)]
pub struct Keyring {
keys: BTreeMap<String, String>,
}
impl Default for Keyring {
fn default() -> Self {
Self::new()
}
}
impl Keyring {
/// Builds the default keyring with `community-default-v1` and, when set at
/// compile time, `pro-v1` from `option_env!("AFFINE_PRO_PUBLIC_KEY")`.
pub fn new() -> Self {
let mut keys = BTreeMap::new();
keys.insert(
COMMUNITY_DEFAULT_KID.to_owned(),
COMMUNITY_DEFAULT_PUBLIC_KEY.to_owned(),
);
if let Some(pro_pem) = option_env!("AFFINE_PRO_PUBLIC_KEY") {
let trimmed = pro_pem.trim();
if !trimmed.is_empty() {
keys.insert(PRO_KID.to_owned(), trimmed.to_owned());
}
}
Self { keys }
}
/// Builds a keyring with `community-default-v1` plus an explicit `pro-v1` PEM public key.
pub fn with_pro_public_key(pro_public_key_pem: impl Into<String>) -> Self {
let mut ring = Self::new();
ring.keys.insert(PRO_KID.to_owned(), pro_public_key_pem.into());
ring
}
/// Inserts or replaces a `kid` entry in the keyring (tests only).
#[cfg(test)]
pub fn with_key(mut self, kid: impl Into<String>, public_key_pem: impl Into<String>) -> Self {
self.keys.insert(kid.into(), public_key_pem.into());
self
}
pub fn get(&self, kid: &str) -> Option<&str> {
self.keys.get(kid).map(String::as_str)
}
}
pub fn verify_license_v2(
payload: &[u8],
keyring: &Keyring,
expected_workspace_id: Option<&str>,
now: DateTime<Utc>,
) -> Result<VerifiedLicenseV2, LicenseV2Error> {
let envelope: LicenseEnvelopeV2 =
serde_json::from_slice(payload).map_err(|e| LicenseV2Error::InvalidJson(e.to_string()))?;
let claims = &envelope.claims;
if claims.format_version != 2 {
return Err(LicenseV2Error::UnsupportedFormatVersion(claims.format_version));
}
if claims.license_id.trim().is_empty() {
return Err(LicenseV2Error::InvalidClaims("licenseId must be non-empty".to_owned()));
}
if claims.audience != LICENSE_AUDIENCE_SELFHOST {
return Err(LicenseV2Error::InvalidClaims(format!(
"invalid audience {:?}, expected {:?}",
claims.audience, LICENSE_AUDIENCE_SELFHOST
)));
}
if claims.kid != COMMUNITY_DEFAULT_KID && claims.kid != PRO_KID {
return Err(LicenseV2Error::UnknownKeyId(claims.kid.clone()));
}
let public_key_pem = keyring
.get(&claims.kid)
.ok_or_else(|| LicenseV2Error::UnknownKeyId(claims.kid.clone()))?;
// Hard privilege separation for community-default-v1.
if claims.kid == COMMUNITY_DEFAULT_KID {
let allowed = claims.scope.kind == "instance_default"
&& claims.scope.workspace_id.is_none()
&& claims.tier == "selfhost_default"
&& !claims.rights.commercial
&& !claims.rights.copilot_byok
&& !claims.rights.unlimited_copilot;
if !allowed {
return Err(LicenseV2Error::InvalidClaims(
"community-default-v1 key may only sign non-commercial instance_default selfhost_default licenses".to_owned(),
));
}
}
let tier = match claims.tier.as_str() {
"selfhost_default" => LicenseTier::SelfhostDefault,
"selfhost_team" => LicenseTier::SelfhostTeam,
"selfhost_enterprise" => LicenseTier::SelfhostEnterprise,
other => {
return Err(LicenseV2Error::InvalidClaims(format!(
"unsupported selfhost license tier: {other:?}"
)));
}
};
match claims.scope.kind.as_str() {
"instance_default" => {
if claims.scope.workspace_id.is_some() {
return Err(LicenseV2Error::InvalidClaims(
"instance_default scope must not specify workspaceId".to_owned(),
));
}
}
"workspace" => {
if claims.kid == PRO_KID && !matches!(claims.tier.as_str(), "selfhost_team" | "selfhost_enterprise") {
return Err(LicenseV2Error::InvalidClaims(format!(
"workspace scope under {PRO_KID} requires tier \"selfhost_team\" or \"selfhost_enterprise\", got {:?}",
claims.tier
)));
}
let ws = claims
.scope
.workspace_id
.as_deref()
.filter(|id| !id.trim().is_empty())
.ok_or_else(|| LicenseV2Error::InvalidClaims("workspace scope requires a non-empty workspaceId".to_owned()))?;
if expected_workspace_id != Some(ws) {
return Err(LicenseV2Error::ScopeMismatch {
expected: expected_workspace_id.map(str::to_owned),
actual: Some(ws.to_owned()),
});
}
}
other => {
return Err(LicenseV2Error::InvalidClaims(format!(
"unsupported scope kind: {other:?}"
)));
}
}
validate_limits(&claims.limits)?;
if let Some(recurring) = claims.recurring.as_deref()
&& !matches!(recurring, "monthly" | "yearly" | "lifetime")
{
return Err(LicenseV2Error::InvalidClaims(format!(
"invalid recurring interval: {recurring:?}"
)));
}
let issued_at = parse_rfc3339("issuedAt", &claims.issued_at)?;
let not_before = parse_rfc3339("notBefore", &claims.not_before)?;
let expires_at = claims
.expires_at
.as_deref()
.map(|raw| parse_rfc3339("expiresAt", raw))
.transpose()?;
if not_before > issued_at {
return Err(LicenseV2Error::InvalidClaims(
"notBefore must be <= issuedAt".to_owned(),
));
}
if let Some(exp) = expires_at {
if issued_at >= exp {
return Err(LicenseV2Error::InvalidClaims("issuedAt must be < expiresAt".to_owned()));
}
if now >= exp {
return Err(LicenseV2Error::Expired { expires_at: exp, now });
}
}
if now < not_before {
return Err(LicenseV2Error::NotYetValid { not_before, now });
}
// Verify ECDSA P-256 SHA-256 ASN.1 DER signature over canonical struct serialization.
let verifying_key =
VerifyingKey::from_public_key_pem(public_key_pem).map_err(|e| LicenseV2Error::InvalidPublicKey {
kid: claims.kid.clone(),
reason: e.to_string(),
})?;
let canonical =
serde_json::to_vec(claims).map_err(|e| LicenseV2Error::InvalidJson(format!("claims re-serialization: {e}")))?;
let sig_bytes = base64::engine::general_purpose::STANDARD
.decode(&envelope.signature)
.map_err(|e| LicenseV2Error::InvalidSignature(format!("base64 decode failed: {e}")))?;
let sig = DerSignature::from_bytes(&sig_bytes)
.map_err(|e| LicenseV2Error::InvalidSignature(format!("invalid DER signature: {e}")))?;
verifying_key
.verify(&canonical, &sig)
.map_err(|e| LicenseV2Error::InvalidSignature(e.to_string()))?;
Ok(VerifiedLicenseV2 {
claims: envelope.claims,
tier,
issued_at,
not_before,
expires_at,
})
}
fn validate_limits(limits: &LicenseLimitsV2) -> Result<(), LicenseV2Error> {
if !(1..=MAX_SEAT_LIMIT).contains(&limits.seat_limit) {
return Err(LicenseV2Error::InvalidClaims(format!(
"seatLimit {} out of allowed range 1..={MAX_SEAT_LIMIT}",
limits.seat_limit
)));
}
if limits.blob_limit_bytes <= 0 {
return Err(LicenseV2Error::InvalidClaims(format!(
"blobLimitBytes must be > 0, got {}",
limits.blob_limit_bytes
)));
}
if limits.storage_quota_bytes <= 0 {
return Err(LicenseV2Error::InvalidClaims(format!(
"storageQuotaBytes must be > 0, got {}",
limits.storage_quota_bytes
)));
}
if let Some(seat_quota_bytes) = limits.seat_quota_bytes
&& seat_quota_bytes < 0
{
return Err(LicenseV2Error::InvalidClaims(format!(
"seatQuotaBytes must be >= 0, got {seat_quota_bytes}"
)));
}
if limits.history_period_seconds < 0 {
return Err(LicenseV2Error::InvalidClaims(format!(
"historyPeriodSeconds must be >= 0, got {}",
limits.history_period_seconds
)));
}
if let Some(copilot_action_limit) = limits.copilot_action_limit
&& copilot_action_limit < 0
{
return Err(LicenseV2Error::InvalidClaims(format!(
"copilotActionLimit must be >= 0, got {copilot_action_limit}"
)));
}
Ok(())
}
fn parse_rfc3339(field: &str, value: &str) -> Result<DateTime<Utc>, LicenseV2Error> {
DateTime::parse_from_rfc3339(value)
.map(|dt| dt.with_timezone(&Utc))
.map_err(|e| LicenseV2Error::InvalidClaims(format!("invalid {field} RFC3339 timestamp {value:?}: {e}")))
}
/// Returns the default self-hosted `AccessGrant` by verifying the bundled signed
/// default license once at its fixed baseline epoch (`2026-01-01T00:00:00Z`).
/// If verification ever fails, fails closed to a 0-seat read-only grant with an
/// actionable diagnostic.
pub fn default_selfhost_access_grant() -> AccessGrant {
static BUNDLED_DEFAULT: OnceLock<AccessGrant> = OnceLock::new();
BUNDLED_DEFAULT
.get_or_init(|| {
let baseline_epoch = DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
.expect("static RFC3339 baseline epoch")
.with_timezone(&Utc);
default_selfhost_access_grant_from(DEFAULT_SELFHOST_LICENSE_BYTES, &Keyring::new(), baseline_epoch)
})
.clone()
}
pub fn default_selfhost_access_grant_from(payload: &[u8], keyring: &Keyring, now: DateTime<Utc>) -> AccessGrant {
match verify_license_v2(payload, keyring, None, now) {
Ok(verified) => verified.into_access_grant(),
Err(err) => AccessGrant {
tier: LicenseTier::SelfhostDefault,
seat_quantity: Some(0),
expires_at: None,
limits: Limits {
blob_limit_bytes: 0,
storage_quota_bytes: 0,
seat_limit: 0,
seat_quota_bytes: None,
history_period_seconds: 0,
copilot_action_limit: Some(0),
},
rights: Rights {
commercial: false,
copilot_byok: false,
unlimited_copilot: false,
},
diagnostics: vec![format!("bundled default selfhost license verification failed: {err}")],
},
}
}
#[cfg(test)]
mod tests {
use p256::{
ecdsa::{SigningKey, signature::Signer as _},
pkcs8::{EncodePublicKey as _, LineEnding},
};
use super::*;
fn fixed_now() -> DateTime<Utc> {
DateTime::parse_from_rfc3339("2026-06-01T00:00:00Z")
.unwrap()
.with_timezone(&Utc)
}
fn test_pro_keypair(seed: u8) -> (SigningKey, String) {
let signing_key = SigningKey::from_slice(&[seed; 32]).unwrap();
let pem = VerifyingKey::from(&signing_key)
.to_public_key_pem(LineEnding::LF)
.unwrap();
(signing_key, pem)
}
fn sign_claims(claims: &LicenseClaimsV2, signing_key: &SigningKey) -> Vec<u8> {
let canonical = serde_json::to_vec(claims).unwrap();
let sig: DerSignature = signing_key.sign(&canonical);
let envelope = LicenseEnvelopeV2 {
claims: claims.clone(),
signature: base64::engine::general_purpose::STANDARD.encode(sig.as_bytes()),
};
serde_json::to_vec(&envelope).unwrap()
}
fn sample_pro_workspace_claims(workspace_id: &str, tier: &str, seats: i32) -> LicenseClaimsV2 {
LicenseClaimsV2 {
format_version: 2,
kid: PRO_KID.to_owned(),
license_id: format!("lic-{workspace_id}-{tier}-{seats}"),
audience: LICENSE_AUDIENCE_SELFHOST.to_owned(),
scope: LicenseScopeV2 {
kind: "workspace".to_owned(),
workspace_id: Some(workspace_id.to_owned()),
},
tier: tier.to_owned(),
limits: LicenseLimitsV2 {
blob_limit_bytes: 524_288_000,
storage_quota_bytes: 1_099_511_627_776,
seat_limit: seats,
seat_quota_bytes: Some(10_737_418_240),
history_period_seconds: 31_536_000,
copilot_action_limit: Some(500),
},
rights: LicenseRightsV2 {
commercial: true,
copilot_byok: true,
unlimited_copilot: true,
},
recurring: Some("yearly".to_owned()),
issued_at: "2026-01-01T00:00:00Z".to_owned(),
not_before: "2026-01-01T00:00:00Z".to_owned(),
expires_at: Some("2027-01-01T00:00:00Z".to_owned()),
}
}
#[test]
fn bundled_default_license_verifies_and_matches_contract() {
let keyring = Keyring::new();
let verified = verify_license_v2(DEFAULT_SELFHOST_LICENSE_BYTES, &keyring, None, fixed_now())
.expect("bundled default license must verify against COMMUNITY_DEFAULT_PUBLIC_KEY");
assert_eq!(verified.tier, LicenseTier::SelfhostDefault);
let grant = verified.into_access_grant();
assert_eq!(grant.tier, LicenseTier::SelfhostDefault);
assert_eq!(grant.seat_quantity, Some(10));
assert_eq!(grant.limits.seat_limit, 10);
assert_eq!(grant.limits.blob_limit_bytes, 104_857_600);
assert_eq!(grant.limits.storage_quota_bytes, 107_374_182_400);
assert_eq!(grant.limits.history_period_seconds, 2_592_000);
assert_eq!(grant.limits.copilot_action_limit, Some(10));
assert!(!grant.rights.commercial);
assert!(!grant.rights.copilot_byok);
assert!(!grant.rights.unlimited_copilot);
assert!(grant.diagnostics.is_empty());
let default_grant = default_selfhost_access_grant();
assert_eq!(default_grant, grant);
}
#[test]
fn default_grant_fails_closed_when_bundled_verification_fails() {
let grant = default_selfhost_access_grant_from(b"{}", &Keyring::new(), fixed_now());
assert_eq!(grant.tier, LicenseTier::SelfhostDefault);
assert_eq!(grant.seat_quantity, Some(0));
assert_eq!(grant.limits.seat_limit, 0);
assert_eq!(grant.limits.blob_limit_bytes, 0);
assert_eq!(grant.limits.storage_quota_bytes, 0);
assert_eq!(grant.limits.copilot_action_limit, Some(0));
assert!(!grant.rights.commercial);
assert_eq!(grant.diagnostics.len(), 1);
}
#[test]
fn pro_v1_workspace_and_instance_licenses_verify_and_enforce_invariants() {
let (signing_key, pro_pem) = test_pro_keypair(0x42);
let keyring = Keyring::with_pro_public_key(&pro_pem);
let ws_claims = sample_pro_workspace_claims("ws-1", "selfhost_team", 25);
let ws_raw = sign_claims(&ws_claims, &signing_key);
let verified = verify_license_v2(&ws_raw, &keyring, Some("ws-1"), fixed_now()).unwrap();
let grant = verified.into_access_grant();
assert_eq!(grant.tier, LicenseTier::SelfhostTeam);
assert_eq!(grant.limits.seat_limit, 25);
assert_eq!(grant.limits.copilot_action_limit, None); // unlimited_copilot => None
// workspace scope with selfhost_default tier under pro-v1 must be rejected.
let mut ws_default_tier = ws_claims.clone();
ws_default_tier.tier = "selfhost_default".to_owned();
let ws_default_raw = sign_claims(&ws_default_tier, &signing_key);
assert!(matches!(
verify_license_v2(&ws_default_raw, &keyring, Some("ws-1"), fixed_now()),
Err(LicenseV2Error::InvalidClaims(_))
));
// Scope mismatch rejected.
assert!(matches!(
verify_license_v2(&ws_raw, &keyring, Some("ws-other"), fixed_now()),
Err(LicenseV2Error::ScopeMismatch { .. })
));
assert!(matches!(
verify_license_v2(&ws_raw, &keyring, None, fixed_now()),
Err(LicenseV2Error::ScopeMismatch { .. })
));
// Negative seat_quota_bytes rejected.
let mut neg_quota = ws_claims.clone();
neg_quota.limits.seat_quota_bytes = Some(-1);
let neg_raw = sign_claims(&neg_quota, &signing_key);
assert!(matches!(
verify_license_v2(&neg_raw, &keyring, Some("ws-1"), fixed_now()),
Err(LicenseV2Error::InvalidClaims(_))
));
// Commercial instance_default allowed under pro-v1.
let mut inst_claims = ws_claims.clone();
inst_claims.scope = LicenseScopeV2 {
kind: "instance_default".to_owned(),
workspace_id: None,
};
inst_claims.tier = "selfhost_enterprise".to_owned();
let inst_raw = sign_claims(&inst_claims, &signing_key);
let verified_inst = verify_license_v2(&inst_raw, &keyring, None, fixed_now()).unwrap();
assert_eq!(verified_inst.tier, LicenseTier::SelfhostEnterprise);
}
#[test]
fn community_default_kid_cannot_authorize_commercial_or_workspace() {
let (signing_key, pem) = test_pro_keypair(0x55);
let keyring = Keyring::new().with_key(COMMUNITY_DEFAULT_KID, pem);
let mut commercial = sample_pro_workspace_claims("ws-1", "selfhost_team", 50);
commercial.kid = COMMUNITY_DEFAULT_KID.to_owned();
let raw = sign_claims(&commercial, &signing_key);
assert!(matches!(
verify_license_v2(&raw, &keyring, Some("ws-1"), fixed_now()),
Err(LicenseV2Error::InvalidClaims(_))
));
let mut byok = LicenseClaimsV2 {
format_version: 2,
kid: COMMUNITY_DEFAULT_KID.to_owned(),
license_id: "fake-byok".to_owned(),
audience: LICENSE_AUDIENCE_SELFHOST.to_owned(),
scope: LicenseScopeV2 {
kind: "instance_default".to_owned(),
workspace_id: None,
},
tier: "selfhost_default".to_owned(),
limits: LicenseLimitsV2 {
blob_limit_bytes: 1024,
storage_quota_bytes: 2048,
seat_limit: 10,
seat_quota_bytes: None,
history_period_seconds: 0,
copilot_action_limit: Some(10),
},
rights: LicenseRightsV2 {
commercial: false,
copilot_byok: true,
unlimited_copilot: false,
},
recurring: None,
issued_at: "2026-01-01T00:00:00Z".to_owned(),
not_before: "2026-01-01T00:00:00Z".to_owned(),
expires_at: None,
};
let byok_raw = sign_claims(&byok, &signing_key);
assert!(matches!(
verify_license_v2(&byok_raw, &keyring, None, fixed_now()),
Err(LicenseV2Error::InvalidClaims(_))
));
byok.rights.copilot_byok = false;
byok.rights.unlimited_copilot = true;
let unlimited_raw = sign_claims(&byok, &signing_key);
assert!(matches!(
verify_license_v2(&unlimited_raw, &keyring, None, fixed_now()),
Err(LicenseV2Error::InvalidClaims(_))
));
}
#[test]
fn rejects_duplicate_json_fields_and_unknown_fields() {
let keyring = Keyring::new();
let dup_top = br#"{"claims":{},"claims":{},"signature":"AA=="}"#;
assert!(matches!(
verify_license_v2(dup_top, &keyring, None, fixed_now()),
Err(LicenseV2Error::InvalidJson(_))
));
let raw_str = std::str::from_utf8(DEFAULT_SELFHOST_LICENSE_BYTES).unwrap();
let dup_nested = raw_str.replacen(r#""seatLimit":10"#, r#""seatLimit":10,"seatLimit":999"#, 1);
assert!(matches!(
verify_license_v2(dup_nested.as_bytes(), &keyring, None, fixed_now()),
Err(LicenseV2Error::InvalidJson(_))
));
let unknown_field = raw_str.replacen(r#""seatLimit":10"#, r#""seatLimit":10,"extra":1"#, 1);
assert!(matches!(
verify_license_v2(unknown_field.as_bytes(), &keyring, None, fixed_now()),
Err(LicenseV2Error::InvalidJson(_))
));
}
}