relay-runtime 0.1.0__tar.gz → 0.2.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,371 @@
1
+ Metadata-Version: 2.4
2
+ Name: relay-runtime
3
+ Version: 0.2.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
+ ### Integration example
249
+
250
+ The following app uses `pymongo` and `httpx` as application dependencies; they
251
+ are not dependencies of `relay-runtime`. The Mongo client is container-scoped,
252
+ while the HTTP client and course catalog are invocation-scoped:
253
+
254
+ ```python
255
+ from collections.abc import AsyncIterator
256
+ from typing import Any
257
+
258
+ import httpx
259
+ from pymongo import AsyncMongoClient
260
+
261
+ from relay_runtime import Depends, bind
262
+ from relay_runtime.typing import HandlerContext
263
+
264
+
265
+ class CourseCatalog:
266
+ def __init__(
267
+ self, mongo: AsyncMongoClient, http: httpx.AsyncClient
268
+ ) -> None:
269
+ self._courses = mongo.get_database("school").courses
270
+ self._http = http
271
+
272
+ async def notify(
273
+ self, course_id: str, event: dict[str, Any], request_id: str
274
+ ) -> None:
275
+ course = await self._courses.find_one({"_id": course_id})
276
+ if course is None:
277
+ return
278
+ await self._http.post(
279
+ "/course-events",
280
+ json={
281
+ "course": str(course["_id"]),
282
+ "event": event,
283
+ "requestId": request_id,
284
+ },
285
+ )
286
+
287
+
288
+ async def get_mongo() -> AsyncIterator[AsyncMongoClient]:
289
+ client = AsyncMongoClient("mongodb://localhost:27017")
290
+ try:
291
+ yield client
292
+ finally:
293
+ await client.close()
294
+
295
+
296
+ async def get_courses(
297
+ mongo: AsyncMongoClient = Depends(get_mongo, scope="container"),
298
+ ) -> AsyncIterator[CourseCatalog]:
299
+ async with httpx.AsyncClient(base_url="https://courses.internal") as http:
300
+ yield CourseCatalog(mongo, http)
301
+
302
+
303
+ @bind
304
+ async def handler(
305
+ event: dict[str, Any],
306
+ context: HandlerContext,
307
+ courses: CourseCatalog = Depends(get_courses),
308
+ ) -> None:
309
+ await courses.notify(event["course_id"], event, context.request_id)
310
+ ```
311
+
312
+ `get_mongo` opens once per warm container. `get_courses` and its HTTP client are
313
+ created for each invocation; their cleanup runs after the handler, and the Mongo
314
+ client closes when the container shuts down. The handler completes its response
315
+ through the injected HTTP client; Relay uses handler completion for success or
316
+ failure, not the Python return value.
317
+
318
+ ### Errors and plain handlers
319
+
320
+ Dependency declaration, resolution, and cleanup failures use Relay's normal
321
+ handler failure path: the invocation fails through the usual error reporting and
322
+ Relay's configured retry policy applies. There is no separate dependency retry
323
+ mechanism. A cleanup failure during an already-failing invocation is reported
324
+ without replacing the original handler or dependency error.
325
+
326
+ `Depends(...)` on a handler is resolved only when that handler is decorated with
327
+ `@bind`. Without `@bind`, Relay executes the ordinary handler exactly as before
328
+ with `(event, context)` and does not resolve dependency markers; a parameter
329
+ whose default is `Depends(...)` simply retains that default value.
330
+
331
+ ## Limitations
332
+
333
+ - Container-scoped values live in one warm container's Python process and event
334
+ loop. They are not shared across containers, replicas, or nodes and are lost
335
+ when the container is discarded. A value created by an async provider belongs
336
+ to the event loop that created it; using it from a different loop fails rather
337
+ than sharing a loop-bound resource.
338
+ - Container cache initialization relies on Relay's serialized invocation model.
339
+ Concurrent bound-handler calls outside Relay are not coordinated.
340
+ - A provider is identified by the callable object used in `Depends(...)`. Use
341
+ module-level callables when the same container-scoped value must be shared by
342
+ more than one handler.
343
+ - Cleanup is best-effort. A hard timeout, container kill, or process crash does
344
+ not run generator finalizers.
345
+ - Dependency injection does not change Relay's at-least-once delivery contract;
346
+ handlers should still be idempotent.
347
+
348
+ The package version is independent of the Relay release version. Future
349
+ releases may add exports, and existing members keep their documented meaning.
350
+
351
+ ## Development
352
+
353
+ The package is managed with [uv](https://docs.astral.sh/uv/) and uses a `src`
354
+ layout with the `uv_build` backend.
355
+
356
+ ```sh
357
+ cd packages/python
358
+ uv lock
359
+ uv sync --locked
360
+ uv run mypy
361
+ uv build
362
+ uv run pytest
363
+ ```
364
+
365
+ `uv.lock` is committed so installs and checks resolve the same versions. The
366
+ `dev` dependency group contains mypy and pytest only; neither is required by
367
+ handlers or by the package at runtime.
368
+
369
+ ## License
370
+
371
+ GPL-3.0-or-later. See [LICENSE](LICENSE).