Skip to content
Snippets Groups Projects

Resolve "Vérification de l’existence dans la piscine/sandbox/mempool"

4 files
+ 89
12
Compare changes
  • Side-by-side
  • Inline

Files

+ 42
0
defmodule Doc.Mempool do
@moduledoc """
Module for the mempool, i.e. documents that are yet to be added to a block
Used this [pattern](https://elixirforum.com/t/ets-or-genserver-for-caching-messages/42065) :
- GenServer owning an ETS table
- GenServer handling write access
- direct ETS calls for read access and concurency
"""
use GenServer
def init(_init_arg) do
:ets.new(:mempool, [:set, :protected, :named_table])
{:ok, 0}
end
def start_link(_initial_value) do
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
@doc """
Check whether a document is already in the mempool or not
"""
def can_add?(document) do
case :ets.match(:mempool, {:"$1", document}) do
[] -> true
_ -> false
end
end
@doc """
Add a document in the mempool
"""
def add(document) do
GenServer.call(__MODULE__, {:add, document})
end
def handle_call({:add, document}, _from, state) do
:ets.insert(:mempool, {state + 1, document})
{:reply, :ok, state + 1}
end
end
Loading