From ce5449abe44981773cbf650e95bbd571a7e2d628 Mon Sep 17 00:00:00 2001 From: Daniel Hedlund Date: Wed, 15 May 2019 13:32:07 -0700 Subject: [PATCH] Initial code commit --- .formatter.exs | 4 ++ .gitignore | 27 ++++++-- LICENSE | 21 ------ LICENSE.md | 9 +++ README.md | 25 +++++++ config/config.exs | 30 +++++++++ lib/deferrable.ex | 139 +++++++++++++++++++++++++++++++++++++++ mix.exs | 64 ++++++++++++++++++ mix.lock | 7 ++ test/deferrable_test.exs | 137 ++++++++++++++++++++++++++++++++++++++ test/test_helper.exs | 1 + 11 files changed, 437 insertions(+), 27 deletions(-) create mode 100644 .formatter.exs delete mode 100644 LICENSE create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 config/config.exs create mode 100644 lib/deferrable.ex create mode 100644 mix.exs create mode 100644 mix.lock create mode 100644 test/deferrable_test.exs create mode 100644 test/test_helper.exs diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000..d2cda26 --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/.gitignore b/.gitignore index 86e4c3f..b99de41 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,24 @@ -/_build -/cover -/deps -/doc +# 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 -*.beam -/config/*.secret.exs + +# Ignore package tarball (built via "mix hex.build"). +deferrable-*.tar + diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 6910e96..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Peek - -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. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..f1e8d16 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright 2019 Peek Travel, Inc. + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0fe6dc1 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Deferrable + +**This is pre-release and will go through a couple more revisions before considered stable.** + +Library for deferring execution of code until the completion of a transaction block. + +Similar in concept to database transactions with support for nesting and partial-rollbacks. + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `deferrable` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [ + {:deferrable, "~> 0.0.1"} + ] +end +``` + +Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) +and published on [HexDocs](https://hexdocs.pm). Once published, the docs can +be found at [https://hexdocs.pm/deferrable](https://hexdocs.pm/deferrable). + diff --git a/config/config.exs b/config/config.exs new file mode 100644 index 0000000..156176c --- /dev/null +++ b/config/config.exs @@ -0,0 +1,30 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Mix.Config module. +use Mix.Config + +# This configuration is loaded before any dependency and is restricted +# to this project. If another project depends on this project, this +# file won't be loaded nor affect the parent project. For this reason, +# if you want to provide default values for your application for +# 3rd-party users, it should be done in your "mix.exs" file. + +# You can configure your application as: +# +# config :deferrable, key: :value +# +# and access this configuration in your application as: +# +# Application.get_env(:deferrable, :key) +# +# You can also configure a 3rd-party app: +# +# config :logger, level: :info +# + +# It is also possible to import configuration files, relative to this +# directory. For example, you can emulate configuration per environment +# by uncommenting the line below and defining dev.exs, test.exs and such. +# Configuration from the imported file will override the ones defined +# here (which is why it is important to import them last). +# +# import_config "#{Mix.env()}.exs" diff --git a/lib/deferrable.ex b/lib/deferrable.ex new file mode 100644 index 0000000..50adc99 --- /dev/null +++ b/lib/deferrable.ex @@ -0,0 +1,139 @@ +defmodule Peek.Deferrable do + @moduledoc """ + Allows deferring of function calls until a transaction succeeds. + + ## Example + + Deferrable.transaction(fn -> + Deferrable.defer(fn -> "do something later" end) + + {:ok, "result"} + end) + """ + + @stack_key :deferrable_stack + + def defer(fun) do + case stack_ref() do + :no_stack -> fun.() + ref -> send(self(), {:deferred, ref, fun}) + end + end + + def transaction(fun) do + stack = push_stack(make_ref()) + + try do + result = + case {stack, fun.()} do + {[_top], {:ok, result}} -> + process_deferred() + {:ok, result} + + {_stack, {:ok, result}} -> + {:ok, result} + + {_stack, {:error, reason}} -> + clear_deferred(stack) + {:error, reason} + end + + result + rescue + err -> + clear_deferred(stack) + + reraise(err, __STACKTRACE__) + after + pop_stack() + end + end + + def process_deferred, do: do_process_deferred([]) + + defp do_process_deferred(results) do + receive do + {:deferred, _ref, fun} -> + try do + do_process_deferred([fun.() | results]) + rescue + # FIXME: Don't clear all later deferred functions when one fails. e.g. losing availability messages + # if another message fails to publish. Running the deferred functions inside tasks could be a way to solve + # this, so each one can fail on its own, raise, and have its own stack-trace. + err -> + clear_deferred() + reraise(err, __STACKTRACE__) + end + after + 0 -> Enum.reverse(results) + end + end + + def clear_deferred do + case stack() do + :no_stack -> :ok + stack -> clear_deferred(stack) + end + end + + defp clear_deferred([]), do: :ok + + defp clear_deferred([ref | _rest] = stack) do + child_tree = get_in(tree(), Enum.reverse(stack)) + child_refs = all_keys(child_tree) + do_clear_deferred([ref | child_refs]) + end + + defp do_clear_deferred([]), do: :ok + + defp do_clear_deferred([ref | rest] = refs) do + receive do + {:deferred, ^ref, _fun} -> do_clear_deferred(refs) + after + 0 -> do_clear_deferred(rest) + end + end + + defp stack_ref do + case Process.get(@stack_key, :no_stack) do + {[ref | _rest], _popped} -> ref + {[], _popped} -> :no_stack + :no_stack -> :no_stack + end + end + + defp stack do + with {stack, _tree} <- Process.get(@stack_key, :no_stack) do + stack + end + end + + defp tree do + with {_stack, tree} <- Process.get(@stack_key, :no_stack) do + tree + end + end + + defp push_stack(ref) do + {stack, tree} = Process.get(@stack_key, {[], %{}}) + stack = [ref | stack] + tree = put_in(tree, Enum.reverse(stack), %{}) + Process.put(@stack_key, {stack, tree}) + stack + end + + defp pop_stack do + with {[_ref | rest], tree} <- Process.get(@stack_key, :no_stack) do + Process.put(@stack_key, {rest, tree}) + :ok + else + {[], _} -> {:error, :top_of_stack} + end + end + + defp all_keys(map) do + Enum.flat_map(map, fn {key, child_map} -> + [key | all_keys(child_map)] + end) + end +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..251197d --- /dev/null +++ b/mix.exs @@ -0,0 +1,64 @@ +defmodule Deferrable.MixProject do + use Mix.Project + + @version "0.0.1" + @source_url "https://github.com/peek-travel/deferrable" + + def project do + [ + app: :deferrable, + version: @version, + elixir: "~> 1.7", + elixirc_paths: elixirc_paths(Mix.env()), + start_permanent: Mix.env() == :prod, + deps: deps(), + docs: docs(), + description: description(), + package: package() + ] + end + + # Run "mix help compile.app" to learn about applications. + def application do + [ + extra_applications: [] + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + defp docs do + [ + main: "Deferrable", + source_ref: @version, + source_url: @source_url, + extras: ["README.md", "LICENSE.md"] + ] + end + + defp description do + """ + Library for deferring execution of code until the completion of a transaction block. + """ + end + + defp package do + [ + files: ["lib", ".formatter.exs", "mix.exs", "README.md", "LICENSE.md"], + maintainers: ["Daniel Hedlund ", "Chris Dosé "], + licenses: ["MIT"], + links: %{ + "GitHub" => @source_url, + "Readme" => "#{@source_url}/blob/#{@version}/README.md" + } + ] + end + + # Run "mix help deps" to learn about dependencies. + defp deps do + [ + {:ex_doc, "~> 0.20", only: :dev, runtime: false} + ] + end +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..4c499e8 --- /dev/null +++ b/mix.lock @@ -0,0 +1,7 @@ +%{ + "earmark": {:hex, :earmark, "1.3.2", "b840562ea3d67795ffbb5bd88940b1bed0ed9fa32834915125ea7d02e35888a5", [:mix], [], "hexpm"}, + "ex_doc": {:hex, :ex_doc, "0.20.2", "1bd0dfb0304bade58beb77f20f21ee3558cc3c753743ae0ddbb0fd7ba2912331", [:mix], [{:earmark, "~> 1.3", [hex: :earmark, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.10", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm"}, + "makeup": {:hex, :makeup, "0.8.0", "9cf32aea71c7fe0a4b2e9246c2c4978f9070257e5c9ce6d4a28ec450a839b55f", [:mix], [{:nimble_parsec, "~> 0.5.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm"}, + "makeup_elixir": {:hex, :makeup_elixir, "0.13.0", "be7a477997dcac2e48a9d695ec730b2d22418292675c75aa2d34ba0909dcdeda", [:mix], [{:makeup, "~> 0.8", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm"}, + "nimble_parsec": {:hex, :nimble_parsec, "0.5.0", "90e2eca3d0266e5c53f8fbe0079694740b9c91b6747f2b7e3c5d21966bba8300", [:mix], [], "hexpm"}, +} diff --git a/test/deferrable_test.exs b/test/deferrable_test.exs new file mode 100644 index 0000000..417977d --- /dev/null +++ b/test/deferrable_test.exs @@ -0,0 +1,137 @@ +defmodule Peek.DeferrableTest do + use ExUnit.Case, async: true + + alias Peek.Deferrable + + describe "defer/1" do + test "executes the given function immediately if not inside a transaction" do + assert "hello" == Deferrable.defer(fn -> "hello" end) + end + end + + describe "process_deferred/0" do + test "does nothing if not inside a transaction" do + assert [] == Deferrable.process_deferred() + end + end + + describe "transaction/1" do + test "defers execution of the given function until after the transaction completes" do + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :hello) end) + + refute_received :hello + + {:ok, "result"} + end) + + assert_received :hello + end + + test "allows calls to process_deferred/0 to execute all deferred functions to this point" do + Deferrable.transaction(fn -> + Deferrable.defer(fn -> "hello" end) + Deferrable.defer(fn -> "world" end) + + assert ["hello", "world"] == Deferrable.process_deferred() + + Deferrable.defer(fn -> send(self(), :goodbye) end) + + {:ok, :ok} + end) + + assert_received :goodbye + end + + test "can clear all deferred functions to this point" do + Deferrable.transaction(fn -> + Deferrable.defer(fn -> "hello" end) + Deferrable.defer(fn -> raise "world" end) + Deferrable.clear_deferred() + + assert [] == Deferrable.process_deferred() + + {:ok, "result"} + end) + end + + test "raising in a deferred function clears all subsequent deferred functions" do + Deferrable.transaction(fn -> + Deferrable.defer(fn -> raise "hello" end) + Deferrable.defer(fn -> send(self(), :world) end) + + assert_raise RuntimeError, "hello", fn -> + Deferrable.process_deferred() + end + + refute_received :world + + {:ok, "result"} + end) + end + + test "handles nested transactions" do + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :level1) end) + + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :level2) end) + + {:ok, _} = + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :level3) end) + + {:ok, "whatever"} + end) + + _error_ignored = + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :level3_failed) end) + + {:error, "oh no!"} + end) + + {:ok, "whatever"} + end) + + {:ok, "whatever"} + end) + + assert_received :level1 + assert_received :level2 + assert_received :level3 + refute_received :level3_failed + end + + test "transaction success" do + assert {:ok, "something"} == + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :hello) end) + {:ok, "something"} + end) + + assert_received :hello + end + + test "transaction failure" do + assert {:error, "oh no!"} == + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :hello) end) + {:error, "oh no!"} + end) + + refute_received :hello + end + + test "transaction raise" do + assert_raise RuntimeError, "oh no!", fn -> + Deferrable.transaction(fn -> + Deferrable.defer(fn -> send(self(), :hello) end) + raise "oh no!" + end) + end + + refute_received :hello + end + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start()