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
19pub trait EventCapability: 'static {
21 type Event: Clone + 'static;
23 const ID: &'static str;
25 const DESCRIPTOR_VERSION: &'static str;
27}
28
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum EventAdmission {
32 Accepted,
34 Unavailable,
36 Exhausted,
38}
39
40pub type EventPublishStatus = EventAdmission;
42
43#[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 pub fn subscriber_instance(&self) -> &str {
60 &self.subscriber_instance
61 }
62
63 pub fn provider_instance(&self) -> &str {
65 self.subscriber_instance()
66 }
67
68 pub const fn admission(&self) -> EventAdmission {
70 self.admission
71 }
72
73 pub const fn status(&self) -> EventPublishStatus {
75 self.admission
76 }
77}
78
79pub trait NativeEventEndpoint: fmt::Debug {
81 fn capability_id(&self) -> &'static str;
83 fn descriptor_version(&self) -> &'static str;
85 fn operations(&self) -> &'static [&'static str];
87 fn owns_event_admission(&self) -> bool {
93 false
94 }
95 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#[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 cancel(&self) {
233 self.cancellation.borrow().cancel();
234 }
235
236 pub(crate) fn install(&self, endpoint: Rc<dyn NativeEventEndpoint>, generation: u64) {
237 self.generation.set(generation);
238 self.cancellation.replace(CancellationToken::new());
239 self.endpoint.replace(Some(endpoint));
240 }
241
242 pub(crate) fn is_current(&self, generation: u64) -> bool {
243 self.generation.get() == generation && self.endpoint.borrow().is_some()
244 }
245
246 pub(crate) fn register_queue(&self, queue: &Rc<NativeEventQueue>) {
247 self.queues.borrow_mut().push(Rc::downgrade(queue));
248 }
249
250 fn reset_queues(&self) {
251 self.queues.borrow_mut().retain(|queue| {
252 let Some(queue) = queue.upgrade() else {
253 return false;
254 };
255 queue.abort();
256 true
257 });
258 }
259}
260
261#[derive(Clone, Debug)]
262pub(crate) struct NativeEventEndpointBinding {
263 pub(super) requirement_id: String,
264 pub(crate) plugin_instance: String,
265 pub(crate) state: Rc<NativeEventEndpointState>,
266 pub(crate) queue: Rc<NativeEventQueue>,
267}
268
269#[derive(Clone, Debug)]
271pub struct PluginEventDependencyHandle {
272 pub(crate) binding: NativeEventEndpointBinding,
273 pub(crate) caller_instance: String,
274 pub(crate) runtime: Rc<RefCell<std::rc::Weak<NativeAppRuntime>>>,
275}
276
277impl PluginEventDependencyHandle {
278 pub fn capability_id(&self) -> &'static str {
280 self.binding.state.capability_id
281 }
282
283 pub fn descriptor_version(&self) -> &'static str {
285 self.binding.state.descriptor_version
286 }
287
288 pub fn operations(&self) -> &'static [&'static str] {
290 self.binding.state.operations
291 }
292
293 pub fn typed<C: EventCapability>(&self) -> Result<NativeEventHandle<C>, RuntimeFailure> {
295 if self.capability_id() != C::ID || self.descriptor_version() != C::DESCRIPTOR_VERSION {
296 return Err(RuntimeFailure::ProtocolViolation { capability: C::ID });
297 }
298 let runtime = self
299 .runtime
300 .borrow()
301 .upgrade()
302 .ok_or(RuntimeFailure::AdmissionClosed)?;
303 Ok(NativeEventHandle::from_endpoints(
304 std::slice::from_ref(&self.binding),
305 runtime,
306 &self.caller_instance,
307 true,
308 ))
309 }
310}
311
312#[derive(Debug)]
314pub struct NativeEventHandle<C: EventCapability> {
315 endpoints: Vec<NativeEventEndpointBinding>,
316 runtime: Rc<NativeAppRuntime>,
317 caller_instance: String,
318 allow_before_ready: bool,
319 capability: PhantomData<fn() -> C>,
320}
321
322impl<C: EventCapability> NativeEventHandle<C> {
323 pub(crate) fn from_endpoints(
324 endpoints: &[NativeEventEndpointBinding],
325 runtime: Rc<NativeAppRuntime>,
326 caller_instance: &str,
327 allow_before_ready: bool,
328 ) -> Self {
329 Self {
330 endpoints: endpoints.to_vec(),
331 runtime,
332 caller_instance: caller_instance.to_owned(),
333 allow_before_ready,
334 capability: PhantomData,
335 }
336 }
337
338 pub fn binding_count(&self) -> usize {
340 self.endpoints.len()
341 }
342
343 pub async fn publish(&self, operation: &str, event: C::Event) -> Vec<EventPublishResult> {
349 self.publish_with_context(operation, self.next_context(), event)
350 .await
351 }
352
353 pub async fn publish_with_context(
355 &self,
356 operation: &str,
357 context: InvocationContext,
358 event: C::Event,
359 ) -> Vec<EventPublishResult> {
360 let context = context
361 .for_caller(&self.caller_instance)
362 .for_target(C::ID, operation);
363 futures::future::join_all(self.endpoints.iter().map(|endpoint| {
364 self.publish_to_endpoint(endpoint, operation, context.clone(), event.clone())
365 }))
366 .await
367 }
368
369 async fn publish_to_endpoint(
370 &self,
371 endpoint: &NativeEventEndpointBinding,
372 operation: &str,
373 context: InvocationContext,
374 event: C::Event,
375 ) -> EventPublishResult {
376 let operation_name = diagnostic_operation(endpoint.state.operations, operation);
377 let was_closed = self.runtime.shutdown_started.get()
378 || (!self.allow_before_ready && self.runtime.admission.is_closed());
379 let result = self
380 .publish_to_endpoint_inner(endpoint, operation, context.clone(), event)
381 .await;
382 let outcome = match result.admission() {
383 EventAdmission::Accepted => DiagnosticAdmission::Accepted,
384 EventAdmission::Unavailable if was_closed => DiagnosticAdmission::Closed,
385 EventAdmission::Unavailable => DiagnosticAdmission::Unavailable,
386 EventAdmission::Exhausted => DiagnosticAdmission::Exhausted,
387 };
388 self.runtime.diagnostics.emit(
389 DiagnosticSource::Admission,
390 (self.runtime.driver.now)(),
391 |_| DiagnosticEvent::EventAdmission {
392 requirement_id: Some(endpoint.requirement_id.clone()),
393 request_id: context.request_id(),
394 publisher_instance: self.caller_instance.clone(),
395 subscriber_instance: endpoint.plugin_instance.clone(),
396 capability: C::ID,
397 operation: operation_name,
398 outcome,
399 },
400 );
401 result
402 }
403
404 #[allow(
405 clippy::too_many_lines,
406 reason = "event admission keeps legacy commit acknowledgement and v2 settlement explicit"
407 )]
408 async fn publish_to_endpoint_inner(
409 &self,
410 endpoint: &NativeEventEndpointBinding,
411 operation: &str,
412 context: InvocationContext,
413 event: C::Event,
414 ) -> EventPublishResult {
415 let subscriber = endpoint.plugin_instance.clone();
416 let unavailable =
417 || EventPublishResult::new(subscriber.clone(), EventAdmission::Unavailable);
418 if self.runtime.shutdown_started.get()
419 || (!self.allow_before_ready && self.runtime.admission.is_closed())
420 {
421 return unavailable();
422 }
423 let Some(snapshot) = endpoint.state.snapshot() else {
424 return unavailable();
425 };
426 if !endpoint.state.operations.contains(&operation) {
427 return unavailable();
428 }
429 let queue = &endpoint.queue;
430 if !endpoint.state.is_current(snapshot.generation)
431 || ensure_context_active(&self.runtime.driver, &context).is_err()
432 {
433 return unavailable();
434 }
435 if snapshot.endpoint.owns_event_admission() {
436 let result = if self
441 .runtime
442 .plan
443 .plugin_instance(&endpoint.plugin_instance)
444 .is_some_and(|instance| instance.authoring_version() == 2)
445 {
446 let endpoint_impl = snapshot.endpoint.clone();
447 let operation_name = operation.to_owned();
448 super::settlement::operation(
449 &self.runtime,
450 &endpoint.plugin_instance,
451 &context,
452 snapshot.cancellation,
453 C::ID,
454 move |execution_context| {
455 endpoint_impl.publish(&operation_name, Box::new(event), execution_context)
456 },
457 )
458 .await
459 .and_then(|result| result)
460 } else {
461 snapshot
462 .endpoint
463 .publish(operation, Box::new(event), context.clone())
464 .await
465 };
466 return match result {
467 Ok(()) => EventPublishResult::new(subscriber, EventAdmission::Accepted),
468 Err(error) => {
469 let error = schedule_plugin_supervision_after_failure(
470 &self.runtime,
471 &endpoint.plugin_instance,
472 error,
473 );
474 self.runtime.diagnostics.emit_runtime_failure(
475 (self.runtime.driver.now)(),
476 Some(&endpoint.plugin_instance),
477 &error,
478 );
479 let admission = if matches!(error, RuntimeFailure::ResourceExhausted { .. }) {
480 EventAdmission::Exhausted
481 } else {
482 EventAdmission::Unavailable
483 };
484 EventPublishResult::new(subscriber, admission)
485 }
486 };
487 }
488 let queued = QueuedEvent {
489 operation: operation.to_owned(),
490 event: Box::new(event),
491 context,
492 snapshot,
493 };
494 let Some(should_start) = queue.try_enqueue(queued) else {
495 return EventPublishResult::new(subscriber, EventAdmission::Exhausted);
496 };
497 if should_start {
498 let Some(tasks) = self
499 .runtime
500 .plugins
501 .get(&endpoint.plugin_instance)
502 .and_then(|plugin| plugin.generation_parts().map(|(_, tasks, _)| tasks))
503 else {
504 queue.abort();
505 return unavailable();
506 };
507 let drain = drain_event_queue(
508 queue.clone(),
509 self.runtime.clone(),
510 endpoint.plugin_instance.clone(),
511 C::ID,
512 );
513 if tasks.spawn_local(Box::pin(drain)).is_err() {
514 queue.abort();
515 return unavailable();
516 }
517 }
518 EventPublishResult::new(subscriber, EventAdmission::Accepted)
519 }
520
521 fn next_context(&self) -> InvocationContext {
522 InvocationContext::new(self.next_request_id(), None, CancellationToken::new())
523 .with_caller_instance(self.caller_instance.clone())
524 }
525
526 fn next_request_id(&self) -> super::RequestId {
527 let request_id = self.runtime.request_ids.get();
528 self.runtime.request_ids.set(request_id.saturating_add(1));
529 request_id
530 }
531}
532
533async fn drain_event_queue(
534 queue: Rc<NativeEventQueue>,
535 runtime: Rc<NativeAppRuntime>,
536 plugin_instance: String,
537 capability: &'static str,
538) {
539 while let Some(queued) = queue.pop() {
540 let endpoint = queued.snapshot.endpoint.clone();
541 let operation = queued.operation;
542 let event = queued.event;
543 let result = AssertUnwindSafe(super::settlement::operation(
544 &runtime,
545 &plugin_instance,
546 &queued.context,
547 queued.snapshot.cancellation,
548 capability,
549 move |execution_context| endpoint.publish(&operation, event, execution_context),
550 ))
551 .catch_unwind()
552 .await;
553 match result {
554 Ok(Ok(Ok(()))) => {}
555 Ok(Ok(Err(error)) | Err(error)) => {
556 runtime.diagnostics.emit_runtime_failure(
557 (runtime.driver.now)(),
558 Some(&plugin_instance),
559 &error,
560 );
561 let _ =
562 schedule_plugin_supervision_after_failure(&runtime, &plugin_instance, error);
563 }
564 Err(_) => {
565 let error = RuntimeFailure::PluginFailure {
566 detail: format!("native Event subscriber `{plugin_instance}` panicked"),
567 };
568 runtime.diagnostics.emit_runtime_failure(
569 (runtime.driver.now)(),
570 Some(&plugin_instance),
571 &error,
572 );
573 let _ =
574 schedule_plugin_supervision_after_failure(&runtime, &plugin_instance, error);
575 }
576 }
577 queue.complete();
578 }
579}