orion-server 0.1.1

Declarative services runtime powered by dataflow-rs
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
use crate::storage::DbPool;
use async_trait::async_trait;
use sea_query::{Asterisk, Condition, Expr, Func, Query};
use serde::Deserialize;

use crate::errors::OrionError;
use crate::storage::models::{self, Trace};
use crate::storage::repositories::workflows::PaginatedResult;
use crate::storage::{build_sqlx, schema::Traces};

#[derive(Debug, Default, Deserialize)]
pub struct TraceFilter {
    pub status: Option<String>,
    pub channel: Option<String>,
    pub mode: Option<String>,
    pub limit: Option<i64>,
    pub offset: Option<i64>,
    /// Column to sort by: created_at (default), updated_at, status, channel, mode.
    pub sort_by: Option<String>,
    /// Sort direction: asc or desc (default).
    pub sort_order: Option<String>,
}

// -- Repository trait --

#[async_trait]
pub trait TraceRepository: Send + Sync {
    async fn create_pending(
        &self,
        channel: &str,
        mode: &str,
        input_json: Option<&str>,
    ) -> Result<Trace, OrionError>;
    async fn get_by_id(&self, id: &str) -> Result<Trace, OrionError>;
    async fn update_status(
        &self,
        id: &str,
        status: &str,
        error_message: Option<&str>,
    ) -> Result<Trace, OrionError>;
    async fn set_result(
        &self,
        id: &str,
        result_json: &str,
        duration_ms: f64,
    ) -> Result<(), OrionError>;
    async fn store_completed(
        &self,
        channel: &str,
        mode: &str,
        input_json: Option<&str>,
        result_json: &str,
        duration_ms: f64,
    ) -> Result<String, OrionError>;
    async fn list_paginated(
        &self,
        filter: &TraceFilter,
    ) -> Result<PaginatedResult<Trace>, OrionError>;
    /// Delete traces older than the given number of hours. Returns the count deleted.
    async fn delete_older_than(&self, hours: u64) -> Result<u64, OrionError>;
}

// -- SQL implementation --

pub struct SqlTraceRepository {
    pool: DbPool,
}

impl SqlTraceRepository {
    pub fn new(pool: DbPool) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl TraceRepository for SqlTraceRepository {
    async fn create_pending(
        &self,
        channel: &str,
        mode: &str,
        input_json: Option<&str>,
    ) -> Result<Trace, OrionError> {
        crate::metrics::timed_db_op("traces.create_pending", async {
            let id = uuid::Uuid::new_v4().to_string();

            let input_val = super::helpers::optional_string_value(input_json);

            let (sql, values) = build_sqlx(
                Query::insert()
                    .into_table(Traces::Table)
                    .columns([
                        Traces::Id,
                        Traces::Status,
                        Traces::Channel,
                        Traces::Mode,
                        Traces::InputJson,
                    ])
                    .values_panic([
                        Expr::val(id.as_str()).into(),
                        Expr::val("pending").into(),
                        Expr::val(channel).into(),
                        Expr::val(mode).into(),
                        Expr::val(input_val).into(),
                    ]),
            );

            self.pool.execute_query(&sql, values).await?;

            self.get_by_id(&id).await
        })
        .await
    }

    async fn get_by_id(&self, id: &str) -> Result<Trace, OrionError> {
        crate::metrics::timed_db_op("traces.get_by_id", async {
            let (sql, values) = build_sqlx(
                Query::select()
                    .column(Asterisk)
                    .from(Traces::Table)
                    .and_where(Expr::col(Traces::Id).eq(id)),
            );

            self.pool
                .fetch_optional_as::<Trace>(&sql, values)
                .await?
                .ok_or_else(|| OrionError::NotFound(format!("Trace '{}' not found", id)))
        })
        .await
    }

    async fn update_status(
        &self,
        id: &str,
        status: &str,
        error_message: Option<&str>,
    ) -> Result<Trace, OrionError> {
        crate::metrics::timed_db_op("traces.update_status", async {
            let now = chrono::Utc::now().naive_utc().to_string();

            let (started_at, completed_at) = if status == models::TRACE_STATUS_RUNNING {
                (Some(now), None)
            } else if status == models::TRACE_STATUS_COMPLETED
                || status == models::TRACE_STATUS_FAILED
            {
                (None, Some(now))
            } else {
                (None, None)
            };

            let mut update = Query::update();
            update.table(Traces::Table).value(Traces::Status, status);

            if let Some(err) = error_message {
                update.value(Traces::ErrorMessage, err);
            }
            if let Some(ref sa) = started_at {
                update.value(Traces::StartedAt, sa.as_str());
            }
            if let Some(ref ca) = completed_at {
                update.value(Traces::CompletedAt, ca.as_str());
            }

            update.and_where(Expr::col(Traces::Id).eq(id));

            let (sql, values) = build_sqlx(&mut update);

            self.pool.execute_query(&sql, values).await?;

            self.get_by_id(id).await
        })
        .await
    }

    async fn set_result(
        &self,
        id: &str,
        result_json: &str,
        duration_ms: f64,
    ) -> Result<(), OrionError> {
        crate::metrics::timed_db_op("traces.set_result", async {
            let (sql, values) = build_sqlx(
                Query::update()
                    .table(Traces::Table)
                    .value(Traces::ResultJson, result_json)
                    .value(Traces::DurationMs, duration_ms)
                    .and_where(Expr::col(Traces::Id).eq(id)),
            );

            self.pool.execute_query(&sql, values).await?;
            Ok(())
        })
        .await
    }

    async fn store_completed(
        &self,
        channel: &str,
        mode: &str,
        input_json: Option<&str>,
        result_json: &str,
        duration_ms: f64,
    ) -> Result<String, OrionError> {
        crate::metrics::timed_db_op("traces.store_completed", async {
            let id = uuid::Uuid::new_v4().to_string();
            let now = chrono::Utc::now().naive_utc().to_string();

            let input_val = super::helpers::optional_string_value(input_json);

            let (sql, values) = build_sqlx(
                Query::insert()
                    .into_table(Traces::Table)
                    .columns([
                        Traces::Id,
                        Traces::Status,
                        Traces::Channel,
                        Traces::Mode,
                        Traces::InputJson,
                        Traces::ResultJson,
                        Traces::DurationMs,
                        Traces::StartedAt,
                        Traces::CompletedAt,
                    ])
                    .values_panic([
                        Expr::val(id.as_str()).into(),
                        Expr::val("completed").into(),
                        Expr::val(channel).into(),
                        Expr::val(mode).into(),
                        Expr::val(input_val).into(),
                        Expr::val(result_json).into(),
                        Expr::val(duration_ms).into(),
                        Expr::val(now.as_str()).into(),
                        Expr::val(now.as_str()).into(),
                    ]),
            );

            self.pool.execute_query(&sql, values).await?;

            Ok(id)
        })
        .await
    }

    async fn list_paginated(
        &self,
        filter: &TraceFilter,
    ) -> Result<PaginatedResult<Trace>, OrionError> {
        crate::metrics::timed_db_op("traces.list_paginated", async {
            let (limit, offset) = super::helpers::clamp_pagination(filter.limit, filter.offset);

            let mut cond = Condition::all();
            if let Some(ref status) = filter.status {
                cond = cond.add(Expr::col(Traces::Status).eq(status.as_str()));
            }
            if let Some(ref channel) = filter.channel {
                cond = cond.add(Expr::col(Traces::Channel).eq(channel.as_str()));
            }
            if let Some(ref mode) = filter.mode {
                cond = cond.add(Expr::col(Traces::Mode).eq(mode.as_str()));
            }

            // COUNT query
            let (sql, values) = build_sqlx(
                Query::select()
                    .expr(Func::count(Expr::col(Asterisk)))
                    .from(Traces::Table)
                    .cond_where(cond.clone()),
            );
            let (total,): (i64,) = self.pool.fetch_one_as::<(i64,)>(&sql, values).await?;

            // Sort column mapping
            let sort_iden = match filter.sort_by.as_deref() {
                Some("updated_at") => Traces::UpdatedAt,
                Some("status") => Traces::Status,
                Some("channel") => Traces::Channel,
                Some("mode") => Traces::Mode,
                _ => Traces::CreatedAt,
            };
            let order = super::helpers::parse_sort_order(filter.sort_order.as_deref());

            // DATA query
            let (sql, values) = build_sqlx(
                Query::select()
                    .column(Asterisk)
                    .from(Traces::Table)
                    .cond_where(cond)
                    .order_by(sort_iden, order)
                    .limit(limit as u64)
                    .offset(offset as u64),
            );
            let data = self.pool.fetch_all_as::<Trace>(&sql, values).await?;

            Ok(PaginatedResult {
                data,
                total,
                limit,
                offset,
            })
        })
        .await
    }

    async fn delete_older_than(&self, hours: u64) -> Result<u64, OrionError> {
        crate::metrics::timed_db_op("traces.delete_older_than", async {
            let cutoff = chrono::Utc::now()
                .naive_utc()
                .checked_sub_signed(chrono::Duration::hours(hours as i64))
                .unwrap_or(chrono::NaiveDateTime::MIN)
                .to_string();

            let (sql, values) = build_sqlx(
                Query::delete()
                    .from_table(Traces::Table)
                    .and_where(Expr::col(Traces::CreatedAt).lt(&cutoff))
                    .and_where(Expr::col(Traces::Status).is_in(["completed", "failed"])),
            );

            let rows_affected = self.pool.execute_query(&sql, values).await?;

            Ok(rows_affected)
        })
        .await
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;

    async fn test_pool() -> crate::storage::DbPool {
        crate::storage::init_pool(&crate::config::StorageConfig {
            url: "sqlite::memory:".to_string(),
            max_connections: 1,
            ..Default::default()
        })
        .await
        .unwrap()
    }

    #[tokio::test]
    async fn test_delete_older_than_removes_old_completed_traces() {
        let pool = test_pool().await;
        let repo = SqlTraceRepository::new(pool.clone());

        // Create a completed trace
        let id = repo
            .store_completed("orders", "sync", None, r#"{"ok":true}"#, 10.0)
            .await
            .unwrap();

        // Backdate it to 100 hours ago
        let old_time = chrono::Utc::now()
            .naive_utc()
            .checked_sub_signed(chrono::Duration::hours(100))
            .unwrap()
            .to_string();
        match &pool {
            crate::storage::DbPool::Sqlite(p) => {
                sqlx::query("UPDATE traces SET created_at = ? WHERE id = ?")
                    .bind(&old_time)
                    .bind(&id)
                    .execute(p)
                    .await
                    .unwrap();
            }
            _ => panic!("Test requires SQLite"),
        }

        // Create a recent trace that should NOT be deleted
        let _recent_id = repo
            .store_completed("orders", "sync", None, r#"{"ok":true}"#, 5.0)
            .await
            .unwrap();

        // Delete traces older than 72 hours
        let deleted = repo.delete_older_than(72).await.unwrap();
        assert_eq!(deleted, 1);

        // Verify the recent trace still exists
        let remaining = repo.list_paginated(&TraceFilter::default()).await.unwrap();
        assert_eq!(remaining.total, 1);
    }

    #[tokio::test]
    async fn test_delete_older_than_preserves_pending_traces() {
        let pool = test_pool().await;
        let repo = SqlTraceRepository::new(pool.clone());

        // Create a pending trace
        let trace = repo.create_pending("orders", "async", None).await.unwrap();

        // Backdate it
        let old_time = chrono::Utc::now()
            .naive_utc()
            .checked_sub_signed(chrono::Duration::hours(200))
            .unwrap()
            .to_string();
        match &pool {
            crate::storage::DbPool::Sqlite(p) => {
                sqlx::query("UPDATE traces SET created_at = ? WHERE id = ?")
                    .bind(&old_time)
                    .bind(&trace.id)
                    .execute(p)
                    .await
                    .unwrap();
            }
            _ => panic!("Test requires SQLite"),
        }

        // Cleanup should NOT delete pending traces
        let deleted = repo.delete_older_than(72).await.unwrap();
        assert_eq!(deleted, 0);
    }
}