1pub(crate) mod wit;
2
3use crate::ExtensionManifest;
4use anyhow::{anyhow, Context as _, Result};
5use fs::{normalize_path, Fs};
6use futures::future::LocalBoxFuture;
7use futures::{
8 channel::{
9 mpsc::{self, UnboundedSender},
10 oneshot,
11 },
12 future::BoxFuture,
13 Future, FutureExt, StreamExt as _,
14};
15use gpui::{AppContext, AsyncAppContext, BackgroundExecutor, Task};
16use http_client::HttpClient;
17use language::LanguageRegistry;
18use node_runtime::NodeRuntime;
19use release_channel::ReleaseChannel;
20use semantic_version::SemanticVersion;
21use std::{
22 path::{Path, PathBuf},
23 sync::{Arc, OnceLock},
24};
25use wasmtime::{
26 component::{Component, ResourceTable},
27 Engine, Store,
28};
29use wasmtime_wasi as wasi;
30use wit::Extension;
31
32pub(crate) struct WasmHost {
33 engine: Engine,
34 release_channel: ReleaseChannel,
35 http_client: Arc<dyn HttpClient>,
36 node_runtime: NodeRuntime,
37 pub(crate) language_registry: Arc<LanguageRegistry>,
38 fs: Arc<dyn Fs>,
39 pub(crate) work_dir: PathBuf,
40 _main_thread_message_task: Task<()>,
41 main_thread_message_tx: mpsc::UnboundedSender<MainThreadCall>,
42}
43
44#[derive(Clone)]
45pub struct WasmExtension {
46 tx: UnboundedSender<ExtensionCall>,
47 pub(crate) manifest: Arc<ExtensionManifest>,
48 #[allow(unused)]
49 pub zed_api_version: SemanticVersion,
50}
51
52pub(crate) struct WasmState {
53 manifest: Arc<ExtensionManifest>,
54 pub(crate) table: ResourceTable,
55 ctx: wasi::WasiCtx,
56 pub(crate) host: Arc<WasmHost>,
57}
58
59type MainThreadCall =
60 Box<dyn Send + for<'a> FnOnce(&'a mut AsyncAppContext) -> LocalBoxFuture<'a, ()>>;
61
62type ExtensionCall = Box<
63 dyn Send + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, ()>,
64>;
65
66fn wasm_engine() -> wasmtime::Engine {
67 static WASM_ENGINE: OnceLock<wasmtime::Engine> = OnceLock::new();
68
69 WASM_ENGINE
70 .get_or_init(|| {
71 let mut config = wasmtime::Config::new();
72 config.wasm_component_model(true);
73 config.async_support(true);
74 wasmtime::Engine::new(&config).unwrap()
75 })
76 .clone()
77}
78
79impl WasmHost {
80 pub fn new(
81 fs: Arc<dyn Fs>,
82 http_client: Arc<dyn HttpClient>,
83 node_runtime: NodeRuntime,
84 language_registry: Arc<LanguageRegistry>,
85 work_dir: PathBuf,
86 cx: &mut AppContext,
87 ) -> Arc<Self> {
88 let (tx, mut rx) = mpsc::unbounded::<MainThreadCall>();
89 let task = cx.spawn(|mut cx| async move {
90 while let Some(message) = rx.next().await {
91 message(&mut cx).await;
92 }
93 });
94 Arc::new(Self {
95 engine: wasm_engine(),
96 fs,
97 work_dir,
98 http_client,
99 node_runtime,
100 language_registry,
101 release_channel: ReleaseChannel::global(cx),
102 _main_thread_message_task: task,
103 main_thread_message_tx: tx,
104 })
105 }
106
107 pub fn load_extension(
108 self: &Arc<Self>,
109 wasm_bytes: Vec<u8>,
110 manifest: Arc<ExtensionManifest>,
111 executor: BackgroundExecutor,
112 ) -> Task<Result<WasmExtension>> {
113 let this = self.clone();
114 executor.clone().spawn(async move {
115 let zed_api_version =
116 extension::parse_wasm_extension_version(&manifest.id, &wasm_bytes)?;
117
118 let component = Component::from_binary(&this.engine, &wasm_bytes)
119 .context("failed to compile wasm component")?;
120
121 let mut store = wasmtime::Store::new(
122 &this.engine,
123 WasmState {
124 ctx: this.build_wasi_ctx(&manifest).await?,
125 manifest: manifest.clone(),
126 table: ResourceTable::new(),
127 host: this.clone(),
128 },
129 );
130
131 let mut extension = Extension::instantiate_async(
132 &mut store,
133 this.release_channel,
134 zed_api_version,
135 &component,
136 )
137 .await?;
138
139 extension
140 .call_init_extension(&mut store)
141 .await
142 .context("failed to initialize wasm extension")?;
143
144 let (tx, mut rx) = mpsc::unbounded::<ExtensionCall>();
145 executor
146 .spawn(async move {
147 while let Some(call) = rx.next().await {
148 (call)(&mut extension, &mut store).await;
149 }
150 })
151 .detach();
152
153 Ok(WasmExtension {
154 manifest,
155 tx,
156 zed_api_version,
157 })
158 })
159 }
160
161 async fn build_wasi_ctx(&self, manifest: &Arc<ExtensionManifest>) -> Result<wasi::WasiCtx> {
162 let extension_work_dir = self.work_dir.join(manifest.id.as_ref());
163 self.fs
164 .create_dir(&extension_work_dir)
165 .await
166 .context("failed to create extension work dir")?;
167
168 let file_perms = wasi::FilePerms::all();
169 let dir_perms = wasi::DirPerms::all();
170
171 Ok(wasi::WasiCtxBuilder::new()
172 .inherit_stdio()
173 .preopened_dir(&extension_work_dir, ".", dir_perms, file_perms)?
174 .preopened_dir(
175 &extension_work_dir,
176 extension_work_dir.to_string_lossy(),
177 dir_perms,
178 file_perms,
179 )?
180 .env("PWD", extension_work_dir.to_string_lossy())
181 .env("RUST_BACKTRACE", "full")
182 .build())
183 }
184
185 pub fn path_from_extension(&self, id: &Arc<str>, path: &Path) -> PathBuf {
186 let extension_work_dir = self.work_dir.join(id.as_ref());
187 normalize_path(&extension_work_dir.join(path))
188 }
189
190 pub fn writeable_path_from_extension(&self, id: &Arc<str>, path: &Path) -> Result<PathBuf> {
191 let extension_work_dir = self.work_dir.join(id.as_ref());
192 let path = normalize_path(&extension_work_dir.join(path));
193 if path.starts_with(&extension_work_dir) {
194 Ok(path)
195 } else {
196 Err(anyhow!("cannot write to path {}", path.display()))
197 }
198 }
199}
200
201impl WasmExtension {
202 pub async fn call<T, Fn>(&self, f: Fn) -> T
203 where
204 T: 'static + Send,
205 Fn: 'static
206 + Send
207 + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, T>,
208 {
209 let (return_tx, return_rx) = oneshot::channel();
210 self.tx
211 .clone()
212 .unbounded_send(Box::new(move |extension, store| {
213 async {
214 let result = f(extension, store).await;
215 return_tx.send(result).ok();
216 }
217 .boxed()
218 }))
219 .expect("wasm extension channel should not be closed yet");
220 return_rx.await.expect("wasm extension channel")
221 }
222}
223
224impl WasmState {
225 fn on_main_thread<T, Fn>(&self, f: Fn) -> impl 'static + Future<Output = T>
226 where
227 T: 'static + Send,
228 Fn: 'static + Send + for<'a> FnOnce(&'a mut AsyncAppContext) -> LocalBoxFuture<'a, T>,
229 {
230 let (return_tx, return_rx) = oneshot::channel();
231 self.host
232 .main_thread_message_tx
233 .clone()
234 .unbounded_send(Box::new(move |cx| {
235 async {
236 let result = f(cx).await;
237 return_tx.send(result).ok();
238 }
239 .boxed_local()
240 }))
241 .expect("main thread message channel should not be closed yet");
242 async move { return_rx.await.expect("main thread message channel") }
243 }
244
245 fn work_dir(&self) -> PathBuf {
246 self.host.work_dir.join(self.manifest.id.as_ref())
247 }
248}
249
250impl wasi::WasiView for WasmState {
251 fn table(&mut self) -> &mut ResourceTable {
252 &mut self.table
253 }
254
255 fn ctx(&mut self) -> &mut wasi::WasiCtx {
256 &mut self.ctx
257 }
258}