From 6c8e2d395799757e5a946fe01226f739d0706741 Mon Sep 17 00:00:00 2001 From: Hansie Odendaal <39146854+hansieodendaal@users.noreply.github.com> Date: Fri, 22 Sep 2023 09:16:50 +0200 Subject: [PATCH] fix: possible exception in request_context (#5784) Description --- Fixed possible exception in `pub struct RequestContext` that could occur when splitting the request and reply channel in `pub fn split` Motivation and Context --- The code should not be allowed to panic in use in the wrong context. How Has This Been Tested? --- Unit tests What process can a PR reviewer use to test or verify this change? --- Code walk through Breaking Changes --- - [x] None - [ ] Requires data directory on base node to be deleted - [ ] Requires hard fork - [ ] Other - Please specify --------- Co-authored-by: SW van Heerden --- base_layer/service_framework/src/lib.rs | 2 +- .../service_framework/src/reply_channel.rs | 22 +++++-------------- 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/base_layer/service_framework/src/lib.rs b/base_layer/service_framework/src/lib.rs index 1b6143d3ed..f2642c15f8 100644 --- a/base_layer/service_framework/src/lib.rs +++ b/base_layer/service_framework/src/lib.rs @@ -52,7 +52,7 @@ //! // At the same time receive the request and reply //! async move { //! let req_context = receiver.next().await.unwrap(); -//! let msg = req_context.request().unwrap().clone(); +//! let msg = req_context.request().clone(); //! req_context.reply(msg.to_uppercase()); //! } //! ); diff --git a/base_layer/service_framework/src/reply_channel.rs b/base_layer/service_framework/src/reply_channel.rs index f69374405b..983fd0afe3 100644 --- a/base_layer/service_framework/src/reply_channel.rs +++ b/base_layer/service_framework/src/reply_channel.rs @@ -131,37 +131,25 @@ impl Future for TransportResponseFuture { /// request. pub struct RequestContext { reply_tx: oneshot::Sender, - request: Option, + request: TReq, } impl RequestContext { /// Create a new RequestContect pub fn new(request: TReq, reply_tx: oneshot::Sender) -> Self { - Self { - request: Some(request), - reply_tx, - } + Self { request, reply_tx } } /// Return a reference to the request object. None is returned after take_request has /// been called. - pub fn request(&self) -> Option<&TReq> { - self.request.as_ref() - } - - /// Take ownership of the request object, if ownership has not already been taken, - /// otherwise None is returned. - pub fn take_request(&mut self) -> Option { - self.request.take() + pub fn request(&self) -> &TReq { + &self.request } /// Consume this object and return it's parts. Namely, the request object and /// the reply oneshot channel. pub fn split(self) -> (TReq, oneshot::Sender) { - ( - self.request.expect("RequestContext must be initialized with a request"), - self.reply_tx, - ) + (self.request, self.reply_tx) } /// Sends a reply to the caller