From 6743384848a1c70225b9187c26d83ed47d7ee04e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Far=C3=ADas=20Santana?= Date: Thu, 2 May 2024 12:08:35 +0200 Subject: [PATCH] refactor: Error instead of breaking --- hook-worker/src/error.rs | 2 ++ hook-worker/src/util.rs | 17 +++++++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/hook-worker/src/error.rs b/hook-worker/src/error.rs index 1d3da8d..48468bc 100644 --- a/hook-worker/src/error.rs +++ b/hook-worker/src/error.rs @@ -47,6 +47,8 @@ pub enum WebhookResponseError { ParseUTF8StringError(#[from] std::str::Utf8Error), #[error("error while iterating over response body chunks")] StreamIterationError(#[from] reqwest::Error), + #[error("attempted to slice a chunk of length {0} with an out of bounds index of {1}")] + ChunkOutOfBoundsError(usize, usize), } /// Implement display of `WebhookRequestError` by appending to the underlying `reqwest::Error` diff --git a/hook-worker/src/util.rs b/hook-worker/src/util.rs index b1ce2af..31fb087 100644 --- a/hook-worker/src/util.rs +++ b/hook-worker/src/util.rs @@ -17,13 +17,18 @@ pub async fn first_n_bytes_of_response( let chunk = chunk?; let chunk_str = std::str::from_utf8(&chunk)?; - if let Some(partial_chunk_str) = - chunk_str.get(0..std::cmp::min(n - buffer.len(), chunk_str.len())) - { - buffer.push_str(&partial_chunk_str); + let upper_bound = std::cmp::min(n - buffer.len(), chunk_str.len()); + + if let Some(partial_chunk_str) = chunk_str.get(0..upper_bound) { + buffer.push_str(partial_chunk_str); } else { - // For whatever reason, we are out of bounds, give up. - break; + // For whatever reason we are out of bounds. We should never land here + // given the `std::cmp::min` usage, but I am being extra careful by not + // using a slice index that would panic instead. + return Err(WebhookResponseError::ChunkOutOfBoundsError( + chunk_str.len(), + upper_bound, + )); } }