Initial Commit

This commit is contained in:
2024-12-24 17:45:52 +01:00
commit c30845575a
42 changed files with 870 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
# Used by "mix format"
[
inputs: ["mix.exs", "config/*.exs"],
subdirectories: ["apps/*"]
]

20
kv_umbrella/.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Temporary files, for example, from tests.
/tmp/

4
kv_umbrella/README.md Normal file
View File

@@ -0,0 +1,4 @@
# KvUmbrella
**TODO: Add description**

View File

@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

26
kv_umbrella/apps/kv/.gitignore vendored Normal file
View File

@@ -0,0 +1,26 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
kv-*.tar
# Temporary files, for example, from tests.
/tmp/

View File

@@ -0,0 +1,21 @@
# KV
**TODO: Add description**
## Installation
If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `kv` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[
{:kv, "~> 0.1.0"}
]
end
```
Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at <https://hexdocs.pm/kv>.

View File

@@ -0,0 +1,10 @@
defmodule KV do
use Application
@impl true
def start(_type, _args) do
# Anche se non usiamo KV.Supervisor name direttamente,
# e' comodo per debug
KV.Supervisor.start_link(name: KV.Supervisor)
end
end

View File

@@ -0,0 +1,33 @@
defmodule KV.Bucket do
use Agent, restart: :temporary
@doc """
Starts a new bucket.
"""
def start_link(_opts) do
Agent.start_link(fn -> %{} end)
end
@doc """
Gets a value from the `bucket` by `key`.
"""
def get(bucket, key) do
Agent.get(bucket, &Map.get(&1, key))
end
@doc """
Puts the `value` for the given `key` in the `bucket`.
"""
def put(bucket, key, value) do
Agent.update(bucket, &Map.put(&1, key, value))
end
@doc """
Deletes `key` from `bucket`.
Returns the current value of `key`, if `key` exists.
"""
def delete(bucket, key) do
Agent.get_and_update(bucket, &Map.pop(&1, key))
end
end

View File

@@ -0,0 +1,69 @@
defmodule KV.Registry do
use GenServer
# Client API
@doc """
Starts the registry.
"""
def start_link(opts) do
server = Keyword.fetch!(opts, :name)
GenServer.start_link(__MODULE__, server, opts)
end
@doc """
Looks up the bucket pid for `name` stored in `server`.
Returns `{:ok, pid}` if the bucket exists, `:error` otherwise.
"""
def lookup(server, name) do
case :ets.lookup(server, name) do
[{^name, pid}] -> {:ok, pid}
[] -> :error
end
end
@doc """
Ensures there is a bucket associated with the given `name` in `server`.
"""
def create(server, name) do
GenServer.call(server, {:create, name})
end
# Server Callbacks
@impl true
def init(table) do
# name -> bucket
names = :ets.new(table, [:named_table, read_concurrency: true])
refs = %{} # ref -> name
{:ok, {names, refs}}
end
@impl true
def handle_call({:create, name}, _from, {names, refs}) do
case lookup(names, name) do
{:ok, bucket} ->
{:reply, bucket, {names, refs}}
:error ->
{:ok, bucket} = DynamicSupervisor.start_child(KV.BucketSupervisor, KV.Bucket)
ref = Process.monitor(bucket)
refs = Map.put(refs, ref, name)
:ets.insert(names, {name, bucket})
{:reply, bucket, {names, refs}}
end
end
@impl true
def handle_info({:DOWN, ref, :process, _pid, _reason}, {names, refs}) do
{name, refs} = Map.pop(refs, ref)
:ets.delete(names, name)
{:noreply, {names, refs}}
end
@impl true
def handle_info(msg, state) do
require Logger
Logger.debug("Unexpected message in KV.Registry: #{inspect(msg)}")
{:noreply, state}
end
end

View File

@@ -0,0 +1,17 @@
defmodule KV.Supervisor do
use Supervisor
def start_link(opts) do
Supervisor.start_link(__MODULE__, :ok, opts)
end
@impl true
def init(:ok) do
children = [
{DynamicSupervisor, name: KV.BucketSupervisor, strategy: :one_for_one},
{KV.Registry, name: KV.Registry},
]
Supervisor.init(children, strategy: :one_for_all)
end
end

View File

@@ -0,0 +1,33 @@
defmodule KV.MixProject do
use Mix.Project
def project do
[
app: :kv,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.17",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {KV, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View File

@@ -0,0 +1,15 @@
defmodule KV.BucketTest do
use ExUnit.Case, async: true
setup do
bucket = start_supervised!(KV.Bucket)
%{bucket: bucket}
end
test "stores values by key", %{bucket: bucket} do
assert KV.Bucket.get(bucket, "milk") == nil
KV.Bucket.put(bucket, "milk", 3)
assert KV.Bucket.get(bucket, "milk") == 3
end
end

View File

@@ -0,0 +1,42 @@
defmodule KV.RegistryTest do
use ExUnit.Case, async: true
setup context do
_ = start_supervised!({KV.Registry, name: context.test})
%{registry: context.test}
end
test "spawns buckets", %{registry: registry} do
assert KV.Registry.lookup(registry, "shopping") == :error
KV.Registry.create(registry, "shopping")
assert {:ok, bucket} = KV.Registry.lookup(registry, "shopping")
KV.Bucket.put(bucket, "milk", 1)
assert KV.Bucket.get(bucket, "milk") == 1
end
test "removes buckets on exit", %{registry: registry} do
KV.Registry.create(registry, "shopping")
{:ok, bucket} = KV.Registry.lookup(registry, "shopping")
Agent.stop(bucket)
# Do a call to ensure the registry processed the DOWN message
_ = KV.Registry.create(registry, "bogus")
assert KV.Registry.lookup(registry, "shopping") == :error
end
test "removes bucket on crash", %{registry: registry} do
KV.Registry.create(registry, "shopping")
{:ok, bucket} = KV.Registry.lookup(registry, "shopping")
# Stop the bucket with non-normal reason
# If a process terminates with a reason other than :normal, all linked processes
# receive an EXIT signal, causing the linked process to
# also terminate unless it is trapping exits.
Agent.stop(bucket, :shutdown)
# Do a call to ensure the registry processed the DOWN message
_ = KV.Registry.create(registry, "bogus")
assert KV.Registry.lookup(registry, "shopping") == :error
end
end

View File

@@ -0,0 +1 @@
ExUnit.start()

View File

@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

23
kv_umbrella/apps/kv_server/.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
kv_server-*.tar
# Temporary files, for example, from tests.
/tmp/

View File

@@ -0,0 +1,21 @@
# KVServer
**TODO: Add description**
## Installation
If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `kv_server` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[
{:kv_server, "~> 0.1.0"}
]
end
```
Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at <https://hexdocs.pm/kv_server>.

View File

@@ -0,0 +1,18 @@
defmodule KVServer do
@moduledoc """
Documentation for `KVServer`.
"""
@doc """
Hello world.
## Examples
iex> KVServer.hello()
:world
"""
def hello do
:world
end
end

View File

@@ -0,0 +1,20 @@
defmodule KVServer.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Starts a worker by calling: KVServer.Worker.start_link(arg)
# {KVServer.Worker, arg}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: KVServer.Supervisor]
Supervisor.start_link(children, opts)
end
end

View File

@@ -0,0 +1,35 @@
defmodule KVServer.MixProject do
use Mix.Project
def project do
[
app: :kv_server,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.18",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {KVServer.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:kv, in_umbrella: true},
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
# {:sibling_app_in_umbrella, in_umbrella: true}
]
end
end

View File

@@ -0,0 +1,8 @@
defmodule KVServerTest do
use ExUnit.Case
doctest KVServer
test "greets the world" do
assert KVServer.hello() == :world
end
end

View File

@@ -0,0 +1 @@
ExUnit.start()

View File

@@ -0,0 +1,18 @@
# This file is responsible for configuring your umbrella
# and **all applications** and their dependencies with the
# help of the Config module.
#
# Note that all applications in your umbrella share the
# same configuration and dependencies, which is why they
# all use the same configuration file. If you want different
# configurations or dependencies per app, it is best to
# move said applications out of the umbrella.
import Config
# Sample configuration:
#
# config :logger, :console,
# level: :info,
# format: "$date $time [$level] $metadata$message\n",
# metadata: [:user_id]
#

21
kv_umbrella/mix.exs Normal file
View File

@@ -0,0 +1,21 @@
defmodule KvUmbrella.MixProject do
use Mix.Project
def project do
[
apps_path: "apps",
version: "0.1.0",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Dependencies listed here are available only for this
# project and cannot be accessed from applications inside
# the apps folder.
#
# Run "mix help deps" for examples and options.
defp deps do
[]
end
end