1#![forbid(unsafe_code)]
9
10use std::{
11 collections::{BTreeMap, BTreeSet},
12 fmt, io,
13 path::{Path, PathBuf},
14 sync::{
15 Arc, Mutex,
16 atomic::{AtomicBool, Ordering},
17 mpsc::{self, Receiver, Sender, SyncSender},
18 },
19 thread::{self, JoinHandle},
20 time::Duration,
21};
22
23use dekopon_capability::EffectKind;
24use dekopon_core::{CapabilityId, CommandWordConflict, ProviderId};
25pub use dekopon_provider_sdk::{
26 ComponentFailure, ComponentResponse, ProviderApiVersion, ProviderCapability, ProviderManifest,
27};
28use serde::Serialize;
29use serde_json::Value;
30use thiserror::Error;
31use wasmtime::component::{Component, Linker};
32use wasmtime::{Cache, CacheConfig, Config, Engine, Store, StoreLimits, StoreLimitsBuilder};
33
34mod bindings {
35 wasmtime::component::bindgen!({
36 path: "wit",
37 world: "provider",
38 });
39}
40
41pub const PROVIDER_WIT: &str = include_str!("../wit/provider.wit");
43
44pub const DEFAULT_MAX_MEMORY_BYTES: usize = 64 * 1024 * 1024;
46pub const DEFAULT_MAX_TABLE_ELEMENTS: usize = 100_000;
48pub const DEFAULT_MAX_INSTANCES: usize = 64;
50pub const DEFAULT_MAX_TABLES: usize = 16;
52pub const DEFAULT_MAX_MEMORIES: usize = 4;
54pub const DEFAULT_MAX_INPUT_BYTES: usize = 1024 * 1024;
56pub const DEFAULT_MAX_OUTPUT_BYTES: usize = 1024 * 1024;
58pub const DEFAULT_FUEL: u64 = 10_000_000;
60pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
62
63#[derive(Clone, Debug, Eq, PartialEq)]
65pub struct HostLimits {
66 pub max_memory_bytes: usize,
71 pub max_table_elements: usize,
73 pub max_instances: usize,
75 pub max_tables: usize,
77 pub max_memories: usize,
79 pub max_input_bytes: usize,
81 pub max_output_bytes: usize,
87 pub fuel: u64,
89 pub timeout: Duration,
91}
92
93impl Default for HostLimits {
94 fn default() -> Self {
95 Self {
96 max_memory_bytes: DEFAULT_MAX_MEMORY_BYTES,
97 max_table_elements: DEFAULT_MAX_TABLE_ELEMENTS,
98 max_instances: DEFAULT_MAX_INSTANCES,
99 max_tables: DEFAULT_MAX_TABLES,
100 max_memories: DEFAULT_MAX_MEMORIES,
101 max_input_bytes: DEFAULT_MAX_INPUT_BYTES,
102 max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
103 fuel: DEFAULT_FUEL,
104 timeout: DEFAULT_TIMEOUT,
105 }
106 }
107}
108
109#[derive(Clone, Debug, Default, Eq, PartialEq)]
115pub struct HostOptions {
116 pub compile_cache_dir: Option<PathBuf>,
125}
126
127#[derive(Clone, Debug, PartialEq, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct InvocationOutput {
131 pub provider: ProviderId,
133 pub capability: CapabilityId,
135 pub output: Value,
137}
138
139struct Runtime {
140 engine: Engine,
141 limits: HostLimits,
142 execution: Mutex<()>,
143 deadline: DeadlineWorker,
144}
145
146impl Runtime {
147 fn new(limits: HostLimits, options: &HostOptions) -> Result<Self, ProviderHostError> {
148 validate_limits(&limits)?;
149
150 let mut config = Config::new();
151 config.wasm_component_model(true);
152 config.consume_fuel(true);
153 config.epoch_interruption(true);
154 if let Some(directory) = &options.compile_cache_dir {
155 let mut cache = CacheConfig::new();
156 cache.with_directory(directory);
157 config.cache(Some(Cache::new(cache).map_err(|source| {
158 ProviderHostError::CompileCache {
159 path: directory.clone(),
160 source,
161 }
162 })?));
163 }
164 let engine = Engine::new(&config).map_err(|source| ProviderHostError::Engine { source })?;
165 let deadline = DeadlineWorker::start(engine.clone())?;
166
167 Ok(Self {
168 engine,
169 limits,
170 execution: Mutex::new(()),
171 deadline,
172 })
173 }
174
175 fn store(&self) -> Result<Store<StoreState>, ProviderHostError> {
176 let store_limits = StoreLimitsBuilder::new()
177 .memory_size(self.limits.max_memory_bytes)
178 .table_elements(self.limits.max_table_elements)
179 .instances(self.limits.max_instances)
180 .tables(self.limits.max_tables)
181 .memories(self.limits.max_memories)
182 .build();
183 let mut store = Store::new(
184 &self.engine,
185 StoreState {
186 limits: store_limits,
187 },
188 );
189 store.limiter(|state| &mut state.limits);
190 store
191 .set_fuel(self.limits.fuel)
192 .map_err(|source| ProviderHostError::Store { source })?;
193 store.set_epoch_deadline(1);
194 Ok(store)
195 }
196}
197
198#[derive(Debug)]
199struct StoreState {
200 limits: StoreLimits,
201}
202
203pub struct WasmProvider {
205 runtime: Arc<Runtime>,
206 component: Component,
207 source: PathBuf,
208 manifest: ProviderManifest,
209}
210
211impl fmt::Debug for WasmProvider {
212 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
213 formatter
214 .debug_struct("WasmProvider")
215 .field("source", &self.source)
216 .field("manifest", &self.manifest)
217 .finish_non_exhaustive()
218 }
219}
220
221impl WasmProvider {
222 fn load(runtime: Arc<Runtime>, source: PathBuf) -> Result<Self, ProviderHostError> {
223 let compile_span = tracing::info_span!(
224 "provider.compile",
225 provider.path = %source.display()
226 );
227 let component = {
228 let _entered = compile_span.enter();
229 Component::from_file(&runtime.engine, &source).map_err(|error| {
230 ProviderHostError::Compile {
231 path: source.clone(),
232 source: error,
233 }
234 })?
235 };
236
237 let manifest_json = describe_component(&runtime, &component, &source)?;
238 if manifest_json.len() > runtime.limits.max_output_bytes {
239 return Err(ProviderHostError::OutputTooLarge {
240 provider: source.display().to_string(),
241 length: manifest_json.len(),
242 maximum: runtime.limits.max_output_bytes,
243 });
244 }
245 let manifest =
246 serde_json::from_str::<ProviderManifest>(&manifest_json).map_err(|error| {
247 ProviderHostError::InvalidManifest {
248 path: source.clone(),
249 source: error,
250 }
251 })?;
252 validate_manifest(&manifest, &source)?;
253
254 Ok(Self {
255 runtime,
256 component,
257 source,
258 manifest,
259 })
260 }
261}
262
263impl WasmProvider {
264 #[must_use]
266 pub const fn manifest(&self) -> &ProviderManifest {
267 &self.manifest
268 }
269
270 pub fn invoke(
279 &self,
280 capability: &CapabilityId,
281 input: &Value,
282 ) -> Result<Value, ProviderHostError> {
283 if !self
284 .manifest
285 .capabilities
286 .iter()
287 .any(|candidate| &candidate.id == capability)
288 {
289 return Err(ProviderHostError::ProviderDoesNotImplement {
290 provider: self.manifest.id.clone(),
291 capability: capability.clone(),
292 });
293 }
294
295 if !input.is_object() {
296 return Err(ProviderHostError::InputNotObject {
297 capability: capability.clone(),
298 });
299 }
300 let input_json = serde_json::to_string(input)
301 .map_err(|source| ProviderHostError::SerializeInput { source })?;
302 if input_json.len() > self.runtime.limits.max_input_bytes {
303 return Err(ProviderHostError::InputTooLarge {
304 capability: capability.clone(),
305 length: input_json.len(),
306 maximum: self.runtime.limits.max_input_bytes,
307 });
308 }
309
310 let timeout_ms = self.runtime.limits.timeout.as_millis();
311 let span = tracing::info_span!(
312 "provider.invoke",
313 provider.id = %self.manifest.id,
314 capability.id = %capability,
315 provider.path = %self.source.display(),
316 input.bytes = input_json.len(),
317 output.bytes = tracing::field::Empty,
318 fuel.remaining = tracing::field::Empty
319 );
320 let _entered = span.enter();
321 let _execution = self
322 .runtime
323 .execution
324 .lock()
325 .unwrap_or_else(|poisoned| poisoned.into_inner());
326
327 let mut store = self.runtime.store()?;
328 let linker = Linker::new(&self.runtime.engine);
329 let mut deadline = self.runtime.deadline.arm(self.runtime.limits.timeout)?;
330 let bindings = match bindings::Provider::instantiate(&mut store, &self.component, &linker) {
331 Ok(bindings) => bindings,
332 Err(source) => {
333 if deadline.stop() {
334 tracing::warn!(
335 provider.id = %self.manifest.id,
336 capability.id = %capability,
337 timeout_ms = %timeout_ms,
338 "instantiating a provider component exceeded its wall-clock deadline"
339 );
340 return Err(ProviderHostError::Timeout {
341 operation: format!("instantiate {}", self.manifest.id),
342 timeout_ms,
343 source: Some(source),
344 });
345 }
346 return Err(ProviderHostError::Instantiate {
347 path: self.source.clone(),
348 source,
349 });
350 }
351 };
352 let result = bindings.call_invoke(&mut store, capability.as_str(), &input_json);
353 let expired = deadline.stop();
354 if let Ok(fuel) = store.get_fuel() {
355 span.record("fuel.remaining", fuel);
356 }
357 let output_json = match settle(result, expired) {
358 CallOutcome::Completed(output_json) => output_json,
359 CallOutcome::TimedOut(source) => {
360 tracing::warn!(
361 provider.id = %self.manifest.id,
362 capability.id = %capability,
363 timeout_ms = %timeout_ms,
364 "provider invocation exceeded its wall-clock deadline"
365 );
366 return Err(ProviderHostError::Timeout {
367 operation: format!("invoke {capability}"),
368 timeout_ms,
369 source: Some(source),
370 });
371 }
372 CallOutcome::Failed(source) => {
373 tracing::warn!(
374 provider.id = %self.manifest.id,
375 capability.id = %capability,
376 "provider invocation trapped or failed inside the component"
377 );
378 return Err(ProviderHostError::Invoke {
379 provider: self.manifest.id.clone(),
380 capability: capability.clone(),
381 source,
382 });
383 }
384 };
385
386 span.record("output.bytes", output_json.len());
387 if output_json.len() > self.runtime.limits.max_output_bytes {
388 tracing::warn!(
389 provider.id = %self.manifest.id,
390 capability.id = %capability,
391 output.bytes = output_json.len(),
392 maximum = self.runtime.limits.max_output_bytes,
393 "provider returned more output than the configured maximum"
394 );
395 return Err(ProviderHostError::OutputTooLarge {
396 provider: self.manifest.id.to_string(),
397 length: output_json.len(),
398 maximum: self.runtime.limits.max_output_bytes,
399 });
400 }
401 let response =
402 serde_json::from_str::<ComponentResponse>(&output_json).map_err(|source| {
403 ProviderHostError::InvalidOutput {
404 provider: self.manifest.id.clone(),
405 capability: capability.clone(),
406 source,
407 }
408 })?;
409 match response {
410 ComponentResponse::Succeeded { output } => Ok(output),
411 ComponentResponse::Failed { error } => Err(ProviderHostError::ProviderFailure {
412 provider: self.manifest.id.clone(),
413 capability: capability.clone(),
414 code: error.code,
415 message: error.message,
416 }),
417 }
418 }
419}
420
421#[derive(Clone, Debug, Eq, PartialEq)]
427pub struct ProviderConflicts {
428 pub providers: Vec<ProviderId>,
430 pub capabilities: Vec<CapabilityId>,
432 pub command_words: Vec<CommandWordConflict>,
434}
435
436impl ProviderConflicts {
437 #[must_use]
439 pub fn len(&self) -> usize {
440 self.providers.len() + self.capabilities.len() + self.command_words.len()
441 }
442
443 #[must_use]
445 pub fn is_empty(&self) -> bool {
446 self.len() == 0
447 }
448}
449
450impl fmt::Display for ProviderConflicts {
451 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
452 writeln!(
453 formatter,
454 "refusing to load \u{2014} {} provider conflict(s)",
455 self.len()
456 )?;
457 for provider in &self.providers {
458 writeln!(formatter, "\n provider {provider}")?;
459 writeln!(formatter, " declared by more than one component")?;
460 writeln!(
461 formatter,
462 " fix: remove one, or drop its --provider argument"
463 )?;
464 }
465 for capability in &self.capabilities {
466 writeln!(formatter, "\n capability {capability}")?;
467 writeln!(formatter, " declared by more than one component")?;
468 writeln!(
469 formatter,
470 " fix: rename it in one provider, or drop that provider"
471 )?;
472 }
473 for conflict in &self.command_words {
474 writeln!(formatter, "\n command word `{}`", conflict.word)?;
475 for claimant in &conflict.claimants {
476 writeln!(formatter, " claimed by {claimant}")?;
477 }
478 writeln!(formatter, " {}", conflict.kind.explanation())?;
479 writeln!(formatter, " fix: {}", conflict.kind.remedy())?;
480 }
481 if !self.command_words.is_empty() {
482 write!(
483 formatter,
484 "\nReserved words: {}",
485 dekopon_core::RESERVED_COMMAND_WORDS.join(" ")
486 )?;
487 }
488 Ok(())
489 }
490}
491
492#[derive(Debug)]
494pub struct ProviderRegistry {
495 providers: Vec<WasmProvider>,
496 routes: BTreeMap<CapabilityId, usize>,
497}
498
499impl ProviderRegistry {
500 pub fn load<I, P>(sources: I, limits: HostLimits) -> Result<Self, ProviderHostError>
502 where
503 I: IntoIterator<Item = P>,
504 P: Into<PathBuf>,
505 {
506 Self::load_with_options(sources, limits, &HostOptions::default())
507 }
508
509 pub fn load_with_options<I, P>(
511 sources: I,
512 limits: HostLimits,
513 options: &HostOptions,
514 ) -> Result<Self, ProviderHostError>
515 where
516 I: IntoIterator<Item = P>,
517 P: Into<PathBuf>,
518 {
519 let sources = sources.into_iter().map(Into::into).collect::<Vec<_>>();
520 if sources.is_empty() {
521 return Err(ProviderHostError::NoProviders);
522 }
523
524 let runtime = Arc::new(Runtime::new(limits, options)?);
525 let mut providers = Vec::with_capacity(sources.len());
526 let mut provider_ids = BTreeSet::new();
527 let mut routes = BTreeMap::new();
528 let mut duplicate_providers = BTreeSet::new();
531 let mut duplicate_capabilities = BTreeSet::new();
532 let mut declared_words = Vec::new();
533
534 for source in sources {
535 let provider = WasmProvider::load(Arc::clone(&runtime), source)?;
536 if !provider_ids.insert(provider.manifest.id.clone()) {
537 duplicate_providers.insert(provider.manifest.id.clone());
538 }
539 declared_words.push((
540 provider.manifest.id.to_string(),
541 provider.manifest.command_words.clone(),
542 ));
543
544 let provider_index = providers.len();
545 for capability in &provider.manifest.capabilities {
546 if routes
547 .insert(capability.id.clone(), provider_index)
548 .is_some()
549 {
550 duplicate_capabilities.insert(capability.id.clone());
551 }
552 }
553 providers.push(provider);
554 }
555
556 let command_words = dekopon_core::command_word_conflicts(&declared_words);
559 if !duplicate_providers.is_empty()
560 || !duplicate_capabilities.is_empty()
561 || !command_words.is_empty()
562 {
563 return Err(ProviderHostError::ConflictingProviders {
564 report: Box::new(ProviderConflicts {
565 providers: duplicate_providers.into_iter().collect(),
566 capabilities: duplicate_capabilities.into_iter().collect(),
567 command_words,
568 }),
569 });
570 }
571
572 Ok(Self { providers, routes })
573 }
574
575 pub fn manifests(&self) -> impl ExactSizeIterator<Item = &ProviderManifest> {
577 self.providers.iter().map(|provider| &provider.manifest)
578 }
579
580 pub fn capabilities(&self) -> impl Iterator<Item = (&ProviderId, &ProviderCapability)> {
582 self.routes.iter().map(|(capability_id, provider_index)| {
583 let provider = &self.providers[*provider_index];
584 let capability = provider
585 .manifest
586 .capabilities
587 .iter()
588 .find(|candidate| &candidate.id == capability_id)
589 .expect("registry routes are built from provider manifests");
590 (&provider.manifest.id, capability)
591 })
592 }
593
594 pub fn invoke(
596 &self,
597 capability: &CapabilityId,
598 input: &Value,
599 ) -> Result<InvocationOutput, ProviderHostError> {
600 let provider_index = self.routes.get(capability).copied().ok_or_else(|| {
601 ProviderHostError::UnknownCapability {
602 capability: capability.clone(),
603 }
604 })?;
605 let provider = &self.providers[provider_index];
606 let output = provider.invoke(capability, input)?;
607
608 Ok(InvocationOutput {
609 provider: provider.manifest.id.clone(),
610 capability: capability.clone(),
611 output,
612 })
613 }
614}
615
616fn describe_component(
617 runtime: &Runtime,
618 component: &Component,
619 source: &Path,
620) -> Result<String, ProviderHostError> {
621 let span = tracing::info_span!("provider.describe", provider.path = %source.display());
622 let _entered = span.enter();
623 let _execution = runtime
624 .execution
625 .lock()
626 .unwrap_or_else(|poisoned| poisoned.into_inner());
627
628 let timeout_ms = runtime.limits.timeout.as_millis();
629 let mut store = runtime.store()?;
630 let linker = Linker::new(&runtime.engine);
631 let mut deadline = runtime.deadline.arm(runtime.limits.timeout)?;
632 let bindings = match bindings::Provider::instantiate(&mut store, component, &linker) {
633 Ok(bindings) => bindings,
634 Err(error) => {
635 if deadline.stop() {
636 tracing::warn!(
637 provider.path = %source.display(),
638 timeout_ms = %timeout_ms,
639 "instantiating a provider component exceeded its wall-clock deadline"
640 );
641 return Err(ProviderHostError::Timeout {
642 operation: format!("instantiate {}", source.display()),
643 timeout_ms,
644 source: Some(error),
645 });
646 }
647 return Err(ProviderHostError::Instantiate {
648 path: source.to_path_buf(),
649 source: error,
650 });
651 }
652 };
653 let result = bindings.call_describe(&mut store);
654 let expired = deadline.stop();
655
656 match settle(result, expired) {
657 CallOutcome::Completed(manifest_json) => Ok(manifest_json),
658 CallOutcome::TimedOut(error) => {
659 tracing::warn!(
660 provider.path = %source.display(),
661 timeout_ms = %timeout_ms,
662 "describing a provider component exceeded its wall-clock deadline"
663 );
664 Err(ProviderHostError::Timeout {
665 operation: format!("describe {}", source.display()),
666 timeout_ms,
667 source: Some(error),
668 })
669 }
670 CallOutcome::Failed(error) => Err(ProviderHostError::Describe {
671 path: source.to_path_buf(),
672 source: error,
673 }),
674 }
675}
676
677enum CallOutcome<T> {
679 Completed(T),
681 TimedOut(wasmtime::Error),
683 Failed(wasmtime::Error),
685}
686
687fn settle<T>(result: Result<T, wasmtime::Error>, expired: bool) -> CallOutcome<T> {
693 match result {
694 Ok(value) => CallOutcome::Completed(value),
695 Err(error) if expired => CallOutcome::TimedOut(error),
696 Err(error) => CallOutcome::Failed(error),
697 }
698}
699
700fn validate_limits(limits: &HostLimits) -> Result<(), ProviderHostError> {
701 for (name, value) in [
702 ("max_memory_bytes", limits.max_memory_bytes as u128),
703 ("max_table_elements", limits.max_table_elements as u128),
704 ("max_instances", limits.max_instances as u128),
705 ("max_tables", limits.max_tables as u128),
706 ("max_memories", limits.max_memories as u128),
707 ("max_input_bytes", limits.max_input_bytes as u128),
708 ("max_output_bytes", limits.max_output_bytes as u128),
709 ("fuel", u128::from(limits.fuel)),
710 ("timeout", limits.timeout.as_nanos()),
711 ] {
712 if value == 0 {
713 return Err(ProviderHostError::InvalidLimit { name });
714 }
715 }
716 Ok(())
717}
718
719fn validate_manifest(manifest: &ProviderManifest, source: &Path) -> Result<(), ProviderHostError> {
720 if manifest.description.trim().is_empty() {
721 return Err(invalid_manifest(source, "description must not be empty"));
722 }
723 if manifest.capabilities.is_empty() {
724 return Err(invalid_manifest(
725 source,
726 "at least one capability is required",
727 ));
728 }
729
730 let mut capabilities = BTreeSet::new();
731 for capability in &manifest.capabilities {
732 if !capabilities.insert(capability.id.clone()) {
733 return Err(invalid_manifest(
734 source,
735 format!("capability {} is declared more than once", capability.id),
736 ));
737 }
738 if capability.description.trim().is_empty() {
739 return Err(invalid_manifest(
740 source,
741 format!("capability {} has an empty description", capability.id),
742 ));
743 }
744 if capability.effect != EffectKind::ReadOnly {
745 return Err(ProviderHostError::UnsupportedEffect {
746 provider: manifest.id.clone(),
747 capability: capability.id.clone(),
748 effect: capability.effect,
749 });
750 }
751 let Some(schema) = capability.input_schema.as_object() else {
752 return Err(invalid_manifest(
753 source,
754 format!("capability {} inputSchema must be an object", capability.id),
755 ));
756 };
757 if schema.get("type").and_then(Value::as_str) != Some("object") {
758 return Err(invalid_manifest(
759 source,
760 format!(
761 "capability {} inputSchema must declare type object",
762 capability.id
763 ),
764 ));
765 }
766 }
767
768 Ok(())
769}
770
771fn invalid_manifest(source: &Path, message: impl Into<String>) -> ProviderHostError {
772 ProviderHostError::Manifest {
773 path: source.to_path_buf(),
774 message: message.into(),
775 }
776}
777
778struct Armed {
780 timeout: Duration,
781 expired: Arc<AtomicBool>,
782 cancel: Receiver<()>,
783 done: SyncSender<()>,
784}
785
786struct DeadlineWorker {
792 deadlines: Option<Sender<Armed>>,
793 handle: Option<JoinHandle<()>>,
794}
795
796impl DeadlineWorker {
797 fn start(engine: Engine) -> Result<Self, ProviderHostError> {
798 let (deadlines, armed) = mpsc::channel::<Armed>();
799 let handle = thread::Builder::new()
800 .name("dekopon-provider-deadline".to_owned())
801 .spawn(move || {
802 while let Ok(armed) = armed.recv() {
803 if matches!(
804 armed.cancel.recv_timeout(armed.timeout),
805 Err(mpsc::RecvTimeoutError::Timeout)
806 ) {
807 armed.expired.store(true, Ordering::Release);
808 engine.increment_epoch();
809 }
810 let _ignored = armed.done.send(());
813 }
814 })
815 .map_err(|source| ProviderHostError::Timer { source })?;
816
817 Ok(Self {
818 deadlines: Some(deadlines),
819 handle: Some(handle),
820 })
821 }
822
823 fn arm(&self, timeout: Duration) -> Result<Deadline, ProviderHostError> {
824 let (cancel, cancelled) = mpsc::channel();
825 let (done, finished) = mpsc::sync_channel(1);
827 let expired = Arc::new(AtomicBool::new(false));
828 self.deadlines
829 .as_ref()
830 .ok_or_else(deadline_worker_stopped)?
831 .send(Armed {
832 timeout,
833 expired: Arc::clone(&expired),
834 cancel: cancelled,
835 done,
836 })
837 .map_err(|_ignored| deadline_worker_stopped())?;
838
839 Ok(Deadline {
840 cancel: Some(cancel),
841 finished,
842 expired,
843 })
844 }
845}
846
847impl Drop for DeadlineWorker {
848 fn drop(&mut self) {
849 drop(self.deadlines.take());
852 if let Some(handle) = self.handle.take() {
853 let _ignored = handle.join();
854 }
855 }
856}
857
858fn deadline_worker_stopped() -> ProviderHostError {
859 ProviderHostError::Timer {
860 source: io::Error::other("the provider deadline worker is no longer running"),
861 }
862}
863
864struct Deadline {
866 cancel: Option<Sender<()>>,
867 finished: Receiver<()>,
868 expired: Arc<AtomicBool>,
869}
870
871impl Deadline {
872 fn stop(&mut self) -> bool {
873 if let Some(cancel) = self.cancel.take() {
874 let _ignored = cancel.send(());
875 let _ignored = self.finished.recv();
876 }
877 self.expired.load(Ordering::Acquire)
878 }
879}
880
881impl Drop for Deadline {
882 fn drop(&mut self) {
883 let _expired = self.stop();
884 }
885}
886
887#[derive(Debug, Error)]
889pub enum ProviderHostError {
890 #[error("at least one provider component is required")]
892 NoProviders,
893 #[error("provider host limit {name} must be greater than zero")]
895 InvalidLimit {
896 name: &'static str,
898 },
899 #[error("could not initialize the Wasmtime engine")]
901 Engine {
902 #[source]
904 source: wasmtime::Error,
905 },
906 #[error("could not open the provider compilation cache at {}", path.display())]
908 CompileCache {
909 path: PathBuf,
911 #[source]
913 source: wasmtime::Error,
914 },
915 #[error("could not initialize a bounded Wasmtime store")]
917 Store {
918 #[source]
920 source: wasmtime::Error,
921 },
922 #[error("could not start provider deadline worker")]
924 Timer {
925 #[source]
927 source: io::Error,
928 },
929 #[error("could not compile provider component {}", path.display())]
931 Compile {
932 path: PathBuf,
934 #[source]
936 source: wasmtime::Error,
937 },
938 #[error("could not instantiate provider component {}", path.display())]
940 Instantiate {
941 path: PathBuf,
943 #[source]
945 source: wasmtime::Error,
946 },
947 #[error("provider component {} failed while describing itself", path.display())]
949 Describe {
950 path: PathBuf,
952 #[source]
954 source: wasmtime::Error,
955 },
956 #[error("provider component {} returned an invalid manifest", path.display())]
958 InvalidManifest {
959 path: PathBuf,
961 #[source]
963 source: serde_json::Error,
964 },
965 #[error("provider component {} has an invalid manifest: {message}", path.display())]
967 Manifest {
968 path: PathBuf,
970 message: String,
972 },
973 #[error(
975 "provider {provider} capability {capability} has unsupported effect {effect}; immediate mode permits read-only capabilities only"
976 )]
977 UnsupportedEffect {
978 provider: ProviderId,
980 capability: CapabilityId,
982 effect: EffectKind,
984 },
985 #[error("{report}")]
987 ConflictingProviders {
988 report: Box<ProviderConflicts>,
990 },
991 #[error("no loaded provider implements capability {capability}")]
993 UnknownCapability {
994 capability: CapabilityId,
996 },
997 #[error("provider {provider} does not implement capability {capability}")]
999 ProviderDoesNotImplement {
1000 provider: ProviderId,
1002 capability: CapabilityId,
1004 },
1005 #[error("input for capability {capability} must be a JSON object")]
1007 InputNotObject {
1008 capability: CapabilityId,
1010 },
1011 #[error("could not serialize provider invocation input")]
1013 SerializeInput {
1014 #[source]
1016 source: serde_json::Error,
1017 },
1018 #[error("input for capability {capability} is {length} bytes; the maximum is {maximum}")]
1020 InputTooLarge {
1021 capability: CapabilityId,
1023 length: usize,
1025 maximum: usize,
1027 },
1028 #[error("provider {provider} returned {length} bytes; the maximum is {maximum}")]
1030 OutputTooLarge {
1031 provider: String,
1033 length: usize,
1035 maximum: usize,
1037 },
1038 #[error("provider operation {operation} exceeded its {timeout_ms} ms timeout")]
1040 Timeout {
1041 operation: String,
1043 timeout_ms: u128,
1045 #[source]
1047 source: Option<wasmtime::Error>,
1048 },
1049 #[error("provider {provider} failed while invoking capability {capability}")]
1051 Invoke {
1052 provider: ProviderId,
1054 capability: CapabilityId,
1056 #[source]
1058 source: wasmtime::Error,
1059 },
1060 #[error("provider {provider} failed capability {capability} with {code}: {message}")]
1062 ProviderFailure {
1063 provider: ProviderId,
1065 capability: CapabilityId,
1067 code: String,
1069 message: String,
1071 },
1072 #[error("provider {provider} returned an invalid response for capability {capability}")]
1074 InvalidOutput {
1075 provider: ProviderId,
1077 capability: CapabilityId,
1079 #[source]
1081 source: serde_json::Error,
1082 },
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087 use std::path::Path;
1088
1089 use dekopon_capability::{EffectKind, Idempotency};
1090 use dekopon_core::RiskLevel;
1091 use serde_json::json;
1092
1093 use super::{
1094 CallOutcome, ProviderApiVersion, ProviderCapability, ProviderHostError, ProviderManifest,
1095 settle, validate_manifest,
1096 };
1097
1098 fn manifest(effect: EffectKind, input_schema: serde_json::Value) -> ProviderManifest {
1099 ProviderManifest {
1100 api_version: ProviderApiVersion::V1Alpha1,
1101 id: "fixture".parse().expect("valid provider fixture"),
1102 description: "Fixture provider".to_owned(),
1103 command_words: Vec::new(),
1104 capabilities: vec![ProviderCapability {
1105 id: "fixture.run".parse().expect("valid capability fixture"),
1106 description: "Runs a fixture".to_owned(),
1107 effect,
1108 risk: RiskLevel::Low,
1109 idempotency: Idempotency::Idempotent,
1110 input_schema,
1111 }],
1112 }
1113 }
1114
1115 #[test]
1116 fn rejects_mutating_provider_manifests() {
1117 let error = validate_manifest(
1118 &manifest(EffectKind::ExternalWrite, json!({"type": "object"})),
1119 Path::new("writer.wasm"),
1120 )
1121 .expect_err("external writes must not load in immediate mode");
1122
1123 assert!(matches!(error, ProviderHostError::UnsupportedEffect { .. }));
1124 }
1125
1126 #[test]
1127 fn requires_object_shaped_prompt_schemas() {
1128 let error = validate_manifest(
1129 &manifest(EffectKind::ReadOnly, json!({"type": "string"})),
1130 Path::new("invalid-schema.wasm"),
1131 )
1132 .expect_err("prompt tools require object arguments");
1133
1134 assert!(matches!(error, ProviderHostError::Manifest { .. }));
1135 }
1136
1137 #[test]
1138 fn a_completed_call_outlives_a_deadline_that_fired_too_late() {
1139 let outcome = settle(Ok::<_, wasmtime::Error>("{\"kind\":\"succeeded\"}"), true);
1142
1143 assert!(matches!(
1144 outcome,
1145 CallOutcome::Completed("{\"kind\":\"succeeded\"}")
1146 ));
1147 }
1148
1149 #[test]
1150 fn a_failed_call_separates_a_fired_deadline_from_a_guest_trap() {
1151 let timed_out = settle(
1152 Err::<(), _>(wasmtime::Error::msg("epoch deadline reached")),
1153 true,
1154 );
1155 let failed = settle(Err::<(), _>(wasmtime::Error::msg("unreachable")), false);
1156
1157 assert!(matches!(timed_out, CallOutcome::TimedOut(_)));
1158 assert!(matches!(failed, CallOutcome::Failed(_)));
1159 }
1160}