encore-dev 2.0.0b10__tar.gz → 2.0.0b13__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 (93) hide show
  1. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/PKG-INFO +5 -4
  2. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/README.md +4 -3
  3. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/__init__.py +2 -0
  4. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/_run.py +77 -20
  5. encore_dev-2.0.0b13/encore/_schema.py +5 -0
  6. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/env/__init__.py +2 -3
  7. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/gateway/__init__.py +1 -1
  8. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/gateway/_serve.py +31 -6
  9. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/_loader.py +6 -8
  10. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/_native.pyi +18 -2
  11. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/clients.py +56 -2
  12. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/grpc.py +3 -1
  13. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/reqfields.py +9 -2
  14. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/runtime.py +52 -9
  15. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/pubsub/__init__.py +48 -6
  16. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/reqctx/__init__.py +6 -2
  17. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/secrets/__init__.py +9 -4
  18. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/server/_serve.py +13 -1
  19. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/services/httpx.py +55 -6
  20. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/testing/__init__.py +3 -2
  21. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/pyproject.toml +2 -1
  22. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/pyproject.toml.orig +5 -1
  23. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/config/__init__.py +0 -0
  24. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/config/_build.py +0 -0
  25. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/config/_markers.py +0 -0
  26. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/cron/__init__.py +0 -0
  27. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/django/__init__.py +0 -0
  28. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/django/base.py +0 -0
  29. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/errs/__init__.py +0 -0
  30. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/frontends/__init__.py +0 -0
  31. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/gateway/match.py +0 -0
  32. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/gateways/__init__.py +0 -0
  33. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/__init__.py +0 -0
  34. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/lazy.py +0 -0
  35. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/startup.py +0 -0
  36. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/internal/testscope.py +0 -0
  37. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/logs/__init__.py +0 -0
  38. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/logs/_api.py +0 -0
  39. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/logs/_console.py +0 -0
  40. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/logs/_runtime.py +0 -0
  41. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/metrics/__init__.py +0 -0
  42. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/metrics/_instrument.py +0 -0
  43. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/metrics/_metrics.py +0 -0
  44. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/metrics/_provider.py +0 -0
  45. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/py.typed +0 -0
  46. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/reqctx/_json.py +0 -0
  47. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/server/__init__.py +0 -0
  48. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/server/_span.py +0 -0
  49. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/server/_tracing.py +0 -0
  50. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/server/asgi.py +0 -0
  51. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/server/wsgi.py +0 -0
  52. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/services/__init__.py +0 -0
  53. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/services/_propagate.py +0 -0
  54. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/services/aiohttp.py +0 -0
  55. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/services/niquests.py +0 -0
  56. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/services/requests.py +0 -0
  57. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/shutdown/__init__.py +0 -0
  58. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/__init__.py +0 -0
  59. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/clickhouse/__init__.py +0 -0
  60. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/objects/__init__.py +0 -0
  61. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/postgres/__init__.py +0 -0
  62. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/__init__.py +0 -0
  63. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/_base.py +0 -0
  64. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/_batch.py +0 -0
  65. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/_errors.py +0 -0
  66. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/_responses.py +0 -0
  67. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/_scan.py +0 -0
  68. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/_values.py +0 -0
  69. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/bitmap.py +0 -0
  70. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/command.py +0 -0
  71. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/generic.py +0 -0
  72. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/geo.py +0 -0
  73. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/hash.py +0 -0
  74. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/hyperloglog.py +0 -0
  75. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/json.py +0 -0
  76. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/list.py +0 -0
  77. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/pubsub.py +0 -0
  78. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/script.py +0 -0
  79. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/set.py +0 -0
  80. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/sorted_set.py +0 -0
  81. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/stream.py +0 -0
  82. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/storage/redis/string.py +0 -0
  83. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/testing/_playwright_fixtures.py +0 -0
  84. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/testing/_steps.py +0 -0
  85. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/testing/playwright.py +0 -0
  86. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/testing/pytest_plugin.py +0 -0
  87. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/testing/system.py +0 -0
  88. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/tracing/__init__.py +0 -0
  89. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/tracing/_context.py +0 -0
  90. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/tracing/_encode.py +0 -0
  91. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/tracing/_provider.py +0 -0
  92. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/tracing/_span.py +0 -0
  93. {encore_dev-2.0.0b10 → encore_dev-2.0.0b13}/encore/tracing/_tracer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: encore-dev
3
- Version: 2.0.0b10
3
+ Version: 2.0.0b13
4
4
  Summary: Encore SDK for Python — infrastructure resources
5
5
  Author: Encore
6
6
  License: MPL-2.0
@@ -69,9 +69,10 @@ async def place_order(order):
69
69
  `secrets.Secret[str]("Name")` belongs to the service that declares it.
70
70
  `secrets.Secret[str]("Name", scope="shared")` is one secret for the whole app,
71
71
  given to the services that read it, and `scope="global"` one that every service
72
- is given. `value` reads the secret as a string, and raises `KeyError` when it
73
- has no value. A secret's value is resolved once per process: a new value
74
- reaches a service when it restarts.
72
+ is given. `value` reads the secret as a string, and as `""` when it has no
73
+ value: only local development can lack one, since a deploy gives each service
74
+ every secret it uses. A secret's value is resolved once per process: a new
75
+ value reaches a service when it restarts.
75
76
 
76
77
  A shared secret is declared once in the app. Another Python service can't
77
78
  import the declaring service's modules, so it references the secret by name
@@ -45,9 +45,10 @@ async def place_order(order):
45
45
  `secrets.Secret[str]("Name")` belongs to the service that declares it.
46
46
  `secrets.Secret[str]("Name", scope="shared")` is one secret for the whole app,
47
47
  given to the services that read it, and `scope="global"` one that every service
48
- is given. `value` reads the secret as a string, and raises `KeyError` when it
49
- has no value. A secret's value is resolved once per process: a new value
50
- reaches a service when it restarts.
48
+ is given. `value` reads the secret as a string, and as `""` when it has no
49
+ value: only local development can lack one, since a deploy gives each service
50
+ every secret it uses. A secret's value is resolved once per process: a new
51
+ value reaches a service when it restarts.
51
52
 
52
53
  A shared secret is declared once in the app. Another Python service can't
53
54
  import the declaring service's modules, so it references the secret by name
@@ -36,6 +36,7 @@ import importlib
36
36
  import sys
37
37
  from typing import TYPE_CHECKING, Any
38
38
 
39
+ from ._schema import Sensitive
39
40
  from .internal import reqfields as _reqfields
40
41
 
41
42
  # A server takes the Request Context fields a request carries, whether or not
@@ -92,6 +93,7 @@ __all__ = [
92
93
  "testing",
93
94
  "tracing",
94
95
  "EncoreError",
96
+ "Sensitive",
95
97
  "app_meta",
96
98
  "run",
97
99
  "start",
@@ -2,8 +2,9 @@
2
2
 
3
3
  It starts the app, if there is one, on Encore's HTTP server, listening where
4
4
  Encore assigns the service, and Encore's Pub/Sub subscriptions; and on SIGTERM
5
- or SIGINT it shuts down with Encore: the requests in flight finish, the app
6
- stops, and Encore cleans up, within Encore's shutdown deadline.
5
+ or SIGINT (on Windows, Ctrl-C or Ctrl-Break) it shuts down with Encore: the
6
+ requests in flight finish, the app stops, and Encore cleans up, within
7
+ Encore's shutdown deadline.
7
8
  """
8
9
 
9
10
  from __future__ import annotations
@@ -12,9 +13,10 @@ import asyncio
12
13
  import logging
13
14
  import os
14
15
  import signal
16
+ import socket
15
17
  import sys
16
18
  import threading
17
- from typing import Any, Awaitable, Callable, List, Optional, Tuple
19
+ from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
18
20
 
19
21
  _log = logging.getLogger("encore")
20
22
 
@@ -46,7 +48,7 @@ def run(
46
48
  messages, lets the requests in flight finish, runs the app's lifespan
47
49
  shutdown, and lets Encore clean up the resources the app used, all within
48
50
  Encore's shutdown deadline. A second SIGINT, a second Ctrl-C, stops
49
- waiting for the app.
51
+ waiting for the app. On Windows, Ctrl-Break is an interrupt as Ctrl-C is.
50
52
 
51
53
  FastAPI can record its own spans when configured with a tracer provider:
52
54
  its server span, and spans of dependencies, endpoints and serialization.
@@ -138,15 +140,16 @@ async def _lifecycle(http: Any) -> int:
138
140
  from .internal.startup import start as start_encore
139
141
 
140
142
  await start_encore()
141
- if http is not None:
142
- http.listen()
143
- bound_host, bound_port = http.address
144
- _log.info("encore: serving on http://%s:%s", bound_host, bound_port)
145
-
143
+ # Before the service says it serves: a stop signal sent once it has must
144
+ # shut it down, not interrupt it.
146
145
  stop = asyncio.Event()
147
146
  force = asyncio.Event()
148
147
  restore = _on_signals(asyncio.get_running_loop(), stop, force)
149
148
  try:
149
+ if http is not None:
150
+ http.listen()
151
+ bound_host, bound_port = http.address
152
+ _log.info("encore: serving on http://%s:%s", bound_host, bound_port)
150
153
  await stop.wait()
151
154
  return await _shutdown(http, force)
152
155
  finally:
@@ -223,8 +226,15 @@ def _on_signals(
223
226
  forwarded by a wrapper in it, as `uv run`. So SIGTERM again changes
224
227
  nothing, and SIGINT again forces only as a second interrupt, a second
225
228
  Ctrl-C, some time after the first.
229
+
230
+ On Windows, where no process can send another SIGTERM, Ctrl-Break
231
+ (SIGBREAK) is an interrupt as Ctrl-C is: it is the one console event
232
+ that can be sent to a process group of its own, and the one Encore sends
233
+ to interrupt a process. Encore's stop request, which it asks of a
234
+ process waiting for it in place of Ctrl-Break, arrives as SIGBREAK too.
226
235
  """
227
236
  first: List[float] = []
237
+ interrupts = _interrupts()
228
238
 
229
239
  def handle(signum: int) -> None:
230
240
  now = loop.time()
@@ -232,26 +242,73 @@ def _on_signals(
232
242
  first.append(now)
233
243
  stop.set()
234
244
  return
235
- if signum == signal.SIGINT and now - first[0] > _REPEAT_SECS:
245
+ if signum in interrupts and now - first[0] > _REPEAT_SECS:
236
246
  force.set()
237
247
 
238
- signals = [signal.SIGTERM, signal.SIGINT]
248
+ signals = [signal.SIGTERM, *interrupts]
239
249
  previous = {s: signal.getsignal(s) for s in signals}
240
250
  if threading.current_thread() is not threading.main_thread():
241
251
  return lambda: None
242
252
  if sys.platform == "win32":
243
- for s in signals:
244
- signal.signal(
245
- s, lambda signum, _: loop.call_soon_threadsafe(handle, signum)
246
- )
247
- else:
248
- for s in signals:
249
- loop.add_signal_handler(s, handle, s)
253
+ from .internal.runtime import listen_stop_request
254
+
255
+ restore = _on_signals_windows(loop, signals, previous, handle)
256
+ # Now that SIGBREAK stops the service.
257
+ listen_stop_request()
258
+ return restore
259
+ for s in signals:
260
+ loop.add_signal_handler(s, handle, s)
261
+
262
+ def restore() -> None:
263
+ for s, handler in previous.items():
264
+ loop.remove_signal_handler(s)
265
+ signal.signal(s, handler)
266
+
267
+ return restore
268
+
269
+
270
+ def _interrupts() -> List[int]:
271
+ """The signals that interrupt: a second one, later, stops waiting for the app."""
272
+ if sys.platform == "win32":
273
+ return [signal.SIGINT, signal.SIGBREAK]
274
+ return [signal.SIGINT]
275
+
276
+
277
+ def _on_signals_windows(
278
+ loop: asyncio.AbstractEventLoop,
279
+ signals: List[int],
280
+ previous: Dict[int, Any],
281
+ handle: Callable[[int], None],
282
+ ) -> Callable[[], None]:
283
+ """Have ``handle`` take ``signals`` on ``loop``, on Windows.
284
+
285
+ A handler runs only once the main thread runs Python again, and on
286
+ Windows the loop waiting for its sockets is not woken by a signal: one
287
+ with nothing else to do would never stop. So each signal also writes to
288
+ a socket the loop watches, as the proactor loop does for itself.
289
+ """
290
+ wake, woken = socket.socketpair()
291
+ wake.setblocking(False)
292
+ woken.setblocking(False)
293
+
294
+ def drain() -> None:
295
+ try:
296
+ while woken.recv(4096):
297
+ pass
298
+ except (BlockingIOError, InterruptedError):
299
+ pass
300
+
301
+ loop.add_reader(woken.fileno(), drain)
302
+ wakeup = signal.set_wakeup_fd(wake.fileno(), warn_on_full_buffer=False)
303
+ for s in signals:
304
+ signal.signal(s, lambda signum, _: loop.call_soon_threadsafe(handle, signum))
250
305
 
251
306
  def restore() -> None:
252
307
  for s, handler in previous.items():
253
- if sys.platform != "win32":
254
- loop.remove_signal_handler(s)
255
308
  signal.signal(s, handler)
309
+ signal.set_wakeup_fd(wakeup)
310
+ loop.remove_reader(woken.fileno())
311
+ wake.close()
312
+ woken.close()
256
313
 
257
314
  return restore
@@ -0,0 +1,5 @@
1
+ """Schema annotations shared by Encore resources."""
2
+
3
+
4
+ class Sensitive:
5
+ """Mark a value for redaction with ``Annotated[T, Sensitive()]``."""
@@ -153,7 +153,7 @@ class AppMeta:
153
153
 
154
154
  Attributes:
155
155
  app_id: The Encore application ID. Empty if the application is not
156
- linked to the Encore platform; run ``encore app link`` to link it.
156
+ linked to the Encore platform; run ``encore cloud link`` to link it.
157
157
  app_slug: The application slug — the human-readable identifier shown in
158
158
  the Encore Cloud dashboard and used by the CLI. Empty if the
159
159
  application is not linked to the Encore platform.
@@ -168,8 +168,7 @@ class AppMeta:
168
168
  base URL for the API — look up the gateway you mean by name. A
169
169
  service's processes, its Workers' included, list the gateways its
170
170
  code names (``gateways.url("api")``) and the one it hosts, and no
171
- other, the default included; one told of none reports an empty
172
- mapping.
171
+ other; one told of none reports an empty mapping.
173
172
  frontends: The application's frontends the service is given — those
174
173
  its code looks up the URL of (``frontends.url("web")``), and the
175
174
  one it hosts — keyed by name, with where each is reached. One the
@@ -11,7 +11,7 @@ service::
11
11
  {
12
12
  "name": "edge",
13
13
  "lang": "python",
14
- "gateway": {"default": true}
14
+ "gateway": {}
15
15
  }
16
16
 
17
17
  The service's program serves the gateway with its Middleware, and nothing
@@ -332,12 +332,12 @@ class _Dispatcher:
332
332
  req._deciding = True
333
333
  taken = False
334
334
  try:
335
- await asyncio.wait_for(_traced(req, reg.mw.on_request(req)), remaining)
335
+ await _within(_traced(req, reg.mw.on_request(req)), remaining)
336
336
  except Rejection as rej:
337
337
  taken = self._respond(event_id, rej)
338
338
  except APIError as err:
339
339
  taken = self._respond(event_id, reject(err.code, err.message))
340
- except asyncio.TimeoutError:
340
+ except _TimedOut:
341
341
  self._timed_out(reg, "request", event_id)
342
342
  except asyncio.CancelledError:
343
343
  self._answer(native.gateway_fail, event_id, "request", "cancelled", "panic")
@@ -380,10 +380,8 @@ class _Dispatcher:
380
380
  resp._editing = True
381
381
  taken = False
382
382
  try:
383
- await asyncio.wait_for(
384
- _traced(req, reg.mw.on_response(req, resp)), remaining
385
- )
386
- except asyncio.TimeoutError:
383
+ await _within(_traced(req, reg.mw.on_response(req, resp)), remaining)
384
+ except _TimedOut:
387
385
  self._timed_out(reg, "response", event.event_id)
388
386
  except asyncio.CancelledError:
389
387
  self._answer(
@@ -494,6 +492,33 @@ async def _traced(req: Request, hook: Awaitable[None]) -> None:
494
492
  otel_context.detach(token)
495
493
 
496
494
 
495
+ class _TimedOut(Exception):
496
+ """A hook took longer than its timeout."""
497
+
498
+
499
+ async def _within(hook: Awaitable[None], timeout: float) -> None:
500
+ """Awaits ``hook`` for at most ``timeout`` seconds, raising _TimedOut after.
501
+
502
+ Not ``asyncio.TimeoutError``, which from Python 3.11 is the TimeoutError
503
+ a hook may raise itself, as a timeout of its own inside it does: that one
504
+ is passed on, as any other error the hook raises is. Whether the hook
505
+ timed out is whether it was still running at its deadline, whatever it
506
+ raises once cancelled there.
507
+ """
508
+ task = asyncio.ensure_future(hook)
509
+ try:
510
+ done, _ = await asyncio.wait((task,), timeout=timeout)
511
+ except asyncio.CancelledError:
512
+ task.cancel()
513
+ await asyncio.gather(task, return_exceptions=True)
514
+ raise
515
+ if done:
516
+ return await task
517
+ task.cancel()
518
+ await asyncio.gather(task, return_exceptions=True)
519
+ raise _TimedOut()
520
+
521
+
497
522
  def _completed(req: Request, done: Any) -> Completed:
498
523
  return Completed(
499
524
  request=req,
@@ -121,16 +121,14 @@ def _load_native():
121
121
  None,
122
122
  )
123
123
  # The Encore installation's, for a process Encore did not start: a
124
- # test runner's, a script's.
124
+ # test runner's, a script's. Kept when it is missing, so that the
125
+ # error names where it was looked for.
125
126
  if path is None and (runtimes := _installed_runtimes()) is not None:
126
- candidate = runtimes / "python" / relative
127
- if candidate.is_file():
128
- path = candidate
127
+ path = runtimes / "python" / relative
129
128
  # Else its runtime component.
130
- if (
131
- path is None
132
- and (component := _component_runtimes(_gateway_program())) is not None
133
- ):
129
+ if (path is None or not path.is_file()) and (
130
+ component := _component_runtimes(_gateway_program())
131
+ ) is not None:
134
132
  path = component / relative
135
133
  if path is None or not path.is_file():
136
134
  gateway = (
@@ -425,6 +425,13 @@ class HttpRequest:
425
425
  """
426
426
  `send_body`, waiting for room for the chunk.
427
427
  """
428
+ def send_trailers(self, /, headers: Sequence[tuple[Sequence[int], Sequence[int]]], more: bool) -> "None":
429
+ """
430
+ The response's trailers: `http.response.trailers`, after the last of
431
+ its body. `more` says whether others follow; all are sent together,
432
+ once none do. Raises `ConnectionResetError` once the client went
433
+ away.
434
+ """
428
435
  def span_add_event(self, /, name: str, attributes: Sequence[tuple[str, Any]] |None = None, timestamp_ns: int |None = None) -> "None":
429
436
  """
430
437
  Adds an event to the request's span.
@@ -453,9 +460,10 @@ class HttpRequest:
453
460
  Renames the request's span. The route the app matched names it again
454
461
  when the request finishes.
455
462
  """
456
- def start_response(self, /, status: int, headers: Sequence[tuple[Sequence[int], Sequence[int]]]) -> "None":
463
+ def start_response(self, /, status: int, headers: Sequence[tuple[Sequence[int], Sequence[int]]], trailers: bool = False) -> "None":
457
464
  """
458
- The response's status and headers: `http.response.start`.
465
+ The response's status and headers: `http.response.start`. With
466
+ `trailers`, the response ends with `send_trailers`, after its body.
459
467
  """
460
468
  @property
461
469
  def started(self, /) -> bool:
@@ -1390,6 +1398,14 @@ class Runtime:
1390
1398
  rather than awaiting: for the exit, which runs no event loop and
1391
1399
  leaves the runtime nothing to complete. Call begin_shutdown first.
1392
1400
  """
1401
+ def wait_stop_request(self, /) -> "bool":
1402
+ """
1403
+ Block this thread until Encore asks the process to stop through the
1404
+ event it gave it on Windows: True then, and False at once when there
1405
+ is none to wait for, as on Unix. Waiting tells Encore to ask through
1406
+ the event rather than with Ctrl-Break: wait only where the request
1407
+ starts the shutdown. Raises OSError if the event can't be waited on.
1408
+ """
1393
1409
 
1394
1410
  @final
1395
1411
  class Secret:
@@ -8,11 +8,15 @@ generator's.
8
8
  from __future__ import annotations
9
9
 
10
10
  import asyncio
11
+ import atexit
11
12
  import base64
12
13
  import importlib
13
14
  import json
15
+ import math
14
16
  import os
17
+ import sys
15
18
  import threading
19
+ import time
16
20
  import weakref
17
21
  from typing import (
18
22
  TYPE_CHECKING,
@@ -72,12 +76,20 @@ def param_text(value: Any) -> str:
72
76
  """
73
77
  if isinstance(value, bool):
74
78
  return "true" if value else "false"
79
+ if isinstance(value, float) and not math.isfinite(value):
80
+ # JSON has no form for NaN or Infinity, which the other languages'
81
+ # servers reject: refused with the error json gives for one in a list.
82
+ raise CallError(
83
+ ErrCode.INVALID_ARGUMENT,
84
+ f"encoding a parameter: Out of range float values are not JSON compliant: {value!r}",
85
+ 0,
86
+ )
75
87
  if isinstance(value, (str, int, float)):
76
88
  return str(value)
77
89
  if isinstance(value, (bytes, bytearray)):
78
90
  return base64.b64encode(value).decode("ascii")
79
91
  try:
80
- return json.dumps(_jsonable(value))
92
+ return json.dumps(_jsonable(value), allow_nan=False)
81
93
  except (TypeError, ValueError) as error:
82
94
  raise CallError(
83
95
  ErrCode.INVALID_ARGUMENT, f"encoding a parameter: {error}", 0
@@ -98,7 +110,7 @@ def json_body(value: Any) -> bytes:
98
110
  CallError: ``INVALID_ARGUMENT``, for a value JSON has no form for.
99
111
  """
100
112
  try:
101
- return json.dumps(_jsonable(value)).encode()
113
+ return json.dumps(_jsonable(value), allow_nan=False).encode()
102
114
  except (TypeError, ValueError) as error:
103
115
  raise CallError(
104
116
  ErrCode.INVALID_ARGUMENT, f"encoding the body: {error}", 0
@@ -276,6 +288,48 @@ def _step(awaitable: Any) -> None:
276
288
  _pyqwest_client: Optional[pyqwest.Client] = None
277
289
  _pyqwest_lock = threading.Lock()
278
290
 
291
+ #: How long the threads Python didn't start may take to leave it at exit.
292
+ _LEAVE_PYTHON = 1.0
293
+ _leaves_python_at_exit = False
294
+
295
+
296
+ def leave_python_at_exit() -> None:
297
+ """Have the process, as it exits, wait for pyqwest's threads to leave Python.
298
+
299
+ pyqwest hands an answer to its event loop from a thread of its own, with
300
+ ``call_soon_threadsafe``, whose wakeup of the loop releases the GIL: the
301
+ loop can take the answer, and the program finish, before that thread has
302
+ the GIL back. A thread that takes it as the interpreter finalizes is
303
+ ended, which before Python 3.14 unwinds its Rust frames, and that aborts
304
+ the process (SIGABRT), saying nothing.
305
+ """
306
+ global _leaves_python_at_exit
307
+ with _pyqwest_lock:
308
+ if not _leaves_python_at_exit:
309
+ _leaves_python_at_exit = True
310
+ atexit.register(_leave_python, _LEAVE_PYTHON)
311
+
312
+
313
+ def _leave_python(timeout: float) -> None:
314
+ """Wait, up to ``timeout`` seconds, for the threads Python didn't start to leave it.
315
+
316
+ Without the GIL, which those in Python wait for.
317
+ """
318
+ deadline = time.monotonic() + timeout
319
+ while _foreign_threads_in_python() and time.monotonic() < deadline:
320
+ time.sleep(0.001)
321
+
322
+
323
+ def _foreign_threads_in_python() -> bool:
324
+ """Whether a thread Python didn't start runs Python code, or waits to."""
325
+ started = {
326
+ thread.ident
327
+ for thread in threading.enumerate()
328
+ # A thread of its own that asked for its threading.Thread.
329
+ if not isinstance(thread, threading._DummyThread)
330
+ }
331
+ return any(ident not in started for ident in sys._current_frames())
332
+
279
333
 
280
334
  def pyqwest_client() -> pyqwest.Client:
281
335
  """Return the ``pyqwest.Client`` generated gRPC clients share.
@@ -56,8 +56,10 @@ def connect_client(
56
56
 
57
57
  Over ``http_client``, or the HTTP/2 connections the SDK shares. Requests
58
58
  are sent uncompressed, as grpc-go and tonic send them; answers may be
59
- gzipped.
59
+ gzipped. The process waits, as it exits, for pyqwest's threads to leave
60
+ Python, which would otherwise abort it.
60
61
  """
62
+ clients.leave_python_at_exit()
61
63
  return ConnectClient(
62
64
  base_url,
63
65
  protocol=ProtocolType.GRPC,
@@ -111,8 +111,15 @@ def _declared(name: str) -> Optional[Config]:
111
111
 
112
112
 
113
113
  def encode(data: Any) -> str:
114
- """A JSON value's wire form."""
115
- raw = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode()
114
+ """A JSON value's wire form.
115
+
116
+ Raises:
117
+ ValueError: It holds a NaN or an infinite float, which JSON has no
118
+ form for, and the other languages' services reject.
119
+ """
120
+ raw = json.dumps(
121
+ data, separators=(",", ":"), ensure_ascii=False, allow_nan=False
122
+ ).encode()
116
123
  return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
117
124
 
118
125
 
@@ -61,6 +61,13 @@ for _name, _value in _runtime.test_dotenv():
61
61
  os.environ.setdefault(_name, _value)
62
62
 
63
63
 
64
+ #: The signals that stop a process unaware of shutdown, skipping atexit: SIGTERM,
65
+ #: and on Windows, where no process can send another SIGTERM, Ctrl-Break, the
66
+ #: console event a process group of its own can be sent.
67
+ _STOP_SIGNALS = (
68
+ (signal.SIGTERM, signal.SIGBREAK) if sys.platform == "win32" else (signal.SIGTERM,)
69
+ )
70
+
64
71
  #: The outcome of the shutdown at exit, once run: whether it completed in time.
65
72
  _shutdown_ok: bool | None = None
66
73
 
@@ -80,7 +87,8 @@ def _shutdown() -> bool:
80
87
  # SIGTERM handler, which may interrupt an import.
81
88
  if threading.current_thread() is threading.main_thread():
82
89
  # A repeated SIGTERM must not interrupt the flush.
83
- signal.signal(signal.SIGTERM, signal.SIG_IGN)
90
+ for stop in _STOP_SIGNALS:
91
+ signal.signal(stop, signal.SIG_IGN)
84
92
  _runtime.begin_shutdown()
85
93
  try:
86
94
  result = _runtime.wait_completed()
@@ -110,15 +118,50 @@ def _testing() -> bool:
110
118
  return (meta.get("environment") or {}).get("type") == "test"
111
119
 
112
120
 
121
+ #: Whether a thread waits for Encore's stop request.
122
+ _listening = False
123
+
124
+
125
+ def listen_stop_request() -> None:
126
+ """On Windows, take Encore's stop request as Ctrl-Break from now on.
127
+
128
+ Once a process waits for the request, Encore asks it to stop that way
129
+ alone, and sends it no Ctrl-Break: call this only once SIGBREAK's handler
130
+ shuts the process down. On the request, a thread raises SIGBREAK, which
131
+ reaches the handler and the signal wakeup fd as Ctrl-Break does. Only the
132
+ first call waits.
133
+ """
134
+ global _listening
135
+ if sys.platform != "win32" or _listening:
136
+ return
137
+ _listening = True
138
+ threading.Thread(target=_wait_stop_request, daemon=True).start()
139
+
140
+
141
+ def _wait_stop_request() -> None:
142
+ try:
143
+ requested = _runtime.wait_stop_request()
144
+ except OSError as exc:
145
+ print(f"encore: cannot wait for Encore's stop request: {exc}", file=sys.stderr)
146
+ return
147
+ if requested and sys.platform == "win32":
148
+ signal.raise_signal(signal.SIGBREAK)
149
+
150
+
113
151
  atexit.register(_shutdown_at_exit)
114
- # SIGTERM's default action skips atexit. Servers that handle it themselves
115
- # replace this handler, and re-raise the signal after restoring it.
116
- if (
117
- threading.current_thread() is threading.main_thread()
118
- and signal.getsignal(signal.SIGTERM) is signal.SIG_DFL
119
- and not _testing()
120
- ):
121
- signal.signal(signal.SIGTERM, _exit_on_sigterm)
152
+ # SIGTERM's default action skips atexit, as Ctrl-Break's does. Servers that
153
+ # handle them themselves replace this handler, and re-raise the signal after
154
+ # restoring it.
155
+ if threading.current_thread() is threading.main_thread() and not _testing():
156
+ for _stop in _STOP_SIGNALS:
157
+ if signal.getsignal(_stop) is signal.SIG_DFL:
158
+ signal.signal(_stop, _exit_on_sigterm)
159
+ # And Encore's stop request, if Ctrl-Break now shuts the process down.
160
+ if (
161
+ sys.platform == "win32"
162
+ and signal.getsignal(signal.SIGBREAK) is _exit_on_sigterm
163
+ ):
164
+ listen_stop_request()
122
165
 
123
166
 
124
167
  def runtime() -> _native.Runtime:
@@ -34,9 +34,12 @@ from __future__ import annotations
34
34
  import asyncio
35
35
  from dataclasses import dataclass
36
36
  from datetime import datetime
37
+ import functools
38
+ import inspect
37
39
  import json
38
40
  import types
39
41
  from typing import (
42
+ Annotated,
40
43
  Any,
41
44
  Awaitable,
42
45
  Callable,
@@ -71,6 +74,35 @@ try:
71
74
  except ImportError:
72
75
  BaseModel = None
73
76
 
77
+ #: A model's message is published by field name, and validated by name too,
78
+ #: whatever aliases its fields have: from pydantic 2.11, which takes
79
+ #: ``by_name``. Before it, a model takes field names only where it has no
80
+ #: aliases, or sets ``populate_by_name``.
81
+ _BY_NAME: dict[str, Any] = (
82
+ {"by_name": True}
83
+ if BaseModel is not None
84
+ and "by_name" in inspect.signature(BaseModel.model_validate_json).parameters
85
+ else {}
86
+ )
87
+
88
+
89
+ @functools.lru_cache(maxsize=None)
90
+ def _by_name(model: Any) -> dict[str, Any]:
91
+ """``_BY_NAME``, where ``model``'s ``model_validate_json`` takes it.
92
+
93
+ A model may override the classmethod with a signature of its own, from
94
+ before pydantic took ``by_name``; it is called as it was then, without it.
95
+ """
96
+ if not _BY_NAME:
97
+ return _BY_NAME
98
+ try:
99
+ params = inspect.signature(model.model_validate_json).parameters.values()
100
+ except (TypeError, ValueError):
101
+ return {}
102
+ if any(p.name == "by_name" or p.kind is p.VAR_KEYWORD for p in params):
103
+ return _BY_NAME
104
+ return {}
105
+
74
106
 
75
107
  _UNION_ORIGINS = (Union, getattr(types, "UnionType", Union))
76
108
  _json_ref = ForwardRef("JSON", module=__name__)
@@ -99,8 +131,15 @@ _T_co = TypeVar("_T_co", covariant=True)
99
131
  _T_contra = TypeVarDefault("_T_contra", bound=Payload, contravariant=True, default=Any)
100
132
 
101
133
 
134
+ def _without_annotations(tp: Any) -> Any:
135
+ while get_origin(tp) is Annotated:
136
+ tp = get_args(tp)[0]
137
+ return tp
138
+
139
+
102
140
  def _validate_payload_type(payload_type: Any) -> None:
103
141
  """Check decoder support, without validating individual JSON values."""
142
+ payload_type = _without_annotations(payload_type)
104
143
  if payload_type is bytes or (
105
144
  BaseModel is not None
106
145
  and isinstance(payload_type, type)
@@ -111,7 +150,7 @@ def _validate_payload_type(payload_type: Any) -> None:
111
150
  pending = [payload_type]
112
151
  seen: set[int] = set()
113
152
  while pending:
114
- current = pending.pop()
153
+ current = _without_annotations(pending.pop())
115
154
  if id(current) in seen:
116
155
  continue
117
156
  seen.add(id(current))
@@ -141,6 +180,7 @@ def _decode_message_data(payload_type: Any, data: bytes) -> Payload:
141
180
  Other supported annotations use ordinary JSON decoding; nested annotations
142
181
  do not coerce or validate JSON values. Use a model for field validation.
143
182
  """
183
+ payload_type = _without_annotations(payload_type)
144
184
  if payload_type is bytes:
145
185
  return data
146
186
 
@@ -150,7 +190,7 @@ def _decode_message_data(payload_type: Any, data: bytes) -> Payload:
150
190
  and issubclass(payload_type, BaseModel)
151
191
  ):
152
192
  try:
153
- return payload_type.model_validate_json(data)
193
+ return payload_type.model_validate_json(data, **_by_name(payload_type))
154
194
  except ValueError as error:
155
195
  raise ValueError(
156
196
  f"Cannot decode Pub/Sub message as {payload_type.__name__}. "
@@ -224,12 +264,14 @@ def _serialize_payload(value: Any) -> bytes:
224
264
  return value.model_dump_json().encode("utf-8")
225
265
 
226
266
  try:
227
- return json.dumps(value).encode("utf-8")
267
+ # Not the NaN and Infinity JSON has no form for, which the other
268
+ # languages' subscribers reject.
269
+ return json.dumps(value, allow_nan=False).encode("utf-8")
228
270
  except (TypeError, ValueError) as error:
229
271
  raise TypeError(
230
- "Cannot publish Pub/Sub message. Use JSON values, bytes, or a top-level "
231
- "Pydantic v2 model. Dataclasses and models nested in plain JSON containers "
232
- "are not supported."
272
+ f"Cannot publish Pub/Sub message: {error}. Use JSON values, which have "
273
+ "no NaN or Infinity, bytes, or a top-level Pydantic v2 model. "
274
+ "Dataclasses and models nested in plain JSON containers are not supported."
233
275
  ) from error
234
276
 
235
277
 
@@ -199,12 +199,15 @@ class Field(Generic[_T]):
199
199
 
200
200
  Raises:
201
201
  TypeError: The value is not one of the types a field may hold.
202
- ValueError: The value encodes to more than the field may.
202
+ ValueError: The value encodes to more than the field may, or
203
+ holds a NaN or an infinite float, which JSON has no form for.
203
204
  """
204
205
  try:
205
206
  encoded = reqfields.encode(to_json(value))
206
207
  except TypeError as error:
207
208
  raise TypeError(f"reqctx: field {self._name!r}: {error}") from None
209
+ except ValueError as error:
210
+ raise ValueError(f"reqctx: field {self._name!r}: {error}") from None
208
211
  try:
209
212
  return reqfields.with_value(self._name, encoded, context)
210
213
  except ValueError as error:
@@ -220,7 +223,8 @@ class Field(Generic[_T]):
220
223
  TypeError: The value is not one of the types a field may hold.
221
224
  ValueError: The value encodes to more than the field may: 4 KiB,
222
225
  or 1 KiB for a field declared with ``pubsub``, or makes the
223
- request's fields encode to more than 8 KiB.
226
+ request's fields encode to more than 8 KiB; or it holds a NaN
227
+ or an infinite float, which JSON has no form for.
224
228
  """
225
229
  token = context_api.attach(self.context(value))
226
230
  try:
@@ -9,7 +9,9 @@ scope across the app.
9
9
 
10
10
  A secret's value is a string, read with value. It is resolved once per
11
11
  process and does not change while the process runs: a new value reaches a
12
- service when the service restarts.
12
+ service when the service restarts. A secret with no value reads as "": only
13
+ local development can lack one, since a deploy gives each service every
14
+ secret it uses.
13
15
 
14
16
  A shared secret is declared once in the app. Another service, which cannot
15
17
  import the declaring service's modules, reads it by name with
@@ -160,13 +162,16 @@ class Secret(Generic[_T]):
160
162
 
161
163
  @property
162
164
  def value(self) -> str:
163
- """The secret's value.
165
+ """The secret's value, or "" if it has none.
166
+
167
+ Only local development can lack a value, before one is set: a deploy
168
+ gives each service every secret it uses. An unset secret reads as "",
169
+ like one set empty.
164
170
 
165
171
  A variable annotation alone does not supply the type argument.
166
172
 
167
173
  Raises:
168
174
  TypeError: The secret was declared without its type argument.
169
- KeyError: The secret has no value.
170
175
  UnicodeDecodeError: The value is not valid UTF-8.
171
176
  """
172
177
  args = get_args(getattr(self, "__orig_class__", None))
@@ -181,7 +186,7 @@ class Secret(Generic[_T]):
181
186
  return value.decode("utf-8")
182
187
  secret = self._handle.get()
183
188
  if secret is None:
184
- raise KeyError(f'secret "{self._name}" is not set')
189
+ return ""
185
190
  return secret.get_bytes().decode("utf-8")
186
191
 
187
192
  def __repr__(self) -> str:
@@ -295,6 +295,11 @@ async def _handle(
295
295
  # A shallow copy of the worker's lifespan state, as ASGI says.
296
296
  "state": state.copy(),
297
297
  }
298
+ # HTTP/2 can end any response in trailers, as gRPC needs; HTTP/1.1 only
299
+ # a chunked one a client asked them for, and gRPC never uses it.
300
+ trailers = version == "2"
301
+ if trailers:
302
+ scope["extensions"] = {"http.response.trailers": {}}
298
303
 
299
304
  # The request's context: its span, which the server records, and its
300
305
  # Request Context fields.
@@ -341,7 +346,11 @@ async def _handle(
341
346
  if kind == "http.response.start":
342
347
  # ASGI allows each header as a list, and bytes-like values.
343
348
  headers = [(bytes(k), bytes(v)) for k, v in message.get("headers") or ()]
344
- request.start_response(message["status"], headers)
349
+ request.start_response(
350
+ message["status"],
351
+ headers,
352
+ trailers and bool(message.get("trailers", False)),
353
+ )
345
354
  elif kind == "http.response.body":
346
355
  data = message.get("body", b"")
347
356
  if type(data) is not bytes:
@@ -349,6 +358,9 @@ async def _handle(
349
358
  more = bool(message.get("more_body", False))
350
359
  if not request.send_body(data, more):
351
360
  await request.send_body_wait(bytes(data), more)
361
+ elif kind == "http.response.trailers" and trailers:
362
+ headers = [(bytes(k), bytes(v)) for k, v in message.get("headers") or ()]
363
+ request.send_trailers(headers, bool(message.get("more_trailers", False)))
352
364
  else:
353
365
  raise RuntimeError(
354
366
  f"ASGI: unexpected message type {kind!r} for an HTTP request"
@@ -22,9 +22,10 @@ Requires httpx: ``pip install 'encore-dev[httpx]'``.
22
22
  from __future__ import annotations
23
23
 
24
24
  import asyncio
25
+ import threading
25
26
  import weakref
26
27
  from types import TracebackType
27
- from typing import Any, Optional
28
+ from typing import Any, AsyncGenerator, Optional
28
29
 
29
30
  try:
30
31
  import httpx
@@ -34,6 +35,7 @@ except ImportError as error: # pragma: no cover - exercised without httpx insta
34
35
  ) from error
35
36
 
36
37
  from ..internal import testscope
38
+ from ..internal.clients import _step
37
39
  from . import (
38
40
  CLIENT_DEFAULT,
39
41
  CallError,
@@ -96,25 +98,65 @@ class AsyncTransport(httpx.AsyncBaseTransport):
96
98
  each event loop it is used on: a connection belongs to the loop that
97
99
  opened it, and a client an app keeps at module scope is used on more than
98
100
  one where tests run, a test's and the one a fixture's setup runs on.
101
+ Each closes when its loop finishes.
99
102
  """
100
103
 
101
104
  def __init__(self, base: Optional[httpx.AsyncBaseTransport] = None) -> None:
102
105
  """Wrap ``base``, httpx's default async transport when ``None``."""
103
106
  self._base = base
107
+ # Each event loop's own transport, and the generator that closes it
108
+ # when the loop finishes. A transport's connections refer to their
109
+ # loop, so being weak in the loop alone would not let a finished one
110
+ # go: an entry leaves when its loop finishes, or is found closed.
104
111
  self._own: weakref.WeakKeyDictionary[
105
- asyncio.AbstractEventLoop, httpx.AsyncBaseTransport
112
+ asyncio.AbstractEventLoop,
113
+ tuple[httpx.AsyncBaseTransport, AsyncGenerator[None, None]],
106
114
  ] = weakref.WeakKeyDictionary()
115
+ # Reentrant: dropping a closed loop's transport, under it, runs the
116
+ # cleanup that takes it too.
117
+ self._lock = threading.RLock()
107
118
 
108
119
  def _transport(self) -> httpx.AsyncBaseTransport:
109
120
  """The transport requests made now go through."""
110
121
  if self._base is not None:
111
122
  return self._base
112
123
  loop = asyncio.get_running_loop()
113
- own = self._own.get(loop)
114
- if own is None:
115
- own = self._own[loop] = httpx.AsyncHTTPTransport()
124
+ with self._lock:
125
+ held = self._own.get(loop)
126
+ if held is not None:
127
+ return held[0]
128
+ self._forget_closed_loops()
129
+ own = httpx.AsyncHTTPTransport()
130
+ closer = self._close_with_loop(loop, own)
131
+ _step(closer.asend(None))
132
+ self._own[loop] = (own, closer)
116
133
  return own
117
134
 
135
+ async def _close_with_loop(
136
+ self, loop: asyncio.AbstractEventLoop, own: httpx.AsyncBaseTransport
137
+ ) -> AsyncGenerator[None, None]:
138
+ """Keep ``own`` until ``loop`` finishes, then close it.
139
+
140
+ As ``encore.internal.clients`` keeps a loop's client: an async
141
+ generator the loop closes in ``loop.shutdown_asyncgens``, which
142
+ ``asyncio.run`` calls before it closes a loop.
143
+ """
144
+ try:
145
+ yield
146
+ finally:
147
+ with self._lock:
148
+ if self._own.get(loop, (None,))[0] is own:
149
+ del self._own[loop]
150
+ # A loop closed without finishing its generators runs nothing more.
151
+ if not loop.is_closed():
152
+ await own.aclose()
153
+
154
+ def _forget_closed_loops(self) -> None:
155
+ """Drop the transports of loops closed without finishing their generators."""
156
+ for loop in [loop for loop in self._own if loop.is_closed()]:
157
+ _, closer = self._own.pop(loop)
158
+ _step(closer.aclose())
159
+
118
160
  async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
119
161
  """Send ``request`` through the base transport, with its Request Context."""
120
162
  _propagate.prepare(str(request.url), request.headers)
@@ -136,7 +178,14 @@ class AsyncTransport(httpx.AsyncBaseTransport):
136
178
 
137
179
  async def aclose(self) -> None:
138
180
  """Close the base transport: the caller's, or this event loop's own."""
139
- await self._transport().aclose()
181
+ if self._base is not None:
182
+ await self._base.aclose()
183
+ return
184
+ # Without making one: the loop may be finishing, its own closed and
185
+ # forgotten already.
186
+ held = self._own.get(asyncio.get_running_loop())
187
+ if held is not None:
188
+ await held[0].aclose()
140
189
 
141
190
 
142
191
  def _patient(kwargs: dict[str, Any]) -> None:
@@ -272,7 +272,8 @@ def set_config(config: Config[Any], value: Any) -> None:
272
272
  config its value for tests in its ``test`` config file instead.
273
273
 
274
274
  Raises:
275
- ValueError: The value does not satisfy the config's schema.
275
+ ValueError: The value does not satisfy the config's schema, or holds
276
+ a NaN or an infinite float, which JSON has no form for.
276
277
  RuntimeError: The process runs no tests, or the call belongs to none;
277
278
  or the test is a system test.
278
279
  """
@@ -286,7 +287,7 @@ def set_config(config: Config[Any], value: Any) -> None:
286
287
  "tests in its `test` config file (<name>.test.config.toml)"
287
288
  )
288
289
  name = config.name
289
- text = test._core().set_config(name, json.dumps(_json_form(value)))
290
+ text = test._core().set_config(name, json.dumps(_json_form(value), allow_nan=False))
290
291
  test._configs[name] = (build(config._type(), json.loads(text), name),)
291
292
 
292
293
 
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "encore-dev"
7
- version = "2.0.0b10"
7
+ version = "2.0.0b13"
8
8
  description = "Encore SDK for Python — infrastructure resources"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -40,6 +40,7 @@ dev = [
40
40
  "connectrpc>=0.13.0,<0.14; python_version >= '3.11'",
41
41
  "django>=5,<6; python_version >= '3.10'",
42
42
  "fastapi>=0.156; python_version >= '3.10'",
43
+ "h2>=4.4.1; python_version >= '3.10'",
43
44
  "httpx>=0.27",
44
45
  "hypercorn>=0.17; python_version >= '3.11'",
45
46
  "hypothesis>=6",
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "encore-dev"
7
- version = "2.0.0b10"
7
+ version = "2.0.0b13"
8
8
  description = "Encore SDK for Python — infrastructure resources"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -61,6 +61,10 @@ dev = [
61
61
  # encore.run turns FastAPI's own spans off for its requests: the tests
62
62
  # hold FastAPI to how it does.
63
63
  "fastapi>=0.156; python_version >= '3.10'",
64
+ # The h2c tests speak HTTP/2 through httpx, which needs h2 for it, and
65
+ # frame by frame through h2. Its last release for 3.9 has known
66
+ # vulnerabilities.
67
+ "h2>=4.4.1; python_version >= '3.10'",
64
68
  "httpx>=0.27",
65
69
  "hypercorn>=0.17; python_version >= '3.11'",
66
70
  "hypothesis>=6",