lothc 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lothc
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Lord Of The Http Clients — a typed HTTP client built on pyreqwest, with first-class pydantic and msgspec support
5
5
  Project-URL: Homepage, https://github.com/RogerThomas/lothc
6
6
  Project-URL: Repository, https://github.com/RogerThomas/lothc
@@ -12,6 +12,7 @@ Classifier: Development Status :: 3 - Alpha
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Programming Language :: Python :: 3.13
14
14
  Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
15
16
  Classifier: Typing :: Typed
16
17
  Requires-Python: >=3.13
17
18
  Requires-Dist: pyreqwest>=0.13.0
@@ -190,7 +190,9 @@ class HTTPResponseError[E = object](Exception):
190
190
  `.error` is the body decoded: as `E` when a subclass pins it
191
191
  (`class APIError(HTTPResponseError[NotFound | Conflict]): pass`, passed as `raises=`), else
192
192
  as a JSON object (`dict`), else `None` (HTML, text, an array). When a pinned `E` didn't match,
193
- `.parse_error` holds why (the decode library's own `ValueError`). `.parse_error` isn't
193
+ `.parse_error` holds why (the decode library's own `ValueError`, or a `ValueError` chained to
194
+ whatever else decoding raised, e.g. a `RecursionError` for a body nested too deep to parse).
195
+ `.parse_error` isn't
194
196
  carried across pickling, since pydantic's `ValidationError` can't be pickled.
195
197
  """
196
198
 
@@ -310,16 +312,14 @@ def _atomic_download_file(dest: Path) -> Generator[BufferedWriter]:
310
312
  raise
311
313
 
312
314
 
313
- def _complete_ndjson_lines(pending: bytearray, chunk: Buffer) -> list[bytearray]:
314
- """Append `chunk` to `pending` and return the non-blank lines it completes, leaving only the
315
+ def _take_completed_lines(pending: bytearray, chunk: Buffer) -> list[bytearray]:
316
+ """Append `chunk` to `pending` and return every line it completes, leaving only the
315
317
  still-unterminated tail in `pending`.
316
318
 
317
319
  Linear in the bytes received. The old `line, buffer = buffer.split(b"\\n", 1)` loop copied the
318
320
  whole remainder once per line (a 4MB chunk took ~4.7s; this takes ~15ms), and only the newly
319
321
  appended bytes are searched for a newline, since everything before the last one has already
320
- been consumed; rescanning all of `pending` made one long line quadratic instead. A line that
321
- is only whitespace is skipped rather than decoded, which covers the `\\r` a CRLF-terminated
322
- stream leaves on its blank lines.
322
+ been consumed; rescanning all of `pending` made one long line quadratic instead.
323
323
  """
324
324
  start = len(pending)
325
325
  pending += chunk
@@ -328,7 +328,32 @@ def _complete_ndjson_lines(pending: bytearray, chunk: Buffer) -> list[bytearray]
328
328
  return []
329
329
  lines = pending[:end].split(b"\n")
330
330
  del pending[: end + 1]
331
- return [line for line in lines if line.strip()]
331
+ return lines
332
+
333
+
334
+ def _complete_ndjson_lines(pending: bytearray, chunk: Buffer) -> list[bytearray]:
335
+ """The non-blank NDJSON lines `chunk` completes (see `_take_completed_lines`). A line that is
336
+ only whitespace is skipped rather than decoded, which covers the `\\r` a CRLF-terminated
337
+ stream leaves on its blank lines; a JSON decoder tolerates the `\\r` ending any other line."""
338
+ return [line for line in _take_completed_lines(pending, chunk) if line.strip()]
339
+
340
+
341
+ def _strip_carriage_return(line: bytearray) -> bytearray:
342
+ return line[:-1] if line.endswith(b"\r") else line
343
+
344
+
345
+ def _complete_text_lines(pending: bytearray, chunk: Buffer) -> list[bytearray]:
346
+ """The raw text lines `chunk` completes, for `into=str` (see `_take_completed_lines`): every
347
+ one, blank lines included, with one trailing `\\r` (from a CRLF terminator) stripped."""
348
+ return [_strip_carriage_return(line) for line in _take_completed_lines(pending, chunk)]
349
+
350
+
351
+ def _final_line(pending: bytearray, *, raw_text: bool) -> bytearray | None:
352
+ """The unterminated tail left in `pending` when a line stream ends, if it holds a line: any
353
+ bytes at all for `into=str` (CR-stripped like the others), else only a non-blank one."""
354
+ if raw_text:
355
+ return _strip_carriage_return(pending) if pending else None
356
+ return pending if pending.strip() else None
332
357
 
333
358
 
334
359
  def _idle_timeout_error(idle: float) -> HTTPTimeoutError:
@@ -1100,8 +1125,22 @@ class _TextDecoder:
1100
1125
  return data if isinstance(data, str) else str(data, "utf-8")
1101
1126
 
1102
1127
 
1128
+ @dataclass(slots=True)
1129
+ class _SSEBytesDecoder:
1130
+ """`sse(into=bytes)`: an event's `data`, which arrives as text, back as its UTF-8 bytes.
1131
+ Only `sse()` uses it; everywhere else `bytes` is no decoder at all (`None`)."""
1132
+
1133
+ def decode(self, data: _JSONInput) -> bytes:
1134
+ return data.encode() if isinstance(data, str) else bytes(data)
1135
+
1136
+
1103
1137
  type _Decoder = (
1104
- Decoder[Any] | TypeAdapter[Any] | _JSONObjectDecoder | _DictSubclassDecoder | _TextDecoder
1138
+ Decoder[Any]
1139
+ | TypeAdapter[Any]
1140
+ | _JSONObjectDecoder
1141
+ | _DictSubclassDecoder
1142
+ | _TextDecoder
1143
+ | _SSEBytesDecoder
1105
1144
  )
1106
1145
  type _Into = TypeForm[Any] | TypeAdapterTyping[Any] | DecoderTyping[Any] | None
1107
1146
 
@@ -1237,6 +1276,53 @@ def _is_bare_dict_subclass(form: object) -> TypeIs[type[dict[Any, Any]]]:
1237
1276
  return _is_class(form) and not is_typeddict(form) and issubclass(form, dict)
1238
1277
 
1239
1278
 
1279
+ def _is_json_object_form(form: object) -> bool:
1280
+ """Whether `form` means "any JSON object", which stdlib `json` decodes with no extra: `dict`,
1281
+ `dict[str, Any]` however it's spelled (`typing.Dict[str, Any]`, bare `typing.Dict`), and
1282
+ `Mapping[str, Any]`, since the `dict` it gets is one.
1283
+
1284
+ >>> from typing import Dict
1285
+ >>> [_is_json_object_form(f) for f in (dict, Dict[str, Any], Mapping[str, Any], dict[str, int])]
1286
+ [True, True, True, False]
1287
+ """
1288
+ if form is dict:
1289
+ return True
1290
+ # `in` a tuple, not a set: an argument can be unhashable (`Annotated` with a `dict` in it).
1291
+ return get_origin(form) in {dict, Mapping} and get_args(form) in ((), (str, Any))
1292
+
1293
+
1294
+ def _is_tuple(value: object) -> TypeIs[tuple[object, ...]]:
1295
+ # A `TypeIs`, not an inline `isinstance`: that narrows to a partially unknown tuple.
1296
+ return isinstance(value, tuple)
1297
+
1298
+
1299
+ def _has_msgspec_custom_type(form: object) -> bool:
1300
+ """Whether msgspec reads some part of `form` as a "custom type" (`Path`, `deque[int]`,
1301
+ `IPv4Address`, a parametrized `dict` subclass such as `OrderedDict[str, int]`): one it only
1302
+ decodes through a `dec_hook`, which lothc doesn't pass, so its `Decoder` builds fine and then
1303
+ rejects every body. Walks `msgspec.inspect.type_info`'s tree, a recursive one ending at the
1304
+ first node seen twice. `object` is a custom type to `type_info` but decodes as `Any`."""
1305
+ try:
1306
+ root = msgspec.inspect.type_info(form)
1307
+ except TypeError:
1308
+ # Not a type msgspec knows at all: its `Decoder` reports that itself.
1309
+ return False
1310
+ seen: set[int] = set()
1311
+ pending: list[object] = [root]
1312
+ while pending:
1313
+ node = pending.pop()
1314
+ if _is_tuple(node):
1315
+ pending.extend(node)
1316
+ continue
1317
+ if not isinstance(node, (msgspec.inspect.Type, msgspec.inspect.Field)) or id(node) in seen:
1318
+ continue
1319
+ if isinstance(node, msgspec.inspect.CustomType) and node.cls is not object:
1320
+ return True
1321
+ seen.add(id(node))
1322
+ pending.extend(getattr(node, name) for name in node.__struct_fields__)
1323
+ return False
1324
+
1325
+
1240
1326
  def _msgspec_decoder(form: object) -> Decoder[Any]:
1241
1327
  try:
1242
1328
  return Decoder(form)
@@ -1253,12 +1339,13 @@ def _pydantic_adapter(form: object) -> TypeAdapter[Any]:
1253
1339
 
1254
1340
 
1255
1341
  def _build_decoder(form: object, model_bases: set[type]) -> _Decoder:
1256
- """The decoder for a type expression: raw text for `str`, stdlib `json` for `dict` and its
1257
- bare subclasses, else whichever library the form's models (or pydantic-only metadata) belong
1258
- to, else msgspec (faster), else pydantic."""
1342
+ """The decoder for a type expression: raw text for `str`, stdlib `json` for a JSON object
1343
+ (`dict`, `dict[str, Any]`, `Mapping[str, Any]`) and bare `dict` subclasses, else whichever
1344
+ library the form's models (or pydantic-only metadata) belong to, else msgspec (faster) unless
1345
+ it can't decode part of the form, else pydantic."""
1259
1346
  if form is str:
1260
1347
  return _TextDecoder()
1261
- if form is dict or form == dict[str, Any]:
1348
+ if _is_json_object_form(form):
1262
1349
  return _JSONObjectDecoder()
1263
1350
  if _is_bare_dict_subclass(form):
1264
1351
  return _DictSubclassDecoder(form)
@@ -1276,14 +1363,22 @@ def _build_decoder(form: object, model_bases: set[type]) -> _Decoder:
1276
1363
  " msgspec would silently skip: install lothc[pydantic]."
1277
1364
  )
1278
1365
  return _pydantic_adapter(form)
1279
- if msgspec_installed:
1366
+ # A Struct form stays with msgspec whatever its fields are: pydantic can't build a Struct.
1367
+ if msgspec_installed and (Struct in model_bases or not _has_msgspec_custom_type(form)):
1280
1368
  return _msgspec_decoder(form)
1369
+ if msgspec_installed and not pydantic_installed:
1370
+ raise TypeError(
1371
+ f"into={form!r} contains a type msgspec can't decode from JSON (e.g. Path, deque,"
1372
+ " IPv4Address, or a parametrized dict subclass such as OrderedDict[str, int]), so"
1373
+ " every response would fail to decode: install lothc[pydantic], which can. A bare"
1374
+ " dict subclass (into=OrderedDict) needs neither extra."
1375
+ )
1281
1376
  if pydantic_installed:
1282
1377
  return _pydantic_adapter(form)
1283
1378
  raise TypeError(
1284
1379
  f"into={form!r} needs msgspec or pydantic to decode it: install lothc[msgspec] or"
1285
- " lothc[pydantic]. Only bytes, str, dict (and its subclasses) and dict[str, Any] work"
1286
- " without either."
1380
+ " lothc[pydantic]. Only bytes, str, dict (and its bare subclasses), dict[str, Any] and"
1381
+ " Mapping[str, Any] work without either."
1287
1382
  )
1288
1383
 
1289
1384
 
@@ -1344,11 +1439,18 @@ def _decode_json_line(data: _JSONInput, decoder: _Decoder) -> Any: # noqa: ANN4
1344
1439
  return decoder.decode(data)
1345
1440
 
1346
1441
 
1442
+ def _sse_data_decoder(into: _Into) -> _Decoder:
1443
+ """The decoder for each SSE event's `data`, resolved once per stream. Never `None`, unlike
1444
+ `_decoder_for`'s: `data` arrives as text, so the default (`into=None`) keeps it as text and
1445
+ `into=bytes` encodes it back."""
1446
+ if into is bytes:
1447
+ return _SSEBytesDecoder()
1448
+ decoder = _decoder_for(into)
1449
+ return _TextDecoder() if decoder is None else decoder
1450
+
1451
+
1347
1452
  def _dispatch_sse_record(
1348
- record: bytes,
1349
- state: _SSEStreamState,
1350
- into: _Into,
1351
- decoder: _Decoder | None,
1453
+ record: bytes, state: _SSEStreamState, decoder: _Decoder
1352
1454
  ) -> SSEEvent[Any] | None:
1353
1455
  """Apply one record's `retry:`/`id:` fields to `state`, then build its event (if it has data).
1354
1456
 
@@ -1364,12 +1466,7 @@ def _dispatch_sse_record(
1364
1466
  state.last_event_id = parsed_record.id
1365
1467
  if parsed_record.data is None:
1366
1468
  return None
1367
- if decoder is not None:
1368
- data = _decode_json_line(parsed_record.data, decoder)
1369
- elif into is bytes:
1370
- data = parsed_record.data.encode()
1371
- else:
1372
- data = parsed_record.data
1469
+ data = _decode_json_line(parsed_record.data, decoder)
1373
1470
  return SSEEvent(id=state.last_event_id, event=parsed_record.event, data=data)
1374
1471
 
1375
1472
 
@@ -2297,12 +2394,6 @@ class _ErrorBodyDecoding:
2297
2394
  decoder: _Decoder | None
2298
2395
 
2299
2396
 
2300
- # One per `raises=` class, shared by both clients, like `_decoders` (which caches the decoder
2301
- # itself): what this saves is the walk through the class's bases on every error. Unbounded,
2302
- # since the classes come from source code, not data.
2303
- _error_body_decodings: dict[type, _ErrorBodyDecoding] = {}
2304
-
2305
-
2306
2397
  def _is_response_error_class(value: object) -> TypeIs[type[HTTPResponseError[Any]]]:
2307
2398
  return isinstance(value, type) and issubclass(value, HTTPResponseError)
2308
2399
 
@@ -2366,7 +2457,15 @@ def _pinned_error_form(cls: type, bindings: Mapping[TypeVar, object]) -> tuple[(
2366
2457
  return ()
2367
2458
 
2368
2459
 
2369
- def _resolve_error_body_decoding(raises: object) -> _ErrorBodyDecoding:
2460
+ # One per `raises=` class, shared by both clients, like `_decoders` (which caches the decoder
2461
+ # itself): what this saves is the walk through the class's bases on every error. Unbounded, since
2462
+ # the classes come from source code, not data. `cache` stores nothing when the call raises, so an
2463
+ # unusable `raises` (not an `HTTPResponseError` subclass, an unbound `E`, an `E` no library can
2464
+ # decode) is a `TypeError` on every call: a caller bug, never cached and never swallowed.
2465
+ @cache
2466
+ def _error_body_decoding(raises: object) -> _ErrorBodyDecoding:
2467
+ """`raises`'s resolved `E` and its decoder. Takes `object`, since nothing has checked yet
2468
+ that `raises` really is an `HTTPResponseError` subclass."""
2370
2469
  if not _is_response_error_class(raises):
2371
2470
  raise TypeError(
2372
2471
  f"raises= must be HTTPResponseError or a subclass of it, got {raises!r}. To decode"
@@ -2385,16 +2484,6 @@ def _resolve_error_body_decoding(raises: object) -> _ErrorBodyDecoding:
2385
2484
  return _ErrorBodyDecoding(pinned=True, decoder=_decoder_for(form))
2386
2485
 
2387
2486
 
2388
- def _error_body_decoding(raises: type[HTTPResponseError[Any]]) -> _ErrorBodyDecoding:
2389
- """`raises`'s resolved `E` and its decoder, cached per class. An unusable `raises` (not an
2390
- `HTTPResponseError` subclass, an unbound `E`, an `E` no library can decode) raises
2391
- `TypeError`: a caller bug, so it's never cached and never swallowed."""
2392
- decoding = _error_body_decodings.get(raises)
2393
- if decoding is None:
2394
- decoding = _error_body_decodings[raises] = _resolve_error_body_decoding(raises)
2395
- return decoding
2396
-
2397
-
2398
2487
  def _validate_raises(raises: type[HTTPResponseError[Any]] | None) -> None:
2399
2488
  """Resolve a per-call `raises=` before anything is sent, so a bad class is a `TypeError` on
2400
2489
  every call rather than one that only surfaces on a real 4xx/5xx, in place of that error.
@@ -2404,10 +2493,11 @@ def _validate_raises(raises: type[HTTPResponseError[Any]] | None) -> None:
2404
2493
 
2405
2494
 
2406
2495
  def _json_object_or_none(body: bytes) -> dict[str, Any] | None:
2407
- """`body` as a JSON object, or `None` if it isn't one (HTML, text, an array, `null`)."""
2496
+ """`body` as a JSON object, or `None` if it isn't one (HTML, text, an array, `null`, or
2497
+ nested too deep to parse)."""
2408
2498
  try:
2409
2499
  return _JSONObjectDecoder().decode(body)
2410
- except ValueError:
2500
+ except (ValueError, RecursionError): # `RecursionError`: nested too deep for stdlib `json`
2411
2501
  return None
2412
2502
 
2413
2503
 
@@ -2416,6 +2506,18 @@ def _decode_pinned_error(body: bytes, decoder: _Decoder | None) -> Any: # noqa:
2416
2506
  return body if decoder is None else _decode_json_line(body, decoder)
2417
2507
 
2418
2508
 
2509
+ def _as_parse_error(error: Exception) -> ValueError:
2510
+ """`error` as the `ValueError` `.parse_error` promises: itself if it already is one (every
2511
+ decode library's own failure), else a `ValueError` chained to it (`__cause__`), for the
2512
+ `RecursionError` a deeply nested body raises and the `TypeError` a pinned `dict` subclass's
2513
+ own constructor can raise."""
2514
+ if isinstance(error, ValueError):
2515
+ return error
2516
+ parse_error = ValueError(f"error body could not be decoded: {error!r}")
2517
+ parse_error.__cause__ = error
2518
+ return parse_error
2519
+
2520
+
2419
2521
  def _status_error(
2420
2522
  raises: type[HTTPResponseError[Any]],
2421
2523
  status: int,
@@ -2429,21 +2531,26 @@ def _status_error(
2429
2531
  own contract: a body that doesn't match the pinned `E` (a proxy's HTML 502, an error shape
2430
2532
  the union doesn't cover) keeps the decode library's `ValueError` on `.parse_error` and falls
2431
2533
  back to a JSON object, else `None`, rather than replacing the status error with a
2432
- `ValidationError`. Nothing pinned: a JSON object, else `None`.
2534
+ `ValidationError`. A body too deeply nested to parse, or one a pinned `dict` subclass's
2535
+ constructor rejects, is treated the same, its error wrapped in a `ValueError`. Nothing pinned:
2536
+ a JSON object, else `None`.
2433
2537
  """
2434
2538
  decoding = _error_body_decoding(raises)
2435
2539
  if not decoding.pinned:
2436
2540
  return raises(status, body, request_info, _json_object_or_none(body), headers=headers)
2437
2541
  try:
2438
2542
  error = _decode_pinned_error(body, decoding.decoder)
2439
- except ValueError as parse_error:
2543
+ # An unusable `E` was already rejected when `raises` was resolved, so anything decoding
2544
+ # raises here is the body's fault: too deeply nested (`RecursionError`), or refused by a
2545
+ # pinned `dict` subclass's own constructor (`TypeError`).
2546
+ except (ValueError, RecursionError, TypeError) as decode_error:
2440
2547
  return raises(
2441
2548
  status,
2442
2549
  body,
2443
2550
  request_info,
2444
2551
  _json_object_or_none(body),
2445
2552
  headers=headers,
2446
- parse_error=parse_error,
2553
+ parse_error=_as_parse_error(decode_error),
2447
2554
  )
2448
2555
  return raises(status, body, request_info, error, headers=headers)
2449
2556
 
@@ -3662,8 +3769,7 @@ class HTTPClient:
3662
3769
  self,
3663
3770
  request_builder: RequestBuilder,
3664
3771
  state: _SSEStreamState,
3665
- into: _Into,
3666
- decoder: _Decoder | None,
3772
+ decoder: _Decoder,
3667
3773
  *,
3668
3774
  error_for_status: bool,
3669
3775
  raises: type[HTTPResponseError[Any]] | None,
@@ -3700,7 +3806,7 @@ class HTTPClient:
3700
3806
  records, tail = _split_sse_records(bytes(buffer))
3701
3807
  buffer = bytearray(tail)
3702
3808
  for record in records:
3703
- event = _dispatch_sse_record(record, state, into, decoder)
3809
+ event = _dispatch_sse_record(record, state, decoder)
3704
3810
  if event is not None:
3705
3811
  yield event
3706
3812
  except (PyreqwestRequestError, PyreqwestBuilderError) as error:
@@ -3723,7 +3829,7 @@ class HTTPClient:
3723
3829
  ) -> AsyncGenerator[SSEEvent[Any]]:
3724
3830
  _validate_raises(raises)
3725
3831
  # Resolved once per stream, not per event or per reconnect.
3726
- decoder = _decoder_for(into)
3832
+ decoder = _sse_data_decoder(into)
3727
3833
  state = _SSEStreamState(retry_delay=reconnect_delay)
3728
3834
  consecutive_reconnects = 0
3729
3835
  effective_timeout = timeout if timeout is not None else self._streaming_default_timeout
@@ -3737,7 +3843,6 @@ class HTTPClient:
3737
3843
  connection = self._sse_connection(
3738
3844
  request_builder,
3739
3845
  state,
3740
- into,
3741
3846
  decoder,
3742
3847
  error_for_status=error_for_status,
3743
3848
  raises=raises,
@@ -3932,15 +4037,18 @@ class HTTPClient:
3932
4037
  if chunk is None:
3933
4038
  return
3934
4039
  yield bytes(chunk)
4040
+ raw_text = isinstance(decoder, _TextDecoder)
4041
+ complete_lines = _complete_text_lines if raw_text else _complete_ndjson_lines
3935
4042
  pending = bytearray()
3936
4043
  while True:
3937
4044
  chunk = await _read_chunk_within(raw_response, idle)
3938
4045
  if chunk is None:
3939
4046
  break
3940
- for line in _complete_ndjson_lines(pending, chunk):
4047
+ for line in complete_lines(pending, chunk):
3941
4048
  yield _decode_json_line(line, decoder)
3942
- if pending.strip():
3943
- yield _decode_json_line(pending, decoder)
4049
+ final_line = _final_line(pending, raw_text=raw_text)
4050
+ if final_line is not None:
4051
+ yield _decode_json_line(final_line, decoder)
3944
4052
  except (PyreqwestRequestError, PyreqwestBuilderError) as error:
3945
4053
  raise _translate_transport_error(error) from error
3946
4054
 
@@ -5555,8 +5663,7 @@ class SyncHTTPClient:
5555
5663
  self,
5556
5664
  request_builder: SyncRequestBuilder,
5557
5665
  state: _SSEStreamState,
5558
- into: _Into,
5559
- decoder: _Decoder | None,
5666
+ decoder: _Decoder,
5560
5667
  *,
5561
5668
  error_for_status: bool,
5562
5669
  raises: type[HTTPResponseError[Any]] | None,
@@ -5589,7 +5696,7 @@ class SyncHTTPClient:
5589
5696
  records, tail = _split_sse_records(bytes(buffer))
5590
5697
  buffer = bytearray(tail)
5591
5698
  for record in records:
5592
- event = _dispatch_sse_record(record, state, into, decoder)
5699
+ event = _dispatch_sse_record(record, state, decoder)
5593
5700
  if event is not None:
5594
5701
  yield event
5595
5702
  except (PyreqwestRequestError, PyreqwestBuilderError) as error:
@@ -5613,7 +5720,7 @@ class SyncHTTPClient:
5613
5720
  ) -> Generator[SSEEvent[Any]]:
5614
5721
  _validate_raises(raises)
5615
5722
  # Resolved once per stream, not per event or per reconnect.
5616
- decoder = _decoder_for(into)
5723
+ decoder = _sse_data_decoder(into)
5617
5724
  state = _SSEStreamState(retry_delay=reconnect_delay)
5618
5725
  consecutive_reconnects = 0
5619
5726
  effective_timeout = timeout if timeout is not None else self._streaming_default_timeout
@@ -5627,7 +5734,6 @@ class SyncHTTPClient:
5627
5734
  connection = self._sse_connection(
5628
5735
  request_builder,
5629
5736
  state,
5630
- into,
5631
5737
  decoder,
5632
5738
  error_for_status=error_for_status,
5633
5739
  raises=raises,
@@ -5841,12 +5947,15 @@ class SyncHTTPClient:
5841
5947
  if decoder is None:
5842
5948
  yield from chunks
5843
5949
  return
5950
+ raw_text = isinstance(decoder, _TextDecoder)
5951
+ complete_lines = _complete_text_lines if raw_text else _complete_ndjson_lines
5844
5952
  pending = bytearray()
5845
5953
  for chunk in chunks:
5846
- for line in _complete_ndjson_lines(pending, chunk):
5954
+ for line in complete_lines(pending, chunk):
5847
5955
  yield _decode_json_line(line, decoder)
5848
- if pending.strip():
5849
- yield _decode_json_line(pending, decoder)
5956
+ final_line = _final_line(pending, raw_text=raw_text)
5957
+ if final_line is not None:
5958
+ yield _decode_json_line(final_line, decoder)
5850
5959
  except (PyreqwestRequestError, PyreqwestBuilderError) as error:
5851
5960
  raise _translate_transport_error(error) from error
5852
5961
 
@@ -17,6 +17,7 @@ classifiers = [
17
17
  "Intended Audience :: Developers",
18
18
  "Programming Language :: Python :: 3.13",
19
19
  "Programming Language :: Python :: 3.14",
20
+ "Programming Language :: Python :: 3.15",
20
21
  "Typing :: Typed",
21
22
  ]
22
23
 
@@ -48,35 +49,45 @@ lothc = "lothc.testing"
48
49
 
49
50
  [dependency-groups]
50
51
  dev = [
51
- "aiohttp>=3.14.3",
52
- "aiosonic>=1.0.5",
53
52
  "asv>=0.6.4",
54
53
  "basedpyright>=1.38.0",
55
54
  "coverage>=7.16.0",
56
55
  "deptry>=0.25.1",
57
- "httpx>=0.28.1",
58
- "httpx2>=2.12.0",
59
56
  "msgspec>=0.19.0",
60
57
  "mypy>=2.3.1",
61
- "niquests>=3.21.0",
62
58
  "prek>=0.4.14",
63
59
  "pydantic>=2.12.5",
64
60
  "pylint>=4.0.7",
65
61
  "pytest>=9.0.2",
66
62
  "pytest-asyncio>=1.3.0",
67
63
  "pytest-codspeed>=5.0.3",
68
- "requests>=2.34.2",
69
64
  "rich>=15.0.0",
70
65
  "ruff>=0.15.14",
71
66
  "trustme>=1.2.1",
72
67
  "ty>=0.0.74",
73
- "types-requests>=2.33.0.20260712",
74
68
  "vulture>=2.16",
75
69
  "yeetr[uvloop]>=2026.8.14.post1",
76
70
  "zuban>=0.9.1",
77
71
  ]
72
+ # The other HTTP clients perf.py races lothc against (plus requests' stubs, since `basedpyright .`
73
+ # type-checks perf.py). Nothing in lothc/ or tests/ imports them, so the test-only free-threaded
74
+ # CI jobs leave this group out: niquests pulls in qh3, which has no free-threaded 3.15 wheel.
75
+ perf = [
76
+ "aiohttp>=3.14.3",
77
+ "aiosonic>=1.0.5",
78
+ "httpx>=0.28.1",
79
+ "httpx2>=2.12.0",
80
+ "niquests>=3.21.0",
81
+ "requests>=2.34.2",
82
+ "types-requests>=2.33.0.20260712",
83
+ ]
78
84
  docs = ["zensical>=0.0.56"]
79
85
 
86
+ [tool.uv]
87
+ # perf too, so a plain `uv run` (which syncs the default groups) keeps perf.py runnable and
88
+ # type-checkable locally; jobs that must not install it pass --no-default-groups.
89
+ default-groups = ["dev", "perf"]
90
+
80
91
  [build-system]
81
92
  requires = ["hatchling", "hatch-vcs"]
82
93
  build-backend = "hatchling.build"
@@ -193,6 +204,7 @@ known-first-party = ["lothc"]
193
204
  "S105", # hardcoded-password false positives on deliberate literal test values, e.g.
194
205
  # test_oauth.py asserting a cache file holds `"access_token": "token-1"`
195
206
  "S106", # hardcoded-password false positives on deliberate literal test values
207
+ "S107", # the same, as a default: `_oauth_server.py`'s `client_secret="client-secret"`
196
208
  "S603", # subprocess call with a fixed, non-attacker-controlled argument list
197
209
  "S607", # partial executable path — deliberately PATH-resolved, matching Taskfile invocations
198
210
  ]
@@ -251,8 +263,8 @@ max-attributes = 15 # `OAuthProvider`/`SyncOAuthProvider` (lothc/_oauth.py) stor
251
263
  max-locals = 29 # one real case (the streaming line-buffering generator) legitimately needs a
252
264
  # couple more than pylint's default 15 — matches this project's own mccabe complexity ceiling
253
265
  # ([tool.ruff.lint.mccabe] max-complexity = 15) in spirit, just a different metric. Bumped again,
254
- # 20 -> 21, after `_sse_stream`/its sync mirror gained a 21st local (the new `error_type` param,
255
- # threaded through for typed error bodies), then 21 -> 27 after `build`/its sync mirror gained
266
+ # 20 -> 21, after `_sse_stream`/its sync mirror gained a 21st local (the then-new `error_type`
267
+ # param, since replaced by `raises`, threaded through for typed error bodies), then 21 -> 27 after `build`/its sync mirror gained
256
268
  # the TLS/connection-pool config params (`connect_timeout`, `root_certificates`, `identity_pem`,
257
269
  # `min_tls_version`, `max_tls_version`, `danger_accept_invalid_certs`, `https_only`,
258
270
  # `max_connections`, `pool_idle_timeout`, `pool_max_idle_per_host`, `pool_timeout`), then
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes