Prepare to join servers

This commit is contained in:
Maciej 2026-02-28 16:19:35 +02:00
parent 3afaf346c7
commit 984ac15084
Signed by: maciej
GPG key ID: 28243AF437E32F99
12 changed files with 137 additions and 17 deletions

View file

@ -10,6 +10,8 @@ defmodule BirdyChat.Application do
children = [
BirdyChatWeb.Telemetry,
BirdyChat.Identity,
BirdyChat.PeerSupervisor,
{Registry, keys: :unique, name: BirdyChat.PeerRegistry},
{DNSCluster, query: Application.get_env(:birdy_chat, :dns_cluster_query) || :ignore},
{Phoenix.PubSub, name: BirdyChat.PubSub},
# Start a worker by calling: BirdyChat.Worker.start_link(arg)

View file

@ -49,7 +49,12 @@ defmodule BirdyChat.Identity do
peers = System.get_env("BIRDY_CHAT_PEERS")
case {identity, peers} do
{nil, nil} -> %__MODULE__{identity: "test", peers: [], mode: :singleton}
{nil, nil} ->
%__MODULE__{
identity: "test1",
peers: %{"test2" => "http://localhost:4001"},
mode: :test
}
end
end
end

View file

@ -19,4 +19,21 @@ defmodule BirdyChat.Message do
{:error, changeset}
end
end
def find_peer(%{to: to}) do
identity = BirdyChat.Identity.identity()
if String.starts_with?(to, identity) do
{:ok, :local}
else
result =
BirdyChat.Identity.peers()
|> Enum.find(fn {name, _url} -> String.starts_with?(to, name) end)
case result do
{name, _url} -> {:ok, name}
nil -> {:error, :not_found}
end
end
end
end

View file

@ -0,0 +1,9 @@
defmodule BirdyChat.PeerClient do
use Slipstream, restart: :temporary
def start_link(args) do
name = args[:peer_name]
name = {:via, BirdyChat.PeerRegistry, {:peers, name}}
Slipstream.start_link(__MODULE__, args, name: name)
end
end

View file

@ -0,0 +1,17 @@
defmodule BirdyChat.PeerSupervisor do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
def start_child(peer_name, peer_address) do
spec = {BirdyChat.PeerClient, peer_name: peer_name, peer_address: peer_address}
DynamicSupervisor.start_child(__MODULE__, spec)
end
@impl true
def init(init_arg) do
DynamicSupervisor.init(strategy: :one_for_one, extra_arguments: [init_arg])
end
end

View file

@ -4,6 +4,8 @@ defmodule BirdyChatWeb.Api.Messages.Controller do
def create(conn, params) do
case BirdyChat.Message.validate(params) do
{:ok, changeset} ->
case BirdyChat.Message.find_peer(changeset.changes) do
{:ok, :local} ->
case BirdyChat.MessageWriter.write(changeset.changes) do
:ok ->
conn
@ -11,6 +13,23 @@ defmodule BirdyChatWeb.Api.Messages.Controller do
|> render(:create, message: changeset.changes)
end
{:ok, peer_name} ->
BirdyChatWeb.ServerChannel.broadcast!(peer_name, changeset.changes)
conn
|> put_status(:created)
|> render(:create, message: changeset.changes)
{:error, :not_found} ->
changeset =
changeset
|> Ecto.Changeset.add_error(:to, "Unknown 'to' server")
conn
|> put_status(:unprocessable_entity)
|> render(:error, changeset: changeset)
end
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)

View file

@ -24,6 +24,13 @@ defmodule BirdyChatWeb.ServerChannel do
end
end
# This is how we send messages
def broadcast!(peer, message) do
channel = "server:#{peer}"
encoded_message = :erlang.term_to_binary(message)
BirdyChatWeb.Endpoint.broadcast!(channel, "new_message", {:binary, encoded_message})
end
# Simple token-based authentication. Servers should use the same Phoenix secret key so they will
# have the basis for generating tokens.
defp authorised?(%{"token" => token}, server_id) do

View file

@ -1,5 +1,5 @@
defmodule BirdyChat.IdentityTest do
use BirdyChat.DataCase
use BirdyChat.DataCase, async: true
setup do
registry = start_supervised!({Registry, keys: :unique, name: __MODULE__})
@ -11,7 +11,7 @@ defmodule BirdyChat.IdentityTest do
name = {:via, Registry, {__MODULE__, "identity"}}
{:ok, process} = BirdyChat.Identity.start_link(name: name)
mode = BirdyChat.Identity.mode(process)
assert mode == :singleton
assert mode == :test
end
test "can be started by giving values like environment variables" do

View file

@ -0,0 +1,3 @@
defmodule BirdyChat.PeerTest do
use BirdyChat.DataCase, async: true
end

View file

@ -1,10 +1,12 @@
defmodule BirdyChatWeb.Api.MessagesTest do
use BirdyChatWeb.ConnCase
use BirdyChatWeb.ConnCase, async: true
import Phoenix.ChannelTest
setup %{conn: conn} do
url = ~p"/api/messages"
path = Application.app_dir(:birdy_chat, ["priv", "messages", "test-user.txt"])
path = Application.app_dir(:birdy_chat, ["priv", "messages", "test1-user.txt"])
on_exit(fn -> File.rm(path) end)
conn =
@ -14,6 +16,45 @@ defmodule BirdyChatWeb.Api.MessagesTest do
%{conn: conn, url: url}
end
describe "POST /api/messages to other server" do
setup do
server_id = "test2"
token = Phoenix.Token.sign(BirdyChatWeb.Endpoint, "serverAuth", server_id)
{:ok, _, socket} =
BirdyChatWeb.ServerSocket
|> socket("server_socket", %{server_id: server_id})
|> subscribe_and_join(BirdyChatWeb.ServerChannel, "server:#{server_id}", %{token: token})
%{socket: socket}
end
test "returns error when a peer is unknown", %{conn: conn, url: url} do
message = %{from: "test1-user", to: "fake-user", message: "123"}
payload = Jason.encode!(message)
conn = post(conn, url, payload)
assert result = json_response(conn, :unprocessable_entity)
expected_result = %{"errors" => %{"to" => ["Unknown 'to' server"]}}
assert result == expected_result
end
test "broadcasts message to websocket", %{conn: conn, url: url} do
message = %{from: "test1-user", to: "test2-user", message: "123"}
string_message = %{"from" => "test1-user", "message" => "123", "to" => "test2-user"}
payload = Jason.encode!(message)
conn = post(conn, url, payload)
assert result = json_response(conn, :created)
assert result == string_message
assert_broadcast "new_message", {:binary, encoded_message}
assert :erlang.binary_to_term(encoded_message, [:safe]) == message
end
end
describe "POST /api/messages" do
test "returns errors for invalid message", %{conn: conn, url: url} do
payload = Jason.encode!(%{})
@ -32,7 +73,7 @@ defmodule BirdyChatWeb.Api.MessagesTest do
end
test "returns message and 201 when successful", %{conn: conn, url: url} do
message = %{"from" => "2-user", "to" => "1-user", "message" => "123"}
message = %{"from" => "test2-user", "to" => "test1-user", "message" => "123"}
payload = Jason.encode!(message)
conn = post(conn, url, payload)
assert result = json_response(conn, :created)
@ -40,30 +81,30 @@ defmodule BirdyChatWeb.Api.MessagesTest do
end
test "writes message to file", %{conn: conn, url: url} do
message = %{"from" => "2-user", "to" => "test-user", "message" => "123"}
message = %{"from" => "test2-user", "to" => "test1-user", "message" => "123"}
payload = Jason.encode!(message)
conn = post(conn, url, payload)
assert result = json_response(conn, :created)
assert result == message
path = Application.app_dir(:birdy_chat, ["priv", "messages", "test-user.txt"])
path = Application.app_dir(:birdy_chat, ["priv", "messages", "test1-user.txt"])
contents = File.read!(path)
assert contents == "2-user: 123\n"
assert contents == "test2-user: 123\n"
end
test "appends message to file", %{conn: conn, url: url} do
message = %{"from" => "2-user", "to" => "test-user", "message" => "123"}
message = %{"from" => "test2-user", "to" => "test1-user", "message" => "123"}
payload = Jason.encode!(message)
post(conn, url, payload)
message = %{"from" => "2-user", "to" => "test-user", "message" => "456"}
message = %{"from" => "test2-user", "to" => "test1-user", "message" => "456"}
payload = Jason.encode!(message)
conn = post(conn, url, payload)
assert json_response(conn, :created)
path = Application.app_dir(:birdy_chat, ["priv", "messages", "test-user.txt"])
path = Application.app_dir(:birdy_chat, ["priv", "messages", "test1-user.txt"])
contents = File.read!(path)
assert contents == "2-user: 123\n2-user: 456\n"
assert contents == "test2-user: 123\ntest2-user: 456\n"
end
end
end

View file

@ -1,5 +1,5 @@
defmodule BirdyChatWeb.ServerChannelTest do
use BirdyChatWeb.ChannelCase
use BirdyChatWeb.ChannelCase, async: true
setup do
server_id = "test2"

View file

@ -1,5 +1,5 @@
defmodule BirdyChatWeb.PageControllerTest do
use BirdyChatWeb.ConnCase
use BirdyChatWeb.ConnCase, async: true
test "GET /", %{conn: conn} do
conn = get(conn, ~p"/")