dactor-coerce 0.3.3

Coerce adapter for the dactor distributed actor framework
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
//! Tests for CP5/CP6: native coerce system actors.
//!
//! Validates that the native coerce system actors (SpawnManagerActor,
//! WatchManagerActor, CancelManagerActor, NodeDirectoryActor) work correctly
//! when spawned via the CoerceRuntime.

use dactor::node::{ActorId, NodeId};
use dactor::system_actors::{CancelResponse, SpawnRequest};
use dactor_coerce::system_actors::*;
use dactor_coerce::CoerceRuntime;

// ---------------------------------------------------------------------------
// CP5: SpawnManagerActor
// ---------------------------------------------------------------------------

#[tokio::test]
async fn cp5_spawn_manager_handle_spawn_request() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().expect("system actors started");

    // Register a factory via the native actor
    let factory: FactoryFn = Box::new(|bytes: &[u8]| {
        let value: i32 = serde_json::from_slice(bytes)
            .map_err(|e| dactor::remote::SerializationError::new(e.to_string()))?;
        Ok(Box::new(value))
    });
    refs.spawn_manager()
        .send(RegisterFactory {
            type_name: "test::Counter".into(),
            factory,
        })
        .await
        .expect("register factory");

    let request = SpawnRequest {
        type_name: "test::Counter".into(),
        args_bytes: serde_json::to_vec(&42i32).unwrap(),
        name: "counter-1".into(),
        request_id: "req-1".into(),
    };
    let outcome = refs
        .spawn_manager()
        .send(HandleSpawnRequest(request))
        .await
        .expect("send spawn request");

    match outcome {
        SpawnOutcome::Success { ref actor_id, .. } => {
            assert_eq!(actor_id.node, *runtime.node_id());
            let actor = outcome.take_actor().expect("actor should be present");
            let value = actor.downcast::<i32>().expect("should be i32");
            assert_eq!(*value, 42);
        }
        SpawnOutcome::Failure(resp) => panic!("spawn should succeed, got: {resp:?}"),
    }

    let spawned = refs
        .spawn_manager()
        .send(GetSpawnedActors)
        .await
        .expect("get spawned actors");
    assert_eq!(spawned.len(), 1);
}

#[tokio::test]
async fn cp5_spawn_manager_unknown_type_fails() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let request = SpawnRequest {
        type_name: "nonexistent::Actor".into(),
        args_bytes: vec![],
        name: "ghost".into(),
        request_id: "req-2".into(),
    };
    let outcome = refs
        .spawn_manager()
        .send(HandleSpawnRequest(request))
        .await
        .expect("send spawn request");

    match outcome {
        SpawnOutcome::Failure(resp) => {
            if let dactor::system_actors::SpawnResponse::Failure { request_id, .. } = resp {
                assert_eq!(request_id, "req-2");
            } else {
                panic!("expected SpawnResponse::Failure");
            }
        }
        SpawnOutcome::Success { .. } => panic!("spawn of unknown type should fail"),
    }
}

#[tokio::test]
async fn cp5_spawn_manager_multiple_unique_ids() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let factory: FactoryFn = Box::new(|_| Ok(Box::new(())));
    refs.spawn_manager()
        .send(RegisterFactory {
            type_name: "test::Actor".into(),
            factory,
        })
        .await
        .unwrap();

    let mut ids = Vec::new();
    for i in 0..5 {
        let request = SpawnRequest {
            type_name: "test::Actor".into(),
            args_bytes: serde_json::to_vec(&()).unwrap(),
            name: format!("actor-{i}"),
            request_id: format!("req-{i}"),
        };
        let outcome = refs
            .spawn_manager()
            .send(HandleSpawnRequest(request))
            .await
            .unwrap();
        if let SpawnOutcome::Success { actor_id, .. } = outcome {
            ids.push(actor_id);
        }
    }
    assert_eq!(ids.len(), 5);
    let unique: std::collections::HashSet<_> = ids.iter().map(|id| id.local).collect();
    assert_eq!(unique.len(), 5);
}

// ---------------------------------------------------------------------------
// CP5: WatchManagerActor
// ---------------------------------------------------------------------------

#[tokio::test]
async fn cp5_watch_manager_watch_and_notify() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let target = ActorId {
        node: NodeId("n1".into()),
        local: 1,
    };
    let watcher = ActorId {
        node: NodeId("n2".into()),
        local: 10,
    };

    refs.watch_manager
        .send(RemoteWatch {
            target: target.clone(),
            watcher: watcher.clone(),
        })
        .await
        .unwrap();

    let count = refs.watch_manager.send(GetWatchedCount).await.unwrap();
    assert_eq!(count, 1);

    let notifications = refs
        .watch_manager
        .send(OnTerminated(target.clone()))
        .await
        .unwrap();
    assert_eq!(notifications.len(), 1);
    assert_eq!(notifications[0].terminated, target);
    assert_eq!(notifications[0].watcher, watcher);

    let count = refs.watch_manager.send(GetWatchedCount).await.unwrap();
    assert_eq!(count, 0);
}

#[tokio::test]
async fn cp5_watch_manager_unwatch() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let target = ActorId {
        node: NodeId("n1".into()),
        local: 1,
    };
    let watcher = ActorId {
        node: NodeId("n2".into()),
        local: 10,
    };

    refs.watch_manager
        .send(RemoteWatch {
            target: target.clone(),
            watcher: watcher.clone(),
        })
        .await
        .unwrap();

    refs.watch_manager
        .send(RemoteUnwatch {
            target: target.clone(),
            watcher: watcher.clone(),
        })
        .await
        .unwrap();

    let count = refs.watch_manager.send(GetWatchedCount).await.unwrap();
    assert_eq!(count, 0);

    let notifications = refs
        .watch_manager
        .send(OnTerminated(target))
        .await
        .unwrap();
    assert_eq!(notifications.len(), 0);
}

// ---------------------------------------------------------------------------
// CP5: CancelManagerActor
// ---------------------------------------------------------------------------

#[tokio::test]
async fn cp5_cancel_manager_register_and_cancel() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let token = tokio_util::sync::CancellationToken::new();
    let token_clone = token.clone();

    refs.cancel_manager
        .send(RegisterCancel {
            request_id: "req-1".into(),
            token,
        })
        .await
        .unwrap();

    let count = refs.cancel_manager.send(GetActiveCount).await.unwrap();
    assert_eq!(count, 1);

    let outcome = refs
        .cancel_manager
        .send(CancelById("req-1".into()))
        .await
        .unwrap();
    assert!(matches!(outcome.0, CancelResponse::Acknowledged));
    assert!(token_clone.is_cancelled());

    let count = refs.cancel_manager.send(GetActiveCount).await.unwrap();
    assert_eq!(count, 0);
}

#[tokio::test]
async fn cp5_cancel_manager_cancel_unknown() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let outcome = refs
        .cancel_manager
        .send(CancelById("nope".into()))
        .await
        .unwrap();
    assert!(matches!(outcome.0, CancelResponse::NotFound { .. }));
}

#[tokio::test]
async fn cp5_cancel_manager_complete_request() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    refs.cancel_manager
        .send(RegisterCancel {
            request_id: "req-cleanup".into(),
            token: tokio_util::sync::CancellationToken::new(),
        })
        .await
        .unwrap();

    let count = refs.cancel_manager.send(GetActiveCount).await.unwrap();
    assert_eq!(count, 1);

    refs.cancel_manager
        .send(CompleteRequest("req-cleanup".into()))
        .await
        .unwrap();

    let count = refs.cancel_manager.send(GetActiveCount).await.unwrap();
    assert_eq!(count, 0);
}

// ---------------------------------------------------------------------------
// CP5: NodeDirectoryActor
// ---------------------------------------------------------------------------

#[tokio::test]
async fn cp5_node_directory_connect_and_query() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let peer = NodeId("peer-1".into());

    refs.node_directory
        .send(ConnectPeer {
            peer_id: peer.clone(),
            address: Some("10.0.0.1:4697".into()),
        })
        .await
        .unwrap();

    let connected = refs
        .node_directory
        .send(IsConnected(peer.clone()))
        .await
        .unwrap();
    assert!(connected);

    let count = refs.node_directory.send(GetPeerCount).await.unwrap();
    assert_eq!(count, 1);

    let connected_count = refs.node_directory.send(GetConnectedCount).await.unwrap();
    assert_eq!(connected_count, 1);

    let info = refs
        .node_directory
        .send(GetPeerInfo(peer.clone()))
        .await
        .unwrap();
    assert!(info.is_some());
    assert_eq!(info.unwrap().address.as_deref(), Some("10.0.0.1:4697"));
}

#[tokio::test]
async fn cp5_node_directory_disconnect() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let peer = NodeId("peer-1".into());

    refs.node_directory
        .send(ConnectPeer {
            peer_id: peer.clone(),
            address: None,
        })
        .await
        .unwrap();

    refs.node_directory
        .send(DisconnectPeer(peer.clone()))
        .await
        .unwrap();

    let connected = refs
        .node_directory
        .send(IsConnected(peer.clone()))
        .await
        .unwrap();
    assert!(!connected);

    let count = refs.node_directory.send(GetPeerCount).await.unwrap();
    assert_eq!(count, 1);
}

#[tokio::test]
async fn cp5_node_directory_reconnect_preserves_address() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    let refs = runtime.system_actor_refs().unwrap();

    let peer = NodeId("peer-1".into());

    refs.node_directory
        .send(ConnectPeer {
            peer_id: peer.clone(),
            address: Some("10.0.0.1:4697".into()),
        })
        .await
        .unwrap();

    refs.node_directory
        .send(DisconnectPeer(peer.clone()))
        .await
        .unwrap();

    // Reconnect without address
    refs.node_directory
        .send(ConnectPeer {
            peer_id: peer.clone(),
            address: None,
        })
        .await
        .unwrap();

    let info = refs
        .node_directory
        .send(GetPeerInfo(peer.clone()))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        info.address.as_deref(),
        Some("10.0.0.1:4697"),
        "address should be preserved on reconnect without explicit address"
    );
}

// ---------------------------------------------------------------------------
// CP6: Runtime auto-start integration
// ---------------------------------------------------------------------------

#[tokio::test]
async fn cp6_system_actors_none_before_start() {
    let runtime = CoerceRuntime::new();
    assert!(runtime.system_actor_refs().is_none());
}

#[tokio::test]
async fn cp6_system_actors_available_after_start() {
    let mut runtime = CoerceRuntime::new();
    runtime.start_system_actors();
    assert!(runtime.system_actor_refs().is_some());
}

#[tokio::test]
async fn cp6_system_actors_with_custom_node_id() {
    let mut runtime = CoerceRuntime::with_node_id(NodeId("custom-42".into()));
    runtime.start_system_actors();

    let refs = runtime.system_actor_refs().unwrap();

    // The spawn manager should use the custom node ID
    let factory: FactoryFn = Box::new(|_| Ok(Box::new(())));
    refs.spawn_manager()
        .send(RegisterFactory {
            type_name: "test::Actor".into(),
            factory,
        })
        .await
        .unwrap();

    let request = SpawnRequest {
        type_name: "test::Actor".into(),
        args_bytes: serde_json::to_vec(&()).unwrap(),
        name: "a".into(),
        request_id: "req-1".into(),
    };
    let outcome = refs
        .spawn_manager()
        .send(HandleSpawnRequest(request))
        .await
        .unwrap();

    if let SpawnOutcome::Success { actor_id, .. } = outcome {
        assert_eq!(actor_id.node, NodeId("custom-42".into()));
    } else {
        panic!("expected success");
    }
}