Skip to main content

wabot_addon_async_in_memory/
lib.rs

1//! In-memory `JobRepository` + `CronJobRepository` — port of wabot-ts
2//! `addon/async/in-memory`. Designed for tests, examples, and
3//! single-process deployments where durability isn't required.
4//!
5//! Unlike the TS version we don't persist to disk; the lifetime of a
6//! repository is the lifetime of the process. Phase 5b will add a
7//! Postgres-backed durable alternative.
8
9use std::collections::HashMap;
10use std::sync::Arc;
11
12use async_trait::async_trait;
13use chrono::{DateTime, Utc};
14use parking_lot::Mutex;
15
16use wabot_feature_async::{
17    cron_job::{self, CronJob},
18    job::Job,
19    repository::{CronJobRepository, JobRepository},
20    types::AsyncError,
21};
22
23#[derive(Default)]
24pub struct InMemoryJobRepository {
25    by_id: Mutex<HashMap<String, Job>>,
26}
27
28impl InMemoryJobRepository {
29    pub fn new() -> Self {
30        Self::default()
31    }
32}
33
34impl wabot_core::injection::IsSingleton for InMemoryJobRepository {
35    fn register_in(c: &wabot_core::injection::Container) {
36        c.register_singleton_factory::<InMemoryJobRepository, _>(|_| {
37            Arc::new(InMemoryJobRepository::new())
38        });
39    }
40}
41
42#[async_trait]
43impl JobRepository for InMemoryJobRepository {
44    async fn find(&self, id: &str) -> Result<Option<Job>, AsyncError> {
45        Ok(self.by_id.lock().get(id).cloned())
46    }
47
48    async fn create(&self, job: &Job) -> Result<(), AsyncError> {
49        let id = job.id().to_string();
50        self.by_id.lock().insert(id, job.clone());
51        Ok(())
52    }
53
54    async fn update(&self, job: &Job) -> Result<(), AsyncError> {
55        let id = job.id().to_string();
56        self.by_id.lock().insert(id, job.clone());
57        Ok(())
58    }
59
60    async fn delete(&self, job: &Job) -> Result<(), AsyncError> {
61        self.by_id.lock().remove(job.id());
62        Ok(())
63    }
64
65    async fn find_pending_for_run_from(
66        &self,
67        as_of: DateTime<Utc>,
68        limit: usize,
69    ) -> Result<Vec<Job>, AsyncError> {
70        let now_ms = as_of.timestamp_millis();
71        let mut out: Vec<Job> = self
72            .by_id
73            .lock()
74            .values()
75            .filter(|j| {
76                let d = j.data();
77                d.scheduled_at.is_some_and(|t| t <= now_ms)
78                    && d.started_at.is_none()
79                    && d.success_at.is_none()
80                    && d.failed_at.is_none()
81            })
82            .cloned()
83            .collect();
84        out.sort_by_key(|j| j.data().scheduled_at.unwrap_or(0));
85        out.truncate(limit);
86        Ok(out)
87    }
88
89    async fn find_running(&self) -> Result<Vec<Job>, AsyncError> {
90        Ok(self
91            .by_id
92            .lock()
93            .values()
94            .filter(|j| {
95                let d = j.data();
96                d.success_at.is_none()
97                    && d.failed_at.is_none()
98                    && d.scheduled_at.is_some()
99                    && d.started_at.is_some()
100            })
101            .cloned()
102            .collect())
103    }
104
105    async fn count_running_by_command(&self, command_name: &str) -> Result<usize, AsyncError> {
106        Ok(self
107            .by_id
108            .lock()
109            .values()
110            .filter(|j| {
111                let d = j.data();
112                d.command_name == command_name
113                    && d.success_at.is_none()
114                    && d.failed_at.is_none()
115                    && d.scheduled_at.is_some()
116                    && d.started_at.is_some()
117            })
118            .count())
119    }
120
121    async fn find_active_by_dedup_key(
122        &self,
123        command_name: &str,
124        dedup_key: &str,
125        succeeded_since_ms: i64,
126    ) -> Result<Option<Job>, AsyncError> {
127        let candidates: Vec<Job> = {
128            let map = self.by_id.lock();
129            let mut v: Vec<Job> = map
130                .values()
131                .filter(|j| {
132                    let d = j.data();
133                    let cmd_match = d.command_name == command_name;
134                    let key_match = d.dedup_key.as_deref() == Some(dedup_key);
135                    let not_failed = d.failed_at.is_none();
136                    let success_window = match d.success_at {
137                        Some(t) => t >= succeeded_since_ms,
138                        None => true,
139                    };
140                    cmd_match && key_match && not_failed && success_window
141                })
142                .cloned()
143                .collect();
144            v.sort_by_key(|j| std::cmp::Reverse(j.data().base.created_at.unwrap_or(0)));
145            v
146        };
147        Ok(candidates.into_iter().next())
148    }
149}
150
151#[derive(Default)]
152pub struct InMemoryCronJobRepository {
153    by_id: Mutex<HashMap<String, CronJob>>,
154}
155
156impl InMemoryCronJobRepository {
157    pub fn new() -> Self {
158        Self::default()
159    }
160}
161
162impl wabot_core::injection::IsSingleton for InMemoryCronJobRepository {
163    fn register_in(c: &wabot_core::injection::Container) {
164        c.register_singleton_factory::<InMemoryCronJobRepository, _>(|_| {
165            Arc::new(InMemoryCronJobRepository::new())
166        });
167    }
168}
169
170#[async_trait]
171impl CronJobRepository for InMemoryCronJobRepository {
172    async fn find(&self, id: &str) -> Result<Option<CronJob>, AsyncError> {
173        Ok(self.by_id.lock().get(id).cloned())
174    }
175
176    async fn find_by_name(&self, name: &str) -> Result<Option<CronJob>, AsyncError> {
177        Ok(self
178            .by_id
179            .lock()
180            .values()
181            .find(|c| c.data().name == name)
182            .cloned())
183    }
184
185    async fn create(&self, cron: &CronJob) -> Result<(), AsyncError> {
186        self.by_id
187            .lock()
188            .insert(cron.id().to_string(), cron.clone());
189        Ok(())
190    }
191
192    async fn update(&self, cron: &CronJob) -> Result<(), AsyncError> {
193        self.by_id
194            .lock()
195            .insert(cron.id().to_string(), cron.clone());
196        Ok(())
197    }
198
199    async fn find_due(&self, now: DateTime<Utc>) -> Result<Vec<CronJob>, AsyncError> {
200        Ok(self
201            .by_id
202            .lock()
203            .values()
204            .filter(|c| cron_job::is_due(c, now))
205            .cloned()
206            .collect())
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use serde_json::json;
214    use wabot_core::entity::EntityData;
215    use wabot_feature_async::cron_job::CronJobData;
216    use wabot_feature_async::job::{new_job, JobData};
217    use wabot_feature_async::types::MisfirePolicy;
218
219    fn ts(ms: i64) -> DateTime<Utc> {
220        DateTime::<Utc>::from_timestamp_millis(ms).unwrap()
221    }
222
223    #[tokio::test]
224    async fn job_lifecycle_round_trip() {
225        let repo = InMemoryJobRepository::new();
226        let now_ms = Utc::now().timestamp_millis();
227        let job = new_job(JobData {
228            base: EntityData::default(),
229            command_name: "ping".into(),
230            command_data: json!({ "n": 1 }),
231            scheduled_at: Some(now_ms),
232            started_at: None,
233            success_at: None,
234            failed_at: None,
235            retry_delays_seconds: None,
236            intent_number: None,
237            error: None,
238            acceptable_running_time_seconds: None,
239            stuck_retry_attempts: None,
240            dedup_key: None,
241            actor: None,
242            request_id: None,
243        });
244        repo.create(&job).await.unwrap();
245
246        let pending = repo
247            .find_pending_for_run_from(ts(now_ms), 10)
248            .await
249            .unwrap();
250        assert_eq!(pending.len(), 1);
251        assert_eq!(pending[0].id(), job.id());
252
253        let running = repo.find_running().await.unwrap();
254        assert!(running.is_empty(), "job hasn't started yet");
255    }
256
257    #[tokio::test]
258    async fn cron_round_trip() {
259        let repo = InMemoryCronJobRepository::new();
260        let cron = cron_job::new_cron_job(CronJobData {
261            base: EntityData::default(),
262            name: "nightly".into(),
263            command_name: "ping".into(),
264            command_data: None,
265            cron: "0 0 * * * *".into(),
266            enabled: true,
267            last_run_at: None,
268            next_run_at: None,
269            max_running_jobs: Some(1),
270            misfire_policy: Some(MisfirePolicy::RunOnce),
271            retry_delays_seconds: None,
272            acceptable_running_time_seconds: None,
273            stuck_retry_attempts: None,
274        })
275        .unwrap();
276        repo.create(&cron).await.unwrap();
277        assert!(repo.find_by_name("nightly").await.unwrap().is_some());
278    }
279}