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
//! This module contains the gRPC cancel_itinerary endpoint implementation.

use crate::grpc::server::grpc_server::{
    CancelItineraryRequest, TaskAction, TaskMetadata, TaskResponse, TaskStatus,
};
use crate::tasks::pool::RedisPool;
use crate::tasks::{Task, TaskBody};
use chrono::{Duration, Utc};
use num_traits::FromPrimitive;
use tonic::Status;
use uuid::Uuid;

/// Cancels an itinerary
pub async fn cancel_itinerary(request: CancelItineraryRequest) -> Result<TaskResponse, Status> {
    let itinerary_id = match Uuid::parse_str(&request.itinerary_id) {
        Ok(id) => id,
        Err(_) => {
            return Err(Status::invalid_argument("Invalid itinerary ID."));
        }
    };

    let user_id = match Uuid::parse_str(&request.user_id) {
        Ok(id) => id,
        Err(_) => {
            return Err(Status::invalid_argument("Invalid user ID."));
        }
    };

    let Some(priority) = FromPrimitive::from_i32(request.priority) else {
        return Err(Status::invalid_argument("Invalid priority provided."));
    };

    // TODO(R4): Get the itinerary start time from storage
    // For now hardcode next hour
    let delta = Duration::try_hours(1).ok_or_else(|| {
        grpc_error!("(cancel_itinerary) error creating time delta.");
        Status::internal("Could not create new task.")
    })?;

    let expiry = Utc::now() + delta;
    let task = Task {
        metadata: TaskMetadata {
            status: TaskStatus::Queued as i32,
            status_rationale: None,
            action: TaskAction::CancelItinerary as i32,
            user_id: user_id.to_string(),
        },
        body: TaskBody::CancelItinerary(itinerary_id),
    };

    let Some(mut pool) = crate::tasks::pool::get_pool().await else {
        grpc_error!("(cancel_itinerary) Couldn't get the redis pool.");
        return Err(Status::internal("Internal error."));
    };

    // Add the task to the scheduler:tasks table
    match pool.new_task(&task, priority, expiry).await {
        Ok(task_id) => {
            grpc_info!("(cancel_itinerary) Created new task with ID: {}", task_id);

            Ok(TaskResponse {
                task_id,
                task_metadata: Some(task.metadata),
            })
        }
        Err(e) => {
            let error_msg = "Could not create new task.";
            grpc_error!("(cancel_itinerary) {error_msg}: {e}");
            Err(Status::internal(format!("{error_msg}.")))
        }
    }
}