1#![doc = include_str!("../README.md")]
2
3use std::fmt;
4use std::marker::PhantomData;
5use std::path::Path;
6
7use serde_json::Value;
8use wasmtime::component::{Component, HasData, Linker, ResourceAny, ResourceTable};
9use wasmtime::{AsContextMut, Engine};
10use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
11
12pub use wasmtime;
13pub use wasmtime_wasi;
14
15pub mod bindings {
22 pub mod runtime {
27 wasmtime::component::bindgen!({
28 path: ["wit/workflow.wit", "wit/runtime.wit"],
29 inline: "package xmachines:hosts;
30 world runtime {
31 import xmachines:runtime/implementations@0.4.0;
32 export xmachines:runtime/actors@0.4.0;
33 }",
34 world: "xmachines:hosts/runtime",
35 imports: { default: trappable },
36 });
37 }
38
39 pub mod runtime_runs {
42 wasmtime::component::bindgen!({
43 path: ["wit/workflow.wit", "wit/runtime.wit"],
44 inline: "package xmachines:hosts;
45 world runtime-runs {
46 export xmachines:workflow/runs@0.1.0;
47 }",
48 world: "xmachines:hosts/runtime-runs",
49 });
50 }
51
52 pub mod machine {
55 wasmtime::component::bindgen!({
56 path: ["wit/workflow.wit", "wit/machine.wit"],
57 inline: "package xmachines:hosts;
58 world machine {
59 export xmachines:machine/info@0.3.0;
60 export xmachines:machine/actors@0.3.0;
61 }",
62 world: "xmachines:hosts/machine",
63 });
64 }
65
66 pub mod machine_runs {
69 wasmtime::component::bindgen!({
70 path: ["wit/workflow.wit", "wit/machine.wit"],
71 inline: "package xmachines:hosts;
72 world machine-runs {
73 export xmachines:workflow/machine-runs@0.1.0;
74 }",
75 world: "xmachines:hosts/machine-runs",
76 });
77 }
78}
79
80use bindings::runtime::xmachines::runtime::implementations;
81
82#[derive(Debug)]
84#[non_exhaustive]
85pub enum Error {
86 Wasmtime(wasmtime::Error),
89 Component(String),
93 Rejected { message: String, data: Option<Value> },
99 Fault { code: String, message: String },
106 RunFault { code: String, message: String, seq: u64 },
111 Json(serde_json::Error),
113}
114
115impl fmt::Display for Error {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 match self {
118 Error::Wasmtime(e) => fmt::Display::fmt(e, f),
119 Error::Component(message) => f.write_str(message),
120 Error::Rejected { message, .. } => write!(f, "rejected: {message}"),
121 Error::Fault { code, message } => write!(f, "{code}: {message}"),
122 Error::RunFault { code, message, seq } => write!(f, "{code} (chunk {seq}): {message}"),
123 Error::Json(e) => fmt::Display::fmt(e, f),
124 }
125 }
126}
127
128impl std::error::Error for Error {
129 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
130 match self {
132 Error::Wasmtime(e) => e.source(),
133 Error::Json(e) => e.source(),
134 Error::Component(_) | Error::Rejected { .. } | Error::Fault { .. } | Error::RunFault { .. } => None,
135 }
136 }
137}
138
139impl From<wasmtime::Error> for Error {
140 fn from(e: wasmtime::Error) -> Self {
143 match e.downcast::<Error>() {
144 Ok(e) => e,
145 Err(e) => Error::Wasmtime(e),
146 }
147 }
148}
149
150impl From<serde_json::Error> for Error {
151 fn from(e: serde_json::Error) -> Self {
152 Error::Json(e)
153 }
154}
155
156pub fn engine() -> Result<Engine, Error> {
160 Ok(Engine::new(&wasmtime::Config::new())?)
161}
162
163pub fn load(engine: &Engine, bytes: &[u8]) -> Result<Component, Error> {
165 Ok(Component::from_binary(engine, bytes)?)
166}
167
168pub fn load_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component, Error> {
170 Ok(Component::from_file(engine, path)?)
171}
172
173pub trait Implementations {
195 fn guard(&mut self, name: &str, params: Option<Value>, context: Value, event: Value) -> Result<bool, String> {
199 let _ = (params, context, event);
200 Err(missing("guard", name))
201 }
202
203 fn action(&mut self, name: &str, params: Option<Value>) -> Result<(), String> {
208 let _ = params;
209 Err(missing("action", name))
210 }
211
212 fn delay(&mut self, name: &str, context: Value, event: Value) -> Result<u64, String> {
214 let _ = (context, event);
215 Err(missing("delay", name))
216 }
217
218 fn expr(&mut self, name: &str, scope: Value) -> Result<Value, String> {
221 let _ = scope;
222 Err(missing("expr", name))
223 }
224
225 fn context_expr(&mut self, name: &str, input: Option<Value>) -> Result<Value, String> {
228 let _ = input;
229 Err(missing("context-expr", name))
230 }
231
232 fn evaluate(&mut self, code: Value, scope: Value) -> Result<Value, String> {
237 let _ = scope;
238 Err(missing("evaluate", code.get("lang").and_then(Value::as_str).unwrap_or_default()))
239 }
240}
241
242fn missing(import: &str, name: &str) -> String {
246 format!("missing implementation: {import} \"{name}\"")
247}
248
249impl Implementations for () {}
251
252pub struct Host<I> {
256 pub wasi: WasiCtx,
258 pub table: ResourceTable,
260 pub implementations: I,
262}
263
264impl<I> Host<I> {
265 pub fn new(wasi: WasiCtx, implementations: I) -> Self {
267 Host { wasi, table: ResourceTable::new(), implementations }
268 }
269}
270
271impl<I: Send> WasiView for Host<I> {
272 fn ctx(&mut self) -> WasiCtxView<'_> {
273 WasiCtxView { ctx: &mut self.wasi, table: &mut self.table }
274 }
275}
276
277impl<I: Implementations> Implementations for Host<I> {
278 fn guard(&mut self, name: &str, params: Option<Value>, context: Value, event: Value) -> Result<bool, String> {
279 self.implementations.guard(name, params, context, event)
280 }
281
282 fn action(&mut self, name: &str, params: Option<Value>) -> Result<(), String> {
283 self.implementations.action(name, params)
284 }
285
286 fn delay(&mut self, name: &str, context: Value, event: Value) -> Result<u64, String> {
287 self.implementations.delay(name, context, event)
288 }
289
290 fn expr(&mut self, name: &str, scope: Value) -> Result<Value, String> {
291 self.implementations.expr(name, scope)
292 }
293
294 fn context_expr(&mut self, name: &str, input: Option<Value>) -> Result<Value, String> {
295 self.implementations.context_expr(name, input)
296 }
297
298 fn evaluate(&mut self, code: Value, scope: Value) -> Result<Value, String> {
299 self.implementations.evaluate(code, scope)
300 }
301}
302
303struct Imports<'a, T: ?Sized>(&'a mut T);
305
306struct HasImports<T: ?Sized>(PhantomData<T>);
308
309impl<T: ?Sized + 'static> HasData for HasImports<T> {
310 type Data<'a> = Imports<'a, T>;
311}
312
313fn parse_import(text: &str) -> wasmtime::Result<Value> {
315 serde_json::from_str(text).map_err(|e| wasmtime::Error::new(Error::Json(e)))
316}
317
318impl<T: Implementations + ?Sized> implementations::Host for Imports<'_, T> {
319 fn guard(
320 &mut self,
321 name: String,
322 params: Option<String>,
323 context: String,
324 event: String,
325 ) -> wasmtime::Result<Result<bool, String>> {
326 let params = params.as_deref().map(parse_import).transpose()?;
327 Ok(self.0.guard(&name, params, parse_import(&context)?, parse_import(&event)?))
328 }
329
330 fn action(&mut self, name: String, params: Option<String>) -> wasmtime::Result<Result<(), String>> {
331 let params = params.as_deref().map(parse_import).transpose()?;
332 Ok(self.0.action(&name, params))
333 }
334
335 fn delay(&mut self, name: String, context: String, event: String) -> wasmtime::Result<Result<u64, String>> {
336 Ok(self.0.delay(&name, parse_import(&context)?, parse_import(&event)?))
337 }
338
339 fn expr(&mut self, name: String, scope: String) -> wasmtime::Result<Result<String, String>> {
340 Ok(self.0.expr(&name, parse_import(&scope)?).map(|v| v.to_string()))
341 }
342
343 fn context_expr(&mut self, name: String, input: Option<String>) -> wasmtime::Result<Result<String, String>> {
344 let input = input.as_deref().map(parse_import).transpose()?;
345 Ok(self.0.context_expr(&name, input).map(|v| v.to_string()))
346 }
347
348 fn evaluate(&mut self, code: String, scope: String) -> wasmtime::Result<String> {
349 let result = self.0.evaluate(parse_import(&code)?, parse_import(&scope)?);
350 Ok(result.unwrap_or_else(|error| serde_json::json!({ "error": error })).to_string())
351 }
352}
353
354fn parse(text: &str) -> Result<Value, Error> {
356 Ok(serde_json::from_str(text)?)
357}
358
359fn parse_all(texts: Vec<String>) -> Result<Vec<Value>, Error> {
361 texts.iter().map(|t| parse(t)).collect()
362}
363
364pub struct Runtime {
367 bindings: bindings::runtime::Runtime,
368 runs: Option<bindings::runtime_runs::RuntimeRuns>,
370}
371
372impl Runtime {
373 pub fn linker<T: WasiView + Implementations + 'static>(engine: &Engine) -> Result<Linker<T>, Error> {
377 let mut linker = Linker::new(engine);
378 Self::add_to_linker(&mut linker)?;
379 Ok(linker)
380 }
381
382 pub fn add_to_linker<T: WasiView + Implementations + 'static>(linker: &mut Linker<T>) -> Result<(), Error> {
386 wasmtime_wasi::p2::add_to_linker_sync(linker)?;
387 implementations::add_to_linker::<T, HasImports<T>>(linker, |data| Imports(data))?;
388 Ok(())
389 }
390
391 pub fn instantiate<T: 'static>(
393 store: impl AsContextMut<Data = T>,
394 component: &Component,
395 linker: &Linker<T>,
396 ) -> Result<Self, Error> {
397 let mut store = store;
398 let instance = linker.instantiate(&mut store, component)?;
399 let bindings = bindings::runtime::Runtime::new(&mut store, &instance)?;
400 let runs = match exports_workflow(component, store.as_context_mut().engine()) {
403 true => Some(bindings::runtime_runs::RuntimeRuns::new(&mut store, &instance).map_err(unreadable_runs)?),
404 false => None,
405 };
406 Ok(Runtime { bindings, runs })
407 }
408
409 pub fn has_runs(&self) -> bool {
412 self.runs.is_some()
413 }
414
415 pub fn bindings(&self) -> &bindings::runtime::Runtime {
417 &self.bindings
418 }
419}
420
421pub struct Machine {
424 bindings: bindings::machine::Machine,
425 runs: Option<bindings::machine_runs::MachineRuns>,
427}
428
429#[derive(Debug, Clone, PartialEq)]
431pub struct Info {
432 pub id: String,
434 pub version: Option<String>,
436 pub definition: Value,
438 pub schemas: Value,
441}
442
443impl Machine {
444 pub fn linker<T: WasiView + 'static>(engine: &Engine) -> Result<Linker<T>, Error> {
447 let mut linker = Linker::new(engine);
448 Self::add_to_linker(&mut linker)?;
449 Ok(linker)
450 }
451
452 pub fn add_to_linker<T: WasiView + 'static>(linker: &mut Linker<T>) -> Result<(), Error> {
454 Ok(wasmtime_wasi::p2::add_to_linker_sync(linker)?)
455 }
456
457 pub fn instantiate<T: 'static>(
459 store: impl AsContextMut<Data = T>,
460 component: &Component,
461 linker: &Linker<T>,
462 ) -> Result<Self, Error> {
463 let mut store = store;
464 let instance = linker.instantiate(&mut store, component)?;
465 let bindings = bindings::machine::Machine::new(&mut store, &instance)?;
466 let runs = match exports_workflow(component, store.as_context_mut().engine()) {
469 true => Some(bindings::machine_runs::MachineRuns::new(&mut store, &instance).map_err(unreadable_runs)?),
470 false => None,
471 };
472 Ok(Machine { bindings, runs })
473 }
474
475 pub fn info(&self, mut store: impl AsContextMut) -> Result<Info, Error> {
477 let info = self.bindings.xmachines_machine_info();
478 Ok(Info {
479 id: info.call_id(&mut store)?,
480 version: info.call_version(&mut store)?,
481 definition: parse(&info.call_definition(&mut store)?)?,
482 schemas: parse(&info.call_schemas(&mut store)?)?,
483 })
484 }
485
486 pub fn has_runs(&self) -> bool {
489 self.runs.is_some()
490 }
491
492 pub fn bindings(&self) -> &bindings::machine::Machine {
494 &self.bindings
495 }
496}
497
498fn contract_error(text: String) -> Error {
503 let Ok(Value::Object(mut e)) = serde_json::from_str::<Value>(&text) else { return Error::Component(text) };
504 let message = |v: &serde_json::Map<String, Value>| v.get("message").and_then(Value::as_str).map(str::to_owned);
505 match (e.remove("rejected"), e.get("code").and_then(Value::as_str)) {
506 (Some(Value::Object(mut rejected)), None) => match message(&rejected) {
507 Some(message) => Error::Rejected { message, data: rejected.remove("data") },
508 None => Error::Component(text),
509 },
510 (None, Some(code)) => match message(&e) {
511 Some(message) => Error::Fault { code: code.to_owned(), message },
512 None => Error::Component(text),
513 },
514 _ => Error::Component(text),
515 }
516}
517
518pub struct RuntimeMachine {
525 actors: bindings::runtime::exports::xmachines::runtime::actors::Guest,
526 resource: ResourceAny,
527}
528
529impl RuntimeMachine {
530 pub fn load(
535 mut store: impl AsContextMut,
536 runtime: &Runtime,
537 definition: &Value,
538 options: &Value,
539 ) -> Result<Self, Error> {
540 let actors = runtime.bindings.xmachines_runtime_actors().clone();
541 let (definition, options) = (definition.to_string(), options.to_string());
542 let resource = actors.machine().call_load(&mut store, &definition, &options)?.map_err(contract_error)?;
543 Ok(RuntimeMachine { actors, resource })
544 }
545
546 pub fn start(&self, mut store: impl AsContextMut, options: &Value, now: u64) -> Result<Actor, Error> {
552 let options = options.to_string();
553 let resource =
554 self.actors.machine().call_start(&mut store, self.resource, &options, now)?.map_err(contract_error)?;
555 Ok(Actor { actors: self.actors.clone(), resource })
556 }
557
558 pub fn restore(&self, mut store: impl AsContextMut, snapshot: &Value) -> Result<Actor, Error> {
562 let snapshot = snapshot.to_string();
563 let resource =
564 self.actors.machine().call_restore(&mut store, self.resource, &snapshot)?.map_err(contract_error)?;
565 Ok(Actor { actors: self.actors.clone(), resource })
566 }
567
568 pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
570 Ok(self.resource.resource_drop(&mut store)?)
571 }
572}
573
574pub struct Actor {
578 actors: bindings::runtime::exports::xmachines::runtime::actors::Guest,
579 resource: ResourceAny,
580}
581
582pub struct TypedMachine {
587 actors: bindings::machine::exports::xmachines::machine::actors::Guest,
588 resource: ResourceAny,
589}
590
591impl TypedMachine {
592 pub fn load(mut store: impl AsContextMut, machine: &Machine, options: &Value) -> Result<Self, Error> {
596 let actors = machine.bindings.xmachines_machine_actors().clone();
597 let resource = actors.machine().call_load(&mut store, &options.to_string())?.map_err(contract_error)?;
598 Ok(TypedMachine { actors, resource })
599 }
600
601 pub fn start(&self, mut store: impl AsContextMut, options: &Value, now: u64) -> Result<MachineActor, Error> {
604 let options = options.to_string();
605 let resource =
606 self.actors.machine().call_start(&mut store, self.resource, &options, now)?.map_err(contract_error)?;
607 Ok(MachineActor { actors: self.actors.clone(), resource })
608 }
609
610 pub fn restore(&self, mut store: impl AsContextMut, snapshot: &Value) -> Result<MachineActor, Error> {
614 let snapshot = snapshot.to_string();
615 let resource =
616 self.actors.machine().call_restore(&mut store, self.resource, &snapshot)?.map_err(contract_error)?;
617 Ok(MachineActor { actors: self.actors.clone(), resource })
618 }
619
620 pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
622 Ok(self.resource.resource_drop(&mut store)?)
623 }
624}
625
626pub struct MachineActor {
630 actors: bindings::machine::exports::xmachines::machine::actors::Guest,
631 resource: ResourceAny,
632}
633
634macro_rules! actor_calls {
636 ($actor:ident) => {
637 impl $actor {
638 pub fn apply(&self, mut store: impl AsContextMut, batch: &Value) -> Result<Value, Error> {
650 let step = self
651 .actors
652 .actor()
653 .call_apply(&mut store, self.resource, &batch.to_string())?
654 .map_err(contract_error)?;
655 parse(&step)
656 }
657
658 pub fn can(&self, mut store: impl AsContextMut, event: &Value) -> Result<bool, Error> {
662 self.actors.actor().call_can(&mut store, self.resource, &event.to_string())?.map_err(Error::Component)
663 }
664
665 pub fn persist(&self, mut store: impl AsContextMut) -> Result<Value, Error> {
667 parse(&self.actors.actor().call_persist(&mut store, self.resource)?)
668 }
669
670 pub fn take_system_emitted(&self, mut store: impl AsContextMut) -> Result<Vec<Value>, Error> {
675 parse_all(self.actors.actor().call_take_system_emitted(&mut store, self.resource)?)
676 }
677
678 pub fn take_logs(&self, mut store: impl AsContextMut) -> Result<Vec<Value>, Error> {
681 parse_all(self.actors.actor().call_take_logs(&mut store, self.resource)?)
682 }
683
684 pub fn stop(&self, mut store: impl AsContextMut) -> Result<(), Error> {
686 self.actors.actor().call_stop(&mut store, self.resource)?.map_err(Error::Component)
687 }
688
689 pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
692 Ok(self.resource.resource_drop(&mut store)?)
693 }
694 }
695 };
696}
697
698actor_calls!(Actor);
699actor_calls!(MachineActor);
700
701fn exports_workflow(component: &Component, engine: &Engine) -> bool {
704 component.component_type().exports(engine).any(|(name, _)| name.starts_with("xmachines:workflow/"))
705}
706
707fn unreadable_runs(error: wasmtime::Error) -> Error {
710 Error::Component(format!(
711 "the component exports runs of xmachines:workflow that this host, of xmachines:workflow@0.1.0, cannot read: {error}"
712 ))
713}
714
715fn no_runs() -> Error {
718 Error::Component("the component exports no runs of xmachines:workflow: it was built before them".into())
719}
720
721fn run_fault(text: String) -> Error {
725 let Ok(Value::Object(e)) = serde_json::from_str::<Value>(&text) else { return Error::Component(text) };
726 match (e.get("code").and_then(Value::as_str), e.get("message").and_then(Value::as_str), e.get("seq")) {
727 (Some(code), Some(message), Some(seq)) if seq.is_u64() => {
728 Error::RunFault { code: code.to_owned(), message: message.to_owned(), seq: seq.as_u64().unwrap_or(0) }
729 }
730 _ => Error::Component(text),
731 }
732}
733
734pub struct RunsMachine {
738 runs: bindings::runtime_runs::exports::xmachines::workflow::runs::Guest,
739 resource: ResourceAny,
740}
741
742impl RunsMachine {
743 pub fn load(
748 mut store: impl AsContextMut,
749 runtime: &Runtime,
750 definition: &Value,
751 options: &Value,
752 ) -> Result<Self, Error> {
753 let runs = runtime.runs.as_ref().ok_or_else(no_runs)?.xmachines_workflow_runs().clone();
754 let (definition, options) = (definition.to_string(), options.to_string());
755 let resource = runs.machine().call_load(&mut store, &definition, &options)?.map_err(run_fault)?;
756 Ok(RunsMachine { runs, resource })
757 }
758
759 pub fn open(&self, mut store: impl AsContextMut, options: &Value) -> Result<(Run, Vec<Value>), Error> {
763 let (resource, opening) =
764 self.runs.machine().call_open(&mut store, self.resource, &options.to_string())?.map_err(run_fault)?;
765 Ok((Run { runs: self.runs.clone(), resource }, parse_all(opening)?))
766 }
767
768 pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
770 Ok(self.resource.resource_drop(&mut store)?)
771 }
772}
773
774pub struct Run {
778 runs: bindings::runtime_runs::exports::xmachines::workflow::runs::Guest,
779 resource: ResourceAny,
780}
781
782pub struct MachineRun {
785 runs: bindings::machine_runs::exports::xmachines::workflow::machine_runs::Guest,
786 resource: ResourceAny,
787}
788
789impl MachineRun {
790 pub fn open(mut store: impl AsContextMut, machine: &Machine, options: &Value) -> Result<(Self, Vec<Value>), Error> {
793 let runs = machine.runs.as_ref().ok_or_else(no_runs)?.xmachines_workflow_machine_runs().clone();
794 let (resource, opening) = runs.run().call_open(&mut store, &options.to_string())?.map_err(run_fault)?;
795 Ok((MachineRun { runs, resource }, parse_all(opening)?))
796 }
797}
798
799macro_rules! run_calls {
801 ($run:ident) => {
802 impl $run {
803 pub fn apply(&self, mut store: impl AsContextMut, chunk: &Value) -> Result<Vec<Value>, Error> {
808 let records =
809 self.runs.run().call_apply(&mut store, self.resource, &chunk.to_string())?.map_err(run_fault)?;
810 parse_all(records)
811 }
812
813 pub fn can(&self, mut store: impl AsContextMut, event: &Value) -> Result<bool, Error> {
815 Ok(self.runs.run().call_can(&mut store, self.resource, &event.to_string())?)
816 }
817
818 pub fn checkpoint(&self, mut store: impl AsContextMut) -> Result<Value, Error> {
821 parse(&self.runs.run().call_checkpoint(&mut store, self.resource)?)
822 }
823
824 pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
826 Ok(self.resource.resource_drop(&mut store)?)
827 }
828 }
829 };
830}
831
832run_calls!(Run);
833run_calls!(MachineRun);
834
835#[cfg(test)]
836mod tests {
837 use super::*;
838
839 #[test]
840 fn a_component_exports_workflow_by_any_interface_of_the_package() {
841 let engine = Engine::default();
842 let of = |export: &str| {
843 let text = format!(r#"(component (instance $i) (export "{export}" (instance $i)))"#);
844 exports_workflow(&Component::new(&engine, text).unwrap(), &engine)
845 };
846 assert!(of("xmachines:workflow/runs@0.1.0"));
847 assert!(of("xmachines:workflow/runs@0.2.0"));
848 assert!(!of("xmachines:runtime/engine@0.1.0"));
849 }
850}