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 =
360                            AllLanguageSettings::get(location, cx).language(key.as_ref());
361                        Ok(serde_json::to_string(&settings::LanguageSettings {
362                            tab_size: settings.tab_size,
363                        })?)
364                    }
365                    "lsp" => {
366                        let settings = key
367                            .and_then(|key| {
368                                ProjectSettings::get(location, cx)
369                                    .lsp
370                                    .get(&LanguageServerName(key.into()))
371                            })
372                            .cloned()
373                            .unwrap_or_default();
374                        Ok(serde_json::to_string(&settings::LspSettings {
375                            binary: settings.binary.map(|binary| settings::BinarySettings {
376                                path: binary.path,
377                                arguments: binary.arguments,
378                            }),
379                            settings: settings.settings,
380                            initialization_options: settings.initialization_options,
381                        })?)
382                    }
383                    _ => {
384                        bail!("Unknown settings category: {}", category);
385                    }
386                })
387            }
388            .boxed_local()
389        })
390        .await?
391        .to_wasmtime_result()
392    }
393
394    async fn set_language_server_installation_status(
395        &mut self,
396        server_name: String,
397        status: LanguageServerInstallationStatus,
398    ) -> wasmtime::Result<()> {
399        let status = match status {
400            LanguageServerInstallationStatus::CheckingForUpdate => {
401                LanguageServerBinaryStatus::CheckingForUpdate
402            }
403            LanguageServerInstallationStatus::Downloading => {
404                LanguageServerBinaryStatus::Downloading
405            }
406            LanguageServerInstallationStatus::None => LanguageServerBinaryStatus::None,
407            LanguageServerInstallationStatus::Failed(error) => {
408                LanguageServerBinaryStatus::Failed { error }
409            }
410        };
411
412        self.host
413            .language_registry
414            .update_lsp_status(language::LanguageServerName(server_name.into()), status);
415        Ok(())
416    }
417
418    async fn download_file(
419        &mut self,
420        url: String,
421        path: String,
422        file_type: DownloadedFileType,
423    ) -> wasmtime::Result<Result<(), String>> {
424        maybe!(async {
425            let path = PathBuf::from(path);
426            let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
427
428            self.host.fs.create_dir(&extension_work_dir).await?;
429
430            let destination_path = self
431                .host
432                .writeable_path_from_extension(&self.manifest.id, &path)?;
433
434            let mut response = self
435                .host
436                .http_client
437                .get(&url, Default::default(), true)
438                .await
439                .map_err(|err| anyhow!("error downloading release: {}", err))?;
440
441            if !response.status().is_success() {
442                Err(anyhow!(
443                    "download failed with status {}",
444                    response.status().to_string()
445                ))?;
446            }
447            let body = BufReader::new(response.body_mut());
448
449            match file_type {
450                DownloadedFileType::Uncompressed => {
451                    futures::pin_mut!(body);
452                    self.host
453                        .fs
454                        .create_file_with(&destination_path, body)
455                        .await?;
456                }
457                DownloadedFileType::Gzip => {
458                    let body = GzipDecoder::new(body);
459                    futures::pin_mut!(body);
460                    self.host
461                        .fs
462                        .create_file_with(&destination_path, body)
463                        .await?;
464                }
465                DownloadedFileType::GzipTar => {
466                    let body = GzipDecoder::new(body);
467                    futures::pin_mut!(body);
468                    self.host
469                        .fs
470                        .extract_tar_file(&destination_path, Archive::new(body))
471                        .await?;
472                }
473                DownloadedFileType::Zip => {
474                    futures::pin_mut!(body);
475                    node_runtime::extract_zip(&destination_path, body)
476                        .await
477                        .with_context(|| format!("failed to unzip {} archive", path.display()))?;
478                }
479            }
480
481            Ok(())
482        })
483        .await
484        .to_wasmtime_result()
485    }
486
487    async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
488        #[allow(unused)]
489        let path = self
490            .host
491            .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
492
493        #[cfg(unix)]
494        {
495            use std::fs::{self, Permissions};
496            use std::os::unix::fs::PermissionsExt;
497
498            return fs::set_permissions(&path, Permissions::from_mode(0o755))
499                .map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
500                .to_wasmtime_result();
501        }
502
503        #[cfg(not(unix))]
504        Ok(Ok(()))
505    }
506}