extension_host 0.0.2

wasm host
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
pub mod executor;
pub mod plugin_manifest;
pub mod wit;

use anyhow::{Context, Result};
use futures::{
    channel::{
        mpsc::{self, UnboundedSender},
        oneshot,
    },
    future::BoxFuture,
    FutureExt, StreamExt,
};
use plugin_manifest::PluginManifest;
use std::{
    collections::HashMap,
    path::PathBuf,
    sync::{Arc, Mutex, OnceLock},
};
use wasmtime::{component::Linker, Store};
use wit::Extension;

use extension_http::HttpClient;

type ExtensionCall = Box<
    dyn Send + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, ()>,
>;

struct WasmState {
    pub table: wasmtime_wasi::ResourceTable,
    ctx: wasmtime_wasi::WasiCtx,
    pub host: Arc<WasmHost>,
}

pub struct WasmHost {
    engine: wasmtime::Engine,
    http_client: Arc<dyn HttpClient>,
    // fs: Arc<dyn Fs>,
    // home_dir/.config/wasm_extension
    pub work_dir: PathBuf,
}

fn wasm_engine() -> wasmtime::Engine {
    static WASM_ENGINE: OnceLock<wasmtime::Engine> = OnceLock::new();
    WASM_ENGINE
        .get_or_init(|| {
            let mut config = wasmtime::Config::new();
            config
                .async_support(true)
                .wasm_component_model(true)
                .debug_info(true)
                .wasm_memory64(true);

            let engine = wasmtime::Engine::new(&config).unwrap();
            engine
        })
        .clone()
}

impl WasmHost {
    pub fn new(work_dir: PathBuf) -> Arc<Self> {
        // let (tx, mut rx) = mpsc::unbounded::<ExtensionCall>();
        Arc::new(Self {
            engine: wasm_engine(),
            http_client: Arc::new(::extension_http::DefaultHttpClient::new(
                None,
                Some(vec![
                    "https?://httpbin.org/**".to_string(),
                    "https?://www.baidu.com".to_string(),
                ]),
            )),
            work_dir,
        })
    }

    /// 异步加载wasi component 并初始化,开启异步监听线程
    pub fn load_plugin(
        self: &Arc<Self>,
        wasm_bytes: Vec<u8>,
        manifest: &Arc<PluginManifest>,
        executor: executor::BackgroundExecutor,
    ) -> executor::Task<Result<WasmExtension>> {
        let this = self.clone();
        let manifest = manifest.clone();
        let extension_work_dir = self.work_dir.join(manifest.id.clone());
        executor.clone().spawn(async move {
            let component = wasmtime::component::Component::from_binary(&this.engine, &wasm_bytes)
                .context("failed to compile wasm component")?;

            let mut linker: Linker<WasmState> = Linker::<WasmState>::new(&this.engine);
            wasmtime_wasi::add_to_linker_async(&mut linker)?;
            Extension::add_to_linker(&mut linker, |s: &mut WasmState| s)?;

            let wasi_ctx = wasmtime_wasi::WasiCtx::builder()
                .inherit_stdio()
                .preopened_dir(
                    &extension_work_dir,
                    ".",
                    wasmtime_wasi::DirPerms::all(),
                    wasmtime_wasi::FilePerms::all(),
                )?
                .env("PWD", extension_work_dir.to_string_lossy())
                .build();

            let mut store = wasmtime::Store::new(
                &this.engine,
                WasmState {
                    ctx: wasi_ctx,
                    table: wasmtime_wasi::ResourceTable::new(),
                    host: this.clone(),
                },
            );

            let mut extension =
                Extension::instantiate_async(&mut store, &component, &linker).await?;

            extension
                .call_init_plugin(&mut store)
                .await
                .context("failed to initialize wasm extension")?;

            let (sender, mut receiver) = mpsc::unbounded::<ExtensionCall>();

            executor
                .spawn(async move {
                    while let Some(call) = receiver.next().await {
                        (call)(&mut extension, &mut store).await;
                    }
                })
                .detach();

            Ok(WasmExtension {
                tx: sender,
                work_dir: this.work_dir.join(manifest.id.clone()).into(),
                manifest: manifest.clone(),
            })
        })

        // futures::executor::block_on(call_future);
    }
}

#[derive(Clone)]
pub struct WasmExtension {
    tx: UnboundedSender<ExtensionCall>,
    pub manifest: Arc<PluginManifest>,
    pub work_dir: Arc<PathBuf>,
}

static GLOBAL_EXTENSION: OnceLock<Mutex<HashMap<String, WasmExtension>>> = OnceLock::new();

impl WasmExtension {
    pub async fn load(wasm_path: PathBuf) -> Result<Self> {
        let key = wasm_path.to_str().unwrap();
        let ext_map = GLOBAL_EXTENSION.get_or_init(|| Mutex::new(HashMap::new()));
        if let Ok(table) = ext_map.lock() {
            if table.contains_key(key) {
                return Ok(table.get(key).unwrap().clone());
            }
        }
        log::info!("wasm load:{}", key);
        let work_dir = dirs::home_dir()
            .unwrap()
            .join(".config")
            .join("wasm_extension")
            .join("plugin");
        //TODO 缓存起来
        let wasm_host = WasmHost::new(work_dir.clone());

        // wasm bytes
        let wasm_bytes = async_fs::read(&wasm_path).await?;
        if wasm_bytes.is_empty() {
            anyhow::bail!("wasm extension file:{:#?} not exists", wasm_path)
        }

        let manifest = parse_wasm_manifest(&wasm_bytes)?;

        let wasm_extension = wasm_host
            .load_plugin(
                wasm_bytes,
                &Arc::new(manifest.clone()),
                executor::BackgroundExecutor::new(),
            )
            .await
            .with_context(|| format!("failed to load wasm extension {}", manifest.id))?;

        if let Ok(mut table) = ext_map.lock() {
            table.insert(key.to_string(), wasm_extension.clone());
        }
        Ok(wasm_extension)
    }

    // pub async install(manifest: &Arc<PluginManifest>,PathBu)

    pub async fn run_plugin(&self, input: wit::PluginInput) -> Result<wit::PluginOutput> {
        self.call(|extension, store| {
            async move {
                let plugin_out = extension
                    .call_run_plugin(store, &input)
                    .await?
                    .map_err(|error| anyhow::anyhow!("{error}"))?;

                Ok(plugin_out.into())
            }
            .boxed()
        })
        .await
    }

    async fn call<T, Fn>(&self, f: Fn) -> T
    where
        T: 'static + Send,
        Fn: 'static
            + Send
            + for<'a> FnOnce(&'a mut Extension, &'a mut Store<WasmState>) -> BoxFuture<'a, T>,
    {
        let (return_tx, return_rx) = oneshot::channel::<T>();
        self.tx
            .clone()
            .unbounded_send(Box::new(move |extension, store| {
                async {
                    let result = f(extension, store).await;
                    return_tx.send(result).ok();
                }
                .boxed()
            }))
            .expect("wasm extension channel should not be closed yet");
        return_rx.await.expect("wasm extension channel")
    }
}

fn parse_wasm_manifest(wasm_byte: &[u8]) -> Result<PluginManifest> {
    let payloads = wasmparser::Parser::new(0).parse_all(wasm_byte);
    let mut api_version = String::new();
    let mut api_schema = String::new();
    for payload in payloads {
        match payload.unwrap() {
            wasmparser::Payload::CustomSection(custom_section_reader) => {
                match custom_section_reader.name() {
                    "workoss:api-version" => {
                        let data = custom_section_reader.data();
                        let version = String::from_utf8_lossy(data).to_string();
                        api_version.push_str(&version);
                    }
                    "workoss:api-schema" => {
                        let data = custom_section_reader.data();
                        let schema = String::from_utf8_lossy(data).to_string();
                        api_schema.push_str(&schema);
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }
    if api_version.is_empty() || api_schema.is_empty() {
        anyhow::bail!("api_version,api_schema can't be null");
    }

    // parse api_schema
    let schema_map: HashMap<String, String> = api_schema
        .split("\n")
        .map(|pair| {
            let mut kv = pair.split("::");
            (
                kv.next().unwrap().to_string(),
                kv.next().unwrap().to_string(),
            )
        })
        .collect();
    let id = schema_map.get("id").unwrap().to_string();
    let name = schema_map.get("name").unwrap().to_string();
    let version = schema_map.get("version").unwrap().to_string();
    let description = schema_map.get("description").map(ToString::to_string);
    let repository = schema_map.get("repository").map(ToString::to_string);
    let authors = schema_map
        .get("authors")
        .unwrap()
        .split(":")
        .into_iter()
        .map(ToString::to_string)
        .collect::<Vec<String>>();

    Ok(PluginManifest::new(
        id,
        name,
        version,
        description,
        authors,
        repository,
        Some(api_version),
    ))
}

#[cfg(test)]

mod tests {
    use std::{
        path::{Path, PathBuf},
        thread,
        time::Instant,
    };

    use futures::{
        channel::mpsc::{self},
        executor::{self, ThreadPool},
        StreamExt,
    };
    use wasmparser::Parser;
    use wasmtime::{
        component::{Component, Linker},
        Config, Engine, Store,
    };
    use wasmtime_wasi::ResourceTable;

    use crate::{
        parse_wasm_manifest,
        wit::{Extension, PluginInput},
        WasmExtension, WasmHost, WasmState,
    };

    #[test]
    fn test_parse() -> anyhow::Result<()> {
        let bytes = std::fs::read("/Users/workoss/IDE/rustProjects/wasm-extension/target/wasm32-wasip2/release/extension_plugin.wasm").unwrap();
        let manifest = parse_wasm_manifest(&bytes)?;
        let json_string = serde_json::to_string(&manifest).unwrap();
        println!("{json_string:#?}");
        Ok(())
    }

    #[test]
    fn test_futures() {
        let pool = ThreadPool::builder()
            .pool_size(4)
            .create()
            .expect("failed create pool");
        let (tx, rx) = mpsc::unbounded::<i32>();
        let fut_values = async {
            let thread = thread::current();
            let thread_name = thread.name().expect("----");
            println!("thread-name:{thread_name}");
            let fut_tx_result = async move {
                (0..100).for_each(|v| {
                    // let thread = thread::current();
                    // let thread_name = thread.name().expect("----");
                    // println!("{thread_name}-{v}");
                    tx.unbounded_send(v).expect("Failed to send");
                })
            };

            pool.spawn_ok(fut_tx_result);

            let fut_values = rx.map(|v| v * 2).collect();

            // Use the executor provided to this async block to wait for the
            // future to complete.
            fut_values.await
        };

        let values: Vec<i32> = executor::block_on(fut_values);

        println!("Values={values:?}");

        println!("{:#?}", dirs::home_dir());
        println!("{:#?}", dirs::public_dir());
        println!("{:#?}", dirs::cache_dir());
        println!("{:#?}", dirs::config_dir());
    }

    #[tokio::test]
    async fn test_load() {
        let wasm_path = PathBuf::new().join("/Users/workoss/IDE/rustProjects/wasm-extension/target/wasm32-wasip2/release/extension_plugin.min.wasm");
        let _wasm_extension = WasmExtension::load(wasm_path).await.unwrap();
        let now = Instant::now();
        for i in 0..100 {
            let wasm_path = PathBuf::new().join("/Users/workoss/IDE/rustProjects/wasm-extension/target/wasm32-wasip2/release/extension_plugin.min.wasm");
            let wasm_extension = WasmExtension::load(wasm_path).await.unwrap();
            let json_string = format!("{{\"id\":\"{i:?}\",\"name\":\"lisi\"}}");
            let input = PluginInput {
                body: Some(json_string.into_bytes()),
                mime_type: crate::wit::MimeType::Json,
                envs: None,
            };

            let out = wasm_extension.run_plugin(input).await.unwrap();
            println!("body:{:#?}", String::from_utf8(out.body.unwrap()));
        }
        println!("run plugin cost:{:?}", now.elapsed());
    }

    #[tokio::test]
    async fn test_wasm() -> anyhow::Result<()> {
        let _now = Instant::now();
        let mut config = Config::new();
        config.async_support(true);
        config.wasm_component_model(true);
        config.debug_info(true);

        let engine = Engine::new(&config)?;

        let component = Component::from_file(
            &engine,
            Path::new("/Users/workoss/IDE/rustProjects/wasm-extension/target/wasm32-wasip2/release/extension_plugin.wasm"),
        )?;
        let mut linker: Linker<WasmState> = Linker::<WasmState>::new(&engine);
        wasmtime_wasi::add_to_linker_async(&mut linker)?;

        Extension::add_to_linker(&mut linker, |s: &mut WasmState| s)?;

        let wasi_ctx = wasmtime_wasi::WasiCtx::builder()
            .inherit_stdio()
            .preopened_dir(
                "/Users/workoss/IDE",
                ".",
                wasmtime_wasi::DirPerms::all(),
                wasmtime_wasi::FilePerms::all(),
            )?
            .env(
                "PWD",
                "/Users/workoss/.config/wasm_extension/plugin/extension_plugin",
            )
            .build();

        let wasm_state = WasmState {
            table: ResourceTable::new(),
            ctx: wasi_ctx,
            host: WasmHost::new(PathBuf::new().join("path")),
        };

        let mut store = Store::new(&engine, wasm_state);

        let extension = Extension::instantiate_async(&mut store, &component, &linker)
            .await
            .unwrap();

        extension.call_init_plugin(&mut store).await.unwrap();

        for _i in 0..100 {
            let input = PluginInput {
                body: Some(r#"{"id":"2","name":"lisi"}"#.into()),
                mime_type: crate::wit::MimeType::Json,
                envs: None,
            };
            let _out = extension.call_run_plugin(&mut store, &input).await.unwrap();
        }

        Ok(())
    }

    #[test]
    fn test_wasmparser() {
        let bytes = std::fs::read("/Users/workoss/IDE/rustProjects/wasm-extension/target/wasm32-wasip2/release/extension_plugin.wasm").unwrap();
        let payloads = Parser::new(0).parse_all(&bytes);
        for payload in payloads {
            match payload.unwrap() {
                wasmparser::Payload::Version {
                    num,
                    encoding: _,
                    range,
                } => {
                    println!("num:{},range:{:#?}", num, range);
                }
                wasmparser::Payload::CustomSection(custom_section_reader) => {
                    let name = custom_section_reader.name();
                    match name {
                        "producers" => {
                            match custom_section_reader.as_known() {
                                wasmparser::KnownCustom::Producers(section_limited) => {
                                    let _data = custom_section_reader.data();

                                    let fields = section_limited.into_iter().collect::<Vec<_>>();
                                    for field in fields {
                                        let field = field.unwrap();
                                        println!("field {}", field.name);
                                        let values = field.values.into_iter().collect::<Vec<_>>();
                                        for value in values {
                                            let value = value.unwrap();
                                            println!(
                                                "field value:{} version:{}",
                                                value.name, value.version
                                            );
                                        }
                                    }
                                }
                                _ => {
                                    let data =
                                        String::from_utf8_lossy(custom_section_reader.data())
                                            .to_string();
                                    println!("CustomSection name:{name:?} - {data:#?}");
                                }
                            };
                        }
                        "workoss:api-version" => {
                            let data = custom_section_reader.data();
                            let version = String::from_utf8_lossy(data).to_string();

                            println!("CustomSection name:{name:?} - {version:#?}");
                        }
                        "workoss:api-schema" => {
                            let data = custom_section_reader.data();
                            let version = String::from_utf8_lossy(data).to_string();

                            println!("CustomSection name:{name:?} - {version:#?}");
                        }
                        _ => {
                            println!("CustomSection name:{name:?}");
                        }
                    }
                }
                _ => {}
            }
        }
    }
}