summaryrefslogtreecommitdiff
path: root/lib/polyjuice/client/storage/dets.ex
blob: 71999ee71dfd2070e46ec7c879f53ba641003c8d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Copyright 2019 Hubert Chathi <hubert@uhoreg.ca>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

defmodule Polyjuice.Client.Storage.Dets do
  @moduledoc """
  Storage using Erlang [dets](http://erlang.org/doc/man/dets.html).
  """

  defstruct [
    :table
  ]

  @doc """
  Create a new dets storage.

  `file` is the filename for the dets file.
  """
  def open(file) when is_binary(file) do
    table = make_ref()
    :dets.open_file(table, file: to_charlist(file), auto_save: 10000)

    %__MODULE__{
      table: table
    }
  end

  defimpl Polyjuice.Client.Storage, for: __MODULE__ do
    def close(%{table: table}) do
      :dets.close(table)
    end

    def get_sync_token(%{table: table}) do
      case :dets.lookup(table, :sync_token) do
        [sync_token: token] -> token
        _ -> nil
      end
    end

    def set_sync_token(%{table: table}, token) do
      :dets.insert(table, {:sync_token, token})
    end

    def set_filter_id(%{table: table}, filter, id) when is_map(filter) and is_binary(id) do
      {:ok, json} = Polyjuice.Util.JSON.canonical_json(filter)
      hash = :crypto.hash(:sha256, json)
      :dets.insert(table, {"filter_" <> hash, id})
    end

    def get_filter_id(%{table: table}, filter) do
      {:ok, json} = Polyjuice.Util.JSON.canonical_json(filter)
      hash = :crypto.hash(:sha256, json)

      case :dets.lookup(table, "filter_" <> hash) do
        [{_, id}] -> id
        _ -> nil
      end
    end

    def kv_put(%{table: table}, key, value) when is_binary(key) do
      :dets.insert(table, {"kv_" <> key, value})
    end

    def kv_get(%{table: table}, key, default \\ nil) when is_binary(key) do
      case :dets.lookup(table, "kv_" <> key) do
        [{_, value}] -> value
        _ -> default
      end
    end
  end
end