-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrent_progress.txt
More file actions
1892 lines (1815 loc) · 99.4 KB
/
current_progress.txt
File metadata and controls
1892 lines (1815 loc) · 99.4 KB
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
▐▛███▜▌ Claude Code v2.1.86
▝▜█████▛▘ Sonnet 4.6 · Claude Pro
▘▘ ▝▝ ~/Boxxed/@dev/ewe_platform
✻ Conversation compacted (ctrl+o for history)
⎿ Referenced file .agents/skills/rust-valtron-usage/skill.md
⎿ Read backends/foundation_core/tests/sync_boundary_helpers.rs (356 lines)
⎿ Referenced file backends/foundation_core/src/valtron/executors/unified.rs
⎿ Read
specifications/07-foundation-ai/features/00a-foundation-db/LEARNINGS.md
(179 lines)
⎿ Read specifications/07-foundation-ai/LEARNINGS.md (318 lines)
Read 3 files (ctrl+o to expand)
● Now let me read the turso and libsql backends, the json_file backend, and the
callers.
Read 4 files (ctrl+o to expand)
● Good — crypto/zeroize.rs doesn't call storage methods, it's just a utility
type. Let me check for actual callers of the storage traits.
Searched for 1 pattern, read 3 files (ctrl+o to expand)
● Let me check if BlobStore is implemented anywhere.
Searched for 1 pattern, read 1 file (ctrl+o to expand)
● Good. BlobStore has no implementations — I'll update its trait signatures but
don't need to implement them. Now let me check what Valtron exports are
available.
Searched for 3 patterns, read 1 file (ctrl+o to expand)
● Let me check the execute function signature to understand what it returns.
Searched for 3 patterns (ctrl+o to expand)
● Good. DrivenStreamIterator<T> implements Iterator<Item = Stream<T::Ready,
T::Pending>>. For FutureTask<F> where F: Future<Output = Result<T, E>>,
T::Ready = Result<T, E> and T::Pending = FuturePollState.
So the stream yields Stream<Result<T, E>, FuturePollState>. Now let me also
check if DrivenStreamIterator is Send.
Searched for 3 patterns (ctrl+o to expand)
● Now I have full context. Let me implement the refactor systematically.
Starting with the helper function and trait changes.
Searched for 1 pattern (ctrl+o to expand)
● Good. Now let me implement all the changes. I'll start with async_utils.rs
(add schedule_future), then the trait signatures, then each backend, then
callers.
● Update(backends/foundation_db/src/backends/async_utils.rs)
⎿ Added 55 lines, removed 9 lines
1 //! Shared async utilities for SQL backends (Turso, libsql).
2 //!
3 -//! Provides a common pattern for wrapping async futures using
-Valtron's
4 -//! `from_future` + `execute` pattern.
3 +//! Provides two patterns for wrapping async futures using Valt
+ron's
4 +//! `from_future` + `execute` pattern:
5 +//!
6 +//! - **`schedule_future`** (preferred): Schedules work and ret
+urns a stream.
7 +//! Callers collect at boundaries using `collect_one`, `colle
+ct_result`, etc.
8 +//! Enables composability and parallel scheduling.
9 +//!
10 +//! - **`exec_future`** (legacy): Blocks immediately at the lea
+f. Use only for
11 +//! one-shot initialization (DB connection, migrations), not
+for trait methods.
12
13 use foundation_core::valtron::{execute, from_future, Stream};
14
15 use crate::errors::StorageError;
16 +use crate::storage_provider::StorageItemStream;
17
10 -/// Helper function for single-value results from futures that
-return Result types.
18 +/// WHY: Enables non-blocking, composable storage operations.
19 ///
12 -/// Wraps a future using Valtron's `from_future` + `execute` pa
-ttern,
13 -/// extracting the result from the stream iterator.
20 +/// WHAT: Schedules a future for execution via Valtron's `from_
+future` + `execute`,
21 +/// returning a mapped stream of results. The future runs on th
+e Valtron worker pool;
22 +/// the returned stream lazily yields results when drained by t
+he caller.
23 ///
15 -/// # Type Parameters
24 +/// HOW: Wraps the future with `from_future`, schedules via `ex
+ecute`, then maps
25 +/// `Stream<Result<T, E>, FuturePollState>` to `Stream<T, ()>`.
+ Errors from the
26 +/// future are logged via tracing and result in no `Next` items
+ being yielded.
27 ///
17 -/// * `T` - The success type (must be `Send + 'static`)
18 -/// * `E` - The error type (must implement `Display + Send + 's
-tatic`)
19 -/// * `F` - The future type (must output `Result<T, E>` and be
-`Send + 'static`)
28 +/// # Errors
29 ///
30 +/// Returns a `StorageError` if Valtron scheduling fails (pool
+not initialized, etc.).
31 +/// Execution errors from the future are logged and yield an em
+pty stream — callers
32 +/// should treat `None` from `collect_one` as an execution fail
+ure.
33 +pub fn schedule_future<T, E, F>(future: F) -> Result<StorageIte
+mStream<'static, T>, StorageError>
34 +where
35 + F: std::future::Future<Output = Result<T, E>> + Send + 'sta
+tic,
36 + T: Send + 'static,
37 + E: std::fmt::Display + Send + 'static,
38 +{
39 + let task = from_future(future);
40 + let stream = execute(task, None)
41 + .map_err(|e| StorageError::Backend(format!("Valtron sch
+eduling failed: {e}")))?;
42 +
43 + let mapped = stream.into_iter().filter_map(|s| match s {
44 + Stream::Next(Ok(v)) => Some(Stream::Next(v)),
45 + Stream::Next(Err(e)) => {
46 + tracing::error!("Async execution error: {e}");
47 + None
48 + }
49 + Stream::Pending(_) => Some(Stream::Pending(())),
50 + Stream::Init => Some(Stream::Init),
51 + Stream::Ignore => Some(Stream::Ignore),
52 + Stream::Delayed(d) => Some(Stream::Delayed(d)),
53 + });
54 +
55 + Ok(Box::new(mapped))
56 +}
57 +
58 +/// WHY: One-shot blocking bridge for initialization and migrat
+ions.
59 +///
60 +/// WHAT: Wraps a future using Valtron's `from_future` + `execu
+te` pattern,
61 +/// blocking until the result is available. **Use sparingly** —
+ prefer
62 +/// `schedule_future` for trait methods to preserve composabili
+ty.
63 +///
64 +/// HOW: Schedules the future, then eagerly drains the stream t
+o extract
65 +/// the single result.
66 +///
67 /// # Errors
68 ///
69 /// Returns a `StorageError` if:
● Now update the trait signatures in storage_provider.rs.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 7 lines, removed 3 lines
1 //! Core storage provider traits and abstractions.
2 //!
3 -//! All storage traits are synchronous. Multi-value operations
-return
4 -//! `StorageItemStream` (a Valtron Stream-based lazy iterator)
-instead
5 -//! of allocating Vecs. Single-value operations return `Storage
-Result<T>` directly.
3 +//! All storage operations return `StorageItemStream` (a Valtro
+n Stream-based
4 +//! lazy iterator) wrapped in `StorageResult`. Single-value ope
+rations yield
5 +//! exactly one `Stream::Next` item; multi-value operations yie
+ld many.
6 +//!
7 +//! Callers collect at sync boundaries using Valtron helpers:
8 +//! - `collect_one(stream)` — extract first `Next` value
9 +//! - `collect_result(stream)` — drain all `Next` values into `
+Vec<T>`
10
11 use serde::{de::DeserializeOwned, Serialize};
12
● Now update KeyValueStore trait.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 14 lines, removed 13 lines
179
180 /// Key-value store operations available on all backends.
181 ///
182 -/// All methods are synchronous. Multi-value operations return
183 -/// `StorageItemStream` for lazy iteration.
182 +/// All methods return `StorageItemStream` for composable, non
+-blocking I/O.
183 +/// Single-value operations yield exactly one `Stream::Next` i
+tem.
184 +/// Use `collect_one` / `collect_result` at sync boundaries to
+ extract values.
185 pub trait KeyValueStore: Send + Sync {
185 - /// Get a value by key.
186 + /// Get a value by key. Yields one `Next(Option<V>)`.
187 ///
188 /// # Errors
189 ///
189 - /// Returns an error if deserialization fails or the backe
-nd encounters an error.
190 - fn get<V: DeserializeOwned>(&self, key: &str) -> StorageRe
-sult<Option<V>>;
190 + /// Returns an error if scheduling fails or deserializatio
+n fails.
191 + fn get<V: DeserializeOwned + Send>(&self, key: &str) -> St
+orageResult<StorageItemStream<'_, Option<V>>>;
192
192 - /// Set a key-value pair.
193 + /// Set a key-value pair. Yields one `Next(())`.
194 ///
195 /// # Errors
196 ///
196 - /// Returns an error if serialization fails or the backend
- encounters an error.
197 - fn set<V: Serialize>(&self, key: &str, value: V) -> Storag
-eResult<()>;
197 + /// Returns an error if serialization or scheduling fails.
198 + fn set<V: Serialize>(&self, key: &str, value: V) -> Storag
+eResult<StorageItemStream<'_, ()>>;
199
199 - /// Delete a key.
200 + /// Delete a key. Yields one `Next(())`.
201 ///
202 /// # Errors
203 ///
204 /// Returns an error if the backend encounters an error.
204 - fn delete(&self, key: &str) -> StorageResult<()>;
205 + fn delete(&self, key: &str) -> StorageResult<StorageItemSt
+ream<'_, ()>>;
206
206 - /// Check if a key exists.
207 + /// Check if a key exists. Yields one `Next(bool)`.
208 ///
209 /// # Errors
210 ///
211 /// Returns an error if the backend encounters an error.
211 - fn exists(&self, key: &str) -> StorageResult<bool>;
212 + fn exists(&self, key: &str) -> StorageResult<StorageItemSt
+ream<'_, bool>>;
213
214 /// List all keys with optional prefix filter.
214 - /// Returns a stream for lazy iteration over keys.
215 + /// Yields multiple `Next(String)` items.
216 ///
217 /// # Errors
218 ///
● Now update BlobStore trait.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 8 lines, removed 8 lines
222
223 /// Blob storage operations for binary large objects.
224 pub trait BlobStore: Send + Sync {
225 - /// Put a blob into storage.
225 + /// Put a blob into storage. Yields one `Next(())`.
226 ///
227 /// # Errors
228 ///
229 /// Returns an error if the backend encounters an error.
230 - fn put_blob(&self, key: &str, data: &[u8]) -> StorageResul
-t<()>;
230 + fn put_blob(&self, key: &str, data: &[u8]) -> StorageResul
+t<StorageItemStream<'_, ()>>;
231
232 - /// Get a blob from storage.
232 + /// Get a blob from storage. Yields one `Next(Option<Vec<u
+8>>)`.
233 ///
234 /// # Errors
235 ///
236 /// Returns an error if the backend encounters an error.
237 - fn get_blob(&self, key: &str) -> StorageResult<Option<Vec<
-u8>>>;
237 + fn get_blob(&self, key: &str) -> StorageResult<StorageItem
+Stream<'_, Option<Vec<u8>>>>;
238
239 - /// Delete a blob.
239 + /// Delete a blob. Yields one `Next(())`.
240 ///
241 /// # Errors
242 ///
243 /// Returns an error if the backend encounters an error.
244 - fn delete_blob(&self, key: &str) -> StorageResult<()>;
244 + fn delete_blob(&self, key: &str) -> StorageResult<StorageI
+temStream<'_, ()>>;
245
246 - /// Check if a blob exists.
246 + /// Check if a blob exists. Yields one `Next(bool)`.
247 ///
248 /// # Errors
249 ///
250 /// Returns an error if the backend encounters an error.
251 - fn blob_exists(&self, key: &str) -> StorageResult<bool>;
251 + fn blob_exists(&self, key: &str) -> StorageResult<StorageI
+temStream<'_, bool>>;
252 }
253
254 /// SQL query operations for relational backends (Turso, D1).
● Now update QueryStore trait.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 5 lines, removed 4 lines
254 /// SQL query operations for relational backends (Turso, D1).
255 pub trait QueryStore: Send + Sync {
256 /// Execute a query that returns rows.
257 - /// Returns a stream for lazy iteration over rows.
257 + /// Yields multiple `Next(SqlRow)` items.
258 ///
259 /// # Errors
260 ///
...
262 fn query(&self, sql: &str, params: &[DataValue]) -> Storag
eResult<StorageItemStream<'_, SqlRow>>;
263
264 /// Execute a statement that returns number of rows affect
ed.
265 + /// Yields one `Next(u64)`.
266 ///
267 /// # Errors
268 ///
269 /// Returns an error if the statement fails or parameter c
onversion fails.
269 - fn execute(&self, sql: &str, params: &[DataValue]) -> Stor
-ageResult<u64>;
270 + fn execute(&self, sql: &str, params: &[DataValue]) -> Stor
+ageResult<StorageItemStream<'_, u64>>;
271
271 - /// Execute a batch of SQL statements.
272 + /// Execute a batch of SQL statements. Yields one `Next(()
+)`.
273 ///
274 /// # Errors
275 ///
276 /// Returns an error if any statement in the batch fails.
276 - fn execute_batch(&self, sql: &str) -> StorageResult<()>;
277 + fn execute_batch(&self, sql: &str) -> StorageResult<Storag
+eItemStream<'_, ()>>;
278 }
279
280 /// Rate limiting operations.
● Now update RateLimiterStore trait.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 6 lines, removed 6 lines
279
280 /// Rate limiting operations.
281 pub trait RateLimiterStore: Send + Sync {
282 - /// Check if a rate limit key is allowed.
282 + /// Check if a rate limit key is allowed. Yields one `Next
+(bool)`.
283 ///
284 /// # Errors
285 ///
...
289 key: &str,
290 max_count: u32,
291 window_seconds: u64,
292 - ) -> StorageResult<bool>;
292 + ) -> StorageResult<StorageItemStream<'_, bool>>;
293
294 - /// Record a rate-limited action.
294 + /// Record a rate-limited action. Yields one `Next(u32)`.
295 ///
296 /// # Errors
297 ///
298 /// Returns an error if the backend encounters an error.
299 - fn record_rate_limit(&self, key: &str) -> StorageResult<u3
-2>;
299 + fn record_rate_limit(&self, key: &str) -> StorageResult<St
+orageItemStream<'_, u32>>;
300
301 - /// Reset a rate limit key.
301 + /// Reset a rate limit key. Yields one `Next(())`.
302 ///
303 /// # Errors
304 ///
305 /// Returns an error if the backend encounters an error.
306 - fn reset_rate_limit(&self, key: &str) -> StorageResult<()>
-;
306 + fn reset_rate_limit(&self, key: &str) -> StorageResult<Sto
+rageItemStream<'_, ()>>;
307 }
308
309 /// Storage backend enumeration for runtime selection.
● Now update the StorageProvider impl blocks — the dispatch methods.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 4 lines, removed 4 lines
413 }
414
415 impl KeyValueStore for StorageProvider {
416 - fn get<V: DeserializeOwned>(&self, key: &str) -> StorageRe
-sult<Option<V>> {
416 + fn get<V: DeserializeOwned + Send>(&self, key: &str) -> St
+orageResult<StorageItemStream<'_, Option<V>>> {
417 match &self.inner {
418 #[cfg(feature = "turso")]
419 StorageProviderInner::Turso(storage) => storage.ge
t(key),
...
427 }
428 }
429
430 - fn set<V: Serialize>(&self, key: &str, value: V) -> Storag
-eResult<()> {
430 + fn set<V: Serialize>(&self, key: &str, value: V) -> Storag
+eResult<StorageItemStream<'_, ()>> {
431 match &self.inner {
432 #[cfg(feature = "turso")]
433 StorageProviderInner::Turso(storage) => storage.se
t(key, value),
...
441 }
442 }
443
444 - fn delete(&self, key: &str) -> StorageResult<()> {
444 + fn delete(&self, key: &str) -> StorageResult<StorageItemSt
+ream<'_, ()>> {
445 match &self.inner {
446 #[cfg(feature = "turso")]
447 StorageProviderInner::Turso(storage) => storage.de
lete(key),
...
455 }
456 }
457
458 - fn exists(&self, key: &str) -> StorageResult<bool> {
458 + fn exists(&self, key: &str) -> StorageResult<StorageItemSt
+ream<'_, bool>> {
459 match &self.inner {
460 #[cfg(feature = "turso")]
461 StorageProviderInner::Turso(storage) => storage.ex
ists(key),
● Now update the RateLimiterStore impl for StorageProvider.
● Update(backends/foundation_db/src/storage_provider.rs)
⎿ Added 3 lines, removed 3 lines
490 key: &str,
491 max_count: u32,
492 window_seconds: u64,
493 - ) -> StorageResult<bool> {
493 + ) -> StorageResult<StorageItemStream<'_, bool>> {
494 match &self.inner {
495 #[cfg(feature = "turso")]
496 StorageProviderInner::Turso(storage) => storage.ch
eck_rate_limit(key, max_count, window_seconds),
...
504 }
505 }
506
507 - fn record_rate_limit(&self, key: &str) -> StorageResult<u3
-2> {
507 + fn record_rate_limit(&self, key: &str) -> StorageResult<St
+orageItemStream<'_, u32>> {
508 match &self.inner {
509 #[cfg(feature = "turso")]
510 StorageProviderInner::Turso(storage) => storage.re
cord_rate_limit(key),
...
518 }
519 }
520
521 - fn reset_rate_limit(&self, key: &str) -> StorageResult<()>
- {
521 + fn reset_rate_limit(&self, key: &str) -> StorageResult<Sto
+rageItemStream<'_, ()>> {
522 match &self.inner {
523 #[cfg(feature = "turso")]
524 StorageProviderInner::Turso(storage) => storage.re
set_rate_limit(key),
● Now update memory.rs — wrap sync results in streams.
● Update(backends/foundation_db/src/backends/memory.rs)
⎿ Added 12 lines, removed 12 lines
35 }
36
37 impl KeyValueStore for MemoryStorage {
38 - fn get<V: DeserializeOwned>(&self, key: &str) -> StorageRes
-ult<Option<V>> {
38 + fn get<V: DeserializeOwned + Send>(&self, key: &str) -> Sto
+rageResult<StorageItemStream<'_, Option<V>>> {
39 let data = self.data.lock().map_err(|e| {
40 StorageError::Backend(format!("Mutex poisoned: {e}"
))
41 })?;
42
43 - match data.get(key) {
43 + let result = match data.get(key) {
44 Some(bytes) => {
45 let value: V = serde_json::from_slice(bytes)
46 .map_err(|e| StorageError::Serialization(e.
to_string()))?;
47 - Ok(Some(value))
47 + Some(value)
48 }
49 - None => Ok(None),
50 - }
49 + None => None,
50 + };
51 + Ok(Box::new(std::iter::once(Stream::Next(result))))
52 }
53
53 - fn set<V: Serialize>(&self, key: &str, value: V) -> Storage
-Result<()> {
54 + fn set<V: Serialize>(&self, key: &str, value: V) -> Storage
+Result<StorageItemStream<'_, ()>> {
55 let bytes = serde_json::to_vec(&value)
56 .map_err(|e| StorageError::Serialization(e.to_strin
g()))?;
57
...
59 StorageError::Backend(format!("Mutex poisoned: {e}"
))
60 })?;
61
61 - // Use Zeroizing to ensure secure memory handling
62 data.insert(key.to_string(), Zeroizing::new(bytes));
63 - Ok(())
63 + Ok(Box::new(std::iter::once(Stream::Next(()))))
64 }
65
66 - fn delete(&self, key: &str) -> StorageResult<()> {
66 + fn delete(&self, key: &str) -> StorageResult<StorageItemStr
+eam<'_, ()>> {
67 let mut data = self.data.lock().map_err(|e| {
68 StorageError::Backend(format!("Mutex poisoned: {e}"
))
69 })?;
70 data.remove(key);
71 - Ok(())
71 + Ok(Box::new(std::iter::once(Stream::Next(()))))
72 }
73
74 - fn exists(&self, key: &str) -> StorageResult<bool> {
74 + fn exists(&self, key: &str) -> StorageResult<StorageItemStr
+eam<'_, bool>> {
75 let data = self.data.lock().map_err(|e| {
76 StorageError::Backend(format!("Mutex poisoned: {e}"
))
77 })?;
78 - Ok(data.contains_key(key))
78 + Ok(Box::new(std::iter::once(Stream::Next(data.contains_
+key(key)))))
79 }
80
81 fn list_keys(&self, prefix: Option<&str>) -> StorageResult<
StorageItemStream<'_, String>> {
● Now update the QueryStore impl for MemoryStorage.
● Update(backends/foundation_db/src/backends/memory.rs)
⎿ Added 2 lines, removed 2 lines
102 ))
103 }
104
105 - fn execute(&self, _sql: &str, _params: &[DataValue]) -> St
-orageResult<u64> {
105 + fn execute(&self, _sql: &str, _params: &[DataValue]) -> St
+orageResult<StorageItemStream<'_, u64>> {
106 Err(StorageError::Generic(
107 "QueryStore not supported for MemoryStorage".to_st
ring(),
108 ))
109 }
110
111 - fn execute_batch(&self, _sql: &str) -> StorageResult<()> {
111 + fn execute_batch(&self, _sql: &str) -> StorageResult<Stora
+geItemStream<'_, ()>> {
112 Err(StorageError::Generic(
113 "QueryStore not supported for MemoryStorage".to_st
ring(),
114 ))
● Now update RateLimiterStore for MemoryStorage.
● Update(backends/foundation_db/src/backends/memory.rs)
⎿ Added 12 lines, removed 14 lines
129 key: &str,
130 max_count: u32,
131 window_seconds: u64,
132 - ) -> StorageResult<bool> {
132 + ) -> StorageResult<StorageItemStream<'_, bool>> {
133 let now = std::time::SystemTime::now()
134 .duration_since(std::time::UNIX_EPOCH)
135 .unwrap()
136 .as_secs();
137
138 - // Get rate limit data from storage
138 let data = self.data.lock().map_err(|e| {
139 StorageError::Backend(format!("Mutex poisoned: {e}
"))
140 })?;
141
142 let rate_key = format!("_rate_limit:{key}");
144 - match data.get(&rate_key) {
143 + let allowed = match data.get(&rate_key) {
144 Some(bytes) => {
145 let entry: RateLimitEntry = serde_json::from_s
lice(bytes)
146 .map_err(|e| StorageError::Serialization(e
.to_string()))?;
147
149 - // Check if window has expired
148 if entry.window_start < now - window_seconds {
151 - return Ok(true);
149 + true
150 + } else {
151 + entry.count < max_count
152 }
153 -
154 - // Check if within limit
155 - Ok(entry.count < max_count)
153 }
157 - None => Ok(true), // No record yet, allow
158 - }
154 + None => true,
155 + };
156 + Ok(Box::new(std::iter::once(Stream::Next(allowed))))
157 }
158
161 - fn record_rate_limit(&self, key: &str) -> StorageResult<u3
-2> {
159 + fn record_rate_limit(&self, key: &str) -> StorageResult<St
+orageItemStream<'_, u32>> {
160 let now = std::time::SystemTime::now()
161 .duration_since(std::time::UNIX_EPOCH)
162 .unwrap()
...
185 1
186 };
187
190 - Ok(new_count)
188 + Ok(Box::new(std::iter::once(Stream::Next(new_count))))
189 }
190
193 - fn reset_rate_limit(&self, key: &str) -> StorageResult<()>
- {
191 + fn reset_rate_limit(&self, key: &str) -> StorageResult<Sto
+rageItemStream<'_, ()>> {
192 let rate_key = format!("_rate_limit:{key}");
193 let mut data = self.data.lock().map_err(|e| {
194 StorageError::Backend(format!("Mutex poisoned: {e}
"))
195 })?;
196 data.remove(&rate_key);
199 - Ok(())
197 + Ok(Box::new(std::iter::once(Stream::Next(()))))
198 }
199 }
200
● Now update the memory.rs tests to use collect_one/collect_result.
● Update(backends/foundation_db/src/backends/memory.rs)
⎿ Added 17 lines, removed 28 lines
201 #[cfg(test)]
202 mod tests {
203 use super::*;
204 + use foundation_core::valtron::{collect_one, collect_result
+};
205
206 #[test]
207 fn test_memory_storage_basic() {
208 let storage = MemoryStorage::new();
209
210 // Test set and get
210 - storage.set("test_key", "test_value").unwrap();
211 + collect_one(storage.set("test_key", "test_value").unwr
+ap()).unwrap();
212
212 - let value: String = storage.get("test_key").unwrap().u
-nwrap();
213 - assert_eq!(value, "test_value");
213 + let value: Option<String> = collect_one(storage.get("t
+est_key").unwrap()).unwrap();
214 + assert_eq!(value, Some("test_value".to_string()));
215
216 // Test exists
216 - assert!(storage.exists("test_key").unwrap());
217 - assert!(!storage.exists("nonexistent").unwrap());
217 + assert!(collect_one(storage.exists("test_key").unwrap(
+)).unwrap());
218 + assert!(!collect_one(storage.exists("nonexistent").unw
+rap()).unwrap());
219
220 // Test delete
220 - storage.delete("test_key").unwrap();
221 - assert!(!storage.exists("test_key").unwrap());
221 + collect_one(storage.delete("test_key").unwrap()).unwra
+p();
222 + assert!(!collect_one(storage.exists("test_key").unwrap
+()).unwrap());
223 }
224
225 #[test]
226 fn test_memory_storage_list_keys() {
226 - use foundation_core::valtron::Stream;
227 -
227 let storage = MemoryStorage::new();
228
230 - storage.set("prefix:key1", "value1").unwrap();
231 - storage.set("prefix:key2", "value2").unwrap();
232 - storage.set("other:key3", "value3").unwrap();
229 + collect_one(storage.set("prefix:key1", "value1").unwra
+p()).unwrap();
230 + collect_one(storage.set("prefix:key2", "value2").unwra
+p()).unwrap();
231 + collect_one(storage.set("other:key3", "value3").unwrap
+()).unwrap();
232
234 - // List all keys - need to extract values from Stream:
-:Next
235 - let keys: Vec<String> = storage.list_keys(None).unwrap
-()
236 - .filter_map(|s| match s {
237 - Stream::Next(key) => Some(key),
238 - _ => None,
239 - })
240 - .collect();
233 + // List all keys
234 + let keys = collect_result(storage.list_keys(None).unwr
+ap());
235 assert_eq!(keys.len(), 3);
236
237 // List keys with prefix
244 - let keys: Vec<String> = storage.list_keys(Some("prefix
-:")).unwrap()
245 - .filter_map(|s| match s {
246 - Stream::Next(key) => Some(key),
247 - _ => None,
248 - })
249 - .collect();
238 + let keys = collect_result(storage.list_keys(Some("pref
+ix:")).unwrap());
239 assert_eq!(keys.len(), 2);
240 assert!(keys.contains(&"prefix:key1".to_string()));
241 assert!(keys.contains(&"prefix:key2".to_string()));
...
256 count: 42,
257 };
258
270 - storage.set("complex", &data).unwrap();
259 + collect_one(storage.set("complex", &data).unwrap()).un
+wrap();
260
272 - let retrieved: TestData = storage.get("complex").unwra
-p().unwrap();
273 - assert_eq!(data, retrieved);
261 + let retrieved: Option<TestData> = collect_one(storage.
+get("complex").unwrap()).unwrap();
262 + assert_eq!(retrieved, Some(data));
263 }
264 }
● Now update json_file.rs.
● Update(backends/foundation_db/src/backends/json_file.rs)
⎿ Added 12 lines, removed 13 lines
121 }
122
123 impl KeyValueStore for JsonFileStorage {
124 - fn get<V: DeserializeOwned>(&self, key: &str) -> StorageRe
-sult<Option<V>> {
124 + fn get<V: DeserializeOwned + Send>(&self, key: &str) -> St
+orageResult<StorageItemStream<'_, Option<V>>> {
125 let data = self.data.lock().map_err(|e| {
126 StorageError::Backend(format!("Mutex poisoned: {e}
"))
127 })?;
128
129 - match data.get(key) {
129 + let result = match data.get(key) {
130 Some(bytes) => {
131 let value: V = serde_json::from_slice(bytes)
132 .map_err(|e| StorageError::Serialization(e
.to_string()))?;
133 - Ok(Some(value))
133 + Some(value)
134 }
135 - None => Ok(None),
136 - }
135 + None => None,
136 + };
137 + Ok(Box::new(std::iter::once(Stream::Next(result))))
138 }
139
139 - fn set<V: Serialize>(&self, key: &str, value: V) -> Storag
-eResult<()> {
140 + fn set<V: Serialize>(&self, key: &str, value: V) -> Storag
+eResult<StorageItemStream<'_, ()>> {
141 let bytes = serde_json::to_vec(&value)
142 .map_err(|e| StorageError::Serialization(e.to_stri
ng()))?;
143
...
148 data.insert(key.to_string(), Zeroizing::new(bytes));
149 drop(data); // Release lock before flushing
150
150 - // Flush to disk atomically
151 self.flush_to_disk()?;
152
153 - Ok(())
153 + Ok(Box::new(std::iter::once(Stream::Next(()))))
154 }
155
156 - fn delete(&self, key: &str) -> StorageResult<()> {
156 + fn delete(&self, key: &str) -> StorageResult<StorageItemSt
+ream<'_, ()>> {
157 let mut data = self.data.lock().map_err(|e| {
158 StorageError::Backend(format!("Mutex poisoned: {e}
"))
159 })?;
...
161 data.remove(key);
162 drop(data); // Release lock before flushing
163
164 - // Flush to disk atomically
164 self.flush_to_disk()?;
165
167 - Ok(())
166 + Ok(Box::new(std::iter::once(Stream::Next(()))))
167 }
168
170 - fn exists(&self, key: &str) -> StorageResult<bool> {
169 + fn exists(&self, key: &str) -> StorageResult<StorageItemSt
+ream<'_, bool>> {
170 let data = self.data.lock().map_err(|e| {
171 StorageError::Backend(format!("Mutex poisoned: {e}
"))
172 })?;
174 - Ok(data.contains_key(key))
173 + Ok(Box::new(std::iter::once(Stream::Next(data.contains
+_key(key)))))
174 }
175
176 fn list_keys(&self, prefix: Option<&str>) -> StorageResult
<StorageItemStream<'_, String>> {
● Now update RateLimiterStore for JsonFileStorage.
● Update(backends/foundation_db/src/backends/json_file.rs)
⎿ Added 3 lines, removed 3 lines
195 _key: &str,
196 _max_count: u32,
197 _window_seconds: u64,
198 - ) -> StorageResult<bool> {
198 + ) -> StorageResult<StorageItemStream<'_, bool>> {
199 Err(StorageError::Generic(
200 "RateLimiterStore not supported for JsonFileStorag
e".to_string(),
201 ))
202 }
203
204 - fn record_rate_limit(&self, _key: &str) -> StorageResult<u
-32> {
204 + fn record_rate_limit(&self, _key: &str) -> StorageResult<S
+torageItemStream<'_, u32>> {
205 Err(StorageError::Generic(
206 "RateLimiterStore not supported for JsonFileStorag
e".to_string(),
207 ))
208 }
209
210 - fn reset_rate_limit(&self, _key: &str) -> StorageResult<()
-> {
210 + fn reset_rate_limit(&self, _key: &str) -> StorageResult<St
+orageItemStream<'_, ()>> {
211 Err(StorageError::Generic(
212 "RateLimiterStore not supported for JsonFileStorag
e".to_string(),
213 ))
● Now update json_file.rs tests.
● Update(backends/foundation_db/src/backends/json_file.rs)
⎿ Added 24 lines, removed 36 lines
217 #[cfg(test)]
218 mod tests {
219 use super::*;
220 + use foundation_core::valtron::{collect_one, collect_result
+};
221 use tempfile::TempDir;
222
223 #[test]
...
228 let storage = JsonFileStorage::new(&file_path).unwrap(
);
229
230 // Test set and get
230 - storage.set("test_key", "test_value").unwrap();
231 + collect_one(storage.set("test_key", "test_value").unwr
+ap()).unwrap();
232
232 - let value: String = storage.get("test_key").unwrap().u
-nwrap();
233 - assert_eq!(value, "test_value");
233 + let value: Option<String> = collect_one(storage.get("t
+est_key").unwrap()).unwrap();
234 + assert_eq!(value, Some("test_value".to_string()));
235
236 // Test exists
236 - assert!(storage.exists("test_key").unwrap());
237 - assert!(!storage.exists("nonexistent").unwrap());
237 + assert!(collect_one(storage.exists("test_key").unwrap(
+)).unwrap());
238 + assert!(!collect_one(storage.exists("nonexistent").unw
+rap()).unwrap());
239
240 // Test delete
240 - storage.delete("test_key").unwrap();
241 - assert!(!storage.exists("test_key").unwrap());
241 + collect_one(storage.delete("test_key").unwrap()).unwra
+p();
242 + assert!(!collect_one(storage.exists("test_key").unwrap
+()).unwrap());
243 }
244
245 #[test]
246 fn test_json_file_storage_list_keys() {
246 - use foundation_core::valtron::Stream;
247 -
247 let temp_dir = TempDir::new().unwrap();
248 let file_path = temp_dir.path().join("test.json");
249
250 let storage = JsonFileStorage::new(&file_path).unwrap(
);
251
253 - storage.set("prefix:key1", "value1").unwrap();
254 - storage.set("prefix:key2", "value2").unwrap();
255 - storage.set("other:key3", "value3").unwrap();
252 + collect_one(storage.set("prefix:key1", "value1").unwra
+p()).unwrap();
253 + collect_one(storage.set("prefix:key2", "value2").unwra
+p()).unwrap();
254 + collect_one(storage.set("other:key3", "value3").unwrap
+()).unwrap();
255
257 - // List all keys - need to extract values from Stream:
-:Next
258 - let keys: Vec<String> = storage.list_keys(None).unwrap
-()
259 - .filter_map(|s| match s {
260 - Stream::Next(key) => Some(key),
261 - _ => None,
262 - })
263 - .collect();
256 + // List all keys
257 + let keys = collect_result(storage.list_keys(None).unwr
+ap());
258 assert_eq!(keys.len(), 3);
259
260 // List keys with prefix
267 - let keys: Vec<String> = storage.list_keys(Some("prefix
-:")).unwrap()
268 - .filter_map(|s| match s {
269 - Stream::Next(key) => Some(key),
270 - _ => None,
271 - })
272 - .collect();
261 + let keys = collect_result(storage.list_keys(Some("pref
+ix:")).unwrap());
262 assert_eq!(keys.len(), 2);
263 assert!(keys.contains(&"prefix:key1".to_string()));
264 assert!(keys.contains(&"prefix:key2".to_string()));
...
271
272 // Create storage and add data
273 let storage = JsonFileStorage::new(&file_path).unwrap(
);
285 - storage.set("key1", "value1").unwrap();
286 - storage.set("key2", "value2").unwrap();
274 + collect_one(storage.set("key1", "value1").unwrap()).un
+wrap();
275 + collect_one(storage.set("key2", "value2").unwrap()).un
+wrap();
276
277 // Verify file was created
278 assert!(file_path.exists());
...