cogno-sync 0.1.1__py3-none-any.whl
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.
- cogno_sync/__init__.py +62 -0
- cogno_sync/_redis.py +66 -0
- cogno_sync/asgi.py +118 -0
- cogno_sync/daily_cap.py +81 -0
- cogno_sync/idempotency.py +113 -0
- cogno_sync/locks.py +176 -0
- cogno_sync/py.typed +0 -0
- cogno_sync/ratelimit.py +145 -0
- cogno_sync-0.1.1.dist-info/METADATA +191 -0
- cogno_sync-0.1.1.dist-info/RECORD +13 -0
- cogno_sync-0.1.1.dist-info/WHEEL +5 -0
- cogno_sync-0.1.1.dist-info/licenses/LICENSE +201 -0
- cogno_sync-0.1.1.dist-info/top_level.txt +1 -0
cogno_sync/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cogno-sync — distributed coordination primitives for the Cogno stack.
|
|
3
|
+
|
|
4
|
+
Four small ports, each with a zero-infra in-process default and a Redis adapter that shares the
|
|
5
|
+
state across workers: a lock, a token-bucket rate limiter, a claim-once idempotency store, and a
|
|
6
|
+
rolling daily counter. Every adapter is async, every one **fails open**, and every one takes the
|
|
7
|
+
same constructor — a ready client, or a URL to build one from.
|
|
8
|
+
|
|
9
|
+
Redis is an optional extra (``cogno-sync[redis]``), imported only when a client is built; the
|
|
10
|
+
ASGI middleware lives in :mod:`cogno_sync.asgi` behind ``cogno-sync[asgi]``. Importing this
|
|
11
|
+
package pulls in neither.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from importlib.metadata import PackageNotFoundError
|
|
15
|
+
from importlib.metadata import version as _dist_version
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
__version__ = _dist_version("cogno-sync")
|
|
19
|
+
except PackageNotFoundError: # source tree without an installed dist (e.g. vendored checkout)
|
|
20
|
+
__version__ = "0.0.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
from cogno_sync._redis import client_from_url
|
|
24
|
+
from cogno_sync.daily_cap import DailyCap, InMemoryDailyCap, RedisDailyCap, utc_day
|
|
25
|
+
from cogno_sync.idempotency import (
|
|
26
|
+
DEFAULT_CLAIM_TTL,
|
|
27
|
+
IdempotencyStore,
|
|
28
|
+
InMemoryIdempotencyStore,
|
|
29
|
+
RedisIdempotencyStore,
|
|
30
|
+
)
|
|
31
|
+
from cogno_sync.locks import (
|
|
32
|
+
DEFAULT_LOCK_TTL,
|
|
33
|
+
InProcessLockProvider,
|
|
34
|
+
LockProvider,
|
|
35
|
+
RedisLockProvider,
|
|
36
|
+
)
|
|
37
|
+
from cogno_sync.ratelimit import (
|
|
38
|
+
InMemoryTokenBucketLimiter,
|
|
39
|
+
RateLimitDecision,
|
|
40
|
+
RateLimiter,
|
|
41
|
+
RedisTokenBucketLimiter,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"client_from_url",
|
|
46
|
+
"LockProvider",
|
|
47
|
+
"InProcessLockProvider",
|
|
48
|
+
"RedisLockProvider",
|
|
49
|
+
"DEFAULT_LOCK_TTL",
|
|
50
|
+
"RateLimiter",
|
|
51
|
+
"RateLimitDecision",
|
|
52
|
+
"InMemoryTokenBucketLimiter",
|
|
53
|
+
"RedisTokenBucketLimiter",
|
|
54
|
+
"IdempotencyStore",
|
|
55
|
+
"InMemoryIdempotencyStore",
|
|
56
|
+
"RedisIdempotencyStore",
|
|
57
|
+
"DEFAULT_CLAIM_TTL",
|
|
58
|
+
"DailyCap",
|
|
59
|
+
"InMemoryDailyCap",
|
|
60
|
+
"RedisDailyCap",
|
|
61
|
+
"utc_day",
|
|
62
|
+
]
|
cogno_sync/_redis.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""One lazy Redis client factory, and the shared shape every ``Redis*`` adapter here follows.
|
|
2
|
+
|
|
3
|
+
``redis`` is an **optional extra** (``cogno-sync[redis]``): it is imported the first time a
|
|
4
|
+
client is actually built, so ``import cogno_sync`` never needs it.
|
|
5
|
+
|
|
6
|
+
Every adapter in this package takes the same two arguments — a ready client, or a URL to build
|
|
7
|
+
one from — and holds the same three fields. That uniformity is the point: the library this code
|
|
8
|
+
came from had three different constructor conventions across five adapters, and each one grew
|
|
9
|
+
its own copy of ``Redis.from_url``, so a process ended up holding one connection pool per
|
|
10
|
+
adapter. **Build one client and inject it everywhere**; the URL form stays for a one-adapter
|
|
11
|
+
script and for tests.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def client_from_url(url: str, *, decode_responses: bool = False) -> Any:
|
|
20
|
+
"""Build a ``redis.asyncio.Redis`` from ``url``.
|
|
21
|
+
|
|
22
|
+
Nothing connects here — the client opens its pool on the first command — so this is safe
|
|
23
|
+
to call at start-up, before the server is up.
|
|
24
|
+
|
|
25
|
+
``decode_responses=True`` makes the client return ``str`` instead of ``bytes``. Every
|
|
26
|
+
adapter in this package works either way: none of them compares a returned value against a
|
|
27
|
+
literal (the lock's owner check runs inside Redis, the limiter reads integers), so a caller
|
|
28
|
+
that shares one client with its own code is free to pick whichever that code needs.
|
|
29
|
+
"""
|
|
30
|
+
if not url:
|
|
31
|
+
raise ValueError("client_from_url needs a non-empty redis url")
|
|
32
|
+
from redis.asyncio import Redis # lazy: the [redis] extra
|
|
33
|
+
return Redis.from_url(url, decode_responses=decode_responses)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _RedisAdapter:
|
|
37
|
+
"""Constructor + lazy-client behaviour shared by the ``Redis*`` adapters.
|
|
38
|
+
|
|
39
|
+
Subclasses declare the full public signature themselves — ``(client=None, *, url="",
|
|
40
|
+
key_prefix="cogno:…:")`` — so the default keyspace is readable at the class that owns it.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, client: Any = None, *, url: str = "", key_prefix: str = "",
|
|
44
|
+
decode_responses: bool = False) -> None:
|
|
45
|
+
if isinstance(client, str):
|
|
46
|
+
# A URL handed in the positional (the CLIENT slot) would only surface on the first
|
|
47
|
+
# command — and every adapter here fails open, so it would be swallowed forever and
|
|
48
|
+
# the coordination would be silently off. Accept it as the url instead.
|
|
49
|
+
client, url = None, client
|
|
50
|
+
if client is None and not url:
|
|
51
|
+
raise ValueError(f"{type(self).__name__} needs a redis client or a url")
|
|
52
|
+
self._client: Any = client
|
|
53
|
+
self._url: str = url
|
|
54
|
+
self._decode = decode_responses
|
|
55
|
+
self._prefix = key_prefix
|
|
56
|
+
|
|
57
|
+
def _conn(self) -> Any:
|
|
58
|
+
if self._client is None:
|
|
59
|
+
self._client = client_from_url(self._url, decode_responses=self._decode)
|
|
60
|
+
return self._client
|
|
61
|
+
|
|
62
|
+
def _key(self, key: str) -> str:
|
|
63
|
+
return f"{self._prefix}{key}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
__all__ = ["client_from_url"]
|
cogno_sync/asgi.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""ASGI edge helpers — the rate-limit middleware and a bounded body read.
|
|
2
|
+
|
|
3
|
+
This is the only module here that needs a web framework, so it lives apart and behind the
|
|
4
|
+
``[asgi]`` extra (Starlette): importing :mod:`cogno_sync` itself never pulls one in.
|
|
5
|
+
|
|
6
|
+
* :class:`RateLimitMiddleware` applies a :class:`~cogno_sync.ratelimit.RateLimiter` to the
|
|
7
|
+
guarded path prefixes and answers ``429`` with a ``Retry-After`` header.
|
|
8
|
+
* :func:`read_capped_body` reads a request body incrementally and gives up past a limit,
|
|
9
|
+
instead of buffering an unbounded stream into the worker's heap.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from typing import Any, Callable, Optional, Sequence
|
|
16
|
+
|
|
17
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
18
|
+
from starlette.requests import Request
|
|
19
|
+
from starlette.responses import JSONResponse
|
|
20
|
+
|
|
21
|
+
from cogno_sync.ratelimit import RateLimiter
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
# Every path. Narrow it per deployment: which routes are worth guarding is a property of the
|
|
26
|
+
# application, never of this library.
|
|
27
|
+
ALL_PATHS: tuple[str, ...] = ("/",)
|
|
28
|
+
|
|
29
|
+
# A generous ceiling for a machine-to-machine POST (batched webhook events and the like).
|
|
30
|
+
DEFAULT_MAX_BODY_BYTES = 2 * 1024 * 1024
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def client_ip_key(request: Request, *, trusted_proxy_hops: int = 1) -> str:
|
|
34
|
+
"""The caller's IP, resolved against the number of TRUSTED reverse proxies in front.
|
|
35
|
+
|
|
36
|
+
The real client is the entry the OUTERMOST trusted proxy recorded — the N-th from the RIGHT
|
|
37
|
+
of ``X-Forwarded-For``, since each proxy appends the address it received the connection
|
|
38
|
+
from. Taking the leftmost hop is spoofable: a caller sets ``X-Forwarded-For: <anything>``
|
|
39
|
+
and lands at position 0 with a fresh budget on every request.
|
|
40
|
+
|
|
41
|
+
``trusted_proxy_hops=0`` ignores the header entirely (the app is directly exposed). A chain
|
|
42
|
+
shorter than the hop count — a direct hit, or a misconfigured deployment — falls back to the
|
|
43
|
+
peer address, never to a client-controlled value. ``anon`` when there is no peer either: a
|
|
44
|
+
limiter must not crash on a missing client.
|
|
45
|
+
"""
|
|
46
|
+
peer = request.client.host if request.client else "anon"
|
|
47
|
+
if trusted_proxy_hops <= 0:
|
|
48
|
+
return peer
|
|
49
|
+
xff = request.headers.get("x-forwarded-for", "")
|
|
50
|
+
hops = [h.strip() for h in xff.split(",") if h.strip()] if xff else []
|
|
51
|
+
if len(hops) >= trusted_proxy_hops:
|
|
52
|
+
return hops[-trusted_proxy_hops]
|
|
53
|
+
return peer
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RateLimitMiddleware(BaseHTTPMiddleware):
|
|
57
|
+
"""429s a request whose key is over budget — but only on the guarded ``prefixes``;
|
|
58
|
+
everything else (a health probe, static assets) passes straight through.
|
|
59
|
+
|
|
60
|
+
``key_fn`` decides what is being limited; the default is the caller's IP resolved with
|
|
61
|
+
``trusted_proxy_hops``. That number is a **constructor argument on purpose**: read from the
|
|
62
|
+
environment at import time it would be fixed for the whole process, invisible to a test, and
|
|
63
|
+
impossible to differ between two apps in one runtime.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, app: Any, *, limiter: RateLimiter,
|
|
67
|
+
prefixes: Sequence[str] = ALL_PATHS,
|
|
68
|
+
key_fn: Optional[Callable[[Request], str]] = None,
|
|
69
|
+
trusted_proxy_hops: int = 1) -> None:
|
|
70
|
+
super().__init__(app)
|
|
71
|
+
self._limiter = limiter
|
|
72
|
+
self._prefixes = tuple(prefixes)
|
|
73
|
+
self._hops = trusted_proxy_hops
|
|
74
|
+
self._key_fn = key_fn or (lambda r: client_ip_key(r, trusted_proxy_hops=self._hops))
|
|
75
|
+
|
|
76
|
+
async def dispatch(self, request: Request, call_next): # noqa: ANN001,ANN201 — Starlette shape
|
|
77
|
+
if request.url.path.startswith(self._prefixes):
|
|
78
|
+
key = self._key_fn(request)
|
|
79
|
+
decision = await self._limiter.check(key)
|
|
80
|
+
if not decision.allowed:
|
|
81
|
+
log.warning("event=rate_limited key=%s path=%s", key, request.url.path)
|
|
82
|
+
return JSONResponse(
|
|
83
|
+
{"detail": "rate limit exceeded"}, status_code=429,
|
|
84
|
+
headers={"Retry-After": str(max(1, int(decision.retry_after) + 1))})
|
|
85
|
+
return await call_next(request)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class BodyTooLarge(Exception):
|
|
89
|
+
"""Raised when the request body exceeds the cap. Callers answer ``413``."""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def read_capped_body(request: Request, limit: int = DEFAULT_MAX_BODY_BYTES) -> bytes:
|
|
93
|
+
"""Return the body, or raise :class:`BodyTooLarge` without ever buffering past ``limit``.
|
|
94
|
+
|
|
95
|
+
Unauthenticated routes are the reason this exists: a signature can only be verified AFTER
|
|
96
|
+
the payload is read, and such routes are usually exempt from an IP limiter too (a provider's
|
|
97
|
+
shared egress addresses would collapse onto one key). ``await request.body()`` buffers the
|
|
98
|
+
whole stream into the worker's heap, so a handful of concurrent multi-GB POSTs is enough to
|
|
99
|
+
OOM-kill the process and take every caller down with it.
|
|
100
|
+
|
|
101
|
+
``Content-Length`` is advisory — simply absent on a ``Transfer-Encoding: chunked`` request —
|
|
102
|
+
so it is a fast pre-check here, never the guard: the running total is.
|
|
103
|
+
"""
|
|
104
|
+
declared: Optional[str] = request.headers.get("content-length")
|
|
105
|
+
if declared and declared.isdigit() and int(declared) > limit:
|
|
106
|
+
raise BodyTooLarge()
|
|
107
|
+
parts: list[bytes] = []
|
|
108
|
+
total = 0
|
|
109
|
+
async for chunk in request.stream():
|
|
110
|
+
total += len(chunk)
|
|
111
|
+
if total > limit:
|
|
112
|
+
raise BodyTooLarge()
|
|
113
|
+
parts.append(chunk)
|
|
114
|
+
return b"".join(parts)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
__all__ = ["RateLimitMiddleware", "client_ip_key", "read_capped_body", "BodyTooLarge",
|
|
118
|
+
"DEFAULT_MAX_BODY_BYTES", "ALL_PATHS"]
|
cogno_sync/daily_cap.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Per-key DAILY counters — a rolling cost ceiling for anonymous surfaces.
|
|
2
|
+
|
|
3
|
+
A per-second limiter bounds REQUESTS PER SECOND, not spend: at 10 rps one caller can still
|
|
4
|
+
drive an unbounded amount of expensive work over a day. A per-session counter does not close it
|
|
5
|
+
either whenever the session id comes from the client — omitting it starts a fresh session on
|
|
6
|
+
every request. A rolling daily count per caller is the missing ceiling: cheap, anonymous-
|
|
7
|
+
friendly (a real user never reaches it) and checkable BEFORE any money is spent.
|
|
8
|
+
|
|
9
|
+
Both implementations **fail open** — a counter outage returns ``0``, which every caller must
|
|
10
|
+
read as "unknown, let it through". A quota exists to bound cost, not to be a correctness
|
|
11
|
+
barrier.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from typing import Any, Protocol, runtime_checkable
|
|
19
|
+
|
|
20
|
+
from cogno_sync._redis import _RedisAdapter
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def utc_day() -> str:
|
|
26
|
+
"""The current UTC day stamp — the natural reset boundary for a rolling daily quota."""
|
|
27
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@runtime_checkable
|
|
31
|
+
class DailyCap(Protocol):
|
|
32
|
+
"""Count one hit for ``key`` today; returns the count INCLUDING this hit (0 = unknown)."""
|
|
33
|
+
|
|
34
|
+
async def hit(self, key: str) -> int: ...
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InMemoryDailyCap:
|
|
38
|
+
"""Process-local counter — dev / single worker. A multi-worker deployment injects the Redis
|
|
39
|
+
one, or each worker hands out its own full allowance."""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self._day = utc_day()
|
|
43
|
+
self._counts: dict[str, int] = {}
|
|
44
|
+
|
|
45
|
+
async def hit(self, key: str) -> int:
|
|
46
|
+
today = utc_day()
|
|
47
|
+
if today != self._day: # cheap rollover: drop yesterday wholesale
|
|
48
|
+
self._day, self._counts = today, {}
|
|
49
|
+
self._counts[key] = self._counts.get(key, 0) + 1
|
|
50
|
+
return self._counts[key]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RedisDailyCap(_RedisAdapter):
|
|
54
|
+
"""Shared counter across workers and restarts: ``INCR`` + a TTL that expires the key itself.
|
|
55
|
+
|
|
56
|
+
The **caller** puts the day in the key (see :func:`utc_day`) — the window then rolls over on
|
|
57
|
+
its own and yesterday's keys expire, so nothing has to be swept. Only the first hit of a
|
|
58
|
+
window sets the expiry: re-setting it on every hit would let a caller who keeps hitting the
|
|
59
|
+
key hold it alive forever, and the count would never reset.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, client: Any = None, *, url: str = "", key_prefix: str = "cogno:cap:",
|
|
63
|
+
ttl_seconds: int = 26 * 3600) -> None:
|
|
64
|
+
super().__init__(client, url=url, key_prefix=key_prefix)
|
|
65
|
+
self._ttl = ttl_seconds # > 24h so a day boundary never truncates a window
|
|
66
|
+
|
|
67
|
+
async def hit(self, key: str) -> int:
|
|
68
|
+
try:
|
|
69
|
+
conn = self._conn()
|
|
70
|
+
full = self._key(key)
|
|
71
|
+
count = int(await conn.incr(full))
|
|
72
|
+
if count == 1: # first hit of the window owns the expiry
|
|
73
|
+
await conn.expire(full, self._ttl)
|
|
74
|
+
return count
|
|
75
|
+
except Exception as exc: # noqa: BLE001 — a cache blip must not wall a legitimate user
|
|
76
|
+
log.warning("event=daily_cap_error key=%s error=%s proceeding_fail_open",
|
|
77
|
+
key, type(exc).__name__)
|
|
78
|
+
return 0
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
__all__ = ["DailyCap", "InMemoryDailyCap", "RedisDailyCap", "utc_day"]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Claim-once idempotency — handle a delivery ONCE, however many times it arrives.
|
|
2
|
+
|
|
3
|
+
A lock (:mod:`cogno_sync.locks`) **serializes** work; it does not **deduplicate** it. Once the
|
|
4
|
+
first run finishes and releases, a re-delivery takes the lock and does the whole thing again.
|
|
5
|
+
At-least-once transports (webhooks, queues, mobile clients on a flaky link) re-deliver by
|
|
6
|
+
design, so the receiver is the only place that can make the effect once.
|
|
7
|
+
|
|
8
|
+
Two decisions shape this port, and both are worth stating because the opposite choice looks
|
|
9
|
+
equally reasonable until it ships:
|
|
10
|
+
|
|
11
|
+
* **Claim BEFORE the work, release on failure.** Claiming afterwards leaves the concurrent
|
|
12
|
+
window open; claiming before with no way to release turns one transient crash into a message
|
|
13
|
+
lost forever. As written: a concurrent re-delivery is refused, a re-delivery after success is
|
|
14
|
+
refused, and a re-delivery after a crash — before anything committed — is let through, because
|
|
15
|
+
the caller called :meth:`forget`.
|
|
16
|
+
* **Fail-OPEN.** A store error lets the delivery through with a warning, the same direction
|
|
17
|
+
:class:`~cogno_sync.locks.RedisLockProvider` takes. A store that goes down must not take the
|
|
18
|
+
service with it.
|
|
19
|
+
|
|
20
|
+
The KEY is the caller's business: it must carry whatever makes one delivery distinct in that
|
|
21
|
+
system (the sender, the source, the provider's own id), because a provider's ids are unique per
|
|
22
|
+
provider, not globally. This package never composes it.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import logging
|
|
28
|
+
import time
|
|
29
|
+
from typing import Any, Callable, Protocol, runtime_checkable
|
|
30
|
+
|
|
31
|
+
from cogno_sync._redis import _RedisAdapter
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
# Senders retry within minutes; a day is generous and costs nothing (Redis expires it).
|
|
36
|
+
DEFAULT_CLAIM_TTL = 24 * 60 * 60
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@runtime_checkable
|
|
40
|
+
class IdempotencyStore(Protocol):
|
|
41
|
+
"""Port: has this delivery been claimed, and claim it if not — in ONE atomic step."""
|
|
42
|
+
|
|
43
|
+
async def seen_before(self, key: str, *, ttl: int = DEFAULT_CLAIM_TTL) -> bool:
|
|
44
|
+
"""True when ``key`` was already claimed. False claims it for this caller.
|
|
45
|
+
|
|
46
|
+
Must be atomic (test-and-set). A ``get`` followed by a ``set`` would let two concurrent
|
|
47
|
+
re-deliveries both read "unseen" and both proceed — which is the exact race this
|
|
48
|
+
exists to close.
|
|
49
|
+
"""
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
async def forget(self, key: str) -> None:
|
|
53
|
+
"""Release a claim, so a re-delivery may retry work that never happened."""
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class InMemoryIdempotencyStore:
|
|
58
|
+
"""Process-local claims — the zero-infra default. Correct for ONE process; swap for
|
|
59
|
+
:class:`RedisIdempotencyStore` when more than one of them receives the same stream."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, *, now: Callable[[], float] = time.monotonic) -> None:
|
|
62
|
+
self._seen: dict[str, float] = {} # key → expiry (monotonic seconds)
|
|
63
|
+
self._now = now
|
|
64
|
+
|
|
65
|
+
def _sweep(self) -> None:
|
|
66
|
+
cutoff = self._now()
|
|
67
|
+
for key in [k for k, exp in self._seen.items() if exp <= cutoff]:
|
|
68
|
+
self._seen.pop(key, None)
|
|
69
|
+
|
|
70
|
+
async def seen_before(self, key: str, *, ttl: int = DEFAULT_CLAIM_TTL) -> bool:
|
|
71
|
+
self._sweep()
|
|
72
|
+
# Single-threaded asyncio: no await between the read and the write, so this IS atomic
|
|
73
|
+
# with respect to other tasks. Adding an await here would reopen the race.
|
|
74
|
+
if key in self._seen:
|
|
75
|
+
return True
|
|
76
|
+
self._seen[key] = self._now() + ttl
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
async def forget(self, key: str) -> None:
|
|
80
|
+
self._seen.pop(key, None)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class RedisIdempotencyStore(_RedisAdapter):
|
|
84
|
+
"""Cross-process claims over Redis (``SET NX EX`` — atomic by construction).
|
|
85
|
+
|
|
86
|
+
Pass a ready ``redis.asyncio.Redis`` client, or a URL to build one lazily. Fail-open: any
|
|
87
|
+
Redis error logs a WARNING and reports "not seen", so the delivery is handled rather than
|
|
88
|
+
dropped.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(self, client: Any = None, *, url: str = "",
|
|
92
|
+
key_prefix: str = "cogno:claim:") -> None:
|
|
93
|
+
super().__init__(client, url=url, key_prefix=key_prefix)
|
|
94
|
+
|
|
95
|
+
async def seen_before(self, key: str, *, ttl: int = DEFAULT_CLAIM_TTL) -> bool:
|
|
96
|
+
try:
|
|
97
|
+
# NX returns None when the key already exists → already claimed by someone.
|
|
98
|
+
claimed = await self._conn().set(self._key(key), "1", nx=True, ex=ttl)
|
|
99
|
+
return not claimed
|
|
100
|
+
except Exception as exc: # noqa: BLE001 — fail-open, see the module doc
|
|
101
|
+
log.warning("event=claim_store_unavailable key=%s error=%s — proceeding anyway",
|
|
102
|
+
key, type(exc).__name__)
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
async def forget(self, key: str) -> None:
|
|
106
|
+
try:
|
|
107
|
+
await self._conn().delete(self._key(key))
|
|
108
|
+
except Exception as exc: # noqa: BLE001 — best-effort release
|
|
109
|
+
log.warning("event=claim_release_failed key=%s error=%s", key, type(exc).__name__)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
__all__ = ["IdempotencyStore", "InMemoryIdempotencyStore", "RedisIdempotencyStore",
|
|
113
|
+
"DEFAULT_CLAIM_TTL"]
|
cogno_sync/locks.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Mutual exclusion on a key — serialize concurrent work across workers.
|
|
2
|
+
|
|
3
|
+
A unit of work that reads some state, changes it and writes it back races with itself whenever
|
|
4
|
+
two copies run at once: a client retrying, a user acting twice in a second, two HTTP requests
|
|
5
|
+
arriving at different processes. One process is covered by an :class:`asyncio.Lock`; **several
|
|
6
|
+
processes are not** — they share no memory.
|
|
7
|
+
|
|
8
|
+
* :class:`LockProvider` — the port: ``lock(key)`` → an async context manager that holds the
|
|
9
|
+
lock for the duration of the body.
|
|
10
|
+
* :class:`InProcessLockProvider` — the zero-infra default: a per-key ``asyncio.Lock``. Correct
|
|
11
|
+
inside ONE process, and only there.
|
|
12
|
+
* :class:`RedisLockProvider` — the cross-process adapter: ``SET NX EX`` with a per-acquisition
|
|
13
|
+
token plus an owner-only Lua compare-and-delete on release, so a worker can never delete a
|
|
14
|
+
lock someone else took after its own TTL expired.
|
|
15
|
+
|
|
16
|
+
**The TTL is RENEWED while the body runs** (0.1.1). A heartbeat, every ``ttl / 3``, extends the
|
|
17
|
+
key's TTL with an owner-only Lua compare-and-expire — so a body slower than the TTL keeps its lock
|
|
18
|
+
and the next acquirer WAITS, instead of taking an expired key and running beside it (measured on
|
|
19
|
+
the reference host: a turn's p99 of 126 s against the 120 s default). The heartbeat stops when the
|
|
20
|
+
body ends or is cancelled, stops for good the moment the key holds someone else's token (it never
|
|
21
|
+
renews a lock that is not its own), and treats a Redis error as one missed beat: it logs and tries
|
|
22
|
+
again on the next one, and the body never waits on it.
|
|
23
|
+
|
|
24
|
+
**Fail-open.** If Redis is unreachable, or the lock cannot be taken within ``max_wait``, the
|
|
25
|
+
body runs anyway with a WARNING. These primitives guard against a rare double-run; refusing to
|
|
26
|
+
do the work at all is the worse failure.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import asyncio
|
|
32
|
+
import contextlib
|
|
33
|
+
import logging
|
|
34
|
+
import uuid
|
|
35
|
+
from typing import (Any, AsyncIterator, Awaitable, Callable, Optional, Protocol,
|
|
36
|
+
runtime_checkable)
|
|
37
|
+
|
|
38
|
+
from cogno_sync._redis import _RedisAdapter
|
|
39
|
+
|
|
40
|
+
log = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
DEFAULT_LOCK_TTL = 120 # seconds — must exceed the slowest critical section
|
|
43
|
+
_RETRY_INTERVAL = 0.5 # seconds between acquisition attempts
|
|
44
|
+
_MAX_WAIT = 60.0 # seconds — then fail-open (proceed without the lock)
|
|
45
|
+
_RENEW_FRACTION = 3 # renew every ttl / 3: two beats can be missed before it expires
|
|
46
|
+
_MIN_RENEW_INTERVAL = 0.05 # seconds — a floor, for a tiny ttl
|
|
47
|
+
_HEARTBEAT_STOP_WAIT = 1.0 # seconds — how long the exit waits for the cancelled heartbeat
|
|
48
|
+
|
|
49
|
+
# Owner-only release: delete the key only if it still holds OUR token (never delete a lock a
|
|
50
|
+
# later acquirer took after our TTL expired).
|
|
51
|
+
_LUA_RELEASE = """
|
|
52
|
+
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
|
53
|
+
return redis.call("DEL", KEYS[1])
|
|
54
|
+
else
|
|
55
|
+
return 0
|
|
56
|
+
end
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
# Owner-only renewal: extend the TTL only if the key still holds OUR token — never a lock a later
|
|
60
|
+
# acquirer took after ours expired.
|
|
61
|
+
_LUA_RENEW = """
|
|
62
|
+
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
|
63
|
+
return redis.call("EXPIRE", KEYS[1], ARGV[2])
|
|
64
|
+
else
|
|
65
|
+
return 0
|
|
66
|
+
end
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@runtime_checkable
|
|
71
|
+
class LockProvider(Protocol):
|
|
72
|
+
"""Yields an async context manager that holds the lock for ``key`` while the body runs."""
|
|
73
|
+
|
|
74
|
+
def lock(self, key: str, *,
|
|
75
|
+
ttl: int = DEFAULT_LOCK_TTL) -> "contextlib.AbstractAsyncContextManager[None]": ...
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class InProcessLockProvider:
|
|
79
|
+
"""A per-key ``asyncio.Lock`` — the zero-infra default. Serializes within ONE process only;
|
|
80
|
+
swap for :class:`RedisLockProvider` to serialize across processes."""
|
|
81
|
+
|
|
82
|
+
def __init__(self) -> None:
|
|
83
|
+
self._locks: dict[str, asyncio.Lock] = {}
|
|
84
|
+
|
|
85
|
+
@contextlib.asynccontextmanager
|
|
86
|
+
async def lock(self, key: str, *, ttl: int = DEFAULT_LOCK_TTL) -> AsyncIterator[None]:
|
|
87
|
+
existing = self._locks.get(key)
|
|
88
|
+
if existing is None:
|
|
89
|
+
existing = self._locks[key] = asyncio.Lock()
|
|
90
|
+
async with existing:
|
|
91
|
+
yield
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class RedisLockProvider(_RedisAdapter):
|
|
95
|
+
"""Distributed lock over Redis (``SET NX EX`` + owner-only Lua release + an owner-only
|
|
96
|
+
renewal of the TTL while the body runs).
|
|
97
|
+
|
|
98
|
+
Pass a ready ``redis.asyncio.Redis`` client, or a URL to build one lazily. Fail-open by
|
|
99
|
+
design: any Redis error or an acquisition timeout logs a WARNING and runs the body.
|
|
100
|
+
|
|
101
|
+
``renew=False`` turns the heartbeat off (the 0.1.0 behaviour). ``sleep`` is the clock the
|
|
102
|
+
acquisition retries and the heartbeat wait on — injectable so a test drives a fake one. When
|
|
103
|
+
it is not given, ``asyncio.sleep`` is looked up at CALL time, as 0.1.0 did, so a caller that
|
|
104
|
+
patches this module's ``asyncio`` keeps driving the waits.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(self, client: Any = None, *, url: str = "",
|
|
108
|
+
key_prefix: str = "cogno:lock:", retry_interval: float = _RETRY_INTERVAL,
|
|
109
|
+
max_wait: float = _MAX_WAIT, renew: bool = True,
|
|
110
|
+
sleep: "Optional[Callable[[float], Awaitable[Any]]]" = None) -> None:
|
|
111
|
+
super().__init__(client, url=url, key_prefix=key_prefix)
|
|
112
|
+
self._retry = retry_interval
|
|
113
|
+
self._max_wait = max_wait
|
|
114
|
+
self._renew = renew
|
|
115
|
+
self._sleep = sleep
|
|
116
|
+
self._owner = uuid.uuid4().hex # stable per process
|
|
117
|
+
|
|
118
|
+
@contextlib.asynccontextmanager
|
|
119
|
+
async def lock(self, key: str, *, ttl: int = DEFAULT_LOCK_TTL) -> AsyncIterator[None]:
|
|
120
|
+
lock_key = self._key(key)
|
|
121
|
+
token = f"{self._owner}:{uuid.uuid4().hex}"
|
|
122
|
+
acquired = False
|
|
123
|
+
try:
|
|
124
|
+
r = self._conn()
|
|
125
|
+
elapsed = 0.0
|
|
126
|
+
while elapsed < self._max_wait:
|
|
127
|
+
if await r.set(lock_key, token, nx=True, ex=ttl):
|
|
128
|
+
acquired = True
|
|
129
|
+
break
|
|
130
|
+
await self._wait(self._retry)
|
|
131
|
+
elapsed += self._retry
|
|
132
|
+
if not acquired:
|
|
133
|
+
log.warning("event=lock_timeout key=%s waited=%.1fs proceeding_fail_open",
|
|
134
|
+
key, elapsed)
|
|
135
|
+
except Exception as exc: # noqa: BLE001 — fail-open: never drop work on a lock error
|
|
136
|
+
log.warning("event=lock_error key=%s error=%s proceeding_fail_open", key, exc)
|
|
137
|
+
yield
|
|
138
|
+
return
|
|
139
|
+
beat = (asyncio.ensure_future(self._heartbeat(r, lock_key, token, ttl, key))
|
|
140
|
+
if acquired and self._renew else None)
|
|
141
|
+
try:
|
|
142
|
+
yield
|
|
143
|
+
finally:
|
|
144
|
+
if beat is not None:
|
|
145
|
+
# Stopped BEFORE the release, so no beat can renew a key we are about to free.
|
|
146
|
+
# `asyncio.wait`, never `wait_for`: on 3.10 `wait_for` hangs on a task that
|
|
147
|
+
# swallows its cancel; this returns after the bound whatever the task does.
|
|
148
|
+
beat.cancel()
|
|
149
|
+
await asyncio.wait({beat}, timeout=_HEARTBEAT_STOP_WAIT)
|
|
150
|
+
if acquired:
|
|
151
|
+
try:
|
|
152
|
+
await r.eval(_LUA_RELEASE, 1, lock_key, token)
|
|
153
|
+
except Exception as exc: # noqa: BLE001
|
|
154
|
+
log.warning("event=lock_release_failed key=%s error=%s", key, exc)
|
|
155
|
+
|
|
156
|
+
async def _wait(self, seconds: float) -> None:
|
|
157
|
+
await (self._sleep or asyncio.sleep)(seconds)
|
|
158
|
+
|
|
159
|
+
async def _heartbeat(self, r: Any, lock_key: str, token: str, ttl: int, key: str) -> None:
|
|
160
|
+
"""Renew ``lock_key``'s TTL every ``ttl / 3`` while it holds ``token``. Ends when the key
|
|
161
|
+
holds another token (``event=lock_lost``) or when cancelled; a Redis error is one missed
|
|
162
|
+
beat (``event=lock_renew_failed``), never an exception the body sees."""
|
|
163
|
+
interval = max(float(ttl) / _RENEW_FRACTION, _MIN_RENEW_INTERVAL)
|
|
164
|
+
while True:
|
|
165
|
+
await self._wait(interval)
|
|
166
|
+
try:
|
|
167
|
+
kept = await r.eval(_LUA_RENEW, 1, lock_key, token, int(ttl))
|
|
168
|
+
except Exception as exc: # noqa: BLE001 — a missed beat, never the body's problem
|
|
169
|
+
log.warning("event=lock_renew_failed key=%s error=%s", key, type(exc).__name__)
|
|
170
|
+
continue
|
|
171
|
+
if not kept:
|
|
172
|
+
log.warning("event=lock_lost key=%s", key)
|
|
173
|
+
return
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
__all__ = ["LockProvider", "InProcessLockProvider", "RedisLockProvider", "DEFAULT_LOCK_TTL"]
|
cogno_sync/py.typed
ADDED
|
File without changes
|
cogno_sync/ratelimit.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Rate limiting — a token-bucket port with an in-process default and a Redis adapter.
|
|
2
|
+
|
|
3
|
+
A service that is reachable without an infrastructure edge in front of it carries its own
|
|
4
|
+
limit. This module is the **pure** limiter (no web framework, so importing it never needs the
|
|
5
|
+
``[asgi]`` extra); the ASGI middleware that applies it lives in :mod:`cogno_sync.asgi`.
|
|
6
|
+
|
|
7
|
+
:class:`RateLimiter` is the port, :class:`InMemoryTokenBucketLimiter` the zero-infra default —
|
|
8
|
+
**per process**, so N workers behind a balancer let one caller burst ~N× the configured rate —
|
|
9
|
+
and :class:`RedisTokenBucketLimiter` the multi-worker adapter with shared counters.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import logging
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any, Callable, Protocol, runtime_checkable
|
|
19
|
+
|
|
20
|
+
from cogno_sync._redis import _RedisAdapter
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class RateLimitDecision:
|
|
27
|
+
"""The outcome of a limiter check. ``retry_after`` (seconds) is meaningful only when denied."""
|
|
28
|
+
|
|
29
|
+
allowed: bool
|
|
30
|
+
retry_after: float = 0.0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@runtime_checkable
|
|
34
|
+
class RateLimiter(Protocol):
|
|
35
|
+
"""Decides whether a request keyed by ``key`` may proceed. Async — a real adapter does I/O.
|
|
36
|
+
One ``check`` consumes one unit of budget."""
|
|
37
|
+
|
|
38
|
+
async def check(self, key: str) -> RateLimitDecision: ...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class _Bucket:
|
|
43
|
+
tokens: float
|
|
44
|
+
updated: float
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class InMemoryTokenBucketLimiter:
|
|
48
|
+
"""Per-process token bucket: each ``key`` refills at ``rate_per_sec`` up to ``burst`` tokens;
|
|
49
|
+
a ``check`` spends one. ``burst`` is the max instantaneous spike; ``rate_per_sec`` the steady
|
|
50
|
+
state. Async-locked so concurrent requests for the same key don't race the refill."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, *, rate_per_sec: float, burst: int,
|
|
53
|
+
clock: Callable[[], float] = time.monotonic) -> None:
|
|
54
|
+
if rate_per_sec <= 0 or burst <= 0:
|
|
55
|
+
raise ValueError("rate_per_sec and burst must be positive")
|
|
56
|
+
self._rate = float(rate_per_sec)
|
|
57
|
+
self._burst = float(burst)
|
|
58
|
+
self._clock = clock
|
|
59
|
+
self._buckets: dict[str, _Bucket] = {}
|
|
60
|
+
self._lock = asyncio.Lock()
|
|
61
|
+
|
|
62
|
+
async def check(self, key: str) -> RateLimitDecision:
|
|
63
|
+
async with self._lock:
|
|
64
|
+
now = self._clock()
|
|
65
|
+
b = self._buckets.get(key)
|
|
66
|
+
if b is None:
|
|
67
|
+
b = _Bucket(tokens=self._burst, updated=now)
|
|
68
|
+
self._buckets[key] = b
|
|
69
|
+
else: # refill for elapsed time, capped at burst
|
|
70
|
+
b.tokens = min(self._burst, b.tokens + (now - b.updated) * self._rate)
|
|
71
|
+
b.updated = now
|
|
72
|
+
if b.tokens >= 1.0:
|
|
73
|
+
b.tokens -= 1.0
|
|
74
|
+
return RateLimitDecision(True)
|
|
75
|
+
return RateLimitDecision(False, retry_after=(1.0 - b.tokens) / self._rate)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# Atomic token bucket in one round-trip. Uses the Redis server clock (``TIME``) so every worker
|
|
79
|
+
# shares one clock, works in integer milliseconds (Lua floats are lossy over the wire), and expires
|
|
80
|
+
# idle buckets so the keyspace stays bounded. Returns ``{allowed(0|1), retry_after_ms}``.
|
|
81
|
+
_LUA_TOKEN_BUCKET = """
|
|
82
|
+
local key = KEYS[1]
|
|
83
|
+
local rate = tonumber(ARGV[1]) -- tokens per second (steady state)
|
|
84
|
+
local burst = tonumber(ARGV[2]) -- bucket capacity (max spike)
|
|
85
|
+
local t = redis.call('TIME')
|
|
86
|
+
local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
|
|
87
|
+
local data = redis.call('HMGET', key, 'tokens', 'ts')
|
|
88
|
+
local tokens = tonumber(data[1])
|
|
89
|
+
local ts = tonumber(data[2])
|
|
90
|
+
if tokens == nil then
|
|
91
|
+
tokens = burst
|
|
92
|
+
ts = now_ms
|
|
93
|
+
end
|
|
94
|
+
local elapsed = now_ms - ts
|
|
95
|
+
if elapsed < 0 then elapsed = 0 end
|
|
96
|
+
tokens = math.min(burst, tokens + elapsed * rate / 1000.0)
|
|
97
|
+
local allowed = 0
|
|
98
|
+
local retry_ms = 0
|
|
99
|
+
if tokens >= 1.0 then
|
|
100
|
+
tokens = tokens - 1.0
|
|
101
|
+
allowed = 1
|
|
102
|
+
else
|
|
103
|
+
retry_ms = math.ceil((1.0 - tokens) / rate * 1000.0)
|
|
104
|
+
end
|
|
105
|
+
redis.call('HSET', key, 'tokens', tokens, 'ts', now_ms)
|
|
106
|
+
redis.call('EXPIRE', key, math.ceil(burst / rate) + 1)
|
|
107
|
+
return {allowed, retry_ms}
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class RedisTokenBucketLimiter(_RedisAdapter):
|
|
112
|
+
"""Token bucket over Redis — the **multi-worker** limiter (shared counters across processes).
|
|
113
|
+
|
|
114
|
+
The in-memory bucket is per-process, so N workers behind a balancer let a client burst ~N×
|
|
115
|
+
the configured rate; this adapter keeps one bucket per key in Redis (refilled atomically in a
|
|
116
|
+
Lua script under the Redis server clock), so the limit holds regardless of worker count. Same
|
|
117
|
+
:class:`RateLimiter` port as the in-memory default.
|
|
118
|
+
|
|
119
|
+
**Fail-open** (like the distributed lock): a Redis error → the request is *allowed* and a
|
|
120
|
+
warning is logged. A limiter is a cost/abuse guard, not an authentication check — refusing
|
|
121
|
+
every legitimate caller during a cache blip is worse than briefly not limiting.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, client: Any = None, *, url: str = "", key_prefix: str = "cogno:rl:",
|
|
125
|
+
rate_per_sec: float, burst: int) -> None:
|
|
126
|
+
if rate_per_sec <= 0 or burst <= 0:
|
|
127
|
+
raise ValueError("rate_per_sec and burst must be positive")
|
|
128
|
+
super().__init__(client, url=url, key_prefix=key_prefix)
|
|
129
|
+
self._rate = float(rate_per_sec)
|
|
130
|
+
self._burst = int(burst)
|
|
131
|
+
|
|
132
|
+
async def check(self, key: str) -> RateLimitDecision:
|
|
133
|
+
try:
|
|
134
|
+
allowed, retry_ms = await self._conn().eval(
|
|
135
|
+
_LUA_TOKEN_BUCKET, 1, self._key(key), self._rate, self._burst)
|
|
136
|
+
if int(allowed) == 1:
|
|
137
|
+
return RateLimitDecision(True)
|
|
138
|
+
return RateLimitDecision(False, retry_after=float(retry_ms) / 1000.0)
|
|
139
|
+
except Exception as exc: # noqa: BLE001 — fail-open: a Redis error never blocks a caller
|
|
140
|
+
log.warning("event=ratelimit_error key=%s error=%s proceeding_fail_open", key, exc)
|
|
141
|
+
return RateLimitDecision(True)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
__all__ = ["RateLimiter", "RateLimitDecision", "InMemoryTokenBucketLimiter",
|
|
145
|
+
"RedisTokenBucketLimiter"]
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cogno-sync
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Distributed coordination primitives for the Cogno stack — async lock, token-bucket rate limiter, claim-once idempotency store and rolling daily cap, each with an in-process default and a Redis adapter
|
|
5
|
+
Author: Vinicius Vale
|
|
6
|
+
Maintainer: Sudoers AI
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/sudoers-ai/cogno-sync
|
|
9
|
+
Project-URL: Repository, https://github.com/sudoers-ai/cogno-sync
|
|
10
|
+
Project-URL: Issues, https://github.com/sudoers-ai/cogno-sync/issues
|
|
11
|
+
Keywords: redis,distributed-lock,rate-limiting,token-bucket,idempotency,quota,asgi,agents
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Provides-Extra: redis
|
|
26
|
+
Requires-Dist: redis>=5.0; extra == "redis"
|
|
27
|
+
Provides-Extra: asgi
|
|
28
|
+
Requires-Dist: starlette>=0.36; extra == "asgi"
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
33
|
+
Requires-Dist: redis>=5.0; extra == "dev"
|
|
34
|
+
Requires-Dist: starlette>=0.36; extra == "dev"
|
|
35
|
+
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
36
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
37
|
+
Requires-Dist: mypy>=1.8; extra == "dev"
|
|
38
|
+
Dynamic: license-file
|
|
39
|
+
|
|
40
|
+
# cogno-sync
|
|
41
|
+
|
|
42
|
+
**Distributed coordination primitives for the [Cogno](https://github.com/sudoers-ai/cogno-anima) stack** — an async lock, a token-bucket rate limiter, a claim-once idempotency store and a rolling daily cap. Each is a `Protocol` port with a zero-infra in-process default and a Redis adapter that shares the state across workers.
|
|
43
|
+
|
|
44
|
+
> Status: **alpha** — extracted from a production host, with its suite.
|
|
45
|
+
|
|
46
|
+
## The problem this is for
|
|
47
|
+
|
|
48
|
+
Everything here exists because **one process is not the deployment**. The in-process versions of
|
|
49
|
+
these four things are five lines each and they are all correct — until a second worker starts.
|
|
50
|
+
Then the lock guards nothing, the limiter hands out N× the budget, the same delivery is handled
|
|
51
|
+
twice, and each worker gives every caller its own daily allowance.
|
|
52
|
+
|
|
53
|
+
| Port | In-process default | Redis adapter | What the adapter buys |
|
|
54
|
+
| --- | --- | --- | --- |
|
|
55
|
+
| `LockProvider` | `InProcessLockProvider` | `RedisLockProvider` | mutual exclusion **across** processes (`SET NX EX` + owner-only Lua release) |
|
|
56
|
+
| `RateLimiter` | `InMemoryTokenBucketLimiter` | `RedisTokenBucketLimiter` | one shared bucket, refilled atomically under the **server's** clock |
|
|
57
|
+
| `IdempotencyStore` | `InMemoryIdempotencyStore` | `RedisIdempotencyStore` | a claim two workers cannot both win (`SET NX`) |
|
|
58
|
+
| `DailyCap` | `InMemoryDailyCap` | `RedisDailyCap` | one allowance per caller, not one per worker |
|
|
59
|
+
|
|
60
|
+
## Everything fails OPEN
|
|
61
|
+
|
|
62
|
+
A Redis outage, a lock that cannot be acquired within `max_wait`, a counter that will not
|
|
63
|
+
answer: the work runs anyway, with a `WARNING`. These are guards against a rare double-run and
|
|
64
|
+
against cost — never correctness barriers. Refusing to serve a legitimate caller because a cache
|
|
65
|
+
blipped is the worse failure, and it is the one that takes the product down with the cache.
|
|
66
|
+
|
|
67
|
+
If you need the opposite (a strict guard that must refuse when it cannot verify), do not
|
|
68
|
+
configure your way there — wrap the port and decide it in your own code, where the trade-off is
|
|
69
|
+
visible.
|
|
70
|
+
|
|
71
|
+
## One client, one pool
|
|
72
|
+
|
|
73
|
+
Every `Redis*` adapter here takes the **same** constructor:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
Adapter(client=None, *, url="", key_prefix="cogno:…:")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Build one client in your process and inject it everywhere:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from cogno_sync import (client_from_url, RedisLockProvider, RedisTokenBucketLimiter,
|
|
83
|
+
RedisIdempotencyStore, RedisDailyCap)
|
|
84
|
+
|
|
85
|
+
redis = client_from_url(os.environ["REDIS_URL"], decode_responses=True)
|
|
86
|
+
|
|
87
|
+
locks = RedisLockProvider(redis)
|
|
88
|
+
limiter = RedisTokenBucketLimiter(redis, rate_per_sec=10, burst=20)
|
|
89
|
+
claims = RedisIdempotencyStore(redis)
|
|
90
|
+
cap = RedisDailyCap(redis)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
That uniformity is the feature. The code this was extracted from had **three** constructor
|
|
94
|
+
conventions across five adapters and a copy of `Redis.from_url` in each one, so a worker held
|
|
95
|
+
one connection pool per adapter — and a URL passed in the client slot failed on the first
|
|
96
|
+
command, where fail-open swallowed it and the coordination was silently off for months.
|
|
97
|
+
|
|
98
|
+
Passing `url=` instead builds the client lazily, on first use: handy for a one-adapter script,
|
|
99
|
+
and it keeps start-up independent of whether the server is up yet.
|
|
100
|
+
|
|
101
|
+
## Using them
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
# serialize a critical section by key (across workers)
|
|
105
|
+
async with locks.lock(f"session:{session_id}"):
|
|
106
|
+
...
|
|
107
|
+
|
|
108
|
+
# spend one unit of budget
|
|
109
|
+
decision = await limiter.check(client_ip)
|
|
110
|
+
if not decision.allowed:
|
|
111
|
+
return too_many_requests(retry_after=decision.retry_after)
|
|
112
|
+
|
|
113
|
+
# handle a delivery once (claim BEFORE the work, release if nothing happened)
|
|
114
|
+
if await claims.seen_before(key):
|
|
115
|
+
return
|
|
116
|
+
try:
|
|
117
|
+
...
|
|
118
|
+
except NothingHappenedYet:
|
|
119
|
+
await claims.forget(key)
|
|
120
|
+
|
|
121
|
+
# a rolling daily ceiling (the caller owns the key, including the day stamp)
|
|
122
|
+
from cogno_sync import utc_day
|
|
123
|
+
used = await cap.hit(f"demo:{utc_day()}:{client_ip}")
|
|
124
|
+
if used > DAILY_LIMIT:
|
|
125
|
+
return politely_closed()
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The **key is always yours to compose**. This library never invents one: what makes two deliveries
|
|
129
|
+
distinct, or two callers separate, is a property of your system — and getting it wrong is
|
|
130
|
+
silent (one caller's budget spent by another, one message dropped as a duplicate of a different
|
|
131
|
+
one).
|
|
132
|
+
|
|
133
|
+
## ASGI extra
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
pip install "cogno-sync[asgi]"
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from cogno_sync.asgi import RateLimitMiddleware, read_capped_body, BodyTooLarge
|
|
141
|
+
|
|
142
|
+
app.add_middleware(RateLimitMiddleware, limiter=limiter,
|
|
143
|
+
prefixes=("/api", "/chat"), # default: every path
|
|
144
|
+
trusted_proxy_hops=1) # how many proxies you trust in front
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`trusted_proxy_hops` decides which `X-Forwarded-For` entry is the real caller — the N-th from
|
|
148
|
+
the **right**, because each proxy appends the address it saw. Reading the leftmost hop is
|
|
149
|
+
spoofable: a caller sets the header and gets a fresh budget on every request. It is a
|
|
150
|
+
constructor argument, never an environment read at import time, so a test can set it and two
|
|
151
|
+
apps in one runtime can differ.
|
|
152
|
+
|
|
153
|
+
`read_capped_body` reads a request body incrementally and raises `BodyTooLarge` past the limit —
|
|
154
|
+
for the unauthenticated routes where the signature can only be verified *after* the payload is
|
|
155
|
+
read, and where `await request.body()` would buffer an unbounded stream into the worker's heap.
|
|
156
|
+
|
|
157
|
+
## Install
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
pip install cogno-sync # zero hard dependencies
|
|
161
|
+
pip install "cogno-sync[redis]" # the cross-worker adapters
|
|
162
|
+
pip install "cogno-sync[asgi]" # the middleware + body cap
|
|
163
|
+
pip install -e ".[dev]" # tests + lint + type-check
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## The Cogno ecosystem
|
|
167
|
+
|
|
168
|
+
`cogno-sync` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
|
|
169
|
+
small, composable, Apache-2.0 libraries that together form a complete
|
|
170
|
+
conversational-agent platform. Each library owns a single concern and stays
|
|
171
|
+
infra-agnostic; a **host** assembles them into a running agent:
|
|
172
|
+
|
|
173
|
+

|
|
174
|
+
|
|
175
|
+
The open-source libraries are the organs; the **host is the body** that joins
|
|
176
|
+
them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
|
|
177
|
+
private product layer, but it holds no special powers: everything it does rides
|
|
178
|
+
on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
|
|
179
|
+
you can assemble a body of your own.
|
|
180
|
+
|
|
181
|
+
## Test
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
pytest tests/unit -q # no server needed
|
|
185
|
+
COGNO_TEST_REDIS_URL=redis://127.0.0.1:6379/0 pytest tests/integration -q
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The unit suite drives the Redis adapters against fakes; the integration suite proves the parts
|
|
189
|
+
only a server can show — two clients sharing one bucket, a claim that survives across
|
|
190
|
+
connections, the TTL Redis itself holds, and the release script comparing the owner token
|
|
191
|
+
inside Redis.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
cogno_sync/__init__.py,sha256=MBlNR5wt5lmACgK9pPMqaiHyaIDEoDd-WizzJDXO4a0,1896
|
|
2
|
+
cogno_sync/_redis.py,sha256=f9VIqH3IdPgXiREaxoIZFBQ1B5Tgm5Yzw-5QTH_86Ak,3031
|
|
3
|
+
cogno_sync/asgi.py,sha256=BQitlm_ZLaASV_wSnHcMKgtFJEJgWW9xMuH2cx1pl9Y,5524
|
|
4
|
+
cogno_sync/daily_cap.py,sha256=CNUliqw6QL9PZ4jyK6dU7M3ZhT6IcSDt1uU1eVSxuzo,3361
|
|
5
|
+
cogno_sync/idempotency.py,sha256=mniLF5Q6rmqBTtPgWgpP7JeA3IaxmhywL0TnQ_2az7k,5037
|
|
6
|
+
cogno_sync/locks.py,sha256=i461BtPwbMoHFqSMZq9mHHFhPQTXEhyObesdbHAdrSc,8238
|
|
7
|
+
cogno_sync/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
cogno_sync/ratelimit.py,sha256=wmyc8QzTZu7N_M8fmDpHjTlHJIjBXPN0hqi0iI_Am1o,5970
|
|
9
|
+
cogno_sync-0.1.1.dist-info/licenses/LICENSE,sha256=4cK96oGhr1hZsZT3Bo5cnKQ3mx6DJ0u8XuTtJ-TNuso,11340
|
|
10
|
+
cogno_sync-0.1.1.dist-info/METADATA,sha256=oVMF9Cc4KJPJlR2dtobSTULpHgPG_1aMl_jj40WGxm4,8449
|
|
11
|
+
cogno_sync-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
cogno_sync-0.1.1.dist-info/top_level.txt,sha256=OQxpIzp-QL2YqCL0EyzdaEm9CurWrBv7LcTGKMobZbc,11
|
|
13
|
+
cogno_sync-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Sudoers AI
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cogno_sync
|