Skip to content

Commit d94bb81

Browse files
committed
chore(sidecar): JsonRpcResponse should be an enum
1 parent c232c3a commit d94bb81

File tree

5 files changed

+155
-65
lines changed

5 files changed

+155
-65
lines changed

bolt-sidecar/src/api/commitments/firewall/processor.rs

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use futures::{
22
stream::{FuturesUnordered, SplitSink, SplitStream},
33
FutureExt, SinkExt, StreamExt,
44
};
5+
use serde::Serialize;
56
use serde_json::{json, Value};
67
use std::{collections::VecDeque, future::Future, pin::Pin, task::Poll};
78
use tokio::{
@@ -30,7 +31,9 @@ use crate::{
3031
config::limits::LimitsOpts,
3132
primitives::{
3233
commitment::SignedCommitment,
33-
jsonrpc::{JsonResponse, JsonRpcRequestUuid},
34+
jsonrpc::{
35+
JsonRpcErrorResponse, JsonRpcRequestUuid, JsonRpcResponse, JsonRpcSuccessResponse,
36+
},
3437
misc::{Identified, IntoIdentified},
3538
CommitmentRequest, InclusionRequest,
3639
},
@@ -257,15 +260,14 @@ impl CommitmentRequestProcessor {
257260
return;
258261
};
259262

260-
let mut response =
261-
JsonResponse { id: Some(Value::String(id.to_string())), ..Default::default() };
262-
263-
match result_commitment {
264-
Ok(commitment) => response.result = json!(commitment),
263+
let response: JsonRpcResponse = match result_commitment {
264+
Ok(commitment) => JsonRpcSuccessResponse::new(json!(commitment))
265+
.with_id(Value::String(id.to_string()))
266+
.into(),
265267
Err(e) => {
266-
response.error = Some(e.into());
268+
JsonRpcErrorResponse::new(e.into()).with_id(Value::String(id.to_string())).into()
267269
}
268-
}
270+
};
269271

270272
let message =
271273
Message::Text(serde_json::to_string(&response).expect("to stringify response"));
@@ -289,26 +291,27 @@ impl CommitmentRequestProcessor {
289291
};
290292

291293
let id = request.id;
292-
let mut response = JsonResponse {
293-
id: Some(Value::String(id.to_string())),
294-
jsonrpc: "2.0".to_string(),
295-
..Default::default()
296-
};
297294

298295
match request.method.as_str() {
299296
GET_VERSION_METHOD => {
300-
response.result = Value::String(BOLT_SIDECAR_VERSION.clone());
297+
let response =
298+
JsonRpcSuccessResponse::new(Value::String(BOLT_SIDECAR_VERSION.clone()))
299+
.with_uuid(id)
300+
.into();
301301
self.send_response(response);
302302
}
303303
GET_METADATA_METHOD => {
304-
response.result = serde_json::to_value(self.state.limits).expect("infallible");
304+
let response =
305+
JsonRpcSuccessResponse::new(json!(self.state.limits)).with_uuid(id).into();
305306
self.send_response(response);
306307
}
307308
REQUEST_INCLUSION_METHOD => {
308309
let Some(param) = request.params.first().cloned() else {
309-
response.error = Some(
310+
let response: JsonRpcResponse = JsonRpcErrorResponse::new(
310311
CommitmentError::InvalidParams("missing inclusion request".into()).into(),
311-
);
312+
)
313+
.with_uuid(id)
314+
.into();
312315
self.send_response(response);
313316
return;
314317
};
@@ -318,7 +321,10 @@ impl CommitmentRequestProcessor {
318321
Err(e) => {
319322
let msg = format!("failed to parse inclusion request: {}", e);
320323
error!(?e, "failed to parse inclusion request");
321-
response.error = Some(CommitmentError::InvalidParams(msg).into());
324+
let response: JsonRpcResponse =
325+
JsonRpcErrorResponse::new(CommitmentError::InvalidParams(msg).into())
326+
.with_uuid(id)
327+
.into();
322328
self.send_response(response);
323329
return;
324330
}
@@ -330,7 +336,10 @@ impl CommitmentRequestProcessor {
330336

331337
if let Err(e) = self.api_events_tx.try_send(commitment_event) {
332338
error!(?e, "failed to send commitment event through channel");
333-
response.error = Some(CommitmentError::Internal.into());
339+
let response: JsonRpcResponse =
340+
JsonRpcErrorResponse::new(CommitmentError::Internal.into())
341+
.with_uuid(id)
342+
.into();
334343
self.send_response(response);
335344
return;
336345
}
@@ -344,7 +353,7 @@ impl CommitmentRequestProcessor {
344353
};
345354
}
346355

347-
fn send_response(&mut self, response: JsonResponse) {
356+
fn send_response<T: Serialize>(&mut self, response: JsonRpcResponse<T>) {
348357
let message =
349358
Message::text(serde_json::to_string(&response).expect("to stringify response"));
350359
self.outgoing_messages.push_back(message);

bolt-sidecar/src/api/commitments/server/handlers.rs

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use axum::{
99
};
1010
use axum_extra::extract::WithRejection;
1111
use serde::{Deserialize, Serialize};
12-
use serde_json::Value;
12+
use serde_json::json;
1313
use tracing::{debug, error, info, instrument};
1414

1515
use crate::{
@@ -23,7 +23,7 @@ use crate::{
2323
common::BOLT_SIDECAR_VERSION,
2424
config::limits::LimitsOpts,
2525
primitives::{
26-
jsonrpc::{JsonResponse, JsonRpcRequest},
26+
jsonrpc::{JsonRpcRequest, JsonRpcResponse, JsonRpcSuccessResponse},
2727
signature::SignatureError,
2828
InclusionRequest,
2929
},
@@ -48,28 +48,31 @@ pub async fn rpc_entrypoint(
4848
headers: HeaderMap,
4949
State(api): State<Arc<CommitmentsApiInner>>,
5050
WithRejection(Json(payload), _): WithRejection<Json<JsonRpcRequest>, CommitmentError>,
51-
) -> Result<Json<JsonResponse>, CommitmentError> {
51+
) -> Result<Json<JsonRpcResponse>, CommitmentError> {
5252
debug!("Received new request");
5353

5454
match payload.method.as_str() {
55-
GET_VERSION_METHOD => Ok(Json(JsonResponse {
56-
id: payload.id,
57-
result: Value::String(BOLT_SIDECAR_VERSION.clone()),
58-
..Default::default()
59-
})),
55+
GET_VERSION_METHOD => Ok(Json(
56+
JsonRpcSuccessResponse {
57+
id: payload.id,
58+
result: json!(BOLT_SIDECAR_VERSION.to_string()),
59+
..Default::default()
60+
}
61+
.into(),
62+
)),
6063

6164
GET_METADATA_METHOD => {
6265
let metadata = MetadataResponse {
6366
limits: api.limits(),
6467
version: BOLT_SIDECAR_VERSION.to_string(),
6568
};
6669

67-
let response = JsonResponse {
70+
let response = JsonRpcSuccessResponse {
6871
id: payload.id,
69-
result: serde_json::to_value(metadata)
70-
.expect("infallible - metadata only contains primitive types"),
72+
result: json!(metadata),
7173
..Default::default()
72-
};
74+
}
75+
.into();
7376
Ok(Json(response))
7477
}
7578

@@ -113,11 +116,12 @@ pub async fn rpc_entrypoint(
113116
let inclusion_commitment = api.request_inclusion(inclusion_request).await?;
114117

115118
// Create the JSON-RPC response
116-
let response = JsonResponse {
119+
let response = JsonRpcSuccessResponse {
117120
id: payload.id,
118-
result: serde_json::to_value(inclusion_commitment).expect("infallible"),
121+
result: json!(inclusion_commitment),
119122
..Default::default()
120-
};
123+
}
124+
.into();
121125

122126
Ok(Json(response))
123127
}

bolt-sidecar/src/api/commitments/server/mod.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -179,14 +179,14 @@ fn make_router(state: Arc<CommitmentsApiInner>) -> Router {
179179
mod test {
180180
use crate::{
181181
api::commitments::spec::SIGNATURE_HEADER, common::BOLT_SIDECAR_VERSION,
182-
primitives::jsonrpc::JsonError,
182+
primitives::jsonrpc::JsonRpcError,
183183
};
184184
use alloy::signers::{k256::SecretKey, local::PrivateKeySigner};
185185
use handlers::MetadataResponse;
186186
use serde_json::json;
187187

188188
use crate::{
189-
primitives::{jsonrpc::JsonResponse, signature::ECDSASignatureExt},
189+
primitives::{jsonrpc::JsonRpcResponse, signature::ECDSASignatureExt},
190190
test_util::{create_signed_inclusion_request, default_test_transaction},
191191
};
192192

@@ -226,13 +226,13 @@ mod test {
226226
.send()
227227
.await
228228
.unwrap()
229-
.json::<JsonResponse>()
229+
.json::<JsonRpcResponse>()
230230
.await
231231
.unwrap();
232232

233233
// Assert unauthorized because of missing signature
234-
let expected_error: JsonError = CommitmentError::NoSignature.into();
235-
assert_eq!(response.error.unwrap().code, expected_error.code);
234+
let expected_error: JsonRpcError = CommitmentError::NoSignature.into();
235+
assert_eq!(response.into_error().unwrap().code(), expected_error.code);
236236
}
237237

238238
#[tokio::test]
@@ -276,10 +276,10 @@ mod test {
276276
.await
277277
.unwrap();
278278

279-
let json = response.json::<JsonResponse>().await.unwrap();
279+
let json = response.json::<JsonRpcResponse>().await.unwrap();
280280

281281
// Assert unauthorized because of missing signature
282-
assert!(json.error.is_none());
282+
assert!(json.into_success().is_some());
283283

284284
let _ = tx.send(());
285285
});
@@ -320,11 +320,12 @@ mod test {
320320
.send()
321321
.await
322322
.unwrap()
323-
.json::<JsonResponse>()
323+
.json::<JsonRpcResponse>()
324324
.await
325325
.unwrap();
326326

327-
let metadata: MetadataResponse = serde_json::from_value(response.result).unwrap();
327+
let metadata: MetadataResponse =
328+
serde_json::from_value(response.into_success().unwrap().result).unwrap();
328329

329330
assert_eq!(
330331
metadata.limits.max_committed_gas_per_slot,

bolt-sidecar/src/api/commitments/spec.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use thiserror::Error;
1111
use crate::{
1212
primitives::{
1313
commitment::InclusionCommitment,
14-
jsonrpc::{JsonError, JsonResponse},
14+
jsonrpc::{JsonRpcError, JsonRpcErrorResponse},
1515
signature::SignatureError,
1616
InclusionRequest,
1717
},
@@ -72,7 +72,7 @@ pub enum CommitmentError {
7272
RejectedJson(#[from] JsonRejection),
7373
}
7474

75-
impl From<CommitmentError> for JsonError {
75+
impl From<CommitmentError> for JsonRpcError {
7676
fn from(err: CommitmentError) -> Self {
7777
// Reference: https://www.jsonrpc.org/specification#error_object
7878
// TODO: the custom defined ones should be clearly documented.
@@ -117,7 +117,8 @@ impl From<&CommitmentError> for StatusCode {
117117
impl IntoResponse for CommitmentError {
118118
fn into_response(self) -> Response<Body> {
119119
let status_code = StatusCode::from(&self);
120-
let json = Json(JsonResponse::from_error(self.into()));
120+
let err = JsonRpcError::from(self);
121+
let json = Json(JsonRpcErrorResponse::new(err));
121122

122123
(status_code, json).into_response()
123124
}

0 commit comments

Comments
 (0)