Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding ttl and delete api #37

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: adding ttl and delete api
  • Loading branch information
Sola-Aremu 'Pelumi committed Oct 26, 2024
commit 21f63e154a56f54ded8ca8dbfb82153ae931509e
36 changes: 33 additions & 3 deletions lib/groot/storage.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,19 @@ defmodule Groot.Storage do
end

# The main api for setting a keys value
def set(key, value) do
GenServer.call(__MODULE__, {:set, key, value})
def set(key, value, expires_in \\ nil) do
GenServer.call(__MODULE__, {:set, key, value, expires_in})
end

# The main api for deleting a key
def delete(key) do
case :ets.lookup(__MODULE__, key) do
[] ->
:ok

[{^key, _value}] ->
GenServer.call(__MODULE__, {:delete, key})
end
end

# Deletes all keys in the currently connected cluster. This is only
Expand All @@ -44,13 +55,26 @@ defmodule Groot.Storage do
{:ok, %{table: tab, registers: registers}}
end

def handle_call({:set, key, value}, _from, data) do
def handle_call({:set, key, value, expires_in}, _from, data) do
registers = Map.update(data.registers, key, Register.new(key, value), fn reg ->
Register.update(reg, value)
end)
:ets.insert(data.table, {key, registers[key].value})
GenServer.abcast(__MODULE__, {:update_register, registers[key]})

case expires_in == nil do
true -> :ok
false -> Process.send_after(self(), {:delete, key}, expires_in)
end

{:reply, :ok, %{data | registers: registers}}
end

def handle_call({:delete, key}, _from, data) do
registers = Map.delete(data.registers, key)
:ets.delete(data.table, key)
GenServer.abcast(__MODULE__, {:propagate_delete, registers[key]})

{:reply, :ok, %{data | registers: registers}}
end

Expand Down Expand Up @@ -79,6 +103,12 @@ defmodule Groot.Storage do
{:noreply, %{data | registers: new_registers}}
end

def handle_cast({:propagate_delete, reg}, data) do
registers = Map.delete(data.registers, reg.key)
:ets.delete(data.table, reg.key)
{:noreply, %{data | registers: registers}}
end

def handle_info(msg, data) do
case msg do
{:nodeup, node} ->
Expand Down