Skip to main content

hyprstream_workers/events/
types.rs

1//! Worker event types for EventService pub/sub.
2//!
3//! These types mirror the Cap'n Proto WorkerEvent schema and provide:
4//! - Rust-friendly struct representations with ToCapnp/FromCapnp derives
5//! - A WorkerEvent enum for type-safe event handling
6//! - ReceivedEvent wrapper for EventSubscriber integration
7//!
8//! # Usage
9//!
10//! ```ignore
11//! use hyprstream_workers::events::{WorkerEvent, ReceivedEvent, SandboxStarted};
12//!
13//! // Publishing (in WorkerService)
14//! let event = SandboxStarted {
15//!     sandbox_id: "abc123".to_owned(),
16//!     metadata: "{}".to_owned(),
17//!     vm_pid: 1234,
18//! };
19//! let payload = event.to_bytes()?;
20//! publisher.publish("abc123", "started", &payload).await?;
21//!
22//! // Subscribing (in WorkflowService)
23//! let (topic, payload) = subscriber.recv().await?;
24//! let event = ReceivedEvent::from_message(&topic, &payload);
25//! if let Some(WorkerEvent::SandboxStarted(ss)) = &event.worker_event {
26//!     println!("Sandbox {} started with PID {}", ss.sandbox_id, ss.vm_pid);
27//! }
28//! ```
29
30use anyhow::Result;
31use hyprstream_rpc::prelude::{FromCapnp, ToCapnp};
32
33use hyprstream_rpc_std::worker_capnp;
34
35// ═══════════════════════════════════════════════════════════════════════════════
36// Individual Event Types (with derive macros)
37// ═══════════════════════════════════════════════════════════════════════════════
38
39/// Sandbox started event.
40///
41/// Published when a Kata VM sandbox is successfully started.
42/// Topic format: `worker.{sandbox_id}.started`
43#[derive(Debug, Clone, ToCapnp, FromCapnp)]
44#[capnp(worker_capnp::sandbox_started)]
45pub struct SandboxStarted {
46    /// Unique sandbox identifier
47    pub sandbox_id: String,
48    /// JSON metadata about the sandbox
49    pub metadata: String,
50    /// VM process ID
51    pub vm_pid: u32,
52}
53
54/// Sandbox stopped event.
55///
56/// Published when a Kata VM sandbox stops (gracefully or due to error).
57/// Topic format: `worker.{sandbox_id}.stopped`
58#[derive(Debug, Clone, ToCapnp, FromCapnp)]
59#[capnp(worker_capnp::sandbox_stopped)]
60pub struct SandboxStopped {
61    /// Unique sandbox identifier
62    pub sandbox_id: String,
63    /// Reason for stopping (e.g., "completed", "error", "timeout")
64    pub reason: String,
65    /// VM exit code
66    pub exit_code: i32,
67}
68
69/// Container started event.
70///
71/// Published when an OCI container starts within a sandbox.
72/// Topic format: `worker.{container_id}.started`
73#[derive(Debug, Clone, ToCapnp, FromCapnp)]
74#[capnp(worker_capnp::container_started)]
75pub struct ContainerStarted {
76    /// Unique container identifier
77    pub container_id: String,
78    /// Parent sandbox identifier
79    pub sandbox_id: String,
80    /// Container image reference
81    pub image: String,
82}
83
84/// Container stopped event.
85///
86/// Published when an OCI container stops within a sandbox.
87/// Topic format: `worker.{container_id}.stopped`
88#[derive(Debug, Clone, ToCapnp, FromCapnp)]
89#[capnp(worker_capnp::container_stopped)]
90pub struct ContainerStopped {
91    /// Unique container identifier
92    pub container_id: String,
93    /// Parent sandbox identifier
94    pub sandbox_id: String,
95    /// Container exit code
96    pub exit_code: i32,
97    /// Reason for stopping
98    pub reason: String,
99}
100
101// ═══════════════════════════════════════════════════════════════════════════════
102// WorkerEvent Union (manual serialization for enum)
103// ═══════════════════════════════════════════════════════════════════════════════
104
105/// Union of all worker event types.
106///
107/// Represents the Cap'n Proto WorkerEvent union for type-safe event handling.
108#[derive(Debug, Clone)]
109pub enum WorkerEvent {
110    SandboxStarted(SandboxStarted),
111    SandboxStopped(SandboxStopped),
112    ContainerStarted(ContainerStarted),
113    ContainerStopped(ContainerStopped),
114}
115
116impl WorkerEvent {
117    /// Deserialize from Cap'n Proto bytes.
118    ///
119    /// Reads the WorkerEvent union and returns the appropriate variant.
120    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
121        use capnp::message::ReaderOptions;
122        use capnp::serialize;
123        use worker_capnp::worker_event;
124
125        let reader =
126            serialize::read_message(&mut std::io::Cursor::new(bytes), ReaderOptions::new())?;
127        let event = reader.get_root::<worker_event::Reader>()?;
128
129        match event.which()? {
130            worker_event::Which::SandboxStarted(r) => {
131                Ok(Self::SandboxStarted(SandboxStarted::read_from(r?)?))
132            }
133            worker_event::Which::SandboxStopped(r) => {
134                Ok(Self::SandboxStopped(SandboxStopped::read_from(r?)?))
135            }
136            worker_event::Which::ContainerStarted(r) => {
137                Ok(Self::ContainerStarted(ContainerStarted::read_from(r?)?))
138            }
139            worker_event::Which::ContainerStopped(r) => {
140                Ok(Self::ContainerStopped(ContainerStopped::read_from(r?)?))
141            }
142        }
143    }
144
145    /// Get the event type name (e.g., "started", "stopped").
146    pub fn event_type(&self) -> &'static str {
147        match self {
148            Self::SandboxStarted(_) | Self::ContainerStarted(_) => "started",
149            Self::SandboxStopped(_) | Self::ContainerStopped(_) => "stopped",
150        }
151    }
152
153    /// Get the entity ID (sandbox_id or container_id).
154    pub fn entity_id(&self) -> &str {
155        match self {
156            Self::SandboxStarted(e) => &e.sandbox_id,
157            Self::SandboxStopped(e) => &e.sandbox_id,
158            Self::ContainerStarted(e) => &e.container_id,
159            Self::ContainerStopped(e) => &e.container_id,
160        }
161    }
162
163    /// Check if this is a sandbox event.
164    pub fn is_sandbox_event(&self) -> bool {
165        matches!(self, Self::SandboxStarted(_) | Self::SandboxStopped(_))
166    }
167
168    /// Check if this is a container event.
169    pub fn is_container_event(&self) -> bool {
170        matches!(self, Self::ContainerStarted(_) | Self::ContainerStopped(_))
171    }
172}
173
174// ═══════════════════════════════════════════════════════════════════════════════
175// Serialization helpers for publishing
176// ═══════════════════════════════════════════════════════════════════════════════
177
178/// Serialize a SandboxStarted event to Cap'n Proto bytes.
179pub fn serialize_sandbox_started(event: &SandboxStarted) -> Result<Vec<u8>> {
180    hyprstream_rpc::serialize_message(|msg| {
181        let builder = msg.init_root::<worker_capnp::worker_event::Builder>();
182        let mut started = builder.init_sandbox_started();
183        event.write_to(&mut started);
184    })
185}
186
187/// Serialize a SandboxStopped event to Cap'n Proto bytes.
188pub fn serialize_sandbox_stopped(event: &SandboxStopped) -> Result<Vec<u8>> {
189    hyprstream_rpc::serialize_message(|msg| {
190        let builder = msg.init_root::<worker_capnp::worker_event::Builder>();
191        let mut stopped = builder.init_sandbox_stopped();
192        event.write_to(&mut stopped);
193    })
194}
195
196/// Serialize a ContainerStarted event to Cap'n Proto bytes.
197pub fn serialize_container_started(event: &ContainerStarted) -> Result<Vec<u8>> {
198    hyprstream_rpc::serialize_message(|msg| {
199        let builder = msg.init_root::<worker_capnp::worker_event::Builder>();
200        let mut started = builder.init_container_started();
201        event.write_to(&mut started);
202    })
203}
204
205/// Serialize a ContainerStopped event to Cap'n Proto bytes.
206pub fn serialize_container_stopped(event: &ContainerStopped) -> Result<Vec<u8>> {
207    hyprstream_rpc::serialize_message(|msg| {
208        let builder = msg.init_root::<worker_capnp::worker_event::Builder>();
209        let mut stopped = builder.init_container_stopped();
210        event.write_to(&mut stopped);
211    })
212}
213
214// ═══════════════════════════════════════════════════════════════════════════════
215// ReceivedEvent - EventSubscriber integration
216// ═══════════════════════════════════════════════════════════════════════════════
217
218/// Event received from EventService.
219///
220/// Wraps the raw topic and payload from EventSubscriber and provides
221/// parsed fields for handler dispatch. This replaces the duplicate
222/// EventEnvelope type in workflow/triggers.rs.
223///
224/// # Topic Format
225///
226/// Topics follow the pattern: `{source}.{entity_id}.{event_type}`
227/// - `worker.sandbox123.started` - Sandbox started event
228/// - `worker.container456.stopped` - Container stopped event
229#[derive(Debug, Clone)]
230pub struct ReceivedEvent {
231    /// Full topic string (e.g., "worker.sandbox123.started")
232    pub topic: String,
233
234    /// Source service (e.g., "worker", "registry", "model")
235    pub source: String,
236
237    /// Entity identifier (e.g., sandbox_id, container_id)
238    pub entity_id: String,
239
240    /// Event type (e.g., "started", "stopped")
241    pub event_type: String,
242
243    /// Deserialized worker event (if source is "worker" and payload is valid)
244    pub worker_event: Option<WorkerEvent>,
245
246    /// Event timestamp
247    pub timestamp: chrono::DateTime<chrono::Utc>,
248}
249
250impl ReceivedEvent {
251    /// Create a ReceivedEvent from raw topic and payload.
252    ///
253    /// Parses the topic into components and attempts to deserialize
254    /// the payload for worker events.
255    pub fn from_message(topic: &str, payload: &[u8]) -> Self {
256        let parts: Vec<&str> = topic.split('.').collect();
257        let (source, entity_id, event_type) = if parts.len() >= 3 {
258            (
259                parts[0].to_owned(),
260                parts[1].to_owned(),
261                parts[2].to_owned(),
262            )
263        } else if parts.len() == 2 {
264            (parts[0].to_owned(), parts[1].to_owned(), String::new())
265        } else {
266            (topic.to_owned(), String::new(), String::new())
267        };
268
269        // Attempt to deserialize worker events
270        let worker_event = if source == "worker" && !payload.is_empty() {
271            WorkerEvent::from_bytes(payload).ok()
272        } else {
273            None
274        };
275
276        Self {
277            topic: topic.to_owned(),
278            source,
279            entity_id,
280            event_type,
281            worker_event,
282            timestamp: chrono::Utc::now(),
283        }
284    }
285
286    /// Check if this event matches a topic pattern.
287    ///
288    /// Supports prefix matching (e.g., "worker." matches "worker.abc.started").
289    pub fn matches_pattern(&self, pattern: &str) -> bool {
290        if pattern.ends_with('.') {
291            self.topic.starts_with(pattern)
292        } else {
293            self.topic == pattern
294        }
295    }
296
297    /// Extract inputs for workflow dispatch.
298    ///
299    /// Returns a map of input values extracted from the event payload.
300    pub fn extract_inputs(&self) -> std::collections::HashMap<String, String> {
301        let mut inputs = std::collections::HashMap::new();
302
303        inputs.insert("topic".to_owned(), self.topic.clone());
304        inputs.insert("source".to_owned(), self.source.clone());
305        inputs.insert("entity_id".to_owned(), self.entity_id.clone());
306        inputs.insert("event_type".to_owned(), self.event_type.clone());
307
308        // Add event-specific fields
309        if let Some(ref event) = self.worker_event {
310            match event {
311                WorkerEvent::SandboxStarted(e) => {
312                    inputs.insert("sandbox_id".to_owned(), e.sandbox_id.clone());
313                    inputs.insert("metadata".to_owned(), e.metadata.clone());
314                    inputs.insert("vm_pid".to_owned(), e.vm_pid.to_string());
315                }
316                WorkerEvent::SandboxStopped(e) => {
317                    inputs.insert("sandbox_id".to_owned(), e.sandbox_id.clone());
318                    inputs.insert("reason".to_owned(), e.reason.clone());
319                    inputs.insert("exit_code".to_owned(), e.exit_code.to_string());
320                }
321                WorkerEvent::ContainerStarted(e) => {
322                    inputs.insert("container_id".to_owned(), e.container_id.clone());
323                    inputs.insert("sandbox_id".to_owned(), e.sandbox_id.clone());
324                    inputs.insert("image".to_owned(), e.image.clone());
325                }
326                WorkerEvent::ContainerStopped(e) => {
327                    inputs.insert("container_id".to_owned(), e.container_id.clone());
328                    inputs.insert("sandbox_id".to_owned(), e.sandbox_id.clone());
329                    inputs.insert("exit_code".to_owned(), e.exit_code.to_string());
330                    inputs.insert("reason".to_owned(), e.reason.clone());
331                }
332            }
333        }
334
335        inputs
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn test_received_event_parsing() {
345        let event = ReceivedEvent::from_message("worker.sandbox123.started", &[]);
346
347        assert_eq!(event.source, "worker");
348        assert_eq!(event.entity_id, "sandbox123");
349        assert_eq!(event.event_type, "started");
350        assert!(event.worker_event.is_none()); // Empty payload
351    }
352
353    #[test]
354    fn test_received_event_pattern_matching() {
355        let event = ReceivedEvent::from_message("worker.sandbox123.started", &[]);
356
357        assert!(event.matches_pattern("worker."));
358        assert!(event.matches_pattern("worker.sandbox123.started"));
359        assert!(!event.matches_pattern("registry."));
360    }
361
362    #[test]
363    fn test_sandbox_started_roundtrip() -> Result<()> {
364        let original = SandboxStarted {
365            sandbox_id: "test-123".to_owned(),
366            metadata: r#"{"cpu":2}"#.to_owned(),
367            vm_pid: 9876,
368        };
369
370        let bytes = serialize_sandbox_started(&original)?;
371        let event = WorkerEvent::from_bytes(&bytes)?;
372
373        match event {
374            WorkerEvent::SandboxStarted(ss) => {
375                assert_eq!(ss.sandbox_id, "test-123");
376                assert_eq!(ss.metadata, r#"{"cpu":2}"#);
377                assert_eq!(ss.vm_pid, 9876);
378            }
379            _ => panic!("Expected SandboxStarted"),
380        }
381        Ok(())
382    }
383
384    #[test]
385    fn test_container_stopped_roundtrip() -> Result<()> {
386        let original = ContainerStopped {
387            container_id: "cont-456".to_owned(),
388            sandbox_id: "sb-123".to_owned(),
389            exit_code: 0,
390            reason: "completed".to_owned(),
391        };
392
393        let bytes = serialize_container_stopped(&original)?;
394        let event = WorkerEvent::from_bytes(&bytes)?;
395
396        match event {
397            WorkerEvent::ContainerStopped(cs) => {
398                assert_eq!(cs.container_id, "cont-456");
399                assert_eq!(cs.sandbox_id, "sb-123");
400                assert_eq!(cs.exit_code, 0);
401                assert_eq!(cs.reason, "completed");
402            }
403            _ => panic!("Expected ContainerStopped"),
404        }
405        Ok(())
406    }
407
408    #[test]
409    fn test_extract_inputs() -> Result<()> {
410        let original = SandboxStarted {
411            sandbox_id: "sb-789".to_owned(),
412            metadata: "{}".to_owned(),
413            vm_pid: 1234,
414        };
415        let bytes = serialize_sandbox_started(&original)?;
416
417        let event = ReceivedEvent::from_message("worker.sb-789.started", &bytes);
418        let inputs = event.extract_inputs();
419
420        assert_eq!(inputs.get("sandbox_id"), Some(&"sb-789".to_owned()));
421        assert_eq!(inputs.get("vm_pid"), Some(&"1234".to_owned()));
422        assert_eq!(inputs.get("event_type"), Some(&"started".to_owned()));
423        Ok(())
424    }
425}