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