Skip to main content

dekopon_provider_host/
lib.rs

1//! Bounded WebAssembly component hosting for immediate-mode Dekopon providers.
2//!
3//! This crate intentionally supports only read-only components with no host imports. It is a
4//! useful execution laboratory, not an authorization broker: loading a component does not grant
5//! external authority, credentials, filesystem access, network access, clocks, or environment
6//! variables.
7
8#![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
41/// The WIT contract implemented by provider components.
42pub const PROVIDER_WIT: &str = include_str!("../wit/provider.wit");
43
44/// Default maximum size of each linear memory in one store (64 MiB).
45pub const DEFAULT_MAX_MEMORY_BYTES: usize = 64 * 1024 * 1024;
46/// Default maximum elements in each Wasm table.
47pub const DEFAULT_MAX_TABLE_ELEMENTS: usize = 100_000;
48/// Default maximum core instances in one store.
49pub const DEFAULT_MAX_INSTANCES: usize = 64;
50/// Default maximum tables in one store.
51pub const DEFAULT_MAX_TABLES: usize = 16;
52/// Default maximum linear memories in one store.
53pub const DEFAULT_MAX_MEMORIES: usize = 4;
54/// Default maximum serialized provider input size (1 MiB).
55pub const DEFAULT_MAX_INPUT_BYTES: usize = 1024 * 1024;
56/// Default maximum serialized provider output or manifest size (1 MiB).
57pub const DEFAULT_MAX_OUTPUT_BYTES: usize = 1024 * 1024;
58/// Default Wasm instruction fuel supplied to each store.
59pub const DEFAULT_FUEL: u64 = 10_000_000;
60/// Default wall-clock timeout for instantiation and invocation.
61pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
62
63/// Limits applied independently to every provider description or invocation call.
64#[derive(Clone, Debug, Eq, PartialEq)]
65pub struct HostLimits {
66    /// Maximum size of each linear memory in one store.
67    ///
68    /// Wasmtime applies this per memory, not per store, which is why the store also bounds how many
69    /// memories, tables, table elements, and instances a component may create.
70    pub max_memory_bytes: usize,
71    /// Maximum elements in each Wasm table.
72    pub max_table_elements: usize,
73    /// Maximum core instances in one store.
74    pub max_instances: usize,
75    /// Maximum tables in one store.
76    pub max_tables: usize,
77    /// Maximum linear memories in one store.
78    pub max_memories: usize,
79    /// Maximum serialized invocation input.
80    pub max_input_bytes: usize,
81    /// Maximum serialized manifest or invocation output.
82    ///
83    /// This bounds what the host will parse, not peak host allocation: the buffered-string WIT
84    /// contract lifts the whole guest string into host memory before it can be measured, so the
85    /// transient allocation is bounded by the store's memory limits instead.
86    pub max_output_bytes: usize,
87    /// Wasm instruction fuel supplied to one store.
88    pub fuel: u64,
89    /// Wall-clock bound for instantiation plus the exported call.
90    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/// Operational host settings that bound nothing a component may do.
110///
111/// These are separate from [`HostLimits`] for the same reason the broker host keeps them apart:
112/// a limit is part of what a call is allowed to consume, while a cache directory only decides
113/// where already-compiled machine code is kept between processes.
114#[derive(Clone, Debug, Default, Eq, PartialEq)]
115pub struct HostOptions {
116    /// Directory for Wasmtime's content-addressed compilation cache.
117    ///
118    /// `None` recompiles every component with Cranelift in every process, which is the dominant
119    /// cost of a short `inspect` or `invoke`. A hit is keyed by the artifact bytes and the engine
120    /// configuration, so a rebuilt component compiles again rather than being served stale.
121    ///
122    /// The cache holds compiled code this process executes: point it only at a directory the
123    /// invoking user controls.
124    pub compile_cache_dir: Option<PathBuf>,
125}
126
127/// Successful output from a routed provider invocation.
128#[derive(Clone, Debug, PartialEq, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct InvocationOutput {
131    /// Provider selected for the capability.
132    pub provider: ProviderId,
133    /// Invoked capability.
134    pub capability: CapabilityId,
135    /// Valid JSON returned by the component.
136    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
203/// A provider component compiled by Wasmtime.
204pub 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    /// Returns the validated component manifest.
265    #[must_use]
266    pub const fn manifest(&self) -> &ProviderManifest {
267        &self.manifest
268    }
269
270    /// Invokes one capability in a fresh bounded execution context.
271    ///
272    /// This carries no authorization semantics: immediate mode is read-only and unprivileged.
273    ///
274    /// # Errors
275    ///
276    /// Returns [`ProviderHostError`] when the component does not implement the capability, the
277    /// input is not object-shaped, execution exceeds a bound, or the response does not decode.
278    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/// Everything wrong with one provider set, gathered so an operator sees it once.
422///
423/// Ambiguity is fatal in a way absence is not: a word or capability two components both claim has no
424/// meaning this host can pick without silently choosing for the operator. This reports rather than
425/// resolves, and reports *all of it* — fixing a `--provider` list should take one run.
426#[derive(Clone, Debug, Eq, PartialEq)]
427pub struct ProviderConflicts {
428    /// Provider identities declared by more than one component.
429    pub providers: Vec<ProviderId>,
430    /// Capability identifiers declared by more than one component.
431    pub capabilities: Vec<CapabilityId>,
432    /// Command words that cannot be granted to the providers claiming them.
433    pub command_words: Vec<CommandWordConflict>,
434}
435
436impl ProviderConflicts {
437    /// Reports how many distinct conflicts this covers.
438    #[must_use]
439    pub fn len(&self) -> usize {
440        self.providers.len() + self.capabilities.len() + self.command_words.len()
441    }
442
443    /// Reports whether there is nothing to complain about.
444    #[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/// A deterministic capability-to-component registry.
493#[derive(Debug)]
494pub struct ProviderRegistry {
495    providers: Vec<WasmProvider>,
496    routes: BTreeMap<CapabilityId, usize>,
497}
498
499impl ProviderRegistry {
500    /// Loads and validates all components with one shared Wasmtime engine.
501    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    /// Loads and validates all components, optionally reusing a persistent compilation cache.
510    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        // Every conflict, then one failure. Returning on the first would make fixing a provider set
529        // take one run per mistake; an operator should see the whole picture once.
530        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        // The broker refuses these words at startup; the lab host has to agree, or an author learns
557        // about a conflict only once the provider reaches `dekopon-brokerd`.
558        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    /// Returns manifests in command-line load order.
576    pub fn manifests(&self) -> impl ExactSizeIterator<Item = &ProviderManifest> {
577        self.providers.iter().map(|provider| &provider.manifest)
578    }
579
580    /// Returns capabilities in deterministic identifier order.
581    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    /// Routes and invokes one capability.
595    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
677/// Outcome of one guest call once its wall-clock deadline has been disarmed.
678enum CallOutcome<T> {
679    /// The call returned before anything interrupted it.
680    Completed(T),
681    /// The call failed and the deadline had already fired.
682    TimedOut(wasmtime::Error),
683    /// The call failed on its own.
684    Failed(wasmtime::Error),
685}
686
687/// Settles the race between a completed call and a deadline that fired around the same moment.
688///
689/// The epoch can tick in the window between the guest returning and the deadline being disarmed,
690/// where it interrupted nothing — an interruption that landed in time produces `Err` instead. So a
691/// completed `Ok` wins, and only a failed call may be reported as a timeout.
692fn 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
778/// One deadline armed on the runtime's worker.
779struct Armed {
780    timeout: Duration,
781    expired: Arc<AtomicBool>,
782    cancel: Receiver<()>,
783    done: SyncSender<()>,
784}
785
786/// The single wall-clock deadline thread a [`Runtime`] owns.
787///
788/// The execution mutex admits one call at a time, so a thread spawned and joined per describe and
789/// invoke was pure overhead on the hot path — and thread creation is the first thing a loaded host
790/// refuses. This one parks on its command channel between calls and outlives all of them.
791struct 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                    // Only now is `expired` final, so a caller waiting on this signal cannot read
811                    // the flag while the deadline is still firing.
812                    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        // Bounded at one so the worker's completion signal never blocks on a caller that is gone.
826        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        // Closing the command channel ends the loop; join so the worker cannot outlive the engine
850        // whose epoch it increments.
851        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
864/// One call's armed deadline, disarmed exactly once.
865struct 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/// Failure to load, validate, route, or invoke a provider component.
888#[derive(Debug, Error)]
889pub enum ProviderHostError {
890    /// No component paths were supplied.
891    #[error("at least one provider component is required")]
892    NoProviders,
893    /// A configured execution limit was zero.
894    #[error("provider host limit {name} must be greater than zero")]
895    InvalidLimit {
896        /// Invalid limit name.
897        name: &'static str,
898    },
899    /// Wasmtime engine initialization failed.
900    #[error("could not initialize the Wasmtime engine")]
901    Engine {
902        /// Wasmtime error.
903        #[source]
904        source: wasmtime::Error,
905    },
906    /// The persistent compilation cache directory could not be prepared.
907    #[error("could not open the provider compilation cache at {}", path.display())]
908    CompileCache {
909        /// Configured cache directory.
910        path: PathBuf,
911        /// Wasmtime error.
912        #[source]
913        source: wasmtime::Error,
914    },
915    /// Store initialization failed.
916    #[error("could not initialize a bounded Wasmtime store")]
917    Store {
918        /// Wasmtime error.
919        #[source]
920        source: wasmtime::Error,
921    },
922    /// Starting the wall-clock deadline worker failed.
923    #[error("could not start provider deadline worker")]
924    Timer {
925        /// Thread creation error.
926        #[source]
927        source: io::Error,
928    },
929    /// Component compilation or decoding failed.
930    #[error("could not compile provider component {}", path.display())]
931    Compile {
932        /// Component path.
933        path: PathBuf,
934        /// Wasmtime error.
935        #[source]
936        source: wasmtime::Error,
937    },
938    /// Component imports could not be linked or instantiated.
939    #[error("could not instantiate provider component {}", path.display())]
940    Instantiate {
941        /// Component path.
942        path: PathBuf,
943        /// Wasmtime error.
944        #[source]
945        source: wasmtime::Error,
946    },
947    /// Calling the provider description export failed.
948    #[error("provider component {} failed while describing itself", path.display())]
949    Describe {
950        /// Component path.
951        path: PathBuf,
952        /// Wasmtime error.
953        #[source]
954        source: wasmtime::Error,
955    },
956    /// A component returned malformed manifest JSON.
957    #[error("provider component {} returned an invalid manifest", path.display())]
958    InvalidManifest {
959        /// Component path.
960        path: PathBuf,
961        /// JSON error.
962        #[source]
963        source: serde_json::Error,
964    },
965    /// A component manifest violated a semantic constraint.
966    #[error("provider component {} has an invalid manifest: {message}", path.display())]
967    Manifest {
968        /// Component path.
969        path: PathBuf,
970        /// Validation detail.
971        message: String,
972    },
973    /// Immediate mode was asked to load a mutating capability.
974    #[error(
975        "provider {provider} capability {capability} has unsupported effect {effect}; immediate mode permits read-only capabilities only"
976    )]
977    UnsupportedEffect {
978        /// Provider identity.
979        provider: ProviderId,
980        /// Capability identity.
981        capability: CapabilityId,
982        /// Rejected effect.
983        effect: EffectKind,
984    },
985    /// The loaded component set contained duplicate providers, capabilities, or command words.
986    #[error("{report}")]
987    ConflictingProviders {
988        /// Every conflict found across the whole load.
989        report: Box<ProviderConflicts>,
990    },
991    /// No loaded component declared the requested capability.
992    #[error("no loaded provider implements capability {capability}")]
993    UnknownCapability {
994        /// Requested capability.
995        capability: CapabilityId,
996    },
997    /// A provider was called with a capability absent from its own manifest.
998    #[error("provider {provider} does not implement capability {capability}")]
999    ProviderDoesNotImplement {
1000        /// Provider identity.
1001        provider: ProviderId,
1002        /// Requested capability.
1003        capability: CapabilityId,
1004    },
1005    /// Invocation input did not match the object-shaped provider contract.
1006    #[error("input for capability {capability} must be a JSON object")]
1007    InputNotObject {
1008        /// Capability identity.
1009        capability: CapabilityId,
1010    },
1011    /// Invocation input could not be serialized.
1012    #[error("could not serialize provider invocation input")]
1013    SerializeInput {
1014        /// JSON error.
1015        #[source]
1016        source: serde_json::Error,
1017    },
1018    /// Invocation input exceeded its bound.
1019    #[error("input for capability {capability} is {length} bytes; the maximum is {maximum}")]
1020    InputTooLarge {
1021        /// Capability identity.
1022        capability: CapabilityId,
1023        /// Actual serialized size.
1024        length: usize,
1025        /// Configured bound.
1026        maximum: usize,
1027    },
1028    /// Invocation or manifest output exceeded its bound.
1029    #[error("provider {provider} returned {length} bytes; the maximum is {maximum}")]
1030    OutputTooLarge {
1031        /// Provider identity or source path.
1032        provider: String,
1033        /// Actual serialized size.
1034        length: usize,
1035        /// Configured bound.
1036        maximum: usize,
1037    },
1038    /// Component execution exceeded its wall-clock timeout.
1039    #[error("provider operation {operation} exceeded its {timeout_ms} ms timeout")]
1040    Timeout {
1041        /// Operation description.
1042        operation: String,
1043        /// Configured timeout.
1044        timeout_ms: u128,
1045        /// The interruption Wasmtime reported, when the call reported one.
1046        #[source]
1047        source: Option<wasmtime::Error>,
1048    },
1049    /// Calling a provider export trapped or otherwise failed.
1050    #[error("provider {provider} failed while invoking capability {capability}")]
1051    Invoke {
1052        /// Provider identity.
1053        provider: ProviderId,
1054        /// Capability identity.
1055        capability: CapabilityId,
1056        /// Wasmtime error.
1057        #[source]
1058        source: wasmtime::Error,
1059    },
1060    /// A provider returned an explicit typed failure.
1061    #[error("provider {provider} failed capability {capability} with {code}: {message}")]
1062    ProviderFailure {
1063        /// Provider identity.
1064        provider: ProviderId,
1065        /// Capability identity.
1066        capability: CapabilityId,
1067        /// Stable provider error code.
1068        code: String,
1069        /// Bounded provider error detail.
1070        message: String,
1071    },
1072    /// A provider returned data that was not a valid component response.
1073    #[error("provider {provider} returned an invalid response for capability {capability}")]
1074    InvalidOutput {
1075        /// Provider identity.
1076        provider: ProviderId,
1077        /// Capability identity.
1078        capability: CapabilityId,
1079        /// JSON error.
1080        #[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        // The epoch can tick between the guest returning and the deadline being disarmed. It
1140        // interrupted nothing, so the output stands rather than being reported as a timeout.
1141        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}