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::p2::{self as wasi, IoView as _};
 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
608        // Parse version and compile component on gpui's background executor.
609        // These are cpu-bound operations that don't require a tokio runtime.
610        let compile_task = {
611            let manifest_id = manifest.id.clone();
612            let engine = this.engine.clone();
613
614            executor.spawn(async move {
615                let zed_api_version = parse_wasm_extension_version(&manifest_id, &wasm_bytes)?;
616                let component = Component::from_binary(&engine, &wasm_bytes)
617                    .context("failed to compile wasm component")?;
618
619                anyhow::Ok((zed_api_version, component))
620            })
621        };
622
623        let load_extension = |zed_api_version: Version, component| async move {
624            let wasi_ctx = this.build_wasi_ctx(&manifest).await?;
625            let mut store = wasmtime::Store::new(
626                &this.engine,
627                WasmState {
628                    ctx: wasi_ctx,
629                    manifest: manifest.clone(),
630                    table: ResourceTable::new(),
631                    host: this.clone(),
632                    capability_granter: CapabilityGranter::new(
633                        this.granted_capabilities.clone(),
634                        manifest.clone(),
635                    ),
636                },
637            );
638            // Store will yield after 1 tick, and get a new deadline of 1 tick after each yield.
639            store.set_epoch_deadline(1);
640            store.epoch_deadline_async_yield_and_update(1);
641
642            let mut extension = Extension::instantiate_async(
643                &executor,
644                &mut store,
645                this.release_channel,
646                zed_api_version.clone(),
647                &component,
648            )
649            .await?;
650
651            extension
652                .call_init_extension(&mut store)
653                .await
654                .context("failed to initialize wasm extension")?;
655
656            let (tx, mut rx) = mpsc::unbounded::<ExtensionCall>();
657            let extension_task = async move {
658                // note: Setting the thread local here will slowly "poison" all tokio threads
659                // causing us to not record their panics any longer.
660                //
661                // This is fine though, the main zed binary only uses tokio for livekit and wasm extensions.
662                // Livekit seldom (if ever) panics 🤞 so the likelihood of us missing a panic in sentry is very low.
663                IS_WASM_THREAD.with(|v| v.store(true, Ordering::Release));
664                while let Some(call) = rx.next().await {
665                    (call)(&mut extension, &mut store).await;
666                }
667            };
668
669            anyhow::Ok((
670                extension_task,
671                manifest.clone(),
672                this.work_dir.join(manifest.id.as_ref()).into(),
673                tx,
674                zed_api_version,
675            ))
676        };
677
678        cx.spawn(async move |cx| {
679            let (zed_api_version, component) = compile_task.await?;
680
681            // Run wasi-dependent operations on tokio.
682            // wasmtime_wasi internally uses tokio for I/O operations.
683            let (extension_task, manifest, work_dir, tx, zed_api_version) =
684                gpui_tokio::Tokio::spawn(cx, load_extension(zed_api_version, component)).await??;
685
686            // Run the extension message loop on tokio since extension
687            // calls may invoke wasi functions that require a tokio runtime.
688            let task = Arc::new(gpui_tokio::Tokio::spawn(cx, extension_task));
689
690            Ok(WasmExtension {
691                manifest,
692                work_dir,
693                tx,
694                zed_api_version,
695                _task: task,
696            })
697        })
698    }
699
700    async fn build_wasi_ctx(&self, manifest: &Arc<ExtensionManifest>) -> Result<wasi::WasiCtx> {
701        let extension_work_dir = self.work_dir.join(manifest.id.as_ref());
702        self.fs
703            .create_dir(&extension_work_dir)
704            .await
705            .context("failed to create extension work dir")?;
706
707        let file_perms = wasmtime_wasi::FilePerms::all();
708        let dir_perms = wasmtime_wasi::DirPerms::all();
709        let path = SanitizedPath::new(&extension_work_dir).to_string();
710        #[cfg(target_os = "windows")]
711        let path = path.replace('\\', "/");
712
713        let mut ctx = wasi::WasiCtxBuilder::new();
714        ctx.inherit_stdio()
715            .env("PWD", &path)
716            .env("RUST_BACKTRACE", "full");
717
718        ctx.preopened_dir(&path, ".", dir_perms, file_perms)?;
719        ctx.preopened_dir(&path, &path, dir_perms, file_perms)?;
720
721        Ok(ctx.build())
722    }
723
724    pub fn writeable_path_from_extension(&self, id: &Arc<str>, path: &Path) -> Result<PathBuf> {
725        let extension_work_dir = self.work_dir.join(id.as_ref());
726        let path = normalize_path(&extension_work_dir.join(path));
727        anyhow::ensure!(
728            path.starts_with(&extension_work_dir),
729            "cannot write to path {path:?}",
730        );
731        Ok(path)
732    }
733}
734
735pub fn parse_wasm_extension_version(extension_id: &str, wasm_bytes: &[u8]) -> Result<Version> {
736    let mut version = None;
737
738    for part in wasmparser::Parser::new(0).parse_all(wasm_bytes) {
739        if let wasmparser::Payload::CustomSection(s) =
740            part.context("error parsing wasm extension")?
741            && s.name() == "zed:api-version"
742        {
743            version = parse_wasm_extension_version_custom_section(s.data());
744            if version.is_none() {
745                bail!(
746                    "extension {} has invalid zed:api-version section: {:?}",
747                    extension_id,
748                    s.data()
749                );
750            }
751        }
752    }
753
754    // The reason we wait until we're done parsing all of the Wasm bytes to return the version
755    // is to work around a panic that can happen inside of Wasmtime when the bytes are invalid.
756    //
757    // By parsing the entirety of the Wasm bytes before we return, we're able to detect this problem
758    // earlier as an `Err` rather than as a panic.
759    version.with_context(|| format!("extension {extension_id} has no zed:api-version section"))
760}
761
762fn parse_wasm_extension_version_custom_section(data: &[u8]) -> Option<Version> {
763    if data.len() == 6 {
764        Some(Version::new(
765            u16::from_be_bytes([data[0], data[1]]) as _,
766            u16::from_be_bytes([data[2], data[3]]) as _,
767            u16::from_be_bytes([data[4], data[5]]) as _,
768        ))
769    } else {
770        None
771    }
772}
773
774impl WasmExtension {
775    pub async fn load(
776        extension_dir: &Path,
777        manifest: &Arc<ExtensionManifest>,
778        wasm_host: Arc<WasmHost>,
779        cx: &AsyncApp,
780    ) -> Result<Self> {
781        let path = extension_dir.join("extension.wasm");
782
783        let mut wasm_file = wasm_host
784            .fs
785            .open_sync(&path)
786            .await
787            .context(format!("opening wasm file, path: {path:?}"))?;
788
789        let mut wasm_bytes = Vec::new();
790        wasm_file
791            .read_to_end(&mut wasm_bytes)
792            .context(format!("reading wasm file, path: {path:?}"))?;
793
794        wasm_host
795            .load_extension(wasm_bytes, manifest, cx)
796            .await
797            .with_context(|| format!("loading wasm extension: {}", manifest.id))
798    }
799
800    pub async fn call<T, Fn>(&self, f: Fn) -> Result<T>
801    where
802        T: 'static + Send,
803        Fn: 'static
804            + Send
805            + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, T>,
806    {
807        let (return_tx, return_rx) = oneshot::channel();
808        self.tx
809            .unbounded_send(Box::new(move |extension, store| {
810                async {
811                    let result = f(extension, store).await;
812                    return_tx.send(result).ok();
813                }
814                .boxed()
815            }))
816            .map_err(|_| {
817                anyhow!(
818                    "wasm extension channel should not be closed yet, extension {} (id {})",
819                    self.manifest.name,
820                    self.manifest.id,
821                )
822            })?;
823        return_rx.await.with_context(|| {
824            format!(
825                "wasm extension channel, extension {} (id {})",
826                self.manifest.name, self.manifest.id,
827            )
828        })
829    }
830}
831
832impl WasmState {
833    fn on_main_thread<T, Fn>(&self, f: Fn) -> impl 'static + Future<Output = T>
834    where
835        T: 'static + Send,
836        Fn: 'static + Send + for<'a> FnOnce(&'a mut AsyncApp) -> LocalBoxFuture<'a, T>,
837    {
838        let (return_tx, return_rx) = oneshot::channel();
839        self.host
840            .main_thread_message_tx
841            .clone()
842            .unbounded_send(Box::new(move |cx| {
843                async {
844                    let result = f(cx).await;
845                    return_tx.send(result).ok();
846                }
847                .boxed_local()
848            }))
849            .unwrap_or_else(|_| {
850                panic!(
851                    "main thread message channel should not be closed yet, extension {} (id {})",
852                    self.manifest.name, self.manifest.id,
853                )
854            });
855        let name = self.manifest.name.clone();
856        let id = self.manifest.id.clone();
857        async move {
858            return_rx.await.unwrap_or_else(|_| {
859                panic!("main thread message channel, extension {name} (id {id})")
860            })
861        }
862    }
863
864    fn work_dir(&self) -> PathBuf {
865        self.host.work_dir.join(self.manifest.id.as_ref())
866    }
867
868    fn extension_error(&self, message: String) -> anyhow::Error {
869        anyhow!(
870            "from extension \"{}\" version {}: {}",
871            self.manifest.name,
872            self.manifest.version,
873            message
874        )
875    }
876}
877
878impl wasi::IoView for WasmState {
879    fn table(&mut self) -> &mut ResourceTable {
880        &mut self.table
881    }
882}
883
884impl wasi::WasiView for WasmState {
885    fn ctx(&mut self) -> &mut wasi::WasiCtx {
886        &mut self.ctx
887    }
888}
889
890/// Wrapper around a mini-moka bounded cache for storing incremental compilation artifacts.
891/// Since wasm modules have many similar elements, this can save us a lot of work at the
892/// cost of a small memory footprint. However, we don't want this to be unbounded, so we use
893/// a LFU/LRU cache to evict less used cache entries.
894#[derive(Debug)]
895struct IncrementalCompilationCache {
896    cache: Cache<Vec<u8>, Vec<u8>>,
897}
898
899impl IncrementalCompilationCache {
900    fn new() -> Self {
901        let cache = Cache::builder()
902            // Cap this at 32 MB for now. Our extensions turn into roughly 512kb in the cache,
903            // which means we could store 64 completely novel extensions in the cache, but in
904            // practice we will more than that, which is more than enough for our use case.
905            .max_capacity(32 * 1024 * 1024)
906            .weigher(|k: &Vec<u8>, v: &Vec<u8>| (k.len() + v.len()).try_into().unwrap_or(u32::MAX))
907            .build();
908        Self { cache }
909    }
910}
911
912impl CacheStore for IncrementalCompilationCache {
913    fn get(&self, key: &[u8]) -> Option<Cow<'_, [u8]>> {
914        self.cache.get(key).map(|v| v.into())
915    }
916
917    fn insert(&self, key: &[u8], value: Vec<u8>) -> bool {
918        self.cache.insert(key.to_vec(), value);
919        true
920    }
921}