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 async_stream::stream;
use tokio::fs as tokio_fs;
use tokio_stream::Stream;
use tracing::{debug, trace};
use crate::{streaming::stream_document_ids, Document, Result, SentinelError};
use super::coll::Collection;
#[allow(
clippy::multiple_inherent_impl,
reason = "multiple impl blocks for Collection are intentional for organization"
)]
impl Collection {
/// Lists all document IDs in the collection.
///
/// Returns a stream of document IDs from the collection directory.
/// IDs are streamed as they are discovered, without guaranteed ordering.
/// For sorted results, collect the stream and sort manually.
///
/// # Returns
///
/// Returns a stream of document IDs (filenames without the .json extension),
/// or a `SentinelError` if the operation fails due to filesystem errors.
///
/// # Example
///
/// ```rust
/// use sentinel_dbms::{Store, Collection};
/// use serde_json::json;
/// use futures::TryStreamExt;
///
/// # async fn example() -> sentinel_dbms::Result<()> {
/// let store = Store::new("/path/to/data", None).await?;
/// let collection = store.collection("users").await?;
///
/// // Insert some documents
/// collection.insert("user-123", json!({"name": "Alice"})).await?;
/// collection.insert("user-456", json!({"name": "Bob"})).await?;
///
/// // Stream all document IDs
/// let ids: Vec<_> = collection.list().try_collect().await?;
/// assert_eq!(ids.len(), 2);
/// assert!(ids.contains(&"user-123".to_string()));
/// assert!(ids.contains(&"user-456".to_string()));
/// # Ok(())
/// # }
/// ```
pub fn list(&self) -> std::pin::Pin<Box<dyn Stream<Item = Result<String>> + Send>> {
trace!("Streaming document IDs from collection: {}", self.name());
stream_document_ids(self.path.clone())
}
/// Filters documents in the collection using a predicate function.
///
/// This method performs streaming filtering by loading and checking documents
/// one by one, keeping only matching documents in memory. This approach
/// minimizes memory usage while maintaining good performance for most use cases.
///
/// By default, this method verifies both hash and signature with strict mode.
/// Use `filter_with_verification()` to customize verification behavior.
///
/// # Arguments
///
/// * `predicate` - A function that takes a `&Document` and returns `true` if the document
/// should be included in the results.
///
/// # Returns
///
/// Returns a stream of documents that match the predicate.
///
/// # Example
///
/// ```rust
/// use sentinel_dbms::{Store, Collection};
/// use serde_json::json;
/// use futures::stream::StreamExt;
///
/// # async fn example() -> sentinel_dbms::Result<()> {
/// let store = Store::new("/path/to/data", None).await?;
/// let collection = store.collection("users").await?;
///
/// // Insert some test data
/// collection.insert("user-1", json!({"name": "Alice", "age": 25})).await?;
/// collection.insert("user-2", json!({"name": "Bob", "age": 30})).await?;
///
/// // Filter for users older than 26
/// let mut adults = collection.filter(|doc| {
/// doc.data().get("age")
/// .and_then(|v| v.as_i64())
/// .map_or(false, |age| age > 26)
/// });
///
/// let mut count = 0;
/// while let Some(doc) = adults.next().await {
/// let doc = doc?;
/// assert_eq!(doc.id(), "user-2");
/// count += 1;
/// }
/// assert_eq!(count, 1);
/// # Ok(())
/// # }
/// ```
pub fn filter<F>(&self, predicate: F) -> std::pin::Pin<Box<dyn Stream<Item = Result<Document>> + Send>>
where
F: Fn(&Document) -> bool + Send + Sync + 'static,
{
self.filter_with_verification(predicate, &crate::VerificationOptions::default())
}
/// Filters documents in the collection using a predicate function with custom verification
/// options.
///
/// This method performs streaming filtering by loading and checking documents
/// one by one, keeping only matching documents in memory. This approach
/// minimizes memory usage while maintaining good performance for most use cases.
///
/// # Arguments
///
/// * `predicate` - A function that takes a `&Document` and returns `true` if the document
/// should be included in the results.
/// * `options` - Verification options controlling hash and signature verification.
///
/// # Returns
///
/// Returns a stream of documents that match the predicate.
///
/// # Example
///
/// ```rust
/// use sentinel_dbms::{Store, Collection, VerificationOptions};
/// use serde_json::json;
/// use futures::stream::StreamExt;
///
/// # async fn example() -> sentinel_dbms::Result<()> {
/// let store = Store::new("/path/to/data", None).await?;
/// let collection = store.collection("users").await?;
///
/// // Insert some test data
/// collection.insert("user-1", json!({"name": "Alice", "age": 25})).await?;
/// collection.insert("user-2", json!({"name": "Bob", "age": 30})).await?;
///
/// // Filter with warnings enabled
/// let options = VerificationOptions::warn();
/// let mut adults = collection.filter_with_verification(
/// |doc| {
/// doc.data().get("age")
/// .and_then(|v| v.as_i64())
/// .map_or(false, |age| age > 26)
/// },
/// &options
/// );
///
/// let mut count = 0;
/// while let Some(doc) = adults.next().await {
/// let doc = doc?;
/// assert_eq!(doc.id(), "user-2");
/// count += 1;
/// }
/// assert_eq!(count, 1);
/// # Ok(())
/// # }
/// ```
pub fn filter_with_verification<F>(
&self,
predicate: F,
options: &crate::VerificationOptions,
) -> std::pin::Pin<Box<dyn Stream<Item = Result<Document>> + Send>>
where
F: Fn(&Document) -> bool + Send + Sync + 'static,
{
let collection_path = self.path.clone();
let signing_key = self.signing_key.clone();
let options = *options;
Box::pin(stream! {
trace!(
"Streaming filter on collection (verification enabled: {})",
options.verify_signature || options.verify_hash
);
let mut entries = match tokio_fs::read_dir(&collection_path).await {
Ok(entries) => entries,
Err(e) => {
yield Err(e.into());
return;
}
};
loop {
let entry = match entries.next_entry().await {
Ok(Some(entry)) => entry,
Ok(None) => break,
Err(e) => {
yield Err(e.into());
continue;
}
};
let path = entry.path();
if !tokio_fs::metadata(&path).await.map(|m| m.is_dir()).unwrap_or(false)
&& let Some(file_name) = path.file_name().and_then(|n| n.to_str())
&& file_name.ends_with(".json") && !file_name.starts_with('.') {
let id = file_name.strip_suffix(".json").unwrap();
let file_path = collection_path.join(format!("{}.json", id));
match tokio_fs::read_to_string(&file_path).await {
Ok(content) => {
match serde_json::from_str::<Document>(&content) {
Ok(mut doc) => {
doc.id = id.to_owned();
let collection_ref = Self {
path: collection_path.clone(),
created_at: chrono::Utc::now(),
updated_at: std::sync::RwLock::new(chrono::Utc::now()),
last_checkpoint_at: std::sync::RwLock::new(None),
total_documents: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
total_size_bytes: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
signing_key: signing_key.clone(),
wal_manager: None,
stored_wal_config: sentinel_wal::CollectionWalConfig::default(),
wal_config: sentinel_wal::CollectionWalConfig::default(),
event_sender: None,
event_task: None,
recovery_mode: std::sync::atomic::AtomicBool::new(false),
};
if let Err(e) = collection_ref.verify_document(&doc, &options).await {
if matches!(e, SentinelError::HashVerificationFailed { .. } | SentinelError::SignatureVerificationFailed { .. }) {
if options.hash_verification_mode == crate::VerificationMode::Strict
|| options.signature_verification_mode == crate::VerificationMode::Strict
{
yield Err(e);
continue;
}
} else {
yield Err(e);
continue;
}
}
if predicate(&doc) {
yield Ok(doc);
}
}
Err(e) => yield Err(e.into()),
}
}
Err(e) => yield Err(e.into()),
}
}
}
debug!("Streaming filter completed");
})
}
/// Streams all documents in the collection.
///
/// This method performs streaming by loading documents one by one,
/// minimizing memory usage.
///
/// By default, this method verifies both hash and signature with strict mode.
/// Use `all_with_verification()` to customize verification behavior.
///
/// # Returns
///
/// Returns a stream of all documents in the collection.
///
/// # Example
///
/// ```rust
/// use sentinel_dbms::{Collection, Store};
/// use futures::stream::StreamExt;
///
/// # async fn example() -> sentinel_dbms::Result<()> {
/// let store = Store::new("/path/to/data", None).await?;
/// let collection = store.collection("users").await?;
///
/// // Stream all documents
/// let mut all_docs = collection.all();
/// while let Some(doc) = all_docs.next().await {
/// let doc = doc?;
/// println!("Document: {}", doc.id());
/// }
/// # Ok(())
/// # }
/// ```
pub fn all(&self) -> std::pin::Pin<Box<dyn Stream<Item = Result<Document>> + Send>> {
self.all_with_verification(&crate::VerificationOptions::default())
}
/// Streams all documents in the collection with custom verification options.
///
/// This method performs streaming by loading documents one by one,
/// minimizing memory usage.
///
/// # Arguments
///
/// * `options` - Verification options controlling hash and signature verification.
///
/// # Returns
///
/// Returns a stream of all documents in the collection.
///
/// # Example
///
/// ```rust
/// use sentinel_dbms::{Collection, Store, VerificationOptions};
/// use futures::stream::StreamExt;
///
/// # async fn example() -> sentinel_dbms::Result<()> {
/// let store = Store::new("/path/to/data", None).await?;
/// let collection = store.collection("users").await?;
///
/// // Stream all documents with warnings instead of errors
/// let options = VerificationOptions::warn();
/// let mut all_docs = collection.all_with_verification(&options);
/// while let Some(doc) = all_docs.next().await {
/// let doc = doc?;
/// println!("Document: {}", doc.id());
/// }
/// # Ok(())
/// # }
/// ```
pub fn all_with_verification(
&self,
options: &crate::VerificationOptions,
) -> std::pin::Pin<Box<dyn Stream<Item = Result<Document>> + Send>> {
let collection_path = self.path.clone();
let signing_key = self.signing_key.clone();
let options = *options;
Box::pin(stream! {
trace!(
"Streaming all documents on collection (verification enabled: {})",
options.verify_signature || options.verify_hash
);
let mut entries = match tokio_fs::read_dir(&collection_path).await {
Ok(entries) => entries,
Err(e) => {
yield Err(e.into());
return;
}
};
loop {
let entry = match entries.next_entry().await {
Ok(Some(entry)) => entry,
Ok(None) => break,
Err(e) => {
yield Err(e.into());
continue;
}
};
let path = entry.path();
if !tokio_fs::metadata(&path).await.map(|m| m.is_dir()).unwrap_or(false)
&& let Some(file_name) = path.file_name().and_then(|n| n.to_str())
&& file_name.ends_with(".json") && !file_name.starts_with('.') {
let id = file_name.strip_suffix(".json").unwrap();
let file_path = collection_path.join(format!("{}.json", id));
match tokio_fs::read_to_string(&file_path).await {
Ok(content) => {
match serde_json::from_str::<Document>(&content) {
Ok(mut doc) => {
doc.id = id.to_owned();
let collection_ref = Self {
path: collection_path.clone(),
created_at: chrono::Utc::now(),
updated_at: std::sync::RwLock::new(chrono::Utc::now()),
last_checkpoint_at: std::sync::RwLock::new(None),
total_documents: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
total_size_bytes: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
signing_key: signing_key.clone(),
wal_manager: None,
stored_wal_config: sentinel_wal::CollectionWalConfig::default(),
wal_config: sentinel_wal::CollectionWalConfig::default(),
event_sender: None,
event_task: None,
recovery_mode: std::sync::atomic::AtomicBool::new(false),
};
if let Err(e) = collection_ref.verify_document(&doc, &options).await {
if matches!(e, SentinelError::HashVerificationFailed { .. } | SentinelError::SignatureVerificationFailed { .. }) {
if options.hash_verification_mode == crate::VerificationMode::Strict
|| options.signature_verification_mode == crate::VerificationMode::Strict
{
yield Err(e);
continue;
}
} else {
yield Err(e);
continue;
}
}
yield Ok(doc);
}
Err(e) => yield Err(e.into()),
}
}
Err(e) => yield Err(e.into()),
}
}
}
debug!("Streaming all completed");
})
}
}