Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix web-sys public agents and improve multithread web-sys #1006

Merged
merged 1 commit into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ cfg-if = "0.1"
cfg-match = "0.2"
console_error_panic_hook = { version = "0.1", optional = true }
futures = { version = "0.3", optional = true }
gloo = { version = "0.2", optional = true }
gloo = { git = "https://github.com/rustwasm/gloo", optional = true, rev = "f9b1727" }
http = "0.2"
indexmap = "1.0.2"
js-sys = { version = "0.3", optional = true }
Expand Down
6 changes: 3 additions & 3 deletions examples/web_sys/multi_thread/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ authors = ["Denis Kolodin <[email protected]>"]
edition = "2018"

[[bin]]
name = "main"
path = "src/bin/main.rs"
name = "multi_thread_app"
path = "src/bin/app.rs"

[[bin]]
name = "native_worker"
name = "multi_thread_worker"
path = "src/bin/native_worker.rs"

[dependencies]
Expand Down
18 changes: 16 additions & 2 deletions examples/web_sys/multi_thread/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
### multi_thread

You should compile a worker which have to be spawned in a separate thread:
First, build your web app

```sh
wasm-pack build --target no-modules --release -- --features web_sys --bin native_worker
cargo build --target wasm32-unknown-unknown --bin multi_thread_app
wasm-bindgen --target web --no-typescript --out-dir static/ --out-name app ../../target/wasm32-unknown-unknown/debug/multi_thread_app.wasm
```

Then, build your web worker

```sh
cargo build --target wasm32-unknown-unknown --bin multi_thread_worker
wasm-bindgen --target no-modules --no-typescript --out-dir static/ --out-name worker ../../target/wasm32-unknown-unknown/debug/multi_thread_worker.wasm
```

Finally, serve the content from the `./static` directory

```sh
python3 -m http.server
```
1 change: 0 additions & 1 deletion examples/web_sys/multi_thread/Web.toml

This file was deleted.

2 changes: 0 additions & 2 deletions examples/web_sys/multi_thread/src/bin/native_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@ use yew::agent::Threaded;

fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::initialize();
multi_thread_web_sys::native_worker::Worker::register();
yew::run_loop();
}
16 changes: 5 additions & 11 deletions examples/web_sys/multi_thread/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use log::info;
use serde_derive::{Deserialize, Serialize};
use std::time::Duration;
use yew::worker::*;
// TODO use yew::services::{IntervalService, FetchService, Task};
use yew::services::fetch::FetchService;
use yew::services::interval::IntervalService;
use yew::services::Task;
use yew::worker::*;

#[derive(Serialize, Deserialize, Debug)]
pub enum Request {
Expand All @@ -23,9 +21,7 @@ pub enum Msg {

pub struct Worker {
link: AgentLink<Worker>,
interval: IntervalService,
task: Box<dyn Task>,
fetch: FetchService,
_task: Box<dyn Task>,
}

impl Agent for Worker {
Expand All @@ -35,15 +31,12 @@ impl Agent for Worker {
type Output = Response;

fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
let task = IntervalService::new().spawn(duration, callback);
Worker {
link,
interval,
task: Box::new(task),
fetch: FetchService::new(),
_task: Box::new(task),
}
}

Expand All @@ -59,6 +52,7 @@ impl Agent for Worker {
info!("Request: {:?}", msg);
match msg {
Request::GetDataFromServer => {
// TODO fetch actual data
self.link.respond(who, Response::DataFetched);
}
}
Expand Down
16 changes: 5 additions & 11 deletions examples/web_sys/multi_thread/src/job.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use log::info;
use serde_derive::{Deserialize, Serialize};
use std::time::Duration;
use yew::worker::*;
// TODO use yew::services::{IntervalService, FetchService, Task};
use yew::services::fetch::FetchService;
use yew::services::interval::IntervalService;
use yew::services::Task;
use yew::worker::*;

#[derive(Serialize, Deserialize, Debug)]
pub enum Request {
Expand All @@ -23,9 +21,7 @@ pub enum Msg {

pub struct Worker {
link: AgentLink<Worker>,
interval: IntervalService,
task: Box<dyn Task>,
fetch: FetchService,
_task: Box<dyn Task>,
}

impl Agent for Worker {
Expand All @@ -35,15 +31,12 @@ impl Agent for Worker {
type Output = Response;

fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
let task = IntervalService::new().spawn(duration, callback);
Worker {
link,
interval,
task: Box::new(task),
fetch: FetchService::new(),
_task: Box::new(task),
}
}

Expand All @@ -59,6 +52,7 @@ impl Agent for Worker {
info!("Request: {:?}", msg);
match msg {
Request::GetDataFromServer => {
// TODO fetch actual data
self.link.respond(who, Response::DataFetched);
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/web_sys/multi_thread/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub mod job;
pub mod native_worker;

use log::info;
use yew::worker::*;
use yew::worker::{Bridge, Bridged};
use yew::{html, Component, ComponentLink, Html, ShouldRender};

pub struct Model {
Expand Down
18 changes: 6 additions & 12 deletions examples/web_sys/multi_thread/src/native_worker.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use log::info;
use serde_derive::{Deserialize, Serialize};
use std::time::Duration;
use yew::worker::*;
// TODO use yew::services::{IntervalService, FetchService, Task};
use yew::services::fetch::FetchService;
use yew::services::interval::IntervalService;
use yew::services::Task;
use yew::worker::*;

#[derive(Serialize, Deserialize, Debug)]
pub enum Request {
Expand All @@ -23,9 +21,7 @@ pub enum Msg {

pub struct Worker {
link: AgentLink<Worker>,
interval: IntervalService,
task: Box<dyn Task>,
fetch: FetchService,
_task: Box<dyn Task>,
}

impl Agent for Worker {
Expand All @@ -35,15 +31,12 @@ impl Agent for Worker {
type Output = Response;

fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
let task = IntervalService::new().spawn(duration, callback);
Worker {
link,
interval,
task: Box::new(task),
fetch: FetchService::new(),
_task: Box::new(task),
}
}

Expand All @@ -59,12 +52,13 @@ impl Agent for Worker {
info!("Request: {:?}", msg);
match msg {
Request::GetDataFromServer => {
// TODO fetch actual data
self.link.respond(who, Response::DataFetched);
}
}
}

fn name_of_resource() -> &'static str {
"bin/native_worker.js"
"worker.js"
}
}
2 changes: 2 additions & 0 deletions examples/web_sys/multi_thread/static/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.js
*.wasm
1 change: 0 additions & 1 deletion examples/web_sys/multi_thread/static/bin

This file was deleted.

5 changes: 2 additions & 3 deletions examples/web_sys/multi_thread/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
<head>
<meta charset="utf-8">
<title>Yew • Multi-Thread</title>
<script type="module">import init from "./app.js"; init()</script>
</head>
<body>
<script src="/main.js"></script>
</body>
<body></body>
</html>

22 changes: 19 additions & 3 deletions src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1010,12 +1010,28 @@ where
#[cfg(feature = "web_sys")]
fn worker_new(name_of_resource: &str, is_module: bool) -> Worker {
let href = utils::document().location().unwrap().href().unwrap();

let script_url = format!("{}{}", href, name_of_resource);
let wasm_url = format!("{}{}", href, name_of_resource.replace(".js", "_bg.wasm"));
let array = Array::new();
array.push(
&format!(
"importScripts(\"{}{}\");onmessage=e=>{{wasm_bindgen(e.data)}}",
href, name_of_resource,
r#"importScripts("{}");

let initialized = wasm_bindgen("{}").catch(err => {{
// Propagate to main `onerror`:
setTimeout(() => {{
throw err;
}});

// Rethrow to keep promise rejected and prevent execution of further commands:
throw err;
}});

self.onmessage = async (event) => {{
await initialized;
wasm_bindgen.child_entry_point(event.data);
}};"#,
Comment on lines +1030 to +1033
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By the way, I was trying to figure out why we had a onmessage here, I couldn't figure it out, but in any case this code doesn't do anything.
If it does, but not in the example, it would error because wasm_bindgen.child_entry_point doesn't exist.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

#1013

script_url, wasm_url
)
.into(),
);
Expand Down