relay-runtime 0.1.0__tar.gz → 0.3.0__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.
@@ -0,0 +1,535 @@
1
+ Metadata-Version: 2.4
2
+ Name: relay-runtime
3
+ Version: 0.3.0
4
+ Summary: Official Python library and public handler interfaces for Relay applications.
5
+ Keywords: relay,application-development,handlers
6
+ Author: Relay Contributors
7
+ License-Expression: GPL-3.0-or-later
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.14
12
+ Description-Content-Type: text/markdown
13
+
14
+ # relay-runtime
15
+
16
+ The official Python library for developing Relay applications and using Relay's
17
+ public handler interfaces.
18
+
19
+ The package is optional for Relay's execution. Add it as a normal application
20
+ dependency when your handlers import it.
21
+
22
+ ## Install
23
+
24
+ With uv:
25
+
26
+ ```sh
27
+ uv add relay-runtime
28
+ ```
29
+
30
+ Or with pip:
31
+
32
+ ```sh
33
+ pip install relay-runtime
34
+ ```
35
+
36
+ The library supports Python 3.14 and newer.
37
+
38
+ ## Handler example
39
+
40
+ Relay calls a handler with the event as its first argument and the context as
41
+ its second:
42
+
43
+ ```python
44
+ from relay_runtime.typing import HandlerContext
45
+
46
+
47
+ async def handler(event: dict, context: HandlerContext) -> None:
48
+ print(
49
+ f"request {context.request_id} "
50
+ f"has {context.get_remaining_time_ms()}ms left"
51
+ )
52
+ ```
53
+
54
+ `HandlerContext` is a public `typing.Protocol`, not the concrete context
55
+ implementation. Relay's Python bootstrap creates and supplies that actual
56
+ per-invocation object.
57
+
58
+ ## Contract
59
+
60
+ `HandlerContext` provides:
61
+
62
+ | Member | Type | Meaning |
63
+ | ------------------------- | ------------- | --------------------------------------------- |
64
+ | `request_id` | `str` | Stable identity for one logical invocation |
65
+ | `attempt` | `int` | 1-based attempt number |
66
+ | `max_attempts` | `int` | Configured total attempt budget |
67
+ | `deadline` | `datetime` | Absolute, timezone-aware cancellation instant |
68
+ | `message_id` | `str \| None` | Source message identity when one exists |
69
+ | `trace_id` | `str \| None` | W3C trace ID when tracing is enabled |
70
+ | `app` | `str` | Owning app name |
71
+ | `handler` | `str` | Handler identity |
72
+ | `get_remaining_time_ms()` | `int` | Milliseconds left, clamped at zero |
73
+
74
+ `max_attempts` is the configured budget, not an upper bound on `attempt`: a
75
+ configuration change can leave a claimed attempt above the current budget.
76
+
77
+ ## Dependency injection
78
+
79
+ Dependency injection is optional. A handler that does not use it keeps the
80
+ plain `handler(event, context)` form and does not need to import the library.
81
+ Mark a handler with `@bind` and default the parameters you want Relay to
82
+ resolve to `Depends(...)`:
83
+
84
+ ```python
85
+ from collections.abc import AsyncIterator
86
+
87
+ from relay_runtime import Depends, bind
88
+ from relay_runtime.typing import HandlerContext
89
+
90
+
91
+ class Settings:
92
+ def __init__(self, database_url: str) -> None:
93
+ self.database_url = database_url
94
+
95
+
96
+ async def get_settings() -> Settings:
97
+ return Settings("postgres://localhost/app")
98
+
99
+
100
+ class Connection:
101
+ async def close(self) -> None:
102
+ ...
103
+
104
+
105
+ async def get_connection(
106
+ settings: Settings = Depends(get_settings),
107
+ ) -> AsyncIterator[Connection]:
108
+ connection = Connection()
109
+ try:
110
+ yield connection
111
+ finally:
112
+ await connection.close()
113
+
114
+
115
+ @bind
116
+ async def handler(
117
+ event: dict[str, object],
118
+ context: HandlerContext,
119
+ settings: Settings = Depends(get_settings, scope="container"),
120
+ connection: Connection = Depends(get_connection),
121
+ ) -> None:
122
+ ...
123
+ ```
124
+
125
+ Relay still calls the decorated handler with exactly `(event, context)`; the
126
+ wrapper resolves the remaining parameters and awaits the original result. A
127
+ decorated handler is always async, even when the original function is sync.
128
+
129
+ ### Decorators
130
+
131
+ `@bind` composes with an ordinary decorator that uses `functools.wraps` and
132
+ forwards the call:
133
+
134
+ ```python
135
+ import functools
136
+ from collections.abc import Awaitable, Callable
137
+ from typing import Any
138
+
139
+ from relay_runtime import Depends, bind
140
+ from relay_runtime.typing import HandlerContext
141
+
142
+
143
+ def track_activity(
144
+ func: Callable[..., Awaitable[Any]],
145
+ ) -> Callable[..., Awaitable[Any]]:
146
+ @functools.wraps(func)
147
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
148
+ # tracing/metrics here
149
+ return await func(*args, **kwargs)
150
+
151
+ return wrapper
152
+
153
+
154
+ async def get_activity_log() -> object:
155
+ return object()
156
+
157
+
158
+ @bind
159
+ @track_activity
160
+ async def handler(
161
+ event: dict[str, object],
162
+ context: HandlerContext,
163
+ activity_log: object = Depends(get_activity_log),
164
+ ) -> None:
165
+ ...
166
+ ```
167
+
168
+ In this order `@bind` sees the signature preserved by `functools.wraps` and
169
+ resolves `activity_log` before calling `track_activity`. A `functools.wraps`
170
+ decorator may also be placed outside `@bind`; it then wraps the already-bound
171
+ `(event, context)` callable. Both orders work when the ordinary decorator
172
+ forwards arguments and preserves the signature. Relay resolves dependencies
173
+ only at the `@bind` layer; it does not inject into a third-party decorator. A
174
+ decorator that changes the handler signature or does not forward the call is
175
+ unsupported.
176
+
177
+ ### Provider parameters
178
+
179
+ Invocation-scoped providers receive the special values only through parameters
180
+ named exactly `event` and `context`:
181
+
182
+ ```python
183
+ def request_label(event, context) -> str:
184
+ return f"{context.request_id}:{event['kind']}"
185
+ ```
186
+
187
+ No other parameter name or type annotation is inferred. Every other required
188
+ provider parameter must use `Depends(...)` or have an ordinary default.
189
+ Container-scoped providers cannot use `event` or `context`.
190
+
191
+ ### Rules
192
+
193
+ - `event` and `context` are reserved parameter names. A handler must declare
194
+ exactly one of each, and they receive the invocation values. They cannot use
195
+ `Depends(...)` or a default.
196
+ - Every other handler and provider parameter must have a `Depends(...)` default
197
+ or an ordinary default. Relay never infers a dependency from a type
198
+ annotation or from a parameter name.
199
+ - `Depends(provider, *, scope="invocation", use_cache=True)` references a
200
+ callable provider directly. The only supported scopes are `"invocation"` and
201
+ `"container"`. No registration step is required.
202
+ - Provider parameters are resolved the same way. Invocation-scoped providers
203
+ may also use the reserved `event` and `context` parameters. Container-scoped
204
+ providers may not use them and may not depend on an invocation-scoped
205
+ dependency.
206
+ - `Annotated[T, Depends(provider)]` is accepted in addition to a default. Do
207
+ not combine both forms on one parameter. If a parameter's annotation cannot
208
+ be resolved when it is needed to find `Depends(...)`, relay reports that
209
+ parameter and the resolution error instead of failing later with a generic
210
+ missing-dependency message.
211
+ - `*args` and `**kwargs` are rejected. Dependency cycles and invalid signatures
212
+ fail when the handler is decorated.
213
+ - `use_cache=False` is valid only with `scope="invocation"`. Combining it with
214
+ `scope="container"` is rejected when `Depends(...)` is declared.
215
+
216
+ ### Scopes and cleanup
217
+
218
+ - `invocation`: created at most once per handler call when cached, shared only
219
+ within that call, and closed when the call finishes.
220
+ - `container`: created at most once per warm container, shared across calls and
221
+ bound handlers, and closed when Relay's event loop is shutting down.
222
+
223
+ `use_cache=False` calls the provider each time that dependency is requested and
224
+ gives the value to the requesting invocation. Use it for cheap or intentionally
225
+ fresh values.
226
+
227
+ Within one dependency graph, cached declarations of the same provider in the
228
+ same scope share one cached value. Each uncached declaration is a separate
229
+ resolution path: it bypasses that cached slot, creates a fresh value every time
230
+ it is requested, and its cleanup belongs to the invocation. Declaring the same
231
+ provider in both modes does not make their values shared; the uncached path
232
+ neither observes nor replaces the cached value.
233
+
234
+ Providers may be sync or async functions, generators, or async generators. A
235
+ generator provider yields exactly one value; code after the `yield` is its
236
+ cleanup path. On success, invocation-scoped generators are resumed so that code
237
+ after the `yield` runs and must terminate; a second yield fails the invocation.
238
+ On handler or dependency-resolution failure, the active exception is thrown
239
+ into each invocation generator (`throw`/`athrow`) before it is closed, so
240
+ familiar `except` cleanup runs. If a provider catches or suppresses that
241
+ exception, the original handler/dependency failure still propagates; cleanup
242
+ failures are reported and never replace it. The same applies when the
243
+ invocation is cancelled. Cleanup runs in reverse creation order and every
244
+ resource is attempted. Container-scoped dependencies use the same normal
245
+ teardown and close when Relay's long-lived event loop exits, without replaying
246
+ an older invocation's error.
247
+
248
+ ### Overriding dependencies
249
+
250
+ `relay_runtime.dependencies.override_dependencies` temporarily replaces
251
+ providers for the current context. It is available only from the
252
+ `relay_runtime.dependencies` module; the top-level `relay_runtime` package does
253
+ not export it.
254
+
255
+ A test can replace the production email provider with a fake and call the bound
256
+ handler inside the context:
257
+
258
+ ```python
259
+ import asyncio
260
+ from typing import Protocol
261
+
262
+ from relay_runtime import Depends, bind
263
+ from relay_runtime.dependencies import override_dependencies
264
+ from relay_runtime.typing import HandlerContext
265
+
266
+
267
+ class EmailSender(Protocol):
268
+ def send(self, address: str, subject: str) -> None: ...
269
+
270
+
271
+ def get_email_sender() -> EmailSender:
272
+ ... # return the production SES-backed sender
273
+
274
+
275
+ @bind
276
+ async def handler(
277
+ event: dict[str, object],
278
+ context: HandlerContext,
279
+ email: EmailSender = Depends(get_email_sender),
280
+ ) -> None:
281
+ email.send(str(event["address"]), "Welcome")
282
+
283
+
284
+ class FakeEmailSender:
285
+ def __init__(self) -> None:
286
+ self.sent: list[tuple[str, str]] = []
287
+
288
+ def send(self, address: str, subject: str) -> None:
289
+ self.sent.append((address, subject))
290
+
291
+
292
+ def test_handler_sends_welcome_email(context: HandlerContext) -> None:
293
+ fake = FakeEmailSender()
294
+ with override_dependencies({get_email_sender: lambda: fake}):
295
+ asyncio.run(handler({"address": "user@example.com"}, context))
296
+ assert fake.sent == [("user@example.com", "Welcome")]
297
+ ```
298
+
299
+ `context` is the invocation context Relay supplies; a unit test can pass a stub
300
+ that implements `HandlerContext`.
301
+
302
+ Keys are matched by provider identity, not equality. The mapping is snapshotted
303
+ and validated when the context is entered; later changes to the mapping object
304
+ do not affect an active context. Mapping a provider to itself is a no-op.
305
+ For parametrized provider factories, use the same cached provider object in the
306
+ handler declaration and override mapping; for example, cache `get_table("users")`
307
+ with `functools.cache` if it is constructed at both sites.
308
+ Nested contexts compose: an inner context inherits the outer overrides and its
309
+ entries take precedence. Leaving the inner context restores the outer mapping.
310
+
311
+ Overrides apply only where a `Depends(...)` declaration references the original
312
+ provider. The replacement inherits that declaration's `scope` and `use_cache`.
313
+ The replacement's own dependencies are resolved with the same overrides, but
314
+ the replacement root is not replaced again. An override chain is therefore not
315
+ followed recursively, and a replacement that depends on the provider it replaces
316
+ is reported as a dependency cycle. Container and invocation caches are keyed by
317
+ the original declaration, so two different originals mapped to one replacement
318
+ remain separate cache entries and own separate resource instances. The effective
319
+ graph is compiled lazily the first time a bound handler runs under the context;
320
+ replacement signatures, cycles, and scope rules are validated then.
321
+
322
+ Each active context owns an isolated container cache. Container-scoped values
323
+ created inside the context are not shared with the global warm container or with
324
+ another context, and their managed resources are closed when that context exits.
325
+ Nested contexts each own their own cache; an inner context does not see the
326
+ outer context's container values, and leaving the inner context closes only the
327
+ resources it created.
328
+
329
+ Use `with` for synchronous code and `async with` when container-scoped async
330
+ generator providers may be involved:
331
+
332
+ - `with` closes synchronous generator container resources without starting an
333
+ event loop. A container-scoped async generator is rejected before it is
334
+ started, including when another callable returns it indirectly; the error
335
+ asks for `async with`.
336
+ - `async with` closes both synchronous and asynchronous container resources.
337
+ - Invocation-scoped resources are always cleaned up inside the handler call, so
338
+ either form works for them.
339
+
340
+ Container-scoped async generator replacements require `async with` so their
341
+ cleanup path can run:
342
+
343
+ ```python
344
+ from collections.abc import AsyncIterator
345
+
346
+ from relay_runtime import Depends, bind
347
+ from relay_runtime.dependencies import override_dependencies
348
+ from relay_runtime.typing import HandlerContext
349
+
350
+
351
+ class Bucket:
352
+ async def put(self, key: str, body: bytes) -> None: ...
353
+ async def close(self) -> None: ...
354
+
355
+
356
+ async def get_bucket() -> AsyncIterator[Bucket]:
357
+ bucket = Bucket()
358
+ try:
359
+ yield bucket
360
+ finally:
361
+ await bucket.close()
362
+
363
+
364
+ @bind
365
+ async def upload(
366
+ event: dict[str, object],
367
+ context: HandlerContext,
368
+ bucket: Bucket = Depends(get_bucket, scope="container"),
369
+ ) -> None:
370
+ await bucket.put(str(event["key"]), b"...")
371
+
372
+
373
+ async def get_fake_bucket() -> AsyncIterator[Bucket]:
374
+ bucket = Bucket()
375
+ try:
376
+ yield bucket
377
+ finally:
378
+ await bucket.close()
379
+
380
+
381
+ async def test_upload_uses_fake_bucket(context: HandlerContext) -> None:
382
+ async with override_dependencies({get_bucket: get_fake_bucket}):
383
+ await upload({"key": "report.csv"}, context)
384
+ ```
385
+
386
+ `get_fake_bucket` is a container-scoped async generator, so its resource is
387
+ started and closed by `async with`. A synchronous `with` rejects that
388
+ replacement before the generator starts and reports that `async with` is
389
+ required.
390
+
391
+ If cleanup fails on exit, the error is raised when no other exception is active;
392
+ the context variable is restored first. If an exception is already propagating,
393
+ cleanup failures are logged and the original exception is preserved.
394
+ Invocation-scoped resources are cleaned up inside the handler on success,
395
+ failure, and cancellation; container-scoped resources are cleaned up when their
396
+ owning override context exits.
397
+
398
+ The active context is stored in a `contextvars.ContextVar`. It is visible in the
399
+ task that entered the context and in child tasks created while it is active.
400
+ Contexts are independent across tasks. A child task that outlives the context
401
+ and tries to resolve a dependency after the owner exits fails instead of using
402
+ the closed container. That inherited task context also cannot enter a new
403
+ override context after its parent has exited; create longer-lived tasks outside
404
+ the override context. Enter and exit the context in the same task; do not move a
405
+ context manager object to another task or thread.
406
+
407
+ Overrides affect only dependency resolution performed by `@bind` and
408
+ `Depends(...)`. They do not monkeypatch providers, change direct calls to a
409
+ provider, or alter container values that were resolved outside dependency
410
+ injection. Relay's at-least-once delivery contract is unchanged.
411
+
412
+ ### Integration example
413
+
414
+ The following app uses `pymongo` and `httpx` as application dependencies; they
415
+ are not dependencies of `relay-runtime`. The Mongo client is container-scoped,
416
+ while the HTTP client and course catalog are invocation-scoped:
417
+
418
+ ```python
419
+ from collections.abc import AsyncIterator
420
+ from typing import Any
421
+
422
+ import httpx
423
+ from pymongo import AsyncMongoClient
424
+
425
+ from relay_runtime import Depends, bind
426
+ from relay_runtime.typing import HandlerContext
427
+
428
+
429
+ class CourseCatalog:
430
+ def __init__(
431
+ self, mongo: AsyncMongoClient, http: httpx.AsyncClient
432
+ ) -> None:
433
+ self._courses = mongo.get_database("school").courses
434
+ self._http = http
435
+
436
+ async def notify(
437
+ self, course_id: str, event: dict[str, Any], request_id: str
438
+ ) -> None:
439
+ course = await self._courses.find_one({"_id": course_id})
440
+ if course is None:
441
+ return
442
+ await self._http.post(
443
+ "/course-events",
444
+ json={
445
+ "course": str(course["_id"]),
446
+ "event": event,
447
+ "requestId": request_id,
448
+ },
449
+ )
450
+
451
+
452
+ async def get_mongo() -> AsyncIterator[AsyncMongoClient]:
453
+ client = AsyncMongoClient("mongodb://localhost:27017")
454
+ try:
455
+ yield client
456
+ finally:
457
+ await client.close()
458
+
459
+
460
+ async def get_courses(
461
+ mongo: AsyncMongoClient = Depends(get_mongo, scope="container"),
462
+ ) -> AsyncIterator[CourseCatalog]:
463
+ async with httpx.AsyncClient(base_url="https://courses.internal") as http:
464
+ yield CourseCatalog(mongo, http)
465
+
466
+
467
+ @bind
468
+ async def handler(
469
+ event: dict[str, Any],
470
+ context: HandlerContext,
471
+ courses: CourseCatalog = Depends(get_courses),
472
+ ) -> None:
473
+ await courses.notify(event["course_id"], event, context.request_id)
474
+ ```
475
+
476
+ `get_mongo` opens once per warm container. `get_courses` and its HTTP client are
477
+ created for each invocation; their cleanup runs after the handler, and the Mongo
478
+ client closes when the container shuts down. The handler completes its response
479
+ through the injected HTTP client; Relay uses handler completion for success or
480
+ failure, not the Python return value.
481
+
482
+ ### Errors and plain handlers
483
+
484
+ Dependency declaration, resolution, and cleanup failures use Relay's normal
485
+ handler failure path: the invocation fails through the usual error reporting and
486
+ Relay's configured retry policy applies. There is no separate dependency retry
487
+ mechanism. A cleanup failure during an already-failing invocation is reported
488
+ without replacing the original handler or dependency error.
489
+
490
+ `Depends(...)` on a handler is resolved only when that handler is decorated with
491
+ `@bind`. Without `@bind`, Relay executes the ordinary handler exactly as before
492
+ with `(event, context)` and does not resolve dependency markers; a parameter
493
+ whose default is `Depends(...)` simply retains that default value.
494
+
495
+ ## Limitations
496
+
497
+ - Container-scoped values live in one warm container's Python process and event
498
+ loop. They are not shared across containers, replicas, or nodes and are lost
499
+ when the container is discarded. A value created by an async provider belongs
500
+ to the event loop that created it; using it from a different loop fails rather
501
+ than sharing a loop-bound resource.
502
+ - Container cache initialization relies on Relay's serialized invocation model.
503
+ Concurrent bound-handler calls outside Relay are not coordinated.
504
+ - A provider is identified by the callable object used in `Depends(...)`. Use
505
+ module-level callables when the same container-scoped value must be shared by
506
+ more than one handler.
507
+ - Cleanup is best-effort. A hard timeout, container kill, or process crash does
508
+ not run generator finalizers.
509
+ - Dependency injection does not change Relay's at-least-once delivery contract;
510
+ handlers should still be idempotent.
511
+
512
+ The package version is independent of the Relay release version. Future
513
+ releases may add exports, and existing members keep their documented meaning.
514
+
515
+ ## Development
516
+
517
+ The package is managed with [uv](https://docs.astral.sh/uv/) and uses a `src`
518
+ layout with the `uv_build` backend.
519
+
520
+ ```sh
521
+ cd packages/python
522
+ uv lock
523
+ uv sync --locked
524
+ uv run mypy
525
+ uv build
526
+ uv run pytest
527
+ ```
528
+
529
+ `uv.lock` is committed so installs and checks resolve the same versions. The
530
+ `dev` dependency group contains mypy and pytest only; neither is required by
531
+ handlers or by the package at runtime.
532
+
533
+ ## License
534
+
535
+ GPL-3.0-or-later. See [LICENSE](LICENSE).