Skip to content

Instantly share code, notes, and snippets.

View chiragtoor's full-sized avatar

Chirag Singh Toor chiragtoor

View GitHub Profile
# ...
def init(customer) do
Process.flag(:trap_exit, true)
# check for order_contents for the customer
order_contents = ExCluster.StateHandoff.pickup(customer)
{ :ok, { customer, order_contents } }
end
# ...
# ...
children = [
# **it's important that this is the first child in our tree
{ ExCluster.StateHandoff, [] },
{ Horde.Registry, [name: ExCluster.Registry, keys: :unique] },
{ Horde.Supervisor, [name: ExCluster.OrderSupervisor, strategy: :one_for_one ] },
%{
id: ExCluster.HordeConnector,
restart: :transient,
defmodule ExCluster.StateHandoff do
use GenServer
require Logger
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
def child_spec(opts \\ []) do
%{
# ...
def init(customer) do
Process.flag(:trap_exit, true)
# ...
end
# ...
# at the end of the module add a terminate callback
def terminate(_reason, { customer, order_contents }) do
# store our order_contents for this customer somwhere
# ...
defp via_tuple(customer) do
# Order GenServer needs to use Horde.Registry
{ :via, Horde.Registry, { ExCluster.Registry, customer } }
end
# ...
@chiragtoor
chiragtoor / order.ex
Created December 2, 2018 06:50
Add logging to Order GenServer
# ...
def init(customer) do
Logger.warn("Starting #{__MODULE__} for #{customer}")
{ :ok, [] }
end
# ...
@chiragtoor
chiragtoor / ex_cluster.ex
Last active December 2, 2018 02:00
Connect Nodes into a cluster
# ...
case System.get_env("NODES") do
nodes when is_binary(nodes) ->
nodes
|> String.split(",")
|> Enum.map(&String.to_atom/1)
|> Enum.each(&Node.connect/1)
_ ->
nil
end
@chiragtoor
chiragtoor / ex_cluster.ex
Last active December 6, 2018 00:13
Add Horde Registry and Supervisor
# ...
# take in list of nodes from the env
case System.get_env("NODES") do
nodes when is_binary(nodes) ->
nodes
# convert list of nodes into atoms of node names
|> String.split(",")
|> Enum.map(&String.to_atom/1)
# connect to all nodes to make a cluster
|> Enum.each(&Node.connect/1)
@chiragtoor
chiragtoor / order.ex
Last active December 6, 2018 00:10
Order GenServer using Registry and additions for adding to and getting contents from an order
defmodule ExCluster.Order do
use GenServer
require Logger
def child_spec(customer), do: %{ id: customer,
start: { __MODULE__, :start_link, [customer] } }
def start_link(customer) do
Logger.info("Starting Order for #{customer}")
# note the change here in providing a name: instead of [] as the 3rd param
@chiragtoor
chiragtoor / ex_cluster.ex
Created November 30, 2018 23:49
Add Registry to Supervision tree
# ...
children = [
{ Registry, keys: :unique, name: ExCluster.Registry },
{ DynamicSupervisor, name: ExCluster.OrderSupervisor, strategy: :one_for_one },
]
# ...