Last active
February 16, 2023 14:03
-
-
Save ream88/52680fdea14852602db7b6e8e024b1ee to your computer and use it in GitHub Desktop.
Run it via: CHAOS=100 ./chaos_server.exs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env elixir | |
# This is a small HTTP server that accepts requests and is designed to randomly | |
# fail, allowing other software to be tested for robustness. | |
Mix.install([ | |
{:bandit, "~> 0.6.8"}, | |
{:plug, "~> 1.14"} | |
]) | |
defmodule ChaosServer do | |
import Plug.Conn | |
require Logger | |
def init(opts) do | |
opts | |
|> Keyword.put_new(:chaos, 30) | |
|> tap(fn opts -> | |
Logger.info("ChaosServer will crash #{Keyword.fetch!(opts, :chaos)}% of the requests") | |
end) | |
end | |
def call(conn, opts) do | |
if crash?(opts) do | |
raise RuntimeError | |
else | |
conn | |
|> put_resp_content_type("text/plain") | |
|> send_resp(200, "") | |
end | |
end | |
defp crash?(opts) do | |
Enum.random(1..100) <= Keyword.fetch!(opts, :chaos) | |
end | |
end | |
Bandit.start_link( | |
plug: {ChaosServer, chaos: String.to_integer(System.get_env("CHAOS", "30"))}, | |
options: [port: 4000] | |
) | |
Process.sleep(:infinity) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment