From 9f3848199d6018b2d59aac6f773337c0e08ece9c Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 07:02:20 +0800 Subject: [PATCH 01/14] Use native drivers for Bedrock SQL storage --- Cargo.lock | 1301 +++++++++++++++++++++-------------- Cargo.toml | 10 +- crates/db/Cargo.toml | 12 +- crates/db/src/common.rs | 407 +++-------- crates/db/src/connection.rs | 92 ++- crates/db/src/lib.rs | 11 +- crates/db/src/mysql.rs | 351 ++++++++-- crates/db/src/postgres.rs | 269 +++++++- crates/db/src/sqlite.rs | 201 +++++- crates/db/tests/storage.rs | 13 + 10 files changed, 1687 insertions(+), 980 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a2ca10a..2f38097 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,34 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +dependencies = [ + "cfg-if", + "getrandom 0.4.3", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "allocator-api2" version = "0.2.22" @@ -9,12 +37,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" [[package]] -name = "atoi" -version = "2.0.0" +name = "async-trait" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ - "num-traits", + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] @@ -49,9 +79,6 @@ 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" @@ -62,6 +89,30 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "btoi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" +dependencies = [ + "num-traits", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + [[package]] name = "byteorder" version = "1.5.0" @@ -90,6 +141,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "clusters" version = "0.1.0" @@ -99,12 +161,24 @@ dependencies = [ "url", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "const-oid" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -115,19 +189,31 @@ dependencies = [ ] [[package]] -name = "crc" -version = "3.4.0" +name = "cpufeatures" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ - "crc-catalog", + "libc", ] [[package]] -name = "crc-catalog" -version = "2.5.0" +name = "crc32fast" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] [[package]] name = "crossbeam-queue" @@ -154,16 +240,76 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "db" version = "0.1.0" dependencies = [ "clusters", + "deadpool-postgres", + "mysql_async", + "rusqlite", + "rustls", + "rustls-pemfile", "serde_json", - "sqlx", "tempfile", "thiserror", "tokio", + "tokio-postgres", + "tokio-postgres-rustls", + "tokio-rusqlite", + "url", + "webpki-roots 1.0.12", +] + +[[package]] +name = "deadpool" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e98a7e119cd347f4201e1159b19831029e203e2d8b790547708e8157b4acf1e" +dependencies = [ + "deadpool-runtime", + "tokio", +] + +[[package]] +name = "deadpool-postgres" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65a536565624b97fc19f758cd01b15d12908d3344425066efc8162236fbd3749" +dependencies = [ + "async-trait", + "deadpool", + "getrandom 0.4.3", + "tokio", + "tokio-postgres", + "tracing", +] + +[[package]] +name = "deadpool-runtime" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2657f61fb1dd8bf37a8d51093cc7cee4e77125b22f7753f49b289f831bec2bae" +dependencies = [ + "tokio", ] [[package]] @@ -172,21 +318,43 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", - "pem-rfc7468", + "const-oid 0.9.6", + "der_derive", + "flagset", "zeroize", ] +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[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", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -200,21 +368,6 @@ dependencies = [ "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" @@ -232,25 +385,22 @@ dependencies = [ ] [[package]] -name = "etcetera" -version = "0.8.0" +name = "fallible-iterator" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" -dependencies = [ - "cfg-if", - "home", - "windows-sys 0.48.0", -] +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" [[package]] -name = "event-listener" -version = "5.4.2" +name = "fallible-iterator" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" @@ -265,21 +415,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" [[package]] -name = "flume" -version = "0.11.1" +name = "flagset" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ - "futures-core", - "futures-sink", - "spin", + "crc32fast", + "miniz_oxide", ] [[package]] name = "foldhash" -version = "0.1.5" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" @@ -307,33 +462,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] -name = "futures-executor" +name = "futures-macro" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ - "futures-core", - "futures-task", - "futures-util", + "proc-macro2", + "quote", + "syn 3.0.10", ] -[[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" @@ -353,10 +491,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", - "futures-io", + "futures-macro", "futures-sink", "futures-task", - "memchr", "pin-project-lite", "slab", ] @@ -379,7 +516,19 @@ checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", ] [[package]] @@ -389,15 +538,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] name = "hashbrown" -version = "0.15.5" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", @@ -412,50 +573,29 @@ checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" [[package]] name = "hashlink" -version = "0.10.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" 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", + "hashbrown 0.14.5", ] [[package]] name = "hmac" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest", + "digest 0.11.3", ] [[package]] -name = "home" -version = "0.5.12" +name = "hybrid-array" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ - "windows-sys 0.61.2", + "typenum", ] [[package]] @@ -579,12 +719,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] -name = "lazy_static" -version = "1.5.1" +name = "js-sys" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "spin", + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "keyed_priority_queue" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ee7893dab2e44ae5f9d0173f26ff4aa327c10b01b06a72b52dd9405b628640d" +dependencies = [ + "indexmap", ] [[package]] @@ -593,22 +744,13 @@ 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]] @@ -650,13 +792,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] -name = "md-5" -version = "0.10.6" +name = "lru" +version = "0.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ "cfg-if", - "digest", + "digest 0.11.3", ] [[package]] @@ -665,6 +816,16 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.5" @@ -672,24 +833,76 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.61.2", ] [[package]] -name = "num-bigint-dig" -version = "0.8.6" +name = "mysql_async" +version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +checksum = "d1d9585dc9058886ff3a1f48a23024dd1d054264dee7c5ae0e4bd640c953bee5" dependencies = [ - "lazy_static", - "libm", - "num-integer", - "num-iter", + "bytes", + "crossbeam-queue", + "flate2", + "futures-core", + "futures-sink", + "futures-util", + "keyed_priority_queue", + "lru", + "mysql_common", + "pem", + "percent-encoding", + "rand 0.9.5", + "rustls", + "rustls-pemfile", + "serde", + "serde_json", + "socket2 0.5.10", + "thiserror", + "tokio", + "tokio-rustls", + "tokio-util", + "twox-hash", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "mysql_common" +version = "0.35.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbb9f371618ce723f095c61fbcdc36e8936956d2b62832f9c7648689b338e052" +dependencies = [ + "base64", + "bitflags", + "btoi", + "byteorder", + "bytes", + "crc32fast", + "flate2", + "getrandom 0.3.4", + "num-bigint", + "num-traits", + "regex", + "saturating", + "serde", + "serde_json", + "sha1", + "sha2 0.10.9", + "thiserror", + "uuid", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", "num-traits", - "rand", - "smallvec", - "zeroize", ] [[package]] @@ -701,16 +914,6 @@ 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" @@ -718,7 +921,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", - "libm", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", ] [[package]] @@ -727,12 +947,6 @@ 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" @@ -751,18 +965,19 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.18", + "redox_syscall", "smallvec", "windows-link", ] [[package]] -name = "pem-rfc7468" -version = "0.7.0" +name = "pem" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64ct", + "base64", + "serde_core", ] [[package]] @@ -771,33 +986,31 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[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" @@ -805,10 +1018,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] -name = "plain" -version = "0.2.3" +name = "postgres-protocol" +version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64", + "byteorder", + "bytes", + "fallible-iterator 0.2.0", + "hmac", + "md-5", + "memchr", + "rand 0.10.4", + "sha2 0.11.2", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" +dependencies = [ + "bytes", + "fallible-iterator 0.2.0", + "postgres-protocol", +] [[package]] name = "potential_utf" @@ -846,6 +1082,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -854,34 +1096,50 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.8" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "libc", "rand_chacha", - "rand_core", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] name = "rand_chacha" -version = "0.3.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.9.5", ] [[package]] name = "rand_core" -version = "0.6.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ - "getrandom 0.2.17", + "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -892,14 +1150,34 @@ dependencies = [ ] [[package]] -name = "redox_syscall" -version = "0.9.5" +name = "regex" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ - "bitflags", + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", ] +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + [[package]] name = "ring" version = "0.17.14" @@ -915,23 +1193,17 @@ dependencies = [ ] [[package]] -name = "rsa" -version = "0.9.10" +name = "rusqlite" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" dependencies = [ - "const-oid", - "digest", - "num-bigint-dig", - "num-integer", - "num-traits", - "pkcs1", - "pkcs8", - "rand_core", - "signature", - "spki", - "subtle", - "zeroize", + "bitflags", + "fallible-iterator 0.3.0", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", ] [[package]] @@ -961,6 +1233,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" @@ -982,10 +1263,16 @@ dependencies = [ ] [[package]] -name = "ryu" +name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "saturating" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "scopeguard" @@ -1036,18 +1323,6 @@ dependencies = [ "zmij", ] -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - [[package]] name = "sha1" version = "0.10.7" @@ -1055,8 +1330,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", ] [[package]] @@ -1066,8 +1341,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1077,14 +1363,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] -name = "signature" -version = "2.2.0" +name = "simd-adler32" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "digest", - "rand_core", -] +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "slab" @@ -1097,8 +1385,15 @@ name = "smallvec" version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ - "serde", + "libc", + "windows-sys 0.52.0", ] [[package]] @@ -1111,15 +1406,6 @@ dependencies = [ "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" @@ -1130,196 +1416,6 @@ dependencies = [ "der", ] -[[package]] -name = "sqlx" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" -dependencies = [ - "sqlx-core", - "sqlx-macros", - "sqlx-mysql", - "sqlx-postgres", - "sqlx-sqlite", -] - -[[package]] -name = "sqlx-core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" -dependencies = [ - "base64", - "bytes", - "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" @@ -1425,6 +1521,27 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tokio" version = "1.54.1" @@ -1435,7 +1552,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", - "socket2", + "socket2 0.6.5", "tokio-macros", "windows-sys 0.61.2", ] @@ -1452,12 +1569,77 @@ dependencies = [ ] [[package]] -name = "tokio-stream" -version = "0.1.19" +name = "tokio-postgres" +version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator 0.2.0", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand 0.10.4", + "socket2 0.6.5", + "tokio", + "tokio-util", + "whoami", +] + +[[package]] +name = "tokio-postgres-rustls" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27d684bad428a0f2481f42241f821db42c54e2dc81d8c00db8536c506b0a0144" +dependencies = [ + "const-oid 0.9.6", + "ring", + "rustls", + "tokio", + "tokio-postgres", + "tokio-rustls", + "x509-cert", +] + +[[package]] +name = "tokio-rusqlite" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b65501378eb676f400c57991f42cbd0986827ab5c5200c53f206d710fb32a945" +dependencies = [ + "crossbeam-channel", + "rusqlite", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", "futures-core", + "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -1468,7 +1650,6 @@ 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", @@ -1494,6 +1675,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + [[package]] name = "typenum" version = "1.20.1" @@ -1560,6 +1747,16 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -1579,10 +1776,85 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] -name = "wasite" -version = "0.1.0" +name = "wasi" +version = "0.14.7+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] [[package]] name = "webpki-roots" @@ -1604,12 +1876,15 @@ dependencies = [ [[package]] name = "whoami" -version = "1.6.1" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" dependencies = [ + "libc", "libredox", + "objc2-system-configuration", "wasite", + "web-sys", ] [[package]] @@ -1618,22 +1893,13 @@ 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", + "windows-targets", ] [[package]] @@ -1645,67 +1911,34 @@ 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_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", "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", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[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" @@ -1718,60 +1951,54 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid 0.9.6", + "der", + "spki", + "tls_codec", +] + [[package]] name = "yoke" version = "0.8.4" @@ -1841,6 +2068,20 @@ name = "zeroize" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 08da929..106fe02 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,13 +9,21 @@ rust-version = "1.91" [workspace.dependencies] clusters = { path = "crates/clusters" } db = { path = "crates/db" } +deadpool-postgres = "0.14.1" +mysql_async = { version = "0.36.1", default-features = false, features = ["minimal-rust", "ring", "rustls-tls", "tls12"] } +rusqlite = { version = "0.32.1", features = ["bundled"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +rustls-pemfile = "2" 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"] } +tokio-postgres = "0.7.18" +tokio-postgres-rustls = { version = "0.13", default-features = false } +tokio-rusqlite = "0.6" url = "2" +webpki-roots = "1" [package] name = "bedrock" diff --git a/crates/db/Cargo.toml b/crates/db/Cargo.toml index 9717099..b492f7f 100644 --- a/crates/db/Cargo.toml +++ b/crates/db/Cargo.toml @@ -6,9 +6,19 @@ rust-version.workspace = true [dependencies] clusters.workspace = true +deadpool-postgres.workspace = true +mysql_async.workspace = true +rusqlite.workspace = true +rustls.workspace = true +rustls-pemfile.workspace = true serde_json.workspace = true -sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } thiserror.workspace = true +tokio = { workspace = true, features = ["sync", "time"] } +tokio-postgres.workspace = true +tokio-postgres-rustls.workspace = true +tokio-rusqlite.workspace = true +url.workspace = true +webpki-roots.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/db/src/common.rs b/crates/db/src/common.rs index ca2c37c..61d7f99 100644 --- a/crates/db/src/common.rs +++ b/crates/db/src/common.rs @@ -1,22 +1,29 @@ -//! Shared SQL connection pools, documents, snapshots and write transactions. +//! Driver-independent documents, revisions, validation and encoding. -use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; +use std::{collections::HashSet, 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; +pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + #[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("SQLite operation failed: {0}")] + Sqlite(#[from] rusqlite::Error), + #[error("PostgreSQL operation failed: {0}")] + Postgres(#[from] tokio_postgres::Error), + #[error("MySQL operation failed: {0}")] + Mysql(#[from] mysql_async::Error), + #[error("invalid database row")] + InvalidRow, #[error("document encoding failed: {0}")] Encoding(#[from] serde_json::Error), #[error("the connection is read-only")] @@ -38,18 +45,17 @@ 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, - }, + Self::Postgres(error) => { + error.is_closed() + || error.code().is_some_and(|code| { + code.code().starts_with("08") + || matches!(code.code(), "57P01" | "57P03" | "42P01") + }) + } + Self::Mysql(mysql_async::Error::Server(error)) => { + error.state.starts_with("08") || error.code == 1146 + } + Self::Mysql(error) => error.is_fatal(), _ => false, } } @@ -75,272 +81,75 @@ pub struct Mutation { pub value: Option, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Dialect { - Sqlite, - Postgres, - Mysql, +pub(crate) type EncodedSnapshot = (Revision, Option, Option>); + +pub(crate) struct EncodedMutation<'a> { + pub collection: &'a [u8], + pub id: &'a [u8], + pub payload: Option>, } -/// 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")); +pub(crate) fn validate_read(collection: &str, id: &str, at: Option) -> Result<()> { + validate_id(collection)?; + validate_id(id)?; + if at.is_some_and(|revision| revision < 0) { + return Err(Error::Invalid("snapshot revision")); } - 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<()> { +pub(crate) fn snapshot(row: Option, at: Option) -> Result { + let (available, document_revision, payload) = row.ok_or(Error::MissingDeployment)?; + let revision = at.unwrap_or(available); + if revision > available { + return Err(Error::Behind { + requested: revision, + available, + }); + } + let document = match (document_revision, payload) { + (Some(revision), Some(payload)) => Some(Document { + revision, + value: serde_json::from_slice(&payload)?, + }), + _ => None, + }; + Ok(Snapshot { revision, document }) +} + +pub(crate) fn encode_batch( + expected: Revision, + mutations: &[Mutation], +) -> Result<(Revision, Vec>)> { + 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::with_capacity(mutations.len()); + 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")); + } + rows.push(EncodedMutation { + collection: mutation.collection.as_bytes(), + id: mutation.id.as_bytes(), + payload: mutation + .value + .as_ref() + .map(serde_json::to_vec) + .transpose()?, + }); + } + Ok((revision, rows)) +} + +pub(crate) 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)", @@ -349,38 +158,12 @@ fn validate_id(value: &str) -> Result<()> { 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), - } -} +// A single statement observes the revision and the document at the same point in time. +pub(crate) const GET_DOCUMENT: &str = " + SELECT d.revision, v.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"; diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 708094f..e50d51b 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -6,9 +6,10 @@ 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, + common::{Error as StorageError, Mutation, Revision, Snapshot}, + mysql::{self, MySql, MySqlReader}, + postgres::{self, Postgres, PostgresReader}, + sqlite::{self, Sqlite, SqliteReader}, }; #[derive(Debug, Error)] @@ -29,14 +30,69 @@ pub enum ReadPreference { PreferReplica, } -enum Writer { - Sql(Store), - MySql(MySql), +/// A reader backed by the configured database. It exposes no raw SQL connection. +#[derive(Clone)] +pub enum Reader { + Sqlite(SqliteReader), + Postgres(PostgresReader), + Mysql(MySqlReader), +} + +impl Reader { + pub async fn revision(&self) -> Result { + match self { + Self::Sqlite(reader) => reader.revision().await, + Self::Postgres(reader) => reader.revision().await, + Self::Mysql(reader) => reader.revision().await, + } + } + + pub async fn get( + &self, + collection: &str, + id: &str, + at: Option, + ) -> Result { + match self { + Self::Sqlite(reader) => reader.get(collection, id, at).await, + Self::Postgres(reader) => reader.get(collection, id, at).await, + Self::Mysql(reader) => reader.get(collection, id, at).await, + } + } +} + +#[derive(Clone)] +pub enum Store { + Sqlite(Sqlite), + Postgres(Postgres), + Mysql(MySql), +} + +impl Store { + pub fn reader(&self) -> Reader { + match self { + Self::Sqlite(store) => Reader::Sqlite(store.reader()), + Self::Postgres(store) => Reader::Postgres(store.reader()), + Self::Mysql(store) => Reader::Mysql(store.reader()), + } + } + + pub async fn commit( + &self, + expected: Revision, + changes: &[Mutation], + ) -> Result { + match self { + Self::Sqlite(store) => store.commit(expected, changes).await, + Self::Postgres(store) => store.commit(expected, changes).await, + Self::Mysql(store) => store.commit(expected, changes).await, + } + } } pub struct Connection { driver: Driver, - writer: Option, + writer: Option, primary: Reader, replicas: Vec, next_replica: AtomicUsize, @@ -51,14 +107,13 @@ pub async fn connect(config: &DeploymentConfig) -> Result 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?), + Driver::Sqlite => Store::Sqlite(sqlite::connect(url, name).await?), + Driver::Postgres => Store::Postgres(postgres::connect(url, name, max).await?), + Driver::Mysql => Store::Mysql(MySql::connect(url, name, max).await?), }) }; let primary = match &writer { - Some(Writer::Sql(store)) => store.reader(), - Some(Writer::MySql(store)) => store.reader(), + Some(store) => store.reader(), None => { let reader = reader(&config, &config.primary)?; reader.revision().await?; @@ -83,9 +138,11 @@ fn reader(config: &ResolvedDeployment, address: &Address) -> Result sqlite::reader(url, name), - Driver::Postgres => postgres::reader(url, name, config.max_connections), - Driver::Mysql => mysql::reader(url, name, config.max_connections), + Driver::Sqlite => sqlite::reader(url, name).map(Reader::Sqlite), + Driver::Postgres => { + postgres::reader(url, name, config.max_connections).map(Reader::Postgres) + } + Driver::Mysql => mysql::reader(url, name, config.max_connections).map(Reader::Mysql), } } @@ -129,15 +186,14 @@ impl Connection { changes: &[Mutation], ) -> Result { match &self.writer { - Some(Writer::Sql(store)) => store.commit(expected, changes).await, - Some(Writer::MySql(store)) => store.commit(expected, changes).await, + Some(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), + Some(Store::Mysql(store)) => Some(store), _ => None, } } diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 4253f53..b928ef8 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -6,12 +6,9 @@ pub mod mysql; pub mod postgres; pub mod sqlite; +pub use clusters::Driver as Dialect; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; -pub use connection::{ConnectError, Connection, ReadPreference, connect}; -pub use mysql::{Lease, MySql}; - pub use common::Error as StorageError; -pub use common::{ - Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store, - lock_mysql_deployment, pool, -}; +pub use common::{Document, Error, Mutation, Result, Revision, Snapshot}; +pub use connection::{ConnectError, Connection, ReadPreference, Reader, Store, connect}; +pub use mysql::{Lease, MySql}; diff --git a/crates/db/src/mysql.rs b/crates/db/src/mysql.rs index 83c851e..bad844d 100644 --- a/crates/db/src/mysql.rs +++ b/crates/db/src/mysql.rs @@ -1,12 +1,19 @@ //! MySQL storage, writer leases and deployment cleanup. -use std::{sync::Arc, time::Duration}; +use std::{fmt::Write, path::PathBuf, sync::Arc, time::Duration}; + +use mysql_async::{ + ClientIdentity, Conn, Opts, OptsBuilder, Pool, PoolConstraints, PoolOpts, Row, SslOpts, TxOpts, + from_row_opt, prelude::Queryable, +}; +use url::Url; use crate::common::{ - Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, - pool, + CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch, + snapshot, validate_id, validate_read, }; -use sqlx::AnyPool; + +const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)"; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( @@ -29,12 +36,68 @@ const SCHEMA: &[&str] = &[ #[derive(Clone)] pub struct MySql { - store: Store, - pool: AnyPool, - deployment: Vec, + reader: MySqlReader, identity: Arc<()>, } +#[derive(Clone)] +pub struct MySqlReader { + pool: Pool, + deployment: Arc<[u8]>, +} + +impl MySqlReader { + fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result { + validate_id(deployment)?; + Ok(Self { + pool: Pool::new(connection_options(url, max_connections, read_only)?), + deployment: Arc::from(deployment.as_bytes()), + }) + } + + async fn connection(&self) -> Result { + tokio::time::timeout(CONNECT_TIMEOUT, self.pool.get_conn()) + .await + .map_err(|_| Error::Connection)? + .map_err(|_| Error::Connection) + } + + pub async fn revision(&self) -> Result { + let row: Row = self + .connection() + .await? + .exec_first( + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", + (self.deployment.as_ref(),), + ) + .await? + .ok_or(Error::MissingDeployment)?; + from_row_opt(row).map_err(|_| Error::InvalidRow) + } + + pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { + validate_read(collection, id, at)?; + let row: Option = self + .connection() + .await? + .exec_first( + GET_DOCUMENT, + ( + collection.as_bytes(), + id.as_bytes(), + at, + self.deployment.as_ref(), + ), + ) + .await?; + let row = row + .map(from_row_opt) + .transpose() + .map_err(|_| Error::InvalidRow)?; + snapshot(row, at) + } +} + /// The monotonically increasing epoch fences off holders whose lease expired. #[derive(Debug)] pub struct Lease { @@ -50,31 +113,34 @@ impl Lease { 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?; + let reader = MySqlReader::new(url, deployment, max_connections, false)?; + { + let mut connection = reader.connection().await?; + for ddl in SCHEMA { + connection.query_drop(*ddl).await?; + } + connection + .exec_drop( + "INSERT INTO bedrock_deployments (deployment) VALUES (?) + ON DUPLICATE KEY UPDATE revision = revision", + (reader.deployment.as_ref(),), + ) + .await?; + } + reader.revision().await?; Ok(Self { - store, - pool, - deployment: deployment.as_bytes().to_vec(), + reader, identity: Arc::new(()), }) } - pub fn reader(&self) -> Reader { - self.store.reader() + pub fn reader(&self) -> MySqlReader { + self.reader.clone() } /// 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 + self.commit_with_fence(expected, mutations, None).await } pub async fn commit_with_lease( @@ -83,12 +149,44 @@ impl MySql { expected: Revision, mutations: &[Mutation], ) -> Result { - let epoch = self.epoch(lease)?; - self.store - .commit_with_fence(expected, mutations, Some(epoch)) + self.commit_with_fence(expected, mutations, Some(self.epoch(lease)?)) .await } + async fn commit_with_fence( + &self, + expected: Revision, + mutations: &[Mutation], + fence: Option, + ) -> Result { + let (revision, rows) = encode_batch(expected, mutations)?; + let deployment = self.reader.deployment.as_ref(); + let mut connection = self.reader.connection().await?; + let mut transaction = connection.start_transaction(TxOpts::default()).await?; + lock_deployment(&mut transaction, deployment).await?; + transaction + .exec_drop( + format!( + "UPDATE bedrock_deployments SET revision = ? + WHERE deployment = ? AND revision = ? AND retired = 0 + AND ((? IS NULL AND lease_until <= {MYSQL_NOW}) + OR (lease_epoch = ? AND lease_until > {MYSQL_NOW}))" + ), + (revision, deployment, expected, fence, fence), + ) + .await?; + if transaction.affected_rows() != 1 { + return Err(Error::WriteConflict); + } + transaction.exec_batch( + "INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) + VALUES (?, ?, ?, ?, ?)", + rows.into_iter().map(|row| (deployment, row.collection, row.id, revision, row.payload)), + ).await?; + transaction.commit().await?; + Ok(revision) + } + /// Acquires an expired or unheld lease using the database clock. pub async fn acquire_lease(&self, ttl: Duration) -> Result> { let ttl = lease_millis(ttl)?; @@ -98,21 +196,21 @@ impl MySql { 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 { + let deployment = self.reader.deployment.as_ref(); + let mut connection = self.reader.connection().await?; + let mut transaction = connection.start_transaction(TxOpts::default()).await?; + lock_deployment(&mut transaction, deployment).await?; + transaction.exec_drop(update, (ttl, deployment)).await?; + if transaction.affected_rows() != 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?; + let epoch: i64 = transaction + .exec_first( + "SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?", + (deployment,), + ) + .await? + .ok_or(Error::MissingDeployment)?; transaction.commit().await?; Ok(Some(Lease { epoch, @@ -130,15 +228,14 @@ impl MySql { 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) + let deployment = self.reader.deployment.as_ref(); + let mut connection = self.reader.connection().await?; + let mut transaction = connection.start_transaction(TxOpts::default()).await?; + lock_deployment(&mut transaction, deployment).await?; + transaction + .exec_drop(update, (ttl, deployment, epoch)) .await?; - if changed.rows_affected() != 1 { + if transaction.affected_rows() != 1 { return Err(Error::LeaseLost); } transaction.commit().await?; @@ -147,16 +244,15 @@ impl MySql { 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) + let mut connection = self.reader.connection().await?; + connection + .exec_drop( + "UPDATE bedrock_deployments SET lease_until = 0 + WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0", + (self.reader.deployment.as_ref(), epoch), + ) + .await?; + Ok(connection.affected_rows() == 1) } /// Removes only this deployment's documents and retires its identity in one transaction. @@ -168,22 +264,23 @@ impl MySql { 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 { + let deployment = self.reader.deployment.as_ref(); + let mut connection = self.reader.connection().await?; + let mut transaction = connection.start_transaction(TxOpts::default()).await?; + lock_deployment(&mut transaction, deployment).await?; + transaction.exec_drop(update, (deployment, epoch)).await?; + if transaction.affected_rows() != 1 { return Err(Error::LeaseLost); } - let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?") - .bind(self.deployment.as_slice()) - .execute(&mut *transaction) + transaction + .exec_drop( + "DELETE FROM bedrock_documents WHERE deployment = ?", + (deployment,), + ) .await?; + let removed = transaction.affected_rows(); transaction.commit().await?; - Ok(removed.rows_affected()) + Ok(removed) } fn epoch(&self, lease: &Lease) -> Result { @@ -194,12 +291,116 @@ impl MySql { } } -pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { - Reader::new( - pool(Dialect::Mysql, url, max_connections, true)?, - Dialect::Mysql, - deployment, - ) +pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { + MySqlReader::new(url, deployment, max_connections, true) +} + +// MySQL evaluates the clock at statement start. Take the lock before checking the lease. +async fn lock_deployment( + transaction: &mut mysql_async::Transaction<'_>, + deployment: &[u8], +) -> Result<()> { + let revision: Option = transaction.exec_first( + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE", + (deployment,), + ).await?; + revision.ok_or(Error::MissingDeployment)?; + Ok(()) +} + +fn connection_options(address: &str, max_connections: u32, read_only: bool) -> Result { + if max_connections == 0 { + return Err(Error::Invalid("database pool size")); + } + let mut url = Url::parse(address).map_err(|_| Error::Connection)?; + let mut tls = true; + let (mut ca, mut cert, mut key) = (None, None, None); + let (mut charset, mut collation, mut timezone, mut cache_size) = (None, None, None, None); + for (name, value) in url.query_pairs() { + match name.as_ref() { + "sslmode" | "ssl-mode" => { + tls = match value.as_ref() { + "DISABLED" => false, + "VERIFY_IDENTITY" => true, + _ => return Err(Error::Connection), + } + } + "sslca" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())), + "sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())), + "sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())), + "charset" => charset = Some(mysql_identifier(&value)?), + "collation" => collation = Some(mysql_identifier(&value)?), + "timezone" | "time-zone" => timezone = Some(value.into_owned()), + "statement-cache-capacity" => { + cache_size = Some(value.parse::().map_err(|_| Error::Connection)?) + } + _ => {} + } + } + url.set_query(None); + let mut setup = Vec::new(); + if charset.is_some() || collation.is_some() { + let charset = charset.as_deref().unwrap_or("utf8mb4"); + let names = match collation { + Some(collation) => format!("SET NAMES {charset} COLLATE {collation}"), + None => format!("SET NAMES {charset}"), + }; + setup.push(names); + } + if let Some(timezone) = timezone { + // A hex literal preserves the configured value without interpolating SQL syntax. + let mut encoded = String::new(); + for byte in timezone.as_bytes() { + write!(encoded, "{byte:02x}").expect("writing to a string cannot fail"); + } + setup.push(format!("SET time_zone = X'{encoded}'")); + } + if read_only { + setup.push("SET SESSION TRANSACTION READ ONLY".into()); + } + let constraints = + PoolConstraints::new(max_connections.min(8) as usize, max_connections as usize) + .ok_or(Error::Invalid("database pool size"))?; + let opts = Opts::from_url(url.as_str()).map_err(|_| Error::Connection)?; + let mut builder = OptsBuilder::from_opts(opts) + .prefer_socket(false) + .pool_opts( + PoolOpts::new() + .with_constraints(constraints) + .with_reset_connection(false), + ) + .setup(setup); + if let Some(cache_size) = cache_size { + builder = builder.stmt_cache_size(cache_size); + } + if tls { + let mut ssl = SslOpts::default(); + if let Some(ca) = ca { + ssl = ssl + .with_disable_built_in_roots(true) + .with_root_certs(vec![ca.into()]); + } + match (cert, key) { + (Some(cert), Some(key)) => { + ssl = ssl.with_client_identity(Some(ClientIdentity::new(cert.into(), key.into()))) + } + (None, None) => {} + _ => return Err(Error::Connection), + } + builder = builder.ssl_opts(Some(ssl)); + } + Ok(builder.into()) +} + +fn mysql_identifier(value: &str) -> Result { + if value.is_empty() + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + { + return Err(Error::Connection); + } + Ok(format!("`{value}`")) } fn lease_millis(ttl: Duration) -> Result { diff --git a/crates/db/src/postgres.rs b/crates/db/src/postgres.rs index d857daf..e2bf92d 100644 --- a/crates/db/src/postgres.rs +++ b/crates/db/src/postgres.rs @@ -1,6 +1,17 @@ //! PostgreSQL connection pools and the Bedrock document layout. -use crate::common::{Dialect, Reader, Result, Store, pool}; +use std::{fs::File, io::BufReader, path::PathBuf, sync::Arc}; + +use deadpool_postgres::{Manager, Pool, Runtime}; +use rustls::{ClientConfig, RootCertStore}; +use tokio_postgres::{Config, config::SslMode}; +use tokio_postgres_rustls::MakeRustlsConnect; +use url::Url; + +use crate::common::{ + CONNECT_TIMEOUT, Error, Mutation, Result, Revision, Snapshot, encode_batch, snapshot, + validate_id, validate_read, +}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( @@ -18,23 +29,245 @@ const SCHEMA: &[&str] = &[ )", ]; -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 +const GET_DOCUMENT: &str = " + SELECT d.revision, v.revision, v.payload + FROM bedrock_deployments d + LEFT JOIN bedrock_documents v + ON v.deployment = d.deployment AND v.collection = $1 AND v.document_id = $2 + AND v.revision <= COALESCE($3, d.revision) + WHERE d.deployment = $4 AND d.retired = 0 + ORDER BY v.revision DESC LIMIT 1"; + +#[derive(Clone)] +pub struct PostgresReader { + pool: Pool, + deployment: Arc<[u8]>, } -pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { - Reader::new( - pool(Dialect::Postgres, url, max_connections, true)?, - Dialect::Postgres, - deployment, - ) +#[derive(Clone)] +pub struct Postgres { + reader: PostgresReader, +} + +pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result { + let reader = PostgresReader::new(url, deployment, max_connections, false)?; + { + let mut client = reader.client().await?; + let transaction = client.transaction().await?; + // PostgreSQL catalog inserts can race even with IF NOT EXISTS. + transaction + .batch_execute("SELECT pg_advisory_xact_lock(1694199371)") + .await?; + for ddl in SCHEMA { + transaction.batch_execute(ddl).await?; + } + transaction + .execute( + "INSERT INTO bedrock_deployments (deployment) VALUES ($1) + ON CONFLICT (deployment) DO NOTHING", + &[&reader.deployment.as_ref()], + ) + .await?; + transaction.commit().await?; + } + reader.revision().await?; + Ok(Postgres { reader }) +} + +pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { + PostgresReader::new(url, deployment, max_connections, true) +} + +impl PostgresReader { + fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result { + validate_id(deployment)?; + if max_connections == 0 { + return Err(Error::Invalid("database pool size")); + } + let (config, tls) = connection_options(url, read_only)?; + let manager = Manager::new(config, tls); + let pool = Pool::builder(manager) + .max_size(max_connections as usize) + .runtime(Runtime::Tokio1) + .wait_timeout(Some(CONNECT_TIMEOUT)) + .create_timeout(Some(CONNECT_TIMEOUT)) + .build() + .map_err(|_| Error::Connection)?; + Ok(Self { + pool, + deployment: Arc::from(deployment.as_bytes()), + }) + } + + async fn client(&self) -> Result { + self.pool.get().await.map_err(|_| Error::Connection) + } + + pub async fn revision(&self) -> Result { + let client = self.client().await?; + let query = client + .prepare_cached( + "SELECT revision FROM bedrock_deployments WHERE deployment = $1 AND retired = 0", + ) + .await?; + let row = client + .query_opt(&query, &[&self.deployment.as_ref()]) + .await? + .ok_or(Error::MissingDeployment)?; + Ok(row.try_get(0)?) + } + + pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { + validate_read(collection, id, at)?; + let client = self.client().await?; + let query = client.prepare_cached(GET_DOCUMENT).await?; + let row = client + .query_opt( + &query, + &[ + &collection.as_bytes(), + &id.as_bytes(), + &at, + &self.deployment.as_ref(), + ], + ) + .await? + .map(|row| -> Result<_> { Ok((row.try_get(0)?, row.try_get(1)?, row.try_get(2)?)) }) + .transpose()?; + snapshot(row, at) + } +} + +impl Postgres { + pub fn reader(&self) -> PostgresReader { + self.reader.clone() + } + + pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { + let (revision, rows) = encode_batch(expected, mutations)?; + let deployment = self.reader.deployment.as_ref(); + let mut client = self.reader.client().await?; + let transaction = client.transaction().await?; + let advance = transaction + .prepare_cached( + "UPDATE bedrock_deployments SET revision = $1 + WHERE deployment = $2 AND revision = $3 AND retired = 0", + ) + .await?; + if transaction + .execute(&advance, &[&revision, &deployment, &expected]) + .await? + != 1 + { + return Err(Error::WriteConflict); + } + let insert = transaction.prepare_cached( + "INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) + VALUES ($1, $2, $3, $4, $5)", + ).await?; + for row in rows { + transaction + .execute( + &insert, + &[ + &deployment, + &row.collection, + &row.id, + &revision, + &row.payload, + ], + ) + .await?; + } + transaction.commit().await?; + Ok(revision) + } +} + +fn connection_options(address: &str, read_only: bool) -> Result<(Config, MakeRustlsConnect)> { + let mut url = Url::parse(address).map_err(|_| Error::Connection)?; + let mut mode = SslMode::Require; + let (mut ca, mut cert, mut key) = (None, None, None); + let mut parameters = Vec::new(); + for (name, value) in url.query_pairs() { + match name.as_ref() { + "sslmode" | "ssl-mode" => { + mode = match value.as_ref() { + "disable" => SslMode::Disable, + // The rustls connector verifies both the certificate chain and hostname. + "verify-full" | "require" => SslMode::Require, + _ => return Err(Error::Connection), + }; + } + "sslrootcert" | "ssl-root-cert" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())), + "sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())), + "sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())), + "application_name" | "user" | "password" => { + parameters.push((name.into_owned(), value.into_owned())) + } + _ => {} + } + } + url.set_query(None); + if !parameters.is_empty() { + url.query_pairs_mut().extend_pairs(parameters); + } + let mut config: Config = url.as_str().parse().map_err(|_| Error::Connection)?; + config.ssl_mode(mode).connect_timeout(CONNECT_TIMEOUT); + if read_only { + config.options("-c default_transaction_read_only=on"); + } + let tls = tls_config(mode, ca, cert, key)?; + Ok((config, MakeRustlsConnect::new(tls))) +} + +fn tls_config( + mode: SslMode, + ca: Option, + cert: Option, + key: Option, +) -> Result { + let open = |path| { + File::open(path) + .map(BufReader::new) + .map_err(|_| Error::Connection) + }; + let mut roots = RootCertStore::empty(); + if mode != SslMode::Disable { + if let Some(path) = ca { + let mut file = open(path)?; + let mut count = 0; + for cert in rustls_pemfile::certs(&mut file) { + roots + .add(cert.map_err(|_| Error::Connection)?) + .map_err(|_| Error::Connection)?; + count += 1; + } + if count == 0 { + return Err(Error::Connection); + } + } else { + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + } + } + let builder = + ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions() + .map_err(|_| Error::Connection)? + .with_root_certificates(roots); + match (mode, cert, key) { + (SslMode::Disable, _, _) | (_, None, None) => Ok(builder.with_no_client_auth()), + (_, Some(cert), Some(key)) => { + let chain = rustls_pemfile::certs(&mut open(cert)?) + .collect::>>() + .map_err(|_| Error::Connection)?; + let key = rustls_pemfile::private_key(&mut open(key)?) + .map_err(|_| Error::Connection)? + .ok_or(Error::Connection)?; + builder + .with_client_auth_cert(chain, key) + .map_err(|_| Error::Connection) + } + _ => Err(Error::Connection), + } } diff --git a/crates/db/src/sqlite.rs b/crates/db/src/sqlite.rs index ed338b6..8ca0de7 100644 --- a/crates/db/src/sqlite.rs +++ b/crates/db/src/sqlite.rs @@ -1,6 +1,15 @@ //! File-backed Bedrock storage for self-hosted deployments. -use crate::common::{Dialect, Reader, Result, Store, pool}; +use std::sync::Arc; + +use rusqlite::{OpenFlags, OptionalExtension, TransactionBehavior, params}; +use tokio::sync::OnceCell; +use tokio_rusqlite::Connection; + +use crate::common::{ + CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch, + snapshot, validate_id, validate_read, +}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( @@ -19,23 +28,179 @@ const SCHEMA: &[&str] = &[ )", ]; -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 +#[derive(Clone)] +pub struct SqliteReader { + inner: Arc, } -pub fn reader(url: &str, deployment: &str) -> Result { - Reader::new( - pool(Dialect::Sqlite, url, 1, true)?, - Dialect::Sqlite, - deployment, - ) +struct Endpoint { + uri: String, + flags: OpenFlags, + deployment: Vec, + connection: OnceCell, +} + +#[derive(Clone)] +pub struct Sqlite { + reader: SqliteReader, +} + +pub async fn connect(url: &str, deployment: &str) -> Result { + let reader = SqliteReader::new(url, deployment, false)?; + let deployment = reader.inner.deployment.clone(); + reader + .call(move |connection| { + let transaction = + connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + for ddl in SCHEMA { + transaction.execute_batch(ddl)?; + } + transaction.execute( + "INSERT INTO bedrock_deployments (deployment) VALUES (?) + ON CONFLICT (deployment) DO NOTHING", + [deployment], + )?; + transaction.commit()?; + Ok(()) + }) + .await?; + reader.revision().await?; + Ok(Sqlite { reader }) +} + +pub fn reader(url: &str, deployment: &str) -> Result { + SqliteReader::new(url, deployment, true) +} + +impl SqliteReader { + fn new(url: &str, deployment: &str, read_only: bool) -> Result { + validate_id(deployment)?; + let address = url.strip_prefix("sqlite:").ok_or(Error::Connection)?; + let address = address.strip_prefix("//").unwrap_or(address); + let mut flags = OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX; + let uri = if read_only { + flags |= OpenFlags::SQLITE_OPEN_READ_ONLY; + let (path, query) = address.split_once('?').unwrap_or((address, "")); + let options = + url::form_urlencoded::parse(query.as_bytes()).filter(|(key, _)| key != "mode"); + let query = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs(options) + .append_pair("mode", "ro") + .finish(); + format!("file:{path}?{query}") + } else { + flags |= OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE; + if address == ":memory:" { + address.to_owned() + } else { + format!("file:{address}") + } + }; + Ok(Self { + inner: Arc::new(Endpoint { + uri, + flags, + deployment: deployment.as_bytes().to_vec(), + connection: OnceCell::new(), + }), + }) + } + + async fn call( + &self, + operation: impl FnOnce(&mut rusqlite::Connection) -> Result + Send + 'static, + ) -> Result { + let connection = self + .inner + .connection + .get_or_try_init(|| async { + let connection = Connection::open_with_flags(&self.inner.uri, self.inner.flags) + .await + .map_err(|_| Error::Connection)?; + connection + .call(|connection| { + connection.busy_timeout(CONNECT_TIMEOUT)?; + connection.pragma_update(None, "foreign_keys", "ON")?; + Ok(()) + }) + .await + .map_err(|_| Error::Connection)?; + Ok::<_, Error>(connection) + }) + .await?; + connection + .call(move |connection| Ok(operation(connection))) + .await + .map_err(|_| Error::Connection)? + } + + pub async fn revision(&self) -> Result { + let deployment = self.inner.deployment.clone(); + self.call(move |connection| { + connection + .prepare_cached( + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", + )? + .query_row([deployment], |row| row.get(0)) + .optional()? + .ok_or(Error::MissingDeployment) + }) + .await + } + + pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { + validate_read(collection, id, at)?; + let collection = collection.as_bytes().to_vec(); + let id = id.as_bytes().to_vec(); + let deployment = self.inner.deployment.clone(); + let row = self + .call(move |connection| { + Ok(connection + .prepare_cached(GET_DOCUMENT)? + .query_row(params![collection, id, at, deployment], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .optional()?) + }) + .await?; + snapshot(row, at) + } +} + +impl Sqlite { + pub fn reader(&self) -> SqliteReader { + self.reader.clone() + } + + pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { + let (revision, rows) = encode_batch(expected, mutations)?; + let rows: Vec<_> = rows + .into_iter() + .map(|row| (row.collection.to_vec(), row.id.to_vec(), row.payload)) + .collect(); + let deployment = self.reader.inner.deployment.clone(); + self.reader + .call(move |connection| { + let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + let advanced = transaction.prepare_cached( + "UPDATE bedrock_deployments SET revision = ? + WHERE deployment = ? AND revision = ? AND retired = 0", + )?.execute(params![revision, deployment, expected])?; + if advanced != 1 { + return Err(Error::WriteConflict); + } + { + let mut insert = transaction.prepare_cached( + "INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) + VALUES (?, ?, ?, ?, ?)", + )?; + for (collection, id, payload) in rows { + insert.execute(params![deployment, collection, id, revision, payload])?; + } + } + transaction.commit()?; + Ok(revision) + }) + .await + } } diff --git a/crates/db/tests/storage.rs b/crates/db/tests/storage.rs index baea0f5..f7989af 100644 --- a/crates/db/tests/storage.rs +++ b/crates/db/tests/storage.rs @@ -136,6 +136,19 @@ async fn sqlite_persists_across_reopening_and_enforces_read_only() { )); } +#[tokio::test] +async fn sqlite_read_only_startup_does_not_create_a_database() { + let folder = tempfile::tempdir().unwrap(); + let filename = folder.path().join("missing.sqlite"); + let config = DeploymentConfig { + read_only: true, + sqlite_path: filename.to_str().unwrap().into(), + ..DeploymentConfig::default() + }; + assert!(connect(&config).await.is_err()); + assert!(!filename.exists()); +} + #[tokio::test] async fn postgres_reads_replicas_and_falls_back_when_behind() { let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else { From c270adbab4104ed203f2e8c77df705814fcec2b6 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 07:37:02 +0800 Subject: [PATCH 02/14] Print the inner string in Address debug output --- crates/clusters/src/lib.rs | 4 ++-- crates/clusters/tests/deployment_config.rs | 12 ++++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index 6fe4767..eb8bb2d 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -21,7 +21,7 @@ pub enum Tls { Disabled, } -/// A database address may contain credentials. +/// A database address. Debug output includes the full value, which may contain credentials. #[derive(Clone, Deserialize)] #[serde(transparent)] pub struct Address(String); @@ -40,7 +40,7 @@ impl From for Address { impl fmt::Debug for Address { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("Address([redacted])") + fmt::Debug::fmt(&self.0, formatter) } } diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 46bf1f0..796997e 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -1,9 +1,15 @@ use std::collections::BTreeMap; -use clusters::{Cluster, ConfigError, DeploymentConfig, Driver, Tls}; +use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; #[test] -fn named_cluster_requires_matching_addresses_and_redacts_credentials() { +fn address_debug_formats_the_inner_string() { + let value = "bedrock.sqlite3"; + assert_eq!(format!("{:?}", Address::from(value)), format!("{value:?}")); +} + +#[test] +fn named_cluster_requires_matching_addresses() { let mut config = DeploymentConfig { cluster: Some("regional".into()), clusters: BTreeMap::from([( @@ -30,8 +36,6 @@ fn named_cluster_requires_matching_addresses_and_redacts_credentials() { .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!( From 7982fffcda0ca8fc05c02309906c9b5e1e8cd33e Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:11:03 +0800 Subject: [PATCH 03/14] Add a versioned backend catalog and YAML deployment configuration --- Cargo.lock | 168 ++++++++++++- Cargo.toml | 4 +- README.md | 23 +- crates/clusters/Cargo.toml | 3 + crates/clusters/src/catalog.rs | 88 +++++++ crates/clusters/src/driver.rs | 49 ++++ crates/clusters/src/format.rs | 127 ++++++++++ crates/clusters/src/lib.rs | 260 ++++++++------------- crates/clusters/src/object_storage.rs | 34 +++ crates/clusters/src/sql.rs | 169 ++++++++++++++ crates/clusters/tests/deployment_config.rs | 84 ++++++- crates/db/src/connection.rs | 14 +- crates/db/src/lib.rs | 8 +- deploy/README.md | 13 +- deploy/bedrock-deployment.svg | 2 +- deploy/kubernetes-catalog.yaml | 16 ++ deploy/multi-storage.yaml | 18 ++ deploy/release.sh | 7 +- deploy/render-postgres.py | 27 ++- deploy/sqlite.json | 4 - deploy/sqlite.yaml | 3 + src/main.rs | 26 ++- 22 files changed, 924 insertions(+), 223 deletions(-) create mode 100644 crates/clusters/src/catalog.rs create mode 100644 crates/clusters/src/driver.rs create mode 100644 crates/clusters/src/format.rs create mode 100644 crates/clusters/src/object_storage.rs create mode 100644 crates/clusters/src/sql.rs create mode 100644 deploy/kubernetes-catalog.yaml create mode 100644 deploy/multi-storage.yaml delete mode 100644 deploy/sqlite.json create mode 100644 deploy/sqlite.yaml diff --git a/Cargo.lock b/Cargo.lock index 2f38097..42ecca8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,6 +36,29 @@ version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" +[[package]] +name = "annotate-snippets" +version = "0.12.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" +dependencies = [ + "anstyle", + "memchr", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "arraydeque" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" + [[package]] name = "async-trait" version = "0.1.92" @@ -69,8 +92,8 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" name = "bedrock" version = "0.1.0" dependencies = [ + "clusters", "db", - "serde_json", "tokio", ] @@ -157,7 +180,10 @@ name = "clusters" version = "0.1.0" dependencies = [ "serde", + "serde-saphyr", + "serde_json", "thiserror", + "toml", "url", ] @@ -179,6 +205,12 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -368,6 +400,29 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "encoding_rs_io" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" +dependencies = [ + "encoding_rs", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -545,6 +600,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "granit-parser" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd04d0d9c7079b416b458d2317aea4aa964c81938cb7c20f559758c4f422dc8" +dependencies = [ + "arraydeque", + "smallvec", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -837,6 +902,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "mysql_async" version = "0.36.2" @@ -895,6 +966,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + [[package]] name = "num-bigint" version = "0.4.8" @@ -1290,6 +1367,23 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-saphyr" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" +dependencies = [ + "annotate-snippets", + "base64", + "encoding_rs_io", + "granit-parser", + "nohash-hasher", + "num-traits", + "serde_core", + "smallvec", + "zmij", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -1323,6 +1417,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "sha1" version = "0.10.7" @@ -1368,6 +1471,12 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "siphasher" version = "1.0.4" @@ -1644,6 +1753,45 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tracing" version = "0.1.44" @@ -1714,6 +1862,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "untrusted" version = "0.9.0" @@ -1975,6 +2129,18 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index 106fe02..1e29d5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,8 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std" rustls-pemfile = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" +serde-saphyr = { version = "2.2", default-features = false, features = ["deserialize", "serialize"] } +toml = "0.9" tempfile = "3" thiserror = "2" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } @@ -32,6 +34,6 @@ edition.workspace = true rust-version.workspace = true [dependencies] +clusters.workspace = true db.workspace = true -serde_json.workspace = true tokio.workspace = true diff --git a/README.md b/README.md index 37bbfcd..ed26a55 100644 --- a/README.md +++ b/README.md @@ -4,32 +4,19 @@ 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 `common.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 document types, validation, and encoding 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) +Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock supports named SQL roles and read replicas. The catalog can describe S3 buckets. Object I/O, workspace routing, 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: +Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model. -```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 - } - } -} -``` +`clusters` lists SQL connection targets, and `sql` binds roles such as `documents` to those targets. The legacy `cluster` field selects the `documents` role. `object_storage` describes named object stores. The executable logs the configuration version and initializes every configured SQL role at startup. 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::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 use `db::connect` for the documents role or `db::connect_sql` for an explicitly resolved SQL role. 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/clusters/Cargo.toml b/crates/clusters/Cargo.toml index 5fdebbe..459c6b0 100644 --- a/crates/clusters/Cargo.toml +++ b/crates/clusters/Cargo.toml @@ -6,5 +6,8 @@ rust-version.workspace = true [dependencies] serde.workspace = true +serde_json.workspace = true +serde-saphyr.workspace = true +toml.workspace = true thiserror.workspace = true url.workspace = true diff --git a/crates/clusters/src/catalog.rs b/crates/clusters/src/catalog.rs new file mode 100644 index 0000000..09f1327 --- /dev/null +++ b/crates/clusters/src/catalog.rs @@ -0,0 +1,88 @@ +use serde::{Deserialize, Serialize}; + +use crate::{Cluster, ConfigError, DeploymentConfig, Driver, ObjectStorage, validate_name}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Resource { + Sql(Cluster), + ObjectStore(ObjectStorage), +} + +#[derive(Clone, Copy, Debug)] +pub enum ResourceRef<'a> { + Sql(&'a Cluster), + ObjectStore(&'a ObjectStorage), +} + +impl ResourceRef<'_> { + pub fn driver(self) -> Driver { + match self { + Self::Sql(cluster) => Driver::Sql(cluster.driver), + Self::ObjectStore(store) => Driver::ObjectStore(store.driver), + } + } +} + +impl DeploymentConfig { + pub fn resource(&self, name: &str) -> Option> { + self.clusters + .get(name) + .map(ResourceRef::Sql) + .or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore)) + } + + pub fn resources(&self) -> impl Iterator)> { + self.clusters + .iter() + .map(|(name, value)| (name.as_str(), ResourceRef::Sql(value))) + .chain( + self.object_storage + .iter() + .map(|(name, value)| (name.as_str(), ResourceRef::ObjectStore(value))), + ) + } + + pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> { + if self.resource(&name).is_some() { + return Err(ConfigError::DuplicateResource); + } + self.store_resource(name, resource) + } + + pub fn update_resource(&mut self, name: &str, resource: Resource) -> Result<(), ConfigError> { + match (self.resource(name), &resource) { + (None, _) => return Err(ConfigError::MissingResource), + (Some(ResourceRef::Sql(_)), Resource::Sql(_)) + | (Some(ResourceRef::ObjectStore(_)), Resource::ObjectStore(_)) => {} + _ => return Err(ConfigError::ResourceCategory), + } + self.store_resource(name.to_owned(), resource) + } + + pub fn remove_resource(&mut self, name: &str) -> Result { + if self.cluster.as_deref() == Some(name) || self.sql.values().any(|target| target == name) { + return Err(ConfigError::ResourceInUse); + } + self.clusters + .remove(name) + .map(Resource::Sql) + .or_else(|| self.object_storage.remove(name).map(Resource::ObjectStore)) + .ok_or(ConfigError::MissingResource) + } + + fn store_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> { + validate_name(&name, "resource")?; + match resource { + Resource::Sql(cluster) => { + cluster.resolve(&self.deployment, Some(&name), self.read_only)?; + self.clusters.insert(name, cluster); + } + Resource::ObjectStore(store) => { + store.validate()?; + self.object_storage.insert(name, store); + } + } + Ok(()) + } +} diff --git a/crates/clusters/src/driver.rs b/crates/clusters/src/driver.rs new file mode 100644 index 0000000..3e40b4e --- /dev/null +++ b/crates/clusters/src/driver.rs @@ -0,0 +1,49 @@ +use serde::{Deserialize, Serialize}; + +use crate::SqlDriver; + +/// Backend taxonomy. Configuration currently enables SQL and object storage. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Driver { + Sql(SqlDriver), + ObjectStore(ObjectStoreDriver), + // Reserved for future adapters. + Cache(CacheDriver), + Search(SearchDriver), + EventStream(EventStreamDriver), + BatchCompute(BatchComputeDriver), + OnlineService(OnlineServiceKind), +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ObjectStoreDriver { + S3, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CacheDriver { + Redis, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SearchDriver { + OpenSearch, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum EventStreamDriver { + Kafka, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum BatchComputeDriver { + Spark, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum OnlineServiceKind { + Recommendation, + Retrieval, + Ranking, +} diff --git a/crates/clusters/src/format.rs b/crates/clusters/src/format.rs new file mode 100644 index 0000000..f4adec0 --- /dev/null +++ b/crates/clusters/src/format.rs @@ -0,0 +1,127 @@ +use std::{collections::BTreeMap, path::Path}; + +use serde::Deserialize; +use serde::de::DeserializeOwned; +use thiserror::Error; + +use crate::{ConfigError, DeploymentConfig, Resource}; + +#[derive(Clone, Copy, Debug)] +pub enum ConfigFormat { + Yaml, + Toml, + /// Compatibility with previously published deployment files. + Json, +} + +#[derive(Clone, Copy, Debug)] +pub enum ImportFormat { + Catalog(ConfigFormat), + /// The bedrock_resources output of terraform output -json. + TerraformOutputs, + /// A ConfigMap carrying a catalog in data["bedrock-resources.yaml"]. + KubernetesConfigMap, +} + +#[derive(Debug, Error)] +pub enum FormatError { + #[error("configuration filename must end in .yaml, .yml, .toml or .json")] + FileExtension, + #[error("could not read the deployment configuration: {0}")] + Io(#[from] std::io::Error), + // Parser errors may quote connection strings or credentials. + #[error("invalid {0} configuration document")] + Parse(&'static str), + #[error("could not serialize the deployment configuration as YAML")] + Serialize, + #[error("import does not contain a Bedrock resource catalog")] + MissingCatalog, + #[error("publishable deployment configuration requires a valid catalog: {0}")] + Config(#[from] ConfigError), +} + +impl ConfigFormat { + fn parse(self, input: &str) -> Result { + match self { + Self::Yaml => serde_saphyr::from_str(input).map_err(|_| FormatError::Parse("YAML")), + Self::Toml => toml::from_str(input).map_err(|_| FormatError::Parse("TOML")), + Self::Json => serde_json::from_str(input).map_err(|_| FormatError::Parse("JSON")), + } + } +} + +impl DeploymentConfig { + pub fn parse(input: &str, format: ConfigFormat) -> Result { + format.parse(input) + } + + pub fn load(path: impl AsRef) -> Result { + let path = path.as_ref(); + let format = match path.extension().and_then(|value| value.to_str()) { + Some("yaml" | "yml") => ConfigFormat::Yaml, + Some("toml") => ConfigFormat::Toml, + Some("json") => ConfigFormat::Json, + _ => return Err(FormatError::FileExtension), + }; + Self::parse(&std::fs::read_to_string(path)?, format) + } + + /// Serializes the configuration, including any credentials in connection strings. + pub fn to_yaml(&self) -> Result { + self.resolve()?; + serde_saphyr::to_string(self).map_err(|_| FormatError::Serialize) + } + + /// Imports an inventory atomically. Deployment roles are assigned separately. + pub fn import_resources( + &mut self, + input: &str, + format: ImportFormat, + ) -> Result<(), FormatError> { + let resources: BTreeMap = match format { + ImportFormat::Catalog(format) => format.parse(input)?, + ImportFormat::TerraformOutputs => { + let exports: TerraformOutputs = ConfigFormat::Json.parse(input)?; + exports + .bedrock_resources + .ok_or(FormatError::MissingCatalog)? + .value + } + ImportFormat::KubernetesConfigMap => { + let manifest: ConfigMap = ConfigFormat::Yaml.parse(input)?; + if manifest.kind != "ConfigMap" || manifest.api_version != "v1" { + return Err(FormatError::MissingCatalog); + } + let catalog = manifest + .data + .get("bedrock-resources.yaml") + .ok_or(FormatError::MissingCatalog)?; + ConfigFormat::Yaml.parse(catalog)? + } + }; + let mut candidate = self.clone(); + for (name, resource) in resources { + candidate.insert_resource(name, resource)?; + } + *self = candidate; + Ok(()) + } +} + +#[derive(Deserialize)] +struct TerraformOutputs { + bedrock_resources: Option, +} + +#[derive(Deserialize)] +struct TerraformOutput { + value: BTreeMap, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ConfigMap { + api_version: String, + kind: String, + data: BTreeMap, +} diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index eb8bb2d..feb7c3a 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -1,78 +1,35 @@ -use std::{collections::BTreeMap, fmt, path::Path}; +//! Runtime configuration and named backend resources for Bedrock. -use serde::Deserialize; +mod catalog; +mod driver; +mod format; +mod object_storage; +mod sql; + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; 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, -} +pub use catalog::{Resource, ResourceRef}; +pub use driver::*; +pub use format::{ConfigFormat, FormatError, ImportFormat}; +pub use object_storage::ObjectStorage; +pub use sql::{Address, Cluster, ResolvedSql, SqlDriver, Tls}; -#[derive(Clone, Copy, Debug, Default, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Tls { - #[default] - VerifyFull, - Disabled, -} +pub const DOCUMENTS: &str = "documents"; -/// A database address. Debug output includes the full value, which 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 { - fmt::Debug::fmt(&self.0, formatter) - } -} - -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)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default, deny_unknown_fields)] pub struct DeploymentConfig { pub deployment: String, + pub config_version: String, + /// Legacy shorthand for sql.documents. pub cluster: Option, pub clusters: BTreeMap, + /// SQL role to named cluster. + pub sql: BTreeMap, + pub object_storage: BTreeMap, pub read_only: bool, pub sqlite_path: Address, } @@ -81,23 +38,30 @@ impl Default for DeploymentConfig { fn default() -> Self { Self { deployment: "default".into(), + config_version: "local".into(), cluster: None, clusters: BTreeMap::new(), + sql: BTreeMap::new(), + object_storage: BTreeMap::new(), read_only: false, sqlite_path: "bedrock.sqlite3".into(), } } } -#[derive(Debug)] +/// A validated startup snapshot. The version identifies the configuration release. +#[derive(Clone, 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, + pub config_version: String, + pub sql: BTreeMap, + pub object_storage: BTreeMap, +} + +impl ResolvedDeployment { + pub fn documents(&self) -> Option<&ResolvedSql> { + self.sql.get(DOCUMENTS) + } } #[derive(Debug, Error)] @@ -108,6 +72,18 @@ pub enum ConfigError { UnknownCluster, #[error("a cluster must be selected when clusters are configured")] ClusterRequired, + #[error("legacy cluster and sql.documents refer to different resources")] + ConflictingDocuments, + #[error("invalid object storage configuration")] + ObjectStorage, + #[error("resource already exists")] + DuplicateResource, + #[error("resource does not exist")] + MissingResource, + #[error("resource is referenced by a SQL binding")] + ResourceInUse, + #[error("a resource update must preserve its category")] + ResourceCategory, #[error("the database pool size must be greater than zero")] PoolSize, #[error("SQLite does not support a replica list")] @@ -121,46 +97,68 @@ pub enum ConfigError { 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)? + validate_name(&self.config_version, "config version")?; + let mut targets = BTreeMap::new(); + for (name, cluster) in &self.clusters { + validate_name(name, "cluster")?; + targets.insert( + name.as_str(), + cluster.resolve(&self.deployment, Some(name), self.read_only)?, + ); + } + for (name, store) in &self.object_storage { + validate_name(name, "object store")?; + if self.clusters.contains_key(name) { + return Err(ConfigError::DuplicateResource); } - None if self.clusters.is_empty() => &local, - None => return Err(ConfigError::ClusterRequired), - }; - if cluster.max_connections == 0 { - return Err(ConfigError::PoolSize); + store.validate()?; } - if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() { - return Err(ConfigError::SqliteReplicas); + + let mut sql = BTreeMap::new(); + for (role, target) in &self.sql { + validate_name(role, "SQL role")?; + validate_name(target, "cluster")?; + let settings = targets + .get(target.as_str()) + .ok_or(ConfigError::UnknownCluster)?; + sql.insert(role.clone(), settings.clone()); + } + if let Some(name) = &self.cluster { + validate_name(name, "cluster")?; + if self.sql.get(DOCUMENTS).is_some_and(|target| target != name) { + return Err(ConfigError::ConflictingDocuments); + } + let settings = targets + .get(name.as_str()) + .ok_or(ConfigError::UnknownCluster)?; + sql.insert(DOCUMENTS.into(), settings.clone()); + } + if sql.is_empty() { + if !targets.is_empty() { + return Err(ConfigError::ClusterRequired); + } + let local = Cluster { + driver: SqlDriver::Sqlite, + primary: self.sqlite_path.clone(), + replicas: vec![], + tls: Tls::Disabled, + max_connections: 1, + }; + sql.insert( + DOCUMENTS.into(), + local.resolve(&self.deployment, None, self.read_only)?, + ); } - 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, + config_version: self.config_version.clone(), + sql, + object_storage: self.object_storage.clone(), }) } } -fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> { +pub(crate) fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> { if value.is_empty() || value.len() > 128 || !value @@ -171,59 +169,3 @@ fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> { } 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}"))) -} diff --git a/crates/clusters/src/object_storage.rs b/crates/clusters/src/object_storage.rs new file mode 100644 index 0000000..1aeb33e --- /dev/null +++ b/crates/clusters/src/object_storage.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; +use url::Url; + +use crate::{ConfigError, ObjectStoreDriver}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ObjectStorage { + pub driver: ObjectStoreDriver, + pub bucket: String, + pub region: String, + pub endpoint: Option, +} + +impl ObjectStorage { + pub(crate) fn validate(&self) -> Result<(), ConfigError> { + if self.bucket.trim().is_empty() || self.region.trim().is_empty() { + return Err(ConfigError::ObjectStorage); + } + if let Some(endpoint) = &self.endpoint { + let url = Url::parse(endpoint).map_err(|_| ConfigError::ObjectStorage)?; + if !matches!(url.scheme(), "http" | "https") + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(ConfigError::ObjectStorage); + } + } + Ok(()) + } +} diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs new file mode 100644 index 0000000..02fc1d0 --- /dev/null +++ b/crates/clusters/src/sql.rs @@ -0,0 +1,169 @@ +use std::{fmt, path::Path}; + +use serde::{Deserialize, Serialize}; +use url::Url; + +use crate::ConfigError; + +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SqlDriver { + #[default] + Sqlite, + Postgres, + Mysql, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Tls { + #[default] + VerifyFull, + Disabled, +} + +/// A database address. Debug output includes the full value, which may contain credentials. +#[derive(Clone, Deserialize, Serialize)] +#[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 { + fmt::Debug::fmt(&self.0, formatter) + } +} + +impl Address { + pub fn connection_string(&self) -> &str { + &self.0 + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Cluster { + pub driver: SqlDriver, + pub primary: Address, + #[serde(default)] + pub replicas: Vec
, + #[serde(default)] + pub tls: Tls, + #[serde(default = "default_pool_size")] + pub max_connections: u32, +} + +const DEFAULT_POOL_SIZE: u32 = 5; + +fn default_pool_size() -> u32 { + DEFAULT_POOL_SIZE +} + +#[derive(Clone, Debug)] +pub struct ResolvedSql { + pub deployment: String, + pub cluster: Option, + pub driver: SqlDriver, + pub primary: Address, + pub replicas: Vec
, + pub read_only: bool, + pub max_connections: u32, +} + +impl Cluster { + pub(crate) fn resolve( + &self, + deployment: &str, + name: Option<&str>, + read_only: bool, + ) -> Result { + if self.max_connections == 0 { + return Err(ConfigError::PoolSize); + } + if self.driver == SqlDriver::Sqlite && !self.replicas.is_empty() { + return Err(ConfigError::SqliteReplicas); + } + let primary = resolve_address(self, &self.primary, read_only)?; + let replicas = self + .replicas + .iter() + .map(|address| resolve_address(self, address, true)) + .collect::>()?; + Ok(ResolvedSql { + deployment: deployment.into(), + cluster: name.map(str::to_owned), + driver: self.driver, + primary, + replicas, + read_only, + max_connections: self.max_connections, + }) + } +} + +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 { + SqlDriver::Sqlite => return sqlite_url(address, read_only), + SqlDriver::Postgres => ("postgres", "sslmode", "verify-full", "disable"), + SqlDriver::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}"))) +} diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 796997e..6702806 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; +use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver, Tls}; #[test] fn address_debug_formats_the_inner_string() { @@ -15,7 +15,7 @@ fn named_cluster_requires_matching_addresses() { clusters: BTreeMap::from([( "regional".into(), Cluster { - driver: Driver::Postgres, + driver: SqlDriver::Postgres, primary: "postgres://user:secret@primary/bedrock".into(), replicas: vec!["postgresql://reader:secret@replica/bedrock".into()], tls: Tls::VerifyFull, @@ -25,6 +25,7 @@ fn named_cluster_requires_matching_addresses() { ..DeploymentConfig::default() }; let resolved = config.resolve().unwrap(); + let resolved = resolved.documents().unwrap(); assert!( resolved .primary @@ -43,3 +44,82 @@ fn named_cluster_requires_matching_addresses() { Err(ConfigError::Url("postgres")) )); } + +#[test] +fn resolves_named_connections_and_round_trips_yaml() { + use clusters::ConfigFormat; + + let config = DeploymentConfig::parse( + include_str!("../../../deploy/multi-storage.yaml"), + ConfigFormat::Yaml, + ) + .unwrap(); + let snapshot = config.resolve().unwrap(); + assert_eq!(snapshot.config_version, "example-1"); + assert_eq!(snapshot.documents().unwrap().driver, SqlDriver::Postgres); + assert_eq!(snapshot.sql["legacy"].driver, SqlDriver::Mysql); + assert_eq!( + snapshot.object_storage["attachments"].bucket, + "bedrock-attachments" + ); + assert_eq!(snapshot.documents().unwrap().max_connections, 5); + + let serialized = config.to_yaml().unwrap(); + let roundtrip = DeploymentConfig::parse(&serialized, ConfigFormat::Yaml) + .unwrap() + .resolve() + .unwrap(); + assert_eq!(roundtrip.sql["legacy"].driver, SqlDriver::Mysql); +} + +#[test] +fn imports_catalog_atomically_and_preserves_role_references() { + use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver, Resource}; + + let mut config = + DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap(); + config + .import_resources( + include_str!("../../../deploy/kubernetes-catalog.yaml"), + ImportFormat::KubernetesConfigMap, + ) + .unwrap(); + config.sql.insert("documents".into(), "pg-main".into()); + + let before = config.resource("attachments").unwrap().driver(); + assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3)); + assert!(matches!( + config.remove_resource("pg-main"), + Err(ConfigError::ResourceInUse) + )); + + let inventory = r#"{ + "bedrock_resources": { + "value": { + "another-bucket": {"kind":"object_store","driver":"s3","bucket":"other","region":"us-east-1"}, + "attachments": {"kind":"object_store","driver":"s3","bucket":"duplicate","region":"us-east-1"} + } + } + }"#; + assert!( + config + .import_resources(inventory, ImportFormat::TerraformOutputs) + .is_err() + ); + assert!(config.resource("another-bucket").is_none()); + let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else { + panic!("expected S3 configuration"); + }; + updated.bucket = "updated".into(); + config + .insert_resource("attachments".into(), Resource::ObjectStore(updated.clone())) + .unwrap(); + updated.bucket = "replaced".into(); + config + .update_resource("attachments", Resource::ObjectStore(updated)) + .unwrap(); + assert_eq!( + config.resolve().unwrap().object_storage["attachments"].bucket, + "replaced" + ); +} diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index e50d51b..9d5d974 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -2,7 +2,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; -use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment}; +use clusters::{Address, ConfigError, DeploymentConfig, ResolvedSql, SqlDriver as Driver}; use thiserror::Error; use crate::{ @@ -16,6 +16,8 @@ use crate::{ pub enum ConnectError { #[error(transparent)] Config(#[from] ConfigError), + #[error("the documents SQL role is not configured")] + MissingDocuments, #[error(transparent)] Storage(#[from] StorageError), } @@ -100,6 +102,10 @@ pub struct Connection { pub async fn connect(config: &DeploymentConfig) -> Result { let config = config.resolve()?; + connect_sql(config.documents().ok_or(ConnectError::MissingDocuments)?).await +} + +pub async fn connect_sql(config: &ResolvedSql) -> Result { let writer = if config.read_only { None } else { @@ -115,7 +121,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result store.reader(), None => { - let reader = reader(&config, &config.primary)?; + let reader = reader(config, &config.primary)?; reader.revision().await?; reader } @@ -123,7 +129,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result>()?; Ok(Connection { driver: config.driver, @@ -134,7 +140,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result Result { +fn reader(config: &ResolvedSql, address: &Address) -> Result { let url = address.connection_string(); let name = &config.deployment; match config.driver { diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index b928ef8..a4efbfd 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -6,9 +6,11 @@ pub mod mysql; pub mod postgres; pub mod sqlite; -pub use clusters::Driver as Dialect; -pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; +pub use clusters::SqlDriver as Dialect; +pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver as Driver, Tls}; pub use common::Error as StorageError; pub use common::{Document, Error, Mutation, Result, Revision, Snapshot}; -pub use connection::{ConnectError, Connection, ReadPreference, Reader, Store, connect}; +pub use connection::{ + ConnectError, Connection, ReadPreference, Reader, Store, connect, connect_sql, +}; pub use mysql::{Lease, MySql}; diff --git a/deploy/README.md b/deploy/README.md index 45d8eaa..5b79e8f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,12 +1,15 @@ # 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. +Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. See [local SQLite](sqlite.yaml) and [multiple SQL roles with S3 settings](multi-storage.yaml). The loader also accepts TOML and existing JSON files. -- **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. +- **SQLite** uses a persistent, writable path for `sqlite_path`. +- **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. +- **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose. +- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment 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. +Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances. + +S3 entries describe endpoints and buckets. Keep access credentials in the deployment's secret store for the eventual object storage client. 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 c07065e..67b1a6d 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -65,7 +65,7 @@ 和密码 Secret render-postgres.py -由 release.sh 调用,生成权限为 0600 的 bedrock.json。 +由 release.sh 调用,生成权限为 0600 的 bedrock.yaml。 release.sh 启动临时容器 挂载二进制和配置,运行 Rust bedrock。 diff --git a/deploy/kubernetes-catalog.yaml b/deploy/kubernetes-catalog.yaml new file mode 100644 index 0000000..9da516c --- /dev/null +++ b/deploy/kubernetes-catalog.yaml @@ -0,0 +1,16 @@ +# Resource catalog for ImportFormat::KubernetesConfigMap. +apiVersion: v1 +kind: ConfigMap +metadata: + name: bedrock-resources +data: + bedrock-resources.yaml: | + pg-main: + kind: sql + driver: postgres + primary: postgres://bedrock@pg-main:5432/bedrock + attachments: + kind: object_store + driver: s3 + bucket: bedrock-attachments + region: us-east-1 diff --git a/deploy/multi-storage.yaml b/deploy/multi-storage.yaml new file mode 100644 index 0000000..e2b3f15 --- /dev/null +++ b/deploy/multi-storage.yaml @@ -0,0 +1,18 @@ +# Illustrative service names. Inject deployment credentials before publishing. +deployment: production +config_version: example-1 +clusters: + pg-main: + driver: postgres + primary: postgres://bedrock@pg-main:5432/bedrock + mysql-legacy: + driver: mysql + primary: mysql://bedrock@mysql-legacy:3306/legacy +sql: + documents: pg-main + legacy: mysql-legacy +object_storage: + attachments: + driver: s3 + bucket: bedrock-attachments + region: us-east-1 diff --git a/deploy/release.sh b/deploy/release.sh index 57fb953..e88606a 100644 --- a/deploy/release.sh +++ b/deploy/release.sh @@ -21,16 +21,17 @@ 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 +release="$revision.${stage##*.}" +python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \ + --deployment production --config-version "$release" # 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 \ + -e BEDROCK_DB_CONFIG=/release/bedrock.yaml \ 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 diff --git a/deploy/render-postgres.py b/deploy/render-postgres.py index a3d00e2..01d8aa4 100644 --- a/deploy/render-postgres.py +++ b/deploy/render-postgres.py @@ -45,26 +45,29 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output", type=Path) parser.add_argument("--deployment", default="default") + parser.add_argument("--config-version", default="local") 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(), - } - }, - } + if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.config_version): + parser.error("invalid config version") + # JSON quoting is valid for scalars in YAML and handles special characters. + config = ( + f"deployment: {json.dumps(options.deployment)}\n" + f"config_version: {json.dumps(options.config_version)}\n" + "sql:\n" + " documents: postgres\n" + "clusters:\n" + " postgres:\n" + " driver: postgres\n" + f" primary: {json.dumps(database_url())}\n" + ) # 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") + file.write(config) os.replace(file.name, options.output) finally: Path(file.name).unlink(missing_ok=True) diff --git a/deploy/sqlite.json b/deploy/sqlite.json deleted file mode 100644 index 6e61a4d..0000000 --- a/deploy/sqlite.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "deployment": "default", - "sqlite_path": "bedrock.sqlite3" -} diff --git a/deploy/sqlite.yaml b/deploy/sqlite.yaml new file mode 100644 index 0000000..b3e7294 --- /dev/null +++ b/deploy/sqlite.yaml @@ -0,0 +1,3 @@ +deployment: default +config_version: local +sqlite_path: bedrock.sqlite3 diff --git a/src/main.rs b/src/main.rs index 5036bf6..3be0f3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,19 +1,25 @@ -use std::{env, error::Error, fs}; +use std::{env, error::Error}; -use db::{DeploymentConfig, connect}; +use clusters::DeploymentConfig; +use db::connect_sql; #[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)?)?, + Some(path) => DeploymentConfig::load(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() - ); + let resolved = config.resolve()?; + for (role, settings) in &resolved.sql { + let connection = connect_sql(settings).await?; + println!( + "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})", + resolved.config_version, + role, + connection.driver(), + connection.revision().await?, + connection.is_read_only(), + ); + } Ok(()) } From 51beaafc4c4133536bdbf826994f18b7ab1f69cc Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:19:28 +0800 Subject: [PATCH 04/14] Explain Serde derives on backend driver enums --- crates/clusters/src/driver.rs | 8 ++++++-- crates/clusters/src/sql.rs | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/clusters/src/driver.rs b/crates/clusters/src/driver.rs index 3e40b4e..998b0e2 100644 --- a/crates/clusters/src/driver.rs +++ b/crates/clusters/src/driver.rs @@ -2,12 +2,15 @@ use serde::{Deserialize, Serialize}; use crate::SqlDriver; -/// Backend taxonomy. Configuration currently enables SQL and object storage. +/// Common backend type for catalog lookups in Rust. +/// +/// Serialized configuration uses category-specific driver types in its fields. +/// Deriving Serde traits on this enum would also require them on every wrapped type. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Driver { Sql(SqlDriver), ObjectStore(ObjectStoreDriver), - // Reserved for future adapters. + // Reserved categories gain Serde traits when their configuration fields are added. Cache(CacheDriver), Search(SearchDriver), EventStream(EventStreamDriver), @@ -15,6 +18,7 @@ pub enum Driver { OnlineService(OnlineServiceKind), } +/// The driver in object storage configuration. Serde reads and writes `S3` as `s3`. #[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ObjectStoreDriver { diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs index 02fc1d0..a3cfb02 100644 --- a/crates/clusters/src/sql.rs +++ b/crates/clusters/src/sql.rs @@ -5,6 +5,8 @@ use url::Url; use crate::ConfigError; +/// The driver in SQL cluster configuration. Serde uses snake_case names such as `postgres`. +/// `SqlDriver::default()` selects `Sqlite`. #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum SqlDriver { From 73192bf944e8e6c596a639dffeb5ef64c6dad707 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:24:36 +0800 Subject: [PATCH 05/14] Document clusters module dependencies --- crates/clusters/README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 crates/clusters/README.md diff --git a/crates/clusters/README.md b/crates/clusters/README.md new file mode 100644 index 0000000..a8f7b45 --- /dev/null +++ b/crates/clusters/README.md @@ -0,0 +1,26 @@ +# clusters + +`clusters` 负责读取和校验 Bedrock 的部署配置,并解析出各用途的连接参数。 + +## 模块依赖 + +箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。 + +```mermaid +flowchart LR + lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"] + lib -->|校验对象存储配置| obj["object_storage.rs"] + + sql -->|ConfigError| lib + obj -->|ConfigError| lib + obj -->|ObjectStoreDriver| drv["driver.rs"] + drv -->|SqlDriver| sql + + cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib + cat -->|统一表示驱动类别| drv + cat -->|编辑 SQL 资源| sql + cat -->|编辑对象存储资源| obj + + fmt["format.rs"] -->|读取和输出 DeploymentConfig| lib + fmt -->|导入时调用 insert_resource| cat +``` From 3d0ce4ad7d6e82407c4fe6d701b1e65d023dc76a Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:34:40 +0800 Subject: [PATCH 06/14] Document deployment and SQL checks with Mermaid --- ci/README.md | 21 ++++++++++++++++++++- deploy/README.md | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/ci/README.md b/ci/README.md index ddef802..f02b9d9 100644 --- a/ci/README.md +++ b/ci/README.md @@ -2,4 +2,23 @@ `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) +```mermaid +flowchart TD + subgraph cd["main 更新后自动部署"] + M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] + W --> B["build-release.sh 编译发布版"] + B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] + R --> P["render-postgres.py 生成私有 bedrock.yaml"] + E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P + P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] + I -->|成功| S["保存版本并原子切换 current"] + P -->|失败| F["清理暂存目录,保留现有 current"] + I -->|失败| F + end + + subgraph manual["手动 SQL 检查"] + H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"] + C --> T["测试 SQLite、PostgreSQL 和 MySQL"] + T -->|退出时| U["清理测试容器和临时网络"] + end +``` diff --git a/deploy/README.md b/deploy/README.md index 5b79e8f..6e6e6e2 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -17,4 +17,23 @@ Pull requests currently run without an automatic storage check. The optional `ci 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) +```mermaid +flowchart TD + subgraph cd["main 更新后自动部署"] + M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] + W --> B["build-release.sh 编译发布版"] + B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] + R --> P["render-postgres.py 生成私有 bedrock.yaml"] + E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P + P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] + I -->|成功| S["保存版本并原子切换 current"] + P -->|失败| F["清理暂存目录,保留现有 current"] + I -->|失败| F + end + + subgraph manual["手动 SQL 检查"] + H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"] + C --> T["测试 SQLite、PostgreSQL 和 MySQL"] + T -->|退出时| U["清理测试容器和临时网络"] + end +``` From 353ea1558c39d57a5319d9b566a954ab2cddba36 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:43:15 +0800 Subject: [PATCH 07/14] Stack deployment and SQL check diagrams vertically --- ci/README.md | 37 ++++++++++++++++++++----------------- deploy/README.md | 37 ++++++++++++++++++++----------------- 2 files changed, 40 insertions(+), 34 deletions(-) diff --git a/ci/README.md b/ci/README.md index f02b9d9..b8d7bc1 100644 --- a/ci/README.md +++ b/ci/README.md @@ -2,23 +2,26 @@ `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. +## Automatic deployment + ```mermaid flowchart TD - subgraph cd["main 更新后自动部署"] - M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] - W --> B["build-release.sh 编译发布版"] - B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] - R --> P["render-postgres.py 生成私有 bedrock.yaml"] - E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P - P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] - I -->|成功| S["保存版本并原子切换 current"] - P -->|失败| F["清理暂存目录,保留现有 current"] - I -->|失败| F - end - - subgraph manual["手动 SQL 检查"] - H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"] - C --> T["测试 SQLite、PostgreSQL 和 MySQL"] - T -->|退出时| U["清理测试容器和临时网络"] - end + M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] + W --> B["build-release.sh 编译发布版"] + B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] + R --> P["render-postgres.py 生成私有 bedrock.yaml"] + E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P + P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] + I -->|成功| S["保存版本并原子切换 current"] + P -->|失败| F["清理暂存目录,保留现有 current"] + I -->|失败| F +``` + +## Manual SQL checks + +```mermaid +flowchart TD + H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"] + C --> T["测试 SQLite、PostgreSQL 和 MySQL"] + T -->|退出时| U["清理测试容器和临时网络"] ``` diff --git a/deploy/README.md b/deploy/README.md index 6e6e6e2..8da61dc 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -17,23 +17,26 @@ Pull requests currently run without an automatic storage check. The optional `ci 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. +### Automatic deployment + ```mermaid flowchart TD - subgraph cd["main 更新后自动部署"] - M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] - W --> B["build-release.sh 编译发布版"] - B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] - R --> P["render-postgres.py 生成私有 bedrock.yaml"] - E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P - P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] - I -->|成功| S["保存版本并原子切换 current"] - P -->|失败| F["清理暂存目录,保留现有 current"] - I -->|失败| F - end - - subgraph manual["手动 SQL 检查"] - H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"] - C --> T["测试 SQLite、PostgreSQL 和 MySQL"] - T -->|退出时| U["清理测试容器和临时网络"] - end + M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] + W --> B["build-release.sh 编译发布版"] + B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] + R --> P["render-postgres.py 生成私有 bedrock.yaml"] + E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P + P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] + I -->|成功| S["保存版本并原子切换 current"] + P -->|失败| F["清理暂存目录,保留现有 current"] + I -->|失败| F +``` + +### Manual SQL checks + +```mermaid +flowchart TD + H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"] + C --> T["测试 SQLite、PostgreSQL 和 MySQL"] + T -->|退出时| U["清理测试容器和临时网络"] ``` From 3c551ca0a334ebc51dbdb868f02934caa87e6ff5 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:59:32 +0800 Subject: [PATCH 08/14] Define all cluster drivers in the driver module --- crates/clusters/README.md | 6 ++++-- crates/clusters/src/driver.rs | 15 +++++++++++++-- crates/clusters/src/lib.rs | 2 +- crates/clusters/src/object_storage.rs | 2 +- crates/clusters/src/sql.rs | 13 +------------ 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/crates/clusters/README.md b/crates/clusters/README.md index a8f7b45..720143c 100644 --- a/crates/clusters/README.md +++ b/crates/clusters/README.md @@ -6,6 +6,8 @@ 箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。 +`driver.rs` 集中定义驱动类型,供 SQL 和对象存储配置模块使用。 + ```mermaid flowchart LR lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"] @@ -13,8 +15,8 @@ flowchart LR sql -->|ConfigError| lib obj -->|ConfigError| lib - obj -->|ObjectStoreDriver| drv["driver.rs"] - drv -->|SqlDriver| sql + sql -->|SqlDriver| drv["driver.rs"] + obj -->|ObjectStoreDriver| drv cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib cat -->|统一表示驱动类别| drv diff --git a/crates/clusters/src/driver.rs b/crates/clusters/src/driver.rs index 998b0e2..1cb94db 100644 --- a/crates/clusters/src/driver.rs +++ b/crates/clusters/src/driver.rs @@ -1,6 +1,6 @@ -use serde::{Deserialize, Serialize}; +//! Driver definitions shared by the backend configuration modules. -use crate::SqlDriver; +use serde::{Deserialize, Serialize}; /// Common backend type for catalog lookups in Rust. /// @@ -18,6 +18,17 @@ pub enum Driver { OnlineService(OnlineServiceKind), } +/// The driver in SQL cluster configuration. Serde uses snake_case names such as `postgres`. +/// `SqlDriver::default()` selects `Sqlite`. +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SqlDriver { + #[default] + Sqlite, + Postgres, + Mysql, +} + /// The driver in object storage configuration. Serde reads and writes `S3` as `s3`. #[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index feb7c3a..6ca9cae 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -15,7 +15,7 @@ pub use catalog::{Resource, ResourceRef}; pub use driver::*; pub use format::{ConfigFormat, FormatError, ImportFormat}; pub use object_storage::ObjectStorage; -pub use sql::{Address, Cluster, ResolvedSql, SqlDriver, Tls}; +pub use sql::{Address, Cluster, ResolvedSql, Tls}; pub const DOCUMENTS: &str = "documents"; diff --git a/crates/clusters/src/object_storage.rs b/crates/clusters/src/object_storage.rs index 1aeb33e..1fc48eb 100644 --- a/crates/clusters/src/object_storage.rs +++ b/crates/clusters/src/object_storage.rs @@ -1,7 +1,7 @@ use serde::{Deserialize, Serialize}; use url::Url; -use crate::{ConfigError, ObjectStoreDriver}; +use crate::{ConfigError, driver::ObjectStoreDriver}; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs index a3cfb02..8464bf1 100644 --- a/crates/clusters/src/sql.rs +++ b/crates/clusters/src/sql.rs @@ -3,18 +3,7 @@ use std::{fmt, path::Path}; use serde::{Deserialize, Serialize}; use url::Url; -use crate::ConfigError; - -/// The driver in SQL cluster configuration. Serde uses snake_case names such as `postgres`. -/// `SqlDriver::default()` selects `Sqlite`. -#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SqlDriver { - #[default] - Sqlite, - Postgres, - Mysql, -} +use crate::{ConfigError, driver::SqlDriver}; #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] From ac62c8a655c54dcac40acf84abc8782ab45f1525 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:05:01 +0800 Subject: [PATCH 09/14] Name SQL cluster configuration explicitly --- crates/clusters/README.md | 2 ++ crates/clusters/src/catalog.rs | 6 +++--- crates/clusters/src/lib.rs | 9 ++++++--- crates/clusters/src/sql.rs | 7 ++++--- crates/clusters/tests/deployment_config.rs | 4 ++-- crates/db/src/lib.rs | 4 +++- crates/db/tests/storage.rs | 4 ++-- 7 files changed, 22 insertions(+), 14 deletions(-) diff --git a/crates/clusters/README.md b/crates/clusters/README.md index 720143c..1d98bed 100644 --- a/crates/clusters/README.md +++ b/crates/clusters/README.md @@ -8,6 +8,8 @@ `driver.rs` 集中定义驱动类型,供 SQL 和对象存储配置模块使用。 +`sql.rs` 定义 `SqlCluster`,描述 SQL 主库和可选读副本。`catalog.rs` 的 `Resource` 统一表示 SQL 和对象存储资源。 + ```mermaid flowchart LR lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"] diff --git a/crates/clusters/src/catalog.rs b/crates/clusters/src/catalog.rs index 09f1327..60d9ae4 100644 --- a/crates/clusters/src/catalog.rs +++ b/crates/clusters/src/catalog.rs @@ -1,17 +1,17 @@ use serde::{Deserialize, Serialize}; -use crate::{Cluster, ConfigError, DeploymentConfig, Driver, ObjectStorage, validate_name}; +use crate::{ConfigError, DeploymentConfig, Driver, ObjectStorage, SqlCluster, validate_name}; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Resource { - Sql(Cluster), + Sql(SqlCluster), ObjectStore(ObjectStorage), } #[derive(Clone, Copy, Debug)] pub enum ResourceRef<'a> { - Sql(&'a Cluster), + Sql(&'a SqlCluster), ObjectStore(&'a ObjectStorage), } diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index 6ca9cae..f663554 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -15,7 +15,9 @@ pub use catalog::{Resource, ResourceRef}; pub use driver::*; pub use format::{ConfigFormat, FormatError, ImportFormat}; pub use object_storage::ObjectStorage; -pub use sql::{Address, Cluster, ResolvedSql, Tls}; +/// Compatibility name for the SQL cluster configuration. +pub use sql::SqlCluster as Cluster; +pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; pub const DOCUMENTS: &str = "documents"; @@ -26,7 +28,8 @@ pub struct DeploymentConfig { pub config_version: String, /// Legacy shorthand for sql.documents. pub cluster: Option, - pub clusters: BTreeMap, + /// Named SQL targets that can be bound to entries in `sql`. + pub clusters: BTreeMap, /// SQL role to named cluster. pub sql: BTreeMap, pub object_storage: BTreeMap, @@ -137,7 +140,7 @@ impl DeploymentConfig { if !targets.is_empty() { return Err(ConfigError::ClusterRequired); } - let local = Cluster { + let local = SqlCluster { driver: SqlDriver::Sqlite, primary: self.sqlite_path.clone(), replicas: vec![], diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs index 8464bf1..21e43da 100644 --- a/crates/clusters/src/sql.rs +++ b/crates/clusters/src/sql.rs @@ -42,9 +42,10 @@ impl Address { } } +/// A SQL target with a primary connection and optional read replicas. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct Cluster { +pub struct SqlCluster { pub driver: SqlDriver, pub primary: Address, #[serde(default)] @@ -72,7 +73,7 @@ pub struct ResolvedSql { pub max_connections: u32, } -impl Cluster { +impl SqlCluster { pub(crate) fn resolve( &self, deployment: &str, @@ -104,7 +105,7 @@ impl Cluster { } fn resolve_address( - cluster: &Cluster, + cluster: &SqlCluster, address: &Address, read_only: bool, ) -> Result { diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 6702806..45e56ba 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver, Tls}; +use clusters::{Address, ConfigError, DeploymentConfig, SqlCluster, SqlDriver, Tls}; #[test] fn address_debug_formats_the_inner_string() { @@ -14,7 +14,7 @@ fn named_cluster_requires_matching_addresses() { cluster: Some("regional".into()), clusters: BTreeMap::from([( "regional".into(), - Cluster { + SqlCluster { driver: SqlDriver::Postgres, primary: "postgres://user:secret@primary/bedrock".into(), replicas: vec!["postgresql://reader:secret@replica/bedrock".into()], diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index a4efbfd..5b95c83 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -7,7 +7,9 @@ pub mod postgres; pub mod sqlite; pub use clusters::SqlDriver as Dialect; -pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver as Driver, Tls}; +pub use clusters::{ + Address, Cluster, ConfigError, DeploymentConfig, SqlCluster, SqlDriver as Driver, Tls, +}; pub use common::Error as StorageError; pub use common::{Document, Error, Mutation, Result, Revision, Snapshot}; pub use connection::{ diff --git a/crates/db/tests/storage.rs b/crates/db/tests/storage.rs index f7989af..f485de0 100644 --- a/crates/db/tests/storage.rs +++ b/crates/db/tests/storage.rs @@ -1,7 +1,7 @@ use std::{collections::BTreeMap, env, time::Duration}; use db::{ - Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls, + Connection, DeploymentConfig, Driver, Mutation, ReadPreference, SqlCluster, StorageError, Tls, connect, }; use serde_json::json; @@ -20,7 +20,7 @@ fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig { cluster: Some("test".into()), clusters: BTreeMap::from([( "test".into(), - Cluster { + SqlCluster { driver, primary: url.into(), replicas: vec![], From 9869a9966c071167fd1ff06ba3104c84008c43ac Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:24:24 +0800 Subject: [PATCH 10/14] Unify backend resources and role bindings in clusters --- README.md | 4 +- crates/clusters/README.md | 36 ++--- crates/clusters/src/catalog.rs | 68 ++-------- crates/clusters/src/error.rs | 35 +++++ crates/clusters/src/format.rs | 95 +++++++++++++- crates/clusters/src/lib.rs | 146 +++++++-------------- crates/clusters/src/object_storage.rs | 4 +- crates/clusters/src/resource.rs | 67 ++++++++++ crates/clusters/src/sql.rs | 10 ++ crates/clusters/tests/deployment_config.rs | 138 ++++++++++++++++--- crates/db/src/connection.rs | 11 +- crates/db/src/lib.rs | 2 +- crates/db/tests/storage.rs | 34 ++--- deploy/README.md | 4 +- deploy/multi-storage.yaml | 15 ++- deploy/render-postgres.py | 5 +- deploy/sqlite.yaml | 9 +- src/main.rs | 13 +- 18 files changed, 469 insertions(+), 227 deletions(-) create mode 100644 crates/clusters/src/error.rs create mode 100644 crates/clusters/src/resource.rs diff --git a/README.md b/README.md index ed26a55..05d2767 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,9 @@ Notion describes sharding online PostgreSQL block data by workspace and feeding Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model. -`clusters` lists SQL connection targets, and `sql` binds roles such as `documents` to those targets. The legacy `cluster` field selects the `documents` role. `object_storage` describes named object stores. The executable logs the configuration version and initializes every configured SQL role at startup. +`resources` lists named backends, each with a `kind` and its own settings. `bindings` maps roles such as `documents` or `attachments` to those resources. The executable logs the configuration version and initializes bound SQL resources at startup. Existing `cluster`, `clusters`, `sql`, `object_storage`, and `sqlite_path` inputs are migrated to this shape when loaded. -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. +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 SQL resource's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. For SQLite, set the resource's `primary` to the file path. Applications use `db::connect` for the documents role or `db::connect_sql` for an explicitly resolved SQL role. 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. diff --git a/crates/clusters/README.md b/crates/clusters/README.md index 1d98bed..48f5a8e 100644 --- a/crates/clusters/README.md +++ b/crates/clusters/README.md @@ -2,29 +2,33 @@ `clusters` 负责读取和校验 Bedrock 的部署配置,并解析出各用途的连接参数。 +`resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。 + ## 模块依赖 -箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。 - -`driver.rs` 集中定义驱动类型,供 SQL 和对象存储配置模块使用。 - -`sql.rs` 定义 `SqlCluster`,描述 SQL 主库和可选读副本。`catalog.rs` 的 `Resource` 统一表示 SQL 和对象存储资源。 +箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。 ```mermaid flowchart LR - lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"] - lib -->|校验对象存储配置| obj["object_storage.rs"] - - sql -->|ConfigError| lib - obj -->|ConfigError| lib - sql -->|SqlDriver| drv["driver.rs"] - obj -->|ObjectStoreDriver| drv - + lib["lib.rs"] -->|解析资源和用途| res["resource.rs"] + lib --> err["error.rs"] cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib - cat -->|统一表示驱动类别| drv - cat -->|编辑 SQL 资源| sql - cat -->|编辑对象存储资源| obj + cat -->|统一校验资源| res + cat --> err + + res -->|SQL 配置和解析| sql["sql.rs"] + res -->|对象存储配置和解析| obj["object_storage.rs"] + res -->|统一驱动类型| drv["driver.rs"] + res --> err + sql -->|SqlDriver| drv + obj -->|ObjectStoreDriver| drv + sql --> err + obj --> err fmt["format.rs"] -->|读取和输出 DeploymentConfig| lib fmt -->|导入时调用 insert_resource| cat + fmt -->|读取资源格式| res + fmt -->|读取旧 SQL 配置| sql + fmt -->|读取旧对象存储配置| obj + fmt --> err ``` diff --git a/crates/clusters/src/catalog.rs b/crates/clusters/src/catalog.rs index 60d9ae4..9528a01 100644 --- a/crates/clusters/src/catalog.rs +++ b/crates/clusters/src/catalog.rs @@ -1,88 +1,48 @@ -use serde::{Deserialize, Serialize}; +//! Named resource lookup and editing. -use crate::{ConfigError, DeploymentConfig, Driver, ObjectStorage, SqlCluster, validate_name}; +use std::mem::discriminant; -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum Resource { - Sql(SqlCluster), - ObjectStore(ObjectStorage), -} - -#[derive(Clone, Copy, Debug)] -pub enum ResourceRef<'a> { - Sql(&'a SqlCluster), - ObjectStore(&'a ObjectStorage), -} - -impl ResourceRef<'_> { - pub fn driver(self) -> Driver { - match self { - Self::Sql(cluster) => Driver::Sql(cluster.driver), - Self::ObjectStore(store) => Driver::ObjectStore(store.driver), - } - } -} +use crate::{ConfigError, DeploymentConfig, Resource, ResourceRef, validate_name}; impl DeploymentConfig { pub fn resource(&self, name: &str) -> Option> { - self.clusters - .get(name) - .map(ResourceRef::Sql) - .or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore)) + self.resources.get(name) } pub fn resources(&self) -> impl Iterator)> { - self.clusters + self.resources .iter() - .map(|(name, value)| (name.as_str(), ResourceRef::Sql(value))) - .chain( - self.object_storage - .iter() - .map(|(name, value)| (name.as_str(), ResourceRef::ObjectStore(value))), - ) + .map(|(name, resource)| (name.as_str(), resource)) } pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> { - if self.resource(&name).is_some() { + if self.resources.contains_key(&name) { return Err(ConfigError::DuplicateResource); } self.store_resource(name, resource) } pub fn update_resource(&mut self, name: &str, resource: Resource) -> Result<(), ConfigError> { - match (self.resource(name), &resource) { - (None, _) => return Err(ConfigError::MissingResource), - (Some(ResourceRef::Sql(_)), Resource::Sql(_)) - | (Some(ResourceRef::ObjectStore(_)), Resource::ObjectStore(_)) => {} - _ => return Err(ConfigError::ResourceCategory), + let previous = self.resource(name).ok_or(ConfigError::MissingResource)?; + if discriminant(previous) != discriminant(&resource) { + return Err(ConfigError::ResourceCategory); } self.store_resource(name.to_owned(), resource) } pub fn remove_resource(&mut self, name: &str) -> Result { - if self.cluster.as_deref() == Some(name) || self.sql.values().any(|target| target == name) { + if self.bindings.values().any(|target| target == name) { return Err(ConfigError::ResourceInUse); } - self.clusters + self.resources .remove(name) - .map(Resource::Sql) - .or_else(|| self.object_storage.remove(name).map(Resource::ObjectStore)) .ok_or(ConfigError::MissingResource) } fn store_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> { validate_name(&name, "resource")?; - match resource { - Resource::Sql(cluster) => { - cluster.resolve(&self.deployment, Some(&name), self.read_only)?; - self.clusters.insert(name, cluster); - } - Resource::ObjectStore(store) => { - store.validate()?; - self.object_storage.insert(name, store); - } - } + resource.resolve(&self.deployment, Some(&name), self.read_only)?; + self.resources.insert(name, resource); Ok(()) } } diff --git a/crates/clusters/src/error.rs b/crates/clusters/src/error.rs new file mode 100644 index 0000000..40ab20f --- /dev/null +++ b/crates/clusters/src/error.rs @@ -0,0 +1,35 @@ +use thiserror::Error; + +#[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("legacy cluster and sql.documents refer to different resources")] + ConflictingDocuments, + #[error("binding {role} references unknown resource {target}")] + UnknownBinding { role: String, target: String }, + #[error("conflicting bindings for role {0}")] + ConflictingBinding(String), + #[error("invalid object storage configuration")] + ObjectStorage, + #[error("resource already exists")] + DuplicateResource, + #[error("resource does not exist")] + MissingResource, + #[error("resource is referenced by a deployment binding")] + ResourceInUse, + #[error("a resource update must preserve its category")] + ResourceCategory, + #[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), +} diff --git a/crates/clusters/src/format.rs b/crates/clusters/src/format.rs index f4adec0..532d158 100644 --- a/crates/clusters/src/format.rs +++ b/crates/clusters/src/format.rs @@ -4,7 +4,9 @@ use serde::Deserialize; use serde::de::DeserializeOwned; use thiserror::Error; -use crate::{ConfigError, DeploymentConfig, Resource}; +use crate::{ + Address, ConfigError, DOCUMENTS, DeploymentConfig, ObjectStorage, Resource, SqlCluster, +}; #[derive(Clone, Copy, Debug)] pub enum ConfigFormat { @@ -52,7 +54,10 @@ impl ConfigFormat { impl DeploymentConfig { pub fn parse(input: &str, format: ConfigFormat) -> Result { - format.parse(input) + format + .parse::(input)? + .try_into() + .map_err(Into::into) } pub fn load(path: impl AsRef) -> Result { @@ -108,6 +113,92 @@ impl DeploymentConfig { } } +// Compatibility for the older, category-specific on-disk layout. Normalize once on load. +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct DeploymentInput { + deployment: Option, + config_version: Option, + resources: BTreeMap, + bindings: BTreeMap, + read_only: bool, + cluster: Option, + clusters: BTreeMap, + sql: BTreeMap, + object_storage: BTreeMap, + sqlite_path: Option
, +} + +impl TryFrom for DeploymentConfig { + type Error = ConfigError; + + fn try_from(input: DeploymentInput) -> Result { + let defaults = Self::default(); + let mut config = Self { + deployment: input.deployment.unwrap_or(defaults.deployment), + config_version: input.config_version.unwrap_or(defaults.config_version), + resources: input.resources, + bindings: input.bindings, + read_only: input.read_only, + }; + let has_canonical_config = !config.resources.is_empty() || !config.bindings.is_empty(); + let has_legacy_sql_targets = !input.clusters.is_empty(); + for (name, resource) in input + .clusters + .into_iter() + .map(|(name, cluster)| (name, Resource::Sql(cluster))) + .chain( + input + .object_storage + .into_iter() + .map(|(name, store)| (name, Resource::ObjectStore(store))), + ) + { + if config.resources.insert(name, resource).is_some() { + return Err(ConfigError::DuplicateResource); + } + } + let mut sql = input.sql; + if let Some(name) = input.cluster { + if sql.get(DOCUMENTS).is_some_and(|target| target != &name) { + return Err(ConfigError::ConflictingDocuments); + } + sql.insert(DOCUMENTS.into(), name); + } + if !has_canonical_config && has_legacy_sql_targets && sql.is_empty() { + return Err(ConfigError::ClusterRequired); + } + for (role, target) in sql { + if !matches!(config.resources.get(&target), Some(Resource::Sql(_))) { + return Err(ConfigError::UnknownCluster); + } + if config + .bindings + .get(&role) + .is_some_and(|existing| existing != &target) + { + return Err(ConfigError::ConflictingBinding(role)); + } + config.bindings.insert(role, target); + } + if !has_canonical_config + && config.bindings.is_empty() + && (input.sqlite_path.is_some() || !config.resources.is_empty()) + { + let mut name = String::from("local"); + while config.resources.contains_key(&name) { + name.push('-'); + } + let local = input + .sqlite_path + .map_or_else(Resource::default_documents, Resource::local_documents); + config.resources.insert(name.clone(), local); + config.bindings.insert(DOCUMENTS.into(), name); + } + Ok(config) + } +} + #[derive(Deserialize)] struct TerraformOutputs { bedrock_resources: Option, diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index f663554..96786cd 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -2,19 +2,21 @@ mod catalog; mod driver; +mod error; mod format; mod object_storage; +mod resource; mod sql; use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use thiserror::Error; -pub use catalog::{Resource, ResourceRef}; pub use driver::*; +pub use error::ConfigError; pub use format::{ConfigFormat, FormatError, ImportFormat}; pub use object_storage::ObjectStorage; +pub use resource::{ResolvedResource, Resource, ResourceRef}; /// Compatibility name for the SQL cluster configuration. pub use sql::SqlCluster as Cluster; pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; @@ -22,19 +24,14 @@ pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; pub const DOCUMENTS: &str = "documents"; #[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(default, deny_unknown_fields)] +#[serde(try_from = "format::DeploymentInput")] pub struct DeploymentConfig { pub deployment: String, pub config_version: String, - /// Legacy shorthand for sql.documents. - pub cluster: Option, - /// Named SQL targets that can be bound to entries in `sql`. - pub clusters: BTreeMap, - /// SQL role to named cluster. - pub sql: BTreeMap, - pub object_storage: BTreeMap, + pub resources: BTreeMap, + /// Role to named resource. + pub bindings: BTreeMap, pub read_only: bool, - pub sqlite_path: Address, } impl Default for DeploymentConfig { @@ -42,12 +39,9 @@ impl Default for DeploymentConfig { Self { deployment: "default".into(), config_version: "local".into(), - cluster: None, - clusters: BTreeMap::new(), - sql: BTreeMap::new(), - object_storage: BTreeMap::new(), + resources: BTreeMap::new(), + bindings: BTreeMap::new(), read_only: false, - sqlite_path: "bedrock.sqlite3".into(), } } } @@ -57,106 +51,62 @@ impl Default for DeploymentConfig { pub struct ResolvedDeployment { pub deployment: String, pub config_version: String, - pub sql: BTreeMap, - pub object_storage: BTreeMap, + resources: BTreeMap, + bindings: BTreeMap, } impl ResolvedDeployment { - pub fn documents(&self) -> Option<&ResolvedSql> { - self.sql.get(DOCUMENTS) + pub fn resource(&self, name: &str) -> Option<&ResolvedResource> { + self.resources.get(name) } -} -#[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("legacy cluster and sql.documents refer to different resources")] - ConflictingDocuments, - #[error("invalid object storage configuration")] - ObjectStorage, - #[error("resource already exists")] - DuplicateResource, - #[error("resource does not exist")] - MissingResource, - #[error("resource is referenced by a SQL binding")] - ResourceInUse, - #[error("a resource update must preserve its category")] - ResourceCategory, - #[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), + pub fn binding(&self, role: &str) -> Option<&ResolvedResource> { + self.resource(self.bindings.get(role)?) + } + + pub fn bound_resources(&self) -> impl Iterator { + self.bindings + .iter() + .map(|(role, target)| (role.as_str(), &self.resources[target])) + } } impl DeploymentConfig { pub fn resolve(&self) -> Result { validate_name(&self.deployment, "deployment")?; validate_name(&self.config_version, "config version")?; - let mut targets = BTreeMap::new(); - for (name, cluster) in &self.clusters { - validate_name(name, "cluster")?; - targets.insert( - name.as_str(), - cluster.resolve(&self.deployment, Some(name), self.read_only)?, + let mut resources = BTreeMap::new(); + let mut bindings = self.bindings.clone(); + for (name, resource) in &self.resources { + validate_name(name, "resource")?; + resources.insert( + name.clone(), + resource.resolve(&self.deployment, Some(name), self.read_only)?, ); } - for (name, store) in &self.object_storage { - validate_name(name, "object store")?; - if self.clusters.contains_key(name) { - return Err(ConfigError::DuplicateResource); - } - store.validate()?; - } - - let mut sql = BTreeMap::new(); - for (role, target) in &self.sql { - validate_name(role, "SQL role")?; - validate_name(target, "cluster")?; - let settings = targets - .get(target.as_str()) - .ok_or(ConfigError::UnknownCluster)?; - sql.insert(role.clone(), settings.clone()); - } - if let Some(name) = &self.cluster { - validate_name(name, "cluster")?; - if self.sql.get(DOCUMENTS).is_some_and(|target| target != name) { - return Err(ConfigError::ConflictingDocuments); - } - let settings = targets - .get(name.as_str()) - .ok_or(ConfigError::UnknownCluster)?; - sql.insert(DOCUMENTS.into(), settings.clone()); - } - if sql.is_empty() { - if !targets.is_empty() { - return Err(ConfigError::ClusterRequired); - } - let local = SqlCluster { - driver: SqlDriver::Sqlite, - primary: self.sqlite_path.clone(), - replicas: vec![], - tls: Tls::Disabled, - max_connections: 1, - }; - sql.insert( - DOCUMENTS.into(), - local.resolve(&self.deployment, None, self.read_only)?, + if resources.is_empty() && bindings.is_empty() { + let default = Resource::default_documents(); + resources.insert( + "local".into(), + default.resolve(&self.deployment, None, self.read_only)?, ); + bindings.insert(DOCUMENTS.into(), "local".into()); + } + for (role, target) in &bindings { + validate_name(role, "role")?; + validate_name(target, "resource")?; + if !resources.contains_key(target) { + return Err(ConfigError::UnknownBinding { + role: role.clone(), + target: target.clone(), + }); + } } Ok(ResolvedDeployment { deployment: self.deployment.clone(), config_version: self.config_version.clone(), - sql, - object_storage: self.object_storage.clone(), + resources, + bindings, }) } } diff --git a/crates/clusters/src/object_storage.rs b/crates/clusters/src/object_storage.rs index 1fc48eb..52d11ca 100644 --- a/crates/clusters/src/object_storage.rs +++ b/crates/clusters/src/object_storage.rs @@ -13,7 +13,7 @@ pub struct ObjectStorage { } impl ObjectStorage { - pub(crate) fn validate(&self) -> Result<(), ConfigError> { + pub(crate) fn resolve(&self) -> Result { if self.bucket.trim().is_empty() || self.region.trim().is_empty() { return Err(ConfigError::ObjectStorage); } @@ -29,6 +29,6 @@ impl ObjectStorage { return Err(ConfigError::ObjectStorage); } } - Ok(()) + Ok(self.clone()) } } diff --git a/crates/clusters/src/resource.rs b/crates/clusters/src/resource.rs new file mode 100644 index 0000000..7ff7d53 --- /dev/null +++ b/crates/clusters/src/resource.rs @@ -0,0 +1,67 @@ +//! Configurations and resolved settings dispatched by resource category. + +use serde::{Deserialize, Serialize}; + +use crate::{Address, ConfigError, Driver, ObjectStorage, ResolvedSql, SqlCluster}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Resource { + Sql(SqlCluster), + ObjectStore(ObjectStorage), +} + +pub type ResourceRef<'a> = &'a Resource; + +impl Resource { + pub fn driver(&self) -> Driver { + match self { + Self::Sql(cluster) => Driver::Sql(cluster.driver), + Self::ObjectStore(store) => Driver::ObjectStore(store.driver), + } + } + + pub(crate) fn default_documents() -> Self { + Self::local_documents("bedrock.sqlite3".into()) + } + + pub(crate) fn local_documents(path: Address) -> Self { + Self::Sql(SqlCluster::local(path)) + } + + pub(crate) fn resolve( + &self, + deployment: &str, + name: Option<&str>, + read_only: bool, + ) -> Result { + match self { + Self::Sql(cluster) => cluster + .resolve(deployment, name, read_only) + .map(ResolvedResource::Sql), + Self::ObjectStore(store) => store.resolve().map(ResolvedResource::ObjectStore), + } + } +} + +#[derive(Clone, Debug)] +pub enum ResolvedResource { + Sql(ResolvedSql), + ObjectStore(ObjectStorage), +} + +impl ResolvedResource { + pub fn as_sql(&self) -> Option<&ResolvedSql> { + match self { + Self::Sql(sql) => Some(sql), + _ => None, + } + } + + pub fn as_object_store(&self) -> Option<&ObjectStorage> { + match self { + Self::ObjectStore(store) => Some(store), + _ => None, + } + } +} diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs index 21e43da..275cecd 100644 --- a/crates/clusters/src/sql.rs +++ b/crates/clusters/src/sql.rs @@ -74,6 +74,16 @@ pub struct ResolvedSql { } impl SqlCluster { + pub(crate) fn local(path: Address) -> Self { + Self { + driver: SqlDriver::Sqlite, + primary: path, + replicas: vec![], + tls: Tls::Disabled, + max_connections: 1, + } + } + pub(crate) fn resolve( &self, deployment: &str, diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 45e56ba..9dc2783 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -1,6 +1,8 @@ use std::collections::BTreeMap; -use clusters::{Address, ConfigError, DeploymentConfig, SqlCluster, SqlDriver, Tls}; +use clusters::{ + Address, ConfigError, DOCUMENTS, DeploymentConfig, Resource, SqlCluster, SqlDriver, Tls, +}; #[test] fn address_debug_formats_the_inner_string() { @@ -11,21 +13,21 @@ fn address_debug_formats_the_inner_string() { #[test] fn named_cluster_requires_matching_addresses() { let mut config = DeploymentConfig { - cluster: Some("regional".into()), - clusters: BTreeMap::from([( + bindings: BTreeMap::from([(DOCUMENTS.into(), "regional".into())]), + resources: BTreeMap::from([( "regional".into(), - SqlCluster { + Resource::Sql(SqlCluster { driver: SqlDriver::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(); - let resolved = resolved.documents().unwrap(); + let resolved = resolved.binding(DOCUMENTS).unwrap().as_sql().unwrap(); assert!( resolved .primary @@ -37,8 +39,10 @@ fn named_cluster_requires_matching_addresses() { .connection_string() .ends_with("sslmode=verify-full") ); - config.clusters.get_mut("regional").unwrap().replicas[0] = - "mysql://user:secret@replica/bedrock".into(); + let Some(Resource::Sql(cluster)) = config.resources.get_mut("regional") else { + panic!("expected a SQL resource"); + }; + cluster.replicas[0] = "mysql://user:secret@replica/bedrock".into(); assert!(matches!( config.resolve(), Err(ConfigError::Url("postgres")) @@ -56,25 +60,57 @@ fn resolves_named_connections_and_round_trips_yaml() { .unwrap(); let snapshot = config.resolve().unwrap(); assert_eq!(snapshot.config_version, "example-1"); - assert_eq!(snapshot.documents().unwrap().driver, SqlDriver::Postgres); - assert_eq!(snapshot.sql["legacy"].driver, SqlDriver::Mysql); assert_eq!( - snapshot.object_storage["attachments"].bucket, + snapshot + .binding(DOCUMENTS) + .unwrap() + .as_sql() + .unwrap() + .driver, + SqlDriver::Postgres + ); + assert_eq!( + snapshot.binding("legacy").unwrap().as_sql().unwrap().driver, + SqlDriver::Mysql + ); + assert_eq!( + snapshot + .binding("attachments") + .unwrap() + .as_object_store() + .unwrap() + .bucket, "bedrock-attachments" ); - assert_eq!(snapshot.documents().unwrap().max_connections, 5); + assert_eq!( + snapshot + .binding(DOCUMENTS) + .unwrap() + .as_sql() + .unwrap() + .max_connections, + 5 + ); let serialized = config.to_yaml().unwrap(); let roundtrip = DeploymentConfig::parse(&serialized, ConfigFormat::Yaml) .unwrap() .resolve() .unwrap(); - assert_eq!(roundtrip.sql["legacy"].driver, SqlDriver::Mysql); + assert_eq!( + roundtrip + .binding("legacy") + .unwrap() + .as_sql() + .unwrap() + .driver, + SqlDriver::Mysql + ); } #[test] fn imports_catalog_atomically_and_preserves_role_references() { - use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver, Resource}; + use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver}; let mut config = DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap(); @@ -84,7 +120,8 @@ fn imports_catalog_atomically_and_preserves_role_references() { ImportFormat::KubernetesConfigMap, ) .unwrap(); - config.sql.insert("documents".into(), "pg-main".into()); + config.bindings.insert(DOCUMENTS.into(), "pg-main".into()); + config.bindings.insert("files".into(), "attachments".into()); let before = config.resource("attachments").unwrap().driver(); assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3)); @@ -107,6 +144,11 @@ fn imports_catalog_atomically_and_preserves_role_references() { .is_err() ); assert!(config.resource("another-bucket").is_none()); + assert!(matches!( + config.remove_resource("attachments"), + Err(ConfigError::ResourceInUse) + )); + config.bindings.remove("files"); let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else { panic!("expected S3 configuration"); }; @@ -119,7 +161,71 @@ fn imports_catalog_atomically_and_preserves_role_references() { .update_resource("attachments", Resource::ObjectStore(updated)) .unwrap(); assert_eq!( - config.resolve().unwrap().object_storage["attachments"].bucket, + config + .resolve() + .unwrap() + .resource("attachments") + .unwrap() + .as_object_store() + .unwrap() + .bucket, "replaced" ); } + +#[test] +fn legacy_configuration_is_normalized_at_load() { + use clusters::ConfigFormat; + + let config = DeploymentConfig::parse( + r#"{ + "cluster":"east", + "clusters":{"east":{"driver":"postgres","primary":"postgres://u@primary/db"}}, + "object_storage":{"files":{"driver":"s3","bucket":"files","region":"us-east-1"}} + }"#, + ConfigFormat::Json, + ) + .unwrap(); + let snapshot = config.resolve().unwrap(); + assert_eq!( + snapshot + .binding(DOCUMENTS) + .unwrap() + .as_sql() + .unwrap() + .driver, + SqlDriver::Postgres + ); + assert_eq!( + snapshot + .resource("files") + .unwrap() + .as_object_store() + .unwrap() + .bucket, + "files" + ); + + let config = + DeploymentConfig::parse("sqlite_path: custom.sqlite3", ConfigFormat::Yaml).unwrap(); + let snapshot = config.resolve().unwrap(); + let connection = snapshot.binding(DOCUMENTS).unwrap().as_sql().unwrap(); + assert!( + connection + .primary + .connection_string() + .ends_with("/custom.sqlite3?mode=rwc") + ); +} + +#[test] +fn missing_binding_target_is_rejected_for_any_role() { + let mut config = DeploymentConfig::default(); + config + .bindings + .insert("attachments".into(), "missing".into()); + assert!( + matches!(config.resolve(), Err(ConfigError::UnknownBinding { role, target }) + if role == "attachments" && target == "missing") + ); +} diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 9d5d974..675676d 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -2,7 +2,9 @@ use std::sync::atomic::{AtomicUsize, Ordering}; -use clusters::{Address, ConfigError, DeploymentConfig, ResolvedSql, SqlDriver as Driver}; +use clusters::{ + Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedSql, SqlDriver as Driver, +}; use thiserror::Error; use crate::{ @@ -18,6 +20,8 @@ pub enum ConnectError { Config(#[from] ConfigError), #[error("the documents SQL role is not configured")] MissingDocuments, + #[error("the documents role must reference a SQL resource")] + InvalidDocuments, #[error(transparent)] Storage(#[from] StorageError), } @@ -102,7 +106,10 @@ pub struct Connection { pub async fn connect(config: &DeploymentConfig) -> Result { let config = config.resolve()?; - connect_sql(config.documents().ok_or(ConnectError::MissingDocuments)?).await + let resource = config + .binding(DOCUMENTS) + .ok_or(ConnectError::MissingDocuments)?; + connect_sql(resource.as_sql().ok_or(ConnectError::InvalidDocuments)?).await } pub async fn connect_sql(config: &ResolvedSql) -> Result { diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 5b95c83..11ea074 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -8,7 +8,7 @@ pub mod sqlite; pub use clusters::SqlDriver as Dialect; pub use clusters::{ - Address, Cluster, ConfigError, DeploymentConfig, SqlCluster, SqlDriver as Driver, Tls, + Address, Cluster, ConfigError, DeploymentConfig, Resource, SqlCluster, SqlDriver as Driver, Tls, }; pub use common::Error as StorageError; pub use common::{Document, Error, Mutation, Result, Revision, Snapshot}; diff --git a/crates/db/tests/storage.rs b/crates/db/tests/storage.rs index f485de0..8c138ae 100644 --- a/crates/db/tests/storage.rs +++ b/crates/db/tests/storage.rs @@ -1,8 +1,8 @@ use std::{collections::BTreeMap, env, time::Duration}; use db::{ - Connection, DeploymentConfig, Driver, Mutation, ReadPreference, SqlCluster, StorageError, Tls, - connect, + Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster, + StorageError, Tls, connect, }; use serde_json::json; @@ -17,16 +17,16 @@ fn change(id: &str, text: &str) -> Mutation { fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig { DeploymentConfig { deployment: deployment.into(), - cluster: Some("test".into()), - clusters: BTreeMap::from([( + bindings: BTreeMap::from([("documents".into(), "test".into())]), + resources: BTreeMap::from([( "test".into(), - SqlCluster { + Resource::Sql(SqlCluster { driver, primary: url.into(), replicas: vec![], tls: Tls::Disabled, max_connections: 4, - }, + }), )]), ..DeploymentConfig::default() } @@ -118,10 +118,7 @@ async fn check_document_contract(db: &Connection) { 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 mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default"); let db = connect(&config).await.unwrap(); assert_eq!(db.driver(), Driver::Sqlite); check_document_contract(&db).await; @@ -140,11 +137,8 @@ async fn sqlite_persists_across_reopening_and_enforces_read_only() { async fn sqlite_read_only_startup_does_not_create_a_database() { let folder = tempfile::tempdir().unwrap(); let filename = folder.path().join("missing.sqlite"); - let config = DeploymentConfig { - read_only: true, - sqlite_path: filename.to_str().unwrap().into(), - ..DeploymentConfig::default() - }; + let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default"); + config.read_only = true; assert!(connect(&config).await.is_err()); assert!(!filename.exists()); } @@ -156,12 +150,10 @@ async fn postgres_reads_replicas_and_falls_back_when_behind() { }; 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 Some(Resource::Sql(cluster)) = config.resources.get_mut("test") else { + panic!("expected a SQL resource"); + }; + cluster.replicas.push(replica_url.clone().into()); let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract")) .await .unwrap(); diff --git a/deploy/README.md b/deploy/README.md index 8da61dc..e8f110d 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -2,10 +2,10 @@ Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. See [local SQLite](sqlite.yaml) and [multiple SQL roles with S3 settings](multi-storage.yaml). The loader also accepts TOML and existing JSON files. -- **SQLite** uses a persistent, writable path for `sqlite_path`. +- **SQLite** uses a persistent, writable path in the SQL resource's `primary` field. - **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. - **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose. -- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration. +- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration under `bindings`. Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances. diff --git a/deploy/multi-storage.yaml b/deploy/multi-storage.yaml index e2b3f15..3432043 100644 --- a/deploy/multi-storage.yaml +++ b/deploy/multi-storage.yaml @@ -1,18 +1,21 @@ # Illustrative service names. Inject deployment credentials before publishing. deployment: production config_version: example-1 -clusters: +resources: pg-main: + kind: sql driver: postgres primary: postgres://bedrock@pg-main:5432/bedrock mysql-legacy: + kind: sql driver: mysql primary: mysql://bedrock@mysql-legacy:3306/legacy -sql: - documents: pg-main - legacy: mysql-legacy -object_storage: - attachments: + attachment-store: + kind: object_store driver: s3 bucket: bedrock-attachments region: us-east-1 +bindings: + documents: pg-main + legacy: mysql-legacy + attachments: attachment-store diff --git a/deploy/render-postgres.py b/deploy/render-postgres.py index 01d8aa4..9944389 100644 --- a/deploy/render-postgres.py +++ b/deploy/render-postgres.py @@ -55,10 +55,11 @@ def main(): config = ( f"deployment: {json.dumps(options.deployment)}\n" f"config_version: {json.dumps(options.config_version)}\n" - "sql:\n" + "bindings:\n" " documents: postgres\n" - "clusters:\n" + "resources:\n" " postgres:\n" + " kind: sql\n" " driver: postgres\n" f" primary: {json.dumps(database_url())}\n" ) diff --git a/deploy/sqlite.yaml b/deploy/sqlite.yaml index b3e7294..9243e79 100644 --- a/deploy/sqlite.yaml +++ b/deploy/sqlite.yaml @@ -1,3 +1,10 @@ deployment: default config_version: local -sqlite_path: bedrock.sqlite3 +resources: + local: + kind: sql + driver: sqlite + primary: bedrock.sqlite3 + max_connections: 1 +bindings: + documents: local diff --git a/src/main.rs b/src/main.rs index 3be0f3e..d8f4cce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::{env, error::Error}; -use clusters::DeploymentConfig; +use clusters::{DOCUMENTS, DeploymentConfig}; use db::connect_sql; #[tokio::main] @@ -10,7 +10,16 @@ async fn main() -> Result<(), Box> { None => DeploymentConfig::default(), }; let resolved = config.resolve()?; - for (role, settings) in &resolved.sql { + if resolved + .binding(DOCUMENTS) + .is_some_and(|resource| resource.as_sql().is_none()) + { + return Err(db::ConnectError::InvalidDocuments.into()); + } + for (role, resource) in resolved.bound_resources() { + let Some(settings) = resource.as_sql() else { + continue; + }; let connection = connect_sql(settings).await?; println!( "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})", From 69513d9ffb333de753f80f59cbdb8497e3e302d5 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:27:11 +0800 Subject: [PATCH 11/14] Group deployment files by deployment method --- .gitea/workflows/deploy.yml | 4 +- README.md | 2 +- crates/clusters/tests/deployment_config.rs | 4 +- deploy/README.md | 14 ++- deploy/bedrock-deployment.svg | 105 ------------------ deploy/{ => gitea}/build-release.sh | 0 deploy/{ => gitea}/release.sh | 0 deploy/{ => gitea}/render-postgres.py | 0 .../{ => kubernetes}/kubernetes-catalog.yaml | 0 deploy/{ => kubernetes}/multi-storage.yaml | 0 deploy/{ => local}/sqlite.yaml | 0 11 files changed, 15 insertions(+), 114 deletions(-) delete mode 100644 deploy/bedrock-deployment.svg rename deploy/{ => gitea}/build-release.sh (100%) rename deploy/{ => gitea}/release.sh (100%) rename deploy/{ => gitea}/render-postgres.py (100%) rename deploy/{ => kubernetes}/kubernetes-catalog.yaml (100%) rename deploy/{ => kubernetes}/multi-storage.yaml (100%) rename deploy/{ => local}/sqlite.yaml (100%) diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 516ff90..7beb37a 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -18,7 +18,7 @@ jobs: with: persist-credentials: false - name: Build the Rust release - run: bash deploy/build-release.sh + run: bash deploy/gitea/build-release.sh - name: Publish and initialize Bedrock storage env: BEDROCK_PG_HOST: ${{ vars.BEDROCK_PG_HOST }} @@ -26,4 +26,4 @@ jobs: 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" + run: bash deploy/gitea/release.sh target/bedrock-release/bedrock "$GITHUB_SHA" diff --git a/README.md b/README.md index 05d2767..16c16bf 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Notion describes sharding online PostgreSQL block data by workspace and feeding ## Database configuration -Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model. +Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/kubernetes/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model. `resources` lists named backends, each with a `kind` and its own settings. `bindings` maps roles such as `documents` or `attachments` to those resources. The executable logs the configuration version and initializes bound SQL resources at startup. Existing `cluster`, `clusters`, `sql`, `object_storage`, and `sqlite_path` inputs are migrated to this shape when loaded. diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 9dc2783..c05b9d3 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -54,7 +54,7 @@ fn resolves_named_connections_and_round_trips_yaml() { use clusters::ConfigFormat; let config = DeploymentConfig::parse( - include_str!("../../../deploy/multi-storage.yaml"), + include_str!("../../../deploy/kubernetes/multi-storage.yaml"), ConfigFormat::Yaml, ) .unwrap(); @@ -116,7 +116,7 @@ fn imports_catalog_atomically_and_preserves_role_references() { DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap(); config .import_resources( - include_str!("../../../deploy/kubernetes-catalog.yaml"), + include_str!("../../../deploy/kubernetes/kubernetes-catalog.yaml"), ImportFormat::KubernetesConfigMap, ) .unwrap(); diff --git a/deploy/README.md b/deploy/README.md index e8f110d..ebb5442 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,10 +1,16 @@ # Deployment configuration -Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. See [local SQLite](sqlite.yaml) and [multiple SQL roles with S3 settings](multi-storage.yaml). The loader also accepts TOML and existing JSON files. +Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. The loader also accepts TOML and existing JSON files. -- **SQLite** uses a persistent, writable path in the SQL resource's `primary` field. -- **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. -- **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose. +| Deployment method | Directory | +|---|---| +| Local SQLite | [local/](local/) | +| Gitea release to the existing host | [gitea/](gitea/) | +| Kubernetes | [kubernetes/](kubernetes/) | + +- **Local SQLite** uses the [SQLite configuration](local/sqlite.yaml). Set a persistent, writable path in the SQL resource's `primary` field. +- **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. +- **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. The [multi-storage example](kubernetes/multi-storage.yaml) shows such addresses in the Bedrock configuration. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes/kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose. - **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration under `bindings`. Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances. diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg deleted file mode 100644 index 67b1a6d..0000000 --- a/deploy/bedrock-deployment.svg +++ /dev/null @@ -1,105 +0,0 @@ - -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.yaml。 - -release.sh 启动临时容器 -挂载二进制和配置,运行 Rust bedrock。 - - -Rust Bedrock 读取配置 -通过 db::connect 选择 postgres。 -配置由 BEDROCK_DB_CONFIG 指定。 - -在已有 PostgreSQL 数据库内初始化 -postgres.rs 提供 SQL,common.rs 在事务里执行。 -创建 Bedrock 表并登记 production 部署。 -进入 Store::initialize() -成功 -失败 - - -保存版本并切换 current - -清理暂存目录,保留上一版 current - -手动运行 - -ci/check-sql.sh -脚本独立于部署工作流。 - -准备隔离环境 -启动临时 PostgreSQL 和 MySQL。 -SQLite 使用临时本地文件。 - -运行三库检查 -执行格式检查、测试、构建, -验证 SQLite 默认启动。 - -退出时清理 -删除测试容器和临时网络。 - \ No newline at end of file diff --git a/deploy/build-release.sh b/deploy/gitea/build-release.sh similarity index 100% rename from deploy/build-release.sh rename to deploy/gitea/build-release.sh diff --git a/deploy/release.sh b/deploy/gitea/release.sh similarity index 100% rename from deploy/release.sh rename to deploy/gitea/release.sh diff --git a/deploy/render-postgres.py b/deploy/gitea/render-postgres.py similarity index 100% rename from deploy/render-postgres.py rename to deploy/gitea/render-postgres.py diff --git a/deploy/kubernetes-catalog.yaml b/deploy/kubernetes/kubernetes-catalog.yaml similarity index 100% rename from deploy/kubernetes-catalog.yaml rename to deploy/kubernetes/kubernetes-catalog.yaml diff --git a/deploy/multi-storage.yaml b/deploy/kubernetes/multi-storage.yaml similarity index 100% rename from deploy/multi-storage.yaml rename to deploy/kubernetes/multi-storage.yaml diff --git a/deploy/sqlite.yaml b/deploy/local/sqlite.yaml similarity index 100% rename from deploy/sqlite.yaml rename to deploy/local/sqlite.yaml From 8707eb87b6b88b6b20ffc401117fa598d4f3159f Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:39:52 +0800 Subject: [PATCH 12/14] Share address and TLS types across backend configurations --- crates/clusters/README.md | 4 ++ crates/clusters/src/lib.rs | 4 +- crates/clusters/src/object_storage.rs | 43 ++++++++++++------- crates/clusters/src/sql.rs | 49 ++++------------------ crates/clusters/src/transport.rs | 43 +++++++++++++++++++ crates/clusters/tests/deployment_config.rs | 32 ++++++++++++++ 6 files changed, 119 insertions(+), 56 deletions(-) create mode 100644 crates/clusters/src/transport.rs diff --git a/crates/clusters/README.md b/crates/clusters/README.md index 48f5a8e..b6a34f6 100644 --- a/crates/clusters/README.md +++ b/crates/clusters/README.md @@ -4,6 +4,8 @@ `resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。 +`transport.rs` 提供共享的 `Address` 和 `Tls`。SQL 通过 `tls` 字段配置 TLS,S3 从 endpoint 的协议得到 TLS 策略。省略 S3 endpoint 时使用默认 HTTPS 地址。 + ## 模块依赖 箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。 @@ -22,6 +24,8 @@ flowchart LR res --> err sql -->|SqlDriver| drv obj -->|ObjectStoreDriver| drv + sql -->|Address 和 Tls| net["transport.rs"] + obj -->|Address 和 Tls| net sql --> err obj --> err diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index 96786cd..c29c6c5 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -7,6 +7,7 @@ mod format; mod object_storage; mod resource; mod sql; +mod transport; use std::collections::BTreeMap; @@ -19,7 +20,8 @@ pub use object_storage::ObjectStorage; pub use resource::{ResolvedResource, Resource, ResourceRef}; /// Compatibility name for the SQL cluster configuration. pub use sql::SqlCluster as Cluster; -pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; +pub use sql::{ResolvedSql, SqlCluster}; +pub use transport::{Address, Tls}; pub const DOCUMENTS: &str = "documents"; diff --git a/crates/clusters/src/object_storage.rs b/crates/clusters/src/object_storage.rs index 52d11ca..6919f6c 100644 --- a/crates/clusters/src/object_storage.rs +++ b/crates/clusters/src/object_storage.rs @@ -1,7 +1,11 @@ use serde::{Deserialize, Serialize}; use url::Url; -use crate::{ConfigError, driver::ObjectStoreDriver}; +use crate::{ + ConfigError, + driver::ObjectStoreDriver, + transport::{Address, Tls}, +}; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] @@ -9,7 +13,7 @@ pub struct ObjectStorage { pub driver: ObjectStoreDriver, pub bucket: String, pub region: String, - pub endpoint: Option, + pub endpoint: Option
, } impl ObjectStorage { @@ -17,18 +21,29 @@ impl ObjectStorage { if self.bucket.trim().is_empty() || self.region.trim().is_empty() { return Err(ConfigError::ObjectStorage); } - if let Some(endpoint) = &self.endpoint { - let url = Url::parse(endpoint).map_err(|_| ConfigError::ObjectStorage)?; - if !matches!(url.scheme(), "http" | "https") - || url.host_str().is_none() - || !url.username().is_empty() - || url.password().is_some() - || url.query().is_some() - || url.fragment().is_some() - { - return Err(ConfigError::ObjectStorage); - } - } + self.tls()?; Ok(self.clone()) } + + /// The TLS policy implied by this endpoint. The default S3 endpoint uses HTTPS. + pub fn tls(&self) -> Result { + let Some(endpoint) = &self.endpoint else { + return Ok(Tls::VerifyFull); + }; + let url = + Url::parse(endpoint.connection_string()).map_err(|_| ConfigError::ObjectStorage)?; + if url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(ConfigError::ObjectStorage); + } + match url.scheme() { + "https" => Ok(Tls::VerifyFull), + "http" => Ok(Tls::Disabled), + _ => Err(ConfigError::ObjectStorage), + } + } } diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs index 275cecd..c3a0d06 100644 --- a/crates/clusters/src/sql.rs +++ b/crates/clusters/src/sql.rs @@ -1,46 +1,13 @@ -use std::{fmt, path::Path}; +use std::path::Path; use serde::{Deserialize, Serialize}; use url::Url; -use crate::{ConfigError, driver::SqlDriver}; - -#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum Tls { - #[default] - VerifyFull, - Disabled, -} - -/// A database address. Debug output includes the full value, which may contain credentials. -#[derive(Clone, Deserialize, Serialize)] -#[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 { - fmt::Debug::fmt(&self.0, formatter) - } -} - -impl Address { - pub fn connection_string(&self) -> &str { - &self.0 - } -} +use crate::{ + ConfigError, + driver::SqlDriver, + transport::{Address, Tls}, +}; /// A SQL target with a primary connection and optional read replicas. #[derive(Clone, Debug, Deserialize, Serialize)] @@ -153,7 +120,7 @@ fn resolve_address( Tls::Disabled => tls_disabled, }; url.query_pairs_mut().append_pair(tls_key, tls_mode); - Ok(Address(url.into())) + Ok(Address::from(String::from(url))) } fn sqlite_url(path: &str, read_only: bool) -> Result { @@ -167,5 +134,5 @@ fn sqlite_url(path: &str, read_only: bool) -> Result { .strip_prefix("file:") .ok_or(ConfigError::SqlitePath)?; let mode = if read_only { "ro" } else { "rwc" }; - Ok(Address(format!("sqlite:{file}?mode={mode}"))) + Ok(Address::from(format!("sqlite:{file}?mode={mode}"))) } diff --git a/crates/clusters/src/transport.rs b/crates/clusters/src/transport.rs new file mode 100644 index 0000000..32067f9 --- /dev/null +++ b/crates/clusters/src/transport.rs @@ -0,0 +1,43 @@ +//! Address and TLS settings shared by backend configurations. + +use std::fmt; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Tls { + #[default] + VerifyFull, + Disabled, +} + +/// A backend connection string, endpoint URL, or local path. +/// Debug output includes the full value, which may contain credentials. +#[derive(Clone, Deserialize, Serialize)] +#[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 { + fmt::Debug::fmt(&self.0, formatter) + } +} + +impl Address { + pub fn connection_string(&self) -> &str { + &self.0 + } +} diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index c05b9d3..a84c053 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -229,3 +229,35 @@ fn missing_binding_target_is_rejected_for_any_role() { if role == "attachments" && target == "missing") ); } + +#[test] +fn s3_uses_shared_address_and_endpoint_tls() { + use clusters::{ConfigFormat, ObjectStorage}; + + let config = DeploymentConfig::parse( + include_str!("../../../deploy/kubernetes/multi-storage.yaml"), + ConfigFormat::Yaml, + ) + .unwrap(); + let Some(Resource::ObjectStore(store)) = config.resource("attachment-store") else { + panic!("expected object storage configuration"); + }; + assert_eq!(store.tls().unwrap(), Tls::VerifyFull); + + for (url, expected) in [ + ("https://objects.example.test", Tls::VerifyFull), + ("http://objects.example.test", Tls::Disabled), + ] { + let store = ObjectStorage { + endpoint: Some(url.into()), + ..store.clone() + }; + assert_eq!(store.endpoint.as_ref().unwrap().connection_string(), url); + assert_eq!(store.tls().unwrap(), expected); + } + let store = ObjectStorage { + endpoint: Some("https://user@objects.example.test".into()), + ..store.clone() + }; + assert!(matches!(store.tls(), Err(ConfigError::ObjectStorage))); +} From 01023404bee835c7a9583fb46267824b5d6c3ea2 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 20:13:51 +0800 Subject: [PATCH 13/14] Show a separate flow for each deployment method --- deploy/README.md | 50 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/deploy/README.md b/deploy/README.md index ebb5442..15b3837 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -8,23 +8,26 @@ Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. The loader also a | Gitea release to the existing host | [gitea/](gitea/) | | Kubernetes | [kubernetes/](kubernetes/) | -- **Local SQLite** uses the [SQLite configuration](local/sqlite.yaml). Set a persistent, writable path in the SQL resource's `primary` field. -- **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. -- **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. The [multi-storage example](kubernetes/multi-storage.yaml) shows such addresses in the Bedrock configuration. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes/kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose. -- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration under `bindings`. +## Local SQLite -Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances. +Bedrock defaults to `bedrock.sqlite3` in the working directory. To choose another path, set `BEDROCK_DB_CONFIG` to a [SQLite configuration](local/sqlite.yaml) and set the resource's `primary` to a persistent, writable path. -S3 entries describe endpoints and buckets. Keep access credentials in the deployment's secret store for the eventual object storage client. +```mermaid +flowchart TD + A["在本机启动 Bedrock"] --> B{"是否设置 BEDROCK_DB_CONFIG"} + B -->|是| C["读取指定的 SQLite 配置,取得文件路径"] + B -->|否| D["使用工作目录下的 bedrock.sqlite3"] + C --> E["打开或创建 SQLite 文件"] + D --> E + E --> F["Bedrock 初始化文档存储"] +``` -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. +## Gitea release to the existing host -## Release on the existing deployment host +PostgreSQL on the existing host uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. 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. -### Automatic deployment - ```mermaid flowchart TD M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] @@ -38,7 +41,32 @@ flowchart TD I -->|失败| F ``` -### Manual SQL checks +## Kubernetes + +The database and Bedrock workload manifests are supplied by the deployment. Use each database's Service DNS name as its address, such as `pg-main:5432` within the same namespace. The [multi-storage example](kubernetes/multi-storage.yaml) shows how to declare resource kinds, drivers and role bindings. Render the final YAML with deployment credentials, store it in a Secret, and mount it into the Bedrock workload at the path set in `BEDROCK_DB_CONFIG`. The optional [catalog ConfigMap](kubernetes/kubernetes-catalog.yaml) packages named resources for the library import API. + +```mermaid +flowchart TD + A["准备 Kubernetes 工作负载和数据库 Service"] --> B["用 Service 名称配置数据库连接地址"] + B --> C["用 multi-storage.yaml 的结构准备 Bedrock 配置和用途绑定"] + D["可选:从 ConfigMap 导入命名资源"] -.-> C + E["部署时提供数据库凭据"] --> C + C --> F["把私有 bedrock.yaml 写入 Kubernetes Secret"] + F --> G["Bedrock Pod 挂载配置,设置 BEDROCK_DB_CONFIG"] + G --> H["Bedrock 通过 Service 地址连接数据库"] +``` + +## Shared deployment settings + +Terraform or cloud inventory can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration under `bindings`. + +Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances. + +S3 entries describe endpoints and buckets. Keep access credentials in the deployment's secret store for the eventual object storage client. + +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. + +## Manual SQL checks ```mermaid flowchart TD From 1775943d79890eab0bb887ba124e14b14e83336e Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 20:16:54 +0800 Subject: [PATCH 14/14] Group release script steps in deployment diagrams --- ci/README.md | 15 +++++++++------ deploy/README.md | 15 +++++++++------ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/ci/README.md b/ci/README.md index b8d7bc1..ed0eac5 100644 --- a/ci/README.md +++ b/ci/README.md @@ -8,13 +8,16 @@ flowchart TD M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] W --> B["build-release.sh 编译发布版"] - B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] - R --> P["render-postgres.py 生成私有 bedrock.yaml"] + B -->|Bedrock 二进制和 Git SHA| R E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P - P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] - I -->|成功| S["保存版本并原子切换 current"] - P -->|失败| F["清理暂存目录,保留现有 current"] - I -->|失败| F + + subgraph release["release.sh"] + R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"] + P -->|配置就绪| I["启动临时容器,由 Bedrock 初始化 PostgreSQL"] + I -->|成功| S["保存版本并原子切换 current"] + P -->|失败| F["清理暂存目录,保留现有 current"] + I -->|失败| F + end ``` ## Manual SQL checks diff --git a/deploy/README.md b/deploy/README.md index 15b3837..b2ca387 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -32,13 +32,16 @@ Gitea builds a release on `ces-control` when a commit lands on `main`. The deplo flowchart TD M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] W --> B["build-release.sh 编译发布版"] - B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"] - R --> P["render-postgres.py 生成私有 bedrock.yaml"] + B -->|Bedrock 二进制和 Git SHA| R E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P - P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"] - I -->|成功| S["保存版本并原子切换 current"] - P -->|失败| F["清理暂存目录,保留现有 current"] - I -->|失败| F + + subgraph release["release.sh"] + R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"] + P -->|配置就绪| I["启动临时容器,由 Bedrock 初始化 PostgreSQL"] + I -->|成功| S["保存版本并原子切换 current"] + P -->|失败| F["清理暂存目录,保留现有 current"] + I -->|失败| F + end ``` ## Kubernetes