|
| 1 | +// SPDX-License-Identifier: BUSL-1.1 |
| 2 | + |
| 3 | +//! Durable tenant-id allocator for the `_system.tenant_id_hwm` table. |
| 4 | +//! |
| 5 | +//! Singleton table — one row keyed `"global"` holding the highest |
| 6 | +//! tenant id ever allocated. The high-water-mark is monotonic: it is |
| 7 | +//! advanced on every tenant write and never lowered by `DROP TENANT`, |
| 8 | +//! so a tenant id is never reused for a different tenant across a drop |
| 9 | +//! or a restart. This is the same durable-counter idiom the global |
| 10 | +//! surrogate identity uses; see [`super::surrogate_hwm`]. |
| 11 | +//! |
| 12 | +//! Auto-allocation derives the next id from the max of this counter |
| 13 | +//! and the ids actually present in `_system.tenants`, so a database |
| 14 | +//! whose tenants predate the counter self-heals on first allocation |
| 15 | +//! instead of colliding with an existing tenant. |
| 16 | +
|
| 17 | +use redb::ReadableTable; |
| 18 | + |
| 19 | +use super::types::{SystemCatalog, TENANTS, catalog_err}; |
| 20 | + |
| 21 | +/// Redb table: singleton `"global"` -> highest allocated tenant id (`u64`). |
| 22 | +pub(super) const TENANT_ID_HWM: redb::TableDefinition<&str, u64> = |
| 23 | + redb::TableDefinition::new("_system.tenant_id_hwm"); |
| 24 | + |
| 25 | +/// Singleton row key. |
| 26 | +pub(super) const HWM_KEY: &str = "global"; |
| 27 | + |
| 28 | +/// Lowest id handed to an auto-allocated tenant. `0` is the system |
| 29 | +/// tenant and `1` is the bootstrap/default tenant; user tenants start |
| 30 | +/// at `2` so neither reserved slot is ever handed out by allocation. |
| 31 | +pub(crate) const FIRST_USER_TENANT_ID: u64 = 2; |
| 32 | + |
| 33 | +impl SystemCatalog { |
| 34 | + /// Atomically allocate the next tenant id. |
| 35 | + /// |
| 36 | + /// Durable and monotonic: the returned id is strictly greater than |
| 37 | + /// every id previously allocated or currently stored, and the |
| 38 | + /// counter is never reused after a `DROP TENANT`. Self-heals on |
| 39 | + /// first use by taking the max of the stored hwm and the highest id |
| 40 | + /// in `_system.tenants`, so tenants created before this counter |
| 41 | + /// existed can never collide with a fresh allocation. |
| 42 | + pub fn allocate_tenant_id(&self) -> crate::Result<u64> { |
| 43 | + let write_txn = self |
| 44 | + .db |
| 45 | + .begin_write() |
| 46 | + .map_err(|e| catalog_err("tenant_id_hwm write txn", e))?; |
| 47 | + let next; |
| 48 | + { |
| 49 | + // Highest id currently materialised in the tenants table. |
| 50 | + let mut max_existing = 0u64; |
| 51 | + { |
| 52 | + let tenants = write_txn |
| 53 | + .open_table(TENANTS) |
| 54 | + .map_err(|e| catalog_err("open tenants", e))?; |
| 55 | + for entry in tenants |
| 56 | + .range::<&str>(..) |
| 57 | + .map_err(|e| catalog_err("range tenants", e))? |
| 58 | + { |
| 59 | + let (key, _) = entry.map_err(|e| catalog_err("read tenant", e))?; |
| 60 | + if let Ok(id) = key.value().parse::<u64>() { |
| 61 | + max_existing = max_existing.max(id); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + let mut hwm = write_txn |
| 66 | + .open_table(TENANT_ID_HWM) |
| 67 | + .map_err(|e| catalog_err("open tenant_id_hwm", e))?; |
| 68 | + let stored = hwm |
| 69 | + .get(HWM_KEY) |
| 70 | + .map_err(|e| catalog_err("get tenant_id_hwm", e))? |
| 71 | + .map(|v| v.value()) |
| 72 | + .unwrap_or(0); |
| 73 | + next = stored.max(max_existing).max(FIRST_USER_TENANT_ID - 1) + 1; |
| 74 | + hwm.insert(HWM_KEY, next) |
| 75 | + .map_err(|e| catalog_err("insert tenant_id_hwm", e))?; |
| 76 | + } |
| 77 | + write_txn |
| 78 | + .commit() |
| 79 | + .map_err(|e| catalog_err("tenant_id_hwm commit", e))?; |
| 80 | + Ok(next) |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +#[cfg(test)] |
| 85 | +mod tests { |
| 86 | + use super::*; |
| 87 | + use crate::control::security::catalog::StoredTenant; |
| 88 | + |
| 89 | + fn open() -> (tempfile::TempDir, SystemCatalog) { |
| 90 | + let dir = tempfile::tempdir().unwrap(); |
| 91 | + let path = dir.path().join("system.redb"); |
| 92 | + let catalog = SystemCatalog::open(&path).unwrap(); |
| 93 | + (dir, catalog) |
| 94 | + } |
| 95 | + |
| 96 | + #[test] |
| 97 | + fn first_allocation_skips_reserved_slots() { |
| 98 | + let (_dir, catalog) = open(); |
| 99 | + assert_eq!(catalog.allocate_tenant_id().unwrap(), FIRST_USER_TENANT_ID); |
| 100 | + } |
| 101 | + |
| 102 | + #[test] |
| 103 | + fn allocations_are_strictly_increasing_and_distinct() { |
| 104 | + let (_dir, catalog) = open(); |
| 105 | + let a = catalog.allocate_tenant_id().unwrap(); |
| 106 | + let b = catalog.allocate_tenant_id().unwrap(); |
| 107 | + let c = catalog.allocate_tenant_id().unwrap(); |
| 108 | + assert!(a < b && b < c, "{a} {b} {c}"); |
| 109 | + } |
| 110 | + |
| 111 | + #[test] |
| 112 | + fn never_reuses_id_after_delete() { |
| 113 | + let (_dir, catalog) = open(); |
| 114 | + let id = catalog.allocate_tenant_id().unwrap(); |
| 115 | + catalog |
| 116 | + .put_tenant(&StoredTenant { |
| 117 | + tenant_id: id, |
| 118 | + name: "t".into(), |
| 119 | + created_at: 0, |
| 120 | + is_active: true, |
| 121 | + }) |
| 122 | + .unwrap(); |
| 123 | + catalog.delete_tenant(id).unwrap(); |
| 124 | + // The dropped id must not be handed out again. |
| 125 | + assert!(catalog.allocate_tenant_id().unwrap() > id); |
| 126 | + } |
| 127 | + |
| 128 | + #[test] |
| 129 | + fn self_heals_against_preexisting_tenants() { |
| 130 | + let (_dir, catalog) = open(); |
| 131 | + // A tenant row written without ever bumping the counter (the |
| 132 | + // pre-fix world): insert directly so the hwm stays at 0, then |
| 133 | + // assert allocation still skips past the existing id. |
| 134 | + let bytes = zerompk::to_msgpack_vec(&StoredTenant { |
| 135 | + tenant_id: 500, |
| 136 | + name: "legacy".into(), |
| 137 | + created_at: 0, |
| 138 | + is_active: true, |
| 139 | + }) |
| 140 | + .unwrap(); |
| 141 | + let txn = catalog.db.begin_write().unwrap(); |
| 142 | + { |
| 143 | + let mut t = txn.open_table(TENANTS).unwrap(); |
| 144 | + t.insert("500", bytes.as_slice()).unwrap(); |
| 145 | + } |
| 146 | + txn.commit().unwrap(); |
| 147 | + assert!(catalog.allocate_tenant_id().unwrap() > 500); |
| 148 | + } |
| 149 | + |
| 150 | + #[test] |
| 151 | + fn put_tenant_with_explicit_id_advances_hwm() { |
| 152 | + let (_dir, catalog) = open(); |
| 153 | + // An explicitly-chosen high id must push the hwm forward so a |
| 154 | + // later auto-allocation never collides with it. |
| 155 | + catalog |
| 156 | + .put_tenant(&StoredTenant { |
| 157 | + tenant_id: 10, |
| 158 | + name: "explicit".into(), |
| 159 | + created_at: 0, |
| 160 | + is_active: true, |
| 161 | + }) |
| 162 | + .unwrap(); |
| 163 | + assert_eq!(catalog.allocate_tenant_id().unwrap(), 11); |
| 164 | + } |
| 165 | +} |
0 commit comments