since_v0_1_0.rs

  1use crate::wasm_host::{wit::ToWasmtimeResult, WasmState};
  2use ::http_client::{AsyncBody, HttpRequestExt};
  3use ::settings::{Settings, WorktreeId};
  4use anyhow::{anyhow, bail, Context, Result};
  5use async_compression::futures::bufread::GzipDecoder;
  6use async_tar::Archive;
  7use async_trait::async_trait;
  8use futures::{io::BufReader, FutureExt as _};
  9use futures::{lock::Mutex, AsyncReadExt};
 10use indexed_docs::IndexedDocsDatabase;
 11use language::{
 12    language_settings::AllLanguageSettings, LanguageServerBinaryStatus, LspAdapterDelegate,
 13};
 14use language::{LanguageName, LanguageServerName};
 15use project::project_settings::ProjectSettings;
 16use semantic_version::SemanticVersion;
 17use std::{
 18    path::{Path, PathBuf},
 19    sync::{Arc, OnceLock},
 20};
 21use util::maybe;
 22use wasmtime::component::{Linker, Resource};
 23
 24use super::latest;
 25
 26pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 1, 0);
 27pub const MAX_VERSION: SemanticVersion = SemanticVersion::new(0, 1, 0);
 28
 29wasmtime::component::bindgen!({
 30    async: true,
 31    trappable_imports: true,
 32    path: "../extension_api/wit/since_v0.1.0",
 33    with: {
 34         "worktree": ExtensionWorktree,
 35         "key-value-store": ExtensionKeyValueStore,
 36         "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream,
 37         "zed:extension/github": latest::zed::extension::github,
 38         "zed:extension/lsp": latest::zed::extension::lsp,
 39         "zed:extension/nodejs": latest::zed::extension::nodejs,
 40         "zed:extension/platform": latest::zed::extension::platform,
 41         "zed:extension/slash-command": latest::zed::extension::slash_command,
 42    },
 43});
 44
 45pub use self::zed::extension::*;
 46
 47mod settings {
 48    include!(concat!(env!("OUT_DIR"), "/since_v0.1.0/settings.rs"));
 49}
 50
 51pub type ExtensionWorktree = Arc<dyn LspAdapterDelegate>;
 52pub type ExtensionKeyValueStore = Arc<IndexedDocsDatabase>;
 53pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
 54
 55pub fn linker() -> &'static Linker<WasmState> {
 56    static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
 57    LINKER.get_or_init(|| super::new_linker(Extension::add_to_linker))
 58}
 59
 60impl From<Command> for latest::Command {
 61    fn from(value: Command) -> Self {
 62        Self {
 63            command: value.command,
 64            args: value.args,
 65            env: value.env,
 66        }
 67    }
 68}
 69
 70impl From<SettingsLocation> for latest::SettingsLocation {
 71    fn from(value: SettingsLocation) -> Self {
 72        Self {
 73            worktree_id: value.worktree_id,
 74            path: value.path,
 75        }
 76    }
 77}
 78
 79impl From<LanguageServerInstallationStatus> for latest::LanguageServerInstallationStatus {
 80    fn from(value: LanguageServerInstallationStatus) -> Self {
 81        match value {
 82            LanguageServerInstallationStatus::None => Self::None,
 83            LanguageServerInstallationStatus::Downloading => Self::Downloading,
 84            LanguageServerInstallationStatus::CheckingForUpdate => Self::CheckingForUpdate,
 85            LanguageServerInstallationStatus::Failed(message) => Self::Failed(message),
 86        }
 87    }
 88}
 89
 90impl From<DownloadedFileType> for latest::DownloadedFileType {
 91    fn from(value: DownloadedFileType) -> Self {
 92        match value {
 93            DownloadedFileType::Gzip => Self::Gzip,
 94            DownloadedFileType::GzipTar => Self::GzipTar,
 95            DownloadedFileType::Zip => Self::Zip,
 96            DownloadedFileType::Uncompressed => Self::Uncompressed,
 97        }
 98    }
 99}
100
101impl From<Range> for latest::Range {
102    fn from(value: Range) -> Self {
103        Self {
104            start: value.start,
105            end: value.end,
106        }
107    }
108}
109
110impl From<CodeLabelSpan> for latest::CodeLabelSpan {
111    fn from(value: CodeLabelSpan) -> Self {
112        match value {
113            CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
114            CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
115        }
116    }
117}
118
119impl From<CodeLabelSpanLiteral> for latest::CodeLabelSpanLiteral {
120    fn from(value: CodeLabelSpanLiteral) -> Self {
121        Self {
122            text: value.text,
123            highlight_name: value.highlight_name,
124        }
125    }
126}
127
128impl From<CodeLabel> for latest::CodeLabel {
129    fn from(value: CodeLabel) -> Self {
130        Self {
131            code: value.code,
132            spans: value.spans.into_iter().map(Into::into).collect(),
133            filter_range: value.filter_range.into(),
134        }
135    }
136}
137
138#[async_trait]
139impl HostKeyValueStore for WasmState {
140    async fn insert(
141        &mut self,
142        kv_store: Resource<ExtensionKeyValueStore>,
143        key: String,
144        value: String,
145    ) -> wasmtime::Result<Result<(), String>> {
146        let kv_store = self.table.get(&kv_store)?;
147        kv_store.insert(key, value).await.to_wasmtime_result()
148    }
149
150    fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
151        // We only ever hand out borrows of key-value stores.
152        Ok(())
153    }
154}
155
156#[async_trait]
157impl HostWorktree for WasmState {
158    async fn id(
159        &mut self,
160        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
161    ) -> wasmtime::Result<u64> {
162        let delegate = self.table.get(&delegate)?;
163        Ok(delegate.worktree_id().to_proto())
164    }
165
166    async fn root_path(
167        &mut self,
168        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
169    ) -> wasmtime::Result<String> {
170        let delegate = self.table.get(&delegate)?;
171        Ok(delegate.worktree_root_path().to_string_lossy().to_string())
172    }
173
174    async fn read_text_file(
175        &mut self,
176        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
177        path: String,
178    ) -> wasmtime::Result<Result<String, String>> {
179        let delegate = self.table.get(&delegate)?;
180        Ok(delegate
181            .read_text_file(path.into())
182            .await
183            .map_err(|error| error.to_string()))
184    }
185
186    async fn shell_env(
187        &mut self,
188        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
189    ) -> wasmtime::Result<EnvVars> {
190        let delegate = self.table.get(&delegate)?;
191        Ok(delegate.shell_env().await.into_iter().collect())
192    }
193
194    async fn which(
195        &mut self,
196        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
197        binary_name: String,
198    ) -> wasmtime::Result<Option<String>> {
199        let delegate = self.table.get(&delegate)?;
200        Ok(delegate
201            .which(binary_name.as_ref())
202            .await
203            .map(|path| path.to_string_lossy().to_string()))
204    }
205
206    fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
207        // We only ever hand out borrows of worktrees.
208        Ok(())
209    }
210}
211
212#[async_trait]
213impl common::Host for WasmState {}
214
215#[async_trait]
216impl http_client::Host for WasmState {
217    async fn fetch(
218        &mut self,
219        request: http_client::HttpRequest,
220    ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
221        maybe!(async {
222            let url = &request.url;
223            let request = convert_request(&request)?;
224            let mut response = self.host.http_client.send(request).await?;
225
226            if response.status().is_client_error() || response.status().is_server_error() {
227                bail!("failed to fetch '{url}': status code {}", response.status())
228            }
229            convert_response(&mut response).await
230        })
231        .await
232        .to_wasmtime_result()
233    }
234
235    async fn fetch_stream(
236        &mut self,
237        request: http_client::HttpRequest,
238    ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
239        let request = convert_request(&request)?;
240        let response = self.host.http_client.send(request);
241        maybe!(async {
242            let response = response.await?;
243            let stream = Arc::new(Mutex::new(response));
244            let resource = self.table.push(stream)?;
245            Ok(resource)
246        })
247        .await
248        .to_wasmtime_result()
249    }
250}
251
252#[async_trait]
253impl http_client::HostHttpResponseStream for WasmState {
254    async fn next_chunk(
255        &mut self,
256        resource: Resource<ExtensionHttpResponseStream>,
257    ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
258        let stream = self.table.get(&resource)?.clone();
259        maybe!(async move {
260            let mut response = stream.lock().await;
261            let mut buffer = vec![0; 8192]; // 8KB buffer
262            let bytes_read = response.body_mut().read(&mut buffer).await?;
263            if bytes_read == 0 {
264                Ok(None)
265            } else {
266                buffer.truncate(bytes_read);
267                Ok(Some(buffer))
268            }
269        })
270        .await
271        .to_wasmtime_result()
272    }
273
274    fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
275        Ok(())
276    }
277}
278
279impl From<http_client::HttpMethod> for ::http_client::Method {
280    fn from(value: http_client::HttpMethod) -> Self {
281        match value {
282            http_client::HttpMethod::Get => Self::GET,
283            http_client::HttpMethod::Post => Self::POST,
284            http_client::HttpMethod::Put => Self::PUT,
285            http_client::HttpMethod::Delete => Self::DELETE,
286            http_client::HttpMethod::Head => Self::HEAD,
287            http_client::HttpMethod::Options => Self::OPTIONS,
288            http_client::HttpMethod::Patch => Self::PATCH,
289        }
290    }
291}
292
293fn convert_request(
294    extension_request: &http_client::HttpRequest,
295) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
296    let mut request = ::http_client::Request::builder()
297        .method(::http_client::Method::from(extension_request.method))
298        .uri(&extension_request.url)
299        .follow_redirects(match extension_request.redirect_policy {
300            http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
301            http_client::RedirectPolicy::FollowLimit(limit) => {
302                ::http_client::RedirectPolicy::FollowLimit(limit)
303            }
304            http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
305        });
306    for (key, value) in &extension_request.headers {
307        request = request.header(key, value);
308    }
309    let body = extension_request
310        .body
311        .clone()
312        .map(AsyncBody::from)
313        .unwrap_or_default();
314    request.body(body).map_err(anyhow::Error::from)
315}
316
317async fn convert_response(
318    response: &mut ::http_client::Response<AsyncBody>,
319) -> Result<http_client::HttpResponse, anyhow::Error> {
320    let mut extension_response = http_client::HttpResponse {
321        body: Vec::new(),
322        headers: Vec::new(),
323    };
324
325    for (key, value) in response.headers() {
326        extension_response
327            .headers
328            .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
329    }
330
331    response
332        .body_mut()
333        .read_to_end(&mut extension_response.body)
334        .await?;
335
336    Ok(extension_response)
337}
338
339#[async_trait]
340impl ExtensionImports for WasmState {
341    async fn get_settings(
342        &mut self,
343        location: Option<self::SettingsLocation>,
344        category: String,
345        key: Option<String>,
346    ) -> wasmtime::Result<Result<String, String>> {
347        self.on_main_thread(|cx| {
348            async move {
349                let location = location
350                    .as_ref()
351                    .map(|location| ::settings::SettingsLocation {
352                        worktree_id: WorktreeId::from_proto(location.worktree_id),
353                        path: Path::new(&location.path),
354                    });
355
356                cx.update(|cx| match category.as_str() {
357                    "language" => {
358                        let key = key.map(|k| LanguageName::new(&k));
359                        let settings = AllLanguageSettings::get(location, cx).language(
360                            location,
361                            key.as_ref(),
362                            cx,
363                        );
364                        Ok(serde_json::to_string(&settings::LanguageSettings {
365                            tab_size: settings.tab_size,
366                        })?)
367                    }
368                    "lsp" => {
369                        let settings = key
370                            .and_then(|key| {
371                                ProjectSettings::get(location, cx)
372                                    .lsp
373                                    .get(&LanguageServerName(key.into()))
374                            })
375                            .cloned()
376                            .unwrap_or_default();
377                        Ok(serde_json::to_string(&settings::LspSettings {
378                            binary: settings.binary.map(|binary| settings::BinarySettings {
379                                path: binary.path,
380                                arguments: binary.arguments,
381                            }),
382                            settings: settings.settings,
383                            initialization_options: settings.initialization_options,
384                        })?)
385                    }
386                    _ => {
387                        bail!("Unknown settings category: {}", category);
388                    }
389                })
390            }
391            .boxed_local()
392        })
393        .await?
394        .to_wasmtime_result()
395    }
396
397    async fn set_language_server_installation_status(
398        &mut self,
399        server_name: String,
400        status: LanguageServerInstallationStatus,
401    ) -> wasmtime::Result<()> {
402        let status = match status {
403            LanguageServerInstallationStatus::CheckingForUpdate => {
404                LanguageServerBinaryStatus::CheckingForUpdate
405            }
406            LanguageServerInstallationStatus::Downloading => {
407                LanguageServerBinaryStatus::Downloading
408            }
409            LanguageServerInstallationStatus::None => LanguageServerBinaryStatus::None,
410            LanguageServerInstallationStatus::Failed(error) => {
411                LanguageServerBinaryStatus::Failed { error }
412            }
413        };
414
415        self.host
416            .language_registry
417            .update_lsp_status(language::LanguageServerName(server_name.into()), status);
418        Ok(())
419    }
420
421    async fn download_file(
422        &mut self,
423        url: String,
424        path: String,
425        file_type: DownloadedFileType,
426    ) -> wasmtime::Result<Result<(), String>> {
427        maybe!(async {
428            let path = PathBuf::from(path);
429            let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
430
431            self.host.fs.create_dir(&extension_work_dir).await?;
432
433            let destination_path = self
434                .host
435                .writeable_path_from_extension(&self.manifest.id, &path)?;
436
437            let mut response = self
438                .host
439                .http_client
440                .get(&url, Default::default(), true)
441                .await
442                .map_err(|err| anyhow!("error downloading release: {}", err))?;
443
444            if !response.status().is_success() {
445                Err(anyhow!(
446                    "download failed with status {}",
447                    response.status().to_string()
448                ))?;
449            }
450            let body = BufReader::new(response.body_mut());
451
452            match file_type {
453                DownloadedFileType::Uncompressed => {
454                    futures::pin_mut!(body);
455                    self.host
456                        .fs
457                        .create_file_with(&destination_path, body)
458                        .await?;
459                }
460                DownloadedFileType::Gzip => {
461                    let body = GzipDecoder::new(body);
462                    futures::pin_mut!(body);
463                    self.host
464                        .fs
465                        .create_file_with(&destination_path, body)
466                        .await?;
467                }
468                DownloadedFileType::GzipTar => {
469                    let body = GzipDecoder::new(body);
470                    futures::pin_mut!(body);
471                    self.host
472                        .fs
473                        .extract_tar_file(&destination_path, Archive::new(body))
474                        .await?;
475                }
476                DownloadedFileType::Zip => {
477                    futures::pin_mut!(body);
478                    node_runtime::extract_zip(&destination_path, body)
479                        .await
480                        .with_context(|| format!("failed to unzip {} archive", path.display()))?;
481                }
482            }
483
484            Ok(())
485        })
486        .await
487        .to_wasmtime_result()
488    }
489
490    async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
491        #[allow(unused)]
492        let path = self
493            .host
494            .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
495
496        #[cfg(unix)]
497        {
498            use std::fs::{self, Permissions};
499            use std::os::unix::fs::PermissionsExt;
500
501            return fs::set_permissions(&path, Permissions::from_mode(0o755))
502                .map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
503                .to_wasmtime_result();
504        }
505
506        #[cfg(not(unix))]
507        Ok(Ok(()))
508    }
509}