linkrs-storage 0.1.0

Storage engine with CSR and memory-mapped containers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Storage Layer Synchronous Wrapper
//!
//! Decorator pattern implementation that wraps any StorageClient to automatically
//! synchronize storage operations with external index systems (fulltext, vector).

use crate::StorageClient;
use linkrs_core::StorageError;
use std::fmt::Debug;
use std::sync::Arc;

/// Decorator that wraps a StorageClient to provide automatic index synchronization.
#[derive(Clone, Debug)]
pub struct SyncWrapper<S: StorageClient + Debug> {
    inner: S,
    sync_manager: Option<Arc<linkrs_sync::SyncManager>>,
    enabled: bool,
    auto_commit_owner: bool,
}

/// One internal index definition snapshotted before a destructive schema op,
/// staged afterwards as a replay-visible `DropIndex` intent.
struct IndexDropSnapshotEntry {
    space_id: u64,
    index_name: String,
    schema_name: String,
    index_type: String,
    fields: Vec<String>,
}

struct IndexDropSnapshot {
    space_id: Option<u64>,
    drops: Vec<IndexDropSnapshotEntry>,
}

impl<S: StorageClient> SyncWrapper<S> {
    /// Create a new wrapper without synchronization.
    pub fn new(storage: S) -> Self {
        Self {
            inner: storage,
            sync_manager: None,
            enabled: false,
            auto_commit_owner: false,
        }
    }

    /// Create a new wrapper with a SyncManager for index synchronization.
    pub fn with_sync_manager(storage: S, sync_manager: Arc<linkrs_sync::SyncManager>) -> Self {
        let frontier_manager = sync_manager.clone();
        storage.set_outbox_materialized_lsn_provider(Arc::new(move || {
            frontier_manager
                .outbox_materialized_lsn()
                .map_err(|error| StorageError::db_error(error.to_string()))
        }));
        Self {
            inner: storage,
            sync_manager: Some(sync_manager),
            enabled: true,
            auto_commit_owner: false,
        }
    }

    /// Check if synchronization is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Get reference to the sync manager.
    pub fn get_sync_manager(&self) -> Option<Arc<linkrs_sync::SyncManager>> {
        self.sync_manager.clone()
    }

    /// Get reference to the inner storage client.
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Get mutable reference to the inner storage client.
    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }
}

impl<S: StorageClient> SyncWrapper<S> {
    /// Get the current transaction ID from storage context.
    fn get_current_txn_id(&self) -> Option<linkrs_core::types::TransactionId> {
        self.inner
            .operation_context()
            .and_then(|ctx| ctx.transaction_id)
    }
    fn commit_transaction_fact(
        &self,
        transaction_id: linkrs_core::types::TransactionId,
    ) -> Result<linkrs_core::types::CommitLsn, StorageError> {
        self.commit_transaction_fact_with_durability(
            transaction_id,
            linkrs_core::types::DurabilityLevel::Sync,
        )
    }

    fn commit_transaction_fact_with_durability(
        &self,
        transaction_id: linkrs_core::types::TransactionId,
        durability: linkrs_core::types::DurabilityLevel,
    ) -> Result<linkrs_core::types::CommitLsn, StorageError> {
        let intents = match self.sync_manager.as_ref() {
            Some(manager) => manager
                .pending_transaction_intents(transaction_id)
                .map_err(|error| {
                    StorageError::db_error(format!(
                        "Failed to build transaction index intents: {}",
                        error
                    ))
                })?,
            None => Vec::new(),
        };
        let commit_lsn = match self.inner.commit_staged_writes_with_durability(
            transaction_id,
            &intents,
            durability,
        ) {
            Ok(commit_lsn) => commit_lsn,
            Err(error) => {
                // A failed durability fence must not leave redo or target
                // intents attached to an auto-commit transaction that the
                // caller is allowed to retry.
                let _ = self.inner.abort_staged_writes(transaction_id);
                if let Some(manager) = self.sync_manager.as_ref() {
                    let _ = manager.rollback_transaction_sync(transaction_id);
                }
                return Err(error);
            }
        };
        Ok(commit_lsn)
    }

    fn finalize_commit_fact(
        &self,
        transaction_id: linkrs_core::types::TransactionId,
        commit_lsn: linkrs_core::types::CommitLsn,
    ) -> Result<(), StorageError> {
        if let Some(manager) = self.sync_manager.as_ref() {
            let intents = manager
                .pending_transaction_intents(transaction_id)
                .map_err(|error| {
                    StorageError::db_error(format!(
                        "Failed to load committed transaction intents: {}",
                        error
                    ))
                })?;
            if let Err(error) =
                manager.materialize_committed_transaction(transaction_id, commit_lsn, &intents)
            {
                log::error!(
                    "Committed transaction {} at {} but outbox materialization is pending recovery: {}",
                    transaction_id,
                    commit_lsn,
                    error
                );
            }
            if let Err(error) = manager.rollback_transaction_sync(transaction_id) {
                log::warn!(
                    "Committed transaction {} at {} but staging cleanup failed: {}",
                    transaction_id,
                    commit_lsn,
                    error
                );
            }
            manager.clear_transaction_intents(transaction_id);
            if let Err(error) = manager.retry_outbox_sync() {
                log::debug!(
                    "Committed transaction {} at {}; target delivery will retry: {}",
                    transaction_id,
                    commit_lsn,
                    error
                );
            }
        }
        Ok(())
    }

    fn commit_auto_transaction(
        &self,
    ) -> Result<Option<linkrs_core::types::CommitLsn>, StorageError> {
        let Some(context) = self.inner.operation_context() else {
            return Ok(None);
        };
        if (!self.auto_commit_owner && !context.auto_commit) || context.read_only {
            return Ok(None);
        }
        let transaction_id = context.transaction_id.ok_or_else(|| {
            StorageError::db_error("Auto-commit write has no transaction ID".to_string())
        })?;
        let commit_lsn = self.commit_transaction_fact(transaction_id)?;
        // Mirror the explicit-transaction sink flow: after the WAL durability
        // fence, materialize the staged intents into the durable outbox and
        // release them. Skipping this step would pin the outbox frontier at
        // its pre-commit value forever, which in turn pins the checkpoint
        // safe-WAL boundary at 0 (WAL never truncated) and leaks the staged
        // intents in `pending_intents`.
        self.finalize_commit_fact(transaction_id, commit_lsn)?;
        Ok(Some(commit_lsn))
    }

    fn abort_transaction_fact(
        &self,
        transaction_id: linkrs_core::types::TransactionId,
    ) -> Result<(), StorageError> {
        self.inner.abort_staged_writes(transaction_id)?;
        if let Some(manager) = self.sync_manager.as_ref() {
            manager
                .rollback_transaction_sync(transaction_id)
                .map_err(|error| {
                    StorageError::db_error(format!(
                        "Failed to discard transaction index intents: {}",
                        error
                    ))
                })?;
        }
        Ok(())
    }

    fn stage_index_create(
        &self,
        index: &linkrs_core::types::Index,
        index_type: &str,
    ) -> Result<(), StorageError> {
        if !self.enabled {
            return Ok(());
        }
        let Some(sync_manager) = self.get_sync_manager() else {
            return Ok(());
        };
        let transaction_id = self.get_current_txn_id().ok_or_else(|| {
            StorageError::db_error(
                "Synchronized schema changes require an operation transaction context".to_string(),
            )
        })?;
        let fields = index
            .fields
            .iter()
            .map(|field| (field.name.clone(), field.value_type.clone()))
            .collect::<Vec<_>>();
        sync_manager
            .on_index_create(
                transaction_id,
                linkrs_sync::manager::IndexCreateRequest {
                    space_id: index.space_id,
                    index_name: index.name.clone(),
                    schema_name: index.schema_name.clone(),
                    index_type: index_type.to_string(),
                    fields,
                    properties: index.properties.clone(),
                },
            )
            .map_err(|error| {
                StorageError::db_error(format!("Failed to stage index creation intent: {error}"))
            })
    }

    fn validate_schema_sync_context(&self) -> Result<(), StorageError> {
        if self.enabled && self.get_sync_manager().is_some() && self.get_current_txn_id().is_none()
        {
            return Err(StorageError::db_error(
                "Synchronized schema changes require an operation transaction context".to_string(),
            ));
        }
        Ok(())
    }

    fn stage_index_drop(
        &self,
        space_id: u64,
        index_name: &str,
        schema_name: &str,
        index_type: &str,
        fields: &[String],
    ) -> Result<(), StorageError> {
        if !self.enabled {
            return Ok(());
        }
        let Some(sync_manager) = self.get_sync_manager() else {
            return Ok(());
        };
        let transaction_id = self.get_current_txn_id().ok_or_else(|| {
            StorageError::db_error(
                "Synchronized schema changes require an operation transaction context".to_string(),
            )
        })?;
        sync_manager
            .on_index_drop(
                transaction_id,
                space_id,
                index_name,
                schema_name,
                index_type,
                fields,
            )
            .map_err(|error| {
                StorageError::db_error(format!("Failed to stage index drop intent: {error}"))
            })
    }

    /// One internal index definition snapshotted before a destructive op.
    fn stage_snapshot_drops(&self, snapshot: &IndexDropSnapshot) -> Result<(), StorageError> {
        for drop in &snapshot.drops {
            self.stage_index_drop(
                drop.space_id,
                &drop.index_name,
                &drop.schema_name,
                &drop.index_type,
                &drop.fields,
            )?;
        }
        Ok(())
    }

    fn stage_space_drop(&self, space_id: u64) -> Result<(), StorageError> {
        if !self.enabled {
            return Ok(());
        }
        let Some(sync_manager) = self.get_sync_manager() else {
            return Ok(());
        };
        let transaction_id = self.get_current_txn_id().ok_or_else(|| {
            StorageError::db_error(
                "Synchronized schema changes require an operation transaction context".to_string(),
            )
        })?;
        sync_manager
            .on_space_drop(transaction_id, space_id)
            .map_err(|error| {
                StorageError::db_error(format!("Failed to stage space drop intent: {error}"))
            })
    }

    fn stage_tag_drop(&self, space_id: u64, tag_name: &str) -> Result<(), StorageError> {
        if !self.enabled {
            return Ok(());
        }
        let Some(sync_manager) = self.get_sync_manager() else {
            return Ok(());
        };
        let transaction_id = self.get_current_txn_id().ok_or_else(|| {
            StorageError::db_error(
                "Synchronized schema changes require an operation transaction context".to_string(),
            )
        })?;
        sync_manager
            .on_tag_drop(transaction_id, space_id, tag_name)
            .map_err(|error| {
                StorageError::db_error(format!("Failed to stage tag drop intent: {error}"))
            })
    }

    /// Shared `drop_space` / `clear_space` path: snapshot index definitions
    /// first (the inner op removes them), then stage one replay-visible
    /// `DropIndex` per index plus a generic `DropSpace` safety net covering
    /// directly created external indexes.
    fn drop_or_clear_space(&mut self, space: &str, is_clear: bool) -> Result<bool, StorageError> {
        let snapshot = self.snapshot_tag_indexes(space, None);
        let space_id = snapshot.space_id;
        self.validate_schema_sync_context()?;
        let result = if is_clear {
            self.inner.clear_space(space)?
        } else {
            self.inner.drop_space(space)?
        };
        if result {
            if let Err(error) = self.stage_snapshot_drops(&snapshot) {
                if let Some(transaction_id) = self.get_current_txn_id() {
                    let _ = self.abort_transaction_fact(transaction_id);
                }
                return Err(error);
            }
            if let Some(sid) = space_id {
                if let Err(error) = self.stage_space_drop(sid) {
                    if let Some(transaction_id) = self.get_current_txn_id() {
                        let _ = self.abort_transaction_fact(transaction_id);
                    }
                    return Err(error);
                }
            }
        }
        self.commit_auto_transaction()?;
        Ok(result)
    }

    /// Snapshot tag+edge index definitions of one space, optionally filtered
    /// to a single schema (tag/edge type). Best effort: unreadable scopes
    /// yield an empty snapshot rather than failing the schema op.
    fn snapshot_tag_indexes(&self, space: &str, schema_filter: Option<&str>) -> IndexDropSnapshot {
        let space_id = self.inner.get_space_id(space).ok();
        let mut drops = Vec::new();
        if let Some(sid) = space_id {
            let mut push_index = |index: &linkrs_core::types::Index, index_type: &str| {
                if schema_filter.is_some_and(|f| f != index.schema_name) {
                    return;
                }
                drops.push(IndexDropSnapshotEntry {
                    space_id: sid,
                    index_name: index.name.clone(),
                    schema_name: index.schema_name.clone(),
                    index_type: index_type.to_string(),
                    fields: index
                        .fields
                        .iter()
                        .map(|field| field.name.clone())
                        .collect(),
                });
            };
            if let Ok(indexes) = self.inner.list_tag_indexes(space) {
                for index in &indexes {
                    push_index(index, "tag");
                }
            }
            if let Ok(indexes) = self.inner.list_edge_indexes(space) {
                for index in &indexes {
                    push_index(index, "edge");
                }
            }
        }
        IndexDropSnapshot { space_id, drops }
    }
}

pub mod admin;
pub mod operation;
pub mod persistence;
pub mod reader;
pub mod schema;
pub mod transaction;
pub mod undo;
mod write;
mod write_edge;
mod write_vertex;

#[cfg(test)]
mod tests;