dactor-kameo 0.3.3

Kameo 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
//! Kameo-backed test node binary for E2E integration tests.
//!
//! Runs a [`TestNode`] gRPC server with a [`KameoCommandHandler`] that
//! manages a simple counter actor via the `dactor-kameo` runtime.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;

use async_trait::async_trait;
use dactor::actor::{Actor, ActorContext, ActorRef, Handler};
use dactor::message::Message;
use dactor::supervision::ChildTerminated;
use dactor_kameo::{KameoActorRef, KameoRuntime};
use dactor_test_harness::handler::CommandHandler;
use dactor_test_harness::node::{TestNode, TestNodeConfig};

// ---------------------------------------------------------------------------
// Counter actor — the test actor used by T4–T5 E2E tests
// ---------------------------------------------------------------------------

struct CounterActor {
    count: i64,
}

impl Actor for CounterActor {
    type Args = i64; // initial count
    type Deps = ();
    fn create(args: Self::Args, _deps: ()) -> Self {
        CounterActor { count: args }
    }
}

// Tell message: increment the counter
struct Increment {
    amount: i64,
}
impl Message for Increment {
    type Reply = ();
}

#[async_trait]
impl Handler<Increment> for CounterActor {
    async fn handle(&mut self, msg: Increment, _ctx: &mut ActorContext) {
        self.count += msg.amount;
    }
}

// Tell message: set the counter directly
struct SetCount {
    value: i64,
}
impl Message for SetCount {
    type Reply = ();
}

#[async_trait]
impl Handler<SetCount> for CounterActor {
    async fn handle(&mut self, msg: SetCount, _ctx: &mut ActorContext) {
        self.count = msg.value;
    }
}

// Tell message: increment after a delay (for concurrency testing)
struct SlowIncrement {
    amount: i64,
}
impl Message for SlowIncrement {
    type Reply = ();
}

#[async_trait]
impl Handler<SlowIncrement> for CounterActor {
    async fn handle(&mut self, msg: SlowIncrement, _ctx: &mut ActorContext) {
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        self.count += msg.amount;
    }
}

// Ask message: get the current count
struct GetCount;
impl Message for GetCount {
    type Reply = i64;
}

#[async_trait]
impl Handler<GetCount> for CounterActor {
    async fn handle(&mut self, _msg: GetCount, _ctx: &mut ActorContext) -> i64 {
        self.count
    }
}

// Ask message: echo back payload bytes
struct Echo(Vec<u8>);
impl Message for Echo {
    type Reply = Vec<u8>;
}

#[async_trait]
impl Handler<Echo> for CounterActor {
    async fn handle(&mut self, msg: Echo, _ctx: &mut ActorContext) -> Vec<u8> {
        msg.0
    }
}

// Ask message: echo back payload bytes after a 2s delay (for timeout testing)
struct SlowEcho(Vec<u8>);
impl Message for SlowEcho {
    type Reply = Vec<u8>;
}

#[async_trait]
impl Handler<SlowEcho> for CounterActor {
    async fn handle(&mut self, msg: SlowEcho, _ctx: &mut ActorContext) -> Vec<u8> {
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
        msg.0
    }
}

// Watch handler: receive notification when a watched actor stops
#[async_trait]
impl Handler<ChildTerminated> for CounterActor {
    async fn handle(&mut self, msg: ChildTerminated, _ctx: &mut ActorContext) {
        tracing::info!(
            child_name = %msg.child_name,
            "watched actor terminated"
        );
        // Encode notification as a negative count so tests can detect it
        self.count = -999;
    }
}

// ---------------------------------------------------------------------------
// KameoCommandHandler — bridges gRPC commands to the kameo runtime
// ---------------------------------------------------------------------------

struct KameoCommandHandler {
    runtime: KameoRuntime,
    actors: Mutex<HashMap<String, KameoActorRef<CounterActor>>>,
    watches: Mutex<Vec<(String, String)>>,
    live_count: AtomicU32,
}

impl KameoCommandHandler {
    fn new(runtime: KameoRuntime) -> Self {
        Self {
            runtime,
            actors: Mutex::new(HashMap::new()),
            watches: Mutex::new(Vec::new()),
            live_count: AtomicU32::new(0),
        }
    }
}

#[async_trait]
impl CommandHandler for KameoCommandHandler {
    fn adapter_name(&self) -> &str {
        "kameo"
    }

    async fn spawn_actor(
        &self,
        actor_type: &str,
        actor_name: &str,
        args: &[u8],
    ) -> Result<String, String> {
        if actor_type != "counter" {
            return Err(format!("unknown actor type: {}", actor_type));
        }

        let initial: i64 = if args.is_empty() {
            0
        } else {
            serde_json::from_slice(args).map_err(|e| format!("bad args: {}", e))?
        };

        let actor_ref = self
            .runtime
            .spawn::<CounterActor>(actor_name, initial)
            .await
            .map_err(|e| format!("spawn failed: {}", e))?;

        let id = actor_ref.id().to_string();
        let mut actors = self.actors.lock().await;
        if actors.contains_key(actor_name) {
            return Err(format!("actor '{}' already exists", actor_name));
        }
        actors.insert(actor_name.to_string(), actor_ref);
        self.live_count.fetch_add(1, Ordering::Relaxed);
        Ok(id)
    }

    async fn tell_actor(
        &self,
        actor_name: &str,
        message_type: &str,
        payload: &[u8],
    ) -> Result<(), String> {
        let actor_ref = {
            let actors = self.actors.lock().await;
            actors
                .get(actor_name)
                .ok_or_else(|| format!("actor '{}' not found", actor_name))?
                .clone()
        };

        match message_type {
            "increment" => {
                let amount: i64 = if payload.is_empty() {
                    1
                } else {
                    serde_json::from_slice(payload).map_err(|e| format!("bad payload: {}", e))?
                };
                actor_ref
                    .tell(Increment { amount })
                    .map_err(|e| format!("tell failed: {}", e))
            }
            "set_count" => {
                let value: i64 =
                    serde_json::from_slice(payload).map_err(|e| format!("bad payload: {}", e))?;
                actor_ref
                    .tell(SetCount { value })
                    .map_err(|e| format!("tell failed: {}", e))
            }
            "slow_increment" => {
                let amount: i64 =
                    serde_json::from_slice(payload).map_err(|e| format!("bad payload: {}", e))?;
                actor_ref
                    .tell(SlowIncrement { amount })
                    .map_err(|e| format!("tell failed: {}", e))
            }
            "forward_increment" => {
                let fwd: serde_json::Value =
                    serde_json::from_slice(payload).map_err(|e| format!("bad payload: {}", e))?;
                let target = fwd["target"]
                    .as_str()
                    .ok_or_else(|| "missing target".to_string())?;
                let amount = fwd["amount"]
                    .as_i64()
                    .ok_or_else(|| "missing amount".to_string())?;
                let target_ref = {
                    let actors = self.actors.lock().await;
                    actors
                        .get(target)
                        .ok_or_else(|| format!("forward target '{}' not found", target))?
                        .clone()
                };
                target_ref
                    .tell(Increment { amount })
                    .map_err(|e| format!("forward failed: {}", e))
            }
            _ => Err(format!("unknown message type: {}", message_type)),
        }
    }

    async fn ask_actor(
        &self,
        actor_name: &str,
        message_type: &str,
        payload: &[u8],
        timeout_ms: u64,
    ) -> Result<Vec<u8>, String> {
        let actor_ref = {
            let actors = self.actors.lock().await;
            actors
                .get(actor_name)
                .ok_or_else(|| format!("actor '{}' not found", actor_name))?
                .clone()
        };

        let actor_name_owned = actor_name.to_string();
        let ask_fut = async {
            match message_type {
                "get_count" => {
                    let reply = actor_ref
                        .ask(GetCount, None)
                        .map_err(|e| format!("ask failed: {}", e))?;
                    let count = reply.await.map_err(|e| format!("reply failed: {}", e))?;
                    serde_json::to_vec(&count).map_err(|e| format!("serialize failed: {}", e))
                }
                "get_state" => {
                    let reply = actor_ref
                        .ask(GetCount, None)
                        .map_err(|e| format!("ask failed: {}", e))?;
                    let count = reply.await.map_err(|e| format!("reply failed: {}", e))?;
                    let state = serde_json::json!({
                        "count": count,
                        "name": actor_name_owned,
                    });
                    serde_json::to_vec(&state).map_err(|e| format!("serialize failed: {}", e))
                }
                "echo" => {
                    let reply = actor_ref
                        .ask(Echo(payload.to_vec()), None)
                        .map_err(|e| format!("ask failed: {}", e))?;
                    reply.await.map_err(|e| format!("reply failed: {}", e))
                }
                "slow_echo" => {
                    let reply = actor_ref
                        .ask(SlowEcho(payload.to_vec()), None)
                        .map_err(|e| format!("ask failed: {}", e))?;
                    reply.await.map_err(|e| format!("reply failed: {}", e))
                }
                _ => Err(format!("unknown message type: {}", message_type)),
            }
        };

        if timeout_ms > 0 {
            match tokio::time::timeout(
                std::time::Duration::from_millis(timeout_ms),
                ask_fut,
            )
            .await
            {
                Ok(result) => result,
                Err(_) => Err("ask timed out".into()),
            }
        } else {
            ask_fut.await
        }
    }

    async fn stop_actor(&self, actor_name: &str) -> Result<(), String> {
        let actor_ref = {
            let mut actors = self.actors.lock().await;
            actors
                .remove(actor_name)
                .ok_or_else(|| format!("actor '{}' not found", actor_name))?
        };
        actor_ref.stop();
        for _ in 0..100 {
            if !actor_ref.is_alive() {
                self.live_count.fetch_sub(1, Ordering::Relaxed);

                // Collect watcher refs, then drop lock before notifying
                let watcher_refs: Vec<_> = {
                    let watches = self.watches.lock().await;
                    let actors = self.actors.lock().await;
                    watches
                        .iter()
                        .filter(|(_, target)| target == actor_name)
                        .filter_map(|(watcher, _)| actors.get(watcher).cloned())
                        .collect()
                };
                for watcher_ref in watcher_refs {
                    let _ = watcher_ref.tell(ChildTerminated {
                        child_id: dactor::node::ActorId {
                            node: dactor::node::NodeId("local".into()),
                            local: 0,
                        },
                        child_name: actor_name.to_string(),
                        reason: None,
                    });
                }

                return Ok(());
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        // Actor didn't terminate in time — still decrement since we removed from map
        self.live_count.fetch_sub(1, Ordering::Relaxed);
        Err(format!("actor '{}' did not terminate within 1s", actor_name))
    }

    async fn watch_actor(&self, watcher_name: &str, target_name: &str) -> Result<(), String> {
        let actors = self.actors.lock().await;
        if !actors.contains_key(watcher_name) {
            return Err(format!("watcher '{}' not found", watcher_name));
        }
        if !actors.contains_key(target_name) {
            return Err(format!("target '{}' not found", target_name));
        }
        drop(actors);
        let mut watches = self.watches.lock().await;
        if watches.iter().any(|(w, t)| w == watcher_name && t == target_name) {
            return Ok(());
        }
        watches.push((watcher_name.to_string(), target_name.to_string()));
        Ok(())
    }

    fn actor_count(&self) -> u32 {
        self.live_count.load(Ordering::Relaxed)
    }
}

// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let node_id = std::env::var("DACTOR_NODE_ID").unwrap_or_else(|_| "test-node".to_string());
    let port: u16 = std::env::var("DACTOR_CONTROL_PORT")
        .unwrap_or_else(|_| "50051".to_string())
        .parse()
        .expect("invalid port");

    let runtime = KameoRuntime::with_node_id(dactor::node::NodeId(node_id.clone()));
    let handler = Arc::new(KameoCommandHandler::new(runtime));

    let config = TestNodeConfig::from_args(&node_id, port);
    let node = TestNode::with_handler(config, handler);

    if let Err(e) = node.run().await {
        eprintln!("Test node error: {}", e);
        std::process::exit(1);
    }
}