wasm-link 0.4.0

A WebAssembly plugin runtime based around Wasmtime intended for building fully modular applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Plugin metadata types.
//!
//! A plugin is a WASM component that implements one [`Binding`]( crate::Binding )
//! (its **plug**) and may depend on zero or more other [`Binding`]( crate::Binding )s
//! (its **sockets**). The plug declares what the plugin exports; sockets declare what
//! the plugin expects to import from other plugins.

use std::collections::HashMap ;
use wasmtime::{ Engine, Store };
use wasmtime::component::{ Component, ResourceTable, Linker, Val };
use futures::task::Spawn ;

use crate::BindingAny ;
use crate::plugin_instance::{ PluginInstanceAsync, PluginInstanceSync };
use crate::Function ;
use crate::Remap ;

/// Trait for accessing a [`ResourceTable`] from the store's data type.
///
/// Resources that flow between plugins need to be wrapped to track ownership.
/// This trait provides access to the table where those wrapped resources are stored.
/// [`ResourceTable`] is part of the wasmtime component model; see the
/// [wasmtime docs](https://docs.rs/wasmtime/latest/wasmtime/component/) for details.
///
/// # Example
///
/// ```
/// use wasmtime::component::ResourceTable ;
/// use wasm_link::PluginContext ;
///
/// struct MyPluginData {
/// 	resource_table: ResourceTable,
/// 	// ... other fields
/// }
///
/// impl PluginContext for MyPluginData {
/// 	fn resource_table( &mut self ) -> &mut ResourceTable {
/// 		&mut self.resource_table
/// 	}
/// }
/// ```
pub trait PluginContext: Send {
	/// Returns a mutable reference to a resource table.
	fn resource_table( &mut self ) -> &mut ResourceTable ;
}

/// A WASM component bundled with its runtime context, ready for instantiation.
///
/// The component's exports (its **plug**) and imports (its **sockets**) are defined through
/// the [`crate::Binding`], not by this struct.
///
/// The `context` is consumed during linking to become the wasmtime [`Store`]( wasmtime::Store )'s data.
///
/// # Type Parameters
/// - `Ctx`: User context type that will be stored in the wasmtime [`Store`]( wasmtime::Store )
///
/// # Example
///
/// ```
/// # use wasm_link::{ Plugin, PluginContext, ResourceTable, Component, Engine, Linker };
/// # struct Ctx { resource_table: ResourceTable }
/// # impl PluginContext for Ctx {
/// # 	fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.resource_table }
/// # }
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let engine = Engine::default();
/// let linker = Linker::new( &engine );
///
/// let plugin = Plugin::new(
/// 	Component::new( &engine, "(component)" )?,
/// 	Ctx { resource_table: ResourceTable::new() },
/// ).instantiate( &engine, &linker )?;
/// # let _ = plugin;
/// # Ok(())
/// # }
/// ```
#[must_use = "call .instantiate() or .link() to create a PluginInstanceSync"]
pub struct Plugin<Ctx: 'static> {
	/// Compiled WASM component
	component: Component,
	/// User context consumed at load time to become `Store<Ctx>`
	context: Ctx,
	/// Per-interface export name remaps for this plugin
	interface_remaps: HashMap<String, Remap>,
	/// Closure that determines fuel for each function call
	#[allow( clippy::type_complexity )]
	fuel_limiter: Option<Box<dyn FnMut( &mut Store<Ctx>, &str, &str, &Function ) -> u64 + Send>>,
	/// Closure that determines epoch deadline for each function call
	#[allow( clippy::type_complexity )]
	epoch_limiter: Option<Box<dyn FnMut( &mut Store<Ctx>, &str, &str, &Function ) -> u64 + Send>>,
	/// Closure that returns a mutable reference to the `ResourceLimiter` in the context
	#[allow( clippy::type_complexity )]
	memory_limiter: Option<Box<dyn (FnMut( &mut Ctx ) -> &mut dyn wasmtime::ResourceLimiter) + Send + Sync>>,
}

impl<Ctx> Plugin<Ctx>
where
	Ctx: PluginContext + 'static,
{

	/// Creates a new plugin declaration.
	///
	/// Note that the plugin ID is not specified here - it's provided when constructing
	/// the cardinality wrapper that holds this plugin. This is done to prevent duplicate ids.
	pub fn new(
		component: Component,
		context: Ctx,
	) -> Self {
		Self {
			component,
			context,
			interface_remaps: HashMap::new(),
			fuel_limiter: None,
			epoch_limiter: None,
			memory_limiter: None,
		}
	}

	/// Sets a closure that determines the fuel limit for each function call.
	///
	/// The closure receives the store, the interface path (e.g., `"my:package/api"`),
	/// the function name, and the [`Function`] metadata. It returns the fuel to set.
	///
	/// **Warning:** Fuel consumption must be enabled in the [`Engine`]( wasmtime::Engine )
	/// via [`Config::consume_fuel`]( wasmtime::Config::consume_fuel ). If not enabled,
	/// dispatch will fail with a [`RuntimeException`]( crate::DispatchError::RuntimeException )
	/// at call time.
	///
	/// ```
	/// # use wasm_link::{ Plugin, PluginContext, ResourceTable, Component, Engine };
	/// # struct Ctx { resource_table: ResourceTable }
	/// # impl PluginContext for Ctx {
	/// # 	fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.resource_table }
	/// # }
	/// # fn example( component: Component ) {
	/// let plugin = Plugin::new( component, Ctx { resource_table: ResourceTable::new() })
	/// 	.with_fuel_limiter(| _store, _interface, _function, _metadata | 100_000 );
	/// # }
	/// ```
	pub fn with_fuel_limiter( mut self, limiter: impl FnMut( &mut Store<Ctx>, &str, &str, &Function ) -> u64 + Send + 'static ) -> Self {
		self.fuel_limiter = Some( Box::new( limiter ));
		self
	}

	/// Sets a closure that determines the epoch deadline for each function call.
	///
	/// The closure receives the store, the interface path (e.g., `"my:package/api"`),
	/// the function name, and the [`Function`] metadata. It returns the epoch deadline
	/// in ticks.
	///
	/// **Warning:** Epoch interruption must be enabled in the [`Engine`]( wasmtime::Engine )
	/// via [`Config::epoch_interruption`]( wasmtime::Config::epoch_interruption ). If not
	/// enabled, the deadline is silently ignored.
	///
	/// ```
	/// # use wasm_link::{ Plugin, PluginContext, ResourceTable, Component, Engine };
	/// # struct Ctx { resource_table: ResourceTable }
	/// # impl PluginContext for Ctx {
	/// # 	fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.resource_table }
	/// # }
	/// # fn example( component: Component ) {
	/// let plugin = Plugin::new( component, Ctx { resource_table: ResourceTable::new() })
	/// 	.with_epoch_limiter(| _store, _interface, _function, _metadata | 5 );
	/// # }
	/// ```
	pub fn with_epoch_limiter( mut self, limiter: impl FnMut( &mut Store<Ctx>, &str, &str, &Function ) -> u64 + Send + 'static ) -> Self {
		self.epoch_limiter = Some( Box::new( limiter ));
		self
	}

	/// Sets a closure that returns a mutable reference to a [`ResourceLimiter`]( wasmtime::ResourceLimiter )
	/// embedded in the plugin context.
	///
	/// The limiter is installed into the wasmtime [`Store`]( wasmtime::Store ) once at instantiation
	/// and controls memory and table growth for the lifetime of the plugin.
	///
	/// The [`ResourceLimiter`]( wasmtime::ResourceLimiter ) must be stored inside the context type `Ctx`
	/// so that wasmtime can access it through a `&mut Ctx` reference.
	///
	/// ```
	/// # use wasm_link::{ Plugin, PluginContext, ResourceTable, Component, Engine };
	/// # struct Ctx { resource_table: ResourceTable, limiter: MyLimiter }
	/// # impl PluginContext for Ctx {
	/// # 	fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.resource_table }
	/// # }
	/// # struct MyLimiter;
	/// # impl wasmtime::ResourceLimiter for MyLimiter {
	/// # 	fn memory_growing( &mut self, _: usize, _: usize, _: Option<usize> ) -> wasmtime::Result<bool> { Ok( true ) }
	/// # 	fn table_growing( &mut self, _: usize, _: usize, _: Option<usize> ) -> wasmtime::Result<bool> { Ok( true ) }
	/// # }
	/// # fn example( component: Component ) {
	/// let plugin = Plugin::new( component, Ctx { resource_table: ResourceTable::new(), limiter: MyLimiter })
	/// 	.with_memory_limiter(| ctx | &mut ctx.limiter );
	/// # }
	/// ```
	pub fn with_memory_limiter(
		mut self,
		limiter: impl (FnMut( &mut Ctx ) -> &mut dyn wasmtime::ResourceLimiter) + Send + Sync + 'static,
	) -> Self {
		self.memory_limiter = Some( Box::new( limiter ));
		self
	}

	/// Sets interface export remaps for this plugin.
	///
	/// Use this when a plugin implements the same interface types as its binding
	/// but exports one or more interfaces or functions under different names.
	///
	/// The outer map is a lookup table from requested interface name to [`Remap`].
	/// Each [`Remap`] describes where that requested interface, and optionally
	/// requested items inside it, are found in this plugin's exports.
	///
	/// All remap tables use the same direction:
	///
	/// ```text
	/// requested name -> exported name
	/// ```
	///
	/// ```
	/// # use std::collections::HashMap ;
	/// # use wasm_link::{ Plugin, PluginContext, ResourceTable, Component, Engine, Remap };
	/// # struct Ctx { resource_table: ResourceTable }
	/// # impl PluginContext for Ctx {
	/// # 	fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.resource_table }
	/// # }
	/// # fn example( engine: &Engine ) -> Result<(), Box<dyn std::error::Error>> {
	/// let plugin = Plugin::new(
	/// 	Component::new( engine, "(component)" )?,
	/// 	Ctx { resource_table: ResourceTable::new() },
	/// ).remap_interfaces( HashMap::from([
	/// 	( "root".to_string(), Remap::found_as( "legacy-root" )),
	/// ]));
	/// # let _ = plugin ;
	/// # Ok(())
	/// # }
	/// ```
	pub fn remap_interfaces( mut self, interface_remaps: HashMap<String, Remap> ) -> Self {
		self.interface_remaps = interface_remaps ;
		self
	}

	/// Links this plugin with its socket bindings and instantiates it.
	///
	/// Takes ownership of the `linker` because socket bindings are added to it. If you need
	/// to reuse the same linker for multiple plugins, clone it before passing it in.
	///
	/// # Type Parameters
	/// - `PluginId`: Must implement `Into<Val>` so plugin IDs can be passed to WASM when
	/// 	dispatching to multi-plugin sockets (the ID identifies which plugin produced each result).
	///
	/// # Errors
	/// Returns an error if linking or instantiation fails.
	pub fn link<PluginId, Sockets>(
		self,
		engine: &Engine,
		mut linker: Linker<Ctx>,
		sockets: Sockets,
	) -> Result<PluginInstanceSync<Ctx>, wasmtime::Error>
	where
		PluginId: Eq + std::hash::Hash + Clone + std::fmt::Debug + Send + Sync + Into<Val> + 'static,
		Sockets: IntoIterator,
		Sockets::Item: Into<BindingAny<PluginId, Ctx>>,
	{
		sockets.into_iter()
			.map( Into::into )
			.try_for_each(| binding | binding.add_to_linker( &mut linker ))?;
		Self::instantiate( self, engine, &linker )
	}

	/// Asynchronously links this plugin with its socket bindings and instantiates it.
	///
	/// Use this variant when any socket may suspend or uses Component Model async types.
	/// Every plugin in an asynchronously linked graph should be created with
	/// [`instantiate_async`](Self::instantiate_async) or `link_async`.
	/// Calls to the returned instance are submitted to `executor`, allowing a
	/// thread pool to drive many independent plugin stores without reserving a
	/// worker for each plugin.
	///
	/// # Example
	///
	/// ```
	/// # use wasm_link::{ BindingAny, Component, Engine, Linker, Plugin, PluginContext, ResourceTable };
	/// # struct Context { table: ResourceTable }
	/// # impl PluginContext for Context { fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.table } }
	/// # fn main() -> Result<(), Box<dyn std::error::Error>> { futures::executor::block_on( async {
	/// let engine = Engine::default();
	/// let linker = Linker::new( &engine );
	/// let executor = futures::executor::ThreadPool::new()?;
	/// let instance = Plugin::new(
	/// 	Component::new( &engine, "(component)" )?,
	/// 	Context { table: ResourceTable::new() },
	/// ).link_async(
	/// 	&engine,
	/// 	linker,
	/// 	Vec::<BindingAny<String, Context, wasm_link::PluginInstanceAsync<Context>>>::new(),
	/// 	executor,
	/// ).await?;
	/// # let _ = instance;
	/// # Ok(()) }) }
	/// ```
	///
	/// # Errors
	/// Returns an error if linking or instantiation fails.
	pub async fn link_async<PluginId, Sockets, Executor>(
		self,
		engine: &Engine,
		mut linker: Linker<Ctx>,
		sockets: Sockets,
		executor: Executor,
	) -> Result<PluginInstanceAsync<Ctx>, wasmtime::Error>
	where
		PluginId: Eq + std::hash::Hash + Clone + std::fmt::Debug + Send + Sync + Into<Val> + 'static,
		Sockets: IntoIterator,
		Sockets::Item: Into<BindingAny<PluginId, Ctx, PluginInstanceAsync<Ctx>>>,
		Executor: Spawn + Send + Sync + 'static,
	{
		sockets.into_iter()
			.map( Into::into )
			.try_for_each(| binding | binding.add_to_linker_async( &mut linker ))?;
		Self::instantiate_async( self, engine, &linker, executor ).await
	}

	/// A convenience alias for [`Plugin::link`] with 0 sockets
	///
	/// # Errors
	/// Returns an error if instantiation fails.
	pub fn instantiate(
		self,
		engine: &Engine,
		linker: &Linker<Ctx>
	) -> Result<PluginInstanceSync<Ctx>, wasmtime::Error> {
		let mut store = Store::new( engine, self.context );
		if let Some( limiter ) = self.memory_limiter { store.limiter( limiter ); }
		let instance = linker.instantiate( &mut store, &self.component )?;
		Ok( PluginInstanceSync::new_sync(
			store,
			instance,
			self.interface_remaps,
			self.fuel_limiter,
			self.epoch_limiter,
		))
	}

	/// Asynchronously instantiates this plugin.
	///
	/// This variant is required for WIT async functions, asynchronous host functions,
	/// and plugins that will be used in a graph created with [`link_async`](Self::link_async).
	/// Calls to the returned instance are submitted to `executor`. This keeps each
	/// plugin's [`Store`](wasmtime::Store) isolated while allowing a thread pool to
	/// drive many plugin stores without dedicating an idle thread to each one.
	/// Wasmtime concurrency support, which is enabled by default, must not be disabled
	/// on the `engine` used for asynchronous instances.
	///
	/// # Example
	///
	/// ```
	/// # use wasm_link::{ Component, Engine, Linker, Plugin, PluginContext, ResourceTable };
	/// # struct Context { table: ResourceTable }
	/// # impl PluginContext for Context { fn resource_table( &mut self ) -> &mut ResourceTable { &mut self.table } }
	/// # fn main() -> Result<(), Box<dyn std::error::Error>> { futures::executor::block_on( async {
	/// let engine = Engine::default();
	/// let linker = Linker::new( &engine );
	/// let executor = futures::executor::ThreadPool::new()?;
	/// let instance = Plugin::new(
	/// 	Component::new( &engine, "(component)" )?,
	/// 	Context { table: ResourceTable::new() },
	/// ).instantiate_async( &engine, &linker, executor ).await?;
	/// # let _ = instance;
	/// # Ok(()) }) }
	/// ```
	///
	/// # Errors
	/// Returns an error if instantiation fails.
	pub async fn instantiate_async<Executor>(
		self,
		engine: &Engine,
		linker: &Linker<Ctx>,
		executor: Executor,
	) -> Result<PluginInstanceAsync<Ctx>, wasmtime::Error>
	where
		Executor: Spawn + Send + Sync + 'static,
	{
		let mut store = Store::new( engine, self.context );
		if let Some( limiter ) = self.memory_limiter { store.limiter( limiter ); }
		let instance = linker.instantiate_async( &mut store, &self.component ).await?;
		Ok( PluginInstanceAsync::new(
			store,
			instance,
			self.interface_remaps,
			self.fuel_limiter,
			self.epoch_limiter,
			executor,
		))
	}

}

impl<Ctx: std::fmt::Debug + 'static> std::fmt::Debug for Plugin<Ctx> {
	fn fmt( &self, f: &mut std::fmt::Formatter<'_> ) -> std::fmt::Result {
		f.debug_struct( "Plugin" )
			.field( "component", &"<Component>" )
			.field( "context", &self.context )
			.field( "interface_remaps", &self.interface_remaps )
			.field( "fuel_limiter", &self.fuel_limiter.as_ref().map(| _ | "<closure>" ))
			.field( "epoch_limiter", &self.epoch_limiter.as_ref().map(| _ | "<closure>" ))
			.field( "memory_limiter", &self.memory_limiter.as_ref().map(| _ | "<closure>" ))
			.finish_non_exhaustive()
	}
}