Skip to content

Commit a0ce8d4

Browse files
authored
fix: remove needless Semaphore::(u32::MAX) (#1051)
1 parent 014f771 commit a0ce8d4

File tree

2 files changed

+22
-33
lines changed

2 files changed

+22
-33
lines changed

core/src/server/helpers.rs

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore};
3838

3939
use super::rpc_module::{DisconnectError, SendTimeoutError, SubscriptionMessage, TrySendError};
4040

41+
/// Subscription permit.
42+
pub type SubscriptionPermit = OwnedSemaphorePermit;
43+
4144
/// Bounded writer that allows writing at most `max_len` bytes.
4245
///
4346
/// ```
@@ -191,20 +194,6 @@ pub fn prepare_error(data: &[u8]) -> (Id<'_>, ErrorCode) {
191194
}
192195
}
193196

194-
/// A permitted subscription.
195-
#[derive(Debug)]
196-
pub struct SubscriptionPermit {
197-
_permit: OwnedSemaphorePermit,
198-
resource: Arc<Notify>,
199-
}
200-
201-
impl SubscriptionPermit {
202-
/// Get the handle to [`tokio::sync::Notify`].
203-
pub fn handle(&self) -> Arc<Notify> {
204-
self.resource.clone()
205-
}
206-
}
207-
208197
/// Wrapper over [`tokio::sync::Notify`] with bounds check.
209198
#[derive(Debug, Clone)]
210199
pub struct BoundedSubscriptions {
@@ -227,10 +216,7 @@ impl BoundedSubscriptions {
227216
///
228217
/// Fails if `max_subscriptions` have been exceeded.
229218
pub fn acquire(&self) -> Option<SubscriptionPermit> {
230-
Arc::clone(&self.guard)
231-
.try_acquire_owned()
232-
.ok()
233-
.map(|p| SubscriptionPermit { _permit: p, resource: self.resource.clone() })
219+
Arc::clone(&self.guard).try_acquire_owned().ok()
234220
}
235221

236222
/// Get the maximum number of permitted subscriptions.

core/src/server/rpc_module.rs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,7 @@ pub type MaxResponseSize = usize;
7676
/// A 3-tuple containing:
7777
/// - Call result as a `String`,
7878
/// - a [`mpsc::UnboundedReceiver<String>`] to receive future subscription results
79-
/// - a [`crate::server::helpers::SubscriptionPermit`] to allow subscribers to notify their [`SubscriptionSink`] when
80-
/// they disconnect.
81-
pub type RawRpcResponse = (MethodResponse, mpsc::Receiver<String>, SubscriptionPermit);
79+
pub type RawRpcResponse = (MethodResponse, mpsc::Receiver<String>);
8280

8381
/// Error that may occur during [`SubscriptionSink::try_send`].
8482
#[derive(Debug)]
@@ -408,7 +406,7 @@ impl Methods {
408406
let params = params.to_rpc_params()?;
409407
let req = Request::new(method.into(), params.as_ref().map(|p| p.as_ref()), Id::Number(0));
410408
tracing::trace!("[Methods::call] Method: {:?}, params: {:?}", method, params);
411-
let (resp, _, _) = self.inner_call(req, 1).await;
409+
let (resp, _) = self.inner_call(req, 1, mock_subscription_permit()).await;
412410

413411
if resp.success {
414412
serde_json::from_str::<Response<T>>(&resp.result).map(|r| r.result).map_err(Into::into)
@@ -456,27 +454,28 @@ impl Methods {
456454
) -> Result<(MethodResponse, mpsc::Receiver<String>), Error> {
457455
tracing::trace!("[Methods::raw_json_request] Request: {:?}", request);
458456
let req: Request = serde_json::from_str(request)?;
459-
let (resp, rx, _) = self.inner_call(req, buf_size).await;
457+
let (resp, rx) = self.inner_call(req, buf_size, mock_subscription_permit()).await;
460458

461459
Ok((resp, rx))
462460
}
463461

464462
/// Execute a callback.
465-
async fn inner_call(&self, req: Request<'_>, buf_size: usize) -> RawRpcResponse {
463+
async fn inner_call(
464+
&self,
465+
req: Request<'_>,
466+
buf_size: usize,
467+
subscription_permit: SubscriptionPermit,
468+
) -> RawRpcResponse {
466469
let (tx, mut rx) = mpsc::channel(buf_size);
467470
let id = req.id.clone();
468471
let params = Params::new(req.params.map(|params| params.get()));
469-
let bounded_subs = BoundedSubscriptions::new(u32::MAX);
470-
let p1 = bounded_subs.acquire().expect("u32::MAX permits is sufficient; qed");
471-
let p2 = bounded_subs.acquire().expect("u32::MAX permits is sufficient; qed");
472472

473473
let response = match self.method(&req.method) {
474474
None => MethodResponse::error(req.id, ErrorObject::from(ErrorCode::MethodNotFound)),
475475
Some(MethodCallback::Sync(cb)) => (cb)(id, params, usize::MAX),
476476
Some(MethodCallback::Async(cb)) => (cb)(id.into_owned(), params.into_owned(), 0, usize::MAX).await,
477477
Some(MethodCallback::Subscription(cb)) => {
478-
let conn_state =
479-
ConnState { conn_id: 0, id_provider: &RandomIntegerIdProvider, subscription_permit: p1 };
478+
let conn_state = ConnState { conn_id: 0, id_provider: &RandomIntegerIdProvider, subscription_permit };
480479
let res = match (cb)(id, params, MethodSink::new(tx.clone()), conn_state).await {
481480
Ok(rp) => rp,
482481
Err(id) => MethodResponse::error(id, ErrorObject::from(ErrorCode::InternalError)),
@@ -495,7 +494,7 @@ impl Methods {
495494

496495
tracing::trace!("[Methods::inner_call] Method: {}, response: {:?}", req.method, response);
497496

498-
(response, rx, p2)
497+
(response, rx)
499498
}
500499

501500
/// Helper to create a subscription on the `RPC module` without having to spin up a server.
@@ -544,7 +543,7 @@ impl Methods {
544543

545544
tracing::trace!("[Methods::subscribe] Method: {}, params: {:?}", sub_method, params);
546545

547-
let (resp, rx, permit) = self.inner_call(req, buf_size).await;
546+
let (resp, rx) = self.inner_call(req, buf_size, mock_subscription_permit()).await;
548547

549548
let subscription_response = match serde_json::from_str::<Response<RpcSubscriptionId>>(&resp.result) {
550549
Ok(r) => r,
@@ -556,7 +555,7 @@ impl Methods {
556555

557556
let sub_id = subscription_response.result.into_owned();
558557

559-
Ok(Subscription { sub_id, rx, _permit: permit })
558+
Ok(Subscription { sub_id, rx })
560559
}
561560

562561
/// Returns an `Iterator` with all the method names registered on this server.
@@ -1127,7 +1126,6 @@ impl Drop for SubscriptionSink {
11271126
pub struct Subscription {
11281127
rx: mpsc::Receiver<String>,
11291128
sub_id: RpcSubscriptionId<'static>,
1130-
_permit: SubscriptionPermit,
11311129
}
11321130

11331131
impl Subscription {
@@ -1168,3 +1166,8 @@ impl Drop for Subscription {
11681166
self.close();
11691167
}
11701168
}
1169+
1170+
// Mock subscription permit to be able to make a call.
1171+
fn mock_subscription_permit() -> SubscriptionPermit {
1172+
BoundedSubscriptions::new(1).acquire().expect("1 permit should exist; qed")
1173+
}

0 commit comments

Comments
 (0)