Skip to content

Instantly share code, notes, and snippets.

@ream88
Last active February 16, 2023 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ream88/52680fdea14852602db7b6e8e024b1ee to your computer and use it in GitHub Desktop.
Save ream88/52680fdea14852602db7b6e8e024b1ee to your computer and use it in GitHub Desktop.
Run it via: CHAOS=100 ./chaos_server.exs
#!/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