Skip to main content

alien_core/
sync.rs

1//! Sync protocol types for agent ↔ manager communication.
2//!
3//! The agent periodically calls `POST /v1/sync` with a `SyncRequest` and
4//! receives a `SyncResponse` containing the target deployment state.
5
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    DeploymentConfig, DeploymentState, ObservedInventoryBatch, ReleaseInfo, ResourceHeartbeat,
10};
11
12/// State of an Operator capability as observed inside the environment.
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "kebab-case")]
16pub enum OperatorCapabilityState {
17    /// The Operator has the permission or local facility needed for the capability.
18    Granted,
19    /// The environment explicitly denied the capability.
20    Denied,
21    /// The capability does not apply in this environment.
22    Unavailable,
23}
24
25/// Report-only Operator capability status.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28#[serde(rename_all = "camelCase")]
29pub struct OperatorCapabilityReport {
30    /// Stable capability key, such as `k8s-workloads` or `logs`.
31    pub key: String,
32    /// Whether the capability is currently usable.
33    pub state: OperatorCapabilityState,
34    /// Optional human-readable detail from the Operator.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub detail: Option<String>,
37}
38
39/// Request sent by the agent to the manager during periodic sync.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct SyncRequest {
43    /// The deployment ID this agent is managing.
44    pub deployment_id: String,
45    /// Current deployment state as seen by the agent.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub current_state: Option<DeploymentState>,
48    /// Managed Alien resource status samples emitted by the Operator's deployment step.
49    #[serde(
50        default,
51        rename = "resourceHeartbeats",
52        skip_serializing_if = "Vec::is_empty"
53    )]
54    pub heartbeats: Vec<ResourceHeartbeat>,
55    /// Observed raw-resource inventory batches successfully read by the Operator.
56    #[serde(
57        default,
58        rename = "observedInventoryBatches",
59        skip_serializing_if = "Vec::is_empty"
60    )]
61    pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
62    /// Report-only capabilities observed by the Operator.
63    #[serde(default, skip_serializing_if = "Vec::is_empty")]
64    pub capabilities: Vec<OperatorCapabilityReport>,
65    /// Version of the Operator binary reporting this sync.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub operator_version: Option<String>,
68}
69
70/// Response from the manager to the agent sync request.
71#[derive(Debug, Clone, Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73pub struct SyncResponse {
74    /// Authoritative deployment state from the manager.
75    ///
76    /// Pull agents use this to hydrate local state when attaching to an
77    /// already-imported deployment. Absent means the agent's local state is
78    /// already authoritative or no state has been established yet.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub current_state: Option<DeploymentState>,
81    /// Target deployment the agent should converge toward.
82    /// None means no changes needed or this is an observe-only deployment.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub target: Option<TargetDeployment>,
85    /// Public URL for the commands API (e.g. `https://manager.example.com/v1`).
86    /// Cloud-deployed workers use this to poll for pending commands.
87    /// When absent, the agent falls back to its sync URL.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub commands_url: Option<String>,
90}
91
92/// Target deployment state for the agent to converge toward.
93#[derive(Debug, Clone, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub struct TargetDeployment {
96    /// Release information (ID, version, stack definition).
97    pub release_info: ReleaseInfo,
98    /// Full deployment configuration (settings, env vars, etc.).
99    pub config: DeploymentConfig,
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn test_sync_request_serialization() {
108        let req = SyncRequest {
109            deployment_id: "dep_abc123".to_string(),
110            current_state: None,
111            heartbeats: Vec::new(),
112            observed_inventory_batches: Vec::new(),
113            capabilities: Vec::new(),
114            operator_version: None,
115        };
116
117        let json = serde_json::to_value(&req).unwrap();
118        assert_eq!(json["deploymentId"], "dep_abc123");
119        // current_state is None → should be omitted
120        assert!(json.get("currentState").is_none());
121        assert!(json.get("resourceHeartbeats").is_none());
122        assert!(json.get("capabilities").is_none());
123        assert!(json.get("operatorVersion").is_none());
124    }
125
126    #[test]
127    fn test_sync_request_deserialization() {
128        let json = r#"{"deploymentId": "dep_xyz"}"#;
129        let req: SyncRequest = serde_json::from_str(json).unwrap();
130        assert_eq!(req.deployment_id, "dep_xyz");
131        assert!(req.current_state.is_none());
132        assert!(req.heartbeats.is_empty());
133        assert!(req.observed_inventory_batches.is_empty());
134        assert!(req.capabilities.is_empty());
135        assert!(req.operator_version.is_none());
136    }
137
138    #[test]
139    fn test_sync_response_empty() {
140        let resp = SyncResponse {
141            current_state: None,
142            target: None,
143            commands_url: None,
144        };
145        let json = serde_json::to_value(&resp).unwrap();
146        // target is None → should be omitted
147        assert!(json.get("target").is_none());
148        assert!(json.get("currentState").is_none());
149    }
150
151    #[test]
152    fn test_sync_response_roundtrip_no_target() {
153        let resp = SyncResponse {
154            current_state: None,
155            target: None,
156            commands_url: None,
157        };
158        let serialized = serde_json::to_string(&resp).unwrap();
159        let deserialized: SyncResponse = serde_json::from_str(&serialized).unwrap();
160        assert!(deserialized.target.is_none());
161        assert!(deserialized.current_state.is_none());
162    }
163
164    #[test]
165    fn test_sync_request_with_camel_case() {
166        // Verify camelCase renaming works correctly
167        let json = r#"{"deploymentId": "dep_1", "currentState": null}"#;
168        let req: SyncRequest = serde_json::from_str(json).unwrap();
169        assert_eq!(req.deployment_id, "dep_1");
170        assert!(req.current_state.is_none());
171        assert!(req.heartbeats.is_empty());
172        assert!(req.capabilities.is_empty());
173
174        // snake_case should NOT work
175        let json = r#"{"deployment_id": "dep_1"}"#;
176        assert!(serde_json::from_str::<SyncRequest>(json).is_err());
177    }
178
179    #[test]
180    fn test_sync_request_heartbeats_roundtrip() {
181        let json = serde_json::json!({
182            "deploymentId": "dep_1",
183            "resourceHeartbeats": [{
184                "deploymentId": "dep_1",
185                "resourceId": "api",
186                "resourceType": "container",
187                "controllerPlatform": "kubernetes",
188                "backend": "kubernetes",
189                "observedAt": "2026-01-01T00:00:00Z",
190                "data": {
191                    "resourceType": "container",
192                    "data": {
193                        "backend": "kubernetes",
194                        "status": {
195                            "health": "healthy",
196                            "lifecycle": "running",
197                            "message": null,
198                            "stale": false,
199                            "partial": false,
200                            "collectionIssues": []
201                        },
202                        "namespace": "default",
203                        "name": "api",
204                        "workloadKind": "deployment",
205                        "replicas": { "desired": 1, "current": 1, "ready": 1, "available": 1, "updated": null, "misscheduled": null },
206                        "restarts": 0,
207                        "cpu": null,
208                        "memory": null,
209                        "workload": null,
210                        "pods": [],
211                        "instances": [],
212                        "events": []
213                    }
214                },
215                "raw": []
216            }]
217        });
218
219        let req: SyncRequest = serde_json::from_value(json).unwrap();
220        assert_eq!(req.heartbeats.len(), 1);
221        assert_eq!(req.heartbeats[0].resource_id, "api");
222        assert!(req.capabilities.is_empty());
223
224        let serialized = serde_json::to_value(&req).unwrap();
225        assert_eq!(serialized["resourceHeartbeats"][0]["resourceId"], "api");
226    }
227
228    #[test]
229    fn test_sync_response_observe_only_state_roundtrip() {
230        let state = DeploymentState {
231            status: crate::DeploymentStatus::Running,
232            platform: crate::Platform::Kubernetes,
233            current_release: None,
234            target_release: None,
235            stack_state: None,
236            error: None,
237            environment_info: None,
238            runtime_metadata: None,
239            retry_requested: false,
240            protocol_version: crate::DEPLOYMENT_PROTOCOL_VERSION,
241        };
242        assert!(!state.has_desired());
243
244        let resp = SyncResponse {
245            current_state: Some(state),
246            target: None,
247            commands_url: None,
248        };
249
250        let serialized = serde_json::to_string(&resp).unwrap();
251        let deserialized: SyncResponse = serde_json::from_str(&serialized).unwrap();
252        let current_state = deserialized.current_state.unwrap();
253
254        assert_eq!(current_state.status, crate::DeploymentStatus::Running);
255        assert!(!current_state.has_desired());
256        assert!(deserialized.target.is_none());
257    }
258}