elfo-test 0.2.0-alpha.21

Test utils for the elfo system
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
use std::{
    collections::BTreeMap,
    future::{self, Future},
    panic::Location,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc, LazyLock,
    },
    thread,
    time::Duration,
};

use futures_intrusive::timer::{LocalTimer, StdClock, TimerService};
use serde::{de::Deserializer, Deserialize};
use serde_value::Value;
use tokio::{sync::oneshot, task};

use elfo_core::{
    ActorGroup, Addr, Blueprint, Context, Envelope, Local, Message, MoveOwnership, Request,
    ResponseToken,
    _priv::do_start,
    addr::NodeLaunchId,
    errors::{RequestError, TrySendError},
    message, msg,
    routers::{MapRouter, Outcome},
    scope::{self, Scope},
    topology::Topology,
};

const SYNC_YIELD_COUNT: usize = 32;

/// A proxy for testing actors.
pub struct Proxy {
    context: ProxyContext,
    scope: Scope,
    subject_addr: Addr,
    recv_timeout: Duration,
}

type ProxyContext = Context<(), usize>;

impl Proxy {
    /// Returns an address of the proxy.
    pub fn addr(&self) -> Addr {
        self.context.addr()
    }

    /// Returns a launch ID of the topology.
    ///
    /// It can be used to distinguish produced artifacts (logs, dumps, metrics)
    /// from different concurrent tests if the custom implementation is used.
    pub fn node_launch_id(&self) -> NodeLaunchId {
        self.scope.node_launch_id()
    }

    /// See [`Context::unbounded_send()`] for details.
    #[track_caller]
    pub fn unbounded_send<M: Message>(&self, message: M) {
        self.scope.clone().sync_within(|| {
            let name = message.name();
            if let Err(err) = self.context.unbounded_send(message) {
                panic!("cannot send {name} ({err}) unboundedly")
            }
        })
    }

    /// See [`Context::unbounded_send_to()`] for details.
    #[track_caller]
    pub fn unbounded_send_to<M: Message>(&self, recipient: Addr, message: M) {
        self.scope.clone().sync_within(|| {
            let name = message.name();
            if let Err(err) = self.context.unbounded_send_to(recipient, message) {
                panic!("cannot send {name} ({err}) unboundedly")
            }
        })
    }

    /// See [`Context::send()`] for details.
    #[track_caller]
    pub fn send<M: Message>(&self, message: M) -> impl Future<Output = ()> + '_ {
        let location = Location::caller();
        self.scope.clone().within(async move {
            let name = message.name();
            if let Err(err) = self.context.send(message).await {
                panic!("cannot send {name} ({err}) at {location}");
            }
        })
    }

    /// See [`Context::send_to()`] for details.
    #[track_caller]
    pub fn send_to<M: Message>(
        &self,
        recipient: Addr,
        message: M,
    ) -> impl Future<Output = ()> + '_ {
        let location = Location::caller();
        self.scope.clone().within(async move {
            let name = message.name();
            if let Err(err) = self.context.send_to(recipient, message).await {
                panic!("cannot send {name} ({err}) at {location}");
            }
        })
    }

    /// See [`Context::try_send()`] for details.
    #[track_caller]
    pub fn try_send<M: Message>(&self, message: M) -> Result<(), TrySendError<M>> {
        self.scope
            .clone()
            .sync_within(|| self.context.try_send(message))
    }

    /// See [`Context::try_send_to()`] for details.
    #[track_caller]
    pub fn try_send_to<M: Message>(
        &self,
        recipient: Addr,
        message: M,
    ) -> Result<(), TrySendError<M>> {
        self.scope
            .clone()
            .sync_within(|| self.context.try_send_to(recipient, message))
    }

    /// Same as [`Self::request`], but doesn't unwraps the error.
    pub fn request_fallible<R: Request>(
        &self,
        request: R,
    ) -> impl Future<Output = Result<R::Response, RequestError>> {
        let context = self.context.pruned();
        self.scope
            .clone()
            .within(async move { context.request(request).resolve().await })
    }

    /// See [`Context::request()`] for details.
    #[track_caller]
    pub fn request<R: Request>(&self, request: R) -> impl Future<Output = R::Response> {
        let location = Location::caller();
        let context = self.context.pruned();
        self.scope.clone().within(async move {
            let name = request.name();
            match context.request(request).resolve().await {
                Ok(response) => response,
                Err(err) => panic!("cannot send {name} ({err}) at {location}"),
            }
        })
    }

    /// Same as [`Self::request_to`], but doesn't unwraps the errors.
    pub fn request_to_fallible<R: Request>(
        &self,
        recipient: Addr,
        request: R,
    ) -> impl Future<Output = Result<R::Response, RequestError>> {
        let context = self.context.pruned();
        self.scope
            .clone()
            .within(async move { context.request_to(recipient, request).resolve().await })
    }

    /// See [`Context::request_to()`] for details.
    #[track_caller]
    pub fn request_to<R: Request>(
        &self,
        recipient: Addr,
        request: R,
    ) -> impl Future<Output = R::Response> {
        let location = Location::caller();
        let context = self.context.pruned();
        self.scope.clone().within(async move {
            let name = request.name();
            match context.request_to(recipient, request).resolve().await {
                Ok(response) => response,
                Err(err) => panic!("cannot send {name} ({err}) at {location}"),
            }
        })
    }

    /// See [`Context::respond()`] for details.
    pub fn respond<R: Request>(&self, token: ResponseToken<R>, response: R::Response) {
        self.scope
            .clone()
            .sync_within(|| self.context.respond(token, response))
    }

    /// See [`Context::recv()`] for details.
    #[track_caller]
    pub fn recv(&mut self) -> impl Future<Output = Envelope> + '_ {
        // We use a separate timer here to avoid interaction with the tokio's timer.
        static STD_CLOCK: LazyLock<StdClock> = LazyLock::new(StdClock::new);
        static TIMER_SERVICE: LazyLock<Arc<TimerService>> = LazyLock::new(|| {
            let timer_service = Arc::new(TimerService::new(&*STD_CLOCK));
            thread::spawn({
                let timer_service = timer_service.clone();
                move || loop {
                    std::thread::sleep(Duration::from_millis(25));
                    timer_service.check_expirations();
                }
            });
            timer_service
        });

        let location = Location::caller();
        self.scope.clone().within(async move {
            tokio::select! {
                Some(envelope) = self.context.recv() => {
                    envelope
                },
                _ = TIMER_SERVICE.delay(self.recv_timeout) => {
                    panic!(
                        "timeout ({:?}) while receiving a message at {}",
                        self.recv_timeout, location,
                    );
                }
            }
        })
    }

    /// See [`Context::try_recv()`] for details.
    pub async fn try_recv(&mut self) -> Option<Envelope> {
        self.scope
            .clone()
            .within(async move { self.context.try_recv().await.ok() })
            .await
    }

    /// Waits until the testable actor handles all previously sent messages.
    ///
    /// Now it's implemented as multiple calls `yield_now()`,
    /// but the implementation can be changed in the future.
    pub async fn sync(&mut self) {
        // TODO: it should probably be `request(Ping).await`.
        for _ in 0..SYNC_YIELD_COUNT {
            task::yield_now().await;
        }
    }

    /// Sets message wait time for `recv` call.
    pub fn set_recv_timeout(&mut self, recv_timeout: Duration) {
        self.recv_timeout = recv_timeout;
    }

    /// Creates a subproxy with a different address.
    /// The main purpose is to test `send_to(..)` and `request_to(..)` calls.
    pub async fn subproxy(&self) -> Proxy {
        let f = async {
            self.context
                .request_to(self.context.group(), CreateSubproxy)
                .resolve()
                .await
                .expect("cannot create a new subpoxy")
        };

        let ProxyCreated { context, scope } = self.scope.clone().within(f).await;

        Proxy {
            context: context.into_inner(),
            scope: scope.into_inner(),
            subject_addr: self.subject_addr,
            recv_timeout: self.recv_timeout,
        }
    }

    /// Waits until the testable actor finishes.
    pub async fn finished(&self) {
        let fut = self.context.finished(self.subject_addr);
        self.scope.clone().within(fut).await
    }

    /// Closes a mailbox of the proxy.
    pub fn close(&self) {
        self.scope.clone().sync_within(|| self.context.close());
    }
}

#[message(ret = ProxyCreated)]
struct CreateSubproxy;

#[message(part)]
struct ProxyCreated {
    context: Local<ProxyContext>,
    scope: Local<Scope>,
}

fn testers(tx: oneshot::Sender<ProxyCreated>) -> Blueprint {
    let tx = MoveOwnership::from(tx);
    let key = AtomicUsize::new(1); // 0 is reserved for the main proxy

    ActorGroup::new()
        .router(MapRouter::new(move |envelope| {
            msg!(match envelope {
                CreateSubproxy => Outcome::Unicast(key.fetch_add(1, Ordering::SeqCst)),
                _ => Outcome::Unicast(0),
            })
        }))
        .exec(move |mut ctx| {
            let tx = tx.clone();
            async move {
                // It would be nice to use the code in the `else` branch also for the main
                // proxy. Unfortunately, the main proxy can receive messages from the subject
                // before receiving the `CreateSubproxy` message. That's why we need to use
                // a dedicated oneshot channel for the main proxy.
                // See the `it_handles_race_at_startup` test for an example.
                if let Some(tx) = tx.take() {
                    let _ = tx.send(ProxyCreated {
                        context: ctx.into(),
                        scope: scope::expose().into(),
                    });
                } else {
                    let envelope = ctx.recv().await.unwrap();
                    let (_, token) = crate::extract_request::<CreateSubproxy>(envelope);

                    ctx.pruned().respond(
                        token,
                        ProxyCreated {
                            scope: scope::expose().into(),
                            context: ctx.into(),
                        },
                    );
                }

                // We don't track the lifetime of sent context for now, so keep the actor alive.
                future::pending::<()>().await;
            }
        })
}

#[doc(hidden)]
#[instability::unstable]
pub async fn proxy_with_route<F>(
    blueprint: Blueprint,
    route_filter: F,
    config: impl for<'de> Deserializer<'de>,
) -> Proxy
where
    F: Fn(&Envelope) -> bool + Send + Sync + 'static,
{
    // Initialize logging but skip errors if the logger is already initialized.
    // It occurs when tests are run in the same process.
    let _ = tracing_subscriber::fmt()
        .with_target(false)
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_test_writer()
        .try_init();

    let config = Value::deserialize(config).expect("invalid config");
    let mut map = BTreeMap::new();
    map.insert(Value::String("subject".into()), config);
    let config = Value::Map(map);

    let topology = Topology::empty();
    let subject = topology.local("subject");
    let testers = topology.local("system.testers");
    let configurers = topology.local("system.configurers").entrypoint();

    let subject_addr = subject.addr();

    testers.route_all_to(&subject);
    subject.route_to(&testers, route_filter);

    configurers.mount(elfo_configurer::fixture(&topology, config));
    subject.mount(blueprint);

    let (tx, rx) = oneshot::channel();
    testers.mount(self::testers(tx));
    do_start(topology, false, |_, _| future::ready(()))
        .await
        .expect("cannot start");

    let ProxyCreated { context, scope } = rx.await.expect("cannot create main proxy");

    Proxy {
        context: context.into_inner(),
        scope: scope.into_inner(),
        subject_addr,
        recv_timeout: Duration::from_millis(150),
    }
}

/// Creates a proxy for testing actors.
/// See examples in the repository for more details how to use it.
pub async fn proxy(blueprint: Blueprint, config: impl for<'de> Deserializer<'de>) -> Proxy {
    proxy_with_route(blueprint, |_| true, config).await
}

#[cfg(test)]
mod tests {
    use super::*;

    use elfo_core::{assert_msg_eq, config::AnyConfig, message, msg};

    #[message]
    #[derive(PartialEq)]
    struct SomeMessage;

    #[message(ret = u32)]
    #[derive(PartialEq)]
    struct SomeRequest;

    #[message]
    #[derive(PartialEq)]
    struct SomeMessage2;

    #[tokio::test]
    async fn it_handles_race_at_startup() {
        let mut proxy = super::proxy(
            ActorGroup::new().exec(|ctx| async move {
                ctx.send(SomeMessage).await.unwrap();
            }),
            AnyConfig::default(),
        )
        .await;

        assert_msg_eq!(proxy.recv().await, SomeMessage);
    }

    async fn sample() -> Proxy {
        super::proxy(
            ActorGroup::new().exec(|mut ctx| async move {
                while let Some(envelope) = ctx.recv().await {
                    let addr = envelope.sender();
                    msg!(match envelope {
                        SomeMessage => ctx.send_to(addr, SomeMessage2).await.unwrap(),
                        (SomeRequest, token) => ctx.respond(token, 42),
                    });
                }
            }),
            AnyConfig::default(),
        )
        .await
    }

    #[tokio::test]
    async fn main_proxy_works() {
        let mut proxy = sample().await;
        assert_eq!(proxy.request(SomeRequest).await, 42);
        proxy.send(SomeMessage).await;
        assert_msg_eq!(proxy.recv().await, SomeMessage2);
    }

    #[tokio::test]
    async fn subproxy_works() {
        let proxy = sample().await;
        let mut subproxy = proxy.subproxy().await;
        assert_eq!(subproxy.request(SomeRequest).await, 42);
        subproxy.send(SomeMessage).await;
        assert_msg_eq!(subproxy.recv().await, SomeMessage2);
    }
}