backend
This commit is contained in:
60
backend/lib/backend_web/channels/game_channel.ex
Normal file
60
backend/lib/backend_web/channels/game_channel.ex
Normal file
@@ -0,0 +1,60 @@
|
||||
defmodule BackendWeb.GameChannel do
|
||||
@moduledoc """
|
||||
Channel for handling game events and player movements.
|
||||
"""
|
||||
use BackendWeb, :channel
|
||||
require Logger
|
||||
|
||||
@impl true
|
||||
def join("game:lobby", _payload, socket) do
|
||||
Logger.info("WebSocket connected to #{node()}, waiting for name")
|
||||
Phoenix.PubSub.subscribe(Backend.PubSub, "game_state")
|
||||
|
||||
current_state = Backend.GameState.get_state()
|
||||
{:ok, %{players: current_state}, socket}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info({:game_state_updated, state}, socket) do
|
||||
push(socket, "game_state", %{players: state})
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_in("join_game", %{"name" => name}, socket) do
|
||||
Logger.info("Player '#{name}' joining game on #{node()}")
|
||||
|
||||
socket = assign(socket, :player_name, name)
|
||||
Backend.GameState.add_player(name)
|
||||
|
||||
{:reply, :ok, socket}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_in("move", %{"directions" => directions}, socket) do
|
||||
case socket.assigns[:player_name] do
|
||||
nil ->
|
||||
Logger.warning("Move attempted without joining game")
|
||||
{:noreply, socket}
|
||||
|
||||
player_name ->
|
||||
Logger.debug("Player '#{player_name}' moved #{inspect(directions)} on #{node()}")
|
||||
Backend.GameState.move_player(player_name, directions)
|
||||
{:noreply, socket}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def terminate(_reason, socket) do
|
||||
case socket.assigns[:player_name] do
|
||||
nil ->
|
||||
Logger.info("WebSocket disconnected from #{node()}")
|
||||
|
||||
player_name ->
|
||||
Logger.info("Player '#{player_name}' disconnected from #{node()}")
|
||||
Backend.GameState.remove_player(player_name)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
end
|
||||
36
backend/lib/backend_web/channels/user_socket.ex
Normal file
36
backend/lib/backend_web/channels/user_socket.ex
Normal file
@@ -0,0 +1,36 @@
|
||||
defmodule BackendWeb.UserSocket do
|
||||
use Phoenix.Socket
|
||||
|
||||
# A Socket handler
|
||||
#
|
||||
# It's possible to control the websocket connection and
|
||||
# assign values that can be accessed by your channel topics.
|
||||
|
||||
## Channels
|
||||
channel("game:*", BackendWeb.GameChannel)
|
||||
|
||||
# Socket params are passed from the client and can
|
||||
# be used to verify and authenticate a user. After
|
||||
# verification, you can put default assigns into
|
||||
# the socket that will be set for all channels, ie
|
||||
#
|
||||
# {:ok, assign(socket, :user_id, verified_user_id)}
|
||||
#
|
||||
# To deny connection, return `:error` or `{:error, term}`.
|
||||
@impl true
|
||||
def connect(_params, socket, _connect_info) do
|
||||
{:ok, socket}
|
||||
end
|
||||
|
||||
# Socket id's are topics that allow you to identify all sockets for a given user:
|
||||
#
|
||||
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
|
||||
#
|
||||
# Would allow you to broadcast a "disconnect" event and terminate
|
||||
# all active sockets and channels for a given user:
|
||||
#
|
||||
#
|
||||
# Returning `nil` makes this socket anonymous.
|
||||
@impl true
|
||||
def id(_socket), do: nil
|
||||
end
|
||||
21
backend/lib/backend_web/controllers/error_json.ex
Normal file
21
backend/lib/backend_web/controllers/error_json.ex
Normal file
@@ -0,0 +1,21 @@
|
||||
defmodule BackendWeb.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
|
||||
15
backend/lib/backend_web/controllers/health_controller.ex
Normal file
15
backend/lib/backend_web/controllers/health_controller.ex
Normal file
@@ -0,0 +1,15 @@
|
||||
defmodule BackendWeb.HealthController do
|
||||
use BackendWeb, :controller
|
||||
|
||||
# Disable logging for health checks
|
||||
plug(:disable_logging)
|
||||
|
||||
def check(conn, _params) do
|
||||
json(conn, %{status: "ok", node: node()})
|
||||
end
|
||||
|
||||
defp disable_logging(conn, _opts) do
|
||||
Logger.metadata(plug_log_level: :none)
|
||||
conn
|
||||
end
|
||||
end
|
||||
61
backend/lib/backend_web/endpoint.ex
Normal file
61
backend/lib/backend_web/endpoint.ex
Normal file
@@ -0,0 +1,61 @@
|
||||
defmodule BackendWeb.Endpoint do
|
||||
use Phoenix.Endpoint, otp_app: :backend
|
||||
|
||||
# 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: "_backend_key",
|
||||
signing_salt: "AnIFBp4s",
|
||||
same_site: "Lax"
|
||||
]
|
||||
|
||||
socket("/live", Phoenix.LiveView.Socket,
|
||||
websocket: [connect_info: [session: @session_options]],
|
||||
longpoll: [connect_info: [session: @session_options]]
|
||||
)
|
||||
|
||||
socket("/socket", BackendWeb.UserSocket,
|
||||
websocket: true,
|
||||
longpoll: false
|
||||
)
|
||||
|
||||
# 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: :backend,
|
||||
gzip: not code_reloading?,
|
||||
only: BackendWeb.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(BackendWeb.Plugs.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(BackendWeb.Router)
|
||||
end
|
||||
17
backend/lib/backend_web/health_check_filter.ex
Normal file
17
backend/lib/backend_web/health_check_filter.ex
Normal file
@@ -0,0 +1,17 @@
|
||||
defmodule BackendWeb.HealthCheckFilter do
|
||||
@moduledoc """
|
||||
Custom Phoenix logger that filters out health check requests.
|
||||
"""
|
||||
require Logger
|
||||
|
||||
def phoenix_filter(level, msg, ts, meta) do
|
||||
# Filter out health check logs
|
||||
case meta do
|
||||
%{request_path: "/api/health"} ->
|
||||
:ignore
|
||||
|
||||
_ ->
|
||||
Phoenix.Logger.log(level, msg, ts, meta)
|
||||
end
|
||||
end
|
||||
end
|
||||
14
backend/lib/backend_web/plugs/telemetry.ex
Normal file
14
backend/lib/backend_web/plugs/telemetry.ex
Normal file
@@ -0,0 +1,14 @@
|
||||
defmodule BackendWeb.Plugs.Telemetry do
|
||||
@behaviour Plug
|
||||
|
||||
@impl true
|
||||
def init(opts), do: Plug.Telemetry.init(opts)
|
||||
|
||||
@impl true
|
||||
def call(%{path_info: ["api", "health"]} = conn, {start_event, stop_event, opts}) do
|
||||
# Suppress logs for health check endpoint
|
||||
Plug.Telemetry.call(conn, {start_event, stop_event, Keyword.put(opts, :log, false)})
|
||||
end
|
||||
|
||||
def call(conn, args), do: Plug.Telemetry.call(conn, args)
|
||||
end
|
||||
30
backend/lib/backend_web/router.ex
Normal file
30
backend/lib/backend_web/router.ex
Normal file
@@ -0,0 +1,30 @@
|
||||
defmodule BackendWeb.Router do
|
||||
use BackendWeb, :router
|
||||
|
||||
pipeline :api do
|
||||
plug(:accepts, ["json"])
|
||||
end
|
||||
|
||||
scope "/api", BackendWeb do
|
||||
pipe_through(:api)
|
||||
|
||||
get("/health", HealthController, :check)
|
||||
end
|
||||
|
||||
# Enable LiveDashboard and Swoosh mailbox preview in development
|
||||
if Application.compile_env(:backend, :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: BackendWeb.Telemetry)
|
||||
forward("/mailbox", Plug.Swoosh.MailboxPreview)
|
||||
end
|
||||
end
|
||||
end
|
||||
70
backend/lib/backend_web/telemetry.ex
Normal file
70
backend/lib/backend_web/telemetry.ex
Normal file
@@ -0,0 +1,70 @@
|
||||
defmodule BackendWeb.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://hexdocs.pm/telemetry_metrics
|
||||
{: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.
|
||||
# {BackendWeb, :count_users, []}
|
||||
]
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user