Skip to main content

wasm_link/
binding.rs

1//! Binding specification and metadata types.
2//!
3//! A [`Binding`] defines an abstract contract specifying what plugins must implement
4//! (via plugs) or what they could depend on (via sockets). It bundles one or more WIT
5//! [`Interface`]s under a single identifier.
6
7use std::sync::{ Arc, Mutex };
8use std::collections::HashMap ;
9use wasmtime::component::{ Linker, Val };
10
11use crate::{ Interface, PluginContext };
12use crate::cardinality::{ Any, AtLeastOne, AtMostOne, Cardinality, ExactlyOne };
13use crate::plugin_instance::PluginInstance ;
14
15
16
17type PluginSockets<PluginId, Ctx, Plugins> =
18	<Plugins as Cardinality<PluginId, PluginInstance<Ctx>>>::Rebind<Mutex<PluginInstance<Ctx>>> ;
19
20type DispatchResults<PluginId, Ctx, Plugins> =
21	<PluginSockets<PluginId, Ctx, Plugins> as Cardinality<PluginId, Mutex<PluginInstance<Ctx>>>>::Rebind<
22		Result<wasmtime::component::Val, crate::DispatchError>
23	>;
24
25type DispatchVals<PluginId, Ctx, Plugins> =
26	<PluginSockets<PluginId, Ctx, Plugins> as Cardinality<PluginId, Mutex<PluginInstance<Ctx>>>>::Rebind<
27		wasmtime::component::Val
28	>;
29
30struct BindingData<PluginId, Ctx, Plugins>
31where
32	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
33	Ctx: PluginContext + 'static,
34	Plugins: Cardinality<PluginId, PluginInstance<Ctx>>,
35	PluginSockets<PluginId, Ctx, Plugins>: Send + Sync,
36{
37	package_name: String,
38	interfaces: HashMap<String, Interface>,
39	plugins: PluginSockets<PluginId, Ctx, Plugins>,
40}
41
42/// An abstract contract specifying what plugins must implement (via plugs) or what
43/// they could depend on (via sockets). It bundles one or more WIT [`Interface`]s
44/// under a single package name.
45///
46/// `Binding` is a handle to shared state. Cloning a `Binding` creates another handle
47/// to the same underlying binding, enabling shared dependencies where multiple
48/// plugins depend on the same binding.
49///
50/// ```
51/// # use std::collections::{ HashMap, HashSet };
52/// # use wasm_link::{ Binding, Interface, Function, FunctionKind, ReturnKind, Plugin, Engine, Component, Linker, ResourceTable };
53/// # use wasm_link::cardinality::ExactlyOne ;
54/// # struct Ctx { resource_table: ResourceTable }
55/// # impl wasm_link::PluginContext for Ctx {
56/// # 	fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.resource_table }
57/// # }
58/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
59/// # let engine = Engine::default();
60/// # let linker = Linker::new( &engine );
61/// # let plugin = Plugin::new( Component::new( &engine, "(component)" )?, Ctx { resource_table: ResourceTable::new() }).instantiate( &engine, &linker )?;
62/// let binding: Binding<String, Ctx> = Binding::new(
63/// 	"my:package",
64/// 	HashMap::from([
65/// 		( "api".to_string(), Interface::new(
66/// 			HashMap::from([( "get-value".into(), Function::new(
67/// 				FunctionKind::Freestanding,
68/// 				ReturnKind::MayContainResources,
69/// 			))]),
70/// 			HashSet::from([ "my-resource".to_string() ]),
71/// 		)),
72/// 	]),
73/// 	ExactlyOne( "my-plugin".to_string(), plugin ),
74/// );
75///
76/// // Clone for shared dependencies - both refer to the same binding
77/// let binding_clone = binding.clone();
78/// # Ok(())
79/// # }
80/// ```
81///
82/// # Type Parameters
83/// - `PluginId`: Unique identifier type for plugins (e.g., `String`, `UUID`)
84pub struct Binding<PluginId, Ctx, Plugins = ExactlyOne<PluginId, PluginInstance<Ctx>>>(Arc<BindingData<PluginId, Ctx, Plugins>>)
85where
86	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
87	Ctx: PluginContext + 'static,
88	Plugins: Cardinality<PluginId, PluginInstance<Ctx>> + 'static,
89	PluginSockets<PluginId, Ctx, Plugins>: Send + Sync;
90
91impl<PluginId, Ctx, Plugins> Clone for Binding<PluginId, Ctx, Plugins>
92where
93	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
94	Ctx: PluginContext + 'static,
95	Plugins: Cardinality<PluginId, PluginInstance<Ctx>> + 'static,
96	PluginSockets<PluginId, Ctx, Plugins>: Send + Sync,
97{
98	fn clone( &self ) -> Self {
99		Self( Arc::clone( &self.0 ))
100	}
101}
102
103impl<PluginId, Ctx, Plugins> std::fmt::Debug for Binding<PluginId, Ctx, Plugins>
104where
105	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + std::fmt::Debug + 'static,
106	Ctx: PluginContext + std::fmt::Debug + 'static,
107	Plugins: Cardinality<PluginId, PluginInstance<Ctx>> + 'static,
108	PluginSockets<PluginId, Ctx, Plugins>: Send + Sync,
109	PluginSockets<PluginId, Ctx, Plugins>: std::fmt::Debug,
110{
111	fn fmt( &self, f: &mut std::fmt::Formatter<'_> ) -> std::fmt::Result {
112		f.debug_struct( "Binding" )
113			.field( "package_name", &self.0.package_name )
114			.field( "interfaces", &self.0.interfaces )
115			.field( "plugins", &self.0.plugins )
116			.finish()
117	}
118}
119
120impl<PluginId, Ctx, Plugins> Binding<PluginId, Ctx, Plugins>
121where
122	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
123	Ctx: PluginContext + 'static,
124	Plugins: Cardinality<PluginId, PluginInstance<Ctx>> + 'static,
125	PluginSockets<PluginId, Ctx, Plugins>: Cardinality<PluginId, Mutex<PluginInstance<Ctx>>>,
126	PluginSockets<PluginId, Ctx, Plugins>: Send + Sync,
127{
128
129	/// Creates a new binding specification.
130	pub fn new(
131		package_name: impl Into<String>,
132		interfaces: HashMap<String, Interface>,
133		plugins: Plugins
134	) -> Self {
135		Self( Arc::new( BindingData {
136			package_name: package_name.into(),
137			interfaces,
138			plugins: plugins.map_mut( Mutex::new ),
139		}))
140	}
141
142	pub(crate) fn add_to_linker( binding: &Binding<PluginId, Ctx, Plugins>, linker: &mut Linker<Ctx> ) -> Result<(), wasmtime::Error>
143	where
144		PluginId: Into<Val>,
145		DispatchVals<PluginId, Ctx, Plugins>: Into<Val>,
146	{
147		binding.0.interfaces.iter().try_for_each(|( name, interface )| {
148			let interface_ident = format!( "{}/{}", binding.0.package_name, name );
149			interface.add_to_linker( linker, &binding.0.package_name, &interface_ident, name, binding )
150		})
151	}
152
153	pub(crate) fn plugins( &self ) -> &PluginSockets<PluginId, Ctx, Plugins> {
154		&self.0.plugins
155	}
156
157	/// Dispatches a function call to all plugins implementing this binding.
158	///
159	/// This is used for external dispatch (calling into the plugin graph from outside).
160	/// The result is wrapped in a type matching the binding's cardinality.
161	///
162	/// # Arguments
163	/// * `interface_name` - The interface name within this binding (e.g., "example")
164	/// * `function_name` - The function name within the interface (e.g., "get-value")
165	/// * `args` - Arguments to pass to the function
166	///
167	/// # Returns
168	/// A cardinality wrapper containing `Result<Val, DispatchError>` for each plugin.
169	/// For [`ReturnKind::Void`]( crate::ReturnKind::Void ), the value is an empty tuple
170	/// (`Val::Option( None )`) placeholder.
171	///
172	/// # Errors
173	/// Returns an error if the interface or function is not found in this binding.
174	pub fn dispatch(
175		&self,
176		interface_name: &str,
177		function_name: &str,
178		args: &[wasmtime::component::Val],
179	) -> Result<DispatchResults<PluginId, Ctx, Plugins>, crate::DispatchError> {
180
181		let interface = self.0.interfaces.get( interface_name )
182			.ok_or_else(|| crate::DispatchError::InvalidInterfacePath( format!( "{}/{}", self.0.package_name, interface_name )))?;
183
184		let function = interface.function( function_name )
185			.ok_or_else(|| crate::DispatchError::InvalidFunction( function_name.to_string() ))?;
186
187		Ok( self.0.plugins.map(| _, plugin | plugin
188			.lock().map_err(|_| crate::DispatchError::LockRejected )
189			.and_then(| mut lock | lock.dispatch(
190				&self.0.package_name,
191				interface_name,
192				function_name,
193				function,
194				args,
195			))
196		))
197
198	}
199
200}
201
202/// Type-erased binding wrapper for heterogeneous socket lists.
203///
204/// Use when a plugin's sockets include bindings with different cardinalities.
205#[derive( Debug, Clone )]
206pub enum BindingAny<PluginId, Ctx>
207where
208	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
209	Ctx: PluginContext + 'static,
210{
211	/// Exactly one plugin implementation.
212	ExactlyOne( Binding<PluginId, Ctx, ExactlyOne<PluginId, PluginInstance<Ctx>>> ),
213	/// Zero or one plugin implementation.
214	AtMostOne( Binding<PluginId, Ctx, AtMostOne<PluginId, PluginInstance<Ctx>>> ),
215	/// One or more plugin implementations.
216	AtLeastOne( Binding<PluginId, Ctx, AtLeastOne<PluginId, PluginInstance<Ctx>>> ),
217	/// Zero or more plugin implementations.
218	Any( Binding<PluginId, Ctx, Any<PluginId, PluginInstance<Ctx>>> ),
219}
220
221impl<PluginId, Ctx> BindingAny<PluginId, Ctx>
222where
223	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + Into<Val> + 'static,
224	Ctx: PluginContext + 'static,
225{
226	pub(crate) fn add_to_linker( &self, linker: &mut Linker<Ctx> ) -> Result<(), wasmtime::Error> {
227		match self {
228			Self::ExactlyOne( binding ) => Binding::add_to_linker( binding, linker ),
229			Self::AtMostOne( binding ) => Binding::add_to_linker( binding, linker ),
230			Self::AtLeastOne( binding ) => Binding::add_to_linker( binding, linker ),
231			Self::Any( binding ) => Binding::add_to_linker( binding, linker ),
232		}
233	}
234}
235
236impl<PluginId, Ctx> From<Binding<PluginId, Ctx, ExactlyOne<PluginId, PluginInstance<Ctx>>>> for BindingAny<PluginId, Ctx>
237where
238	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
239	Ctx: PluginContext + 'static,
240{
241	fn from( binding: Binding<PluginId, Ctx, ExactlyOne<PluginId, PluginInstance<Ctx>>> ) -> Self {
242		Self::ExactlyOne( binding )
243	}
244}
245
246impl<PluginId, Ctx> From<Binding<PluginId, Ctx, AtMostOne<PluginId, PluginInstance<Ctx>>>> for BindingAny<PluginId, Ctx>
247where
248	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
249	Ctx: PluginContext + 'static,
250{
251	fn from( binding: Binding<PluginId, Ctx, AtMostOne<PluginId, PluginInstance<Ctx>>> ) -> Self {
252		Self::AtMostOne( binding )
253	}
254}
255
256impl<PluginId, Ctx> From<Binding<PluginId, Ctx, AtLeastOne<PluginId, PluginInstance<Ctx>>>> for BindingAny<PluginId, Ctx>
257where
258	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
259	Ctx: PluginContext + 'static,
260{
261	fn from( binding: Binding<PluginId, Ctx, AtLeastOne<PluginId, PluginInstance<Ctx>>> ) -> Self {
262		Self::AtLeastOne( binding )
263	}
264}
265
266impl<PluginId, Ctx> From<Binding<PluginId, Ctx, Any<PluginId, PluginInstance<Ctx>>>> for BindingAny<PluginId, Ctx>
267where
268	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
269	Ctx: PluginContext + 'static,
270{
271	fn from( binding: Binding<PluginId, Ctx, Any<PluginId, PluginInstance<Ctx>>> ) -> Self {
272		Self::Any( binding )
273	}
274}
275
276impl<PluginId, Ctx, Plugins> Binding<PluginId, Ctx, Plugins>
277where
278	PluginId: std::hash::Hash + Eq + Clone + Send + Sync + 'static,
279	Ctx: PluginContext + 'static,
280	Plugins: Cardinality<PluginId, PluginInstance<Ctx>>,
281	PluginSockets<PluginId, Ctx, Plugins>: Send + Sync,
282	BindingAny<PluginId, Ctx>: From<Binding<PluginId, Ctx, Plugins>>,
283{
284	/// Converts this binding into a type-erased [`BindingAny`] for heterogeneous socket lists.
285	pub fn into_any( self ) -> BindingAny<PluginId, Ctx> {
286		self.into()
287	}
288}