allframe 0.1.28

Complete Rust web framework with built-in HTTP/2 server, REST/GraphQL/gRPC, compile-time DI, CQRS - TDD from day zero
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
//! tests/08_offline_first.rs
//!
//! E2E tests for GitHub Issue #36: Offline-first and offline-only optimizations
//! for desktop/embedded deployments.
//!
//! These tests define the expected behavior for:
//! - UC-036.1: Offline Event Store Backend (SQLite)
//! - UC-036.2: Offline-Aware Resilience Patterns
//! - UC-036.3: Local-First Projection Sync
//! - UC-036.4: Feature Flag (`offline`)
//! - UC-036.5: Embedded MCP Server Without Network
//! - UC-036.6: DI Container Lazy Initialization
//! - UC-036.7: Saga Compensation with Local Rollback

// =============================================================================
// Shared test fixtures
// =============================================================================

#![allow(dead_code, unused_variables, unused_imports)]

use std::collections::HashMap;

use allframe_core::cqrs::{
    Aggregate, Event, EventStore, EventTypeName, OrchestratorSagaStep, Projection, SagaDefinition,
    SagaOrchestrator, Snapshot,
};

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
enum DocumentEvent {
    Created {
        doc_id: String,
        title: String,
    },
    Updated {
        title: String,
        content: String,
    },
    Deleted,
    TagAdded {
        tag: String,
    },
    SyncedToRemote {
        remote_id: String,
        timestamp: u64,
    },
}

impl EventTypeName for DocumentEvent {}
impl Event for DocumentEvent {}

#[derive(Default, Clone)]
struct DocumentAggregate {
    id: String,
    title: String,
    content: String,
    tags: Vec<String>,
    is_deleted: bool,
    version: u64,
}

impl Aggregate for DocumentAggregate {
    type Event = DocumentEvent;

    fn apply_event(&mut self, event: &Self::Event) {
        self.version += 1;
        match event {
            DocumentEvent::Created { doc_id, title } => {
                self.id = doc_id.clone();
                self.title = title.clone();
            }
            DocumentEvent::Updated { title, content } => {
                self.title = title.clone();
                self.content = content.clone();
            }
            DocumentEvent::Deleted => {
                self.is_deleted = true;
            }
            DocumentEvent::TagAdded { tag } => {
                self.tags.push(tag.clone());
            }
            DocumentEvent::SyncedToRemote { .. } => {}
        }
    }
}

struct DocumentProjection {
    documents: HashMap<String, DocumentView>,
}

#[derive(Clone, Debug)]
struct DocumentView {
    id: String,
    title: String,
    content: String,
    tags: Vec<String>,
}

impl Projection for DocumentProjection {
    type Event = DocumentEvent;

    fn apply(&mut self, event: &Self::Event) {
        match event {
            DocumentEvent::Created { doc_id, title } => {
                self.documents.insert(
                    doc_id.clone(),
                    DocumentView {
                        id: doc_id.clone(),
                        title: title.clone(),
                        content: String::new(),
                        tags: Vec::new(),
                    },
                );
            }
            DocumentEvent::Updated { title, content } => {}
            DocumentEvent::TagAdded { tag } => {}
            DocumentEvent::Deleted => {}
            DocumentEvent::SyncedToRemote { .. } => {}
        }
    }
}

// =============================================================================
// UC-036.1: Offline Event Store Backend (SQLite)
// =============================================================================

/// Test that a SQLite-backed event store can be created with a file path
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_creation() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");

    let backend =
        SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
            .await
            .unwrap();

    let store = EventStore::with_backend(backend);

    // Store should be empty initially
    let events = store.get_all_events().await.unwrap();
    assert!(events.is_empty());

    let stats = store.backend().stats().await;
    assert_eq!(stats.total_events, 0);
    assert_eq!(stats.total_aggregates, 0);
}

/// Test that SQLite backend implements full EventStoreBackend contract
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_append_and_retrieve() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");
    let backend =
        SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
            .await
            .unwrap();
    let store = EventStore::with_backend(backend);

    // Append events
    store
        .append(
            "doc-1",
            vec![
                DocumentEvent::Created {
                    doc_id: "doc-1".into(),
                    title: "My Doc".into(),
                },
                DocumentEvent::Updated {
                    title: "Updated Doc".into(),
                    content: "Hello".into(),
                },
            ],
        )
        .await
        .unwrap();

    // Retrieve events for aggregate
    let events = store.get_events("doc-1").await.unwrap();
    assert_eq!(events.len(), 2);

    // Verify event ordering
    assert!(matches!(&events[0], DocumentEvent::Created { .. }));
    assert!(matches!(&events[1], DocumentEvent::Updated { .. }));

    // Stats reflect the append
    let stats = store.backend().stats().await;
    assert_eq!(stats.total_events, 2);
    assert_eq!(stats.total_aggregates, 1);
}

/// Test that SQLite backend supports get_events_after for snapshot optimization
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_events_after_version() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");
    let backend =
        SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
            .await
            .unwrap();
    let store = EventStore::with_backend(backend);

    // Append 100 events
    for i in 0..100 {
        store
            .append(
                "doc-1",
                vec![DocumentEvent::TagAdded {
                    tag: format!("tag-{}", i),
                }],
            )
            .await
            .unwrap();
    }

    // Get events after version 50
    let events = store.get_events_after("doc-1", 50).await.unwrap();
    assert_eq!(events.len(), 50);
}

/// Test that SQLite backend supports snapshot persistence
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_snapshots() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");
    let backend =
        SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
            .await
            .unwrap();
    let store = EventStore::with_backend(backend);

    // Save a snapshot
    let snapshot_data = serde_json::to_vec(&serde_json::json!({
        "id": "doc-1", "title": "My Doc", "version": 50
    }))
    .unwrap();
    store
        .backend()
        .save_snapshot("doc-1", snapshot_data.clone(), 50)
        .await
        .unwrap();

    // Retrieve snapshot
    let (data, version) = store.backend().get_latest_snapshot("doc-1").await.unwrap();
    assert_eq!(version, 50);
    assert_eq!(data, snapshot_data);
}

/// Test that SQLite backend enables WAL mode for concurrent access
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_wal_mode_concurrent_access() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");

    let backend =
        SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
            .await
            .unwrap();

    // Verify WAL mode is enabled
    assert!(backend
        .stats()
        .await
        .backend_specific
        .get("journal_mode")
        .map(|m| m == "wal")
        .unwrap_or(false));

    let store = EventStore::with_backend(backend);

    // Concurrent reads and writes should not block each other
    let store_clone = store.clone();
    let write_handle = tokio::spawn(async move {
        for i in 0..50 {
            store_clone
                .append(
                    "doc-concurrent",
                    vec![DocumentEvent::TagAdded {
                        tag: format!("tag-{}", i),
                    }],
                )
                .await
                .unwrap();
        }
    });

    let store_clone2 = store.clone();
    let read_handle = tokio::spawn(async move {
        for _ in 0..50 {
            let _ = store_clone2.get_events("doc-concurrent").await;
        }
    });

    write_handle.await.unwrap();
    read_handle.await.unwrap();

    let events = store.get_events("doc-concurrent").await.unwrap();
    assert_eq!(events.len(), 50);
}

/// Test that SQLite backend persists across restarts
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_persistence_across_restarts() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");

    // First session: write events
    {
        let backend =
            SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
                .await
                .unwrap();
        let store = EventStore::with_backend(backend);
        store
            .append(
                "doc-1",
                vec![DocumentEvent::Created {
                    doc_id: "doc-1".into(),
                    title: "Persisted".into(),
                }],
            )
            .await
            .unwrap();
        store.backend().flush().await.unwrap();
    }

    // Second session: read events back
    {
        let backend =
            SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
                .await
                .unwrap();
        let store = EventStore::with_backend(backend);
        let events = store.get_events("doc-1").await.unwrap();
        assert_eq!(events.len(), 1);
        assert!(
            matches!(&events[0], DocumentEvent::Created { title, .. } if title == "Persisted")
        );
    }
}

/// Test that atomic append prevents partial writes
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_sqlite_event_store_atomic_append() {
    use allframe_core::cqrs::SqliteEventStoreBackend;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("events.db");
    let backend =
        SqliteEventStoreBackend::<DocumentEvent>::new(db_path.to_str().unwrap())
            .await
            .unwrap();
    let store = EventStore::with_backend(backend);

    // Append a batch of events atomically
    store
        .append(
            "doc-1",
            vec![
                DocumentEvent::Created {
                    doc_id: "doc-1".into(),
                    title: "Doc".into(),
                },
                DocumentEvent::Updated {
                    title: "Updated".into(),
                    content: "Content".into(),
                },
                DocumentEvent::TagAdded {
                    tag: "important".into(),
                },
            ],
        )
        .await
        .unwrap();

    // All or nothing: all 3 events should be present
    let events = store.get_events("doc-1").await.unwrap();
    assert_eq!(events.len(), 3);
}

// =============================================================================
// UC-036.2: Offline-Aware Resilience Patterns
// =============================================================================

/// Test ConnectivityProbe trait contract
#[tokio::test]
#[cfg(feature = "resilience")]
async fn test_connectivity_probe_trait() {
    use allframe_core::resilience::{ConnectivityProbe, ConnectivityStatus};

    // A mock probe that starts offline
    struct MockProbe {
        online: std::sync::Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait::async_trait]
    impl ConnectivityProbe for MockProbe {
        async fn check(&self) -> ConnectivityStatus {
            if self
                .online
                .load(std::sync::atomic::Ordering::SeqCst)
            {
                ConnectivityStatus::Online
            } else {
                ConnectivityStatus::Offline
            }
        }
    }

    let online = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let probe = MockProbe {
        online: online.clone(),
    };

    assert!(matches!(probe.check().await, ConnectivityStatus::Offline));

    online.store(true, std::sync::atomic::Ordering::SeqCst);
    assert!(matches!(probe.check().await, ConnectivityStatus::Online));
}

/// Test OfflineCircuitBreaker queues operations when offline
#[tokio::test]
#[cfg(feature = "resilience")]
async fn test_offline_circuit_breaker_queues_when_offline() {
    use allframe_core::resilience::{
        ConnectivityProbe, ConnectivityStatus, OfflineCircuitBreaker,
    };

    struct AlwaysOfflineProbe;

    #[async_trait::async_trait]
    impl ConnectivityProbe for AlwaysOfflineProbe {
        async fn check(&self) -> ConnectivityStatus {
            ConnectivityStatus::Offline
        }
    }

    let probe = AlwaysOfflineProbe;
    let cb = OfflineCircuitBreaker::new("sync-service", probe);

    // When offline, operations should be queued, not failed
    let result = cb
        .call(|| async { Ok::<_, String>("should be queued") })
        .await;

    // The operation was queued, not executed
    assert!(result.is_queued());
    assert_eq!(cb.queued_count().await, 1);
}

/// Test OfflineCircuitBreaker drains queue when connectivity returns
#[tokio::test]
#[cfg(feature = "resilience")]
async fn test_offline_circuit_breaker_drains_on_reconnect() {
    use allframe_core::resilience::{
        ConnectivityProbe, ConnectivityStatus, OfflineCircuitBreaker,
    };

    struct ToggleProbe {
        online: std::sync::Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait::async_trait]
    impl ConnectivityProbe for ToggleProbe {
        async fn check(&self) -> ConnectivityStatus {
            if self
                .online
                .load(std::sync::atomic::Ordering::SeqCst)
            {
                ConnectivityStatus::Online
            } else {
                ConnectivityStatus::Offline
            }
        }
    }

    let online = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let probe = ToggleProbe {
        online: online.clone(),
    };
    let cb = OfflineCircuitBreaker::new("sync-service", probe);

    // Queue operations while offline
    let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
    let cc = call_count.clone();
    cb.call(move || {
        let cc = cc.clone();
        async move {
            cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok::<_, String>("done")
        }
    })
    .await;

    assert_eq!(
        call_count.load(std::sync::atomic::Ordering::SeqCst),
        0
    );

    // Go online — queued operations should drain
    online.store(true, std::sync::atomic::Ordering::SeqCst);
    cb.drain().await.unwrap();

    assert_eq!(
        call_count.load(std::sync::atomic::Ordering::SeqCst),
        1
    );
    assert_eq!(cb.queued_count().await, 0);
}

/// Test StoreAndForward persists operations locally when offline
#[tokio::test]
#[cfg(feature = "resilience")]
async fn test_store_and_forward_persists_operations() {
    use allframe_core::resilience::{InMemoryQueue, StoreAndForward};

    struct AlwaysOfflineProbe;

    #[async_trait::async_trait]
    impl allframe_core::resilience::ConnectivityProbe for AlwaysOfflineProbe {
        async fn check(&self) -> allframe_core::resilience::ConnectivityStatus {
            allframe_core::resilience::ConnectivityStatus::Offline
        }
    }

    let queue = InMemoryQueue::new();
    let probe = AlwaysOfflineProbe;
    let saf = StoreAndForward::new(queue, probe);

    // Execute operation while offline — should be stored
    saf.execute("sync-payload-1", || async {
        Err::<(), _>("network unavailable".to_string())
    })
    .await;

    saf.execute("sync-payload-2", || async {
        Err::<(), _>("network unavailable".to_string())
    })
    .await;

    // Two operations queued
    assert_eq!(saf.pending_count().await, 2);

    // Queue preserves FIFO order
    let pending = saf.peek_pending().await;
    assert_eq!(pending[0].id, "sync-payload-1");
    assert_eq!(pending[1].id, "sync-payload-2");
}

/// Test StoreAndForward replays operations when connectivity returns
#[tokio::test]
#[cfg(feature = "resilience")]
async fn test_store_and_forward_replay_on_reconnect() {
    use allframe_core::resilience::{InMemoryQueue, StoreAndForward};

    struct ToggleProbe {
        online: std::sync::Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait::async_trait]
    impl allframe_core::resilience::ConnectivityProbe for ToggleProbe {
        async fn check(&self) -> allframe_core::resilience::ConnectivityStatus {
            if self
                .online
                .load(std::sync::atomic::Ordering::SeqCst)
            {
                allframe_core::resilience::ConnectivityStatus::Online
            } else {
                allframe_core::resilience::ConnectivityStatus::Offline
            }
        }
    }

    let online = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let queue = InMemoryQueue::new();
    let probe = ToggleProbe {
        online: online.clone(),
    };
    let saf = StoreAndForward::new(queue, probe);

    // Store operations while offline
    saf.execute("op-1", || async {
        Err::<(), _>("offline".into())
    })
    .await;
    saf.execute("op-2", || async {
        Err::<(), _>("offline".into())
    })
    .await;

    // Go online and replay
    online.store(true, std::sync::atomic::Ordering::SeqCst);

    let report = saf.replay_all(|_id| async { Ok(()) }).await.unwrap();
    assert_eq!(report.replayed, 2);
    assert_eq!(report.failed, 0);
    assert_eq!(saf.pending_count().await, 0);
}

// =============================================================================
// UC-036.3: Local-First Projection Sync
// =============================================================================

/// Test that projections rebuild from local event store
#[tokio::test]
async fn test_local_projection_rebuild_from_event_store() {
    let store = EventStore::new();

    store
        .append(
            "doc-1",
            vec![
                DocumentEvent::Created {
                    doc_id: "doc-1".into(),
                    title: "First Doc".into(),
                },
                DocumentEvent::TagAdded {
                    tag: "rust".into(),
                },
            ],
        )
        .await
        .unwrap();

    store
        .append(
            "doc-2",
            vec![DocumentEvent::Created {
                doc_id: "doc-2".into(),
                title: "Second Doc".into(),
            }],
        )
        .await
        .unwrap();

    // Rebuild projection from all events
    let mut projection = DocumentProjection {
        documents: HashMap::new(),
    };
    let all_events = store.get_all_events().await.unwrap();
    for event in &all_events {
        projection.apply(event);
    }

    assert_eq!(projection.documents.len(), 2);
    assert_eq!(projection.documents["doc-1"].title, "First Doc");
    assert_eq!(projection.documents["doc-2"].title, "Second Doc");
}

/// Test SyncEngine trait contract for bidirectional sync
#[tokio::test]
#[cfg(feature = "cqrs")]
async fn test_sync_engine_bidirectional_sync() {
    use allframe_core::cqrs::{LastWriteWins, SyncEngine};

    let local_store = EventStore::new();
    let remote_store = EventStore::new();

    // Local events
    local_store
        .append(
            "doc-1",
            vec![DocumentEvent::Created {
                doc_id: "doc-1".into(),
                title: "Local Doc".into(),
            }],
        )
        .await
        .unwrap();

    // Remote events (simulated)
    remote_store
        .append(
            "doc-2",
            vec![DocumentEvent::Created {
                doc_id: "doc-2".into(),
                title: "Remote Doc".into(),
            }],
        )
        .await
        .unwrap();

    let sync = SyncEngine::new(local_store.clone(), remote_store.clone(), LastWriteWins);
    let report = sync.sync().await.unwrap();

    // After sync, both stores should have all events
    assert_eq!(report.pushed, 1); // local → remote
    assert_eq!(report.pulled, 1); // remote → local
    assert_eq!(report.conflicts, 0);

    let local_events = local_store.get_all_events().await.unwrap();
    assert_eq!(local_events.len(), 2);
}

/// Test ConflictResolver with LastWriteWins strategy
#[tokio::test]
#[cfg(feature = "cqrs")]
async fn test_conflict_resolver_last_write_wins() {
    use allframe_core::cqrs::{ConflictResolver, LastWriteWins};

    let resolver = LastWriteWins;

    let local = vec![DocumentEvent::Updated {
        title: "Local Title".into(),
        content: "local".into(),
    }];
    let remote = vec![DocumentEvent::Updated {
        title: "Remote Title".into(),
        content: "remote".into(),
    }];

    // With LastWriteWins, remote wins
    let resolved = resolver.resolve(&local, &remote).await;
    assert_eq!(resolved.len(), 1); // One event wins
}

/// Test sync idempotency — replaying same sync produces same result
#[tokio::test]
#[cfg(feature = "cqrs")]
async fn test_sync_idempotency() {
    use allframe_core::cqrs::{LastWriteWins, SyncEngine};

    let local_store = EventStore::new();
    let remote_store = EventStore::new();

    local_store
        .append(
            "doc-1",
            vec![DocumentEvent::Created {
                doc_id: "doc-1".into(),
                title: "Doc".into(),
            }],
        )
        .await
        .unwrap();

    let sync = SyncEngine::new(local_store, remote_store, LastWriteWins);

    let report1 = sync.sync().await.unwrap();
    let report2 = sync.sync().await.unwrap();

    // Second sync should be a no-op
    assert_eq!(report2.pushed, 0);
    assert_eq!(report2.pulled, 0);
    assert_eq!(report2.conflicts, 0);
}

// =============================================================================
// UC-036.4: Feature Flag — `offline` or `embedded`
// =============================================================================

/// Test that cqrs feature is available (baseline for offline)
#[test]
#[cfg(feature = "cqrs")]
fn test_cqrs_feature_available_for_offline() {
    use allframe_core::cqrs::{EventStore, EventStoreBackend};

    let store = EventStore::<DocumentEvent>::new();
    let _: &dyn EventStoreBackend<DocumentEvent> = store.backend();
}

/// Test that DI feature is available (baseline for offline)
#[test]
#[cfg(feature = "di")]
fn test_di_feature_available_for_offline() {
    use allframe_core::di::{ContainerBuilder, DependencyRegistry, Scope};

    let mut registry = DependencyRegistry::new();
    registry.store_singleton(42i32);
    assert!(registry.has_singleton::<i32>());

    let builder = ContainerBuilder::new();
    assert_eq!(builder.initialization_order().len(), 0);
}

/// Test that the offline feature flag implies the expected feature set
#[test]
#[cfg(feature = "offline")]
fn test_offline_feature_flag_implies_cqrs_and_di() {
    // When `offline` is enabled, both cqrs and di should be available
    use allframe_core::cqrs::EventStore;
    use allframe_core::di::DependencyRegistry;

    let _store = EventStore::<DocumentEvent>::new();
    let _registry = DependencyRegistry::new();

    // SQLite backend should also be available
    use allframe_core::cqrs::SqliteEventStoreBackend;
}

/// Test that offline feature does not pull in network dependencies
#[test]
fn test_offline_feature_no_network_deps() {
    // This is a documentation/CI test:
    // `cargo tree --features offline --no-default-features`
    // should NOT contain: reqwest, redis, opentelemetry-otlp, tonic, hyper, rustls, openssl
    assert!(true);
}

// =============================================================================
// UC-036.5: Embedded MCP Server Without Network
// =============================================================================

/// Test in-process MCP tool call without network
#[tokio::test]
async fn test_mcp_local_tool_call_no_network() {
    use allframe_mcp::McpServer;

    let mcp = McpServer::new();
    mcp.register_tool("echo", |args: serde_json::Value| async move { Ok(args) });

    // Direct in-process call — no serialization overhead
    let result = mcp
        .call_tool_local("echo", serde_json::json!({"message": "hello"}))
        .await
        .unwrap();

    assert_eq!(result["message"], "hello");
}

/// Test that MCP local and network paths share the same tool registry
#[tokio::test]
async fn test_mcp_shared_tool_registry() {
    use allframe_mcp::McpServer;

    let mcp = McpServer::new();
    mcp.register_tool("add", |args: serde_json::Value| async move {
        let a = args["a"].as_i64().unwrap();
        let b = args["b"].as_i64().unwrap();
        Ok(serde_json::json!({"result": a + b}))
    });

    // Local call
    let local_result = mcp
        .call_tool_local("add", serde_json::json!({"a": 2, "b": 3}))
        .await
        .unwrap();

    assert_eq!(local_result["result"], 5);

    // Tool list should be the same for local and network paths
    let tools = mcp.list_tools();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "add");
}

/// Test that no network port is opened in local-only mode
#[tokio::test]
async fn test_mcp_no_network_port_in_local_mode() {
    use allframe_mcp::McpServer;

    let mcp = McpServer::new();
    mcp.register_tool("noop", |_| async { Ok(serde_json::json!({})) });

    // In local-only mode, no listener should be created
    assert!(!mcp.is_listening());

    // Tool calls still work
    let result = mcp
        .call_tool_local("noop", serde_json::json!({}))
        .await;
    assert!(result.is_ok());
}

// =============================================================================
// UC-036.6: DI Container — Lazy Initialization
// =============================================================================

/// Test that DI container supports eager initialization (current behavior)
#[test]
fn test_di_container_eager_initialization_baseline() {
    use allframe_core::di::DependencyRegistry;

    let mut registry = DependencyRegistry::new();

    // Eager: available immediately after store
    registry.store_singleton(String::from("config-value"));
    assert!(registry.has_singleton::<String>());

    let value = registry.get_singleton::<String>().unwrap();
    assert_eq!(*value, "config-value");
}

/// Test that DI container supports lazy binding that initializes on first get
#[tokio::test]
#[cfg(feature = "di")]
async fn test_di_lazy_binding_initializes_on_first_get() {
    use allframe_core::di::LazyProvider;

    let initialized = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let init_flag = initialized.clone();

    let provider = LazyProvider::new(move || {
        let flag = init_flag.clone();
        async move {
            flag.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok::<_, allframe_core::di::DependencyError>("heavy-resource".to_string())
        }
    });

    // Not yet initialized
    assert!(!initialized.load(std::sync::atomic::Ordering::SeqCst));

    // First get triggers initialization
    let value = provider.get().await.unwrap();
    assert_eq!(value, "heavy-resource");
    assert!(initialized.load(std::sync::atomic::Ordering::SeqCst));

    // Second get returns cached value (no re-initialization)
    let value2 = provider.get().await.unwrap();
    assert_eq!(value2, "heavy-resource");
}

/// Test that warm_up initializes all lazy bindings concurrently
#[tokio::test]
#[cfg(feature = "di")]
async fn test_di_warm_up_initializes_lazy_bindings() {
    use allframe_core::di::LazyContainer;

    let mut container = LazyContainer::new();

    let init_order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

    let order1 = init_order.clone();
    container.register_lazy::<String, _, _>("service_a", move || {
        let order = order1.clone();
        async move {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            order.lock().unwrap().push("a");
            Ok("service_a".to_string())
        }
    });

    let order2 = init_order.clone();
    container.register_lazy::<i32, _, _>("service_b", move || {
        let order = order2.clone();
        async move {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            order.lock().unwrap().push("b");
            Ok(42i32)
        }
    });

    // Warm up initializes all concurrently
    container.warm_up().await.unwrap();

    // Both should be initialized
    let order = init_order.lock().unwrap();
    assert_eq!(order.len(), 2);
}

/// Test thread safety of lazy initialization under concurrent access
#[tokio::test]
#[cfg(feature = "di")]
async fn test_di_lazy_concurrent_get_no_double_init() {
    use allframe_core::di::LazyProvider;

    let init_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
    let count = init_count.clone();

    let provider = std::sync::Arc::new(LazyProvider::new(move || {
        let count = count.clone();
        async move {
            count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            Ok::<_, allframe_core::di::DependencyError>(42i32)
        }
    }));

    // Launch 10 concurrent gets
    let mut handles = vec![];
    for _ in 0..10 {
        let p = provider.clone();
        handles.push(tokio::spawn(async move { p.get().await.unwrap() }));
    }

    for h in handles {
        assert_eq!(h.await.unwrap(), 42);
    }

    // Should only have initialized once
    assert_eq!(
        init_count.load(std::sync::atomic::Ordering::SeqCst),
        1
    );
}

// =============================================================================
// UC-036.7: Saga Compensation with Local Rollback
// =============================================================================

/// Test saga with in-memory steps (existing behavior, baseline)
#[tokio::test]
async fn test_saga_compensation_baseline() {
    struct SuccessStep;

    #[async_trait::async_trait]
    impl OrchestratorSagaStep<DocumentEvent> for SuccessStep {
        async fn execute(&self) -> Result<Vec<DocumentEvent>, String> {
            Ok(vec![DocumentEvent::Created {
                doc_id: "saga-doc".into(),
                title: "Saga Created".into(),
            }])
        }

        async fn compensate(&self) -> Result<Vec<DocumentEvent>, String> {
            Ok(vec![DocumentEvent::Deleted])
        }

        fn name(&self) -> &str {
            "SuccessStep"
        }
    }

    struct FailStep;

    #[async_trait::async_trait]
    impl OrchestratorSagaStep<DocumentEvent> for FailStep {
        async fn execute(&self) -> Result<Vec<DocumentEvent>, String> {
            Err("simulated failure".into())
        }

        async fn compensate(&self) -> Result<Vec<DocumentEvent>, String> {
            Ok(vec![])
        }

        fn name(&self) -> &str {
            "FailStep"
        }
    }

    let orchestrator = SagaOrchestrator::<DocumentEvent>::new();

    let saga = SagaDefinition::new("test-compensation")
        .add_step(SuccessStep)
        .add_step(FailStep);

    let result = orchestrator.execute(saga).await;
    assert!(result.is_err());
}

/// Test FileSnapshot compensation primitive for saga local rollback
#[tokio::test]
#[cfg(feature = "cqrs")]
async fn test_saga_file_snapshot_compensation() {
    use allframe_core::cqrs::FileSnapshot;

    let dir = tempfile::tempdir().unwrap();
    let file_path = dir.path().join("document.txt");

    // Write initial content
    std::fs::write(&file_path, "original content").unwrap();

    // Create a snapshot before modification
    let snapshot = FileSnapshot::capture(&file_path).await.unwrap();

    // Modify the file
    std::fs::write(&file_path, "modified content").unwrap();
    assert_eq!(
        std::fs::read_to_string(&file_path).unwrap(),
        "modified content"
    );

    // Restore from snapshot (compensation)
    snapshot.restore().await.unwrap();
    assert_eq!(
        std::fs::read_to_string(&file_path).unwrap(),
        "original content"
    );
}

/// Test SqliteSavepoint compensation primitive for saga local rollback
#[tokio::test]
#[cfg(feature = "cqrs-sqlite")]
async fn test_saga_sqlite_savepoint_compensation() {
    use allframe_core::cqrs::SqliteSavepoint;

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("saga_test.db");

    // Setup: create a SQLite database with a table
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    conn.execute(
        "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)",
        [],
    )
    .unwrap();
    conn.execute(
        "INSERT INTO items (id, name) VALUES (1, 'original')",
        [],
    )
    .unwrap();

    // Create savepoint
    let savepoint = SqliteSavepoint::create(&conn, "saga_step_1").unwrap();

    // Modify data
    conn.execute("UPDATE items SET name = 'modified' WHERE id = 1", [])
        .unwrap();

    // Rollback to savepoint (compensation)
    savepoint.rollback().unwrap();

    // Data should be restored
    let name: String = conn
        .query_row("SELECT name FROM items WHERE id = 1", [], |row| {
            row.get(0)
        })
        .unwrap();
    assert_eq!(name, "original");
}

/// Test saga with file write step and automatic compensation on failure
#[tokio::test]
#[cfg(feature = "cqrs")]
async fn test_saga_local_rollback_on_failure() {
    use allframe_core::cqrs::{CompensationStrategy, WriteFileStep};

    let dir = tempfile::tempdir().unwrap();
    let file_path = dir.path().join("saga_output.txt");

    // Write initial content
    std::fs::write(&file_path, "original").unwrap();

    struct AlwaysFailStep;

    #[async_trait::async_trait]
    impl OrchestratorSagaStep<DocumentEvent> for AlwaysFailStep {
        async fn execute(&self) -> Result<Vec<DocumentEvent>, String> {
            Err("intentional failure".into())
        }
        async fn compensate(&self) -> Result<Vec<DocumentEvent>, String> {
            Ok(vec![])
        }
        fn name(&self) -> &str {
            "AlwaysFailStep"
        }
    }

    let saga = SagaDefinition::new("file-write-saga")
        .add_step(WriteFileStep::new(
            file_path.clone(),
            "modified by saga".to_string(),
        ))
        .add_step(AlwaysFailStep)
        .with_compensation(CompensationStrategy::LocalRollback);

    let orchestrator = SagaOrchestrator::new();
    let result = orchestrator.execute(saga).await;

    // Saga failed
    assert!(result.is_err());

    // File should be restored to original content (compensation ran)
    assert_eq!(
        std::fs::read_to_string(&file_path).unwrap(),
        "original"
    );
}

/// Test that compensation cleanup removes snapshots after successful saga
#[tokio::test]
#[cfg(feature = "cqrs")]
async fn test_saga_compensation_cleanup_on_success() {
    use allframe_core::cqrs::{CompensationStrategy, WriteFileStep};

    let dir = tempfile::tempdir().unwrap();
    let snapshot_dir = dir.path().join(".saga_snapshots");

    // Run a successful saga with file steps
    let saga = SagaDefinition::<DocumentEvent>::new("cleanup-test")
        .add_step(WriteFileStep::new(
            dir.path().join("output.txt"),
            "success".to_string(),
        ))
        .with_compensation(CompensationStrategy::LocalRollback)
        .with_snapshot_dir(&snapshot_dir);

    let orchestrator = SagaOrchestrator::new();
    orchestrator.execute(saga).await.unwrap();

    // Snapshot directory should be empty or removed after success
    assert!(
        !snapshot_dir.exists()
            || std::fs::read_dir(&snapshot_dir).unwrap().count() == 0
    );
}

// =============================================================================
// Integration: Full offline-first CQRS flow
// =============================================================================

/// Test full offline CQRS flow: Command → Event → Store → Projection → Query
#[tokio::test]
async fn test_full_offline_cqrs_flow_with_in_memory() {
    use allframe_macros::{command, command_handler, query, query_handler};

    #[command]
    struct CreateDocumentCommand {
        doc_id: String,
        title: String,
    }

    #[command_handler]
    async fn handle_create_document(
        cmd: CreateDocumentCommand,
        store: &EventStore<DocumentEvent>,
    ) -> Result<(), String> {
        store
            .append(
                &cmd.doc_id,
                vec![DocumentEvent::Created {
                    doc_id: cmd.doc_id.clone(),
                    title: cmd.title.clone(),
                }],
            )
            .await?;
        Ok(())
    }

    #[query]
    struct GetDocumentQuery {
        doc_id: String,
    }

    #[query_handler]
    async fn handle_get_document(
        query: GetDocumentQuery,
        projection: &DocumentProjection,
    ) -> Option<DocumentView> {
        projection.documents.get(&query.doc_id).cloned()
    }

    let store = EventStore::new();
    let mut projection = DocumentProjection {
        documents: HashMap::new(),
    };

    handle_create_document(
        CreateDocumentCommand {
            doc_id: "doc-offline-1".into(),
            title: "Offline Document".into(),
        },
        &store,
    )
    .await
    .unwrap();

    let events = store.get_all_events().await.unwrap();
    for event in &events {
        projection.apply(event);
    }

    let doc = handle_get_document(
        GetDocumentQuery {
            doc_id: "doc-offline-1".into(),
        },
        &projection,
    )
    .await;

    assert!(doc.is_some());
    assert_eq!(doc.unwrap().title, "Offline Document");
}

/// Test aggregate rebuild from event store (offline pattern)
#[tokio::test]
async fn test_aggregate_rebuild_from_event_store_offline() {
    let store = EventStore::new();

    store
        .append(
            "doc-1",
            vec![DocumentEvent::Created {
                doc_id: "doc-1".into(),
                title: "Initial".into(),
            }],
        )
        .await
        .unwrap();

    store
        .append(
            "doc-1",
            vec![DocumentEvent::Updated {
                title: "Revised".into(),
                content: "Some content".into(),
            }],
        )
        .await
        .unwrap();

    store
        .append(
            "doc-1",
            vec![
                DocumentEvent::TagAdded {
                    tag: "rust".into(),
                },
                DocumentEvent::TagAdded {
                    tag: "offline".into(),
                },
            ],
        )
        .await
        .unwrap();

    let events = store.get_events("doc-1").await.unwrap();
    let mut aggregate = DocumentAggregate::default();
    for event in &events {
        aggregate.apply_event(event);
    }

    assert_eq!(aggregate.title, "Revised");
    assert_eq!(aggregate.content, "Some content");
    assert_eq!(aggregate.tags, vec!["rust", "offline"]);
    assert_eq!(aggregate.version, 4);
    assert!(!aggregate.is_deleted);
}

/// Test snapshot + replay pattern for offline performance
#[tokio::test]
async fn test_snapshot_replay_pattern_for_offline_performance() {
    let store = EventStore::new();

    let mut events_batch = Vec::new();
    for i in 0..500 {
        events_batch.push(DocumentEvent::TagAdded {
            tag: format!("tag-{}", i),
        });
    }
    store
        .append(
            "doc-1",
            std::iter::once(DocumentEvent::Created {
                doc_id: "doc-1".into(),
                title: "Tagged Doc".into(),
            })
            .chain(events_batch)
            .collect(),
        )
        .await
        .unwrap();

    let all_events = store.get_events("doc-1").await.unwrap();
    let mut aggregate = DocumentAggregate::default();
    for event in &all_events {
        aggregate.apply_event(&event);
    }
    assert_eq!(aggregate.version, 501);

    let snapshot = Snapshot::create(aggregate.clone(), 501);

    store
        .append(
            "doc-1",
            vec![DocumentEvent::TagAdded {
                tag: "new-tag".into(),
            }],
        )
        .await
        .unwrap();

    // Rebuild from snapshot + only new events
    let mut rebuilt = snapshot.into_aggregate();
    let new_events = store.get_events_after("doc-1", 501).await.unwrap();
    for event in &new_events {
        rebuilt.apply_event(&event);
    }

    assert_eq!(rebuilt.version, 502);
    assert_eq!(rebuilt.tags.len(), 501); // 500 original + 1 new
    assert_eq!(rebuilt.tags.last().unwrap(), "new-tag");
}

/// Test event subscription for real-time local projections (offline-capable)
#[tokio::test]
async fn test_event_subscription_for_offline_projections() {
    let store = EventStore::new();
    let (tx, mut rx) = tokio::sync::mpsc::channel::<DocumentEvent>(100);
    store.subscribe(tx).await;

    store
        .append(
            "doc-1",
            vec![DocumentEvent::Created {
                doc_id: "doc-1".into(),
                title: "Subscribed Doc".into(),
            }],
        )
        .await
        .unwrap();

    let received = rx.recv().await.unwrap();
    assert!(matches!(
        received,
        DocumentEvent::Created { title, .. } if title == "Subscribed Doc"
    ));
}