torc 0.23.0

Workflow management system
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Result-related API endpoints

#![allow(clippy::too_many_arguments)]

use crate::server::transport_types::context_types::{ApiError, Has, XSpanIdString};
use async_trait::async_trait;
use log::{debug, error, info};
use sqlx::Row;

use crate::server::api_responses::{
    CreateResultResponse, DeleteResultResponse, DeleteResultsResponse, GetResultResponse,
    ListResultsResponse, UpdateResultResponse,
};

use crate::models;

use super::{ApiContext, MAX_RECORD_TRANSFER_COUNT, SqlQueryBuilder, database_error_with_msg};

/// Trait defining result-related API operations
#[async_trait]
pub trait ResultsApi<C> {
    /// Store a job result.
    async fn create_result(
        &self,
        mut body: models::ResultModel,
        context: &C,
    ) -> Result<CreateResultResponse, ApiError>;

    /// Delete all results for one workflow.
    async fn delete_results(
        &self,
        workflow_id: i64,
        context: &C,
    ) -> Result<DeleteResultsResponse, ApiError>;

    /// Retrieve a result by ID.
    async fn get_result(&self, id: i64, context: &C) -> Result<GetResultResponse, ApiError>;

    /// Retrieve all job results for one workflow.
    async fn list_results(
        &self,
        workflow_id: i64,
        job_id: Option<i64>,
        run_id: Option<i64>,
        return_code: Option<i64>,
        status: Option<models::JobStatus>,
        compute_node_id: Option<i64>,
        offset: i64,
        limit: i64,
        sort_by: Option<String>,
        reverse_sort: Option<bool>,
        all_runs: Option<bool>,
        context: &C,
    ) -> Result<ListResultsResponse, ApiError>;

    /// Update a result.
    async fn update_result(
        &self,
        id: i64,
        body: models::ResultModel,
        context: &C,
    ) -> Result<UpdateResultResponse, ApiError>;

    /// Delete a result.
    async fn delete_result(&self, id: i64, context: &C) -> Result<DeleteResultResponse, ApiError>;
}

/// Implementation of results API for the server
#[derive(Clone)]
pub struct ResultsApiImpl {
    pub context: ApiContext,
}

const RESULT_COLUMNS: &[&str] = &[
    "id",
    "job_id",
    "workflow_id",
    "run_id",
    "attempt_id",
    "compute_node_id",
    "return_code",
    "exec_time_minutes",
    "completion_time",
    "status",
    "peak_memory_bytes",
    "avg_memory_bytes",
    "peak_cpu_percent",
    "avg_cpu_percent",
];

impl ResultsApiImpl {
    pub fn new(context: ApiContext) -> Self {
        Self { context }
    }
}

#[async_trait]
impl<C> ResultsApi<C> for ResultsApiImpl
where
    C: Has<XSpanIdString> + Send + Sync,
{
    /// Store a job result.
    async fn create_result(
        &self,
        mut body: models::ResultModel,
        context: &C,
    ) -> Result<CreateResultResponse, ApiError> {
        debug!("create_result - X-Span-ID: {:?}", context.get().0.clone());
        let status = body.status.to_int();
        let attempt_id = body.attempt_id.unwrap_or(1);

        // Use a transaction to atomically insert into both result and workflow_result.
        let mut tx = self
            .context
            .pool
            .begin()
            .await
            .map_err(|e| database_error_with_msg(e, "Failed to begin transaction"))?;

        let result = match sqlx::query!(
            r#"
            INSERT INTO result
            (
                job_id
                ,workflow_id
                ,run_id
                ,attempt_id
                ,compute_node_id
                ,return_code
                ,exec_time_minutes
                ,completion_time
                ,status
                ,peak_memory_bytes
                ,avg_memory_bytes
                ,peak_cpu_percent
                ,avg_cpu_percent
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
            RETURNING rowid
        "#,
            body.job_id,
            body.workflow_id,
            body.run_id,
            attempt_id,
            body.compute_node_id,
            body.return_code,
            body.exec_time_minutes,
            body.completion_time,
            status,
            body.peak_memory_bytes,
            body.avg_memory_bytes,
            body.peak_cpu_percent,
            body.avg_cpu_percent,
        )
        .fetch_one(&mut *tx)
        .await
        {
            Ok(result) => result,
            Err(e) => {
                return Err(database_error_with_msg(e, "Failed to create result record"));
            }
        };
        body.id = Some(result.id);

        // Also populate workflow_result so this result is visible via default list queries.
        // workflow_result tracks the latest result per (workflow_id, job_id).
        let result_id = result.id;
        let workflow_id = body.workflow_id;
        let job_id = body.job_id;
        if let Err(e) = sqlx::query!(
            r#"
            INSERT OR REPLACE INTO workflow_result (workflow_id, job_id, result_id)
            VALUES (?, ?, ?)
            "#,
            workflow_id,
            job_id,
            result_id,
        )
        .execute(&mut *tx)
        .await
        {
            error!(
                "Failed to insert workflow_result for workflow_id={}, job_id={}: {}",
                workflow_id, job_id, e
            );
            return Err(database_error_with_msg(
                e,
                "Failed to create workflow_result record",
            ));
        }

        tx.commit()
            .await
            .map_err(|e| database_error_with_msg(e, "Failed to commit transaction"))?;

        Ok(CreateResultResponse::SuccessfulResponse(body))
    }

    /// Delete all results for one workflow.
    async fn delete_results(
        &self,
        workflow_id: i64,
        context: &C,
    ) -> Result<DeleteResultsResponse, ApiError> {
        debug!(
            "delete_results({}) - X-Span-ID: {:?}",
            workflow_id,
            context.get().0.clone()
        );

        let result = match sqlx::query!("DELETE FROM result WHERE workflow_id = $1", workflow_id)
            .execute(self.context.pool.as_ref())
            .await
        {
            Ok(result) => result,
            Err(e) => {
                return Err(database_error_with_msg(e, "Failed to delete results"));
            }
        };

        let deleted_count = result.rows_affected() as i64;

        info!(
            "Deleted {} results for workflow {}",
            deleted_count, workflow_id
        );

        Ok(DeleteResultsResponse::SuccessfulResponse(
            serde_json::json!({
                "count": deleted_count
            }),
        ))
    }

    /// Retrieve a result by ID.
    async fn get_result(&self, id: i64, context: &C) -> Result<GetResultResponse, ApiError> {
        debug!(
            "get_result({}) - X-Span-ID: {:?}",
            id,
            context.get().0.clone()
        );

        let record = match sqlx::query!(
            r#"
            SELECT id, job_id, workflow_id, run_id, attempt_id, compute_node_id, return_code, exec_time_minutes, completion_time, status,
                   peak_memory_bytes, avg_memory_bytes, peak_cpu_percent, avg_cpu_percent
            FROM result
            WHERE id = $1
            "#,
            id
        )
        .fetch_optional(self.context.pool.as_ref())
        .await
        {
            Ok(Some(record)) => record,
            Ok(None) => {
                let error_response = models::ErrorResponse::new(
                    serde_json::json!({
                        "message": format!("Result not found with ID: {}", id)
                    })
                );
                return Ok(GetResultResponse::NotFoundErrorResponse(error_response));
            }
            Err(e) => {
                return Err(database_error_with_msg(e, "Failed to fetch result"));
            }
        };

        let status_int = record.status;
        let status = match models::JobStatus::from_int(status_int as i32) {
            Ok(s) => s,
            Err(e) => {
                error!("Failed to parse job status '{}': {}", status_int, e);
                return Err(ApiError(format!("Failed to parse job status: {}", e)));
            }
        };

        let result_model = models::ResultModel {
            id: Some(record.id),
            workflow_id: record.workflow_id,
            job_id: record.job_id,
            run_id: record.run_id,
            attempt_id: Some(record.attempt_id),
            compute_node_id: record.compute_node_id,
            return_code: record.return_code,
            exec_time_minutes: record.exec_time_minutes,
            completion_time: record.completion_time,
            peak_memory_bytes: record.peak_memory_bytes,
            avg_memory_bytes: record.avg_memory_bytes,
            peak_cpu_percent: record.peak_cpu_percent,
            avg_cpu_percent: record.avg_cpu_percent,
            status,
        };

        Ok(GetResultResponse::SuccessfulResponse(result_model))
    }

    /// Retrieve all job results for one workflow.
    async fn list_results(
        &self,
        workflow_id: i64,
        job_id: Option<i64>,
        run_id: Option<i64>,
        return_code: Option<i64>,
        status: Option<models::JobStatus>,
        compute_node_id: Option<i64>,
        offset: i64,
        limit: i64,
        sort_by: Option<String>,
        reverse_sort: Option<bool>,
        all_runs: Option<bool>,
        context: &C,
    ) -> Result<ListResultsResponse, ApiError> {
        // all_runs defaults to false - only show current results in workflow_result table
        let show_all_results = all_runs.unwrap_or(false);

        debug!(
            "list_results({}, {:?}, {:?}, {:?}, {:?}, {:?}, {}, {}, {:?}, {:?}, all_runs={}) - X-Span-ID: {:?}",
            workflow_id,
            job_id,
            run_id,
            return_code,
            status,
            compute_node_id,
            offset,
            limit,
            sort_by,
            reverse_sort,
            show_all_results,
            context.get().0.clone()
        );

        // Build base query
        // If all_runs is false, only return results that are in workflow_result table (current results)
        let base_query = if show_all_results {
            "SELECT id, job_id, workflow_id, run_id, attempt_id, compute_node_id, return_code, exec_time_minutes, completion_time, status, peak_memory_bytes, avg_memory_bytes, peak_cpu_percent, avg_cpu_percent FROM result".to_string()
        } else {
            "SELECT r.id, r.job_id, r.workflow_id, r.run_id, r.attempt_id, r.compute_node_id, r.return_code, r.exec_time_minutes, r.completion_time, r.status, r.peak_memory_bytes, r.avg_memory_bytes, r.peak_cpu_percent, r.avg_cpu_percent FROM result r INNER JOIN workflow_result wr ON r.id = wr.result_id".to_string()
        };

        // Build WHERE clause conditions
        // Use table alias prefix when joining with workflow_result
        let col_prefix = if show_all_results { "" } else { "r." };

        let mut where_conditions = vec![format!("{}workflow_id = ?", col_prefix)];
        let mut bind_values: Vec<Box<dyn sqlx::Encode<'_, sqlx::Sqlite> + Send>> =
            vec![Box::new(workflow_id)];

        if let Some(j_id) = job_id {
            where_conditions.push(format!("{}job_id = ?", col_prefix));
            bind_values.push(Box::new(j_id));
        }

        if let Some(r_id) = run_id {
            where_conditions.push(format!("{}run_id = ?", col_prefix));
            bind_values.push(Box::new(r_id));
        }

        if let Some(ret_code) = return_code {
            where_conditions.push(format!("{}return_code = ?", col_prefix));
            bind_values.push(Box::new(ret_code));
        }

        if let Some(result_status) = &status {
            where_conditions.push(format!("{}status = ?", col_prefix));
            bind_values.push(Box::new(result_status.to_int()));
        }

        if let Some(cn_id) = compute_node_id {
            where_conditions.push(format!("{}compute_node_id = ?", col_prefix));
            bind_values.push(Box::new(cn_id));
        }

        let where_clause = where_conditions.join(" AND ");

        // Validate sort_by against whitelist
        let validated_sort_by = if let Some(ref col) = sort_by {
            if RESULT_COLUMNS.contains(&col.as_str()) {
                // If we have a join (show_all_results is false), prefix with "r." if it's a result column
                if !show_all_results {
                    Some(format!("r.{}", col))
                } else {
                    Some(col.clone())
                }
            } else {
                debug!("Invalid sort column requested: {}", col);
                None // Fall back to default
            }
        } else {
            None
        };

        // Build the complete query with pagination and sorting
        let query = SqlQueryBuilder::new(base_query)
            .with_where(where_clause.clone())
            .with_pagination_and_sorting(
                offset,
                limit,
                validated_sort_by,
                reverse_sort,
                "id",
                RESULT_COLUMNS,
            )
            .build();

        debug!("Executing query: {}", query);

        // Execute the query
        let mut sqlx_query = sqlx::query(&query);

        // Bind workflow_id
        sqlx_query = sqlx_query.bind(workflow_id);

        // Bind optional parameters in order
        if let Some(j_id) = job_id {
            sqlx_query = sqlx_query.bind(j_id);
        }
        if let Some(r_id) = run_id {
            sqlx_query = sqlx_query.bind(r_id);
        }
        if let Some(ret_code) = return_code {
            sqlx_query = sqlx_query.bind(ret_code);
        }
        if let Some(ref s) = status {
            sqlx_query = sqlx_query.bind(s.to_int());
        }
        if let Some(cn_id) = compute_node_id {
            sqlx_query = sqlx_query.bind(cn_id);
        }

        let records = match sqlx_query.fetch_all(self.context.pool.as_ref()).await {
            Ok(recs) => recs,
            Err(e) => {
                return Err(database_error_with_msg(e, "Failed to list results"));
            }
        };

        let mut items: Vec<models::ResultModel> = Vec::new();
        for record in records {
            let status_int: i64 = record.get("status");
            let status = match models::JobStatus::from_int(status_int as i32) {
                Ok(s) => s,
                Err(e) => {
                    error!("Failed to parse job status '{}': {}", status_int, e);
                    return Err(ApiError(format!("Failed to parse job status: {}", e)));
                }
            };
            items.push(models::ResultModel {
                id: Some(record.get("id")),
                workflow_id: record.get("workflow_id"),
                job_id: record.get("job_id"),
                run_id: record.get("run_id"),
                attempt_id: Some(record.get("attempt_id")),
                compute_node_id: record.get("compute_node_id"),
                return_code: record.get("return_code"),
                exec_time_minutes: record.get("exec_time_minutes"),
                completion_time: record.get("completion_time"),
                peak_memory_bytes: record.get("peak_memory_bytes"),
                avg_memory_bytes: record.get("avg_memory_bytes"),
                peak_cpu_percent: record.get("peak_cpu_percent"),
                avg_cpu_percent: record.get("avg_cpu_percent"),
                status,
            });
        }

        // For proper pagination, we should get the total count without LIMIT/OFFSET
        let count_base = if show_all_results {
            "SELECT COUNT(*) as total FROM result".to_string()
        } else {
            "SELECT COUNT(*) as total FROM result r INNER JOIN workflow_result wr ON r.id = wr.result_id".to_string()
        };
        let count_query = SqlQueryBuilder::new(count_base)
            .with_where(where_clause)
            .build();

        let mut count_sqlx_query = sqlx::query(&count_query);
        count_sqlx_query = count_sqlx_query.bind(workflow_id);
        if let Some(j_id) = job_id {
            count_sqlx_query = count_sqlx_query.bind(j_id);
        }
        if let Some(r_id) = run_id {
            count_sqlx_query = count_sqlx_query.bind(r_id);
        }
        if let Some(ret_code) = return_code {
            count_sqlx_query = count_sqlx_query.bind(ret_code);
        }
        if let Some(ref s) = status {
            count_sqlx_query = count_sqlx_query.bind(s.to_int());
        }
        if let Some(cn_id) = compute_node_id {
            count_sqlx_query = count_sqlx_query.bind(cn_id);
        }

        let total_count = match count_sqlx_query.fetch_one(self.context.pool.as_ref()).await {
            Ok(row) => row.get::<i64, _>("total"),
            Err(e) => {
                return Err(database_error_with_msg(e, "Failed to list results"));
            }
        };

        let current_count = items.len() as i64;
        let offset_val = offset;
        let has_more = offset_val + current_count < total_count;

        debug!(
            "list_results({}, {}/{}) - X-Span-ID: {:?}",
            workflow_id,
            current_count,
            total_count,
            context.get().0.clone()
        );

        Ok(ListResultsResponse::SuccessfulResponse(
            models::ListResultsResponse {
                items,
                offset: offset_val,
                max_limit: MAX_RECORD_TRANSFER_COUNT,
                count: current_count,
                total_count,
                has_more,
            },
        ))
    }

    /// Update a result.
    async fn update_result(
        &self,
        id: i64,
        body: models::ResultModel,
        context: &C,
    ) -> Result<UpdateResultResponse, ApiError> {
        debug!(
            "update_result({}) - X-Span-ID: {:?}",
            id,
            context.get().0.clone()
        );

        // First get the existing result to ensure it exists
        match self.get_result(id, context).await? {
            GetResultResponse::SuccessfulResponse(result) => result,
            GetResultResponse::ForbiddenErrorResponse(err) => {
                return Ok(UpdateResultResponse::ForbiddenErrorResponse(err));
            }
            GetResultResponse::NotFoundErrorResponse(err) => {
                return Ok(UpdateResultResponse::NotFoundErrorResponse(err));
            }
            GetResultResponse::DefaultErrorResponse(_) => {
                return Err(ApiError("Failed to get result".to_string()));
            }
        };

        let status_int = body.status.to_int();

        let result = match sqlx::query!(
            r#"
            UPDATE result
            SET
                job_id = COALESCE($1, job_id)
                ,workflow_id = COALESCE($2, workflow_id)
                ,run_id = COALESCE($3, run_id)
                ,return_code = COALESCE($4, return_code)
                ,exec_time_minutes = COALESCE($5, exec_time_minutes)
                ,completion_time = COALESCE($6, completion_time)
                ,status = COALESCE($7, status)
            WHERE id = $8
            "#,
            body.job_id,
            body.workflow_id,
            body.run_id,
            body.return_code,
            body.exec_time_minutes,
            body.completion_time,
            status_int,
            id,
        )
        .execute(self.context.pool.as_ref())
        .await
        {
            Ok(result) => result,
            Err(e) => {
                return Err(database_error_with_msg(e, "Failed to update result"));
            }
        };

        if result.rows_affected() == 0 {
            let error_response = models::ErrorResponse::new(serde_json::json!({
                "message": format!("Result not found with ID: {}", id)
            }));
            return Ok(UpdateResultResponse::NotFoundErrorResponse(error_response));
        }

        // Return the updated result by fetching it again
        let updated_result = match self.get_result(id, context).await? {
            GetResultResponse::SuccessfulResponse(result) => result,
            _ => return Err(ApiError("Failed to get updated result".to_string())),
        };

        debug!("Modified result with id: {}", id);
        Ok(UpdateResultResponse::SuccessfulResponse(updated_result))
    }

    /// Delete a result.
    async fn delete_result(&self, id: i64, context: &C) -> Result<DeleteResultResponse, ApiError> {
        debug!(
            "delete_result({}) - X-Span-ID: {:?}",
            id,
            context.get().0.clone()
        );

        // First get the result to ensure it exists and extract the ResultModel
        let result = match self.get_result(id, context).await? {
            GetResultResponse::SuccessfulResponse(result) => result,
            GetResultResponse::ForbiddenErrorResponse(err) => {
                return Ok(DeleteResultResponse::ForbiddenErrorResponse(err));
            }
            GetResultResponse::NotFoundErrorResponse(err) => {
                return Ok(DeleteResultResponse::NotFoundErrorResponse(err));
            }
            GetResultResponse::DefaultErrorResponse(_) => {
                return Err(ApiError("Failed to get result".to_string()));
            }
        };

        match sqlx::query!(r#"DELETE FROM result WHERE id = $1"#, id)
            .execute(self.context.pool.as_ref())
            .await
        {
            Ok(res) => {
                if res.rows_affected() > 1 {
                    Err(ApiError(format!(
                        "Database error: Unexpected number of rows affected: {}",
                        res.rows_affected()
                    )))
                } else if res.rows_affected() == 0 {
                    Err(ApiError("Database error: No rows affected".to_string()))
                } else {
                    info!("Deleted result with id: {}", id);
                    Ok(DeleteResultResponse::SuccessfulResponse(result))
                }
            }
            Err(e) => Err(database_error_with_msg(e, "Failed to delete result")),
        }
    }
}