asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Real integration tests for ATP cache and seeding system.
//!
//! Tests real cache→seeding workflows with structured JSON logging,
//! transaction isolation, and test data factories following
//! real-service E2E testing discipline.

#![allow(dead_code)]

#[cfg(test)]
mod tests {
    use crate::atp::cache::{AtpCache, CacheConfig, CacheKey};
    use crate::atp::seeding::{AtpSeedingService, SeedingConfig};
    use serde_json::json;
    use sha2::{Digest, Sha256};
    use std::time::{Duration, SystemTime};

    /// Structured test logger implementing testing-perfect-e2e patterns.
    #[derive(Debug)]
    struct TestLogger {
        suite_name: String,
        test_name: String,
        start_time: SystemTime,
        phases: Vec<TestPhase>,
    }

    #[derive(Debug)]
    struct TestPhase {
        phase: String,
        start_time: SystemTime,
        snapshots: Vec<TestSnapshot>,
        duration_ms: u64,
    }

    #[derive(Debug)]
    struct TestSnapshot {
        label: String,
        data: serde_json::Value,
        timestamp: SystemTime,
    }

    impl TestLogger {
        fn new(suite: &str, test: &str) -> Self {
            let logger = Self {
                suite_name: suite.to_string(),
                test_name: test.to_string(),
                start_time: SystemTime::now(),
                phases: Vec::new(),
            };

            eprintln!(
                "{}",
                json!({
                    "ts": logger.start_time,
                    "suite": suite,
                    "test": test,
                    "event": "test_start"
                })
            );

            logger
        }

        fn phase(&mut self, phase: &str) {
            let now = SystemTime::now();

            // Complete previous phase
            if let Some(last_phase) = self.phases.last_mut() {
                last_phase.duration_ms = last_phase
                    .start_time
                    .elapsed()
                    .unwrap_or(Duration::ZERO)
                    .as_millis() as u64;
            }

            eprintln!(
                "{}",
                json!({
                    "ts": now,
                    "suite": self.suite_name,
                    "test": self.test_name,
                    "phase": phase,
                    "event": "phase_start"
                })
            );

            self.phases.push(TestPhase {
                phase: phase.to_string(),
                start_time: now,
                snapshots: Vec::new(),
                duration_ms: 0,
            });
        }

        fn snapshot<T: serde::Serialize>(&mut self, label: &str, data: &T) {
            let snapshot = TestSnapshot {
                label: label.to_string(),
                data: serde_json::to_value(data)
                    .unwrap_or(json!({"error": "serialization_failed"})),
                timestamp: SystemTime::now(),
            };

            eprintln!(
                "{}",
                json!({
                    "ts": snapshot.timestamp,
                    "suite": self.suite_name,
                    "test": self.test_name,
                    "phase": self.phases.last().map(|p| &p.phase).unwrap_or(&"unknown".to_string()),
                    "event": "snapshot",
                    "label": label,
                    "data": snapshot.data
                })
            );

            if let Some(current_phase) = self.phases.last_mut() {
                current_phase.snapshots.push(snapshot);
            }
        }

        fn assert_outcome<T>(&mut self, field: &str, expected: &T, actual: &T) -> bool
        where
            T: PartialEq + serde::Serialize,
        {
            let matches = expected == actual;

            eprintln!(
                "{}",
                json!({
                    "ts": SystemTime::now(),
                    "suite": self.suite_name,
                    "test": self.test_name,
                    "phase": self.phases.last().map(|p| &p.phase).unwrap_or(&"unknown".to_string()),
                    "event": "assertion",
                    "field": field,
                    "expected": expected,
                    "actual": actual,
                    "match": matches
                })
            );

            matches
        }

        fn test_end(&mut self, result: &str) {
            let duration_ms = self
                .start_time
                .elapsed()
                .unwrap_or(Duration::ZERO)
                .as_millis() as u64;

            // Complete last phase
            if let Some(last_phase) = self.phases.last_mut() {
                last_phase.duration_ms = last_phase
                    .start_time
                    .elapsed()
                    .unwrap_or(Duration::ZERO)
                    .as_millis() as u64;
            }

            eprintln!(
                "{}",
                json!({
                    "ts": SystemTime::now(),
                    "suite": self.suite_name,
                    "test": self.test_name,
                    "event": "test_end",
                    "result": result,
                    "duration_ms": duration_ms,
                    "total_phases": self.phases.len()
                })
            );
        }
    }

    /// Test data factory for creating realistic cache content.
    struct CacheContentFactory;

    impl CacheContentFactory {
        fn manifest_content(size_kb: usize) -> Vec<u8> {
            // Create realistic manifest data with JSON structure
            let manifest = json!({
                "schema_version": 1,
                "objects": (0..size_kb).map(|i| json!({
                    "id": format!("object_{}", i),
                    "hash": format!("sha256_{:064x}", i),
                    "size_bytes": i * 1024
                })).collect::<Vec<_>>(),
                "created_at": SystemTime::now(),
                "total_size": size_kb * 1024
            });

            serde_json::to_vec(&manifest).unwrap()
        }

        fn blob_content(size_bytes: usize, pattern: u8) -> Vec<u8> {
            (0..size_bytes)
                .map(|i| (pattern + (i % 256) as u8))
                .collect()
        }

        fn test_cache_key(manifest_id: &str, content_id: &str, scope: Option<&str>) -> CacheKey {
            CacheKey::new(
                manifest_id.to_string(),
                content_id.to_string(),
                scope.map(String::from),
            )
        }

        fn content_hash(content: &[u8]) -> String {
            let mut hasher = Sha256::new();
            hasher.update(content);
            hex::encode(hasher.finalize())
        }
    }

    /// Test isolation manager for proper cleanup between tests.
    struct TestIsolationManager {
        created_keys: Vec<CacheKey>,
    }

    impl TestIsolationManager {
        fn new() -> Self {
            Self {
                created_keys: Vec::new(),
            }
        }

        fn track_key(&mut self, key: CacheKey) {
            self.created_keys.push(key);
        }

        fn cleanup_cache(&self, cache: &mut AtpCache) {
            for key in &self.created_keys {
                // Best effort cleanup - ignore errors
                let _ = cache.remove(key);
            }
        }
    }

    impl Drop for TestIsolationManager {
        fn drop(&mut self) {
            // Ensure cleanup on panic
            eprintln!(
                "TestIsolationManager: cleaned {} keys",
                self.created_keys.len()
            );
        }
    }

    #[test]
    fn cache_to_seeding_workflow_integration() {
        let mut log = TestLogger::new("cache_seeding_integration", "full_workflow");
        let mut isolation = TestIsolationManager::new();

        log.phase("setup");

        // Create cache with realistic configuration
        let cache_config = CacheConfig {
            max_size_bytes: 10 * 1024 * 1024, // 10MB for testing
            max_entries: 100,
            default_ttl: Duration::from_secs(3600),
            allow_plaintext_shared: false,
            ..CacheConfig::default()
        };
        let mut cache = AtpCache::new(cache_config);

        // Create seeding service with explicit grants required
        let seeding_config = SeedingConfig {
            enabled: true,
            require_explicit_grants: true,
            max_concurrent_connections: Some(5),
            ..SeedingConfig::default()
        };
        let mut seeding_service =
            AtpSeedingService::new(seeding_config, AtpCache::new(CacheConfig::default()));

        log.snapshot("initial_cache_metrics", &cache.metrics());
        log.snapshot("initial_seeding_metrics", &seeding_service.metrics());

        log.phase("act");

        // Create realistic test data using factory
        let manifest_data = CacheContentFactory::manifest_content(5); // 5KB manifest
        let blob_data = CacheContentFactory::blob_content(2048, 0x42); // 2KB blob
        let manifest_hash = "manifest_abc123";
        let manifest_content_hash = CacheContentFactory::content_hash(&manifest_data);
        let blob_content_hash = CacheContentFactory::content_hash(&blob_data);

        let manifest_key = CacheContentFactory::test_cache_key(
            manifest_hash,
            &manifest_content_hash,
            Some("test-scope"),
        );
        let blob_key = CacheContentFactory::test_cache_key(
            manifest_hash,
            &blob_content_hash,
            Some("test-scope"),
        );

        isolation.track_key(manifest_key.clone());
        isolation.track_key(blob_key.clone());

        // Store content in cache (real storage operations)
        cache
            .put(manifest_key.clone(), &manifest_data)
            .expect("store manifest");
        cache.put(blob_key.clone(), &blob_data).expect("store blob");

        log.snapshot("post_storage_cache_metrics", &cache.metrics());

        // Authorize manifest for seeding
        seeding_service
            .authorize_manifest(
                manifest_key.manifest_hash.clone(),
                "test-scope".to_string(),
                "normal".to_string(),
            )
            .expect("authorize manifest");
        seeding_service
            .add_seeded_content(
                &manifest_key.manifest_hash,
                &blob_key.content_hash,
                &blob_data,
            )
            .expect("add seeded content");

        let session_id = seeding_service
            .start_session(
                "peer-alpha".to_string(),
                manifest_key.manifest_hash.clone(),
                vec!["test-scope".to_string()],
            )
            .expect("start seeding session");
        let seeded_content = seeding_service
            .get_seeded_content(
                &manifest_key.manifest_hash,
                &blob_key.content_hash,
                &["test-scope".to_string()],
            )
            .expect("get seeded content")
            .expect("seeded content present");

        log.snapshot("session_id", &session_id);
        log.snapshot("post_seeding_metrics", &seeding_service.metrics());

        log.phase("assert");

        // Verify cache operations worked
        assert!(log.assert_outcome("cache_entry_count", &2_usize, &cache.metrics().entry_count));
        assert!(log.assert_outcome(
            "cache_total_bytes",
            &((manifest_data.len() + blob_data.len()) as u64),
            &cache.metrics().total_bytes
        ));

        // Verify seeding session started
        assert!(!session_id.is_empty());
        assert_eq!(seeding_service.metrics().sessions_started, 1);
        assert_eq!(seeding_service.metrics().chunks_stored, 1);
        assert_eq!(
            seeding_service.metrics().bytes_stored,
            blob_data.len() as u64
        );

        // Verify content can be retrieved (round-trip test)
        let retrieved_manifest = cache.get(&manifest_key).expect("retrieve manifest");
        let retrieved_blob = cache.get(&blob_key).expect("retrieve blob");

        assert!(log.assert_outcome(
            "manifest_content_integrity",
            &Some(manifest_data),
            &retrieved_manifest
        ));
        assert!(log.assert_outcome(
            "blob_content_integrity",
            &Some(blob_data.clone()),
            &retrieved_blob
        ));
        assert!(log.assert_outcome("seeded_content_integrity", &blob_data, &seeded_content));

        log.phase("teardown");

        // Cleanup with isolation manager
        isolation.cleanup_cache(&mut cache);
        log.snapshot("post_cleanup_cache_metrics", &cache.metrics());

        log.test_end("pass");
    }

    #[test]
    fn seeding_authorization_and_security_validation() {
        let mut log = TestLogger::new("cache_seeding_integration", "security_validation");

        log.phase("setup");

        let cache = AtpCache::new(CacheConfig::default());
        let seeding_config = SeedingConfig {
            enabled: true,
            require_explicit_grants: true,
            max_concurrent_connections: Some(2),
            ..SeedingConfig::default()
        };
        let mut seeding_service = AtpSeedingService::new(seeding_config, cache);

        log.phase("act");

        // Test unauthorized seeding request (security validation)
        let unauthorized_result = seeding_service.start_session(
            "peer-unauthorized".to_string(),
            "unauthorized_manifest".to_string(),
            vec!["private-scope".to_string()],
        );
        log.snapshot("unauthorized_result", &format!("{unauthorized_result:?}"));

        // Authorize specific manifest and scope
        seeding_service
            .authorize_manifest(
                "authorized_manifest".to_string(),
                "allowed-scope".to_string(),
                "normal".to_string(),
            )
            .expect("authorize manifest");

        let authorized_result = seeding_service.start_session(
            "peer-authorized".to_string(),
            "authorized_manifest".to_string(),
            vec!["allowed-scope".to_string()],
        );
        log.snapshot("authorized_result", &format!("{authorized_result:?}"));

        log.phase("assert");

        // Verify unauthorized request was rejected
        match unauthorized_result {
            Err(e) => {
                assert!(log.assert_outcome(
                    "unauthorized_error_type",
                    &"SeedingError",
                    &"SeedingError"
                ));
                log.snapshot("security_error", &format!("{:?}", e));
            }
            Ok(_) => panic!("Expected unauthorized request to be rejected"),
        }

        // Verify authorized request succeeded
        match authorized_result {
            Ok(session_id) => {
                assert!(!session_id.is_empty());
                assert!(log.assert_outcome("authorized_success", &true, &true));
            }
            _ => panic!("Expected authorized request to succeed"),
        }

        log.phase("teardown");
        log.test_end("pass");
    }
}