apcore-toolkit 0.14.0__tar.gz → 0.14.2__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.
Files changed (91) hide show
  1. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/CHANGELOG.md +27 -0
  2. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/PKG-INFO +28 -2
  3. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/README.md +26 -0
  4. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/pyproject.toml +2 -2
  5. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/__init__.py +7 -6
  6. apcore_toolkit-0.14.2/src/apcore_toolkit/_http.py +288 -0
  7. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/grant.py +41 -19
  8. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/transport.py +41 -16
  9. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/openapi_scanner.py +4 -3
  10. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/http_proxy_writer.py +39 -1
  11. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_device_auth.py +1 -1
  12. apcore_toolkit-0.14.2/tests/test_http_deadlines.py +863 -0
  13. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_openapi_scanner_malformed_input.py +6 -6
  14. apcore_toolkit-0.14.2/tests/test_version.py +17 -0
  15. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/.github/CODEOWNERS +0 -0
  16. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/.github/copilot-ignore +0 -0
  17. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/.github/workflows/ci.yml +0 -0
  18. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/.gitignore +0 -0
  19. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/.gitmessage +0 -0
  20. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/.pre-commit-config.yaml +0 -0
  21. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/LICENSE +0 -0
  22. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/_type_mapping.py +0 -0
  23. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/ai_enhancer.py +0 -0
  24. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/__init__.py +0 -0
  25. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/builder.py +0 -0
  26. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/client.py +0 -0
  27. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/config.py +0 -0
  28. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/errors.py +0 -0
  29. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/parsing.py +0 -0
  30. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/store.py +0 -0
  31. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/auth/tokens.py +0 -0
  32. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/binding_loader.py +0 -0
  33. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/conformance.py +0 -0
  34. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/convention_scanner.py +0 -0
  35. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/display/__init__.py +0 -0
  36. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/display/resolver.py +0 -0
  37. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/formatting/__init__.py +0 -0
  38. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/formatting/markdown.py +0 -0
  39. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/formatting/surface.py +0 -0
  40. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/formatting/tabular.py +0 -0
  41. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/http_verb_map.py +0 -0
  42. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/openapi.py +0 -0
  43. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/__init__.py +0 -0
  44. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/errors.py +0 -0
  45. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/python_writer.py +0 -0
  46. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/registry_writer.py +0 -0
  47. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/types.py +0 -0
  48. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/verifiers.py +0 -0
  49. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/output/yaml_writer.py +0 -0
  50. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/pydantic_utils.py +0 -0
  51. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/resolve_target.py +0 -0
  52. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/scanner.py +0 -0
  53. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/schema_utils.py +0 -0
  54. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/serializers.py +0 -0
  55. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/tui_view_model.py +0 -0
  56. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/src/apcore_toolkit/types.py +0 -0
  57. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/conftest.py +0 -0
  58. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/fixtures/scanner_verb_map.json +0 -0
  59. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_ai_enhancer.py +0 -0
  60. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_binding_loader.py +0 -0
  61. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_binding_pattern_conformance.py +0 -0
  62. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_binding_structure_conformance.py +0 -0
  63. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_conformance.py +0 -0
  64. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_convention_scanner.py +0 -0
  65. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_device_auth_conformance.py +0 -0
  66. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_display_resolve_conformance.py +0 -0
  67. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_display_resolver.py +0 -0
  68. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_format_surface.py +0 -0
  69. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_http_proxy_writer.py +0 -0
  70. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_http_verb_map.py +0 -0
  71. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_markdown.py +0 -0
  72. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_openapi.py +0 -0
  73. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_openapi_scan_conformance.py +0 -0
  74. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_openapi_scanner_module_id.py +0 -0
  75. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_output_factory.py +0 -0
  76. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_pydantic_utils.py +0 -0
  77. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_python_writer.py +0 -0
  78. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_ref_resolution_conformance.py +0 -0
  79. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_registry_writer.py +0 -0
  80. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_scanner.py +0 -0
  81. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_schema_utils.py +0 -0
  82. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_serializers.py +0 -0
  83. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_tabular.py +0 -0
  84. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_tabular_conformance.py +0 -0
  85. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_tui_view_model.py +0 -0
  86. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_types.py +0 -0
  87. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_verifiers.py +0 -0
  88. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_view_model_conformance.py +0 -0
  89. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_write_error.py +0 -0
  90. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_write_result.py +0 -0
  91. {apcore_toolkit-0.14.0 → apcore_toolkit-0.14.2}/tests/test_yaml_writer.py +0 -0
@@ -2,6 +2,33 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [0.14.2] - 2026-11-19
6
+
7
+ Toolkit update for apcore 0.33.0.
8
+
9
+ ## [0.14.1] - 2026-10-25
10
+
11
+ ### Fixed
12
+
13
+ - HTTP proxy execution now observes `Context.cancel_token`, interrupts in-flight
14
+ HTTP I/O, and joins request cleanup before reporting cancellation.
15
+ - Proxy requests, URL-based OpenAPI loading, and the default authentication
16
+ transport enforce configured HTTP timeouts across the complete response body,
17
+ including responses that continuously send small chunks.
18
+ - Device authorization polling clamps sleeps and outbound requests to the
19
+ remaining flow deadline, counts user-code callbacks against device-code
20
+ expiry, and rejects results that arrive after expiry.
21
+ `PreparedRequest.timeout_seconds` passes this budget to custom transports;
22
+ injected synchronous clients retain ownership and must bound their own I/O.
23
+ The optional `http_timeout=None` default is unchanged.
24
+ - Ctrl-C during synchronous HTTP calls from a running event loop now cancels
25
+ actual HTTP work and joins cleanup, including startup and repeated-interrupt
26
+ windows. Context variables and previously recovered task cancellation state
27
+ are preserved across the bridge.
28
+ - Slow OS DNS no longer delays configured HTTP deadlines during loop shutdown.
29
+ A process-wide resolver bounds running/queued lookups, discards late results,
30
+ and resets safely after fork; HTTP workers are still fully joined.
31
+
5
32
  ## [0.14.0] - 2026-10-09
6
33
 
7
34
  Toolkit update for apcore 0.32.0. Public loader signatures and error types
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: apcore-toolkit
3
- Version: 0.14.0
3
+ Version: 0.14.2
4
4
  Summary: Shared scanner, schema extraction, and output toolkit for apcore framework adapters
5
5
  Project-URL: Homepage, https://aiperceivable.com
6
6
  Project-URL: Repository, https://github.com/aiperceivable/apcore-toolkit-python
@@ -11,7 +11,7 @@ License-Expression: Apache-2.0
11
11
  License-File: LICENSE
12
12
  Keywords: apcore,mcp,openapi,pydantic,scanner,schema,toolkit,yaml
13
13
  Requires-Python: >=3.11
14
- Requires-Dist: apcore>=0.32.0
14
+ Requires-Dist: apcore>=0.33.0
15
15
  Requires-Dist: pydantic>=2.0
16
16
  Requires-Dist: pyyaml>=6.0
17
17
  Provides-Extra: auth
@@ -394,6 +394,32 @@ RFC are handled with configuration rather than a fork -- `error_aliases`,
394
394
  `request_encoding`, and four extension hooks (`transform_request`,
395
395
  `parse_response`, `classify_error`, `http_client`).
396
396
 
397
+ HTTP proxy requests observe `Context.cancel_token` and enforce `timeout` across
398
+ connection setup and the complete response body. URL-based `load_spec()` and the
399
+ default authentication transport also enforce a total HTTP timeout, including
400
+ slow responses that keep sending small chunks. Their public APIs remain
401
+ synchronous; internally, cancellable async HTTP runs to completion and cleans up
402
+ before returning, including when called from an existing event loop. Ctrl-C
403
+ cancels the actual HTTP task and waits for client/worker cleanup; instrumentation
404
+ context variables are preserved across the synchronous bridge.
405
+
406
+ OS DNS resolution cannot be safely interrupted. The synchronous APIs use a
407
+ process-wide resolver capped at two active lookups and two queued jobs. Queue
408
+ waiting and DNS count towards the HTTP deadline; cancelled queued lookups never
409
+ start, and completed late DNS results cannot resume the cancelled HTTP request.
410
+ HTTP worker threads are joined before returning. The bounded DNS workers belong
411
+ to the process lifetime and do not delay request timeout or process exit while
412
+ an OS lookup is stuck. Forked processes initialize their own resolver.
413
+
414
+ Authentication's optional `http_timeout` remains a per-request setting (`None`
415
+ disables that limit). Token polling additionally caps each request and sleep by
416
+ the flow's remaining deadline. Custom `Transport` implementations receive this
417
+ budget as `PreparedRequest.timeout_seconds` and must enforce it themselves.
418
+ An injected synchronous `http_client` keeps its timeout policy and ownership;
419
+ its stage timeouts are capped by the flow budget, and late responses are rejected.
420
+ Arbitrary injected synchronous I/O cannot be forcibly interrupted by the toolkit,
421
+ so custom transports/clients must bound their own blocking operations.
422
+
397
423
  Credentials live at `$XDG_CONFIG_HOME/apcore/credentials.json`
398
424
  (`~/.config/apcore/credentials.json` on macOS, `%APPDATA%\apcore\credentials.json`
399
425
  on Windows), created `0600` and written by atomic replace. `FileTokenStore`
@@ -363,6 +363,32 @@ RFC are handled with configuration rather than a fork -- `error_aliases`,
363
363
  `request_encoding`, and four extension hooks (`transform_request`,
364
364
  `parse_response`, `classify_error`, `http_client`).
365
365
 
366
+ HTTP proxy requests observe `Context.cancel_token` and enforce `timeout` across
367
+ connection setup and the complete response body. URL-based `load_spec()` and the
368
+ default authentication transport also enforce a total HTTP timeout, including
369
+ slow responses that keep sending small chunks. Their public APIs remain
370
+ synchronous; internally, cancellable async HTTP runs to completion and cleans up
371
+ before returning, including when called from an existing event loop. Ctrl-C
372
+ cancels the actual HTTP task and waits for client/worker cleanup; instrumentation
373
+ context variables are preserved across the synchronous bridge.
374
+
375
+ OS DNS resolution cannot be safely interrupted. The synchronous APIs use a
376
+ process-wide resolver capped at two active lookups and two queued jobs. Queue
377
+ waiting and DNS count towards the HTTP deadline; cancelled queued lookups never
378
+ start, and completed late DNS results cannot resume the cancelled HTTP request.
379
+ HTTP worker threads are joined before returning. The bounded DNS workers belong
380
+ to the process lifetime and do not delay request timeout or process exit while
381
+ an OS lookup is stuck. Forked processes initialize their own resolver.
382
+
383
+ Authentication's optional `http_timeout` remains a per-request setting (`None`
384
+ disables that limit). Token polling additionally caps each request and sleep by
385
+ the flow's remaining deadline. Custom `Transport` implementations receive this
386
+ budget as `PreparedRequest.timeout_seconds` and must enforce it themselves.
387
+ An injected synchronous `http_client` keeps its timeout policy and ownership;
388
+ its stage timeouts are capped by the flow budget, and late responses are rejected.
389
+ Arbitrary injected synchronous I/O cannot be forcibly interrupted by the toolkit,
390
+ so custom transports/clients must bound their own blocking operations.
391
+
366
392
  Credentials live at `$XDG_CONFIG_HOME/apcore/credentials.json`
367
393
  (`~/.config/apcore/credentials.json` on macOS, `%APPDATA%\apcore\credentials.json`
368
394
  on Windows), created `0600` and written by atomic replace. `FileTokenStore`
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "apcore-toolkit"
7
- version = "0.14.0"
7
+ version = "0.14.2"
8
8
  description = "Shared scanner, schema extraction, and output toolkit for apcore framework adapters"
9
9
  requires-python = ">=3.11"
10
10
  readme = "README.md"
@@ -23,7 +23,7 @@ keywords = [
23
23
  "toolkit",
24
24
  ]
25
25
  dependencies = [
26
- "apcore>=0.32.0",
26
+ "apcore>=0.33.0",
27
27
  "pydantic>=2.0",
28
28
  "PyYAML>=6.0",
29
29
  ]
@@ -3,6 +3,9 @@
3
3
  Public API re-exports for convenient access to core types and utilities.
4
4
  """
5
5
 
6
+ from importlib.metadata import PackageNotFoundError
7
+ from importlib.metadata import version as _get_version
8
+
6
9
  from apcore_toolkit.ai_enhancer import AIEnhancer, Enhancer
7
10
  from apcore_toolkit.auth import (
8
11
  AuthError,
@@ -89,12 +92,10 @@ from apcore_toolkit.schema_utils import enrich_schema_descriptions
89
92
  from apcore_toolkit.serializers import annotations_to_dict, module_to_dict, modules_to_dicts
90
93
  from apcore_toolkit.types import ScannedModule, clone_module, create_scanned_module
91
94
 
92
- # Kept in sync with the `version` field in pyproject.toml. A previous
93
- # implementation derived this from `importlib.metadata.version(...)`, but that
94
- # reflects whatever distribution happens to be installed in the current
95
- # environment (which can be stale or absent, e.g. in editable/dev checkouts
96
- # or fresh CI environments), not the version of this source tree.
97
- __version__ = "0.14.0"
95
+ try:
96
+ __version__ = _get_version("apcore-toolkit")
97
+ except PackageNotFoundError:
98
+ __version__ = "unknown"
98
99
 
99
100
  __all__ = [
100
101
  "AIEnhancer",
@@ -0,0 +1,288 @@
1
+ """Cancellable HTTP behind the synchronous loader/authentication APIs.
2
+
3
+ HTTP tasks and bridge threads are always closed and joined. OS DNS cannot be
4
+ preempted safely, so request loops share a process-lifetime resolver with two
5
+ workers and two queued jobs; cancelled requests discard DNS results and never
6
+ continue sending HTTP. Loop shutdown never waits for an OS resolver.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import atexit
12
+ import asyncio
13
+ import contextvars
14
+ import os
15
+ import queue
16
+ import signal
17
+ import socket
18
+ import threading
19
+ import time
20
+ from concurrent.futures import Future
21
+ from types import FrameType
22
+ from typing import Any
23
+
24
+
25
+ def _start_thread(worker: threading.Thread) -> None:
26
+ """Keep SIGINT from leaving a spawned thread without a published identity."""
27
+ if threading.current_thread() is not threading.main_thread():
28
+ worker.start()
29
+ return
30
+ previous = signal.getsignal(signal.SIGINT)
31
+ if not callable(previous):
32
+ worker.start()
33
+ return
34
+ pending: list[tuple[int, FrameType | None]] = []
35
+
36
+ def interrupted(signum: int, frame: FrameType | None) -> None:
37
+ if worker.ident is None:
38
+ pending.append((signum, frame))
39
+ else:
40
+ previous(signum, frame)
41
+
42
+ signal.signal(signal.SIGINT, interrupted)
43
+ try:
44
+ worker.start()
45
+ finally:
46
+ signal.signal(signal.SIGINT, previous)
47
+ for signum, frame in pending:
48
+ previous(signum, frame)
49
+
50
+
51
+ def _join_thread(worker: threading.Thread, finished: threading.Event) -> None:
52
+ # Event completion means HTTP/loop cleanup has finished. Only then join:
53
+ # interrupted Thread.join() can corrupt CPython's liveness bookkeeping.
54
+ while not finished.is_set():
55
+ try:
56
+ finished.wait(0.01)
57
+ except KeyboardInterrupt:
58
+ pass
59
+ while worker.is_alive():
60
+ try:
61
+ worker.join()
62
+ except KeyboardInterrupt:
63
+ pass
64
+
65
+
66
+ class _Resolver:
67
+ """Bound blocking OS DNS independently of request/loop lifetimes."""
68
+
69
+ def __init__(self) -> None:
70
+ self._closed = threading.Event()
71
+ self._jobs: queue.Queue[tuple[Future[Any], tuple[Any, ...]]] = queue.Queue(maxsize=2)
72
+ self._workers: list[tuple[threading.Thread, threading.Event]] = []
73
+ try:
74
+ for number in range(2):
75
+ finished = threading.Event()
76
+ worker = threading.Thread(target=self._work, args=(finished,), name=f"apcore-dns-{number}", daemon=True)
77
+ self._workers.append((worker, finished))
78
+ _start_thread(worker)
79
+ except BaseException:
80
+ # The instance has not been published globally yet. Failed startup
81
+ # must retire every idle worker before a later attempt creates more.
82
+ while True:
83
+ try:
84
+ self.close()
85
+ for worker, finished in self._workers:
86
+ if worker.ident is not None:
87
+ _join_thread(worker, finished)
88
+ break
89
+ except KeyboardInterrupt:
90
+ pass
91
+ raise
92
+
93
+ def close(self) -> None:
94
+ self._closed.set()
95
+ while True:
96
+ try:
97
+ future, _ = self._jobs.get_nowait()
98
+ except queue.Empty:
99
+ break
100
+ future.cancel()
101
+ self._jobs.task_done()
102
+
103
+ def _work(self, finished: threading.Event) -> None:
104
+ try:
105
+ while not self._closed.is_set():
106
+ try:
107
+ future, arguments = self._jobs.get(timeout=0.1)
108
+ except queue.Empty:
109
+ continue
110
+ try:
111
+ if future.set_running_or_notify_cancel():
112
+ try:
113
+ result = socket.getaddrinfo(*arguments)
114
+ except BaseException as exc:
115
+ future.set_exception(exc)
116
+ else:
117
+ future.set_result(result)
118
+ finally:
119
+ self._jobs.task_done()
120
+ finally:
121
+ finished.set()
122
+
123
+ async def getaddrinfo(
124
+ self,
125
+ host: Any,
126
+ port: Any,
127
+ *,
128
+ family: int = 0,
129
+ type: int = 0,
130
+ proto: int = 0,
131
+ flags: int = 0,
132
+ ) -> Any:
133
+ future: Future[Any] = Future()
134
+ try:
135
+ while True:
136
+ if self._closed.is_set():
137
+ raise RuntimeError("HTTP resolver is closed")
138
+ try:
139
+ self._jobs.put_nowait((future, (host, port, family, type, proto, flags)))
140
+ break
141
+ except queue.Full:
142
+ # Waiting for resolver capacity is cancellable and consumes
143
+ # the same HTTP deadline as connection setup and body I/O.
144
+ await asyncio.sleep(0.01)
145
+ return await asyncio.wrap_future(future)
146
+ finally:
147
+ # Queued jobs never start after cancellation. Running OS calls are
148
+ # bounded by the fixed worker count; their results are discarded.
149
+ future.cancel()
150
+
151
+
152
+ _resolver: _Resolver | None = None
153
+ _resolver_lock = threading.Lock()
154
+
155
+
156
+ def _shutdown_resolver() -> None:
157
+ # Resolve the process's current pool at exit rather than capturing one:
158
+ # a forked child must never close a parent's inherited, possibly locked pool.
159
+ if _resolver is not None:
160
+ _resolver.close()
161
+
162
+
163
+ atexit.register(_shutdown_resolver)
164
+
165
+
166
+ def _after_fork() -> None:
167
+ # Daemon threads do not survive fork; a child needs its own process pool.
168
+ global _resolver, _resolver_lock
169
+ _resolver = None
170
+ _resolver_lock = threading.Lock()
171
+
172
+
173
+ if hasattr(os, "register_at_fork"):
174
+ os.register_at_fork(after_in_child=_after_fork)
175
+
176
+
177
+ def _new_loop() -> asyncio.AbstractEventLoop:
178
+ loop = asyncio.new_event_loop()
179
+
180
+ async def getaddrinfo(
181
+ host: Any, port: Any, *, family: int = 0, type: int = 0, proto: int = 0, flags: int = 0
182
+ ) -> Any:
183
+ global _resolver
184
+ with _resolver_lock:
185
+ if _resolver is None:
186
+ _resolver = _Resolver()
187
+ resolver = _resolver
188
+ return await resolver.getaddrinfo(host, port, family=family, type=type, proto=proto, flags=flags)
189
+
190
+ # This is the public resolver hook on a loop owned exclusively by this
191
+ # request. No caller loop or global asyncio policy is modified.
192
+ loop.getaddrinfo = getaddrinfo # type: ignore[method-assign]
193
+ return loop
194
+
195
+
196
+ def request(method: str, url: str, *, timeout: float | None, **kwargs: Any) -> Any:
197
+ """Perform a buffered request without abandoning HTTP work on interruption."""
198
+ import httpx
199
+
200
+ expires = None if timeout is None else time.monotonic() + timeout
201
+
202
+ async def send() -> Any:
203
+ try:
204
+ remaining = None if expires is None else expires - time.monotonic()
205
+ if remaining is not None and remaining <= 0:
206
+ raise TimeoutError
207
+ async with asyncio.timeout(remaining):
208
+ async with httpx.AsyncClient(timeout=remaining) as client:
209
+ response = await client.request(method, url, **kwargs)
210
+ if expires is not None and time.monotonic() >= expires:
211
+ raise TimeoutError
212
+ return response
213
+ except TimeoutError as exc:
214
+ raise httpx.TimeoutException(
215
+ "HTTP request timed out" + (f" after {timeout:g}s" if timeout is not None else "")
216
+ ) from exc
217
+
218
+ try:
219
+ asyncio.get_running_loop()
220
+ except RuntimeError:
221
+ running_loop = False
222
+ else:
223
+ running_loop = True
224
+ if not running_loop:
225
+ with asyncio.Runner(loop_factory=_new_loop) as runner:
226
+ return runner.run(send())
227
+
228
+ caller = asyncio.current_task()
229
+ initial_cancels = caller.cancelling() if caller is not None else 0
230
+ cancelled = threading.Event()
231
+ finished = threading.Event()
232
+ outcome: Future[Any] = Future()
233
+
234
+ async def tracked_send() -> Any:
235
+ # The main thread only sets an Event. Cancellation is delivered once
236
+ # here, avoiding an interruptible cross-thread scheduling/latch window.
237
+ if cancelled.is_set():
238
+ raise asyncio.CancelledError
239
+ task = asyncio.create_task(send())
240
+ try:
241
+ while not task.done():
242
+ if cancelled.is_set():
243
+ task.cancel()
244
+ return await task
245
+ await asyncio.wait({task}, timeout=0.01)
246
+ return await task
247
+ finally:
248
+ if not task.done():
249
+ task.cancel()
250
+ await asyncio.gather(task, return_exceptions=True)
251
+
252
+ def run() -> None:
253
+ try:
254
+ with asyncio.Runner(loop_factory=_new_loop) as runner:
255
+ result = runner.run(tracked_send())
256
+ except BaseException as exc:
257
+ outcome.set_exception(exc)
258
+ else:
259
+ outcome.set_result(result)
260
+ finally:
261
+ finished.set()
262
+
263
+ context = contextvars.copy_context()
264
+ worker = threading.Thread(target=lambda: context.run(run), name="apcore-http")
265
+ try:
266
+ _start_thread(worker)
267
+ while not finished.wait(0.01):
268
+ # Runner's first SIGINT cancels its main task instead of raising
269
+ # KeyboardInterrupt in this synchronous function. Do not reapply a
270
+ # cancellation count left over from an already recovered exception.
271
+ if caller is not None and caller.cancelling() > initial_cancels:
272
+ raise asyncio.CancelledError
273
+ worker.join()
274
+ if caller is not None and caller.cancelling() > initial_cancels:
275
+ raise asyncio.CancelledError
276
+ return outcome.result()
277
+ except BaseException:
278
+ while True:
279
+ try:
280
+ # Event.set() itself can be interrupted; retry it together with
281
+ # the wait instead of latching before cancellation is delivered.
282
+ cancelled.set()
283
+ if worker.ident is not None:
284
+ _join_thread(worker, finished)
285
+ break
286
+ except KeyboardInterrupt:
287
+ pass
288
+ raise
@@ -17,7 +17,7 @@ import logging
17
17
  import time
18
18
  from abc import ABC, abstractmethod
19
19
  from collections.abc import Callable, Mapping
20
- from dataclasses import dataclass, field
20
+ from dataclasses import dataclass, field, replace
21
21
  from typing import Any
22
22
 
23
23
  from apcore_toolkit.auth.builder import build_device_request, build_token_request, decode_response
@@ -206,6 +206,7 @@ class DeviceCodeGrant(Grant):
206
206
  # stops on it, so a consumer's countdown cannot disagree with when the
207
207
  # client actually gives up — and a later edit cannot let the two drift.
208
208
  deadline = effective_deadline(device.expires_in, timeout_seconds)
209
+ started = self.clock()
209
210
  self._notify(
210
211
  on_user_code,
211
212
  "on_user_code",
@@ -214,7 +215,8 @@ class DeviceCodeGrant(Grant):
214
215
  verification_uri_complete=device.verification_uri_complete,
215
216
  expires_in=deadline,
216
217
  )
217
- return self.poll_for_token(device, on_poll=on_poll, deadline=deadline)
218
+ # The device code is already expiring while the UI callback runs.
219
+ return self._poll_for_token(device, on_poll=on_poll, deadline=deadline, started=started)
218
220
 
219
221
  def request_device_code(self) -> DeviceCodeResponse:
220
222
  """Step 1: ``POST`` to the device authorization endpoint."""
@@ -276,52 +278,72 @@ class DeviceCodeGrant(Grant):
276
278
  that clamp is computed. Omitting it polls for the device response's own
277
279
  ``expires_in``.
278
280
  """
279
- interval = device.interval if device.interval is not None else self.config.default_interval
280
- if deadline is None:
281
- deadline = float(device.expires_in)
281
+ return self._poll_for_token(
282
+ device,
283
+ on_poll=on_poll,
284
+ deadline=float(device.expires_in) if deadline is None else deadline,
285
+ started=self.clock(),
286
+ )
282
287
 
288
+ # -- internals ---------------------------------------------------------
289
+
290
+ def _poll_for_token(
291
+ self,
292
+ device: DeviceCodeResponse,
293
+ *,
294
+ on_poll: Callable[..., Any] | None,
295
+ deadline: float,
296
+ started: float,
297
+ ) -> TokenSet:
298
+ """Run against one origin, shared by expiry and callback elapsed time."""
299
+ interval = device.interval if device.interval is not None else self.config.default_interval
283
300
  self.final_interval = interval
284
301
  self.polls_made = 0
285
- started = self.clock()
286
302
  attempt = 0
287
303
 
304
+ def remaining() -> float:
305
+ budget = deadline - (self.clock() - started)
306
+ if budget <= 0:
307
+ raise AuthorizationExpiredError(
308
+ f"device authorization deadline of {deadline:g}s elapsed without a decision",
309
+ reason=DEADLINE_EXCEEDED,
310
+ )
311
+ return budget
312
+
288
313
  while True:
289
314
  # RFC 8628 §3.5: the client must not poll faster than the
290
315
  # interval, and the user has not had time to act yet — so the wait
291
316
  # comes BEFORE the first poll, never after it.
292
- self.sleep(interval)
317
+ self.sleep(min(interval, remaining()))
318
+ remaining()
293
319
  elapsed = self.clock() - started
294
320
 
295
- # Stop at expires_in even when the server never says
296
- # expired_token. Relying on the server's error alone leaves a
297
- # client polling indefinitely against a server that never sends it.
298
- if elapsed >= deadline:
299
- raise AuthorizationExpiredError(
300
- f"device authorization deadline of {deadline:g}s elapsed without a decision",
301
- reason=DEADLINE_EXCEEDED,
302
- )
303
-
304
321
  attempt += 1
305
322
  self._notify(on_poll, "on_poll", attempt=attempt, interval=interval, elapsed=elapsed)
306
323
 
324
+ request = build_token_request(self.config, device.device_code)
325
+ # Hooks may consume time too. Derive the request budget immediately
326
+ # before dispatch, keeping Transport.send(request) compatible.
327
+ request = replace(request, timeout_seconds=remaining())
307
328
  try:
308
- response = self.transport.send(build_token_request(self.config, device.device_code))
329
+ response = self.transport.send(request)
309
330
  except TransportError as exc:
310
331
  # Retryable, not terminal: a dropped connection mid-flow is
311
332
  # common on flaky networks, and the deadline already bounds the
312
333
  # total wait, so retrying cannot loop forever.
313
334
  self.polls_made += 1
335
+ remaining()
314
336
  logger.debug("token poll %d failed at the transport layer, retrying: %s", attempt, exc)
315
337
  continue
316
338
 
317
339
  self.polls_made += 1
340
+ remaining()
318
341
  tokens, interval = self._dispatch(response, interval)
319
342
  self.final_interval = interval
320
343
  if tokens is not None:
344
+ remaining()
321
345
  return tokens
322
346
 
323
- # -- internals ---------------------------------------------------------
324
-
325
347
  def _dispatch(self, response: HttpResponse, interval: int) -> tuple[TokenSet | None, int]:
326
348
  """Dispatch on the response **body**, never on the HTTP status code.
327
349
 
@@ -12,6 +12,7 @@ response sequence, and the state machine above it is unchanged.
12
12
  from __future__ import annotations
13
13
 
14
14
  import json
15
+ import time
15
16
  from collections.abc import Mapping
16
17
  from dataclasses import dataclass, field
17
18
  from typing import Any, Protocol
@@ -52,6 +53,9 @@ class PreparedRequest:
52
53
  headers: Mapping[str, str] = field(default_factory=dict)
53
54
  encoding: str = "form"
54
55
  body: str = ""
56
+ # Optional remaining flow budget. Custom synchronous transports must enforce
57
+ # this themselves; the grant also rejects responses arriving after expiry.
58
+ timeout_seconds: float | None = None
55
59
 
56
60
 
57
61
  @dataclass(frozen=True)
@@ -83,9 +87,10 @@ class HttpxTransport:
83
87
  :class:`~apcore_toolkit.output.http_proxy_writer.HTTPProxyRegistryWriter`
84
88
  already does it: importing the package must not require it.
85
89
 
86
- Python's client is synchronous throughout, per the recorded decision on
87
- Open Question 1 — the shipped ``auth_header_factory`` seam is synchronous
88
- and the ``httpx`` path here already is too.
90
+ The public API stays synchronous to match ``auth_header_factory``. The
91
+ default network path uses cancellable async HTTP internally so its total
92
+ deadline includes the complete response body. Injected synchronous clients
93
+ retain their configuration and ownership.
89
94
  """
90
95
 
91
96
  def __init__(self, client: Any = None, *, timeout: float | None = None) -> None:
@@ -95,22 +100,42 @@ class HttpxTransport:
95
100
  def send(self, request: PreparedRequest) -> HttpResponse:
96
101
  import httpx as _httpx
97
102
 
98
- client = self._client
99
- owns_client = client is None
100
- if owns_client:
101
- client = _httpx.Client(timeout=self._timeout)
103
+ budget = request.timeout_seconds
104
+ if self._client is None and self._timeout is not None:
105
+ budget = self._timeout if budget is None else min(self._timeout, budget)
106
+ began = time.monotonic()
102
107
  try:
103
- response = client.request(
104
- request.method,
105
- request.url,
106
- content=request.body.encode("utf-8") if request.body else None,
107
- headers=dict(request.headers),
108
- )
108
+ kwargs: dict[str, Any] = {
109
+ "content": request.body.encode("utf-8") if request.body else None,
110
+ "headers": dict(request.headers),
111
+ }
112
+ if self._client is None:
113
+ from apcore_toolkit._http import request as send
114
+
115
+ response = send(request.method, request.url, timeout=budget, **kwargs)
116
+ else:
117
+ # An injected synchronous client owns its transport and timeout
118
+ # policy. Cap its stage timeouts by the flow budget without
119
+ # changing the client or closing it. Arbitrary synchronous I/O
120
+ # cannot be safely forcibly cancelled; its owner must enforce
121
+ # the supplied budget. Never accept a late result.
122
+ if budget is not None:
123
+ configured = getattr(self._client, "timeout", None)
124
+ kwargs["timeout"] = (
125
+ _httpx.Timeout(
126
+ **{
127
+ stage: budget if value is None else min(value, budget)
128
+ for stage, value in configured.as_dict().items()
129
+ }
130
+ )
131
+ if isinstance(configured, _httpx.Timeout)
132
+ else budget
133
+ )
134
+ response = self._client.request(request.method, request.url, **kwargs)
135
+ if budget is not None and time.monotonic() - began >= budget:
136
+ raise _httpx.TimeoutException(f"HTTP request timed out after {budget:g}s")
109
137
  except _httpx.HTTPError as exc:
110
138
  raise TransportError(f"{request.kind} request to {request.url} failed: {exc}") from exc
111
- finally:
112
- if owns_client:
113
- client.close()
114
139
  return HttpResponse(
115
140
  status=response.status_code,
116
141
  body=response.text,