-
Notifications
You must be signed in to change notification settings - Fork 0
/
ane.ex
387 lines (273 loc) · 8.3 KB
/
ane.ex
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
defmodule Ane do
@moduledoc """
A very efficient way to share mutable data by utilizing `:atomics` and `:ets` modules.
[github.com/gyson/ane](https://github.com/gyson/ane) has detailed guides.
"""
@type atomics_ref() :: :atomics.atomics_ref()
@type tid() :: :ets.tid() | atom()
@type t_for_ane_mode() :: {tid(), atomics_ref(), atomics_ref(), map()}
@type t_for_ets_mode() :: {tid(), pos_integer()}
@type t() :: t_for_ane_mode() | t_for_ets_mode()
@destroyed_message "Ane instance is destroyed"
@doc """
Create and return an Ane instance.
## Options
* `:mode` (atom) - set mode of Ane instance. Default to `:ane`.
* `:read_concurrency` (boolean) - set read_concurrency for underneath ETS table. Default to `false`.
* `:write_concurrency` (boolean) - set write_concurrency for underneath ETS table. Default to `false`.
* `:compressed` (boolean) - set compressed for underneath ETS table. Default to `false`.
## Example
iex> a = Ane.new(1, read_concurrency: false, write_concurrency: false, compressed: false)
iex> t = Ane.get_table(a)
iex> :ets.info(t, :read_concurrency)
false
iex> :ets.info(t, :write_concurrency)
false
iex> :ets.info(t, :compressed)
false
"""
@spec new(pos_integer(), keyword()) :: t()
def new(size, options \\ []) do
read = Keyword.get(options, :read_concurrency, false)
write = Keyword.get(options, :write_concurrency, false)
compressed =
case Keyword.get(options, :compressed, false) do
true ->
[:compressed]
false ->
[]
end
table_options = [
:set,
:public,
{:read_concurrency, read},
{:write_concurrency, write}
| compressed
]
case Keyword.get(options, :mode, :ane) do
:ane ->
a1 = :atomics.new(size, signed: true)
a2 = :atomics.new(size, signed: true)
e = :ets.new(__MODULE__, table_options)
{e, a1, a2, %{}}
:ets ->
e = :ets.new(__MODULE__, table_options)
{e, size}
end
end
@doc """
Get value at one-based index in Ane instance.
It returns a tuple with two elements:
* First element is new Ane instance which includes latest cached data.
- Note: we need to use this returned new Ane instance for following read operations to make cache work properly.
* Second element is the value at one-based index. Value is initialized as `nil` by default.
## Example
iex> a = Ane.new(1)
iex> {a, value} = Ane.get(a, 1)
iex> value
nil
iex> Ane.put(a, 1, "hello")
:ok
iex> {_, value} = Ane.get(a, 1)
iex> value
"hello"
"""
@spec get(t(), pos_integer()) :: {t(), any()}
def get({e, a1, a2, cache} = ane, i) do
case :atomics.get(a2, i) do
version when version > 0 ->
case cache do
# cache hit
%{^i => {^version, value}} ->
{ane, value}
# cache miss
_ ->
{_, value} = updated = lookup(e, a2, i, version)
{{e, a1, a2, Map.put(cache, i, updated)}, value}
end
0 ->
{ane, nil}
_ ->
raise ArgumentError, @destroyed_message
end
end
def get({e, size} = ane, i) when is_integer(i) and i > 0 and i <= size do
case :ets.lookup(e, i) do
[{_, value}] ->
{ane, value}
[] ->
{ane, nil}
end
end
@spec lookup(tid(), atomics_ref(), pos_integer(), integer()) :: {integer(), any()}
defp lookup(e, a2, i, version) do
case :ets.lookup(e, [i, version]) do
[{_, value}] ->
{version, value}
[] ->
case :atomics.get(a2, i) do
new_version when new_version > 0 ->
lookup(e, a2, i, new_version)
_ ->
raise ArgumentError, @destroyed_message
end
end
end
@doc """
Put value at one-based index in Ane instance.
It would always return `:ok`.
`Ane.put` includes one `:ets.insert` operation and one `:ets.delete`
operation. When the process running `Ane.put` is interrupted (e.g. by
`:erlang.exit(pid, :kill)`), garbage data could be generated if it
finished insert operation but did not start delete operation. These
garbabge data could be removed by `Ane.clear`.
## Example
iex> a = Ane.new(1)
iex> {a, value} = Ane.get(a, 1)
iex> value
nil
iex> Ane.put(a, 1, "world")
:ok
iex> {_, value} = Ane.get(a, 1)
iex> value
"world"
"""
@spec put(t(), pos_integer(), any()) :: :ok
def put({e, a1, a2, _} = _ane, i, value) do
case :atomics.add_get(a1, i, 1) do
new_version when new_version > 0 ->
:ets.insert(e, {[i, new_version], value})
commit(e, a2, i, new_version - 1, new_version)
_ ->
raise ArgumentError, @destroyed_message
end
end
def put({e, size} = _ane, i, value) when is_integer(i) and i > 0 and i <= size do
:ets.insert(e, {i, value})
:ok
end
@spec commit(tid(), atomics_ref(), pos_integer(), integer(), integer()) :: :ok
defp commit(e, a2, i, expected, desired) do
case :atomics.compare_exchange(a2, i, expected, desired) do
:ok ->
:ets.delete(e, [i, expected])
:ok
actual when actual < 0 ->
raise ArgumentError, @destroyed_message
actual when actual < desired ->
commit(e, a2, i, actual, desired)
_ ->
:ets.delete(e, [i, desired])
:ok
end
end
@doc """
Clear garbage data which could be generated when `Ane.put` is interrupted.
## Example
iex> a = Ane.new(1)
iex> Ane.clear(a)
:ok
"""
@spec clear(t()) :: :ok
def clear({e, _, a2, _} = _ane) do
:ets.safe_fixtable(e, true)
clear_table(e, a2, %{}, :ets.first(e))
:ets.safe_fixtable(e, false)
:ok
end
def clear({_, _} = _ane), do: :ok
@spec clear_table(tid(), atomics_ref(), map(), any()) :: :ok
defp clear_table(_, _, _, :"$end_of_table"), do: :ok
defp clear_table(e, a2, cache, [i, version] = key) do
{updated_cache, current_version} =
case cache do
%{^i => v} ->
{cache, v}
_ ->
v = :atomics.get(a2, i)
{Map.put(cache, i, v), v}
end
if version < current_version do
:ets.delete(e, key)
end
clear_table(e, a2, updated_cache, :ets.next(e, key))
end
@doc """
Destroy an Ane instance.
## Example
iex> a = Ane.new(1)
iex> Ane.destroyed?(a)
false
iex> Ane.destroy(a)
:ok
iex> Ane.destroyed?(a)
true
"""
@spec destroy(t()) :: :ok
def destroy({e, a1, a2, _} = ane) do
# min for 64 bits signed number
min = -9_223_372_036_854_775_808
1..get_size(ane)
|> Enum.each(fn i ->
:atomics.put(a1, i, min)
:atomics.put(a2, i, min)
end)
:ets.delete(e)
:ok
end
def destroy({e, _} = _ane) do
:ets.delete(e)
:ok
end
@doc """
Check if Ane instance is destroyed.
## Example
iex> a = Ane.new(1)
iex> Ane.destroyed?(a)
false
iex> Ane.destroy(a)
:ok
iex> Ane.destroyed?(a)
true
"""
@spec destroyed?(t()) :: boolean()
def destroyed?({e, _, _, _} = _ane), do: :ets.info(e, :type) == :undefined
def destroyed?({e, _} = _ane), do: :ets.info(e, :type) == :undefined
@doc """
Get mode of Ane instance.
## Example
iex> Ane.new(1) |> Ane.get_mode()
:ane
iex> Ane.new(1, mode: :ane) |> Ane.get_mode()
:ane
iex> Ane.new(1, mode: :ets) |> Ane.get_mode()
:ets
"""
@spec get_mode(t()) :: :ane | :ets
def get_mode({_, _, _, _} = _ane), do: :ane
def get_mode({_, _} = _ane), do: :ets
@doc """
Get size of Ane instance.
## Example
iex> Ane.new(1) |> Ane.get_size()
1
iex> Ane.new(10) |> Ane.get_size()
10
"""
@spec get_size(t()) :: pos_integer()
def get_size({_, _, a2, _} = _ane), do: :atomics.info(a2).size
def get_size({_, size} = _ane), do: size
@doc """
Get ETS table of Ane instance.
The returned ETS table could be used to
* get more info via `:ets.info`
* change ownership via `:ets.give_away`
* change configuration via `:ets.setopts`
## Example
iex> Ane.new(1) |> Ane.get_table() |> :ets.info(:type)
:set
"""
@spec get_table(t()) :: tid()
def get_table({e, _, _, _} = _ane), do: e
def get_table({e, _} = _ane), do: e
end