-
Notifications
You must be signed in to change notification settings - Fork 1
/
high_level_commands.py
602 lines (555 loc) · 19.5 KB
/
high_level_commands.py
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import time
from typing import (
Any,
Dict,
Iterable,
Optional,
Protocol,
Tuple,
Type,
TypeVar,
Union,
)
from meta_memcache.configuration import LeasePolicy, RecachePolicy, StalePolicy
from meta_memcache.errors import MemcacheError
from meta_memcache.interfaces.high_level_commands import HighLevelCommandsProtocol
from meta_memcache.interfaces.meta_commands import MetaCommandsProtocol
from meta_memcache.interfaces.router import FailureHandling
from meta_memcache.protocol import (
Key,
Miss,
ReadResponse,
RequestFlags,
SetMode,
Success,
Value,
MA_MODE_DEC,
)
T = TypeVar("T")
_REFILL_FAILURE_HANDLING = FailureHandling(track_write_failures=False)
DEFAULT_GET_FLAGS = RequestFlags(
return_value=True,
return_ttl=True,
return_client_flag=True,
return_last_access=True,
return_fetched=True,
)
DEFAULT_GET_CAS_FLAGS = RequestFlags(
return_value=True,
return_ttl=True,
return_client_flag=True,
return_last_access=True,
return_fetched=True,
return_cas_token=True,
)
class HighLevelCommandMixinWithMetaCommands(
HighLevelCommandsProtocol, MetaCommandsProtocol, Protocol
):
def _get(
self,
key: Union[Key, str],
touch_ttl: Optional[int] = None,
lease_policy: Optional[LeasePolicy] = None,
recache_policy: Optional[RecachePolicy] = None,
return_cas_token: bool = False,
) -> Optional[Value]: ... # pragma: no cover
def _process_get_result(
self, key: Union[Key, str], result: ReadResponse
) -> Optional[Value]: ... # pragma: no cover
def _get_typed_value(
self,
key: Union[Key, str],
value: Any,
cls: Type[T],
error_on_type_mismatch: bool = False,
) -> Optional[T]: ... # pragma: no cover
def _get_delta_flags(
self,
delta: int,
refresh_ttl: Optional[int] = None,
no_reply: bool = False,
cas_token: Optional[int] = None,
return_value: bool = False,
) -> RequestFlags: ... # pragma: no cover
class HighLevelCommandsMixin:
def set(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
value: Any,
ttl: int,
no_reply: bool = False,
cas_token: Optional[int] = None,
stale_policy: Optional[StalePolicy] = None,
set_mode: SetMode = SetMode.SET,
) -> bool:
"""
Write a value using the specified `set_mode`
"""
key = key if isinstance(key, Key) else Key(key)
flags = RequestFlags(cache_ttl=ttl)
if no_reply:
flags.no_reply = True
if cas_token is not None:
flags.cas_token = cas_token
if stale_policy and stale_policy.mark_stale_on_cas_mismatch:
flags.mark_stale = True
if set_mode != SetMode.SET:
flags.mode = set_mode.value
result = self.meta_set(
key=key,
value=value,
ttl=ttl,
flags=flags,
)
return isinstance(result, Success)
def refill(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
value: Any,
ttl: int,
no_reply: bool = False,
) -> bool:
"""
Try to refill a value.
Use this method when you got a cache miss, read from DB and
are trying to refill the value.
DO NOT USE to write new state.
It will:
* use "ADD" mode, so it will fail if the value is already
present in cache.
* It will also disable write failure tracking. The write
failure tracking is often used to invalidate keys that
fail to be written. Since this is not writting new state,
there is no need to track failures.
"""
key = key if isinstance(key, Key) else Key(key)
flags = RequestFlags(
cache_ttl=ttl,
mode=SetMode.ADD.value,
)
if no_reply:
flags.no_reply = True
result = self.meta_set(
key=key,
value=value,
ttl=ttl,
flags=flags,
failure_handling=_REFILL_FAILURE_HANDLING,
)
return isinstance(result, Success)
def delete(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
cas_token: Optional[int] = None,
no_reply: bool = False,
stale_policy: Optional[StalePolicy] = None,
) -> bool:
"""
Returns True if the key existed and it was deleted.
If the key is not found in the cache it will return False. If
you just want to the key to be deleted not caring of whether
it exists or not, use invalidate() instead.
"""
key = key if isinstance(key, Key) else Key(key)
flags = RequestFlags()
if no_reply:
flags.no_reply = True
if cas_token is not None:
flags.cas_token = cas_token
if stale_policy and stale_policy.mark_stale_on_deletion_ttl > 0:
flags.mark_stale = True
flags.cache_ttl = stale_policy.mark_stale_on_deletion_ttl
result = self.meta_delete(key=key, flags=flags)
return isinstance(result, Success)
def invalidate(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
cas_token: Optional[int] = None,
no_reply: bool = False,
stale_policy: Optional[StalePolicy] = None,
) -> bool:
"""
Returns true of the key deleted or it didn't exist anyway
"""
key = key if isinstance(key, Key) else Key(key)
flags = RequestFlags()
if no_reply:
flags.no_reply = True
if cas_token is not None:
flags.cas_token = cas_token
if stale_policy and stale_policy.mark_stale_on_deletion_ttl > 0:
flags.mark_stale = True
flags.cache_ttl = stale_policy.mark_stale_on_deletion_ttl
result = self.meta_delete(key=key, flags=flags)
return isinstance(result, (Success, Miss))
def touch(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
ttl: int,
no_reply: bool = False,
) -> bool:
"""
Modify the TTL of a key without retrieving the value
"""
key = key if isinstance(key, Key) else Key(key)
flags = RequestFlags(cache_ttl=ttl)
if no_reply:
flags.no_reply = True
result = self.meta_get(key, flags=flags)
return isinstance(result, Success)
def get_or_lease(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
lease_policy: LeasePolicy,
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
) -> Optional[Any]:
"""
Get a key. On miss try to get a lease.
Guarantees only one cache client will get the miss and
gets to repopulate cache, while the others are blocked
waiting (according to the settings in the LeasePolicy)
"""
value, _ = self.get_or_lease_cas(
key=key,
lease_policy=lease_policy,
touch_ttl=touch_ttl,
recache_policy=recache_policy,
)
return value
def get_or_lease_cas(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
lease_policy: LeasePolicy,
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
) -> Tuple[Optional[Any], Optional[int]]:
"""
Same as get_or_lease(), but also return the CAS token so
it can be used during writes and detect races
"""
if lease_policy.miss_retries <= 0:
raise ValueError(
"Wrong lease_policy: miss_retries needs to be greater than 0"
)
i = 0
while True:
if i > 0:
time.sleep(
min(
lease_policy.miss_max_retry_wait,
lease_policy.miss_retry_wait
* pow(lease_policy.wait_backoff_factor, i - 1),
)
)
i += 1
result = self._get(
key=key,
touch_ttl=touch_ttl,
lease_policy=lease_policy,
recache_policy=recache_policy,
return_cas_token=True,
)
if isinstance(result, Value):
# It is a hit.
if result.flags.win:
# Win flag present, meaning we got the lease to
# recache/cache the item. We need to mimic a miss.
return None, result.flags.cas_token
if result.size == 0 and result.flags.win is False:
# The value is empty, this is a miss lease,
# and we lost, so we must keep retrying and
# wait for the.flags.winner to populate the value.
if i < lease_policy.miss_retries:
continue
else:
# We run out of retries, behave as a miss
return None, result.flags.cas_token
else:
# There is data, either the is no lease or
# we lost and should use the stale value.
return result.value, result.flags.cas_token
else:
# With MISS_LEASE_TTL we should always get a value
# because on miss a lease empty value is generated
raise MemcacheError(f"Unexpected response: {result} for key {key}")
def get(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
) -> Optional[Any]:
"""
Get a key
"""
result = self._get(
key=key,
touch_ttl=touch_ttl,
recache_policy=recache_policy,
return_cas_token=False,
)
return result.value if result is not None else None
def multi_get(
self: HighLevelCommandMixinWithMetaCommands,
keys: Iterable[Union[Key, str]],
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
) -> Dict[Key, Optional[Any]]:
"""
Get multiple keys at once
"""
results = self._multi_get(
keys=keys,
touch_ttl=touch_ttl,
recache_policy=recache_policy,
)
return {k: v.value if v is not None else None for k, v in results.items()}
def _multi_get(
self: HighLevelCommandMixinWithMetaCommands,
keys: Iterable[Union[Key, str]],
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
return_cas_token: bool = False,
) -> Dict[Key, Optional[Value]]:
if return_cas_token:
flags = DEFAULT_GET_CAS_FLAGS.copy()
else:
flags = DEFAULT_GET_FLAGS.copy()
if recache_policy:
flags.recache_ttl = recache_policy.ttl
if touch_ttl is not None and touch_ttl >= 0:
flags.cache_ttl = touch_ttl
results = self.meta_multiget(
keys=[key if isinstance(key, Key) else Key(key) for key in keys],
flags=flags,
)
return {k: self._process_get_result(k, v) for k, v in results.items()}
def get_cas(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
) -> Tuple[Optional[Any], Optional[int]]:
"""
Same as get(), but also return the CAS token so
it can be used during writes and detect races
"""
result = self._get(
key=key,
touch_ttl=touch_ttl,
recache_policy=recache_policy,
return_cas_token=True,
)
if result is None:
return None, None
else:
return result.value, result.flags.cas_token
def _get(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
touch_ttl: Optional[int] = None,
lease_policy: Optional[LeasePolicy] = None,
recache_policy: Optional[RecachePolicy] = None,
return_cas_token: bool = False,
) -> Optional[Value]:
key = key if isinstance(key, Key) else Key(key)
if return_cas_token:
flags = DEFAULT_GET_CAS_FLAGS.copy()
else:
flags = DEFAULT_GET_FLAGS.copy()
if lease_policy:
flags.vivify_on_miss_ttl = lease_policy.ttl
if recache_policy:
flags.recache_ttl = recache_policy.ttl
if touch_ttl is not None and touch_ttl >= 0:
flags.cache_ttl = touch_ttl
result = self.meta_get(key, flags=flags)
return self._process_get_result(key, result)
def _process_get_result(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
result: ReadResponse,
) -> Optional[Value]:
if isinstance(result, Value):
# It is a hit
if result.flags.win:
# Win flag present, meaning we got the lease to
# recache the item. We need to mimic a miss, so
# we set the value to None.
result.value = None
return result
elif isinstance(result, Miss):
return None
else:
raise MemcacheError(f"Unexpected response: {result} for key {key}")
def get_typed(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
cls: Type[T],
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
error_on_type_mismatch: bool = False,
) -> Optional[T]:
"""
Same as get(), but ensure the type matched the provided cls
"""
value = self.get(
key=key,
touch_ttl=touch_ttl,
recache_policy=recache_policy,
)
return self._get_typed_value(key, value, cls, error_on_type_mismatch)
def get_cas_typed(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
cls: Type[T],
touch_ttl: Optional[int] = None,
recache_policy: Optional[RecachePolicy] = None,
error_on_type_mismatch: bool = False,
) -> Tuple[Optional[T], Optional[int]]:
"""
Same as get_typed(), but also return the CAS token so
it can be used during writes and detect races
"""
value, cas_token = self.get_cas(
key=key, touch_ttl=touch_ttl, recache_policy=recache_policy
)
return self._get_typed_value(key, value, cls, error_on_type_mismatch), cas_token
def _get_typed_value(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
value: Any,
cls: Type[T],
error_on_type_mismatch: bool = False,
) -> Optional[T]:
result: Optional[T] = None
if value is not None:
if isinstance(value, cls):
result = value
elif error_on_type_mismatch:
raise ValueError(f"Expecting {cls} got {value} for {key}")
return result
def _get_delta_flags(
self: HighLevelCommandMixinWithMetaCommands,
delta: int,
refresh_ttl: Optional[int] = None,
no_reply: bool = False,
cas_token: Optional[int] = None,
return_value: bool = False,
) -> RequestFlags:
flags = RequestFlags(
ma_delta_value=abs(delta),
)
if return_value:
flags.return_value = True
if no_reply:
flags.no_reply = True
if refresh_ttl is not None:
flags.cache_ttl = refresh_ttl
if cas_token is not None:
flags.cas_token = cas_token
if delta < 0:
flags.mode = MA_MODE_DEC
return flags
def delta(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
delta: int,
refresh_ttl: Optional[int] = None,
no_reply: bool = False,
cas_token: Optional[int] = None,
) -> bool:
"""
Increment/Decrement a key that contains a counter
"""
key = key if isinstance(key, Key) else Key(key)
flags = self._get_delta_flags(
delta=delta,
refresh_ttl=refresh_ttl,
no_reply=no_reply,
cas_token=cas_token,
)
result = self.meta_arithmetic(key=key, flags=flags)
return isinstance(result, Success)
def delta_initialize(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
delta: int,
initial_value: int,
initial_ttl: int,
refresh_ttl: Optional[int] = None,
no_reply: bool = False,
cas_token: Optional[int] = None,
) -> bool:
"""
Increment/Decrement a key that contains a counter,
creating and setting it to the initial value if the
counter does not exist.
"""
key = key if isinstance(key, Key) else Key(key)
flags = self._get_delta_flags(
delta=delta,
refresh_ttl=refresh_ttl,
no_reply=no_reply,
cas_token=cas_token,
)
flags.ma_initial_value = abs(initial_value)
flags.vivify_on_miss_ttl = initial_ttl
result = self.meta_arithmetic(key=key, flags=flags)
return isinstance(result, Success)
def delta_and_get(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
delta: int,
refresh_ttl: Optional[int] = None,
cas_token: Optional[int] = None,
) -> Optional[int]:
"""
Same as delta(), but return the resulting value
"""
key = key if isinstance(key, Key) else Key(key)
flags = self._get_delta_flags(
return_value=True,
delta=delta,
refresh_ttl=refresh_ttl,
cas_token=cas_token,
)
result = self.meta_arithmetic(key=key, flags=flags)
if isinstance(result, Value):
if isinstance(result.value, str) and result.value.isnumeric():
return int(result.value)
else:
raise MemcacheError(
f"Unexpected value from meta arithmetic command: {result.value}"
)
return None
def delta_initialize_and_get(
self: HighLevelCommandMixinWithMetaCommands,
key: Union[Key, str],
delta: int,
initial_value: int,
initial_ttl: int,
refresh_ttl: Optional[int] = None,
cas_token: Optional[int] = None,
) -> Optional[int]:
"""
Same as delta_initialize(), but return the resulting value
"""
key = key if isinstance(key, Key) else Key(key)
flags = self._get_delta_flags(
return_value=True,
delta=delta,
refresh_ttl=refresh_ttl,
cas_token=cas_token,
)
flags.ma_initial_value = abs(initial_value)
flags.vivify_on_miss_ttl = initial_ttl
result = self.meta_arithmetic(key=key, flags=flags)
if isinstance(result, Value):
if isinstance(result.value, str) and result.value.isnumeric():
return int(result.value)
else:
raise MemcacheError(
f"Unexpected value from meta arithmetic command: {result.value}"
)
return None