# Copyright 2019 Hubert Chathi # # 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