apcore 0.20.0

Schema-driven module standard for AI-perceivable interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// APCore Protocol — Event emitter
// Spec reference: Event types and emission

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use super::subscribers::EventSubscriber;
use crate::errors::ModuleError;

/// An event emitted by the `APCore` system.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApCoreEvent {
    pub event_type: String,
    /// ISO 8601 timestamp string.
    pub timestamp: String,
    pub data: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub module_id: Option<String>,
    pub severity: String,
}

impl ApCoreEvent {
    /// Create a new event with "info" severity.
    pub fn new(event_type: impl Into<String>, data: serde_json::Value) -> Self {
        Self {
            event_type: event_type.into(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            data,
            module_id: None,
            severity: "info".to_string(),
        }
    }

    /// Create a new event with explicit `module_id` and severity.
    pub fn with_module(
        event_type: impl Into<String>,
        data: serde_json::Value,
        module_id: impl Into<String>,
        severity: impl Into<String>,
    ) -> Self {
        Self {
            event_type: event_type.into(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            data,
            module_id: Some(module_id.into()),
            severity: severity.into(),
        }
    }
}

/// Manages event subscribers and dispatches events.
///
/// Subscribers are stored as `Arc<dyn EventSubscriber>` so they can be
/// cheaply cloned into spawned tasks for [`Self::emit_spawn`]'s
/// fire-and-forget dispatch model (sync finding A-D-501).
#[derive(Debug)]
pub struct EventEmitter {
    subscribers: Vec<Arc<dyn EventSubscriber>>,
    pub max_workers: usize,
    /// Set to `true` by [`Self::shutdown`]. Once set, all `emit*` methods
    /// drop incoming events as no-ops (sync finding A-D-502).
    is_shutdown: Arc<AtomicBool>,
}

impl EventEmitter {
    /// Create a new event emitter.
    #[must_use]
    pub fn new() -> Self {
        Self {
            subscribers: vec![],
            max_workers: 4,
            is_shutdown: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Add a subscriber (matching Python's void return signature).
    pub fn subscribe(&mut self, subscriber: Box<dyn EventSubscriber>) {
        // Convert Box -> Arc so subscribers can be cloned into spawned
        // tasks by `emit_spawn` (sync finding A-D-501).
        self.subscribers.push(Arc::from(subscriber));
    }

    /// Remove the first subscriber whose `subscriber_id()` matches the given
    /// subscriber's ID, matching Python's identity-based removal semantics.
    pub fn unsubscribe(&mut self, subscriber: &dyn EventSubscriber) -> bool {
        let target_id = subscriber.subscriber_id();
        self.unsubscribe_by_id(target_id)
    }

    /// Remove the first subscriber whose `subscriber_id()` matches the given ID string.
    pub fn unsubscribe_by_id(&mut self, subscriber_id: &str) -> bool {
        let pos = self
            .subscribers
            .iter()
            .position(|s| s.subscriber_id() == subscriber_id);
        if let Some(i) = pos {
            self.subscribers.remove(i);
            true
        } else {
            false
        }
    }

    /// Remove all subscribers whose `event_type_filter()` equals `event_type`.
    ///
    /// Returns the number of subscribers removed. Matches Python/TypeScript
    /// `off(event_type)` semantics where passing an event-type string removes
    /// all handlers bound to that type.
    pub fn unsubscribe_by_event_type(&mut self, event_type: &str) -> usize {
        let before = self.subscribers.len();
        self.subscribers
            .retain(|s| s.event_type_filter().is_none_or(|t| t != event_type));
        before - self.subscribers.len()
    }

    /// Emit an event to all subscribers whose pattern matches the event type.
    ///
    /// Errors from individual subscribers are logged but not propagated
    /// (error isolation), matching Python's behaviour.
    ///
    /// **Post-shutdown behaviour:** if [`Self::shutdown`] has been called,
    /// this method returns immediately as a no-op (sync finding A-D-502).
    ///
    /// Spec event-system.md:448 declares `No errors raised`. The body is
    /// infallible — subscriber errors are caught and logged internally —
    /// so the return type is unit, not `Result<(), ModuleError>` (D10-008).
    pub async fn emit(&self, event: &ApCoreEvent) {
        if self.is_shutdown.load(Ordering::SeqCst) {
            return;
        }
        for subscriber in &self.subscribers {
            if Self::matches_pattern(subscriber.event_pattern(), &event.event_type) {
                if let Err(e) = subscriber.on_event(event).await {
                    tracing::warn!(
                        subscriber_id = %subscriber.subscriber_id(),
                        event_type = %event.event_type,
                        error = %e,
                        "event subscriber failed"
                    );
                }
            }
        }
    }

    /// Emit an event to subscribers matching both the caller's filter pattern
    /// AND the subscriber's own `event_pattern`.
    ///
    /// **Post-shutdown behaviour:** drops the event as a no-op (sync
    /// finding A-D-502).
    pub async fn emit_filtered(
        &self,
        event: &ApCoreEvent,
        pattern: &str,
    ) -> Result<(), ModuleError> {
        if self.is_shutdown.load(Ordering::SeqCst) {
            return Ok(());
        }
        for subscriber in &self.subscribers {
            if Self::matches_pattern(pattern, &event.event_type)
                && Self::matches_pattern(subscriber.event_pattern(), &event.event_type)
            {
                if let Err(e) = subscriber.on_event(event).await {
                    tracing::warn!(
                        subscriber_id = %subscriber.subscriber_id(),
                        event_type = %event.event_type,
                        error = %e,
                        "event subscriber failed"
                    );
                }
            }
        }
        Ok(())
    }

    /// Flush all pending events, waiting up to `timeout_ms` milliseconds.
    ///
    /// This implementation uses a synchronous dispatch model — all events are
    /// dispatched inline during `emit()`, so there is nothing to flush.
    pub fn flush(&self, _timeout_ms: u64) -> Result<(), ModuleError> {
        // Synchronous dispatch model — nothing to flush.
        Ok(())
    }

    /// Fire-and-forget dispatch: spawns one `tokio::task` per matching
    /// subscriber and returns immediately.
    ///
    /// Use this when the caller cannot wait for subscriber completion (the
    /// canonical "fire-and-forget" path called out by the spec, sync finding
    /// A-D-501). Errors from subscribers are logged via `tracing::warn!` and
    /// never propagated. Subscribers run **concurrently** because each is
    /// driven on its own task.
    ///
    /// `emit_spawn` is the preferred dispatch path for runtime modules
    /// (system modules, circuit breaker, etc.); the sequential `emit` is
    /// retained for tests that need deterministic ordering.
    ///
    /// **Post-shutdown behaviour:** drops the event as a no-op once
    /// [`Self::shutdown`] has been called (sync finding A-D-502).
    // Takes `event: ApCoreEvent` by value because each spawned task needs an
    // owned `ApCoreEvent`; passing by reference would force the caller to
    // clone, hiding the cost. The spec's pseudocode signature also
    // matches by-value (sync finding A-D-501).
    #[allow(clippy::needless_pass_by_value)]
    pub fn emit_spawn(&self, event: ApCoreEvent) {
        if self.is_shutdown.load(Ordering::SeqCst) {
            return;
        }
        for subscriber in &self.subscribers {
            if !Self::matches_pattern(subscriber.event_pattern(), &event.event_type) {
                continue;
            }
            let sub = Arc::clone(subscriber);
            let evt = event.clone();
            tokio::spawn(async move {
                if let Err(e) = sub.on_event(&evt).await {
                    tracing::warn!(
                        subscriber_id = %sub.subscriber_id(),
                        event_type = %evt.event_type,
                        error = %e,
                        "emit_spawn: subscriber on_event failed"
                    );
                }
            });
        }
    }

    /// Mark this emitter as shut down and flush any pending work.
    ///
    /// After `shutdown` returns:
    /// - Subsequent calls to `emit`, `emit_filtered`, and `emit_spawn` are
    ///   no-ops — the event is dropped.
    /// - Subsequent calls to `shutdown` return `Ok(())` immediately
    ///   (idempotent).
    ///
    /// `timeout_ms` bounds the wait for any in-flight flush. The current
    /// implementation dispatches events synchronously / via spawned tasks
    /// that the emitter does not own, so flush is a no-op pass-through —
    /// the parameter is reserved for future buffering implementations and
    /// kept for API parity with apcore-python and apcore-typescript
    /// (sync finding A-D-502).
    ///
    /// `async fn` is preserved for cross-language API parity even though
    /// the current body has no `.await` points; future buffered/spawned
    /// implementations will need to await flush completion.
    #[allow(clippy::unused_async)]
    pub async fn shutdown(&mut self, timeout_ms: u64) -> Result<(), ModuleError> {
        if self.is_shutdown.swap(true, Ordering::SeqCst) {
            // Already shut down — idempotent.
            return Ok(());
        }
        self.flush(timeout_ms)
    }

    /// Returns `true` if this emitter has been shut down.
    #[must_use]
    pub fn is_shutdown(&self) -> bool {
        self.is_shutdown.load(Ordering::SeqCst)
    }

    /// Simple glob-style pattern matching with `*` wildcard.
    ///
    /// - `"*"` matches everything.
    /// - `"foo.*"` matches `"foo.bar"`, `"foo.baz"`, etc.
    /// - An exact string matches only itself.
    fn matches_pattern(pattern: &str, event_type: &str) -> bool {
        if pattern == "*" {
            return true;
        }
        // Split pattern by '*' and check that all parts appear in order.
        let parts: Vec<&str> = pattern.split('*').collect();
        let mut remaining = event_type;
        for (i, part) in parts.iter().enumerate() {
            if part.is_empty() {
                continue;
            }
            if i == 0 {
                // First part must be a prefix.
                if let Some(rest) = remaining.strip_prefix(part) {
                    remaining = rest;
                } else {
                    return false;
                }
            } else if let Some(pos) = remaining.find(part) {
                remaining = &remaining[pos + part.len()..];
            } else {
                return false;
            }
        }
        // If pattern doesn't end with *, remaining must be empty.
        if !pattern.ends_with('*') && !remaining.is_empty() {
            return false;
        }
        true
    }
}

impl Default for EventEmitter {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use parking_lot::Mutex;
    use serde_json::json;
    use std::sync::Arc;

    #[derive(Debug, Clone)]
    struct RecordingSubscriber {
        id: String,
        pattern: String,
        received: Arc<Mutex<Vec<String>>>,
    }

    impl RecordingSubscriber {
        fn new(id: &str, pattern: &str) -> Self {
            Self {
                id: id.to_string(),
                pattern: pattern.to_string(),
                received: Arc::new(Mutex::new(Vec::new())),
            }
        }
    }

    #[async_trait]
    impl EventSubscriber for RecordingSubscriber {
        fn subscriber_id(&self) -> &str {
            &self.id
        }
        fn event_pattern(&self) -> &str {
            &self.pattern
        }
        async fn on_event(&self, event: &ApCoreEvent) -> Result<(), ModuleError> {
            self.received.lock().push(event.event_type.clone());
            Ok(())
        }
    }

    #[test]
    fn test_event_new_defaults() {
        let event = ApCoreEvent::new("test.event", json!({"key": "val"}));
        assert_eq!(event.event_type, "test.event");
        assert_eq!(event.severity, "info");
        assert!(event.module_id.is_none());
        assert!(!event.timestamp.is_empty());
    }

    #[test]
    fn test_event_with_module() {
        let event = ApCoreEvent::with_module("err.event", json!({}), "mod.a", "error");
        assert_eq!(event.event_type, "err.event");
        assert_eq!(event.severity, "error");
        assert_eq!(event.module_id.as_deref(), Some("mod.a"));
    }

    #[test]
    fn test_event_serialization_skips_none_module_id() {
        let event = ApCoreEvent::new("test", json!(null));
        let serialized = serde_json::to_value(&event).unwrap();
        assert!(serialized.get("module_id").is_none());
    }

    #[test]
    fn test_emitter_default_max_workers() {
        let emitter = EventEmitter::new();
        assert_eq!(emitter.max_workers, 4);
    }

    #[tokio::test]
    async fn test_emit_to_matching_subscriber() {
        let mut emitter = EventEmitter::new();
        let sub = RecordingSubscriber::new("sub1", "test.*");
        let received = sub.received.clone();
        emitter.subscribe(Box::new(sub));

        let event = ApCoreEvent::new("test.hello", json!({}));
        emitter.emit(&event).await;
        assert_eq!(received.lock().len(), 1);
        assert_eq!(received.lock()[0], "test.hello");
    }

    #[tokio::test]
    async fn test_emit_skips_non_matching_subscriber() {
        let mut emitter = EventEmitter::new();
        let sub = RecordingSubscriber::new("sub1", "other.*");
        let received = sub.received.clone();
        emitter.subscribe(Box::new(sub));

        let event = ApCoreEvent::new("test.hello", json!({}));
        emitter.emit(&event).await;
        assert!(received.lock().is_empty());
    }

    #[tokio::test]
    async fn test_emit_wildcard_matches_all() {
        let mut emitter = EventEmitter::new();
        let sub = RecordingSubscriber::new("sub1", "*");
        let received = sub.received.clone();
        emitter.subscribe(Box::new(sub));

        let event = ApCoreEvent::new("anything.at.all", json!({}));
        emitter.emit(&event).await;
        assert_eq!(received.lock().len(), 1);
    }

    #[tokio::test]
    async fn test_unsubscribe_by_id() {
        let mut emitter = EventEmitter::new();
        let sub = RecordingSubscriber::new("sub1", "*");
        emitter.subscribe(Box::new(sub));
        assert!(emitter.unsubscribe_by_id("sub1"));
        assert!(!emitter.unsubscribe_by_id("sub1"));
    }

    #[tokio::test]
    async fn test_unsubscribe_removes_subscriber() {
        let mut emitter = EventEmitter::new();
        let sub = RecordingSubscriber::new("sub1", "*");
        let received = sub.received.clone();
        emitter.subscribe(Box::new(sub.clone()));
        emitter.unsubscribe(&sub);

        let event = ApCoreEvent::new("test", json!({}));
        emitter.emit(&event).await;
        assert!(received.lock().is_empty());
    }

    #[tokio::test]
    async fn test_emit_filtered() {
        let mut emitter = EventEmitter::new();
        let sub = RecordingSubscriber::new("sub1", "test.*");
        let received = sub.received.clone();
        emitter.subscribe(Box::new(sub));

        let event = ApCoreEvent::new("test.hello", json!({}));
        emitter.emit_filtered(&event, "test.*").await.unwrap();
        assert_eq!(received.lock().len(), 1);

        emitter.emit_filtered(&event, "other.*").await.unwrap();
        assert_eq!(received.lock().len(), 1);
    }

    #[test]
    fn test_flush_succeeds() {
        let emitter = EventEmitter::new();
        emitter.flush(1000).unwrap();
    }

    #[test]
    fn test_matches_pattern_wildcard() {
        assert!(EventEmitter::matches_pattern("*", "anything"));
    }

    #[test]
    fn test_matches_pattern_exact() {
        assert!(EventEmitter::matches_pattern("test.event", "test.event"));
        assert!(!EventEmitter::matches_pattern("test.event", "test.other"));
    }

    #[test]
    fn test_matches_pattern_prefix_wildcard() {
        assert!(EventEmitter::matches_pattern("test.*", "test.hello"));
        assert!(EventEmitter::matches_pattern("test.*", "test."));
        assert!(!EventEmitter::matches_pattern("test.*", "other.hello"));
    }

    #[test]
    fn test_matches_pattern_suffix_wildcard() {
        assert!(EventEmitter::matches_pattern("*.event", "test.event"));
        assert!(!EventEmitter::matches_pattern("*.event", "test.other"));
    }

    #[test]
    fn test_matches_pattern_middle_wildcard() {
        assert!(EventEmitter::matches_pattern("a.*.z", "a.b.z"));
        assert!(EventEmitter::matches_pattern("a.*.z", "a.anything.z"));
        assert!(!EventEmitter::matches_pattern("a.*.z", "a.b.c"));
    }

    #[tokio::test]
    async fn test_emit_error_isolation() {
        #[derive(Debug)]
        struct FailingSub;

        #[async_trait]
        impl EventSubscriber for FailingSub {
            fn subscriber_id(&self) -> &'static str {
                "fail"
            }
            fn event_pattern(&self) -> &'static str {
                "*"
            }
            async fn on_event(&self, _event: &ApCoreEvent) -> Result<(), ModuleError> {
                Err(ModuleError::new(
                    crate::errors::ErrorCode::GeneralInternalError,
                    "boom",
                ))
            }
        }

        let mut emitter = EventEmitter::new();
        emitter.subscribe(Box::new(FailingSub));
        let good_sub = RecordingSubscriber::new("good", "*");
        let received = good_sub.received.clone();
        emitter.subscribe(Box::new(good_sub));

        let event = ApCoreEvent::new("test", json!({}));
        emitter.emit(&event).await;
        assert_eq!(received.lock().len(), 1);
    }
}