⎇ c6a131ac259b8809d1d65e463a9203e6493decb4
crates/ente-brain/src/engine.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
1//! Motor de inferencia. HashMap<EventKindDiscriminant, Vec<Arc<Rule>>> para
2//! lookup O(1) por tipo de evento, luego filter lineal por scope + filtros
3//! del payload (BusInvokeOf, Custom).
4//!
5//! Inmutabilidad fractal: `Arc<Rule>` es el unit de compartición. Clonar una
6//! regla del motor para entregarla al dispatcher es un refcount bump, no copia.
7
8use crate::observer::TimedEvent;
9use crate::rules::{EventKind, EventPattern, Rule, Scope};
10use ente_card::Capability;
11use std::collections::HashMap;
12use std::sync::Arc;
13use std::time::Duration;
14use ulid::Ulid;
15
16/// Discriminante barato de `EventKind` para indexar el HashMap. Sin payload —
17/// el match de payload se hace en una segunda pasada lineal en O(k) donde k
18/// es el número de reglas para ese tag.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum EventKindDiscriminant {
21 EnteSpawned,
22 EnteDied,
23 BusAnnounce,
24 BusInvoke,
25 BusInvokeOf,
26 DeviceAdded,
27 DeviceRemoved,
28 Custom,
29}
30
31impl From<&EventKind> for EventKindDiscriminant {
32 fn from(k: &EventKind) -> Self {
33 match k {
34 EventKind::EnteSpawned => Self::EnteSpawned,
35 EventKind::EnteDied => Self::EnteDied,
36 EventKind::BusAnnounce => Self::BusAnnounce,
37 EventKind::BusInvoke => Self::BusInvoke,
38 EventKind::BusInvokeOf(_) => Self::BusInvokeOf,
39 EventKind::DeviceAdded => Self::DeviceAdded,
40 EventKind::DeviceRemoved => Self::DeviceRemoved,
41 EventKind::Custom(_) => Self::Custom,
42 }
43 }
44}
45
46/// Snapshot del Ente que disparó el evento. Necesario para evaluar `Scope`.
47#[derive(Debug, Clone, Default)]
48pub struct SubjectInfo {
49 pub id: Option<Ulid>,
50 pub label: Option<String>,
51 pub capabilities: Vec<Capability>,
52}
53
54pub struct RuleEngine {
55 rules: Vec<Arc<Rule>>,
56 /// Reglas atómicas (Single, Sequence) indexadas por discriminante del
57 /// kind que las dispara. Lookup O(1).
58 by_kind: HashMap<EventKindDiscriminant, Vec<Arc<Rule>>>,
59 /// Reglas compuestas (Either, All): se evalúan contra cada evento.
60 /// Para fractales con N pequeño no afecta perf; con N grande, optimizar
61 /// emitiendo a múltiples buckets en insert (fan-out).
62 compound: Vec<Arc<Rule>>,
63}
64
65impl Default for RuleEngine {
66 fn default() -> Self { Self::empty() }
67}
68
69impl RuleEngine {
70 pub fn empty() -> Self {
71 Self { rules: Vec::new(), by_kind: HashMap::new(), compound: Vec::new() }
72 }
73
74 /// Carga reglas desde JSON (lista de Rule).
75 pub fn load_json(json: &str) -> anyhow::Result<Self> {
76 let rules: Vec<Rule> = serde_json::from_str(json)?;
77 let mut engine = Self::empty();
78 for r in rules {
79 r.validate().map_err(|e| anyhow::anyhow!("regla inválida: {e}"))?;
80 engine.insert(r);
81 }
82 Ok(engine)
83 }
84
85 pub fn insert(&mut self, rule: Rule) {
86 let arc = Arc::new(rule);
87 // Atómicas → bucket por discriminante. Compuestas → bucket fallback.
88 if let Some(trigger) = arc.when.trigger_kind() {
89 let disc = EventKindDiscriminant::from(trigger);
90 self.by_kind.entry(disc).or_default().push(arc.clone());
91 } else {
92 self.compound.push(arc.clone());
93 }
94 self.rules.push(arc);
95 }
96
97 pub fn remove(&mut self, id: Ulid) -> bool {
98 let before = self.rules.len();
99 self.rules.retain(|r| r.id != id);
100 for v in self.by_kind.values_mut() {
101 v.retain(|r| r.id != id);
102 }
103 self.compound.retain(|r| r.id != id);
104 before != self.rules.len()
105 }
106
107 pub fn rules(&self) -> impl Iterator<Item = &Arc<Rule>> { self.rules.iter() }
108
109 pub fn len(&self) -> usize { self.rules.len() }
110 pub fn is_empty(&self) -> bool { self.rules.is_empty() }
111
112 /// Despacho determinista. Devuelve reglas que matchean, ordenadas por
113 /// prioridad descendente. Cada Arc<Rule> se clona (refcount) — sin copiar
114 /// los datos.
115 ///
116 /// `history` es el slice de eventos recientes (en orden cronológico,
117 /// más reciente al final) usado para evaluar Sequence patterns.
118 /// Para reglas Single, history se ignora.
119 ///
120 /// Si el evento es `BusInvokeOf(_)`, también consultamos el bucket
121 /// `BusInvoke` (regla genérica que ignora la cap).
122 pub fn dispatch(
123 &self,
124 event: &EventKind,
125 subject: &SubjectInfo,
126 history: &[TimedEvent],
127 ) -> Vec<Arc<Rule>> {
128 let primary = EventKindDiscriminant::from(event);
129 let mut buckets: Vec<&Vec<Arc<Rule>>> = Vec::with_capacity(2);
130 if let Some(v) = self.by_kind.get(&primary) {
131 buckets.push(v);
132 }
133 if matches!(event, EventKind::BusInvokeOf(_)) {
134 if let Some(v) = self.by_kind.get(&EventKindDiscriminant::BusInvoke) {
135 buckets.push(v);
136 }
137 }
138 let mut hits: Vec<Arc<Rule>> = buckets.into_iter()
139 .flat_map(|v| v.iter())
140 .filter(|r| matches_pattern(&r.when, event, history))
141 .filter(|r| matches_scope(&r.scope, subject))
142 .cloned()
143 .collect();
144 // Fallback: reglas compuestas (Either/All) se evalúan siempre.
145 for r in &self.compound {
146 if matches_pattern(&r.when, event, history) && matches_scope(&r.scope, subject) {
147 hits.push(r.clone());
148 }
149 }
150 hits.sort_by(|a, b| b.priority.cmp(&a.priority));
151 hits
152 }
153}
154
155/// Match recursivo del pattern. Atomic patterns evalúan contra el evento
156/// actual + history. Compuestos (Either/All) recursan sobre sus children.
157fn matches_pattern(pattern: &EventPattern, event: &EventKind, history: &[TimedEvent]) -> bool {
158 match pattern {
159 EventPattern::Single { kind } => matches_event_payload(kind, event),
160 EventPattern::Sequence { kinds, within_ms } => {
161 if kinds.is_empty() { return false; }
162 let last_kind = kinds.last().unwrap();
163 if !matches_event_payload(last_kind, event) { return false; }
164 if history.len() < kinds.len() { return false; }
165 let tail = &history[history.len() - kinds.len()..];
166 for (t, k) in tail.iter().zip(kinds) {
167 if !matches_event_payload(k, &t.kind) { return false; }
168 }
169 if *within_ms > 0 {
170 let span = tail.last().unwrap().at.duration_since(tail.first().unwrap().at);
171 if span > Duration::from_millis(*within_ms) { return false; }
172 }
173 true
174 }
175 EventPattern::Either { patterns } => {
176 patterns.iter().any(|p| matches_pattern(p, event, history))
177 }
178 EventPattern::All { patterns } => {
179 patterns.iter().all(|p| matches_pattern(p, event, history))
180 }
181 }
182}
183
184fn matches_event_payload(rule_kind: &EventKind, evt: &EventKind) -> bool {
185 use EventKind::*;
186 match (rule_kind, evt) {
187 (EnteSpawned, EnteSpawned) => true,
188 (EnteDied, EnteDied) => true,
189 (BusAnnounce, BusAnnounce) => true,
190 (BusInvoke, BusInvoke) | (BusInvoke, BusInvokeOf(_)) => true,
191 (BusInvokeOf(want), BusInvokeOf(got)) => want == got,
192 (DeviceAdded, DeviceAdded) => true,
193 (DeviceRemoved, DeviceRemoved) => true,
194 (Custom(want), Custom(got)) => want == got,
195 _ => false,
196 }
197}
198
199fn matches_scope(scope: &Scope, subj: &SubjectInfo) -> bool {
200 if scope.is_wildcard() { return true; }
201 if let Some(id) = scope.subject_id {
202 if subj.id != Some(id) { return false; }
203 }
204 if let Some(lbl) = &scope.subject_label {
205 if subj.label.as_ref() != Some(lbl) { return false; }
206 }
207 if let Some(cap) = &scope.subject_has_cap {
208 if !subj.capabilities.contains(cap) { return false; }
209 }
210 true
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use crate::rules::{Action, EventPattern, LogLevel};
217 use std::time::{Duration, Instant};
218
219 fn rule_single(id_str: &str, kind: EventKind, prio: u8) -> Rule {
220 Rule {
221 id: id_str.parse().unwrap(),
222 priority: prio,
223 when: EventPattern::Single { kind },
224 then: vec![Action::Log {
225 level: LogLevel::Info,
226 message: id_str.into(),
227 }],
228 scope: Scope::default(),
229 }
230 }
231
232 fn empty_history() -> Vec<TimedEvent> { Vec::new() }
233
234 #[test]
235 fn dispatch_picks_only_matching_kind() {
236 let mut e = RuleEngine::empty();
237 e.insert(rule_single("01KQQ100000000000000000001", EventKind::EnteSpawned, 5));
238 e.insert(rule_single("01KQQ100000000000000000002", EventKind::EnteDied, 5));
239 let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &empty_history());
240 assert_eq!(hits.len(), 1);
241 }
242
243 #[test]
244 fn priority_orders_descending() {
245 let mut e = RuleEngine::empty();
246 e.insert(rule_single("01KQQ100000000000000000003", EventKind::EnteSpawned, 1));
247 e.insert(rule_single("01KQQ100000000000000000004", EventKind::EnteSpawned, 9));
248 let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &empty_history());
249 assert_eq!(hits[0].priority, 9);
250 assert_eq!(hits[1].priority, 1);
251 }
252
253 #[test]
254 fn scope_filters_by_label() {
255 let mut e = RuleEngine::empty();
256 let mut r = rule_single("01KQQ100000000000000000005", EventKind::EnteSpawned, 5);
257 r.scope = Scope { subject_label: Some("foo".into()), ..Default::default() };
258 e.insert(r);
259 let foo = SubjectInfo { label: Some("foo".into()), ..Default::default() };
260 let bar = SubjectInfo { label: Some("bar".into()), ..Default::default() };
261 assert_eq!(e.dispatch(&EventKind::EnteSpawned, &foo, &empty_history()).len(), 1);
262 assert_eq!(e.dispatch(&EventKind::EnteSpawned, &bar, &empty_history()).len(), 0);
263 }
264
265 #[test]
266 fn bus_invoke_generic_matches_specific() {
267 let mut e = RuleEngine::empty();
268 e.insert(rule_single("01KQQ100000000000000000006", EventKind::BusInvoke, 5));
269 let hits = e.dispatch(
270 &EventKind::BusInvokeOf(Capability::LegacyLogind),
271 &SubjectInfo::default(),
272 &empty_history(),
273 );
274 assert_eq!(hits.len(), 1);
275 }
276
277 #[test]
278 fn sequence_pattern_matches_with_history() {
279 let mut e = RuleEngine::empty();
280 let r = Rule {
281 id: "01KQQ100000000000000000007".parse().unwrap(),
282 priority: 5,
283 when: EventPattern::Sequence {
284 kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
285 within_ms: 1000,
286 },
287 then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
288 scope: Scope::default(),
289 };
290 e.insert(r);
291
292 let now = Instant::now();
293 let history = vec![
294 TimedEvent { kind: EventKind::EnteSpawned, at: now },
295 TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(50) },
296 ];
297 let hits = e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history);
298 assert_eq!(hits.len(), 1, "esperaba match secuencia, got {}", hits.len());
299 }
300
301 #[test]
302 fn sequence_rejects_outside_time_window() {
303 let mut e = RuleEngine::empty();
304 let r = Rule {
305 id: "01KQQ100000000000000000008".parse().unwrap(),
306 priority: 5,
307 when: EventPattern::Sequence {
308 kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
309 within_ms: 100,
310 },
311 then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
312 scope: Scope::default(),
313 };
314 e.insert(r);
315 let now = Instant::now();
316 let history = vec![
317 TimedEvent { kind: EventKind::EnteSpawned, at: now },
318 TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(500) },
319 ];
320 let hits = e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history);
321 assert!(hits.is_empty(), "no debería matchear fuera de la ventana");
322 }
323
324 #[test]
325 fn either_matches_any_branch() {
326 let mut e = RuleEngine::empty();
327 let r = Rule {
328 id: "01KQQ100000000000000000010".parse().unwrap(),
329 priority: 5,
330 when: EventPattern::Either { patterns: vec![
331 EventPattern::Single { kind: EventKind::EnteSpawned },
332 EventPattern::Single { kind: EventKind::EnteDied },
333 ]},
334 then: vec![Action::Log { level: LogLevel::Info, message: "either".into() }],
335 scope: Scope::default(),
336 };
337 e.insert(r);
338 assert_eq!(e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &[]).len(), 1);
339 assert_eq!(e.dispatch(&EventKind::EnteDied, &SubjectInfo::default(), &[]).len(), 1);
340 assert_eq!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &[]).len(), 0);
341 }
342
343 #[test]
344 fn all_requires_every_branch() {
345 let mut e = RuleEngine::empty();
346 // All: matchear sólo si el evento actual es BusAnnounce Y la
347 // secuencia EnteSpawned→BusAnnounce ocurrió en history.
348 let r = Rule {
349 id: "01KQQ100000000000000000011".parse().unwrap(),
350 priority: 5,
351 when: EventPattern::All { patterns: vec![
352 EventPattern::Single { kind: EventKind::BusAnnounce },
353 EventPattern::Sequence {
354 kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
355 within_ms: 0,
356 },
357 ]},
358 then: vec![Action::Log { level: LogLevel::Info, message: "all".into() }],
359 scope: Scope::default(),
360 };
361 e.insert(r);
362
363 let now = Instant::now();
364 let history = vec![
365 TimedEvent { kind: EventKind::EnteSpawned, at: now },
366 TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(10) },
367 ];
368 // Single y Sequence ambos matchean → All matches.
369 assert_eq!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history).len(), 1);
370 // Sólo Single matchea (history vacío) → All no matches.
371 assert!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &[]).is_empty());
372 }
373
374 #[test]
375 fn sequence_requires_correct_order() {
376 let mut e = RuleEngine::empty();
377 let r = Rule {
378 id: "01KQQ100000000000000000009".parse().unwrap(),
379 priority: 5,
380 when: EventPattern::Sequence {
381 kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
382 within_ms: 0,
383 },
384 then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
385 scope: Scope::default(),
386 };
387 e.insert(r);
388 let now = Instant::now();
389 // Orden invertido en el history.
390 let history = vec![
391 TimedEvent { kind: EventKind::BusAnnounce, at: now },
392 TimedEvent { kind: EventKind::EnteSpawned, at: now + Duration::from_millis(10) },
393 ];
394 // El evento actual es EnteSpawned, pero el último de la secuencia
395 // requerida es BusAnnounce — no debería matchear.
396 let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &history);
397 assert!(hits.is_empty());
398 }
399}