Skip to main content

reifydb_sub_flow/operator/
extern_rust.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use std::{
5	collections::HashMap,
6	path::{Path, PathBuf},
7	sync::OnceLock,
8};
9
10use libloading::Symbol;
11use reifydb_core::{
12	common::{OperatorClass, WindowRequirements},
13	interface::catalog::flow::OperatorId,
14	operator_with::ApplyWith,
15};
16use reifydb_extension::loader::extern_load::ExternLoad;
17use reifydb_flow_async::operator::BoxedHostOperator;
18use reifydb_runtime::sync::rwlock::RwLock;
19use reifydb_value::{Result, config::ExtensionParams, error::Error, value::constraint::TypeConstraint};
20
21use crate::error::ExternOperatorError;
22
23pub const EXTERN_RUST_OPERATOR_MAGIC: u32 = 0x5244_424E;
24
25pub const EXTERN_RUST_ABI_TAG: u32 = 0x0308;
26
27pub type ExternRustOperatorCreateFn = fn(OperatorId, &ExtensionParams, &ApplyWith) -> Result<BoxedHostOperator>;
28
29pub struct ExternRustOperatorColumn {
30	pub name: String,
31	pub field_type: TypeConstraint,
32	pub description: String,
33}
34
35pub struct ExternRustOperatorDescriptor {
36	pub abi_tag: u32,
37	pub name: String,
38	pub version: String,
39	pub description: String,
40	pub capabilities: u32,
41	pub input_columns: Vec<ExternRustOperatorColumn>,
42	pub output_columns: Vec<ExternRustOperatorColumn>,
43	pub class: OperatorClass,
44	pub window: WindowRequirements,
45	pub unmanaged_because: Option<&'static str>,
46}
47
48pub fn extern_rust_operator_magic() -> u32 {
49	EXTERN_RUST_OPERATOR_MAGIC
50}
51
52pub fn check_extern_rust_abi_tag(abi_tag: u32) -> Result<()> {
53	if abi_tag != EXTERN_RUST_ABI_TAG {
54		return Err(Error::from(ExternOperatorError::AbiTagMismatch {
55			plugin: abi_tag,
56			host: EXTERN_RUST_ABI_TAG,
57		}));
58	}
59	Ok(())
60}
61
62pub struct LoadedExternRustOperatorInfo {
63	pub operator: String,
64	pub library_path: PathBuf,
65	pub abi_tag: u32,
66	pub version: String,
67	pub description: String,
68	pub input_columns: Vec<ExternRustOperatorColumn>,
69	pub output_columns: Vec<ExternRustOperatorColumn>,
70	pub capabilities: u32,
71	pub class: OperatorClass,
72	pub window: WindowRequirements,
73	pub unmanaged_because: Option<&'static str>,
74}
75
76static GLOBAL_EXTERN_RUST_OPERATOR_LOADER: OnceLock<RwLock<ExternRustOperatorLoader>> = OnceLock::new();
77
78pub fn extern_rust_operator_loader() -> &'static RwLock<ExternRustOperatorLoader> {
79	GLOBAL_EXTERN_RUST_OPERATOR_LOADER.get_or_init(|| RwLock::new(ExternRustOperatorLoader::new()))
80}
81
82pub struct ExternRustOperatorLoader {
83	cache: ExternLoad,
84	operator_paths: HashMap<String, PathBuf>,
85}
86
87impl ExternRustOperatorLoader {
88	fn new() -> Self {
89		Self {
90			cache: ExternLoad::new(),
91			operator_paths: HashMap::new(),
92		}
93	}
94
95	fn load_library(&mut self, path: &Path) -> Result<bool> {
96		self.cache
97			.check_magic(path, b"reifydb_extern_rust_operator_magic\0", EXTERN_RUST_OPERATOR_MAGIC)
98			.map_err(|e| {
99				Error::from(ExternOperatorError::LibraryLoadFailed {
100					path: path.display().to_string(),
101					cause: e.to_string(),
102				})
103			})
104	}
105
106	fn descriptor(&self, path: &Path) -> Result<ExternRustOperatorDescriptor> {
107		let library = self.cache.get(path).ok_or_else(|| {
108			Error::from(ExternOperatorError::LibraryNotLoaded {
109				path: path.display().to_string(),
110			})
111		})?;
112
113		// SAFETY: load_library accepted this path only after the extern-Rust operator magic symbol
114		// matched, so the object was built against this crate and declares the descriptor symbol with
115		// this signature; Symbol borrows library, which stays loaded for the call.
116		let descriptor = unsafe {
117			let get_descriptor: Symbol<fn() -> ExternRustOperatorDescriptor> =
118				library.get(b"reifydb_extern_rust_operator_descriptor\0").map_err(|e| {
119					Error::from(ExternOperatorError::SymbolNotFound {
120						symbol: "reifydb_extern_rust_operator_descriptor",
121						cause: e.to_string(),
122					})
123				})?;
124			get_descriptor()
125		};
126
127		check_extern_rust_abi_tag(descriptor.abi_tag)?;
128
129		Ok(descriptor)
130	}
131
132	pub fn register_operator(&mut self, path: &Path) -> Result<Option<LoadedExternRustOperatorInfo>> {
133		if !self.load_library(path)? {
134			return Ok(None);
135		}
136
137		let descriptor = self.descriptor(path)?;
138		self.operator_paths.insert(descriptor.name.clone(), path.to_path_buf());
139
140		Ok(Some(loaded_info(descriptor, path)))
141	}
142
143	pub fn has_operator(&self, operator: &str) -> bool {
144		self.operator_paths.contains_key(operator)
145	}
146
147	pub fn create_operator_by_name(
148		&mut self,
149		operator: &str,
150		operator_id: OperatorId,
151		params: &ExtensionParams,
152		with: &ApplyWith,
153	) -> Result<BoxedHostOperator> {
154		let path = self
155			.operator_paths
156			.get(operator)
157			.ok_or_else(|| {
158				Error::from(ExternOperatorError::OperatorNotFound {
159					operator: operator.to_string(),
160				})
161			})?
162			.clone();
163
164		if !self.load_library(&path)? {
165			return Err(Error::from(ExternOperatorError::LibraryNotLoaded {
166				path: operator.to_string(),
167			}));
168		}
169
170		self.descriptor(&path)?;
171
172		let library = self.cache.library(&path).map_err(|_| {
173			Error::from(ExternOperatorError::LibraryNotLoaded {
174				path: operator.to_string(),
175			})
176		})?;
177		// SAFETY: load_library and descriptor accepted this path, so the object was built against this
178		// crate and declares the create symbol with this signature; the copied-out pointer is called
179		// before this method returns, while &mut self still holds the cache entry that keeps it mapped.
180		let create: ExternRustOperatorCreateFn = unsafe {
181			let create_symbol: Symbol<ExternRustOperatorCreateFn> =
182				library.get(b"reifydb_extern_rust_operator_create\0").map_err(|e| {
183					Error::from(ExternOperatorError::SymbolNotFound {
184						symbol: "reifydb_extern_rust_operator_create",
185						cause: e.to_string(),
186					})
187				})?;
188			*create_symbol
189		};
190
191		create(operator_id, params, with)
192	}
193}
194
195fn loaded_info(descriptor: ExternRustOperatorDescriptor, path: &Path) -> LoadedExternRustOperatorInfo {
196	LoadedExternRustOperatorInfo {
197		operator: descriptor.name,
198		library_path: path.to_path_buf(),
199		abi_tag: descriptor.abi_tag,
200		version: descriptor.version,
201		description: descriptor.description,
202		input_columns: descriptor.input_columns,
203		output_columns: descriptor.output_columns,
204		capabilities: descriptor.capabilities,
205		class: descriptor.class,
206		window: descriptor.window,
207		unmanaged_because: descriptor.unmanaged_because,
208	}
209}
210
211impl Default for ExternRustOperatorLoader {
212	fn default() -> Self {
213		Self::new()
214	}
215}
216
217#[cfg(test)]
218mod tests {
219	use std::path::Path;
220
221	use reifydb_core::common::{OperatorClass, WindowRequirements, WindowSizeDomain};
222	use reifydb_extension::operator::extern_c::loader::check_operator_abi_tag;
223	use reifydb_sdk::flow::operator::extern_c::wire::types::OPERATOR_ABI_TAG;
224
225	use super::{EXTERN_RUST_ABI_TAG, ExternRustOperatorDescriptor, check_extern_rust_abi_tag, loaded_info};
226
227	#[test]
228	fn extern_rust_abi_tag_accepts_match_rejects_mismatch() {
229		// A mismatched tag must be refused, or an operator built against a different toolchain gets loaded.
230		assert!(check_extern_rust_abi_tag(EXTERN_RUST_ABI_TAG).is_ok());
231		assert!(check_extern_rust_abi_tag(EXTERN_RUST_ABI_TAG ^ 0x1).is_err());
232		assert!(check_extern_rust_abi_tag(0).is_err());
233	}
234
235	#[test]
236	fn extern_c_abi_tag_accepts_match_rejects_mismatch() {
237		assert!(check_operator_abi_tag(OPERATOR_ABI_TAG).is_ok());
238		assert!(check_operator_abi_tag(OPERATOR_ABI_TAG ^ 0x1).is_err());
239		assert!(check_operator_abi_tag(0).is_err());
240	}
241
242	#[test]
243	fn extern_rust_and_extern_c_tags_do_not_accept_each_other() {
244		// The two tags must reject each other, or an extern-Rust `.so` validates against the extern-C check.
245		assert_ne!(EXTERN_RUST_ABI_TAG, OPERATOR_ABI_TAG);
246		assert!(check_extern_rust_abi_tag(OPERATOR_ABI_TAG).is_err());
247		assert!(check_operator_abi_tag(EXTERN_RUST_ABI_TAG).is_err());
248	}
249
250	#[test]
251	fn the_loaded_info_carries_the_descriptor_class_window_and_reason() {
252		// A field dropped here reaches CREATE as some other class or window and skips its checks.
253		let window = WindowRequirements {
254			takes_window: true,
255			kinds: &["sliding"],
256			domain: WindowSizeDomain::Slots,
257			needs_pane: true,
258		};
259		let descriptor = ExternRustOperatorDescriptor {
260			abi_tag: EXTERN_RUST_ABI_TAG,
261			name: "probe".to_string(),
262			version: "0.0.1".to_string(),
263			description: String::new(),
264			capabilities: 0,
265			input_columns: Vec::new(),
266			output_columns: Vec::new(),
267			class: OperatorClass::Unmanaged,
268			window,
269			unmanaged_because: Some("frees its own rows"),
270		};
271		let info = loaded_info(descriptor, Path::new("/probe.so"));
272		assert_eq!(info.class, OperatorClass::Unmanaged);
273		assert_eq!(info.window, window);
274		assert_eq!(info.unmanaged_because, Some("frees its own rows"));
275	}
276}