blvm_sdk/module/database.rs
1//! Module database utilities
2//!
3//! Each module has its own database at `{data_dir}/db/`. Use this helper to open it.
4//!
5//! `MODULE_CONFIG_DATABASE_BACKEND` is normally set by the node when spawning a module from
6//! [`module_subprocess_database_backend_preference`](blvm_node::storage::database::module_subprocess_database_backend_preference):
7//! **sled** when the chain uses RocksDB or Redb, **tidesdb** when the chain uses TidesDB, unless
8//! `[modules] module_database_backend` overrides. That value
9//! matches the chain store name; if it is not suitable for dynamic module trees (RocksDB / Redb),
10//! this crate falls back by trying **Sled** then **TidesDB** via
11//! [`create_database`](blvm_node::storage::database::create_database) (same order as
12//! `try_create_module_kv_database` in newer `blvm-node`).
13
14use anyhow::Result;
15use blvm_node::storage::database::{create_database, default_backend, Database, DatabaseBackend};
16use std::path::Path;
17use std::sync::Arc;
18use tracing::warn;
19
20fn parse_backend(s: &str) -> DatabaseBackend {
21 match s.to_lowercase().as_str() {
22 "redb" => DatabaseBackend::Redb,
23 "rocksdb" => DatabaseBackend::RocksDB,
24 "sled" => DatabaseBackend::Sled,
25 "tidesdb" => DatabaseBackend::TidesDB,
26 // "auto" and anything unrecognised: let the caller fall through to the default selection
27 _ => default_backend(),
28 }
29}
30
31/// Returns true for backends that support fully dynamic `open_tree()` without any pre-declaration.
32///
33/// - **Sled**: any tree name is created on demand.
34/// - **TidesDB**: uses `get_or_create_cf`, fully dynamic.
35/// - **Redb**: only works for a hard-coded set of node/module tables (`schema`, `items`, etc.).
36/// Arbitrary tree names return an error — use Sled or TidesDB for general module storage.
37/// - **RocksDB**: column families must be declared at database open time.
38fn supports_dynamic_trees(backend: DatabaseBackend) -> bool {
39 matches!(backend, DatabaseBackend::Sled | DatabaseBackend::TidesDB)
40}
41
42/// Best available backend for module databases (prefers fully-dynamic backends).
43///
44/// Returns Sled as the preferred target; `create_database` will surface an error if the
45/// feature is not compiled into blvm-node, and the caller falls through to TidesDB.
46fn best_module_backend() -> DatabaseBackend {
47 // Prefer Sled: lightweight, embedded, fully dynamic open_tree().
48 // If Sled is not compiled in, create_database will return an error and the caller
49 // falls back to TidesDB. The node default (rocksdb) is intentionally NOT used here.
50 DatabaseBackend::Sled
51}
52
53/// Try Sled then TidesDB for a module-process KV store (dynamic `open_tree` names).
54///
55/// Uses only [`create_database`] so this builds against `blvm-node` releases that predate the
56/// `try_create_module_kv_database` helper.
57fn try_open_dynamic_module_kv(db_path: &Path) -> Result<Arc<dyn Database>> {
58 let sled_err = match create_database(db_path, DatabaseBackend::Sled, None) {
59 Ok(db) => return Ok(Arc::from(db)),
60 Err(e) => e,
61 };
62 match create_database(db_path, DatabaseBackend::TidesDB, None) {
63 Ok(db) => Ok(Arc::from(db)),
64 Err(e) => Err(anyhow::anyhow!(
65 "Failed to open module KV store at {:?}: sled: {}; tidesdb: {}",
66 db_path,
67 sled_err,
68 e
69 )),
70 }
71}
72
73/// Open the module's database at `{data_dir}/db/`.
74///
75/// Module databases need to create named trees on demand (`open_tree()`). Only **Sled** and
76/// **TidesDB** support fully dynamic tree creation. Redb only supports a fixed set of
77/// pre-declared tables; RocksDB requires all column families to be declared at open time.
78///
79/// Backend selection (first match wins):
80/// 1. `MODULE_CONFIG_DATABASE_BACKEND` — set by the node from effective module DB policy (see
81/// `blvm_node::storage::database::module_subprocess_database_backend_preference`)
82/// 2. `MODULE_DATABASE_BACKEND` env var (same values; manual override)
83/// 3. Auto-select Sled as first choice, then fall back through Sled→TidesDB
84/// [`create_database`](blvm_node::storage::database::create_database) attempts
85///
86/// If the resolved backend does not support dynamic trees the function warns and falls back
87/// as above. If no dynamic backend is compiled into `blvm-node`, it returns an error.
88///
89/// # Example
90/// ```ignore
91/// let db = open_module_db(module_data_dir)?;
92/// let tree = db.open_tree("my_tree")?;
93/// tree.insert(b"key", b"value")?;
94/// ```
95pub fn open_module_db<P: AsRef<Path>>(data_dir: P) -> Result<Arc<dyn Database>> {
96 let db_path = data_dir.as_ref().join("db");
97 std::fs::create_dir_all(&db_path)?;
98
99 let explicit = std::env::var("MODULE_CONFIG_DATABASE_BACKEND")
100 .or_else(|_| std::env::var("MODULE_DATABASE_BACKEND"))
101 .ok();
102
103 let backend = explicit
104 .as_deref()
105 .map(parse_backend)
106 .unwrap_or_else(best_module_backend);
107
108 if supports_dynamic_trees(backend) {
109 // Explicitly requested or auto-selected a good module backend.
110 return create_database(&db_path, backend, None).map(Arc::from);
111 }
112
113 // The resolved backend does not support fully-dynamic open_tree().
114 if explicit.is_some() {
115 // User explicitly asked for this backend — warn but still try to fall back so
116 // existing module processes don't hard-fail on start-up.
117 warn!(
118 "MODULE_DATABASE_BACKEND={:?} does not support dynamic open_tree(). \
119 Module databases require Sled or TidesDB. \
120 Set MODULE_CONFIG_DATABASE_BACKEND=sled (or tidesdb) to remove this warning. \
121 Note: Redb only supports pre-declared tables (schema, items); \
122 RocksDB requires all column families at open time.",
123 backend
124 );
125 } else {
126 // Auto-detected a static backend (e.g. rocksdb is the node default).
127 warn!(
128 "Default backend {:?} does not support dynamic open_tree(); \
129 auto-selecting best available module backend (sled or tidesdb). \
130 Set MODULE_CONFIG_DATABASE_BACKEND=sled to suppress this warning.",
131 backend
132 );
133 }
134
135 // Use whichever dynamic KV backends are compiled into blvm-node (Sled / TidesDB).
136 try_open_dynamic_module_kv(&db_path).map_err(|e| {
137 anyhow::anyhow!(
138 "{e} (hint: {:?} is not usable for arbitrary module `open_tree` names; \
139 `blvm-sdk` feature `node` enables `blvm-node/sled`, or build `blvm-node` with `tidesdb`)",
140 backend
141 )
142 })
143}
144
145/// Schema version key (stored in the schema tree).
146const SCHEMA_VERSION_KEY: &[u8] = b"schema_version";
147
148/// Context passed to migration functions. Provides put/get/delete against the module's schema tree
149/// and access to the database for opening other trees.
150///
151/// Migrations run locally in the module process. Use `put`/`get`/`delete` for schema metadata.
152/// For application data migrations, use `open_tree` to open and migrate other trees.
153#[derive(Clone)]
154pub struct MigrationContext {
155 tree: Arc<dyn blvm_node::storage::database::Tree>,
156 db: Arc<dyn Database>,
157}
158
159impl MigrationContext {
160 /// Create a new MigrationContext wrapping the schema tree and database.
161 pub fn new(tree: Arc<dyn blvm_node::storage::database::Tree>, db: Arc<dyn Database>) -> Self {
162 Self { tree, db }
163 }
164
165 /// Insert a key-value pair into the schema tree.
166 pub fn put(&self, key: &[u8], value: &[u8]) -> Result<()> {
167 self.tree.insert(key, value)
168 }
169
170 /// Get a value by key from the schema tree.
171 pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
172 self.tree.get(key)
173 }
174
175 /// Remove a key from the schema tree.
176 pub fn delete(&self, key: &[u8]) -> Result<()> {
177 self.tree.remove(key)
178 }
179
180 /// Open a named tree for application data migrations.
181 pub fn open_tree(&self, name: &str) -> Result<Box<dyn blvm_node::storage::database::Tree>> {
182 self.db.open_tree(name)
183 }
184}
185
186/// A single up migration step.
187pub type MigrationUp = fn(&MigrationContext) -> Result<()>;
188
189/// A single down migration step (for rollback).
190pub type MigrationDown = fn(&MigrationContext) -> Result<()>;
191
192/// Migration pair: (version, up, optional down for rollback).
193pub type Migration = (u32, MigrationUp, Option<MigrationDown>);
194
195/// Run pending up migrations. Opens the "schema" tree, reads current version, runs each migration
196/// with version > current in order, then updates schema_version.
197///
198/// # Example
199/// ```ignore
200/// let db = open_module_db(data_dir)?;
201/// run_migrations(&db, &[(1, up_initial, Some(down_initial)), (2, up_add_cache, None)])?;
202/// ```
203pub fn run_migrations(db: &Arc<dyn Database>, migrations: &[(u32, MigrationUp)]) -> Result<()> {
204 run_migrations_with_down(
205 db,
206 &migrations
207 .iter()
208 .map(|(v, u)| (*v, *u, None))
209 .collect::<Vec<_>>(),
210 )
211}
212
213/// Run pending up migrations. Supports optional down migrations for rollback.
214pub fn run_migrations_with_down(db: &Arc<dyn Database>, migrations: &[Migration]) -> Result<()> {
215 let tree = db.open_tree("schema")?;
216 let tree = Arc::from(tree);
217 let ctx = MigrationContext::new(tree, Arc::clone(db));
218
219 let current: u32 = ctx
220 .get(SCHEMA_VERSION_KEY)?
221 .and_then(|v| String::from_utf8(v).ok())
222 .and_then(|s| s.parse().ok())
223 .unwrap_or(0);
224
225 let mut pending: Vec<_> = migrations
226 .iter()
227 .filter(|(v, _, _)| *v > current)
228 .copied()
229 .collect();
230 pending.sort_by_key(|(v, _, _)| *v);
231
232 for (version, up, _down) in pending {
233 up(&ctx)?;
234 ctx.put(SCHEMA_VERSION_KEY, version.to_string().as_bytes())?;
235 }
236
237 Ok(())
238}
239
240/// Rollback migrations down to `target_version` (exclusive). Runs down migrations in reverse
241/// order for each applied version > target_version. Requires down functions to be provided.
242///
243/// # Example
244/// ```ignore
245/// run_migrations_down(&db, &[(1, up_initial, Some(down_initial)), (2, up_add_cache, Some(down_cache))], 1)?;
246/// // Rolls back from 2 to 1 (runs down_cache only).
247/// ```
248pub fn run_migrations_down(
249 db: &Arc<dyn Database>,
250 migrations: &[Migration],
251 target_version: u32,
252) -> Result<()> {
253 let tree = db.open_tree("schema")?;
254 let tree = Arc::from(tree);
255 let ctx = MigrationContext::new(tree, Arc::clone(db));
256
257 let current: u32 = ctx
258 .get(SCHEMA_VERSION_KEY)?
259 .and_then(|v| String::from_utf8(v).ok())
260 .and_then(|s| s.parse().ok())
261 .unwrap_or(0);
262
263 if current <= target_version {
264 return Ok(());
265 }
266
267 let mut to_rollback: Vec<_> = migrations
268 .iter()
269 .filter(|(v, _, d)| *v > target_version && *v <= current && d.is_some())
270 .copied()
271 .collect();
272 to_rollback.sort_by_key(|(v, _, _)| std::cmp::Reverse(*v));
273
274 for (version, _up, down) in to_rollback {
275 if let Some(down_fn) = down {
276 down_fn(&ctx)?;
277 } else {
278 anyhow::bail!("Migration version {} has no down function", version);
279 }
280 }
281
282 ctx.put(SCHEMA_VERSION_KEY, target_version.to_string().as_bytes())?;
283 Ok(())
284}