torvyn_types/traits.rs
1//! Shared traits for the Torvyn runtime.
2//!
3//! The primary trait here is [`EventSink`], the hot-path interface for
4//! recording observability events. All methods must be non-blocking and
5//! allocation-free on the hot path.
6
7use std::sync::Arc;
8
9use crate::{
10 enums::{CopyReason, ObservabilityLevel},
11 error::ProcessErrorKind,
12 ComponentId, FlowId, ResourceId, StreamId, TraceContext,
13};
14
15/// The hot-path trait for recording observability events.
16///
17/// Implemented by the observability collector (`torvyn-observability`) and
18/// provided to the reactor, resource manager, and host lifecycle manager.
19///
20/// Per Doc 05, Section 9.1: all methods must be non-blocking and
21/// allocation-free on the hot path.
22///
23/// Use [`NoopEventSink`] for testing or when observability is disabled.
24///
25/// # Examples
26/// ```
27/// use torvyn_types::{NoopEventSink, EventSink, ObservabilityLevel};
28///
29/// let sink = NoopEventSink;
30/// assert_eq!(sink.level(), ObservabilityLevel::Off);
31/// ```
32pub trait EventSink: Send + Sync + 'static {
33 /// Record a component invocation completion.
34 ///
35 /// Called by the reactor after every component invocation.
36 ///
37 /// # HOT PATH — must be non-blocking, allocation-free.
38 fn record_invocation(
39 &self,
40 flow_id: FlowId,
41 component_id: ComponentId,
42 start_ns: u64,
43 end_ns: u64,
44 status: InvocationStatus,
45 );
46
47 /// Record a stream element transfer between components.
48 ///
49 /// Called by the reactor when an element moves through a stream queue.
50 ///
51 /// # HOT PATH — must be non-blocking, allocation-free.
52 fn record_element_transfer(
53 &self,
54 flow_id: FlowId,
55 stream_id: StreamId,
56 element_sequence: u64,
57 queue_depth_after: u32,
58 );
59
60 /// Record a backpressure state change.
61 ///
62 /// Called by the reactor when backpressure activates or deactivates.
63 ///
64 /// # WARM PATH — called per backpressure event.
65 fn record_backpressure(
66 &self,
67 flow_id: FlowId,
68 stream_id: StreamId,
69 activated: bool,
70 queue_depth: u32,
71 timestamp_ns: u64,
72 );
73
74 /// Record a resource copy operation.
75 ///
76 /// Called by the resource manager when data is copied across a boundary.
77 ///
78 /// # HOT PATH — must be non-blocking, allocation-free.
79 fn record_copy(
80 &self,
81 flow_id: FlowId,
82 resource_id: ResourceId,
83 from_component: ComponentId,
84 to_component: ComponentId,
85 copy_bytes: u64,
86 reason: CopyReason,
87 );
88
89 /// Record an element's end-to-end latency through the flow.
90 ///
91 /// Called by the reactor when a sink consumes an element, measured from the
92 /// element's pipeline-entry timestamp (set at the source) to its
93 /// consumption at the sink. Unlike per-component processing time, this is
94 /// the full journey — queueing plus every stage. The default is a no-op.
95 ///
96 /// # HOT PATH — called once per element delivered to a sink.
97 fn record_flow_latency(&self, flow_id: FlowId, latency_ns: u64) {
98 let _ = (flow_id, latency_ns);
99 }
100
101 /// Record one component invocation as a per-element span.
102 ///
103 /// Called by the reactor immediately after [`record_invocation`], with
104 /// the sequence number of the element the invocation handled.
105 ///
106 /// This is the per-element counterpart to `record_invocation`: where that
107 /// call folds the invocation into aggregate counters and histograms, this
108 /// one retains the individual event so a trace can reconstruct one
109 /// element's path through the pipeline. Sinks are expected to drop these
110 /// below [`ObservabilityLevel::Diagnostic`] — the level check is the
111 /// sink's responsibility, and at Production level this must cost no more
112 /// than the atomic load it takes to decide to do nothing.
113 ///
114 /// `start_ns` and `end_ns` are nanoseconds since the Unix epoch, so a
115 /// span is directly exportable without a second clock reading.
116 ///
117 /// The default is a no-op: sinks that do not retain per-element detail
118 /// (such as [`NoopEventSink`]) need not implement it.
119 ///
120 /// # HOT PATH — called once per invocation; must be non-blocking.
121 ///
122 /// [`record_invocation`]: EventSink::record_invocation
123 fn record_element_span(
124 &self,
125 flow_id: FlowId,
126 component_id: ComponentId,
127 element_sequence: u64,
128 start_ns: u64,
129 end_ns: u64,
130 status: InvocationStatus,
131 ) {
132 let _ = (
133 flow_id,
134 component_id,
135 element_sequence,
136 start_ns,
137 end_ns,
138 status,
139 );
140 }
141
142 /// The trace context assigned to a flow, if this sink is tracing it.
143 ///
144 /// Called once per flow, after [`on_flow_start`], so the host can
145 /// propagate the flow's W3C trace and span identifiers into each
146 /// component's store — which is what lets a guest calling
147 /// `flow-context.trace-id()` correlate its own work with the host's
148 /// trace.
149 ///
150 /// Returns `None` when the sink is not tracing (the default), when the
151 /// flow is unknown, or when the flow was not selected by head sampling.
152 ///
153 /// # COLD PATH — called once per flow.
154 ///
155 /// [`on_flow_start`]: EventSink::on_flow_start
156 fn flow_trace_context(&self, flow_id: FlowId) -> Option<TraceContext> {
157 let _ = flow_id;
158 None
159 }
160
161 /// Returns the current observability level.
162 ///
163 /// Hot-path callers can skip expensive recording at lower levels.
164 ///
165 /// # HOT PATH — checked per element to skip recording.
166 fn level(&self) -> ObservabilityLevel;
167
168 /// Pre-register a flow's per-flow metric state before its driver starts.
169 ///
170 /// Called by the reactor exactly once per flow — after the flow id is
171 /// assigned and before the flow driver is spawned — so that no later
172 /// `record_*` call can observe a flow whose metrics have not yet been
173 /// allocated. `component_ids` and `stream_ids` enumerate the flow's
174 /// stages and stream connections in the same order the reactor records
175 /// them, letting the sink allocate matching metric slots up front.
176 ///
177 /// The default is a no-op: sinks that hold no per-flow state (such as
178 /// [`NoopEventSink`]) need not implement it.
179 ///
180 /// # COLD PATH — called once per flow, off the element hot path.
181 fn on_flow_start(
182 &self,
183 flow_id: FlowId,
184 component_ids: &[ComponentId],
185 stream_ids: &[StreamId],
186 ) {
187 let _ = (flow_id, component_ids, stream_ids);
188 }
189}
190
191/// Forwarding implementation so any `Arc`-shared sink satisfies the reactor's
192/// `E: EventSink + Clone + 'static` bound without the sink itself being
193/// `Clone`: the `Arc` provides the cheap clone (one shared sink, reference
194/// counted), and every call forwards to the single instance behind it.
195///
196/// This lets the host install a shared [`ObservabilityCollector`] (which owns
197/// `Arc`-backed registries and a background event recorder, and so is not
198/// `Clone`) by wrapping it in an `Arc`.
199///
200/// [`ObservabilityCollector`]: https://docs.rs/torvyn-observability
201impl<E: EventSink> EventSink for Arc<E> {
202 #[inline]
203 fn record_invocation(
204 &self,
205 flow_id: FlowId,
206 component_id: ComponentId,
207 start_ns: u64,
208 end_ns: u64,
209 status: InvocationStatus,
210 ) {
211 (**self).record_invocation(flow_id, component_id, start_ns, end_ns, status);
212 }
213
214 #[inline]
215 fn record_element_transfer(
216 &self,
217 flow_id: FlowId,
218 stream_id: StreamId,
219 element_sequence: u64,
220 queue_depth_after: u32,
221 ) {
222 (**self).record_element_transfer(flow_id, stream_id, element_sequence, queue_depth_after);
223 }
224
225 #[inline]
226 fn record_backpressure(
227 &self,
228 flow_id: FlowId,
229 stream_id: StreamId,
230 activated: bool,
231 queue_depth: u32,
232 timestamp_ns: u64,
233 ) {
234 (**self).record_backpressure(flow_id, stream_id, activated, queue_depth, timestamp_ns);
235 }
236
237 #[inline]
238 fn record_copy(
239 &self,
240 flow_id: FlowId,
241 resource_id: ResourceId,
242 from_component: ComponentId,
243 to_component: ComponentId,
244 copy_bytes: u64,
245 reason: CopyReason,
246 ) {
247 (**self).record_copy(
248 flow_id,
249 resource_id,
250 from_component,
251 to_component,
252 copy_bytes,
253 reason,
254 );
255 }
256
257 #[inline]
258 fn record_flow_latency(&self, flow_id: FlowId, latency_ns: u64) {
259 (**self).record_flow_latency(flow_id, latency_ns);
260 }
261
262 #[inline]
263 fn record_element_span(
264 &self,
265 flow_id: FlowId,
266 component_id: ComponentId,
267 element_sequence: u64,
268 start_ns: u64,
269 end_ns: u64,
270 status: InvocationStatus,
271 ) {
272 (**self).record_element_span(
273 flow_id,
274 component_id,
275 element_sequence,
276 start_ns,
277 end_ns,
278 status,
279 );
280 }
281
282 #[inline]
283 fn flow_trace_context(&self, flow_id: FlowId) -> Option<TraceContext> {
284 (**self).flow_trace_context(flow_id)
285 }
286
287 #[inline]
288 fn level(&self) -> ObservabilityLevel {
289 (**self).level()
290 }
291
292 #[inline]
293 fn on_flow_start(
294 &self,
295 flow_id: FlowId,
296 component_ids: &[ComponentId],
297 stream_ids: &[StreamId],
298 ) {
299 (**self).on_flow_start(flow_id, component_ids, stream_ids);
300 }
301}
302
303/// Status of a component invocation, for observability recording.
304///
305/// # HOT PATH — created per invocation.
306#[derive(Clone, Copy, Debug, PartialEq, Eq)]
307pub enum InvocationStatus {
308 /// Invocation completed successfully.
309 Ok,
310 /// Invocation completed with an error.
311 Error(ProcessErrorKind),
312 /// Invocation timed out.
313 Timeout,
314 /// Invocation was cancelled.
315 Cancelled,
316}
317
318impl std::fmt::Display for InvocationStatus {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 match self {
321 InvocationStatus::Ok => write!(f, "ok"),
322 InvocationStatus::Error(kind) => write!(f, "error({:?})", kind),
323 InvocationStatus::Timeout => write!(f, "timeout"),
324 InvocationStatus::Cancelled => write!(f, "cancelled"),
325 }
326 }
327}
328
329/// A no-op implementation of [`EventSink`] for testing and benchmarking.
330///
331/// All methods are empty. Returns [`ObservabilityLevel::Off`].
332///
333/// # Examples
334/// ```
335/// use torvyn_types::{NoopEventSink, EventSink, FlowId, ComponentId, ObservabilityLevel};
336/// use torvyn_types::InvocationStatus;
337///
338/// let sink = NoopEventSink;
339/// sink.record_invocation(FlowId::new(1), ComponentId::new(1), 0, 100, InvocationStatus::Ok);
340/// assert_eq!(sink.level(), ObservabilityLevel::Off);
341/// ```
342#[derive(Clone, Copy)]
343pub struct NoopEventSink;
344
345impl EventSink for NoopEventSink {
346 #[inline]
347 fn record_invocation(
348 &self,
349 _flow_id: FlowId,
350 _component_id: ComponentId,
351 _start_ns: u64,
352 _end_ns: u64,
353 _status: InvocationStatus,
354 ) {
355 // No-op: zero cost when observability is off.
356 }
357
358 #[inline]
359 fn record_element_transfer(
360 &self,
361 _flow_id: FlowId,
362 _stream_id: StreamId,
363 _element_sequence: u64,
364 _queue_depth_after: u32,
365 ) {
366 // No-op.
367 }
368
369 #[inline]
370 fn record_backpressure(
371 &self,
372 _flow_id: FlowId,
373 _stream_id: StreamId,
374 _activated: bool,
375 _queue_depth: u32,
376 _timestamp_ns: u64,
377 ) {
378 // No-op.
379 }
380
381 #[inline]
382 fn record_copy(
383 &self,
384 _flow_id: FlowId,
385 _resource_id: ResourceId,
386 _from_component: ComponentId,
387 _to_component: ComponentId,
388 _copy_bytes: u64,
389 _reason: CopyReason,
390 ) {
391 // No-op.
392 }
393
394 #[inline]
395 fn level(&self) -> ObservabilityLevel {
396 ObservabilityLevel::Off
397 }
398}
399
400// ---------------------------------------------------------------------------
401// Tests
402// ---------------------------------------------------------------------------
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 #[test]
409 fn test_noop_event_sink_level() {
410 let sink = NoopEventSink;
411 assert_eq!(sink.level(), ObservabilityLevel::Off);
412 }
413
414 #[test]
415 fn test_noop_event_sink_record_invocation_does_not_panic() {
416 let sink = NoopEventSink;
417 sink.record_invocation(
418 FlowId::new(1),
419 ComponentId::new(1),
420 0,
421 100,
422 InvocationStatus::Ok,
423 );
424 }
425
426 #[test]
427 fn test_noop_event_sink_record_copy_does_not_panic() {
428 let sink = NoopEventSink;
429 sink.record_copy(
430 FlowId::new(1),
431 ResourceId::new(0, 0),
432 ComponentId::new(1),
433 ComponentId::new(2),
434 1024,
435 CopyReason::CrossComponent,
436 );
437 }
438
439 #[test]
440 fn test_invocation_status_display() {
441 assert_eq!(format!("{}", InvocationStatus::Ok), "ok");
442 assert_eq!(format!("{}", InvocationStatus::Timeout), "timeout");
443 assert_eq!(format!("{}", InvocationStatus::Cancelled), "cancelled");
444 }
445
446 #[test]
447 fn test_noop_event_sink_is_send_sync() {
448 fn assert_send_sync<T: Send + Sync + 'static>() {}
449 assert_send_sync::<NoopEventSink>();
450 }
451
452 #[test]
453 fn test_noop_event_sink_on_flow_start_default_does_not_panic() {
454 let sink = NoopEventSink;
455 sink.on_flow_start(
456 FlowId::new(1),
457 &[ComponentId::new(1), ComponentId::new(2)],
458 &[StreamId::new(0)],
459 );
460 }
461
462 /// A recording sink that counts invocations and the components/streams it
463 /// was asked to register, used to prove the `Arc<E>` forwarding impl reaches
464 /// the inner sink.
465 #[derive(Default)]
466 struct CountingSink {
467 invocations: std::sync::atomic::AtomicU64,
468 registered_components: std::sync::atomic::AtomicU64,
469 registered_streams: std::sync::atomic::AtomicU64,
470 }
471
472 impl EventSink for CountingSink {
473 fn record_invocation(
474 &self,
475 _flow_id: FlowId,
476 _component_id: ComponentId,
477 _start_ns: u64,
478 _end_ns: u64,
479 _status: InvocationStatus,
480 ) {
481 self.invocations
482 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
483 }
484
485 fn record_element_transfer(
486 &self,
487 _flow_id: FlowId,
488 _stream_id: StreamId,
489 _element_sequence: u64,
490 _queue_depth_after: u32,
491 ) {
492 }
493
494 fn record_backpressure(
495 &self,
496 _flow_id: FlowId,
497 _stream_id: StreamId,
498 _activated: bool,
499 _queue_depth: u32,
500 _timestamp_ns: u64,
501 ) {
502 }
503
504 fn record_copy(
505 &self,
506 _flow_id: FlowId,
507 _resource_id: ResourceId,
508 _from_component: ComponentId,
509 _to_component: ComponentId,
510 _copy_bytes: u64,
511 _reason: CopyReason,
512 ) {
513 }
514
515 fn level(&self) -> ObservabilityLevel {
516 ObservabilityLevel::Production
517 }
518
519 fn on_flow_start(
520 &self,
521 _flow_id: FlowId,
522 component_ids: &[ComponentId],
523 stream_ids: &[StreamId],
524 ) {
525 self.registered_components.fetch_add(
526 component_ids.len() as u64,
527 std::sync::atomic::Ordering::Relaxed,
528 );
529 self.registered_streams.fetch_add(
530 stream_ids.len() as u64,
531 std::sync::atomic::Ordering::Relaxed,
532 );
533 }
534 }
535
536 #[test]
537 fn test_arc_event_sink_forwards_to_inner() {
538 use std::sync::atomic::Ordering;
539
540 let sink: Arc<CountingSink> = Arc::new(CountingSink::default());
541
542 // Every method must forward through the `Arc` to the inner sink.
543 EventSink::on_flow_start(
544 &sink,
545 FlowId::new(7),
546 &[
547 ComponentId::new(1),
548 ComponentId::new(2),
549 ComponentId::new(3),
550 ],
551 &[StreamId::new(0), StreamId::new(1)],
552 );
553 sink.record_invocation(
554 FlowId::new(7),
555 ComponentId::new(1),
556 0,
557 100,
558 InvocationStatus::Ok,
559 );
560 sink.record_invocation(
561 FlowId::new(7),
562 ComponentId::new(2),
563 100,
564 250,
565 InvocationStatus::Ok,
566 );
567
568 assert_eq!(sink.invocations.load(Ordering::Relaxed), 2);
569 assert_eq!(sink.registered_components.load(Ordering::Relaxed), 3);
570 assert_eq!(sink.registered_streams.load(Ordering::Relaxed), 2);
571 assert_eq!(EventSink::level(&sink), ObservabilityLevel::Production);
572 }
573
574 #[test]
575 fn test_arc_event_sink_clone_shares_state() {
576 use std::sync::atomic::Ordering;
577
578 // The reactor clones the sink once per flow driver; an `Arc` clone must
579 // share the single underlying sink so all drivers record into one place.
580 let sink: Arc<CountingSink> = Arc::new(CountingSink::default());
581 let clone = Arc::clone(&sink);
582
583 clone.record_invocation(
584 FlowId::new(1),
585 ComponentId::new(1),
586 0,
587 1,
588 InvocationStatus::Ok,
589 );
590 sink.record_invocation(
591 FlowId::new(1),
592 ComponentId::new(1),
593 0,
594 1,
595 InvocationStatus::Ok,
596 );
597
598 assert_eq!(sink.invocations.load(Ordering::Relaxed), 2);
599 }
600
601 #[test]
602 fn test_arc_event_sink_satisfies_clone_bound() {
603 // The coordinator requires `E: EventSink + Clone + 'static`; assert the
604 // `Arc<E>` wrapper meets exactly that bound.
605 fn assert_event_sink_clone<T: EventSink + Clone + 'static>() {}
606 assert_event_sink_clone::<Arc<CountingSink>>();
607 }
608}