encore-dev 2.0.0b9__tar.gz → 2.0.0b11__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 (94) hide show
  1. encore_dev-2.0.0b9/README.md → encore_dev-2.0.0b11/PKG-INFO +60 -6
  2. encore_dev-2.0.0b9/PKG-INFO → encore_dev-2.0.0b11/README.md +36 -29
  3. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/__init__.py +2 -0
  4. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/_run.py +71 -20
  5. encore_dev-2.0.0b11/encore/_schema.py +5 -0
  6. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/env/__init__.py +2 -3
  7. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/gateway/__init__.py +1 -1
  8. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/gateway/_serve.py +31 -6
  9. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/_loader.py +6 -8
  10. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/_native.pyi +167 -2
  11. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/clients.py +95 -10
  12. encore_dev-2.0.0b11/encore/internal/grpc.py +210 -0
  13. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/reqfields.py +9 -2
  14. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/runtime.py +16 -9
  15. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/pubsub/__init__.py +48 -6
  16. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/reqctx/__init__.py +6 -2
  17. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/secrets/__init__.py +9 -4
  18. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/server/_serve.py +13 -1
  19. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/services/__init__.py +17 -3
  20. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/services/httpx.py +55 -6
  21. encore_dev-2.0.0b11/encore/storage/__init__.py +5 -0
  22. encore_dev-2.0.0b11/encore/storage/clickhouse/__init__.py +654 -0
  23. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/testing/__init__.py +3 -2
  24. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/pyproject.toml +7 -5
  25. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/pyproject.toml.orig +14 -8
  26. encore_dev-2.0.0b9/encore/storage/__init__.py +0 -5
  27. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/config/__init__.py +0 -0
  28. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/config/_build.py +0 -0
  29. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/config/_markers.py +0 -0
  30. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/cron/__init__.py +0 -0
  31. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/django/__init__.py +0 -0
  32. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/django/base.py +0 -0
  33. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/errs/__init__.py +0 -0
  34. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/frontends/__init__.py +0 -0
  35. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/gateway/match.py +0 -0
  36. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/gateways/__init__.py +0 -0
  37. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/__init__.py +0 -0
  38. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/lazy.py +0 -0
  39. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/startup.py +0 -0
  40. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/internal/testscope.py +0 -0
  41. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/logs/__init__.py +0 -0
  42. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/logs/_api.py +0 -0
  43. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/logs/_console.py +0 -0
  44. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/logs/_runtime.py +0 -0
  45. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/metrics/__init__.py +0 -0
  46. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/metrics/_instrument.py +0 -0
  47. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/metrics/_metrics.py +0 -0
  48. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/metrics/_provider.py +0 -0
  49. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/py.typed +0 -0
  50. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/reqctx/_json.py +0 -0
  51. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/server/__init__.py +0 -0
  52. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/server/_span.py +0 -0
  53. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/server/_tracing.py +0 -0
  54. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/server/asgi.py +0 -0
  55. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/server/wsgi.py +0 -0
  56. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/services/_propagate.py +0 -0
  57. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/services/aiohttp.py +0 -0
  58. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/services/niquests.py +0 -0
  59. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/services/requests.py +0 -0
  60. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/shutdown/__init__.py +0 -0
  61. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/objects/__init__.py +0 -0
  62. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/postgres/__init__.py +0 -0
  63. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/__init__.py +0 -0
  64. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/_base.py +0 -0
  65. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/_batch.py +0 -0
  66. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/_errors.py +0 -0
  67. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/_responses.py +0 -0
  68. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/_scan.py +0 -0
  69. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/_values.py +0 -0
  70. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/bitmap.py +0 -0
  71. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/command.py +0 -0
  72. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/generic.py +0 -0
  73. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/geo.py +0 -0
  74. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/hash.py +0 -0
  75. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/hyperloglog.py +0 -0
  76. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/json.py +0 -0
  77. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/list.py +0 -0
  78. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/pubsub.py +0 -0
  79. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/script.py +0 -0
  80. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/set.py +0 -0
  81. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/sorted_set.py +0 -0
  82. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/stream.py +0 -0
  83. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/storage/redis/string.py +0 -0
  84. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/testing/_playwright_fixtures.py +0 -0
  85. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/testing/_steps.py +0 -0
  86. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/testing/playwright.py +0 -0
  87. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/testing/pytest_plugin.py +0 -0
  88. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/testing/system.py +0 -0
  89. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/tracing/__init__.py +0 -0
  90. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/tracing/_context.py +0 -0
  91. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/tracing/_encode.py +0 -0
  92. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/tracing/_provider.py +0 -0
  93. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/tracing/_span.py +0 -0
  94. {encore_dev-2.0.0b9 → encore_dev-2.0.0b11}/encore/tracing/_tracer.py +0 -0
@@ -1,3 +1,27 @@
1
+ Metadata-Version: 2.3
2
+ Name: encore-dev
3
+ Version: 2.0.0b11
4
+ Summary: Encore SDK for Python — infrastructure resources
5
+ Author: Encore
6
+ License: MPL-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Dist: opentelemetry-api>=1.27
9
+ Requires-Dist: typing-extensions>=4.13
10
+ Requires-Dist: aiohttp>=3.14.4 ; python_full_version >= '3.10' and extra == 'aiohttp'
11
+ Requires-Dist: connectrpc>=0.13.0,<0.14 ; python_full_version >= '3.11' and extra == 'grpc'
12
+ Requires-Dist: protobuf-py==0.7.0 ; python_full_version >= '3.11' and extra == 'grpc'
13
+ Requires-Dist: pyqwest>=0.14 ; python_full_version >= '3.11' and extra == 'grpc'
14
+ Requires-Dist: httpx>=0.27 ; extra == 'httpx'
15
+ Requires-Dist: niquests>=3.19 ; extra == 'niquests'
16
+ Requires-Dist: requests>=2.34 ; python_full_version >= '3.10' and extra == 'requests'
17
+ Requires-Python: >=3.9
18
+ Provides-Extra: aiohttp
19
+ Provides-Extra: grpc
20
+ Provides-Extra: httpx
21
+ Provides-Extra: niquests
22
+ Provides-Extra: requests
23
+ Description-Content-Type: text/markdown
24
+
1
25
  # Encore SDK for Python
2
26
 
3
27
  The Python SDK for [Encore](https://encore.dev) — **infrastructure resources only**.
@@ -45,9 +69,10 @@ async def place_order(order):
45
69
  `secrets.Secret[str]("Name")` belongs to the service that declares it.
46
70
  `secrets.Secret[str]("Name", scope="shared")` is one secret for the whole app,
47
71
  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.
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.
51
76
 
52
77
  A shared secret is declared once in the app. Another Python service can't
53
78
  import the declaring service's modules, so it references the secret by name
@@ -187,7 +212,9 @@ its `code` is the `ErrCode` the service answered with, or the one its HTTP
187
212
  status means; `UNAVAILABLE` when no answer came, and `DEADLINE_EXCEEDED` when
188
213
  the call took longer than its timeout. `message` says what went wrong, and
189
214
  `status` is the HTTP status of the service's answer, 0 when there was none. A GraphQL answer with errors raises its subclass
190
- `GraphQLRequestError`, whose `errors` are the answer's.
215
+ `GraphQLRequestError`, whose `errors` are the answer's, and a gRPC status's
216
+ details are its `details`, each its protobuf-py message, or the
217
+ `protobuf.wkt.Any` it came as, for a type the client's protos lack.
191
218
 
192
219
  ```python
193
220
  from encore.errs import ErrCode
@@ -201,9 +228,36 @@ except CallError as error:
201
228
  product = None
202
229
  ```
203
230
 
231
+ A gRPC module speaks the gRPC protocol over HTTP/2, with connectrpc, so it
232
+ calls any gRPC server: h2c to an `http://` URL, TLS to an `https://` one,
233
+ trusting the system's certificates and those `SSL_CERT_FILE` and
234
+ `SSL_CERT_DIR` name. A server or bidi stream is an async iterator, and a client
235
+ or bidi stream takes an async iterable of requests. Its messages are
236
+ protobuf-py's, which `protoc-gen-py` generates into `encore_gen/protos/`, a
237
+ module per `.proto` file that every client of the service shares; the gRPC
238
+ module has the top-level messages and enums of the service's protos as its
239
+ own, and the well-known types its RPCs take and return.
240
+
241
+ ```python
242
+ async for update in catalog.grpc.stuff_service.watch_stuff(
243
+ catalog.grpc.WatchRequest(), timeout=30.0
244
+ ):
245
+ print(update)
246
+ ```
247
+
248
+ A gRPC call behaves as connectrpc makes it, which `CallError` only carries
249
+ the code of. Its timeout is its deadline, which the service is told, and which
250
+ applies to each read from the network: a stream raises `DEADLINE_EXCEEDED` at
251
+ the read after it, so messages that arrived together in one read can still
252
+ come past it. Cancelling the task that makes a call fails the call with
253
+ `CANCELED`, which an `except CallError` catches too unless it raises that code
254
+ again, and an exception the requests of a stream raise fails it with
255
+ `UNAVAILABLE`, that exception its `__cause__`.
256
+
204
257
  OpenAPI and GraphQL modules need httpx (`encore-dev[httpx]`), and gRPC modules
205
- connectrpc (`encore-dev[grpc]`, on Python 3.11 and later). A module is imported
206
- when first used, so a service needs only what the modules it uses need.
258
+ connectrpc and protobuf-py (`encore-dev[grpc]`, on Python 3.11 and later). A
259
+ module is imported when first used, so a service needs only what the modules it
260
+ uses need.
207
261
 
208
262
  ## Request Context
209
263
 
@@ -1,26 +1,3 @@
1
- Metadata-Version: 2.3
2
- Name: encore-dev
3
- Version: 2.0.0b9
4
- Summary: Encore SDK for Python — infrastructure resources
5
- Author: Encore
6
- License: MPL-2.0
7
- Classifier: Programming Language :: Python :: 3
8
- Requires-Dist: opentelemetry-api>=1.27
9
- Requires-Dist: typing-extensions>=4.13
10
- Requires-Dist: aiohttp>=3.14.4 ; python_full_version >= '3.10' and extra == 'aiohttp'
11
- Requires-Dist: connectrpc>=0.10.1,<0.11 ; python_full_version >= '3.11' and extra == 'grpc'
12
- Requires-Dist: pyqwest>=0.12 ; python_full_version >= '3.11' and extra == 'grpc'
13
- Requires-Dist: httpx>=0.27 ; extra == 'httpx'
14
- Requires-Dist: niquests>=3.19 ; extra == 'niquests'
15
- Requires-Dist: requests>=2.34 ; python_full_version >= '3.10' and extra == 'requests'
16
- Requires-Python: >=3.9
17
- Provides-Extra: aiohttp
18
- Provides-Extra: grpc
19
- Provides-Extra: httpx
20
- Provides-Extra: niquests
21
- Provides-Extra: requests
22
- Description-Content-Type: text/markdown
23
-
24
1
  # Encore SDK for Python
25
2
 
26
3
  The Python SDK for [Encore](https://encore.dev) — **infrastructure resources only**.
@@ -68,9 +45,10 @@ async def place_order(order):
68
45
  `secrets.Secret[str]("Name")` belongs to the service that declares it.
69
46
  `secrets.Secret[str]("Name", scope="shared")` is one secret for the whole app,
70
47
  given to the services that read it, and `scope="global"` one that every service
71
- is given. `value` reads the secret as a string, and raises `KeyError` when it
72
- has no value. A secret's value is resolved once per process: a new value
73
- 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.
74
52
 
75
53
  A shared secret is declared once in the app. Another Python service can't
76
54
  import the declaring service's modules, so it references the secret by name
@@ -210,7 +188,9 @@ its `code` is the `ErrCode` the service answered with, or the one its HTTP
210
188
  status means; `UNAVAILABLE` when no answer came, and `DEADLINE_EXCEEDED` when
211
189
  the call took longer than its timeout. `message` says what went wrong, and
212
190
  `status` is the HTTP status of the service's answer, 0 when there was none. A GraphQL answer with errors raises its subclass
213
- `GraphQLRequestError`, whose `errors` are the answer's.
191
+ `GraphQLRequestError`, whose `errors` are the answer's, and a gRPC status's
192
+ details are its `details`, each its protobuf-py message, or the
193
+ `protobuf.wkt.Any` it came as, for a type the client's protos lack.
214
194
 
215
195
  ```python
216
196
  from encore.errs import ErrCode
@@ -224,9 +204,36 @@ except CallError as error:
224
204
  product = None
225
205
  ```
226
206
 
207
+ A gRPC module speaks the gRPC protocol over HTTP/2, with connectrpc, so it
208
+ calls any gRPC server: h2c to an `http://` URL, TLS to an `https://` one,
209
+ trusting the system's certificates and those `SSL_CERT_FILE` and
210
+ `SSL_CERT_DIR` name. A server or bidi stream is an async iterator, and a client
211
+ or bidi stream takes an async iterable of requests. Its messages are
212
+ protobuf-py's, which `protoc-gen-py` generates into `encore_gen/protos/`, a
213
+ module per `.proto` file that every client of the service shares; the gRPC
214
+ module has the top-level messages and enums of the service's protos as its
215
+ own, and the well-known types its RPCs take and return.
216
+
217
+ ```python
218
+ async for update in catalog.grpc.stuff_service.watch_stuff(
219
+ catalog.grpc.WatchRequest(), timeout=30.0
220
+ ):
221
+ print(update)
222
+ ```
223
+
224
+ A gRPC call behaves as connectrpc makes it, which `CallError` only carries
225
+ the code of. Its timeout is its deadline, which the service is told, and which
226
+ applies to each read from the network: a stream raises `DEADLINE_EXCEEDED` at
227
+ the read after it, so messages that arrived together in one read can still
228
+ come past it. Cancelling the task that makes a call fails the call with
229
+ `CANCELED`, which an `except CallError` catches too unless it raises that code
230
+ again, and an exception the requests of a stream raise fails it with
231
+ `UNAVAILABLE`, that exception its `__cause__`.
232
+
227
233
  OpenAPI and GraphQL modules need httpx (`encore-dev[httpx]`), and gRPC modules
228
- connectrpc (`encore-dev[grpc]`, on Python 3.11 and later). A module is imported
229
- when first used, so a service needs only what the modules it uses need.
234
+ connectrpc and protobuf-py (`encore-dev[grpc]`, on Python 3.11 and later). A
235
+ module is imported when first used, so a service needs only what the modules it
236
+ uses need.
230
237
 
231
238
  ## Request Context
232
239
 
@@ -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,14 @@ 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.
226
234
  """
227
235
  first: List[float] = []
236
+ interrupts = _interrupts()
228
237
 
229
238
  def handle(signum: int) -> None:
230
239
  now = loop.time()
@@ -232,26 +241,68 @@ def _on_signals(
232
241
  first.append(now)
233
242
  stop.set()
234
243
  return
235
- if signum == signal.SIGINT and now - first[0] > _REPEAT_SECS:
244
+ if signum in interrupts and now - first[0] > _REPEAT_SECS:
236
245
  force.set()
237
246
 
238
- signals = [signal.SIGTERM, signal.SIGINT]
247
+ signals = [signal.SIGTERM, *interrupts]
239
248
  previous = {s: signal.getsignal(s) for s in signals}
240
249
  if threading.current_thread() is not threading.main_thread():
241
250
  return lambda: None
242
251
  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)
252
+ return _on_signals_windows(loop, signals, previous, handle)
253
+ for s in signals:
254
+ loop.add_signal_handler(s, handle, s)
255
+
256
+ def restore() -> None:
257
+ for s, handler in previous.items():
258
+ loop.remove_signal_handler(s)
259
+ signal.signal(s, handler)
260
+
261
+ return restore
262
+
263
+
264
+ def _interrupts() -> List[int]:
265
+ """The signals that interrupt: a second one, later, stops waiting for the app."""
266
+ if sys.platform == "win32":
267
+ return [signal.SIGINT, signal.SIGBREAK]
268
+ return [signal.SIGINT]
269
+
270
+
271
+ def _on_signals_windows(
272
+ loop: asyncio.AbstractEventLoop,
273
+ signals: List[int],
274
+ previous: Dict[int, Any],
275
+ handle: Callable[[int], None],
276
+ ) -> Callable[[], None]:
277
+ """Have ``handle`` take ``signals`` on ``loop``, on Windows.
278
+
279
+ A handler runs only once the main thread runs Python again, and on
280
+ Windows the loop waiting for its sockets is not woken by a signal: one
281
+ with nothing else to do would never stop. So each signal also writes to
282
+ a socket the loop watches, as the proactor loop does for itself.
283
+ """
284
+ wake, woken = socket.socketpair()
285
+ wake.setblocking(False)
286
+ woken.setblocking(False)
287
+
288
+ def drain() -> None:
289
+ try:
290
+ while woken.recv(4096):
291
+ pass
292
+ except (BlockingIOError, InterruptedError):
293
+ pass
294
+
295
+ loop.add_reader(woken.fileno(), drain)
296
+ wakeup = signal.set_wakeup_fd(wake.fileno(), warn_on_full_buffer=False)
297
+ for s in signals:
298
+ signal.signal(s, lambda signum, _: loop.call_soon_threadsafe(handle, signum))
250
299
 
251
300
  def restore() -> None:
252
301
  for s, handler in previous.items():
253
- if sys.platform != "win32":
254
- loop.remove_signal_handler(s)
255
302
  signal.signal(s, handler)
303
+ signal.set_wakeup_fd(wakeup)
304
+ loop.remove_reader(woken.fileno())
305
+ wake.close()
306
+ woken.close()
256
307
 
257
308
  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 = (
@@ -56,6 +56,153 @@ class BucketObject:
56
56
  class ByteRange:
57
57
  def __new__(cls, /, *, offset: int, length: int |None = None) -> "ByteRange": ...
58
58
 
59
+ @final
60
+ class ClickHouseAccess:
61
+ """
62
+ What a handle may do: which of the database's users its requests are
63
+ made as. A level without a user of its own uses the next one up, and
64
+ reads made so are kept read-only by setting.
65
+ """
66
+ Admin: Final[ClickHouseAccess]
67
+ Read: Final[ClickHouseAccess]
68
+ Write: Final[ClickHouseAccess]
69
+ def __eq__(self, value: object, /) -> bool: ...
70
+ def __int__(self, /) -> int: ...
71
+ def __ne__(self, value: object, /) -> bool: ...
72
+ def __repr__(self, /) -> str: ...
73
+
74
+ @final
75
+ class ClickHouseCursor:
76
+ """
77
+ A streaming query result. Its rows are read in batches; closing it, or
78
+ dropping it, stops a read-only query on the server.
79
+ """
80
+ def close(self, /) -> "typing.Awaitable[None]":
81
+ """
82
+ Close the cursor: a read-only query still running stops.
83
+
84
+ Returns:
85
+ An awaitable that completes once any active read finishes.
86
+ Repeated closes have no effect.
87
+ """
88
+ @property
89
+ def columns(self, /) -> list[tuple[str, str]]:
90
+ """
91
+ The result's columns: (name, ClickHouse type) pairs.
92
+ """
93
+ def next_batch(self, /, max: int) -> "typing.Awaitable[typing.Optional[list[dict[str, typing.Any]]]]":
94
+ """
95
+ Fetch the next rows.
96
+
97
+ Args:
98
+ max: The most rows to fetch.
99
+
100
+ Returns:
101
+ An awaitable that produces up to max dictionaries of column names
102
+ to values, or None once the rows are exhausted or the cursor
103
+ closed.
104
+
105
+ Raises:
106
+ DatabaseError: The server fails the query while sending its rows,
107
+ or they can't be decoded.
108
+ """
109
+ @property
110
+ def query_id(self, /) -> str:
111
+ """
112
+ The query's id on the server.
113
+ """
114
+
115
+ @final
116
+ class ClickHouseDatabase:
117
+ """
118
+ A handle to a ClickHouse database at an access level.
119
+ """
120
+ def conn_string(self, /) -> "str":
121
+ """
122
+ Return a URL to connect to the database with as the handle's user.
123
+
124
+ Returns:
125
+ `http[s]://user:password@host:port/database`.
126
+
127
+ Raises:
128
+ DatabaseError: The database is not configured, or has no user for
129
+ the handle's access level.
130
+ """
131
+ def exec(self, /, sql: str, params: Any |None = None, settings: Sequence[tuple[str, str]] |None = None, query_id: str |None = None, source: bytes |None = None) -> "typing.Awaitable[tuple[int, int, int, str]]":
132
+ """
133
+ Run a statement, discarding any rows it returns.
134
+
135
+ Args:
136
+ sql: The statement, its parameters named and typed in it as
137
+ `{name:Type}`.
138
+ params: The parameters' values, by name.
139
+ settings: Settings for this statement only, by name.
140
+ query_id: The statement's id on the server; None lets it choose one.
141
+ source: Encoded parent tracing context, or None when no context is active.
142
+
143
+ Returns:
144
+ An awaitable that produces the server's summary: (rows written,
145
+ bytes written, rows read, query id).
146
+
147
+ Raises:
148
+ DatabaseError: A parameter can't be sent, or the server can't be
149
+ reached or fails the statement.
150
+ """
151
+ def insert(self, /, table: str, rows: Any, settings: Sequence[tuple[str, str]] |None = None, source: bytes |None = None) -> "typing.Awaitable[tuple[int, int, int, str]]":
152
+ """
153
+ Insert rows into a table.
154
+
155
+ The columns are the union of the rows' keys, in the order first seen.
156
+ A column a row has no key for is sent as NULL, which a column that
157
+ isn't Nullable takes as its default. (The core's insert can't leave
158
+ a row's value out, which would give a Nullable column its DEFAULT.)
159
+
160
+ Args:
161
+ table: The table, as `table` or `database.table`.
162
+ rows: The rows: mappings of column names to values.
163
+ settings: Settings for this insert only, by name.
164
+ source: Encoded parent tracing context, or None when no context is active.
165
+
166
+ Returns:
167
+ An awaitable that produces the server's summary: (rows written,
168
+ bytes written, rows read, query id). No rows insert nothing, and
169
+ produce zeros.
170
+
171
+ Raises:
172
+ DatabaseError: A value can't be sent, the table name is invalid, or
173
+ the server can't be reached or fails the insert.
174
+ """
175
+ def query(self, /, sql: str, params: Any |None = None, settings: Sequence[tuple[str, str]] |None = None, query_id: str |None = None, source: bytes |None = None) -> "typing.Awaitable[ClickHouseCursor]":
176
+ """
177
+ Start a query and return an awaitable cursor over its rows.
178
+
179
+ Args:
180
+ sql: The query, its parameters named and typed in it as
181
+ `{name:Type}`.
182
+ params: The parameters' values, by name.
183
+ settings: Settings for this query only, by name.
184
+ query_id: The query's id on the server; None lets it choose one.
185
+ source: Encoded parent tracing context, or None when no context is active.
186
+
187
+ Returns:
188
+ An awaitable that produces a ClickHouseCursor once the server has
189
+ started sending rows.
190
+
191
+ Raises:
192
+ DatabaseError: A parameter can't be sent, or the server can't be
193
+ reached or fails the query.
194
+ """
195
+ def with_access(self, /, access: ClickHouseAccess) -> "ClickHouseDatabase":
196
+ """
197
+ Return a handle to the same database for another access level.
198
+
199
+ Args:
200
+ access: What the handle may do.
201
+
202
+ Returns:
203
+ A handle whose requests are made as that level's user.
204
+ """
205
+
59
206
  @final
60
207
  class Config:
61
208
  def current(self, /) -> "tuple[int, str]":
@@ -278,6 +425,13 @@ class HttpRequest:
278
425
  """
279
426
  `send_body`, waiting for room for the chunk.
280
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
+ """
281
435
  def span_add_event(self, /, name: str, attributes: Sequence[tuple[str, Any]] |None = None, timestamp_ns: int |None = None) -> "None":
282
436
  """
283
437
  Adds an event to the request's span.
@@ -306,9 +460,10 @@ class HttpRequest:
306
460
  Renames the request's span. The route the app matched names it again
307
461
  when the request finishes.
308
462
  """
309
- 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":
310
464
  """
311
- 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.
312
467
  """
313
468
  @property
314
469
  def started(self, /) -> bool:
@@ -1117,6 +1272,11 @@ class Runtime:
1117
1272
  """
1118
1273
  Wait until shutdown has reached or passed Cleanup. Call begin_shutdown first.
1119
1274
  """
1275
+ def clickhouse_database(self, /, name: str) -> "ClickHouseDatabase":
1276
+ """
1277
+ A write handle to the named ClickHouse database (looked up in the
1278
+ runtime config). One that isn't configured fails each call with why.
1279
+ """
1120
1280
  def completed(self, /) -> "typing.Awaitable[ShutdownResult]":
1121
1281
  """
1122
1282
  Wait for cleanup to finish, including after its deadline has elapsed.
@@ -1307,6 +1467,11 @@ class TestScope:
1307
1467
  span, as its 25-byte context and tracestate, where the process
1308
1468
  records spans. None for any other test.
1309
1469
  """
1470
+ def clickhouse_database(self, /, name: str) -> "ClickHouseDatabase":
1471
+ """
1472
+ The test's write handle on its instance of the ClickHouse database
1473
+ `name`. The instance is provisioned when the handle is first used.
1474
+ """
1310
1475
  def config(self, /, name: str) -> "typing.Optional[str]":
1311
1476
  """
1312
1477
  The value the test has given the config `name`, as `set_config`