Skip to content

Commit 4dc0f71

Browse files
committed
Remove some redundancies from wasm32 rust sdk
1 parent 0db89fa commit 4dc0f71

4 files changed

Lines changed: 26 additions & 51 deletions

File tree

Cargo.lock

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/sdk/Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@ getrandom = { version = "0.3.2", features = ["wasm_js"]}
3737
gloo-console = "0.3.0"
3838
gloo-storage = "0.3.0"
3939
rustls-pki-types = { version = "1.11.0", features = ["web"] }
40-
tokio-tungstenite-wasm = { git = "https://github.com/thlsrms/tokio-tungstenite-wasm", rev = "c788b7cfc30f576c" }
4140
tokio = { version = "1.37", default-features = false, features = [
42-
"rt", "macros", "sync"
41+
"rt", "macros", "sync", "io-util"
4342
] }
43+
tokio-tungstenite-wasm = "0.6.0"
4444
tungstenite = { version = "0.26.2", features = ["rustls"] }
4545
wasm-bindgen = "0.2.100"
4646
wasm-bindgen-futures = "0.4.45"
47-
web-sys = { version = "0.3.77", features = [ "Document", "HtmlDocument", "Window", "Storage" ] }
47+
web-sys = { version = "0.3.77", features = [ "Document", "HtmlDocument", "Window" ] }
4848

4949
[dev-dependencies]
5050
# for quickstart-chat and cursive-chat examples

crates/sdk/src/db_connection.rs

Lines changed: 16 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ pub struct DbContextImpl<M: SpacetimeModule> {
6767
/// which are pre-parsed in the background by [`parse_loop`].
6868
#[cfg(not(target_arch = "wasm32"))]
6969
recv: Arc<TokioMutex<mpsc::UnboundedReceiver<ParsedMessage<M>>>>,
70-
7170
#[cfg(target_arch = "wasm32")]
7271
recv: SharedCell<mpsc::UnboundedReceiver<ParsedMessage<M>>>,
7372

@@ -81,7 +80,6 @@ pub struct DbContextImpl<M: SpacetimeModule> {
8180
/// from which [Self::apply_pending_mutations] and friends read mutations.
8281
#[cfg(not(target_arch = "wasm32"))]
8382
pending_mutations_recv: Arc<TokioMutex<mpsc::UnboundedReceiver<PendingMutation<M>>>>,
84-
8583
#[cfg(target_arch = "wasm32")]
8684
pending_mutations_recv: SharedCell<mpsc::UnboundedReceiver<PendingMutation<M>>>,
8785

@@ -473,7 +471,6 @@ impl<M: SpacetimeModule> DbContextImpl<M> {
473471
/// If no WebSocket messages are in the queue, immediately return `false`.
474472
///
475473
/// Called by the autogenerated `DbConnection` method of the same name.
476-
#[cfg(not(target_arch = "wasm32"))]
477474
pub fn advance_one_message(&self) -> crate::Result<bool> {
478475
// Apply any pending mutations before processing a WS message,
479476
// so that pending callbacks don't get skipped.
@@ -490,42 +487,27 @@ impl<M: SpacetimeModule> DbContextImpl<M> {
490487
// returns `Err(_)`. Similar behavior as `Iterator::next` and
491488
// `Stream::poll_next`. No comment on whether this is a good mental
492489
// model or not.
493-
let res = match self.recv.blocking_lock().try_next() {
494-
Ok(None) => {
495-
let disconnect_ctx = self.make_event_ctx(None);
496-
self.invoke_disconnected(&disconnect_ctx);
497-
Err(crate::Error::Disconnected)
498-
}
499-
Err(_) => Ok(false),
500-
Ok(Some(msg)) => self.process_message(msg).map(|_| true),
501-
};
502490

503-
// Also apply any new pending messages afterwards,
504-
// so that outgoing WS messages get sent as soon as possible.
505-
self.apply_pending_mutations()?;
491+
let res = {
492+
#[cfg(not(target_arch = "wasm32"))]
493+
let mut recv = self.recv.blocking_lock();
506494

507-
res
508-
}
495+
#[cfg(target_arch = "wasm32")]
496+
let mut recv = self.recv.lock().unwrap();
509497

510-
#[cfg(target_arch = "wasm32")]
511-
pub fn advance_one_message(&self) -> crate::Result<bool> {
512-
self.apply_pending_mutations()?;
513-
// Synchronously try to pull one server message
514-
let res = {
515-
let mut chan = self.recv.lock().unwrap();
516-
match chan.try_next() {
498+
match recv.try_next() {
517499
Ok(None) => {
518-
// Shouldn’t happen on unbounded, treat as disconnect
519-
let ctx = self.make_event_ctx(None);
520-
self.invoke_disconnected(&ctx);
500+
let disconnect_ctx = self.make_event_ctx(None);
501+
self.invoke_disconnected(&disconnect_ctx);
521502
Err(crate::Error::Disconnected)
522503
}
523504
Err(_) => Ok(false),
524505
Ok(Some(msg)) => self.process_message(msg).map(|_| true),
525506
}
526507
};
527508

528-
// send any pending outgoing mutations now that we've done a read
509+
// Also apply any new pending messages afterwards,
510+
// so that outgoing WS messages get sent as soon as possible.
529511
self.apply_pending_mutations()?;
530512

531513
res
@@ -971,7 +953,7 @@ but you must call one of them, or else the connection will never progress.
971953
})?;
972954

973955
let (raw_msg_recv, raw_msg_send) = ws_connection.spawn_message_loop();
974-
let parsed_recv_chan = spawn_parse_loop::<M>(raw_msg_recv, &handle);
956+
let parsed_recv_chan = spawn_parse_loop::<M>(raw_msg_recv);
975957

976958
let inner = Arc::new(StdMutex::new(DbContextImplInner {
977959
runtime,
@@ -997,10 +979,8 @@ but you must call one of them, or else the connection will never progress.
997979
inner,
998980
send_chan,
999981
cache,
1000-
#[cfg(target_arch = "wasm32")]
1001982
recv: Arc::new(StdMutex::new(parsed_recv_chan)),
1002983
pending_mutations_send,
1003-
#[cfg(target_arch = "wasm32")]
1004984
pending_mutations_recv: Arc::new(StdMutex::new(pending_mutations_recv)),
1005985
identity: Arc::new(StdMutex::new(None)),
1006986
};
@@ -1125,14 +1105,12 @@ fn enter_or_create_runtime() -> crate::Result<(Option<Runtime>, runtime::Handle)
11251105
match runtime::Handle::try_current() {
11261106
Err(e) if e.is_missing_context() => {
11271107
#[cfg(not(target_arch = "wasm32"))]
1128-
let rt = tokio::runtime::Builder::new_multi_thread()
1129-
.enable_all()
1130-
.worker_threads(1)
1131-
.thread_name("spacetimedb-background-connection")
1132-
.build()
1133-
.map_err(|source| InternalError::new("Failed to create Tokio runtime").with_cause(source))?;
1108+
let mut rt = tokio::runtime::Builder::new_multi_thread();
11341109
#[cfg(target_arch = "wasm32")]
1135-
let rt = tokio::runtime::Builder::new_current_thread()
1110+
let mut rt = tokio::runtime::Builder::new_current_thread();
1111+
1112+
let rt = rt
1113+
.enable_all()
11361114
.worker_threads(1)
11371115
.thread_name("spacetimedb-background-connection")
11381116
.build()
@@ -1173,7 +1151,6 @@ fn spawn_parse_loop<M: SpacetimeModule>(
11731151
#[cfg(target_arch = "wasm32")]
11741152
fn spawn_parse_loop<M: SpacetimeModule>(
11751153
raw_message_recv: mpsc::UnboundedReceiver<ws::ServerMessage<BsatnFormat>>,
1176-
_handle: &runtime::Handle,
11771154
) -> mpsc::UnboundedReceiver<ParsedMessage<M>> {
11781155
let (parsed_message_send, parsed_message_recv) = mpsc::unbounded();
11791156
wasm_bindgen_futures::spawn_local(parse_loop(raw_message_recv, parsed_message_send));

crates/sdk/src/websocket.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -525,11 +525,6 @@ impl WsConnection {
525525
}
526526
},
527527

528-
Some(Ok(WebSocketMessage::Ping(payload)))
529-
| Some(Ok(WebSocketMessage::Pong(payload))) => {
530-
record_metrics(payload.len());
531-
},
532-
533528
Some(Ok(WebSocketMessage::Close(r))) => {
534529
let reason: String = if let Some(r) = r {
535530
format!("{}:{:?}", r, r.code)
@@ -557,12 +552,14 @@ impl WsConnection {
557552
outbound = outgoing.next() => if let Some(client_msg) = outbound {
558553
let raw = Self::encode_message(client_msg);
559554
if let Err(e) = ws_writer.send(raw).await {
560-
gloo_console::warn!("WS Send error: ", format!("{:?}",e));
555+
gloo_console::warn!("Error sending outgoing message:", format!("{:?}",e));
561556
break;
562557
}
563558
} else {
564559
// channel closed, so we're done sending
565-
let _ = ws_writer.close().await;
560+
if let Err(e) = ws_writer.close().await {
561+
gloo_console::warn!("Error sending close frame:", format!("{:?}", e));
562+
}
566563
break;
567564
},
568565
}

0 commit comments

Comments
 (0)