frame-core 0.3.0

Component model, lifecycle, process isolation — hosts components as supervised BEAM process trees
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
//! Typed, bounded lifecycle event delivery.

use std::collections::VecDeque;
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, Weak};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::capability::CapabilityDenied;
use crate::component::ComponentId;

/// An externally observable component lifecycle state.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum LifecycleState {
    /// Definition is registered but has not started.
    Registered,
    /// Module loading and child liveness checks are in progress.
    Starting,
    /// Every declared child completed a mailbox round-trip.
    Running,
    /// Ordered child and supervisor drain is in progress.
    Stopping,
    /// All component processes have normal tombstones.
    Stopped,
    /// Start or supervision failed; the associated status carries the reason.
    Failed,
    /// Modules and registration were removed without residue.
    Removed,
}

/// One ordered item on the component lifecycle and security-news stream.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct LifecycleEvent {
    /// Registry-wide monotonic sequence number.
    pub sequence: u64,
    /// Component associated with this news item.
    pub component_id: ComponentId,
    /// Typed transition or capability denial payload.
    pub kind: LifecycleEventKind,
}

/// The typed payload carried by one lifecycle stream item.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum LifecycleEventKind {
    /// One component lifecycle transition.
    Transition {
        /// State before this transition, absent for initial registration.
        from: Option<LifecycleState>,
        /// State after this transition.
        to: LifecycleState,
    },
    /// One consuming act was denied by the fresh capability check.
    CapabilityDenied(CapabilityDenied),
    /// One committed live fragment content update (F-5a R2/R3). The stream
    /// carries the news, never the bytes: the registry's fragment snapshot
    /// stays the authority, and a consumer that misses this event converges
    /// through its next lag-forced resync.
    FragmentContentUpdated {
        /// The updated fragment.
        key: crate::fragment::FragmentKey,
    },
}

/// A bounded subscription that reports every event it had to discard.
pub struct LifecycleSubscription {
    queue: Arc<SubscriberQueue>,
}

impl LifecycleSubscription {
    /// Waits up to `timeout` for the next retained event.
    ///
    /// # Errors
    ///
    /// Returns a typed timeout, closure, or synchronization failure.
    pub fn recv_timeout(&self, timeout: Duration) -> Result<LifecycleEvent, EventReceiveError> {
        let guard = self
            .queue
            .state
            .lock()
            .map_err(|_| EventReceiveError::Poisoned)?;
        let (mut guard, _wait) = self
            .queue
            .ready
            .wait_timeout_while(guard, timeout, |state| {
                state.events.is_empty() && !state.closed
            })
            .map_err(|_| EventReceiveError::Poisoned)?;
        if let Some(event) = guard.events.pop_front() {
            return Ok(event);
        }
        if guard.closed {
            Err(EventReceiveError::Closed)
        } else {
            Err(EventReceiveError::Timeout)
        }
    }

    /// Returns the next retained event without waiting.
    ///
    /// # Errors
    ///
    /// Returns closure, emptiness, or synchronization failures distinctly.
    pub fn try_recv(&self) -> Result<LifecycleEvent, EventTryReceiveError> {
        let mut state = self
            .queue
            .state
            .lock()
            .map_err(|_| EventTryReceiveError::Poisoned)?;
        if let Some(event) = state.events.pop_front() {
            Ok(event)
        } else if state.closed {
            Err(EventTryReceiveError::Closed)
        } else {
            Err(EventTryReceiveError::Empty)
        }
    }

    /// Blocks until the next retained event arrives or the subscription is
    /// closed — the timeout-less sibling of [`Self::recv_timeout`], same
    /// condvar, no timer anywhere (Ruling B's sanctioned blocking shape:
    /// close is the only external wake, delivered by
    /// [`SubscriptionCloseHandle::close`] or this subscription's drop).
    ///
    /// # Errors
    ///
    /// Returns a typed closure or synchronization failure; never a timeout.
    pub fn recv(&self) -> Result<LifecycleEvent, EventReceiveError> {
        let guard = self
            .queue
            .state
            .lock()
            .map_err(|_| EventReceiveError::Poisoned)?;
        let mut guard = self
            .queue
            .ready
            .wait_while(guard, |state| state.events.is_empty() && !state.closed)
            .map_err(|_| EventReceiveError::Poisoned)?;
        if let Some(event) = guard.events.pop_front() {
            return Ok(event);
        }
        Err(EventReceiveError::Closed)
    }

    /// Returns the cumulative number of events dropped from this subscriber.
    #[must_use]
    pub fn lagged_events(&self) -> usize {
        self.queue.lagged.load(Ordering::Acquire)
    }

    /// Returns a handle that closes this subscription from another thread,
    /// waking every blocked receiver (the demand-driven teardown wake — the
    /// F-6a frame-core sanction amendment).
    ///
    /// The handle holds only a weak reference: retaining it never keeps the
    /// subscription's queue alive after the subscription drops.
    #[must_use]
    pub fn close_handle(&self) -> SubscriptionCloseHandle {
        SubscriptionCloseHandle {
            queue: Arc::downgrade(&self.queue),
        }
    }
}

/// Externally-holdable close switch for one [`LifecycleSubscription`].
pub struct SubscriptionCloseHandle {
    queue: Weak<SubscriberQueue>,
}

impl SubscriptionCloseHandle {
    /// Closes the subscription and wakes every blocked receiver. Idempotent;
    /// a no-op once the subscription itself has dropped.
    ///
    /// A poisoned subscriber lock cannot mark the queue closed, but blocked
    /// receivers are still woken and then observe their own typed
    /// [`EventReceiveError::Poisoned`] — the failure is propagated at the
    /// receive surface, never swallowed silently.
    pub fn close(&self) {
        if let Some(queue) = self.queue.upgrade() {
            if let Ok(mut state) = queue.state.lock() {
                state.closed = true;
            }
            queue.ready.notify_all();
        }
    }
}

impl Drop for LifecycleSubscription {
    fn drop(&mut self) {
        if let Ok(mut state) = self.queue.state.lock() {
            state.closed = true;
            self.queue.ready.notify_all();
        }
    }
}

/// Failure while waiting for an event.
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
pub enum EventReceiveError {
    /// No event arrived before the caller's deadline.
    #[error("lifecycle event receive timed out")]
    Timeout,
    /// The subscription was closed.
    #[error("lifecycle event subscription is closed")]
    Closed,
    /// Subscriber synchronization was poisoned by a panic.
    #[error("lifecycle event subscription synchronization is poisoned")]
    Poisoned,
}

/// Failure while polling for an event.
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
pub enum EventTryReceiveError {
    /// No retained event is currently available.
    #[error("lifecycle event subscription is empty")]
    Empty,
    /// The subscription was closed.
    #[error("lifecycle event subscription is closed")]
    Closed,
    /// Subscriber synchronization was poisoned by a panic.
    #[error("lifecycle event subscription synchronization is poisoned")]
    Poisoned,
}

#[derive(Default)]
pub(crate) struct EventHub {
    next_sequence: AtomicU64,
    subscribers: Mutex<Vec<Weak<SubscriberQueue>>>,
    /// Deterministic count of constructed events — the F-5a R6 zero-cost
    /// choke point: with no live subscriber, publication must return before
    /// ANY event is constructed, and this counter proves it stayed zero.
    #[cfg(test)]
    pub(crate) constructed: AtomicUsize,
}

impl EventHub {
    pub(crate) fn subscribe(
        &self,
        capacity: NonZeroUsize,
    ) -> Result<LifecycleSubscription, EventPublishError> {
        let queue = Arc::new(SubscriberQueue {
            capacity: capacity.get(),
            state: Mutex::new(QueueState::default()),
            ready: Condvar::new(),
            lagged: AtomicUsize::new(0),
        });
        self.subscribers
            .lock()
            .map_err(|_| EventPublishError::Poisoned)?
            .push(Arc::downgrade(&queue));
        Ok(LifecycleSubscription { queue })
    }

    pub(crate) fn publish_transition(
        &self,
        component_id: ComponentId,
        from: Option<LifecycleState>,
        to: LifecycleState,
    ) -> Result<(), EventPublishError> {
        self.publish(component_id, LifecycleEventKind::Transition { from, to })
    }

    pub(crate) fn publish_denial(&self, denial: CapabilityDenied) -> Result<(), EventPublishError> {
        self.publish(
            denial.component_id,
            LifecycleEventKind::CapabilityDenied(denial),
        )
    }

    pub(crate) fn publish_fragment_update(
        &self,
        key: crate::fragment::FragmentKey,
    ) -> Result<(), EventPublishError> {
        self.publish(
            key.component_id,
            LifecycleEventKind::FragmentContentUpdated { key },
        )
    }

    fn publish(
        &self,
        component_id: ComponentId,
        kind: LifecycleEventKind,
    ) -> Result<(), EventPublishError> {
        let mut subscribers = self
            .subscribers
            .lock()
            .map_err(|_| EventPublishError::Poisoned)?;
        subscribers.retain(|subscriber| subscriber.strong_count() > 0);
        if subscribers.is_empty() {
            return Ok(());
        }
        #[cfg(test)]
        self.constructed.fetch_add(1, Ordering::AcqRel);
        let event = LifecycleEvent {
            sequence: self.next_sequence.fetch_add(1, Ordering::AcqRel),
            component_id,
            kind,
        };
        for subscriber in subscribers.iter().filter_map(Weak::upgrade) {
            let mut state = subscriber
                .state
                .lock()
                .map_err(|_| EventPublishError::Poisoned)?;
            if state.events.len() == subscriber.capacity {
                let _discarded = state.events.pop_front();
                subscriber.lagged.fetch_add(1, Ordering::AcqRel);
            }
            state.events.push_back(event.clone());
            subscriber.ready.notify_one();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
pub(crate) enum EventPublishError {
    #[error("lifecycle event stream synchronization is poisoned")]
    Poisoned,
}

struct SubscriberQueue {
    capacity: usize,
    state: Mutex<QueueState>,
    ready: Condvar,
    lagged: AtomicUsize,
}

#[derive(Default)]
struct QueueState {
    events: VecDeque<LifecycleEvent>,
    closed: bool,
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]

    use std::num::NonZeroUsize;
    use std::sync::mpsc;
    use std::thread;
    use std::time::Duration;

    use super::{EventHub, EventReceiveError, LifecycleState};
    use crate::component::ComponentId;

    /// Generous wall for the TEST harness only (the code under test carries
    /// no timeout — that is the point).
    const HARNESS_WALL: Duration = Duration::from_secs(10);

    fn capacity(value: usize) -> NonZeroUsize {
        NonZeroUsize::new(value).unwrap_or(NonZeroUsize::MIN)
    }

    #[test]
    fn blocked_recv_wakes_promptly_on_external_close() {
        let hub = EventHub::default();
        let subscription = hub
            .subscribe(capacity(4))
            .unwrap_or_else(|_| unreachable!("subscribing to a fresh hub cannot be poisoned"));
        let close = subscription.close_handle();
        let (done, observed) = mpsc::channel();
        let (entering, entered) = mpsc::channel();
        let worker = thread::spawn(move || {
            entering.send(()).ok();
            let outcome = subscription.recv();
            done.send(outcome).ok();
        });
        entered
            .recv_timeout(HARNESS_WALL)
            .unwrap_or_else(|_| panic!("receiver thread never started"));
        // Settle so the worker is INSIDE the condvar wait before close fires;
        // without this the close-before-block path returns via the wait
        // predicate alone and the notify wake is never exercised.
        thread::sleep(Duration::from_millis(100));
        close.close();
        let outcome = observed
            .recv_timeout(HARNESS_WALL)
            .unwrap_or_else(|_| panic!("blocked recv() never woke on external close"));
        assert!(
            matches!(outcome, Err(EventReceiveError::Closed)),
            "external close must surface the typed Closed error, got: {outcome:?}"
        );
        worker
            .join()
            .unwrap_or_else(|_| panic!("receiver thread panicked"));
    }

    #[test]
    fn no_subscriber_churn_constructs_zero_events() {
        use std::sync::atomic::Ordering;
        let hub = EventHub::default();
        let id = ComponentId::derive("frame.test", "zero-cost");
        for _ in 0..64 {
            hub.publish_transition(id, None, LifecycleState::Registered)
                .unwrap_or_else(|_| unreachable!("publish with no subscribers cannot be poisoned"));
        }
        // The F-5a R6 zero-cost choke point: with no live subscriber,
        // publication returns before ANY event is constructed — the
        // deterministic counter at the construction site stays zero across
        // churn.
        assert_eq!(
            hub.constructed.load(Ordering::Acquire),
            0,
            "zero live subscribers must cost zero event constructions"
        );
        // Companion isolation: the counter genuinely counts — the same
        // publish with one live subscriber constructs exactly one event.
        let subscription = hub
            .subscribe(capacity(4))
            .unwrap_or_else(|_| unreachable!("subscribing to a fresh hub cannot be poisoned"));
        hub.publish_transition(id, None, LifecycleState::Registered)
            .unwrap_or_else(|_| unreachable!("publish to a live subscriber cannot be poisoned"));
        assert_eq!(hub.constructed.load(Ordering::Acquire), 1);
        drop(subscription);
    }

    #[test]
    fn recv_delivers_a_published_event_without_any_close() {
        let hub = EventHub::default();
        let subscription = hub
            .subscribe(capacity(4))
            .unwrap_or_else(|_| unreachable!("subscribing to a fresh hub cannot be poisoned"));
        let id = ComponentId::derive("frame.test", "event-close");
        hub.publish_transition(id, None, LifecycleState::Registered)
            .unwrap_or_else(|_| unreachable!("publish to a live subscriber cannot be poisoned"));
        let event = subscription
            .recv()
            .unwrap_or_else(|error| panic!("recv with a queued event must succeed: {error}"));
        assert_eq!(event.component_id, id);
    }

    #[test]
    fn close_is_idempotent_and_still_typed_after_drop() {
        let hub = EventHub::default();
        let subscription = hub
            .subscribe(capacity(4))
            .unwrap_or_else(|_| unreachable!("subscribing to a fresh hub cannot be poisoned"));
        let close = subscription.close_handle();
        close.close();
        close.close();
        assert!(matches!(
            subscription.recv(),
            Err(EventReceiveError::Closed)
        ));
        drop(subscription);
        close.close();
    }

    #[test]
    fn close_handle_does_not_keep_the_queue_alive() {
        let hub = EventHub::default();
        let subscription = hub
            .subscribe(capacity(1))
            .unwrap_or_else(|_| unreachable!("subscribing to a fresh hub cannot be poisoned"));
        let close = subscription.close_handle();
        drop(subscription);
        // Publication after the subscription dropped must construct no event
        // for it; the weak handle upgrading to nothing proves the queue died.
        let id = ComponentId::derive("frame.test", "event-close-weak");
        hub.publish_transition(id, None, LifecycleState::Registered)
            .unwrap_or_else(|_| unreachable!("publish with no live subscriber is a no-op"));
        assert!(close.queue.upgrade().is_none());
    }
}