loopctl 0.1.0

A trait-based framework for building agent loops with pluggable LLM clients, tools, and memory
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
//! Composable heartbeat and timeout wrapper for any stream.
//!
//! [`HeartbeatStream`] wraps any `Stream<Item = Result<StreamEvent, ApiError>>`
//! and adds two behaviours:
//!
//! 1. **Heartbeat callbacks** — Fires a callback at regular intervals to report
//!    elapsed time and timeout status.
//! 2. **Hard timeout** — Returns an [`ApiError`] if the stream exceeds a
//!    configured maximum duration.
//!
//! It does **not** retry or fall back — that's [`StreamHandler`](super::handler::StreamHandler)'s
//! job. Use this when you need heartbeat/timeout on a stream you've already opened.
//!
//! # Architecture
//!
//! ```text
//! ┌────────────────────────────────────┐
//! │        HeartbeatStream<S>          │
//! │                                    │
//! │  poll_next():                      │
//! │    1. Check heartbeat interval     │
//! │       └─ fire callback if elapsed  │
//! │    2. Check hard timeout           │
//! │       └─ return ApiError if hit    │
//! │    3. Delegate to inner stream     │
//! └────────────────────────────────────┘
//! ```
//!
//! # Quick Start
//!
//! ```rust
//! use loopctl::stream::heartbeat::{HeartbeatStream, HeartbeatConfig, HeartbeatData};
//! use std::time::Duration;
//! use std::sync::{Arc, Mutex};
//!
//! let callbacks = Arc::new(Mutex::new(Vec::new()));
//! let cb = callbacks.clone();
//!
//! let config = HeartbeatConfig::new(
//!     Duration::from_secs(30),  // heartbeat_interval
//!     Duration::from_secs(600), // timeout
//!     Box::new(move |data: HeartbeatData| {
//!         cb.lock().unwrap().push(data.elapsed);
//!     }),
//! );
//! ```

use crate::api::error::ApiError;
use crate::stream::StreamEvent;
use futures::Stream;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

// ===================================================
// HeartbeatData
// ===================================================

/// Data emitted on each heartbeat callback.
///
/// Passed to the callback registered in [`HeartbeatConfig`] at each
/// heartbeat interval.
///
/// # Example
///
/// ```rust
/// use loopctl::stream::heartbeat::HeartbeatData;
/// use std::time::Duration;
///
/// let data = HeartbeatData {
///     elapsed: Duration::from_secs(45),
///     is_timeout: false,
/// };
/// assert!(!data.is_timeout);
/// ```
#[derive(Debug, Clone)]
pub struct HeartbeatData {
    /// Time elapsed since stream start.
    pub elapsed: Duration,
    /// Whether the stream has exceeded its configured timeout.
    pub is_timeout: bool,
}

// ===================================================
// HeartbeatCallback
// ===================================================

/// Callback type for heartbeat events.
///
/// A `Box<dyn Fn(HeartbeatData) + Send + Sync>` that is called at each
/// heartbeat interval with the current stream status.
pub type HeartbeatCallback = Box<dyn Fn(HeartbeatData) + Send + Sync>;

// ===================================================
// HeartbeatConfig
// ===================================================

/// Configuration for a [`HeartbeatStream`].
///
/// Holds the heartbeat interval, hard timeout, and callback function.
/// Created via [`HeartbeatConfig::new()`].
///
/// # Example
///
/// ```rust
/// use loopctl::stream::heartbeat::{HeartbeatConfig, HeartbeatData};
/// use std::time::Duration;
///
/// let config = HeartbeatConfig::new(
///     Duration::from_secs(30),
///     Duration::from_secs(600),
///     Box::new(|_data: HeartbeatData| {}),
/// );
/// assert_eq!(config.heartbeat_interval(), Duration::from_secs(30));
/// assert_eq!(config.timeout(), Duration::from_secs(600));
/// ```
pub struct HeartbeatConfig {
    /// Interval between heartbeat callbacks.
    heartbeat_interval: Duration,
    /// Maximum total stream duration before triggering a hard timeout.
    timeout: Duration,
    /// Callback fired at each heartbeat interval.
    on_heartbeat: HeartbeatCallback,
}

impl std::fmt::Debug for HeartbeatConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HeartbeatConfig")
            .field("heartbeat_interval", &self.heartbeat_interval)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}

impl HeartbeatConfig {
    /// Create a new heartbeat configuration.
    ///
    /// # Arguments
    ///
    /// - `heartbeat_interval` — How often to fire the callback.
    /// - `timeout` — Maximum stream duration before returning an error.
    /// - `on_heartbeat` — Callback invoked at each interval.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::stream::heartbeat::{HeartbeatConfig, HeartbeatData};
    /// use std::time::Duration;
    ///
    /// let config = HeartbeatConfig::new(
    ///     Duration::from_secs(15),
    ///     Duration::from_secs(300),
    ///     Box::new(|data: HeartbeatData| {
    ///         println!("heartbeat: {:.1}s elapsed", data.elapsed.as_secs_f64());
    ///     }),
    /// );
    /// ```
    #[must_use]
    pub fn new(
        heartbeat_interval: Duration,
        timeout: Duration,
        on_heartbeat: HeartbeatCallback,
    ) -> Self {
        Self {
            heartbeat_interval,
            timeout,
            on_heartbeat,
        }
    }

    /// Returns the configured heartbeat interval.
    #[must_use]
    pub fn heartbeat_interval(&self) -> Duration {
        self.heartbeat_interval
    }

    /// Returns the configured hard timeout.
    #[must_use]
    pub fn timeout(&self) -> Duration {
        self.timeout
    }
}

// ===================================================
// HeartbeatStream
// ===================================================

/// A stream wrapper that emits heartbeat callbacks and enforces a hard timeout.
///
/// Wraps any `Stream<Item = Result<StreamEvent, ApiError>>` and adds:
/// - Periodic heartbeat callbacks via [`HeartbeatConfig`].
/// - A hard timeout that returns an [`ApiError`] when exceeded.
///
/// Does **not** retry or fallback — use [`StreamHandler`](super::handler::StreamHandler) instead.
///
/// # Composability
///
/// `HeartbeatStream` implements `Stream` directly, so it composes with
/// any other stream wrapper. Use it on any stream you've already opened
/// when you need heartbeat/timeout without the full handler lifecycle.
///
/// # Example
///
/// ```rust
/// use loopctl::stream::heartbeat::{HeartbeatStream, HeartbeatConfig, HeartbeatData};
/// use std::time::Duration;
///
/// let config = HeartbeatConfig::new(
///     Duration::from_secs(30),
///     Duration::from_secs(600),
///     Box::new(|_data: HeartbeatData| {}),
/// );
///
/// // Wrap any stream:
/// // let heartbeat_stream = HeartbeatStream::new(inner_stream, config);
/// // while let Some(result) = futures::StreamExt::next(&mut heartbeat_stream).await {
/// //     // ...
/// // }
/// ```
pub struct HeartbeatStream<S> {
    /// The inner stream being wrapped.
    inner: S,
    /// Heartbeat and timeout configuration.
    config: HeartbeatConfig,
    /// Time of the last heartbeat callback.
    last_heartbeat: Instant,
    /// Time the stream was created.
    start: Instant,
    /// A Sleep that fires at the hard timeout deadline.
    ///
    /// Ensures the runtime wakes this task when the timeout expires,
    /// even if the inner stream is Pending and nobody re-polls.
    timeout_sleep: std::pin::Pin<Box<tokio::time::Sleep>>,
}

impl<S> HeartbeatStream<S> {
    /// Create a new heartbeat stream wrapping the given inner stream.
    ///
    /// The heartbeat timer starts immediately upon construction.
    /// The first heartbeat callback fires after `heartbeat_interval`
    /// elapses (checked on each `poll_next`).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::stream::heartbeat::{HeartbeatStream, HeartbeatConfig, HeartbeatData};
    /// use std::time::Duration;
    ///
    /// let config = HeartbeatConfig::new(
    ///     Duration::from_secs(30),
    ///     Duration::from_secs(600),
    ///     Box::new(|_data: HeartbeatData| {}),
    /// );
    /// // let stream = HeartbeatStream::new(inner_stream, config);
    /// ```
    pub fn new(inner: S, config: HeartbeatConfig) -> Self {
        /// 30 years in seconds — used as a far-future deadline fallback.
        /// Computed as a const so the compiler verifies no overflow.
        const THIRTY_YEARS_SECS: u64 = 86400 * 365 * 30;

        let now = Instant::now();
        // checked_add returns None only for extreme Duration values (hundreds of years).
        // Fallback: 30 years from now, which is effectively infinite.
        let far_future = || {
            Instant::now()
                .checked_add(Duration::from_secs(THIRTY_YEARS_SECS))
                .unwrap_or(Instant::now())
        };
        let deadline = now.checked_add(config.timeout).unwrap_or_else(far_future);
        let timeout_sleep = Box::pin(tokio::time::sleep_until(tokio::time::Instant::from_std(
            deadline,
        )));
        Self {
            inner,
            config,
            last_heartbeat: now,
            start: now,
            timeout_sleep,
        }
    }
}

impl<S> Stream for HeartbeatStream<S>
where
    S: Stream<Item = Result<StreamEvent, ApiError>> + Unpin,
{
    type Item = Result<StreamEvent, ApiError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();

        // Check heartbeat interval — fire callback if elapsed.
        if this.last_heartbeat.elapsed() >= this.config.heartbeat_interval {
            let elapsed = this.start.elapsed();
            let data = HeartbeatData {
                elapsed,
                is_timeout: elapsed > this.config.timeout,
            };
            (this.config.on_heartbeat)(data);
            this.last_heartbeat = Instant::now();
        }

        // Hard timeout — check the Sleep first (proactive wake-up),
        // then fall back to elapsed() for the sync case.
        if this.timeout_sleep.as_mut().poll(cx).is_ready()
            || this.start.elapsed() > this.config.timeout
        {
            return Poll::Ready(Some(Err(ApiError::Api(format!(
                "Stream timeout after {}s",
                this.config.timeout.as_secs()
            )))));
        }

        // Delegate to inner stream.
        Pin::new(&mut this.inner).poll_next(cx)
    }
}

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

    struct VecStream {
        items: Vec<Result<StreamEvent, ApiError>>,
    }

    impl Stream for VecStream {
        type Item = Result<StreamEvent, ApiError>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Ready(self.get_mut().items.pop())
        }
    }

    fn make_config(
        callbacks: &std::sync::Arc<std::sync::Mutex<Vec<HeartbeatData>>>,
    ) -> HeartbeatConfig {
        let cb = callbacks.clone();
        HeartbeatConfig::new(
            Duration::from_millis(10),
            Duration::from_secs(60),
            Box::new(move |data: HeartbeatData| {
                cb.lock().unwrap().push(data);
            }),
        )
    }

    #[test]
    fn heartbeat_data_fields() {
        let data = HeartbeatData {
            elapsed: Duration::from_secs(30),
            is_timeout: true,
        };
        assert_eq!(data.elapsed, Duration::from_secs(30));
        assert!(data.is_timeout);
    }

    #[test]
    fn config_accessors() {
        let config = HeartbeatConfig::new(
            Duration::from_secs(15),
            Duration::from_secs(300),
            Box::new(|_| {}),
        );
        assert_eq!(config.heartbeat_interval(), Duration::from_secs(15));
        assert_eq!(config.timeout(), Duration::from_secs(300));
    }

    #[test]
    fn config_debug() {
        let config = HeartbeatConfig::new(
            Duration::from_secs(30),
            Duration::from_secs(600),
            Box::new(|_| {}),
        );
        let debug = format!("{config:?}");
        assert!(debug.contains("HeartbeatConfig"));
        assert!(debug.contains("heartbeat_interval"));
        assert!(debug.contains("timeout"));
    }

    #[tokio::test]
    async fn passes_through_events() {
        let callbacks: std::sync::Arc<std::sync::Mutex<Vec<HeartbeatData>>> =
            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let config = make_config(&callbacks);

        let inner = VecStream {
            items: vec![Ok(StreamEvent::Ping), Ok(StreamEvent::Ping)],
        };

        let mut stream = HeartbeatStream::new(inner, config);
        let first = stream.next().await;
        assert!(first.is_some());

        let second = stream.next().await;
        assert!(second.is_some());

        let third = stream.next().await;
        assert!(third.is_none());
    }

    #[tokio::test]
    async fn passes_through_errors() {
        let callbacks: std::sync::Arc<std::sync::Mutex<Vec<HeartbeatData>>> =
            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let config = make_config(&callbacks);

        let inner = VecStream {
            items: vec![Err(ApiError::Api("test error".to_string()))],
        };

        let mut stream = HeartbeatStream::new(inner, config);
        let result = stream.next().await;
        assert!(matches!(result, Some(Err(ApiError::Api(_)))));
    }

    #[tokio::test]
    async fn fires_heartbeat_on_interval_sync() {
        let callbacks: std::sync::Arc<std::sync::Mutex<Vec<HeartbeatData>>> =
            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let config = make_config(&callbacks);
        let inner = VecStream {
            items: vec![Ok(StreamEvent::Ping)],
        };
        let mut stream = HeartbeatStream::new(inner, config);

        stream.last_heartbeat = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();

        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        let result = Pin::new(&mut stream).poll_next(&mut cx);

        assert!(matches!(result, Poll::Ready(Some(Ok(StreamEvent::Ping)))));

        let cbs = callbacks.lock().unwrap();
        assert_eq!(cbs.len(), 1);
        assert!(cbs[0].elapsed > Duration::ZERO);
    }

    #[tokio::test]
    async fn timeout_returns_error_sync() {
        // Verify that poll_next returns a timeout error when the timeout
        // has elapsed. We construct the stream, manually advance time by
        // setting start into the past, then poll.
        let callbacks: std::sync::Arc<std::sync::Mutex<Vec<HeartbeatData>>> =
            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let config = HeartbeatConfig::new(
            Duration::from_millis(10),
            Duration::from_millis(1),
            Box::new(move |data: HeartbeatData| {
                callbacks.lock().unwrap().push(data);
            }),
        );

        // VecStream that returns Pending on first poll (simulates waiting).
        let inner = VecStream { items: vec![] };
        let mut stream = HeartbeatStream::new(inner, config);

        // Manually set start into the past so timeout has elapsed.
        stream.start = Instant::now().checked_sub(Duration::from_secs(10)).unwrap();

        // Use a no-op waker to poll manually.
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        let result = Pin::new(&mut stream).poll_next(&mut cx);

        assert!(
            matches!(result, Poll::Ready(Some(Err(ApiError::Api(msg)))) if msg.contains("timeout"))
        );
    }
}