diff --git a/crates/AGENTS.md b/crates/AGENTS.md index 11985783fd..15b85b2e07 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -12,6 +12,8 @@ - Redis: an explicit `AFFINE_TEST_REDIS_URL` isolated by the `test::` 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=`. `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`. +- `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:::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. diff --git a/crates/Cargo.lock b/crates/Cargo.lock index 93d2a4aac7..950b8a02ba 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -10,20 +25,50 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "block-buffer" @@ -61,6 +106,16 @@ version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -75,7 +130,19 @@ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.1", - "rand_core", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", ] [[package]] @@ -84,12 +151,24 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -108,6 +187,48 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -136,6 +257,17 @@ dependencies = [ "cmov", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -143,7 +275,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -153,17 +287,156 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + [[package]] name = "fallible-iterator" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + [[package]] name = "frame-audit" version = "0.1.0" @@ -188,6 +461,45 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -207,8 +519,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", + "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -221,6 +536,18 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", ] [[package]] @@ -232,7 +559,74 @@ dependencies = [ "cfg-if", "libc", "r-efi", - "rand_core", + "rand_core 0.10.1", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac 0.12.1", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", ] [[package]] @@ -244,6 +638,15 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "hybrid-array" version = "0.4.15" @@ -253,6 +656,144 @@ dependencies = [ "typenum", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + [[package]] name = "itoa" version = "1.0.19" @@ -270,21 +811,55 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ + "bitflags", "libc", + "plain", + "redox_syscall 0.9.5", ] +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "lock_api" version = "0.4.14" @@ -300,6 +875,16 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + [[package]] name = "md-5" version = "0.11.0" @@ -324,7 +909,52 @@ checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", ] [[package]] @@ -345,6 +975,30 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -363,11 +1017,20 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", "smallvec", "windows-link", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -399,6 +1062,39 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + [[package]] name = "postgres" version = "0.19.14" @@ -423,10 +1119,10 @@ dependencies = [ "byteorder", "bytes", "fallible-iterator", - "hmac", - "md-5", + "hmac 0.13.0", + "md-5 0.11.0", "memchr", - "rand", + "rand 0.10.4", "sha2 0.11.1", "stringprep", ] @@ -442,6 +1138,33 @@ dependencies = [ "postgres-protocol", ] +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -466,6 +1189,17 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.10.4" @@ -473,8 +1207,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", - "getrandom", - "rand_core", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", ] [[package]] @@ -492,18 +1245,125 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "serde" version = "1.0.229" @@ -531,7 +1391,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -547,6 +1407,58 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "server-db" +version = "0.1.0" +dependencies = [ + "chrono", + "futures-util", + "postgres", + "serde", + "server-types", + "sha2 0.10.9", + "sqlx", + "test-db-harness", + "thiserror", + "tokio", + "uuid", +] + +[[package]] +name = "server-types" +version = "0.1.0" +dependencies = [ + "base64", + "chrono", + "p256", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.10.9" @@ -569,6 +1481,32 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -586,6 +1524,9 @@ name = "smallvec" version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] [[package]] name = "socket2" @@ -594,9 +1535,232 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2 0.10.9", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "chrono", + "crc", + "digest 0.10.7", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac 0.12.1", + "itoa", + "log", + "md-5 0.10.6", + "memchr", + "once_cell", + "percent-encoding", + "rand 0.8.8", + "rsa", + "serde", + "sha1", + "sha2 0.10.9", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami 1.6.1", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac 0.12.1", + "home", + "itoa", + "log", + "md-5 0.10.6", + "memchr", + "once_cell", + "rand 0.8.8", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami 1.6.1", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "stringprep" version = "0.1.5" @@ -608,6 +1772,23 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -619,6 +1800,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "test-db-harness" version = "0.1.0" @@ -629,6 +1821,36 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinyvec" version = "1.13.3" @@ -645,8 +1867,21 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", - "windows-sys", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] @@ -668,11 +1903,22 @@ dependencies = [ "pin-project-lite", "postgres-protocol", "postgres-types", - "rand", + "rand 0.10.4", "socket2", "tokio", "tokio-util", - "whoami", + "whoami 2.1.3", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", ] [[package]] @@ -689,6 +1935,38 @@ dependencies = [ "tokio", ] +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + [[package]] name = "typenum" version = "1.20.1" @@ -722,6 +2000,57 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -752,6 +2081,12 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + [[package]] name = "wasite" version = "1.0.2" @@ -792,7 +2127,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -815,6 +2150,34 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite 0.1.0", +] + [[package]] name = "whoami" version = "2.1.3" @@ -824,16 +2187,87 @@ dependencies = [ "libc", "libredox", "objc2-system-configuration", - "wasite", + "wasite 1.0.2", "web-sys", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -843,12 +2277,242 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/Cargo.toml b/crates/Cargo.toml index 860f36ad97..24fac8ebbc 100644 --- a/crates/Cargo.toml +++ b/crates/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["frame-audit", "test-db-harness"] +members = ["frame-audit", "test-db-harness", "server-types", "server-db"] resolver = "3" [workspace.package] @@ -9,10 +9,23 @@ publish = false rust-version = "1.88" [workspace.dependencies] -postgres = "0.19" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sha2 = "0.10" +base64 = "0.22" +chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] } +futures-util = "0.3" +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] unsafe_code = "forbid" diff --git a/crates/server-db/Cargo.toml b/crates/server-db/Cargo.toml new file mode 100644 index 0000000000..27a313d6fb --- /dev/null +++ b/crates/server-db/Cargo.toml @@ -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 diff --git a/crates/server-db/build.rs b/crates/server-db/build.rs new file mode 100644 index 0000000000..fb5ef40e5e --- /dev/null +++ b/crates/server-db/build.rs @@ -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 +} diff --git a/crates/server-db/src/error.rs b/crates/server-db/src/error.rs new file mode 100644 index 0000000000..d5371eff74 --- /dev/null +++ b/crates/server-db/src/error.rs @@ -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, + message: String, + }, + #[error("schema readiness check failed: {0}")] + SchemaCheck(String), +} diff --git a/crates/server-db/src/lib.rs b/crates/server-db/src/lib.rs new file mode 100644 index 0000000000..6927eba9cf --- /dev/null +++ b/crates/server-db/src/lib.rs @@ -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) -> 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; 4], +} + +#[derive(Clone)] +pub struct ServerDb { + inner: Arc, +} + +/// 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, + _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, 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, 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, sqlx::Error>> + where + 'c: 'e, + { + (&mut *self.conn).prepare_with(sql, parameters) + } + + fn describe<'e, 'q: 'e>(self, sql: &'q str) -> BoxFuture<'e, Result, 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, 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, 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, sqlx::Error>> + where + 'c: 'e, + { + (&mut *self.tx).prepare_with(sql, parameters) + } + + fn describe<'e, 'q: 'e>(self, sql: &'q str) -> BoxFuture<'e, Result, sqlx::Error>> + where + 'c: 'e, + { + (&mut *self.tx).describe(sql) + } +} + +impl ServerDb { + pub async fn connect(config: DbConfig) -> Result { + 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 { + 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, 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 = '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(&self, timeout_ms: u64, f: F) -> Result + where + F: for<'a, 'b> FnOnce(&'a mut TieredTx<'b>) -> Pin> + 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 { + 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 { + schema::ensure_schema_ready_impl(self).await + } +} diff --git a/crates/server-db/src/metrics.rs b/crates/server-db/src/metrics.rs new file mode 100644 index 0000000000..642f790ae3 --- /dev/null +++ b/crates/server-db/src/metrics.rs @@ -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; +} + +/// 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(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 { + QUERY_SCOPE.try_with(|c| c.snapshot()).ok() +} diff --git a/crates/server-db/src/phase_a_compat/mod.rs b/crates/server-db/src/phase_a_compat/mod.rs new file mode 100644 index 0000000000..35a7604905 --- /dev/null +++ b/crates/server-db/src/phase_a_compat/mod.rs @@ -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 { + 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 { + 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 { + 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, + }) +} diff --git a/crates/server-db/src/schema.rs b/crates/server-db/src/schema.rs new file mode 100644 index 0000000000..814f0d4265 --- /dev/null +++ b/crates/server-db/src/schema.rs @@ -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 = 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 { + 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 { + 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 = 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::>() + } else { + BUNDLED_PRISMA_MIGRATIONS + .iter() + .map(|m| m.name.to_owned()) + .collect::>() + }; + + 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::>() + .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 { + 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 = 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$;")); + } +} diff --git a/crates/server-db/tests/pg_integration.rs b/crates/server-db/tests/pg_integration.rs new file mode 100644 index 0000000000..9053c1655c --- /dev/null +++ b/crates/server-db/tests/pg_integration.rs @@ -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; + }); +} diff --git a/crates/server-types/Cargo.toml b/crates/server-types/Cargo.toml new file mode 100644 index 0000000000..fc91b78ce0 --- /dev/null +++ b/crates/server-types/Cargo.toml @@ -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 diff --git a/crates/server-types/assets/default-selfhost-10s-100g.license.json b/crates/server-types/assets/default-selfhost-10s-100g.license.json new file mode 100644 index 0000000000..c4442caec9 --- /dev/null +++ b/crates/server-types/assets/default-selfhost-10s-100g.license.json @@ -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=="} \ No newline at end of file diff --git a/crates/server-types/src/lib.rs b/crates/server-types/src/lib.rs new file mode 100644 index 0000000000..1d95ca5dfb --- /dev/null +++ b/crates/server-types/src/lib.rs @@ -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 { + 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, + pub history_period_seconds: i64, + pub copilot_action_limit: Option, +} + +#[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, + pub expires_at: Option>, + pub limits: Limits, + pub rights: Rights, + pub diagnostics: Vec, +} + +#[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), +} diff --git a/crates/server-types/src/license.rs b/crates/server-types/src/license.rs new file mode 100644 index 0000000000..f4b715b33a --- /dev/null +++ b/crates/server-types/src/license.rs @@ -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, +} + +#[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, + pub history_period_seconds: i64, + pub copilot_action_limit: Option, +} + +#[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, + pub issued_at: String, + pub not_before: String, + pub expires_at: Option, +} + +#[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, + actual: Option, + }, + #[error("license not yet valid: not_before={not_before}, now={now}")] + NotYetValid { + not_before: DateTime, + now: DateTime, + }, + #[error("license expired: expires_at={expires_at}, now={now}")] + Expired { + expires_at: DateTime, + now: DateTime, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct VerifiedLicenseV2 { + pub claims: LicenseClaimsV2, + pub tier: LicenseTier, + pub issued_at: DateTime, + pub not_before: DateTime, + pub expires_at: Option>, +} + +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, +} + +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) -> 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, public_key_pem: impl Into) -> 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, +) -> Result { + 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, 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 = 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) -> 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 { + 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 { + 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(_)) + )); + } +}