transientdb 0.2.5

A lightweight, thread-safe temporary data storage system designed for efficient handling of transient data in Rust applications
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
439
440
441
442
443
444
445
446
447
use crate::{DataResult, DataStore, Equivalent};
use serde_json::json;
use serde_json::Value;
use std::any::Any;
use std::collections::VecDeque;
use std::io::Result;

impl Equivalent for Value {
	fn equals(&self, other: &dyn Equivalent) -> bool {
		if let Some(other_value) = other.as_any().downcast_ref::<Value>() {
			self == other_value
		} else {
			false
		}
	}

	fn as_any(&self) -> &dyn Any {
		self
	}
}

/// Configuration options for the in-memory data store.
///
/// This struct provides the configuration parameters needed to create a new MemoryStore instance.
/// It controls the store's identification, capacity, and fetch size limits.
///
/// # Examples
/// ```
/// use transientdb::{MemoryConfig, MemoryStore};
///
/// let config = MemoryConfig {
///     write_key: "my-store".into(),
///     max_items: 1000,
///     max_fetch_size: 1024 * 1024, // 1MB
/// };
///
/// let store = MemoryStore::new(config);
/// ```
#[derive(Clone)]
pub struct MemoryConfig {
	/// Key used to identify writes to this store.
	/// This is included in the metadata of each batch of data fetched from the store.
	pub write_key: String,
	/// Maximum number of items to store before old items are removed.
	/// Once this limit is reached, adding new items will remove the oldest items to make space.
	pub max_items: usize,
	/// Maximum size in bytes that can be fetched in a single operation.
	/// This prevents memory spikes during fetch operations by limiting the amount of data returned.
	pub max_fetch_size: usize,
}

/// A FIFO data store that keeps items in memory.
///
/// Items are stored until fetched or until max_items is reached, at which point
/// older items are removed to make space for new ones. The store maintains data in a
/// queue structure and supports concurrent access.
///
/// When items are fetched, they are packaged into a JSON batch with metadata including:
/// - A batch array containing the items
/// - A timestamp indicating when the batch was created
/// - The store's write key
pub struct MemoryStore {
	config: MemoryConfig,
	items: VecDeque<Value>,
}

impl MemoryStore {
	/// Creates a new MemoryStore with the specified configuration.
	///
	/// # Panics
	/// * If max_fetch_size is less than 100 bytes
	/// * If max_items is 0
	pub fn new(config: MemoryConfig) -> Self {
		if config.max_fetch_size < 100 {
			panic!("max_fetch_size < 100 bytes? What are you even trying to fetch, empty arrays?");
		}
		if config.max_items == 0 {
			panic!("max_items = 0? So... you want a store that stores nothing? That's what /dev/null is for.");
		}

		Self {
			config,
			items: VecDeque::new(),
		}
	}

	/// Creates a JSON batch object containing the provided items and metadata.
	///
	/// # Arguments
	/// * `items` - Slice of JSON values to include in the batch
	///
	/// # Returns
	/// A JSON value containing:
	/// - A `batch` array of the provided items
	/// - A `sentAt` timestamp in RFC3339 format
	/// - The store's `writeKey`
	fn create_batch(&self, items: &[Value]) -> Value {
		json!({
			"batch": items,
			"sentAt": chrono::Utc::now().to_rfc3339(),
			"writeKey": self.config.write_key
		})
	}

	fn get_item_size(item: &Value) -> usize {
		item.to_string().len()
	}
}

impl DataStore for MemoryStore {
	type Output = Value;

	fn has_data(&self) -> bool {
		!self.items.is_empty()
	}

	fn reset(&mut self) {
		self.items.clear();
	}

	fn append(&mut self, data: Value) -> Result<()> {
		self.items.push_back(data);

		while self.items.len() > self.config.max_items {
			self.items.pop_front();
		}

		Ok(())
	}

	fn fetch(
		&mut self,
		count: Option<usize>,
		max_bytes: Option<usize>,
	) -> Result<Option<DataResult<Self::Output>>> {
		let max_bytes = max_bytes.unwrap_or(self.config.max_fetch_size);
		let mut accumulated_size = 0;
		let mut num_items = 0;

		// Just look at items without draining
		for item in self.items.iter() {
			let item_size = Self::get_item_size(item);
			if accumulated_size + item_size > max_bytes {
				break;
			}
			if let Some(count) = count {
				if num_items >= count {
					break;
				}
			}
			accumulated_size += item_size;
			num_items += 1;
		}

		if num_items == 0 {
			return Ok(None);
		}

		// Create vectors of items and removable references
		let items: Vec<Value> = self.items.iter().take(num_items).cloned().collect();

		let removable: Vec<Box<dyn Equivalent>> = items
			.iter()
			.map(|item| Box::new(item.clone()) as Box<dyn Equivalent>)
			.collect();

		let batch = self.create_batch(&items);

		Ok(Some(DataResult {
			data: Some(batch),
			removable: Some(removable),
		}))
	}

	fn remove(&mut self, data: &[Box<dyn Equivalent>]) -> Result<()> {
		// Remove items that match the provided equivalents
		self.items
			.retain(|item| !data.iter().any(|removable| removable.equals(item)));
		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use crate::memory::{MemoryConfig, MemoryStore};
	use crate::DataStore;
	use serde_json::{json, Value};
	use std::io::Result;

	#[test]
	fn test_basic_operations() -> Result<()> {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 1000,
			max_fetch_size: 1024,
		};

		let mut store = MemoryStore::new(config);

		// Test empty state
		assert!(!store.has_data());

		// Test append
		let event = json!({"event": "test", "value": 123});
		store.append(event.clone())?;
		assert!(store.has_data());

		// Test fetch - data should still be there after fetch
		if let Some(result) = store.fetch(None, None)? {
			let batch: Value = result.data.unwrap();
			let items = batch["batch"].as_array().unwrap();
			assert_eq!(items.len(), 1);
			assert_eq!(items[0]["value"], 123);

			// Verify items are still in store after fetch
			assert!(store.has_data());

			// Now remove the items
			if let Some(removable) = result.removable {
				store.remove(&removable)?;
				// Verify items were removed
				assert!(!store.has_data());
			} else {
				panic!("Expected removable items but got none");
			}
		} else {
			panic!("Expected data but got none");
		}

		Ok(())
	}

	#[test]
	fn test_fifo_behavior() -> Result<()> {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 3, // Small limit to test FIFO
			max_fetch_size: 1024,
		};

		let mut store = MemoryStore::new(config);

		// Add more items than max_items
		for i in 0..5 {
			store.append(json!({"index": i}))?;
		}

		// Should only have last 3 items
		assert!(store.has_data());

		// Verify they're the right items (2,3,4)
		if let Some(result) = store.fetch(None, None)? {
			let batch: Value = result.data.unwrap();
			let items = batch["batch"].as_array().unwrap();
			assert_eq!(items.len(), 3);
			assert_eq!(items[0]["index"], 2);
			assert_eq!(items[1]["index"], 3);
			assert_eq!(items[2]["index"], 4);
		}

		Ok(())
	}

	#[test]
	fn test_fetch_limits() -> Result<()> {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 100,
			max_fetch_size: 1000,
		};

		let mut store = MemoryStore::new(config);

		// Add items with predictable sizes
		for i in 0..10 {
			let padding = "x".repeat(50); // Each item will be roughly ~70 bytes
			store.append(json!({
				"index": i,
				"padding": padding
			}))?;
		}

		// Test count limit
		if let Some(result) = store.fetch(Some(3), None)? {
			let batch: Value = result.data.unwrap();
			let items = batch["batch"].as_array().unwrap();
			assert_eq!(items.len(), 3, "Count limit not respected");
		}

		// Add more items for size limit test
		for i in 0..10 {
			let padding = "x".repeat(50);
			store.append(json!({
				"index": i,
				"padding": padding
			}))?;
		}

		// Test byte limit (200 bytes should get us about 2-3 items)
		if let Some(result) = store.fetch(None, Some(200))? {
			let items = result.data.unwrap();
			let items = items["batch"].as_array().unwrap();
			assert!(items.len() <= 3, "Too many items for byte limit");

			// Each raw item should be under the limit
			let total_raw_size: usize = items
				.iter()
				.map(|item| MemoryStore::get_item_size(item))
				.sum();
			assert!(total_raw_size <= 200, "Raw items exceed byte limit");
		}

		Ok(())
	}

	#[test]
	fn test_reset() -> Result<()> {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 100,
			max_fetch_size: 1000,
		};

		let mut store = MemoryStore::new(config);

		// Add some items
		for i in 0..5 {
			store.append(json!({"index": i}))?;
		}
		// we have 5 items
		assert!(store.has_data());

		// Reset and verify
		store.reset();
		assert!(!store.has_data());

		Ok(())
	}

	#[test]
	fn test_memory_store_max_fetch_size_edge_cases() -> Result<()> {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 100,
			max_fetch_size: 300, // Reasonable size that's easy to stay under/go over
		};

		let mut store = MemoryStore::new(config);

		// Small item ~30-40 bytes
		store.append(json!({"type": "small", "value": "tiny"}))?;

		// Large item ~500 bytes
		store.append(json!({
			"type": "large",
			"value": "x".repeat(400),  // Make it obviously too big
		}))?;

		// First fetch should only get the small item
		if let Some(result) = store.fetch(None, None)? {
			let batch: Value = result.data.unwrap();
			let items = batch["batch"].as_array().unwrap();
			assert_eq!(items.len(), 1, "Should only fetch the small item");
			assert_eq!(items[0]["type"], "small");

			// Remove the fetched item
			if let Some(removable) = result.removable {
				store.remove(&removable)?;
			}
		}

		// Second fetch should get the large item
		if let Some(result) = store.fetch(None, None)? {
			let batch: Value = result.data.unwrap();
			let items = batch["batch"].as_array().unwrap();
			assert_eq!(items.len(), 1, "Should fetch the large item");
			assert_eq!(items[0]["type"], "large");

			// Remove the fetched item
			if let Some(removable) = result.removable {
				store.remove(&removable)?;
			}
		}

		Ok(())
	}

	#[test]
	fn test_memory_store_json_types() -> Result<()> {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 100,
			max_fetch_size: 1024,
		};

		let mut store = MemoryStore::new(config);

		// Test all JSON types
		store.append(json!(null))?;
		store.append(json!(true))?;
		store.append(json!(42))?;
		store.append(json!(42.5))?;
		store.append(json!("string"))?;
		store.append(json!([1, 2, 3]))?;
		store.append(json!({"key": "value"}))?;

		if let Some(result) = store.fetch(None, None)? {
			let batch: Value = result.data.unwrap();
			let items = batch["batch"].as_array().unwrap();
			assert_eq!(
				items.len(),
				7,
				"All JSON types should be stored and retrieved"
			);
		}

		Ok(())
	}

	#[test]
	#[should_panic(
		expected = "max_fetch_size < 100 bytes? What are you even trying to fetch, empty arrays?"
	)]
	fn test_rejects_tiny_max_fetch_size() {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 1000,
			max_fetch_size: 50, // Ridiculously small
		};

		let _store = MemoryStore::new(config);
	}

	#[test]
	#[should_panic(
		expected = "max_items = 0? So... you want a store that stores nothing? That's what /dev/null is for."
	)]
	fn test_rejects_zero_max_items() {
		let config = MemoryConfig {
			write_key: "test-key".to_string(),
			max_items: 0, // Why even bother?
			max_fetch_size: 1024,
		};

		let _store = MemoryStore::new(config);
	}
}