encore-dev 2.0.0b8__tar.gz → 2.0.0b10__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.0b8/README.md → encore_dev-2.0.0b10/PKG-INFO +59 -4
  2. encore_dev-2.0.0b8/PKG-INFO → encore_dev-2.0.0b10/README.md +35 -27
  3. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/__init__.py +6 -0
  4. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/config/_build.py +6 -11
  5. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/cron/__init__.py +33 -3
  6. encore_dev-2.0.0b10/encore/django/__init__.py +56 -0
  7. encore_dev-2.0.0b10/encore/django/base.py +48 -0
  8. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/env/__init__.py +56 -14
  9. encore_dev-2.0.0b10/encore/frontends/__init__.py +49 -0
  10. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/gateway/__init__.py +3 -2
  11. encore_dev-2.0.0b10/encore/gateways/__init__.py +57 -0
  12. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/_loader.py +38 -3
  13. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/_native.pyi +221 -0
  14. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/clients.py +50 -9
  15. encore_dev-2.0.0b10/encore/internal/grpc.py +208 -0
  16. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/reqfields.py +14 -1
  17. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/testscope.py +115 -0
  18. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/pubsub/__init__.py +20 -7
  19. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/services/__init__.py +17 -3
  20. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/services/_propagate.py +35 -5
  21. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/services/httpx.py +51 -11
  22. encore_dev-2.0.0b10/encore/storage/__init__.py +5 -0
  23. encore_dev-2.0.0b10/encore/storage/clickhouse/__init__.py +654 -0
  24. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/hash.py +68 -27
  25. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/testing/__init__.py +53 -7
  26. encore_dev-2.0.0b10/encore/testing/_playwright_fixtures.py +147 -0
  27. encore_dev-2.0.0b10/encore/testing/_steps.py +216 -0
  28. encore_dev-2.0.0b10/encore/testing/playwright.py +369 -0
  29. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/testing/pytest_plugin.py +56 -5
  30. encore_dev-2.0.0b10/encore/testing/system.py +881 -0
  31. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/tracing/_context.py +28 -3
  32. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/pyproject.toml +9 -5
  33. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/pyproject.toml.orig +17 -8
  34. encore_dev-2.0.0b8/encore/storage/__init__.py +0 -5
  35. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/_run.py +0 -0
  36. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/config/__init__.py +0 -0
  37. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/config/_markers.py +0 -0
  38. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/errs/__init__.py +0 -0
  39. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/gateway/_serve.py +0 -0
  40. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/gateway/match.py +0 -0
  41. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/__init__.py +0 -0
  42. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/lazy.py +0 -0
  43. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/runtime.py +0 -0
  44. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/internal/startup.py +0 -0
  45. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/logs/__init__.py +0 -0
  46. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/logs/_api.py +0 -0
  47. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/logs/_console.py +0 -0
  48. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/logs/_runtime.py +0 -0
  49. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/metrics/__init__.py +0 -0
  50. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/metrics/_instrument.py +0 -0
  51. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/metrics/_metrics.py +0 -0
  52. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/metrics/_provider.py +0 -0
  53. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/py.typed +0 -0
  54. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/reqctx/__init__.py +0 -0
  55. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/reqctx/_json.py +0 -0
  56. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/secrets/__init__.py +0 -0
  57. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/server/__init__.py +0 -0
  58. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/server/_serve.py +0 -0
  59. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/server/_span.py +0 -0
  60. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/server/_tracing.py +0 -0
  61. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/server/asgi.py +0 -0
  62. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/server/wsgi.py +0 -0
  63. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/services/aiohttp.py +0 -0
  64. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/services/niquests.py +0 -0
  65. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/services/requests.py +0 -0
  66. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/shutdown/__init__.py +0 -0
  67. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/objects/__init__.py +0 -0
  68. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/postgres/__init__.py +0 -0
  69. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/__init__.py +0 -0
  70. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/_base.py +0 -0
  71. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/_batch.py +0 -0
  72. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/_errors.py +0 -0
  73. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/_responses.py +0 -0
  74. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/_scan.py +0 -0
  75. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/_values.py +0 -0
  76. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/bitmap.py +0 -0
  77. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/command.py +0 -0
  78. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/generic.py +0 -0
  79. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/geo.py +0 -0
  80. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/hyperloglog.py +0 -0
  81. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/json.py +0 -0
  82. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/list.py +0 -0
  83. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/pubsub.py +0 -0
  84. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/script.py +0 -0
  85. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/set.py +0 -0
  86. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/sorted_set.py +0 -0
  87. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/stream.py +0 -0
  88. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/storage/redis/string.py +0 -0
  89. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/tracing/__init__.py +0 -0
  90. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/tracing/_encode.py +0 -0
  91. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/tracing/_provider.py +0 -0
  92. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/tracing/_span.py +0 -0
  93. {encore_dev-2.0.0b8 → encore_dev-2.0.0b10}/encore/tracing/_tracer.py +0 -0
@@ -1,3 +1,27 @@
1
+ Metadata-Version: 2.3
2
+ Name: encore-dev
3
+ Version: 2.0.0b10
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**.
@@ -187,7 +211,9 @@ its `code` is the `ErrCode` the service answered with, or the one its HTTP
187
211
  status means; `UNAVAILABLE` when no answer came, and `DEADLINE_EXCEEDED` when
188
212
  the call took longer than its timeout. `message` says what went wrong, and
189
213
  `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.
214
+ `GraphQLRequestError`, whose `errors` are the answer's, and a gRPC status's
215
+ details are its `details`, each its protobuf-py message, or the
216
+ `protobuf.wkt.Any` it came as, for a type the client's protos lack.
191
217
 
192
218
  ```python
193
219
  from encore.errs import ErrCode
@@ -201,9 +227,36 @@ except CallError as error:
201
227
  product = None
202
228
  ```
203
229
 
230
+ A gRPC module speaks the gRPC protocol over HTTP/2, with connectrpc, so it
231
+ calls any gRPC server: h2c to an `http://` URL, TLS to an `https://` one,
232
+ trusting the system's certificates and those `SSL_CERT_FILE` and
233
+ `SSL_CERT_DIR` name. A server or bidi stream is an async iterator, and a client
234
+ or bidi stream takes an async iterable of requests. Its messages are
235
+ protobuf-py's, which `protoc-gen-py` generates into `encore_gen/protos/`, a
236
+ module per `.proto` file that every client of the service shares; the gRPC
237
+ module has the top-level messages and enums of the service's protos as its
238
+ own, and the well-known types its RPCs take and return.
239
+
240
+ ```python
241
+ async for update in catalog.grpc.stuff_service.watch_stuff(
242
+ catalog.grpc.WatchRequest(), timeout=30.0
243
+ ):
244
+ print(update)
245
+ ```
246
+
247
+ A gRPC call behaves as connectrpc makes it, which `CallError` only carries
248
+ the code of. Its timeout is its deadline, which the service is told, and which
249
+ applies to each read from the network: a stream raises `DEADLINE_EXCEEDED` at
250
+ the read after it, so messages that arrived together in one read can still
251
+ come past it. Cancelling the task that makes a call fails the call with
252
+ `CANCELED`, which an `except CallError` catches too unless it raises that code
253
+ again, and an exception the requests of a stream raise fails it with
254
+ `UNAVAILABLE`, that exception its `__cause__`.
255
+
204
256
  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.
257
+ connectrpc and protobuf-py (`encore-dev[grpc]`, on Python 3.11 and later). A
258
+ module is imported when first used, so a service needs only what the modules it
259
+ uses need.
207
260
 
208
261
  ## Request Context
209
262
 
@@ -1055,7 +1108,9 @@ The same conversion applies to list elements, hash values, set/sorted-set/geo
1055
1108
  members, stream field values, and pubsub payloads. For pubsub, use `subscribe[User](...)`
1056
1109
  or `psubscribe[User](...)`; `Message.payload` then has that type.
1057
1110
  Database keys, hash/stream field names, stream IDs, channel names, cursors,
1058
- scores, and other metadata retain their existing types. A custom value class
1111
+ scores, and other metadata retain their existing types. Where hash field names
1112
+ are what a command returns (`hkeys`, and `hrandfield` without values), they
1113
+ are its values: `hkeys[str]` reads them as `str`. A custom value class
1059
1114
  is not recorded in Redis: callers must choose the matching decoder.
1060
1115
 
1061
1116
  Missing values remain `None`, and empty collections remain empty. Malformed
@@ -1,26 +1,3 @@
1
- Metadata-Version: 2.3
2
- Name: encore-dev
3
- Version: 2.0.0b8
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**.
@@ -210,7 +187,9 @@ its `code` is the `ErrCode` the service answered with, or the one its HTTP
210
187
  status means; `UNAVAILABLE` when no answer came, and `DEADLINE_EXCEEDED` when
211
188
  the call took longer than its timeout. `message` says what went wrong, and
212
189
  `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.
190
+ `GraphQLRequestError`, whose `errors` are the answer's, and a gRPC status's
191
+ details are its `details`, each its protobuf-py message, or the
192
+ `protobuf.wkt.Any` it came as, for a type the client's protos lack.
214
193
 
215
194
  ```python
216
195
  from encore.errs import ErrCode
@@ -224,9 +203,36 @@ except CallError as error:
224
203
  product = None
225
204
  ```
226
205
 
206
+ A gRPC module speaks the gRPC protocol over HTTP/2, with connectrpc, so it
207
+ calls any gRPC server: h2c to an `http://` URL, TLS to an `https://` one,
208
+ trusting the system's certificates and those `SSL_CERT_FILE` and
209
+ `SSL_CERT_DIR` name. A server or bidi stream is an async iterator, and a client
210
+ or bidi stream takes an async iterable of requests. Its messages are
211
+ protobuf-py's, which `protoc-gen-py` generates into `encore_gen/protos/`, a
212
+ module per `.proto` file that every client of the service shares; the gRPC
213
+ module has the top-level messages and enums of the service's protos as its
214
+ own, and the well-known types its RPCs take and return.
215
+
216
+ ```python
217
+ async for update in catalog.grpc.stuff_service.watch_stuff(
218
+ catalog.grpc.WatchRequest(), timeout=30.0
219
+ ):
220
+ print(update)
221
+ ```
222
+
223
+ A gRPC call behaves as connectrpc makes it, which `CallError` only carries
224
+ the code of. Its timeout is its deadline, which the service is told, and which
225
+ applies to each read from the network: a stream raises `DEADLINE_EXCEEDED` at
226
+ the read after it, so messages that arrived together in one read can still
227
+ come past it. Cancelling the task that makes a call fails the call with
228
+ `CANCELED`, which an `except CallError` catches too unless it raises that code
229
+ again, and an exception the requests of a stream raise fails it with
230
+ `UNAVAILABLE`, that exception its `__cause__`.
231
+
227
232
  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.
233
+ connectrpc and protobuf-py (`encore-dev[grpc]`, on Python 3.11 and later). A
234
+ module is imported when first used, so a service needs only what the modules it
235
+ uses need.
230
236
 
231
237
  ## Request Context
232
238
 
@@ -1078,7 +1084,9 @@ The same conversion applies to list elements, hash values, set/sorted-set/geo
1078
1084
  members, stream field values, and pubsub payloads. For pubsub, use `subscribe[User](...)`
1079
1085
  or `psubscribe[User](...)`; `Message.payload` then has that type.
1080
1086
  Database keys, hash/stream field names, stream IDs, channel names, cursors,
1081
- scores, and other metadata retain their existing types. A custom value class
1087
+ scores, and other metadata retain their existing types. Where hash field names
1088
+ are what a command returns (`hkeys`, and `hrandfield` without values), they
1089
+ are its values: `hkeys[str]` reads them as `str`. A custom value class
1082
1090
  is not recorded in Redis: callers must choose the matching decoder.
1083
1091
 
1084
1092
  Missing values remain `None`, and empty collections remain empty. Malformed
@@ -52,7 +52,9 @@ if TYPE_CHECKING or "_pytest" not in sys.modules:
52
52
  cron,
53
53
  env,
54
54
  errs,
55
+ frontends,
55
56
  gateway,
57
+ gateways,
56
58
  logs,
57
59
  metrics,
58
60
  pubsub,
@@ -78,7 +80,9 @@ __all__ = [
78
80
  "cron",
79
81
  "env",
80
82
  "errs",
83
+ "frontends",
81
84
  "gateway",
85
+ "gateways",
82
86
  "logs",
83
87
  "metrics",
84
88
  "reqctx",
@@ -100,7 +104,9 @@ _SUBMODULES = {
100
104
  "cron",
101
105
  "env",
102
106
  "errs",
107
+ "frontends",
103
108
  "gateway",
109
+ "gateways",
104
110
  "logs",
105
111
  "metrics",
106
112
  "pubsub",
@@ -21,7 +21,9 @@ import typing_extensions
21
21
 
22
22
  from ..secrets import Secret, _config_field
23
23
 
24
- #: The key of the placeholder a secret field's value is, as the runtime puts it.
24
+ #: The key of the placeholder a secret field's value is, as the runtime puts it:
25
+ #: ``{"$encore_secret": "<name>"}``. The name alone says which secret it is: a
26
+ #: secret's name has one scope across the app.
25
27
  PLACEHOLDER_KEY = "$encore_secret"
26
28
 
27
29
  _UNION_TYPES: Tuple[Any, ...] = (Union,)
@@ -185,18 +187,11 @@ class _Builder:
185
187
  raise self.fail(path, "matches none of the union's types")
186
188
 
187
189
  def secret(self, data: Any, path: List[str]) -> Any:
188
- placeholder = data.get(PLACEHOLDER_KEY) if isinstance(data, dict) else None
189
- if not isinstance(placeholder, dict):
190
+ name = data.get(PLACEHOLDER_KEY) if isinstance(data, dict) else None
191
+ if not isinstance(name, str) or not name or len(data) != 1:
190
192
  # Never say what the value is: it may be a pasted secret.
191
193
  raise self.fail(path, "is a secret field without the runtime's placeholder")
192
- # The placeholder's scope is the config's. The secret is read by name
193
- # alone, but a scope the runtime does not know means a mismatch.
194
- scope = placeholder.get("scope")
195
- if scope not in ("service", "shared", "global"):
196
- raise self.fail(
197
- path, "is a secret field with a placeholder of no known scope"
198
- )
199
- return _config_field(placeholder["name"])
194
+ return _config_field(name)
200
195
 
201
196
  def dataclass(
202
197
  self,
@@ -4,18 +4,20 @@ Typical usage example:
4
4
 
5
5
  from encore import cron
6
6
 
7
- _ = cron.Job("cleanup", path="/internal/cleanup", title="Nightly cleanup", every="24h")
7
+ CLEANUP = cron.Job("cleanup", path="/internal/cleanup", title="Nightly cleanup", every="24h")
8
8
 
9
9
  A cron job is a parse-time declaration: the parser discovers it and, when the
10
10
  job is due, the platform sends a ``POST`` request for ``path`` to the service
11
- that declares the job. There is no runtime client.
11
+ that declares the job. There is no runtime client. A job keeps what it was
12
+ declared with, to read but not change: declare its route from ``path``, so
13
+ the route is always the one Encore requests.
12
14
 
13
15
  The request carries an idempotency key in ``IDEMPOTENCY_KEY_HEADER``: an id
14
16
  for the run that is the same each time Encore sends it, as when it sends it
15
17
  again after a failure. A job that must not do its work twice can check
16
18
  whether it has seen the key before::
17
19
 
18
- @app.post("/internal/cleanup")
20
+ @app.post(CLEANUP.path)
19
21
  async def cleanup(request: Request) -> None:
20
22
  key = request.headers.get(cron.IDEMPOTENCY_KEY_HEADER)
21
23
  ...
@@ -81,3 +83,31 @@ class Job:
81
83
  self._title = title
82
84
  self._every = every
83
85
  self._schedule = schedule
86
+
87
+ # Read-only: Encore schedules the job from its declaration in the source,
88
+ # so a changed path would not be the one it requests.
89
+
90
+ @property
91
+ def name(self) -> str:
92
+ """The cron job's resource name."""
93
+ return self._name
94
+
95
+ @property
96
+ def path(self) -> str:
97
+ """The service path Encore calls with POST when the job is due."""
98
+ return self._path
99
+
100
+ @property
101
+ def title(self) -> str | None:
102
+ """The human-readable title, if one was declared."""
103
+ return self._title
104
+
105
+ @property
106
+ def every(self) -> str | None:
107
+ """The interval between calls, such as "24h", if declared with one."""
108
+ return self._every
109
+
110
+ @property
111
+ def schedule(self) -> str | None:
112
+ """The cron expression, if declared with one."""
113
+ return self._schedule
@@ -0,0 +1,56 @@
1
+ """Django's database backend for an Encore database.
2
+
3
+ Point a Django database at one of the app's databases with :func:`database`::
4
+
5
+ from encore.django import database
6
+ from storage.resources import db
7
+
8
+ DATABASES = {"default": database(db.write())}
9
+
10
+ Django then connects to it as it connects to any PostgreSQL database, with
11
+ psycopg, but finds where it is when it connects rather than when the
12
+ settings are read. Under ``encore test`` each test has a database of its
13
+ own, which only exists once the test has begun: a connection is to the
14
+ database of the test it is opened in, and a connection a test before it
15
+ opened is closed and opened again.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import threading
21
+ from typing import Any
22
+
23
+ from ..storage.postgres import DatabaseRef
24
+
25
+ _lock = threading.Lock()
26
+ # The databases settings name, by the NAME they have there.
27
+ _databases: dict[str, DatabaseRef] = {}
28
+
29
+
30
+ def database(ref: DatabaseRef, **settings: Any) -> dict[str, Any]:
31
+ """Return the settings of a Django database that is ``ref``'s.
32
+
33
+ Args:
34
+ ref: A handle of the database, from its ``write()`` or ``read()``,
35
+ which grants the service the access it gives.
36
+ **settings: Further Django settings of the database, such as
37
+ ``CONN_MAX_AGE`` or ``OPTIONS``.
38
+
39
+ Returns:
40
+ An entry of ``DATABASES``.
41
+ """
42
+ with _lock:
43
+ name = f"encore-{len(_databases)}"
44
+ _databases[name] = ref
45
+ return {**settings, "ENGINE": "encore.django", "NAME": name}
46
+
47
+
48
+ def _database(name: str) -> DatabaseRef:
49
+ """The database :func:`database` gave the settings NAME ``name``."""
50
+ try:
51
+ return _databases[name]
52
+ except KeyError:
53
+ raise LookupError(
54
+ f"no Encore database is named {name!r} in Django's settings: give "
55
+ "it with encore.django.database(db.write()) rather than by hand"
56
+ ) from None
@@ -0,0 +1,48 @@
1
+ """The backend Django loads for ``"ENGINE": "encore.django"``.
2
+
3
+ Django's PostgreSQL backend, connecting where the Encore database is.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Optional
9
+
10
+ from django.db.backends.postgresql import base
11
+ from psycopg.conninfo import conninfo_to_dict
12
+
13
+ from ..internal import testscope
14
+ from . import _database
15
+
16
+
17
+ class DatabaseWrapper(base.DatabaseWrapper):
18
+ """A connection to an Encore database, through the runtime's proxy."""
19
+
20
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
21
+ """Make the connection, as Django's PostgreSQL backend does."""
22
+ super().__init__(*args, **kwargs)
23
+ # The test the connection was opened in, if any.
24
+ self._encore_test: Optional[testscope.Scope] = None
25
+
26
+ def get_connection_params(self) -> dict[str, Any]:
27
+ """Django's parameters, connecting where the Encore database is.
28
+
29
+ In place of the NAME the settings give it: under test, the test's own.
30
+ """
31
+ params = super().get_connection_params()
32
+ ref = _database(self.settings_dict["NAME"])
33
+ params.update(conninfo_to_dict(ref.connection_string))
34
+ return params
35
+
36
+ def connect(self) -> None:
37
+ """Connect, in the test the call belongs to, if any."""
38
+ # Before connecting, which runs queries of its own.
39
+ self._encore_test = testscope.current()
40
+ super().connect()
41
+
42
+ def ensure_connection(self) -> None:
43
+ """Connect if not connected, or connected for another test."""
44
+ # Django keeps a thread's connection from one test to the next; this
45
+ # test's database is another.
46
+ if self.connection is not None and self._encore_test is not testscope.current():
47
+ self.close()
48
+ super().ensure_connection()
@@ -1,4 +1,4 @@
1
- """Metadata for the running application and its API gateways.
1
+ """Metadata for the running application, its API gateways and frontends.
2
2
 
3
3
  Typical usage example:
4
4
 
@@ -11,7 +11,7 @@ Typical usage example:
11
11
  # An app can declare several gateways, so look one up by name.
12
12
  gw = md.gateways.get("api")
13
13
  if gw is not None:
14
- print("api is at", gw.base_url)
14
+ print("api is at", gw.url)
15
15
  """
16
16
 
17
17
  from __future__ import annotations
@@ -28,6 +28,7 @@ __all__ = [
28
28
  "app_meta",
29
29
  "AppMeta",
30
30
  "GatewayMeta",
31
+ "FrontendMeta",
31
32
  "EnvironmentMeta",
32
33
  "BuildMeta",
33
34
  "DeployMeta",
@@ -41,20 +42,41 @@ class GatewayMeta:
41
42
 
42
43
  Attributes:
43
44
  name: The name of the gateway, as declared by the application.
44
- base_url: The base URL which can be used to call the API of this running
45
- application through this gateway.
45
+ url: The URL the API of this running application is called at through
46
+ this gateway: the first of its origins. Empty when the environment
47
+ gives the gateway no origins.
48
+ origins: Every origin the gateway is reached at in this environment
49
+ (``scheme://host[:port]``), the first its URL. After the first, an
50
+ entry may be a pattern of one, ``https://*.example.com``, or
51
+ ``*``, which makes the gateway the one serving requests no other
52
+ origin matches.
53
+ """
54
+
55
+ name: str
56
+
57
+ url: str
58
+
59
+ origins: List[str] = field(default_factory=list)
60
+
46
61
 
47
- For local development it is ``http://localhost:<port>``, typically
48
- ``http://localhost:4000``.
62
+ @dataclass(frozen=True)
63
+ class FrontendMeta:
64
+ """A frontend of the application, and where it is reached.
49
65
 
50
- If a custom domain is used for this environment it is returned here,
51
- but note that changes only take effect at the time of deployment
52
- while custom domains can be updated at any time.
66
+ Attributes:
67
+ name: The name of the frontend: for one a service hosts, the
68
+ service's.
69
+ url: The URL the frontend is reached at: the first of its origins.
70
+ origins: Every origin the frontend is reached at in this environment,
71
+ the first its URL; after the first, an entry may be a pattern of
72
+ one, ``https://*.example.com``.
53
73
  """
54
74
 
55
75
  name: str
56
76
 
57
- base_url: str
77
+ url: str
78
+
79
+ origins: List[str] = field(default_factory=list)
58
80
 
59
81
 
60
82
  @dataclass(frozen=True)
@@ -138,12 +160,20 @@ class AppMeta:
138
160
 
139
161
  Distinct from :attr:`app_id`: the id is opaque and stable, the slug
140
162
  is readable and may be renamed. Locally the two are the same.
141
- gateways: The API gateways that serve this application, keyed by gateway
142
- name.
163
+ gateways: The API gateways of this application the service is given,
164
+ keyed by gateway name: those its code looks up the URL of, and the
165
+ one it hosts.
143
166
 
144
167
  An application can declare several gateways, so there is no single
145
168
  base URL for the API — look up the gateway you mean by name. A
146
- process that serves no gateway (a worker) reports an empty mapping.
169
+ service's processes, its Workers' included, list the gateways its
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.
173
+ frontends: The application's frontends the service is given — those
174
+ its code looks up the URL of (``frontends.url("web")``), and the
175
+ one it hosts — keyed by name, with where each is reached. One the
176
+ environment gives no origins is left out.
147
177
  environment: The environment the app is running in.
148
178
  build: The build the running binary came from.
149
179
  deploy: This deployment of the binary.
@@ -155,6 +185,8 @@ class AppMeta:
155
185
 
156
186
  gateways: Dict[str, GatewayMeta]
157
187
 
188
+ frontends: Dict[str, FrontendMeta]
189
+
158
190
  environment: EnvironmentMeta
159
191
 
160
192
  build: BuildMeta
@@ -187,10 +219,20 @@ def _decode(raw: dict) -> AppMeta:
187
219
  app_slug=raw.get("app_slug", ""),
188
220
  gateways={
189
221
  name: GatewayMeta(
190
- name=gw.get("name", name), base_url=gw.get("base_url", "")
222
+ name=gw.get("name", name),
223
+ url=gw.get("url", ""),
224
+ origins=list(gw.get("origins") or []),
191
225
  )
192
226
  for name, gw in (raw.get("gateways") or {}).items()
193
227
  },
228
+ frontends={
229
+ name: FrontendMeta(
230
+ name=fe.get("name", name),
231
+ url=fe.get("url", ""),
232
+ origins=list(fe.get("origins") or []),
233
+ )
234
+ for name, fe in (raw.get("frontends") or {}).items()
235
+ },
194
236
  environment=EnvironmentMeta(
195
237
  name=env.get("name", ""),
196
238
  type=env.get("type", "development"),
@@ -0,0 +1,49 @@
1
+ """Where the application's frontends are reached.
2
+
3
+ :func:`url` is a frontend's URL in the environment the code runs in, as to
4
+ send a user there or to build a link to one of its pages::
5
+
6
+ from encore import frontends
7
+
8
+ reset = f"{frontends.url('web')}/reset?token={token}"
9
+
10
+ Looking a frontend's URL up links the calling service to it. Encore reads the
11
+ link from the code, as it reads which services a service depends on: so the
12
+ name must be a string literal, written as the frontend declares it, the
13
+ function must be called directly rather than passed around, and the call must
14
+ be in a service.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from .. import env
20
+
21
+ __all__ = ["url"]
22
+
23
+
24
+ def url(frontend: str) -> str:
25
+ """Return the URL a frontend is reached at, without a trailing slash.
26
+
27
+ It is the first of the frontend's origins in this environment, as
28
+ :func:`encore.env.app_meta` lists them. The name is the one the frontend is
29
+ declared with, in its ``encore.frontend.json`` or as the service hosting
30
+ it: ``web_app`` does not find ``web-app``.
31
+
32
+ Args:
33
+ frontend: The name of the frontend to look up.
34
+
35
+ Returns:
36
+ The frontend's URL, with no trailing ``/``.
37
+
38
+ Raises:
39
+ ValueError: If the app has no frontend of that name, or the
40
+ environment gives it no origins.
41
+ """
42
+ fe = env.app_meta().frontends.get(frontend)
43
+ found = fe.origins[0].rstrip("/") if fe is not None and fe.origins else ""
44
+ if not found:
45
+ raise ValueError(
46
+ f"encore: no URL is known for frontend {frontend!r}: the app has no "
47
+ "frontend of that name, or the environment gives it no origins"
48
+ )
49
+ return found
@@ -69,8 +69,9 @@ Hooks:
69
69
  cookies; each reaches Python only as the hook reads it.
70
70
 
71
71
  Middleware see only public requests the gateway routes: calls between
72
- services, Pub/Sub pushes, CORS preflights and requests for paths the
73
- gateway does not expose are Encore's alone.
72
+ services, Pub/Sub pushes and requests for paths the gateway does not
73
+ expose are Encore's alone, and so are CORS preflights, but for a gateway
74
+ whose CORS is off (``"cors": false``), which routes them as any request.
74
75
 
75
76
  Answering a request:
76
77
  ``on_request`` returns to let the request through, or raises a
@@ -0,0 +1,57 @@
1
+ """Where the application's gateways are reached.
2
+
3
+ :func:`url` is a gateway's URL in the environment the code runs in, as to
4
+ hand a client outside the app the address of its API::
5
+
6
+ from encore import gateways
7
+
8
+ callback = f"{gateways.url('api')}/webhooks/stripe"
9
+
10
+ A service calls the app's other services with :mod:`encore.services`, not
11
+ through a gateway. A gateway's Middleware is :mod:`encore.gateway`'s.
12
+
13
+ Looking a gateway's URL up links the calling service to it. Encore reads the
14
+ link from the code, as it reads which services a service depends on: so the
15
+ name must be a string literal, written as the gateway declares it, the
16
+ function must be called directly rather than passed around, and the call must
17
+ be in a service.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from .. import env
23
+
24
+ __all__ = ["url"]
25
+
26
+
27
+ def url(gateway: str) -> str:
28
+ """Return the URL a gateway is reached at, without a trailing slash.
29
+
30
+ It is the first of the gateway's origins in this environment, as
31
+ :func:`encore.env.app_meta` lists them. The name is the one the gateway is
32
+ declared with, in its ``encore.gateway.json`` or as the service hosting
33
+ it: ``public_api`` does not find ``public-api``.
34
+
35
+ Args:
36
+ gateway: The name of the gateway to look up.
37
+
38
+ Returns:
39
+ The gateway's URL, with no trailing ``/``.
40
+
41
+ Raises:
42
+ ValueError: If the app has no gateway of that name, or the
43
+ environment gives it no origins.
44
+ """
45
+ gw = env.app_meta().gateways.get(gateway)
46
+ if gw is None:
47
+ raise ValueError(
48
+ f"encore: no URL is known for gateway {gateway!r}: the app has no gateway "
49
+ "of that name"
50
+ )
51
+ found = gw.origins[0].rstrip("/") if gw.origins else ""
52
+ if not found:
53
+ raise ValueError(
54
+ f"encore: no URL is known for gateway {gateway!r}: the environment gives "
55
+ "it no origins"
56
+ )
57
+ return found