Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added message validation with structured casting #9

Merged
merged 2 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,15 @@ Next, you can declare `mutation/5` where the first argument is mutation name, se
defmodule ExampleApp.Store.Counter do
use Storex.Store

def init(session_id, params) do
def init(session_id, _params) do
{:ok, 0}
end

# Params have binary keys and result of `init/2` function can return `key` which will be the key for mutations.
# def init(session_id, %{"someKey" => someKeyValue}) do
# {:ok, 0, someKeyValue}
# end

# `increase` is mutation name, `data` is payload from front-end, `session_id` is current session id of connecton, `initial_params` with which store was initialized, `state` is store current state.
def mutation("increase", _data, _session_id, _initial_params, state) do
state = state + 1
Expand Down
11 changes: 5 additions & 6 deletions lib/storex/handler/cowboy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@ defmodule Storex.Handler.Cowboy do
end

def websocket_handle({:text, frame}, state) do
Jason.decode(frame, keys: :atoms)
|> case do
{:ok, message} ->
Socket.message_handle(message, state)
|> map_response()

with {:ok, decoded_message} <- Jason.decode(frame),
{:ok, cast_message} <- Storex.Message.cast(decoded_message) do
Socket.message_handle(cast_message, state)
|> map_response()
else
{:error, _} ->
{:reply, {:close, 1007, "Payload is malformed."}, state}
end
Expand Down
11 changes: 5 additions & 6 deletions lib/storex/handler/plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,11 @@ defmodule Storex.Handler.Plug do
end

def handle_in({message, [opcode: :text]}, state) do
Jason.decode(message, keys: :atoms)
|> case do
{:ok, message} ->
Socket.message_handle(message, state)
|> map_response()

with {:ok, decoded_message} <- Jason.decode(message),
{:ok, cast_message} <- Storex.Message.cast(decoded_message) do
Socket.message_handle(cast_message, state)
|> map_response()
else
{:error, _} ->
{:stop, "Payload is malformed.", 1007, state}
end
Expand Down
2 changes: 1 addition & 1 deletion lib/storex/http.ex
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ defmodule Storex.HTTP do

defp get_params(params) do
params
|> Jason.decode(keys: :atoms)
|> Jason.decode()
end

defp get_state(module, params) do
Expand Down
50 changes: 50 additions & 0 deletions lib/storex/message.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
defmodule Storex.Message do
@derive {Jason.Encoder, only: [:type, :store, :data, :request, :session]}
defstruct [:type, :store, :data, :request, :session]

def cast(%{
"type" => "join",
"store" => store,
"data" => data,
"request" => request,
"session" => session
}) do
{:ok, %__MODULE__{type: "join", store: store, data: data, request: request, session: session}}
end

def cast(%{"type" => "join", "store" => store, "data" => data, "request" => request}) do
{:ok, %__MODULE__{type: "join", store: store, data: data, request: request}}
end

def cast(%{
"type" => "mutation",
"store" => store,
"data" => %{"name" => name, "data" => data},
"request" => request,
"session" => session
}) do
{:ok,
%__MODULE__{
type: "mutation",
store: store,
data: %{name: name, data: data},
request: request,
session: session
}}
end

def cast(%{
"type" => "error",
"store" => store,
"data" => data,
"request" => request,
"session" => session
}) do
{:ok,
%__MODULE__{type: "error", store: store, data: data, request: request, session: session}}
end

def cast(_) do
{:error, "Unknown message type"}
end
end
6 changes: 3 additions & 3 deletions lib/storex/store.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ defmodule Storex.Store do
@doc """
Called when store session starts.
"""
@callback init(session_id :: binary(), params :: any()) ::
@callback init(session_id :: binary(), params :: %{binary() => any()}) ::
{:ok, state :: any()}
| {:ok, state :: any(), key :: binary()}
| {:error, reason :: binary()}
Expand All @@ -11,7 +11,7 @@ defmodule Storex.Store do
name :: binary(),
data :: any(),
session_id :: binary(),
params :: any(),
params :: %{binary() => any()},
state :: any()
) ::
{:reply, message :: any(), state :: any()}
Expand All @@ -20,7 +20,7 @@ defmodule Storex.Store do
@doc """
Called when store session ends.
"""
@callback terminate(session_id :: binary(), params :: any(), state :: any()) :: any()
@callback terminate(session_id :: binary(), params :: %{binary() => any()}, state :: any()) :: any()
@optional_callbacks terminate: 3

defmacro __using__(_opts) do
Expand Down
6 changes: 4 additions & 2 deletions test/fixtures/stores/text.ex
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
defmodule StorexTest.Store.Text do
use Storex.Store

def init(_session, _params) do
{:ok, "abc"}
def init(_session, params) do
initial_value = Map.get(params, "initial_value", "abc")

{:ok, initial_value}
end

def mutation("change", [value], _session_id, _params, _state) do
Expand Down
24 changes: 16 additions & 8 deletions test/storex/handler/cowboy_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ defmodule StorexTest.Handler.Cowboy do
{
"type": "join",
"store": "StorexTest.Store.Counter",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -44,7 +45,8 @@ defmodule StorexTest.Handler.Cowboy do
{
"type": "join",
"store": "StorexTest.Store.ErrorInit",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -61,7 +63,8 @@ defmodule StorexTest.Handler.Cowboy do
{
"type": "join",
"store": "StorexTest.Store.NotExisting",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -79,7 +82,8 @@ defmodule StorexTest.Handler.Cowboy do
{
"type": "join",
"store": null,
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -97,7 +101,8 @@ defmodule StorexTest.Handler.Cowboy do
{
"type": "join",
"store": "StorexTest.Store.Counter",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -113,7 +118,8 @@ defmodule StorexTest.Handler.Cowboy do
"data": {
"name": "increase",
"data": []
}
},
"request": "#{random_string()}"
}
""")

Expand All @@ -135,7 +141,8 @@ defmodule StorexTest.Handler.Cowboy do
{
"type": "join",
"store": "StorexTest.Store.Counter",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -151,7 +158,8 @@ defmodule StorexTest.Handler.Cowboy do
"data": {
"name": "not_existing",
"data": []
}
},
"request": "#{random_string()}"
}
""")

Expand Down
24 changes: 16 additions & 8 deletions test/storex/handler/plug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ defmodule StorexTest.Handler.Plug do
{
"type": "join",
"store": "StorexTest.Store.Counter",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -48,7 +49,8 @@ defmodule StorexTest.Handler.Plug do
{
"type": "join",
"store": "StorexTest.Store.ErrorInit",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -65,7 +67,8 @@ defmodule StorexTest.Handler.Plug do
{
"type": "join",
"store": "StorexTest.Store.NotExisting",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -83,7 +86,8 @@ defmodule StorexTest.Handler.Plug do
{
"type": "join",
"store": null,
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -101,7 +105,8 @@ defmodule StorexTest.Handler.Plug do
{
"type": "join",
"store": "StorexTest.Store.Counter",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -117,7 +122,8 @@ defmodule StorexTest.Handler.Plug do
"data": {
"name": "increase",
"data": []
}
},
"request": "#{random_string()}"
}
""")

Expand All @@ -139,7 +145,8 @@ defmodule StorexTest.Handler.Plug do
{
"type": "join",
"store": "StorexTest.Store.Counter",
"data": {}
"data": {},
"request": "#{random_string()}"
}
""")

Expand All @@ -155,7 +162,8 @@ defmodule StorexTest.Handler.Plug do
"data": {
"name": "not_existing",
"data": []
}
},
"request": "#{random_string()}"
}
""")

Expand Down
6 changes: 6 additions & 0 deletions test/storex/node_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ defmodule StorexTest.Node do
assert result == %{"error" => nil, "state" => %{"counter" => 0}}
end

test "test params" do
result = run_store("StorexTest.Store.Text", %{"initial_value" => "custom_text"})

assert result == %{"error" => nil, "state" => "custom_text"}
end

test "test error" do
result = run_store("StorexTest.Store.ErrorInit")

Expand Down
4 changes: 4 additions & 0 deletions test/support/handler_helpers.ex
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
defmodule StorexTest.HandlerHelpers do
def random_string(length \\ 10) do
for _ <- 1..length, into: "", do: <<Enum.random(?a..?z)>>
end

def connection_closed_for_reading?(client) do
:gen_tcp.recv(client, 0) == {:error, :closed}
end
Expand Down
Loading