From 807a02e0813c1c76ff08afddd0149bcceccdfbd6 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 00:23:48 +0800 Subject: [PATCH 01/13] Implement Bedrock SQL persistence backends --- .gitea/workflows/sql.yml | 14 + .gitignore | 2 + Cargo.lock | 1912 +++++++++++++++++++++++++ Cargo.toml | 29 +- README.md | 26 + ci/check-sql.sh | 49 + crates/clusters/Cargo.toml | 10 + crates/clusters/src/lib.rs | 272 ++++ crates/db_connection/Cargo.toml | 19 + crates/db_connection/src/lib.rs | 143 ++ crates/db_connection/tests/storage.rs | 272 ++++ crates/mysql/Cargo.toml | 9 + crates/mysql/src/lib.rs | 211 +++ crates/persistence/Cargo.toml | 10 + crates/persistence/src/lib.rs | 386 +++++ crates/postgres/Cargo.toml | 9 + crates/postgres/src/lib.rs | 40 + crates/sqlite/Cargo.toml | 9 + crates/sqlite/src/lib.rs | 41 + src/main.rs | 20 +- 20 files changed, 3480 insertions(+), 3 deletions(-) create mode 100644 .gitea/workflows/sql.yml create mode 100644 README.md create mode 100644 ci/check-sql.sh create mode 100644 crates/clusters/Cargo.toml create mode 100644 crates/clusters/src/lib.rs create mode 100644 crates/db_connection/Cargo.toml create mode 100644 crates/db_connection/src/lib.rs create mode 100644 crates/db_connection/tests/storage.rs create mode 100644 crates/mysql/Cargo.toml create mode 100644 crates/mysql/src/lib.rs create mode 100644 crates/persistence/Cargo.toml create mode 100644 crates/persistence/src/lib.rs create mode 100644 crates/postgres/Cargo.toml create mode 100644 crates/postgres/src/lib.rs create mode 100644 crates/sqlite/Cargo.toml create mode 100644 crates/sqlite/src/lib.rs diff --git a/.gitea/workflows/sql.yml b/.gitea/workflows/sql.yml new file mode 100644 index 0000000..fae370a --- /dev/null +++ b/.gitea/workflows/sql.yml @@ -0,0 +1,14 @@ +name: Bedrock SQL storage + +on: + push: + pull_request: + +jobs: + sql: + runs-on: ces-control + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - name: Compile and test SQLite, PostgreSQL and MySQL + run: bash ci/check-sql.sh diff --git a/.gitignore b/.gitignore index ea8c4bf..5d04868 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /target +/bedrock.sqlite3 +/bedrock.sqlite3-* diff --git a/Cargo.lock b/Cargo.lock index e0b6f7c..fb16ff8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,1918 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "allocator-api2" +version = "0.2.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" + +[[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 = "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 = "bedrock" version = "0.1.0" +dependencies = [ + "db_connection", + "serde_json", + "tokio", +] + +[[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" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clusters" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror", + "url", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +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-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "db_connection" +version = "0.1.0" +dependencies = [ + "clusters", + "mysql", + "persistence", + "postgres", + "serde_json", + "sqlite", + "sqlx", + "tempfile", + "thiserror", + "tokio", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[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 = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[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 = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[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 = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +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-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[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", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[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 = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +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", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "mysql" +version = "0.1.0" +dependencies = [ + "persistence", + "sqlx", +] + +[[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", + "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]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "persistence" +version = "0.1.0" +dependencies = [ + "serde_json", + "sqlx", + "thiserror", +] + +[[package]] +name = "pin-project-lite" +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.1.0" +dependencies = [ + "persistence", + "sqlx", +] + +[[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 = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +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", +] + +[[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", +] + +[[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]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +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 = "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", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[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 = "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 = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "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 = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "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 = "sqlite" +version = "0.1.0" +dependencies = [ + "persistence", + "sqlx", +] + +[[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", + "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", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "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", + "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", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[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", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "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 = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "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]] +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]] +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[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", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +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 = "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.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 7546666..533566c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,33 @@ +[workspace] +members = ["crates/*"] +resolver = "3" + +[workspace.package] +edition = "2024" +rust-version = "1.91" + +[workspace.dependencies] +clusters = { path = "crates/clusters" } +db_connection = { path = "crates/db_connection" } +persistence = { path = "crates/persistence" } +sqlite = { path = "crates/sqlite" } +postgres = { path = "crates/postgres" } +mysql = { path = "crates/mysql" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } +tempfile = "3" +thiserror = "2" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +url = "2" + [package] name = "bedrock" version = "0.1.0" -edition = "2024" +edition.workspace = true +rust-version.workspace = true [dependencies] +db_connection.workspace = true +serde_json.workspace = true +tokio.workspace = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..2d1b1d4 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# Bedrock storage + +Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. + +Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example: + +```json +{ + "deployment": "production", + "cluster": "east", + "clusters": { + "east": { + "driver": "postgres", + "primary": "postgres://bedrock@primary.example.net/bedrock", + "replicas": ["postgres://bedrock_reader@replica.example.net/bedrock"], + "max_connections": 5 + } + } +} +``` + +The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file. + +Applications connect with `db_connection::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. + +For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database. diff --git a/ci/check-sql.sh b/ci/check-sql.sh new file mode 100644 index 0000000..192fe6d --- /dev/null +++ b/ci/check-sql.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -euo pipefail + +prefix="bedrock-sql-$(openssl rand -hex 8)" +password="$(openssl rand -hex 16)" + +cleanup() { + docker rm -f "$prefix-rust" "$prefix-mysql" "$prefix-postgres" >/dev/null 2>&1 || true + docker network rm "$prefix" >/dev/null 2>&1 || true +} +trap cleanup EXIT + +docker network create "$prefix" >/dev/null +docker run -d --name "$prefix-postgres" --network "$prefix" --network-alias postgres \ + -e POSTGRES_PASSWORD="$password" -e POSTGRES_DB=bedrock postgres:17-alpine >/dev/null +docker run -d --name "$prefix-mysql" --network "$prefix" --network-alias mysql \ + -e MYSQL_RANDOM_ROOT_PASSWORD=1 -e MYSQL_USER=bedrock -e MYSQL_PASSWORD="$password" \ + -e MYSQL_DATABASE=bedrock mysql:8.4 >/dev/null + +wait_for() { + for _ in {1..90}; do + if "$@" >/dev/null 2>&1; then return; fi + sleep 2 + done + "$@" +} + +wait_for docker exec "$prefix-postgres" pg_isready -h 127.0.0.1 -U postgres -d bedrock +docker exec -e PGPASSWORD="$password" "$prefix-postgres" \ + createdb -h 127.0.0.1 -U postgres bedrock_replica +wait_for docker exec -e MYSQL_PWD="$password" "$prefix-mysql" \ + mysql -h 127.0.0.1 -u bedrock -D bedrock -e 'SELECT 1' + +docker run --rm --name "$prefix-rust" --network "$prefix" \ + --mount "type=bind,src=$PWD,dst=/work,readonly" -w /work \ + -e CARGO_TARGET_DIR=/tmp/bedrock-target \ + -e BEDROCK_REQUIRE_SQL_TESTS=1 \ + -e BEDROCK_TEST_POSTGRES="postgres://postgres:$password@postgres/bedrock" \ + -e BEDROCK_TEST_POSTGRES_REPLICA="postgres://postgres:$password@postgres/bedrock_replica" \ + -e BEDROCK_TEST_MYSQL="mysql://bedrock:$password@mysql/bedrock" \ + rust:1.91.1-bookworm sh -ec ' + rustup component add rustfmt + cargo fmt --all --check + cargo test --locked --workspace + cargo build --locked --workspace + cd "$(mktemp -d)" + /tmp/bedrock-target/debug/bedrock + test -f bedrock.sqlite3 + ' diff --git a/crates/clusters/Cargo.toml b/crates/clusters/Cargo.toml new file mode 100644 index 0000000..5fdebbe --- /dev/null +++ b/crates/clusters/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "clusters" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +serde.workspace = true +thiserror.workspace = true +url.workspace = true diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs new file mode 100644 index 0000000..4d30fce --- /dev/null +++ b/crates/clusters/src/lib.rs @@ -0,0 +1,272 @@ +use std::{collections::BTreeMap, fmt, path::Path}; + +use serde::Deserialize; +use thiserror::Error; +use url::Url; + +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum Driver { + #[default] + Sqlite, + Postgres, + Mysql, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Tls { + #[default] + VerifyFull, + Disabled, +} + +/// A database address may contain credentials. +#[derive(Clone, Deserialize)] +#[serde(transparent)] +pub struct Address(String); + +impl From<&str> for Address { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +impl From for Address { + fn from(value: String) -> Self { + Self(value) + } +} + +impl fmt::Debug for Address { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("Address([redacted])") + } +} + +impl Address { + pub fn connection_string(&self) -> &str { + &self.0 + } +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Cluster { + pub driver: Driver, + pub primary: Address, + #[serde(default)] + pub replicas: Vec
, + #[serde(default)] + pub tls: Tls, + #[serde(default = "default_pool_size")] + pub max_connections: u32, +} + +const fn default_pool_size() -> u32 { + 5 +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct DeploymentConfig { + pub deployment: String, + pub cluster: Option, + pub clusters: BTreeMap, + pub read_only: bool, + pub sqlite_path: Address, +} + +impl Default for DeploymentConfig { + fn default() -> Self { + Self { + deployment: "default".into(), + cluster: None, + clusters: BTreeMap::new(), + read_only: false, + sqlite_path: "bedrock.sqlite3".into(), + } + } +} + +#[derive(Debug)] +pub struct ResolvedDeployment { + pub deployment: String, + pub cluster: Option, + pub driver: Driver, + pub primary: Address, + pub replicas: Vec
, + pub read_only: bool, + pub max_connections: u32, +} + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("invalid {0} name")] + Name(&'static str), + #[error("the selected database cluster is not configured")] + UnknownCluster, + #[error("a cluster must be selected when clusters are configured")] + ClusterRequired, + #[error("the database pool size must be greater than zero")] + PoolSize, + #[error("SQLite does not support a replica list")] + SqliteReplicas, + #[error("invalid SQLite file path")] + SqlitePath, + #[error("invalid {0} database URL")] + Url(&'static str), +} + +impl DeploymentConfig { + pub fn resolve(&self) -> Result { + validate_name(&self.deployment, "deployment")?; + let local = Cluster { + driver: Driver::Sqlite, + primary: self.sqlite_path.clone(), + replicas: vec![], + tls: Tls::Disabled, + max_connections: 1, + }; + let cluster = match &self.cluster { + Some(name) => { + validate_name(name, "cluster")?; + self.clusters.get(name).ok_or(ConfigError::UnknownCluster)? + } + None if self.clusters.is_empty() => &local, + None => return Err(ConfigError::ClusterRequired), + }; + if cluster.max_connections == 0 { + return Err(ConfigError::PoolSize); + } + if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() { + return Err(ConfigError::SqliteReplicas); + } + let primary = resolve_address(cluster, &cluster.primary, self.read_only)?; + let replicas = cluster + .replicas + .iter() + .map(|address| resolve_address(cluster, address, true)) + .collect::>()?; + Ok(ResolvedDeployment { + deployment: self.deployment.clone(), + cluster: self.cluster.clone(), + driver: cluster.driver, + primary, + replicas, + read_only: self.read_only, + max_connections: cluster.max_connections, + }) + } +} + +fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> { + if value.is_empty() + || value.len() > 128 + || !value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) + { + return Err(ConfigError::Name(kind)); + } + Ok(()) +} + +fn resolve_address( + cluster: &Cluster, + address: &Address, + read_only: bool, +) -> Result { + let address = address.connection_string(); + let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver { + Driver::Sqlite => return sqlite_url(address, read_only), + Driver::Postgres => ("postgres", "sslmode", "verify-full", "disable"), + Driver::Mysql => ("mysql", "ssl-mode", "VERIFY_IDENTITY", "DISABLED"), + }; + let mut url = Url::parse(address).map_err(|_| ConfigError::Url(driver))?; + let compatible = url.scheme() == driver || driver == "postgres" && url.scheme() == "postgresql"; + if !compatible + || url.host_str().is_none() + || url.username().is_empty() + || url.path().trim_matches('/').is_empty() + || url.fragment().is_some() + || url.query_pairs().any(|(key, _)| { + matches!( + key.as_ref(), + "sslmode" + | "ssl-mode" + | "host" + | "hostaddr" + | "port" + | "socket" + | "dbname" + | "options" + ) + }) + { + return Err(ConfigError::Url(driver)); + } + let tls_mode = match cluster.tls { + Tls::VerifyFull => tls_enabled, + Tls::Disabled => tls_disabled, + }; + url.query_pairs_mut().append_pair(tls_key, tls_mode); + Ok(Address(url.into())) +} + +fn sqlite_url(path: &str, read_only: bool) -> Result { + if path.is_empty() || path == ":memory:" || path.contains('\0') { + return Err(ConfigError::SqlitePath); + } + let absolute = std::path::absolute(Path::new(path)).map_err(|_| ConfigError::SqlitePath)?; + let file = Url::from_file_path(absolute).map_err(|_| ConfigError::SqlitePath)?; + let file = file + .as_str() + .strip_prefix("file:") + .ok_or(ConfigError::SqlitePath)?; + let mode = if read_only { "ro" } else { "rwc" }; + Ok(Address(format!("sqlite:{file}?mode={mode}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn named_cluster_requires_matching_addresses_and_redacts_credentials() { + let mut config = DeploymentConfig { + cluster: Some("regional".into()), + clusters: BTreeMap::from([( + "regional".into(), + Cluster { + driver: Driver::Postgres, + primary: "postgres://user:secret@primary/bedrock".into(), + replicas: vec!["postgresql://reader:secret@replica/bedrock".into()], + tls: Tls::VerifyFull, + max_connections: 5, + }, + )]), + ..DeploymentConfig::default() + }; + let resolved = config.resolve().unwrap(); + assert!( + resolved + .primary + .connection_string() + .ends_with("sslmode=verify-full") + ); + assert!( + resolved.replicas[0] + .connection_string() + .ends_with("sslmode=verify-full") + ); + assert!(!format!("{resolved:?}").contains("secret")); + + config.clusters.get_mut("regional").unwrap().replicas[0] = + "mysql://user:secret@replica/bedrock".into(); + assert!(matches!( + config.resolve(), + Err(ConfigError::Url("postgres")) + )); + } +} diff --git a/crates/db_connection/Cargo.toml b/crates/db_connection/Cargo.toml new file mode 100644 index 0000000..13b09a1 --- /dev/null +++ b/crates/db_connection/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "db_connection" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +clusters.workspace = true +mysql.workspace = true +persistence.workspace = true +postgres.workspace = true +sqlite.workspace = true +thiserror.workspace = true + +[dev-dependencies] +serde_json.workspace = true +sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } +tempfile.workspace = true +tokio.workspace = true diff --git a/crates/db_connection/src/lib.rs b/crates/db_connection/src/lib.rs new file mode 100644 index 0000000..23f6b92 --- /dev/null +++ b/crates/db_connection/src/lib.rs @@ -0,0 +1,143 @@ +//! Deployment bootstrap and read routing. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; +pub use mysql::{Lease, MySql}; +pub use persistence::{Document, Error as StorageError, Mutation, Revision, Snapshot}; + +use clusters::ResolvedDeployment; +use persistence::{Reader, Store}; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum ConnectError { + #[error(transparent)] + Config(#[from] ConfigError), + #[error(transparent)] + Storage(#[from] StorageError), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ReadPreference { + /// Read from the primary endpoint. + #[default] + Primary, + /// Try configured replicas in round-robin order, then fall back to the primary. + /// Without an explicit snapshot revision a replica may return stale data. + PreferReplica, +} + +enum Writer { + Sql(Store), + MySql(MySql), +} + +pub struct Connection { + driver: Driver, + writer: Option, + primary: Reader, + replicas: Vec, + next_replica: AtomicUsize, +} + +pub async fn connect(config: &DeploymentConfig) -> Result { + let config = config.resolve()?; + let writer = if config.read_only { + None + } else { + let url = config.primary.connection_string(); + let name = &config.deployment; + let max = config.max_connections; + Some(match config.driver { + Driver::Sqlite => Writer::Sql(sqlite::connect(url, name).await?), + Driver::Postgres => Writer::Sql(postgres::connect(url, name, max).await?), + Driver::Mysql => Writer::MySql(MySql::connect(url, name, max).await?), + }) + }; + let primary = match &writer { + Some(Writer::Sql(store)) => store.reader(), + Some(Writer::MySql(store)) => store.reader(), + None => { + let reader = reader(&config, &config.primary)?; + reader.revision().await?; + reader + } + }; + let replicas = config + .replicas + .iter() + .map(|address| reader(&config, address)) + .collect::>()?; + Ok(Connection { + driver: config.driver, + writer, + primary, + replicas, + next_replica: AtomicUsize::new(0), + }) +} + +fn reader(config: &ResolvedDeployment, address: &Address) -> Result { + let url = address.connection_string(); + let name = &config.deployment; + match config.driver { + Driver::Sqlite => sqlite::reader(url, name), + Driver::Postgres => postgres::reader(url, name, config.max_connections), + Driver::Mysql => mysql::reader(url, name, config.max_connections), + } +} + +impl Connection { + pub fn driver(&self) -> Driver { + self.driver + } + + pub fn is_read_only(&self) -> bool { + self.writer.is_none() + } + + pub async fn revision(&self) -> Result { + self.primary.revision().await + } + + pub async fn get( + &self, + collection: &str, + id: &str, + at: Option, + preference: ReadPreference, + ) -> Result { + if preference == ReadPreference::PreferReplica && !self.replicas.is_empty() { + let count = self.replicas.len(); + let start = self.next_replica.fetch_add(1, Ordering::Relaxed) % count; + for replica in self.replicas.iter().cycle().skip(start).take(count) { + match replica.get(collection, id, at).await { + Ok(snapshot) => return Ok(snapshot), + Err(error) if error.retry_on_primary() => {} + Err(error) => return Err(error), + } + } + } + self.primary.get(collection, id, at).await + } + + pub async fn commit( + &self, + expected: Revision, + changes: &[Mutation], + ) -> Result { + match &self.writer { + Some(Writer::Sql(store)) => store.commit(expected, changes).await, + Some(Writer::MySql(store)) => store.commit(expected, changes).await, + None => Err(StorageError::ReadOnly), + } + } + + pub fn mysql_writer(&self) -> Option<&MySql> { + match &self.writer { + Some(Writer::MySql(store)) => Some(store), + _ => None, + } + } +} diff --git a/crates/db_connection/tests/storage.rs b/crates/db_connection/tests/storage.rs new file mode 100644 index 0000000..245957f --- /dev/null +++ b/crates/db_connection/tests/storage.rs @@ -0,0 +1,272 @@ +use std::{collections::BTreeMap, env, time::Duration}; + +use db_connection::{ + Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls, + connect, +}; +use serde_json::json; + +fn change(id: &str, text: &str) -> Mutation { + Mutation { + collection: "notes".into(), + id: id.into(), + value: Some(json!({ "text": text })), + } +} + +fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig { + DeploymentConfig { + deployment: deployment.into(), + cluster: Some("test".into()), + clusters: BTreeMap::from([( + "test".into(), + Cluster { + driver, + primary: url.into(), + replicas: vec![], + tls: Tls::Disabled, + max_connections: 4, + }, + )]), + ..DeploymentConfig::default() + } +} + +fn test_url(variable: &str) -> Option { + match env::var(variable) { + Ok(url) => Some(url), + Err(_) if env::var_os("BEDROCK_REQUIRE_SQL_TESTS").is_some() => { + panic!("{variable} is required for the remote storage checks") + } + Err(_) => None, + } +} + +async fn check_document_contract(db: &Connection) { + assert_eq!(db.revision().await.unwrap(), 0); + let original = change("doc", "first"); + assert_eq!(db.commit(0, &[original]).await.unwrap(), 1); + + let duplicate = [ + change("other", "never written"), + change("other", "duplicate"), + ]; + assert!(matches!( + db.commit(1, &duplicate).await, + Err(StorageError::Invalid(_)) + )); + assert!(matches!( + db.commit(0, &[change("other", "stale")]).await, + Err(StorageError::WriteConflict) + )); + + let second = [change("doc", "second")]; + let alternative = [change("doc", "alternative")]; + let (one, two) = tokio::join!(db.commit(1, &second), db.commit(1, &alternative)); + assert!(matches!( + (&one, &two), + (Ok(2), Err(StorageError::WriteConflict)) | (Err(StorageError::WriteConflict), Ok(2)) + )); + + let old = db + .get("notes", "doc", Some(1), ReadPreference::Primary) + .await + .unwrap(); + assert_eq!(old.document.unwrap().value, json!({ "text": "first" })); + assert!(matches!( + db.get("notes", "doc", Some(3), ReadPreference::Primary) + .await, + Err(StorageError::Behind { + requested: 3, + available: 2 + }) + )); + assert!( + db.get("notes", "other", None, ReadPreference::Primary) + .await + .unwrap() + .document + .is_none() + ); + + let tombstone = Mutation { + collection: "notes".into(), + id: "doc".into(), + value: None, + }; + let null_document = Mutation { + collection: "notes".into(), + id: "null".into(), + value: Some(json!(null)), + }; + assert_eq!(db.commit(2, &[tombstone, null_document]).await.unwrap(), 3); + assert!( + db.get("notes", "doc", None, ReadPreference::Primary) + .await + .unwrap() + .document + .is_none() + ); + let null_document = db + .get("notes", "null", None, ReadPreference::Primary) + .await + .unwrap(); + assert_eq!(null_document.document.unwrap().value, json!(null)); +} + +#[tokio::test] +async fn sqlite_persists_across_reopening_and_enforces_read_only() { + let folder = tempfile::tempdir().unwrap(); + let filename = folder.path().join("bedrock +?#%.sqlite"); + let mut config = DeploymentConfig { + sqlite_path: filename.to_str().unwrap().into(), + ..DeploymentConfig::default() + }; + let db = connect(&config).await.unwrap(); + assert_eq!(db.driver(), Driver::Sqlite); + check_document_contract(&db).await; + drop(db); + config.read_only = true; + let db = connect(&config).await.unwrap(); + assert_eq!(db.revision().await.unwrap(), 3); + assert!(db.is_read_only()); + assert!(matches!( + db.commit(3, &[change("doc", "invalid")]).await, + Err(StorageError::ReadOnly) + )); +} + +#[tokio::test] +async fn postgres_reads_replicas_and_falls_back_when_behind() { + let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else { + return; + }; + let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap(); + let mut config = sql_config(Driver::Postgres, &url, "pg_contract"); + config + .clusters + .get_mut("test") + .unwrap() + .replicas + .push(replica_url.clone().into()); + let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract")) + .await + .unwrap(); + let (db, concurrent) = tokio::join!(connect(&config), connect(&config)); + let db = db.unwrap(); + assert_eq!(concurrent.unwrap().revision().await.unwrap(), 0); + check_document_contract(&db).await; + replica + .commit(0, &[change("doc", "replica")]) + .await + .unwrap(); + + let stale = db + .get("notes", "doc", None, ReadPreference::PreferReplica) + .await + .unwrap(); + assert_eq!(stale.revision, 1); + assert_eq!(stale.document.unwrap().value, json!({ "text": "replica" })); + let fresh = db + .get("notes", "null", Some(3), ReadPreference::PreferReplica) + .await + .unwrap(); + assert_eq!(fresh.revision, 3); + assert_eq!(fresh.document.unwrap().value, json!(null)); + + config.read_only = true; + let db = connect(&config).await.unwrap(); + assert!(db.is_read_only()); + assert_eq!(db.revision().await.unwrap(), 3); +} + +#[tokio::test] +async fn mysql_fences_writers_and_cleans_only_one_deployment() { + let Some(url) = test_url("BEDROCK_TEST_MYSQL") else { + return; + }; + let config = sql_config(Driver::Mysql, &url, "mysql_contract"); + let db = connect(&config).await.unwrap(); + check_document_contract(&db).await; + let other = connect(&sql_config(Driver::Mysql, &url, "mysql_other")) + .await + .unwrap(); + other.commit(0, &[change("doc", "keep")]).await.unwrap(); + + let mysql = db.mysql_writer().unwrap(); + let lease = mysql + .acquire_lease(Duration::from_secs(30)) + .await + .unwrap() + .unwrap(); + assert!( + mysql + .acquire_lease(Duration::from_secs(30)) + .await + .unwrap() + .is_none() + ); + assert!(matches!( + db.commit(3, &[change("doc", "blocked")]).await, + Err(StorageError::WriteConflict) + )); + assert!(matches!( + other + .mysql_writer() + .unwrap() + .delete_deployment(&lease) + .await, + Err(StorageError::LeaseLost) + )); + mysql + .renew_lease(&lease, Duration::from_secs(30)) + .await + .unwrap(); + assert_eq!( + mysql + .commit_with_lease(&lease, 3, &[change("doc", "leased")]) + .await + .unwrap(), + 4 + ); + assert!(mysql.release_lease(&lease).await.unwrap()); + let next = mysql + .acquire_lease(Duration::from_secs(30)) + .await + .unwrap() + .unwrap(); + assert!(next.epoch() > lease.epoch()); + assert!(matches!( + mysql + .commit_with_lease(&lease, 4, &[change("doc", "stale")]) + .await, + Err(StorageError::WriteConflict) + )); + assert!(mysql.delete_deployment(&next).await.unwrap() > 0); + assert!(matches!( + db.revision().await, + Err(StorageError::MissingDeployment) + )); + assert!(connect(&config).await.is_err()); + assert_eq!( + other + .get("notes", "doc", None, ReadPreference::Primary) + .await + .unwrap() + .document + .unwrap() + .value, + json!({ "text": "keep" }) + ); + let mut other_config = sql_config(Driver::Mysql, &url, "mysql_other"); + other_config.read_only = true; + assert_eq!( + connect(&other_config) + .await + .unwrap() + .revision() + .await + .unwrap(), + 1 + ); +} diff --git a/crates/mysql/Cargo.toml b/crates/mysql/Cargo.toml new file mode 100644 index 0000000..c9b0559 --- /dev/null +++ b/crates/mysql/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "mysql" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +persistence.workspace = true +sqlx = { workspace = true, features = ["mysql"] } diff --git a/crates/mysql/src/lib.rs b/crates/mysql/src/lib.rs new file mode 100644 index 0000000..031d506 --- /dev/null +++ b/crates/mysql/src/lib.rs @@ -0,0 +1,211 @@ +//! MySQL storage, writer leases and deployment cleanup. + +use std::{sync::Arc, time::Duration}; + +use persistence::{ + Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, + pool, +}; +use sqlx::AnyPool; + +const SCHEMA: &[&str] = &[ + "CREATE TABLE IF NOT EXISTS bedrock_deployments ( + deployment VARBINARY(128) PRIMARY KEY, + revision BIGINT NOT NULL DEFAULT 0, + retired BIGINT NOT NULL DEFAULT 0, + lease_epoch BIGINT NOT NULL DEFAULT 0, + lease_until BIGINT NOT NULL DEFAULT 0 + ) ENGINE=InnoDB", + "CREATE TABLE IF NOT EXISTS bedrock_documents ( + deployment VARBINARY(128) NOT NULL, + collection VARBINARY(128) NOT NULL, + document_id VARBINARY(128) NOT NULL, + revision BIGINT NOT NULL, + payload LONGBLOB, + PRIMARY KEY (deployment, collection, document_id, revision), + FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment) + ) ENGINE=InnoDB", +]; + +#[derive(Clone)] +pub struct MySql { + store: Store, + pool: AnyPool, + deployment: Vec, + identity: Arc<()>, +} + +/// The monotonically increasing epoch fences off holders whose lease expired. +#[derive(Debug)] +pub struct Lease { + epoch: i64, + issuer: Arc<()>, +} + +impl Lease { + pub fn epoch(&self) -> i64 { + self.epoch + } +} + +impl MySql { + pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result { + let pool = pool(Dialect::Mysql, url, max_connections, false)?; + let store = Store::initialize( + pool.clone(), + Dialect::Mysql, + deployment, + SCHEMA, + "INSERT INTO bedrock_deployments (deployment) VALUES (?) + ON DUPLICATE KEY UPDATE revision = revision", + ) + .await?; + Ok(Self { + store, + pool, + deployment: deployment.as_bytes().to_vec(), + identity: Arc::new(()), + }) + } + + pub fn reader(&self) -> Reader { + self.store.reader() + } + + /// An ordinary write is allowed while no lease is active. + pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { + self.store.commit(expected, mutations).await + } + + pub async fn commit_with_lease( + &self, + lease: &Lease, + expected: Revision, + mutations: &[Mutation], + ) -> Result { + let epoch = self.epoch(lease)?; + self.store + .commit_with_fence(expected, mutations, Some(epoch)) + .await + } + + /// Acquires an expired or unheld lease using the database clock. + pub async fn acquire_lease(&self, ttl: Duration) -> Result> { + let ttl = lease_millis(ttl)?; + let update = format!( + " + UPDATE bedrock_deployments + SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ? + WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}" + ); + let mut transaction = self.pool.begin().await?; + lock_mysql_deployment(&mut transaction, &self.deployment).await?; + let changed = sqlx::query(&update) + .bind(ttl) + .bind(self.deployment.as_slice()) + .execute(&mut *transaction) + .await?; + if changed.rows_affected() != 1 { + return Ok(None); + } + let epoch = + sqlx::query_scalar("SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?") + .bind(self.deployment.as_slice()) + .fetch_one(&mut *transaction) + .await?; + transaction.commit().await?; + Ok(Some(Lease { + epoch, + issuer: self.identity.clone(), + })) + } + + /// Extends an active lease from the current database time without shortening it. + pub async fn renew_lease(&self, lease: &Lease, ttl: Duration) -> Result<()> { + let epoch = self.epoch(lease)?; + let ttl = lease_millis(ttl)?; + let update = format!( + " + UPDATE bedrock_deployments + SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?) + WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}" + ); + let mut transaction = self.pool.begin().await?; + lock_mysql_deployment(&mut transaction, &self.deployment).await?; + let changed = sqlx::query(&update) + .bind(ttl) + .bind(self.deployment.as_slice()) + .bind(epoch) + .execute(&mut *transaction) + .await?; + if changed.rows_affected() != 1 { + return Err(Error::LeaseLost); + } + transaction.commit().await?; + Ok(()) + } + + pub async fn release_lease(&self, lease: &Lease) -> Result { + let epoch = self.epoch(lease)?; + let changed = sqlx::query( + " + UPDATE bedrock_deployments SET lease_until = 0 + WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0", + ) + .bind(self.deployment.as_slice()) + .bind(epoch) + .execute(&self.pool) + .await?; + Ok(changed.rows_affected() == 1) + } + + /// Removes only this deployment's documents and retires its identity in one transaction. + /// The retained deployment row prevents a restart from recreating the deleted deployment. + pub async fn delete_deployment(&self, lease: &Lease) -> Result { + let epoch = self.epoch(lease)?; + let update = format!( + " + UPDATE bedrock_deployments SET retired = 1, lease_until = 0 + WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}" + ); + let mut transaction = self.pool.begin().await?; + lock_mysql_deployment(&mut transaction, &self.deployment).await?; + let changed = sqlx::query(&update) + .bind(self.deployment.as_slice()) + .bind(epoch) + .execute(&mut *transaction) + .await?; + if changed.rows_affected() != 1 { + return Err(Error::LeaseLost); + } + let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?") + .bind(self.deployment.as_slice()) + .execute(&mut *transaction) + .await?; + transaction.commit().await?; + Ok(removed.rows_affected()) + } + + fn epoch(&self, lease: &Lease) -> Result { + if !Arc::ptr_eq(&self.identity, &lease.issuer) { + return Err(Error::LeaseLost); + } + Ok(lease.epoch) + } +} + +pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { + Reader::new( + pool(Dialect::Mysql, url, max_connections, true)?, + Dialect::Mysql, + deployment, + ) +} + +fn lease_millis(ttl: Duration) -> Result { + let millis = ttl.as_millis(); + if millis == 0 || millis >= i64::MAX as u128 / 2 { + return Err(Error::Invalid("lease duration")); + } + Ok(millis as i64) +} diff --git a/crates/persistence/Cargo.toml b/crates/persistence/Cargo.toml new file mode 100644 index 0000000..bf27ee2 --- /dev/null +++ b/crates/persistence/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "persistence" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +serde_json.workspace = true +sqlx.workspace = true +thiserror.workspace = true diff --git a/crates/persistence/src/lib.rs b/crates/persistence/src/lib.rs new file mode 100644 index 0000000..51cb518 --- /dev/null +++ b/crates/persistence/src/lib.rs @@ -0,0 +1,386 @@ +//! Shared storage contract for Bedrock's SQL backends. + +use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; + +use serde_json::Value; +use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions}; +use thiserror::Error; + +pub type Revision = i64; +pub type Result = std::result::Result; + +#[derive(Debug, Error)] +pub enum Error { + #[error("invalid {0}")] + Invalid(&'static str), + #[error("the database connection failed")] + Connection, + #[error("SQL operation failed: {0}")] + Sql(#[from] sqlx::Error), + #[error("document encoding failed: {0}")] + Encoding(#[from] serde_json::Error), + #[error("the connection is read-only")] + ReadOnly, + #[error("the deployment is missing or retired")] + MissingDeployment, + #[error("database is at revision {available}, requested revision {requested}")] + Behind { + requested: Revision, + available: Revision, + }, + #[error("the write conflicts with the current revision or lease")] + WriteConflict, + #[error("lease is missing, expired, or belongs to another store")] + LeaseLost, +} + +impl Error { + pub fn retry_on_primary(&self) -> bool { + match self { + Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true, + Self::Sql(error) => match error { + sqlx::Error::Io(_) + | sqlx::Error::Tls(_) + | sqlx::Error::PoolTimedOut + | sqlx::Error::PoolClosed + | sqlx::Error::WorkerCrashed => true, + sqlx::Error::Database(db) => db.code().is_some_and(|code| { + code.starts_with("08") + || matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146") + }), + _ => false, + }, + _ => false, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Document { + pub revision: Revision, + pub value: Value, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Snapshot { + pub revision: Revision, + pub document: Option, +} + +#[derive(Clone, Debug)] +pub struct Mutation { + pub collection: String, + pub id: String, + /// None writes a tombstone. Some(Value::Null) stores a JSON null. + pub value: Option, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Dialect { + Sqlite, + Postgres, + Mysql, +} + +/// Opened SQL reader. Its pool is private so callers cannot bypass the read API. +#[derive(Clone)] +pub struct Reader { + pool: AnyPool, + dialect: Dialect, + deployment: Vec, +} + +#[derive(Clone)] +pub struct Store { + reader: Reader, +} + +/// Returns a lazily connected pool. The writer initializes schema before use. +#[doc(hidden)] +pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result { + if connections == 0 { + return Err(Error::Invalid("database pool size")); + } + sqlx::any::install_default_drivers(); + let mut options = AnyPoolOptions::new() + .max_connections(connections) + .acquire_timeout(Duration::from_secs(5)); + let read_only_statement = match dialect { + Dialect::Sqlite => "PRAGMA query_only = ON", + Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", + Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY", + }; + if read_only { + options = options.after_connect(move |connection, _| { + Box::pin(async move { + sqlx::query(read_only_statement).execute(connection).await?; + Ok(()) + }) + }); + } + options.connect_lazy(url).map_err(|_| Error::Connection) +} + +impl Reader { + #[doc(hidden)] + pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result { + validate_id(deployment)?; + Ok(Self { + pool, + dialect, + deployment: deployment.as_bytes().to_vec(), + }) + } + + pub async fn revision(&self) -> Result { + let statement = statement( + self.dialect, + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", + ); + sqlx::query_scalar(&statement) + .bind(self.deployment.as_slice()) + .fetch_optional(&self.pool) + .await + .map_err(connection_error)? + .ok_or(Error::MissingDeployment) + } + + /// Fetch at the latest revision or at an exact, previously committed snapshot. + pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { + validate_id(collection)?; + validate_id(id)?; + if at.is_some_and(|at| at < 0) { + return Err(Error::Invalid("snapshot revision")); + } + // A single statement keeps the revision and document on the same database snapshot. + let statement = statement( + self.dialect, + " + SELECT d.revision AS available, v.revision AS document_revision, v.payload + FROM bedrock_deployments d + LEFT JOIN bedrock_documents v + ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ? + AND v.revision <= COALESCE(?, d.revision) + WHERE d.deployment = ? AND d.retired = 0 + ORDER BY v.revision DESC LIMIT 1", + ); + let row = sqlx::query(&statement) + .bind(collection.as_bytes()) + .bind(id.as_bytes()) + .bind(at) + .bind(self.deployment.as_slice()) + .fetch_optional(&self.pool) + .await + .map_err(connection_error)? + .ok_or(Error::MissingDeployment)?; + let available = row.try_get("available")?; + let revision = at.unwrap_or(available); + if revision > available { + return Err(Error::Behind { + requested: revision, + available, + }); + } + let document_revision: Option = row.try_get("document_revision")?; + let payload: Option> = row.try_get("payload")?; + let document = match (document_revision, payload) { + (Some(revision), Some(payload)) => Some(Document { + revision, + value: serde_json::from_slice(&payload)?, + }), + _ => None, + }; + Ok(Snapshot { revision, document }) + } +} + +impl Store { + #[doc(hidden)] + pub async fn initialize( + pool: AnyPool, + dialect: Dialect, + deployment: &str, + schema: &[&str], + insert_deployment: &str, + ) -> Result { + let reader = Reader::new(pool, dialect, deployment)?; + if dialect == Dialect::Postgres { + // PostgreSQL catalog inserts can race even with IF NOT EXISTS. + let mut transaction = reader.pool.begin().await.map_err(connection_error)?; + sqlx::query("SELECT pg_advisory_xact_lock(1694199371)") + .execute(&mut *transaction) + .await?; + initialize_schema( + &mut transaction, + schema, + insert_deployment, + &reader.deployment, + ) + .await?; + transaction.commit().await?; + } else { + let mut connection = reader.pool.acquire().await.map_err(connection_error)?; + initialize_schema( + &mut connection, + schema, + insert_deployment, + &reader.deployment, + ) + .await?; + } + reader.revision().await?; + Ok(Self { reader }) + } + + pub fn reader(&self) -> Reader { + self.reader.clone() + } + + pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { + self.commit_with_fence(expected, mutations, None).await + } + + #[doc(hidden)] + pub async fn commit_with_fence( + &self, + expected: Revision, + mutations: &[Mutation], + fence: Option, + ) -> Result { + let revision = expected + .checked_add(1) + .filter(|_| expected >= 0) + .ok_or(Error::Invalid("expected revision"))?; + if mutations.is_empty() { + return Err(Error::Invalid("empty write batch")); + } + let mut seen = HashSet::new(); + let mut rows = Vec::with_capacity(mutations.len()); + for mutation in mutations { + validate_id(&mutation.collection)?; + validate_id(&mutation.id)?; + if !seen.insert((&mutation.collection, &mutation.id)) { + return Err(Error::Invalid("duplicate document in write batch")); + } + let payload = mutation + .value + .as_ref() + .map(serde_json::to_vec) + .transpose()?; + rows.push(( + mutation.collection.as_bytes(), + mutation.id.as_bytes(), + payload, + )); + } + + let store = &self.reader; + let mut transaction = store.pool.begin().await.map_err(connection_error)?; + let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned(); + if store.dialect == Dialect::Mysql { + lock_mysql_deployment(&mut transaction, &store.deployment).await?; + if fence.is_some() { + advance.push_str(" AND lease_epoch = ? AND lease_until > "); + } else { + advance.push_str(" AND lease_until <= "); + } + advance.push_str(MYSQL_NOW); + } else if fence.is_some() { + return Err(Error::Invalid("lease on a database without lease support")); + } + let advance = statement(store.dialect, &advance); + let mut query = sqlx::query(&advance) + .bind(revision) + .bind(store.deployment.as_slice()) + .bind(expected); + if let Some(fence) = fence { + query = query.bind(fence); + } + if query.execute(&mut *transaction).await?.rows_affected() != 1 { + return Err(Error::WriteConflict); + } + let insert = statement( + store.dialect, + " + INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) + VALUES (?, ?, ?, ?, ?)", + ); + for (collection, id, payload) in rows { + sqlx::query(&insert) + .bind(store.deployment.as_slice()) + .bind(collection) + .bind(id) + .bind(revision) + .bind(payload) + .execute(&mut *transaction) + .await?; + } + transaction.commit().await?; + Ok(revision) + } +} + +/// MySQL server time in milliseconds, shared by lease management and fenced writes. +#[doc(hidden)] +pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)"; + +/// Lock before reading the database clock. MySQL timestamps are fixed at statement start. +#[doc(hidden)] +pub async fn lock_mysql_deployment( + connection: &mut AnyConnection, + deployment: &[u8], +) -> Result<()> { + sqlx::query_scalar::<_, Revision>( + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE", + ) + .bind(deployment) + .fetch_optional(connection) + .await? + .ok_or(Error::MissingDeployment)?; + Ok(()) +} + +fn validate_id(value: &str) -> Result<()> { + if value.is_empty() || value.len() > 128 || value.contains('\0') { + return Err(Error::Invalid( + "identifier (expected 1–128 bytes without NUL)", + )); + } + Ok(()) +} + +async fn initialize_schema( + connection: &mut AnyConnection, + schema: &[&str], + insert_deployment: &str, + deployment: &[u8], +) -> Result<()> { + for ddl in schema { + sqlx::query(ddl).execute(&mut *connection).await?; + } + sqlx::query(insert_deployment) + .bind(deployment) + .execute(connection) + .await?; + Ok(()) +} + +fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> { + if dialect != Dialect::Postgres { + return Cow::Borrowed(sql); + } + let mut parts = sql.split('?'); + let mut translated = parts.next().unwrap_or_default().to_owned(); + for (index, part) in parts.enumerate() { + let _ = write!(translated, "${}", index + 1); + translated.push_str(part); + } + Cow::Owned(translated) +} + +fn connection_error(error: sqlx::Error) -> Error { + match error { + sqlx::Error::Configuration(_) => Error::Connection, + other => Error::Sql(other), + } +} diff --git a/crates/postgres/Cargo.toml b/crates/postgres/Cargo.toml new file mode 100644 index 0000000..195f869 --- /dev/null +++ b/crates/postgres/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "postgres" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +persistence.workspace = true +sqlx = { workspace = true, features = ["postgres"] } diff --git a/crates/postgres/src/lib.rs b/crates/postgres/src/lib.rs new file mode 100644 index 0000000..343c898 --- /dev/null +++ b/crates/postgres/src/lib.rs @@ -0,0 +1,40 @@ +//! PostgreSQL connection pools and the Bedrock document layout. + +use persistence::{Dialect, Reader, Result, Store, pool}; + +const SCHEMA: &[&str] = &[ + "CREATE TABLE IF NOT EXISTS bedrock_deployments ( + deployment BYTEA PRIMARY KEY, + revision BIGINT NOT NULL DEFAULT 0, + retired BIGINT NOT NULL DEFAULT 0 + )", + "CREATE TABLE IF NOT EXISTS bedrock_documents ( + deployment BYTEA NOT NULL REFERENCES bedrock_deployments(deployment), + collection BYTEA NOT NULL, + document_id BYTEA NOT NULL, + revision BIGINT NOT NULL, + payload BYTEA, + PRIMARY KEY (deployment, collection, document_id, revision) + )", +]; + +pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result { + let pool = pool(Dialect::Postgres, url, max_connections, false)?; + Store::initialize( + pool, + Dialect::Postgres, + deployment, + SCHEMA, + "INSERT INTO bedrock_deployments (deployment) VALUES ($1) + ON CONFLICT (deployment) DO NOTHING", + ) + .await +} + +pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { + Reader::new( + pool(Dialect::Postgres, url, max_connections, true)?, + Dialect::Postgres, + deployment, + ) +} diff --git a/crates/sqlite/Cargo.toml b/crates/sqlite/Cargo.toml new file mode 100644 index 0000000..93e2f00 --- /dev/null +++ b/crates/sqlite/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "sqlite" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +persistence.workspace = true +sqlx = { workspace = true, features = ["sqlite"] } diff --git a/crates/sqlite/src/lib.rs b/crates/sqlite/src/lib.rs new file mode 100644 index 0000000..09b483f --- /dev/null +++ b/crates/sqlite/src/lib.rs @@ -0,0 +1,41 @@ +//! File-backed Bedrock storage for self-hosted deployments. + +use persistence::{Dialect, Reader, Result, Store, pool}; + +const SCHEMA: &[&str] = &[ + "CREATE TABLE IF NOT EXISTS bedrock_deployments ( + deployment BLOB PRIMARY KEY NOT NULL, + revision INTEGER NOT NULL DEFAULT 0, + retired INTEGER NOT NULL DEFAULT 0 + )", + "CREATE TABLE IF NOT EXISTS bedrock_documents ( + deployment BLOB NOT NULL, + collection BLOB NOT NULL, + document_id BLOB NOT NULL, + revision INTEGER NOT NULL, + payload BLOB, + PRIMARY KEY (deployment, collection, document_id, revision), + FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment) + )", +]; + +pub async fn connect(url: &str, deployment: &str) -> Result { + let pool = pool(Dialect::Sqlite, url, 1, false)?; + Store::initialize( + pool, + Dialect::Sqlite, + deployment, + SCHEMA, + "INSERT INTO bedrock_deployments (deployment) VALUES (?) + ON CONFLICT (deployment) DO NOTHING", + ) + .await +} + +pub fn reader(url: &str, deployment: &str) -> Result { + Reader::new( + pool(Dialect::Sqlite, url, 1, true)?, + Dialect::Sqlite, + deployment, + ) +} diff --git a/src/main.rs b/src/main.rs index e7a11a9..ae7d0f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,19 @@ -fn main() { - println!("Hello, world!"); +use std::{env, error::Error, fs}; + +use db_connection::{DeploymentConfig, connect}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let config = match env::var_os("BEDROCK_DB_CONFIG") { + Some(path) => serde_json::from_slice::(&fs::read(path)?)?, + None => DeploymentConfig::default(), + }; + let db = connect(&config).await?; + println!( + "Bedrock storage ready ({:?}, revision {}, read-only: {})", + db.driver(), + db.revision().await?, + db.is_read_only() + ); + Ok(()) } -- 2.52.0 From 632c3a8882db4605cb79ac924ed10f362b0b98ab Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 00:26:15 +0800 Subject: [PATCH 02/13] Scope SQL verification to main PRs and render deployment configuration --- .gitea/workflows/sql.yml | 4 ++- README.md | 2 ++ deploy/README.md | 11 ++++++ deploy/render-postgres.py | 74 +++++++++++++++++++++++++++++++++++++++ deploy/sqlite.json | 4 +++ 5 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 deploy/README.md create mode 100644 deploy/render-postgres.py create mode 100644 deploy/sqlite.json diff --git a/.gitea/workflows/sql.yml b/.gitea/workflows/sql.yml index fae370a..e5591ac 100644 --- a/.gitea/workflows/sql.yml +++ b/.gitea/workflows/sql.yml @@ -1,8 +1,8 @@ name: Bedrock SQL storage on: - push: pull_request: + branches: [main] jobs: sql: @@ -10,5 +10,7 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - name: Compile and test SQLite, PostgreSQL and MySQL run: bash ci/check-sql.sh diff --git a/README.md b/README.md index 2d1b1d4..1103162 100644 --- a/README.md +++ b/README.md @@ -24,3 +24,5 @@ The database must already exist for PostgreSQL and MySQL. Bedrock creates its ow Applications connect with `db_connection::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database. + +See [deployment configuration](deploy/README.md) for the PostgreSQL configuration renderer and deployment-only variables. diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..1f5cd60 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,11 @@ +# Deployment configuration + +Deployments pass the path of a JSON configuration file to the Bedrock executable using `BEDROCK_DB_CONFIG`. The Rust libraries accept structured configuration. + +- **SQLite** uses `deploy/sqlite.json` as a template. Set `sqlite_path` to a persistent, writable volume path. +- **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address. +- **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint. + +Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. The SQL renderer and crates have no S3 dependency. + +The `ces-control` storage checks run on pull requests targeting `main`. They use isolated database containers and generated fixture credentials. The workflow does not deploy the application. diff --git a/deploy/render-postgres.py b/deploy/render-postgres.py new file mode 100644 index 0000000..a3d00e2 --- /dev/null +++ b/deploy/render-postgres.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Render the private Bedrock PostgreSQL config at deploy time.""" + +import argparse +import ipaddress +import json +import os +from pathlib import Path +import re +import tempfile +from urllib.parse import quote + + +def required(variable): + value = os.environ.get(variable) + if not value: + raise SystemExit(f"Missing {variable}") + return value + + +def database_url(): + host = required("BEDROCK_PG_HOST").removeprefix("[").removesuffix("]") + if ":" in host: + try: + host = f"[{ipaddress.IPv6Address(host)}]" + except ValueError: + raise SystemExit("Invalid BEDROCK_PG_HOST") from None + elif not re.fullmatch(r"[A-Za-z0-9.-]+", host): + raise SystemExit("Invalid BEDROCK_PG_HOST") + + try: + port = int(required("BEDROCK_PG_PORT")) + if not 1 <= port <= 65535: + raise ValueError + except ValueError: + raise SystemExit("Invalid BEDROCK_PG_PORT") from None + + user = quote(required("BEDROCK_PG_USER"), safe="") + password = quote(required("BEDROCK_PG_PASSWORD"), safe="") + database = quote(required("BEDROCK_PG_DATABASE"), safe="") + return f"postgres://{user}:{password}@{host}:{port}/{database}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--deployment", default="default") + options = parser.parse_args() + if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment): + parser.error("invalid deployment name") + config = { + "deployment": options.deployment, + "cluster": "postgres", + "clusters": { + "postgres": { + "driver": "postgres", + "primary": database_url(), + } + }, + } + + # Write with owner-only permissions, then replace the destination atomically. + file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False) + try: + with file: + json.dump(config, file, indent=2) + file.write("\n") + os.replace(file.name, options.output) + finally: + Path(file.name).unlink(missing_ok=True) + + +if __name__ == "__main__": + main() diff --git a/deploy/sqlite.json b/deploy/sqlite.json new file mode 100644 index 0000000..6e61a4d --- /dev/null +++ b/deploy/sqlite.json @@ -0,0 +1,4 @@ +{ + "deployment": "default", + "sqlite_path": "bedrock.sqlite3" +} -- 2.52.0 From a01bac3a488f43e48dc6c049b3a32a6712588bfb Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 00:48:59 +0800 Subject: [PATCH 03/13] Pause automated SQL verification --- .gitea/workflows/sql.yml | 16 ---------------- deploy/README.md | 2 +- 2 files changed, 1 insertion(+), 17 deletions(-) delete mode 100644 .gitea/workflows/sql.yml diff --git a/.gitea/workflows/sql.yml b/.gitea/workflows/sql.yml deleted file mode 100644 index e5591ac..0000000 --- a/.gitea/workflows/sql.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Bedrock SQL storage - -on: - pull_request: - branches: [main] - -jobs: - sql: - runs-on: ces-control - timeout-minutes: 30 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - name: Compile and test SQLite, PostgreSQL and MySQL - run: bash ci/check-sql.sh diff --git a/deploy/README.md b/deploy/README.md index 1f5cd60..b5ae7b9 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -8,4 +8,4 @@ Deployments pass the path of a JSON configuration file to the Bedrock executable Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. The SQL renderer and crates have no S3 dependency. -The `ces-control` storage checks run on pull requests targeting `main`. They use isolated database containers and generated fixture credentials. The workflow does not deploy the application. +Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner. -- 2.52.0 From 351cc156dd407769e080b5e036d87bf9eff361e9 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 00:50:58 +0800 Subject: [PATCH 04/13] Deploy Rust Bedrock from main on the existing host --- .gitea/workflows/deploy.yml | 29 ++++++++++++++++++++++ deploy/README.md | 4 +++ deploy/build-release.sh | 13 ++++++++++ deploy/release.sh | 49 +++++++++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+) create mode 100644 .gitea/workflows/deploy.yml create mode 100644 deploy/build-release.sh create mode 100644 deploy/release.sh diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..516ff90 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,29 @@ +name: Deploy Rust Bedrock + +on: + push: + branches: [main] + +concurrency: + group: bedrock-rust-deploy + cancel-in-progress: false + +jobs: + deploy: + if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push' + runs-on: ces-control + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Build the Rust release + run: bash deploy/build-release.sh + - name: Publish and initialize Bedrock storage + env: + BEDROCK_PG_HOST: ${{ vars.BEDROCK_PG_HOST }} + BEDROCK_PG_PORT: ${{ vars.BEDROCK_PG_PORT }} + BEDROCK_PG_DATABASE: ${{ vars.BEDROCK_PG_DATABASE }} + BEDROCK_PG_USER: ${{ vars.BEDROCK_PG_USER }} + BEDROCK_PG_PASSWORD: ${{ secrets.BEDROCK_PG_PASSWORD }} + run: bash deploy/release.sh target/bedrock-release/bedrock "$GITHUB_SHA" diff --git a/deploy/README.md b/deploy/README.md index b5ae7b9..fb57ebb 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,3 +9,7 @@ Deployments pass the path of a JSON configuration file to the Bedrock executable Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. The SQL renderer and crates have no S3 dependency. Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner. + +## Release on the existing deployment host + +Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs the current one-shot Rust storage initializer on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes. diff --git a/deploy/build-release.sh b/deploy/build-release.sh new file mode 100644 index 0000000..546f0eb --- /dev/null +++ b/deploy/build-release.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail + +output="$PWD/target/bedrock-release" +mkdir -p "$output" +docker run --rm \ + --mount "type=bind,source=$PWD,target=/work,readonly" \ + --mount "type=bind,source=$output,target=/out" \ + -w /work -e CARGO_TARGET_DIR=/tmp/bedrock-target \ + rust:1.91.1-bookworm sh -ec ' + cargo build --locked --release --bin bedrock + install -m 755 /tmp/bedrock-target/release/bedrock /out/bedrock + ' diff --git a/deploy/release.sh b/deploy/release.sh new file mode 100644 index 0000000..57fb953 --- /dev/null +++ b/deploy/release.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +binary=${1:?Path to the built Bedrock executable is required} +revision=${2:?Git commit is required} +if [[ ! $revision =~ ^[0-9a-f]{40}$ || ! -x $binary ]]; then + printf 'Invalid release commit or executable\n' >&2 + exit 1 +fi + +infra=/opt/endoleap-infra +root=$infra/bedrock-rust +network=endoleap-dev_default +test -d "$infra" +test ! -L "$root" +docker network inspect "$network" >/dev/null +install -d -m 700 "$root/releases" + +stage=$(mktemp -d "$root/releases/.staging.XXXXXXXX") +cleanup() { rm -rf -- "$stage"; } +trap cleanup EXIT +install -m 755 "$binary" "$stage/bedrock" +python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.json" --deployment production + +# The current binary is a one-shot storage initializer. It publishes no ports. +docker run --rm --network "$network" \ + --user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \ + --mount "type=bind,source=$stage,target=/release,readonly" \ + -e BEDROCK_DB_CONFIG=/release/bedrock.json \ + debian:bookworm-slim /release/bedrock + +release="$revision.${stage##*.}" +# Keep the final release private; only switch current after initialization succeeds. +python3 - "$stage" "$root" "$release" <<'PY' +import os +from pathlib import Path +import sys +import tempfile + +stage, root, release = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3] +destination = Path("releases") / release +stage.rename(root / destination) +with tempfile.TemporaryDirectory(prefix=".activate.", dir=root) as activation: + link = Path(activation) / "current" + link.symlink_to(destination) + os.replace(link, root / "current") +PY +printf 'Published Bedrock Rust release %s\n' "$release" -- 2.52.0 From d31cd5615e16531152635a192bb0f5659536b748 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 00:53:05 +0800 Subject: [PATCH 05/13] Move cluster configuration test to integration tests --- crates/clusters/src/lib.rs | 43 ---------------------- crates/clusters/tests/deployment_config.rs | 41 +++++++++++++++++++++ 2 files changed, 41 insertions(+), 43 deletions(-) create mode 100644 crates/clusters/tests/deployment_config.rs diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index 4d30fce..6fe4767 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -227,46 +227,3 @@ fn sqlite_url(path: &str, read_only: bool) -> Result { let mode = if read_only { "ro" } else { "rwc" }; Ok(Address(format!("sqlite:{file}?mode={mode}"))) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn named_cluster_requires_matching_addresses_and_redacts_credentials() { - let mut config = DeploymentConfig { - cluster: Some("regional".into()), - clusters: BTreeMap::from([( - "regional".into(), - Cluster { - driver: Driver::Postgres, - primary: "postgres://user:secret@primary/bedrock".into(), - replicas: vec!["postgresql://reader:secret@replica/bedrock".into()], - tls: Tls::VerifyFull, - max_connections: 5, - }, - )]), - ..DeploymentConfig::default() - }; - let resolved = config.resolve().unwrap(); - assert!( - resolved - .primary - .connection_string() - .ends_with("sslmode=verify-full") - ); - assert!( - resolved.replicas[0] - .connection_string() - .ends_with("sslmode=verify-full") - ); - assert!(!format!("{resolved:?}").contains("secret")); - - config.clusters.get_mut("regional").unwrap().replicas[0] = - "mysql://user:secret@replica/bedrock".into(); - assert!(matches!( - config.resolve(), - Err(ConfigError::Url("postgres")) - )); - } -} diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs new file mode 100644 index 0000000..46bf1f0 --- /dev/null +++ b/crates/clusters/tests/deployment_config.rs @@ -0,0 +1,41 @@ +use std::collections::BTreeMap; + +use clusters::{Cluster, ConfigError, DeploymentConfig, Driver, Tls}; + +#[test] +fn named_cluster_requires_matching_addresses_and_redacts_credentials() { + let mut config = DeploymentConfig { + cluster: Some("regional".into()), + clusters: BTreeMap::from([( + "regional".into(), + Cluster { + driver: Driver::Postgres, + primary: "postgres://user:secret@primary/bedrock".into(), + replicas: vec!["postgresql://reader:secret@replica/bedrock".into()], + tls: Tls::VerifyFull, + max_connections: 5, + }, + )]), + ..DeploymentConfig::default() + }; + let resolved = config.resolve().unwrap(); + assert!( + resolved + .primary + .connection_string() + .ends_with("sslmode=verify-full") + ); + assert!( + resolved.replicas[0] + .connection_string() + .ends_with("sslmode=verify-full") + ); + assert!(!format!("{resolved:?}").contains("secret")); + + config.clusters.get_mut("regional").unwrap().replicas[0] = + "mysql://user:secret@replica/bedrock".into(); + assert!(matches!( + config.resolve(), + Err(ConfigError::Url("postgres")) + )); +} -- 2.52.0 From 55d66d5d9ba7965a4c501310cdfa87f7325813ac Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 01:17:13 +0800 Subject: [PATCH 06/13] Embed the deployment flow in deployment and CI docs --- ci/README.md | 5 ++ deploy/README.md | 2 + deploy/bedrock-deployment.svg | 105 ++++++++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 ci/README.md create mode 100644 deploy/bedrock-deployment.svg diff --git a/ci/README.md b/ci/README.md new file mode 100644 index 0000000..ddef802 --- /dev/null +++ b/ci/README.md @@ -0,0 +1,5 @@ +# Manual SQL verification + +`ci/check-sql.sh` runs storage checks against SQLite and temporary PostgreSQL and MySQL containers. Run it from the workspace root on an approved remote runner. It removes its test containers and network on exit. + +![Bedrock deployment and manual SQL verification flow](../deploy/bedrock-deployment.svg) diff --git a/deploy/README.md b/deploy/README.md index fb57ebb..b7f1139 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -13,3 +13,5 @@ Pull requests currently run without an automatic storage check. The optional `ci ## Release on the existing deployment host Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs the current one-shot Rust storage initializer on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes. + +![Bedrock deployment and manual SQL verification flow](./bedrock-deployment.svg) diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg new file mode 100644 index 0000000..59c165d --- /dev/null +++ b/deploy/bedrock-deployment.svg @@ -0,0 +1,105 @@ + +Bedrock 的部署与手动验证流程 +main 提交触发 Gitea CD。release.sh 调用配置渲染器并启动临时容器。容器内 Rust Bedrock 初始化已有 PostgreSQL 数据库中的 Bedrock 表。另有独立手动检查路径。 + + + + + + + + + + + + + +BEDROCK / DEPLOYMENT +Bedrock 的部署与手动验证流程 +CD · 原部署机 +手动验证 + + + + + + + + + + + + + + + + +main 收到提交 + +deploy.yml +Gitea 在 ces-control 上检出代码并编排部署。 + +build-release.sh +在 Rust 容器内编译 release,输出 Bedrock 二进制。 +二进制路径与 Git SHA 交给发布脚本 + +release.sh +建立暂存目录,放入二进制。 + +Gitea 部署配置 +PostgreSQL Variables +和密码 Secret + +render-postgres.py +由 release.sh 调用,生成权限为 0600 的 bedrock.json。 + +release.sh 启动临时容器 +挂载二进制和配置,运行 Rust bedrock。 + + +Rust Bedrock 读取配置 +通过 db_connection 选择 postgres。 +配置由 BEDROCK_DB_CONFIG 指定。 + +在已有 PostgreSQL 数据库内初始化 +postgres 提供 SQL,persistence 在事务里执行。 +创建 Bedrock 表并登记 production 部署。 +进入 Store::initialize() +成功 +失败 + + +保存版本并切换 current + +清理暂存目录,保留上一版 current + +手动运行 + +ci/check-sql.sh +脚本独立于部署工作流。 + +准备隔离环境 +启动临时 PostgreSQL 和 MySQL。 +SQLite 使用临时本地文件。 + +运行三库检查 +执行格式检查、测试、构建, +验证 SQLite 默认启动。 + +退出时清理 +删除测试容器和临时网络。 + \ No newline at end of file -- 2.52.0 From 2f2a39621cc161bcd63086a109aa951996790d3a Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 03:43:47 +0800 Subject: [PATCH 07/13] Consolidate SQL backends into persistence modules --- Cargo.lock | 28 ------------------- Cargo.toml | 3 -- README.md | 2 +- crates/db_connection/Cargo.toml | 4 --- crates/db_connection/src/lib.rs | 4 +-- crates/mysql/Cargo.toml | 9 ------ crates/persistence/Cargo.toml | 2 +- crates/persistence/src/lib.rs | 6 +++- .../src/lib.rs => persistence/src/mysql.rs} | 2 +- .../lib.rs => persistence/src/postgres.rs} | 2 +- .../src/lib.rs => persistence/src/sqlite.rs} | 2 +- crates/postgres/Cargo.toml | 9 ------ crates/sqlite/Cargo.toml | 9 ------ deploy/bedrock-deployment.svg | 2 +- 14 files changed, 13 insertions(+), 71 deletions(-) delete mode 100644 crates/mysql/Cargo.toml rename crates/{mysql/src/lib.rs => persistence/src/mysql.rs} (99%) rename crates/{postgres/src/lib.rs => persistence/src/postgres.rs} (95%) rename crates/{sqlite/src/lib.rs => persistence/src/sqlite.rs} (95%) delete mode 100644 crates/postgres/Cargo.toml delete mode 100644 crates/sqlite/Cargo.toml diff --git a/Cargo.lock b/Cargo.lock index fb16ff8..b23b241 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -159,12 +159,8 @@ name = "db_connection" version = "0.1.0" dependencies = [ "clusters", - "mysql", "persistence", - "postgres", "serde_json", - "sqlite", - "sqlx", "tempfile", "thiserror", "tokio", @@ -680,14 +676,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "mysql" -version = "0.1.0" -dependencies = [ - "persistence", - "sqlx", -] - [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -831,14 +819,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" -[[package]] -name = "postgres" -version = "0.1.0" -dependencies = [ - "persistence", - "sqlx", -] - [[package]] name = "potential_utf" version = "0.1.6" @@ -1159,14 +1139,6 @@ dependencies = [ "der", ] -[[package]] -name = "sqlite" -version = "0.1.0" -dependencies = [ - "persistence", - "sqlx", -] - [[package]] name = "sqlx" version = "0.8.6" diff --git a/Cargo.toml b/Cargo.toml index 533566c..c574d7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,6 @@ rust-version = "1.91" clusters = { path = "crates/clusters" } db_connection = { path = "crates/db_connection" } persistence = { path = "crates/persistence" } -sqlite = { path = "crates/sqlite" } -postgres = { path = "crates/postgres" } -mysql = { path = "crates/mysql" } serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } diff --git a/README.md b/README.md index 1103162..0365b65 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bedrock storage -Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. +Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `persistence` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example: diff --git a/crates/db_connection/Cargo.toml b/crates/db_connection/Cargo.toml index 13b09a1..2ac602b 100644 --- a/crates/db_connection/Cargo.toml +++ b/crates/db_connection/Cargo.toml @@ -6,14 +6,10 @@ rust-version.workspace = true [dependencies] clusters.workspace = true -mysql.workspace = true persistence.workspace = true -postgres.workspace = true -sqlite.workspace = true thiserror.workspace = true [dev-dependencies] serde_json.workspace = true -sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } tempfile.workspace = true tokio.workspace = true diff --git a/crates/db_connection/src/lib.rs b/crates/db_connection/src/lib.rs index 23f6b92..2dc78d9 100644 --- a/crates/db_connection/src/lib.rs +++ b/crates/db_connection/src/lib.rs @@ -3,11 +3,11 @@ use std::sync::atomic::{AtomicUsize, Ordering}; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; -pub use mysql::{Lease, MySql}; +pub use persistence::mysql::{Lease, MySql}; pub use persistence::{Document, Error as StorageError, Mutation, Revision, Snapshot}; use clusters::ResolvedDeployment; -use persistence::{Reader, Store}; +use persistence::{Reader, Store, mysql, postgres, sqlite}; use thiserror::Error; #[derive(Debug, Error)] diff --git a/crates/mysql/Cargo.toml b/crates/mysql/Cargo.toml deleted file mode 100644 index c9b0559..0000000 --- a/crates/mysql/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "mysql" -version = "0.1.0" -edition.workspace = true -rust-version.workspace = true - -[dependencies] -persistence.workspace = true -sqlx = { workspace = true, features = ["mysql"] } diff --git a/crates/persistence/Cargo.toml b/crates/persistence/Cargo.toml index bf27ee2..8b7ed65 100644 --- a/crates/persistence/Cargo.toml +++ b/crates/persistence/Cargo.toml @@ -6,5 +6,5 @@ rust-version.workspace = true [dependencies] serde_json.workspace = true -sqlx.workspace = true +sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } thiserror.workspace = true diff --git a/crates/persistence/src/lib.rs b/crates/persistence/src/lib.rs index 51cb518..dedbf43 100644 --- a/crates/persistence/src/lib.rs +++ b/crates/persistence/src/lib.rs @@ -1,4 +1,8 @@ -//! Shared storage contract for Bedrock's SQL backends. +//! Shared storage contract and SQL backends for Bedrock. + +pub mod mysql; +pub mod postgres; +pub mod sqlite; use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; diff --git a/crates/mysql/src/lib.rs b/crates/persistence/src/mysql.rs similarity index 99% rename from crates/mysql/src/lib.rs rename to crates/persistence/src/mysql.rs index 031d506..e1a1e6d 100644 --- a/crates/mysql/src/lib.rs +++ b/crates/persistence/src/mysql.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; -use persistence::{ +use crate::{ Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, pool, }; diff --git a/crates/postgres/src/lib.rs b/crates/persistence/src/postgres.rs similarity index 95% rename from crates/postgres/src/lib.rs rename to crates/persistence/src/postgres.rs index 343c898..612dad9 100644 --- a/crates/postgres/src/lib.rs +++ b/crates/persistence/src/postgres.rs @@ -1,6 +1,6 @@ //! PostgreSQL connection pools and the Bedrock document layout. -use persistence::{Dialect, Reader, Result, Store, pool}; +use crate::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/sqlite/src/lib.rs b/crates/persistence/src/sqlite.rs similarity index 95% rename from crates/sqlite/src/lib.rs rename to crates/persistence/src/sqlite.rs index 09b483f..ee3ce1e 100644 --- a/crates/sqlite/src/lib.rs +++ b/crates/persistence/src/sqlite.rs @@ -1,6 +1,6 @@ //! File-backed Bedrock storage for self-hosted deployments. -use persistence::{Dialect, Reader, Result, Store, pool}; +use crate::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/postgres/Cargo.toml b/crates/postgres/Cargo.toml deleted file mode 100644 index 195f869..0000000 --- a/crates/postgres/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "postgres" -version = "0.1.0" -edition.workspace = true -rust-version.workspace = true - -[dependencies] -persistence.workspace = true -sqlx = { workspace = true, features = ["postgres"] } diff --git a/crates/sqlite/Cargo.toml b/crates/sqlite/Cargo.toml deleted file mode 100644 index 93e2f00..0000000 --- a/crates/sqlite/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "sqlite" -version = "0.1.0" -edition.workspace = true -rust-version.workspace = true - -[dependencies] -persistence.workspace = true -sqlx = { workspace = true, features = ["sqlite"] } diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 59c165d..2f62e66 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -76,7 +76,7 @@ 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres 提供 SQL,persistence 在事务里执行。 +postgres 模块提供 SQL,共用存储层在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功 -- 2.52.0 From bb15a7043c5f3735d1758fd77699039916dfb06e Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 03:47:24 +0800 Subject: [PATCH 08/13] Name the SQL document storage crate sql_storage --- Cargo.lock | 20 +++++++++---------- Cargo.toml | 2 +- README.md | 10 +++++++++- crates/db_connection/Cargo.toml | 2 +- crates/db_connection/src/lib.rs | 6 +++--- .../{persistence => sql_storage}/Cargo.toml | 2 +- .../{persistence => sql_storage}/src/lib.rs | 2 +- .../{persistence => sql_storage}/src/mysql.rs | 0 .../src/postgres.rs | 0 .../src/sqlite.rs | 0 deploy/README.md | 2 +- deploy/bedrock-deployment.svg | 2 +- 12 files changed, 28 insertions(+), 20 deletions(-) rename crates/{persistence => sql_storage}/Cargo.toml (91%) rename crates/{persistence => sql_storage}/src/lib.rs (99%) rename crates/{persistence => sql_storage}/src/mysql.rs (100%) rename crates/{persistence => sql_storage}/src/postgres.rs (100%) rename crates/{persistence => sql_storage}/src/sqlite.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index b23b241..55805f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -159,8 +159,8 @@ name = "db_connection" version = "0.1.0" dependencies = [ "clusters", - "persistence", "serde_json", + "sql_storage", "tempfile", "thiserror", "tokio", @@ -771,15 +771,6 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" -[[package]] -name = "persistence" -version = "0.1.0" -dependencies = [ - "serde_json", - "sqlx", - "thiserror", -] - [[package]] name = "pin-project-lite" version = "0.2.18" @@ -1139,6 +1130,15 @@ dependencies = [ "der", ] +[[package]] +name = "sql_storage" +version = "0.1.0" +dependencies = [ + "serde_json", + "sqlx", + "thiserror", +] + [[package]] name = "sqlx" version = "0.8.6" diff --git a/Cargo.toml b/Cargo.toml index c574d7a..baaaf58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ rust-version = "1.91" [workspace.dependencies] clusters = { path = "crates/clusters" } db_connection = { path = "crates/db_connection" } -persistence = { path = "crates/persistence" } +sql_storage = { path = "crates/sql_storage" } serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } diff --git a/README.md b/README.md index 0365b65..1bb5d2a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,14 @@ # Bedrock storage -Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `persistence` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. +Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `sql_storage` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. + +## Storage boundaries + +`sql_storage` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings and `db_connection` selects the SQL driver and read endpoints. + +Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) + +## Database configuration Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example: diff --git a/crates/db_connection/Cargo.toml b/crates/db_connection/Cargo.toml index 2ac602b..652c873 100644 --- a/crates/db_connection/Cargo.toml +++ b/crates/db_connection/Cargo.toml @@ -6,7 +6,7 @@ rust-version.workspace = true [dependencies] clusters.workspace = true -persistence.workspace = true +sql_storage.workspace = true thiserror.workspace = true [dev-dependencies] diff --git a/crates/db_connection/src/lib.rs b/crates/db_connection/src/lib.rs index 2dc78d9..123f7dd 100644 --- a/crates/db_connection/src/lib.rs +++ b/crates/db_connection/src/lib.rs @@ -3,11 +3,11 @@ use std::sync::atomic::{AtomicUsize, Ordering}; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; -pub use persistence::mysql::{Lease, MySql}; -pub use persistence::{Document, Error as StorageError, Mutation, Revision, Snapshot}; +pub use sql_storage::mysql::{Lease, MySql}; +pub use sql_storage::{Document, Error as StorageError, Mutation, Revision, Snapshot}; use clusters::ResolvedDeployment; -use persistence::{Reader, Store, mysql, postgres, sqlite}; +use sql_storage::{Reader, Store, mysql, postgres, sqlite}; use thiserror::Error; #[derive(Debug, Error)] diff --git a/crates/persistence/Cargo.toml b/crates/sql_storage/Cargo.toml similarity index 91% rename from crates/persistence/Cargo.toml rename to crates/sql_storage/Cargo.toml index 8b7ed65..09251b4 100644 --- a/crates/persistence/Cargo.toml +++ b/crates/sql_storage/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "persistence" +name = "sql_storage" version = "0.1.0" edition.workspace = true rust-version.workspace = true diff --git a/crates/persistence/src/lib.rs b/crates/sql_storage/src/lib.rs similarity index 99% rename from crates/persistence/src/lib.rs rename to crates/sql_storage/src/lib.rs index dedbf43..c2a1d60 100644 --- a/crates/persistence/src/lib.rs +++ b/crates/sql_storage/src/lib.rs @@ -1,4 +1,4 @@ -//! Shared storage contract and SQL backends for Bedrock. +//! Bedrock's transactional document storage for SQL databases. pub mod mysql; pub mod postgres; diff --git a/crates/persistence/src/mysql.rs b/crates/sql_storage/src/mysql.rs similarity index 100% rename from crates/persistence/src/mysql.rs rename to crates/sql_storage/src/mysql.rs diff --git a/crates/persistence/src/postgres.rs b/crates/sql_storage/src/postgres.rs similarity index 100% rename from crates/persistence/src/postgres.rs rename to crates/sql_storage/src/postgres.rs diff --git a/crates/persistence/src/sqlite.rs b/crates/sql_storage/src/sqlite.rs similarity index 100% rename from crates/persistence/src/sqlite.rs rename to crates/sql_storage/src/sqlite.rs diff --git a/deploy/README.md b/deploy/README.md index b7f1139..e253b9f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -6,7 +6,7 @@ Deployments pass the path of a JSON configuration file to the Bedrock executable - **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address. - **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint. -Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. The SQL renderer and crates have no S3 dependency. +Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `sql_storage` use only SQL configuration. Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner. diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 2f62e66..ae00a0f 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -76,7 +76,7 @@ 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres 模块提供 SQL,共用存储层在事务里执行。 +postgres 模块提供 SQL,sql_storage 在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功 -- 2.52.0 From 36184b07a0e0d8f8cc0f2ac2ba3546c5094741fd Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 03:50:39 +0800 Subject: [PATCH 09/13] Move SQL connection routing into sql_storage --- Cargo.lock | 17 ++++------------- Cargo.toml | 3 +-- README.md | 4 ++-- crates/db_connection/Cargo.toml | 15 --------------- crates/sql_storage/Cargo.toml | 5 +++++ .../lib.rs => sql_storage/src/connection.rs} | 13 +++++++------ crates/sql_storage/src/lib.rs | 6 ++++++ .../tests/storage.rs | 4 ++-- deploy/bedrock-deployment.svg | 2 +- src/main.rs | 2 +- 10 files changed, 29 insertions(+), 42 deletions(-) delete mode 100644 crates/db_connection/Cargo.toml rename crates/{db_connection/src/lib.rs => sql_storage/src/connection.rs} (93%) rename crates/{db_connection => sql_storage}/tests/storage.rs (99%) diff --git a/Cargo.lock b/Cargo.lock index 55805f1..67dcf8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -39,8 +39,8 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" name = "bedrock" version = "0.1.0" dependencies = [ - "db_connection", "serde_json", + "sql_storage", "tokio", ] @@ -154,18 +154,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "db_connection" -version = "0.1.0" -dependencies = [ - "clusters", - "serde_json", - "sql_storage", - "tempfile", - "thiserror", - "tokio", -] - [[package]] name = "der" version = "0.7.10" @@ -1134,9 +1122,12 @@ dependencies = [ name = "sql_storage" version = "0.1.0" dependencies = [ + "clusters", "serde_json", "sqlx", + "tempfile", "thiserror", + "tokio", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index baaaf58..d09f87b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ rust-version = "1.91" [workspace.dependencies] clusters = { path = "crates/clusters" } -db_connection = { path = "crates/db_connection" } sql_storage = { path = "crates/sql_storage" } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -25,6 +24,6 @@ edition.workspace = true rust-version.workspace = true [dependencies] -db_connection.workspace = true +sql_storage.workspace = true serde_json.workspace = true tokio.workspace = true diff --git a/README.md b/README.md index 1bb5d2a..713291d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i ## Storage boundaries -`sql_storage` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings and `db_connection` selects the SQL driver and read endpoints. +`sql_storage` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `sql_storage` connection module selects the SQL driver and read endpoints. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) @@ -29,7 +29,7 @@ Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration t The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file. -Applications connect with `db_connection::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. +Applications connect with `sql_storage::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database. diff --git a/crates/db_connection/Cargo.toml b/crates/db_connection/Cargo.toml deleted file mode 100644 index 652c873..0000000 --- a/crates/db_connection/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "db_connection" -version = "0.1.0" -edition.workspace = true -rust-version.workspace = true - -[dependencies] -clusters.workspace = true -sql_storage.workspace = true -thiserror.workspace = true - -[dev-dependencies] -serde_json.workspace = true -tempfile.workspace = true -tokio.workspace = true diff --git a/crates/sql_storage/Cargo.toml b/crates/sql_storage/Cargo.toml index 09251b4..6c143ed 100644 --- a/crates/sql_storage/Cargo.toml +++ b/crates/sql_storage/Cargo.toml @@ -5,6 +5,11 @@ edition.workspace = true rust-version.workspace = true [dependencies] +clusters.workspace = true serde_json.workspace = true sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } thiserror.workspace = true + +[dev-dependencies] +tempfile.workspace = true +tokio.workspace = true diff --git a/crates/db_connection/src/lib.rs b/crates/sql_storage/src/connection.rs similarity index 93% rename from crates/db_connection/src/lib.rs rename to crates/sql_storage/src/connection.rs index 123f7dd..33afeaf 100644 --- a/crates/db_connection/src/lib.rs +++ b/crates/sql_storage/src/connection.rs @@ -2,14 +2,15 @@ use std::sync::atomic::{AtomicUsize, Ordering}; -pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; -pub use sql_storage::mysql::{Lease, MySql}; -pub use sql_storage::{Document, Error as StorageError, Mutation, Revision, Snapshot}; - -use clusters::ResolvedDeployment; -use sql_storage::{Reader, Store, mysql, postgres, sqlite}; +use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment}; use thiserror::Error; +use crate::{ + Error as StorageError, Mutation, Reader, Revision, Snapshot, Store, + mysql::{self, MySql}, + postgres, sqlite, +}; + #[derive(Debug, Error)] pub enum ConnectError { #[error(transparent)] diff --git a/crates/sql_storage/src/lib.rs b/crates/sql_storage/src/lib.rs index c2a1d60..887d9a4 100644 --- a/crates/sql_storage/src/lib.rs +++ b/crates/sql_storage/src/lib.rs @@ -1,9 +1,15 @@ //! Bedrock's transactional document storage for SQL databases. +mod connection; pub mod mysql; pub mod postgres; pub mod sqlite; +pub use Error as StorageError; +pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; +pub use connection::{ConnectError, Connection, ReadPreference, connect}; +pub use mysql::{Lease, MySql}; + use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; use serde_json::Value; diff --git a/crates/db_connection/tests/storage.rs b/crates/sql_storage/tests/storage.rs similarity index 99% rename from crates/db_connection/tests/storage.rs rename to crates/sql_storage/tests/storage.rs index 245957f..8631144 100644 --- a/crates/db_connection/tests/storage.rs +++ b/crates/sql_storage/tests/storage.rs @@ -1,10 +1,10 @@ use std::{collections::BTreeMap, env, time::Duration}; -use db_connection::{ +use serde_json::json; +use sql_storage::{ Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls, connect, }; -use serde_json::json; fn change(id: &str, text: &str) -> Mutation { Mutation { diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index ae00a0f..0b15e4d 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -72,7 +72,7 @@ Rust Bedrock 读取配置 -通过 db_connection 选择 postgres。 +通过 sql_storage::connect 选择 postgres。 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 diff --git a/src/main.rs b/src/main.rs index ae7d0f0..604cba9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::{env, error::Error, fs}; -use db_connection::{DeploymentConfig, connect}; +use sql_storage::{DeploymentConfig, connect}; #[tokio::main] async fn main() -> Result<(), Box> { -- 2.52.0 From 6b34a11dbb14c160cba0256de7e9455d1be73ea9 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 04:00:38 +0800 Subject: [PATCH 10/13] Rename the SQL storage crate to sql --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- README.md | 6 +++--- crates/{sql_storage => sql}/Cargo.toml | 2 +- crates/{sql_storage => sql}/src/connection.rs | 0 crates/{sql_storage => sql}/src/lib.rs | 0 crates/{sql_storage => sql}/src/mysql.rs | 0 crates/{sql_storage => sql}/src/postgres.rs | 0 crates/{sql_storage => sql}/src/sqlite.rs | 0 crates/{sql_storage => sql}/tests/storage.rs | 2 +- deploy/README.md | 2 +- deploy/bedrock-deployment.svg | 4 ++-- src/main.rs | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) rename crates/{sql_storage => sql}/Cargo.toml (93%) rename crates/{sql_storage => sql}/src/connection.rs (100%) rename crates/{sql_storage => sql}/src/lib.rs (100%) rename crates/{sql_storage => sql}/src/mysql.rs (100%) rename crates/{sql_storage => sql}/src/postgres.rs (100%) rename crates/{sql_storage => sql}/src/sqlite.rs (100%) rename crates/{sql_storage => sql}/tests/storage.rs (99%) diff --git a/Cargo.lock b/Cargo.lock index 67dcf8e..32586c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,7 +40,7 @@ name = "bedrock" version = "0.1.0" dependencies = [ "serde_json", - "sql_storage", + "sql", "tokio", ] @@ -1119,7 +1119,7 @@ dependencies = [ ] [[package]] -name = "sql_storage" +name = "sql" version = "0.1.0" dependencies = [ "clusters", diff --git a/Cargo.toml b/Cargo.toml index d09f87b..7b54633 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ rust-version = "1.91" [workspace.dependencies] clusters = { path = "crates/clusters" } -sql_storage = { path = "crates/sql_storage" } +sql = { path = "crates/sql" } serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } @@ -24,6 +24,6 @@ edition.workspace = true rust-version.workspace = true [dependencies] -sql_storage.workspace = true +sql.workspace = true serde_json.workspace = true tokio.workspace = true diff --git a/README.md b/README.md index 713291d..413704e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Bedrock storage -Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `sql_storage` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. +Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `sql` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. ## Storage boundaries -`sql_storage` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `sql_storage` connection module selects the SQL driver and read endpoints. +`sql` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `sql` connection module selects the SQL driver and read endpoints. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) @@ -29,7 +29,7 @@ Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration t The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file. -Applications connect with `sql_storage::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. +Applications connect with `sql::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database. diff --git a/crates/sql_storage/Cargo.toml b/crates/sql/Cargo.toml similarity index 93% rename from crates/sql_storage/Cargo.toml rename to crates/sql/Cargo.toml index 6c143ed..65cf2b4 100644 --- a/crates/sql_storage/Cargo.toml +++ b/crates/sql/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "sql_storage" +name = "sql" version = "0.1.0" edition.workspace = true rust-version.workspace = true diff --git a/crates/sql_storage/src/connection.rs b/crates/sql/src/connection.rs similarity index 100% rename from crates/sql_storage/src/connection.rs rename to crates/sql/src/connection.rs diff --git a/crates/sql_storage/src/lib.rs b/crates/sql/src/lib.rs similarity index 100% rename from crates/sql_storage/src/lib.rs rename to crates/sql/src/lib.rs diff --git a/crates/sql_storage/src/mysql.rs b/crates/sql/src/mysql.rs similarity index 100% rename from crates/sql_storage/src/mysql.rs rename to crates/sql/src/mysql.rs diff --git a/crates/sql_storage/src/postgres.rs b/crates/sql/src/postgres.rs similarity index 100% rename from crates/sql_storage/src/postgres.rs rename to crates/sql/src/postgres.rs diff --git a/crates/sql_storage/src/sqlite.rs b/crates/sql/src/sqlite.rs similarity index 100% rename from crates/sql_storage/src/sqlite.rs rename to crates/sql/src/sqlite.rs diff --git a/crates/sql_storage/tests/storage.rs b/crates/sql/tests/storage.rs similarity index 99% rename from crates/sql_storage/tests/storage.rs rename to crates/sql/tests/storage.rs index 8631144..96580a8 100644 --- a/crates/sql_storage/tests/storage.rs +++ b/crates/sql/tests/storage.rs @@ -1,7 +1,7 @@ use std::{collections::BTreeMap, env, time::Duration}; use serde_json::json; -use sql_storage::{ +use sql::{ Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls, connect, }; diff --git a/deploy/README.md b/deploy/README.md index e253b9f..756d0ab 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -6,7 +6,7 @@ Deployments pass the path of a JSON configuration file to the Bedrock executable - **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address. - **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint. -Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `sql_storage` use only SQL configuration. +Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `sql` use only SQL configuration. Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner. diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 0b15e4d..9733078 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -72,11 +72,11 @@ Rust Bedrock 读取配置 -通过 sql_storage::connect 选择 postgres。 +通过 sql::connect 选择 postgres。 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres 模块提供 SQL,sql_storage 在事务里执行。 +postgres 模块提供 SQL,sql 在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功 diff --git a/src/main.rs b/src/main.rs index 604cba9..9404e66 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::{env, error::Error, fs}; -use sql_storage::{DeploymentConfig, connect}; +use sql::{DeploymentConfig, connect}; #[tokio::main] async fn main() -> Result<(), Box> { -- 2.52.0 From 81b70f0046440293000c8e7391a495a5fdcc5f43 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 04:09:40 +0800 Subject: [PATCH 11/13] Rename the database crate to db --- Cargo.lock | 26 +++++++++++++------------- Cargo.toml | 4 ++-- README.md | 6 +++--- crates/{sql => db}/Cargo.toml | 2 +- crates/{sql => db}/src/connection.rs | 0 crates/{sql => db}/src/lib.rs | 0 crates/{sql => db}/src/mysql.rs | 0 crates/{sql => db}/src/postgres.rs | 0 crates/{sql => db}/src/sqlite.rs | 0 crates/{sql => db}/tests/storage.rs | 4 ++-- deploy/README.md | 2 +- deploy/bedrock-deployment.svg | 4 ++-- src/main.rs | 2 +- 13 files changed, 25 insertions(+), 25 deletions(-) rename crates/{sql => db}/Cargo.toml (96%) rename crates/{sql => db}/src/connection.rs (100%) rename crates/{sql => db}/src/lib.rs (100%) rename crates/{sql => db}/src/mysql.rs (100%) rename crates/{sql => db}/src/postgres.rs (100%) rename crates/{sql => db}/src/sqlite.rs (100%) rename crates/{sql => db}/tests/storage.rs (99%) diff --git a/Cargo.lock b/Cargo.lock index 32586c3..a2ca10a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -39,8 +39,8 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" name = "bedrock" version = "0.1.0" dependencies = [ + "db", "serde_json", - "sql", "tokio", ] @@ -154,6 +154,18 @@ dependencies = [ "typenum", ] +[[package]] +name = "db" +version = "0.1.0" +dependencies = [ + "clusters", + "serde_json", + "sqlx", + "tempfile", + "thiserror", + "tokio", +] + [[package]] name = "der" version = "0.7.10" @@ -1118,18 +1130,6 @@ dependencies = [ "der", ] -[[package]] -name = "sql" -version = "0.1.0" -dependencies = [ - "clusters", - "serde_json", - "sqlx", - "tempfile", - "thiserror", - "tokio", -] - [[package]] name = "sqlx" version = "0.8.6" diff --git a/Cargo.toml b/Cargo.toml index 7b54633..08da929 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ rust-version = "1.91" [workspace.dependencies] clusters = { path = "crates/clusters" } -sql = { path = "crates/sql" } +db = { path = "crates/db" } serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } @@ -24,6 +24,6 @@ edition.workspace = true rust-version.workspace = true [dependencies] -sql.workspace = true +db.workspace = true serde_json.workspace = true tokio.workspace = true diff --git a/README.md b/README.md index 413704e..259e9f2 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Bedrock storage -Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `sql` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. +Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `db` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start. ## Storage boundaries -`sql` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `sql` connection module selects the SQL driver and read endpoints. +`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) @@ -29,7 +29,7 @@ Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration t The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file. -Applications connect with `sql::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. +Applications connect with `db::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database. diff --git a/crates/sql/Cargo.toml b/crates/db/Cargo.toml similarity index 96% rename from crates/sql/Cargo.toml rename to crates/db/Cargo.toml index 65cf2b4..9717099 100644 --- a/crates/sql/Cargo.toml +++ b/crates/db/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "sql" +name = "db" version = "0.1.0" edition.workspace = true rust-version.workspace = true diff --git a/crates/sql/src/connection.rs b/crates/db/src/connection.rs similarity index 100% rename from crates/sql/src/connection.rs rename to crates/db/src/connection.rs diff --git a/crates/sql/src/lib.rs b/crates/db/src/lib.rs similarity index 100% rename from crates/sql/src/lib.rs rename to crates/db/src/lib.rs diff --git a/crates/sql/src/mysql.rs b/crates/db/src/mysql.rs similarity index 100% rename from crates/sql/src/mysql.rs rename to crates/db/src/mysql.rs diff --git a/crates/sql/src/postgres.rs b/crates/db/src/postgres.rs similarity index 100% rename from crates/sql/src/postgres.rs rename to crates/db/src/postgres.rs diff --git a/crates/sql/src/sqlite.rs b/crates/db/src/sqlite.rs similarity index 100% rename from crates/sql/src/sqlite.rs rename to crates/db/src/sqlite.rs diff --git a/crates/sql/tests/storage.rs b/crates/db/tests/storage.rs similarity index 99% rename from crates/sql/tests/storage.rs rename to crates/db/tests/storage.rs index 96580a8..baea0f5 100644 --- a/crates/sql/tests/storage.rs +++ b/crates/db/tests/storage.rs @@ -1,10 +1,10 @@ use std::{collections::BTreeMap, env, time::Duration}; -use serde_json::json; -use sql::{ +use db::{ Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls, connect, }; +use serde_json::json; fn change(id: &str, text: &str) -> Mutation { Mutation { diff --git a/deploy/README.md b/deploy/README.md index 756d0ab..45d8eaa 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -6,7 +6,7 @@ Deployments pass the path of a JSON configuration file to the Bedrock executable - **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address. - **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint. -Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `sql` use only SQL configuration. +Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `db` use only SQL configuration. Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner. diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 9733078..2c7feab 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -72,11 +72,11 @@ Rust Bedrock 读取配置 -通过 sql::connect 选择 postgres。 +通过 db::connect 选择 postgres。 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres 模块提供 SQL,sql 在事务里执行。 +postgres 模块提供 SQL,db 在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功 diff --git a/src/main.rs b/src/main.rs index 9404e66..5036bf6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::{env, error::Error, fs}; -use sql::{DeploymentConfig, connect}; +use db::{DeploymentConfig, connect}; #[tokio::main] async fn main() -> Result<(), Box> { -- 2.52.0 From 6c51e6881747369302c0568c7b29dcba4f5af364 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 04:35:54 +0800 Subject: [PATCH 12/13] Separate shared database implementation from crate exports --- README.md | 2 +- crates/db/src/connection.rs | 2 +- crates/db/src/lib.rs | 391 +--------------------------------- crates/db/src/mysql.rs | 2 +- crates/db/src/postgres.rs | 2 +- crates/db/src/sqlite.rs | 2 +- crates/db/src/store.rs | 386 +++++++++++++++++++++++++++++++++ deploy/bedrock-deployment.svg | 2 +- 8 files changed, 398 insertions(+), 391 deletions(-) create mode 100644 crates/db/src/store.rs diff --git a/README.md b/README.md index 259e9f2..2aaed51 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i ## Storage boundaries -`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. +`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `store.rs`. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 33afeaf..0fa87d0 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -6,9 +6,9 @@ use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeploymen use thiserror::Error; use crate::{ - Error as StorageError, Mutation, Reader, Revision, Snapshot, Store, mysql::{self, MySql}, postgres, sqlite, + store::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store}, }; #[derive(Debug, Error)] diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 887d9a4..b5cb6b1 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -4,393 +4,14 @@ mod connection; pub mod mysql; pub mod postgres; pub mod sqlite; +mod store; -pub use Error as StorageError; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use connection::{ConnectError, Connection, ReadPreference, connect}; pub use mysql::{Lease, MySql}; -use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; - -use serde_json::Value; -use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions}; -use thiserror::Error; - -pub type Revision = i64; -pub type Result = std::result::Result; - -#[derive(Debug, Error)] -pub enum Error { - #[error("invalid {0}")] - Invalid(&'static str), - #[error("the database connection failed")] - Connection, - #[error("SQL operation failed: {0}")] - Sql(#[from] sqlx::Error), - #[error("document encoding failed: {0}")] - Encoding(#[from] serde_json::Error), - #[error("the connection is read-only")] - ReadOnly, - #[error("the deployment is missing or retired")] - MissingDeployment, - #[error("database is at revision {available}, requested revision {requested}")] - Behind { - requested: Revision, - available: Revision, - }, - #[error("the write conflicts with the current revision or lease")] - WriteConflict, - #[error("lease is missing, expired, or belongs to another store")] - LeaseLost, -} - -impl Error { - pub fn retry_on_primary(&self) -> bool { - match self { - Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true, - Self::Sql(error) => match error { - sqlx::Error::Io(_) - | sqlx::Error::Tls(_) - | sqlx::Error::PoolTimedOut - | sqlx::Error::PoolClosed - | sqlx::Error::WorkerCrashed => true, - sqlx::Error::Database(db) => db.code().is_some_and(|code| { - code.starts_with("08") - || matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146") - }), - _ => false, - }, - _ => false, - } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Document { - pub revision: Revision, - pub value: Value, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Snapshot { - pub revision: Revision, - pub document: Option, -} - -#[derive(Clone, Debug)] -pub struct Mutation { - pub collection: String, - pub id: String, - /// None writes a tombstone. Some(Value::Null) stores a JSON null. - pub value: Option, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Dialect { - Sqlite, - Postgres, - Mysql, -} - -/// Opened SQL reader. Its pool is private so callers cannot bypass the read API. -#[derive(Clone)] -pub struct Reader { - pool: AnyPool, - dialect: Dialect, - deployment: Vec, -} - -#[derive(Clone)] -pub struct Store { - reader: Reader, -} - -/// Returns a lazily connected pool. The writer initializes schema before use. -#[doc(hidden)] -pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result { - if connections == 0 { - return Err(Error::Invalid("database pool size")); - } - sqlx::any::install_default_drivers(); - let mut options = AnyPoolOptions::new() - .max_connections(connections) - .acquire_timeout(Duration::from_secs(5)); - let read_only_statement = match dialect { - Dialect::Sqlite => "PRAGMA query_only = ON", - Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", - Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY", - }; - if read_only { - options = options.after_connect(move |connection, _| { - Box::pin(async move { - sqlx::query(read_only_statement).execute(connection).await?; - Ok(()) - }) - }); - } - options.connect_lazy(url).map_err(|_| Error::Connection) -} - -impl Reader { - #[doc(hidden)] - pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result { - validate_id(deployment)?; - Ok(Self { - pool, - dialect, - deployment: deployment.as_bytes().to_vec(), - }) - } - - pub async fn revision(&self) -> Result { - let statement = statement( - self.dialect, - "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", - ); - sqlx::query_scalar(&statement) - .bind(self.deployment.as_slice()) - .fetch_optional(&self.pool) - .await - .map_err(connection_error)? - .ok_or(Error::MissingDeployment) - } - - /// Fetch at the latest revision or at an exact, previously committed snapshot. - pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { - validate_id(collection)?; - validate_id(id)?; - if at.is_some_and(|at| at < 0) { - return Err(Error::Invalid("snapshot revision")); - } - // A single statement keeps the revision and document on the same database snapshot. - let statement = statement( - self.dialect, - " - SELECT d.revision AS available, v.revision AS document_revision, v.payload - FROM bedrock_deployments d - LEFT JOIN bedrock_documents v - ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ? - AND v.revision <= COALESCE(?, d.revision) - WHERE d.deployment = ? AND d.retired = 0 - ORDER BY v.revision DESC LIMIT 1", - ); - let row = sqlx::query(&statement) - .bind(collection.as_bytes()) - .bind(id.as_bytes()) - .bind(at) - .bind(self.deployment.as_slice()) - .fetch_optional(&self.pool) - .await - .map_err(connection_error)? - .ok_or(Error::MissingDeployment)?; - let available = row.try_get("available")?; - let revision = at.unwrap_or(available); - if revision > available { - return Err(Error::Behind { - requested: revision, - available, - }); - } - let document_revision: Option = row.try_get("document_revision")?; - let payload: Option> = row.try_get("payload")?; - let document = match (document_revision, payload) { - (Some(revision), Some(payload)) => Some(Document { - revision, - value: serde_json::from_slice(&payload)?, - }), - _ => None, - }; - Ok(Snapshot { revision, document }) - } -} - -impl Store { - #[doc(hidden)] - pub async fn initialize( - pool: AnyPool, - dialect: Dialect, - deployment: &str, - schema: &[&str], - insert_deployment: &str, - ) -> Result { - let reader = Reader::new(pool, dialect, deployment)?; - if dialect == Dialect::Postgres { - // PostgreSQL catalog inserts can race even with IF NOT EXISTS. - let mut transaction = reader.pool.begin().await.map_err(connection_error)?; - sqlx::query("SELECT pg_advisory_xact_lock(1694199371)") - .execute(&mut *transaction) - .await?; - initialize_schema( - &mut transaction, - schema, - insert_deployment, - &reader.deployment, - ) - .await?; - transaction.commit().await?; - } else { - let mut connection = reader.pool.acquire().await.map_err(connection_error)?; - initialize_schema( - &mut connection, - schema, - insert_deployment, - &reader.deployment, - ) - .await?; - } - reader.revision().await?; - Ok(Self { reader }) - } - - pub fn reader(&self) -> Reader { - self.reader.clone() - } - - pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { - self.commit_with_fence(expected, mutations, None).await - } - - #[doc(hidden)] - pub async fn commit_with_fence( - &self, - expected: Revision, - mutations: &[Mutation], - fence: Option, - ) -> Result { - let revision = expected - .checked_add(1) - .filter(|_| expected >= 0) - .ok_or(Error::Invalid("expected revision"))?; - if mutations.is_empty() { - return Err(Error::Invalid("empty write batch")); - } - let mut seen = HashSet::new(); - let mut rows = Vec::with_capacity(mutations.len()); - for mutation in mutations { - validate_id(&mutation.collection)?; - validate_id(&mutation.id)?; - if !seen.insert((&mutation.collection, &mutation.id)) { - return Err(Error::Invalid("duplicate document in write batch")); - } - let payload = mutation - .value - .as_ref() - .map(serde_json::to_vec) - .transpose()?; - rows.push(( - mutation.collection.as_bytes(), - mutation.id.as_bytes(), - payload, - )); - } - - let store = &self.reader; - let mut transaction = store.pool.begin().await.map_err(connection_error)?; - let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned(); - if store.dialect == Dialect::Mysql { - lock_mysql_deployment(&mut transaction, &store.deployment).await?; - if fence.is_some() { - advance.push_str(" AND lease_epoch = ? AND lease_until > "); - } else { - advance.push_str(" AND lease_until <= "); - } - advance.push_str(MYSQL_NOW); - } else if fence.is_some() { - return Err(Error::Invalid("lease on a database without lease support")); - } - let advance = statement(store.dialect, &advance); - let mut query = sqlx::query(&advance) - .bind(revision) - .bind(store.deployment.as_slice()) - .bind(expected); - if let Some(fence) = fence { - query = query.bind(fence); - } - if query.execute(&mut *transaction).await?.rows_affected() != 1 { - return Err(Error::WriteConflict); - } - let insert = statement( - store.dialect, - " - INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) - VALUES (?, ?, ?, ?, ?)", - ); - for (collection, id, payload) in rows { - sqlx::query(&insert) - .bind(store.deployment.as_slice()) - .bind(collection) - .bind(id) - .bind(revision) - .bind(payload) - .execute(&mut *transaction) - .await?; - } - transaction.commit().await?; - Ok(revision) - } -} - -/// MySQL server time in milliseconds, shared by lease management and fenced writes. -#[doc(hidden)] -pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)"; - -/// Lock before reading the database clock. MySQL timestamps are fixed at statement start. -#[doc(hidden)] -pub async fn lock_mysql_deployment( - connection: &mut AnyConnection, - deployment: &[u8], -) -> Result<()> { - sqlx::query_scalar::<_, Revision>( - "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE", - ) - .bind(deployment) - .fetch_optional(connection) - .await? - .ok_or(Error::MissingDeployment)?; - Ok(()) -} - -fn validate_id(value: &str) -> Result<()> { - if value.is_empty() || value.len() > 128 || value.contains('\0') { - return Err(Error::Invalid( - "identifier (expected 1–128 bytes without NUL)", - )); - } - Ok(()) -} - -async fn initialize_schema( - connection: &mut AnyConnection, - schema: &[&str], - insert_deployment: &str, - deployment: &[u8], -) -> Result<()> { - for ddl in schema { - sqlx::query(ddl).execute(&mut *connection).await?; - } - sqlx::query(insert_deployment) - .bind(deployment) - .execute(connection) - .await?; - Ok(()) -} - -fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> { - if dialect != Dialect::Postgres { - return Cow::Borrowed(sql); - } - let mut parts = sql.split('?'); - let mut translated = parts.next().unwrap_or_default().to_owned(); - for (index, part) in parts.enumerate() { - let _ = write!(translated, "${}", index + 1); - translated.push_str(part); - } - Cow::Owned(translated) -} - -fn connection_error(error: sqlx::Error) -> Error { - match error { - sqlx::Error::Configuration(_) => Error::Connection, - other => Error::Sql(other), - } -} +pub use store::Error as StorageError; +pub use store::{ + Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store, + lock_mysql_deployment, pool, +}; diff --git a/crates/db/src/mysql.rs b/crates/db/src/mysql.rs index e1a1e6d..20c3024 100644 --- a/crates/db/src/mysql.rs +++ b/crates/db/src/mysql.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; -use crate::{ +use crate::store::{ Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, pool, }; diff --git a/crates/db/src/postgres.rs b/crates/db/src/postgres.rs index 612dad9..1164b90 100644 --- a/crates/db/src/postgres.rs +++ b/crates/db/src/postgres.rs @@ -1,6 +1,6 @@ //! PostgreSQL connection pools and the Bedrock document layout. -use crate::{Dialect, Reader, Result, Store, pool}; +use crate::store::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/db/src/sqlite.rs b/crates/db/src/sqlite.rs index ee3ce1e..88a0592 100644 --- a/crates/db/src/sqlite.rs +++ b/crates/db/src/sqlite.rs @@ -1,6 +1,6 @@ //! File-backed Bedrock storage for self-hosted deployments. -use crate::{Dialect, Reader, Result, Store, pool}; +use crate::store::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/db/src/store.rs b/crates/db/src/store.rs new file mode 100644 index 0000000..ca2c37c --- /dev/null +++ b/crates/db/src/store.rs @@ -0,0 +1,386 @@ +//! Shared SQL connection pools, documents, snapshots and write transactions. + +use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; + +use serde_json::Value; +use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions}; +use thiserror::Error; + +pub type Revision = i64; +pub type Result = std::result::Result; + +#[derive(Debug, Error)] +pub enum Error { + #[error("invalid {0}")] + Invalid(&'static str), + #[error("the database connection failed")] + Connection, + #[error("SQL operation failed: {0}")] + Sql(#[from] sqlx::Error), + #[error("document encoding failed: {0}")] + Encoding(#[from] serde_json::Error), + #[error("the connection is read-only")] + ReadOnly, + #[error("the deployment is missing or retired")] + MissingDeployment, + #[error("database is at revision {available}, requested revision {requested}")] + Behind { + requested: Revision, + available: Revision, + }, + #[error("the write conflicts with the current revision or lease")] + WriteConflict, + #[error("lease is missing, expired, or belongs to another store")] + LeaseLost, +} + +impl Error { + pub fn retry_on_primary(&self) -> bool { + match self { + Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true, + Self::Sql(error) => match error { + sqlx::Error::Io(_) + | sqlx::Error::Tls(_) + | sqlx::Error::PoolTimedOut + | sqlx::Error::PoolClosed + | sqlx::Error::WorkerCrashed => true, + sqlx::Error::Database(db) => db.code().is_some_and(|code| { + code.starts_with("08") + || matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146") + }), + _ => false, + }, + _ => false, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Document { + pub revision: Revision, + pub value: Value, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Snapshot { + pub revision: Revision, + pub document: Option, +} + +#[derive(Clone, Debug)] +pub struct Mutation { + pub collection: String, + pub id: String, + /// None writes a tombstone. Some(Value::Null) stores a JSON null. + pub value: Option, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Dialect { + Sqlite, + Postgres, + Mysql, +} + +/// Opened SQL reader. Its pool is private so callers cannot bypass the read API. +#[derive(Clone)] +pub struct Reader { + pool: AnyPool, + dialect: Dialect, + deployment: Vec, +} + +#[derive(Clone)] +pub struct Store { + reader: Reader, +} + +/// Returns a lazily connected pool. The writer initializes schema before use. +#[doc(hidden)] +pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result { + if connections == 0 { + return Err(Error::Invalid("database pool size")); + } + sqlx::any::install_default_drivers(); + let mut options = AnyPoolOptions::new() + .max_connections(connections) + .acquire_timeout(Duration::from_secs(5)); + let read_only_statement = match dialect { + Dialect::Sqlite => "PRAGMA query_only = ON", + Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", + Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY", + }; + if read_only { + options = options.after_connect(move |connection, _| { + Box::pin(async move { + sqlx::query(read_only_statement).execute(connection).await?; + Ok(()) + }) + }); + } + options.connect_lazy(url).map_err(|_| Error::Connection) +} + +impl Reader { + #[doc(hidden)] + pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result { + validate_id(deployment)?; + Ok(Self { + pool, + dialect, + deployment: deployment.as_bytes().to_vec(), + }) + } + + pub async fn revision(&self) -> Result { + let statement = statement( + self.dialect, + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", + ); + sqlx::query_scalar(&statement) + .bind(self.deployment.as_slice()) + .fetch_optional(&self.pool) + .await + .map_err(connection_error)? + .ok_or(Error::MissingDeployment) + } + + /// Fetch at the latest revision or at an exact, previously committed snapshot. + pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { + validate_id(collection)?; + validate_id(id)?; + if at.is_some_and(|at| at < 0) { + return Err(Error::Invalid("snapshot revision")); + } + // A single statement keeps the revision and document on the same database snapshot. + let statement = statement( + self.dialect, + " + SELECT d.revision AS available, v.revision AS document_revision, v.payload + FROM bedrock_deployments d + LEFT JOIN bedrock_documents v + ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ? + AND v.revision <= COALESCE(?, d.revision) + WHERE d.deployment = ? AND d.retired = 0 + ORDER BY v.revision DESC LIMIT 1", + ); + let row = sqlx::query(&statement) + .bind(collection.as_bytes()) + .bind(id.as_bytes()) + .bind(at) + .bind(self.deployment.as_slice()) + .fetch_optional(&self.pool) + .await + .map_err(connection_error)? + .ok_or(Error::MissingDeployment)?; + let available = row.try_get("available")?; + let revision = at.unwrap_or(available); + if revision > available { + return Err(Error::Behind { + requested: revision, + available, + }); + } + let document_revision: Option = row.try_get("document_revision")?; + let payload: Option> = row.try_get("payload")?; + let document = match (document_revision, payload) { + (Some(revision), Some(payload)) => Some(Document { + revision, + value: serde_json::from_slice(&payload)?, + }), + _ => None, + }; + Ok(Snapshot { revision, document }) + } +} + +impl Store { + #[doc(hidden)] + pub async fn initialize( + pool: AnyPool, + dialect: Dialect, + deployment: &str, + schema: &[&str], + insert_deployment: &str, + ) -> Result { + let reader = Reader::new(pool, dialect, deployment)?; + if dialect == Dialect::Postgres { + // PostgreSQL catalog inserts can race even with IF NOT EXISTS. + let mut transaction = reader.pool.begin().await.map_err(connection_error)?; + sqlx::query("SELECT pg_advisory_xact_lock(1694199371)") + .execute(&mut *transaction) + .await?; + initialize_schema( + &mut transaction, + schema, + insert_deployment, + &reader.deployment, + ) + .await?; + transaction.commit().await?; + } else { + let mut connection = reader.pool.acquire().await.map_err(connection_error)?; + initialize_schema( + &mut connection, + schema, + insert_deployment, + &reader.deployment, + ) + .await?; + } + reader.revision().await?; + Ok(Self { reader }) + } + + pub fn reader(&self) -> Reader { + self.reader.clone() + } + + pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { + self.commit_with_fence(expected, mutations, None).await + } + + #[doc(hidden)] + pub async fn commit_with_fence( + &self, + expected: Revision, + mutations: &[Mutation], + fence: Option, + ) -> Result { + let revision = expected + .checked_add(1) + .filter(|_| expected >= 0) + .ok_or(Error::Invalid("expected revision"))?; + if mutations.is_empty() { + return Err(Error::Invalid("empty write batch")); + } + let mut seen = HashSet::new(); + let mut rows = Vec::with_capacity(mutations.len()); + for mutation in mutations { + validate_id(&mutation.collection)?; + validate_id(&mutation.id)?; + if !seen.insert((&mutation.collection, &mutation.id)) { + return Err(Error::Invalid("duplicate document in write batch")); + } + let payload = mutation + .value + .as_ref() + .map(serde_json::to_vec) + .transpose()?; + rows.push(( + mutation.collection.as_bytes(), + mutation.id.as_bytes(), + payload, + )); + } + + let store = &self.reader; + let mut transaction = store.pool.begin().await.map_err(connection_error)?; + let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned(); + if store.dialect == Dialect::Mysql { + lock_mysql_deployment(&mut transaction, &store.deployment).await?; + if fence.is_some() { + advance.push_str(" AND lease_epoch = ? AND lease_until > "); + } else { + advance.push_str(" AND lease_until <= "); + } + advance.push_str(MYSQL_NOW); + } else if fence.is_some() { + return Err(Error::Invalid("lease on a database without lease support")); + } + let advance = statement(store.dialect, &advance); + let mut query = sqlx::query(&advance) + .bind(revision) + .bind(store.deployment.as_slice()) + .bind(expected); + if let Some(fence) = fence { + query = query.bind(fence); + } + if query.execute(&mut *transaction).await?.rows_affected() != 1 { + return Err(Error::WriteConflict); + } + let insert = statement( + store.dialect, + " + INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) + VALUES (?, ?, ?, ?, ?)", + ); + for (collection, id, payload) in rows { + sqlx::query(&insert) + .bind(store.deployment.as_slice()) + .bind(collection) + .bind(id) + .bind(revision) + .bind(payload) + .execute(&mut *transaction) + .await?; + } + transaction.commit().await?; + Ok(revision) + } +} + +/// MySQL server time in milliseconds, shared by lease management and fenced writes. +#[doc(hidden)] +pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)"; + +/// Lock before reading the database clock. MySQL timestamps are fixed at statement start. +#[doc(hidden)] +pub async fn lock_mysql_deployment( + connection: &mut AnyConnection, + deployment: &[u8], +) -> Result<()> { + sqlx::query_scalar::<_, Revision>( + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE", + ) + .bind(deployment) + .fetch_optional(connection) + .await? + .ok_or(Error::MissingDeployment)?; + Ok(()) +} + +fn validate_id(value: &str) -> Result<()> { + if value.is_empty() || value.len() > 128 || value.contains('\0') { + return Err(Error::Invalid( + "identifier (expected 1–128 bytes without NUL)", + )); + } + Ok(()) +} + +async fn initialize_schema( + connection: &mut AnyConnection, + schema: &[&str], + insert_deployment: &str, + deployment: &[u8], +) -> Result<()> { + for ddl in schema { + sqlx::query(ddl).execute(&mut *connection).await?; + } + sqlx::query(insert_deployment) + .bind(deployment) + .execute(connection) + .await?; + Ok(()) +} + +fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> { + if dialect != Dialect::Postgres { + return Cow::Borrowed(sql); + } + let mut parts = sql.split('?'); + let mut translated = parts.next().unwrap_or_default().to_owned(); + for (index, part) in parts.enumerate() { + let _ = write!(translated, "${}", index + 1); + translated.push_str(part); + } + Cow::Owned(translated) +} + +fn connection_error(error: sqlx::Error) -> Error { + match error { + sqlx::Error::Configuration(_) => Error::Connection, + other => Error::Sql(other), + } +} diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 2c7feab..73c2a2c 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -76,7 +76,7 @@ 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres 模块提供 SQL,db 在事务里执行。 +postgres.rs 提供 SQL,store.rs 在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功 -- 2.52.0 From c98b694a70bb1ec41437c8cd0f1428e023cfd186 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 04:40:53 +0800 Subject: [PATCH 13/13] Name the shared database module common --- README.md | 2 +- crates/db/src/{store.rs => common.rs} | 0 crates/db/src/connection.rs | 2 +- crates/db/src/lib.rs | 6 +++--- crates/db/src/mysql.rs | 2 +- crates/db/src/postgres.rs | 2 +- crates/db/src/sqlite.rs | 2 +- deploy/bedrock-deployment.svg | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) rename crates/db/src/{store.rs => common.rs} (100%) diff --git a/README.md b/README.md index 2aaed51..37bbfcd 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i ## Storage boundaries -`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `store.rs`. +`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `common.rs`. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) diff --git a/crates/db/src/store.rs b/crates/db/src/common.rs similarity index 100% rename from crates/db/src/store.rs rename to crates/db/src/common.rs diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 0fa87d0..708094f 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -6,9 +6,9 @@ use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeploymen use thiserror::Error; use crate::{ + common::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store}, mysql::{self, MySql}, postgres, sqlite, - store::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store}, }; #[derive(Debug, Error)] diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index b5cb6b1..4253f53 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -1,17 +1,17 @@ //! Bedrock's transactional document storage for SQL databases. +mod common; mod connection; pub mod mysql; pub mod postgres; pub mod sqlite; -mod store; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use connection::{ConnectError, Connection, ReadPreference, connect}; pub use mysql::{Lease, MySql}; -pub use store::Error as StorageError; -pub use store::{ +pub use common::Error as StorageError; +pub use common::{ Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store, lock_mysql_deployment, pool, }; diff --git a/crates/db/src/mysql.rs b/crates/db/src/mysql.rs index 20c3024..83c851e 100644 --- a/crates/db/src/mysql.rs +++ b/crates/db/src/mysql.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; -use crate::store::{ +use crate::common::{ Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, pool, }; diff --git a/crates/db/src/postgres.rs b/crates/db/src/postgres.rs index 1164b90..d857daf 100644 --- a/crates/db/src/postgres.rs +++ b/crates/db/src/postgres.rs @@ -1,6 +1,6 @@ //! PostgreSQL connection pools and the Bedrock document layout. -use crate::store::{Dialect, Reader, Result, Store, pool}; +use crate::common::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/db/src/sqlite.rs b/crates/db/src/sqlite.rs index 88a0592..ed338b6 100644 --- a/crates/db/src/sqlite.rs +++ b/crates/db/src/sqlite.rs @@ -1,6 +1,6 @@ //! File-backed Bedrock storage for self-hosted deployments. -use crate::store::{Dialect, Reader, Result, Store, pool}; +use crate::common::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 73c2a2c..c07065e 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -76,7 +76,7 @@ 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres.rs 提供 SQL,store.rs 在事务里执行。 +postgres.rs 提供 SQL,common.rs 在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功 -- 2.52.0