Skip to main content

reddb_server/storage/unified/store/
impl_file.rs

1use super::*;
2
3impl UnifiedStore {
4    pub fn new() -> Self {
5        Self::with_config(UnifiedStoreConfig::default())
6    }
7
8    /// Get the current storage format version
9    pub fn format_version(&self) -> u32 {
10        self.format_version.load(Ordering::SeqCst)
11    }
12
13    pub(crate) fn set_format_version(&self, version: u32) {
14        self.format_version.store(version, Ordering::SeqCst);
15    }
16
17    /// Allocate a global entity ID
18    pub fn next_entity_id(&self) -> EntityId {
19        self.resident.next_entity_id()
20    }
21
22    /// Reserve `n` contiguous global entity IDs with one fetch_add.
23    /// Caller assigns `id = EntityId::new(start + i)` per entity.
24    pub fn reserve_entity_ids(&self, n: u64) -> std::ops::Range<u64> {
25        self.resident.reserve_entity_ids(n)
26    }
27
28    pub(crate) fn register_entity_id(&self, id: EntityId) {
29        self.resident.register_entity_id(id)
30    }
31
32    /// Load store from binary file
33    ///
34    /// Binary dump framing is defined by `reddb_file::native_store`.
35    ///
36    /// Store payload shape:
37    /// ```text
38    /// [collection_count: varu32]
39    /// [collections...]
40    /// [cross_ref_count: varu32]
41    /// [cross_refs...]
42    /// ```
43    pub fn load_from_file(path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
44        let file = File::open(path)?;
45        let mut reader = BufReader::new(file);
46        let mut buf = Vec::new();
47        reader.read_to_end(&mut buf)?;
48        Self::load_from_bytes(&buf)
49    }
50
51    pub(crate) fn load_from_bytes(buf: &[u8]) -> Result<Self, Box<dyn std::error::Error>> {
52        Self::load_from_bytes_with_config(buf, UnifiedStoreConfig::default())
53    }
54
55    pub(crate) fn load_from_bytes_with_config(
56        buf: &[u8],
57        config: UnifiedStoreConfig,
58    ) -> Result<Self, Box<dyn std::error::Error>> {
59        let (resident, version) =
60            reddb_engine::storage::resident_store::ResidentStore::from_snapshot(
61                buf,
62                &config.manager_config,
63                config.auto_index_refs,
64                config.max_cross_refs,
65            )?;
66        let mut store = Self::with_config(config);
67        store.resident = resident;
68        store.note_result_cache_snapshot_version(version);
69        // The snapshot envelope has its own version. New logical records
70        // (including WAL and Vault exports) use the current entity schema.
71        store.set_format_version(STORE_VERSION_CURRENT);
72        store.load_result_cache_epoch()?;
73
74        Ok(store)
75    }
76
77    /// Save store to binary file
78    ///
79    /// Uses compact binary encoding with varint for efficient storage.
80    /// No JSON - pure binary with pages and indices.
81    pub fn save_to_file(&self, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
82        let buf = self.to_binary_dump_bytes();
83        reddb_file::write_native_store_bytes_atomically(path, &buf)?;
84        Ok(())
85    }
86
87    pub(crate) fn to_binary_dump_bytes(&self) -> Vec<u8> {
88        let _vault_guard = self.vault_publication_lock.lock();
89        let pending_vault_versions = self.pending_vault_versions.read();
90        let (_, excluded) = self.snapshot_manager.get().map_or_else(
91            || (0, Default::default()),
92            |manager| manager.checkpoint_excluded_state(),
93        );
94        self.resident
95            .snapshot_bytes(&pending_vault_versions, &excluded, || {
96                self.set_format_version(STORE_VERSION_CURRENT);
97            })
98    }
99
100    /// Read entity using the canonical native/browser logical codec.
101    pub(crate) fn read_entity_binary(
102        buf: &[u8],
103        pos: &mut usize,
104        format_version: u32,
105    ) -> Result<UnifiedEntity, Box<dyn std::error::Error>> {
106        Ok(reddb_engine::storage::entity_codec::read_entity_binary(
107            buf,
108            pos,
109            format_version,
110        )?)
111    }
112
113    /// Write entity using the canonical native/browser logical codec.
114    pub(crate) fn write_entity_binary(
115        buf: &mut Vec<u8>,
116        entity: &UnifiedEntity,
117        format_version: u32,
118    ) {
119        reddb_engine::storage::entity_codec::write_entity_binary(buf, entity, format_version);
120    }
121}
122
123#[cfg(test)]
124mod aux_metadata_dump_tests {
125    use super::*;
126    use std::collections::HashMap;
127
128    #[test]
129    fn snapshot_load_preserves_existing_wal_and_restores_future_appends() {
130        let directory = tempfile::tempdir().expect("directory");
131        let path = directory.path().join("snapshot.rdb");
132        let store = UnifiedStore::with_config(UnifiedStoreConfig::default());
133        let old =
134            UnifiedEntity::table_row(EntityId::new(1), "rows", 1, vec![Value::text("snapshot")]);
135        store.insert_auto("rows", old).expect("snapshot row");
136        let snapshot = store.to_binary_dump_bytes();
137        crate::storage::EmbeddedRdbArtifact::create_with_snapshot(&path, &snapshot)
138            .expect("artifact");
139        let newer = UnifiedEntity::table_row(
140            EntityId::new(1),
141            "rows",
142            1,
143            vec![Value::text("durable WAL")],
144        );
145        let action = StoreWalAction::upsert_entity("rows", &newer, None, STORE_VERSION_CURRENT);
146        UnifiedStore::with_config(UnifiedStoreConfig::default().with_embedded_wal_path(&path))
147            .finish_paged_write([action])
148            .expect("durable update after snapshot");
149        let before = std::fs::read(&path).expect("original artifact bytes");
150        let loaded = UnifiedStore::load_from_bytes_with_config(
151            &snapshot,
152            UnifiedStoreConfig::default().with_embedded_wal_path(&path),
153        )
154        .expect("reconstruct snapshot");
155        assert_eq!(std::fs::read(&path).expect("artifact after load"), before);
156        assert_eq!(
157            loaded.config().embedded_wal_path.as_deref(),
158            Some(path.as_path())
159        );
160
161        let generation = crate::storage::EmbeddedRdbArtifact::open(&path)
162            .expect("boundary before future write")
163            .selected_superblock
164            .generation;
165        loaded
166            .insert_auto(
167                "rows",
168                UnifiedEntity::table_row(
169                    EntityId::new(2),
170                    "rows",
171                    2,
172                    vec![Value::text("future write")],
173                ),
174            )
175            .expect("future writes still append WAL");
176        assert_eq!(
177            crate::storage::EmbeddedRdbArtifact::open(&path)
178                .expect("boundary after future write")
179                .selected_superblock
180                .generation,
181            generation + 1
182        );
183    }
184
185    #[test]
186    fn aux_metadata_round_trips_through_binary_dump() {
187        let store = UnifiedStore::with_config(UnifiedStoreConfig::default());
188        store.create_collection("k").expect("create collection");
189        store.set_aux_metadata(b"contract-blob".to_vec());
190
191        let bytes = store.to_binary_dump_bytes();
192        let reloaded = UnifiedStore::load_from_bytes(&bytes).expect("reload dump");
193
194        assert_eq!(reloaded.aux_metadata(), b"contract-blob".to_vec());
195    }
196
197    #[test]
198    fn empty_aux_metadata_round_trips_as_empty() {
199        let store = UnifiedStore::with_config(UnifiedStoreConfig::default());
200        let bytes = store.to_binary_dump_bytes();
201        let reloaded = UnifiedStore::load_from_bytes(&bytes).expect("reload dump");
202
203        assert!(reloaded.aux_metadata().is_empty());
204    }
205
206    #[test]
207    fn legacy_system_collection_snapshot_loads_and_republishes_canonical_name() {
208        let store = UnifiedStore::with_config(UnifiedStoreConfig::default());
209        store
210            .insert_auto(
211                "red_config",
212                UnifiedEntity::table_row(
213                    EntityId::new(1),
214                    "red_config",
215                    1,
216                    vec![Value::text("preserved")],
217                ),
218            )
219            .expect("config row");
220        let mut legacy = store.to_binary_dump_bytes();
221        let canonical = b"red.config";
222        let old = b"red_config";
223        let mut replacements = 0;
224        for offset in 0..=legacy.len() - canonical.len() {
225            if &legacy[offset..offset + canonical.len()] == canonical {
226                legacy[offset..offset + old.len()].copy_from_slice(old);
227                replacements += 1;
228            }
229        }
230        assert!(
231            replacements >= 2,
232            "snapshot carries catalog and entity names"
233        );
234        legacy.truncate(legacy.len() - 4);
235        reddb_file::append_native_store_crc32_footer(&mut legacy);
236
237        let migrated = UnifiedStore::load_from_bytes(&legacy).expect("legacy snapshot");
238        assert_eq!(migrated.list_collections(), vec!["red.config".to_string()]);
239        assert_eq!(
240            migrated
241                .get("red.config", EntityId::new(1))
242                .expect("preserved row")
243                .kind
244                .collection(),
245            "red.config"
246        );
247        let republished = migrated.to_binary_dump_bytes();
248        assert!(
249            republished.windows(old.len()).all(|window| window != old),
250            "new snapshots must not republish legacy identities"
251        );
252        assert!(republished
253            .windows(canonical.len())
254            .any(|window| window == canonical));
255    }
256
257    #[test]
258    fn interned_timeseries_series_reduces_repeated_tag_storage() {
259        let tags = HashMap::from([
260            (
261                "host".to_string(),
262                "srv-very-long-hostname-0001".to_string(),
263            ),
264            ("region".to_string(), "us-east-1".to_string()),
265            ("service".to_string(), "checkout-api".to_string()),
266        ]);
267        let inline_bytes: usize = (0..100)
268            .map(|timestamp_ns| {
269                let entity = UnifiedEntity::new(
270                    EntityId::new(0),
271                    EntityKind::TimeSeriesPoint(Box::new(TimeSeriesPointKind {
272                        series: "cpu_metrics".to_string(),
273                        metric: "cpu.idle".to_string(),
274                    })),
275                    EntityData::TimeSeries(crate::storage::TimeSeriesData {
276                        metric: "cpu.idle".to_string(),
277                        series_id: None,
278                        timestamp_ns,
279                        value: 94.8,
280                        tags: tags.clone(),
281                        fields: HashMap::new(),
282                    }),
283                );
284                UnifiedStore::serialize_entity_record(&entity, None, reddb_file::STORE_VERSION_V10)
285                    .len()
286            })
287            .sum();
288
289        let mut dictionary_fields = HashMap::new();
290        dictionary_fields.insert("collection".to_string(), Value::text("cpu_metrics"));
291        dictionary_fields.insert("series_id".to_string(), Value::UnsignedInteger(0));
292        dictionary_fields.insert("metric".to_string(), Value::text("cpu.idle"));
293        dictionary_fields.insert(
294            "canonical_tags".to_string(),
295            Value::text(
296                r#"{"host":"srv-very-long-hostname-0001","region":"us-east-1","service":"checkout-api"}"#,
297            ),
298        );
299        dictionary_fields.insert(
300            "tags".to_string(),
301            Value::Json(
302                br#"{"host":"srv-very-long-hostname-0001","region":"us-east-1","service":"checkout-api"}"#
303                    .to_vec(),
304            ),
305        );
306        let dictionary = UnifiedEntity::new(
307            EntityId::new(0),
308            EntityKind::TableRow {
309                table: Arc::from("red_timeseries_series"),
310                row_id: 0,
311            },
312            EntityData::Row(RowData {
313                columns: Vec::new(),
314                named: Some(dictionary_fields),
315                schema: None,
316            }),
317        );
318        let dictionary_bytes =
319            UnifiedStore::serialize_entity_record(&dictionary, None, STORE_VERSION_V11).len();
320        let interned_bytes = dictionary_bytes
321            + (0..100)
322                .map(|timestamp_ns| {
323                    let entity = UnifiedEntity::new(
324                        EntityId::new(0),
325                        EntityKind::TimeSeriesPoint(Box::new(TimeSeriesPointKind {
326                            series: "cpu_metrics".to_string(),
327                            metric: "cpu.idle".to_string(),
328                        })),
329                        EntityData::TimeSeries(crate::storage::TimeSeriesData {
330                            metric: "cpu.idle".to_string(),
331                            series_id: Some(0),
332                            timestamp_ns,
333                            value: 94.8,
334                            tags: HashMap::new(),
335                            fields: HashMap::new(),
336                        }),
337                    );
338                    UnifiedStore::serialize_entity_record(&entity, None, STORE_VERSION_V11).len()
339                })
340                .sum::<usize>();
341
342        assert!(
343            interned_bytes < inline_bytes,
344            "interned series storage should shrink repeated tags: inline={inline_bytes}, interned={interned_bytes}"
345        );
346    }
347}