cruster 0.0.27

A Rust framework for building distributed, stateful entity systems with durable workflows
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
//! Singleton registration helper.
//!
//! Provides a convenience function for registering singletons with the cluster.
//! A singleton runs on exactly one runner — the one that owns the shard
//! computed by hashing the singleton name within its shard group.
//!
//! Singletons receive a [`SingletonContext`] which includes a cancellation token
//! for graceful shutdown when the singleton's shard migrates to another node.
//!
//! Ported from Effect's `Singleton.ts`.

use crate::error::ClusterError;
use crate::sharding::Sharding;
use futures::future::BoxFuture;
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

/// Context passed to singleton factory functions.
///
/// Contains resources the singleton can use during its lifetime, including
/// a cancellation token for graceful shutdown.
///
/// # Example
///
/// ```text
/// use cruster::singleton::{register_singleton, SingletonContext};
///
/// register_singleton(&*sharding, "leader-election", |ctx: SingletonContext| async move {
///     // Opt-in to graceful shutdown - singleton will wait for this function to return
///     let cancel = ctx.cancellation();
///     
///     loop {
///         tokio::select! {
///             _ = cancel.cancelled() => {
///                 // Graceful shutdown: commit pending work, close connections
///                 tracing::info!("singleton shutting down gracefully");
///                 break;
///             }
///             _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {
///                 // Do periodic work
///             }
///         }
///     }
///     Ok(())
/// }).await?;
/// ```
pub struct SingletonContext {
    /// Inner cancellation token.
    inner: CancellationToken,
    /// Flag indicating whether the singleton has opted in to manage cancellation.
    /// This is shared with the spawner to determine shutdown behavior.
    pub(crate) managed: Arc<AtomicBool>,
}

impl SingletonContext {
    /// Creates a new singleton context with an externally provided managed flag.
    /// This allows the caller to share the managed flag with other components
    /// (e.g., `SingletonEntry`) so they can check if the singleton opted in
    /// to manage its own cancellation.
    pub(crate) fn new(cancellation: CancellationToken, managed: Arc<AtomicBool>) -> Self {
        Self {
            inner: cancellation,
            managed,
        }
    }

    /// Returns a cancellation token for graceful shutdown.
    ///
    /// **By calling this method, the singleton commits to observing the token
    /// and returning when cancelled.** The runtime will wait for the singleton
    /// to complete gracefully instead of force-cancelling it.
    ///
    /// If this method is never called, the singleton will be force-cancelled
    /// when shutdown is requested.
    ///
    /// # Example
    ///
    /// ```text
    /// |ctx: SingletonContext| async move {
    ///     let cancel = ctx.cancellation();
    ///     
    ///     loop {
    ///         tokio::select! {
    ///             _ = cancel.cancelled() => break,
    ///             _ = do_work() => {}
    ///         }
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn cancellation(&self) -> CancellationToken {
        self.managed.store(true, Ordering::Release);
        self.inner.clone()
    }

    /// Check if cancellation has been requested without opting in to manage it.
    ///
    /// This is useful for quick checks without committing to graceful shutdown.
    pub fn is_cancelled(&self) -> bool {
        self.inner.is_cancelled()
    }
}

/// Register a singleton that runs on exactly one runner in the cluster.
///
/// The `run` closure is executed only on the runner that owns the shard
/// computed from the singleton name and shard group (default group when not
/// specified). If that runner goes down, the singleton migrates to whichever
/// runner acquires the shard.
///
/// The closure receives a [`SingletonContext`] with a cancellation token that
/// is triggered when the singleton should shut down gracefully.
///
/// # Examples
///
/// ```text
/// use cruster::singleton::{register_singleton, SingletonContext};
///
/// register_singleton(&*sharding, "leader-election", |ctx: SingletonContext| async move {
///     loop {
///         tokio::select! {
///             _ = ctx.cancellation.cancelled() => {
///                 tracing::info!("shutting down");
///                 break;
///             }
///             _ = do_work() => {}
///         }
///     }
///     Ok(())
/// }).await?;
/// ```
pub async fn register_singleton<F, Fut>(
    sharding: &dyn Sharding,
    name: &str,
    run: F,
) -> Result<(), ClusterError>
where
    F: Fn(SingletonContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), ClusterError>> + Send + 'static,
{
    sharding
        .register_singleton(
            name,
            None,
            Arc::new(move |ctx| -> BoxFuture<'static, Result<(), ClusterError>> {
                Box::pin(run(ctx))
            }),
        )
        .await
}

/// Builder for configuring and registering a singleton.
///
/// Provides a fluent API for singleton registration with optional configuration.
pub struct SingletonBuilder<F> {
    name: String,
    run: F,
}

impl<F, Fut> SingletonBuilder<F>
where
    F: Fn(SingletonContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), ClusterError>> + Send + 'static,
{
    /// Create a new singleton builder.
    pub fn new(name: impl Into<String>, run: F) -> Self {
        Self {
            name: name.into(),
            run,
        }
    }

    /// Register this singleton with the given sharding instance.
    pub async fn register(self, sharding: &dyn Sharding) -> Result<(), ClusterError> {
        register_singleton(sharding, &self.name, self.run).await
    }
}

/// Create a singleton builder with the given name and run function.
///
/// # Examples
///
/// ```text
/// use cruster::singleton::{singleton, SingletonContext};
///
/// singleton("metrics-aggregator", |ctx: SingletonContext| async move {
///     loop {
///         tokio::select! {
///             _ = ctx.cancellation.cancelled() => break,
///             _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => {
///                 // aggregate metrics
///             }
///         }
///     }
///     Ok(())
/// })
/// .register(&*sharding)
/// .await?;
/// ```
pub fn singleton<F, Fut>(name: impl Into<String>, run: F) -> SingletonBuilder<F>
where
    F: Fn(SingletonContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), ClusterError>> + Send + 'static,
{
    SingletonBuilder::new(name, run)
}

/// A boxed singleton run function (reusable across re-spawns).
///
/// The function receives a [`SingletonContext`] and returns a future that
/// completes when the singleton finishes (or should be restarted on error).
pub type SingletonRun =
    Arc<dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>> + Send + Sync>;

/// Register multiple singletons at once.
///
/// Registers all singletons sequentially, returning on the first error.
/// Each singleton's factory receives a [`SingletonContext`] for graceful shutdown.
pub async fn register_singletons(
    sharding: &dyn Sharding,
    singletons: Vec<(String, SingletonRun)>,
) -> Result<(), ClusterError> {
    for (name, run) in singletons {
        sharding.register_singleton(&name, None, run).await?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ShardingConfig;
    use crate::metrics::ClusterMetrics;
    use crate::sharding_impl::ShardingImpl;
    use crate::storage::noop_runners::NoopRunners;
    use std::sync::Arc;

    /// Create a minimal ShardingImpl with NoopRunners for unit tests.
    async fn test_sharding() -> Arc<ShardingImpl> {
        let config = Arc::new(ShardingConfig::default());
        let metrics = Arc::new(ClusterMetrics::unregistered());
        let s =
            ShardingImpl::new(config, Arc::new(NoopRunners), None, None, None, metrics).unwrap();
        s.acquire_all_shards().await;
        s
    }

    #[tokio::test]
    async fn register_singleton_via_helper() {
        let sharding = test_sharding().await;
        let executed = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let executed_clone = executed.clone();

        register_singleton(
            sharding.as_ref(),
            "test-singleton",
            move |_ctx: SingletonContext| {
                let e = executed_clone.clone();
                async move {
                    e.store(true, std::sync::atomic::Ordering::SeqCst);
                    Ok(())
                }
            },
        )
        .await
        .unwrap();

        // Give the singleton time to execute
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert!(executed.load(std::sync::atomic::Ordering::SeqCst));
    }

    #[tokio::test]
    async fn singleton_builder_api() {
        let sharding = test_sharding().await;
        let executed = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let executed_clone = executed.clone();

        singleton("builder-singleton", move |_ctx: SingletonContext| {
            let e = executed_clone.clone();
            async move {
                e.store(true, std::sync::atomic::Ordering::SeqCst);
                Ok(())
            }
        })
        .register(sharding.as_ref())
        .await
        .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert!(executed.load(std::sync::atomic::Ordering::SeqCst));
    }

    #[tokio::test]
    async fn register_multiple_singletons() {
        let sharding = test_sharding().await;
        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));

        let mut singletons: Vec<(String, SingletonRun)> = Vec::new();

        for i in 0..3 {
            let c = count.clone();
            singletons.push((
                format!("singleton-{i}"),
                Arc::new(
                    move |_ctx| -> BoxFuture<'static, Result<(), ClusterError>> {
                        let c = c.clone();
                        Box::pin(async move {
                            c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                            Ok(())
                        })
                    },
                ),
            ));
        }

        register_singletons(sharding.as_ref(), singletons)
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn singleton_receives_cancellation_token() {
        let sharding = test_sharding().await;
        let token_received = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let token_received_clone = token_received.clone();

        register_singleton(
            sharding.as_ref(),
            "cancellation-test",
            move |ctx: SingletonContext| {
                let t = token_received_clone.clone();
                async move {
                    // Verify we received a valid cancellation token
                    // (it should not be cancelled initially)
                    if !ctx.is_cancelled() {
                        t.store(true, std::sync::atomic::Ordering::SeqCst);
                    }
                    Ok(())
                }
            },
        )
        .await
        .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert!(token_received.load(std::sync::atomic::Ordering::SeqCst));
    }

    #[tokio::test]
    async fn singleton_not_managing_cancellation_is_force_cancelled() {
        let sharding = test_sharding().await;

        register_singleton(
            sharding.as_ref(),
            "unmanaged-singleton",
            move |_ctx: SingletonContext| async move {
                // This singleton does NOT call ctx.cancellation()
                // so it will be force-cancelled on shutdown
                loop {
                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                }
                #[allow(unreachable_code)]
                Ok(())
            },
        )
        .await
        .unwrap();

        // Give the singleton time to start
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Shutdown should complete quickly because singleton is force-cancelled
        let start = std::time::Instant::now();
        sharding.shutdown().await.unwrap();
        let elapsed = start.elapsed();

        // Should complete in well under 1 second (the singleton's sleep duration)
        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "shutdown took too long ({:?}), singleton may not have been force-cancelled",
            elapsed
        );
    }

    #[tokio::test]
    async fn singleton_managing_cancellation_waits_for_graceful_shutdown() {
        let sharding = test_sharding().await;
        let cleanup_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let cleanup_ran_clone = cleanup_ran.clone();

        register_singleton(
            sharding.as_ref(),
            "managed-singleton",
            move |ctx: SingletonContext| {
                let cleanup = cleanup_ran_clone.clone();
                async move {
                    // This singleton DOES call ctx.cancellation()
                    // so the runtime will wait for it to finish
                    let cancel = ctx.cancellation();

                    loop {
                        tokio::select! {
                            _ = cancel.cancelled() => {
                                // Graceful shutdown - do cleanup
                                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                                cleanup.store(true, std::sync::atomic::Ordering::SeqCst);
                                break;
                            }
                            _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {
                                // Keep running
                            }
                        }
                    }
                    Ok(())
                }
            },
        )
        .await
        .unwrap();

        // Give the singleton time to start
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Shutdown should wait for graceful cleanup
        sharding.shutdown().await.unwrap();

        // Cleanup SHOULD have run
        assert!(
            cleanup_ran.load(std::sync::atomic::Ordering::SeqCst),
            "cleanup should run when singleton manages cancellation"
        );
    }
}