quesurifn

quesurifn

How to store state in module?

So, I’m building an SMTP client that I’d like to be able to be called from different processes and have different state for each process. The SMTP client needs to track for example if the HELO command has been used or not. How do I handle state?

My current code is this:

defmodule Client do
  @moduledoc """
  Documentation for `Smtpclient`.
  """

  use Agent

  def start_link(_opts) do
    Agent.start_link(fn -> %{} end, name: __MODULE__)
  end


  def connect(pid, tld) do
      set_value(pid, "tld", tld)
      {:ok, records} = DNS.resolve(tld, :mx)
      Enum.sort_by(records, fn(r) -> elem(r, 0) end)
      sock = do_connect(records, 0)
      set_socket(pid, sock)
      set_value(pid, "hostname", tld)
      {:ok, sock}
  end

  @spec helo(any) :: any
  def helo(pid) do
      already_helloed = get_value(pid, "already_helloed")
      if already_helloed do # if already helloed return early
        {:error, "already helloed"}
      end
      sock = get_socket(pid)
      tld = get_value(pid, "tld")
      sock |> Socket.Stream.send!("HELO #{tld}")
      set_value(pid, "already_helloed", true)
      sock |> Socket.Stream.recv!
  end

  def noop(pid) do
    try do
      sock = get_socket(pid)
      sock |> Socket.Stream.send!("NOOP")
      sock |> Socket.Stream.recv!
    rescue
      Socker.Error -> {:error, :no_connection}
    end
  end

  def quit(sock) do
      try do
        sock |> Socket.Stream.send!("QUIT")
        sock |> Socket.Stream.recv!
        sock |> Socket.close!()
      rescue
        Socket.Error -> {:error, "something is wrong"}
      end
  end

  def rctp_to(pid, email) do
    try do
      sock = get_socket(pid)
      sock |> Socket.Stream.send!("RCPT_TO #{email}")
      sock |> Socket.Stream.recv!
    rescue
      Socker.Error -> {:error, "something is wrong"}
    end
  end

  defp set_socket(pid, sock) do
    Agent.update(pid, &Map.put(&1, "socket", sock))
  end

  defp get_socket(pid) do
    Agent.get(pid, &Map.get(&1, "socket"))
  end

  defp set_value(pid, key, value) do
    Agent.update(pid, &Map.put(&1, key, value))
  end

  defp get_value(pid, key) do
    Agent.get(pid, &Map.get(&1, key))
  end

  defp do_connect(hostnames, i) do
    try do
      host = elem(Enum.at(hostnames, i), 1)
      Socket.TCP.connect!(to_string(host), 25, packet: :line)
    rescue
        Socket.Error ->
          if Enum.at(hostnames, i) == nil do
            {:error, "all mx servers down"}
          end
          do_connect(hostnames, i + 1)
    end
  end
end

Most Liked

IloSophiep

IloSophiep

I think there are two “default” ways to handle state (and a lot more specific ones):

  • Store them in the client process
  • Store them in a dedicated process

Because Elixir is really good with processes people sometimes expect everything they code to do “process-y” stuff. But if you can, i think, it is recommended to start simple and do not introduce processes if you don’t need to. Your first sentence makes me think, that might work for you.

As an example: You have a module TodoList with a function add/1 that adds one item to the list. You might think “How / Where do i keep that list, so calling add/1 three times keeps all the old entries still there?” The easiest answer is "Just return the data to the caller and let them keep the state around! So instead of

defmodule TodoList do
  def add(item) do
    # Where does before come from?!
    [ item | before ]
    :ok
  end
end

you use

defmodule TodoList do
  def add(state, item) do
    # renamed "before" to "state", so the
    # concept hopefully becomes clearer
    [ item | state ]
  end
end

so the caller of your client keeps the state around and hands it to you for you to work on it.

Sebb

Sebb

I find :gen_statem very hard to understand. I prefer functional fsm with the state in map/struct and pattern matching in multiclauses as handlers. Also because fsm can become hard to test if they have side effects (like timeouts) I think its worth to think about how to make them as pure as possible.

Where Next?

Popular in Chat/Questions Top

wolfiton
Hi everyone, How can i retrieve the name from a structure like this? %{"id" => "1570", "name" => "Croque Monsieur"} My test loo...
New
Allyedge
Hey, I want to learn Elixir OTP and I wanted to know if there are any good resources that teach it. I found some web pages, but none of t...
New
Chawki
Hi,i’m new to elixir. i’m searching elixir small programs to try it out my self,Is any good resources out there? Thank you.
New
Santheepkumar
Hi all, I am a Fullstack JS developer for last 2 years. I need a good guide to learn elixer. Any suggestions please
New
Fl4m3Ph03n1x
GenStage and Flow resources? I have been hearing about GenStage and Flow, a tool built upon it, for quite some time. I understand it allo...
New
shansiddiqui94
Hello, I have an interview coming up and I seem to have forgotten important concepts of Elixir. So I was wondering if you guys know of a...
New
marciol
Hey, I have very restricted resources and time so I’m trying to understand the best way to learn Liveview in terms of cost/time. The Pra...
New
AstonJ
It finally feels like I’ve got some time to catch up on my reading - though I am sure lots of people will be wondering the same: what are...
New
Allyedge
So, I want to get an Elixir book, but don’t know which one to get. Both Programming Elixir 1.6 and Elixir in Action looks interesting, b...
New
venomnert
Background I have been a backend elixir developer for about 3 years now. I have been mainly working on simple CRUD applications. Context...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement