Write an Elixir function that uses Task.async_stream to perform parallel HTTP requests…
- User
Write an Elixir function that uses
Task.async_streamto perform parallel HTTP requests with a controlled concurrency limit. Assistant
Write an Elixir function that uses Task.async_stream to perform parallel HTTP requests with a controlled concurrency limit.
1. Analyze the Request:
* Goal: Write an Elixir function.
* Core Mechanism: Task.async_stream.
* Purpose: Perform parallel HTTP requests.
* Constraint: Controlled concurrency limit (meaning we shouldn't just fire all requests at once, but limit how many are in flight at any given time).
Understand Task.async_stream:
Task.async_stream(enumerable, fun, options).enumerable: A list of things to process (in this case, URLs).fun: The function to run for each item (the HTTP request).:max_concurrency - Sets the maximum number of tasks to be running at the same time. This is exactly what the user asked for.:timeout - How long to wait for a task to finish.:on_timeout - What to do if a task times out (:exit or :kill_task).Choose an HTTP Client:
Req, but usually people use external libs).HTTPoison, Tesla, Req.HTTPoison because it's very common and explicit. I should probably mention that a dependency is needed, or use :hackney directly, or use Req if I want to be modern. Let's stick to HTTPoison for clarity, but maybe provide a version using :httpc (Erlang built-in) so the code runs without dependencies?HTTPoison as the primary example because it's the standard "Elixir way", but add a note about dependencies. Actually, Req is becoming standard. Let's use HTTPoison for the classic example, but abstract the HTTP call so it's clear.Drafting the Code:
Input: A list of URLs.
Function Definition: def fetch_urls(urls, limit \\ 5).
Logic:
urls
|> Task.async_stream(fn url -> fetch_url(url) end, max_concurrency: limit)
|> Enum.map(fn {:ok, result} -> result end) # Handle results
Handling Errors/Timeouts:
Task.async_stream wraps the result in {:ok, result} or {:exit, reason}.fetch_url function.Refining the Code Structure:
defmodule ParallelHttp do
# Use HTTPoison for the example
def fetch_all(urls, concurrency_limit \\ 10) do
urls
|> Task.async_stream(&fetch_url/1, max_concurrency: concurrency_limit, timeout: 30_000)
|> Enum.map(&handle_result/1)
end
defp fetch_url(url) do
# Simulate HTTP request
HTTPoison.get!(url) # Or handle errors inside here
end
defp handle_result({:ok, response}), do: response
defp handle_result({:exit, reason}), do: {:error, reason}
end
Addressing the "No External Dependency" Approach (Optional but helpful):
HTTPoison requires {:httpoison, "~> 2.0"} in mix.exs.Putting it together with Explanations:
max_concurrency option.:ok vs :exit).mix.exs).Self-Correction/Review during drafting:
HTTPoison.get! fails, it raises an exception. Task.async_stream catches linked process crashes (exceptions) and returns {:exit, reason}. This is good behavior.ordered: false might speed things up if order doesn't matter, but default is true. I'll keep it simple.& capture syntax for brevity.Final Code Construction:
defmodule ParallelFetcher do
require Logger
def fetch_urls(urls, max_concurrency \\ 5) do
# We use Task.async_stream with the :max_concurrency option
urls
|> Task.async_stream(
fn url -> make_request(url) end,
max_concurrency: max_concurrency,
timeout: 10_000, # Kill task after 10s
on_timeout: :kill_task # Kill the task process if it times out
)
|> Enum.map(&extract_result/1)
end
defp make_request(url) do
# In a real app, you would use HTTPoison, Req, or Finch.
# Here is an example using HTTPoison:
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, body}
{:ok, %HTTPoison.Response{status_code: status}} ->
{:error, "Status #{status}"}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason}
end
end
defp extract_result({:ok, result}), do: result
defp extract_result({:exit, :timeout}), do: {:error, :timeout}
defp extract_result({:exit, reason}), do: {:error, reason}
end
Final Polish:
mix.exs.Output Generation: (This matches the provided good response). Here is an example of an Elixir module that performs parallel HTTP requests with a controlled concurrency limit.
We will use Task.async_stream with the :max_concurrency option. This allows you to process a large list of URLs without overwhelming your system or the target server.
To run this code, you need a standard Elixir installation. While the example uses the built-in :httpc client (so you don't need to install external dependencies), the logic applies exactly the same if you swap it for popular libraries like HTTPoison, Req, or Tesla.
defmodule ParallelHttp do
@doc """
Fetches a list of URLs in parallel with a controlled concurrency limit.
## Parameters
- urls: List of strings (URLs).
- max_concurrency: Integer (max number of simultaneous requests).
## Returns
A list of results in the same order as the input URLs.
"""
def fetch_all(urls, max_concurrency \\ 5) do
# We set up the HTTP client (inets) required for :httpc
Application.ensure_all_started(:inets)
urls
# Task.async_stream handles the parallel execution
|> Task.async_stream(
&fetch_url/1, # The function to run
max_concurrency: max_concurrency, # The limit (e.g., 5 at a time)
timeout: 10_000, # Kill task if it takes > 10 seconds
on_timeout: :kill_task # Ensure the process dies on timeout
)
# Process the stream results
|> Enum.map(&handle_result/1)
end
# The function executed inside the separate task/process
defp fetch_url(url) do
# Using Erlang's built-in :httpc for zero dependencies.
# Note: :httpc returns a tuple like {:ok, {{...}, body}} or {:error, reason}
case :httpc.request(:get, {String.to_charlist(url), []}, [], body_format: :binary) do
{:ok, {{_http_version, 200, _reason_phrase}, _headers, body}} ->
{:success, body}
{:ok, {{_http_version, status_code, _reason}, _headers, _body}} ->
{:http_error, status_code}
{:error, reason} ->
{:network_error, reason}
end
end
# Helper to unwrap the result from Task.async_stream
# Task.async_stream wraps results in {:ok, result} or {:exit, reason}
defp handle_result({:ok, result}), do: result
defp handle_result({:exit, :timeout}), do: {:error, :task_timeout}
defp handle_result({:exit, reason}), do: {:error, reason}
end
Task.async_stream/3: This is the core of the solution. It takes a collection (our list of URLs) and a function to run on each item.
:max_concurrency: This option limits how many tasks run simultaneously.
5, it will process the first 5, and as soon as one finishes, it will pick up the next one from the list. This prevents memory spikes and port exhaustion.Task.await_many or manual spawning, async_stream preserves the order of the input list. The resulting list matches the order of the URLs you provided.async_stream wraps the return value of your function in an {:ok, ...} tuple. If the task crashes or times out, it returns {:exit, ...}. The handle_result/1 function safely unwraps these.You can copy the code above into an iex shell or a file named parallel_http.ex and run it:
# Define some URLs (using a site designed for testing or placeholder JSON APIs)
urls = [
"https://jsonplaceholder.typicode.com/todos/1",
"https://jsonplaceholder.typicode.com/todos/2",
"https://jsonplaceholder.typicode.com/todos/3"
]
# Run with a concurrency limit of 2
results = ParallelHttp.fetch_all(urls, 2)
# Inspect results
Enum.each(results, fn
{:success, body} -> IO.puts("Fetched #{String.slice(body, 0..20)}...")
{:error, reason} -> IO.inspect(reason, label: "Failed")
end)