Skip to content

Commit fca1910

Browse files
authored
fix: buggy assigned port id and buggy websocket transport (#80)
1 parent a46a422 commit fca1910

5 files changed

Lines changed: 54 additions & 29 deletions

File tree

rpc/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "dcl-rpc"
3-
version = "2.0.0"
3+
version = "2.0.1"
44
edition = "2021"
55
description = "Decentraland RPC Implementation"
66
repository = "https://github.com/decentraland/rpc-rust"

rpc/src/client.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,11 @@ impl<T: Transport> RpcClientPort<T> {
161161
}
162162
}
163163

164+
/// Get the Port's ID assigned by the [`RpcServer`](`crate::server::RpcServer`)
165+
pub fn port_id(&self) -> u32 {
166+
self.port_id
167+
}
168+
164169
/// Sends a request to the [`RpcServer`](crate::server::RpcServer) requesting a remote module so then the returned module is loaded into memory so that it can be used by the client.
165170
///
166171
/// It returns a `impl ServiceClient` that should auto generated by the codegen

rpc/src/messages_handlers.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,15 @@ use tokio_util::sync::CancellationToken;
3939
/// It spawns a background tasks to process every request
4040
///
4141
#[derive(Default)]
42+
#[cfg(feature = "server")]
4243
pub struct ServerMessagesHandler {
4344
/// Data structure in charge of handling all messages related to streams
4445
pub streams_handler: Arc<StreamsHandler>,
4546
/// Stores listeners for client streams messages
4647
listeners: Mutex<HashMap<u32, AsyncChannelSender<StreamPackage>>>,
4748
}
4849

50+
#[cfg(feature = "server")]
4951
impl ServerMessagesHandler {
5052
pub fn new() -> Self {
5153
Self {
@@ -380,6 +382,7 @@ type StreamPackage = (RpcMessageTypes, u32, StreamMessage);
380382
/// It's the data structure that actually owns the Transport attached to a `RpcClient`. The transport is drilled down up to get to `ClientMEssagesHandler`
381383
///
382384
///
385+
#[cfg(feature = "client")]
383386
pub struct ClientMessagesHandler<T: Transport + ?Sized> {
384387
/// Transport received by a `RpcClient`
385388
pub transport: Arc<T>,
@@ -412,6 +415,7 @@ pub struct ClientMessagesHandler<T: Transport + ?Sized> {
412415
process_cancellation_token: CancellationToken,
413416
}
414417

418+
#[cfg(feature = "client")]
415419
impl<T: Transport + ?Sized + 'static> ClientMessagesHandler<T> {
416420
pub fn new(transport: Arc<T>) -> Self {
417421
Self {
@@ -504,7 +508,7 @@ impl<T: Transport + ?Sized + 'static> ClientMessagesHandler<T> {
504508
}
505509
}
506510
Err(error) => {
507-
error!("> ClientMessagesHandler > process > Error on receive, breaking the listening: {error:?}");
511+
error!("> ClientMessagesHandler > process > Error on receive {error:?}");
508512
if matches!(error, TransportError::Closed) {
509513
info!("> ClientMessagesHandler > process > closing...");
510514
break;

rpc/src/server.rs

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,13 @@ pub enum ServerError {
4141
/// Error on decoding bytes (`Vec<u8>`) into a given type using [`crate::rpc_protocol::parse::parse_protocol_message`] or using the [`Message::decode`]
4242
ProtocolError,
4343
/// Port was not found in the server state, possibly not created
44-
PortNotFound,
44+
PortNotFound(u32),
4545
/// Error on loading a Module, unlikely to happen
4646
LoadModuleError,
4747
/// Module was not found, not registered in the server
48-
ModuleNotFound,
48+
ModuleNotFound(String),
4949
/// Given procedure's ID was not found
50-
ProcedureNotFound,
50+
ProcedureNotFound(u32),
5151
/// Unexpexted Error while responding back or Error on sending the original procedure response
5252
///
5353
/// This error should be use as a "re-try" when a [`Transport::send`] failed.
@@ -58,9 +58,9 @@ impl RemoteErrorResponse for ServerError {
5858
fn error_code(&self) -> u32 {
5959
match self {
6060
Self::ProtocolError => 1,
61-
Self::PortNotFound => 2,
62-
Self::ModuleNotFound => 3,
63-
Self::ProcedureNotFound => 4,
61+
Self::PortNotFound(_) => 2,
62+
Self::ModuleNotFound(_) => 3,
63+
Self::ProcedureNotFound(_) => 4,
6464
Self::UnexpectedErrorOnTransport => 5,
6565
Self::LoadModuleError => 0, // it's unlikely to happen
6666
}
@@ -69,10 +69,10 @@ impl RemoteErrorResponse for ServerError {
6969
fn error_message(&self) -> String {
7070
match self {
7171
Self::ProtocolError => "Error on parsing a message. The content seems to be corrupted and not to meet the protocol requirements".to_string(),
72-
Self::PortNotFound => "The given Port's ID was not found".to_string(),
72+
Self::PortNotFound(id) => format!("The given Port's ID: {id} was not found"),
7373
Self::LoadModuleError => "Error on loading a module".to_string(),
74-
Self::ModuleNotFound => "Module wasn't found on the server, check the name".to_string(),
75-
Self::ProcedureNotFound => "Procedure's ID wasn't found on the server".to_string(),
74+
Self::ModuleNotFound(module_name) => format!("Module wasn't found on the server, check the name: {module_name}"),
75+
Self::ProcedureNotFound(id) => format!("Procedure's ID: {id} wasn't found on the server"),
7676
Self::UnexpectedErrorOnTransport => "Error on the transport while sending the original procedure response".to_string()
7777
}
7878
}
@@ -194,6 +194,8 @@ pub struct RpcServer<Context, T: Transport + ?Sized> {
194194
server_events_receiver: Option<UnboundedReceiver<ServerEvents<T>>>,
195195
/// The id that will be assigned if a new transport is a attached
196196
next_transport_id: u32,
197+
/// THe id that will be assigned to a port when it's created.
198+
next_port_id: u32,
197199
}
198200
impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<Context, T> {
199201
pub fn create(ctx: Context) -> Self {
@@ -207,6 +209,7 @@ impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<
207209
context: Arc::new(ctx),
208210
messages_handler: Arc::new(ServerMessagesHandler::new()),
209211
next_transport_id: 1,
212+
next_port_id: 1,
210213
server_events_sender: ServerEventsSender(channel.0),
211214
server_events_receiver: Some(channel.1),
212215
}
@@ -387,10 +390,10 @@ impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<
387390
}
388391
}
389392
Err(error) => {
390-
error!(
391-
"> From a Transport > Error on receiving: {error:?}"
392-
);
393393
if matches!(error, TransportError::Closed) {
394+
error!(
395+
"> From a Transport > Transport is already closed. Breaking..."
396+
);
394397
if tx_cloned
395398
.send(TransportNotification::CloseTransport(id))
396399
.is_err()
@@ -400,6 +403,7 @@ impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<
400403
}
401404
break;
402405
}
406+
error!("> From a Transport > Error on receiving {error:?}");
403407
}
404408
}
405409
}
@@ -558,7 +562,9 @@ impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<
558562

559563
Ok(())
560564
}
561-
_ => Err(ServerResultError::External(ServerError::PortNotFound)),
565+
_ => Err(ServerResultError::External(ServerError::PortNotFound(
566+
request.port_id,
567+
))),
562568
}
563569
}
564570

@@ -605,7 +611,9 @@ impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<
605611
return Err(ServerResultError::External(ServerError::LoadModuleError));
606612
}
607613
} else {
608-
return Err(ServerResultError::External(ServerError::PortNotFound));
614+
return Err(ServerResultError::External(ServerError::PortNotFound(
615+
request_module.port_id,
616+
)));
609617
}
610618

611619
Ok(())
@@ -627,7 +635,8 @@ impl<Context: Send + Sync + 'static, T: Transport + ?Sized + 'static> RpcServer<
627635
message_number: u32,
628636
payload: Vec<u8>,
629637
) -> ServerResult<()> {
630-
let port_id = (self.ports.len() + 1) as u32;
638+
let port_id = self.next_port_id;
639+
self.next_port_id += 1;
631640
let create_port = CreatePort::decode(payload.as_slice())
632641
.map_err(|_| ServerResultError::External(ServerError::ProtocolError))?;
633642
let port_name = create_port.port_name;
@@ -784,7 +793,9 @@ impl<Context> RpcServerPort<Context> {
784793
.expect("Already checked."))
785794
} else {
786795
match self.registered_modules.get(&module_name) {
787-
None => Err(ServerResultError::External(ServerError::ModuleNotFound)),
796+
None => Err(ServerResultError::External(ServerError::ModuleNotFound(
797+
module_name,
798+
))),
788799
Some(module_generator) => {
789800
let mut server_module_declaration = ServerModuleDeclaration {
790801
procedures: Vec::new(),
@@ -823,7 +834,9 @@ impl<Context> RpcServerPort<Context> {
823834
fn get_procedure(&self, procedure_id: u32) -> ServerResult<ProcedureDefinition<Context>> {
824835
match self.procedures.get(&procedure_id) {
825836
Some(procedure_definition) => Ok(procedure_definition.clone()),
826-
_ => Err(ServerResultError::External(ServerError::ProcedureNotFound)),
837+
_ => Err(ServerResultError::External(ServerError::ProcedureNotFound(
838+
procedure_id,
839+
))),
827840
}
828841
}
829842
}

rpc/src/transports/web_socket.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ use super::{Transport, TransportError, TransportMessage};
55
use async_trait::async_trait;
66
use futures_util::{
77
stream::{SplitSink, SplitStream},
8-
SinkExt, StreamExt, TryStreamExt,
8+
SinkExt, StreamExt,
99
};
10-
use log::{debug, error, info};
10+
use log::{debug, error};
1111
use std::error::Error;
1212
use tokio::{
1313
net::{TcpListener, TcpStream},
@@ -188,22 +188,21 @@ impl WebSocketTransport {
188188
#[async_trait]
189189
impl Transport for WebSocketTransport {
190190
async fn receive(&self) -> Result<TransportMessage, TransportError> {
191-
match self.read.lock().await.try_next().await {
192-
Ok(Some(message)) => {
191+
match self.read.lock().await.next().await {
192+
Some(Ok(message)) => {
193193
if message.is_binary() {
194194
let message_data = message.into_data();
195195
return Ok(message_data);
196196
} else {
197+
if message.is_close() {
198+
return Err(TransportError::Closed);
199+
}
197200
// Ignore messages that are not binary
198201
error!("> WebSocketTransport > Received message is not binary");
199202
return Err(TransportError::NotBinaryMessage);
200203
}
201204
}
202-
Ok(_) => {
203-
error!("> WebSocketTransport > WEIRD: Ok(None)");
204-
Err(TransportError::Closed)
205-
}
206-
Err(err) => {
205+
Some(Err(err)) => {
207206
error!(
208207
"> WebSocketTransport > Failed to receive message {}",
209208
err.to_string()
@@ -215,6 +214,10 @@ impl Transport for WebSocketTransport {
215214
error => return Err(TransportError::Internal(Box::new(error))),
216215
}
217216
}
217+
None => {
218+
error!("> WebSocketTransport > None received > Closing...");
219+
return Err(TransportError::Closed);
220+
}
218221
}
219222
}
220223

@@ -243,7 +246,7 @@ impl Transport for WebSocketTransport {
243246
async fn close(&self) {
244247
match self.write.lock().await.close().await {
245248
Ok(_) => {
246-
info!("> WebSocketTransport > Closed successfully")
249+
debug!("> WebSocketTransport > Closed successfully")
247250
}
248251
Err(err) => {
249252
error!("> WebSocketTransport > Error: Couldn't close tranport: {err:?}")

0 commit comments

Comments
 (0)