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/nodejs": latest::zed::extension::nodejs,
 39         "zed:extension/platform": latest::zed::extension::platform,
 40         "zed:extension/slash-command": latest::zed::extension::slash_command,
 41    },
 42});
 43
 44pub use self::zed::extension::*;
 45
 46mod settings {
 47    include!(concat!(env!("OUT_DIR"), "/since_v0.1.0/settings.rs"));
 48}
 49
 50pub type ExtensionWorktree = Arc<dyn LspAdapterDelegate>;
 51pub type ExtensionKeyValueStore = Arc<IndexedDocsDatabase>;
 52pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
 53
 54pub fn linker() -> &'static Linker<WasmState> {
 55    static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
 56    LINKER.get_or_init(|| super::new_linker(Extension::add_to_linker))
 57}
 58
 59impl From<Command> for latest::Command {
 60    fn from(value: Command) -> Self {
 61        Self {
 62            command: value.command,
 63            args: value.args,
 64            env: value.env,
 65        }
 66    }
 67}
 68
 69impl From<SettingsLocation> for latest::SettingsLocation {
 70    fn from(value: SettingsLocation) -> Self {
 71        Self {
 72            worktree_id: value.worktree_id,
 73            path: value.path,
 74        }
 75    }
 76}
 77
 78impl From<LanguageServerInstallationStatus> for latest::LanguageServerInstallationStatus {
 79    fn from(value: LanguageServerInstallationStatus) -> Self {
 80        match value {
 81            LanguageServerInstallationStatus::None => Self::None,
 82            LanguageServerInstallationStatus::Downloading => Self::Downloading,
 83            LanguageServerInstallationStatus::CheckingForUpdate => Self::CheckingForUpdate,
 84            LanguageServerInstallationStatus::Failed(message) => Self::Failed(message),
 85        }
 86    }
 87}
 88
 89impl From<DownloadedFileType> for latest::DownloadedFileType {
 90    fn from(value: DownloadedFileType) -> Self {
 91        match value {
 92            DownloadedFileType::Gzip => Self::Gzip,
 93            DownloadedFileType::GzipTar => Self::GzipTar,
 94            DownloadedFileType::Zip => Self::Zip,
 95            DownloadedFileType::Uncompressed => Self::Uncompressed,
 96        }
 97    }
 98}
 99
100impl From<Range> for latest::Range {
101    fn from(value: Range) -> Self {
102        Self {
103            start: value.start,
104            end: value.end,
105        }
106    }
107}
108
109impl From<CodeLabelSpan> for latest::CodeLabelSpan {
110    fn from(value: CodeLabelSpan) -> Self {
111        match value {
112            CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
113            CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
114        }
115    }
116}
117
118impl From<CodeLabelSpanLiteral> for latest::CodeLabelSpanLiteral {
119    fn from(value: CodeLabelSpanLiteral) -> Self {
120        Self {
121            text: value.text,
122            highlight_name: value.highlight_name,
123        }
124    }
125}
126
127impl From<CodeLabel> for latest::CodeLabel {
128    fn from(value: CodeLabel) -> Self {
129        Self {
130            code: value.code,
131            spans: value.spans.into_iter().map(Into::into).collect(),
132            filter_range: value.filter_range.into(),
133        }
134    }
135}
136
137impl From<latest::Completion> for Completion {
138    fn from(value: latest::Completion) -> Self {
139        Self {
140            label: value.label,
141            detail: value.detail,
142            kind: value.kind.map(Into::into),
143            insert_text_format: value.insert_text_format.map(Into::into),
144        }
145    }
146}
147
148impl From<latest::lsp::CompletionKind> for lsp::CompletionKind {
149    fn from(value: latest::lsp::CompletionKind) -> Self {
150        match value {
151            latest::lsp::CompletionKind::Text => Self::Text,
152            latest::lsp::CompletionKind::Method => Self::Method,
153            latest::lsp::CompletionKind::Function => Self::Function,
154            latest::lsp::CompletionKind::Constructor => Self::Constructor,
155            latest::lsp::CompletionKind::Field => Self::Field,
156            latest::lsp::CompletionKind::Variable => Self::Variable,
157            latest::lsp::CompletionKind::Class => Self::Class,
158            latest::lsp::CompletionKind::Interface => Self::Interface,
159            latest::lsp::CompletionKind::Module => Self::Module,
160            latest::lsp::CompletionKind::Property => Self::Property,
161            latest::lsp::CompletionKind::Unit => Self::Unit,
162            latest::lsp::CompletionKind::Value => Self::Value,
163            latest::lsp::CompletionKind::Enum => Self::Enum,
164            latest::lsp::CompletionKind::Keyword => Self::Keyword,
165            latest::lsp::CompletionKind::Snippet => Self::Snippet,
166            latest::lsp::CompletionKind::Color => Self::Color,
167            latest::lsp::CompletionKind::File => Self::File,
168            latest::lsp::CompletionKind::Reference => Self::Reference,
169            latest::lsp::CompletionKind::Folder => Self::Folder,
170            latest::lsp::CompletionKind::EnumMember => Self::EnumMember,
171            latest::lsp::CompletionKind::Constant => Self::Constant,
172            latest::lsp::CompletionKind::Struct => Self::Struct,
173            latest::lsp::CompletionKind::Event => Self::Event,
174            latest::lsp::CompletionKind::Operator => Self::Operator,
175            latest::lsp::CompletionKind::TypeParameter => Self::TypeParameter,
176            latest::lsp::CompletionKind::Other(kind) => Self::Other(kind),
177        }
178    }
179}
180
181impl From<latest::lsp::InsertTextFormat> for lsp::InsertTextFormat {
182    fn from(value: latest::lsp::InsertTextFormat) -> Self {
183        match value {
184            latest::lsp::InsertTextFormat::PlainText => Self::PlainText,
185            latest::lsp::InsertTextFormat::Snippet => Self::Snippet,
186            latest::lsp::InsertTextFormat::Other(value) => Self::Other(value),
187        }
188    }
189}
190
191impl From<latest::lsp::Symbol> for lsp::Symbol {
192    fn from(value: latest::lsp::Symbol) -> Self {
193        Self {
194            name: value.name,
195            kind: value.kind.into(),
196        }
197    }
198}
199
200impl From<latest::lsp::SymbolKind> for lsp::SymbolKind {
201    fn from(value: latest::lsp::SymbolKind) -> Self {
202        match value {
203            latest::lsp::SymbolKind::File => Self::File,
204            latest::lsp::SymbolKind::Module => Self::Module,
205            latest::lsp::SymbolKind::Namespace => Self::Namespace,
206            latest::lsp::SymbolKind::Package => Self::Package,
207            latest::lsp::SymbolKind::Class => Self::Class,
208            latest::lsp::SymbolKind::Method => Self::Method,
209            latest::lsp::SymbolKind::Property => Self::Property,
210            latest::lsp::SymbolKind::Field => Self::Field,
211            latest::lsp::SymbolKind::Constructor => Self::Constructor,
212            latest::lsp::SymbolKind::Enum => Self::Enum,
213            latest::lsp::SymbolKind::Interface => Self::Interface,
214            latest::lsp::SymbolKind::Function => Self::Function,
215            latest::lsp::SymbolKind::Variable => Self::Variable,
216            latest::lsp::SymbolKind::Constant => Self::Constant,
217            latest::lsp::SymbolKind::String => Self::String,
218            latest::lsp::SymbolKind::Number => Self::Number,
219            latest::lsp::SymbolKind::Boolean => Self::Boolean,
220            latest::lsp::SymbolKind::Array => Self::Array,
221            latest::lsp::SymbolKind::Object => Self::Object,
222            latest::lsp::SymbolKind::Key => Self::Key,
223            latest::lsp::SymbolKind::Null => Self::Null,
224            latest::lsp::SymbolKind::EnumMember => Self::EnumMember,
225            latest::lsp::SymbolKind::Struct => Self::Struct,
226            latest::lsp::SymbolKind::Event => Self::Event,
227            latest::lsp::SymbolKind::Operator => Self::Operator,
228            latest::lsp::SymbolKind::TypeParameter => Self::TypeParameter,
229            latest::lsp::SymbolKind::Other(kind) => Self::Other(kind),
230        }
231    }
232}
233
234#[async_trait]
235impl HostKeyValueStore for WasmState {
236    async fn insert(
237        &mut self,
238        kv_store: Resource<ExtensionKeyValueStore>,
239        key: String,
240        value: String,
241    ) -> wasmtime::Result<Result<(), String>> {
242        let kv_store = self.table.get(&kv_store)?;
243        kv_store.insert(key, value).await.to_wasmtime_result()
244    }
245
246    fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
247        // We only ever hand out borrows of key-value stores.
248        Ok(())
249    }
250}
251
252#[async_trait]
253impl HostWorktree for WasmState {
254    async fn id(
255        &mut self,
256        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
257    ) -> wasmtime::Result<u64> {
258        let delegate = self.table.get(&delegate)?;
259        Ok(delegate.worktree_id().to_proto())
260    }
261
262    async fn root_path(
263        &mut self,
264        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
265    ) -> wasmtime::Result<String> {
266        let delegate = self.table.get(&delegate)?;
267        Ok(delegate.worktree_root_path().to_string_lossy().to_string())
268    }
269
270    async fn read_text_file(
271        &mut self,
272        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
273        path: String,
274    ) -> wasmtime::Result<Result<String, String>> {
275        let delegate = self.table.get(&delegate)?;
276        Ok(delegate
277            .read_text_file(path.into())
278            .await
279            .map_err(|error| error.to_string()))
280    }
281
282    async fn shell_env(
283        &mut self,
284        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
285    ) -> wasmtime::Result<EnvVars> {
286        let delegate = self.table.get(&delegate)?;
287        Ok(delegate.shell_env().await.into_iter().collect())
288    }
289
290    async fn which(
291        &mut self,
292        delegate: Resource<Arc<dyn LspAdapterDelegate>>,
293        binary_name: String,
294    ) -> wasmtime::Result<Option<String>> {
295        let delegate = self.table.get(&delegate)?;
296        Ok(delegate
297            .which(binary_name.as_ref())
298            .await
299            .map(|path| path.to_string_lossy().to_string()))
300    }
301
302    fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
303        // We only ever hand out borrows of worktrees.
304        Ok(())
305    }
306}
307
308#[async_trait]
309impl common::Host for WasmState {}
310
311#[async_trait]
312impl http_client::Host for WasmState {
313    async fn fetch(
314        &mut self,
315        request: http_client::HttpRequest,
316    ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
317        maybe!(async {
318            let url = &request.url;
319            let request = convert_request(&request)?;
320            let mut response = self.host.http_client.send(request).await?;
321
322            if response.status().is_client_error() || response.status().is_server_error() {
323                bail!("failed to fetch '{url}': status code {}", response.status())
324            }
325            convert_response(&mut response).await
326        })
327        .await
328        .to_wasmtime_result()
329    }
330
331    async fn fetch_stream(
332        &mut self,
333        request: http_client::HttpRequest,
334    ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
335        let request = convert_request(&request)?;
336        let response = self.host.http_client.send(request);
337        maybe!(async {
338            let response = response.await?;
339            let stream = Arc::new(Mutex::new(response));
340            let resource = self.table.push(stream)?;
341            Ok(resource)
342        })
343        .await
344        .to_wasmtime_result()
345    }
346}
347
348#[async_trait]
349impl http_client::HostHttpResponseStream for WasmState {
350    async fn next_chunk(
351        &mut self,
352        resource: Resource<ExtensionHttpResponseStream>,
353    ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
354        let stream = self.table.get(&resource)?.clone();
355        maybe!(async move {
356            let mut response = stream.lock().await;
357            let mut buffer = vec![0; 8192]; // 8KB buffer
358            let bytes_read = response.body_mut().read(&mut buffer).await?;
359            if bytes_read == 0 {
360                Ok(None)
361            } else {
362                buffer.truncate(bytes_read);
363                Ok(Some(buffer))
364            }
365        })
366        .await
367        .to_wasmtime_result()
368    }
369
370    fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
371        Ok(())
372    }
373}
374
375impl From<http_client::HttpMethod> for ::http_client::Method {
376    fn from(value: http_client::HttpMethod) -> Self {
377        match value {
378            http_client::HttpMethod::Get => Self::GET,
379            http_client::HttpMethod::Post => Self::POST,
380            http_client::HttpMethod::Put => Self::PUT,
381            http_client::HttpMethod::Delete => Self::DELETE,
382            http_client::HttpMethod::Head => Self::HEAD,
383            http_client::HttpMethod::Options => Self::OPTIONS,
384            http_client::HttpMethod::Patch => Self::PATCH,
385        }
386    }
387}
388
389fn convert_request(
390    extension_request: &http_client::HttpRequest,
391) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
392    let mut request = ::http_client::Request::builder()
393        .method(::http_client::Method::from(extension_request.method))
394        .uri(&extension_request.url)
395        .follow_redirects(match extension_request.redirect_policy {
396            http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
397            http_client::RedirectPolicy::FollowLimit(limit) => {
398                ::http_client::RedirectPolicy::FollowLimit(limit)
399            }
400            http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
401        });
402    for (key, value) in &extension_request.headers {
403        request = request.header(key, value);
404    }
405    let body = extension_request
406        .body
407        .clone()
408        .map(AsyncBody::from)
409        .unwrap_or_default();
410    request.body(body).map_err(anyhow::Error::from)
411}
412
413async fn convert_response(
414    response: &mut ::http_client::Response<AsyncBody>,
415) -> Result<http_client::HttpResponse, anyhow::Error> {
416    let mut extension_response = http_client::HttpResponse {
417        body: Vec::new(),
418        headers: Vec::new(),
419    };
420
421    for (key, value) in response.headers() {
422        extension_response
423            .headers
424            .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
425    }
426
427    response
428        .body_mut()
429        .read_to_end(&mut extension_response.body)
430        .await?;
431
432    Ok(extension_response)
433}
434
435#[async_trait]
436impl lsp::Host for WasmState {}
437
438#[async_trait]
439impl ExtensionImports for WasmState {
440    async fn get_settings(
441        &mut self,
442        location: Option<self::SettingsLocation>,
443        category: String,
444        key: Option<String>,
445    ) -> wasmtime::Result<Result<String, String>> {
446        self.on_main_thread(|cx| {
447            async move {
448                let location = location
449                    .as_ref()
450                    .map(|location| ::settings::SettingsLocation {
451                        worktree_id: WorktreeId::from_proto(location.worktree_id),
452                        path: Path::new(&location.path),
453                    });
454
455                cx.update(|cx| match category.as_str() {
456                    "language" => {
457                        let key = key.map(|k| LanguageName::new(&k));
458                        let settings = AllLanguageSettings::get(location, cx).language(
459                            location,
460                            key.as_ref(),
461                            cx,
462                        );
463                        Ok(serde_json::to_string(&settings::LanguageSettings {
464                            tab_size: settings.tab_size,
465                        })?)
466                    }
467                    "lsp" => {
468                        let settings = key
469                            .and_then(|key| {
470                                ProjectSettings::get(location, cx)
471                                    .lsp
472                                    .get(&LanguageServerName(key.into()))
473                            })
474                            .cloned()
475                            .unwrap_or_default();
476                        Ok(serde_json::to_string(&settings::LspSettings {
477                            binary: settings.binary.map(|binary| settings::BinarySettings {
478                                path: binary.path,
479                                arguments: binary.arguments,
480                            }),
481                            settings: settings.settings,
482                            initialization_options: settings.initialization_options,
483                        })?)
484                    }
485                    _ => {
486                        bail!("Unknown settings category: {}", category);
487                    }
488                })
489            }
490            .boxed_local()
491        })
492        .await?
493        .to_wasmtime_result()
494    }
495
496    async fn set_language_server_installation_status(
497        &mut self,
498        server_name: String,
499        status: LanguageServerInstallationStatus,
500    ) -> wasmtime::Result<()> {
501        let status = match status {
502            LanguageServerInstallationStatus::CheckingForUpdate => {
503                LanguageServerBinaryStatus::CheckingForUpdate
504            }
505            LanguageServerInstallationStatus::Downloading => {
506                LanguageServerBinaryStatus::Downloading
507            }
508            LanguageServerInstallationStatus::None => LanguageServerBinaryStatus::None,
509            LanguageServerInstallationStatus::Failed(error) => {
510                LanguageServerBinaryStatus::Failed { error }
511            }
512        };
513
514        self.host
515            .language_registry
516            .update_lsp_status(language::LanguageServerName(server_name.into()), status);
517        Ok(())
518    }
519
520    async fn download_file(
521        &mut self,
522        url: String,
523        path: String,
524        file_type: DownloadedFileType,
525    ) -> wasmtime::Result<Result<(), String>> {
526        maybe!(async {
527            let path = PathBuf::from(path);
528            let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
529
530            self.host.fs.create_dir(&extension_work_dir).await?;
531
532            let destination_path = self
533                .host
534                .writeable_path_from_extension(&self.manifest.id, &path)?;
535
536            let mut response = self
537                .host
538                .http_client
539                .get(&url, Default::default(), true)
540                .await
541                .map_err(|err| anyhow!("error downloading release: {}", err))?;
542
543            if !response.status().is_success() {
544                Err(anyhow!(
545                    "download failed with status {}",
546                    response.status().to_string()
547                ))?;
548            }
549            let body = BufReader::new(response.body_mut());
550
551            match file_type {
552                DownloadedFileType::Uncompressed => {
553                    futures::pin_mut!(body);
554                    self.host
555                        .fs
556                        .create_file_with(&destination_path, body)
557                        .await?;
558                }
559                DownloadedFileType::Gzip => {
560                    let body = GzipDecoder::new(body);
561                    futures::pin_mut!(body);
562                    self.host
563                        .fs
564                        .create_file_with(&destination_path, body)
565                        .await?;
566                }
567                DownloadedFileType::GzipTar => {
568                    let body = GzipDecoder::new(body);
569                    futures::pin_mut!(body);
570                    self.host
571                        .fs
572                        .extract_tar_file(&destination_path, Archive::new(body))
573                        .await?;
574                }
575                DownloadedFileType::Zip => {
576                    futures::pin_mut!(body);
577                    node_runtime::extract_zip(&destination_path, body)
578                        .await
579                        .with_context(|| format!("failed to unzip {} archive", path.display()))?;
580                }
581            }
582
583            Ok(())
584        })
585        .await
586        .to_wasmtime_result()
587    }
588
589    async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
590        #[allow(unused)]
591        let path = self
592            .host
593            .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
594
595        #[cfg(unix)]
596        {
597            use std::fs::{self, Permissions};
598            use std::os::unix::fs::PermissionsExt;
599
600            return fs::set_permissions(&path, Permissions::from_mode(0o755))
601                .map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
602                .to_wasmtime_result();
603        }
604
605        #[cfg(not(unix))]
606        Ok(Ok(()))
607    }
608}