DidactMacros

DidactMacros

Servers Exiting vs Terminating in Programming Elixir Book

I have a question regarding server termination vs server exit.

I would appreciate that this question be considered in light of the below code and excerpt.

defmodule Duper.Worker do
    use GenServer, restart: :transient

    def start_link(_) do
        GenServer.start_link(__MODULE__, :no_args)
    end

    def init(:no_args) do
        Process.send_after(self(), :do_one_file, 0)
        { :ok, nil }
    end

    def handle_info(:do_one_file, _) do
        Duper.PathFinder.next_path()
        |> add_result()
    end

    defp add_result(nil) do
        Duper.Gatherer.done()
        {:stop, :normal, nil}
    end

    defp add_result(path) do
        Duper.Gatherer.result(path, hash_of_file_at(path))
        send(self(), :do_one_file)
        { :noreply, nil }
    end

    defp hash_of_file_at(path) do
        File.stream!(path, [], 1024*1024)
        |> Enum.reduce(
        :crypto.hash_init(:md5),
        fn (block, hash) ->
            :crypto.hash_update(hash, block)
        end)
        |> :crypto.hash_final()
    end

end

Why Can’t We Just Write a Looping Function?

We can implement a loop in Elixir using a recursive function call.
But the worker server doesn’t do this. Instead, it sends itself a
message and then exits after processing each file.

The reason is that the Elixir runtime won’t let any one invocation of
a server hog the CPU forever. Instead it sets a timeout on each call
or cast into a GenServer (by default 5 seconds). If the call or cast
handler has not returned in that time, the runtime assumes
something has gone wrong and terminates the server.
Processing a million files in a loop will take more than 5 seconds.
So we instead just process one file per entry into the server, and then
queue up another message to process the next on a fresh entry. The
result: no timeouts.

My question is regarding the bolded and italicised statement. My understanding was that a Gen server exited by returning :stop, :terminate, or calling System.halt(num), however the explanation suggests that the server exits implicitly, so I wonder if exiting and terminating are different.

Also just prior to when server is said to exit, it sends itself the :do_one_file atom, but the init of the server already does this, so the server can not be terminating and reinitialising since the sending of such a message when would not be necessary at termination as it also takes place at initialisation.

There definitely seems to be a difference between exiting and termianting, I would appreciate some clarity on the difference(s).

Marked As Solved

al2o3cr

al2o3cr

The use of “exits” here is confusing - I believe the author means “returns” (as in “returns to the GenServer loop that called handle_whatever”) because as you’ve noted “exit” has a very specific meaning.

The “or cast” of this sentence is flatly wrong; a cast can’t timeout - you can even cast to processes that aren’t alive without getting an error.

I’m also unsure what this has to do with anything, since the posted code doesn’t define a handle_call. There’s a different timeout from the supervisor inside start_link - IIRC it will eventually fail if init takes too long to return - but that’s not really the same thing.

Also Liked

lud

lud

Instead, it sends itself a message and then exits after processing each file.

The description is wrong. That server does not exit after processing each file, but only when Duper.PathFinder.next_path() returns nil, I assume when there is no more file.

By returning a stop tuple, the implementation tells GenServer to terminate the current server, which will in the end either call exit/1 or just stop looping forever awaiting messages (I don’t remember how it is done in gen_server). (spawn(fn -> :ok end) and spawn(fn -> :ok; exit(:normal) end) are equivalent.)

but the init of the server already does this, so the server can not be terminating and reinitialising since the sending of such a message when not be necessary at termination when it is also takes place at initialisation.

Rember that if the server restarts, it is a new process, so sending to self will not forward the messages to the new instance.

lud

lud

Where does that material comes from? It seems that the author does not fully understand the very basics of generic servers. Which is quite surprising if the book is “Programming Elixir” by Dave Thomas. Is it some other book?

In your case, send or send_after makes no difference. The generic server init callback is called, and once it is finished the gen_server module will start to pull messages from the process mailbox and dispatch them to handle_info (or handle_call/handle_cast).

During the execution of init, the process can receive many messages from other processes, if those processes know the pid of your process (likely not, your process would have to tell them first in init) or use the registered name of your process. When calling send(self(), message) during init, you just add the message to the mailbox of the process, but that message will only be read after init is complete. So using send_after is slightly different but achieves the same thing.

(Note that a Task would be more appropriate with the current set of features of your code, as the server does not actually handle other types of messages that could be interleaved with the processing of files).

I imagine it would be the same, since the only delaying factor is readiness to receive the message.

So yes, the readiness is just “when init is done, and returned {:ok, ...

I guess send_after must mean send to be received after the block (or process?), there seems be be more internally going on than the explanation elucidates, for me at least.

If you’d use send_after with 5000 for instance, that gives time to other processes to send you messages. But once the loop would be started, as add_result uses send, it would have the same behaviour. Only the start of the loop would be delayed by five seconds.

lud

lud

As I have said:

So the send_after allows for the initialisation (invocation?) to complete

Not really. If in init you call a function that does a loop over files, your init function would not complete until that is done too. But it will complete when there are no more files. As said by @al2o3cr , “it will eventually fail if init takes too long to return - but that’s not really the same thing”.

If the call or cast handler has not returned in that time, the runtime assumes something has gone wrong and terminates the server. Processing a million files in a loop will take more than 5 seconds. So we instead just process one file per entry into the server, and then queue up another message to process the next on a fresh entry. The result: no timeouts.

The timeout in question here is the default timeout of 5 seconds of GenServer.call. The problem with this example is that is does not demonstrate how a call would timeout, because there is no GenServer.call involved.

Where Next?

Popular in Questions Top

jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
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
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New

We're in Beta

About us Mission Statement