Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
maennchen committed Sep 12, 2018
0 parents commit c120559
Show file tree
Hide file tree
Showing 13 changed files with 543 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[
locals_without_parens: [
dynamic_plug: 1,
dynamic_plug: 2,
dynamic_plug: 3
],
inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
26 changes: 26 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# The directory Mix will write compiled artifacts to.
/_build/

# If you run "mix test --cover", coverage assets end up here.
/cover/

# The directory Mix downloads your dependencies sources to.
/deps/

# Where 3rd-party dependencies like ExDoc output generated docs.
/doc/

# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Ignore package tarball (built via "mix hex.build").
plug_dynamic-*.tar

# Library Stuff
/mix.lock
38 changes: 38 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
language: elixir
sudo: false
env:
- MIX_ENV=test
elixir:
- 1.6
- 1.7
otp_release:
- 21.0
script: mix coveralls.travis
cache:
directories:
- ~/.mix
- ~/.hex
- _build
jobs:
include:
- stage: format
env:
- MIX_ENV=dev
script: mix format --check-formatted
elixir: 1.7
- stage: credo
env:
- MIX_ENV=dev
script: mix credo --strict
elixir: 1.7
- stage: dialyzer
env:
- MIX_ENV=dev
before_script: travis_wait mix dialyzer --plt
script: mix dialyzer --halt-exit-status
elixir: 1.7
- stage: inch
env:
- MIX_ENV=docs
script: mix inch.report
elixir: 1.7
8 changes: 8 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2018, JOSHMARTIN GmbH, Jonatan Männchen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Plug Dynamic

[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/jshmrtn/plug-dynamic/master/LICENSE)
[![Build Status](https://travis-ci.org/jshmrtn/plug-dynamic.svg?branch=master)](https://travis-ci.org/jshmrtn/plug-dynamic)
[![Hex.pm Version](https://img.shields.io/hexpm/v/plug_dynamic.svg?style=flat)](https://hex.pm/packages/plug_dynamic)
[![InchCI](https://inch-ci.org/github/jshmrtn/plug-dynamic.svg?branch=master)](https://inch-ci.org/github/jshmrtn/plug-dynamic)
[![Coverage Status](https://coveralls.io/repos/github/jshmrtn/plug-dynamic/badge.svg?branch=master)](https://coveralls.io/github/jshmrtn/plug-dynamic?branch=master)


Allows registration of every Plug with dynamic configuration.

## Installation

The package can be installed by adding `plug_dynamic` to your list of
dependencies in `mix.exs`:

```elixir
def deps do
[
{:plug_dynamic, "~> 1.0"}
]
end
```

Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). The docs can be found at
[https://hexdocs.pm/plug_dynamic](https://hexdocs.pm/plug_dynamic).
143 changes: 143 additions & 0 deletions lib/plug_dynamic.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
defmodule PlugDynamic do
@moduledoc """
Moves any plugs configuration from compile time to runtime.
### Usage Example (plain)
defmodule Acme.Endpoint do
use Plug.Builder
plug(
PlugDynamic,
plug: Plug.IpWhitelist.IpWhitelistEnforcer,
options: {__MODULE__, :ip_whitelist_options, 0},
reevaluate: :first_usage
)
def ip_whitelist_options,
do: Application.fetch_env!(:acme, Plug.IpWhitelist.IpWhitelistEnforcer)
end
### Usage Example (macro)
defmodule Acme.Endpoint do
use Plug.Builder
use PlugDynamic
dynamic_plug Plug.IpWhitelist.IpWhitelistEnforcer, [reevaluate: :first_usage] do
Application.fetch_env!(:acme, Plug.IpWhitelist.IpWhitelistEnforcer)
end
end
### Options
* `options` - anonymous function or `{Module, :function, [args]}` tuple to fetch the configuration
* `reevaluate` - default: `:first_usage` - one of the following values
- `:first_usage` - Evaluate Options when it is used for the first time. The resulting value will be cached in ets.
- `:always` - Evaluate Options for every request. (Attention: This can cause a severe performance impact.)
"""

@behaviour Plug

alias Plug.Conn
alias PlugDynamic.{Builder, Storage}

require Logger

@type options_fetcher :: (() -> any) | {atom, atom, [any]} | mfa
@type reevaluate :: :first_usage | :always
@type plug :: atom

@typep options_fetcher_normalized :: (() -> any)

@enforce_keys [:options_fetcher, :reevaluate, :plug, :reference]
defstruct @enforce_keys

defmacro __using__ do
quote do
import unquote(Builder), only: [dynamic_plug: 1, dynamic_plug: 2, dynamic_plug: 3]
end
end

@impl Plug
@doc false
def init(options) do
plug = Keyword.fetch!(options, :plug)

%__MODULE__{
plug: plug,
options_fetcher: options |> Keyword.get(:options, {__MODULE__, :empty_opts, 0}),
reevaluate: options |> Keyword.get(:reevaluate, :first_usage),
reference: :"#{plug}.#{inspect(make_ref())}"
}
end

@impl Plug
@doc false
def call(%Conn{} = conn, %{reevaluate: :always, plug: plug, options_fetcher: options_fetcher}),
do: plug.call(conn, plug.init(normalize_options_fetcher(options_fetcher).()))

def call(%Conn{} = conn, %{
reevaluate: :first_usage,
plug: plug,
options_fetcher: options_fetcher,
reference: reference
}) do
options = fetch_or_create_options(plug, reference, options_fetcher)
plug.call(conn, options)
end

@spec fetch_or_create_options(
plug :: atom,
reference :: atom,
options_fetcher :: options_fetcher
) :: any
defp fetch_or_create_options(plug, reference, options_fetcher) do
reference
|> Storage.fetch()
|> case do
{:ok, options} ->
options

:error ->
options = plug.init(normalize_options_fetcher(options_fetcher).())

Logger.debug(fn ->
"Options for Plug `#{inspect(plug)}` (#{inspect(reference, pretty: true)}) not found, storing"
end)

Storage.store(reference, options)

options
end
end

@spec normalize_options_fetcher(fun :: options_fetcher) :: options_fetcher_normalized
defp normalize_options_fetcher(fun) when is_function(fun, 0), do: fun

defp normalize_options_fetcher(fun) when is_function(fun),
do: raise("Option fetching function must have 0 arity")

defp normalize_options_fetcher({module, function, arguments})
when is_atom(module) and is_atom(function) and is_list(arguments),
do: fn -> apply(module, function, arguments) end

if function_exported?(Function, :capture, 2) do
defp normalize_options_fetcher({module, function, 0})
when is_atom(module) and is_atom(function),
do: Function.capture(module, function, 0)
else
defp normalize_options_fetcher({module, function, 0})
when is_atom(module) and is_atom(function),
do: fn -> apply(module, function, []) end
end

defp normalize_options_fetcher({module, function, arity})
when is_atom(module) and is_atom(function) and is_integer(0) and arity > 0,
do: raise("Option fetching function must have 0 arity")

@doc false
@spec empty_opts :: []
def empty_opts, do: []
end
15 changes: 15 additions & 0 deletions lib/plug_dynamic/application.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
defmodule PlugDynamic.Application do
@moduledoc false

use Application

alias PlugDynamic.Storage

def start(_type, _args),
do:
Supervisor.start_link(
[Storage],
strategy: :one_for_one,
name: PlugDynamic.Supervisor
)
end
53 changes: 53 additions & 0 deletions lib/plug_dynamic/builder.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
defmodule PlugDynamic.Builder do
@moduledoc """
Exposes Plug Builder Macros
"""

defmacro dynamic_plug(plug, config \\ [], options \\ [])

defmacro dynamic_plug(plug, [do: block], []) do
config = [plug: plug]
{fun_definition, ref} = inplace_config(plug, block)

[
fun_definition,
quote bind_quoted: [config: config, plug: plug, ref: ref] do
plug(PlugDynamic, config ++ [options: {__MODULE__, :__dynamic_plug_config, [plug, ref]}])
end
]
end

defmacro dynamic_plug(plug, config, do: block) do
config = Keyword.put_new(config, :plug, plug)
{fun_definition, ref} = inplace_config(plug, block)

[
fun_definition,
quote bind_quoted: [config: config, plug: plug, ref: ref] do
plug(PlugDynamic, config ++ [options: {__MODULE__, :__dynamic_plug_config, [plug, ref]}])
end
]
end

defmacro dynamic_plug(plug, config, []) do
config = Keyword.put_new(config, :plug, plug)

quote bind_quoted: [config: config] do
plug(PlugDynamic, config)
end
end

defp inplace_config(plug, block) do
ref = :"#{inspect(make_ref())}"

fun_definition =
quote do
@doc false
def __dynamic_plug_config(unquote(plug), unquote(ref)) do
unquote(block)
end
end

{fun_definition, ref}
end
end
68 changes: 68 additions & 0 deletions lib/plug_dynamic/storage.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
defmodule PlugDynamic.Storage do
@moduledoc false
# Store Options so that they do not have to be re-evaluated

use GenServer

@server __MODULE__

@type t :: %__MODULE__{
table_name: atom
}

@enforce_keys [:table_name]
defstruct @enforce_keys

@doc false
@spec start_link(options :: Keyword.t()) :: GenServer.on_start()
def start_link(options),
do: GenServer.start_link(__MODULE__, options, name: Keyword.get(options, :name, @server))

@doc false
@impl GenServer
@spec init(options :: Keyword.t()) :: {:ok, t}
def init(options),
do:
{:ok,
%__MODULE__{
table_name: options |> Keyword.get(:name, @server) |> table_name |> ets_table
}}

@doc false
@impl GenServer
@spec handle_cast(request :: {:store, reference :: atom, options :: any}, t) :: {:noreply, t}
def handle_cast({:store, reference, options}, %__MODULE__{table_name: table_name} = state) do
:ets.insert(table_name, {reference, options})
{:noreply, state}
end

@doc false
@spec fetch(server :: GenServer.name(), reference :: atom) :: {:ok, any} | :error
def fetch(server \\ @server, reference) when is_atom(reference) do
server
|> table_name
|> :ets.lookup(reference)
|> case do
[{^reference, options}] -> {:ok, options}
_ -> :error
end
end

@doc false
@spec store(server :: GenServer.name(), reference :: atom, options :: any) :: :ok
def store(server \\ @server, reference, options) when is_atom(reference),
do: GenServer.cast(server, {:store, reference, options})

@spec ets_table(table_name :: atom) :: atom
defp ets_table(table_name), do: :ets.new(table_name, [:protected, :ordered_set, :named_table])

@spec table_name(server :: GenServer.name()) :: atom
defp table_name(server)
defp table_name(server) when is_atom(server), do: Module.concat(server, Table)

defp table_name({:global, server}) when is_atom(server),
do: {:global, Module.concat(server, Table)}

defp table_name({:via, _, server}) when is_atom(server),
do: raise("Server is not supported with :via name")
end
Loading

0 comments on commit c120559

Please sign in to comment.