From abeb6ec91dcd8ddfcbc0f093835c8acbe6bef13c Mon Sep 17 00:00:00 2001 From: hori75 Date: Wed, 30 Nov 2022 23:50:12 +0700 Subject: [PATCH 01/12] add feature to send message to consumer with matching topic --- src/lib/src/callback_client.ex | 3 ++- src/lib/src/message_queue.ex | 5 +++-- src/lib/src/publisher.ex | 13 ------------- 3 files changed, 5 insertions(+), 16 deletions(-) delete mode 100644 src/lib/src/publisher.ex diff --git a/src/lib/src/callback_client.ex b/src/lib/src/callback_client.ex index 688e2a6..3a11215 100644 --- a/src/lib/src/callback_client.ex +++ b/src/lib/src/callback_client.ex @@ -2,7 +2,8 @@ defmodule Src.CallbackClient do use HTTPoison.Base def send_callback(url, body) do - case post(url, body) do + headers = [{"Content-type", "application/json"}] + case post(url, Poison.encode!(%{"message": body}), headers, []) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> IO.puts body {:ok, %HTTPoison.Response{status_code: 404}} -> diff --git a/src/lib/src/message_queue.ex b/src/lib/src/message_queue.ex index d14e610..f2a86a7 100644 --- a/src/lib/src/message_queue.ex +++ b/src/lib/src/message_queue.ex @@ -10,16 +10,17 @@ 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 IO.puts("Message: #{message}") + Enum.each(Src.Queue.filter_consumer_by_topic("#{topic}"), fn x -> Src.CallbackClient.send_callback(x.url_callback, message) end) {:reply, :ok, state} 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 From fc8d484d5d9ee3509e4cf759541a5165e0412c9c Mon Sep 17 00:00:00 2001 From: Dennis Al Baihaqi Walangadi Date: Fri, 2 Dec 2022 11:38:40 +0700 Subject: [PATCH 02/12] feat(deploy): add railway nixpacks deployment --- nixpacks.toml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 nixpacks.toml 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' From e6c55f1273868309ccf590a60e47af20e4ea732b Mon Sep 17 00:00:00 2001 From: Dennis Al Baihaqi Walangadi Date: Fri, 2 Dec 2022 14:29:45 +0700 Subject: [PATCH 03/12] fix: remove sleep and improve logs --- src/lib/src/message_queue.ex | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/lib/src/message_queue.ex b/src/lib/src/message_queue.ex index f2a86a7..ac3a174 100644 --- a/src/lib/src/message_queue.ex +++ b/src/lib/src/message_queue.ex @@ -16,11 +16,9 @@ defmodule Src.MessageQueue 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 - IO.puts("Message: #{message}") Enum.each(Src.Queue.filter_consumer_by_topic("#{topic}"), fn x -> Src.CallbackClient.send_callback(x.url_callback, message) end) + IO.puts("Message: #{message}") {:reply, :ok, state} end end From bcb2aaca4c8b9e2de81bddbad1c2e0b1b4f9e8c7 Mon Sep 17 00:00:00 2001 From: Taufiq Hadi Pratama Date: Tue, 6 Dec 2022 12:38:56 +0700 Subject: [PATCH 04/12] Added CORS policy --- src/lib/src_web/router.ex | 1 + src/mix.exs | 3 ++- src/mix.lock | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/lib/src_web/router.ex b/src/lib/src_web/router.ex index ae748b5..2869a21 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: "*" 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"}, From b6ef4113ca5b7255356973e8075faa84b4264955 Mon Sep 17 00:00:00 2001 From: Taufiq Hadi Pratama Date: Tue, 6 Dec 2022 14:18:00 +0700 Subject: [PATCH 05/12] CORS policy origin to array --- src/lib/src_web/router.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/src_web/router.ex b/src/lib/src_web/router.ex index 2869a21..7ff58fd 100644 --- a/src/lib/src_web/router.ex +++ b/src/lib/src_web/router.ex @@ -12,7 +12,7 @@ defmodule SrcWeb.Router do pipeline :api do plug :accepts, ["json"] - plug CORSPlug, origin: "*" + plug CORSPlug, origin: ["*"] end scope "/", SrcWeb do From 5b0237aa3d76bca284a3c8c8d04eac601518c109 Mon Sep 17 00:00:00 2001 From: Taufiq Hadi Pratama Date: Tue, 6 Dec 2022 15:07:52 +0700 Subject: [PATCH 06/12] CORS policy to regex --- src/lib/src_web/router.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/src_web/router.ex b/src/lib/src_web/router.ex index 7ff58fd..e66611e 100644 --- a/src/lib/src_web/router.ex +++ b/src/lib/src_web/router.ex @@ -12,7 +12,7 @@ defmodule SrcWeb.Router do pipeline :api do plug :accepts, ["json"] - plug CORSPlug, origin: ["*"] + plug CORSPlug, origin: [~r/*/] end scope "/", SrcWeb do From e86dc118a5a2f9665dd0bcb5479b7d2ee7d37e25 Mon Sep 17 00:00:00 2001 From: Taufiq Hadi Pratama Date: Tue, 6 Dec 2022 15:21:19 +0700 Subject: [PATCH 07/12] CORS policy added hardcoded origin --- src/lib/src/callback_client.ex | 2 +- src/lib/src_web/router.ex | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/src/callback_client.ex b/src/lib/src/callback_client.ex index 3a11215..09a5fff 100644 --- a/src/lib/src/callback_client.ex +++ b/src/lib/src/callback_client.ex @@ -3,7 +3,7 @@ defmodule Src.CallbackClient do def send_callback(url, body) do headers = [{"Content-type", "application/json"}] - case post(url, Poison.encode!(%{"message": body}), headers, []) do + case post(url, Poison.encode!(%{message: body}), headers, []) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> IO.puts body {:ok, %HTTPoison.Response{status_code: 404}} -> diff --git a/src/lib/src_web/router.ex b/src/lib/src_web/router.ex index e66611e..7501e20 100644 --- a/src/lib/src_web/router.ex +++ b/src/lib/src_web/router.ex @@ -12,7 +12,7 @@ defmodule SrcWeb.Router do pipeline :api do plug :accepts, ["json"] - plug CORSPlug, origin: [~r/*/] + 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 From 9f12de5ef188a482129b27a25964a322be287b99 Mon Sep 17 00:00:00 2001 From: Taufiq Hadi Pratama Date: Tue, 6 Dec 2022 16:48:34 +0700 Subject: [PATCH 08/12] Added parameter topic for consumer API --- src/lib/src/callback_client.ex | 14 ++++++++++---- src/lib/src/message_queue.ex | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/lib/src/callback_client.ex b/src/lib/src/callback_client.ex index 09a5fff..fa79dd0 100644 --- a/src/lib/src/callback_client.ex +++ b/src/lib/src/callback_client.ex @@ -3,13 +3,19 @@ defmodule Src.CallbackClient do def send_callback(url, body) do headers = [{"Content-type", "application/json"}] - case post(url, Poison.encode!(%{message: body}), headers, []) do + + case post(url, Poison.encode!(body), headers, []) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> - IO.puts body + IO.puts(body) + {:ok, %HTTPoison.Response{status_code: 404}} -> - IO.puts "Not found" + IO.puts("Not found") + {:error, %HTTPoison.Error{reason: reason}} -> - IO.inspect reason + IO.inspect(reason) + + {:ok, %HTTPoison.Response{status_code: 500}} -> + IO.puts("Consumer`s callback server is down") end end end diff --git a/src/lib/src/message_queue.ex b/src/lib/src/message_queue.ex index ac3a174..0ef2c29 100644 --- a/src/lib/src/message_queue.ex +++ b/src/lib/src/message_queue.ex @@ -17,7 +17,7 @@ defmodule Src.MessageQueue do # add message to queue state = [message | state] # do a job - Enum.each(Src.Queue.filter_consumer_by_topic("#{topic}"), fn x -> Src.CallbackClient.send_callback(x.url_callback, message) end) + Enum.each(Src.Queue.filter_consumer_by_topic("#{topic}"), fn x -> Src.CallbackClient.send_callback(x.url_callback, %{topic: topic, message: message}) end) IO.puts("Message: #{message}") {:reply, :ok, state} end From 2ebf2b98dee438c7244cd67eb3c8b4e51e523475 Mon Sep 17 00:00:00 2001 From: hori75 Date: Wed, 7 Dec 2022 11:13:13 +0700 Subject: [PATCH 09/12] add publish scheduler to set send and retry --- src/lib/src/application.ex | 3 +- src/lib/src/callback_client.ex | 14 ++++---- src/lib/src/message_queue.ex | 8 +++-- src/lib/src/publish_scheduler.ex | 55 ++++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 9 deletions(-) create mode 100644 src/lib/src/publish_scheduler.ex 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 fa79dd0..d732e7d 100644 --- a/src/lib/src/callback_client.ex +++ b/src/lib/src/callback_client.ex @@ -3,19 +3,21 @@ defmodule Src.CallbackClient do def send_callback(url, body) do headers = [{"Content-type", "application/json"}] + response = post(url, Poison.encode!(body), headers, []) - case post(url, Poison.encode!(body), headers, []) do + case response do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> IO.puts(body) + {:success} - {:ok, %HTTPoison.Response{status_code: 404}} -> - IO.puts("Not found") + {:ok, %HTTPoison.Response{}} -> + IO.puts("Request Failed") + {:do_not_retry} {:error, %HTTPoison.Error{reason: reason}} -> IO.inspect(reason) - - {:ok, %HTTPoison.Response{status_code: 500}} -> - IO.puts("Consumer`s callback server is down") + 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 0ef2c29..31157ec 100644 --- a/src/lib/src/message_queue.ex +++ b/src/lib/src/message_queue.ex @@ -16,9 +16,13 @@ defmodule Src.MessageQueue do def handle_call({:add_message, topic, message}, _from, state) do # add message to queue state = [message | state] - # do a job - Enum.each(Src.Queue.filter_consumer_by_topic("#{topic}"), fn x -> Src.CallbackClient.send_callback(x.url_callback, %{topic: topic, message: message}) end) + # 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 From e7c72e460dc6182186176d884566f11b87442a2d Mon Sep 17 00:00:00 2001 From: Dennis Al Baihaqi Walangadi Date: Thu, 15 Dec 2022 11:20:45 +0700 Subject: [PATCH 10/12] chore: improve readme --- README.md | 45 ++++++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 64767e8..2ab8b4c 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,41 @@ -

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 +## 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 From 641ea4311d76a88bc351a595eb88b76caef6c518 Mon Sep 17 00:00:00 2001 From: Dennis Al Baihaqi Walangadi <53461759+dnswd@users.noreply.github.com> Date: Thu, 15 Dec 2022 11:22:12 +0700 Subject: [PATCH 11/12] Update README.md --- src/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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: From ca36301a096ec654c59150af4a495c208b08c640 Mon Sep 17 00:00:00 2001 From: Dennis Al Baihaqi Walangadi Date: Thu, 15 Dec 2022 13:24:07 +0700 Subject: [PATCH 12/12] chore: improve documentation --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 2ab8b4c..15b84f4 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,18 @@ This project implements simple message queue using HTTP Protocol. Due to HTTP's Please refer to [Consumer Example](https://github.com/IoriU/consumer-example). +## 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.