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
use crate::;
use Result;
use async_trait;
use IndexMap;
use Entity;
/// Entity-aware dataset operations built on top of the [`ValueSet`] foundation.
///
/// `DataSet` bridges the gap between raw storage values and typed Rust entities,
/// providing automatic serialization/deserialization while preserving the flexibility
/// of the underlying storage backend.
///
/// # Type Parameters
///
/// - `E`: The entity type that implements [`Entity`] trait, typically your domain models
///
/// # Relationship to ValueSet
///
/// While [`ValueSet`] works with raw storage values (JSON, CBOR, etc.), `DataSet`
/// adds a typed layer that handles conversion between entities and storage format:
///
/// ```text
/// Entity <--serde--> Value <--storage--> Backend
/// ```
///
/// This separation allows the same storage backend to efficiently support both
/// raw value operations and typed entity operations as needed.
///
/// # Implementation Strategy
///
/// Implement the specific capability traits your data source supports:
/// - [`ReadableDataSet`] for read-only sources (CSV files, APIs)
/// - [`InsertableDataSet`] for append-only sources (message queues, logs)
/// - [`WritableDataSet`] for full CRUD sources (databases, caches)
/// - `entityDataSet` for change-tracking scenarios (interactive applications)
///
/// # Example
///
/// ```rust,ignore
/// use vantage_dataset::dataset::{DataSet, ReadableDataSet, WritableDataSet};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Clone)]
/// struct User {
/// name: String,
/// email: String,
/// age: u32,
/// }
///
/// // Your storage implementation
/// struct UserTable;
///
/// impl ValueSet for UserTable {
/// type Id = String;
/// type Value = serde_json::Value;
/// }
///
/// impl DataSet<User> for UserTable {}
///
/// impl ReadableDataSet<User> for UserTable {
/// async fn list(&self) -> Result<IndexMap<String, User>> {
/// // Implementation converts storage values to entities
/// }
/// }
/// ```
/// Read-only access to typed entities with automatic deserialization.
///
/// This trait provides convenient access to entities without requiring knowledge
/// of the underlying storage format. The implementation handles conversion from
/// raw storage values to typed entities automatically.
///
/// # Performance Considerations
///
/// Entity deserialization has overhead compared to raw value access. For
/// performance-critical scenarios, consider using [`crate::ReadableValueSet`] directly
/// and handling deserialization manually or in batches.
///
/// # Example
///
/// ```rust,ignore
/// use vantage_dataset::dataset::ReadableDataSet;
///
/// // Type-safe entity access
/// let all_users: IndexMap<String, User> = users.list().await?;
/// let specific_user: Option<User> = users.get(&user_id).await?;
///
/// // Sample data without loading everything
/// if let Some((id, user)) = users.get_some().await? {
/// println!("Found user: {} with ID {}", user.name, id);
/// }
/// ```
/// Write operations on typed entities with automatic serialization.
///
/// This trait provides convenient write operations that automatically handle
/// entity serialization to the storage format. All operations follow idempotent
/// patterns safe for retry in distributed systems.
///
/// # Serialization Behavior
///
/// Entities are automatically serialized to the storage's `Value` type before
/// persistence. The serialization format depends on your storage backend:
/// - JSON databases use `serde_json` serialization
/// - Binary stores may use CBOR or custom formats
/// - Document databases preserve nested structure
///
/// # Idempotency Guarantees
///
/// All write operations are designed to be safely retryable:
/// - `insert`: No-op if ID already exists
/// - `replace`: Always succeeds, overwrites existing data
/// - `patch`: Atomic update, fails if entity doesn't exist
///
/// # Example
///
/// ```rust,ignore
/// use vantage_dataset::dataset::WritableDataSet;
///
/// let user = User {
/// name: "Alice".to_string(),
/// email: "alice@example.com".to_string(),
/// age: 30,
/// };
///
/// // Idempotent insert
/// users.insert(&"user-123".to_string(), user.clone()).await?;
///
/// // Update specific fields
/// let mut updated_user = user;
/// updated_user.age = 31;
/// users.replace(&"user-123".to_string(), updated_user).await?;
/// ```
/// Append-only operations with automatic ID generation.
///
/// This trait is designed for storage backends that naturally generate unique IDs
/// for new entities, such as message queues, event streams, or auto-incrementing
/// database tables.
///
/// # Idempotency Considerations
///
/// Unlike other dataset operations, `insert_return_id` is **not idempotent** because
/// each call generates a new ID. Use this pattern only when:
/// - Your system can handle duplicate entities (event sourcing)
/// - You have application-level deduplication
/// - The storage naturally handles uniqueness (like message queues)
///
/// For idempotent operations, prefer [`WritableDataSet::insert`] with predetermined IDs.
///
/// # Example
///
/// ```rust,ignore
/// use vantage_dataset::dataset::InsertableDataSet;
///
/// // Message queue scenario - each event gets unique ID
/// let event = UserLoginEvent {
/// user_id: "user-123".to_string(),
/// timestamp: Utc::now(),
/// ip_address: "192.168.1.1".to_string(),
/// };
///
/// let event_id = events.insert_return_id(event).await?;
/// println!("Generated event ID: {}", event_id);
/// ```
/// Change tracking for typed entities with automatic persistence.
///
/// This trait extends readable and writable datasets with a "entity" pattern that
/// tracks entity modifications and enables deferred persistence. entities act as
/// smart wrappers around entities that know how to save themselves back to storage.
///
/// # entity Pattern Benefits
///
/// - **Change tracking**: Only modified fields are serialized and persisted
/// - **Type safety**: Work with native Rust entities, not raw values
/// - **Optimistic locking**: Conflict detection in concurrent scenarios
/// - **Deferred persistence**: Batch multiple changes before saving
/// - **Interactive editing**: Perfect for UI scenarios with undo/redo
///
/// # Example
///
/// ```rust,ignore
/// use vantage_dataset::dataset::entityDataSet;
///
/// // Get entity for interactive editing
/// let mut user_entity = users.get_entity(&user_id).await?.unwrap();
///
/// // Modify through standard field access
/// user_entity.name = "Alice Smith".to_string();
/// user_entity.age = 31;
///
/// // Changes are automatically tracked and persisted
/// user_entity.save().await?;
///
/// // Or work with multiple entities
/// let mut entities = users.list_entities().await?;
/// for mut entity in entities {
/// entity.status = Status::Processed;
/// entity.save().await?; // Each saves independently
/// }
/// ```
// Auto-implement for any type that has both readable and writable traits
// // Auto-implement for any type that has both readable and writable traits
// #[async_trait]
// impl<T> entityValueSet for T
// where
// T: ReadableValueSet + WritableValueSet,
// Self::Value: Send + Sync + Clone,
// {
// async fn get_value_entity(&self, id: &Self::Id) -> Result<entityValue<'_, Self>> {
// let value = self.get_value(id).await?;
// Ok(entityValue::new(id, value, self))
// }
// async fn list_value_entities(&self) -> Result<Vec<entityValue<'_, Self>>> {
// let items = self.list_values().await?;
// Ok(items
// .into_iter()
// .map(|(id, value)| entityValue::new(id, value, self))
// .collect::<Vec<_>>())
// }
// }