dcontext-dactor 0.8.0

Automatic dcontext propagation through dactor actor messages
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
use dactor::{
    ActorContext, ActorId, Disposition, HeaderRegistry, HeaderValue, Headers, InboundContext,
    InboundInterceptor, NodeId, OutboundContext, OutboundInterceptor, RuntimeHeaders, SendMode,
};
use dcontext::ContextSnapshot;

use crate::header::{ContextHeader, ContextSnapshotHeader};
use crate::inbound::ContextInboundInterceptor;
use crate::outbound::ContextOutboundInterceptor;
use crate::propagation::{bytes_to_snapshot, extract_context};
use crate::ErrorPolicy;

// ── Test context type ──────────────────────────────────────────

#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct RequestId(String);

fn init_registry() {
    let mut builder = dcontext::RegistryBuilder::new();
    builder.register::<RequestId>("request_id");
    let _ = dcontext::try_initialize(builder);
}

// ── Header tests ───────────────────────────────────────────────

#[test]
fn context_header_has_wire_bytes() {
    let header = ContextHeader {
        bytes: vec![1, 2, 3],
    };
    assert_eq!(header.header_name(), "dcontext.wire");
    assert_eq!(header.to_bytes(), Some(vec![1, 2, 3]));
}

#[test]
fn snapshot_header_is_local_only() {
    let header = ContextSnapshotHeader {
        snapshot: ContextSnapshot::empty(),
    };
    assert_eq!(header.header_name(), "dcontext.snapshot");
    assert!(
        header.to_bytes().is_none(),
        "snapshot header should be local-only"
    );
}

// ── Outbound interceptor tests ─────────────────────────────────

fn make_outbound_ctx(remote: bool) -> OutboundContext<'static> {
    OutboundContext {
        target_id: ActorId {
            node: NodeId("test-node".into()),
            local: 1,
        },
        target_name: "test-actor",
        message_type: "TestMsg",
        send_mode: SendMode::Tell,
        remote,
    }
}

#[test]
fn outbound_remote_attaches_wire_header_only() {
    init_registry();

    let interceptor = ContextOutboundInterceptor::default();
    let ctx = make_outbound_ctx(true);
    let rh = RuntimeHeaders::new();
    let mut headers = Headers::new();
    let msg = 42u64;

    let disposition = interceptor.on_send(&ctx, &rh, &mut headers, &msg);
    assert!(matches!(disposition, Disposition::Continue));

    assert!(
        headers.get::<ContextHeader>().is_some(),
        "remote should have wire header"
    );
    assert!(
        headers.get::<ContextSnapshotHeader>().is_none(),
        "remote should not have snapshot header"
    );
}

#[tokio::test]
async fn outbound_local_attaches_snapshot_only() {
    init_registry();

    dcontext::async_ctx::with_context(ContextSnapshot::empty(), async {
        dcontext::async_ctx::set_context("request_id", RequestId("req-abc".into()));

        let interceptor = ContextOutboundInterceptor::default();
        let ctx = make_outbound_ctx(false);
        let rh = RuntimeHeaders::new();
        let mut headers = Headers::new();
        let msg = 42u64;

        let disposition = interceptor.on_send(&ctx, &rh, &mut headers, &msg);
        assert!(matches!(disposition, Disposition::Continue));

        assert!(
            headers.get::<ContextSnapshotHeader>().is_some(),
            "local should have snapshot header"
        );
        assert!(
            headers.get::<ContextHeader>().is_none(),
            "local should NOT have wire header — no serialization needed"
        );
    })
    .await;
}

// ── Error policy tests ─────────────────────────────────────────

#[test]
fn outbound_reject_policy_rejects_on_serialization_error() {
    // Don't init_registry — serialization will fail for unregistered types.
    // But serialize_context() won't fail because it only serializes what's
    // in the context. To test rejection, we need to trigger a real error.
    // serialize_context only fails on bincode/size errors which are hard to
    // trigger, so we test the policy plumbing via the inbound interceptor
    // which is easier to trigger with corrupt bytes.

    let interceptor = ContextOutboundInterceptor::new(ErrorPolicy::Reject);
    assert_eq!(interceptor.name(), "dcontext-outbound");
}

#[test]
fn inbound_log_and_continue_on_corrupt_bytes() {
    init_registry();

    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let rh = RuntimeHeaders::new();
    let mut headers = Headers::new();
    let msg = 42u64;

    headers.insert(ContextHeader {
        bytes: vec![0xFF, 0xFE, 0xFD],
    });

    let disposition = interceptor.on_receive(&ctx, &rh, &mut headers, &msg);
    assert!(
        matches!(disposition, Disposition::Continue),
        "LogAndContinue should not reject"
    );
    assert!(
        headers.get::<ContextSnapshotHeader>().is_none(),
        "corrupt bytes should not produce a snapshot"
    );
}

#[test]
fn inbound_reject_policy_rejects_on_corrupt_bytes() {
    init_registry();

    let interceptor = ContextInboundInterceptor::new(ErrorPolicy::Reject);
    let ctx = make_inbound_ctx();
    let rh = RuntimeHeaders::new();
    let mut headers = Headers::new();
    let msg = 42u64;

    headers.insert(ContextHeader {
        bytes: vec![0xFF, 0xFE, 0xFD],
    });

    let disposition = interceptor.on_receive(&ctx, &rh, &mut headers, &msg);
    assert!(
        matches!(disposition, Disposition::Reject(_)),
        "Reject policy should reject on corrupt bytes"
    );
}

// ── Inbound interceptor tests ──────────────────────────────────

fn make_inbound_ctx() -> InboundContext<'static> {
    InboundContext {
        actor_id: ActorId {
            node: NodeId("test-node".into()),
            local: 1,
        },
        actor_name: "test-actor",
        message_type: "TestMsg",
        send_mode: SendMode::Tell,
        remote: false,
        origin_node: None,
    }
}

#[test]
fn inbound_interceptor_preserves_existing_snapshot() {
    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let rh = RuntimeHeaders::new();
    let mut headers = Headers::new();
    let msg = 42u64;

    headers.insert(ContextSnapshotHeader {
        snapshot: ContextSnapshot::empty(),
    });

    let disposition = interceptor.on_receive(&ctx, &rh, &mut headers, &msg);
    assert!(matches!(disposition, Disposition::Continue));
    assert!(headers.get::<ContextSnapshotHeader>().is_some());
}

#[test]
fn inbound_interceptor_converts_wire_to_snapshot() {
    init_registry();

    let wire_bytes = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("req-wire".into()));
        dcontext::sync_ctx::serialize_context().unwrap()
    };

    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let rh = RuntimeHeaders::new();
    let mut headers = Headers::new();
    let msg = 42u64;

    headers.insert(ContextHeader { bytes: wire_bytes });

    let disposition = interceptor.on_receive(&ctx, &rh, &mut headers, &msg);
    assert!(matches!(disposition, Disposition::Continue));
    assert!(
        headers.get::<ContextSnapshotHeader>().is_some(),
        "inbound interceptor should convert wire bytes to snapshot"
    );
}

// ── bytes_to_snapshot tests ────────────────────────────────────

#[test]
fn bytes_to_snapshot_roundtrip() {
    init_registry();

    let wire_bytes = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("roundtrip".into()));
        dcontext::sync_ctx::serialize_context().unwrap()
    };

    let snap = bytes_to_snapshot(&wire_bytes);
    assert!(
        snap.is_some(),
        "should produce a snapshot from valid wire bytes"
    );
}

#[test]
fn bytes_to_snapshot_invalid_bytes() {
    init_registry();

    let snap = bytes_to_snapshot(&[0xFF, 0xFE, 0xFD]);
    assert!(snap.is_none(), "invalid bytes should return None");
}

// ── extract_context tests ──────────────────────────────────────

#[test]
fn extract_context_prefers_snapshot() {
    let mut actor_ctx = ActorContext::new(
        ActorId {
            node: NodeId("n".into()),
            local: 1,
        },
        "test".into(),
    );

    actor_ctx.headers.insert(ContextSnapshotHeader {
        snapshot: ContextSnapshot::empty(),
    });
    actor_ctx.headers.insert(ContextHeader {
        bytes: vec![1, 2, 3],
    });

    let result = extract_context(&actor_ctx);
    assert!(result.is_some());
}

#[test]
fn extract_context_returns_none_when_empty() {
    let actor_ctx = ActorContext::new(
        ActorId {
            node: NodeId("n".into()),
            local: 1,
        },
        "test".into(),
    );

    let result = extract_context(&actor_ctx);
    assert!(result.is_none());
}

// ── End-to-end test: outbound → inbound → extract ──────────────

#[tokio::test]
async fn end_to_end_local_propagation() {
    init_registry();

    let (rh, msg, mut headers) =
        dcontext::async_ctx::with_context(ContextSnapshot::empty(), async {
            dcontext::async_ctx::set_context("request_id", RequestId("e2e-local".into()));

            // Outbound interceptor captures snapshot (no serialization for local).
            let outbound = ContextOutboundInterceptor::default();
            let out_ctx = make_outbound_ctx(false);
            let rh = RuntimeHeaders::new();
            let mut headers = Headers::new();
            let msg = 42u64;
            outbound.on_send(&out_ctx, &rh, &mut headers, &msg);
            (rh, msg, headers)
        })
        .await;

    // Verify no wire header was produced for local target.
    assert!(
        headers.get::<ContextHeader>().is_none(),
        "local should skip serialization"
    );
    assert!(headers.get::<ContextSnapshotHeader>().is_some());

    // Inbound interceptor — snapshot already present, nothing to convert.
    let inbound = ContextInboundInterceptor::default();
    let in_ctx = make_inbound_ctx();
    inbound.on_receive(&in_ctx, &rh, &mut headers, &msg);

    // Build a mock ActorContext with the headers.
    let mut actor_ctx = ActorContext::new(
        ActorId {
            node: NodeId("n".into()),
            local: 1,
        },
        "test".into(),
    );
    actor_ctx.headers = headers;

    // Extract and verify.
    let snap = extract_context(&actor_ctx).expect("should have propagated context");
    let _restore = dcontext::sync_ctx::attach(snap);
    let rid: RequestId = dcontext::sync_ctx::get_context("request_id").unwrap_or_default();
    assert_eq!(rid.0, "e2e-local");
}

#[test]
fn end_to_end_remote_propagation() {
    init_registry();

    // Simulate sender serializing context (remote path).
    let wire_bytes = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("e2e-remote".into()));
        dcontext::sync_ctx::serialize_context().unwrap()
    };

    // Simulate receiving wire bytes (as if from remote transport).
    let mut headers = Headers::new();
    headers.insert(ContextHeader { bytes: wire_bytes });

    // Inbound interceptor converts wire to snapshot.
    let inbound = ContextInboundInterceptor::default();
    let in_ctx = make_inbound_ctx();
    let rh = RuntimeHeaders::new();
    let msg = 42u64;
    inbound.on_receive(&in_ctx, &rh, &mut headers, &msg);

    let mut actor_ctx = ActorContext::new(
        ActorId {
            node: NodeId("n".into()),
            local: 1,
        },
        "test".into(),
    );
    actor_ctx.headers = headers;

    let snap = extract_context(&actor_ctx).expect("should have propagated context");
    let _restore = dcontext::sync_ctx::attach(snap);
    let rid: RequestId = dcontext::sync_ctx::get_context("request_id").unwrap_or_default();
    assert_eq!(rid.0, "e2e-remote");
}

// ── Async propagation test ─────────────────────────────────────

#[allow(deprecated)]
#[tokio::test]
async fn with_propagated_context_establishes_scope() {
    init_registry();

    let snap = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("async-test".into()));
        dcontext::sync_ctx::snapshot()
    };

    let mut actor_ctx = ActorContext::new(
        ActorId {
            node: NodeId("n".into()),
            local: 1,
        },
        "test".into(),
    );
    actor_ctx
        .headers
        .insert(ContextSnapshotHeader { snapshot: snap });

    let result = crate::with_propagated_context(&actor_ctx, async {
        let rid: RequestId = dcontext::async_ctx::get_context("request_id").unwrap_or_default();
        rid.0
    })
    .await;

    assert_eq!(result, "async-test");
}

#[allow(deprecated)]
#[tokio::test]
async fn with_propagated_context_passthrough_without_headers() {
    init_registry();

    let actor_ctx = ActorContext::new(
        ActorId {
            node: NodeId("n".into()),
            local: 1,
        },
        "test".into(),
    );

    let result = crate::with_propagated_context(&actor_ctx, async { 42 }).await;
    assert_eq!(result, 42);
}

// ── wrap_handler tests ─────────────────────────────────────────

#[test]
fn wrap_handler_returns_some_when_snapshot_present() {
    init_registry();

    let snap = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("wrap-test".into()));
        dcontext::sync_ctx::snapshot()
    };

    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let mut headers = Headers::new();
    headers.insert(ContextSnapshotHeader { snapshot: snap });

    let wrapper = interceptor.wrap_handler(&ctx, &headers);
    assert!(
        wrapper.is_some(),
        "wrap_handler should return Some when snapshot header is present"
    );
}

#[test]
fn wrap_handler_returns_none_when_no_context() {
    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let headers = Headers::new();

    let wrapper = interceptor.wrap_handler(&ctx, &headers);
    assert!(
        wrapper.is_none(),
        "wrap_handler should return None when no context headers"
    );
}

#[tokio::test]
async fn wrap_handler_restores_context_in_handler_future() {
    init_registry();

    let snap = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("auto-restore".into()));
        dcontext::sync_ctx::snapshot()
    };

    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let mut headers = Headers::new();
    headers.insert(ContextSnapshotHeader { snapshot: snap });

    let wrapper = interceptor.wrap_handler(&ctx, &headers).unwrap();

    // Simulate what the runtime does: wrap the handler future
    use std::sync::Arc;
    use tokio::sync::Mutex;

    let captured = Arc::new(Mutex::new(String::new()));
    let captured_clone = captured.clone();

    let inner: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> =
        Box::pin(async move {
            let rid: RequestId = dcontext::async_ctx::get_context("request_id").unwrap_or_default();
            *captured_clone.lock().await = rid.0;
        });

    let wrapped = wrapper(inner);
    wrapped.await;

    assert_eq!(*captured.lock().await, "auto-restore");
}

#[tokio::test]
async fn wrap_handler_no_context_passthrough() {
    init_registry();

    let interceptor = ContextInboundInterceptor::default();
    let ctx = make_inbound_ctx();
    let headers = Headers::new();

    // Should return None — no wrapping needed
    let wrapper = interceptor.wrap_handler(&ctx, &headers);
    assert!(wrapper.is_none());

    // The handler future runs as-is (no context scope)
    let result = async { 42 }.await;
    assert_eq!(result, 42);
}

#[tokio::test]
async fn wrap_handler_end_to_end_local() {
    init_registry();

    // Simulate: sender sets context → outbound captures → inbound normalizes → wrap_handler restores
    let snap = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("e2e-wrap-local".into()));
        dcontext::sync_ctx::snapshot()
    };

    // Outbound would capture snapshot for local target; simulate directly.
    let rh = RuntimeHeaders::new();
    let mut headers = Headers::new();
    let msg = 42u64;

    // Insert snapshot directly (simulates what outbound does for local targets)
    headers.insert(ContextSnapshotHeader { snapshot: snap });

    // Inbound: on_receive normalizes, wrap_handler wraps
    let inbound = ContextInboundInterceptor::default();
    let in_ctx = make_inbound_ctx();
    inbound.on_receive(&in_ctx, &rh, &mut headers, &msg);

    let wrapper = inbound.wrap_handler(&in_ctx, &headers);
    assert!(wrapper.is_some(), "should wrap for local context");

    let wrapper = wrapper.unwrap();

    use std::sync::Arc;
    use tokio::sync::Mutex;

    let captured = Arc::new(Mutex::new(String::new()));
    let captured_clone = captured.clone();

    let inner: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> =
        Box::pin(async move {
            let rid: RequestId = dcontext::async_ctx::get_context("request_id").unwrap_or_default();
            *captured_clone.lock().await = rid.0;
        });

    let wrapped = wrapper(inner);
    wrapped.await;

    assert_eq!(*captured.lock().await, "e2e-wrap-local");
}

#[tokio::test]
async fn wrap_handler_end_to_end_remote() {
    init_registry();

    // Simulate remote path: wire bytes → inbound deserializes → wrap_handler restores
    let wire_bytes = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("e2e-wrap-remote".into()));
        dcontext::sync_ctx::serialize_context().unwrap()
    };

    let mut headers = Headers::new();
    headers.insert(ContextHeader { bytes: wire_bytes });

    let inbound = ContextInboundInterceptor::default();
    let in_ctx = make_inbound_ctx();
    let rh = RuntimeHeaders::new();
    let msg = 42u64;
    inbound.on_receive(&in_ctx, &rh, &mut headers, &msg);

    let wrapper = inbound.wrap_handler(&in_ctx, &headers);
    assert!(wrapper.is_some(), "should wrap for remote context");

    let wrapper = wrapper.unwrap();

    use std::sync::Arc;
    use tokio::sync::Mutex;

    let captured = Arc::new(Mutex::new(String::new()));
    let captured_clone = captured.clone();

    let inner: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> =
        Box::pin(async move {
            let rid: RequestId = dcontext::async_ctx::get_context("request_id").unwrap_or_default();
            *captured_clone.lock().await = rid.0;
        });

    let wrapped = wrapper(inner);
    wrapped.await;

    assert_eq!(*captured.lock().await, "e2e-wrap-remote");
}

// ── Wire round-trip via HeaderRegistry ─────────────────────────

#[test]
fn register_context_headers_enables_wire_roundtrip() {
    init_registry();

    // Serialize context to wire bytes.
    let wire_bytes = {
        let _guard = dcontext::sync_ctx::enter_scope();
        dcontext::sync_ctx::set_context("request_id", RequestId("wire-roundtrip".into()));
        dcontext::sync_ctx::serialize_context().unwrap()
    };

    // Outbound: insert ContextHeader into Headers, then convert to wire format.
    let mut headers = Headers::new();
    headers.insert(ContextHeader { bytes: wire_bytes });
    let wire_headers = headers.to_wire();

    // Simulate remote transport: wire_headers arrive on receiver side.
    // Register the deserializer and reconstruct typed headers.
    let mut header_registry = HeaderRegistry::new();
    crate::register_context_headers(&mut header_registry);

    let restored_headers = wire_headers.to_headers(&header_registry);
    assert!(
        restored_headers.get::<ContextHeader>().is_some(),
        "ContextHeader should be reconstructed from wire bytes via HeaderRegistry"
    );

    // Verify the restored header has correct content.
    let restored = restored_headers.get::<ContextHeader>().unwrap();
    let snap = bytes_to_snapshot(&restored.bytes);
    assert!(
        snap.is_some(),
        "restored wire bytes should deserialize to a valid snapshot"
    );

    let snap = snap.unwrap();
    let _restore = dcontext::sync_ctx::attach(snap);
    let rid: RequestId = dcontext::sync_ctx::get_context("request_id").unwrap_or_default();
    assert_eq!(rid.0, "wire-roundtrip");
}