021-python-clients 0.1.0__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.
@@ -0,0 +1,327 @@
1
+ Metadata-Version: 2.5
2
+ Name: 021-python-clients
3
+ Version: 0.1.0
4
+ Summary: Observed clients for Redis, SQS, QStash, S3, HTTP, email and KMS, built on 021-python-observability
5
+ Project-URL: Repository, https://github.com/from021-io/python-clients
6
+ Project-URL: Changelog, https://github.com/from021-io/python-clients/blob/main/CHANGELOG.md
7
+ Project-URL: Contract, https://github.com/from021-io/python-clients/blob/main/CONTRACT.md
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: email,httpx,kms,observability,opentelemetry,qstash,redis,resend,s3,ses,sqs
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: System :: Monitoring
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: 021-python-observability<0.4,>=0.3
23
+ Requires-Dist: httpx<1,>=0.28
24
+ Requires-Dist: opentelemetry-api<2,>=1.44
25
+ Provides-Extra: aws
26
+ Requires-Dist: boto3<2,>=1.40; extra == 'aws'
27
+ Requires-Dist: cryptography>=44; extra == 'aws'
28
+ Provides-Extra: httpx2
29
+ Requires-Dist: httpx2<3,>=2; extra == 'httpx2'
30
+ Provides-Extra: redis
31
+ Requires-Dist: redis<9,>=6; extra == 'redis'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # 021-python-clients
35
+
36
+ Clients for the external services our Python services call, with the observability of
37
+ [021-python-observability](https://pypi.org/project/021-python-observability/) built in.
38
+ A service uses these instead of calling `redis`, `boto3`, `httpx` or an email SDK directly, so every
39
+ dependency call gets the same span, the same metrics under a stable dependency name, and
40
+ the same failure type.
41
+
42
+ ```bash
43
+ uv add "021-python-clients[redis,aws,httpx2]" # pick the extras you use
44
+ ```
45
+
46
+ | Module | Extra | What it gives |
47
+ | --- | --- | --- |
48
+ | `clients_021.http` | none | `HttpClient`: one httpx client per dependency, timeouts, retries on idempotent methods |
49
+ | `clients_021.httpx2` | `httpx2` | `ObservedTransport` for SDKs built on httpx2 (Anthropic, OpenAI) |
50
+ | `clients_021.redis` | `redis` | `RedisClient`: JSON with TTL, one-time reads, windowed counters, ping |
51
+ | `clients_021.queue.qstash` | none | `QStashClient`: JSON publishing, deduplication, delivery options and forwarded trace context |
52
+ | `clients_021.queue.sqs` | `aws` | `SqsClient`: send, receive, delete, visibility, trace carried in the message |
53
+ | `clients_021.s3` | `aws` | `S3Client`: put, get, head, delete, presigned URLs |
54
+ | `clients_021.email` | none | `EmailMessage`, the `EmailSender` protocol, `ResendSender` (Resend's HTTP API) |
55
+ | `clients_021.email.ses` | `aws` | `SesSender`: the same protocol over Amazon SES v2 |
56
+ | `clients_021.kms` | `aws` | `KmsClient`: encrypt, decrypt and data keys bound to an encryption context; AES-256-GCM envelopes |
57
+
58
+ Every client takes the service's `Observability` (from `setup_observability`) and a
59
+ `dependency` name, which becomes the `dependency` label of its metrics.
60
+
61
+ ## Organization
62
+
63
+ Providers with the same purpose live under one capability package: `email/` contains
64
+ Resend and SES; `queue/` contains SQS and QStash. Import queue clients explicitly:
65
+
66
+ ```python
67
+ from clients_021.queue.sqs import SqsClient
68
+ from clients_021.queue.qstash import QStashClient
69
+ ```
70
+
71
+ SQS supports polling, receipts and visibility changes; QStash delivers to an HTTP endpoint.
72
+ Their provider APIs remain separate inside `queue/`. Email providers share `EmailSender`
73
+ because both implement the same send operation. A shared package does not imply that every
74
+ provider implements an interchangeable consumption protocol. Importing `queue` or QStash
75
+ does not load the optional AWS SDK.
76
+
77
+ ## What every call gets
78
+
79
+ - A CLIENT span named `<dependency> <operation>` (`HTTP <dependency>` for HTTP), with the
80
+ system attribute (`db.system.name=redis`, `messaging.system=aws_sqs|resend|aws_ses`,
81
+ `rpc.service=S3|KMS`).
82
+ - A counter and a duration histogram: `db.client.operation.*` (Redis, shared with SQL),
83
+ `messaging.client.operation.*` (SQS, QStash, email), `storage.client.operation.*` (S3),
84
+ `crypto.client.operation.*` (KMS), `http.client.request.*` (HTTP, and the HTTP request
85
+ under QStash and Resend). Labels are bounded; see [CONTRACT.md](CONTRACT.md).
86
+ - Redis, SQS, QStash, S3, email and KMS emit a `dependency.call_failed` warning on failure,
87
+ with dependency, operation and error type only. HTTP transports emit spans and metrics.
88
+ - `DependencyUnavailable(dependency, operation, reason)` when the service timed out,
89
+ refused the connection, throttled or failed with a 5xx. Map it to a 503. Errors that mean
90
+ the request is wrong (access denied, a missing bucket, a wrong Redis type) keep their
91
+ original type: they are bugs, not outages.
92
+
93
+ Never in this library's spans, metrics or logs: keys, URLs, bodies, message ids or object
94
+ names; email addresses, subjects, bodies or tags; KMS key ids, encryption contexts,
95
+ plaintext, ciphertext or data keys. Use static dependency names such as `identity-provider` or `uploads`; never derive
96
+ them from a tenant, user or request. All clients apply observability's identifier rule
97
+ (1–96 letters, digits, `_`, `.` or `-`, starting with a letter or digit).
98
+
99
+ ## Examples
100
+
101
+ ```python
102
+ from clients_021 import DependencyUnavailable, HttpClient
103
+ from clients_021.redis import RedisClient
104
+ from clients_021.s3 import S3Client
105
+ from clients_021.queue.sqs import SqsClient
106
+
107
+ redis = RedisClient.from_url(obs, settings.redis_url)
108
+ await redis.set_json("session:abc", {"user": "ana"}, ttl_seconds=1800)
109
+ used = await redis.incr_window("ratelimit:ip:1.2.3.4:28735", by=1, ttl_seconds=61)
110
+
111
+ queue = SqsClient.create(obs, settings.queue_url, region="us-east-1")
112
+ await queue.send(body, attributes={"type": "notes.created.v1"})
113
+ for message in await queue.receive(wait_seconds=20):
114
+ with obs.tracer.start_as_current_span("handle", context=message.trace_context()):
115
+ ...
116
+ await queue.delete(message.receipt)
117
+
118
+ files = S3Client.create(obs, "service-uploads", region="us-east-1")
119
+ await files.put("reports/2026-10.pdf", data, content_type="application/pdf")
120
+ url = files.presign_get("reports/2026-10.pdf", expires_seconds=300)
121
+
122
+ http = HttpClient(obs, timeout_seconds=10)
123
+ response = await http.request("GET", jwks_url, dependency="identity-provider")
124
+ ```
125
+
126
+ ### QStash
127
+
128
+ ```python
129
+ from clients_021.queue.qstash import QStashClient
130
+
131
+ qstash = QStashClient(
132
+ obs,
133
+ token=settings.qstash_token,
134
+ base_url=settings.qstash_url, # the API URL for your selected region
135
+ timeout_seconds=10, # this service's publication request
136
+ )
137
+ try:
138
+ published = await qstash.publish_json(
139
+ settings.events_url,
140
+ {"type": "notes.created.v1", "data": {"note_id": note_id}},
141
+ deduplication_id=event_id, # stable across retries of this logical event
142
+ delivery_retries=3,
143
+ delivery_timeout_seconds=60,
144
+ delay_seconds=0,
145
+ label="notes.created.v1",
146
+ forward_headers={"X-Request-ID": request_id},
147
+ )
148
+ # published.message_id and published.deduplicated describe QStash acceptance.
149
+ finally:
150
+ await qstash.aclose()
151
+ ```
152
+
153
+ Create the client once per service lifecycle; the example closes it explicitly for
154
+ completeness. `publish_json` targets one HTTP(S) URL and supports any JSON value, including
155
+ `null`. Acknowledgement means queued, not delivered. Deduplication keys are required and
156
+ preserved verbatim; QStash rejects keys containing `:`, so this client raises `ValueError`
157
+ for those keys before making a request. Use a UUID or a stable hash of a composite business
158
+ key instead of replacing punctuation, which can collapse different keys. Reuse the key after an uncertain publication outcome; scope it to the
159
+ logical event and destination. QStash's deduplication window is finite, so consumers must
160
+ still be idempotent. See [Upstash's deduplication contract](https://upstash.com/docs/qstash/features/deduplication).
161
+
162
+ The publisher forwards the current trace to the destination by default. Use
163
+ `propagate=False` for destinations that should not receive it. Caller-supplied forwarded
164
+ trace headers are replaced or removed together. `forward_headers` uses ordinary header
165
+ names; the client adds the provider prefix. These headers are sent to QStash for delivery,
166
+ so only pass credentials intended for that destination.
167
+
168
+ The first slice covers publishing, not schedules, batches, URL groups or a web framework's
169
+ receiving endpoint. Authenticate incoming deliveries using
170
+ [QStash signature verification](https://upstash.com/docs/qstash/howto/signature).
171
+
172
+ ### Email
173
+
174
+ Behind one protocol, so a service can switch between Resend and SES by configuration:
175
+
176
+ ```python
177
+ from clients_021.email import EmailMessage, EmailRejected, EmailSender, ResendSender
178
+ from clients_021.email.ses import SesSender
179
+
180
+ email: EmailSender = (
181
+ ResendSender(obs, settings.resend_api_key)
182
+ if settings.email_provider == "resend"
183
+ else SesSender.create(obs, region="us-east-1", configuration_set="transactional")
184
+ )
185
+ message = EmailMessage(
186
+ sender="021 <hola@from021.io>",
187
+ to=user.email,
188
+ subject="Your sign-in code",
189
+ text=f"Your code is {code}",
190
+ tags={"category": "sign_in"},
191
+ )
192
+ try:
193
+ await email.send(message, idempotency_key=f"sign-in:{attempt.id}")
194
+ except EmailRejected as rejected: # the address, the domain or the credentials; not an outage
195
+ log.warning("email.rejected", status=rejected.status, code=rejected.code)
196
+ ```
197
+
198
+ `EmailRejected` carries the provider's status and error name (`validation_error`,
199
+ `MessageRejected`, ...), never its message. Resend sends each request once; with an
200
+ `idempotency_key` a retry after `DependencyUnavailable` within 24 hours cannot send twice.
201
+ SES has no idempotency key (the argument is ignored): deduplicate in the caller when a retry
202
+ must not send twice. Tags are for provider analytics; never put personal data in them.
203
+
204
+ ### KMS
205
+
206
+ The encryption context is required on every call, so a ciphertext only decrypts for the
207
+ purpose it was made for:
208
+
209
+ ```python
210
+ from clients_021.kms import KmsClient
211
+
212
+ keys = KmsClient.create(obs, settings.session_key_arn, region="us-east-1")
213
+ context = {"purpose": "refresh-token", "tenant": tenant_id}
214
+ stored = await keys.encrypt(refresh_token, context=context) # up to 4096 bytes
215
+ refresh_token = await keys.decrypt(stored, context=context)
216
+ envelope = await keys.seal(document, context=context) # any size
217
+ document = await keys.unseal(envelope, context=context)
218
+ ```
219
+
220
+ The context is logged by KMS in CloudTrail in plaintext: it names a purpose, never a
221
+ secret. `seal` makes one `GenerateDataKey` call and encrypts locally with AES-256-GCM;
222
+ `unseal` makes one `Decrypt` call. A wrong context, a tampered ciphertext or another key's
223
+ ciphertext keep their botocore type (they are bugs or attacks, not outages); a tampered
224
+ envelope raises `cryptography`'s `InvalidTag`. The envelope layout is in
225
+ [CONTRACT.md](CONTRACT.md).
226
+
227
+ ### SDKs on httpx2
228
+
229
+ For an SDK on httpx2:
230
+
231
+ ```python
232
+ from anthropic import AsyncAnthropic, DefaultAsyncHttpxClient
233
+ from clients_021.httpx2 import ObservedTransport
234
+
235
+ transport = ObservedTransport(obs, dependency="anthropic")
236
+ claude = AsyncAnthropic(http_client=DefaultAsyncHttpxClient(transport=transport))
237
+ ```
238
+
239
+ It does not send `traceparent` to third-party APIs unless `propagate=True`.
240
+ The transport preserves SDK exceptions so the SDK retains control of retries and error
241
+ handling; it does not convert them to `DependencyUnavailable`.
242
+
243
+ ## Service integration
244
+
245
+ Create clients once during service startup and reuse their connection pools. Keep business
246
+ rules in service adapters: queue envelopes, deduplication-key generation, storage integrity and key naming
247
+ do not belong in this library. Inject the configured SDK client into the constructor when
248
+ you need provider-specific options (for example S3 addressing style or credentials).
249
+
250
+ Close clients during shutdown, after stopping consumers and waiting for in-flight calls.
251
+ `aclose()` closes the underlying client, including an injected one; do not share that SDK
252
+ client with another owner. An `AsyncExitStack` makes cleanup explicit:
253
+
254
+ ```python
255
+ from contextlib import AsyncExitStack
256
+
257
+ async with AsyncExitStack() as resources:
258
+ http = HttpClient(obs, timeout_seconds=10)
259
+ resources.push_async_callback(http.aclose)
260
+ redis = RedisClient.from_url(obs, settings.redis_url)
261
+ resources.push_async_callback(redis.aclose)
262
+ files = S3Client.create(obs, "service-uploads", region="us-east-1")
263
+ resources.push_async_callback(files.aclose)
264
+ queue = SqsClient.create(obs, settings.queue_url, region="us-east-1")
265
+ resources.push_async_callback(queue.aclose)
266
+ email = ResendSender(obs, settings.resend_api_key)
267
+ resources.push_async_callback(email.aclose)
268
+ keys = KmsClient.create(obs, settings.session_key_arn, region="us-east-1")
269
+ resources.push_async_callback(keys.aclose)
270
+ # Run the service here. Stop its background workers before leaving this scope.
271
+ ```
272
+
273
+ Retry policies are explicit:
274
+
275
+ - HTTP retries GET, HEAD, OPTIONS, PUT and DELETE on network failures, timeouts,
276
+ remote protocol/proxy connection failures and 502/503/504. `retries=2` means at most
277
+ three attempts.
278
+ POST and PATCH run once. Invalid URLs/protocols and invalid request construction keep
279
+ their original exception. HTTP status responses are returned for the caller to handle.
280
+ - Resend sends each request once (POST); send an `idempotency_key` and retry in the caller.
281
+ - AWS factories (SQS, S3, SES, KMS) use botocore standard retries with at most **three total
282
+ attempts**.
283
+ Injected SDK clients keep their configured policy. SQS consumers must tolerate duplicate
284
+ messages; a timeout does not prove that a send or write was not applied.
285
+ SQS allows ten message attributes including trace context; reserve two for `traceparent`
286
+ and `tracestate`, which belong to the library.
287
+ - Redis keeps the injected SDK's retry policy. For non-idempotent operations such as
288
+ `take_json` and `incr_window`, do not configure automatic replay after an ambiguous
289
+ timeout. Authentication and authorization errors keep their Redis exception type.
290
+ - QStash sends each publication POST once. `delivery_retries` configures subsequent
291
+ delivery by QStash, not retrying this request. HTTP 429 and 5xx become
292
+ `DependencyUnavailable`; other rejected statuses and invalid acknowledgements raise
293
+ `QStashResponseError` with a status code and no provider body. Delivery timeouts and
294
+ delays use integer seconds and remain subject to the provider plan's limits.
295
+ - httpx2 SDKs own their retries; `ObservedTransport` adds no extra retry loop.
296
+
297
+ `DependencyUnavailable` signals a transient dependency failure, **not permission to replay
298
+ any operation**. Map it at the service boundary and apply the operation's idempotency rules.
299
+ Its message and structured fields are safe to log when dependency names are static. Its
300
+ chained SDK exception may contain sensitive provider data; do not log exception chains.
301
+
302
+ S3, SQS, SES and KMS run the synchronous AWS SDK in worker threads. Cancelling the await does not
303
+ stop an SDK request already running in its thread. Timeouts are per SDK/network attempt,
304
+ not an overall deadline. Limit consumer concurrency and let in-flight work finish before
305
+ closing the clients. Redis window counters require Redis server 7 or newer (`EXPIRE NX`).
306
+
307
+ HTTP transport spans end when response headers arrive. Body downloads and SDK streaming
308
+ are outside that span; instrument the enclosing service/SDK operation when you need total
309
+ latency or failures while consuming the body. S3 `get` buffers the entire object in memory;
310
+ use a dedicated streaming adapter for large files.
311
+
312
+ ## Development
313
+
314
+ ```bash
315
+ uv sync --all-extras
316
+ make check # ruff, pyright strict, pytest (Redis at REDIS_URL, default redis://127.0.0.1:63799/15)
317
+ ```
318
+
319
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the module layout and the checklist for adding
320
+ clients. QStash protocol tests need no external service. To exercise actual delivery and
321
+ deduplication, start the [official local server](https://upstash.com/docs/qstash/howto/local-development),
322
+ set its `QSTASH_URL` and `QSTASH_TOKEN`, and run `uv run python tests/qstash_local.py`.
323
+ That smoke test accepts only a loopback QStash server and binds its destination dynamically.
324
+
325
+ SQS, S3, SES and KMS tests run against [moto](https://github.com/getmoto/moto) (plus
326
+ botocore's Stubber where moto ignores a field or differs from AWS); Resend tests use httpx's
327
+ `MockTransport`; Redis tests need a real Redis. Licensed under Apache-2.0.
@@ -0,0 +1,21 @@
1
+ clients_021/__init__.py,sha256=-nha2Z2GGtWvRsjSdMt4SLRCa9gDoA5VRyhfFg3v8AY,730
2
+ clients_021/_aws.py,sha256=sj2kCfod-vz9J93UyeVzNVLGK3M25yipKdW15KyIkw4,1722
3
+ clients_021/_observe.py,sha256=7HbFKH3x6sQonz_lpH7DLFuLBnSLgiSGUtlt4lN17NU,3779
4
+ clients_021/errors.py,sha256=GS_fN8mjr7MCOkhqPhH6LweIvQ20Vd29U-aZY8zBeJQ,972
5
+ clients_021/http.py,sha256=-AsGLfngd-eEJnTuZEPdVBI9myYiuggmnrvjQjaMpT8,5045
6
+ clients_021/httpx2.py,sha256=w248IcEtDZtsEDkkvj4Bpfl7MU7IJ08EHqHWhryC_3k,3880
7
+ clients_021/kms.py,sha256=iEzIqzizOhs387VF_w5pV5cRTUCx7uepvYCxFl5gWK8,7254
8
+ clients_021/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ clients_021/redis.py,sha256=sOPUMXE7z7X639T3SLPDWRAQSFysp2bj1kCWzdtXiEM,4926
10
+ clients_021/s3.py,sha256=2iK6N_UVVjZRIFfe24p3PWtRFHqCDsZvjcs5GIzhZSY,5938
11
+ clients_021/email/__init__.py,sha256=ivmdu9hhNDwPqBn3G7uNG0Zpc3DEMnlnWBVVoVQ-fQA,790
12
+ clients_021/email/_message.py,sha256=ulTX2cXPxSVaq_5FVF0e6glePVJ7wiO5P3M4WUWN3N0,3258
13
+ clients_021/email/resend.py,sha256=ugENkEzw9eUlYih3BZcCVQswTF1MDikPgZyuqdapCjc,5347
14
+ clients_021/email/ses.py,sha256=0ukHvuVE0nTU5mYWRy2EaHY5v9dUwi4GSKES93pjqBg,4668
15
+ clients_021/queue/__init__.py,sha256=CesweOrXmX5cyU-mRvqu-4wLkNJI15zi_Lows6SPupY,338
16
+ clients_021/queue/qstash.py,sha256=j3vz_S9-ed0YQZCaWwQg5wPwf8Bv5P1voNsx8WD8Zhc,8315
17
+ clients_021/queue/sqs.py,sha256=jnccgbxyglzs2mR_DsH04IisEwygDlw6s3RxR0UtMTc,6693
18
+ 021_python_clients-0.1.0.dist-info/METADATA,sha256=lqElbrid3Ug6ZM5Mg0jUNhjKpiNPnvormJf32oXNn84,16655
19
+ 021_python_clients-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
20
+ 021_python_clients-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
21
+ 021_python_clients-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,22 @@
1
+ """Observed clients for the external services Python services call.
2
+
3
+ `clients_021.http`, `clients_021.queue.qstash` and `clients_021.email` (Resend) need no extras;
4
+ `clients_021.redis` needs the `redis` extra; `clients_021.queue.sqs`, `clients_021.s3`,
5
+ `clients_021.email.ses` and `clients_021.kms` the `aws` extra; `clients_021.httpx2` the
6
+ `httpx2` extra.
7
+ """
8
+
9
+ from importlib.metadata import version
10
+
11
+ from clients_021.errors import DependencyUnavailable
12
+ from clients_021.http import IDEMPOTENT_METHODS, HttpClient, HttpMethod, HttpResponse
13
+
14
+ __version__ = version("021-python-clients")
15
+ __all__ = [
16
+ "IDEMPOTENT_METHODS",
17
+ "DependencyUnavailable",
18
+ "HttpClient",
19
+ "HttpMethod",
20
+ "HttpResponse",
21
+ "__version__",
22
+ ]
clients_021/_aws.py ADDED
@@ -0,0 +1,55 @@
1
+ """What the AWS clients share: botocore configuration and the error classification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from botocore.config import Config
6
+ from botocore.exceptions import (
7
+ ClientError,
8
+ ConnectionClosedError,
9
+ ConnectTimeoutError,
10
+ EndpointConnectionError,
11
+ ReadTimeoutError,
12
+ )
13
+
14
+ # Codes AWS uses for "slow down" across services.
15
+ _THROTTLED = frozenset(
16
+ {
17
+ "Throttling",
18
+ "ThrottlingException",
19
+ "ThrottledException",
20
+ "RequestThrottled",
21
+ "RequestThrottledException",
22
+ "TooManyRequestsException",
23
+ "SlowDown",
24
+ "RequestLimitExceeded",
25
+ "ProvisionedThroughputExceededException",
26
+ }
27
+ )
28
+
29
+
30
+ def config(*, connect_seconds: float, read_seconds: float) -> Config:
31
+ """Bounded timeouts and the SDK's standard retry mode (backoff with jitter, 3 attempts)."""
32
+ return Config(
33
+ connect_timeout=connect_seconds,
34
+ read_timeout=read_seconds,
35
+ retries={"mode": "standard", "total_max_attempts": 3},
36
+ )
37
+
38
+
39
+ def classify(error: BaseException) -> str | None:
40
+ if isinstance(error, ConnectTimeoutError | ReadTimeoutError):
41
+ return "timeout"
42
+ if isinstance(error, EndpointConnectionError | ConnectionClosedError):
43
+ return "connection_error"
44
+ if isinstance(error, ClientError):
45
+ code = str(error.response.get("Error", {}).get("Code", ""))
46
+ status = int(error.response.get("ResponseMetadata", {}).get("HTTPStatusCode", 0))
47
+ if code in _THROTTLED:
48
+ return "throttled"
49
+ if status >= 500:
50
+ return f"status_{status}"
51
+ return None
52
+
53
+
54
+ def error_code(error: ClientError) -> str:
55
+ return str(error.response.get("Error", {}).get("Code", ""))