Merge branch 'develop' into tests/mastodon_api_controller.ex
[akkoma] / lib / pleroma / workers / worker_helper.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Workers.WorkerHelper do
6 alias Pleroma.Config
7 alias Pleroma.Workers.WorkerHelper
8
9 def worker_args(queue) do
10 case Config.get([:workers, :retries, queue]) do
11 nil -> []
12 max_attempts -> [max_attempts: max_attempts]
13 end
14 end
15
16 def sidekiq_backoff(attempt, pow \\ 4, base_backoff \\ 15) do
17 backoff =
18 :math.pow(attempt, pow) +
19 base_backoff +
20 :rand.uniform(2 * base_backoff) * attempt
21
22 trunc(backoff)
23 end
24
25 defmacro __using__(opts) do
26 caller_module = __CALLER__.module
27 queue = Keyword.fetch!(opts, :queue)
28
29 quote do
30 # Note: `max_attempts` is intended to be overridden in `new/2` call
31 use Oban.Worker,
32 queue: unquote(queue),
33 max_attempts: 1
34
35 def enqueue(op, params, worker_args \\ []) do
36 params = Map.merge(%{"op" => op}, params)
37 queue_atom = String.to_atom(unquote(queue))
38 worker_args = worker_args ++ WorkerHelper.worker_args(queue_atom)
39
40 unquote(caller_module)
41 |> apply(:new, [params, worker_args])
42 |> Pleroma.Repo.insert()
43 end
44 end
45 end
46 end