Skip to main content

hyprstream_workers/workflow/
triggers.rs

1//! Event triggers and handlers for workflow execution
2//!
3//! Provides the EventHandler trait for testable, composable event handling.
4//! Uses ReceivedEvent from the events module for EventService integration.
5
6#![allow(dead_code)] // Handlers will be used when event bus is implemented
7
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12use crate::error::Result;
13use crate::events::{ReceivedEvent, WorkerEvent};
14
15use super::parser::InputDef;
16use super::WorkflowId;
17
18// ═══════════════════════════════════════════════════════════════════════════════
19// Trigger Configuration Types
20// ═══════════════════════════════════════════════════════════════════════════════
21
22/// Event trigger types for workflow configuration
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub enum EventTrigger {
25    /// Repository events - triggers rescan + registered workflows
26    RepositoryEvent {
27        /// Event type
28        event_type: RepoEventType,
29        /// Glob pattern for branch/path filtering
30        pattern: Option<String>,
31    },
32
33    /// Training progress (for auto-checkpoint workflows)
34    TrainingProgress {
35        /// Model ID
36        model_id: String,
37        /// Minimum step to trigger
38        min_step: Option<u32>,
39    },
40
41    /// Metrics threshold breach (for auto-tune workflows)
42    MetricsBreach {
43        /// Metric name
44        metric_name: String,
45        /// Threshold value
46        threshold: f64,
47    },
48
49    /// Manual workflow dispatch
50    WorkflowDispatch {
51        /// Input definitions
52        inputs: HashMap<String, InputDef>,
53    },
54
55    /// Worker lifecycle events (sandbox/container)
56    WorkerLifecycle {
57        /// Event filter: "started", "stopped", or None for all
58        event_filter: Option<String>,
59        /// Entity type: "sandbox", "container", or None for all
60        entity_type: Option<String>,
61    },
62
63    /// Custom topic subscription
64    Custom {
65        /// Topic pattern
66        topic: String,
67        /// Message pattern
68        pattern: String,
69    },
70}
71
72/// Repository event types
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
74pub enum RepoEventType {
75    /// Repository cloned
76    Clone,
77    /// Branch pushed
78    Push,
79    /// Commit created
80    Commit,
81    /// Branch merged
82    Merge,
83    /// Pull request opened/updated
84    PullRequest,
85    /// Tag created
86    Tag,
87}
88
89// ═══════════════════════════════════════════════════════════════════════════════
90// Handler Result
91// ═══════════════════════════════════════════════════════════════════════════════
92
93/// Handler result actions
94#[derive(Debug)]
95pub enum HandlerResult {
96    /// Trigger workflow dispatch
97    Dispatch {
98        workflow_id: WorkflowId,
99        inputs: HashMap<String, String>,
100    },
101
102    /// Rescan repository for workflows
103    Rescan { repo_id: String },
104
105    /// No action needed
106    Ignored,
107}
108
109// ═══════════════════════════════════════════════════════════════════════════════
110// Event Handler Trait (uses ReceivedEvent from EventService)
111// ═══════════════════════════════════════════════════════════════════════════════
112
113/// Event handler trait for testable, composable handlers.
114///
115/// Handlers receive ReceivedEvent from the EventService subscriber
116/// and decide whether to dispatch workflows based on the event.
117#[async_trait]
118pub trait EventHandler: Send + Sync {
119    /// Check if this handler should process the event.
120    ///
121    /// Called for every event; should be fast (topic/type checking only).
122    fn matches(&self, event: &ReceivedEvent) -> bool;
123
124    /// Process the event and return an action.
125    ///
126    /// Only called if `matches()` returned true.
127    async fn handle(&self, event: &ReceivedEvent) -> Result<HandlerResult>;
128
129    /// The workflow id this handler dispatches on behalf of.
130    ///
131    /// Used by adapters to reconcile per-repo handlers: on a strict reload,
132    /// handlers whose workflow id belongs to a repo being rescanned are
133    /// dropped and rebuilt from the fresh workflow set, so a workflow that
134    /// was rejected/deleted can no longer be triggered (#1432 fail-closed).
135    fn workflow_id(&self) -> &super::WorkflowId;
136}
137
138// ═══════════════════════════════════════════════════════════════════════════════
139// Worker Lifecycle Handler
140// ═══════════════════════════════════════════════════════════════════════════════
141
142/// Handler for worker lifecycle events (sandbox/container started/stopped).
143///
144/// Triggers workflows when sandboxes or containers reach specific states.
145pub struct WorkerLifecycleHandler {
146    workflow_id: WorkflowId,
147    /// Filter by event type: "started", "stopped", or None for all
148    event_filter: Option<String>,
149    /// Filter by entity type: "sandbox", "container", or None for all
150    entity_type: Option<String>,
151}
152
153impl WorkerLifecycleHandler {
154    /// Create a new worker lifecycle handler
155    pub fn new(
156        workflow_id: WorkflowId,
157        event_filter: Option<String>,
158        entity_type: Option<String>,
159    ) -> Self {
160        Self {
161            workflow_id,
162            event_filter,
163            entity_type,
164        }
165    }
166
167    /// Create a handler for all sandbox events
168    pub fn sandboxes(workflow_id: WorkflowId) -> Self {
169        Self::new(workflow_id, None, Some("sandbox".to_owned()))
170    }
171
172    /// Create a handler for all container events
173    pub fn containers(workflow_id: WorkflowId) -> Self {
174        Self::new(workflow_id, None, Some("container".to_owned()))
175    }
176
177    /// Create a handler for started events only
178    pub fn on_started(workflow_id: WorkflowId) -> Self {
179        Self::new(workflow_id, Some("started".to_owned()), None)
180    }
181
182    /// Create a handler for stopped events only
183    pub fn on_stopped(workflow_id: WorkflowId) -> Self {
184        Self::new(workflow_id, Some("stopped".to_owned()), None)
185    }
186}
187
188#[async_trait]
189impl EventHandler for WorkerLifecycleHandler {
190    fn matches(&self, event: &ReceivedEvent) -> bool {
191        // Only handle worker events
192        if event.source != "worker" {
193            return false;
194        }
195
196        // Check event type filter
197        if let Some(ref filter) = self.event_filter {
198            if &event.event_type != filter {
199                return false;
200            }
201        }
202
203        // Check entity type filter
204        if let Some(ref entity_type) = self.entity_type {
205            if let Some(ref worker_event) = event.worker_event {
206                let entity_matches = matches!(
207                    (entity_type.as_str(), worker_event),
208                    (
209                        "sandbox",
210                        WorkerEvent::SandboxStarted(_) | WorkerEvent::SandboxStopped(_)
211                    ) | (
212                        "container",
213                        WorkerEvent::ContainerStarted(_) | WorkerEvent::ContainerStopped(_)
214                    )
215                );
216                if !entity_matches {
217                    return false;
218                }
219            } else {
220                return false;
221            }
222        }
223
224        true
225    }
226
227    async fn handle(&self, event: &ReceivedEvent) -> Result<HandlerResult> {
228        let inputs = event.extract_inputs();
229        Ok(HandlerResult::Dispatch {
230            workflow_id: self.workflow_id.clone(),
231            inputs,
232        })
233    }
234
235    fn workflow_id(&self) -> &super::WorkflowId {
236        &self.workflow_id
237    }
238}
239
240// ═══════════════════════════════════════════════════════════════════════════════
241// Topic Pattern Handler
242// ═══════════════════════════════════════════════════════════════════════════════
243
244/// Handler that matches events by topic pattern.
245///
246/// Useful for custom event routing or debugging.
247pub struct TopicPatternHandler {
248    workflow_id: WorkflowId,
249    /// Topic prefix or exact match
250    topic_pattern: String,
251}
252
253impl TopicPatternHandler {
254    /// Create a new topic pattern handler
255    pub fn new(workflow_id: WorkflowId, topic_pattern: String) -> Self {
256        Self {
257            workflow_id,
258            topic_pattern,
259        }
260    }
261}
262
263#[async_trait]
264impl EventHandler for TopicPatternHandler {
265    fn matches(&self, event: &ReceivedEvent) -> bool {
266        event.matches_pattern(&self.topic_pattern)
267    }
268
269    async fn handle(&self, event: &ReceivedEvent) -> Result<HandlerResult> {
270        let inputs = event.extract_inputs();
271        Ok(HandlerResult::Dispatch {
272            workflow_id: self.workflow_id.clone(),
273            inputs,
274        })
275    }
276
277    fn workflow_id(&self) -> &super::WorkflowId {
278        &self.workflow_id
279    }
280}
281
282// ═══════════════════════════════════════════════════════════════════════════════
283// Helpers
284// ═══════════════════════════════════════════════════════════════════════════════
285
286/// Simple glob pattern matching
287pub fn glob_match(pattern: &str, text: &str) -> bool {
288    // Simple implementation: * matches any sequence
289    if pattern == "*" {
290        return true;
291    }
292
293    if pattern.contains('*') {
294        let parts: Vec<&str> = pattern.split('*').collect();
295        if parts.len() == 2 {
296            // prefix*suffix
297            let prefix = parts[0];
298            let suffix = parts[1];
299            return text.starts_with(prefix) && text.ends_with(suffix);
300        }
301    }
302
303    pattern == text
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn test_glob_match() {
312        assert!(glob_match("main", "main"));
313        assert!(glob_match("*", "anything"));
314        assert!(glob_match("feature/*", "feature/foo"));
315        assert!(!glob_match("main", "develop"));
316    }
317
318    #[test]
319    fn test_worker_lifecycle_handler_matches() {
320        // Create a handler for sandbox started events
321        let handler =
322            WorkerLifecycleHandler::new("test:wf".to_owned(), Some("started".to_owned()), None);
323
324        // Create test events
325        let started_event = ReceivedEvent::from_message("worker.sandbox123.started", &[]);
326        let stopped_event = ReceivedEvent::from_message("worker.sandbox123.stopped", &[]);
327        let other_event = ReceivedEvent::from_message("registry.repo456.push", &[]);
328
329        assert!(handler.matches(&started_event));
330        assert!(!handler.matches(&stopped_event));
331        assert!(!handler.matches(&other_event));
332    }
333
334    #[test]
335    fn test_topic_pattern_handler_matches() {
336        let handler = TopicPatternHandler::new("test:wf".to_owned(), "worker.".to_owned());
337
338        let worker_event = ReceivedEvent::from_message("worker.sandbox123.started", &[]);
339        let registry_event = ReceivedEvent::from_message("registry.repo456.push", &[]);
340
341        assert!(handler.matches(&worker_event));
342        assert!(!handler.matches(&registry_event));
343    }
344}