Skip to main content

lenso_kernel/
event.rs

1use std::{
2    any::Any,
3    cell::{Cell, RefCell},
4    collections::VecDeque,
5    fmt,
6    marker::PhantomData,
7    panic::AssertUnwindSafe,
8    rc::{Rc, Weak},
9};
10
11use futures::{FutureExt, future::LocalBoxFuture};
12
13use super::{
14    CancellationToken, DiagnosticAdmission, DiagnosticEvent, DiagnosticSource, EventAdmissionPlan,
15    InvocationContext, NativeAppRuntime, RuntimeFailure, diagnostics::diagnostic_operation,
16    ensure_context_active, schedule_plugin_supervision_after_failure,
17};
18
19/// Static identity and Rust value types generated for one ephemeral Event Capability.
20pub trait EventCapability: 'static {
21    /// Typed value published to each explicitly bound subscriber.
22    type Event: Clone + 'static;
23    /// Stable Capability series identity.
24    const ID: &'static str;
25    /// Exact generated Descriptor version.
26    const DESCRIPTOR_VERSION: &'static str;
27}
28
29/// The admission result for one publisher-to-subscriber binding.
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum EventAdmission {
32    /// The event entered that subscriber's volatile queue.
33    Accepted,
34    /// The subscriber binding is currently unavailable.
35    Unavailable,
36    /// The subscriber's bounded admission is full.
37    Exhausted,
38}
39
40/// Alias emphasizing the result's publication context.
41pub type EventPublishStatus = EventAdmission;
42
43/// One deterministic result for one explicit subscriber binding.
44#[derive(Clone, Debug, Eq, PartialEq)]
45pub struct EventPublishResult {
46    subscriber_instance: String,
47    admission: EventAdmission,
48}
49
50impl EventPublishResult {
51    pub(crate) fn new(subscriber_instance: String, admission: EventAdmission) -> Self {
52        Self {
53            subscriber_instance,
54            admission,
55        }
56    }
57
58    /// Returns the App-local subscriber Instance key.
59    pub fn subscriber_instance(&self) -> &str {
60        &self.subscriber_instance
61    }
62
63    /// Returns the provider Instance key used by the explicit binding.
64    pub fn provider_instance(&self) -> &str {
65        self.subscriber_instance()
66    }
67
68    /// Returns the independent admission result for this binding.
69    pub const fn admission(&self) -> EventAdmission {
70        self.admission
71    }
72
73    /// Returns the status using publication-oriented terminology.
74    pub const fn status(&self) -> EventPublishStatus {
75        self.admission
76    }
77}
78
79/// Adapter-facing endpoint for one or more ephemeral Event Operations.
80pub trait NativeEventEndpoint: fmt::Debug {
81    /// Stable Capability series identity.
82    fn capability_id(&self) -> &'static str;
83    /// Exact Descriptor version implemented by this endpoint.
84    fn descriptor_version(&self) -> &'static str;
85    /// Exact stable Event Operation names implemented by this endpoint.
86    fn operations(&self) -> &'static [&'static str];
87    /// Returns whether the Adapter owns the subscriber's admission queue.
88    ///
89    /// Native endpoints use the Kernel mailbox by default. An out-of-process
90    /// Adapter may return `true` when its transport has already admitted the
91    /// value into the subscriber's own bounded queue before this call returns.
92    fn owns_event_admission(&self) -> bool {
93        false
94    }
95    /// Publishes one value after the endpoint has admitted it.
96    ///
97    /// Implementations must return once the value is accepted into their own
98    /// bounded volatile queue. Subscriber handler failures after that point
99    /// are deliberately outside the publisher's response path.
100    fn publish(
101        &self,
102        operation: &str,
103        event: Box<dyn Any>,
104        context: InvocationContext,
105    ) -> LocalBoxFuture<'static, Result<(), RuntimeFailure>>;
106}
107
108struct QueuedEvent {
109    operation: String,
110    event: Box<dyn Any>,
111    context: InvocationContext,
112    snapshot: NativeEventEndpointSnapshot,
113}
114
115impl fmt::Debug for QueuedEvent {
116    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117        formatter
118            .debug_struct("QueuedEvent")
119            .field("operation", &self.operation)
120            .field("request_id", &self.context.request_id())
121            .field("generation", &self.snapshot.generation)
122            .finish_non_exhaustive()
123    }
124}
125
126#[derive(Debug, Default)]
127struct NativeEventQueueState {
128    pending: VecDeque<QueuedEvent>,
129    admitted: usize,
130    draining: bool,
131}
132
133/// One bounded FIFO mailbox owned by one publisher-to-subscriber binding.
134#[derive(Debug)]
135pub(crate) struct NativeEventQueue {
136    capacity: usize,
137    state: RefCell<NativeEventQueueState>,
138}
139
140impl NativeEventQueue {
141    pub(crate) fn new(admission: EventAdmissionPlan) -> Rc<Self> {
142        Self {
143            capacity: admission.capacity(),
144            state: RefCell::new(NativeEventQueueState::default()),
145        }
146        .into()
147    }
148
149    fn try_enqueue(&self, event: QueuedEvent) -> Option<bool> {
150        let mut state = self.state.borrow_mut();
151        if state.admitted >= self.capacity {
152            return None;
153        }
154        state.admitted += 1;
155        state.pending.push_back(event);
156        if state.draining {
157            Some(false)
158        } else {
159            state.draining = true;
160            Some(true)
161        }
162    }
163
164    fn pop(&self) -> Option<QueuedEvent> {
165        self.state.borrow_mut().pending.pop_front()
166    }
167
168    fn complete(&self) {
169        let mut state = self.state.borrow_mut();
170        state.admitted = state.admitted.saturating_sub(1);
171        if state.pending.is_empty() {
172            state.draining = false;
173        }
174    }
175
176    fn abort(&self) {
177        let mut state = self.state.borrow_mut();
178        state.pending.clear();
179        state.admitted = 0;
180        state.draining = false;
181    }
182}
183
184#[derive(Clone, Debug)]
185pub(crate) struct NativeEventEndpointSnapshot {
186    pub(crate) endpoint: Rc<dyn NativeEventEndpoint>,
187    pub(crate) generation: u64,
188    pub(crate) cancellation: CancellationToken,
189}
190
191#[derive(Debug)]
192pub(crate) struct NativeEventEndpointState {
193    pub(crate) capability_id: &'static str,
194    pub(crate) descriptor_version: &'static str,
195    pub(crate) operations: &'static [&'static str],
196    endpoint: RefCell<Option<Rc<dyn NativeEventEndpoint>>>,
197    generation: Cell<u64>,
198    cancellation: RefCell<CancellationToken>,
199    queues: RefCell<Vec<Weak<NativeEventQueue>>>,
200}
201
202impl NativeEventEndpointState {
203    pub(crate) fn new(endpoint: Rc<dyn NativeEventEndpoint>, generation: u64) -> Self {
204        Self {
205            capability_id: endpoint.capability_id(),
206            descriptor_version: endpoint.descriptor_version(),
207            operations: endpoint.operations(),
208            endpoint: RefCell::new(Some(endpoint)),
209            generation: Cell::new(generation),
210            cancellation: RefCell::new(CancellationToken::new()),
211            queues: RefCell::new(Vec::new()),
212        }
213    }
214
215    pub(crate) fn snapshot(&self) -> Option<NativeEventEndpointSnapshot> {
216        self.endpoint
217            .borrow()
218            .clone()
219            .map(|endpoint| NativeEventEndpointSnapshot {
220                endpoint,
221                generation: self.generation.get(),
222                cancellation: self.cancellation.borrow().clone(),
223            })
224    }
225
226    pub(crate) fn mark_unavailable(&self) {
227        self.cancellation.borrow().cancel();
228        self.endpoint.borrow_mut().take();
229        self.reset_queues();
230    }
231
232    pub(crate) fn install(&self, endpoint: Rc<dyn NativeEventEndpoint>, generation: u64) {
233        self.generation.set(generation);
234        self.cancellation.replace(CancellationToken::new());
235        self.endpoint.replace(Some(endpoint));
236    }
237
238    pub(crate) fn is_current(&self, generation: u64) -> bool {
239        self.generation.get() == generation && self.endpoint.borrow().is_some()
240    }
241
242    pub(crate) fn register_queue(&self, queue: &Rc<NativeEventQueue>) {
243        self.queues.borrow_mut().push(Rc::downgrade(queue));
244    }
245
246    fn reset_queues(&self) {
247        self.queues.borrow_mut().retain(|queue| {
248            let Some(queue) = queue.upgrade() else {
249                return false;
250            };
251            queue.abort();
252            true
253        });
254    }
255}
256
257#[derive(Clone, Debug)]
258pub(crate) struct NativeEventEndpointBinding {
259    pub(super) requirement_id: String,
260    pub(crate) plugin_instance: String,
261    pub(crate) state: Rc<NativeEventEndpointState>,
262    pub(crate) queue: Rc<NativeEventQueue>,
263}
264
265/// An opaque Event endpoint passed to Plugin lifecycle code.
266#[derive(Clone, Debug)]
267pub struct PluginEventDependencyHandle {
268    pub(crate) binding: NativeEventEndpointBinding,
269    pub(crate) caller_instance: String,
270    pub(crate) runtime: Rc<RefCell<std::rc::Weak<NativeAppRuntime>>>,
271}
272
273impl PluginEventDependencyHandle {
274    /// Returns the Capability implemented by this handle.
275    pub fn capability_id(&self) -> &'static str {
276        self.binding.state.capability_id
277    }
278
279    /// Returns the exact Descriptor version implemented by this handle.
280    pub fn descriptor_version(&self) -> &'static str {
281        self.binding.state.descriptor_version
282    }
283
284    /// Returns the exact Event Operation table implemented by this handle.
285    pub fn operations(&self) -> &'static [&'static str] {
286        self.binding.state.operations
287    }
288
289    /// Converts this resolved dependency into its generated typed Event handle.
290    pub fn typed<C: EventCapability>(&self) -> Result<NativeEventHandle<C>, RuntimeFailure> {
291        if self.capability_id() != C::ID || self.descriptor_version() != C::DESCRIPTOR_VERSION {
292            return Err(RuntimeFailure::ProtocolViolation { capability: C::ID });
293        }
294        let runtime = self
295            .runtime
296            .borrow()
297            .upgrade()
298            .ok_or(RuntimeFailure::AdmissionClosed)?;
299        Ok(NativeEventHandle::from_endpoints(
300            std::slice::from_ref(&self.binding),
301            runtime,
302            &self.caller_instance,
303            true,
304        ))
305    }
306}
307
308/// Typed, immutable Event endpoints materialized before App boot completes.
309#[derive(Debug)]
310pub struct NativeEventHandle<C: EventCapability> {
311    endpoints: Vec<NativeEventEndpointBinding>,
312    runtime: Rc<NativeAppRuntime>,
313    caller_instance: String,
314    allow_before_ready: bool,
315    capability: PhantomData<fn() -> C>,
316}
317
318impl<C: EventCapability> NativeEventHandle<C> {
319    pub(crate) fn from_endpoints(
320        endpoints: &[NativeEventEndpointBinding],
321        runtime: Rc<NativeAppRuntime>,
322        caller_instance: &str,
323        allow_before_ready: bool,
324    ) -> Self {
325        Self {
326            endpoints: endpoints.to_vec(),
327            runtime,
328            caller_instance: caller_instance.to_owned(),
329            allow_before_ready,
330            capability: PhantomData,
331        }
332    }
333
334    /// Returns the number of explicitly bound subscriber endpoints.
335    pub fn binding_count(&self) -> usize {
336        self.endpoints.len()
337    }
338
339    /// Publishes to every bound subscriber in deterministic order.
340    ///
341    /// An empty binding set succeeds with an empty result. Each result is
342    /// independent: one exhausted or unavailable subscriber does not prevent
343    /// the remaining bindings from being attempted.
344    pub async fn publish(&self, operation: &str, event: C::Event) -> Vec<EventPublishResult> {
345        self.publish_with_context(operation, self.next_context(), event)
346            .await
347    }
348
349    /// Publishes with one propagated Invocation Context.
350    pub async fn publish_with_context(
351        &self,
352        operation: &str,
353        context: InvocationContext,
354        event: C::Event,
355    ) -> Vec<EventPublishResult> {
356        let context = context
357            .for_caller(&self.caller_instance)
358            .for_target(C::ID, operation);
359        futures::future::join_all(self.endpoints.iter().map(|endpoint| {
360            self.publish_to_endpoint(endpoint, operation, context.clone(), event.clone())
361        }))
362        .await
363    }
364
365    async fn publish_to_endpoint(
366        &self,
367        endpoint: &NativeEventEndpointBinding,
368        operation: &str,
369        context: InvocationContext,
370        event: C::Event,
371    ) -> EventPublishResult {
372        let operation_name = diagnostic_operation(endpoint.state.operations, operation);
373        let was_closed = self.runtime.shutdown_started.get()
374            || (!self.allow_before_ready && self.runtime.admission.is_closed());
375        let result = self
376            .publish_to_endpoint_inner(endpoint, operation, context.clone(), event)
377            .await;
378        let outcome = match result.admission() {
379            EventAdmission::Accepted => DiagnosticAdmission::Accepted,
380            EventAdmission::Unavailable if was_closed => DiagnosticAdmission::Closed,
381            EventAdmission::Unavailable => DiagnosticAdmission::Unavailable,
382            EventAdmission::Exhausted => DiagnosticAdmission::Exhausted,
383        };
384        self.runtime.diagnostics.emit(
385            DiagnosticSource::Admission,
386            (self.runtime.driver.now)(),
387            |_| DiagnosticEvent::EventAdmission {
388                requirement_id: Some(endpoint.requirement_id.clone()),
389                request_id: context.request_id(),
390                publisher_instance: self.caller_instance.clone(),
391                subscriber_instance: endpoint.plugin_instance.clone(),
392                capability: C::ID,
393                operation: operation_name,
394                outcome,
395            },
396        );
397        result
398    }
399
400    #[allow(
401        clippy::too_many_lines,
402        reason = "event admission keeps legacy commit acknowledgement and v2 settlement explicit"
403    )]
404    async fn publish_to_endpoint_inner(
405        &self,
406        endpoint: &NativeEventEndpointBinding,
407        operation: &str,
408        context: InvocationContext,
409        event: C::Event,
410    ) -> EventPublishResult {
411        let subscriber = endpoint.plugin_instance.clone();
412        let unavailable =
413            || EventPublishResult::new(subscriber.clone(), EventAdmission::Unavailable);
414        if self.runtime.shutdown_started.get()
415            || (!self.allow_before_ready && self.runtime.admission.is_closed())
416        {
417            return unavailable();
418        }
419        let Some(snapshot) = endpoint.state.snapshot() else {
420            return unavailable();
421        };
422        if !endpoint.state.operations.contains(&operation) {
423            return unavailable();
424        }
425        let queue = &endpoint.queue;
426        if !endpoint.state.is_current(snapshot.generation)
427            || ensure_context_active(&self.runtime.driver, &context).is_err()
428        {
429            return unavailable();
430        }
431        if snapshot.endpoint.owns_event_admission() {
432            // Once an out-of-process Adapter starts admission, wait for its
433            // commit acknowledgement. Racing that acknowledgement against the
434            // caller deadline can report unavailable after the subscriber has
435            // already accepted the Event.
436            let result = if self
437                .runtime
438                .plan
439                .plugin_instance(&endpoint.plugin_instance)
440                .is_some_and(|instance| instance.authoring_version() == 2)
441            {
442                let endpoint_impl = snapshot.endpoint.clone();
443                let operation_name = operation.to_owned();
444                super::settlement::operation(
445                    &self.runtime,
446                    &endpoint.plugin_instance,
447                    &context,
448                    snapshot.cancellation,
449                    C::ID,
450                    move |execution_context| {
451                        endpoint_impl.publish(&operation_name, Box::new(event), execution_context)
452                    },
453                )
454                .await
455                .and_then(|result| result)
456            } else {
457                snapshot
458                    .endpoint
459                    .publish(operation, Box::new(event), context.clone())
460                    .await
461            };
462            return match result {
463                Ok(()) => EventPublishResult::new(subscriber, EventAdmission::Accepted),
464                Err(error) => {
465                    let error = schedule_plugin_supervision_after_failure(
466                        &self.runtime,
467                        &endpoint.plugin_instance,
468                        error,
469                    );
470                    self.runtime.diagnostics.emit_runtime_failure(
471                        (self.runtime.driver.now)(),
472                        Some(&endpoint.plugin_instance),
473                        &error,
474                    );
475                    let admission = if matches!(error, RuntimeFailure::ResourceExhausted { .. }) {
476                        EventAdmission::Exhausted
477                    } else {
478                        EventAdmission::Unavailable
479                    };
480                    EventPublishResult::new(subscriber, admission)
481                }
482            };
483        }
484        let queued = QueuedEvent {
485            operation: operation.to_owned(),
486            event: Box::new(event),
487            context,
488            snapshot,
489        };
490        let Some(should_start) = queue.try_enqueue(queued) else {
491            return EventPublishResult::new(subscriber, EventAdmission::Exhausted);
492        };
493        if should_start {
494            let Some(tasks) = self
495                .runtime
496                .plugins
497                .get(&endpoint.plugin_instance)
498                .and_then(|plugin| plugin.generation_parts().map(|(_, tasks, _)| tasks))
499            else {
500                queue.abort();
501                return unavailable();
502            };
503            let drain = drain_event_queue(
504                queue.clone(),
505                self.runtime.clone(),
506                endpoint.plugin_instance.clone(),
507                C::ID,
508            );
509            if tasks.spawn_local(Box::pin(drain)).is_err() {
510                queue.abort();
511                return unavailable();
512            }
513        }
514        EventPublishResult::new(subscriber, EventAdmission::Accepted)
515    }
516
517    fn next_context(&self) -> InvocationContext {
518        InvocationContext::new(self.next_request_id(), None, CancellationToken::new())
519            .with_caller_instance(self.caller_instance.clone())
520    }
521
522    fn next_request_id(&self) -> super::RequestId {
523        let request_id = self.runtime.request_ids.get();
524        self.runtime.request_ids.set(request_id.saturating_add(1));
525        request_id
526    }
527}
528
529async fn drain_event_queue(
530    queue: Rc<NativeEventQueue>,
531    runtime: Rc<NativeAppRuntime>,
532    plugin_instance: String,
533    capability: &'static str,
534) {
535    while let Some(queued) = queue.pop() {
536        let endpoint = queued.snapshot.endpoint.clone();
537        let operation = queued.operation;
538        let event = queued.event;
539        let result = AssertUnwindSafe(super::settlement::operation(
540            &runtime,
541            &plugin_instance,
542            &queued.context,
543            queued.snapshot.cancellation,
544            capability,
545            move |execution_context| endpoint.publish(&operation, event, execution_context),
546        ))
547        .catch_unwind()
548        .await;
549        match result {
550            Ok(Ok(Ok(()))) => {}
551            Ok(Ok(Err(error)) | Err(error)) => {
552                runtime.diagnostics.emit_runtime_failure(
553                    (runtime.driver.now)(),
554                    Some(&plugin_instance),
555                    &error,
556                );
557                let _ =
558                    schedule_plugin_supervision_after_failure(&runtime, &plugin_instance, error);
559            }
560            Err(_) => {
561                let error = RuntimeFailure::PluginFailure {
562                    detail: format!("native Event subscriber `{plugin_instance}` panicked"),
563                };
564                runtime.diagnostics.emit_runtime_failure(
565                    (runtime.driver.now)(),
566                    Some(&plugin_instance),
567                    &error,
568                );
569                let _ =
570                    schedule_plugin_supervision_after_failure(&runtime, &plugin_instance, error);
571            }
572        }
573        queue.complete();
574    }
575}