diff --git a/README.md b/README.md index 64767e8..15b84f4 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,53 @@ -

Other Repository

+# ElixirMQ +Poor man's message queue service written in Elixir-Phoenix. This project is now part of Functional Programming final project. -[Consumer Example](https://github.com/IoriU/consumer-example) +This project implements simple message queue using HTTP Protocol. Due to HTTP's half-duplex nature, consumer are required to provide callback URI when connecting to the service. -

Init Project Guide

-Initializing the project will require the following steps: +Please refer to [Consumer Example](https://github.com/IoriU/consumer-example). -- enter nix shell using `nix-shell shell.nix` -- create the db directory `initdb ./db` (inside your mix project folder) -- start the postgres instance `pg_ctl -o "-k /tmp" -l "$PGDATA/server.log" start` -- create the postgres user `createuser -h /tmp postgres -ds` -- create the db `createdb -h /tmp db` -- add the `/db` folder to your `.gitignore` -- change directory into `cd src` -- follow steps in `src/README.md` to run Phoenix server +## Endpoints + +| **Path** | **Payload** | **Description** | +|:-----------------------------:|:---------------------------------------------------------------:|:--------------------------:| +| **POST** `/api/message_queue` | `{ "topic" : "haskell" , "message" : "haskell is functional" }` | Send a message to a topic. | +| **POST** `/api/consumer` | `{ "topic" : "haskell" , "url_callback" : "example.com/api" }` | Subscribe to a topic. | + +## Pages + +- List of consumers `/api/consumers` +- List consumers by topic `/api/consumers/topic/` + +## Development Guide + +The project use [Nix Package Manager](https://nixos.org/) to make reproducible development environment. If you're new to Nix, please follow [this](https://nixos.org/download.html) guide to install Nix Package manager into your system. + +### Initializing Project + +If this is your first time, you are required to initialize the project: + +1. enter nix shell using `nix-shell shell.nix` +2. create the db directory `initdb ./db` (inside your mix project folder) +3. start the postgres instance `pg_ctl -o "-k /tmp" -l "$PGDATA/server.log" start` +4. create the postgres user `createuser -h /tmp postgres -ds` +5. create the db `createdb -h /tmp db` +6. add the `/db` folder to your `.gitignore` +7. change directory into `cd src` +8. follow steps in `src/README.md` to run Phoenix server +9. Happy developing! + +### Developing Project + +Everytime you wants to start developing, you have to run the postgres instance. + +```sh +pg_ctl -o "-k /tmp" -l "$PGDATA/server.log" start +``` + +Don't forget to close the postgres socket when you finished -Don't forget to close the postgres socket upon exit ```sh pg_ctl -o "-k /tmp" -l "$PGDATA/server.log" stop exit # to exit nix-shell ``` +(c) 2022 diff --git a/nixpacks.toml b/nixpacks.toml new file mode 100644 index 0000000..728b52b --- /dev/null +++ b/nixpacks.toml @@ -0,0 +1,13 @@ +# nixpacks.toml + +providers = ['elixir'] + +[phases.setup] +nixPkgs = ['...', 'nodejs', 'yarn', 'python', 'postgresql'] + +[phases.install] +dependsOn = ['setup'] +cmds = ['nix-shell shell.nix', 'initdb ./db', 'pg_ctl -o "-k /tmp" -l "$PGDATA/server.log" start', 'createuser -h /tmp postgres -ds', 'createdb -h /tmp db', 'cd src && mix deps.get', 'cd src && mix ecto.setup'] + +[phases.build] +cmd = 'cd sec && mix phx.server' diff --git a/src/README.md b/src/README.md index 4a4fd74..ccf6c0f 100644 --- a/src/README.md +++ b/src/README.md @@ -1,4 +1,4 @@ -# Src +# ElixirMQ Phoenix Server To start your Phoenix server: diff --git a/src/lib/src/application.ex b/src/lib/src/application.ex index 1d775cb..8733302 100644 --- a/src/lib/src/application.ex +++ b/src/lib/src/application.ex @@ -15,9 +15,10 @@ defmodule Src.Application do # Start the PubSub system {Phoenix.PubSub, name: Src.PubSub}, # Start the Endpoint (http/https) - SrcWeb.Endpoint + SrcWeb.Endpoint, # Start a worker by calling: Src.Worker.start_link(arg) # {Src.Worker, arg} + Src.PublishScheduler ] # See https://hexdocs.pm/elixir/Supervisor.html diff --git a/src/lib/src/callback_client.ex b/src/lib/src/callback_client.ex index 688e2a6..d732e7d 100644 --- a/src/lib/src/callback_client.ex +++ b/src/lib/src/callback_client.ex @@ -2,13 +2,22 @@ defmodule Src.CallbackClient do use HTTPoison.Base def send_callback(url, body) do - case post(url, body) do + headers = [{"Content-type", "application/json"}] + response = post(url, Poison.encode!(body), headers, []) + + case response do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> - IO.puts body - {:ok, %HTTPoison.Response{status_code: 404}} -> - IO.puts "Not found" + IO.puts(body) + {:success} + + {:ok, %HTTPoison.Response{}} -> + IO.puts("Request Failed") + {:do_not_retry} + {:error, %HTTPoison.Error{reason: reason}} -> - IO.inspect reason + IO.inspect(reason) + IO.puts("to be scheduled to retry") + {:do_retry} end end end diff --git a/src/lib/src/message_queue.ex b/src/lib/src/message_queue.ex index d14e610..31157ec 100644 --- a/src/lib/src/message_queue.ex +++ b/src/lib/src/message_queue.ex @@ -10,16 +10,19 @@ defmodule Src.MessageQueue do end def add_message(message, topic) do - GenServer.call(topic, {:add_message, message}, :infinity) + GenServer.call(topic, {:add_message, topic, message}, :infinity) end - def handle_call({:add_message, message}, _from, state) do + def handle_call({:add_message, topic, message}, _from, state) do # add message to queue state = [message | state] - # wait for previous job to finish - Process.sleep(5000) - # do a job + # insert to sender scheduler + Enum.each( + Src.Queue.filter_consumer_by_topic("#{topic}"), + fn x -> GenServer.call(Src.PublishScheduler, {:store, %{url: x.url_callback, body: message, retries: 0}}) end + ) IO.puts("Message: #{message}") {:reply, :ok, state} end + end diff --git a/src/lib/src/publish_scheduler.ex b/src/lib/src/publish_scheduler.ex new file mode 100644 index 0000000..8467099 --- /dev/null +++ b/src/lib/src/publish_scheduler.ex @@ -0,0 +1,55 @@ +defmodule Src.PublishScheduler do + use GenServer + + @send_interval_ms 500 + @retry_limit 5 + + def start_link(_opts) do + GenServer.start_link(__MODULE__, [], name: __MODULE__) + end + + @impl true + def init(queue) do + Process.flag(:trap_exit, true) + timer = Process.send_after(self(), :check, @send_interval_ms) + + {:ok, %{queue: queue, timer: timer}} + end + + @impl true + def handle_call({:store, message}, _from, %{queue: queue, timer: timer} = _state) do + new_queue = [message | queue] + {:reply, :ok, %{_state | queue: new_queue}} + end + + @impl true + def handle_info(:check, %{queue: queue, timer: timer} = state) do + new_timer = Process.send_after(self(), :check, @send_interval_ms) + count = Enum.count(queue) + if count > 0 do + msg = Enum.fetch!(queue, count - 1) + new_queue = Enum.drop(queue, -1) + spawn fn -> send_message(msg) end + {:noreply, %{queue: new_queue, timer: new_timer}} + else + {:noreply, %{state | timer: new_timer}} + end + end + + defp send_message(%{url: url, body: body, retries: retries} = message) do + res = Src.CallbackClient.send_callback(url, body) + case res do + {:success} -> {:success} + {:do_not_retry} -> {:do_not_retry} + {:do_retry} -> + if retries > @retry_limit do + IO.puts("Retry limit reached") + {:do_not_retry} + else + GenServer.call(Src.PublishScheduler, {:store, %{url: url, body: body, retries: retries + 1}}) + {:do_retry} + end + end + end + +end diff --git a/src/lib/src/publisher.ex b/src/lib/src/publisher.ex deleted file mode 100644 index 60a8945..0000000 --- a/src/lib/src/publisher.ex +++ /dev/null @@ -1,13 +0,0 @@ -defmodule Publisher do - - @impl true - def publish_message(body) do - send_message(body) - {:ok} - end - - defp send_message(body) do - Enum.each(Src.Queue.list_consumers, fn x -> Src.CallbackClient.send_callback(x.url_callback, body) end) - end - -end diff --git a/src/lib/src_web/router.ex b/src/lib/src_web/router.ex index ae748b5..7501e20 100644 --- a/src/lib/src_web/router.ex +++ b/src/lib/src_web/router.ex @@ -12,6 +12,7 @@ defmodule SrcWeb.Router do pipeline :api do plug :accepts, ["json"] + plug CORSPlug, origin: ["https://elixir-queue-production.up.railway.app", "https://consumer-example-production.up.railway.app", "http://127.0.0.1"] end scope "/", SrcWeb do diff --git a/src/mix.exs b/src/mix.exs index a2ee2d7..56c89e1 100644 --- a/src/mix.exs +++ b/src/mix.exs @@ -50,7 +50,8 @@ defmodule Src.MixProject do {:jason, "~> 1.2"}, {:plug_cowboy, "~> 2.5"}, {:httpoison, "~> 1.8"}, - {:poison, "~> 5.0"} + {:poison, "~> 5.0"}, + {:cors_plug, "~> 3.0"} ] end diff --git a/src/mix.lock b/src/mix.lock index 6f68b62..5c62fdb 100644 --- a/src/mix.lock +++ b/src/mix.lock @@ -2,6 +2,7 @@ "castore": {:hex, :castore, "0.1.18", "deb5b9ab02400561b6f5708f3e7660fc35ca2d51bfc6a940d2f513f89c2975fc", [:mix], [], "hexpm", "61bbaf6452b782ef80b33cdb45701afbcf0a918a45ebe7e73f1130d661e66a06"}, "certifi": {:hex, :certifi, "2.9.0", "6f2a475689dd47f19fb74334859d460a2dc4e3252a3324bd2111b8f0429e7e21", [:rebar3], [], "hexpm", "266da46bdb06d6c6d35fde799bcb28d36d985d424ad7c08b5bb48f5b5cdd4641"}, "connection": {:hex, :connection, "1.1.0", "ff2a49c4b75b6fb3e674bfc5536451607270aac754ffd1bdfe175abe4a6d7a68", [:mix], [], "hexpm", "722c1eb0a418fbe91ba7bd59a47e28008a189d47e37e0e7bb85585a016b2869c"}, + "cors_plug": {:hex, :cors_plug, "3.0.3", "7c3ac52b39624bc616db2e937c282f3f623f25f8d550068b6710e58d04a0e330", [:mix], [{:plug, "~> 1.13", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "3f2d759e8c272ed3835fab2ef11b46bddab8c1ab9528167bd463b6452edf830d"}, "cowboy": {:hex, :cowboy, "2.9.0", "865dd8b6607e14cf03282e10e934023a1bd8be6f6bacf921a7e2a96d800cd452", [:make, :rebar3], [{:cowlib, "2.11.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "2c729f934b4e1aa149aff882f57c6372c15399a20d54f65c8d67bef583021bde"}, "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"}, "cowlib": {:hex, :cowlib, "2.11.0", "0b9ff9c346629256c42ebe1eeb769a83c6cb771a6ee5960bd110ab0b9b872063", [:make, :rebar3], [], "hexpm", "2b3e9da0b21c4565751a6d4901c20d1b4cc25cbb7fd50d91d2ab6dd287bc86a9"},