Skip to content

Commit

Permalink
Merge local-runtime-handle into local-runtime.
Browse files Browse the repository at this point in the history
  • Loading branch information
futursolo committed Aug 21, 2022
1 parent e117d3f commit fa3e4f6
Show file tree
Hide file tree
Showing 11 changed files with 363 additions and 101 deletions.
31 changes: 31 additions & 0 deletions examples/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions examples/simple_ssr/Cargo.toml
Expand Up @@ -29,6 +29,8 @@ log = "0.4"
tokio = { version = "1.15.0", features = ["full"] }
warp = "0.3"
clap = { version = "3.1.7", features = ["derive"] }
hyper = { version = "0.14", features = ["server", "http1"] }
jemallocator = "0.5"

[features]
hydration = ["yew/hydration"]
Expand Down
33 changes: 32 additions & 1 deletion examples/simple_ssr/src/bin/simple_ssr_server.rs
@@ -1,11 +1,15 @@
use std::convert::Infallible;
use std::error::Error;
use std::future::Future;
use std::path::PathBuf;

use bytes::Bytes;
use clap::Parser;
use futures::stream::{self, Stream, StreamExt};
use hyper::server::Server;
use simple_ssr::App;
use warp::Filter;
use yew::platform::Runtime;

type BoxedError = Box<dyn Error + Send + Sync + 'static>;

Expand All @@ -17,6 +21,23 @@ struct Opt {
dir: PathBuf,
}

// An executor to process requests on the Yew runtime.
#[derive(Clone, Default)]
struct Executor {
inner: Runtime,
}

impl<F> hyper::rt::Executor<F> for Executor
where
F: Future + Send + 'static,
{
fn execute(&self, fut: F) {
self.inner.spawn_pinned(move || async move {
fut.await;
});
}
}

async fn render(
index_html_before: String,
index_html_after: String,
Expand All @@ -34,6 +55,7 @@ async fn render(
#[tokio::main]
async fn main() {
let opts = Opt::parse();
let exec = Executor::default();

let index_html_s = tokio::fs::read_to_string(opts.dir.join("index.html"))
.await
Expand All @@ -55,5 +77,14 @@ async fn main() {

println!("You can view the website at: http://localhost:8080/");

warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
let warp_svc = warp::service(routes);
let svc = hyper::service::make_service_fn(move |_| {
let warp_svc = warp_svc.clone();
async move { Ok::<_, Infallible>(warp_svc) }
});
Server::bind(&"127.0.0.1:8080".parse().unwrap())
.executor(exec)
.serve(svc)
.await
.unwrap();
}
4 changes: 3 additions & 1 deletion examples/ssr_router/Cargo.toml
Expand Up @@ -30,7 +30,9 @@ tower = { version = "0.4", features = ["make"] }
tower-http = { version = "0.3", features = ["fs"] }
env_logger = "0.9"
clap = { version = "3.1.7", features = ["derive"] }
hyper = { version = "0.14", features = ["server", "http1"] }
jemallocator = "0.5"

[features]
ssr = ["yew/ssr"]
ssr = ["yew/ssr", "yew/tokio"]
hydration = ["yew/hydration"]
28 changes: 27 additions & 1 deletion examples/ssr_router/src/bin/ssr_router_server.rs
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future;
use std::path::PathBuf;

use axum::body::{Body, StreamBody};
Expand All @@ -13,8 +14,13 @@ use axum::{Extension, Router};
use clap::Parser;
use function_router::{ServerApp, ServerAppProps};
use futures::stream::{self, StreamExt};
use hyper::server::Server;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use yew::platform::Runtime;

#[global_allocator]
static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc;

/// A basic example
#[derive(Parser, Debug)]
Expand Down Expand Up @@ -44,8 +50,27 @@ async fn render(
)
}

// An executor to process requests on the Yew runtime.
#[derive(Clone, Default)]
struct Executor {
inner: Runtime,
}

impl<F> hyper::rt::Executor<F> for Executor
where
F: Future + Send + 'static,
{
fn execute(&self, fut: F) {
self.inner.spawn_pinned(move || async move {
fut.await;
});
}
}

#[tokio::main]
async fn main() {
let exec = Executor::default();

env_logger::init();

let opts = Opt::parse();
Expand Down Expand Up @@ -86,7 +111,8 @@ async fn main() {

println!("You can view the website at: http://localhost:8080/");

axum::Server::bind(&"0.0.0.0:8080".parse().unwrap())
Server::bind(&"127.0.0.1:8080".parse().unwrap())
.executor(exec)
.serve(app.into_make_service())
.await
.unwrap();
Expand Down
47 changes: 47 additions & 0 deletions packages/yew/src/platform/mod.rs
Expand Up @@ -42,6 +42,7 @@

use std::future::Future;
use std::io::Result;
use std::marker::PhantomData;

#[cfg(feature = "ssr")]
pub(crate) mod io;
Expand Down Expand Up @@ -142,3 +143,49 @@ impl Runtime {
self.inner.spawn_pinned(create_task);
}
}

/// A Local Runtime Handle.
///
/// This type can be used to acquire a runtime handle to spawn local tasks.
#[derive(Debug, Clone)]
pub struct LocalHandle {
inner: imp::LocalHandle,
// This type is not send or sync.
_marker: PhantomData<*const ()>,
}

impl LocalHandle {
/// Creates a Handle to current Runtime worker.
///
/// # Panics
///
/// This method will panic if not called within Yew Runtime.
pub fn current() -> Self {
let inner = imp::LocalHandle::current();

Self {
inner,
_marker: PhantomData,
}
}

/// Creates a Handle to current Runtime worker.
///
/// This methods will return `None` if called from outside Yew Runtime.
pub fn try_current() -> Option<Self> {
let inner = imp::LocalHandle::try_current()?;

Some(Self {
inner,
_marker: PhantomData,
})
}

/// Spawns a Future with current Runtime worker.
pub fn spawn_local<F>(&self, f: F)
where
F: Future<Output = ()> + 'static,
{
self.inner.spawn_local(f);
}
}
24 changes: 24 additions & 0 deletions packages/yew/src/platform/rt_none/mod.rs
@@ -1,5 +1,6 @@
use std::future::Future;
use std::io;
use std::marker::PhantomData;

pub(crate) mod time;

Expand Down Expand Up @@ -46,3 +47,26 @@ impl Runtime {
panic_no_runtime();
}
}

#[derive(Debug, Clone)]
pub(crate) struct LocalHandle {
// This type is not send or sync.
_marker: PhantomData<*const ()>,
}

impl LocalHandle {
pub fn try_current() -> Option<Self> {
panic_no_runtime();
}

pub fn current() -> Self {
panic_no_runtime();
}

pub fn spawn_local<F>(&self, _f: F)
where
F: Future<Output = ()> + 'static,
{
panic_no_runtime();
}
}

0 comments on commit fa3e4f6

Please sign in to comment.