Skip to main content

river_data_core/models/
protocol.rs

1use serde::{Deserialize, Serialize};
2use uuid::Uuid;
3
4use crate::models::status::{SyncEventStatus, SyncEventType};
5
6#[derive(Debug, Serialize, Deserialize)]
7#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
8pub struct EnrollRequest {
9    pub client_id: String,
10    pub client_secret: String,
11    pub instance_id: String,
12}
13
14#[derive(Debug, Serialize, Deserialize)]
15#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
16pub struct EnrollResponse {
17    pub service_id: Uuid,
18    pub session_token: String,
19    /// Operator-desired pause state, persisted server-side; honored before the
20    /// initial sync so a restart cannot undo a pause.
21    #[serde(default)]
22    pub paused: bool,
23}
24
25#[derive(Debug, Serialize, Deserialize)]
26#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
27pub struct HeartbeatRequest {
28    pub service_id: Uuid,
29    pub status: String,
30    pub current_operation: Option<String>,
31}
32
33#[derive(Debug, Serialize, Deserialize)]
34#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
35pub struct HeartbeatResponse {
36    pub session_token: String,
37    pub pending_commands: Vec<PendingCommand>,
38    /// Operator-desired pause state, persisted server-side.
39    #[serde(default)]
40    pub paused: bool,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
45pub struct PendingCommand {
46    pub id: Uuid,
47    pub command: String,
48    #[cfg_attr(feature = "openapi", schema(value_type = Object))]
49    pub payload: Option<serde_json::Value>,
50}
51
52#[derive(Debug, Serialize, Deserialize)]
53#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
54pub struct CommandUpdateRequest {
55    pub status: String,
56    #[cfg_attr(feature = "openapi", schema(value_type = Object))]
57    pub result: Option<serde_json::Value>,
58}
59
60#[derive(Debug, Serialize)]
61pub struct SyncEventCreate {
62    pub service_id: Uuid,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub command_id: Option<Uuid>,
65    pub event_type: SyncEventType,
66    pub status: SyncEventStatus,
67}
68
69#[derive(Debug, Deserialize)]
70pub struct SyncEventRef {
71    pub id: Uuid,
72}
73
74#[derive(Debug, Default, Serialize)]
75pub struct SyncEventUpdate {
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub status: Option<SyncEventStatus>,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub readings_synced: Option<u64>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub status_events_synced: Option<u64>,
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub errors: Vec<String>,
84    #[serde(skip_serializing_if = "Vec::is_empty")]
85    pub log: Vec<String>,
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub duration_ms: Option<u64>,
88}
89
90/// Outcome of one sync cycle. The runner fills `full_sync` and `duration_ms`;
91/// a `SyncService` only reports counts, errors and log lines.
92#[derive(Debug, Default, Serialize)]
93pub struct SyncResult {
94    pub readings_synced: u64,
95    pub status_events_synced: u64,
96    pub full_sync: bool,
97    pub duration_ms: u64,
98    #[serde(skip_serializing_if = "Vec::is_empty")]
99    pub errors: Vec<String>,
100    #[serde(skip_serializing_if = "Vec::is_empty")]
101    pub log: Vec<String>,
102}
103
104#[derive(Debug)]
105pub enum SyncTrigger {
106    Scheduled,
107    Command { id: Uuid, full: bool },
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn test_enroll_request_serialization() {
116        let req = EnrollRequest {
117            client_id: "svc_abc".to_string(),
118            client_secret: "secret123".to_string(),
119            instance_id: "service-01".to_string(),
120        };
121        let json = serde_json::to_value(&req).unwrap();
122        assert_eq!(json["client_id"], "svc_abc");
123        assert_eq!(json["instance_id"], "service-01");
124    }
125
126    #[test]
127    fn test_enroll_response_deserialization() {
128        let json = serde_json::json!({
129            "service_id": "550e8400-e29b-41d4-a716-446655440000",
130            "session_token": "tok-abc"
131        });
132        let resp: EnrollResponse = serde_json::from_value(json).unwrap();
133        assert_eq!(resp.session_token, "tok-abc");
134    }
135
136    #[test]
137    fn test_heartbeat_response_with_commands() {
138        let json = serde_json::json!({
139            "session_token": "new-tok",
140            "pending_commands": [
141                {
142                    "id": "550e8400-e29b-41d4-a716-446655440000",
143                    "command": "trigger_sync",
144                    "payload": null
145                }
146            ]
147        });
148        let resp: HeartbeatResponse = serde_json::from_value(json).unwrap();
149        assert_eq!(resp.pending_commands.len(), 1);
150        assert_eq!(resp.pending_commands[0].command, "trigger_sync");
151    }
152
153    #[test]
154    fn test_sync_result_default() {
155        let r = SyncResult::default();
156        assert_eq!(r.readings_synced, 0);
157        assert!(!r.full_sync);
158        assert!(r.errors.is_empty());
159    }
160
161    #[test]
162    fn test_sync_result_serialization_skips_empty() {
163        let r = SyncResult {
164            readings_synced: 100,
165            ..Default::default()
166        };
167        let json = serde_json::to_value(&r).unwrap();
168        assert_eq!(json["readings_synced"], 100);
169        assert!(json.get("errors").is_none());
170    }
171
172    #[test]
173    fn test_sync_event_create_serialization() {
174        let ev = SyncEventCreate {
175            service_id: Uuid::nil(),
176            command_id: None,
177            event_type: SyncEventType::Scheduled,
178            status: SyncEventStatus::Running,
179        };
180        let json = serde_json::to_value(&ev).unwrap();
181        assert_eq!(json["event_type"], "scheduled");
182        assert_eq!(json["status"], "running");
183        assert!(json.get("command_id").is_none());
184    }
185
186    #[test]
187    fn test_sync_event_update_skips_empty() {
188        let upd = SyncEventUpdate {
189            status: Some(SyncEventStatus::Completed),
190            readings_synced: Some(5),
191            ..Default::default()
192        };
193        let json = serde_json::to_value(&upd).unwrap();
194        assert_eq!(json["status"], "completed");
195        assert_eq!(json["readings_synced"], 5);
196        assert!(json.get("errors").is_none());
197        assert!(json.get("duration_ms").is_none());
198    }
199}