From 9f3848199d6018b2d59aac6f773337c0e08ece9c Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 07:02:20 +0800 Subject: [PATCH] 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 {