Guest User

Untitled

a guest
Mar 30th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. defmodule SageExample do
  2. import Sage
  3. require Logger
  4.  
  5. # It is better to build Saga struct in a module attribute,
  6. # we don't need to spend resources each time we want to execute it
  7. @create_and_subscribe_user_sage
  8. new()
  9. |> run(:user, &create_user/2)
  10. |> run(:plans, &fetch_subscription_plans/2)
  11. |> run(:subscription, &create_subscription/2, &delete_subscription/3)
  12. |> run_async(:delivery, &schedule_delivery/2, &delete_delivery_from_schedule/3)
  13. |> run_async(:receipt, &send_email_receipt/2, &send_excuse_for_email_receipt/3)
  14. |> run(:update_user, &set_plan_for_a_user/2)
  15. |> finally(&acknowledge_job/2)
  16.  
  17. def create_and_subscribe_user(attrs) do
  18. Sage.transaction(@create_and_subscribe_user_sage, Repo, attrs)
  19. end
  20.  
  21. # Transaction callback receives previously created effects
  22. # and attributes passed to `execute/2` or `transaction/3`
  23. def create_user(_effects, attrs) do
  24. # We can use raw insert if we expect Sage to be wrapped in a transaction,
  25. # because DB-related effects would be compensated on transaction rollback
  26. Repo.insert(%SageExample.User{login: attrs["login"], password: attrs["password"]})
  27. end
  28.  
  29. # .. other transaction callbacks
  30.  
  31. # Steps have access to effects created on previous steps
  32. def create_subscription(%{user: user}, attrs) do
  33. BillingAPI.subscribe_user(user, plan: attrs["plan"])
  34. end
  35.  
  36. # If we failed on this step because of timeout of external service, let's keep retrying
  37. def delete_subscription(nil, {:subscription, _reason}, _attrs) do
  38. {:retry, retry_limit: 5}
  39. end
  40.  
  41. # Cleanup effect created by create_subscription/2
  42. def delete_subscription(_subscription_or_nil, _errorred_step_name_and_reason, _attrs) do
  43. Logger.error("Failed to create subscription because of #{inspect(reason)}")
  44. # We must delete all subscriptions for a newly created user,
  45. # because we don't know if it was actually created on third-party service or not
  46. BillingAPI.Subscription.delete_all_by_email(attrs["email"])
  47. end
  48.  
  49. # .. other transaction callbacks
  50.  
  51. def acknowledge_job(:ok, attrs) do
  52. Logger.info("Successfully created user #{attrs["email"]}")
  53. end
  54.  
  55. def acknowledge_job(_error, attrs) do
  56. Logger.warn("Failed to create user #{attrs["email"]}")
  57. end
  58. end
Add Comment
Please, Sign In to add comment