cogno-sync 0.1.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.
@@ -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,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
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
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,152 @@
1
+ # cogno-sync
2
+
3
+ **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.
4
+
5
+ > Status: **alpha** — extracted from a production host, with its suite.
6
+
7
+ ## The problem this is for
8
+
9
+ Everything here exists because **one process is not the deployment**. The in-process versions of
10
+ these four things are five lines each and they are all correct — until a second worker starts.
11
+ Then the lock guards nothing, the limiter hands out N× the budget, the same delivery is handled
12
+ twice, and each worker gives every caller its own daily allowance.
13
+
14
+ | Port | In-process default | Redis adapter | What the adapter buys |
15
+ | --- | --- | --- | --- |
16
+ | `LockProvider` | `InProcessLockProvider` | `RedisLockProvider` | mutual exclusion **across** processes (`SET NX EX` + owner-only Lua release) |
17
+ | `RateLimiter` | `InMemoryTokenBucketLimiter` | `RedisTokenBucketLimiter` | one shared bucket, refilled atomically under the **server's** clock |
18
+ | `IdempotencyStore` | `InMemoryIdempotencyStore` | `RedisIdempotencyStore` | a claim two workers cannot both win (`SET NX`) |
19
+ | `DailyCap` | `InMemoryDailyCap` | `RedisDailyCap` | one allowance per caller, not one per worker |
20
+
21
+ ## Everything fails OPEN
22
+
23
+ A Redis outage, a lock that cannot be acquired within `max_wait`, a counter that will not
24
+ answer: the work runs anyway, with a `WARNING`. These are guards against a rare double-run and
25
+ against cost — never correctness barriers. Refusing to serve a legitimate caller because a cache
26
+ blipped is the worse failure, and it is the one that takes the product down with the cache.
27
+
28
+ If you need the opposite (a strict guard that must refuse when it cannot verify), do not
29
+ configure your way there — wrap the port and decide it in your own code, where the trade-off is
30
+ visible.
31
+
32
+ ## One client, one pool
33
+
34
+ Every `Redis*` adapter here takes the **same** constructor:
35
+
36
+ ```python
37
+ Adapter(client=None, *, url="", key_prefix="cogno:…:")
38
+ ```
39
+
40
+ Build one client in your process and inject it everywhere:
41
+
42
+ ```python
43
+ from cogno_sync import (client_from_url, RedisLockProvider, RedisTokenBucketLimiter,
44
+ RedisIdempotencyStore, RedisDailyCap)
45
+
46
+ redis = client_from_url(os.environ["REDIS_URL"], decode_responses=True)
47
+
48
+ locks = RedisLockProvider(redis)
49
+ limiter = RedisTokenBucketLimiter(redis, rate_per_sec=10, burst=20)
50
+ claims = RedisIdempotencyStore(redis)
51
+ cap = RedisDailyCap(redis)
52
+ ```
53
+
54
+ That uniformity is the feature. The code this was extracted from had **three** constructor
55
+ conventions across five adapters and a copy of `Redis.from_url` in each one, so a worker held
56
+ one connection pool per adapter — and a URL passed in the client slot failed on the first
57
+ command, where fail-open swallowed it and the coordination was silently off for months.
58
+
59
+ Passing `url=` instead builds the client lazily, on first use: handy for a one-adapter script,
60
+ and it keeps start-up independent of whether the server is up yet.
61
+
62
+ ## Using them
63
+
64
+ ```python
65
+ # serialize a critical section by key (across workers)
66
+ async with locks.lock(f"session:{session_id}"):
67
+ ...
68
+
69
+ # spend one unit of budget
70
+ decision = await limiter.check(client_ip)
71
+ if not decision.allowed:
72
+ return too_many_requests(retry_after=decision.retry_after)
73
+
74
+ # handle a delivery once (claim BEFORE the work, release if nothing happened)
75
+ if await claims.seen_before(key):
76
+ return
77
+ try:
78
+ ...
79
+ except NothingHappenedYet:
80
+ await claims.forget(key)
81
+
82
+ # a rolling daily ceiling (the caller owns the key, including the day stamp)
83
+ from cogno_sync import utc_day
84
+ used = await cap.hit(f"demo:{utc_day()}:{client_ip}")
85
+ if used > DAILY_LIMIT:
86
+ return politely_closed()
87
+ ```
88
+
89
+ The **key is always yours to compose**. This library never invents one: what makes two deliveries
90
+ distinct, or two callers separate, is a property of your system — and getting it wrong is
91
+ silent (one caller's budget spent by another, one message dropped as a duplicate of a different
92
+ one).
93
+
94
+ ## ASGI extra
95
+
96
+ ```bash
97
+ pip install "cogno-sync[asgi]"
98
+ ```
99
+
100
+ ```python
101
+ from cogno_sync.asgi import RateLimitMiddleware, read_capped_body, BodyTooLarge
102
+
103
+ app.add_middleware(RateLimitMiddleware, limiter=limiter,
104
+ prefixes=("/api", "/chat"), # default: every path
105
+ trusted_proxy_hops=1) # how many proxies you trust in front
106
+ ```
107
+
108
+ `trusted_proxy_hops` decides which `X-Forwarded-For` entry is the real caller — the N-th from
109
+ the **right**, because each proxy appends the address it saw. Reading the leftmost hop is
110
+ spoofable: a caller sets the header and gets a fresh budget on every request. It is a
111
+ constructor argument, never an environment read at import time, so a test can set it and two
112
+ apps in one runtime can differ.
113
+
114
+ `read_capped_body` reads a request body incrementally and raises `BodyTooLarge` past the limit —
115
+ for the unauthenticated routes where the signature can only be verified *after* the payload is
116
+ read, and where `await request.body()` would buffer an unbounded stream into the worker's heap.
117
+
118
+ ## Install
119
+
120
+ ```bash
121
+ pip install cogno-sync # zero hard dependencies
122
+ pip install "cogno-sync[redis]" # the cross-worker adapters
123
+ pip install "cogno-sync[asgi]" # the middleware + body cap
124
+ pip install -e ".[dev]" # tests + lint + type-check
125
+ ```
126
+
127
+ ## The Cogno ecosystem
128
+
129
+ `cogno-sync` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
130
+ small, composable, Apache-2.0 libraries that together form a complete
131
+ conversational-agent platform. Each library owns a single concern and stays
132
+ infra-agnostic; a **host** assembles them into a running agent:
133
+
134
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
135
+
136
+ The open-source libraries are the organs; the **host is the body** that joins
137
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
138
+ private product layer, but it holds no special powers: everything it does rides
139
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
140
+ you can assemble a body of your own.
141
+
142
+ ## Test
143
+
144
+ ```bash
145
+ pytest tests/unit -q # no server needed
146
+ COGNO_TEST_REDIS_URL=redis://127.0.0.1:6379/0 pytest tests/integration -q
147
+ ```
148
+
149
+ The unit suite drives the Redis adapters against fakes; the integration suite proves the parts
150
+ only a server can show — two clients sharing one bucket, a claim that survives across
151
+ connections, the TTL Redis itself holds, and the release script comparing the owner token
152
+ inside Redis.
@@ -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
+ ]
@@ -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"]