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
use std::sync::Arc;
use tokio::fs as tokio_fs;
use tracing::{debug, error, trace};
use sentinel_wal::WalManager;
use crate::{
events::StoreEvent,
Collection,
CollectionMetadata,
Result,
COLLECTION_METADATA_FILE,
DATA_DIR,
WAL_DIR,
WAL_FILE,
};
use super::{stor::Store, validation::validate_collection_name};
/// Retrieves or creates a collection with the specified name and custom WAL configuration
/// overrides.
///
/// This is an internal function used by the Store impl. Use Store::collection_with_config instead.
pub async fn collection_with_config(
store: &Store,
name: &str,
wal_overrides: Option<sentinel_wal::CollectionWalConfigOverrides>,
) -> Result<Collection> {
trace!("Accessing collection: {} with custom WAL config", name);
validate_collection_name(name)?;
let path = store.root_path.join(DATA_DIR).join(name);
tokio_fs::create_dir_all(&path).await.map_err(|e| {
error!("Failed to create collection directory {:?}: {}", path, e);
e
})?;
debug!("Collection directory ensured: {:?}", path);
// Load or create collection metadata
let metadata_path = path.join(COLLECTION_METADATA_FILE);
let is_new_collection = !tokio_fs::try_exists(&metadata_path).await.unwrap_or(false);
let metadata = if is_new_collection {
debug!("Creating new collection metadata for {}", name);
let mut metadata = CollectionMetadata::new(name.to_owned());
// For new collections, if overrides are provided, create a config with overrides applied to
// defaults
if let Some(overrides) = wal_overrides.as_ref() {
let base_config = store
.wal_config
.collection_configs
.get(name)
.cloned()
.unwrap_or_else(|| store.wal_config.default_collection_config.clone());
let merged_config = base_config.apply_overrides(overrides);
metadata.wal_config = Some(merged_config);
}
let content = serde_json::to_string_pretty(&metadata)?;
tokio_fs::write(&metadata_path, content).await?;
metadata
}
else {
debug!("Loading existing collection metadata for {}", name);
let content = tokio_fs::read_to_string(&metadata_path).await?;
let mut metadata: CollectionMetadata = serde_json::from_str(&content)?;
// For existing collections, conditionally update metadata if persist_overrides is true
if let Some(overrides) = wal_overrides.as_ref() &&
overrides.persist_overrides
{
let base_config = metadata.wal_config.unwrap_or_else(|| {
store
.wal_config
.collection_configs
.get(name)
.cloned()
.unwrap_or_else(|| store.wal_config.default_collection_config.clone())
});
let merged_config = base_config.apply_overrides(overrides);
metadata.wal_config = Some(merged_config);
let content = serde_json::to_string_pretty(&metadata)?;
tokio_fs::write(&metadata_path, content).await?;
}
metadata
};
// If this is a new collection, emit event (metadata will be saved by event handler)
if is_new_collection {
// Emit collection created event
let event = StoreEvent::CollectionCreated {
name: name.to_owned(),
};
let _ = store.event_sender.send(event).ok();
}
// Get collection WAL config: use metadata's config, or provided config, or fall back to
// store-derived
let stored_wal_config = metadata.wal_config.clone().unwrap_or_else(|| {
store
.wal_config
.collection_configs
.get(name)
.cloned()
.unwrap_or_else(|| store.wal_config.default_collection_config.clone())
});
let mut collection_wal_config = stored_wal_config.clone();
// Apply overrides if provided
if let Some(overrides) = wal_overrides {
collection_wal_config = collection_wal_config.apply_overrides(&overrides);
}
// Create WAL manager with collection config
let wal_path = path.join(WAL_DIR).join(WAL_FILE);
let wal_manager = Some(Arc::new(
WalManager::new(wal_path, collection_wal_config.clone().into()).await?,
));
trace!("Collection '{}' accessed successfully", name);
let now = chrono::Utc::now();
// Update store metadata
*store.last_accessed_at.write().unwrap() = now;
let mut collection = Collection {
path,
signing_key: store.signing_key.clone(),
wal_manager,
wal_config: collection_wal_config,
stored_wal_config,
created_at: now,
updated_at: std::sync::RwLock::new(now),
last_checkpoint_at: std::sync::RwLock::new(None),
total_documents: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(metadata.document_count)),
total_size_bytes: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(metadata.total_size_bytes)),
event_sender: Some(store.event_sender.clone()),
event_task: None,
recovery_mode: std::sync::atomic::AtomicBool::new(false),
};
collection.start_event_processor();
Ok(collection)
}
#[allow(
clippy::multiple_inherent_impl,
reason = "multiple impl blocks for Store are intentional for organization"
)]
impl Store {
/// Retrieves or creates a collection with the specified name.
///
/// This method provides access to a named collection within the store. If the
/// collection directory doesn't exist, it will be created automatically under
/// the `data/` subdirectory of the store's root path.
///
/// # Parameters
///
/// * `name` - The name of the collection. This will be used as the directory name under
/// `data/`. The name should be filesystem-safe (avoid special characters that are invalid in
/// directory names on your target platform).
///
/// # Returns
///
/// * `Result<Collection>` - Returns a `Collection` instance on success, or a `SentinelError`
/// if:
/// - The collection directory cannot be created due to permission issues
/// - The name contains invalid characters for the filesystem
/// - I/O errors occur during directory creation
///
/// # Examples
///
/// ```no_run
/// use sentinel_dbms::Store;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let store = Store::new("/var/lib/sentinel", None).await?;
///
/// // Access a users collection
/// let users = store.collection("users").await?;
///
/// // Insert a document into the collection
/// users.insert("user-123", json!({
/// "name": "Alice",
/// "email": "alice@example.com"
/// })).await?;
///
/// // Access multiple collections
/// let audit_logs = store.collection("audit_logs").await?;
/// let certificates = store.collection("certificates").await?;
/// # Ok(())
/// # }
/// ```
///
/// # Collection Naming
///
/// Collection names should follow these guidelines:
/// - Use lowercase letters, numbers, underscores, and hyphens
/// - Avoid spaces and special characters
/// - Keep names descriptive but concise (e.g., `users`, `audit_logs`, `api_keys`)
///
/// # Notes
///
/// - Calling this method multiple times with the same name returns separate `Collection`
/// instances pointing to the same directory
/// - The `data/` subdirectory is created automatically on first collection access
/// - Collections are not cached; each call creates a new `Collection` instance
/// - No validation is performed on the collection name beyond filesystem constraints
#[deprecated(
since = "2.0.2",
note = "Please use collection_with_config to specify WAL configuration"
)]
pub async fn collection(&self, name: &str) -> Result<Collection> { collection_with_config(self, name, None).await }
/// Retrieves or creates a collection with the specified name and custom WAL configuration
/// overrides.
///
/// This method provides access to a named collection within the store with custom WAL settings
/// that override the stored or default configuration. If the collection directory doesn't
/// exist, it will be created automatically under the `data/` subdirectory of the store's
/// root path.
///
/// # Parameters
///
/// * `name` - The name of the collection. This will be used as the directory name under
/// `data/`. The name should be filesystem-safe.
/// * `wal_overrides` - Optional WAL configuration overrides for this collection
///
/// # Returns
///
/// * `Result<Collection>` - Returns a `Collection` instance on success, or a `SentinelError`
/// if:
/// - The collection directory cannot be created due to permission issues
/// - The name contains invalid characters for the filesystem
/// - I/O errors occur during directory creation
///
/// # Examples
///
/// ```no_run
/// use sentinel_dbms::Store;
/// use sentinel_wal::CollectionWalConfigOverrides;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let store = Store::new("/var/lib/sentinel", None).await?;
/// let wal_overrides = CollectionWalConfigOverrides {
/// write_mode: Some(sentinel_wal::WalFailureMode::Warn),
/// ..Default::default()
/// };
///
/// // Access a users collection with WAL overrides
/// let users = store.collection_with_config("users", Some(wal_overrides)).await?;
///
/// // Insert a document into the collection
/// users.insert("user-123", json!({
/// "name": "Alice",
/// "email": "alice@example.com"
/// })).await?;
/// # Ok(())
/// # }
/// ```
pub async fn collection_with_config(
&self,
name: &str,
wal_overrides: Option<sentinel_wal::CollectionWalConfigOverrides>,
) -> Result<Collection> {
collection_with_config(self, name, wal_overrides).await
}
/// Deletes a collection and all its documents.
///
/// This method removes the entire collection directory and all documents within it.
/// The operation is permanent and cannot be undone. If the collection doesn't exist,
/// the operation succeeds silently (idempotent).
///
/// # Arguments
///
/// * `name` - The name of the collection to delete
///
/// # Returns
///
/// Returns `Ok(())` on success, or a `SentinelError` if the operation fails.
///
/// # Examples
///
/// ```rust
/// use sentinel_dbms::Store;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let store = Store::new("/path/to/data", None).await?;
///
/// // Create a collection
/// let collection = store.collection("temp_collection").await?;
///
/// // ... use collection ...
///
/// // Delete the collection
/// store.delete_collection("temp_collection").await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_collection(&self, name: &str) -> Result<()> {
trace!("Deleting collection: {}", name);
validate_collection_name(name)?;
let path = self.root_path.join("data").join(name);
// Check if collection exists
if !path.exists() {
debug!("Collection '{}' does not exist, nothing to delete", name);
return Ok(());
}
// Load collection metadata to get document count and size before deletion
let metadata_path = path.join(COLLECTION_METADATA_FILE);
let collection_metadata = if tokio_fs::try_exists(&metadata_path).await.unwrap_or(false) {
let content = tokio_fs::read_to_string(&metadata_path).await?;
Some(serde_json::from_str::<CollectionMetadata>(&content)?)
}
else {
None
};
// Remove the entire directory
tokio_fs::remove_dir_all(&path).await.map_err(|e| {
error!("Failed to delete collection directory {:?}: {}", path, e);
e
})?;
debug!("Collection '{}' deleted successfully", name);
// Update store metadata
*self.last_accessed_at.write().unwrap() = chrono::Utc::now();
if let Some(metadata) = collection_metadata {
// Emit collection deleted event (metadata will be saved by event handler)
let event = StoreEvent::CollectionDeleted {
name: name.to_owned(),
document_count: metadata.document_count,
total_size_bytes: metadata.total_size_bytes,
};
drop(self.event_sender.send(event));
}
Ok(())
}
/// This method returns a list of all collection names that exist in the store.
/// The names are returned in no particular order.
///
/// # Returns
///
/// Returns a `Vec<String>` containing the names of all collections.
///
/// # Examples
///
/// ```rust
/// use sentinel_dbms::Store;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let store = Store::new("/path/to/data", None).await?;
///
/// // Create some collections
/// store.collection("users").await?;
/// store.collection("products").await?;
///
/// // List all collections
/// let collections = store.list_collections().await?;
/// assert!(collections.contains(&"users".to_string()));
/// assert!(collections.contains(&"products".to_string()));
/// # Ok(())
/// # }
/// ```
pub async fn list_collections(&self) -> Result<Vec<String>> {
trace!("Listing collections");
let data_path = self.root_path.join("data");
// Ensure data directory exists
tokio_fs::create_dir_all(&data_path).await.map_err(|e| {
error!("Failed to create data directory {:?}: {}", data_path, e);
e
})?;
// Read directory entries
let mut entries = tokio_fs::read_dir(&data_path).await.map_err(|e| {
error!("Failed to read data directory {:?}: {}", data_path, e);
e
})?;
let mut collections = Vec::new();
while let Some(entry) = entries.next_entry().await.map_err(|e| {
error!("Failed to read directory entry: {}", e);
e
})? {
if entry
.file_type()
.await
.map_err(|e| {
error!("Failed to get file type for entry: {}", e);
e
})?
.is_dir() &&
let Some(name) = entry.file_name().to_str()
{
collections.push(name.to_owned());
}
}
debug!("Found {} collections", collections.len());
Ok(collections)
}
pub fn set_signing_key(&mut self, key: sentinel_crypto::SigningKey) { self.signing_key = Some(Arc::new(key)); }
}