Skip to main content

nautilus_event_store/capture/
registry.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! The bus capture allow-list.
17//!
18//! [`EncoderRegistry`] is the allow-list the [`crate::capture::BusCaptureAdapter`] consults
19//! at every dispatch boundary. A message whose Rust type has no registered encoder is not
20//! captured: the SPEC names a closed list of state-affecting topics, and silent capture of
21//! out-of-allow-list types would produce entries the verifier process cannot decode.
22//!
23//! Registration binds three things:
24//!
25//! 1. The Rust type the encoder consumes (used as the [`std::any::TypeId`] lookup key).
26//! 2. The canonical [`crate::PayloadType`] tag stamped on every entry the encoder produces.
27//! 3. The encoder closure that produces the payload bytes plus sidecar [`crate::IndexKey`]s.
28//!
29//! A registration may additionally carry an identity extractor: production dispatch pushes
30//! the same typed message through multiple tap-visible boundaries (an order event is sent
31//! to the portfolio endpoint and published on its strategy topic), and the adapter uses the
32//! extracted identity to capture each logical message exactly once.
33
34use std::{
35    any::{Any, TypeId},
36    collections::HashMap,
37    fmt::Debug,
38    marker::PhantomData,
39    sync::Arc,
40};
41
42use nautilus_core::UUID4;
43
44use crate::{
45    capture::encoder::{Encode, EncodeError, EncodedPayload, TypedEncoder},
46    entry::PayloadType,
47    headers::Headers,
48};
49
50/// Extracts correlation [`Headers`] from a captured message at the dispatch boundary.
51///
52/// The encoder boundary deliberately omits headers ([`EncodedPayload`] documents this), so
53/// the bus tap consults the registry-registered extractor instead. Registration without an
54/// explicit extractor falls back to [`Headers::empty`]; that keeps capture working for
55/// allow-list types whose underlying struct has not yet grown `correlation_id` /
56/// `causation_id`
57/// fields (header propagation lands incrementally per the SPEC).
58pub trait HeadersExtractor: Send + Sync {
59    /// Returns the headers carried by `message`. Implementations downcast to the concrete
60    /// type they were registered for and read the relevant fields; mismatched types yield
61    /// [`Headers::empty`] so a stale registration cannot crash the tap.
62    fn extract(&self, message: &dyn Any) -> Headers;
63}
64
65/// Typed adapter that downcasts to `T` and forwards to a `Fn(&T) -> Headers` closure.
66pub struct TypedHeadersExtractor<T: 'static, F> {
67    func: F,
68    _phantom: PhantomData<fn(&T)>,
69}
70
71impl<T: 'static, F> TypedHeadersExtractor<T, F>
72where
73    F: Fn(&T) -> Headers + Send + Sync,
74{
75    /// Wraps `func` as a typed headers extractor for `T`.
76    #[must_use]
77    pub const fn new(func: F) -> Self {
78        Self {
79            func,
80            _phantom: PhantomData,
81        }
82    }
83}
84
85impl<T: 'static, F> Debug for TypedHeadersExtractor<T, F> {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct(stringify!(TypedHeadersExtractor))
88            .field("type", &std::any::type_name::<T>())
89            .finish_non_exhaustive()
90    }
91}
92
93impl<T: 'static, F> HeadersExtractor for TypedHeadersExtractor<T, F>
94where
95    F: Fn(&T) -> Headers + Send + Sync,
96{
97    fn extract(&self, message: &dyn Any) -> Headers {
98        message.downcast_ref::<T>().map_or_default(&self.func)
99    }
100}
101
102// Extractor that always returns `Headers::empty()`; the default for registrations that
103// have no explicit extractor.
104#[derive(Debug, Default)]
105struct EmptyHeadersExtractor;
106
107impl HeadersExtractor for EmptyHeadersExtractor {
108    fn extract(&self, _: &dyn Any) -> Headers {
109        Headers::empty()
110    }
111}
112
113/// Extracts the logical message identity (event id, command id) from a captured message.
114///
115/// The adapter uses the identity to capture a message exactly once when dispatch pushes
116/// it through multiple tap-visible boundaries. Types without an extractor are captured
117/// per dispatch, which is correct only for types that reach the tap on a single boundary.
118pub trait IdentityExtractor: Send + Sync {
119    /// Returns the identity carried by `message`. Mismatched types yield `None` so a
120    /// stale registration cannot crash the tap.
121    fn extract(&self, message: &dyn Any) -> Option<UUID4>;
122}
123
124/// Typed adapter that downcasts to `T` and forwards to a `Fn(&T) -> Option<UUID4>` closure.
125pub struct TypedIdentityExtractor<T: 'static, F> {
126    func: F,
127    _phantom: PhantomData<fn(&T)>,
128}
129
130impl<T: 'static, F> TypedIdentityExtractor<T, F>
131where
132    F: Fn(&T) -> Option<UUID4> + Send + Sync,
133{
134    /// Wraps `func` as a typed identity extractor for `T`.
135    #[must_use]
136    pub const fn new(func: F) -> Self {
137        Self {
138            func,
139            _phantom: PhantomData,
140        }
141    }
142}
143
144impl<T: 'static, F> Debug for TypedIdentityExtractor<T, F> {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        f.debug_struct(stringify!(TypedIdentityExtractor))
147            .field("type", &std::any::type_name::<T>())
148            .finish_non_exhaustive()
149    }
150}
151
152impl<T: 'static, F> IdentityExtractor for TypedIdentityExtractor<T, F>
153where
154    F: Fn(&T) -> Option<UUID4> + Send + Sync,
155{
156    fn extract(&self, message: &dyn Any) -> Option<UUID4> {
157        message.downcast_ref::<T>().and_then(&self.func)
158    }
159}
160
161// One allow-list entry: canonical payload tag, encoder, header extractor, and optional
162// identity extractor.
163#[derive(Clone)]
164struct Registered {
165    payload_type: PayloadType,
166    encoder: Arc<dyn Encode>,
167    headers: Arc<dyn HeadersExtractor>,
168    identity: Option<Arc<dyn IdentityExtractor>>,
169}
170
171impl Debug for Registered {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.debug_struct(stringify!(Registered))
174            .field("payload_type", &self.payload_type.as_str())
175            .finish_non_exhaustive()
176    }
177}
178
179/// Allow-list of capturable Rust message types and their encoders.
180///
181/// Registration is keyed by [`std::any::TypeId`]; the adapter dispatches by `TypeId` so
182/// callers can capture a typed message without naming the encoder concretely. A type
183/// registered twice replaces the prior entry: the SPEC's encoder rules require one
184/// canonical mapping per Rust type, and the registry would otherwise hide the conflict.
185#[derive(Clone, Debug, Default)]
186pub struct EncoderRegistry {
187    by_type: HashMap<TypeId, Registered>,
188}
189
190impl EncoderRegistry {
191    /// Creates a new empty registry.
192    #[must_use]
193    pub fn new() -> Self {
194        Self::default()
195    }
196
197    /// Registers `func` as the encoder for `T` and stamps every captured entry with
198    /// `payload_type`. Captures yield [`Headers::empty`] until [`Self::register_headers`]
199    /// records an extractor for `T`.
200    ///
201    /// Replaces any encoder previously registered for `T`; capture flows hold the
202    /// registry as `Arc<EncoderRegistry>` so registration must happen before the adapter
203    /// is constructed.
204    pub fn register<T, F>(&mut self, payload_type: PayloadType, func: F)
205    where
206        T: 'static,
207        F: Fn(&T) -> Result<EncodedPayload, EncodeError> + Send + Sync + 'static,
208    {
209        let encoder: Arc<dyn Encode> = Arc::new(TypedEncoder::<T, F>::new(func));
210        let headers = self
211            .preserved_headers::<T>()
212            .unwrap_or_else(|| Arc::new(EmptyHeadersExtractor) as Arc<dyn HeadersExtractor>);
213        let identity = self.preserved_identity::<T>();
214        self.by_type.insert(
215            TypeId::of::<T>(),
216            Registered {
217                payload_type,
218                encoder,
219                headers,
220                identity,
221            },
222        );
223    }
224
225    /// Registers `func` as the encoder for `T` and `headers_fn` as the matching headers
226    /// extractor in one call.
227    pub fn register_with_headers<T, F, H>(
228        &mut self,
229        payload_type: PayloadType,
230        func: F,
231        headers_fn: H,
232    ) where
233        T: 'static,
234        F: Fn(&T) -> Result<EncodedPayload, EncodeError> + Send + Sync + 'static,
235        H: Fn(&T) -> Headers + Send + Sync + 'static,
236    {
237        let encoder: Arc<dyn Encode> = Arc::new(TypedEncoder::<T, F>::new(func));
238        let headers: Arc<dyn HeadersExtractor> =
239            Arc::new(TypedHeadersExtractor::<T, H>::new(headers_fn));
240        let identity = self.preserved_identity::<T>();
241        self.by_type.insert(
242            TypeId::of::<T>(),
243            Registered {
244                payload_type,
245                encoder,
246                headers,
247                identity,
248            },
249        );
250    }
251
252    /// Registers an already-built [`Encode`] implementer for `T`. Captures yield
253    /// [`Headers::empty`] until [`Self::register_headers`] records an extractor.
254    ///
255    /// Useful when the encoder owns state (e.g., a schema cache) the closure form cannot
256    /// express ergonomically.
257    pub fn register_encoder<T: 'static>(
258        &mut self,
259        payload_type: PayloadType,
260        encoder: Arc<dyn Encode>,
261    ) {
262        let headers = self
263            .preserved_headers::<T>()
264            .unwrap_or_else(|| Arc::new(EmptyHeadersExtractor) as Arc<dyn HeadersExtractor>);
265        let identity = self.preserved_identity::<T>();
266        self.by_type.insert(
267            TypeId::of::<T>(),
268            Registered {
269                payload_type,
270                encoder,
271                headers,
272                identity,
273            },
274        );
275    }
276
277    /// Registers `headers_fn` as the headers extractor for `T`.
278    ///
279    /// Call after [`Self::register`] when the encoder is preregistered through a shared
280    /// encoder but the call site wants a typed headers extractor. Replaces any prior
281    /// extractor for `T`. Returns silently when `T` has no encoder registered: callers
282    /// that care about the contract should rely on [`Self::contains`].
283    pub fn register_headers<T, H>(&mut self, headers_fn: H)
284    where
285        T: 'static,
286        H: Fn(&T) -> Headers + Send + Sync + 'static,
287    {
288        if let Some(reg) = self.by_type.get_mut(&TypeId::of::<T>()) {
289            reg.headers = Arc::new(TypedHeadersExtractor::<T, H>::new(headers_fn));
290        }
291    }
292
293    /// Registers `identity_fn` as the identity extractor for `T`.
294    ///
295    /// Call after [`Self::register`]. Replaces any prior extractor for `T`. Returns
296    /// silently when `T` has no encoder registered: callers that care about the contract
297    /// should rely on [`Self::contains`].
298    pub fn register_identity<T, F>(&mut self, identity_fn: F)
299    where
300        T: 'static,
301        F: Fn(&T) -> Option<UUID4> + Send + Sync + 'static,
302    {
303        if let Some(reg) = self.by_type.get_mut(&TypeId::of::<T>()) {
304            reg.identity = Some(Arc::new(TypedIdentityExtractor::<T, F>::new(identity_fn)));
305        }
306    }
307
308    fn preserved_headers<T: 'static>(&self) -> Option<Arc<dyn HeadersExtractor>> {
309        self.by_type
310            .get(&TypeId::of::<T>())
311            .map(|reg| Arc::clone(&reg.headers))
312    }
313
314    fn preserved_identity<T: 'static>(&self) -> Option<Arc<dyn IdentityExtractor>> {
315        self.by_type
316            .get(&TypeId::of::<T>())
317            .and_then(|reg| reg.identity.clone())
318    }
319
320    /// Returns the number of registered encoders.
321    #[must_use]
322    pub fn len(&self) -> usize {
323        self.by_type.len()
324    }
325
326    /// Returns whether the registry is empty.
327    #[must_use]
328    pub fn is_empty(&self) -> bool {
329        self.by_type.is_empty()
330    }
331
332    /// Returns whether an encoder is registered for `T`.
333    #[must_use]
334    pub fn contains<T: 'static>(&self) -> bool {
335        self.by_type.contains_key(&TypeId::of::<T>())
336    }
337
338    /// Encodes `message` if a typed encoder is registered for `T`.
339    ///
340    /// Returns `Ok(None)` when no encoder is registered for `T` so the adapter can drop
341    /// the message at the dispatch boundary without surfacing it as an error: the
342    /// allow-list is the source of truth for the captured surface, and out-of-list
343    /// messages are non-state-affecting by definition.
344    ///
345    /// # Errors
346    ///
347    /// Returns an error if an encoder is registered but rejects the message.
348    pub fn encode<T: 'static>(
349        &self,
350        message: &T,
351    ) -> Result<Option<(PayloadType, EncodedPayload)>, EncodeError> {
352        let Some(reg) = self.by_type.get(&TypeId::of::<T>()) else {
353            return Ok(None);
354        };
355
356        let encoded = reg.encoder.encode(message as &dyn Any)?;
357        let payload_type = encoded.payload_type.unwrap_or(reg.payload_type);
358        Ok(Some((payload_type, encoded)))
359    }
360
361    /// Encodes a type-erased `message` if an encoder is registered for the concrete type.
362    ///
363    /// Mirror of [`Self::encode`] for `&dyn Any` callers; the bus tap reaches the
364    /// capture path through this entry point because dispatch returns a `&dyn Any` and
365    /// the static type is not in scope.
366    ///
367    /// # Errors
368    ///
369    /// Returns an error if an encoder is registered for the concrete type but rejects the message.
370    pub fn encode_any(
371        &self,
372        message: &dyn Any,
373    ) -> Result<Option<(PayloadType, EncodedPayload)>, EncodeError> {
374        let Some(reg) = self.by_type.get(&message.type_id()) else {
375            return Ok(None);
376        };
377
378        let encoded = reg.encoder.encode(message)?;
379        let payload_type = encoded.payload_type.unwrap_or(reg.payload_type);
380        Ok(Some((payload_type, encoded)))
381    }
382
383    /// Returns the headers carried by `message` if a registration exists for its concrete
384    /// type. Returns `None` when no encoder is registered: the adapter then drops the
385    /// message without further work.
386    #[must_use]
387    pub fn headers_for_any(&self, message: &dyn Any) -> Option<Headers> {
388        self.by_type
389            .get(&message.type_id())
390            .map(|reg| reg.headers.extract(message))
391    }
392
393    /// Returns the logical identity carried by `message` if its registration has an
394    /// identity extractor. Returns `None` when the type is unregistered or carries no
395    /// extractor; the adapter then captures per dispatch.
396    #[must_use]
397    pub fn identity_for_any(&self, message: &dyn Any) -> Option<UUID4> {
398        self.by_type
399            .get(&message.type_id())
400            .and_then(|reg| reg.identity.as_ref())
401            .and_then(|identity| identity.extract(message))
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use std::sync::Arc;
408
409    use bytes::Bytes;
410    use rstest::rstest;
411    use ustr::Ustr;
412
413    use super::*;
414
415    #[derive(Debug)]
416    struct Sample(u8);
417
418    #[derive(Debug)]
419    struct Other;
420
421    #[derive(Debug)]
422    struct StatefulEncoder {
423        prefix: u8,
424    }
425
426    impl Encode for StatefulEncoder {
427        fn encode(&self, message: &dyn Any) -> Result<EncodedPayload, EncodeError> {
428            let sample = message
429                .downcast_ref::<Sample>()
430                .ok_or(EncodeError::TypeMismatch {
431                    expected: std::any::type_name::<Sample>(),
432                })?;
433            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
434                self.prefix,
435                sample.0,
436            ])))
437        }
438    }
439
440    #[rstest]
441    fn unknown_type_returns_none() {
442        let registry = EncoderRegistry::new();
443
444        assert!(registry.encode(&Sample(1)).expect("encode").is_none());
445        assert!(!registry.contains::<Sample>());
446    }
447
448    #[rstest]
449    fn registered_type_returns_payload_type_and_payload() {
450        let mut registry = EncoderRegistry::new();
451        registry.register::<Sample, _>(Ustr::from("Sample"), |s| {
452            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
453                s.0,
454            ])))
455        });
456
457        let (tag, encoded) = registry.encode(&Sample(9)).expect("encode").expect("hit");
458
459        assert_eq!(tag.as_str(), "Sample");
460        assert_eq!(encoded.payload.as_ref(), &[9]);
461        assert!(registry.contains::<Sample>());
462        assert_eq!(registry.len(), 1);
463    }
464
465    #[rstest]
466    fn re_registering_replaces_prior_encoder() {
467        let mut registry = EncoderRegistry::new();
468        registry.register::<Sample, _>(Ustr::from("Old"), |s| {
469            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
470                s.0,
471            ])))
472        });
473        registry.register::<Sample, _>(Ustr::from("New"), |s| {
474            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
475                s.0, s.0,
476            ])))
477        });
478
479        let (tag, encoded) = registry.encode(&Sample(3)).expect("encode").expect("hit");
480
481        assert_eq!(tag.as_str(), "New");
482        assert_eq!(encoded.payload.as_ref(), &[3, 3]);
483        assert_eq!(registry.len(), 1);
484    }
485
486    #[rstest]
487    fn register_encoder_replaces_encoder_and_preserves_extractors() {
488        let mut registry = EncoderRegistry::new();
489        registry.register::<Sample, _>(Ustr::from("Old"), |s| {
490            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
491                s.0,
492            ])))
493        });
494        let correlation_id = UUID4::new();
495        let causation_id = UUID4::new();
496        registry.register_headers::<Sample, _>(move |_| Headers {
497            correlation_id: Some(correlation_id),
498            causation_id: Some(causation_id),
499        });
500        let identity = UUID4::new();
501        registry.register_identity::<Sample, _>(move |_| Some(identity));
502
503        registry.register_encoder::<Sample>(
504            Ustr::from("Stateful"),
505            Arc::new(StatefulEncoder { prefix: 0xA5 }),
506        );
507        let sample = Sample(7);
508        let (payload_type, encoded) = registry.encode(&sample).expect("encode").expect("hit");
509        let headers = registry
510            .headers_for_any(&sample as &dyn Any)
511            .expect("headers");
512
513        assert_eq!(payload_type.as_str(), "Stateful");
514        assert_eq!(
515            encoded,
516            EncodedPayload::without_indices(Bytes::from_static(&[0xA5, 7])),
517        );
518        assert_eq!(
519            headers,
520            Headers {
521                correlation_id: Some(correlation_id),
522                causation_id: Some(causation_id),
523            },
524        );
525        assert_eq!(
526            registry.identity_for_any(&sample as &dyn Any),
527            Some(identity)
528        );
529        assert_eq!(registry.len(), 1);
530    }
531
532    #[rstest]
533    fn registry_is_empty_by_default() {
534        let registry = EncoderRegistry::new();
535
536        assert!(registry.is_empty());
537        assert_eq!(registry.len(), 0);
538        assert!(!registry.contains::<Other>());
539    }
540
541    #[rstest]
542    fn encode_any_dispatches_by_concrete_type_id() {
543        // The bus tap reaches the registry through `encode_any` because the static
544        // type is not in scope at the dispatch site. Verify the &dyn Any lookup
545        // resolves to the same registration as the typed `encode<T>` path.
546        let mut registry = EncoderRegistry::new();
547        registry.register::<Sample, _>(Ustr::from("Sample"), |s| {
548            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
549                s.0,
550            ])))
551        });
552
553        let sample = Sample(5);
554        let (tag, encoded) = registry
555            .encode_any(&sample as &dyn Any)
556            .expect("encode_any")
557            .expect("hit");
558
559        assert_eq!(tag.as_str(), "Sample");
560        assert_eq!(encoded.payload.as_ref(), &[5]);
561    }
562
563    #[rstest]
564    fn encode_any_returns_none_for_unregistered_type() {
565        // Out-of-allow-list messages must surface as `Ok(None)` so the adapter can
566        // skip them silently at the dispatch boundary rather than treating them as
567        // capture failures.
568        let registry = EncoderRegistry::new();
569
570        let unregistered = Other;
571        let outcome = registry
572            .encode_any(&unregistered as &dyn Any)
573            .expect("encode_any");
574
575        assert!(outcome.is_none());
576    }
577
578    #[rstest]
579    fn encoder_payload_type_override_overrides_registered_tag() {
580        // Envelope encoders (TradingCommand, OrderEventAny) need to stamp the
581        // inner-variant tag on captured entries so forensics scans see the same
582        // payload_type as the bare-type capture path. The override mechanism is
583        // tested here independent of the bus surface so the registry contract
584        // is self-documenting.
585        let mut registry = EncoderRegistry::new();
586        registry.register::<Sample, _>(Ustr::from("Wrapper"), |s| {
587            Ok(EncodedPayload::with_payload_type(
588                Ustr::from("Inner"),
589                Bytes::copy_from_slice(&[s.0]),
590                Vec::new(),
591            ))
592        });
593
594        let (tag, _) = registry.encode(&Sample(1)).expect("encode").expect("hit");
595        assert_eq!(tag.as_str(), "Inner");
596
597        let (any_tag, _) = registry
598            .encode_any(&Sample(1) as &dyn Any)
599            .expect("encode_any")
600            .expect("hit");
601        assert_eq!(any_tag.as_str(), "Inner");
602    }
603
604    #[rstest]
605    fn registered_type_without_headers_extractor_returns_empty_headers() {
606        let mut registry = EncoderRegistry::new();
607        registry.register::<Sample, _>(Ustr::from("Sample"), |s| {
608            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
609                s.0,
610            ])))
611        });
612
613        let headers = registry
614            .headers_for_any(&Sample(1) as &dyn Any)
615            .expect("hit");
616        assert_eq!(headers, Headers::empty());
617    }
618
619    #[rstest]
620    fn headers_for_any_returns_none_for_unregistered_type() {
621        let registry = EncoderRegistry::new();
622        let outcome = registry.headers_for_any(&Other as &dyn Any);
623
624        assert!(outcome.is_none());
625    }
626
627    #[rstest]
628    fn register_with_headers_uses_extractor() {
629        // The tap consults `headers_for_any` to populate the entry's Headers; the
630        // registered extractor must reach the captured message and produce the right
631        // values.
632        let mut registry = EncoderRegistry::new();
633        let causation = nautilus_core::UUID4::new();
634        let causation_captured = causation;
635        registry.register_with_headers::<Sample, _, _>(
636            Ustr::from("Sample"),
637            |s| {
638                Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
639                    s.0,
640                ])))
641            },
642            move |_| Headers {
643                correlation_id: None,
644                causation_id: Some(causation_captured),
645            },
646        );
647
648        let headers = registry
649            .headers_for_any(&Sample(1) as &dyn Any)
650            .expect("hit");
651        assert_eq!(headers.causation_id, Some(causation));
652    }
653
654    #[rstest]
655    fn register_headers_overrides_default_extractor_post_register() {
656        // Callers can attach a headers extractor after registering the encoder, which
657        // is how the shared default_registry encoders compose with site-specific
658        // header propagation.
659        let mut registry = EncoderRegistry::new();
660        registry.register::<Sample, _>(Ustr::from("Sample"), |s| {
661            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
662                s.0,
663            ])))
664        });
665        let correlation = nautilus_core::UUID4::new();
666        let correlation_captured = correlation;
667        registry.register_headers::<Sample, _>(move |_| Headers {
668            correlation_id: Some(correlation_captured),
669            causation_id: None,
670        });
671
672        let headers = registry
673            .headers_for_any(&Sample(1) as &dyn Any)
674            .expect("hit");
675        assert_eq!(headers.correlation_id, Some(correlation));
676    }
677
678    #[rstest]
679    fn identity_for_any_returns_none_without_extractor() {
680        let mut registry = EncoderRegistry::new();
681        registry.register::<Sample, _>(Ustr::from("Sample"), |s| {
682            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
683                s.0,
684            ])))
685        });
686
687        assert!(registry.identity_for_any(&Sample(1) as &dyn Any).is_none());
688        assert!(registry.identity_for_any(&Other as &dyn Any).is_none());
689    }
690
691    #[rstest]
692    fn register_identity_extracts_and_survives_re_register() {
693        // The adapter dedups on the extracted identity; the extractor must survive a
694        // subsequent encoder re-registration the same way headers extractors do.
695        let mut registry = EncoderRegistry::new();
696        registry.register::<Sample, _>(Ustr::from("Old"), |s| {
697            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
698                s.0,
699            ])))
700        });
701        let identity = nautilus_core::UUID4::new();
702        registry.register_identity::<Sample, _>(move |_| Some(identity));
703
704        assert_eq!(
705            registry.identity_for_any(&Sample(1) as &dyn Any),
706            Some(identity),
707        );
708
709        registry.register::<Sample, _>(Ustr::from("New"), |s| {
710            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
711                s.0, s.0,
712            ])))
713        });
714
715        assert_eq!(
716            registry.identity_for_any(&Sample(1) as &dyn Any),
717            Some(identity),
718        );
719    }
720
721    #[rstest]
722    fn register_identity_for_unregistered_type_is_silent_noop() {
723        let mut registry = EncoderRegistry::new();
724        registry.register_identity::<Sample, _>(|_| Some(nautilus_core::UUID4::new()));
725
726        assert!(!registry.contains::<Sample>());
727        assert!(registry.identity_for_any(&Sample(1) as &dyn Any).is_none());
728    }
729
730    #[rstest]
731    fn register_headers_for_unregistered_type_is_silent_noop() {
732        let mut registry = EncoderRegistry::new();
733        registry.register_headers::<Sample, _>(|_| Headers::empty());
734
735        assert!(!registry.contains::<Sample>());
736        assert!(registry.headers_for_any(&Sample(1) as &dyn Any).is_none());
737    }
738
739    #[rstest]
740    fn re_registering_preserves_existing_headers_extractor() {
741        // A subsequent `register` for the same type must keep the previously-attached
742        // headers extractor so callers that compose encoder + headers in two phases do
743        // not silently lose the extractor when the encoder is replaced.
744        let mut registry = EncoderRegistry::new();
745        registry.register::<Sample, _>(Ustr::from("Old"), |s| {
746            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
747                s.0,
748            ])))
749        });
750        let causation = nautilus_core::UUID4::new();
751        let causation_captured = causation;
752        registry.register_headers::<Sample, _>(move |_| Headers {
753            correlation_id: None,
754            causation_id: Some(causation_captured),
755        });
756        registry.register::<Sample, _>(Ustr::from("New"), |s| {
757            Ok(EncodedPayload::without_indices(Bytes::copy_from_slice(&[
758                s.0, s.0,
759            ])))
760        });
761
762        let (tag, _) = registry.encode(&Sample(3)).expect("encode").expect("hit");
763        assert_eq!(tag.as_str(), "New");
764        let headers = registry
765            .headers_for_any(&Sample(3) as &dyn Any)
766            .expect("hit");
767        assert_eq!(headers.causation_id, Some(causation));
768    }
769}