port-monolith-to-wasm-for-chrome-extension

Dea1add99f4cf942792c0f185aa2f2fd?s=47 Linda_pp
January 27, 2020

 port-monolith-to-wasm-for-chrome-extension

Presented at Rust LT #8 https://rust.connpass.com/event/160225/

Dea1add99f4cf942792c0f185aa2f2fd?s=128

Linda_pp

January 27, 2020
Tweet

Transcript

  1. Monolith Λ Wasm ʹҠ২͠ ͯ Chrome ֦ுͭͬͨ͘࿩ at Rust LT

    #8 (2020/1/27) @Linda_pp @rhysd 
  2. monolith https://github.com/Y2Z/monolith 

  3. monolith • ࢦఆͨ͠ URL ͷϖʔδΛ1ͭͷ HTML ϖʔδͱ ͯ͠อଘ͢Δ CLI πʔϧ

    • ϨεϙϯγϒͳϖʔδͳͲ΋ී௨ͷ΢Σϒϖʔδ ͱͯͦ͠ͷ··ϩʔΧϧʹอଘͰ͖Δ • HTML ϖʔδΛύʔε͠ɼϦιʔεΛऔ͖ͬͯͯ Data URL ͱͯ͠ຒΊࠐΉ͜ͱͰ࣮૷͞Ε͍ͯΔ 
  4. monolith-of-web https://github.com/rhysd/monolith-of-web 

  5. monolith-of-web • monolith Λ wasm ʹҠ২͠ɼChrome ֦ுͱ ͯ͠ϒϥ΢β͔Β࢖͑ΔΑ͏ʹͨ͠΋ͷ • ϒϥ΢ζ͍ͯ͠Δϖʔδͷ

    HTML Λͦͷ·· ୯Ұͷ HTML ϖʔδʹͯ͠อଘͰ͖Δ 
  6. σϞ 

  7. :; NPOPMJUI SIZTE NPOPMJUI NPOPMJUIOQN QBDLBHF NPOPMJUIPGXFC CBDLHSPVOEQBHF GPSL XBTNQBDL

    JOTUBOUJBUF 
  8. େ·͔ͳ wasm ΁ͷҠ২ͷखॱ • wasm-pack buid ͕௨ΔΑ͏ʹ͢Δɽwasm ະରԠͷϞδϡʔ ϧ͕͋Δ৔߹͸#[cfg(target_arch =

    "wasm32")] ͰॲཧΛ෼͚ Δ • wasm-bindgen Λ࢖͍ɼ#[wasm_bindgen] Ͱ JS ଆʹݟͤΔ API Λఆٛ͢Δ #[cfg(not(target_arch = "wasm32"))] use reqwest::blocking::Client; #[wasm_bindgen(js_name = monolithOfUrl)] pub async fn monolith_of_url( url_target: String, options: MonolithOptions, ) -> Result<String, JsValue> { // ... } 
  9. network ϦΫΤετ • monolith ͸Ϧιʔεͷ fetch ͷͨΊʹ reqwest ͷϒϩοΩ ϯά

    API Λ࢖͍ͬͯΔ • JavaScript ͷ fetch() ͱ async-await Λ࢖ͬͯॻ͖׵͑ • js_sys::Promise std::future::Future ΁ͷม׵͸؆୯ʹͰ͖Δ use wasm_bindgen_futures::JsFuture; let window = web_sys::window().unwrap(); let resp_value = JsFuture::from( window.fetch_with_request(&request) ).await?; let resp: Response = resp_value.dyn_into().unwrap(); 
  10. ࠶ؼؔ਺ͷ async-await Խ • ࠶ؼؔ਺͸ await ࣌ʹอଘ͓ͯ͘͠ঢ়ଶͷαΠζ͕੩తʹ ܾ·Βͳ͍ͷͰɼasync ؔ਺ʹͰ͖ͳ͍ɽ •

    monolith Ͱ͸ DOM Λ࠶ؼతʹ૸ࠪ͠ͳ͕ΒϦιʔεΛ fetch ͍ͯͨ͠ͷͰɼ͜ͷ໰୊Λ౿ΜͰ͍ͨ // ίϯύΠϧΤϥʔ async fn recursive() { recursive().await; recursive().await; } 
  11. ࠶ؼؔ਺ͷ async-await Խ • ঢ়ଶʢFutureʣΛ Box ʹೖΕͯಈతʹ؅ཧ͢Δ͜ͱͰճ ආͰ͖Δ use std::pin::Pin;

    use std::future::Future; fn recursive<'a>() -> Pin<Box<dyn Future<Output = ()> + 'a>> { Box::pin(async move { recursive().await; recursive().await; }) } 
  12. ·ͱΊ • Rust ੡ͷ CLI πʔϧ monolith Λ wasm ʹҠ

    ২ͯ͠ Chrome ֦ுʹͯ͠Έͨ • https://github.com/rhysd/monolith-of-web • async-await ͸ wasm Ͱ΋ wasm_bindgen_futures Ͱ؆୯ʹ࢖͑Δ @Linda_pp @rhysd presented by