Skip to content

Commit e8897db

Browse files
committed
refactor: apply auth in first reques of batch
- update the `batch_call` method to only add the `authorization` token in the first `Request` of the batch. As mentioned by the PR author, the batch calls are flushed together, therefore we can have this optimization here, although the library does not use JSON-RPC batch arrays.
1 parent 20f4564 commit e8897db

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

src/raw_client.rs

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -909,20 +909,30 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
909909

910910
// Add our listener to the map before we send the request
911911

912-
for (method, params) in batch.iter() {
913-
// if there's an `auth_provider` available, it should get the `authorization`, if any.
914-
// it'll be set into into `Request`.
915-
let authorization = self
916-
.auth_provider
917-
.as_ref()
918-
.and_then(|auth_provider| auth_provider());
919-
920-
let req = Request::new_id(
912+
for (idx, (method, params)) in batch.iter().enumerate() {
913+
let mut req = Request::new_id(
921914
self.last_id.fetch_add(1, Ordering::SeqCst),
922915
method,
923916
params.to_vec(),
924-
)
925-
.with_auth(authorization);
917+
);
918+
919+
// Although the library DOES NOT use JSON-RPC batch arrays,
920+
// It applies the `authorization` ONLY in the first `Request` of the `Batch`.
921+
//
922+
// JWT tokens can be 1KB+, therefore duplicating it across multiple requests adds significant overhead.
923+
// It assumes the server authenticates the `Batch` by the first `Request`. If a server implementation treats
924+
// each newline-delimited request independently, subsequently `Request`'s would be unauthenticated.
925+
//
926+
// It's a known trade-off, not a bug.
927+
if idx == 0 {
928+
// it should get the `authorization`, if there's an `auth_provider` available.
929+
let authorization = self
930+
.auth_provider
931+
.as_ref()
932+
.and_then(|auth_provider| auth_provider());
933+
934+
req = req.with_auth(authorization);
935+
}
926936

927937
// Add distinct channel to each request so when we remove our request id (and sender) from the waiting_map
928938
// we can be sure that the response gets sent to the correct channel in self.recv

0 commit comments

Comments
 (0)