ruvio-client 0.1.3.dev33__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/PKG-INFO +31 -3
  2. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/README.md +30 -2
  3. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/pyproject.toml +1 -1
  4. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/__init__.py +5 -1
  5. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_cluster.py +33 -0
  6. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_commands.py +21 -0
  7. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/asyncio/client.py +16 -4
  8. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/asyncio/cluster.py +13 -4
  9. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/client.py +20 -2
  10. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/cluster.py +15 -4
  11. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/errors.py +57 -0
  12. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio_client.egg-info/PKG-INFO +31 -3
  13. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio_client.egg-info/SOURCES.txt +1 -0
  14. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_cluster_edge.py +25 -0
  15. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_command_encoding.py +78 -0
  16. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_coverage.py +1 -1
  17. ruvio_client-0.2.0/tests/test_errors.py +56 -0
  18. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_helpers_live.py +21 -0
  19. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_live.py +9 -0
  20. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/LICENSE +0 -0
  21. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_blocking.py +0 -0
  22. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_command_keys.py +0 -0
  23. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_constants.py +0 -0
  24. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_converters.py +0 -0
  25. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_follow.py +0 -0
  26. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_models.py +0 -0
  27. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_pipeline.py +0 -0
  28. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_resp.py +0 -0
  29. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/_tls.py +0 -0
  30. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/asyncio/__init__.py +0 -0
  31. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio/py.typed +0 -0
  32. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio_client.egg-info/dependency_links.txt +0 -0
  33. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio_client.egg-info/requires.txt +0 -0
  34. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/ruvio_client.egg-info/top_level.txt +0 -0
  35. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/setup.cfg +0 -0
  36. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_asyncio_timeout.py +0 -0
  37. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_client_edge.py +0 -0
  38. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_cluster_live.py +0 -0
  39. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_cluster_pure.py +0 -0
  40. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_cluster_unit.py +0 -0
  41. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_constants.py +0 -0
  42. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_coordinator_failover_live.py +0 -0
  43. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_durability_live.py +0 -0
  44. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_failover_live.py +0 -0
  45. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_follow_failover.py +0 -0
  46. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_follow_memory.py +0 -0
  47. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_key_vectors.py +0 -0
  48. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_multi_node_live.py +0 -0
  49. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_replica_reads.py +0 -0
  50. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_replica_reads_live.py +0 -0
  51. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_resp.py +0 -0
  52. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_resp_edge.py +0 -0
  53. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_resp_vectors.py +0 -0
  54. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_seeds.py +0 -0
  55. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_slot_vectors.py +0 -0
  56. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_tls_live.py +0 -0
  57. {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.0}/tests/test_ttl_on_create.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ruvio-client
3
- Version: 0.1.3.dev33
3
+ Version: 0.2.0
4
4
  Summary: Fast sync and asyncio Python client for the Ruvio key-value server (RESP2/RESP3)
5
5
  Author: Salih Cantekin
6
6
  License: MIT
@@ -66,7 +66,7 @@ dependencies and needs Python 3.9 or newer. It ships type information (`py.typed
66
66
  The methods also cover the options that change Ruvio's behaviour: `SET … IFEQ`,
67
67
  `INCRBY … MAX`, `FILLGET … WAIT`, `FILLSET … SWR`, `GETEX` in milliseconds,
68
68
  `DELEX key IFEQ v`, `LPUSHCAP`/`RPUSHCAP`, `BF.*`, `JSON.*` (including `JSON.INDEX` and
69
- `JSON.FIND`), `IDEM BEGIN/COMPLETE`, `LEASE`/`RELEASE`, `SEMAPHORE`, `ONCE`, `TAKE`, `TRANSFER`/`HTRANSFER`, `SETV`,
69
+ `JSON.FIND`), `IDEM BEGIN/COMPLETE/ABORT`, `LEASE`/`RELEASE`, `SEMAPHORE`, `ONCE`, `TAKE`, `TRANSFER`/`HTRANSFER`, `SETV`,
70
70
  `CHANGES`, `LIMIT` and `XADD … DELAY`.
71
71
  - Pipelines, MULTI/EXEC transactions, Pub/Sub on a dedicated connection, and RESP3 through
72
72
  `HELLO 3`, including push messages.
@@ -216,7 +216,8 @@ to `on_push=callback` and never reach a command's reply.
216
216
  | `r.limit_sliding(key, max, window_ms)`, `r.limit_tokens(key, capacity, refill_ms, cost=1)` | `LIMIT ... SLIDING`, `LIMIT ... TOKENS` | remaining, or `None` |
217
217
  | `r.limit_sliding_with_retry(...)`, `r.limit_tokens_with_retry(...)` | `LIMIT ... WITHRETRY` | `(allowed, remaining, retry_after_ms)` |
218
218
  | `r.get_or_create(key, factory, ttl_ms, fill_ms=…, swr_ms=…)` | `FILLGET` / `FILLSET` | Exactly one caller runs `factory` (sync or async). Waiters poll plain `FILLGET` with backoff from 5 ms up to 100 ms instead of `WAIT`, which would park the shared connection |
219
- | `r.idempotent(key, fingerprint, ttl_ms, fn)` | `IDEM BEGIN` / `COMPLETE` | `("executed", result)`, `("completed", stored)`, `("pending", None)` or `("conflict", None)` |
219
+ | `r.idempotent(key, fingerprint, ttl_ms, fn, abort_on_error=False)` | `IDEM BEGIN` / `COMPLETE` (+ `ABORT`) | `("executed", result)`, `("completed", stored)`, `("pending", None)` or `("conflict", None)`. If `fn` raises the record stays pending until `ttl_ms`; with `abort_on_error=True` it sends `IDEM ABORT` first, so a retry runs `fn` again at once, and the original exception still propagates (a failed abort is ignored). Use it only when a failed `fn` did not take effect or is safe to run again |
220
+ | `r.idem_abort(key, fingerprint, owner)` | `IDEM ABORT` | `True` when the pending record of that owner and fingerprint was removed; `False` for a missing key, a completed record (its result is never removed) or another owner. Abort only when the work did not take effect or is safe to run again; a retry after an abort runs it again |
220
221
  | `r.scan_iter()` / `hscan_iter` / `sscan_iter` / `zscan_iter` | `SCAN` family | Lazy and driven by the cursor; async iterators on the asyncio client |
221
222
  | `r.json_set_obj` / `json_get_obj` / `json_mget_obj` | `JSON.SET` / `JSON.GET` / `JSON.MGET` | Uses the standard `json` module |
222
223
  | `r.push_recent(key, value, keep)` | `LPUSHCAP` | Newest first, keeps at most `keep` items |
@@ -422,6 +423,33 @@ client = Ruvio(seeds=["10.0.0.1:6379", ("10.0.0.2", 6379), "[::1]:6379"])
422
423
  table). Pipelines, fan-out commands and transactions do not trigger the reload on their own; they fail as
423
424
  before and the next single-key or keyless command reloads. Seeds are never asked while the known nodes answer.
424
425
 
426
+ ## Retry policies of your own
427
+
428
+ `ruvio.is_transient` and `ruvio.may_have_run` sort what a call raises, for a retry policy of your own
429
+ (tenacity, a loop). The client already follows `MOVED`/`ASK`, waits out `TRYAGAIN` during a slot move and
430
+ finds a new primary after a failover; these judge what still reaches you.
431
+
432
+ - `is_transient(e)`: trying again later can succeed. True for `ConnectionError` and `TimeoutError` and for
433
+ `LOADING`, `MASTERDOWN`, `CLUSTERDOWN`, `TRYAGAIN`, `READONLY` and `NOREPLICAS`; false for `WRONGTYPE`, `OOM`,
434
+ syntax errors, `ProtocolError` and a cancelled task.
435
+ - `may_have_run(e)`: the failed call may have changed data. False only for a server error reply (the server
436
+ refused the command), except `NOREPLICAS`: the write was applied and only the replica confirmation timed out.
437
+ A failed connection or a timeout may have run.
438
+
439
+ Repeat a write only when it is safe to repeat or did not run:
440
+
441
+ ```python
442
+ from tenacity import retry, retry_if_exception, stop_after_attempt
443
+ from ruvio import is_transient, may_have_run
444
+
445
+ # incr is not safe to repeat: retry it only when it surely did not run.
446
+ @retry(retry=retry_if_exception(lambda e: is_transient(e) and not may_have_run(e)), stop=stop_after_attempt(3))
447
+ def visit(r):
448
+ return r.incr("visits")
449
+ ```
450
+
451
+ For a read, `is_transient` alone is enough.
452
+
425
453
  ## Following a failover
426
454
 
427
455
  A standalone client with two or more `seeds`, or with `sentinel_master`, finds the primary again after a
@@ -31,7 +31,7 @@ dependencies and needs Python 3.9 or newer. It ships type information (`py.typed
31
31
  The methods also cover the options that change Ruvio's behaviour: `SET … IFEQ`,
32
32
  `INCRBY … MAX`, `FILLGET … WAIT`, `FILLSET … SWR`, `GETEX` in milliseconds,
33
33
  `DELEX key IFEQ v`, `LPUSHCAP`/`RPUSHCAP`, `BF.*`, `JSON.*` (including `JSON.INDEX` and
34
- `JSON.FIND`), `IDEM BEGIN/COMPLETE`, `LEASE`/`RELEASE`, `SEMAPHORE`, `ONCE`, `TAKE`, `TRANSFER`/`HTRANSFER`, `SETV`,
34
+ `JSON.FIND`), `IDEM BEGIN/COMPLETE/ABORT`, `LEASE`/`RELEASE`, `SEMAPHORE`, `ONCE`, `TAKE`, `TRANSFER`/`HTRANSFER`, `SETV`,
35
35
  `CHANGES`, `LIMIT` and `XADD … DELAY`.
36
36
  - Pipelines, MULTI/EXEC transactions, Pub/Sub on a dedicated connection, and RESP3 through
37
37
  `HELLO 3`, including push messages.
@@ -181,7 +181,8 @@ to `on_push=callback` and never reach a command's reply.
181
181
  | `r.limit_sliding(key, max, window_ms)`, `r.limit_tokens(key, capacity, refill_ms, cost=1)` | `LIMIT ... SLIDING`, `LIMIT ... TOKENS` | remaining, or `None` |
182
182
  | `r.limit_sliding_with_retry(...)`, `r.limit_tokens_with_retry(...)` | `LIMIT ... WITHRETRY` | `(allowed, remaining, retry_after_ms)` |
183
183
  | `r.get_or_create(key, factory, ttl_ms, fill_ms=…, swr_ms=…)` | `FILLGET` / `FILLSET` | Exactly one caller runs `factory` (sync or async). Waiters poll plain `FILLGET` with backoff from 5 ms up to 100 ms instead of `WAIT`, which would park the shared connection |
184
- | `r.idempotent(key, fingerprint, ttl_ms, fn)` | `IDEM BEGIN` / `COMPLETE` | `("executed", result)`, `("completed", stored)`, `("pending", None)` or `("conflict", None)` |
184
+ | `r.idempotent(key, fingerprint, ttl_ms, fn, abort_on_error=False)` | `IDEM BEGIN` / `COMPLETE` (+ `ABORT`) | `("executed", result)`, `("completed", stored)`, `("pending", None)` or `("conflict", None)`. If `fn` raises the record stays pending until `ttl_ms`; with `abort_on_error=True` it sends `IDEM ABORT` first, so a retry runs `fn` again at once, and the original exception still propagates (a failed abort is ignored). Use it only when a failed `fn` did not take effect or is safe to run again |
185
+ | `r.idem_abort(key, fingerprint, owner)` | `IDEM ABORT` | `True` when the pending record of that owner and fingerprint was removed; `False` for a missing key, a completed record (its result is never removed) or another owner. Abort only when the work did not take effect or is safe to run again; a retry after an abort runs it again |
185
186
  | `r.scan_iter()` / `hscan_iter` / `sscan_iter` / `zscan_iter` | `SCAN` family | Lazy and driven by the cursor; async iterators on the asyncio client |
186
187
  | `r.json_set_obj` / `json_get_obj` / `json_mget_obj` | `JSON.SET` / `JSON.GET` / `JSON.MGET` | Uses the standard `json` module |
187
188
  | `r.push_recent(key, value, keep)` | `LPUSHCAP` | Newest first, keeps at most `keep` items |
@@ -387,6 +388,33 @@ client = Ruvio(seeds=["10.0.0.1:6379", ("10.0.0.2", 6379), "[::1]:6379"])
387
388
  table). Pipelines, fan-out commands and transactions do not trigger the reload on their own; they fail as
388
389
  before and the next single-key or keyless command reloads. Seeds are never asked while the known nodes answer.
389
390
 
391
+ ## Retry policies of your own
392
+
393
+ `ruvio.is_transient` and `ruvio.may_have_run` sort what a call raises, for a retry policy of your own
394
+ (tenacity, a loop). The client already follows `MOVED`/`ASK`, waits out `TRYAGAIN` during a slot move and
395
+ finds a new primary after a failover; these judge what still reaches you.
396
+
397
+ - `is_transient(e)`: trying again later can succeed. True for `ConnectionError` and `TimeoutError` and for
398
+ `LOADING`, `MASTERDOWN`, `CLUSTERDOWN`, `TRYAGAIN`, `READONLY` and `NOREPLICAS`; false for `WRONGTYPE`, `OOM`,
399
+ syntax errors, `ProtocolError` and a cancelled task.
400
+ - `may_have_run(e)`: the failed call may have changed data. False only for a server error reply (the server
401
+ refused the command), except `NOREPLICAS`: the write was applied and only the replica confirmation timed out.
402
+ A failed connection or a timeout may have run.
403
+
404
+ Repeat a write only when it is safe to repeat or did not run:
405
+
406
+ ```python
407
+ from tenacity import retry, retry_if_exception, stop_after_attempt
408
+ from ruvio import is_transient, may_have_run
409
+
410
+ # incr is not safe to repeat: retry it only when it surely did not run.
411
+ @retry(retry=retry_if_exception(lambda e: is_transient(e) and not may_have_run(e)), stop=stop_after_attempt(3))
412
+ def visit(r):
413
+ return r.incr("visits")
414
+ ```
415
+
416
+ For a read, `is_transient` alone is enough.
417
+
390
418
  ## Following a failover
391
419
 
392
420
  A standalone client with two or more `seeds`, or with `sentinel_master`, finds the primary again after a
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ruvio-client"
7
- version = "0.1.3.dev33"
7
+ version = "0.2.0"
8
8
  description = "Fast sync and asyncio Python client for the Ruvio key-value server (RESP2/RESP3)"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -86,9 +86,11 @@ from .errors import (
86
86
  TimeoutError,
87
87
  WatchError,
88
88
  WrongTypeError,
89
+ is_transient,
90
+ may_have_run,
89
91
  )
90
92
 
91
- __version__ = "0.1.3.dev33"
93
+ __version__ = "0.2.0"
92
94
 
93
95
  __all__ = [
94
96
  "Ruvio",
@@ -136,6 +138,8 @@ __all__ = [
136
138
  "PendingEntry",
137
139
  "PendingSummary",
138
140
  "StreamEntry",
141
+ "is_transient",
142
+ "may_have_run",
139
143
  "BusyError",
140
144
  "ConnectionError",
141
145
  "CrossSlotError",
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import binascii
12
12
  import re
13
+ import time
13
14
  from enum import Enum
14
15
  from typing import Any, Dict, List, Optional, Tuple, Union
15
16
 
@@ -33,6 +34,38 @@ MAX_REDIRECTS = 3
33
34
  #: all): a slot range moving between nodes is frozen for a few hundred milliseconds
34
35
  TRYAGAIN_DELAYS = (0.005, 0.010, 0.020, 0.040, 0.080, 0.160, 0.320)
35
36
 
37
+
38
+ class TryAgainClock:
39
+ """The one ``-TRYAGAIN`` wait of a call. The ``TRYAGAIN_DELAYS`` schedule runs from the first ``-TRYAGAIN``
40
+ the call sees and is shared by every command of a pipeline, so N refused commands wait for one budget, not N."""
41
+
42
+ __slots__ = ("start", "limit")
43
+
44
+ def __init__(self, limit: Optional[float] = None) -> None:
45
+ self.start: Optional[float] = None
46
+ self.limit = limit # the command timeout, when it is shorter than the schedule
47
+
48
+ def pause(self, tries: int) -> Optional[float]:
49
+ """Seconds to sleep before re-send number ``tries`` (from 0), or None when the budget is spent. A command
50
+ that has not been re-sent yet always gets one more try, so a freeze that ended while earlier commands
51
+ waited does not fail the later ones."""
52
+ now = time.monotonic()
53
+ if self.start is None:
54
+ self.start = now
55
+ elapsed = now - self.start
56
+ budget = sum(TRYAGAIN_DELAYS)
57
+ if self.limit is not None:
58
+ budget = min(budget, self.limit)
59
+ at = 0.0
60
+ for step in TRYAGAIN_DELAYS:
61
+ at += step
62
+ if at > budget + 1e-9:
63
+ break
64
+ if at > elapsed:
65
+ return at - elapsed
66
+ return 0.0 if tries == 0 else None
67
+
68
+
36
69
  #: ``ASKING`` as a frame, sent in front of the command an ``-ASK`` redirect names
37
70
  ASKING = b"*1\r\n$6\r\nASKING\r\n"
38
71
 
@@ -1515,6 +1515,27 @@ class Commands:
1515
1515
  """
1516
1516
  return self._c(None, "IDEM", key, "COMPLETE", fingerprint, owner, result)
1517
1517
 
1518
+ def idem_abort(self, key: KeyT, fingerprint: Arg, owner: Arg) -> Any:
1519
+ """``IDEM key ABORT fingerprint owner`` - gives up a pending operation. Ruvio extension.
1520
+
1521
+ The next :meth:`idem_begin` for the key then acquires it at once. Abort only when the work did not
1522
+ take effect or is safe to run again; a retry after an abort runs it again.
1523
+
1524
+ Args:
1525
+ key: The operation key used in :meth:`idem_begin`.
1526
+ fingerprint: Same fingerprint as in ``idem_begin``.
1527
+ owner: Same owner token as in ``idem_begin``.
1528
+
1529
+ Returns:
1530
+ ``True`` when the pending record of this owner and fingerprint was removed. ``False`` when
1531
+ nothing changed: the key is missing or expired, the record is completed (its result is never
1532
+ removed), or another owner or fingerprint holds it.
1533
+
1534
+ Raises:
1535
+ ResponseError: Tokens out of range, or the key holds no idempotency record.
1536
+ """
1537
+ return self._c(_bool, "IDEM", key, "ABORT", fingerprint, owner)
1538
+
1518
1539
  def once(self, key: KeyT, ttl_ms: int) -> Any:
1519
1540
  """``ONCE key ttl_ms`` - true only for the first call within the TTL. Ruvio extension.
1520
1541
 
@@ -1187,10 +1187,13 @@ This is a coroutine: ``ps = await client.pubsub()``.
1187
1187
  ttl_ms: int,
1188
1188
  fn: Callable[[], Union[str, bytes, Awaitable[Union[str, bytes]]]],
1189
1189
  owner: Optional[str] = None,
1190
+ abort_on_error: bool = False,
1190
1191
  ) -> Tuple[str, Any]:
1191
1192
  """Runs ``fn`` (sync or async) at most once per key, using ``IDEM BEGIN``/``COMPLETE``.
1192
1193
 
1193
- See :meth:`ruvio.Ruvio.idempotent`. If ``fn`` raises, the record stays pending until ``ttl_ms``.
1194
+ See :meth:`ruvio.Ruvio.idempotent`. If ``fn`` raises, the record stays pending until ``ttl_ms``,
1195
+ unless ``abort_on_error=True`` sends ``IDEM ABORT`` first (a failed abort is ignored and ``fn``'s
1196
+ exception still propagates). Use it only when a failed ``fn`` did not take effect or is safe to run again.
1194
1197
 
1195
1198
  Args:
1196
1199
  key: Operation key, scoped to the tenant and operation.
@@ -1198,6 +1201,7 @@ This is a coroutine: ``ps = await client.pubsub()``.
1198
1201
  ttl_ms: Retention in milliseconds, 1 to 604800000.
1199
1202
  fn: Zero-argument function or coroutine function returning the result (``str`` or ``bytes``).
1200
1203
  owner: Attempt token; random when omitted.
1204
+ abort_on_error: Release the reservation with ``IDEM ABORT`` when ``fn`` raises. Default ``False``.
1201
1205
 
1202
1206
  Returns:
1203
1207
  ``("executed", result)``, ``("completed", stored_result)``, ``("pending", None)`` or ``("conflict", None)``.
@@ -1205,9 +1209,17 @@ This is a coroutine: ``ps = await client.pubsub()``.
1205
1209
  owner = owner or uuid.uuid4().hex
1206
1210
  r = await self.idem_begin(key, fingerprint, owner, ttl_ms)
1207
1211
  if r.state == "acquired":
1208
- result = fn()
1209
- if inspect.isawaitable(result):
1210
- result = await result
1212
+ try:
1213
+ result = fn()
1214
+ if inspect.isawaitable(result):
1215
+ result = await result
1216
+ except BaseException:
1217
+ if abort_on_error:
1218
+ try:
1219
+ await self.idem_abort(key, fingerprint, owner)
1220
+ except Exception:
1221
+ pass # the record stays pending until ttl_ms; fn's error is the one raised
1222
+ raise
1211
1223
  await self.idem_complete(key, fingerprint, owner, result)
1212
1224
  return "executed", result
1213
1225
  return r.state, r.result
@@ -579,7 +579,9 @@ class ClusterRuvio(Ruvio):
579
579
  return proto
580
580
  raise error
581
581
 
582
- async def _redirect(self, err: ResponseError, data: bytes, conv: Conv, dec: bool, blocking: bool) -> Any:
582
+ async def _redirect(
583
+ self, err: ResponseError, data: bytes, conv: Conv, dec: bool, blocking: bool, clock: Optional[cl.TryAgainClock] = None
584
+ ) -> Any:
583
585
  """Follows ``-MOVED`` and ``-ASK`` (one budget of ``MAX_REDIRECTS`` per command) and re-sends after
584
586
  ``-TRYAGAIN`` (``TRYAGAIN_DELAYS``, one ``asyncio.sleep`` before each re-send); the last error is raised
585
587
  when a budget runs out. ``ASK`` sends ``ASKING`` and the command to the named node and leaves the table alone."""
@@ -590,7 +592,12 @@ class ClusterRuvio(Ruvio):
590
592
  node = self._route_node(data)
591
593
  if node is None or tries == len(cl.TRYAGAIN_DELAYS):
592
594
  raise err
593
- await asyncio.sleep(cl.TRYAGAIN_DELAYS[tries])
595
+ # One command keeps the fixed schedule; a pipeline's commands share a clock.
596
+ pause = cl.TRYAGAIN_DELAYS[tries] if clock is None else clock.pause(tries)
597
+ if pause is None:
598
+ raise err
599
+ if pause > 0:
600
+ await asyncio.sleep(pause)
594
601
  tries += 1
595
602
  else:
596
603
  if hops == cl.MAX_REDIRECTS:
@@ -844,10 +851,11 @@ class ClusterRuvio(Ruvio):
844
851
  nxt[i] = iter(r).__next__
845
852
  replies = [nxt[i]() for i in idx]
846
853
  if MovedError in set(map(type, replies)):
854
+ clock = cl.TryAgainClock()
847
855
  for i, v in enumerate(replies):
848
856
  if v.__class__ is MovedError:
849
857
  try:
850
- replies[i] = await self._redirect(v, payload[i], None, dec, False)
858
+ replies[i] = await self._redirect(v, payload[i], None, dec, False, clock)
851
859
  except ResponseError as e:
852
860
  replies[i] = e
853
861
  return replies
@@ -869,11 +877,12 @@ class ClusterRuvio(Ruvio):
869
877
  replies[i] = v
870
878
  if failure is not None:
871
879
  raise failure
880
+ clock = cl.TryAgainClock()
872
881
  for i, v in enumerate(replies):
873
882
  if v.__class__ is MovedError:
874
883
  frame = payload[i] if i < n else subs[i - n][4] # type: ignore[index]
875
884
  try:
876
- replies[i] = await self._redirect(v, frame, None, dec, False)
885
+ replies[i] = await self._redirect(v, frame, None, dec, False, clock)
877
886
  except ResponseError as e:
878
887
  replies[i] = e
879
888
  return replies if subs is None else cl.merge_pipeline(replies, n, subs)
@@ -1139,12 +1139,21 @@ Acquire is ``SET NX PX``, renew is ``SET IFEQ PX`` and release is ``DELEX IFEQ``
1139
1139
  delay = min(delay * 2, 0.1)
1140
1140
 
1141
1141
  def idempotent(
1142
- self, key: KeyT, fingerprint: str, ttl_ms: int, fn: Callable[[], Union[str, bytes]], owner: Optional[str] = None
1142
+ self,
1143
+ key: KeyT,
1144
+ fingerprint: str,
1145
+ ttl_ms: int,
1146
+ fn: Callable[[], Union[str, bytes]],
1147
+ owner: Optional[str] = None,
1148
+ abort_on_error: bool = False,
1143
1149
  ) -> Tuple[str, Any]:
1144
1150
  """Runs ``fn`` at most once per key, using ``IDEM BEGIN``/``COMPLETE``.
1145
1151
 
1146
1152
  If ``fn`` raises, the record stays pending until ``ttl_ms`` and retries report ``"pending"``; use a
1147
1153
  retention that matches your retry horizon. This is not exactly-once for external side effects.
1154
+ With ``abort_on_error=True`` a raising ``fn`` first sends ``IDEM ABORT`` so a retry runs it again at
1155
+ once, then the original exception propagates; a failed abort is ignored. Use it only when a failed
1156
+ ``fn`` did not take effect or is safe to run again.
1148
1157
 
1149
1158
  Args:
1150
1159
  key: Operation key, scoped to the tenant and operation (for example ``"order:42"``).
@@ -1152,6 +1161,7 @@ Acquire is ``SET NX PX``, renew is ``SET IFEQ PX`` and release is ``DELEX IFEQ``
1152
1161
  ttl_ms: Retention in milliseconds, 1 to 604800000 (7 days).
1153
1162
  fn: Zero-argument callable returning the result (``str`` or ``bytes``) to store.
1154
1163
  owner: Attempt token; a random one is generated when omitted.
1164
+ abort_on_error: Release the reservation with ``IDEM ABORT`` when ``fn`` raises. Default ``False``.
1155
1165
 
1156
1166
  Returns:
1157
1167
  ``("executed", result)`` when ``fn`` ran now, ``("completed", stored_result)`` when an earlier run
@@ -1164,7 +1174,15 @@ Acquire is ``SET NX PX``, renew is ``SET IFEQ PX`` and release is ``DELEX IFEQ``
1164
1174
  owner = owner or uuid.uuid4().hex
1165
1175
  r = self.idem_begin(key, fingerprint, owner, ttl_ms)
1166
1176
  if r.state == "acquired":
1167
- result = fn()
1177
+ try:
1178
+ result = fn()
1179
+ except BaseException:
1180
+ if abort_on_error:
1181
+ try:
1182
+ self.idem_abort(key, fingerprint, owner)
1183
+ except Exception:
1184
+ pass # the record stays pending until ttl_ms; fn's error is the one raised
1185
+ raise
1168
1186
  self.idem_complete(key, fingerprint, owner, result)
1169
1187
  return "executed", result
1170
1188
  return r.state, r.result
@@ -546,7 +546,7 @@ class ClusterRuvio(Ruvio):
546
546
  return node.conn
547
547
  raise error
548
548
 
549
- def _redirect(self, err: MovedError, data: bytes, dec: bool) -> Any:
549
+ def _redirect(self, err: MovedError, data: bytes, dec: bool, clock: Optional[cl.TryAgainClock] = None) -> Any:
550
550
  """Follows ``-MOVED`` and ``-ASK`` (one budget of ``MAX_REDIRECTS`` per command) and re-sends after
551
551
  ``-TRYAGAIN`` (``TRYAGAIN_DELAYS``, one sleep before each re-send); the last error is returned when
552
552
  a budget runs out. ``ASK`` sends ``ASKING`` and the command to the named node and leaves the table alone."""
@@ -559,7 +559,12 @@ class ClusterRuvio(Ruvio):
559
559
  node = self._route_node(data)
560
560
  if node is None:
561
561
  return reply
562
- time.sleep(cl.TRYAGAIN_DELAYS[tries])
562
+ # One command keeps the fixed schedule; a pipeline's commands share a clock.
563
+ pause = cl.TRYAGAIN_DELAYS[tries] if clock is None else clock.pause(tries)
564
+ if pause is None:
565
+ return reply
566
+ if pause > 0:
567
+ time.sleep(pause)
563
568
  tries += 1
564
569
  reply = self._rt(node.conn, data, dec)
565
570
  else:
@@ -578,6 +583,10 @@ class ClusterRuvio(Ruvio):
578
583
  if reply.__class__ is not MovedError and not cl.is_tryagain(reply):
579
584
  return reply
580
585
 
586
+ def _tryagain_clock(self) -> cl.TryAgainClock:
587
+ """A fresh ``-TRYAGAIN`` budget, cut to the socket timeout when that is shorter than the schedule."""
588
+ return cl.TryAgainClock(self._conn.opts.socket_timeout)
589
+
581
590
  def _route_node(self, data: bytes) -> Optional[_Node]:
582
591
  """The node the current table names for a command's frame (the seed for a keyless one); None for a
583
592
  command that is split over several nodes or sent to all of them."""
@@ -771,9 +780,10 @@ class ClusterRuvio(Ruvio):
771
780
  nxt[i] = iter(r).__next__
772
781
  replies = [nxt[i]() for i in idx]
773
782
  if MovedError in set(map(type, replies)):
783
+ clock = self._tryagain_clock()
774
784
  for i, v in enumerate(replies):
775
785
  if v.__class__ is MovedError:
776
- replies[i] = self._redirect(v, payload[i], dec)
786
+ replies[i] = self._redirect(v, payload[i], dec, clock)
777
787
  return replies
778
788
 
779
789
  def _batch_split(self, payload: List[bytes], dec: bool) -> List[Any]:
@@ -793,9 +803,10 @@ class ClusterRuvio(Ruvio):
793
803
  replies[i] = v
794
804
  if failure is not None:
795
805
  raise failure
806
+ clock = self._tryagain_clock()
796
807
  for i, v in enumerate(replies):
797
808
  if v.__class__ is MovedError:
798
- replies[i] = self._redirect(v, payload[i] if i < n else subs[i - n][4], dec) # type: ignore[index]
809
+ replies[i] = self._redirect(v, payload[i] if i < n else subs[i - n][4], dec, clock) # type: ignore[index]
799
810
  return replies if subs is None else cl.merge_pipeline(replies, n, subs)
800
811
 
801
812
  def _batch_tx(self, payload: List[bytes], dec: bool) -> List[Any]:
@@ -23,6 +23,8 @@ __all__ = [
23
23
  "CrossSlotError",
24
24
  "LockError",
25
25
  "WatchError",
26
+ "is_transient",
27
+ "may_have_run",
26
28
  ]
27
29
 
28
30
 
@@ -157,3 +159,58 @@ class WatchError(RuvioError):
157
159
  """``EXEC`` returned nil: a watched key changed, so the transaction did not run. :meth:`ruvio.Ruvio.transaction`
158
160
  retries on it automatically.
159
161
  """
162
+
163
+
164
+ _TRANSIENT_CODES = frozenset(("LOADING", "MASTERDOWN", "CLUSTERDOWN", "TRYAGAIN", "READONLY", "NOREPLICAS"))
165
+
166
+
167
+ def is_transient(error: BaseException) -> bool:
168
+ """Tells whether the same call can succeed later without any change on the caller's side.
169
+
170
+ True for a failed or timed-out connection (:class:`ConnectionError`, :class:`TimeoutError`) and for the
171
+ server replies ``LOADING``, ``MASTERDOWN``, ``CLUSTERDOWN``, ``TRYAGAIN``, ``READONLY`` and ``NOREPLICAS``.
172
+ False for every other server reply (``WRONGTYPE``, ``OOM``, a syntax error), for :class:`ProtocolError`,
173
+ for a cancelled task and for any other exception.
174
+
175
+ The client already follows ``MOVED``/``ASK`` and waits out ``TRYAGAIN`` during a slot move; this judges what
176
+ still reaches the caller, for a retry policy of your own (tenacity, a loop). Retry only when it is true and
177
+ the command is safe to repeat (a read, a ``set`` of the same value, a command with an idempotency key) or
178
+ :func:`may_have_run` is false.
179
+
180
+ Example:
181
+ >>> from tenacity import retry, retry_if_exception, stop_after_attempt
182
+ >>> @retry( # incr is not safe to repeat: retry it only when it surely did not run
183
+ ... retry=retry_if_exception(lambda e: is_transient(e) and not may_have_run(e)),
184
+ ... stop=stop_after_attempt(3),
185
+ ... )
186
+ ... def visit(r):
187
+ ... return r.incr("visits")
188
+
189
+ Args:
190
+ error: The exception the call raised.
191
+
192
+ Returns:
193
+ Whether retrying later can succeed.
194
+ """
195
+ if isinstance(error, ResponseError):
196
+ return error.code in _TRANSIENT_CODES
197
+ return isinstance(error, ConnectionError)
198
+
199
+
200
+ def may_have_run(error: BaseException) -> bool:
201
+ """Tells whether the failed call may have changed data, so repeating a write that is not safe to repeat
202
+ could apply it twice.
203
+
204
+ False only for a server error reply (:class:`ResponseError`), which the server sends instead of running the
205
+ command. ``NOREPLICAS`` is the exception: the write was applied on the primary and only the replica
206
+ confirmation timed out. A failed connection, a timeout or a cancellation after sending may have run.
207
+
208
+ Args:
209
+ error: The exception the call raised.
210
+
211
+ Returns:
212
+ Whether the command may have been applied.
213
+ """
214
+ if isinstance(error, ResponseError):
215
+ return error.code == "NOREPLICAS"
216
+ return True
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ruvio-client
3
- Version: 0.1.3.dev33
3
+ Version: 0.2.0
4
4
  Summary: Fast sync and asyncio Python client for the Ruvio key-value server (RESP2/RESP3)
5
5
  Author: Salih Cantekin
6
6
  License: MIT
@@ -66,7 +66,7 @@ dependencies and needs Python 3.9 or newer. It ships type information (`py.typed
66
66
  The methods also cover the options that change Ruvio's behaviour: `SET … IFEQ`,
67
67
  `INCRBY … MAX`, `FILLGET … WAIT`, `FILLSET … SWR`, `GETEX` in milliseconds,
68
68
  `DELEX key IFEQ v`, `LPUSHCAP`/`RPUSHCAP`, `BF.*`, `JSON.*` (including `JSON.INDEX` and
69
- `JSON.FIND`), `IDEM BEGIN/COMPLETE`, `LEASE`/`RELEASE`, `SEMAPHORE`, `ONCE`, `TAKE`, `TRANSFER`/`HTRANSFER`, `SETV`,
69
+ `JSON.FIND`), `IDEM BEGIN/COMPLETE/ABORT`, `LEASE`/`RELEASE`, `SEMAPHORE`, `ONCE`, `TAKE`, `TRANSFER`/`HTRANSFER`, `SETV`,
70
70
  `CHANGES`, `LIMIT` and `XADD … DELAY`.
71
71
  - Pipelines, MULTI/EXEC transactions, Pub/Sub on a dedicated connection, and RESP3 through
72
72
  `HELLO 3`, including push messages.
@@ -216,7 +216,8 @@ to `on_push=callback` and never reach a command's reply.
216
216
  | `r.limit_sliding(key, max, window_ms)`, `r.limit_tokens(key, capacity, refill_ms, cost=1)` | `LIMIT ... SLIDING`, `LIMIT ... TOKENS` | remaining, or `None` |
217
217
  | `r.limit_sliding_with_retry(...)`, `r.limit_tokens_with_retry(...)` | `LIMIT ... WITHRETRY` | `(allowed, remaining, retry_after_ms)` |
218
218
  | `r.get_or_create(key, factory, ttl_ms, fill_ms=…, swr_ms=…)` | `FILLGET` / `FILLSET` | Exactly one caller runs `factory` (sync or async). Waiters poll plain `FILLGET` with backoff from 5 ms up to 100 ms instead of `WAIT`, which would park the shared connection |
219
- | `r.idempotent(key, fingerprint, ttl_ms, fn)` | `IDEM BEGIN` / `COMPLETE` | `("executed", result)`, `("completed", stored)`, `("pending", None)` or `("conflict", None)` |
219
+ | `r.idempotent(key, fingerprint, ttl_ms, fn, abort_on_error=False)` | `IDEM BEGIN` / `COMPLETE` (+ `ABORT`) | `("executed", result)`, `("completed", stored)`, `("pending", None)` or `("conflict", None)`. If `fn` raises the record stays pending until `ttl_ms`; with `abort_on_error=True` it sends `IDEM ABORT` first, so a retry runs `fn` again at once, and the original exception still propagates (a failed abort is ignored). Use it only when a failed `fn` did not take effect or is safe to run again |
220
+ | `r.idem_abort(key, fingerprint, owner)` | `IDEM ABORT` | `True` when the pending record of that owner and fingerprint was removed; `False` for a missing key, a completed record (its result is never removed) or another owner. Abort only when the work did not take effect or is safe to run again; a retry after an abort runs it again |
220
221
  | `r.scan_iter()` / `hscan_iter` / `sscan_iter` / `zscan_iter` | `SCAN` family | Lazy and driven by the cursor; async iterators on the asyncio client |
221
222
  | `r.json_set_obj` / `json_get_obj` / `json_mget_obj` | `JSON.SET` / `JSON.GET` / `JSON.MGET` | Uses the standard `json` module |
222
223
  | `r.push_recent(key, value, keep)` | `LPUSHCAP` | Newest first, keeps at most `keep` items |
@@ -422,6 +423,33 @@ client = Ruvio(seeds=["10.0.0.1:6379", ("10.0.0.2", 6379), "[::1]:6379"])
422
423
  table). Pipelines, fan-out commands and transactions do not trigger the reload on their own; they fail as
423
424
  before and the next single-key or keyless command reloads. Seeds are never asked while the known nodes answer.
424
425
 
426
+ ## Retry policies of your own
427
+
428
+ `ruvio.is_transient` and `ruvio.may_have_run` sort what a call raises, for a retry policy of your own
429
+ (tenacity, a loop). The client already follows `MOVED`/`ASK`, waits out `TRYAGAIN` during a slot move and
430
+ finds a new primary after a failover; these judge what still reaches you.
431
+
432
+ - `is_transient(e)`: trying again later can succeed. True for `ConnectionError` and `TimeoutError` and for
433
+ `LOADING`, `MASTERDOWN`, `CLUSTERDOWN`, `TRYAGAIN`, `READONLY` and `NOREPLICAS`; false for `WRONGTYPE`, `OOM`,
434
+ syntax errors, `ProtocolError` and a cancelled task.
435
+ - `may_have_run(e)`: the failed call may have changed data. False only for a server error reply (the server
436
+ refused the command), except `NOREPLICAS`: the write was applied and only the replica confirmation timed out.
437
+ A failed connection or a timeout may have run.
438
+
439
+ Repeat a write only when it is safe to repeat or did not run:
440
+
441
+ ```python
442
+ from tenacity import retry, retry_if_exception, stop_after_attempt
443
+ from ruvio import is_transient, may_have_run
444
+
445
+ # incr is not safe to repeat: retry it only when it surely did not run.
446
+ @retry(retry=retry_if_exception(lambda e: is_transient(e) and not may_have_run(e)), stop=stop_after_attempt(3))
447
+ def visit(r):
448
+ return r.incr("visits")
449
+ ```
450
+
451
+ For a read, `is_transient` alone is enough.
452
+
425
453
  ## Following a failover
426
454
 
427
455
  A standalone client with two or more `seeds`, or with `sentinel_master`, finds the primary again after a
@@ -36,6 +36,7 @@ tests/test_constants.py
36
36
  tests/test_coordinator_failover_live.py
37
37
  tests/test_coverage.py
38
38
  tests/test_durability_live.py
39
+ tests/test_errors.py
39
40
  tests/test_failover_live.py
40
41
  tests/test_follow_failover.py
41
42
  tests/test_follow_memory.py
@@ -336,6 +336,31 @@ async def test_tryagain_eight_times_gives_the_error_after_seven_retries(kind, ma
336
336
  await c.aclose()
337
337
 
338
338
 
339
+ async def test_pipeline_of_refused_commands_waits_for_one_tryagain_budget(make, fc):
340
+ k = key_in(8192, 16383)
341
+ slot = cl.key_slot(k)
342
+
343
+ def get(cl_, node, args):
344
+ # The stale owner redirects every command; the new owner is mid-handover and refuses each one.
345
+ if node is cl_.nodes[1]:
346
+ return err(f"MOVED {slot} {cl_.nodes[0].addr}")
347
+ return err("TRYAGAIN slot is being handed over")
348
+
349
+ cluster = fc(extra={"GET": get})
350
+ c = make(cluster.nodes[0].addr)
351
+ p = pipe(c)
352
+ for _ in range(100):
353
+ p.get(k)
354
+ t0 = time.monotonic()
355
+ res = await maybe(p.execute(raise_on_error=False))
356
+ elapsed = time.monotonic() - t0
357
+ assert len(res) == 100
358
+ assert all(isinstance(r, ruvio.ResponseError) and str(r).startswith("TRYAGAIN") for r in res)
359
+ # One budget of 635 ms, not 100 of them; the bound leaves room for a slow machine.
360
+ assert 0.634 <= elapsed < 5.0, elapsed
361
+ await c.aclose()
362
+
363
+
339
364
  async def test_ask_and_moved_share_one_redirect_budget(kind, make, fc):
340
365
  k = key_in(8192, 16383)
341
366
  slot = cl.key_slot(k)
@@ -319,3 +319,81 @@ def test_transfer_commands_encode_the_optional_cap_and_return_a_pair():
319
319
  r.reply = None
320
320
  assert r.transfer("a", "b", 4) is None
321
321
  assert r.htransfer("h", "f", "g", 1) is None
322
+
323
+
324
+ # --------------------------------------------------------------------------- IDEM ABORT
325
+
326
+
327
+ @pytest.mark.parametrize("reply,expected", [(1, True), (0, False)])
328
+ def test_idem_abort_encoding_and_reply(reply, expected):
329
+ r = Rec(reply)
330
+ assert r.idem_abort("k", "fp", "me") is expected
331
+ assert r.args == ["IDEM", "k", "ABORT", "fp", "me"]
332
+
333
+
334
+ class _IdemStub:
335
+ """Just the three methods ``idempotent`` calls, recording whether ABORT was sent."""
336
+
337
+ def __init__(self, abort_fails=False):
338
+ self.aborts = []
339
+ self.abort_fails = abort_fails
340
+
341
+ def idem_begin(self, key, fingerprint, owner, ttl_ms):
342
+ from ruvio import IdemResult
343
+
344
+ return IdemResult("acquired", None)
345
+
346
+ def idem_complete(self, key, fingerprint, owner, result):
347
+ return 1
348
+
349
+ def idem_abort(self, key, fingerprint, owner):
350
+ self.aborts.append((key, fingerprint, owner))
351
+ if self.abort_fails:
352
+ raise ConnectionError("down")
353
+ return True
354
+
355
+
356
+ @pytest.mark.parametrize("flag", [False, True])
357
+ @pytest.mark.parametrize("abort_fails", [False, True])
358
+ def test_idempotent_aborts_only_when_asked_and_keeps_the_error(flag, abort_fails):
359
+ import ruvio
360
+
361
+ stub = _IdemStub(abort_fails)
362
+
363
+ def boom():
364
+ raise RuntimeError("boom")
365
+
366
+ with pytest.raises(RuntimeError, match="boom"):
367
+ ruvio.Ruvio.idempotent(stub, "k", "fp", 1000, boom, owner="me", abort_on_error=flag)
368
+ assert stub.aborts == ([("k", "fp", "me")] if flag else [])
369
+
370
+
371
+ @pytest.mark.parametrize("flag", [False, True])
372
+ def test_async_idempotent_aborts_only_when_asked(flag):
373
+ import asyncio
374
+
375
+ import ruvio.asyncio
376
+
377
+ stub = _IdemStub()
378
+
379
+ async def begin(*a):
380
+ return stub.idem_begin(*a)
381
+
382
+ async def abort(*a):
383
+ return stub.idem_abort(*a)
384
+
385
+ stub.idem_begin_async, stub.idem_abort_async = begin, abort
386
+
387
+ class AStub:
388
+ idem_begin = staticmethod(begin)
389
+ idem_abort = staticmethod(abort)
390
+
391
+ async def boom():
392
+ raise RuntimeError("boom")
393
+
394
+ async def run():
395
+ await ruvio.asyncio.Ruvio.idempotent(AStub(), "k", "fp", 1000, boom, owner="me", abort_on_error=flag)
396
+
397
+ with pytest.raises(RuntimeError, match="boom"):
398
+ asyncio.run(run())
399
+ assert stub.aborts == ([("k", "fp", "me")] if flag else [])
@@ -37,7 +37,7 @@ COMMANDS = _command_methods()
37
37
 
38
38
  # Sub-forms and options with their own methods (also checked for existence and live use).
39
39
  EXTRA = [
40
- "command_count", "command_info", "command_docs", "slowlog_len", "slowlog_reset", "idem_complete",
40
+ "command_count", "command_info", "command_docs", "slowlog_len", "slowlog_reset", "idem_complete", "idem_abort",
41
41
  "changes_start", "object_idletime", "object_freq", "json_index_drop", "json_index_list", "xpending_range",
42
42
  "rate_limit", "limit_sliding", "limit_tokens", "limit_sliding_with_retry", "limit_tokens_with_retry", "seen_before", "push_recent", "json_get_obj", "json_set_obj", "json_mget_obj",
43
43
  "execute_command", "lock", "lease_scope", "semaphore_scope", "get_or_create", "idempotent",
@@ -0,0 +1,56 @@
1
+ """The retry classification every client shares: which failures a retry can get past and which may have run."""
2
+
3
+ import asyncio
4
+
5
+ import pytest
6
+
7
+ from ruvio import (
8
+ ConnectionError,
9
+ ProtocolError,
10
+ ResponseError,
11
+ TimeoutError,
12
+ is_transient,
13
+ may_have_run,
14
+ )
15
+ from ruvio.errors import make_error
16
+
17
+ TRANSIENT_REPLIES = [
18
+ "LOADING Ruvio is loading the dataset in memory",
19
+ "MASTERDOWN Link with MASTER is down",
20
+ "CLUSTERDOWN The cluster is down",
21
+ "TRYAGAIN slot is moving",
22
+ "READONLY You can't write against a read only replica.",
23
+ "NOREPLICAS Not enough good replicas to write.",
24
+ ]
25
+
26
+
27
+ @pytest.mark.parametrize("reply", TRANSIENT_REPLIES)
28
+ def test_retryable_replies_are_transient(reply):
29
+ assert is_transient(make_error(reply))
30
+
31
+
32
+ @pytest.mark.parametrize(
33
+ "reply", ["WRONGTYPE Operation against a key", "OOM command not allowed", "ERR syntax error", "READONLYX x", "LOAD"]
34
+ )
35
+ def test_other_replies_are_not_transient(reply):
36
+ assert not is_transient(make_error(reply))
37
+
38
+
39
+ def test_connection_failures_are_transient_and_others_are_not():
40
+ assert is_transient(ConnectionError("connection closed by server"))
41
+ assert is_transient(TimeoutError("timed out waiting for the reply"))
42
+ assert not is_transient(ProtocolError("bad frame"))
43
+ assert not is_transient(asyncio.CancelledError())
44
+ assert not is_transient(ValueError("bad"))
45
+
46
+
47
+ def test_only_a_refusing_server_reply_surely_did_not_run():
48
+ assert not may_have_run(make_error("WRONGTYPE Operation against a key"))
49
+ assert not may_have_run(make_error("TRYAGAIN slot is moving"))
50
+ assert not may_have_run(ResponseError("READONLY replica"))
51
+ assert may_have_run(make_error("NOREPLICAS Not enough good replicas to write."))
52
+ assert may_have_run(make_error("NOREPLICAS"))
53
+ assert may_have_run(ConnectionError("reset"))
54
+ assert may_have_run(TimeoutError("slow"))
55
+ assert may_have_run(ProtocolError("bad frame"))
56
+ assert may_have_run(asyncio.CancelledError())
@@ -95,6 +95,17 @@ def test_sync_idempotent_and_rate_limit(sync_client):
95
95
  assert r.idempotent(key, "fp", 10000, lambda: runs.append(1) or "again") == ("completed", "done")
96
96
  assert r.idempotent(key, "other", 10000, lambda: "x")[0] == "conflict"
97
97
  assert runs == [1]
98
+
99
+ def boom():
100
+ raise RuntimeError("boom")
101
+
102
+ # abort_on_error frees the key after a failing fn; without it the key stays pending
103
+ with pytest.raises(RuntimeError):
104
+ r.idempotent(key + ":a", "fp", 10000, boom, abort_on_error=True)
105
+ assert r.idempotent(key + ":a", "fp", 10000, lambda: "again") == ("executed", "again")
106
+ with pytest.raises(RuntimeError):
107
+ r.idempotent(key + ":k", "fp", 10000, boom)
108
+ assert r.idempotent(key + ":k", "fp", 10000, lambda: "x") == ("pending", None)
98
109
  assert [r.rate_limit("rl:" + key, 3, 10000) for _ in range(4)] == [(True, 2), (True, 1), (True, 0), (False, 0)]
99
110
 
100
111
 
@@ -314,6 +325,16 @@ async def test_async_idempotent(async_client):
314
325
  assert await r.idempotent(key, "fp", 10000, work) == ("executed", "ok")
315
326
  assert await r.idempotent(key, "fp", 10000, work) == ("completed", "ok")
316
327
 
328
+ async def boom():
329
+ raise RuntimeError("boom")
330
+
331
+ with pytest.raises(RuntimeError):
332
+ await r.idempotent(key + ":a", "fp", 10000, boom, abort_on_error=True)
333
+ assert await r.idempotent(key + ":a", "fp", 10000, work) == ("executed", "ok")
334
+ with pytest.raises(RuntimeError):
335
+ await r.idempotent(key + ":k", "fp", 10000, boom)
336
+ assert await r.idempotent(key + ":k", "fp", 10000, work) == ("pending", None)
337
+
317
338
 
318
339
  async def test_async_pubsub(async_client):
319
340
  r = async_client
@@ -232,6 +232,15 @@ async def test_idem_and_changes(c):
232
232
  assert await c.idem_complete("idem", "fp", "owner1", "result") == 1
233
233
  assert await c.idem_begin("idem", "fp", "owner2", 10000) == IdemResult("completed", "result")
234
234
  assert (await c.idem_begin("idem", "fp2", "owner2", 10000)).state == "conflict"
235
+ # abort frees a pending record, never a completed one, and only for its owner
236
+ assert (await c.idem_begin("idem-abort", "fp", "o1", 10000)).state == "acquired"
237
+ assert await c.idem_abort("idem-abort", "fp", "o2") is False
238
+ assert await c.idem_abort("idem-abort", "other", "o1") is False
239
+ assert await c.idem_abort("idem-abort", "fp", "o1") is True
240
+ assert (await c.idem_begin("idem-abort", "fp", "o2", 10000)).state == "acquired"
241
+ assert await c.idem_complete("idem-abort", "fp", "o2", "kept") == 1
242
+ assert await c.idem_abort("idem-abort", "fp", "o2") is False
243
+ assert await c.idem_begin("idem-abort", "fp", "o3", 10000) == IdemResult("completed", "kept")
235
244
  cursor = await c.changes_start()
236
245
  await c.set("chg", "1")
237
246
  notes = await c.changes(cursor)
File without changes