greentic-runner-host 1.2.2

Host runtime shim for Greentic runner: config, pack loading, activity handling
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
use std::str::FromStr;
use std::sync::{Arc, Weak};
use std::time::Duration;

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use cron::Schedule;
use serde_json::json;
use tokio::task::JoinHandle;
use tokio::time::sleep;
use tokio_util::sync::CancellationToken;

use crate::engine::runtime::IngressEnvelope;
use crate::runtime::TenantRuntime;

/// Check every configured cron expression without starting anything, so a
/// reload can reject a bad schedule BEFORE it swaps the runtime in (timers are
/// only spawned after the swap, see `watcher::reload_once`).
pub fn validate_timers(runtime: &TenantRuntime) -> Result<()> {
    for timer in &runtime.config().timers {
        Schedule::from_str(&normalize_cron(&timer.cron))
            .with_context(|| format!("invalid cron expression for {}", timer.schedule_id()))?;
    }
    Ok(())
}

pub fn spawn_timers(runtime: Arc<TenantRuntime>) -> Result<Vec<JoinHandle<()>>> {
    let mut handles = Vec::new();

    for timer in runtime.config().timers.clone() {
        let cron_expr = timer.cron.clone();
        let normalized = normalize_cron(&cron_expr);
        let schedule = Schedule::from_str(&normalized)
            .with_context(|| format!("invalid cron expression for {}", timer.schedule_id()))?;
        let flow_id = timer.flow_id.clone();
        let schedule_id = timer.schedule_id().to_string();
        let tenant = runtime.config().tenant.clone();
        // Hold the runtime weakly: a task owning an `Arc<TenantRuntime>` would
        // keep it alive forever, so `TenantRuntime::drop` (which aborts the
        // timers) could never run and every reload would duplicate cron firing.
        let runtime_weak: Weak<TenantRuntime> = Arc::downgrade(&runtime);
        let cancel = runtime.timer_cancel_token();

        let handle = tokio::spawn(async move {
            tracing::info!(
                flow_id = %flow_id,
                schedule_id = %schedule_id,
                cron = %cron_expr,
                normalized_cron = %normalized,
                "registered timer schedule"
            );
            drive_schedule(&schedule, &cancel, |next| {
                let runtime_weak = runtime_weak.clone();
                let tenant = tenant.clone();
                let flow_id = flow_id.clone();
                let schedule_id = schedule_id.clone();
                async move {
                    let Some(runtime_clone) = runtime_weak.upgrade() else {
                        tracing::info!(
                            flow_id = %flow_id,
                            schedule_id = %schedule_id,
                            "tenant runtime dropped; stopping timer schedule"
                        );
                        return false;
                    };
                    fire_tick(&runtime_clone, tenant, flow_id, schedule_id, next).await;
                    true
                }
            })
            .await;
        });

        handles.push(handle);
    }

    Ok(handles)
}

/// Sleep-then-fire loop for one schedule. `cancel` is observed ONLY while
/// sleeping: stop before the next tick, never in the middle of one. `fire`
/// returns `false` to end the schedule.
async fn drive_schedule<F, Fut>(schedule: &Schedule, cancel: &CancellationToken, mut fire: F)
where
    F: FnMut(DateTime<Utc>) -> Fut,
    Fut: std::future::Future<Output = bool>,
{
    // Re-derive the next tick from "now" each round (rather than walking
    // one `upcoming` iterator) so ticks that elapsed while a slow flow
    // ran are skipped instead of fired back-to-back.
    let mut last_fired: Option<DateTime<Utc>> = None;
    while let Some(next) = schedule
        .after(&search_origin(Utc::now(), last_fired))
        .next()
    {
        last_fired = Some(next);
        if let Some(wait) = duration_until(next) {
            tokio::select! {
                _ = sleep(wait) => {}
                _ = cancel.cancelled() => {
                    tracing::info!("timer schedule superseded; stopping before next tick");
                    return;
                }
            }
        } else {
            continue;
        }
        // A cancel that raced the sleep finishing must not fire the tick too:
        // the replacement runtime owns it.
        if cancel.is_cancelled() {
            return;
        }
        if !fire(next).await {
            return;
        }
    }
    tracing::info!("timer schedule completed");
}

async fn fire_tick(
    runtime_clone: &Arc<TenantRuntime>,
    tenant: String,
    flow_id: String,
    schedule_id: String,
    next: DateTime<Utc>,
) {
    let pack_id = match runtime_clone.engine().flow_by_id(&flow_id) {
        Some(flow) => flow.pack_id.clone(),
        None => {
            tracing::error!(
                flow_id = %flow_id,
                schedule_id = %schedule_id,
                "timer flow is ambiguous; pack_id is required"
            );
            return;
        }
    };
    let payload = json!({
        "now": next.to_rfc3339(),
        "schedule_id": schedule_id.clone(),
    });
    tracing::info!(
        flow_id = %flow_id,
        schedule_id = %schedule_id,
        scheduled_for = %next,
        "triggering timer flow"
    );
    let envelope = IngressEnvelope {
        tenant,
        env: None,
        pack_id: Some(pack_id),
        flow_id: flow_id.clone(),
        flow_type: Some("timer".into()),
        action: Some("timer".into()),
        session_hint: Some(schedule_id.clone()),
        provider: Some("timer".into()),
        // Timers fire without a messaging endpoint by definition.
        messaging_endpoint_id: None,
        channel: Some(schedule_id.clone()),
        conversation: Some(schedule_id.clone()),
        user: None,
        // A timer fires the flow from its entrypoint; it carries no card nav.
        entry_node: None,
        activity_id: Some(format!("{}@{}", schedule_id, next)),
        timestamp: Some(next.to_rfc3339()),
        payload,
        metadata: None,
        reply_scope: None,
    }
    .canonicalize();
    match runtime_clone.state_machine().handle(envelope).await {
        Ok(output) => {
            tracing::info!(
                flow_id = %flow_id,
                schedule_id = %schedule_id,
                now = %next,
                response = %output,
                "timer flow completed"
            );
        }
        Err(err) => {
            let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
            tracing::error!(
                flow_id = %flow_id,
                schedule_id = %schedule_id,
                error.cause_chain = ?chain,
                "timer flow execution failed"
            );
        }
    }
}

/// Where to search for the next tick: never earlier than the last tick fired,
/// so a wall clock stepped backwards (NTP) cannot make a tick fire twice.
fn search_origin(now: DateTime<Utc>, last_fired: Option<DateTime<Utc>>) -> DateTime<Utc> {
    match last_fired {
        Some(last) if last > now => last,
        _ => now,
    }
}

fn duration_until(next: DateTime<Utc>) -> Option<Duration> {
    let now = Utc::now();
    let duration = next - now;
    if duration.num_milliseconds() <= 0 {
        return Some(Duration::from_secs(0));
    }
    duration.to_std().ok()
}

fn normalize_cron(expr: &str) -> String {
    if expr.split_whitespace().count() == 5 {
        format!("0 {expr}")
    } else {
        expr.to_string()
    }
}

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

    #[test]
    fn normalize_cron_adds_seconds_for_five_fields() {
        assert_eq!(normalize_cron("*/5 * * * *"), "0 */5 * * * *");
        assert_eq!(normalize_cron("0 */2 * * * *"), "0 */2 * * * *");
    }

    #[test]
    fn a_clock_stepped_back_does_not_repeat_a_fired_tick() {
        let schedule = Schedule::from_str("0 * * * * *").expect("cron");
        let now = Utc::now();
        let fired = schedule.after(&now).next().expect("tick");
        // Wall clock stepped back to before the tick that just fired.
        let stepped_back = fired - chrono::Duration::seconds(30);
        let naive = schedule.after(&stepped_back).next().expect("tick");
        assert_eq!(naive, fired, "re-deriving from now would repeat the tick");
        let origin = search_origin(stepped_back, Some(fired));
        let next = schedule.after(&origin).next().expect("tick");
        assert!(next > fired);
        assert_eq!(
            search_origin(fired + chrono::Duration::seconds(5), Some(fired)),
            fired + chrono::Duration::seconds(5)
        );
    }

    #[test]
    fn duration_until_returns_zero_for_past_times() {
        let past = Utc::now() - chrono::Duration::seconds(10);
        assert_eq!(duration_until(past).unwrap(), Duration::from_secs(0));
    }

    #[test]
    fn duration_until_returns_positive_duration_for_future_times() {
        let future = Utc::now() + chrono::Duration::milliseconds(150);
        let wait = duration_until(future).unwrap();
        assert!(wait > Duration::from_secs(0));
        assert!(wait <= Duration::from_secs(1));
    }

    #[test]
    fn normalize_cron_preserves_non_five_field_expressions() {
        assert_eq!(normalize_cron("@daily"), "@daily");
        assert_eq!(normalize_cron("0 0 */2 * * *"), "0 0 */2 * * *");
    }

    #[tokio::test]
    async fn spawn_timers_is_empty_when_config_has_no_timers() {
        let (_workspace, runtime) = crate::test_support::build_test_runtime()
            .await
            .expect("runtime");
        let timers = spawn_timers(Arc::clone(&runtime)).expect("spawn timers");
        assert!(timers.is_empty());
    }

    #[tokio::test]
    async fn timer_task_does_not_keep_the_runtime_alive() {
        let (_workspace, runtime) = crate::test_support::build_test_runtime_with_timers(
            r#"[{ flow_id: "flow.main", cron: "* * * * * *" }]"#,
        )
        .await
        .expect("runtime");
        let weak = Arc::downgrade(&runtime);
        let mut timers = spawn_timers(runtime).expect("spawn timers");
        // The caller's Arc was the only strong reference.
        assert!(
            weak.upgrade().is_none(),
            "timer task must hold the runtime weakly"
        );
        let handle = timers.pop().expect("one timer");
        tokio::time::timeout(Duration::from_secs(5), handle)
            .await
            .expect("timer task must stop once the runtime is gone")
            .expect("timer task must not panic");
    }

    #[test]
    fn next_tick_is_always_in_the_future() {
        let schedule = Schedule::from_str("* * * * * *").expect("schedule");
        let next = schedule.after(&Utc::now()).next().expect("next tick");
        assert!(next > Utc::now() - chrono::Duration::milliseconds(50));
    }

    #[tokio::test]
    async fn spawn_timers_rejects_an_invalid_cron_expression() {
        let (_workspace, runtime) = crate::test_support::build_test_runtime_with_timers(
            r#"[{ flow_id: "flow.main", cron: "not a cron" }]"#,
        )
        .await
        .expect("runtime");
        let err = spawn_timers(runtime).expect_err("bad cron must be refused");
        assert!(
            err.to_string().contains("invalid cron expression"),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn validate_timers_rejects_bad_cron_without_spawning_and_abort_stops_timers() {
        let (_workspace, bad) = crate::test_support::build_test_runtime_with_timers(
            r#"[{ flow_id: "flow.main", cron: "not a cron" }]"#,
        )
        .await
        .expect("runtime");
        assert!(validate_timers(&bad).is_err());

        let (_workspace, good) = crate::test_support::build_test_runtime_with_timers(
            r#"[{ flow_id: "flow.main", cron: "0 0 1 1 *" }]"#,
        )
        .await
        .expect("runtime");
        validate_timers(&good).expect("valid cron");
        let handles = spawn_timers(Arc::clone(&good)).expect("spawn");
        good.register_timers(handles);
        // A superseded runtime stops its timers while still referenced.
        good.abort_timers();
        assert_eq!(good.timer_count(), 0);
    }

    #[tokio::test]
    async fn a_timer_for_an_unknown_flow_keeps_running_instead_of_dying() {
        let (_workspace, runtime) = crate::test_support::build_test_runtime_with_timers(
            r#"[{ flow_id: "flow.does.not.exist", cron: "* * * * * *", schedule_id: "every-second" }]"#,
        )
        .await
        .expect("runtime");
        // Keep the runtime alive: timers only hold it weakly.
        let handles = spawn_timers(Arc::clone(&runtime)).expect("spawn timers");
        assert_eq!(handles.len(), 1);
        // Let at least one tick fire against the missing flow.
        sleep(Duration::from_millis(2300)).await;
        assert!(
            !handles[0].is_finished(),
            "an unresolvable flow must be logged and skipped, not end the schedule"
        );
        for handle in handles {
            handle.abort();
        }
        drop(runtime);
    }

    #[tokio::test]
    async fn cancelling_while_a_tick_runs_lets_that_tick_finish_and_stops_before_the_next() {
        let schedule = Schedule::from_str("* * * * * *").expect("schedule");
        let cancel = CancellationToken::new();
        let started = Arc::new(tokio::sync::Notify::new());
        let finished = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let fires = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let task = {
            let (cancel, started, finished, fires) = (
                cancel.clone(),
                Arc::clone(&started),
                Arc::clone(&finished),
                Arc::clone(&fires),
            );
            tokio::spawn(async move {
                drive_schedule(&schedule, &cancel, |_| {
                    let (started, finished, fires) = (
                        Arc::clone(&started),
                        Arc::clone(&finished),
                        Arc::clone(&fires),
                    );
                    async move {
                        fires.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                        started.notify_one();
                        // Longer than two schedule periods.
                        sleep(Duration::from_millis(2300)).await;
                        finished.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                        true
                    }
                })
                .await;
            })
        };
        tokio::time::timeout(Duration::from_secs(5), started.notified())
            .await
            .expect("first tick must start");
        // What `TenantRuntime::abort_timers` does.
        cancel.cancel();
        tokio::time::timeout(Duration::from_secs(10), task)
            .await
            .expect("schedule must stop after the running tick")
            .expect("no panic");
        assert_eq!(finished.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(
            fires.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "no further tick may start after cancellation"
        );
    }

    #[tokio::test]
    async fn abort_timers_cancels_the_token_the_timer_tasks_watch() {
        let (_workspace, runtime) = crate::test_support::build_test_runtime_with_timers(
            r#"[{ flow_id: "flow.main", cron: "0 0 1 1 *" }]"#,
        )
        .await
        .expect("runtime");
        let token = runtime.timer_cancel_token();
        let handles = spawn_timers(Arc::clone(&runtime)).expect("spawn");
        runtime.register_timers(handles);
        assert!(!token.is_cancelled());
        runtime.abort_timers();
        assert!(token.is_cancelled());
        assert_eq!(runtime.timer_count(), 0);
    }
}