ruvio-client 0.1.3.dev33__tar.gz → 0.2.1__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.
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/PKG-INFO +33 -5
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/README.md +32 -4
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/pyproject.toml +1 -1
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/__init__.py +5 -1
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_cluster.py +33 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_command_keys.py +1 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_commands.py +40 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/asyncio/client.py +16 -4
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/asyncio/cluster.py +69 -10
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/client.py +20 -2
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/cluster.py +35 -4
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/errors.py +57 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio_client.egg-info/PKG-INFO +33 -5
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio_client.egg-info/SOURCES.txt +2 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_cluster_edge.py +25 -0
- ruvio_client-0.2.1/tests/test_cluster_failover_live.py +79 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_command_encoding.py +78 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_coverage.py +1 -1
- ruvio_client-0.2.1/tests/test_errors.py +56 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_helpers_live.py +21 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_live.py +12 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/LICENSE +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_blocking.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_constants.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_converters.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_follow.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_models.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_pipeline.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_resp.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/_tls.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/asyncio/__init__.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio/py.typed +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio_client.egg-info/dependency_links.txt +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio_client.egg-info/requires.txt +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/ruvio_client.egg-info/top_level.txt +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/setup.cfg +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_asyncio_timeout.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_client_edge.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_cluster_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_cluster_pure.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_cluster_unit.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_constants.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_coordinator_failover_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_durability_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_failover_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_follow_failover.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_follow_memory.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_key_vectors.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_multi_node_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_replica_reads.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_replica_reads_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_resp.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_resp_edge.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_resp_vectors.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_seeds.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_slot_vectors.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/tests/test_tls_live.py +0 -0
- {ruvio_client-0.1.3.dev33 → ruvio_client-0.2.1}/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
|
+
Version: 0.2.1
|
|
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
|
|
@@ -62,11 +62,11 @@ dependencies and needs Python 3.9 or newer. It ships type information (`py.typed
|
|
|
62
62
|
- `ruvio.Ruvio` is the synchronous client. It uses one socket and a reusable `recv_into` buffer.
|
|
63
63
|
- `ruvio.asyncio.Ruvio` is the asyncio client. It keeps one multiplexed, pipelined connection
|
|
64
64
|
that all coroutines share.
|
|
65
|
-
- There is a typed method for each of the **
|
|
65
|
+
- There is a typed method for each of the **300** commands in `docs/compatibility-matrix.json`.
|
|
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
|
|
@@ -486,7 +514,7 @@ RUVIO_TEST_FLUSHALL=1 ... # also r
|
|
|
486
514
|
has no typed method on the sync or the async client. It also fails when a typed method is
|
|
487
515
|
never called by a live test.
|
|
488
516
|
- `tests/test_cluster_unit.py` needs no Ruvio server: slot vectors and hashtags, key
|
|
489
|
-
extraction through the typed methods, a check that **all
|
|
517
|
+
extraction through the typed methods, a check that **all 300 matrix commands have a routing
|
|
490
518
|
rule**, topology / `MOVED` / scan-cursor parsing, and the router against scripted fake servers
|
|
491
519
|
(`tests/fakecluster.py`) on both clients: owner-only routing, fail-fast `CROSSSLOT` (no byte
|
|
492
520
|
sent), split reassembly order, `MOVED` patch / refresh / unknown node / at most 3 redirects, no
|
|
@@ -27,11 +27,11 @@ dependencies and needs Python 3.9 or newer. It ships type information (`py.typed
|
|
|
27
27
|
- `ruvio.Ruvio` is the synchronous client. It uses one socket and a reusable `recv_into` buffer.
|
|
28
28
|
- `ruvio.asyncio.Ruvio` is the asyncio client. It keeps one multiplexed, pipelined connection
|
|
29
29
|
that all coroutines share.
|
|
30
|
-
- There is a typed method for each of the **
|
|
30
|
+
- There is a typed method for each of the **300** commands in `docs/compatibility-matrix.json`.
|
|
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
|
|
@@ -451,7 +479,7 @@ RUVIO_TEST_FLUSHALL=1 ... # also r
|
|
|
451
479
|
has no typed method on the sync or the async client. It also fails when a typed method is
|
|
452
480
|
never called by a live test.
|
|
453
481
|
- `tests/test_cluster_unit.py` needs no Ruvio server: slot vectors and hashtags, key
|
|
454
|
-
extraction through the typed methods, a check that **all
|
|
482
|
+
extraction through the typed methods, a check that **all 300 matrix commands have a routing
|
|
455
483
|
rule**, topology / `MOVED` / scan-cursor parsing, and the router against scripted fake servers
|
|
456
484
|
(`tests/fakecluster.py`) on both clients: owner-only routing, fail-fast `CROSSSLOT` (no byte
|
|
457
485
|
sent), split reassembly order, `MOVED` patch / refresh / unknown node / at most 3 redirects, no
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "ruvio-client"
|
|
7
|
-
version = "0.1
|
|
7
|
+
version = "0.2.1"
|
|
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
|
|
93
|
+
__version__ = "0.2.1"
|
|
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
|
|
|
@@ -202,6 +202,7 @@ COMMAND_KEY_RULES = {
|
|
|
202
202
|
b"SETNX": (1, 1, 1, 1, (), 13),
|
|
203
203
|
b"SETRANGE": (1, 1, 1, 1, (), 9),
|
|
204
204
|
b"SETV": (1, 1, 1, 1, (), 13),
|
|
205
|
+
b"SHUTDOWN": (0, 0, 0, 0, (), 0),
|
|
205
206
|
b"SINTER": (1, 1, -1, 1, (), 2),
|
|
206
207
|
b"SINTERCARD": (2, 1, 0, 0, (), 2),
|
|
207
208
|
b"SINTERSTORE": (1, 1, -1, 1, (), 9),
|
|
@@ -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
|
|
|
@@ -5572,6 +5593,25 @@ Sends ``XCLAIM key group consumer min_idle_ms id... [IDLE ms] [TIME ms] [RETRYCO
|
|
|
5572
5593
|
"""
|
|
5573
5594
|
return self._c(None, "BGSAVE")
|
|
5574
5595
|
|
|
5596
|
+
def shutdown(self, *rest) -> Any:
|
|
5597
|
+
"""``SHUTDOWN`` - stops the server the way ``SIGTERM`` does.
|
|
5598
|
+
|
|
5599
|
+
The server drains its clients, flushes its log and writes a final checkpoint; a
|
|
5600
|
+
supervisor has to start it again. Under durability ``memory`` nothing is saved, so the
|
|
5601
|
+
server refuses unless ``rest`` is ``"NOSAVE"``: every key is lost. ``NOSAVE`` is refused
|
|
5602
|
+
under a saving profile.
|
|
5603
|
+
|
|
5604
|
+
Args:
|
|
5605
|
+
*rest: Nothing, ``"SAVE"`` or ``"NOSAVE"``.
|
|
5606
|
+
|
|
5607
|
+
Returns:
|
|
5608
|
+
``OK``, sent before the server stops.
|
|
5609
|
+
|
|
5610
|
+
Raises:
|
|
5611
|
+
ResponseError: The server refused (see above).
|
|
5612
|
+
"""
|
|
5613
|
+
return self._c(None, "SHUTDOWN", *rest)
|
|
5614
|
+
|
|
5575
5615
|
# ======================================================= transactions (raw)
|
|
5576
5616
|
def multi(self) -> Any:
|
|
5577
5617
|
"""``MULTI`` - raw transaction start. Prefer ``pipeline(transaction=True)`` or :meth:`transaction`.
|
|
@@ -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
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
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
|
|
@@ -17,6 +17,7 @@ from typing import Any, Awaitable, Dict, List, Optional, Tuple
|
|
|
17
17
|
from .. import _cluster as cl
|
|
18
18
|
from .._blocking import pipeline_wait
|
|
19
19
|
from .._commands import Conv
|
|
20
|
+
from .._follow import is_readonly
|
|
20
21
|
from .._pipeline import _EXEC, _MULTI
|
|
21
22
|
from ..client import _Options, _ReplicaOptions
|
|
22
23
|
from ..errors import ConnectionError, CrossSlotError, MovedError, ResponseError, RuvioError
|
|
@@ -42,7 +43,10 @@ class _Node:
|
|
|
42
43
|
|
|
43
44
|
|
|
44
45
|
class _State:
|
|
45
|
-
__slots__ = (
|
|
46
|
+
__slots__ = (
|
|
47
|
+
"mode", "slots", "nodes", "by_addr", "seed", "watch", "gate", "targets", "policy", "reps", "rnodes",
|
|
48
|
+
"reloads", "reloading",
|
|
49
|
+
)
|
|
46
50
|
|
|
47
51
|
def __init__(self, seed: _Node) -> None:
|
|
48
52
|
self.mode = 0
|
|
@@ -56,17 +60,19 @@ class _State:
|
|
|
56
60
|
self.policy = cl.POLICY_PRIMARY # where reads go; anything but primary adds the replica paths
|
|
57
61
|
self.reps: List[Optional[_Node]] = [] # per node index: the replica its reads go to (None = none usable)
|
|
58
62
|
self.rnodes: Dict[Tuple[str, int], _Node] = {} # the replica nodes of the last load, by address
|
|
63
|
+
self.reloads = 0 # slot tables installed; a READONLY that saw an older count skips its own reload
|
|
64
|
+
self.reloading: Optional[asyncio.Future] = None # type: ignore[type-arg] # the reload READONLY replies share
|
|
59
65
|
|
|
60
66
|
|
|
61
67
|
class _RoutedFuture(asyncio.Future): # type: ignore[type-arg]
|
|
62
68
|
"""The future of a single-key command handed to the shared connection. It behaves like any
|
|
63
|
-
future; only a ``-MOVED`` / ``-ASK`` / ``-TRYAGAIN`` reply is intercepted (in ``set_exception``) and followed to the node
|
|
69
|
+
future; only a ``-MOVED`` / ``-ASK`` / ``-TRYAGAIN`` / ``-READONLY`` reply is intercepted (in ``set_exception``) and followed to the node
|
|
64
70
|
the reply names. This keeps the warm path free of an extra coroutine."""
|
|
65
71
|
|
|
66
72
|
__slots__ = ("owner", "data", "conv", "dec")
|
|
67
73
|
|
|
68
74
|
def set_exception(self, exc: BaseException) -> None:
|
|
69
|
-
if (exc.__class__ is MovedError or (exc.__class__ is ResponseError and cl.is_tryagain(exc))) and not self.done():
|
|
75
|
+
if (exc.__class__ is MovedError or (exc.__class__ is ResponseError and (cl.is_tryagain(exc) or is_readonly(exc)))) and not self.done():
|
|
70
76
|
asyncio.ensure_future(self.owner._retry_moved(self, exc), loop=self.get_loop())
|
|
71
77
|
else:
|
|
72
78
|
asyncio.Future.set_exception(self, exc)
|
|
@@ -302,6 +308,7 @@ class ClusterRuvio(Ruvio):
|
|
|
302
308
|
c.nodes = nodes
|
|
303
309
|
c.by_addr = by
|
|
304
310
|
c.slots = topo.slots
|
|
311
|
+
c.reloads += 1
|
|
305
312
|
c.targets = [*nodes, c.seed]
|
|
306
313
|
if c.policy:
|
|
307
314
|
self._pick_replicas(topo)
|
|
@@ -479,7 +486,7 @@ class ClusterRuvio(Ruvio):
|
|
|
479
486
|
try:
|
|
480
487
|
return await fut
|
|
481
488
|
except ResponseError as err:
|
|
482
|
-
if err.__class__ is MovedError or cl.is_tryagain(err):
|
|
489
|
+
if err.__class__ is MovedError or cl.is_tryagain(err) or is_readonly(err):
|
|
483
490
|
return await self._redirect(err, data, conv, dec, False)
|
|
484
491
|
raise
|
|
485
492
|
|
|
@@ -579,10 +586,15 @@ class ClusterRuvio(Ruvio):
|
|
|
579
586
|
return proto
|
|
580
587
|
raise error
|
|
581
588
|
|
|
582
|
-
async def _redirect(
|
|
589
|
+
async def _redirect(
|
|
590
|
+
self, err: ResponseError, data: bytes, conv: Conv, dec: bool, blocking: bool, clock: Optional[cl.TryAgainClock] = None
|
|
591
|
+
) -> Any:
|
|
583
592
|
"""Follows ``-MOVED`` and ``-ASK`` (one budget of ``MAX_REDIRECTS`` per command) and re-sends after
|
|
584
593
|
``-TRYAGAIN`` (``TRYAGAIN_DELAYS``, one ``asyncio.sleep`` before each re-send); the last error is raised
|
|
585
|
-
when a budget runs out. ``ASK`` sends ``ASKING`` and the command to the named node and leaves the table alone.
|
|
594
|
+
when a budget runs out. ``ASK`` sends ``ASKING`` and the command to the named node and leaves the table alone.
|
|
595
|
+
``-READONLY`` goes to :meth:`_readonly`."""
|
|
596
|
+
if is_readonly(err):
|
|
597
|
+
return await self._readonly(err, data, conv, dec, blocking)
|
|
586
598
|
hops = moved = tries = 0
|
|
587
599
|
while True:
|
|
588
600
|
ask = None
|
|
@@ -590,7 +602,12 @@ class ClusterRuvio(Ruvio):
|
|
|
590
602
|
node = self._route_node(data)
|
|
591
603
|
if node is None or tries == len(cl.TRYAGAIN_DELAYS):
|
|
592
604
|
raise err
|
|
593
|
-
|
|
605
|
+
# One command keeps the fixed schedule; a pipeline's commands share a clock.
|
|
606
|
+
pause = cl.TRYAGAIN_DELAYS[tries] if clock is None else clock.pause(tries)
|
|
607
|
+
if pause is None:
|
|
608
|
+
raise err
|
|
609
|
+
if pause > 0:
|
|
610
|
+
await asyncio.sleep(pause)
|
|
594
611
|
tries += 1
|
|
595
612
|
else:
|
|
596
613
|
if hops == cl.MAX_REDIRECTS:
|
|
@@ -616,6 +633,46 @@ class ClusterRuvio(Ruvio):
|
|
|
616
633
|
raise
|
|
617
634
|
err = e
|
|
618
635
|
|
|
636
|
+
async def _readonly(self, err: ResponseError, data: bytes, conv: Conv, dec: bool, blocking: bool) -> Any:
|
|
637
|
+
"""After ``-READONLY``: the node that owned the slot was demoted by a failover. The slot table is
|
|
638
|
+
reloaded and, when it names another node for the command, the command is sent there once (``READONLY``
|
|
639
|
+
is sent before a command runs, so it was not applied). The retry's reply, an error included, is
|
|
640
|
+
returned; when the table names the same node, or a ``WATCH`` is open, ``err`` is raised."""
|
|
641
|
+
c = self._cl
|
|
642
|
+
seen = c.reloads
|
|
643
|
+
before = self._route_node(data)
|
|
644
|
+
if before is None or not await self._reload_after(seen):
|
|
645
|
+
raise err
|
|
646
|
+
after = self._route_node(data)
|
|
647
|
+
if after is None or (after.host, after.port) == (before.host, before.port) or c.watch is not None:
|
|
648
|
+
raise err
|
|
649
|
+
try:
|
|
650
|
+
if blocking:
|
|
651
|
+
return await self._send_blocking(after, data, conv, dec)
|
|
652
|
+
return await self._send(after, data, conv, dec)
|
|
653
|
+
except ResponseError as e:
|
|
654
|
+
if e.__class__ is MovedError or cl.is_tryagain(e):
|
|
655
|
+
return await self._redirect(e, data, conv, dec, blocking)
|
|
656
|
+
raise
|
|
657
|
+
|
|
658
|
+
async def _reload_after(self, seen: int) -> bool:
|
|
659
|
+
"""Reloads the slot table unless one was installed since the reload count was ``seen``. The commands a
|
|
660
|
+
demoted node refused at once share one ``CLUSTER SLOTS``: a reload already running is awaited."""
|
|
661
|
+
c = self._cl
|
|
662
|
+
if c.reloads != seen:
|
|
663
|
+
return True
|
|
664
|
+
task = c.reloading
|
|
665
|
+
if task is None:
|
|
666
|
+
task = c.reloading = asyncio.ensure_future(self._refresh())
|
|
667
|
+
task.add_done_callback(self._reloaded)
|
|
668
|
+
return bool(await asyncio.shield(task))
|
|
669
|
+
|
|
670
|
+
def _reloaded(self, task: "asyncio.Future[bool]") -> None:
|
|
671
|
+
if self._cl.reloading is task:
|
|
672
|
+
self._cl.reloading = None
|
|
673
|
+
if not task.cancelled():
|
|
674
|
+
task.exception()
|
|
675
|
+
|
|
619
676
|
def _route_node(self, data: bytes) -> Optional[_Node]:
|
|
620
677
|
"""The node the current table names for a command's frame (the seed for a keyless one); None for a
|
|
621
678
|
command that is split over several nodes or sent to all of them."""
|
|
@@ -695,7 +752,7 @@ class ClusterRuvio(Ruvio):
|
|
|
695
752
|
node = await self._open_owner(slot)
|
|
696
753
|
return await self._send(node, data, conv, dec)
|
|
697
754
|
except ResponseError as err:
|
|
698
|
-
if err.__class__ is MovedError or cl.is_tryagain(err):
|
|
755
|
+
if err.__class__ is MovedError or cl.is_tryagain(err) or is_readonly(err):
|
|
699
756
|
return await self._redirect(err, data, conv, dec, blocking)
|
|
700
757
|
raise
|
|
701
758
|
|
|
@@ -844,10 +901,11 @@ class ClusterRuvio(Ruvio):
|
|
|
844
901
|
nxt[i] = iter(r).__next__
|
|
845
902
|
replies = [nxt[i]() for i in idx]
|
|
846
903
|
if MovedError in set(map(type, replies)):
|
|
904
|
+
clock = cl.TryAgainClock()
|
|
847
905
|
for i, v in enumerate(replies):
|
|
848
906
|
if v.__class__ is MovedError:
|
|
849
907
|
try:
|
|
850
|
-
replies[i] = await self._redirect(v, payload[i], None, dec, False)
|
|
908
|
+
replies[i] = await self._redirect(v, payload[i], None, dec, False, clock)
|
|
851
909
|
except ResponseError as e:
|
|
852
910
|
replies[i] = e
|
|
853
911
|
return replies
|
|
@@ -869,11 +927,12 @@ class ClusterRuvio(Ruvio):
|
|
|
869
927
|
replies[i] = v
|
|
870
928
|
if failure is not None:
|
|
871
929
|
raise failure
|
|
930
|
+
clock = cl.TryAgainClock()
|
|
872
931
|
for i, v in enumerate(replies):
|
|
873
932
|
if v.__class__ is MovedError:
|
|
874
933
|
frame = payload[i] if i < n else subs[i - n][4] # type: ignore[index]
|
|
875
934
|
try:
|
|
876
|
-
replies[i] = await self._redirect(v, frame, None, dec, False)
|
|
935
|
+
replies[i] = await self._redirect(v, frame, None, dec, False, clock)
|
|
877
936
|
except ResponseError as e:
|
|
878
937
|
replies[i] = e
|
|
879
938
|
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,
|
|
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
|
-
|
|
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
|
|
@@ -25,6 +25,7 @@ from typing import Any, Dict, List, Optional, Tuple
|
|
|
25
25
|
from . import _cluster as cl
|
|
26
26
|
from ._blocking import FOREVER, blocking_wait, frames_wait, pipeline_wait
|
|
27
27
|
from ._commands import Conv
|
|
28
|
+
from ._follow import is_readonly
|
|
28
29
|
from ._pipeline import _EXEC, _MULTI
|
|
29
30
|
from .client import PubSub, Ruvio, _Conn, _Options, _ReplicaOptions
|
|
30
31
|
from .errors import ConnectionError, CrossSlotError, MovedError, ResponseError, RuvioError, TimeoutError
|
|
@@ -420,10 +421,29 @@ class ClusterRuvio(Ruvio):
|
|
|
420
421
|
if isinstance(reply, ResponseError):
|
|
421
422
|
if cl.is_tryagain(reply): # only an error reply gets here
|
|
422
423
|
reply = self._redirect(reply, data, dec)
|
|
424
|
+
elif is_readonly(reply):
|
|
425
|
+
reply = self._readonly(reply, data, dec)
|
|
423
426
|
if isinstance(reply, ResponseError):
|
|
424
427
|
raise reply
|
|
425
428
|
return reply if conv is None else conv(reply)
|
|
426
429
|
|
|
430
|
+
def _readonly(self, err: ResponseError, data: bytes, dec: bool) -> Any:
|
|
431
|
+
"""After ``-READONLY``: the node that owned the slot was demoted by a failover. The slot table is
|
|
432
|
+
reloaded and, when it names another node for the command, the command is sent there once (``READONLY``
|
|
433
|
+
is sent before a command runs, so it was not applied). The retry's reply, an error included, is
|
|
434
|
+
returned; when the table names the same node, or a ``WATCH`` is open, ``err`` is returned."""
|
|
435
|
+
c = self._cl
|
|
436
|
+
before = self._route_node(data)
|
|
437
|
+
if before is None or not self._refresh():
|
|
438
|
+
return err
|
|
439
|
+
after = self._route_node(data)
|
|
440
|
+
if after is None or (after.host, after.port) == (before.host, before.port) or c.watch is not None:
|
|
441
|
+
return err
|
|
442
|
+
reply = self._rt(after.conn, data, dec)
|
|
443
|
+
if reply.__class__ is MovedError:
|
|
444
|
+
reply = self._redirect(reply, data, dec)
|
|
445
|
+
return reply
|
|
446
|
+
|
|
427
447
|
def _open_target(self, ni: int, data: bytes) -> _Conn:
|
|
428
448
|
"""Opens the socket of target ``ni`` for an ordinary command. When the node cannot be
|
|
429
449
|
reached the slot table is reloaded and the command goes to the owner the new table names (a
|
|
@@ -546,7 +566,7 @@ class ClusterRuvio(Ruvio):
|
|
|
546
566
|
return node.conn
|
|
547
567
|
raise error
|
|
548
568
|
|
|
549
|
-
def _redirect(self, err: MovedError, data: bytes, dec: bool) -> Any:
|
|
569
|
+
def _redirect(self, err: MovedError, data: bytes, dec: bool, clock: Optional[cl.TryAgainClock] = None) -> Any:
|
|
550
570
|
"""Follows ``-MOVED`` and ``-ASK`` (one budget of ``MAX_REDIRECTS`` per command) and re-sends after
|
|
551
571
|
``-TRYAGAIN`` (``TRYAGAIN_DELAYS``, one sleep before each re-send); the last error is returned when
|
|
552
572
|
a budget runs out. ``ASK`` sends ``ASKING`` and the command to the named node and leaves the table alone."""
|
|
@@ -559,7 +579,12 @@ class ClusterRuvio(Ruvio):
|
|
|
559
579
|
node = self._route_node(data)
|
|
560
580
|
if node is None:
|
|
561
581
|
return reply
|
|
562
|
-
|
|
582
|
+
# One command keeps the fixed schedule; a pipeline's commands share a clock.
|
|
583
|
+
pause = cl.TRYAGAIN_DELAYS[tries] if clock is None else clock.pause(tries)
|
|
584
|
+
if pause is None:
|
|
585
|
+
return reply
|
|
586
|
+
if pause > 0:
|
|
587
|
+
time.sleep(pause)
|
|
563
588
|
tries += 1
|
|
564
589
|
reply = self._rt(node.conn, data, dec)
|
|
565
590
|
else:
|
|
@@ -578,6 +603,10 @@ class ClusterRuvio(Ruvio):
|
|
|
578
603
|
if reply.__class__ is not MovedError and not cl.is_tryagain(reply):
|
|
579
604
|
return reply
|
|
580
605
|
|
|
606
|
+
def _tryagain_clock(self) -> cl.TryAgainClock:
|
|
607
|
+
"""A fresh ``-TRYAGAIN`` budget, cut to the socket timeout when that is shorter than the schedule."""
|
|
608
|
+
return cl.TryAgainClock(self._conn.opts.socket_timeout)
|
|
609
|
+
|
|
581
610
|
def _route_node(self, data: bytes) -> Optional[_Node]:
|
|
582
611
|
"""The node the current table names for a command's frame (the seed for a keyless one); None for a
|
|
583
612
|
command that is split over several nodes or sent to all of them."""
|
|
@@ -771,9 +800,10 @@ class ClusterRuvio(Ruvio):
|
|
|
771
800
|
nxt[i] = iter(r).__next__
|
|
772
801
|
replies = [nxt[i]() for i in idx]
|
|
773
802
|
if MovedError in set(map(type, replies)):
|
|
803
|
+
clock = self._tryagain_clock()
|
|
774
804
|
for i, v in enumerate(replies):
|
|
775
805
|
if v.__class__ is MovedError:
|
|
776
|
-
replies[i] = self._redirect(v, payload[i], dec)
|
|
806
|
+
replies[i] = self._redirect(v, payload[i], dec, clock)
|
|
777
807
|
return replies
|
|
778
808
|
|
|
779
809
|
def _batch_split(self, payload: List[bytes], dec: bool) -> List[Any]:
|
|
@@ -793,9 +823,10 @@ class ClusterRuvio(Ruvio):
|
|
|
793
823
|
replies[i] = v
|
|
794
824
|
if failure is not None:
|
|
795
825
|
raise failure
|
|
826
|
+
clock = self._tryagain_clock()
|
|
796
827
|
for i, v in enumerate(replies):
|
|
797
828
|
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]
|
|
829
|
+
replies[i] = self._redirect(v, payload[i] if i < n else subs[i - n][4], dec, clock) # type: ignore[index]
|
|
799
830
|
return replies if subs is None else cl.merge_pipeline(replies, n, subs)
|
|
800
831
|
|
|
801
832
|
def _batch_tx(self, payload: List[bytes], dec: bool) -> List[Any]:
|