since_v0_1_0.rs

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