lecture 06

This commit is contained in:
SowinskiBraeden committed 2026-10-17 16:34:36 -07:00
1 parent 85297ca4a8
commit 15fbe95787
76 files changed
+3756

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
defmodule Counter do
@moduledoc """
Counter keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
@@ -0,0 +1,38 @@
defmodule Counter.Application do
# See https://elixir.hexdocs.pm/Application.html
# for more information on OTP Applications
@moduledoc false
@table Counter.Table
@registry Counter.Registry
use Application
@impl true
def start(_type, _args) do
:ets.new(@table, [:set, :public, :named_table])
children = [
CounterWeb.Telemetry,
{DNSCluster, query: Application.get_env(:counter, :dns_cluster_query) || :ignore},
{Phoenix.PubSub, name: Counter.PubSub},
{Registry, name: @registry, keys: :unique},
# Starts workers on demand by calling: Counter.DynamicSupervisor.start_worker(name)
Counter.DynamicSupervisor,
# Start to serve requests, typically the last entry
CounterWeb.Endpoint
]
# See https://elixir.hexdocs.pm/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Counter.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
@impl true
def config_change(changed, _new, removed) do
CounterWeb.Endpoint.config_change(changed, removed)
:ok
end
end
@@ -0,0 +1,16 @@
defmodule Counter.DynamicSupervisor do
use DynamicSupervisor
def start_link(_) do
DynamicSupervisor.start_link(__MODULE__, nil, name: __MODULE__)
end
def start_worker(name) do
DynamicSupervisor.start_child(__MODULE__, {Counter.Worker, name})
end
@impl true
def init(_) do
DynamicSupervisor.init(strategy: :one_for_one)
end
end
+52
View File
@@ -0,0 +1,52 @@
defmodule Counter.Worker do
use GenServer
@registry Counter.Registry
@table Counter.Table
### Client API ###
def start_link(name) do
GenServer.start_link(__MODULE__, name, name: via(name))
end
def value(name) do
GenServer.call(via(name), :value)
end
def inc(name, amt \\ 1) do
GenServer.cast(via(name), {:inc, amt})
end
# wrap the name in a triple to use the Registry to get the
# process ID by name
defp via(name) do
{:via, Registry, {@registry, {__MODULE__, name}}}
end
### Server Impl ###
@impl true
def init(arg) do
name = {__MODULE__, arg}
value = case :ets.lookup(@table, name) do
[] -> 0
[{_, v}] -> v
end
{:ok, {name, value}}
end
@impl true
def handle_call(:value, _from, {_, value} = state) do
{:reply, value, state}
end
@impl true
def handle_cast({:inc, amt}, {name, value}) do
{:noreply, {name, value + amt}}
end
# save state to term table when process terminates
@impl true
def terminate(_, state) do
:ets.insert(@table, state)
end
end
+65
View File
@@ -0,0 +1,65 @@
defmodule CounterWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, components, channels, and so on.
This can be used in your application as:
use CounterWeb, :controller
use CounterWeb, :html
The definitions below will be executed for every controller,
component, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define additional modules and import
those modules here.
"""
def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
def router do
quote do
use Phoenix.Router, helpers: false
# Import common connection and controller functions to use in pipelines
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
end
end
def controller do
quote do
use Phoenix.Controller, formats: [:html, :json]
use Gettext, backend: CounterWeb.Gettext
import Plug.Conn
unquote(verified_routes())
end
end
def verified_routes do
quote do
use Phoenix.VerifiedRoutes,
endpoint: CounterWeb.Endpoint,
router: CounterWeb.Router,
statics: CounterWeb.static_paths()
end
end
@doc """
When used, dispatch to the appropriate controller/live_view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
@@ -0,0 +1,18 @@
defmodule CounterWeb.CounterController do
use CounterWeb, :controller
def new(conn, %{"name" => name}) do
Counter.DynamicSupervisor.start_worker(name)
render(conn, :new)
end
def value(conn, %{"name" => name}) do
value = Counter.Worker.value(name)
render(conn, :value, value: value)
end
def inc(conn, %{"name" => name, "amt" => amt}) when is_integer(amt) do
Counter.Worker.inc(name, amt)
render(conn, :inc)
end
end
@@ -0,0 +1,13 @@
defmodule CounterWeb.CounterJSON do
def value(assigns) do
%{value: assigns.value}
end
def new(_assigns) do
%{status: "ok"}
end
def inc(_assigns) do
%{status: "ok"}
end
end
@@ -0,0 +1,21 @@
defmodule CounterWeb.ErrorJSON do
@moduledoc """
This module is invoked by your endpoint in case of errors on JSON requests.
See config/config.exs.
"""
# If you want to customize a particular status code,
# you may add your own clauses, such as:
#
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def render(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
@@ -0,0 +1,52 @@
defmodule CounterWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :counter
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_counter_key",
signing_salt: "u8wt1XSs",
same_site: "Lax"
]
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]],
longpoll: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# When code reloading is disabled (e.g., in production),
# the `gzip` option is enabled to serve compressed
# static files generated by running `phx.digest`.
plug Plug.Static,
at: "/",
from: :counter,
gzip: not code_reloading?,
only: CounterWeb.static_paths(),
raise_on_missing_only: code_reloading?
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug CounterWeb.Router
end
@@ -0,0 +1,25 @@
defmodule CounterWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://gettext.hexdocs.pm), your module compiles translations
that you can use in your application. To use this Gettext backend module,
call `use Gettext` and pass it as an option:
use Gettext, backend: CounterWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://gettext.hexdocs.pm) for detailed usage.
"""
use Gettext.Backend, otp_app: :counter
end
@@ -0,0 +1,31 @@
defmodule CounterWeb.Router do
use CounterWeb, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/api", CounterWeb do
pipe_through :api
post "/counter/new/:name", CounterController, :new
get "/counter/value/:name", CounterController, :value
post "/counter/inc/:name", CounterController, :inc
end
# Enable LiveDashboard in development
if Application.compile_env(:counter, :dev_routes) do
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
import Phoenix.LiveDashboard.Router
scope "/dev" do
pipe_through [:fetch_session, :protect_from_forgery]
live_dashboard "/dashboard", metrics: CounterWeb.Telemetry
end
end
end
@@ -0,0 +1,70 @@
defmodule CounterWeb.Telemetry do
use Supervisor
import Telemetry.Metrics
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
@impl true
def init(_arg) do
children = [
# Telemetry poller will execute the given period measurements
# every 10_000ms. Learn more here: https://telemetry-metrics.hexdocs.pm
{:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
# Add reporters as children of your supervision tree.
# {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
]
Supervisor.init(children, strategy: :one_for_one)
end
def metrics do
[
# Phoenix Metrics
summary("phoenix.endpoint.start.system_time",
unit: {:native, :millisecond}
),
summary("phoenix.endpoint.stop.duration",
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.start.system_time",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.exception.duration",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.stop.duration",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.socket_connected.duration",
unit: {:native, :millisecond}
),
sum("phoenix.socket_drain.count"),
summary("phoenix.channel_joined.duration",
unit: {:native, :millisecond}
),
summary("phoenix.channel_handled_in.duration",
tags: [:event],
unit: {:native, :millisecond}
),
# VM Metrics
summary("vm.memory.total", unit: {:byte, :kilobyte}),
summary("vm.total_run_queue_lengths.total"),
summary("vm.total_run_queue_lengths.cpu"),
summary("vm.total_run_queue_lengths.io")
]
end
defp periodic_measurements do
[
# A module, function and arguments to be invoked periodically.
# This function must call :telemetry.execute/3 and a metric must be added above.
# {CounterWeb, :count_users, []}
]
end
end