Skip to content

Commit

Permalink
Optimize the codes
Browse files Browse the repository at this point in the history
  • Loading branch information
rmqtt committed Jul 5, 2023
1 parent 9450346 commit 662ed4a
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 32 deletions.
2 changes: 1 addition & 1 deletion rmqtt-plugins/rmqtt-http-api/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ async fn kick_client(req: &mut Request, res: &mut Response) {
match entry.kick(true, true).await {
Err(e) => res.set_status_error(StatusError::service_unavailable().with_detail(e.to_string())),
Ok(None) => res.set_status_code(StatusCode::NOT_FOUND),
Ok(Some(offline_info)) => res.render(Text::Plain(offline_info.id.as_str().to_owned())),
Ok(Some(offline_info)) => res.render(Text::Plain(offline_info.id.to_string())),
}
} else {
res.set_status_error(StatusError::bad_request())
Expand Down
2 changes: 1 addition & 1 deletion rmqtt-plugins/rmqtt-http-api/src/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ async fn build_result(s: Option<Session>, c: Option<ClientInfo>) -> SearchResult
SearchResult {
node_id: c.id.node_id,
clientid: c.id.client_id.clone(),
username: c.username().clone(),
username: c.id.username(),
superuser: c.superuser,
proto_ver: c.connect_info.proto_ver(),
ip_address: c.id.remote_addr.map(|addr| addr.ip().to_string()),
Expand Down
4 changes: 2 additions & 2 deletions rmqtt-plugins/rmqtt-web-hook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ impl JsonTo for Id {
.unwrap_or(serde_json::Value::Null),
);
obj.insert("clientid".into(), serde_json::Value::String(self.client_id.to_string()));
obj.insert("username".into(), serde_json::Value::String(self.username.to_string()));
obj.insert("username".into(), serde_json::Value::String(self.username_ref().into()));
}
json
}
Expand All @@ -450,7 +450,7 @@ impl JsonFrom for Id {
.unwrap_or(serde_json::Value::Null),
);
obj.insert("from_clientid".into(), serde_json::Value::String(self.client_id.to_string()));
obj.insert("from_username".into(), serde_json::Value::String(self.username.to_string()));
obj.insert("from_username".into(), serde_json::Value::String(self.username_ref().into()));
}
json
}
Expand Down
4 changes: 2 additions & 2 deletions rmqtt/src/broker/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1022,8 +1022,8 @@ impl ClientInfo {
}

#[inline]
pub fn username(&self) -> &UserName {
&self.id.username
pub fn username(&self) -> &str {
self.id.username_ref()
}

#[inline]
Expand Down
57 changes: 31 additions & 26 deletions rmqtt/src/broker/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ pub type SubscriptionValue = (QoS, Option<SharedGroup>);
pub type HookSubscribeResult = Vec<Option<TopicFilter>>;
pub type HookUnsubscribeResult = Vec<Option<TopicFilter>>;

pub(crate) const UNDEFINED: &str = "undefined";

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ConnectInfo {
V3(Id, ConnectV3),
Expand Down Expand Up @@ -896,19 +898,11 @@ impl Id {
username: Option<UserName>,
) -> Self {
Self(Arc::new(_Id {
id: ByteString::from(format!(
"{}@{}/{}/{}/{}",
node_id,
local_addr.map(|addr| addr.to_string()).unwrap_or_default(),
remote_addr.map(|addr| addr.to_string()).unwrap_or_default(),
client_id,
username.as_ref().map(<UserName as AsRef<str>>::as_ref).unwrap_or_default()
)),
node_id,
local_addr,
remote_addr,
client_id,
username: username.unwrap_or_else(|| "undefined".into()),
username,
create_time: chrono::Local::now().timestamp_millis(),
}))
}
Expand All @@ -919,7 +913,7 @@ impl Id {
"node": self.node(),
"ipaddress": self.remote_addr,
"clientid": self.client_id,
"username": self.username,
"username": self.username_ref(),
"create_time": self.create_time,
})
}
Expand All @@ -930,42 +924,50 @@ impl Id {
}

#[inline]
pub fn as_str(&self) -> &str {
&self.id
pub fn node(&self) -> NodeId {
self.node_id
}

#[inline]
pub fn node(&self) -> NodeId {
//format!("{}/{}", self.node_id, self.local_addr.map(|addr| addr.to_string()).unwrap_or_default())
self.node_id
pub fn username(&self) -> UserName {
self.username.clone().unwrap_or_else(|| UserName::from_static(UNDEFINED))
}
}

impl AsRef<str> for Id {
#[inline]
fn as_ref(&self) -> &str {
&self.id
pub fn username_ref(&self) -> &str {
self.username.as_ref().map(<UserName as AsRef<str>>::as_ref).unwrap_or_else(|| UNDEFINED)
}
}

impl ToString for Id {
#[inline]
fn to_string(&self) -> String {
self.id.to_string()
format!(
"{}@{}/{}/{}/{}",
self.node_id,
self.local_addr.map(|addr| addr.to_string()).unwrap_or_default(),
self.remote_addr.map(|addr| addr.to_string()).unwrap_or_default(),
self.client_id,
self.username_ref()
)
}
}

impl std::fmt::Debug for Id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}-{}", self.id, self.create_time)
write!(f, "{}-{}", self.to_string(), self.create_time)
}
}

impl PartialEq<Id> for Id {
#[inline]
fn eq(&self, other: &Id) -> bool {
self.id == other.id
fn eq(&self, o: &Id) -> bool {
self.node_id == o.node_id
&& self.client_id == o.client_id
&& self.local_addr == o.local_addr
&& self.remote_addr == o.remote_addr
&& self.username == o.username
}
}

Expand All @@ -974,7 +976,11 @@ impl Eq for Id {}
impl std::hash::Hash for Id {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
self.node_id.hash(state);
self.local_addr.hash(state);
self.remote_addr.hash(state);
self.client_id.hash(state);
self.username.hash(state);
}
}

Expand Down Expand Up @@ -1008,12 +1014,11 @@ impl<'de> Deserialize<'de> for Id {

#[derive(Debug, PartialEq, Eq, Hash, Clone, Deserialize, Serialize)]
pub struct _Id {
id: ByteString,
pub node_id: NodeId,
pub local_addr: Option<SocketAddr>,
pub remote_addr: Option<SocketAddr>,
pub client_id: ClientId,
pub username: UserName,
pub username: Option<UserName>,
pub create_time: TimestampMillis,
}

Expand Down

0 comments on commit 662ed4a

Please sign in to comment.