1use crate::ExtensionManifest;
2use anyhow::{anyhow, bail, Context as _, Result};
3use async_compression::futures::bufread::GzipDecoder;
4use async_tar::Archive;
5use async_trait::async_trait;
6use fs::{normalize_path, Fs};
7use futures::{
8 channel::{
9 mpsc::{self, UnboundedSender},
10 oneshot,
11 },
12 future::BoxFuture,
13 io::BufReader,
14 Future, FutureExt, StreamExt as _,
15};
16use gpui::BackgroundExecutor;
17use language::{LanguageRegistry, LanguageServerBinaryStatus, LspAdapterDelegate};
18use node_runtime::NodeRuntime;
19use std::{
20 env,
21 path::{Path, PathBuf},
22 sync::{Arc, OnceLock},
23};
24use util::{http::HttpClient, SemanticVersion};
25use wasmtime::{
26 component::{Component, Linker, Resource, ResourceTable},
27 Engine, Store,
28};
29use wasmtime_wasi::preview2::{self as wasi, WasiCtx};
30
31pub mod wit {
32 wasmtime::component::bindgen!({
33 async: true,
34 path: "../extension_api/wit",
35 with: {
36 "worktree": super::ExtensionWorktree,
37 },
38 });
39}
40
41pub type ExtensionWorktree = Arc<dyn LspAdapterDelegate>;
42
43pub(crate) struct WasmHost {
44 engine: Engine,
45 linker: Arc<wasmtime::component::Linker<WasmState>>,
46 http_client: Arc<dyn HttpClient>,
47 node_runtime: Arc<dyn NodeRuntime>,
48 language_registry: Arc<LanguageRegistry>,
49 fs: Arc<dyn Fs>,
50 pub(crate) work_dir: PathBuf,
51}
52
53#[derive(Clone)]
54pub struct WasmExtension {
55 tx: UnboundedSender<ExtensionCall>,
56 pub(crate) manifest: Arc<ExtensionManifest>,
57 #[allow(unused)]
58 zed_api_version: SemanticVersion,
59}
60
61pub(crate) struct WasmState {
62 manifest: Arc<ExtensionManifest>,
63 table: ResourceTable,
64 ctx: wasi::WasiCtx,
65 host: Arc<WasmHost>,
66}
67
68type ExtensionCall = Box<
69 dyn Send
70 + for<'a> FnOnce(&'a mut wit::Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, ()>,
71>;
72
73static WASM_ENGINE: OnceLock<wasmtime::Engine> = OnceLock::new();
74
75impl WasmHost {
76 pub fn new(
77 fs: Arc<dyn Fs>,
78 http_client: Arc<dyn HttpClient>,
79 node_runtime: Arc<dyn NodeRuntime>,
80 language_registry: Arc<LanguageRegistry>,
81 work_dir: PathBuf,
82 ) -> Arc<Self> {
83 let engine = WASM_ENGINE
84 .get_or_init(|| {
85 let mut config = wasmtime::Config::new();
86 config.wasm_component_model(true);
87 config.async_support(true);
88 wasmtime::Engine::new(&config).unwrap()
89 })
90 .clone();
91 let mut linker = Linker::new(&engine);
92 wasi::command::add_to_linker(&mut linker).unwrap();
93 wit::Extension::add_to_linker(&mut linker, wasi_view).unwrap();
94 Arc::new(Self {
95 engine,
96 linker: Arc::new(linker),
97 fs,
98 work_dir,
99 http_client,
100 node_runtime,
101 language_registry,
102 })
103 }
104
105 pub fn load_extension(
106 self: &Arc<Self>,
107 wasm_bytes: Vec<u8>,
108 manifest: Arc<ExtensionManifest>,
109 executor: BackgroundExecutor,
110 ) -> impl 'static + Future<Output = Result<WasmExtension>> {
111 let this = self.clone();
112 async move {
113 let component = Component::from_binary(&this.engine, &wasm_bytes)
114 .context("failed to compile wasm component")?;
115
116 let mut zed_api_version = None;
117 for part in wasmparser::Parser::new(0).parse_all(&wasm_bytes) {
118 if let wasmparser::Payload::CustomSection(s) = part? {
119 if s.name() == "zed:api-version" {
120 zed_api_version = parse_extension_version(s.data());
121 if zed_api_version.is_none() {
122 bail!(
123 "extension {} has invalid zed:api-version section: {:?}",
124 manifest.id,
125 s.data()
126 );
127 }
128 }
129 }
130 }
131
132 let Some(zed_api_version) = zed_api_version else {
133 bail!("extension {} has no zed:api-version section", manifest.id);
134 };
135
136 let mut store = wasmtime::Store::new(
137 &this.engine,
138 WasmState {
139 ctx: this.build_wasi_ctx(&manifest).await?,
140 manifest: manifest.clone(),
141 table: ResourceTable::new(),
142 host: this.clone(),
143 },
144 );
145
146 let (mut extension, instance) =
147 wit::Extension::instantiate_async(&mut store, &component, &this.linker)
148 .await
149 .context("failed to instantiate wasm extension")?;
150 extension
151 .call_init_extension(&mut store)
152 .await
153 .context("failed to initialize wasm extension")?;
154
155 let (tx, mut rx) = mpsc::unbounded::<ExtensionCall>();
156 executor
157 .spawn(async move {
158 let _instance = instance;
159 while let Some(call) = rx.next().await {
160 (call)(&mut extension, &mut store).await;
161 }
162 })
163 .detach();
164
165 Ok(WasmExtension {
166 manifest,
167 tx,
168 zed_api_version,
169 })
170 }
171 }
172
173 async fn build_wasi_ctx(&self, manifest: &Arc<ExtensionManifest>) -> Result<WasiCtx> {
174 use cap_std::{ambient_authority, fs::Dir};
175
176 let extension_work_dir = self.work_dir.join(manifest.id.as_ref());
177 self.fs
178 .create_dir(&extension_work_dir)
179 .await
180 .context("failed to create extension work dir")?;
181
182 let work_dir_preopen = Dir::open_ambient_dir(&extension_work_dir, ambient_authority())
183 .context("failed to preopen extension work directory")?;
184 let current_dir_preopen = work_dir_preopen
185 .try_clone()
186 .context("failed to preopen extension current directory")?;
187 let extension_work_dir = extension_work_dir.to_string_lossy();
188
189 let perms = wasi::FilePerms::all();
190 let dir_perms = wasi::DirPerms::all();
191
192 Ok(wasi::WasiCtxBuilder::new()
193 .inherit_stdio()
194 .preopened_dir(current_dir_preopen, dir_perms, perms, ".")
195 .preopened_dir(work_dir_preopen, dir_perms, perms, &extension_work_dir)
196 .env("PWD", &extension_work_dir)
197 .env("RUST_BACKTRACE", "full")
198 .build())
199 }
200
201 pub fn path_from_extension(&self, id: &Arc<str>, path: &Path) -> PathBuf {
202 let extension_work_dir = self.work_dir.join(id.as_ref());
203 normalize_path(&extension_work_dir.join(path))
204 }
205
206 pub fn writeable_path_from_extension(&self, id: &Arc<str>, path: &Path) -> Result<PathBuf> {
207 let extension_work_dir = self.work_dir.join(id.as_ref());
208 let path = normalize_path(&extension_work_dir.join(path));
209 if path.starts_with(&extension_work_dir) {
210 Ok(path)
211 } else {
212 Err(anyhow!("cannot write to path {}", path.display()))
213 }
214 }
215}
216
217fn parse_extension_version(data: &[u8]) -> Option<SemanticVersion> {
218 if data.len() == 6 {
219 Some(SemanticVersion {
220 major: u16::from_be_bytes([data[0], data[1]]) as _,
221 minor: u16::from_be_bytes([data[2], data[3]]) as _,
222 patch: u16::from_be_bytes([data[4], data[5]]) as _,
223 })
224 } else {
225 None
226 }
227}
228
229impl WasmExtension {
230 pub async fn call<T, Fn>(&self, f: Fn) -> T
231 where
232 T: 'static + Send,
233 Fn: 'static
234 + Send
235 + for<'a> FnOnce(&'a mut wit::Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, T>,
236 {
237 let (return_tx, return_rx) = oneshot::channel();
238 self.tx
239 .clone()
240 .unbounded_send(Box::new(move |extension, store| {
241 async {
242 let result = f(extension, store).await;
243 return_tx.send(result).ok();
244 }
245 .boxed()
246 }))
247 .expect("wasm extension channel should not be closed yet");
248 return_rx.await.expect("wasm extension channel")
249 }
250}
251
252#[async_trait]
253impl wit::HostWorktree for WasmState {
254 async fn read_text_file(
255 &mut self,
256 delegate: Resource<Arc<dyn LspAdapterDelegate>>,
257 path: String,
258 ) -> wasmtime::Result<Result<String, String>> {
259 let delegate = self.table.get(&delegate)?;
260 Ok(delegate
261 .read_text_file(path.into())
262 .await
263 .map_err(|error| error.to_string()))
264 }
265
266 async fn shell_env(
267 &mut self,
268 delegate: Resource<Arc<dyn LspAdapterDelegate>>,
269 ) -> wasmtime::Result<wit::EnvVars> {
270 let delegate = self.table.get(&delegate)?;
271 Ok(delegate.shell_env().await.into_iter().collect())
272 }
273
274 async fn which(
275 &mut self,
276 delegate: Resource<Arc<dyn LspAdapterDelegate>>,
277 binary_name: String,
278 ) -> wasmtime::Result<Option<String>> {
279 let delegate = self.table.get(&delegate)?;
280 Ok(delegate
281 .which(binary_name.as_ref())
282 .await
283 .map(|path| path.to_string_lossy().to_string()))
284 }
285
286 fn drop(&mut self, _worktree: Resource<wit::Worktree>) -> Result<()> {
287 // we only ever hand out borrows of worktrees
288 Ok(())
289 }
290}
291
292#[async_trait]
293impl wit::ExtensionImports for WasmState {
294 async fn npm_package_latest_version(
295 &mut self,
296 package_name: String,
297 ) -> wasmtime::Result<Result<String, String>> {
298 async fn inner(this: &mut WasmState, package_name: String) -> anyhow::Result<String> {
299 this.host
300 .node_runtime
301 .npm_package_latest_version(&package_name)
302 .await
303 }
304
305 Ok(inner(self, package_name)
306 .await
307 .map_err(|err| err.to_string()))
308 }
309
310 async fn latest_github_release(
311 &mut self,
312 repo: String,
313 options: wit::GithubReleaseOptions,
314 ) -> wasmtime::Result<Result<wit::GithubRelease, String>> {
315 async fn inner(
316 this: &mut WasmState,
317 repo: String,
318 options: wit::GithubReleaseOptions,
319 ) -> anyhow::Result<wit::GithubRelease> {
320 let release = util::github::latest_github_release(
321 &repo,
322 options.require_assets,
323 options.pre_release,
324 this.host.http_client.clone(),
325 )
326 .await?;
327 Ok(wit::GithubRelease {
328 version: release.tag_name,
329 assets: release
330 .assets
331 .into_iter()
332 .map(|asset| wit::GithubReleaseAsset {
333 name: asset.name,
334 download_url: asset.browser_download_url,
335 })
336 .collect(),
337 })
338 }
339
340 Ok(inner(self, repo, options)
341 .await
342 .map_err(|err| err.to_string()))
343 }
344
345 async fn current_platform(&mut self) -> Result<(wit::Os, wit::Architecture)> {
346 Ok((
347 match env::consts::OS {
348 "macos" => wit::Os::Mac,
349 "linux" => wit::Os::Linux,
350 "windows" => wit::Os::Windows,
351 _ => panic!("unsupported os"),
352 },
353 match env::consts::ARCH {
354 "aarch64" => wit::Architecture::Aarch64,
355 "x86" => wit::Architecture::X86,
356 "x86_64" => wit::Architecture::X8664,
357 _ => panic!("unsupported architecture"),
358 },
359 ))
360 }
361
362 async fn set_language_server_installation_status(
363 &mut self,
364 server_name: String,
365 status: wit::LanguageServerInstallationStatus,
366 ) -> wasmtime::Result<()> {
367 let status = match status {
368 wit::LanguageServerInstallationStatus::CheckingForUpdate => {
369 LanguageServerBinaryStatus::CheckingForUpdate
370 }
371 wit::LanguageServerInstallationStatus::Downloading => {
372 LanguageServerBinaryStatus::Downloading
373 }
374 wit::LanguageServerInstallationStatus::Downloaded => {
375 LanguageServerBinaryStatus::Downloaded
376 }
377 wit::LanguageServerInstallationStatus::Cached => LanguageServerBinaryStatus::Cached,
378 wit::LanguageServerInstallationStatus::Failed(error) => {
379 LanguageServerBinaryStatus::Failed { error }
380 }
381 };
382
383 self.host
384 .language_registry
385 .update_lsp_status(language::LanguageServerName(server_name.into()), status);
386 Ok(())
387 }
388
389 async fn download_file(
390 &mut self,
391 url: String,
392 path: String,
393 file_type: wit::DownloadedFileType,
394 ) -> wasmtime::Result<Result<(), String>> {
395 let path = PathBuf::from(path);
396
397 async fn inner(
398 this: &mut WasmState,
399 url: String,
400 path: PathBuf,
401 file_type: wit::DownloadedFileType,
402 ) -> anyhow::Result<()> {
403 let extension_work_dir = this.host.work_dir.join(this.manifest.id.as_ref());
404
405 this.host.fs.create_dir(&extension_work_dir).await?;
406
407 let destination_path = this
408 .host
409 .writeable_path_from_extension(&this.manifest.id, &path)?;
410
411 let mut response = this
412 .host
413 .http_client
414 .get(&url, Default::default(), true)
415 .await
416 .map_err(|err| anyhow!("error downloading release: {}", err))?;
417
418 if !response.status().is_success() {
419 Err(anyhow!(
420 "download failed with status {}",
421 response.status().to_string()
422 ))?;
423 }
424 let body = BufReader::new(response.body_mut());
425
426 match file_type {
427 wit::DownloadedFileType::Uncompressed => {
428 futures::pin_mut!(body);
429 this.host
430 .fs
431 .create_file_with(&destination_path, body)
432 .await?;
433 }
434 wit::DownloadedFileType::Gzip => {
435 let body = GzipDecoder::new(body);
436 futures::pin_mut!(body);
437 this.host
438 .fs
439 .create_file_with(&destination_path, body)
440 .await?;
441 }
442 wit::DownloadedFileType::GzipTar => {
443 let body = GzipDecoder::new(body);
444 futures::pin_mut!(body);
445 this.host
446 .fs
447 .extract_tar_file(&destination_path, Archive::new(body))
448 .await?;
449 }
450 wit::DownloadedFileType::Zip => {
451 let file_name = destination_path
452 .file_name()
453 .ok_or_else(|| anyhow!("invalid download path"))?
454 .to_string_lossy();
455 let zip_filename = format!("{file_name}.zip");
456 let mut zip_path = destination_path.clone();
457 zip_path.set_file_name(zip_filename);
458
459 futures::pin_mut!(body);
460 this.host.fs.create_file_with(&zip_path, body).await?;
461
462 let unzip_status = std::process::Command::new("unzip")
463 .current_dir(&extension_work_dir)
464 .arg(&zip_path)
465 .output()?
466 .status;
467 if !unzip_status.success() {
468 Err(anyhow!("failed to unzip {} archive", path.display()))?;
469 }
470 }
471 }
472
473 Ok(())
474 }
475
476 Ok(inner(self, url, path, file_type)
477 .await
478 .map(|_| ())
479 .map_err(|err| err.to_string()))
480 }
481}
482
483fn wasi_view(state: &mut WasmState) -> &mut WasmState {
484 state
485}
486
487impl wasi::WasiView for WasmState {
488 fn table(&mut self) -> &mut ResourceTable {
489 &mut self.table
490 }
491
492 fn ctx(&mut self) -> &mut wasi::WasiCtx {
493 &mut self.ctx
494 }
495}