wasm_host.rs

  1pub mod wit;
  2
  3use crate::capability_granter::CapabilityGranter;
  4use crate::{ExtensionManifest, ExtensionSettings};
  5use anyhow::{Context as _, Result, anyhow, bail};
  6use async_trait::async_trait;
  7use dap::{DebugRequest, StartDebuggingRequestArgumentsRequest};
  8use extension::{
  9    CodeLabel, Command, Completion, ContextServerConfiguration, DebugAdapterBinary,
 10    DebugTaskDefinition, ExtensionCapability, ExtensionHostProxy, KeyValueStoreDelegate,
 11    ProjectDelegate, SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput, Symbol,
 12    WorktreeDelegate,
 13};
 14use fs::{Fs, normalize_path};
 15use futures::future::LocalBoxFuture;
 16use futures::{
 17    Future, FutureExt, StreamExt as _,
 18    channel::{
 19        mpsc::{self, UnboundedSender},
 20        oneshot,
 21    },
 22    future::BoxFuture,
 23};
 24use gpui::{App, AsyncApp, BackgroundExecutor, Task, Timer};
 25use http_client::HttpClient;
 26use language::LanguageName;
 27use lsp::LanguageServerName;
 28use moka::sync::Cache;
 29use node_runtime::NodeRuntime;
 30use release_channel::ReleaseChannel;
 31use semver::Version;
 32use settings::Settings;
 33use std::{
 34    borrow::Cow,
 35    path::{Path, PathBuf},
 36    sync::{
 37        Arc, LazyLock, OnceLock,
 38        atomic::{AtomicBool, Ordering},
 39    },
 40    time::Duration,
 41};
 42use task::{DebugScenario, SpawnInTerminal, TaskTemplate, ZedDebugConfig};
 43use util::paths::SanitizedPath;
 44use wasmtime::{
 45    CacheStore, Engine, Store,
 46    component::{Component, ResourceTable},
 47};
 48use wasmtime_wasi::{self as wasi, WasiView};
 49use wit::Extension;
 50
 51pub struct WasmHost {
 52    engine: Engine,
 53    release_channel: ReleaseChannel,
 54    http_client: Arc<dyn HttpClient>,
 55    node_runtime: NodeRuntime,
 56    pub(crate) proxy: Arc<ExtensionHostProxy>,
 57    fs: Arc<dyn Fs>,
 58    pub work_dir: PathBuf,
 59    /// The capabilities granted to extensions running on the host.
 60    pub(crate) granted_capabilities: Vec<ExtensionCapability>,
 61    _main_thread_message_task: Task<()>,
 62    main_thread_message_tx: mpsc::UnboundedSender<MainThreadCall>,
 63}
 64
 65#[derive(Clone, Debug)]
 66pub struct WasmExtension {
 67    tx: UnboundedSender<ExtensionCall>,
 68    pub manifest: Arc<ExtensionManifest>,
 69    pub work_dir: Arc<Path>,
 70    #[allow(unused)]
 71    pub zed_api_version: Version,
 72    _task: Arc<Task<Result<(), gpui_tokio::JoinError>>>,
 73}
 74
 75impl Drop for WasmExtension {
 76    fn drop(&mut self) {
 77        self.tx.close_channel();
 78    }
 79}
 80
 81#[async_trait]
 82impl extension::Extension for WasmExtension {
 83    fn manifest(&self) -> Arc<ExtensionManifest> {
 84        self.manifest.clone()
 85    }
 86
 87    fn work_dir(&self) -> Arc<Path> {
 88        self.work_dir.clone()
 89    }
 90
 91    async fn language_server_command(
 92        &self,
 93        language_server_id: LanguageServerName,
 94        language_name: LanguageName,
 95        worktree: Arc<dyn WorktreeDelegate>,
 96    ) -> Result<Command> {
 97        self.call(|extension, store| {
 98            async move {
 99                let resource = store.data_mut().table().push(worktree)?;
100                let command = extension
101                    .call_language_server_command(
102                        store,
103                        &language_server_id,
104                        &language_name,
105                        resource,
106                    )
107                    .await?
108                    .map_err(|err| store.data().extension_error(err))?;
109
110                Ok(command.into())
111            }
112            .boxed()
113        })
114        .await?
115    }
116
117    async fn language_server_initialization_options(
118        &self,
119        language_server_id: LanguageServerName,
120        language_name: LanguageName,
121        worktree: Arc<dyn WorktreeDelegate>,
122    ) -> Result<Option<String>> {
123        self.call(|extension, store| {
124            async move {
125                let resource = store.data_mut().table().push(worktree)?;
126                let options = extension
127                    .call_language_server_initialization_options(
128                        store,
129                        &language_server_id,
130                        &language_name,
131                        resource,
132                    )
133                    .await?
134                    .map_err(|err| store.data().extension_error(err))?;
135                anyhow::Ok(options)
136            }
137            .boxed()
138        })
139        .await?
140    }
141
142    async fn language_server_workspace_configuration(
143        &self,
144        language_server_id: LanguageServerName,
145        worktree: Arc<dyn WorktreeDelegate>,
146    ) -> Result<Option<String>> {
147        self.call(|extension, store| {
148            async move {
149                let resource = store.data_mut().table().push(worktree)?;
150                let options = extension
151                    .call_language_server_workspace_configuration(
152                        store,
153                        &language_server_id,
154                        resource,
155                    )
156                    .await?
157                    .map_err(|err| store.data().extension_error(err))?;
158                anyhow::Ok(options)
159            }
160            .boxed()
161        })
162        .await?
163    }
164
165    async fn language_server_additional_initialization_options(
166        &self,
167        language_server_id: LanguageServerName,
168        target_language_server_id: LanguageServerName,
169        worktree: Arc<dyn WorktreeDelegate>,
170    ) -> Result<Option<String>> {
171        self.call(|extension, store| {
172            async move {
173                let resource = store.data_mut().table().push(worktree)?;
174                let options = extension
175                    .call_language_server_additional_initialization_options(
176                        store,
177                        &language_server_id,
178                        &target_language_server_id,
179                        resource,
180                    )
181                    .await?
182                    .map_err(|err| store.data().extension_error(err))?;
183                anyhow::Ok(options)
184            }
185            .boxed()
186        })
187        .await?
188    }
189
190    async fn language_server_additional_workspace_configuration(
191        &self,
192        language_server_id: LanguageServerName,
193        target_language_server_id: LanguageServerName,
194        worktree: Arc<dyn WorktreeDelegate>,
195    ) -> Result<Option<String>> {
196        self.call(|extension, store| {
197            async move {
198                let resource = store.data_mut().table().push(worktree)?;
199                let options = extension
200                    .call_language_server_additional_workspace_configuration(
201                        store,
202                        &language_server_id,
203                        &target_language_server_id,
204                        resource,
205                    )
206                    .await?
207                    .map_err(|err| store.data().extension_error(err))?;
208                anyhow::Ok(options)
209            }
210            .boxed()
211        })
212        .await?
213    }
214
215    async fn labels_for_completions(
216        &self,
217        language_server_id: LanguageServerName,
218        completions: Vec<Completion>,
219    ) -> Result<Vec<Option<CodeLabel>>> {
220        self.call(|extension, store| {
221            async move {
222                let labels = extension
223                    .call_labels_for_completions(
224                        store,
225                        &language_server_id,
226                        completions.into_iter().map(Into::into).collect(),
227                    )
228                    .await?
229                    .map_err(|err| store.data().extension_error(err))?;
230
231                Ok(labels
232                    .into_iter()
233                    .map(|label| label.map(Into::into))
234                    .collect())
235            }
236            .boxed()
237        })
238        .await?
239    }
240
241    async fn labels_for_symbols(
242        &self,
243        language_server_id: LanguageServerName,
244        symbols: Vec<Symbol>,
245    ) -> Result<Vec<Option<CodeLabel>>> {
246        self.call(|extension, store| {
247            async move {
248                let labels = extension
249                    .call_labels_for_symbols(
250                        store,
251                        &language_server_id,
252                        symbols.into_iter().map(Into::into).collect(),
253                    )
254                    .await?
255                    .map_err(|err| store.data().extension_error(err))?;
256
257                Ok(labels
258                    .into_iter()
259                    .map(|label| label.map(Into::into))
260                    .collect())
261            }
262            .boxed()
263        })
264        .await?
265    }
266
267    async fn complete_slash_command_argument(
268        &self,
269        command: SlashCommand,
270        arguments: Vec<String>,
271    ) -> Result<Vec<SlashCommandArgumentCompletion>> {
272        self.call(|extension, store| {
273            async move {
274                let completions = extension
275                    .call_complete_slash_command_argument(store, &command.into(), &arguments)
276                    .await?
277                    .map_err(|err| store.data().extension_error(err))?;
278
279                Ok(completions.into_iter().map(Into::into).collect())
280            }
281            .boxed()
282        })
283        .await?
284    }
285
286    async fn run_slash_command(
287        &self,
288        command: SlashCommand,
289        arguments: Vec<String>,
290        delegate: Option<Arc<dyn WorktreeDelegate>>,
291    ) -> Result<SlashCommandOutput> {
292        self.call(|extension, store| {
293            async move {
294                let resource = if let Some(delegate) = delegate {
295                    Some(store.data_mut().table().push(delegate)?)
296                } else {
297                    None
298                };
299
300                let output = extension
301                    .call_run_slash_command(store, &command.into(), &arguments, resource)
302                    .await?
303                    .map_err(|err| store.data().extension_error(err))?;
304
305                Ok(output.into())
306            }
307            .boxed()
308        })
309        .await?
310    }
311
312    async fn context_server_command(
313        &self,
314        context_server_id: Arc<str>,
315        project: Arc<dyn ProjectDelegate>,
316    ) -> Result<Command> {
317        self.call(|extension, store| {
318            async move {
319                let project_resource = store.data_mut().table().push(project)?;
320                let command = extension
321                    .call_context_server_command(store, context_server_id.clone(), project_resource)
322                    .await?
323                    .map_err(|err| store.data().extension_error(err))?;
324                anyhow::Ok(command.into())
325            }
326            .boxed()
327        })
328        .await?
329    }
330
331    async fn context_server_configuration(
332        &self,
333        context_server_id: Arc<str>,
334        project: Arc<dyn ProjectDelegate>,
335    ) -> Result<Option<ContextServerConfiguration>> {
336        self.call(|extension, store| {
337            async move {
338                let project_resource = store.data_mut().table().push(project)?;
339                let Some(configuration) = extension
340                    .call_context_server_configuration(
341                        store,
342                        context_server_id.clone(),
343                        project_resource,
344                    )
345                    .await?
346                    .map_err(|err| store.data().extension_error(err))?
347                else {
348                    return Ok(None);
349                };
350
351                Ok(Some(configuration.try_into()?))
352            }
353            .boxed()
354        })
355        .await?
356    }
357
358    async fn suggest_docs_packages(&self, provider: Arc<str>) -> Result<Vec<String>> {
359        self.call(|extension, store| {
360            async move {
361                let packages = extension
362                    .call_suggest_docs_packages(store, provider.as_ref())
363                    .await?
364                    .map_err(|err| store.data().extension_error(err))?;
365
366                Ok(packages)
367            }
368            .boxed()
369        })
370        .await?
371    }
372
373    async fn index_docs(
374        &self,
375        provider: Arc<str>,
376        package_name: Arc<str>,
377        kv_store: Arc<dyn KeyValueStoreDelegate>,
378    ) -> Result<()> {
379        self.call(|extension, store| {
380            async move {
381                let kv_store_resource = store.data_mut().table().push(kv_store)?;
382                extension
383                    .call_index_docs(
384                        store,
385                        provider.as_ref(),
386                        package_name.as_ref(),
387                        kv_store_resource,
388                    )
389                    .await?
390                    .map_err(|err| store.data().extension_error(err))?;
391
392                anyhow::Ok(())
393            }
394            .boxed()
395        })
396        .await?
397    }
398
399    async fn get_dap_binary(
400        &self,
401        dap_name: Arc<str>,
402        config: DebugTaskDefinition,
403        user_installed_path: Option<PathBuf>,
404        worktree: Arc<dyn WorktreeDelegate>,
405    ) -> Result<DebugAdapterBinary> {
406        self.call(|extension, store| {
407            async move {
408                let resource = store.data_mut().table().push(worktree)?;
409                let dap_binary = extension
410                    .call_get_dap_binary(store, dap_name, config, user_installed_path, resource)
411                    .await?
412                    .map_err(|err| store.data().extension_error(err))?;
413                let dap_binary = dap_binary.try_into()?;
414                Ok(dap_binary)
415            }
416            .boxed()
417        })
418        .await?
419    }
420    async fn dap_request_kind(
421        &self,
422        dap_name: Arc<str>,
423        config: serde_json::Value,
424    ) -> Result<StartDebuggingRequestArgumentsRequest> {
425        self.call(|extension, store| {
426            async move {
427                let kind = extension
428                    .call_dap_request_kind(store, dap_name, config)
429                    .await?
430                    .map_err(|err| store.data().extension_error(err))?;
431                Ok(kind.into())
432            }
433            .boxed()
434        })
435        .await?
436    }
437
438    async fn dap_config_to_scenario(&self, config: ZedDebugConfig) -> Result<DebugScenario> {
439        self.call(|extension, store| {
440            async move {
441                let kind = extension
442                    .call_dap_config_to_scenario(store, config)
443                    .await?
444                    .map_err(|err| store.data().extension_error(err))?;
445                Ok(kind)
446            }
447            .boxed()
448        })
449        .await?
450    }
451
452    async fn dap_locator_create_scenario(
453        &self,
454        locator_name: String,
455        build_config_template: TaskTemplate,
456        resolved_label: String,
457        debug_adapter_name: String,
458    ) -> Result<Option<DebugScenario>> {
459        self.call(|extension, store| {
460            async move {
461                extension
462                    .call_dap_locator_create_scenario(
463                        store,
464                        locator_name,
465                        build_config_template,
466                        resolved_label,
467                        debug_adapter_name,
468                    )
469                    .await
470            }
471            .boxed()
472        })
473        .await?
474    }
475    async fn run_dap_locator(
476        &self,
477        locator_name: String,
478        config: SpawnInTerminal,
479    ) -> Result<DebugRequest> {
480        self.call(|extension, store| {
481            async move {
482                extension
483                    .call_run_dap_locator(store, locator_name, config)
484                    .await?
485                    .map_err(|err| store.data().extension_error(err))
486            }
487            .boxed()
488        })
489        .await?
490    }
491}
492
493pub struct WasmState {
494    manifest: Arc<ExtensionManifest>,
495    pub table: ResourceTable,
496    ctx: wasi::WasiCtx,
497    pub host: Arc<WasmHost>,
498    pub(crate) capability_granter: CapabilityGranter,
499}
500
501std::thread_local! {
502    /// Used by the crash handler to ignore panics in extension-related threads.
503    pub static IS_WASM_THREAD: AtomicBool = const { AtomicBool::new(false) };
504}
505
506type MainThreadCall = Box<dyn Send + for<'a> FnOnce(&'a mut AsyncApp) -> LocalBoxFuture<'a, ()>>;
507
508type ExtensionCall = Box<
509    dyn Send + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, ()>,
510>;
511
512fn wasm_engine(executor: &BackgroundExecutor) -> wasmtime::Engine {
513    static WASM_ENGINE: OnceLock<wasmtime::Engine> = OnceLock::new();
514    WASM_ENGINE
515        .get_or_init(|| {
516            let mut config = wasmtime::Config::new();
517            config.wasm_component_model(true);
518            config.async_support(true);
519            config
520                .enable_incremental_compilation(cache_store())
521                .unwrap();
522            // Async support introduces the issue that extension execution happens during `Future::poll`,
523            // which could block an async thread.
524            // https://docs.rs/wasmtime/latest/wasmtime/struct.Config.html#execution-in-poll
525            //
526            // Epoch interruption is a lightweight mechanism to allow the extensions to yield control
527            // back to the executor at regular intervals.
528            config.epoch_interruption(true);
529
530            let engine = wasmtime::Engine::new(&config).unwrap();
531
532            // It might be safer to do this on a non-async thread to make sure it makes progress
533            // regardless of if extensions are blocking.
534            // However, due to our current setup, this isn't a likely occurrence and we'd rather
535            // not have a dedicated thread just for this. If it becomes an issue, we can consider
536            // creating a separate thread for epoch interruption.
537            let engine_ref = engine.weak();
538            executor
539                .spawn(async move {
540                    // Somewhat arbitrary interval, as it isn't a guaranteed interval.
541                    // But this is a rough upper bound for how long the extension execution can block on
542                    // `Future::poll`.
543                    const EPOCH_INTERVAL: Duration = Duration::from_millis(100);
544                    let mut timer = Timer::interval(EPOCH_INTERVAL);
545                    while (timer.next().await).is_some() {
546                        // Exit the loop and thread once the engine is dropped.
547                        let Some(engine) = engine_ref.upgrade() else {
548                            break;
549                        };
550                        engine.increment_epoch();
551                    }
552                })
553                .detach();
554
555            engine
556        })
557        .clone()
558}
559
560fn cache_store() -> Arc<IncrementalCompilationCache> {
561    static CACHE_STORE: LazyLock<Arc<IncrementalCompilationCache>> =
562        LazyLock::new(|| Arc::new(IncrementalCompilationCache::new()));
563    CACHE_STORE.clone()
564}
565
566impl WasmHost {
567    pub fn new(
568        fs: Arc<dyn Fs>,
569        http_client: Arc<dyn HttpClient>,
570        node_runtime: NodeRuntime,
571        proxy: Arc<ExtensionHostProxy>,
572        work_dir: PathBuf,
573        cx: &mut App,
574    ) -> Arc<Self> {
575        let (tx, mut rx) = mpsc::unbounded::<MainThreadCall>();
576        let task = cx.spawn(async move |cx| {
577            while let Some(message) = rx.next().await {
578                message(cx).await;
579            }
580        });
581
582        let extension_settings = ExtensionSettings::get_global(cx);
583
584        Arc::new(Self {
585            engine: wasm_engine(cx.background_executor()),
586            fs,
587            work_dir,
588            http_client,
589            node_runtime,
590            proxy,
591            release_channel: ReleaseChannel::global(cx),
592            granted_capabilities: extension_settings.granted_capabilities.clone(),
593            _main_thread_message_task: task,
594            main_thread_message_tx: tx,
595        })
596    }
597
598    pub fn load_extension(
599        self: &Arc<Self>,
600        wasm_bytes: Vec<u8>,
601        manifest: &Arc<ExtensionManifest>,
602        cx: &AsyncApp,
603    ) -> Task<Result<WasmExtension>> {
604        let this = self.clone();
605        let manifest = manifest.clone();
606        let executor = cx.background_executor().clone();
607        let load_extension_task = async move {
608            let zed_api_version = parse_wasm_extension_version(&manifest.id, &wasm_bytes)?;
609
610            let component = Component::from_binary(&this.engine, &wasm_bytes)
611                .context("failed to compile wasm component")?;
612            let mut store = wasmtime::Store::new(
613                &this.engine,
614                WasmState {
615                    ctx: this.build_wasi_ctx(&manifest).await?,
616                    manifest: manifest.clone(),
617                    table: ResourceTable::new(),
618                    host: this.clone(),
619                    capability_granter: CapabilityGranter::new(
620                        this.granted_capabilities.clone(),
621                        manifest.clone(),
622                    ),
623                },
624            );
625            // Store will yield after 1 tick, and get a new deadline of 1 tick after each yield.
626            store.set_epoch_deadline(1);
627            store.epoch_deadline_async_yield_and_update(1);
628
629            let mut extension = Extension::instantiate_async(
630                &executor,
631                &mut store,
632                this.release_channel,
633                zed_api_version.clone(),
634                &component,
635            )
636            .await?;
637
638            extension
639                .call_init_extension(&mut store)
640                .await
641                .context("failed to initialize wasm extension")?;
642
643            let (tx, mut rx) = mpsc::unbounded::<ExtensionCall>();
644            let extension_task = async move {
645                // note: Setting the thread local here will slowly "poison" all tokio threads
646                // causing us to not record their panics any longer.
647                //
648                // This is fine though, the main zed binary only uses tokio for livekit and wasm extensions.
649                // Livekit seldom (if ever) panics 🤞 so the likelihood of us missing a panic in sentry is very low.
650                IS_WASM_THREAD.with(|v| v.store(true, Ordering::Release));
651                while let Some(call) = rx.next().await {
652                    (call)(&mut extension, &mut store).await;
653                }
654            };
655
656            anyhow::Ok((
657                extension_task,
658                manifest.clone(),
659                this.work_dir.join(manifest.id.as_ref()).into(),
660                tx,
661                zed_api_version,
662            ))
663        };
664        cx.spawn(async move |cx| {
665            let (extension_task, manifest, work_dir, tx, zed_api_version) =
666                cx.background_executor().spawn(load_extension_task).await?;
667            // we need to run run the task in a tokio context as wasmtime_wasi may
668            // call into tokio, accessing its runtime handle when we trigger the `engine.increment_epoch()` above.
669            let task = Arc::new(gpui_tokio::Tokio::spawn(cx, extension_task)?);
670
671            Ok(WasmExtension {
672                manifest,
673                work_dir,
674                tx,
675                zed_api_version,
676                _task: task,
677            })
678        })
679    }
680
681    async fn build_wasi_ctx(&self, manifest: &Arc<ExtensionManifest>) -> Result<wasi::WasiCtx> {
682        let extension_work_dir = self.work_dir.join(manifest.id.as_ref());
683        self.fs
684            .create_dir(&extension_work_dir)
685            .await
686            .context("failed to create extension work dir")?;
687
688        let file_perms = wasi::FilePerms::all();
689        let dir_perms = wasi::DirPerms::all();
690        let path = SanitizedPath::new(&extension_work_dir).to_string();
691        #[cfg(target_os = "windows")]
692        let path = path.replace('\\', "/");
693
694        let mut ctx = wasi::WasiCtxBuilder::new();
695        ctx.inherit_stdio()
696            .env("PWD", &path)
697            .env("RUST_BACKTRACE", "full");
698
699        ctx.preopened_dir(&path, ".", dir_perms, file_perms)?;
700        ctx.preopened_dir(&path, &path, dir_perms, file_perms)?;
701
702        Ok(ctx.build())
703    }
704
705    pub fn writeable_path_from_extension(&self, id: &Arc<str>, path: &Path) -> Result<PathBuf> {
706        let extension_work_dir = self.work_dir.join(id.as_ref());
707        let path = normalize_path(&extension_work_dir.join(path));
708        anyhow::ensure!(
709            path.starts_with(&extension_work_dir),
710            "cannot write to path {path:?}",
711        );
712        Ok(path)
713    }
714}
715
716pub fn parse_wasm_extension_version(extension_id: &str, wasm_bytes: &[u8]) -> Result<Version> {
717    let mut version = None;
718
719    for part in wasmparser::Parser::new(0).parse_all(wasm_bytes) {
720        if let wasmparser::Payload::CustomSection(s) =
721            part.context("error parsing wasm extension")?
722            && s.name() == "zed:api-version"
723        {
724            version = parse_wasm_extension_version_custom_section(s.data());
725            if version.is_none() {
726                bail!(
727                    "extension {} has invalid zed:api-version section: {:?}",
728                    extension_id,
729                    s.data()
730                );
731            }
732        }
733    }
734
735    // The reason we wait until we're done parsing all of the Wasm bytes to return the version
736    // is to work around a panic that can happen inside of Wasmtime when the bytes are invalid.
737    //
738    // By parsing the entirety of the Wasm bytes before we return, we're able to detect this problem
739    // earlier as an `Err` rather than as a panic.
740    version.with_context(|| format!("extension {extension_id} has no zed:api-version section"))
741}
742
743fn parse_wasm_extension_version_custom_section(data: &[u8]) -> Option<Version> {
744    if data.len() == 6 {
745        Some(Version::new(
746            u16::from_be_bytes([data[0], data[1]]) as _,
747            u16::from_be_bytes([data[2], data[3]]) as _,
748            u16::from_be_bytes([data[4], data[5]]) as _,
749        ))
750    } else {
751        None
752    }
753}
754
755impl WasmExtension {
756    pub async fn load(
757        extension_dir: &Path,
758        manifest: &Arc<ExtensionManifest>,
759        wasm_host: Arc<WasmHost>,
760        cx: &AsyncApp,
761    ) -> Result<Self> {
762        let path = extension_dir.join("extension.wasm");
763
764        let mut wasm_file = wasm_host
765            .fs
766            .open_sync(&path)
767            .await
768            .context(format!("opening wasm file, path: {path:?}"))?;
769
770        let mut wasm_bytes = Vec::new();
771        wasm_file
772            .read_to_end(&mut wasm_bytes)
773            .context(format!("reading wasm file, path: {path:?}"))?;
774
775        wasm_host
776            .load_extension(wasm_bytes, manifest, cx)
777            .await
778            .with_context(|| format!("loading wasm extension: {}", manifest.id))
779    }
780
781    pub async fn call<T, Fn>(&self, f: Fn) -> Result<T>
782    where
783        T: 'static + Send,
784        Fn: 'static
785            + Send
786            + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, T>,
787    {
788        let (return_tx, return_rx) = oneshot::channel();
789        self.tx
790            .unbounded_send(Box::new(move |extension, store| {
791                async {
792                    let result = f(extension, store).await;
793                    return_tx.send(result).ok();
794                }
795                .boxed()
796            }))
797            .map_err(|_| {
798                anyhow!(
799                    "wasm extension channel should not be closed yet, extension {} (id {})",
800                    self.manifest.name,
801                    self.manifest.id,
802                )
803            })?;
804        return_rx.await.with_context(|| {
805            format!(
806                "wasm extension channel, extension {} (id {})",
807                self.manifest.name, self.manifest.id,
808            )
809        })
810    }
811}
812
813impl WasmState {
814    fn on_main_thread<T, Fn>(&self, f: Fn) -> impl 'static + Future<Output = T>
815    where
816        T: 'static + Send,
817        Fn: 'static + Send + for<'a> FnOnce(&'a mut AsyncApp) -> LocalBoxFuture<'a, T>,
818    {
819        let (return_tx, return_rx) = oneshot::channel();
820        self.host
821            .main_thread_message_tx
822            .clone()
823            .unbounded_send(Box::new(move |cx| {
824                async {
825                    let result = f(cx).await;
826                    return_tx.send(result).ok();
827                }
828                .boxed_local()
829            }))
830            .unwrap_or_else(|_| {
831                panic!(
832                    "main thread message channel should not be closed yet, extension {} (id {})",
833                    self.manifest.name, self.manifest.id,
834                )
835            });
836        let name = self.manifest.name.clone();
837        let id = self.manifest.id.clone();
838        async move {
839            return_rx.await.unwrap_or_else(|_| {
840                panic!("main thread message channel, extension {name} (id {id})")
841            })
842        }
843    }
844
845    fn work_dir(&self) -> PathBuf {
846        self.host.work_dir.join(self.manifest.id.as_ref())
847    }
848
849    fn extension_error(&self, message: String) -> anyhow::Error {
850        anyhow!(
851            "from extension \"{}\" version {}: {}",
852            self.manifest.name,
853            self.manifest.version,
854            message
855        )
856    }
857}
858
859impl wasi::WasiView for WasmState {
860    fn table(&mut self) -> &mut ResourceTable {
861        &mut self.table
862    }
863
864    fn ctx(&mut self) -> &mut wasi::WasiCtx {
865        &mut self.ctx
866    }
867}
868
869/// Wrapper around a mini-moka bounded cache for storing incremental compilation artifacts.
870/// Since wasm modules have many similar elements, this can save us a lot of work at the
871/// cost of a small memory footprint. However, we don't want this to be unbounded, so we use
872/// a LFU/LRU cache to evict less used cache entries.
873#[derive(Debug)]
874struct IncrementalCompilationCache {
875    cache: Cache<Vec<u8>, Vec<u8>>,
876}
877
878impl IncrementalCompilationCache {
879    fn new() -> Self {
880        let cache = Cache::builder()
881            // Cap this at 32 MB for now. Our extensions turn into roughly 512kb in the cache,
882            // which means we could store 64 completely novel extensions in the cache, but in
883            // practice we will more than that, which is more than enough for our use case.
884            .max_capacity(32 * 1024 * 1024)
885            .weigher(|k: &Vec<u8>, v: &Vec<u8>| (k.len() + v.len()).try_into().unwrap_or(u32::MAX))
886            .build();
887        Self { cache }
888    }
889}
890
891impl CacheStore for IncrementalCompilationCache {
892    fn get(&self, key: &[u8]) -> Option<Cow<'_, [u8]>> {
893        self.cache.get(key).map(|v| v.into())
894    }
895
896    fn insert(&self, key: &[u8], value: Vec<u8>) -> bool {
897        self.cache.insert(key.to_vec(), value);
898        true
899    }
900}