ample-receipts-client 0.2.0rc3__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.
Files changed (50) hide show
  1. ample_receipts_client/__init__.py +521 -0
  2. ample_receipts_client/__main__.py +6 -0
  3. ample_receipts_client/_cli_parser.py +28 -0
  4. ample_receipts_client/_httplib.py +131 -0
  5. ample_receipts_client/_vendored_ed25519.py +256 -0
  6. ample_receipts_client/_vendored_jcs.py +109 -0
  7. ample_receipts_client/_vendored_merkle.py +130 -0
  8. ample_receipts_client/_version.py +3 -0
  9. ample_receipts_client/ack.py +452 -0
  10. ample_receipts_client/app.py +641 -0
  11. ample_receipts_client/builder.py +513 -0
  12. ample_receipts_client/capture.py +234 -0
  13. ample_receipts_client/cli.py +410 -0
  14. ample_receipts_client/commit.py +260 -0
  15. ample_receipts_client/config.py +165 -0
  16. ample_receipts_client/connect.py +116 -0
  17. ample_receipts_client/decode.py +203 -0
  18. ample_receipts_client/demo/__init__.py +40 -0
  19. ample_receipts_client/demo/__main__.py +6 -0
  20. ample_receipts_client/demo/cli.py +335 -0
  21. ample_receipts_client/demo/files.py +187 -0
  22. ample_receipts_client/demo/run.py +349 -0
  23. ample_receipts_client/demo/upstream.py +133 -0
  24. ample_receipts_client/f1.py +189 -0
  25. ample_receipts_client/folder.py +537 -0
  26. ample_receipts_client/handover.py +171 -0
  27. ample_receipts_client/held_acks.py +140 -0
  28. ample_receipts_client/hold.py +301 -0
  29. ample_receipts_client/notices.py +209 -0
  30. ample_receipts_client/parse.py +537 -0
  31. ample_receipts_client/py.typed +0 -0
  32. ample_receipts_client/record.py +814 -0
  33. ample_receipts_client/redact.py +129 -0
  34. ample_receipts_client/reveal.py +744 -0
  35. ample_receipts_client/salts.py +218 -0
  36. ample_receipts_client/service.py +60 -0
  37. ample_receipts_client/sign.py +320 -0
  38. ample_receipts_client/spool.py +1320 -0
  39. ample_receipts_client/statement.py +343 -0
  40. ample_receipts_client/submit.py +566 -0
  41. ample_receipts_client/submitter.py +2089 -0
  42. ample_receipts_client/tee.py +931 -0
  43. ample_receipts_client/tee_httpx2.py +184 -0
  44. ample_receipts_client/vault.py +1719 -0
  45. ample_receipts_client/wire.py +235 -0
  46. ample_receipts_client-0.2.0rc3.dist-info/METADATA +357 -0
  47. ample_receipts_client-0.2.0rc3.dist-info/RECORD +50 -0
  48. ample_receipts_client-0.2.0rc3.dist-info/WHEEL +4 -0
  49. ample_receipts_client-0.2.0rc3.dist-info/entry_points.txt +2 -0
  50. ample_receipts_client-0.2.0rc3.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,521 @@
1
+ """Ample receipts: the client library (working name ``ample-receipts-client``).
2
+
3
+ This release holds the transport tee (unit R05): an httpx transport that
4
+ records each HTTP attempt of an httpx-based provider client and changes
5
+ nothing about the call, conforming to the call-receipt spec
6
+ (``docs/receipts-call/spec.md``) wherever a capture touches it; and the spool
7
+ (unit R11, ``ample_receipts_client.spool``): the local SQLite store that
8
+ numbers and chains each instance's statements, holds the G3 hook and declares
9
+ detected losses; and the vault (unit R09, ``ample_receipts_client.vault``):
10
+ the opt-in local store of encrypted parts in the customer's custody
11
+ (``docs/receipts-call/vault.md``). The library core (unit R12):
12
+ commitments, salts, the parsed parts, statements, client signatures,
13
+ client-key requests and the ack check, with the statement builder the spool
14
+ takes (``CoreStatementBuilder``); and the submitter (unit R11b,
15
+ ``ample_receipts_client.submitter``): background batches to the ledger, the
16
+ in-flight journal, and the ack check and keep. The reveal (unit R17,
17
+ ``ample_receipts_client.reveal``, run as ``python -m
18
+ ample_receipts_client.reveal``): one part's salt derived again from the salt
19
+ key, its bytes read from the vault or the app's copy, checked against the call
20
+ receipt, and written as the inputs of the auditor's ``reveal-call``.
21
+
22
+ The library imports nothing from ``ample`` or ``ample_replay``. Its
23
+ dependencies are httpx (the tee) and cryptography (the vault's encryption
24
+ and the statement signing).
25
+
26
+ The spool's, the vault's and the core's names are imported on first use
27
+ (``__getattr__`` below), so importing the package alone loads neither
28
+ sqlite3 nor cryptography.
29
+
30
+ The httpx2 tee (unit R05b, ``ample_receipts_client.tee_httpx2``):
31
+ :class:`Httpx2TeeTransport` and :class:`AsyncHttpx2TeeTransport`, R05's tee for
32
+ ``httpx2`` clients (the current openai and anthropic SDKs). httpx2 is the
33
+ optional ``httpx2`` extra; its names are imported on first use too, so
34
+ importing the package never loads httpx2.
35
+
36
+ The quick setup (``ample_receipts_client.app``, run from the console as
37
+ ``ample-receipts``): :func:`setup` starts the receipts from the folder
38
+ ``ample-receipts init`` made, and its :class:`Receipts` makes ready httpx and
39
+ httpx2 clients whose every call is recorded; at a normal exit the library
40
+ sends what waits and writes the held acks. ``setup()`` is the only place the
41
+ library reads an environment variable (``AMPLE_RECEIPTS_DIR``). Its names are
42
+ imported on first use too.
43
+
44
+ Where the service is (``ample_receipts_client.service``):
45
+ :func:`service_url`, a tenant's base URL under the root the caller names (the
46
+ library has no default service).
47
+ """
48
+
49
+ import importlib.util
50
+ from typing import TYPE_CHECKING, Any
51
+
52
+ from ample_receipts_client._version import VERSION
53
+ from ample_receipts_client.capture import (
54
+ BodyForm,
55
+ BodyPart,
56
+ Capture,
57
+ CaptureRecord,
58
+ HeaderPairs,
59
+ HoldOutcome,
60
+ PartState,
61
+ RequestHead,
62
+ ResponseHead,
63
+ Terminal,
64
+ Upstream,
65
+ WireKind,
66
+ )
67
+ from ample_receipts_client.config import (
68
+ CREDENTIAL_MARKER,
69
+ DEFAULT_CAPTURE_LIMIT_BYTES,
70
+ DEFAULT_CREDENTIAL_QUERY_NAMES,
71
+ REQUEST_HEADERS,
72
+ REQUEST_ID_HEADERS,
73
+ RESPONSE_HEADERS,
74
+ TeeConfig,
75
+ )
76
+ from ample_receipts_client.hold import DEFAULT_DEADLINE_MS, HoldHook, HookRunner
77
+ from ample_receipts_client.service import service_url
78
+ from ample_receipts_client.tee import AsyncTeeTransport, CaptureCallback, TeeTransport
79
+
80
+ if TYPE_CHECKING:
81
+ from ample_receipts_client.ack import (
82
+ AckCheck,
83
+ LedgerKeys,
84
+ check_ack,
85
+ load_ledger_public_keys,
86
+ )
87
+ from ample_receipts_client.app import (
88
+ CloseReport,
89
+ FolderError,
90
+ Receipts,
91
+ ReceiptsSetupError,
92
+ ServiceError,
93
+ setup,
94
+ )
95
+
96
+ # ---- unit R12: the library core (commit, salts, statement, sign, ack) ----
97
+ from ample_receipts_client.builder import (
98
+ CallFacts,
99
+ CoreStatementBuilder,
100
+ facts_from_capture,
101
+ )
102
+ from ample_receipts_client.commit import (
103
+ RevealOutcome,
104
+ check_reveal,
105
+ )
106
+ from ample_receipts_client.notices import (
107
+ KeyRequest,
108
+ introduction_request,
109
+ rotation_request,
110
+ )
111
+ from ample_receipts_client.salts import (
112
+ SaltKey,
113
+ SaltKeyError,
114
+ load_salt_key_file,
115
+ )
116
+ from ample_receipts_client.sign import (
117
+ ClientKey,
118
+ ClientKeyError,
119
+ PublicKey,
120
+ Signer,
121
+ client_keys_file_text,
122
+ load_client_signing_key_file,
123
+ )
124
+ from ample_receipts_client.spool import (
125
+ Built,
126
+ EntryKind,
127
+ Loss,
128
+ LossReason,
129
+ Spool,
130
+ SpoolClosedError,
131
+ SpooledStatement,
132
+ SpoolHeader,
133
+ StatementBuilder,
134
+ read_statements,
135
+ )
136
+ from ample_receipts_client.statement import (
137
+ StatementError,
138
+ parse_statement,
139
+ )
140
+
141
+ # -- the submitter (unit R11b) --
142
+ from ample_receipts_client.submitter import (
143
+ AckChecker,
144
+ AckVerdict,
145
+ Alarm,
146
+ AlarmKind,
147
+ Answer,
148
+ Backlog,
149
+ HttpxPoster,
150
+ ItemState,
151
+ KeptAck,
152
+ KeptKeyAck,
153
+ KeyAckChecker,
154
+ KeyPoster,
155
+ KeyRequestOutcome,
156
+ KeyRequestResult,
157
+ PassReport,
158
+ Poster,
159
+ PruneReport,
160
+ Submitter,
161
+ )
162
+ from ample_receipts_client.vault import (
163
+ MissingReason,
164
+ RefusalReason,
165
+ Retention,
166
+ SweepReport,
167
+ Vault,
168
+ VaultConfig,
169
+ VaultError,
170
+ VaultKey,
171
+ VaultKeyError,
172
+ VaultPart,
173
+ VaultProof,
174
+ VaultProofExists,
175
+ VaultProofInfo,
176
+ VaultProofMissing,
177
+ VaultProofRefused,
178
+ VaultRecordExists,
179
+ VaultRecordInfo,
180
+ VaultRecordMissing,
181
+ VaultRecordRefused,
182
+ open_vault,
183
+ )
184
+
185
+ # -- unit R17: the reveal (TYPE_CHECKING names) --
186
+ if TYPE_CHECKING:
187
+ from ample_receipts_client.reveal import (
188
+ Reveal,
189
+ RevealError,
190
+ RevealFiles,
191
+ RevealMismatch,
192
+ prepare_reveal,
193
+ receipt_from_held_acks,
194
+ write_reveal,
195
+ )
196
+
197
+ # ---- unit R18: record() after the fact (TYPE_CHECKING names) ----
198
+ if TYPE_CHECKING:
199
+ from ample_receipts_client.record import (
200
+ ReceivedResponse,
201
+ Recorder,
202
+ RecordInputError,
203
+ RecordResult,
204
+ SentRequest,
205
+ capture_after_the_fact,
206
+ )
207
+
208
+ # -- R05b: the httpx2 tee (TYPE_CHECKING names) --
209
+ if TYPE_CHECKING:
210
+ from ample_receipts_client.tee_httpx2 import (
211
+ AsyncHttpx2TeeTransport as AsyncHttpx2TeeTransport,
212
+ )
213
+ from ample_receipts_client.tee_httpx2 import (
214
+ Httpx2TeeTransport as Httpx2TeeTransport,
215
+ )
216
+
217
+ __version__ = VERSION
218
+
219
+ _SPOOL_NAMES = frozenset(
220
+ {
221
+ "Built",
222
+ "EntryKind",
223
+ "Loss",
224
+ "LossReason",
225
+ "Spool",
226
+ "SpoolClosedError",
227
+ "SpooledStatement",
228
+ "SpoolHeader",
229
+ "StatementBuilder",
230
+ "read_statements",
231
+ }
232
+ )
233
+
234
+ _VAULT_NAMES = frozenset(
235
+ {
236
+ "MissingReason",
237
+ "RefusalReason",
238
+ "Retention",
239
+ "SweepReport",
240
+ "Vault",
241
+ "VaultConfig",
242
+ "VaultError",
243
+ "VaultKey",
244
+ "VaultKeyError",
245
+ "VaultPart",
246
+ "VaultProof",
247
+ "VaultProofExists",
248
+ "VaultProofInfo",
249
+ "VaultProofMissing",
250
+ "VaultProofRefused",
251
+ "VaultRecordExists",
252
+ "VaultRecordInfo",
253
+ "VaultRecordMissing",
254
+ "VaultRecordRefused",
255
+ "open_vault",
256
+ }
257
+ )
258
+
259
+
260
+ # ---- unit R12: the library core, imported on first use (it loads cryptography) ----
261
+ _CORE_NAMES: dict[str, str] = {
262
+ "CallFacts": "builder",
263
+ "CoreStatementBuilder": "builder",
264
+ "facts_from_capture": "builder",
265
+ "SaltKey": "salts",
266
+ "SaltKeyError": "salts",
267
+ "load_salt_key_file": "salts",
268
+ "ClientKey": "sign",
269
+ "ClientKeyError": "sign",
270
+ "PublicKey": "sign",
271
+ "Signer": "sign",
272
+ "load_client_signing_key_file": "sign",
273
+ "client_keys_file_text": "sign",
274
+ "KeyRequest": "notices",
275
+ "introduction_request": "notices",
276
+ "rotation_request": "notices",
277
+ "AckCheck": "ack",
278
+ "LedgerKeys": "ack",
279
+ "check_ack": "ack",
280
+ "load_ledger_public_keys": "ack",
281
+ "StatementError": "statement",
282
+ "parse_statement": "statement",
283
+ "RevealOutcome": "commit",
284
+ "check_reveal": "commit",
285
+ }
286
+ # -- the submitter (unit R11b): loaded on first use, like the spool --
287
+ _SUBMITTER_NAMES = frozenset(
288
+ {
289
+ "AckChecker",
290
+ "AckVerdict",
291
+ "Alarm",
292
+ "AlarmKind",
293
+ "Answer",
294
+ "Backlog",
295
+ "HttpxPoster",
296
+ "ItemState",
297
+ "KeptAck",
298
+ "KeptKeyAck",
299
+ "KeyAckChecker",
300
+ "KeyPoster",
301
+ "KeyRequestOutcome",
302
+ "KeyRequestResult",
303
+ "PassReport",
304
+ "Poster",
305
+ "PruneReport",
306
+ "Submitter",
307
+ }
308
+ )
309
+ # -- unit R17: the reveal, imported on first use (it loads the core) --
310
+ _REVEAL_NAMES = frozenset(
311
+ {
312
+ "Reveal",
313
+ "RevealError",
314
+ "RevealFiles",
315
+ "RevealMismatch",
316
+ "prepare_reveal",
317
+ "receipt_from_held_acks",
318
+ "write_reveal",
319
+ }
320
+ )
321
+
322
+ # ---- unit R18: record() after the fact, imported on first use ----
323
+ # The function itself is ``ample_receipts_client.record.record``: a package
324
+ # attribute named ``record`` would be shadowed by the submodule of that name.
325
+ _RECORD_NAMES = frozenset(
326
+ {
327
+ "ReceivedResponse",
328
+ "RecordInputError",
329
+ "RecordResult",
330
+ "Recorder",
331
+ "SentRequest",
332
+ "capture_after_the_fact",
333
+ }
334
+ )
335
+ # -- quick setup: setup() and Receipts, imported on first use (they load the core) --
336
+ _APP_NAMES = frozenset(
337
+ {
338
+ "CloseReport",
339
+ "FolderError",
340
+ "Receipts",
341
+ "ReceiptsSetupError",
342
+ "ServiceError",
343
+ "setup",
344
+ }
345
+ )
346
+ # -- R05b: the httpx2 tee, imported on first use (it imports httpx2) --
347
+ _HTTPX2_TEE_NAMES = frozenset({"AsyncHttpx2TeeTransport", "Httpx2TeeTransport"})
348
+
349
+
350
+ def __getattr__(name: str) -> Any:
351
+ """The spool's and the vault's names, imported on first use.
352
+
353
+ The spool needs POSIX (``fcntl``) and registers a fork handler; the vault
354
+ loads cryptography and is off unless the customer turns it on (MUST-V1).
355
+ Importing the package alone (the tee) does none of this.
356
+ """
357
+ if name in _SPOOL_NAMES:
358
+ from ample_receipts_client import spool
359
+
360
+ return getattr(spool, name)
361
+ if name in _VAULT_NAMES:
362
+ from ample_receipts_client import vault
363
+
364
+ return getattr(vault, name)
365
+ if name in _CORE_NAMES: # unit R12
366
+ import importlib
367
+
368
+ module = importlib.import_module(f"{__name__}.{_CORE_NAMES[name]}")
369
+ return getattr(module, name)
370
+ if name in _SUBMITTER_NAMES:
371
+ from ample_receipts_client import submitter
372
+
373
+ return getattr(submitter, name)
374
+ if name in _REVEAL_NAMES: # unit R17
375
+ from ample_receipts_client import reveal
376
+
377
+ return getattr(reveal, name)
378
+ if name in _RECORD_NAMES: # unit R18
379
+ from ample_receipts_client import record
380
+
381
+ return getattr(record, name)
382
+ if name in _APP_NAMES: # quick setup
383
+ from ample_receipts_client import app
384
+
385
+ return getattr(app, name)
386
+ if name in _HTTPX2_TEE_NAMES: # R05b
387
+ try:
388
+ from ample_receipts_client import tee_httpx2
389
+ except ImportError as exc:
390
+ raise AttributeError(
391
+ f"{name} needs httpx2: install ample-receipts-client[httpx2]"
392
+ ) from exc
393
+ return getattr(tee_httpx2, name)
394
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
395
+
396
+
397
+ __all__ = [
398
+ "CREDENTIAL_MARKER",
399
+ "DEFAULT_CAPTURE_LIMIT_BYTES",
400
+ "DEFAULT_CREDENTIAL_QUERY_NAMES",
401
+ "DEFAULT_DEADLINE_MS",
402
+ "REQUEST_HEADERS",
403
+ "REQUEST_ID_HEADERS",
404
+ "RESPONSE_HEADERS",
405
+ "VERSION",
406
+ "AckCheck",
407
+ "AckChecker",
408
+ "AckVerdict",
409
+ "Alarm",
410
+ "AlarmKind",
411
+ "Answer",
412
+ "AsyncTeeTransport",
413
+ "Backlog",
414
+ "BodyForm",
415
+ "BodyPart",
416
+ "Built",
417
+ "CallFacts",
418
+ "Capture",
419
+ "CaptureCallback",
420
+ "CaptureRecord",
421
+ "ClientKey",
422
+ "ClientKeyError",
423
+ "CloseReport",
424
+ "CoreStatementBuilder",
425
+ "EntryKind",
426
+ "FolderError",
427
+ "HeaderPairs",
428
+ "HoldHook",
429
+ "HoldOutcome",
430
+ "HookRunner",
431
+ "HttpxPoster",
432
+ "ItemState",
433
+ "KeptAck",
434
+ "KeptKeyAck",
435
+ "KeyAckChecker",
436
+ "KeyPoster",
437
+ "KeyRequest",
438
+ "KeyRequestOutcome",
439
+ "KeyRequestResult",
440
+ "LedgerKeys",
441
+ "Loss",
442
+ "LossReason",
443
+ "MissingReason",
444
+ "PartState",
445
+ "PassReport",
446
+ "Poster",
447
+ "PruneReport",
448
+ "PublicKey",
449
+ "Receipts",
450
+ "ReceiptsSetupError",
451
+ "ReceivedResponse",
452
+ "RecordInputError",
453
+ "RecordResult",
454
+ "Recorder",
455
+ "RefusalReason",
456
+ "RequestHead",
457
+ "ResponseHead",
458
+ "Retention",
459
+ "Reveal",
460
+ "RevealError",
461
+ "RevealFiles",
462
+ "RevealMismatch",
463
+ "RevealOutcome",
464
+ "SaltKey",
465
+ "SaltKeyError",
466
+ "SentRequest",
467
+ "ServiceError",
468
+ "Signer",
469
+ "Spool",
470
+ "SpoolClosedError",
471
+ "SpoolHeader",
472
+ "SpooledStatement",
473
+ "StatementBuilder",
474
+ "StatementError",
475
+ "Submitter",
476
+ "SweepReport",
477
+ "TeeConfig",
478
+ "TeeTransport",
479
+ "Terminal",
480
+ "Upstream",
481
+ "Vault",
482
+ "VaultConfig",
483
+ "VaultError",
484
+ "VaultKey",
485
+ "VaultKeyError",
486
+ "VaultPart",
487
+ "VaultProof",
488
+ "VaultProofExists",
489
+ "VaultProofInfo",
490
+ "VaultProofMissing",
491
+ "VaultProofRefused",
492
+ "VaultRecordExists",
493
+ "VaultRecordInfo",
494
+ "VaultRecordMissing",
495
+ "VaultRecordRefused",
496
+ "WireKind",
497
+ "__version__",
498
+ "capture_after_the_fact",
499
+ "check_ack",
500
+ "check_reveal",
501
+ "client_keys_file_text",
502
+ "facts_from_capture",
503
+ "introduction_request",
504
+ "load_client_signing_key_file",
505
+ "load_ledger_public_keys",
506
+ "load_salt_key_file",
507
+ "open_vault",
508
+ "parse_statement",
509
+ "prepare_reveal",
510
+ "read_statements",
511
+ "receipt_from_held_acks",
512
+ "rotation_request",
513
+ "service_url",
514
+ "setup",
515
+ "write_reveal",
516
+ ]
517
+
518
+ # -- R05b: the httpx2 tee's names are listed only where httpx2 is installed
519
+ # (``find_spec`` looks without importing), so a star import never fails. --
520
+ if importlib.util.find_spec("httpx2") is not None:
521
+ __all__ += sorted(_HTTPX2_TEE_NAMES)
@@ -0,0 +1,6 @@
1
+ """``python -m ample_receipts_client``: the ``ample-receipts`` command."""
2
+
3
+ from ample_receipts_client.cli import main
4
+
5
+ if __name__ == "__main__": # pragma: no cover
6
+ raise SystemExit(main())
@@ -0,0 +1,28 @@
1
+ """The command-line parser the library's commands share.
2
+
3
+ An argument the parser does not know is not repeated back: it could be a
4
+ secret typed on the command line, and secrets are read only from files.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ from typing import Final, NoReturn
11
+
12
+ __all__ = ["UNKNOWN_ARGUMENTS", "Parser", "Usage"]
13
+
14
+ UNKNOWN_ARGUMENTS: Final = (
15
+ "unrecognized arguments (not repeated here: a value given on the command "
16
+ "line may be a secret, and secrets are read only from files)"
17
+ )
18
+
19
+
20
+ class Usage(Exception):
21
+ """A usage error (exit 2); the text never repeats an unknown argument."""
22
+
23
+
24
+ class Parser(argparse.ArgumentParser):
25
+ def error(self, message: str) -> NoReturn:
26
+ if message.startswith("unrecognized arguments"):
27
+ message = UNKNOWN_ARGUMENTS
28
+ raise Usage(message)
@@ -0,0 +1,131 @@
1
+ """The HTTP package a tee wraps: httpx, or httpx2 (unit R05b).
2
+
3
+ The tee's core (``tee._Attempt`` and the stream tees) is the same code for
4
+ both packages. What differs is named here, once per package: the stream base
5
+ classes the client checks with ``isinstance``, the "not read" exceptions, the
6
+ decoding error, and the package's own content decoders (spec 5.2, MUST-38: the
7
+ tee decodes each coding with the decoder the client library applies to it).
8
+
9
+ :data:`HTTPX` is built on import (httpx is the library's hard dependency).
10
+ :func:`httpx2_lib` imports httpx2 on its first call only, so importing the
11
+ package (or the httpx tee) never loads httpx2.
12
+
13
+ One exception (wave 3a integration, W3AB): when the app ran
14
+ ``httpx2.alias_httpx()`` before importing this library, ``import httpx``
15
+ gives the httpx2 package itself (:data:`HTTPX_IS_HTTPX2`). Then httpx2 is
16
+ already loaded, and :data:`HTTPX` is httpx2's description, so the httpx tee
17
+ (``TeeTransport``, whose base class is then httpx2's) runs the httpx2 code
18
+ path with httpx2's own decoders, exactly as ``Httpx2TeeTransport`` does.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import functools
24
+ from collections.abc import Callable, Iterable, Mapping, Sequence
25
+ from dataclasses import dataclass
26
+ from typing import Any, cast
27
+
28
+ import httpx
29
+
30
+
31
+ @dataclass(frozen=True, slots=True, eq=False)
32
+ class HttpLib:
33
+ """What the tee's core needs from one HTTP package."""
34
+
35
+ name: str
36
+ module: Any
37
+ """The package itself (``httpx`` or ``httpx2``)."""
38
+ byte_stream: type[Any]
39
+ """The re-readable in-memory stream (``ByteStream``)."""
40
+ sync_byte_stream: type[Any]
41
+ async_byte_stream: type[Any]
42
+ request_not_read: type[Exception]
43
+ response_not_read: type[Exception]
44
+ decoding_error: type[Exception]
45
+ decoders: Mapping[str, type[Any]]
46
+ """The package's ``SUPPORTED_DECODERS`` (``identity`` included)."""
47
+ multi_decoder: Callable[[Sequence[str], Sequence[Any]], Any]
48
+ """``(codings in the order listed, one decoder each) -> one decoder``.
49
+
50
+ May raise ``decoding_error``, as the package's own client would."""
51
+
52
+ def empty_headers(self) -> Any:
53
+ return self.module.Headers()
54
+
55
+
56
+ @functools.cache
57
+ def httpx2_lib() -> HttpLib:
58
+ """httpx2's description. Imports httpx2 (raises ``ImportError`` without it)."""
59
+ import httpx2
60
+ from httpx2 import _decoders as _httpx2_decoders
61
+
62
+ def multi(codings: Sequence[str], _children: Sequence[Any]) -> Any:
63
+ # httpx2's client builds its MultiDecoder from the coding names (and
64
+ # refuses more than ``max_decode_links`` of them with DecodingError);
65
+ # the tee builds it the same way, so it decodes as the client does.
66
+ return _httpx2_decoders.MultiDecoder(list(codings))
67
+
68
+ return HttpLib(
69
+ name="httpx2",
70
+ module=httpx2,
71
+ byte_stream=httpx2.ByteStream,
72
+ sync_byte_stream=httpx2.SyncByteStream,
73
+ async_byte_stream=httpx2.AsyncByteStream,
74
+ request_not_read=httpx2.RequestNotRead,
75
+ response_not_read=httpx2.ResponseNotRead,
76
+ decoding_error=httpx2.DecodingError,
77
+ decoders=_httpx2_decoders.SUPPORTED_DECODERS,
78
+ multi_decoder=multi,
79
+ )
80
+
81
+
82
+ HTTPX_IS_HTTPX2: bool = httpx.__name__ == "httpx2"
83
+ """Whether ``import httpx`` gave httpx2 (``httpx2.alias_httpx()`` ran first).
84
+
85
+ ``httpx2.alias_httpx()`` makes ``import httpx`` return the httpx2 package,
86
+ process-wide. When the app called it before importing this library, the
87
+ httpx tee's requests, replies and decoders are all httpx2's, so the httpx
88
+ tee runs the httpx2 code path (:data:`HTTPX` is :func:`httpx2_lib`'s
89
+ description): the records are the same as under the httpx2 tee.
90
+ """
91
+
92
+
93
+ def _httpx_lib() -> HttpLib:
94
+ """httpx's description (the real httpx package)."""
95
+ from httpx import _decoders as _httpx_decoders
96
+
97
+ def multi(_codings: Sequence[str], children: Sequence[Any]) -> Any:
98
+ return _httpx_decoders.MultiDecoder(
99
+ children=list(children)
100
+ ) # undoes in reverse
101
+
102
+ return HttpLib(
103
+ name="httpx",
104
+ module=httpx,
105
+ byte_stream=httpx.ByteStream,
106
+ sync_byte_stream=httpx.SyncByteStream,
107
+ async_byte_stream=httpx.AsyncByteStream,
108
+ request_not_read=httpx.RequestNotRead,
109
+ response_not_read=httpx.ResponseNotRead,
110
+ decoding_error=httpx.DecodingError,
111
+ decoders=_httpx_decoders.SUPPORTED_DECODERS,
112
+ multi_decoder=multi,
113
+ )
114
+
115
+
116
+ HTTPX: HttpLib = httpx2_lib() if HTTPX_IS_HTTPX2 else _httpx_lib()
117
+ """The package ``import httpx`` gave: httpx's description, or httpx2's when aliased."""
118
+
119
+
120
+ def pieces(out: Any) -> Iterable[bytes]:
121
+ """A decoder's output as byte pieces, read one at a time.
122
+
123
+ httpx's decoders return bytes (one piece, as large as httpx's own client
124
+ makes it). httpx2's return an iterator of pieces of at most 1 MiB each,
125
+ made as they are read: httpx2's bound against a body that inflates without
126
+ end. The tee reads them one at a time and never joins them, so it keeps
127
+ that bound (a piece past the capture limit is dropped once it is read).
128
+ """
129
+ if isinstance(out, bytes):
130
+ return (out,)
131
+ return cast("Iterable[bytes]", out)