mmmmillar
Problem:
As a first go at using GenStage, I’m building a simple task queue. Initially it used consumers that I would add explicitly in my Application supervisor. I’ve since updated it to use a ConsumerSupervisor to add/remove Consumers as required.
The issue I’m having is that every task added to the producer gets picked up by the ProducerConsumer and passed on, but about half of them seem to disappear into thin air (ie I only see the output of IO.inspect("#{job_id} is starting") for about half of them)!
Does anyone know why this is happening or how I can debug this further?
Thanks
Code
producer.ex
defmodule Q.Producer do
use GenStage
require Logger
def start_link(_init_args) do
GenStage.start_link(__MODULE__, {:queue.new(), 0}, name: __MODULE__)
end
@impl true
def init(initial) do
{:producer, initial}
end
@impl true
def handle_demand(demand, {backlog, existing_demand}) do
# IO.inspect("Received demand: #{demand}, existing_demand: #{existing_demand}")
case :queue.len(backlog) do
0 ->
{:noreply, [], {backlog, existing_demand + demand}}
n ->
n = min(demand, n)
{items, backlog} = :queue.split(n, backlog)
:queue.len(backlog) |> Q.Stats.set_waiting()
{:noreply, :queue.to_list(items), {backlog, existing_demand + demand - n}}
end
end
@impl true
def handle_cast({:enqueue, item}, {backlog, 0}) do
{:noreply, [], {:queue.in(item, backlog), 0}}
end
@impl true
def handle_cast({:enqueue, item}, {backlog, existing_demand}) do
IO.inspect("Received item: existing_demand: #{existing_demand}")
backlog = :queue.in(item, backlog)
{{:value, item}, backlog} = :queue.out(backlog)
{:noreply, [item], {backlog, existing_demand - 1}}
end
def enqueue(item), do: GenStage.cast(__MODULE__, {:enqueue, item})
end
producer_consumer.ex
defmodule Q.ProducerConsumer do
use GenStage
def start_link(_init_args) do
GenStage.start_link(__MODULE__, :ok, name: __MODULE__)
end
def init(initial) do
{:producer_consumer, initial, subscribe_to: [{Q.Producer, max_demand: 1}]}
end
def handle_events(events, _from, state) do
# producer "middleware" - do things like filter before passing on to consumer
IO.inspect("passing events to consumer: #{inspect(events)}")
{:noreply, events, state}
end
end
consumer_supervisor.ex
defmodule Q.ConsumerSupervisor do
use ConsumerSupervisor
def start_link(_args) do
{:ok, pid} = ConsumerSupervisor.start_link(__MODULE__, :ok, name: __MODULE__)
{:ok, pid}
end
def init(:ok) do
children = [
%{
id: Q.Consumer,
start: {Q.Consumer, :start_link, []},
restart: :transient
}
]
ConsumerSupervisor.init(children,
strategy: :one_for_one,
subscribe_to: [
{Q.ProducerConsumer, max_demand: 5}
]
)
end
end
consumer.ex
defmodule Q.Consumer do
alias Q.JobRecord
use GenStage
import Q.Constants
@max_job_duration max_job_duration()
def start_link(_init_args) do
GenStage.start_link(__MODULE__, :ok)
end
def init(initial) do
Process.flag(:trap_exit, true)
Q.Stats.increment_consumer_count()
{:consumer, initial, subscribe_to: [{Q.ProducerConsumer, max_demand: 1}]}
end
def handle_events(events, _from, state) do
Enum.each(events, fn job_id ->
task =
Task.async(fn ->
IO.inspect("#{job_id} is starting")
JobRecord.set_started(job_id)
run_job()
end)
case Task.yield(task, @max_job_duration) || Task.shutdown(task) do
{:ok, _result} ->
JobRecord.set_completed(job_id)
nil ->
JobRecord.retry_job(job_id)
end
end)
# As a consumer we never emit events
{:noreply, [], state}
end
def handle_info({:EXIT, _pid, reason}, state) do
Q.Stats.decrement_consumer_count()
{:stop, reason, state}
end
defp run_job do
Process.sleep(100)
end
end
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
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
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #hex
- #security










Showing Posts 1 to 1- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
mmmmillar
My problem was that I was still using GenStage for the “consumer” when in fact I just needed to start a task (as the consumer supervisor was now picking up the events)