Skip to content

Commit 4723b84

Browse files
committed
Simplify interface
1 parent be73430 commit 4723b84

File tree

15 files changed

+104
-195
lines changed

15 files changed

+104
-195
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/binary-echo/src/lib.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
use stateroom_wasm::prelude::*;
22

33
#[stateroom_wasm]
4+
#[derive(Default)]
45
struct BinaryEcho;
56

6-
impl SimpleStateroomService for BinaryEcho {
7-
fn new(_: &str, _: &impl StateroomContext) -> Self {
8-
BinaryEcho
9-
}
10-
7+
impl StateroomService for BinaryEcho {
118
fn message(&mut self, _: ClientId, message: &str, ctx: &impl StateroomContext) {
129
ctx.send_binary(
1310
MessageRecipient::Broadcast,

examples/clock/src/lib.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
use stateroom_wasm::prelude::*;
22

33
#[stateroom_wasm]
4-
struct ClockServer(String, u32);
4+
#[derive(Default)]
5+
struct ClockServer(u32);
56

6-
impl SimpleStateroomService for ClockServer {
7-
fn new(room_id: &str, ctx: &impl StateroomContext) -> Self {
7+
impl StateroomService for ClockServer {
8+
fn init(&mut self, ctx: &impl StateroomContext) {
89
ctx.set_timer(4000);
9-
ClockServer(room_id.to_string(), 0)
1010
}
1111

1212
fn timer(&mut self, ctx: &impl StateroomContext) {
13-
ctx.send_message(MessageRecipient::Broadcast, &format!("Here in room {} from timer @ {}", self.0, self.1));
14-
self.1 += 1;
13+
ctx.send_message(MessageRecipient::Broadcast, &format!("Timer @ {}", self.0));
14+
self.0 += 1;
1515
ctx.set_timer(4000);
1616
}
1717
}

examples/counter-service/src/lib.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
use stateroom_wasm::prelude::*;
22

33
#[stateroom_wasm]
4+
#[derive(Default)]
45
struct SharedCounterServer(i32);
56

6-
impl SimpleStateroomService for SharedCounterServer {
7-
fn new(_: &str, _: &impl StateroomContext) -> Self {
8-
SharedCounterServer(0)
9-
}
10-
7+
impl StateroomService for SharedCounterServer {
118
fn message(&mut self, _: ClientId, message: &str, ctx: &impl StateroomContext) {
129
match message {
1310
"increment" => self.0 += 1,

examples/cpu-hog/src/lib.rs

+5-8
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,20 @@ use stateroom_wasm::prelude::*;
44
const SECONDS: u64 = 1_000_000_000;
55

66
#[stateroom_wasm]
7-
struct CpuHog(String);
7+
#[derive(Default)]
8+
struct CpuHog;
89

910
fn get_time() -> u64 {
1011
unsafe {
1112
wasi::clock_time_get(wasi::CLOCKID_REALTIME, 0).unwrap()
1213
}
1314
}
1415

15-
impl SimpleStateroomService for CpuHog {
16-
fn new(room_id: &str, _: &impl StateroomContext) -> Self {
17-
CpuHog(room_id.to_string())
18-
}
19-
16+
impl StateroomService for CpuHog {
2017
fn connect(&mut self, _: ClientId, ctx: &impl StateroomContext) {
2118
ctx.send_message(
2219
MessageRecipient::Broadcast,
23-
&format!("Connected to room {}", self.0),
20+
&format!("Connected."),
2421
);
2522

2623
let init_time = get_time();
@@ -33,7 +30,7 @@ impl SimpleStateroomService for CpuHog {
3330

3431
ctx.send_message(
3532
MessageRecipient::Broadcast,
36-
&format!("Finished in room {}", self.0),
33+
&format!("Finished."),
3734
);
3835
}
3936
}

examples/echo-server/src/lib.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
use stateroom_wasm::prelude::*;
22

33
#[stateroom_wasm]
4+
#[derive(Default)]
45
struct EchoServer;
56

6-
impl SimpleStateroomService for EchoServer {
7-
fn new(_: &str, _: &impl StateroomContext) -> Self {
8-
EchoServer
9-
}
10-
7+
impl StateroomService for EchoServer {
118
fn connect(&mut self, client_id: ClientId, ctx: &impl StateroomContext) {
129
ctx.send_message(client_id, &format!("User {:?} connected.", client_id));
1310
}

examples/randomness/src/lib.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@ use bytemuck::cast;
22
use stateroom_wasm::prelude::*;
33

44
#[stateroom_wasm]
5+
#[derive(Default)]
56
struct RandomServer;
67

7-
impl SimpleStateroomService for RandomServer {
8-
fn new(_: &str, _: &impl StateroomContext) -> Self {
9-
RandomServer
10-
}
11-
8+
impl StateroomService for RandomServer {
129
fn connect(&mut self, client_id: ClientId, ctx: &impl StateroomContext) {
1310
let mut buf: [u8; 4] = [0, 0, 0, 0];
1411
unsafe {

stateroom-server/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ dashmap = "5.5.3"
1414
futures-util = "0.3.30"
1515
stateroom = {path="../stateroom", version="0.2.8"}
1616
tokio = { version = "1.37.0", features = ["rt-multi-thread"] }
17+
tracing = "0.1.40"

stateroom-server/src/lib.rs

+6-24
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ use axum::{
44
routing::get,
55
Router,
66
};
7-
use server::{ServerState, ServiceActorContext};
8-
use stateroom::{StateroomService, StateroomServiceFactory};
7+
use server::ServerState;
8+
use stateroom::StateroomServiceFactory;
99
use std::{
1010
net::{IpAddr, SocketAddr},
1111
sync::Arc,
@@ -103,17 +103,8 @@ impl Server {
103103
/// endpoints are available:
104104
/// - `/` (GET): return HTTP 200 if the server is running (useful as a baseline status check)
105105
/// - `/ws` (GET): initiate a WebSocket connection to the stateroom service.
106-
pub async fn serve_async<J: StateroomService + Send + Sync + Unpin + 'static>(
107-
self,
108-
service_factory: impl StateroomServiceFactory<ServiceActorContext, Service = J>
109-
+ Send
110-
+ Sync
111-
+ 'static,
112-
) -> std::io::Result<()>
113-
where
114-
J: StateroomService + Send + Sync + Unpin + 'static,
115-
{
116-
let server_state = Arc::new(ServerState::new(service_factory));
106+
pub async fn serve_async(self, factory: impl StateroomServiceFactory) -> std::io::Result<()> {
107+
let server_state = Arc::new(ServerState::new(factory));
117108

118109
let app = Router::new()
119110
.route("/ws", get(serve_websocket))
@@ -133,21 +124,12 @@ impl Server {
133124
/// endpoints are available:
134125
/// - `/` (GET): return HTTP 200 if the server is running (useful as a baseline status check)
135126
/// - `/ws` (GET): initiate a WebSocket connection to the stateroom service.
136-
pub fn serve<J>(
137-
self,
138-
service_factory: impl StateroomServiceFactory<ServiceActorContext, Service = J>
139-
+ Send
140-
+ Sync
141-
+ 'static,
142-
) -> std::io::Result<()>
143-
where
144-
J: StateroomService + Send + Sync + Unpin + 'static,
145-
{
127+
pub fn serve(self, factory: impl StateroomServiceFactory) -> std::io::Result<()> {
146128
tokio::runtime::Builder::new_multi_thread()
147129
.enable_all()
148130
.build()
149131
.unwrap()
150-
.block_on(async { self.serve_async(service_factory).await })
132+
.block_on(async { self.serve_async(factory).await })
151133
}
152134
}
153135

stateroom-server/src/server.rs

+24-30
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,12 @@ use tokio::{
1414

1515
/// A [StateroomContext] implementation for [StateroomService]s hosted in the
1616
/// context of a [ServiceActor].
17-
#[derive(Clone)]
18-
pub struct ServiceActorContext {
17+
pub struct ServerStateroomContext {
1918
senders: Arc<DashMap<ClientId, Sender<Message>>>,
20-
event_sender: Sender<Event>,
19+
event_sender: Arc<Sender<Event>>,
2120
}
2221

23-
impl ServiceActorContext {
22+
impl ServerStateroomContext {
2423
pub fn try_send(&self, recipient: MessageRecipient, message: Message) {
2524
match recipient {
2625
MessageRecipient::Broadcast => {
@@ -39,14 +38,14 @@ impl ServiceActorContext {
3938
if let Some(sender) = self.senders.get(&client_id) {
4039
sender.try_send(message).unwrap();
4140
} else {
42-
println!("No sender for client {:?}", client_id);
41+
tracing::error!(?client_id, "No sender for client.");
4342
}
4443
}
4544
}
4645
}
4746
}
4847

49-
impl StateroomContext for ServiceActorContext {
48+
impl StateroomContext for ServerStateroomContext {
5049
fn send_message(&self, recipient: impl Into<MessageRecipient>, message: &str) {
5150
self.try_send(recipient.into(), Message::Text(message.to_string()));
5251
}
@@ -60,7 +59,7 @@ impl StateroomContext for ServiceActorContext {
6059
let sender = self.event_sender.clone();
6160
tokio::spawn(async move {
6261
tokio::time::sleep(Duration::from_millis(ms_delay as u64)).await;
63-
sender.send(Event::TimerEvent).await.unwrap();
62+
sender.send(Event::Timer).await.unwrap();
6463
});
6564
}
6665
}
@@ -78,44 +77,39 @@ pub enum Event {
7877
Message { client: ClientId, message: Message },
7978
Join { client: ClientId },
8079
Leave { client: ClientId },
81-
TimerEvent,
80+
Timer,
8281
}
8382

8483
impl ServerState {
85-
pub fn new<T: StateroomService + Send + Sync + 'static>(
86-
service_factory: impl StateroomServiceFactory<ServiceActorContext, Service = T> + Send + 'static,
87-
) -> Self {
84+
pub fn new(factory: impl StateroomServiceFactory) -> Self {
8885
let (tx, mut rx) = tokio::sync::mpsc::channel::<Event>(100);
8986

9087
let senders = Arc::new(DashMap::new());
9188

9289
let senders_ = senders.clone();
9390
let tx_ = tx.clone();
9491
let handle = tokio::spawn(async move {
95-
let mut service = service_factory
96-
.build(
97-
"",
98-
ServiceActorContext {
99-
senders: senders_.clone(),
100-
event_sender: tx_,
101-
},
102-
)
103-
.unwrap();
104-
92+
let context = Arc::new(ServerStateroomContext {
93+
senders: senders_.clone(),
94+
event_sender: Arc::new(tx_),
95+
});
96+
97+
let mut service = factory.build("", context.clone()).unwrap();
98+
service.init(context.as_ref());
99+
105100
loop {
106101
let msg = rx.recv().await;
107-
println!("{:?}", msg);
108102
match msg {
109103
Some(Event::Message { client, message }) => match message {
110-
Message::Text(msg) => service.message(client, &msg),
111-
Message::Binary(msg) => service.binary(client, &msg),
104+
Message::Text(msg) => service.message(client, &msg, context.as_ref()),
105+
Message::Binary(msg) => service.binary(client, &msg, context.as_ref()),
112106
Message::Close(_) => {}
113-
msg => println!("Ignoring unhandled message: {:?}", msg),
107+
msg => tracing::warn!("Ignoring unhandled message: {:?}", msg),
114108
},
115-
Some(Event::Join { client }) => service.connect(client),
116-
Some(Event::Leave { client }) => service.disconnect(client),
117-
Some(Event::TimerEvent) => {
118-
service.timer();
109+
Some(Event::Join { client }) => service.connect(client, context.as_ref()),
110+
Some(Event::Leave { client }) => service.disconnect(client, context.as_ref()),
111+
Some(Event::Timer) => {
112+
service.timer(context.as_ref());
119113
}
120114
None => break,
121115
}
@@ -133,7 +127,7 @@ impl ServerState {
133127
pub fn remove(&self, client: &ClientId) {
134128
self.inbound_sender
135129
.try_send(Event::Leave {
136-
client: client.clone(),
130+
client: *client,
137131
})
138132
.unwrap();
139133
self.senders.remove(client);

0 commit comments

Comments
 (0)