zeph-scheduler 0.20.1

Cron-based periodic task scheduler with SQLite persistence for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::future::Future;
use std::pin::Pin;

use semver::Version;
use serde::Deserialize;
use tokio::sync::mpsc;

use crate::error::SchedulerError;
use crate::task::TaskHandler;

const GITHUB_RELEASES_URL: &str = "https://api.github.com/repos/bug-ops/zeph/releases/latest";
const MAX_RESPONSE_BYTES: usize = 64 * 1024;

/// [`TaskHandler`] that polls the GitHub releases API for a newer Zeph version.
///
/// On each execution, `UpdateCheckHandler` fetches the latest release from
/// `https://api.github.com/repos/bug-ops/zeph/releases/latest`, compares the
/// `tag_name` field against `current_version` using semantic versioning, and sends a
/// human-readable notification message on `notify_tx` when a newer release is found.
///
/// Network and parse errors are logged as warnings; `execute` always returns `Ok(())`
/// so a transient failure does not stop the scheduler.
///
/// # Examples
///
/// ```rust,no_run
/// use tokio::sync::mpsc;
/// use zeph_scheduler::UpdateCheckHandler;
///
/// # #[tokio::main]
/// # async fn main() {
/// let (tx, mut rx) = mpsc::channel(1);
/// let handler = UpdateCheckHandler::new(env!("CARGO_PKG_VERSION"), tx);
///
/// use zeph_scheduler::TaskHandler;
/// handler
///     .execute(&serde_json::Value::Null)
///     .await
///     .expect("update check should not fail");
///
/// // A notification is sent only when a newer version exists on GitHub.
/// if let Ok(msg) = rx.try_recv() {
///     println!("{msg}");
/// }
/// # }
/// ```
pub struct UpdateCheckHandler {
    current_version: &'static str,
    notify_tx: mpsc::Sender<String>,
    http_client: reqwest::Client,
    /// Base URL for the GitHub releases API. Configurable for testing.
    base_url: String,
}

#[derive(Deserialize)]
struct ReleaseInfo {
    tag_name: Option<String>,
}

impl UpdateCheckHandler {
    /// Create a new handler.
    ///
    /// `current_version` should be `env!("CARGO_PKG_VERSION")`.
    /// Notifications are sent as formatted strings via `notify_tx`.
    ///
    /// # Panics
    ///
    /// Panics if the underlying `reqwest` client cannot be constructed (unreachable in practice).
    #[must_use]
    pub fn new(current_version: &'static str, notify_tx: mpsc::Sender<String>) -> Self {
        let http_client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(10))
            .user_agent(format!("zeph/{current_version}"))
            .build()
            .expect("reqwest client builder should not fail with timeout and user_agent");
        Self {
            current_version,
            notify_tx,
            http_client,
            base_url: GITHUB_RELEASES_URL.to_owned(),
        }
    }

    /// Override the GitHub releases API URL.
    ///
    /// Intended for tests only: point the handler at a local mock server so the
    /// test does not make real network requests.
    #[must_use]
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Extract and compare versions; returns `Some(remote_version_str)` when remote > current.
    fn newer_version(current: &str, tag_name: &str) -> Option<String> {
        let remote_str = tag_name.trim_start_matches('v');
        if remote_str.is_empty() {
            return None;
        }
        let current_v = Version::parse(current).ok()?;
        let remote_v = Version::parse(remote_str).ok()?;
        if remote_v > current_v {
            Some(remote_str.to_owned())
        } else {
            None
        }
    }
}

impl TaskHandler for UpdateCheckHandler {
    fn execute(
        &self,
        _config: &serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<(), SchedulerError>> + Send + '_>> {
        Box::pin(async move {
            let resp = self
                .http_client
                .get(&self.base_url)
                .header("Accept", "application/vnd.github+json")
                .send()
                .await;

            let resp = match resp {
                Ok(r) => r,
                Err(e) => {
                    tracing::warn!("update check request failed: {e}");
                    return Ok(());
                }
            };

            if !resp.status().is_success() {
                tracing::warn!("update check: HTTP {}", resp.status());
                return Ok(());
            }

            let bytes = match resp.bytes().await {
                Ok(b) => b,
                Err(e) => {
                    tracing::warn!("update check: failed to read response body: {e}");
                    return Ok(());
                }
            };
            if bytes.len() > MAX_RESPONSE_BYTES {
                tracing::warn!(
                    "update check: response body too large ({} bytes), skipping",
                    bytes.len()
                );
                return Ok(());
            }
            let info: ReleaseInfo = match serde_json::from_slice(&bytes) {
                Ok(v) => v,
                Err(e) => {
                    tracing::warn!("update check response parse failed: {e}");
                    return Ok(());
                }
            };

            let Some(tag_name) = info.tag_name else {
                tracing::warn!("update check: missing tag_name in response");
                return Ok(());
            };

            match Self::newer_version(self.current_version, &tag_name) {
                Some(remote) => {
                    let msg = format!(
                        "New version available: v{remote} (current: v{}).\nUpdate: https://github.com/bug-ops/zeph/releases/tag/v{remote}",
                        self.current_version
                    );
                    tracing::debug!("update available: {remote}");
                    let _ = self.notify_tx.send(msg).await;
                }
                None => {
                    tracing::debug!(
                        current = self.current_version,
                        remote = tag_name,
                        "no update available"
                    );
                }
            }

            Ok(())
        })
    }
}

#[cfg(test)]
mod tests {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;

    fn make_handler(
        current_version: &'static str,
        tx: mpsc::Sender<String>,
        server_url: &str,
    ) -> UpdateCheckHandler {
        UpdateCheckHandler::new(current_version, tx).with_base_url(server_url)
    }

    #[test]
    fn newer_version_detects_upgrade() {
        assert_eq!(
            UpdateCheckHandler::newer_version("0.11.0", "v0.12.0"),
            Some("0.12.0".to_owned())
        );
    }

    #[test]
    fn newer_version_same_version_no_notify() {
        assert_eq!(UpdateCheckHandler::newer_version("0.11.0", "v0.11.0"), None);
    }

    #[test]
    fn newer_version_older_remote_no_notify() {
        assert_eq!(UpdateCheckHandler::newer_version("0.11.0", "v0.10.0"), None);
    }

    #[test]
    fn newer_version_strips_v_prefix() {
        assert_eq!(
            UpdateCheckHandler::newer_version("1.0.0", "v2.0.0"),
            Some("2.0.0".to_owned())
        );
        assert_eq!(
            UpdateCheckHandler::newer_version("1.0.0", "2.0.0"),
            Some("2.0.0".to_owned())
        );
    }

    #[test]
    fn newer_version_invalid_current_returns_none() {
        assert_eq!(
            UpdateCheckHandler::newer_version("not-semver", "v1.0.0"),
            None
        );
    }

    #[test]
    fn newer_version_invalid_remote_returns_none() {
        assert_eq!(
            UpdateCheckHandler::newer_version("1.0.0", "v-garbage"),
            None
        );
    }

    #[test]
    fn newer_version_empty_tag_returns_none() {
        assert_eq!(UpdateCheckHandler::newer_version("1.0.0", ""), None);
    }

    // Prerelease versions (e.g. 0.12.0-rc.1) compare as greater than 0.11.0 per semver spec.
    // This is intentional: users should be notified of release candidates if they appear
    // on the GitHub releases/latest endpoint (which typically only returns stable releases).
    #[test]
    fn newer_version_prerelease_is_notified() {
        assert_eq!(
            UpdateCheckHandler::newer_version("0.11.0", "v0.12.0-rc.1"),
            Some("0.12.0-rc.1".to_owned())
        );
    }

    #[tokio::test]
    async fn test_execute_newer_version_sends_notification() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "tag_name": "v99.0.0"
            })))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        handler
            .execute(&serde_json::Value::Null)
            .await
            .expect("handler must not return an error");

        let msg = rx.try_recv().expect("notification must be sent");
        assert!(
            msg.contains("99.0.0"),
            "notification should mention new version"
        );
        assert!(
            msg.contains("0.11.0"),
            "notification should mention current version"
        );
    }

    #[tokio::test]
    async fn test_execute_same_version_no_notification() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "tag_name": "v0.11.0"
            })))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        handler
            .execute(&serde_json::Value::Null)
            .await
            .expect("handler must not return an error");

        assert!(
            rx.try_recv().is_err(),
            "no notification expected for same version"
        );
    }

    #[tokio::test]
    async fn test_execute_http_404_no_notification_no_panic() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(404))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        let result = handler.execute(&serde_json::Value::Null).await;
        assert!(result.is_ok(), "handler must return Ok on 404");
        assert!(rx.try_recv().is_err(), "no notification expected on 404");
    }

    #[tokio::test]
    async fn test_execute_http_429_rate_limit_graceful() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(429))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        let result = handler.execute(&serde_json::Value::Null).await;
        assert!(result.is_ok(), "handler must return Ok on 429");
        assert!(rx.try_recv().is_err(), "no notification expected on 429");
    }

    #[tokio::test]
    async fn test_execute_http_500_server_error_graceful() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        let result = handler.execute(&serde_json::Value::Null).await;
        assert!(result.is_ok(), "handler must return Ok on 500");
        assert!(rx.try_recv().is_err(), "no notification expected on 500");
    }

    #[tokio::test]
    async fn test_execute_malformed_json_graceful() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_string("this is not json {{{"))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        let result = handler.execute(&serde_json::Value::Null).await;
        assert!(result.is_ok(), "handler must return Ok on malformed JSON");
        assert!(
            rx.try_recv().is_err(),
            "no notification expected for malformed JSON"
        );
    }

    #[tokio::test]
    async fn test_execute_missing_tag_name_graceful() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "name": "Latest Release",
                "published_at": "2024-01-01"
            })))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        let result = handler.execute(&serde_json::Value::Null).await;
        assert!(result.is_ok(), "handler must return Ok on missing tag_name");
        assert!(
            rx.try_recv().is_err(),
            "no notification expected for missing tag_name"
        );
    }

    #[tokio::test]
    async fn test_execute_oversized_body_graceful() {
        let server = MockServer::start().await;
        // Body larger than MAX_RESPONSE_BYTES (64 KB): 65 537 bytes
        let large_body = "x".repeat(MAX_RESPONSE_BYTES + 1);
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_string(large_body))
            .mount(&server)
            .await;

        let (tx, mut rx) = mpsc::channel(1);
        let handler = make_handler("0.11.0", tx, &server.uri());

        let result = handler.execute(&serde_json::Value::Null).await;
        assert!(result.is_ok(), "handler must return Ok for oversized body");
        assert!(
            rx.try_recv().is_err(),
            "no notification expected for oversized body"
        );
    }
}