diff --git a/labs/04/arithmetic.ex b/labs/04/arithmetic.ex new file mode 100644 index 0000000..63ed218 --- /dev/null +++ b/labs/04/arithmetic.ex @@ -0,0 +1,90 @@ +defmodule Arithmetic.Worker do + use GenServer + + def start_link() do + GenServer.start_link(__MODULE__, nil) + end + + ### Server Impl ### + @impl true + def init(_arg) do + {:ok, nil} + end + + @impl true + def handle_cast({:square, x, from}, state) do + # The server dispatches work asynchronously, so workers handle casts and + # reply directly to the client that made the original GenServer.call/2. + GenServer.reply(from, {self(), x * x}) + {:noreply, state} + end + + @impl true + def handle_cast({:sqrt, x, from}, state) do + Process.sleep(2000) + GenServer.reply(from, {self(), if(x < 0, do: :error, else: :math.sqrt(x))}) + {:noreply, state} + end +end + +defmodule Arithmetic.Server do + use GenServer + + ### Client API ### + def start(n) do + GenServer.start(__MODULE__, n, name: __MODULE__) + end + + def square(x) do + GenServer.call(__MODULE__, {:square, x}) + end + + def sqrt(x) do + GenServer.call(__MODULE__, {:sqrt, x}) + end + + ### Server Impl ### + @impl true + def init(n) do + Process.flag(:trap_exit, true) + + workers = + Enum.map(1..n, fn _ -> + {:ok, pid} = Arithmetic.Worker.start_link() + IO.inspect(pid) + pid + end) + + {:ok, {workers, 0}} + end + + @impl true + def handle_call({:square, x}, from, {workers, index}) do + worker = Enum.at(workers, index) + + GenServer.cast(worker, {:square, x, from}) + + next = rem(index + 1, length(workers)) + # Do not reply here; the selected worker replies to `from` after the cast. + {:noreply, {workers, next}} + end + + @impl true + def handle_call({:sqrt, x}, from, {workers, index}) do + worker = Enum.at(workers, index) + + GenServer.cast(worker, {:sqrt, x, from}) + + next = rem(index + 1, length(workers)) + {:noreply, {workers, next}} + end + + @impl true + def handle_info({:EXIT, dead, reason}, {workers, index}) do + {:ok, new} = Arithmetic.Worker.start_link() + IO.puts("Worker #{inspect(dead)} died (#{inspect(reason)}), replacement: #{inspect(new)}") + + workers = Enum.map(workers, fn pid -> if pid == dead, do: new, else: pid end) + {:noreply, {workers, index}} + end +end diff --git a/labs/04/card/.formatter.exs b/labs/04/card/.formatter.exs new file mode 100644 index 0000000..d2cda26 --- /dev/null +++ b/labs/04/card/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/labs/04/card/.gitignore b/labs/04/card/.gitignore new file mode 100644 index 0000000..acf9971 --- /dev/null +++ b/labs/04/card/.gitignore @@ -0,0 +1,28 @@ +# 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"). +card-*.tar + +# Temporary files, for example, from tests. +/tmp/ + +cards.db diff --git a/labs/04/card/README.md b/labs/04/card/README.md new file mode 100644 index 0000000..4f4836e --- /dev/null +++ b/labs/04/card/README.md @@ -0,0 +1,21 @@ +# Card + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `card` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [ + {:card, "~> 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 . + diff --git a/labs/04/card/lib/card/application.ex b/labs/04/card/lib/card/application.ex new file mode 100644 index 0000000..c941145 --- /dev/null +++ b/labs/04/card/lib/card/application.ex @@ -0,0 +1,16 @@ +defmodule Card.Application do + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + children = [ + {Card.Store, "cards.db"}, + Card.Worker + ] + + opts = [strategy: :one_for_one, name: Card.Supervisor] + Supervisor.start_link(children, opts) + end +end diff --git a/labs/04/card/lib/card/store.ex b/labs/04/card/lib/card/store.ex new file mode 100644 index 0000000..86a4879 --- /dev/null +++ b/labs/04/card/lib/card/store.ex @@ -0,0 +1,39 @@ +defmodule Card.Store do + use GenServer + + # client + def start_link(file) do + GenServer.start_link(__MODULE__, file, name: __MODULE__) + end + + def put(value) do + GenServer.call(__MODULE__, {:put, value}) + end + + def get() do + GenServer.call(__MODULE__, :get) + end + + # server + @impl true + def init(file) do + {:ok, file} + end + + @impl true + def handle_call(:get, _from, file) do + reply = + case File.read(file) do + {:ok, content} -> :erlang.binary_to_term(content) + _ -> nil + end + + {:reply, reply, file} + end + + @impl true + def handle_call({:put, value}, _from, file) do + reply = File.write(file, :erlang.term_to_binary(value)) + {:reply, reply, file} + end +end diff --git a/labs/04/card/lib/card/worker.ex b/labs/04/card/lib/card/worker.ex new file mode 100644 index 0000000..f935462 --- /dev/null +++ b/labs/04/card/lib/card/worker.ex @@ -0,0 +1,79 @@ +defmodule Card.Worker do + use GenServer + + ### Client API ### + def start_link(_arg \\ nil) do + GenServer.start_link(__MODULE__, nil, name: __MODULE__) + end + + def new() do + GenServer.cast(__MODULE__, :new) + end + + def shuffle() do + GenServer.cast(__MODULE__, :shuffle) + end + + def count() do + GenServer.call(__MODULE__, :count) + end + + def deal(n \\ 1) do + GenServer.call(__MODULE__, {:deal, n}) + end + + ### Server Impl ### + defp fresh() do + values = Enum.map(2..10, &Integer.to_string/1) ++ ["J", "Q", "K", "A"] + suits = ["♣", "♦", "♥", "♠"] + + for v <- values, f <- suits, do: v <> f + end + + defp save(state) do + Card.Store.put(state) + state + end + + @impl true + def init(_arg) do + IO.puts("Card.Worker started/re-started") + {:ok, Card.Store.get() || save(fresh())} + end + + @impl true + def handle_cast(:new, _state) do + # {:noreply, new_state} + {:noreply, save(fresh())} + end + + @impl true + def handle_cast(:shuffle, state) do + # {:noreply, new_state} + {:noreply, save(Enum.shuffle(state))} + end + + @impl true + def handle_call(:count, _from, state) do + # {:reply, actual_reply, new_state} + {:reply, length(state), state} + end + + @impl true + def handle_call({:deal, n}, _from, state) when is_integer(n) do + case n do + _ when n < 0 -> + # {:reply, actual_reply, new_state} + {:reply, {:error, "Cannot deal negative number of cards"}, state} + + _ when n > length(state) -> + # {:reply, actual_reply, new_state} + {:reply, {:error, "Insufficient cards in deck to deal"}, state} + + _ -> + {d, r} = Enum.split(state, n) + # {:reply, actual_reply, new_state} + {:reply, {:ok, d}, save(r)} + end + end +end diff --git a/labs/04/card/mix.exs b/labs/04/card/mix.exs new file mode 100644 index 0000000..3626383 --- /dev/null +++ b/labs/04/card/mix.exs @@ -0,0 +1,29 @@ +defmodule Card.MixProject do + use Mix.Project + + def project do + [ + app: :card, + version: "0.1.0", + 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: {Card.Application, []} + ] + 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 diff --git a/labs/04/card/test/test_helper.exs b/labs/04/card/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/labs/04/card/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start() diff --git a/labs/04/lab4/arithmetic.ex b/labs/04/lab4/arithmetic.ex new file mode 100644 index 0000000..63ed218 --- /dev/null +++ b/labs/04/lab4/arithmetic.ex @@ -0,0 +1,90 @@ +defmodule Arithmetic.Worker do + use GenServer + + def start_link() do + GenServer.start_link(__MODULE__, nil) + end + + ### Server Impl ### + @impl true + def init(_arg) do + {:ok, nil} + end + + @impl true + def handle_cast({:square, x, from}, state) do + # The server dispatches work asynchronously, so workers handle casts and + # reply directly to the client that made the original GenServer.call/2. + GenServer.reply(from, {self(), x * x}) + {:noreply, state} + end + + @impl true + def handle_cast({:sqrt, x, from}, state) do + Process.sleep(2000) + GenServer.reply(from, {self(), if(x < 0, do: :error, else: :math.sqrt(x))}) + {:noreply, state} + end +end + +defmodule Arithmetic.Server do + use GenServer + + ### Client API ### + def start(n) do + GenServer.start(__MODULE__, n, name: __MODULE__) + end + + def square(x) do + GenServer.call(__MODULE__, {:square, x}) + end + + def sqrt(x) do + GenServer.call(__MODULE__, {:sqrt, x}) + end + + ### Server Impl ### + @impl true + def init(n) do + Process.flag(:trap_exit, true) + + workers = + Enum.map(1..n, fn _ -> + {:ok, pid} = Arithmetic.Worker.start_link() + IO.inspect(pid) + pid + end) + + {:ok, {workers, 0}} + end + + @impl true + def handle_call({:square, x}, from, {workers, index}) do + worker = Enum.at(workers, index) + + GenServer.cast(worker, {:square, x, from}) + + next = rem(index + 1, length(workers)) + # Do not reply here; the selected worker replies to `from` after the cast. + {:noreply, {workers, next}} + end + + @impl true + def handle_call({:sqrt, x}, from, {workers, index}) do + worker = Enum.at(workers, index) + + GenServer.cast(worker, {:sqrt, x, from}) + + next = rem(index + 1, length(workers)) + {:noreply, {workers, next}} + end + + @impl true + def handle_info({:EXIT, dead, reason}, {workers, index}) do + {:ok, new} = Arithmetic.Worker.start_link() + IO.puts("Worker #{inspect(dead)} died (#{inspect(reason)}), replacement: #{inspect(new)}") + + workers = Enum.map(workers, fn pid -> if pid == dead, do: new, else: pid end) + {:noreply, {workers, index}} + end +end diff --git a/labs/04/lab4/card/.formatter.exs b/labs/04/lab4/card/.formatter.exs new file mode 100644 index 0000000..d2cda26 --- /dev/null +++ b/labs/04/lab4/card/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/labs/04/lab4/card/.gitignore b/labs/04/lab4/card/.gitignore new file mode 100644 index 0000000..acf9971 --- /dev/null +++ b/labs/04/lab4/card/.gitignore @@ -0,0 +1,28 @@ +# 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"). +card-*.tar + +# Temporary files, for example, from tests. +/tmp/ + +cards.db diff --git a/labs/04/lab4/card/README.md b/labs/04/lab4/card/README.md new file mode 100644 index 0000000..4f4836e --- /dev/null +++ b/labs/04/lab4/card/README.md @@ -0,0 +1,21 @@ +# Card + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `card` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [ + {:card, "~> 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 . + diff --git a/labs/04/lab4/card/lib/card/application.ex b/labs/04/lab4/card/lib/card/application.ex new file mode 100644 index 0000000..c941145 --- /dev/null +++ b/labs/04/lab4/card/lib/card/application.ex @@ -0,0 +1,16 @@ +defmodule Card.Application do + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + children = [ + {Card.Store, "cards.db"}, + Card.Worker + ] + + opts = [strategy: :one_for_one, name: Card.Supervisor] + Supervisor.start_link(children, opts) + end +end diff --git a/labs/04/lab4/card/lib/card/store.ex b/labs/04/lab4/card/lib/card/store.ex new file mode 100644 index 0000000..86a4879 --- /dev/null +++ b/labs/04/lab4/card/lib/card/store.ex @@ -0,0 +1,39 @@ +defmodule Card.Store do + use GenServer + + # client + def start_link(file) do + GenServer.start_link(__MODULE__, file, name: __MODULE__) + end + + def put(value) do + GenServer.call(__MODULE__, {:put, value}) + end + + def get() do + GenServer.call(__MODULE__, :get) + end + + # server + @impl true + def init(file) do + {:ok, file} + end + + @impl true + def handle_call(:get, _from, file) do + reply = + case File.read(file) do + {:ok, content} -> :erlang.binary_to_term(content) + _ -> nil + end + + {:reply, reply, file} + end + + @impl true + def handle_call({:put, value}, _from, file) do + reply = File.write(file, :erlang.term_to_binary(value)) + {:reply, reply, file} + end +end diff --git a/labs/04/lab4/card/lib/card/worker.ex b/labs/04/lab4/card/lib/card/worker.ex new file mode 100644 index 0000000..f935462 --- /dev/null +++ b/labs/04/lab4/card/lib/card/worker.ex @@ -0,0 +1,79 @@ +defmodule Card.Worker do + use GenServer + + ### Client API ### + def start_link(_arg \\ nil) do + GenServer.start_link(__MODULE__, nil, name: __MODULE__) + end + + def new() do + GenServer.cast(__MODULE__, :new) + end + + def shuffle() do + GenServer.cast(__MODULE__, :shuffle) + end + + def count() do + GenServer.call(__MODULE__, :count) + end + + def deal(n \\ 1) do + GenServer.call(__MODULE__, {:deal, n}) + end + + ### Server Impl ### + defp fresh() do + values = Enum.map(2..10, &Integer.to_string/1) ++ ["J", "Q", "K", "A"] + suits = ["♣", "♦", "♥", "♠"] + + for v <- values, f <- suits, do: v <> f + end + + defp save(state) do + Card.Store.put(state) + state + end + + @impl true + def init(_arg) do + IO.puts("Card.Worker started/re-started") + {:ok, Card.Store.get() || save(fresh())} + end + + @impl true + def handle_cast(:new, _state) do + # {:noreply, new_state} + {:noreply, save(fresh())} + end + + @impl true + def handle_cast(:shuffle, state) do + # {:noreply, new_state} + {:noreply, save(Enum.shuffle(state))} + end + + @impl true + def handle_call(:count, _from, state) do + # {:reply, actual_reply, new_state} + {:reply, length(state), state} + end + + @impl true + def handle_call({:deal, n}, _from, state) when is_integer(n) do + case n do + _ when n < 0 -> + # {:reply, actual_reply, new_state} + {:reply, {:error, "Cannot deal negative number of cards"}, state} + + _ when n > length(state) -> + # {:reply, actual_reply, new_state} + {:reply, {:error, "Insufficient cards in deck to deal"}, state} + + _ -> + {d, r} = Enum.split(state, n) + # {:reply, actual_reply, new_state} + {:reply, {:ok, d}, save(r)} + end + end +end diff --git a/labs/04/lab4/card/mix.exs b/labs/04/lab4/card/mix.exs new file mode 100644 index 0000000..3626383 --- /dev/null +++ b/labs/04/lab4/card/mix.exs @@ -0,0 +1,29 @@ +defmodule Card.MixProject do + use Mix.Project + + def project do + [ + app: :card, + version: "0.1.0", + 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: {Card.Application, []} + ] + 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 diff --git a/labs/04/lab4/card/test/test_helper.exs b/labs/04/lab4/card/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/labs/04/lab4/card/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start()