forked from grantjenks/python-diskcache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecipes.py
More file actions
381 lines (317 loc) · 11 KB
/
recipes.py
File metadata and controls
381 lines (317 loc) · 11 KB
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
"""Disk Cache Recipes
>>> import diskcache as dc, time
>>> cache = dc.Cache()
>>> @dc.memoize(cache)
... @dc.barrier(cache, dc.Lock)
... @dc.memoize(cache)
... def work(num):
... time.sleep(1)
... return num
>>> from concurrent.futures import ThreadPoolExecutor
>>> with ThreadPoolExecutor() as executor:
... start = time.time()
... times = list(executor.map(work, range(5)))
... end = time.time()
>>> times
[0, 1, 2, 3, 4]
>>> int(end - start)
5
>>> with ThreadPoolExecutor() as executor:
... start = time.time()
... times = list(executor.map(work, range(5)))
... end = time.time()
>>> times
[0, 1, 2, 3, 4]
>>> int(end - start)
0
"""
import functools
import os
import threading
import time
from .memo import full_name
class Averager(object):
"""Recipe for calculating a running average.
Sometimes known as "online statistics," the running average maintains the
total and count. The average can then be calculated at any time.
>>> import diskcache
>>> cache = diskcache.Cache()
>>> ave = Averager(cache, 'latency')
>>> ave.add(0.080)
>>> ave.add(0.120)
>>> ave.get()
0.1
>>> ave.add(0.160)
>>> ave.get()
0.12
"""
def __init__(self, cache, key, expire=None, tag=None):
self._cache = cache
self._key = key
self._expire = expire
self._tag = tag
def add(self, value):
"Add `value` to average."
with self._cache.transact():
total, count = self._cache.get(self._key, default=(0.0, 0))
total += value
count += 1
self._cache.set(
self._key, (total, count), expire=self._expire, tag=self._tag,
)
def get(self):
"Get current average."
total, count = self._cache.get(self._key, default=(0.0, 0), retry=True)
return 0.0 if count == 0 else total / count
def pop(self):
"Return current average and reset average to 0.0."
total, count = self._cache.pop(self._key, default=(0.0, 0), retry=True)
return 0.0 if count == 0 else total / count
class Lock(object):
"""Recipe for cross-process and cross-thread lock.
>>> import diskcache
>>> cache = diskcache.Cache()
>>> lock = Lock(cache, 'report-123')
>>> lock.acquire()
>>> lock.release()
>>> with lock:
... pass
"""
def __init__(self, cache, key, expire=None, tag=None):
self._cache = cache
self._key = key
self._expire = expire
self._tag = tag
def acquire(self):
"Acquire lock using spin-lock algorithm."
while True:
added = self._cache.add(
self._key, None, expire=self._expire, tag=self._tag, retry=True,
)
if added:
break
time.sleep(0.001)
def release(self):
"Release lock by deleting key."
self._cache.delete(self._key, retry=True)
def __enter__(self):
self.acquire()
def __exit__(self, *exc_info):
self.release()
class RLock(object):
"""Recipe for cross-process and cross-thread re-entrant lock.
>>> import diskcache
>>> cache = diskcache.Cache()
>>> rlock = RLock(cache, 'user-123')
>>> rlock.acquire()
>>> rlock.acquire()
>>> rlock.release()
>>> with rlock:
... pass
>>> rlock.release()
>>> rlock.release()
Traceback (most recent call last):
...
AssertionError: cannot release un-acquired lock
"""
def __init__(self, cache, key, expire=None, tag=None):
self._cache = cache
self._key = key
self._expire = expire
self._tag = tag
pid = os.getpid()
tid = threading.get_ident()
self._value = '{}-{}'.format(pid, tid)
def acquire(self):
"Acquire lock by incrementing count using spin-lock algorithm."
while True:
with self._cache.transact():
value, count = self._cache.get(self._key, default=(None, 0))
if self._value == value or count == 0:
self._cache.set(
self._key, (self._value, count + 1),
expire=self._expire, tag=self._tag,
)
return
time.sleep(0.001)
def release(self):
"Release lock by decrementing count."
with self._cache.transact():
value, count = self._cache.get(self._key, default=(None, 0))
is_owned = self._value == value and count > 0
assert is_owned, 'cannot release un-acquired lock'
self._cache.set(
self._key, (value, count - 1), expire=self._expire,
tag=self._tag,
)
def __enter__(self):
self.acquire()
def __exit__(self, *exc_info):
self.release()
class FairLock(object):
"""Recipe for cross-process and cross-thread fair lock.
Based on the "Ticket Lock" algorithm:
https://en.wikipedia.org/wiki/Ticket_lock
"""
def __init__(self, cache, prefix, expire=None, tag=None):
self._cache = cache
self._tickets_key = prefix + 'tickets'
self._serving_key = prefix + 'serving'
self._expire = expire
self._tag = tag
def setup(self):
self._cache.add(
self._tickets_key, 0,
expire=self._expire, tag=self._tag, retry=True,
)
self._cache.add(
self._serving_key, 1,
expire=self._expire, tag=self._tag, retry=True,
)
def acquire(self):
while True:
ticket = self._cache.incr(
self._tickets_key,
expire=self._expire, tag=self._tag, retry=True,
)
while True:
serving = self._cache.get(self._serving_key, retry=True)
if serving is None:
self._cache.add(
self._serving_key, ticket,
expire=self._expire, tag=self._tag, retry=True,
)
# TODO: How do we know the tickets key has not expired?
# If the tickets key has expired, is it possible that
# another acquire() method has the same ticket?
# Maybe a transaction is necessary to set both keys?
# If both keys are set then what if another thread has
# acquired the lock already?
elif serving < ticket:
time.sleep(0.001)
elif serving == ticket:
return
else:
assert serving > ticket
# We got skipped! Take a new ticket.
break
def release(self):
self._cache.incr(
self._serving_key, expire=self._expire, tag=self._tag, retry=True,
)
class BoundedSemaphore(object):
"""Recipe for cross-process and cross-thread bounded semaphore.
>>> import diskcache
>>> cache = diskcache.Cache()
>>> semaphore = BoundedSemaphore(cache, 'max-connections', value=2)
>>> semaphore.acquire()
>>> semaphore.acquire()
>>> semaphore.release()
>>> with semaphore:
... pass
>>> semaphore.release()
>>> semaphore.release()
Traceback (most recent call last):
...
AssertionError: cannot release un-acquired semaphore
"""
def __init__(self, cache, key, value=1, expire=None, tag=None):
self._cache = cache
self._key = key
self._value = value
self._expire = expire
self._tag = tag
def acquire(self):
"Acquire semaphore by decrementing value using spin-lock algorithm."
while True:
with self._cache.transact():
value = self._cache.get(self._key, default=self._value)
if value > 0:
self._cache.set(
self._key, value - 1, expire=self._expire,
tag=self._tag,
)
return
time.sleep(0.001)
def release(self):
"Release semaphore by incrementing value."
with self._cache.transact():
value = self._cache.get(self._key, default=self._value)
assert self._value > value, 'cannot release un-acquired semaphore'
value += 1
self._cache.set(
self._key, value, expire=self._expire, tag=self._tag,
)
def __enter__(self):
self.acquire()
def __exit__(self, *exc_info):
self.release()
def throttle(cache, count, seconds, name=None, expire=None, tag=None,
time_func=time.time, sleep_func=time.sleep):
"""Decorator to throttle calls to function.
>>> import diskcache, time
>>> cache = diskcache.Cache()
>>> @throttle(cache, 1, 1)
... def int_time():
... return int(time.time())
>>> times = [int_time() for _ in range(4)]
>>> [times[i] - times[i - 1] for i in range(1, 4)]
[1, 1, 1]
"""
def decorator(func):
rate = count / float(seconds)
if name is None:
try:
key = func.__qualname__
except AttributeError:
key = func.__name__
key = func.__module__ + '.' + key
else:
key = name
now = time_func()
cache.set(key, (now, count), expire=expire, tag=tag, retry=True)
@functools.wraps(func)
def wrapper(*args, **kwargs):
while True:
with cache.transact():
last, tally = cache.get(key, retry=True)
now = time_func()
tally += (now - last) * rate
delay = 0
if tally > count:
cache.set(key, (now, count - 1), expire, retry=True)
elif tally >= 1:
cache.set(key, (now, tally - 1), expire, retry=True)
else:
delay = (1 - tally) / rate
if delay:
sleep_func(delay)
else:
break
return func(*args, **kwargs)
return wrapper
return decorator
def barrier(cache, lock_factory, name=None, expire=None, tag=None):
"""Barrier to calling decorated function.
Supports different kinds of locks: Lock, RLock, BoundedSemaphore.
>>> import diskcache, time
>>> cache = diskcache.Cache()
>>> @barrier(cache, Lock)
... def work(num):
... time.sleep(1)
... return int(time.time())
>>> from concurrent.futures import ThreadPoolExecutor
>>> with ThreadPoolExecutor() as executor:
... times = sorted(executor.map(work, range(4)))
>>> [times[i] - times[i - 1] for i in range(1, 4)]
[1, 1, 1]
"""
def decorator(func):
key = full_name(func) if name is None else name
lock = lock_factory(cache, key, expire=expire, tag=tag)
@functools.wraps(func)
def wrapper(*args, **kwargs):
with lock:
return func(*args, **kwargs)
return wrapper
return decorator