swarm repositories / source
aboutsummaryrefslogtreecommitdiff
path: root/crates/fidget-spinner-cli/src/mcp/fault.rs
blob: e9d1fcefbfca425842cdac1af581f09076b1d4c9 (plain)
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
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use time::OffsetDateTime;

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) enum FaultKind {
    InvalidInput,
    NotInitialized,
    Unavailable,
    Transient,
    Internal,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) enum FaultStage {
    Host,
    Worker,
    Store,
    Transport,
    Protocol,
    Rollout,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) struct FaultRecord {
    pub kind: FaultKind,
    pub stage: FaultStage,
    pub operation: String,
    pub message: String,
    pub retryable: bool,
    pub retried: bool,
    pub worker_generation: Option<u64>,
    pub occurred_at: OffsetDateTime,
}

impl FaultRecord {
    #[must_use]
    pub fn new(
        kind: FaultKind,
        stage: FaultStage,
        operation: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            stage,
            operation: operation.into(),
            message: message.into(),
            retryable: false,
            retried: false,
            worker_generation: None,
            occurred_at: OffsetDateTime::now_utc(),
        }
    }

    #[must_use]
    pub fn retryable(mut self, worker_generation: Option<u64>) -> Self {
        self.retryable = true;
        self.worker_generation = worker_generation;
        self
    }

    #[must_use]
    pub fn mark_retried(mut self) -> Self {
        self.retried = true;
        self
    }

    #[must_use]
    pub fn into_jsonrpc_error(self) -> Value {
        json!({
            "code": self.jsonrpc_code(),
            "message": self.message.clone(),
            "data": self,
        })
    }

    #[must_use]
    pub fn into_tool_result(self) -> Value {
        json!({
            "content": [{
                "type": "text",
                "text": self.message,
            }],
            "structuredContent": self,
            "isError": true,
        })
    }

    #[must_use]
    pub const fn jsonrpc_code(&self) -> i64 {
        match self.kind {
            FaultKind::InvalidInput => -32602,
            FaultKind::NotInitialized => -32002,
            FaultKind::Unavailable => -32004,
            FaultKind::Transient | FaultKind::Internal => -32603,
        }
    }
}