spurgus
Hi!
I have a Downloader module that GETs files given a URL, using Req. It has a timeout option but I would like to abort the download when it exceeds a given maximum size, so I don’t have to wait until the file has been completely downloaded to check the final size.
I think that can be done using Req’s streaming capabilities but I’m not being able to get it working. Can anyone help with this? This is my module so far:
defmodule Utils.Downloader do
require Logger
@default_receive_timeout_ms 20_000
def download(url, opts \\ []) do
Logger.debug("[#{__MODULE__}] downloading...")
with {:ok, req_client} <- prepare_req_client(opts),
{:ok, %Req.Response{status: 200, body: body, headers: headers}} <-
Req.get(req_client, url: url),
{:ok, content_type} <- get_content_type(headers) do
Logger.debug("[#{__MODULE__}] finished downloading...")
{:ok, %{content_type: content_type, data: body}}
else
{:error, :cant_get_content_type} ->
{:error, :cant_get_content_type}
%Req.Response{status: status} when status != 200 ->
{:erorr, :cant_download_image}
end
end
defp get_content_type(headers) do
headers
|> Enum.find(fn {key, _} -> String.downcase(key) == "content-type" end)
|> case do
{_, value} when is_list(value) -> {:ok, hd(value)}
{_, value} when is_binary(value) -> {:ok, value}
nil -> {:error, :cant_get_content_type}
end
end
defp prepare_req_client(opts \\ []) do
receive_timeout_ms = opts[:receive_timeout_ms] || @default_receive_timeout_ms
client = Req.new(receive_timeout: receive_timeout_ms)
{:ok, client}
end
end
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #phoenix_html
- #iex
- #elixirconf-us
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
jswanner
Welcome to the forum @spurgus!
If the response includes the
content-lengthheader then you can check that from a response step:Otherwise, you’ll have to keep track of received bytes and halt the request. You mentioned streaming but didn’t say which form of streaming (
into: :self,into: &fun/2,into: collectable). Here’s an example for the function form of streaming:spurgus
Thanks a lot for your help @jswanner !
Most of the times the content-length header will be present but I think that checking for the actual size while downloading is a good measure just in case it’s missing or wrong.
This is what I’m trying, but I get an empty body in the response??
jswanner
Try:
I believe this
into: &fun/2option is envisioned for scenarios where you’ll be doing something with the data as it’s coming in (such as sending it to another process), rather than accumulating it and processing it at the end.spurgus
I see, thanks @jswanner - this is more complicated than I thought in the beginning, maybe I’ll just rely on the content-length header and timeouts to protect against downloading huge files.
jswanner
I was not meaning to imply this use of
into: &fun/2is wrong, just pointing out Req doesn’t accumulate the body for you with this option (maybe it should?).garrison
Using
:intolike this is the correct approach. The example in the docs doesn’t accumulate the body (it just writes it to the console). Frankly this is not a very helpful example and should be updated.You absolutely should not rely on
content-length. There have been serious security problems caused by people mistakenly trusting that header. The server can lie about it at will, maliciously. A timeout is also not a good approach as there is no guarantee you’re not downloading a large file very quickly!spurgus
Yes, that’s my concern, someone trying to take your server down, making you download huge files, so my idea was to use streaming to abort the download as soon as the max size has been detected.
Let’s see if I can get this to work…
BartOtten
Never trust headers unless you’ve validated them.
Once I had an Elixir bot running in a hostile environment (Kodi addon ecosystem) . I am quite sure it would not have survived the first week if I trusted the headers. Content-lengths spoofing (read: simply returning an everlasting stream of random bits) was one of the first concerns.
jswanner
Oops, I just realized my suggestion had a bug that doesn’t include the first chunk of data in the calculated length, should be:
spurgus
Thanks all, I agree that the content-length header is not to be trusted, but then what’s the way to return the whole downloaded file once it has finished downloading (and abort if size exceeds during the streaming phase)?