Skip to content
This repository has been archived by the owner on Jun 21, 2024. It is now read-only.

Commit

Permalink
refactor: Error instead of breaking
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasfarias committed May 2, 2024
1 parent cc05f55 commit 6743384
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
2 changes: 2 additions & 0 deletions hook-worker/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
17 changes: 11 additions & 6 deletions hook-worker/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
));
}
}

Expand Down

0 comments on commit 6743384

Please sign in to comment.