Skip to content

Commit

Permalink
Try to make HTTP fetching more resilient; verify content-length is co…
Browse files Browse the repository at this point in the history
…rrect and use .bytes() instead of .read_to_end()
  • Loading branch information
lilith committed Sep 29, 2022
1 parent e07c3f3 commit d638729
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions imageflow_http_helpers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ use hyper;
use reqwest::Certificate;
use ::imageflow_helpers::filesystem::read_file_bytes;
use std::path::PathBuf;
use std::io::Read;

#[derive(Debug)]
pub enum FetchError {
ReqwestError(reqwest::Error),
HyperError(hyper::Error),
IoError(std::io::Error),
UpstreamResponseError(reqwest::StatusCode),
ContentLengthMismatch,

UpstreamResponseErrorWithResponse{ status: reqwest::StatusCode, response: FetchedResponse},
}
Expand All @@ -31,6 +31,7 @@ impl fmt::Display for FetchError {
FetchError::UpstreamResponseErrorWithResponse {ref status, ..} => {
write!(f, "Response status {}", status)
},
FetchError::ContentLengthMismatch => write!(f, "Content-Length value did not match bytes recieved.")
}
}
}
Expand Down Expand Up @@ -110,28 +111,35 @@ pub fn fetch(url: &str, config: Option<FetchConfig>) -> std::result::Result<Fetc
let conf = config.unwrap_or_default();
let client = conf.build_client();

let mut res = client.get(url).send()?;
let res = client.get(url).send()?;
let status = res.status().to_owned();

let response = if status.is_success() || conf.read_error_body.unwrap_or(false) {

let response = if res.status().is_success() || conf.read_error_body.unwrap_or(false) {
let mut source_bytes = Vec::new();
let _ = res.read_to_end(&mut source_bytes)?;
let content_length = res.content_length();
let code = status;
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).expect("content type required").clone();
let bytes = res.bytes()?.to_vec();
if content_length.is_some() && content_length.unwrap() != bytes.len() as u64{
return Err(FetchError::ContentLengthMismatch);
}
Some(FetchedResponse {
code: res.status(),
bytes: source_bytes,
content_type: res.headers().get(reqwest::header::CONTENT_TYPE).expect("content type required").clone()
code: code,
content_type: content_type,
bytes: bytes,
})
} else {
None
};

if res.status().is_success() && response.is_some(){
if status.is_success() && response.is_some(){
Ok(response.unwrap())
}else {
match (response, res.status()) {
match (response, status) {
(Some(r),
_) =>
Err(FetchError::UpstreamResponseErrorWithResponse { status: res.status(), response: r }),
(None, _) => Err(FetchError::UpstreamResponseError(res.status()))
Err(FetchError::UpstreamResponseErrorWithResponse { status: status, response: r }),
(None, _) => Err(FetchError::UpstreamResponseError(status))
}
}
}
Expand Down

1 comment on commit d638729

@github-actions
Copy link

@github-actions github-actions bot commented on d638729 Sep 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

🔴 Please review

See the 📜action log for details.

Unrecognized words (1)

recieved

To accept ✔️ these unrecognized words as correct, run the following commands

... in a clone of the [email protected]:imazen/imageflow.git repository
on the main branch (ℹ️ how do I use this?):

update_files() {
perl -e '
my $new_expect_file=".github/actions/spell-check/expect/d638729a1e382d81be668c4d1932daef3ef0290e.txt";
use File::Path qw(make_path);
use File::Basename qw(dirname);
make_path (dirname($new_expect_file));
open FILE, q{<}, $new_expect_file; chomp(my @words = <FILE>); close FILE;
my @add=qw('"$patch_add"');
my %items; @items{@words} = @words x (1); @items{@add} = @add x (1);
@words = sort {lc($a)."-".$a cmp lc($b)."-".$b} keys %items;
open FILE, q{>}, $new_expect_file; for my $word (@words) { print FILE "$word\n" if $word =~ /\w/; };
close FILE;
system("git", "add", $new_expect_file);
'
}

comment_json=$(mktemp)
curl -L -s -S \
-H "Content-Type: application/json" \
"https://api.github.com/repos/imazen/imageflow/comments/85400958" > "$comment_json"
comment_body=$(mktemp)
jq -r ".body // empty" "$comment_json" | tr -d "\\r" > $comment_body
rm $comment_json

patch_add=$(perl -e '$/=undef; $_=<>; if (m{Unrecognized words[^<]*</summary>\n*```\n*([^<]*)```\n*</details>$}m) { print "$1" } elsif (m{Unrecognized words[^<]*\n\n((?:\w.*\n)+)\n}m) { print "$1" };' < "$comment_body")

update_files
rm $comment_body
git add -u
Available dictionaries could cover words not in the dictionary

This includes both expected items (946) from .github/actions/spell-check/expect/21a881426bac4ce7da7479525c41638edb10dab3.txt
.github/actions/spell-check/expect/4fd706fd879e80192d1ecef241faca522e84be19.txt
.github/actions/spell-check/expect/896fc69cfc51c47b00d3435ba1a0399e7bdf8187.txt
.github/actions/spell-check/expect/expect.txt and unrecognized words (1)

cspell:fullstack/fullstack.txt (181) covers 11 of them
cspell:aws/aws.txt (1485) covers 10 of them
cspell:rust/rust.txt (112) covers 9 of them
cspell:npm/npm.txt (671) covers 7 of them
cspell:java/java.txt (33524) covers 6 of them

Consider adding them using (in .github/workflows/spelling.yml):

      with:
        extra_dictionaries:
          cspell:fullstack/fullstack.txt
          cspell:aws/aws.txt
          cspell:rust/rust.txt
          cspell:npm/npm.txt
          cspell:java/java.txt

To stop checking additional dictionaries, add:

      with:
        check_extra_dictionaries: ''
✏️ Contributor please read this
  • You can probably just add items into .github/actions/spell-check/expect/expect.txt.
  • If you need to use a specific token in one place and it shouldn't generally be used, you can
    add an item in .github/actions/spell-check/patterns.txt.

Please sign in to comment.