vortex_array/array/plugin.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt;
5use std::fmt::Debug;
6use std::fmt::Formatter;
7use std::sync::Arc;
8
9use vortex_buffer::ByteBuffer;
10use vortex_error::VortexResult;
11use vortex_session::VortexSession;
12
13use crate::ArrayRef;
14use crate::array::ArrayId;
15use crate::buffer::BufferHandle;
16use crate::dtype::DType;
17use crate::serde::ArrayChildren;
18
19/// Reference-counted array plugin.
20pub type ArrayPluginRef = Arc<dyn ArrayPlugin>;
21
22/// The wire representation produced by an in-memory array's serializer.
23///
24/// A serializer may reuse the in-memory array's buffers and children with [`Self::from_array`],
25/// or return the wire representation of another encoding. The node must hold the logical values
26/// of the array under the dtype supplied by the containing format.
27#[derive(Clone, Debug)]
28pub struct ArraySerialization {
29 /// The concrete array ID to write on the wire.
30 pub serialized_id: ArrayId,
31 /// Encoding-specific metadata written into the array node.
32 pub metadata: Vec<u8>,
33 /// Top-level buffers written for this array node.
34 pub buffers: Vec<ByteBuffer>,
35 /// Child arrays to serialize recursively.
36 pub children: Vec<ArrayRef>,
37}
38
39impl ArraySerialization {
40 /// Create a wire representation from an ID, metadata, buffers, and children.
41 pub fn new(
42 serialized_id: ArrayId,
43 metadata: Vec<u8>,
44 buffers: Vec<ByteBuffer>,
45 children: Vec<ArrayRef>,
46 ) -> Self {
47 Self {
48 serialized_id,
49 metadata,
50 buffers,
51 children,
52 }
53 }
54
55 /// Reuse an in-memory array's buffers and children with the supplied serialized metadata.
56 pub fn from_array(serialized_id: ArrayId, array: &ArrayRef, metadata: Vec<u8>) -> Self {
57 Self::new(serialized_id, metadata, array.buffers(), array.children())
58 }
59}
60
61/// The borrowed wire components passed to an array deserializer.
62pub struct ArrayDeserialization<'a> {
63 /// The exact array ID found on the wire.
64 pub serialized_id: ArrayId,
65 /// The logical dtype supplied by the containing format.
66 pub dtype: &'a DType,
67 /// The logical array length supplied by the containing format.
68 pub len: usize,
69 /// Encoding-specific metadata from the array node.
70 pub metadata: &'a [u8],
71 /// Top-level buffers referenced by the array node.
72 pub buffers: &'a [BufferHandle],
73 /// Lazily decoded child arrays referenced by the array node.
74 pub children: &'a dyn ArrayChildren,
75}
76
77impl<'a> ArrayDeserialization<'a> {
78 /// Create borrowed deserialization input from a wire ID and its serialized components.
79 pub fn new(
80 serialized_id: ArrayId,
81 dtype: &'a DType,
82 len: usize,
83 metadata: &'a [u8],
84 buffers: &'a [BufferHandle],
85 children: &'a dyn ArrayChildren,
86 ) -> Self {
87 Self {
88 serialized_id,
89 dtype,
90 len,
91 metadata,
92 buffers,
93 children,
94 }
95 }
96}
97
98/// Registry trait for serializing and deserializing an in-memory array representation.
99///
100/// A plugin writes one in-memory encoding, identified by [`id`](Self::id). It declares the wire
101/// IDs that it reads and writes separately, so it can write another encoding's wire form without
102/// replacing that encoding's reader. The serialization context validates that the chosen wire ID
103/// is permitted before it is written.
104///
105/// A plugin can retain historical read IDs after it stops writing them. A reader that predates a
106/// newer ID has no registration for it and reports it as unknown.
107pub trait ArrayPlugin: 'static + Send + Sync {
108 /// Returns the ID of the in-memory encoding that this plugin writes.
109 fn id(&self) -> ArrayId;
110
111 /// Returns the wire IDs that [`deserialize`](Self::deserialize) accepts, oldest to newest.
112 ///
113 /// [`ArraySession::register`](crate::session::ArraySession::register) makes this plugin the
114 /// reader of each ID. An ID can stay in this list after the plugin stops writing it, so that
115 /// old files stay readable.
116 ///
117 /// By default, a plugin reads only its in-memory [`id`](Self::id).
118 fn read_ids(&self) -> Vec<ArrayId> {
119 vec![self.id()]
120 }
121
122 /// Returns the wire IDs that [`serialize`](Self::serialize) may return.
123 ///
124 /// An ID in this list does not have to be in [`read_ids`](Self::read_ids). A plugin can write
125 /// its arrays in the wire form of another encoding. The plugin that owns that form reads it.
126 /// The node must hold the logical values of the array under the dtype of the array.
127 ///
128 /// By default, a plugin writes only its in-memory [`id`](Self::id).
129 fn write_ids(&self) -> Vec<ArrayId> {
130 vec![self.id()]
131 }
132
133 /// Serialize `array` to its wire representation.
134 ///
135 /// The session calls this only for arrays whose in-memory encoding matches [`id`](Self::id).
136 /// Implementations in this crate check that as well, so a direct caller gets an error rather
137 /// than a panic from the downcast.
138 ///
139 /// The returned ID must be declared by [`write_ids`](Self::write_ids). Return
140 /// `Ok(None)` when the array cannot be serialized.
141 fn serialize(
142 &self,
143 array: &ArrayRef,
144 session: &VortexSession,
145 ) -> VortexResult<Option<ArraySerialization>>;
146
147 /// Deserialize one recognized wire representation into the current in-memory array.
148 ///
149 /// `serialized_id` identifies the exact representation encountered on disk. The session only
150 /// routes IDs from [`read_ids`](Self::read_ids) here; implementations in this crate check it as
151 /// well, so a direct caller gets an error rather than a misread array. The returned
152 /// array does not necessarily have to use this plugin's in-memory ID; this supports legacy
153 /// representations that are normalized into another current in-memory array. Implementations
154 /// must validate the contract of that exact ID rather than accepting every form understood by
155 /// the current in-memory representation under an older ID.
156 fn deserialize(
157 &self,
158 parts: ArrayDeserialization<'_>,
159 session: &VortexSession,
160 ) -> VortexResult<ArrayRef>;
161
162 /// Can this plugin emit an array with the given encoding.
163 ///
164 /// By default, this is just the [ID][Self::id] of the plugin, but
165 /// can be overridden if this plugin instance supports reading/writing multiple arrays.
166 fn is_supported_encoding(&self, id: &ArrayId) -> bool {
167 self.id() == *id
168 }
169}
170
171impl Debug for dyn ArrayPlugin {
172 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
173 f.debug_tuple("ArrayPlugin").field(&self.id()).finish()
174 }
175}