Implement an Elixir Agent to maintain state, then refactor it to a GenServer to add a…
- User
Implement an Elixir
Agentto maintain state, then refactor it to aGenServerto add a custom terminate callback. Assistant
Implement an Elixir Agent to maintain state, then refactor it to a GenServer to add a custom terminate callback.
The user wants an example of state management in Elixir, starting with Agent and then moving to GenServer.
The specific requirement is to add a custom terminate callback in the GenServer version, which isn't easily available in Agent (though Agents are GenServers under the hood, you don't typically override terminate/2 in the Agent module itself).
Part 1: The Agent Implementation
start_link/1: Initialize state.push/2: Update state.pop/1: Get and update state.get/1: View state.Part 2: The GenServer Refactor
GenServer behavior.terminate/2 callback.init/1 corresponds to Agent.start_link.handle_call/3 or handle_cast/2 corresponds to Agent.update or Agent.get_and_update.
cast for fire-and-forget, or call if we want confirmation. Let's use cast for push to show async capabilities, but usually, for consistency in simple examples, call is safer. Let's stick to handle_call for everything to keep it synchronous and simple, or maybe handle_cast for the push. Let's do handle_cast for push and handle_call for pop to show variety.terminate/2: This is the core requirement. It needs to print something or log something when the process dies.Comparison/Explanation:
GenServer provides lifecycle callbacks (init, terminate, handle_info), better control over synchronous vs asynchronous operations, and the ability to handle non-state related messages (like timeouts or external events).Drafting the Code:
Agent Example:
defmodule StackAgent do
use Agent
def start_link(initial_state) do
Agent.start_link(fn -> initial_state end, name: __MODULE__)
end
def push(item) do
Agent.update(__MODULE__, fn state -> [item | state] end)
end
def pop do
Agent.get_and_update(__MODULE__, fn [h|t] -> {h, t} end)
end
end
GenServer Example:
defmodule StackGenServer do
use GenServer
# Client API
def start_link(initial_state) do
GenServer.start_link(__MODULE__, initial_state, name: __MODULE__)
end
def push(item) do
GenServer.cast(__MODULE__, {:push, item})
end
def pop do
GenServer.call(__MODULE__, :pop)
end
# Server Callbacks
@impl true
def init(initial_state) do
{:ok, initial_state}
end
@impl true
def handle_cast({:push, item}, state) do
{:noreply, [item | state]}
end
@impl true
def handle_call(:pop, _from, [head | tail]) do
{:reply, head, tail}
end
@impl true
def terminate(reason, state) do
IO.puts("Terminating with reason: #{inspect(reason)}")
IO.puts("Final state was: #{inspect(state)}")
# Clean up resources here (e.g., close files, sockets)
end
end
Refining the "Terminate" requirement: The user specifically asked to add a custom terminate callback.
terminate get called? When stop is called, or when the supervisor kills it (except in some shutdown modes), or if the process crashes.GenServer.stop(StackGenServer)).Structuring the Response:
terminate/2 callback.Self-Correction/Detail Check:
get_and_update is the most idiomatic way to implement pop.push be cast or call? If I want to ensure the state is saved before a crash, call is better. However, cast is often used for "inserts" in simple examples. I'll stick to cast for push (fire-and-forget) to distinguish it from call for pop (need result), as it demonstrates the richer API design of GenServer.terminate isn't guaranteed to run if the process is brutally killed (exit :kill), but it runs on normal shutdowns.Let's write out the solution clearly.
Plan:
StackAgent module.StackServer (GenServer) module.init, handle_cast, handle_call).terminate.Let's use a "Key-Value Store" or "Stack"? Stack is simpler code. Let's use a Stack (List).
start_link/1push/2pop/1start_link/1push/2 (cast)pop/1 (call)terminate/2That looks solid. I will add comments explaining the specific translation (e.g., "Agent.update" becomes "handle_cast").
Final check on the prompt: "add a custom terminate callback".
I need to make sure the code explicitly shows the terminate function handling specific logic (like logging the final state).
Let's generate the response.
Here is the implementation progression from a simple Agent to a robust GenServer with lifecycle management.
Agents are great for holding state when you don't need complex logic or lifecycle callbacks (like terminate). They are abstractions around a simple state container.
stack_agent.ex
defmodule StackAgent do
use Agent
def start_link(initial_state) do
# Start the agent holding the initial list
Agent.start_link(fn -> initial_state end, name: __MODULE__)
end
def push(item) do
# Update the state by prepending the item
Agent.update(__MODULE__, fn state -> [item | state] end)
end
def pop do
# Get and update: return the head, keep the tail as new state
Agent.get_and_update(__MODULE__, fn [head | tail] -> {head, tail} end)
end
def get_state do
Agent.get(__MODULE__, & &1)
end
end
We refactor to a GenServer to gain access to the terminate/2 callback. This allows us to execute cleanup logic (like closing connections or logging final state) exactly when the process is about to die.
stack_server.ex
defmodule StackServer do
use GenServer
# --- Client API ---
def start_link(initial_state) do
# Pass the initial state to init/1
GenServer.start_link(__MODULE__, initial_state, name: __MODULE__)
end
def push(item) do
# Cast is asynchronous (fire and forget)
GenServer.cast(__MODULE__, {:push, item})
end
def pop do
# Call is synchronous (waits for a reply)
GenServer.call(__MODULE__, :pop)
end
def get_state do
GenServer.call(__MODULE__, :get_state)
end
# --- Server Callbacks ---
@impl true
def init(initial_state) do
# Initialize the state
{:ok, initial_state}
end
@impl true
def handle_cast({:push, item}, state) do
# Handle async push
{:noreply, [item | state]}
end
@impl true
def handle_call(:pop, _from, [head | tail]) do
# Handle sync pop: reply with `head`, set new state to `tail`
{:reply, head, tail}
end
@impl true
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
# --- Custom Terminate Callback ---
@impl true
def terminate(reason, state) do
# This runs when the process is about to exit.
# Reasons can be :normal, :shutdown, or {:error, ...}
IO.puts("\n[StackServer] Terminating...")
IO.puts("Reason: #{inspect(reason)}")
IO.puts("Final State: #{inspect(state)}")
# Perform cleanup here (e.g., save to disk, close socket)
:ok
end
end
You can copy the code into an Elixir file (e.g., demo.exs) or an iex session to see the difference. Here is a script to test the GenServer and verify that the terminate callback works.
demo.exs
# 1. Start the GenServer with an empty list
{:ok, _pid} = StackServer.start_link([])
# 2. Push some items
IO.puts("Pushing :a and :b...")
StackServer.push(:a)
StackServer.push(:b)
# 3. Check state
IO.puts("Current State: #{inspect(StackServer.get_state())}")
# 4. Pop an item
item = StackServer.pop()
IO.puts("Popped: #{item}")
# 5. Trigger the Terminate callback
# We stop the server manually to simulate a shutdown.
IO.puts("\nStopping server manually...")
GenServer.stop(StackServer, :normal)
Expected Output:
Pushing :a and :b...
Current State: [:b, :a]
Popped: b
Stopping server manually...
[StackServer] Terminating...
Reason: :normal
Final State: [:a]
init for setup or terminate for cleanup) or when you need to handle both synchronous (call) and asynchronous (cast) requests differently.