Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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

Linda_pp
January 27, 2020

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

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

Linda_pp

January 27, 2020
Tweet

More Decks by Linda_pp

Other Decks in Programming

Transcript

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

    • ϨεϙϯγϒͳϖʔδͳͲ΋ී௨ͷ΢Σϒϖʔδ ͱͯͦ͠ͷ··ϩʔΧϧʹอଘͰ͖Δ • HTML ϖʔδΛύʔε͠ɼϦιʔεΛऔ͖ͬͯͯ Data URL ͱͯ͠ຒΊࠐΉ͜ͱͰ࣮૷͞Ε͍ͯΔ 
  2. େ·͔ͳ 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> { // ... } 
  3. 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(); 
  4. ࠶ؼؔ਺ͷ async-await Խ • ࠶ؼؔ਺͸ await ࣌ʹอଘ͓ͯ͘͠ঢ়ଶͷαΠζ͕੩తʹ ܾ·Βͳ͍ͷͰɼasync ؔ਺ʹͰ͖ͳ͍ɽ •

    monolith Ͱ͸ DOM Λ࠶ؼతʹ૸ࠪ͠ͳ͕ΒϦιʔεΛ fetch ͍ͯͨ͠ͷͰɼ͜ͷ໰୊Λ౿ΜͰ͍ͨ // ίϯύΠϧΤϥʔ async fn recursive() { recursive().await; recursive().await; } 
  5. ࠶ؼؔ਺ͷ 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; }) } 
  6. ·ͱΊ • Rust ੡ͷ CLI πʔϧ monolith Λ wasm ʹҠ

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