Skip to main content

datafusion_proto_models/
registry.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! A name-keyed store of decoders for extension types.
6//!
7//! DataFusion serializes several kinds of polymorphic value: `ExecutionPlan`,
8//! `PhysicalExpr`, and in time the `DataSource`, `DataSink` and
9//! `LazyBatchGenerator` families. A built-in gets its own wire variant, so the
10//! wire format names it. An extension shares one catch-all variant with every
11//! other extension of its kind, so the payload has to carry a name and the
12//! decoding session has to map that name back to a decoder.
13//!
14//! [`ProtoDecoderRegistry`] is that map, once, for every kind. The key is a
15//! pair: the trait the decoder produces, and the name on the wire. Keying on
16//! the trait as well as the name means one session carries one registry rather
17//! than one per kind, and two kinds may use the same name without a collision.
18//!
19//! The registry never names a decode context, or any trait it dispatches to.
20//! It stores each decoder type-erased and hands it back on a downcast, which is
21//! what lets it sit in this crate, below every crate that owns one of those
22//! traits. Each kind supplies a small typed facade next to its own trait —
23//! `datafusion-physical-plan` for `ExecutionPlan`, and so on — so that a caller
24//! never writes a `TypeId` or a downcast by hand.
25
26use std::any::{Any, TypeId, type_name};
27use std::collections::HashMap;
28use std::collections::hash_map::Entry;
29use std::fmt;
30use std::sync::Arc;
31
32use datafusion_common::{Result, config_err};
33
34/// One registered decoder, plus the identity that makes re-registering the
35/// same type a no-op while a genuine name collision is an error.
36#[derive(Clone)]
37struct Registered {
38    decoder: Arc<dyn Any + Send + Sync>,
39    type_id: TypeId,
40    type_name: &'static str,
41}
42
43/// A store of extension decoders, keyed by the trait they produce and the name
44/// the encoder wrote on the wire.
45///
46/// A session carries one registry, as a `SessionConfig` extension. Every
47/// library that ships extension types adds its decoders to that registry with
48/// `SessionConfig::update_extension`, which creates the registry if there is
49/// none:
50///
51/// ```rust,ignore
52/// // in each library
53/// pub fn register(config: &mut SessionConfig) -> Result<()> {
54///     config.update_extension(MyExec::register_proto)?;
55///     config.update_extension(MyExpr::register_proto)
56/// }
57///
58/// // in the application that owns the session
59/// let mut config = SessionConfig::new();
60/// lib_one::register(&mut config)?;
61/// lib_two::register(&mut config)?;
62/// ```
63///
64/// Do not attach a registry with `SessionConfig::with_extension`: it replaces
65/// the registry, so it discards the decoders that other libraries added.
66///
67/// The libraries need to know nothing about each other, and the order they are
68/// called in does not matter: lookup is by name, and a real collision is an
69/// error from [`register_decoder`](Self::register_decoder).
70///
71/// Callers normally reach this type through a kind's typed facade rather than
72/// through the methods here.
73#[derive(Clone, Default)]
74pub struct ProtoDecoderRegistry {
75    decoders: HashMap<(TypeId, String), Registered>,
76}
77
78impl ProtoDecoderRegistry {
79    /// Create an empty registry.
80    pub fn new() -> Self {
81        Self::default()
82    }
83
84    /// Register `decoder` under `name`, for extensions dispatched as `Kind`.
85    ///
86    /// `Kind` is the trait object the decoder produces, such as
87    /// `dyn ExecutionPlan`. `T` is the concrete type being registered; it is
88    /// used only for identity, so that registering the same type twice is a
89    /// no-op while a *different* type under a taken name is an error. `D` is
90    /// the decoder itself, whose type the matching
91    /// [`decoder`](Self::decoder) call must name exactly.
92    pub fn register_decoder<Kind, T, D>(&mut self, name: &str, decoder: D) -> Result<()>
93    where
94        Kind: ?Sized + 'static,
95        T: ?Sized + 'static,
96        D: Any + Send + Sync,
97    {
98        let registered = Registered {
99            decoder: Arc::new(decoder),
100            type_id: TypeId::of::<T>(),
101            type_name: type_name::<T>(),
102        };
103        if name.is_empty() {
104            return config_err!(
105                "Cannot register the extension {} decoder for {} under an empty name",
106                kind_label::<Kind>(),
107                registered.type_name
108            );
109        }
110        match self
111            .decoders
112            .entry((TypeId::of::<Kind>(), name.to_string()))
113        {
114            Entry::Vacant(entry) => {
115                entry.insert(registered);
116                Ok(())
117            }
118            // Re-registering the same type is a no-op: sessions are often
119            // configured by more than one layer of an application.
120            Entry::Occupied(entry) if entry.get().type_id == registered.type_id => Ok(()),
121            Entry::Occupied(entry) => config_err!(
122                "Extension {} name '{}' is already registered by {}, cannot register {}. \
123                 Namespace the name with the owning crate to avoid the collision.",
124                kind_label::<Kind>(),
125                entry.key().1,
126                entry.get().type_name,
127                registered.type_name
128            ),
129        }
130    }
131
132    /// The decoder registered under `name` for extensions dispatched as `Kind`.
133    ///
134    /// `D` must be the same type the matching
135    /// [`register_decoder`](Self::register_decoder) call supplied. A different
136    /// `D` reads as "not registered" rather than as an error, because the two
137    /// calls are always made by the same facade.
138    pub fn decoder<Kind, D>(&self, name: &str) -> Option<&D>
139    where
140        Kind: ?Sized + 'static,
141        D: Any + Send + Sync,
142    {
143        let registered = self
144            .decoders
145            .get(&(TypeId::of::<Kind>(), name.to_string()))?;
146        registered.decoder.downcast_ref::<D>()
147    }
148
149    /// Every name registered for `Kind`, in arbitrary order.
150    pub fn names<Kind: ?Sized + 'static>(&self) -> impl Iterator<Item = &str> {
151        let kind = TypeId::of::<Kind>();
152        self.decoders
153            .keys()
154            .filter(move |(registered_kind, _)| *registered_kind == kind)
155            .map(|(_, name)| name.as_str())
156    }
157}
158
159impl fmt::Debug for ProtoDecoderRegistry {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        // The decoders are opaque; the registered types are the useful part.
162        let mut entries: Vec<&str> =
163            self.decoders.values().map(|r| r.type_name).collect();
164        entries.sort_unstable();
165        f.debug_struct("ProtoDecoderRegistry")
166            .field("registered", &entries)
167            .finish()
168    }
169}
170
171/// The last path segment of a trait object's type name, for error messages:
172/// `dyn datafusion_physical_plan::execution_plan::ExecutionPlan` reads as
173/// `ExecutionPlan`.
174fn kind_label<Kind: ?Sized + 'static>() -> &'static str {
175    let name = type_name::<Kind>();
176    name.rsplit("::").next().unwrap_or(name)
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    trait Plan {}
184    trait Expr {}
185
186    struct OnePlan;
187    struct OtherPlan;
188
189    type PlanDecoder = fn(u8) -> u8;
190    type ExprDecoder = fn(u8) -> u16;
191
192    fn plan_decoder(v: u8) -> u8 {
193        v
194    }
195    fn other_plan_decoder(v: u8) -> u8 {
196        v + 1
197    }
198    fn expr_decoder(v: u8) -> u16 {
199        u16::from(v) + 1000
200    }
201
202    #[test]
203    fn register_and_look_up_a_decoder() -> Result<()> {
204        let mut registry = ProtoDecoderRegistry::new();
205        registry.register_decoder::<dyn Plan, OnePlan, PlanDecoder>(
206            "a-crate.OnePlan",
207            plan_decoder,
208        )?;
209
210        let decoder = registry
211            .decoder::<dyn Plan, PlanDecoder>("a-crate.OnePlan")
212            .expect("the decoder must be registered");
213        assert_eq!(decoder(7), 7);
214        assert!(
215            registry
216                .decoder::<dyn Plan, PlanDecoder>("a-crate.Missing")
217                .is_none()
218        );
219        Ok(())
220    }
221
222    #[test]
223    fn the_same_name_under_two_kinds_does_not_collide() -> Result<()> {
224        // The point of keying on the trait as well as the name: one session
225        // carries one registry, and two kinds never see each other's names.
226        let mut registry = ProtoDecoderRegistry::new();
227        registry
228            .register_decoder::<dyn Plan, OnePlan, PlanDecoder>("shared", plan_decoder)?;
229        registry.register_decoder::<dyn Expr, OtherPlan, ExprDecoder>(
230            "shared",
231            expr_decoder,
232        )?;
233
234        assert_eq!(
235            registry.decoder::<dyn Plan, PlanDecoder>("shared").unwrap()(1),
236            1
237        );
238        assert_eq!(
239            registry.decoder::<dyn Expr, ExprDecoder>("shared").unwrap()(1),
240            1001
241        );
242        assert_eq!(
243            registry.names::<dyn Plan>().collect::<Vec<_>>(),
244            vec!["shared"]
245        );
246        assert_eq!(
247            registry.names::<dyn Expr>().collect::<Vec<_>>(),
248            vec!["shared"]
249        );
250        Ok(())
251    }
252
253    #[test]
254    fn register_is_idempotent_for_the_same_type() -> Result<()> {
255        let mut registry = ProtoDecoderRegistry::new();
256        registry
257            .register_decoder::<dyn Plan, OnePlan, PlanDecoder>("one", plan_decoder)?;
258        registry
259            .register_decoder::<dyn Plan, OnePlan, PlanDecoder>("one", plan_decoder)?;
260
261        assert_eq!(registry.names::<dyn Plan>().count(), 1);
262        Ok(())
263    }
264
265    #[test]
266    fn register_rejects_a_name_collision_between_types() -> Result<()> {
267        let mut registry = ProtoDecoderRegistry::new();
268        registry
269            .register_decoder::<dyn Plan, OnePlan, PlanDecoder>("one", plan_decoder)?;
270
271        let err = registry
272            .register_decoder::<dyn Plan, OtherPlan, PlanDecoder>(
273                "one",
274                other_plan_decoder,
275            )
276            .expect_err("a colliding registration must fail");
277        let err = err.to_string();
278        assert!(
279            err.contains("already registered"),
280            "unexpected error: {err}"
281        );
282        assert!(err.contains("Plan"), "the kind must be named: {err}");
283        assert!(
284            err.contains("OnePlan") && err.contains("OtherPlan"),
285            "{err}"
286        );
287        Ok(())
288    }
289
290    #[test]
291    fn register_rejects_an_empty_name() {
292        let mut registry = ProtoDecoderRegistry::new();
293        let err = registry
294            .register_decoder::<dyn Plan, OnePlan, PlanDecoder>("", plan_decoder)
295            .expect_err("an empty name must fail");
296        assert!(
297            err.to_string().contains("empty name"),
298            "unexpected error: {err}"
299        );
300        assert_eq!(registry.names::<dyn Plan>().count(), 0);
301    }
302
303    #[test]
304    fn a_decoder_of_another_type_reads_as_absent() -> Result<()> {
305        let mut registry = ProtoDecoderRegistry::new();
306        registry
307            .register_decoder::<dyn Plan, OnePlan, PlanDecoder>("one", plan_decoder)?;
308
309        // A facade always pairs the same `D` with the same `Kind`; a mismatch
310        // means the caller asked the wrong facade.
311        assert!(registry.decoder::<dyn Plan, ExprDecoder>("one").is_none());
312        Ok(())
313    }
314}