effectful 0.3.0

Effect<A, E, R> (sync + async), context/layers, pipe — interpreter-style, no bundled executor
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
//! Deterministic test runtime harness helpers.
//!
//! Prefer effect-returning tests over calling [`Effect::run`](crate::Effect::run) in test bodies.
//! The adapter owns execution, environment creation, hygiene checks, and failure formatting.
//!
//! ```rust
//! use effectful::{Effect, effect_test};
//!
//! #[effect_test]
//! fn succeeds() -> Effect<(), &'static str, ()> {
//!   Effect::new(|_| Ok(()))
//! }
//! ```
//!
//! `#[effect_test]` expands to a current-thread Tokio test through `effectful::testing`, so
//! downstream crates do not need to name `tokio` in each test body.
//!
//! Provide a service context fixture with `env = "path"`:
//!
//! ```rust
//! use effectful::{Effect, Service, ServiceContext, effect_test};
//!
//! #[derive(Clone, Service)]
//! struct Clock { value: u64 }
//!
//! fn test_env() -> ServiceContext {
//!   Clock { value: 1 }.to_context()
//! }
//!
//! #[effect_test(env = "test_env")]
//! fn uses_context() -> Effect<(), effectful::MissingService, ServiceContext> {
//!   Effect::service::<Clock>().map(|clock| assert_eq!(clock.value, 1))
//! }
//! ```

use crate::layer::Layer;
use crate::runtime::Never;
use crate::{Effect, Exit, ServiceContext, TestClock};
use std::cell::{Cell, RefCell};
use std::fmt::Debug;

thread_local! {
  static LEAKED_FIBERS: Cell<usize> = const { Cell::new(0) };
  static UNCLOSED_SCOPES: Cell<usize> = const { Cell::new(0) };
  static ACTIVE_TEST_CLOCK: RefCell<Option<TestClock>> = const { RefCell::new(None) };
}

struct TestClockScope {
  previous: Option<TestClock>,
}

impl Drop for TestClockScope {
  fn drop(&mut self) {
    let previous = self.previous.clone();
    ACTIVE_TEST_CLOCK.with(|clock| {
      *clock.borrow_mut() = previous;
    });
  }
}

fn install_test_clock(clock: TestClock) -> TestClockScope {
  let previous = ACTIVE_TEST_CLOCK.with(|active| active.borrow_mut().replace(clock));
  TestClockScope { previous }
}

pub(crate) fn current_test_clock() -> Option<TestClock> {
  ACTIVE_TEST_CLOCK.with(|clock| clock.borrow().clone())
}

fn reset_counters() {
  LEAKED_FIBERS.with(|c| c.set(0));
  UNCLOSED_SCOPES.with(|c| c.set(0));
}

fn assert_hygiene_counters() {
  let fiber_leaks = LEAKED_FIBERS.with(|c| c.get());
  assert_eq!(
    fiber_leaks, 0,
    "deterministic test harness detected leaked fibers: {fiber_leaks}"
  );

  let scope_leaks = UNCLOSED_SCOPES.with(|c| c.get());
  assert_eq!(
    scope_leaks, 0,
    "deterministic test harness detected unclosed scopes: {scope_leaks}"
  );
}

/// Internal hook for tests that need to simulate leaked fibers.
pub fn record_leaked_fiber() {
  LEAKED_FIBERS.with(|c| c.set(c.get().saturating_add(1)));
}

/// Internal hook for tests that need to simulate unclosed scopes.
pub fn record_unclosed_scope() {
  UNCLOSED_SCOPES.with(|c| c.set(c.get().saturating_add(1)));
}

/// Assert that no leaked fibers were recorded in the current test harness run.
pub fn assert_no_leaked_fibers() -> Effect<(), Never, ()> {
  Effect::new(move |_env| {
    let leaks = LEAKED_FIBERS.with(|c| c.get());
    assert_eq!(
      leaks, 0,
      "deterministic test harness detected leaked fibers: {leaks}"
    );
    Ok(())
  })
}

/// Assert that no unclosed scopes were recorded in the current test harness run.
pub fn assert_no_unclosed_scopes() -> Effect<(), Never, ()> {
  Effect::new(move |_env| {
    let leaks = UNCLOSED_SCOPES.with(|c| c.get());
    assert_eq!(
      leaks, 0,
      "deterministic test harness detected unclosed scopes: {leaks}"
    );
    Ok(())
  })
}

/// Small async runtime adapter for effect-returning tests.
///
/// `TestRuntime` lets downstream crates keep direct effect execution at the test harness edge.
/// Use [`TestRuntime::default`] for `R: Default`, or [`TestRuntime::with_env`] to provide a
/// context/fixture per test run.
pub struct TestRuntime<R, F = fn() -> R>
where
  R: 'static,
  F: FnOnce() -> R,
{
  make_env: F,
}

impl<R> Default for TestRuntime<R>
where
  R: Default + 'static,
{
  fn default() -> Self {
    Self {
      make_env: R::default,
    }
  }
}

impl<R, F> TestRuntime<R, F>
where
  R: 'static,
  F: FnOnce() -> R,
{
  /// Create a test runtime from an environment fixture.
  #[inline]
  pub fn with_env(make_env: F) -> Self {
    Self { make_env }
  }

  /// Run an effect under the test harness and return its result.
  #[inline]
  pub async fn run<A, E>(self, effect: Effect<A, E, R>) -> Result<A, E>
  where
    A: 'static,
    E: 'static,
  {
    let env = (self.make_env)();
    run_effect_test_with_env(effect, env).await
  }

  /// Run an effect under the test harness and panic with `Debug` output on failure.
  #[inline]
  pub async fn expect<A, E>(self, effect: Effect<A, E, R>) -> A
  where
    A: 'static,
    E: Debug + 'static,
  {
    expect_effect_test_with_env(effect, (self.make_env)()).await
  }
}

/// Run an effect-returning test with a default environment.
#[inline]
pub async fn run_effect_test<A, E, R>(effect: Effect<A, E, R>) -> Result<A, E>
where
  A: 'static,
  E: 'static,
  R: Default + 'static,
{
  run_effect_test_with_env(effect, R::default()).await
}

/// Run an effect-returning test with a provided environment.
#[inline]
pub async fn run_effect_test_with_env<A, E, R>(effect: Effect<A, E, R>, mut env: R) -> Result<A, E>
where
  A: 'static,
  E: 'static,
  R: 'static,
{
  reset_counters();
  let result = effect.run(&mut env).await;
  assert_hygiene_counters();
  result
}

/// Run an effect-returning test with a default environment and panic on failure.
#[inline]
pub async fn expect_effect_test<A, E, R>(effect: Effect<A, E, R>) -> A
where
  A: 'static,
  E: Debug + 'static,
  R: Default + 'static,
{
  expect_effect_test_with_env(effect, R::default()).await
}

/// Run an effect-returning test with a provided environment and panic on failure.
#[inline]
pub async fn expect_effect_test_with_env<A, E, R>(effect: Effect<A, E, R>, env: R) -> A
where
  A: 'static,
  E: Debug + 'static,
  R: 'static,
{
  match run_effect_test_with_env(effect, env).await {
    Ok(value) => value,
    Err(error) => panic!("effectful test failed: {error:?}"),
  }
}

/// Run a `ServiceContext` effect-returning test with a layer and panic on failure.
#[inline]
pub async fn expect_effect_test_with_layer<A, E, ROut>(
  effect: Effect<A, E, ServiceContext>,
  layer: Layer<ROut, E, ()>,
) -> A
where
  A: 'static,
  E: Debug + 'static,
  ROut: 'static,
{
  expect_effect_test(effect.provide(layer)).await
}

/// Run an effect in deterministic test mode and return an `Exit` value.
#[inline]
pub fn run_test<A, E, R>(effect: Effect<A, E, R>, env: R) -> Exit<A, E>
where
  A: 'static,
  E: 'static,
  R: 'static,
{
  reset_counters();
  let result = crate::runtime::run_blocking(effect, env);
  assert_hygiene_counters();
  match result {
    Ok(value) => Exit::succeed(value),
    Err(error) => Exit::fail(error),
  }
}

/// Run an effect in deterministic test mode with an explicit test clock.
#[inline]
pub fn run_test_with_clock<A, E, R>(effect: Effect<A, E, R>, env: R, clock: TestClock) -> Exit<A, E>
where
  A: 'static,
  E: 'static,
  R: 'static,
{
  let _scope = install_test_clock(clock);
  run_test(effect, env)
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::scheduling::duration::duration;
  use crate::{
    Metric, MissingService, Schedule, ScheduleInput, fail, retry, retry_with_clock, succeed,
  };
  use rstest::rstest;
  use std::sync::Arc;
  use std::sync::Mutex;
  use std::sync::atomic::{AtomicUsize, Ordering};

  #[derive(Clone, Debug, PartialEq, effectful::Service)]
  struct TestService {
    value: u32,
  }

  struct TestFailure {
    code: u32,
  }

  impl std::fmt::Debug for TestFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("TestFailure")
        .field("code", &self.code)
        .finish()
    }
  }

  fn service_context() -> ServiceContext {
    TestService { value: 9 }.to_context()
  }

  fn service_layer() -> Layer<TestService, MissingService, ()> {
    Layer::succeed(TestService { value: 11 })
  }

  mod run_test {
    use super::*;

    #[test]
    fn run_test_with_success_effect_returns_success_exit() {
      let exit = run_test(succeed::<u32, (), ()>(7), ());
      assert_eq!(exit, Exit::succeed(7));
    }

    #[test]
    fn run_test_with_failure_effect_returns_failure_exit() {
      let exit = run_test(fail::<(), &'static str, ()>("boom"), ());
      assert_eq!(exit, Exit::fail("boom"));
    }

    #[rstest]
    #[case::zero(0u8)]
    #[case::positive(9u8)]
    fn run_test_with_clock_matches_run_test_semantics_for_successful_effect(#[case] value: u8) {
      let effect = succeed::<u8, (), ()>(value);
      let clock = TestClock::new(std::time::Instant::now());
      let exit = run_test_with_clock(effect, (), clock);
      assert_eq!(exit, Exit::succeed(value));
    }

    #[test]
    fn run_test_with_clock_drives_retry_schedule_sleep_without_wall_clock_wait() {
      let start = std::time::Instant::now();
      let clock = TestClock::new(start);
      let attempts = Arc::new(AtomicUsize::new(0));
      let attempts_c = Arc::clone(&attempts);
      let effect = retry(
        move || {
          let attempt = attempts_c.fetch_add(1, Ordering::SeqCst);
          if attempt == 0 {
            fail::<usize, &'static str, ()>("boom")
          } else {
            succeed::<usize, &'static str, ()>(attempt + 1)
          }
        },
        Schedule::spaced(duration::millis(50)).compose(Schedule::recurs(1)),
      );

      let before = std::time::Instant::now();
      let exit = run_test_with_clock(effect, (), clock.clone());
      let elapsed = before.elapsed();

      assert_eq!(exit, Exit::succeed(2));
      assert!(
        elapsed < duration::millis(25),
        "retry waited on wall clock for {elapsed:?}"
      );
      assert_eq!(clock.pending_sleeps(), vec![start + duration::millis(50)]);
    }

    #[test]
    fn run_test_with_clock_retry_composed_schedule_uses_attempt_inputs_and_test_clock() {
      let start = std::time::Instant::now();
      let clock = TestClock::new(start);
      let counter = Metric::counter("retry_composed_attempts", []);

      let predicate_attempts = Arc::new(Mutex::new(Vec::new()));
      let contramap_attempts = Arc::new(Mutex::new(Vec::new()));

      let predicate_attempts_c = Arc::clone(&predicate_attempts);
      let contramap_attempts_c = Arc::clone(&contramap_attempts);

      let attempts = Arc::new(AtomicUsize::new(0));
      let attempts_c = Arc::clone(&attempts);

      let effect = retry_with_clock(
        move || {
          let n = attempts_c.fetch_add(1, Ordering::SeqCst);
          if n < 2 {
            fail::<usize, &'static str, ()>("boom")
          } else {
            succeed::<usize, &'static str, ()>(n + 1)
          }
        },
        Schedule::spaced(duration::millis(50))
          .compose(Schedule::recurs_while({
            let attempts = Arc::clone(&predicate_attempts_c);
            Box::new(move |i: &ScheduleInput| {
              attempts.lock().expect("mutex poisoned").push(i.attempt);
              i.attempt < 2
            })
          }))
          .compose(
            Schedule::recurs_until(Box::new(|i: &ScheduleInput| i.attempt >= 12)).contramap({
              let attempts = Arc::clone(&contramap_attempts_c);
              move |mut i: ScheduleInput| {
                attempts.lock().expect("mutex poisoned").push(i.attempt);
                i.attempt = i.attempt.saturating_add(10);
                i
              }
            }),
          ),
        TestClock::new(start),
        Some(counter.clone()),
      );

      let before = std::time::Instant::now();
      let exit = run_test_with_clock(effect, (), clock.clone());
      let elapsed = before.elapsed();

      assert_eq!(exit, Exit::succeed(3));
      assert_eq!(attempts.load(Ordering::SeqCst), 3);
      assert_eq!(counter.snapshot_count(), 3);

      let pred_seen = predicate_attempts.lock().expect("mutex poisoned");
      assert_eq!(*pred_seen, vec![0, 1]);

      let contra_seen = contramap_attempts.lock().expect("mutex poisoned");
      assert_eq!(*contra_seen, vec![0, 1]);

      assert_eq!(
        clock.pending_sleeps(),
        vec![start + duration::millis(50), start + duration::millis(50)]
      );

      assert!(
        elapsed < duration::millis(25),
        "retry waited on wall clock for {elapsed:?}"
      );
    }
  }

  mod effect_test_attribute {
    use super::*;

    #[crate::effect_test]
    fn effect_returning_test_with_unit_environment_passes() -> Effect<(), &'static str, ()> {
      Effect::new(|_| Ok(()))
    }

    #[crate::effect_test(env = "service_context")]
    fn effect_returning_test_with_provided_context_passes()
    -> Effect<(), MissingService, ServiceContext> {
      Effect::<TestService, MissingService, ServiceContext>::service::<TestService>()
        .map(|service| assert_eq!(service.value, 9))
    }

    #[crate::effect_test(layer = "service_layer")]
    fn effect_returning_test_with_provided_layer_passes()
    -> Effect<(), MissingService, ServiceContext> {
      Effect::<TestService, MissingService, ServiceContext>::service::<TestService>()
        .map(|service| assert_eq!(service.value, 11))
    }
  }

  mod async_harness {
    use super::*;

    #[tokio::test]
    async fn run_effect_test_with_env_returns_success_value() {
      let effect = Effect::<u32, MissingService, ServiceContext>::service::<TestService>()
        .map(|service| service.value);

      let result = run_effect_test_with_env(effect, service_context()).await;

      assert_eq!(result, Ok(9));
    }

    #[tokio::test]
    async fn test_runtime_with_env_returns_success_value() {
      let effect = Effect::<u32, MissingService, ServiceContext>::service::<TestService>()
        .map(|service| service.value);

      let result = TestRuntime::with_env(service_context).run(effect).await;

      assert_eq!(result, Ok(9));
    }

    #[tokio::test]
    #[should_panic(expected = "effectful test failed: TestFailure { code: 7 }")]
    async fn expect_effect_test_with_failure_formats_debug_error() {
      expect_effect_test(fail::<(), TestFailure, ()>(TestFailure { code: 7 })).await;
    }
  }

  mod assertions {
    use super::*;

    #[test]
    #[should_panic(expected = "deterministic test harness detected leaked fibers")]
    fn assert_no_leaked_fibers_when_leaked_fiber_recorded_panics() {
      record_leaked_fiber();
      let _ = crate::runtime::run_blocking(assert_no_leaked_fibers(), ());
    }

    #[test]
    #[should_panic(expected = "deterministic test harness detected unclosed scopes")]
    fn assert_no_unclosed_scopes_when_unclosed_scope_recorded_panics() {
      record_unclosed_scope();
      let _ = crate::runtime::run_blocking(assert_no_unclosed_scopes(), ());
    }
  }
}