1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Migrators.HashtagsTableMigrator.State do
8 alias Pleroma.DataMigration
10 defdelegate data_migration(), to: DataMigration, as: :populate_hashtags_table
12 @reg_name {:global, __MODULE__}
15 Agent.start_link(fn -> load_state_from_db() end, name: @reg_name)
18 defp load_state_from_db do
19 data_migration = data_migration()
23 Map.new(data_migration.data, fn {k, v} -> {String.to_atom(k), v} end)
29 data_migration_id: data_migration && data_migration.id,
35 %{data_migration_id: data_migration_id, data: data} = state()
37 if data_migration_id do
38 DataMigration.update_one_by_id(data_migration_id, data: data)
40 {:error, :nil_data_migration_id}
45 %{data_migration_id: data_migration_id} = state()
47 with false <- is_nil(data_migration_id),
49 DataMigration.update_one_by_id(data_migration_id,
55 true -> {:error, :nil_data_migration_id}
61 Agent.update(@reg_name, fn _state -> load_state_from_db() end)
65 Agent.get(@reg_name, & &1)
68 def get_data_key(key, default \\ nil) do
69 get_in(state(), [:data, key]) || default
72 def put_data_key(key, value) do
73 _ = persist_non_data_change(key, value)
75 Agent.update(@reg_name, fn state ->
76 put_in(state, [:data, key], value)
80 def increment_data_key(key, increment \\ 1) do
81 Agent.update(@reg_name, fn state ->
82 initial_value = get_in(state, [:data, key]) || 0
83 updated_value = initial_value + increment
84 put_in(state, [:data, key], updated_value)
88 defp persist_non_data_change(:state, value) do
89 with true <- get_data_key(:state) != value,
90 true <- value in Pleroma.DataMigration.State.__valid_values__(),
91 %{data_migration_id: data_migration_id} when not is_nil(data_migration_id) <- state() do
92 DataMigration.update_one_by_id(data_migration_id, state: value)
95 _ -> {:error, :nil_data_migration_id}
99 defp persist_non_data_change(_, _) do