encore-dev 2.0.0b7__tar.gz → 2.0.0b8__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 (90) hide show
  1. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/PKG-INFO +315 -47
  2. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/README.md +310 -45
  3. encore_dev-2.0.0b8/encore/__init__.py +140 -0
  4. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/_run.py +15 -13
  5. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/config/__init__.py +85 -78
  6. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/config/_build.py +7 -12
  7. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/cron/__init__.py +33 -0
  8. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/env/__init__.py +7 -0
  9. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/_loader.py +27 -3
  10. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/_native.pyi +318 -22
  11. encore_dev-2.0.0b8/encore/internal/clients.py +318 -0
  12. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/reqfields.py +6 -4
  13. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/runtime.py +7 -1
  14. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/startup.py +6 -0
  15. encore_dev-2.0.0b8/encore/internal/testscope.py +254 -0
  16. encore_dev-2.0.0b8/encore/logs/__init__.py +63 -0
  17. encore_dev-2.0.0b8/encore/logs/_api.py +163 -0
  18. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/logs/_console.py +4 -4
  19. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/metrics/__init__.py +45 -56
  20. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/metrics/_metrics.py +80 -116
  21. encore_dev-2.0.0b8/encore/pubsub/__init__.py +944 -0
  22. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/reqctx/__init__.py +19 -13
  23. encore_dev-2.0.0b8/encore/secrets/__init__.py +198 -0
  24. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/server/_serve.py +6 -8
  25. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/server/_tracing.py +0 -16
  26. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/server/asgi.py +4 -7
  27. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/server/wsgi.py +4 -6
  28. encore_dev-2.0.0b8/encore/services/__init__.py +212 -0
  29. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/services/_propagate.py +14 -3
  30. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/services/aiohttp.py +20 -3
  31. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/services/httpx.py +22 -3
  32. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/services/niquests.py +21 -3
  33. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/services/requests.py +56 -6
  34. encore_dev-2.0.0b8/encore/storage/objects/__init__.py +1243 -0
  35. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/postgres/__init__.py +401 -46
  36. encore_dev-2.0.0b8/encore/storage/redis/__init__.py +589 -0
  37. encore_dev-2.0.0b8/encore/storage/redis/_batch.py +219 -0
  38. encore_dev-2.0.0b8/encore/storage/redis/_errors.py +46 -0
  39. encore_dev-2.0.0b8/encore/storage/redis/_scan.py +37 -0
  40. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/bitmap.py +78 -0
  41. encore_dev-2.0.0b8/encore/storage/redis/command.py +72 -0
  42. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/generic.py +33 -0
  43. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/hash.py +10 -0
  44. encore_dev-2.0.0b8/encore/storage/redis/hyperloglog.py +67 -0
  45. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/list.py +140 -1
  46. encore_dev-2.0.0b8/encore/storage/redis/script.py +139 -0
  47. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/set.py +10 -0
  48. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/sorted_set.py +109 -1
  49. encore_dev-2.0.0b8/encore/testing/__init__.py +401 -0
  50. encore_dev-2.0.0b8/encore/testing/pytest_plugin.py +105 -0
  51. encore_dev-2.0.0b8/encore/tracing/__init__.py +74 -0
  52. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/pyproject.toml +12 -2
  53. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/pyproject.toml.orig +20 -2
  54. encore_dev-2.0.0b7/encore/__init__.py +0 -72
  55. encore_dev-2.0.0b7/encore/logs/__init__.py +0 -19
  56. encore_dev-2.0.0b7/encore/pubsub/__init__.py +0 -476
  57. encore_dev-2.0.0b7/encore/secrets/__init__.py +0 -202
  58. encore_dev-2.0.0b7/encore/services/__init__.py +0 -54
  59. encore_dev-2.0.0b7/encore/storage/objects/__init__.py +0 -396
  60. encore_dev-2.0.0b7/encore/storage/redis/__init__.py +0 -200
  61. encore_dev-2.0.0b7/encore/tracing/__init__.py +0 -27
  62. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/config/_markers.py +0 -0
  63. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/errs/__init__.py +0 -0
  64. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/gateway/__init__.py +0 -0
  65. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/gateway/_serve.py +0 -0
  66. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/gateway/match.py +0 -0
  67. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/__init__.py +0 -0
  68. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/internal/lazy.py +0 -0
  69. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/logs/_runtime.py +0 -0
  70. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/metrics/_instrument.py +0 -0
  71. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/metrics/_provider.py +0 -0
  72. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/py.typed +0 -0
  73. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/reqctx/_json.py +0 -0
  74. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/server/__init__.py +0 -0
  75. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/server/_span.py +0 -0
  76. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/shutdown/__init__.py +0 -0
  77. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/__init__.py +0 -0
  78. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/_base.py +0 -0
  79. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/_responses.py +0 -0
  80. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/_values.py +0 -0
  81. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/geo.py +0 -0
  82. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/json.py +0 -0
  83. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/pubsub.py +0 -0
  84. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/stream.py +0 -0
  85. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/storage/redis/string.py +0 -0
  86. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/tracing/_context.py +0 -0
  87. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/tracing/_encode.py +0 -0
  88. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/tracing/_provider.py +0 -0
  89. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/tracing/_span.py +0 -0
  90. {encore_dev-2.0.0b7 → encore_dev-2.0.0b8}/encore/tracing/_tracer.py +0 -0
@@ -1,18 +1,21 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: encore-dev
3
- Version: 2.0.0b7
3
+ Version: 2.0.0b8
4
4
  Summary: Encore SDK for Python — infrastructure resources
5
5
  Author: Encore
6
6
  License: MPL-2.0
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Requires-Dist: opentelemetry-api>=1.27
9
- Requires-Dist: typing-extensions>=4.12
9
+ Requires-Dist: typing-extensions>=4.13
10
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'
11
13
  Requires-Dist: httpx>=0.27 ; extra == 'httpx'
12
14
  Requires-Dist: niquests>=3.19 ; extra == 'niquests'
13
15
  Requires-Dist: requests>=2.34 ; python_full_version >= '3.10' and extra == 'requests'
14
16
  Requires-Python: >=3.9
15
17
  Provides-Extra: aiohttp
18
+ Provides-Extra: grpc
16
19
  Provides-Extra: httpx
17
20
  Provides-Extra: niquests
18
21
  Provides-Extra: requests
@@ -62,26 +65,26 @@ async def place_order(order):
62
65
 
63
66
  ## Secrets
64
67
 
65
- `secrets.Secret[T]("Name")` belongs to the service that declares it.
66
- `secrets.SharedSecret[T]("Name")` is one secret for the whole app, given to the
67
- services that read it, and `secrets.GlobalSecret[T]("Name")` one that every
68
- service is given. `T` is `str` or `bytes`, and `value` reads the secret decoded
69
- as that.
68
+ `secrets.Secret[str]("Name")` belongs to the service that declares it.
69
+ `secrets.Secret[str]("Name", scope="shared")` is one secret for the whole app,
70
+ 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.
70
74
 
71
75
  A shared secret is declared once in the app. Another Python service can't
72
76
  import the declaring service's modules, so it references the secret by name
73
77
  instead:
74
78
 
75
79
  ```python
76
- from encore.secrets import SharedSecret
80
+ from encore.secrets import Secret
77
81
 
78
- support_email = SharedSecret[str].named("SupportEmail")
82
+ support_email = Secret[str].named("SupportEmail")
79
83
  ```
80
84
 
81
85
  Reading `value` makes the service one the secret is given to. The declaration
82
- can be in any language, and the type argument is how this service decodes the
83
- value, whatever the declaration's. Encore reports a reference to a name that
84
- isn't declared as a shared secret.
86
+ can be in any language. Encore reports a reference to a name that isn't
87
+ declared as a shared secret.
85
88
 
86
89
  ## Service URLs
87
90
 
@@ -130,9 +133,12 @@ The `requests` and `aiohttp` extras need Python 3.10: on 3.9 they install
130
133
  nothing, as their releases for 3.9 have known vulnerabilities, and the adapters
131
134
  use the client the app installed.
132
135
 
133
- A generated client takes an `httpx.Client` as its `http_client`, so give it
134
- `sync_client`. Their other arguments go to the client's constructor, as keywords. The same
135
- rules as `base_url` apply to the service's name. aiohttp joins relative URLs as
136
+ `client` and `sync_client` pass their other arguments to the client's
137
+ constructor, as keywords. A `requests.Session` takes none, so the requests
138
+ adapter's `client` sets them on the session instead, as
139
+ `client("billing", headers={"x-tenant": "a"}, verify=False)`, and takes a
140
+ `timeout` for each request that sets none. The same rules as `base_url` apply
141
+ to the service's name. aiohttp joins relative URLs as
136
142
  links are, so write them without the leading slash there: `get("invoices")`;
137
143
  and it creates a session only in a running event loop, so call its `client` in
138
144
  a coroutine, such as a lifespan handler.
@@ -143,6 +149,85 @@ yourself can do the same with the adapter's hook: `Transport` and
143
149
  `AsyncTransport` for httpx, the requests `Adapter`, the aiohttp `middleware`, or the
144
150
  niquests `pre_request` hook.
145
151
 
152
+ ### Generated clients
153
+
154
+ A service that lists another in its `encore.service.json` `clients` gets
155
+ clients for it in `encore_gen/clients/`: a package per service, with a module
156
+ per entry of the service's `api`, named after the entry's `name` (`openapi`,
157
+ `graphql` or `grpc` for one that sets none). Each operation is an async
158
+ function of its module, with nothing to set up first:
159
+
160
+ ```python
161
+ from encore_gen.clients import catalog
162
+
163
+ product = await catalog.openapi.get_product("xyz")
164
+ products = await catalog.storefront.products(skus=["xyz"])
165
+ stuff = await catalog.grpc.stuff_service.do_stuff(catalog.grpc.DoStuffMessage())
166
+ ```
167
+
168
+ A call looks the service's URL up when it is first made, and carries the
169
+ current trace and Request Context. It has no time limit unless it is given
170
+ one: every call takes a `timeout`, in seconds, for the whole call, and
171
+ `headers` to send:
172
+
173
+ ```python
174
+ product = await catalog.openapi.get_product("xyz", timeout=2.0)
175
+ stuff = await catalog.grpc.stuff_service.do_stuff(
176
+ catalog.grpc.DoStuffMessage(), headers={"x-tenant": "a"}
177
+ )
178
+ ```
179
+
180
+ To give many calls the same settings, make the module's
181
+ `AsyncClient(base_url=None, *, timeout=None, headers=None, http_client=None)`,
182
+ for instance at the top of a module of your service. A call's `timeout` takes
183
+ the place of its client's, and `None` is no limit, as a long stream may need;
184
+ its `headers` are sent over the client's. The clients share their
185
+ connections, so one made for a single call costs nothing:
186
+
187
+ ```python
188
+ catalog_api = catalog.openapi.AsyncClient(timeout=10.0)
189
+
190
+ product = await catalog_api.get_product("xyz")
191
+ report = await catalog_api.export_products(timeout=120.0)
192
+
193
+ async with catalog.storefront.AsyncClient(headers={"x-tenant": "a"}) as client:
194
+ products = await client.products(skus=["xyz"])
195
+ ```
196
+
197
+ A spec's own parameter that is named `timeout` or `headers` is renamed
198
+ `timeout2` or `headers2`.
199
+
200
+ Closing a client, as `async with` does, closes neither the shared connections
201
+ nor an `http_client` it was given, which stays yours to close. An
202
+ `httpx.AsyncClient` you give one carries the Request Context when made with
203
+ `transport=services.AsyncTransport()`. An OpenAPI or GraphQL client given a
204
+ `transport` instead, as a retrying or instrumented one, sends through it under
205
+ the SDK's, so its calls carry their Request Context, and closes the
206
+ connections it opens.
207
+
208
+ A call that fails raises `encore.services.CallError`, whatever the kind of API:
209
+ its `code` is the `ErrCode` the service answered with, or the one its HTTP
210
+ status means; `UNAVAILABLE` when no answer came, and `DEADLINE_EXCEEDED` when
211
+ the call took longer than its timeout. `message` says what went wrong, and
212
+ `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.
214
+
215
+ ```python
216
+ from encore.errs import ErrCode
217
+ from encore.services import CallError
218
+
219
+ try:
220
+ product = await catalog.openapi.get_product("xyz")
221
+ except CallError as error:
222
+ if error.code is not ErrCode.NOT_FOUND:
223
+ raise
224
+ product = None
225
+ ```
226
+
227
+ 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.
230
+
146
231
  ## Request Context
147
232
 
148
233
  Request Context fields are typed values that travel with a request to every
@@ -214,7 +299,7 @@ if __name__ == "__main__":
214
299
  lifespan startup, starts listening, and starts Encore's Pub/Sub
215
300
  subscriptions. A failed startup exits with 1.
216
301
  - **Requests**: HTTP/1.1 and HTTP/2 (h2c). Each request has its Request Context
217
- and a span continuing its trace, with no OpenTelemetry setup in the app. The
302
+ and a span continuing its trace. The
218
303
  server records the span itself, from the request's arrival to its response,
219
304
  named after the route the app matched; the app's code reaches it as
220
305
  `trace.get_current_span()`.
@@ -227,10 +312,10 @@ if __name__ == "__main__":
227
312
  A service without an HTTP API, as one that only handles Pub/Sub messages, calls
228
313
  `encore.run()`: the same, without the server.
229
314
 
230
- - `workers=N` runs N event loops on threads, sharing the app. It needs
231
- free-threaded Python with the GIL disabled (`python3.14t`), where they run in
232
- parallel. Each worker runs the app's lifespan with its own `state`, so
233
- resources bound to an event loop stay on theirs.
315
+ - `threads=N` runs N event loops, each on a thread of its own, sharing the app.
316
+ It needs free-threaded Python with the GIL disabled (`python3.14t`), where
317
+ they run in parallel. Each loop runs the app's lifespan with its own `state`,
318
+ so resources bound to an event loop stay on theirs.
234
319
  - `max_concurrency` caps the requests the app handles at once.
235
320
  - `read_timeout` (30 seconds) bounds how long a client may take to send a
236
321
  request's headers, a body of up to 64 KiB (answered with 408 when it takes
@@ -257,10 +342,20 @@ if __name__ == "__main__":
257
342
  Its spans are not named after its routes: WSGI frameworks don't say which one
258
343
  they matched.
259
344
 
260
- FastAPI records spans of its own once a tracer provider is set, as `run` sets
261
- Encore's: a second server span for each request, and spans of dependencies,
262
- endpoints and serialization. `run` turns them off for its requests; pass
263
- `server_spans=False` to leave the request's span, and those, to FastAPI.
345
+ FastAPI can record its own server, dependency, endpoint and serialization
346
+ spans when configured with a tracer provider. `run` turns them off for its
347
+ requests, preserving one server span. To leave those spans to FastAPI, pass
348
+ `server_spans=False` and configure its provider explicitly:
349
+
350
+ ```python
351
+ from encore.tracing import tracer_provider
352
+
353
+ app = FastAPI(telemetry={"tracer_provider": tracer_provider()})
354
+ encore.run(app, server_spans=False)
355
+ ```
356
+
357
+ `encore.run` and server middleware leave global OpenTelemetry trace, meter and
358
+ logger providers unchanged.
264
359
 
265
360
  An app served by a server of its own adds Encore's middleware instead, for the
266
361
  same Request Context and tracing:
@@ -272,8 +367,7 @@ app.add_middleware(asgi.Middleware) # FastAPI, Starlette
272
367
  app = wsgi.Middleware(app) # Flask, Django's WSGI application
273
368
  ```
274
369
 
275
- Both make Encore's tracer provider OpenTelemetry's global one, unless the app
276
- set its own. The middleware works beside OpenTelemetry's own: inside it, as
370
+ The middleware works beside OpenTelemetry's own: inside it, as
277
371
  `FastAPIInstrumentor` arranges, the request's span is that one's; outside it,
278
372
  OpenTelemetry's records an internal span under Encore's. The ASGI middleware
279
373
  names the span after the route FastAPI or Starlette matched; WSGI frameworks
@@ -605,12 +699,119 @@ resources.
605
699
  Initialize independently in each worker process. Forking an already initialized
606
700
  native runtime is not supported by this startup model.
607
701
 
702
+ ## Logs
703
+
704
+ Write structured application logs with a message and fields:
705
+
706
+ ```python
707
+ from encore import logs
708
+
709
+ logs.info("Order placed", order_id=42, items=3)
710
+ ```
711
+
712
+ `logs.debug`, `info`, `warning`, `error`, and `critical` take a positional
713
+ message and structured keyword fields. `logs.exception` logs the active
714
+ exception at error level. Helper fields cannot replace metadata or trace
715
+ correlation: `message`, `level`, `time`, `logger`, `trace_id`, `span_id`,
716
+ `sampled`, `service.name`, `exception.type`, `exception.message`,
717
+ `exception.stacktrace`, `code.function.name`, `code.file.path`,
718
+ `code.line.number`, `code.column.number`, and `encore.runtime.target` are
719
+ reserved, as are `LogRecord` attributes, methods, and factory-added attributes. Collisions gain `raw.` prefixes until the key
720
+ conflicts with neither record attributes nor other supplied fields. For
721
+ example, `logs.info("charged", level="fatal")` keeps level `info` and writes
722
+ `raw.level="fatal"`; if `raw.level` is also supplied, the `level` field
723
+ becomes `raw.raw.level`. Keyword arguments are fields, not Python logging
724
+ options. Direct `StructuredLogHandler` usage retains its reserved-key behavior:
725
+ valid reserved-key attributes can override the corresponding output fields.
726
+
727
+ The helpers use the standard `encore.logs` logger. With no application
728
+ handler, they write Encore-formatted lines to stderr without changing the
729
+ root logger. The fallback uses INFO when root remains WARNING with no handlers;
730
+ setting root WARNING alone is indistinguishable from the default. To suppress
731
+ INFO, set `encore.logs` to WARNING or install an application handler with the
732
+ desired level. Other explicit levels, filters and disabling are respected.
733
+ Application handlers replace the fallback, without duplicate output.
734
+ To enable debug output:
735
+
736
+ ```python
737
+ import logging
738
+
739
+ logging.getLogger("encore.logs").setLevel(logging.DEBUG)
740
+ ```
741
+
742
+ ### Python logging
743
+
744
+ Use `StructuredLogHandler` for structured JSON output from standard Python loggers:
745
+
746
+ ```python
747
+ import logging
748
+
749
+ from encore.logs import StructuredLogHandler
750
+
751
+ logging.basicConfig(level=logging.INFO, handlers=[StructuredLogHandler()])
752
+ ```
753
+
754
+ ### OpenTelemetry
755
+
756
+ Encore collects process output and exports it through an out-of-process
757
+ collector as OpenTelemetry logs over OTLP. Encore-formatted logs preserve
758
+ structured fields, severity and current trace/span IDs, including those from
759
+ OpenTelemetry instrumentation. Other output is collected as unstructured text.
760
+ Use the helpers or Python `logging` with `StructuredLogHandler` for structured logs;
761
+ global OpenTelemetry logger providers are unchanged.
762
+
763
+ ## Traces
764
+
765
+ Create spans around application work:
766
+
767
+ ```python
768
+ from encore import tracing
769
+
770
+ with tracing.span("place_order", attributes={"order.id": order_id}) as span:
771
+ span.set_attribute("order.items", 3)
772
+ with tracing.span("validate_order"):
773
+ ...
774
+ ```
775
+
776
+ A span becomes current inside its block. Nested spans inherit its trace; spans
777
+ end on block exit, and uncaught exceptions are recorded as failures and
778
+ propagate. Use regular `with` blocks in async code too.
779
+
780
+ ### OpenTelemetry
781
+
782
+ Encore spans share OpenTelemetry context. Obtain a tracer directly from Encore's
783
+ provider for standard trace API calls:
784
+
785
+ ```python
786
+ from encore.tracing import tracer_provider
787
+
788
+ tracer = tracer_provider().get_tracer(__name__)
789
+
790
+ with tracer.start_as_current_span("place_order") as span:
791
+ span.set_attribute("order.id", order_id)
792
+ ```
793
+
794
+ Optional `opentelemetry-instrumentation-*` packages instrument frameworks and
795
+ libraries. Pass the provider directly, for example
796
+ `FastAPIInstrumentor().instrument_app(app, tracer_provider=tracer_provider())`,
797
+ or opt in once if your app owns global OpenTelemetry setup:
798
+
799
+ ```python
800
+ from opentelemetry import trace
801
+
802
+ trace.set_tracer_provider(tracer_provider())
803
+ ```
804
+
805
+ Encore always uses its cached, owned provider for SDK-created spans,
806
+ independent of the global provider. `tracing.span`, `encore.run` and server
807
+ middleware leave global trace, meter and logger providers unchanged.
808
+
608
809
  ## Metrics
609
810
 
610
- Metrics are OpenTelemetry instruments of the meter `encore`, declared at module
611
- scope in three scopes (`Counter`, `SharedCounter`, `GlobalCounter`, and so on
612
- for `UpDownCounter`, `Gauge` and `Histogram`), each with a `…Group` form whose
613
- labels are a `TypedDict` or a dataclass:
811
+ Declare metrics at module scope: `Counter` for increasing totals,
812
+ `UpDownCounter` for totals that can decrease, `Gauge` for current values, and
813
+ `Histogram` for distributions. Each has a `…Group` form whose labels are a
814
+ `TypedDict` or a dataclass:
614
815
 
615
816
  ```python
616
817
  from dataclasses import dataclass
@@ -628,35 +829,52 @@ latency = metrics.HistogramGroup[Labels]("request_duration", unit="s")
628
829
  latency.with_labels(Labels("/orders")).record(0.025)
629
830
  ```
630
831
 
631
- A service's own metric (`Counter`, `HistogramGroup`, …) is exported as
632
- `<service>.<name>`: `request_duration` of the service `shop` is
633
- `shop.request_duration`. Shared and global ones keep their name, and are
832
+ A service's own metric, the default scope, is exported as `<service>.<name>`:
833
+ `request_duration` of the service `shop` is `shop.request_duration`. Shared
834
+ (`scope="shared"`) and global (`scope="global"`) ones keep their name, and are
634
835
  declared once: other modules import the declaration, and code in another
635
836
  language binds one by name, as in
636
837
  `metrics.CounterGroup[Labels].named("responses_total")`. Hand a metric to other
637
838
  code as a reference, `latency.ref()`.
638
839
 
639
- Label keys are snake_case; values are strings, ints and bools, anything else a
640
- `TypeError`. `unit`, `description` and a histogram's `buckets` must be literals:
641
- Encore's parser reads them.
840
+ Metric names and scopes must be string literals. Names start with a letter,
841
+ followed by letters, digits, `_`, `.`, `-` or `/`. Label keys are snake_case;
842
+ values are strings, ints and bools, anything else a `TypeError`. `unit`,
843
+ `description` and a histogram's `buckets` must be literals: Encore's parser reads
844
+ them.
642
845
 
643
- ## OpenTelemetry
846
+ ### OpenTelemetry
644
847
 
645
- Encore records its spans and metrics through its own providers and installs no
646
- OpenTelemetry globals, leaving an app's own setup alone. For the app's spans
647
- and instruments, and instrumentation packages', install Encore's providers or
648
- pass them to an instrumentation:
848
+ Encore metric declarations use the `encore` meter. Obtain a meter from Encore's
849
+ provider for standard metrics API calls:
649
850
 
650
851
  ```python
651
- from opentelemetry import metrics, trace
652
-
653
852
  from encore.metrics import meter_provider
654
- from encore.tracing import tracer_provider
655
853
 
656
- trace.set_tracer_provider(tracer_provider())
854
+ meter = meter_provider().get_meter("orders")
855
+ orders = meter.create_counter("orders_placed", unit="{order}")
856
+ orders.add(1, attributes={"outcome": "success"})
857
+ ```
858
+
859
+ These instruments are exported alongside Encore metrics, with their names
860
+ unchanged. The meter's instrumentation scope (`orders` here) is distinct from
861
+ an Encore declaration's service/shared/global scope. The process resource
862
+ identifies the service recording them. Use the standard API for observable
863
+ instruments or attributes beyond Encore's label types.
864
+
865
+ Encore declarations always use the cached, owned meter provider, independent
866
+ of the global provider. Pass `meter_provider()` directly to instrumentation,
867
+ or opt in once if your app owns global OpenTelemetry setup:
868
+
869
+ ```python
870
+ from opentelemetry import metrics
871
+
657
872
  metrics.set_meter_provider(meter_provider())
658
873
  ```
659
874
 
875
+ Encore leaves global trace, meter and logger providers unchanged, including in
876
+ `encore.run` and server middleware.
877
+
660
878
  ## Object storage
661
879
 
662
880
  Declare a bucket at module scope, then use its async methods:
@@ -744,7 +962,10 @@ async def handle_request():
744
962
  return await load(sessions.read())
745
963
  ```
746
964
 
747
- `Database(name)` has no persistence or eviction options yet. Creating a database,
965
+ A database is a cache unless declared `Database(name, persistent=True)`: a
966
+ cache may lose what it holds, and evicts the least recently used keys when it
967
+ runs out of memory. `Database.named(name)` references a database declared
968
+ elsewhere. Creating a database,
748
969
  selecting a family, and creating a handle defer native lookup until first use.
749
970
  Direct resource calls must keep the family and command together, as in
750
971
  `sessions.string.get(...)`, so Encore can determine their permissions. To pass
@@ -752,11 +973,58 @@ access to another function or keep a family interface in a variable, obtain a
752
973
  `read()` or `write()` handle first.
753
974
 
754
975
  Families are the properties `generic`, `string`, `bitmap`, `geo`, `hash`, `json`,
755
- `list`, `set`, `sorted_set`, `stream`, and `pubsub`. Read handles expose
976
+ `list`, `set`, `sorted_set`, `stream`, `hyperloglog`, and `pubsub`. Read handles expose
756
977
  only read operations, and the native runtime also rejects writes through them.
757
978
  `read(primary=True)` requests primary access; the current runtime uses the primary
758
979
  for all reads, including when this flag is false.
759
980
 
981
+ A pipeline sends commands in one round trip, and a transaction (MULTI/EXEC)
982
+ runs them together. Commands are queued through the same families, each
983
+ returning a `Queued` whose `value` is the decoded result once the batch has
984
+ run; `execute()` raises `BatchError` if any failed, each `Queued` its own
985
+ error:
986
+
987
+ ```python
988
+ pipe = sessions.pipeline()
989
+ name = pipe.string.get[str]("name:1")
990
+ hits = pipe.string.incr("hits")
991
+ await pipe.execute()
992
+ print(name.value, hits.value)
993
+ ```
994
+
995
+ `watch(keys, body)` runs `body(conn, tx)` as an optimistic transaction,
996
+ retrying while a watched key changes; `acquire()` takes a connection out of the
997
+ pool (`async with sessions.acquire() as conn:`). A `Script` runs by its hash,
998
+ falling back to its source; only its `KEYS` get the database's prefix, so it
999
+ must take every key it touches through `key()`:
1000
+
1001
+ ```python
1002
+ RELEASE = Script(
1003
+ 'if redis.call("get", KEYS[1]) == ARGV[1] then '
1004
+ 'return redis.call("del", KEYS[1]) end return 0'
1005
+ )
1006
+ released = await sessions.script(RELEASE).key("lock:job").arg(token).invoke()
1007
+ ```
1008
+
1009
+ The blocking pops (`list.blpop`, `brpop`, `blmove`, `blmpop`,
1010
+ `sorted_set.bzpopmin`, `bzpopmax`, `bzmpop`) take a keyword-only `timeout` in
1011
+ seconds, 0 waiting for ever, and return `None` once it passes. They wait on a
1012
+ connection of their own, so they hold up no other command; cancelling the task
1013
+ ends the wait. They can't be queued, nor run on an acquired connection.
1014
+ `bitmap.bitfield(key)` builds a BITFIELD (`.get()`, `.set()`, `.incrby()`,
1015
+ `.overflow()`, then `await .invoke()`), and `generic.scan_iter()`,
1016
+ `hash.hscan_iter`, `set.sscan_iter` and `sorted_set.zscan_iter` follow a scan's
1017
+ cursor to the end.
1018
+
1019
+ `command(name)` sends a command the families lack, by its name, which must be
1020
+ a string literal: `await sessions.command("OBJECT").arg("FREQ").key("hot").invoke()`.
1021
+ Before it is sent the runtime checks it against Redis's command table, and
1022
+ raises `CommandRefused` if a key it takes isn't passed with `key()`, or if it
1023
+ would reach past the database, change a connection other calls share, or has a
1024
+ call of its own here (MULTI, SUBSCRIBE, EVAL, SCAN, FLUSHALL, ...). A command
1025
+ the server rejects raises `ServerError`, whose `code` is the first word of the
1026
+ server's message (`WRONGTYPE`).
1027
+
760
1028
  Keys and hash/stream field names are `str` inputs. Stored values, members, and
761
1029
  message payloads accept `Value`: `bytes`, `str`, `int`, `float`, or an implementation of
762
1030
  `RedisValue`. Strings are encoded as UTF-8, integers as decimal text, floats as