# 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.Ets do @moduledoc """ Storage using Erlang [ets](http://erlang.org/doc/man/ets.html). This should only be used for testing. """ defstruct [ :table ] def open() do table = :ets.new(:polyjuice_client, []) %__MODULE__{ table: table } end defimpl Polyjuice.Client.Storage, for: __MODULE__ do def close(%{table: table}) do :ets.delete_all_objects(table) end def get_sync_token(%{table: table}) do case :ets.lookup(table, :sync_token) do [sync_token: token] -> token _ -> nil end end def set_sync_token(%{table: table}, token) do :ets.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) :ets.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 :ets.lookup(table, "filter_" <> hash) do [{_, id}] -> id _ -> nil end end def kv_put(%{table: table}, key, value) when is_binary(key) do :ets.insert(table, {"kv_" <> key, value}) end def kv_get(%{table: table}, key, default \\ nil) when is_binary(key) do case :ets.lookup(table, "kv_" <> key) do [{_, value}] -> value _ -> default end end end end