aws-pynamo 0.1.0b1__py3-none-any.whl

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,131 @@
1
+ Metadata-Version: 2.5
2
+ Name: aws-pynamo
3
+ Version: 0.1.0b1
4
+ Summary: Event-driven applications on DynamoDB and AWS AppSync, built from pydantic models.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Programming Language :: Python :: 3.14
9
+ Requires-Python: >=3.14
10
+ Requires-Dist: boto3>=1.44.3
11
+ Requires-Dist: botocore>=1.44.3
12
+ Requires-Dist: mypy-boto3-dynamodb>=1.44.0
13
+ Requires-Dist: pydantic>=2.14.3
14
+ Provides-Extra: graphql
15
+ Requires-Dist: graphql-core>=3.3.2; extra == 'graphql'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # pynamo
19
+
20
+ pynamo is a toolkit for building event-driven, serverless applications on DynamoDB and AWS AppSync with pydantic. You describe your data once, as pydantic models, and pynamo uses those same models at every stage of a change's life:
21
+
22
+ 1. **Stored**: [`pynamo.models`](models.md) reads and writes the models in a DynamoDB table, building every key from the model's own attributes.
23
+ 2. **Served**: [`pynamo.api`](api.md) publishes functions that take and return the models as an AppSync GraphQL API, generating the schema from their type hints.
24
+ 3. **Reacted to**: [`pynamo.streams`](streams.md) hands every change to an item back to your code as a before and after pair of models, so work can follow on from a write without the writer knowing about it.
25
+
26
+ A change moves through an application like a tide. It comes in through the API, is written to the table, and then flows back out through the stream to whatever reacts to it:
27
+
28
+ ```
29
+ client ── GraphQL ──▶ AppSync ──▶ Lambda: pynamo.api ──▶ DynamoDB: pynamo.models
30
+ │
31
+ item change
32
+ ▼
33
+ Lambda: pynamo.streams ◀───────── Kinesis data stream
34
+ ```
35
+
36
+ At every step the data is validated as the same pydantic class, so a field added to a model is stored, published in the schema and delivered to stream handlers without being declared anywhere else.
37
+
38
+ ## Installation
39
+
40
+ pynamo needs Python 3.14 or later.
41
+
42
+ ```
43
+ pip install aws-pynamo
44
+ ```
45
+
46
+ `pynamo.api` also needs `graphql-core`, which the `graphql` extra installs:
47
+
48
+ ```
49
+ pip install "aws-pynamo[graphql]"
50
+ ```
51
+
52
+ ## A model's life
53
+
54
+ One model, served through the API and reacted to when it changes:
55
+
56
+ ```python
57
+ import logging
58
+
59
+ import boto3
60
+
61
+ from pynamo.api import Router
62
+ from pynamo.models import DynamoModel, single_table_indexes
63
+ from pynamo.streams import DynamoStreamHandler
64
+
65
+ DynamoModel.default_table(boto3.resource("dynamodb").Table("app"))
66
+
67
+
68
+ # Stored: keys are built from the model's attributes
69
+ class User(DynamoModel):
70
+ """A user of the app."""
71
+
72
+ indexes = single_table_indexes(base=("USER#{user_id}", "USER"))
73
+
74
+ user_id: str
75
+ name: str
76
+
77
+
78
+ # Served: the schema is generated from the resolvers' signatures
79
+ router = Router()
80
+
81
+
82
+ @router.query()
83
+ def get_user(user_id: str) -> User:
84
+ """Get a user by ID."""
85
+ return User.get({"user_id": user_id})
86
+
87
+
88
+ @router.mutation()
89
+ def rename_user(user_id: str, name: str) -> User:
90
+ """Change a user's name."""
91
+ return User.update({"user_id": user_id}, {"name": name})
92
+
93
+
94
+ # Reacted to: each change arrives as the item before and after it
95
+ stream = DynamoStreamHandler()
96
+
97
+
98
+ @stream.handle(User, events=["MODIFY"])
99
+ def on_user_changed(old: User | None, new: User | None) -> None:
100
+ """Record renames once they've been written."""
101
+ if old is not None and new is not None and old.name != new.name:
102
+ logging.info("User %s renamed from %s to %s", new.user_id, old.name, new.name)
103
+
104
+
105
+ # Each function is deployed as its own Lambda
106
+ def api_handler(event, context):
107
+ return router(event, context)
108
+
109
+
110
+ def stream_handler(event, context):
111
+ return stream.lambda_handler(event, context)
112
+ ```
113
+
114
+ `rename_user` doesn't know that anything is listening, and `on_user_changed` doesn't know where the change came from. A rename made by an admin script, a migration or another service reaches the same handler.
115
+
116
+ ## Using the parts on their own
117
+
118
+ The three subpackages share models but don't depend on each other:
119
+
120
+ - `pynamo.models` is a complete DynamoDB ORM without the API or streams.
121
+ - `pynamo.api` serves any pydantic model, not just `DynamoModel`s, so it can front data stored elsewhere.
122
+ - `pynamo.streams` validates change images as any pydantic model, so it can consume changes from a table written by other code.
123
+
124
+ ## Guides
125
+
126
+ - [Models](models.md): defining models and their keys, and reading and writing them with `get`, `query`, `scan`, `put`, `update` and `delete`.
127
+ - [GraphQL API](api.md): registering resolvers, how Python types map to GraphQL, and deploying the router to AppSync.
128
+ - [Streams](streams.md): registering change handlers, how a change finds its handler, and how failures and timeouts are retried.
129
+ - [Considerations](CONSIDERATIONS.md): the limitations and quirks of each part.
130
+
131
+ [`new_graphql_router.py`](new_graphql_router.py) is a complete AppSync API for users and their posts.
@@ -0,0 +1,23 @@
1
+ pynamo/__init__.py,sha256=wBlhnDTpza5w1rOC5yZ1yX3J-BT97pgYBfocubaK_4M,632
2
+ pynamo/api/__init__.py,sha256=MoArKYXkioyPQlF-RGEaBjD2J53DlhgE1e-6BM6vhHU,1087
3
+ pynamo/api/codec.py,sha256=SoMcLCbTIyhJ1SAetpP6XOIMHfSrTgnSQjPNOVrVw8c,11210
4
+ pynamo/api/errors.py,sha256=YfKVFcXyTIvWzE7t7yV5-5ZLoE17zUuFFGGUgn7pCWE,882
5
+ pynamo/api/events.py,sha256=B37UsPTPvRSj_zmHWmxVZrghhURi9WlHZ9EM_iq3r2w,2379
6
+ pynamo/api/resolvers.py,sha256=JnTNuraQ5PWO8Ur4meRFdrlDDPEtkhnZLnWeE0iRYrM,5033
7
+ pynamo/api/router.py,sha256=W5d_GDelYcS23BL5-O9jD2N_2RvHVOIo56D7_hocehQ,7844
8
+ pynamo/api/schema.py,sha256=Bw4Yr93t8MYhloDBikmJ-ZZQSVyF0DkbS9EZEgQ84HA,17700
9
+ pynamo/models/__init__.py,sha256=1gOZXlZFADmFcxBZ_8kkNJ1PO54__QXrme2iyOPZKu0,730
10
+ pynamo/models/base.py,sha256=Q_DUbymRk5SwUamVGR5tOMgUNE9jM8fGVvH8SMqn-9I,28558
11
+ pynamo/models/collection.py,sha256=v30SB_zr0rdYybeHrdTBD8lPnX3_Sn-Vzj4t-ZRoyWg,12721
12
+ pynamo/models/conditions.py,sha256=8saE-Oj2xhVHHzqU-DqpP1yWM_qH2iUf8HvvR2hue_s,10483
13
+ pynamo/models/indexes.py,sha256=ucfsYoypUT8nioNVIQI0KphnNQWBK39bhvIH8ntDFK4,12240
14
+ pynamo/models/meta.py,sha256=5RnzC-mnRP1JXu9NEZjTYSjFJALGX_Un8sc6anPZaQ8,5862
15
+ pynamo/models/updates.py,sha256=j5kR8dzGcSZpoaFXiulygcCFEWniqW5Qy8PsYGI3nxw,11355
16
+ pynamo/streams/__init__.py,sha256=8zAGGVLu5Q49YszVZFFya1egfnFpOTce0lumZyhplSo,536
17
+ pynamo/streams/events.py,sha256=vrT18EVIALKJhI_fIwbH6nCsIYuvaLLKNuTalhwnrpk,2865
18
+ pynamo/streams/exceptions.py,sha256=zpWxOX8X-dCHBiaIcWDumoC4WiEilwlxPRwWILb7DbQ,333
19
+ pynamo/streams/stream_handler.py,sha256=KfJuzxXp5fPAxbrb5mtjNqiFBdY_rHZxsySs1sn9IaQ,11355
20
+ aws_pynamo-0.1.0b1.dist-info/METADATA,sha256=0sa3lP9yN9Jjiwi_k8q7RXGxvS1ChS8QpMlUKDkGxz0,5054
21
+ aws_pynamo-0.1.0b1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
22
+ aws_pynamo-0.1.0b1.dist-info/licenses/LICENSE,sha256=Zoba0xUkDouwXe_Fcyk8mwZZvfN2trx1lTfVUoGaKNU,1069
23
+ aws_pynamo-0.1.0b1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kieran Bacon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pynamo/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Event-driven applications on DynamoDB and AWS AppSync, built from pydantic models.
2
+
3
+ A model is defined once and used at every stage of a change's life:
4
+
5
+ - `pynamo.models` stores models in a DynamoDB table as `DynamoModel`s.
6
+ - `pynamo.api` serves them through AppSync, with a `Router` as a direct Lambda resolver.
7
+ - `pynamo.streams` reacts to their changes, delivered through Kinesis, with a
8
+ `DynamoStreamHandler`.
9
+
10
+ Each subpackage is imported on its own; `pynamo.api` needs the `graphql` extra.
11
+ """
12
+
13
+ from .models import (
14
+ DynamoModel,
15
+ GlobalSecondaryIndex,
16
+ LocalIndex,
17
+ PrimaryIndex,
18
+ single_table_indexes,
19
+ )
pynamo/api/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """Serve pydantic models through AWS AppSync, with Lambda as a direct resolver.
2
+
3
+ `events` types the AppSync Lambda event, `errors` the exceptions raised, `resolvers`
4
+ the functions resolving root fields, `schema` the GraphQL schema built from them,
5
+ `codec` the conversion of arguments and results, and `router` the `Router` tying them
6
+ together. The public API is re-exported here.
7
+ """
8
+
9
+ from .errors import ArgumentError, GraphQLApiError, ResolverNotFoundError, SchemaError
10
+ from .events import (
11
+ AppSyncEvent,
12
+ AppSyncInfo,
13
+ AppSyncRequest,
14
+ CognitoIdentity,
15
+ IamIdentity,
16
+ Identity,
17
+ LambdaIdentity,
18
+ OidcIdentity,
19
+ PreviousResult,
20
+ )
21
+ from .router import Router
22
+ from .schema import NameConverter
23
+
24
+ __all__ = [
25
+ "AppSyncEvent",
26
+ "AppSyncInfo",
27
+ "AppSyncRequest",
28
+ "ArgumentError",
29
+ "CognitoIdentity",
30
+ "GraphQLApiError",
31
+ "IamIdentity",
32
+ "Identity",
33
+ "LambdaIdentity",
34
+ "NameConverter",
35
+ "OidcIdentity",
36
+ "PreviousResult",
37
+ "ResolverNotFoundError",
38
+ "Router",
39
+ "SchemaError",
40
+ ]
pynamo/api/codec.py ADDED
@@ -0,0 +1,303 @@
1
+ """Convert between AppSync's JSON values and the Python values resolvers work with.
2
+
3
+ `decode_arguments` turns an event's arguments into keyword arguments for a resolver:
4
+ GraphQL names become Python names, enum names become members, `AWSJSON` text is parsed,
5
+ and each value is then validated against its parameter's annotation with pydantic.
6
+
7
+ `encode_result` turns what a resolver returns into JSON for AppSync, following the
8
+ same type mapping as the schema. Only the fields the request selected are read, so a
9
+ property such as `User.posts` only runs when a client asks for it.
10
+ """
11
+
12
+ import datetime
13
+ import decimal
14
+ import enum
15
+ import functools
16
+ import json
17
+ import typing
18
+ from collections.abc import Mapping
19
+ from typing import Any, NamedTuple
20
+
21
+ import pydantic
22
+ import pydantic_core
23
+
24
+ from .errors import ArgumentError
25
+ from .resolvers import Argument, Resolver
26
+ from .schema import NameConverter, graphql_names, model_fields, unwrap_annotation
27
+
28
+ type Selection = dict[str, Selection]
29
+ """The fields selected from a value, each with the fields selected from it in turn."""
30
+
31
+
32
+ class _Field(NamedTuple):
33
+ """A model field as it's named in Python, and its annotation."""
34
+
35
+ python_name: str
36
+ annotation: Any
37
+
38
+
39
+ class _ArgumentSpec(NamedTuple):
40
+ """How to decode one of a resolver's arguments.
41
+
42
+ Attributes:
43
+ python_name: The parameter the argument is passed as
44
+ argument: The parameter's annotation and whether it has a default
45
+ nullable: Whether the parameter's annotation accepts None
46
+ adapter: Validates the decoded value against the parameter's annotation
47
+ """
48
+
49
+ python_name: str
50
+ argument: Argument
51
+ nullable: bool
52
+ adapter: pydantic.TypeAdapter[Any]
53
+
54
+
55
+ @functools.cache
56
+ def _fields(
57
+ model: type[pydantic.BaseModel], converter: NameConverter, input: bool
58
+ ) -> dict[str, _Field]:
59
+ """Get a model's exposed fields by GraphQL name, as the schema publishes them."""
60
+ exposed = model_fields(model, input=input)
61
+ names = graphql_names(exposed, converter, model.__name__)
62
+ return {
63
+ names[name]: _Field(name, field.annotation) for name, field in exposed.items()
64
+ }
65
+
66
+
67
+ def _decode(value: Any, annotation: Any, converter: NameConverter) -> Any:
68
+ """Convert a GraphQL input value into data pydantic can validate as `annotation`.
69
+
70
+ Raises:
71
+ ArgumentError: If the value doesn't have the shape the annotation requires
72
+ """
73
+ if value is None:
74
+ return None
75
+ annotation, _ = unwrap_annotation(annotation)
76
+ origin = typing.get_origin(annotation)
77
+
78
+ # Lists are decoded item by item
79
+ if origin in (list, set, frozenset):
80
+ if not isinstance(value, list):
81
+ raise ArgumentError(f"expected a list, got {value!r}")
82
+ (item,) = typing.get_args(annotation)
83
+ return [_decode(entry, item, converter) for entry in value]
84
+
85
+ # AWSJSON may arrive as JSON text rather than parsed
86
+ if annotation is dict or origin is dict:
87
+ if not isinstance(value, str):
88
+ return value
89
+ try:
90
+ return json.loads(value)
91
+ except json.JSONDecodeError as error:
92
+ raise ArgumentError(f"invalid JSON: {error}") from error
93
+
94
+ if not isinstance(annotation, type):
95
+ return value
96
+
97
+ # GraphQL enum values are member names, which pydantic would read as values
98
+ if issubclass(annotation, enum.Enum):
99
+ try:
100
+ return annotation[value]
101
+ except KeyError as error:
102
+ raise ArgumentError(
103
+ f"{value!r} isn't a member of {annotation.__name__}"
104
+ ) from error
105
+
106
+ # Input objects are renamed to Python field names, decoding each field in turn
107
+ if issubclass(annotation, pydantic.BaseModel):
108
+ if not isinstance(value, Mapping):
109
+ raise ArgumentError(f"expected an object, got {value!r}")
110
+ fields = _fields(annotation, converter, True)
111
+ decoded = {}
112
+ for name, entry in value.items():
113
+ if name not in fields:
114
+ raise ArgumentError(f"{annotation.__name__} has no field {name!r}")
115
+ field = fields[name]
116
+ decoded[field.python_name] = _decode(entry, field.annotation, converter)
117
+ return decoded
118
+
119
+ return value
120
+
121
+
122
+ @functools.cache
123
+ def _argument_specs(
124
+ resolver: Resolver, converter: NameConverter
125
+ ) -> dict[str, _ArgumentSpec]:
126
+ """Describe how to decode each of a resolver's arguments, by GraphQL name."""
127
+ arguments = resolver.arguments
128
+ names = graphql_names(arguments, converter, f"Resolver {resolver.name!r}")
129
+ specs = {}
130
+ for python_name, argument in arguments.items():
131
+ _, nullable = unwrap_annotation(argument.annotation)
132
+ specs[names[python_name]] = _ArgumentSpec(
133
+ python_name=python_name,
134
+ argument=argument,
135
+ nullable=nullable,
136
+ adapter=pydantic.TypeAdapter(argument.annotation),
137
+ )
138
+ return specs
139
+
140
+
141
+ def decode_arguments(
142
+ resolver: Resolver, arguments: Mapping[str, Any], converter: NameConverter
143
+ ) -> dict[str, Any]:
144
+ """Convert an event's arguments into validated keyword arguments for a resolver.
145
+
146
+ An omitted argument takes its parameter's default, or None if it has no default
147
+ and accepts None. An explicit null takes the default only if the parameter
148
+ doesn't accept None.
149
+
150
+ Args:
151
+ resolver: The resolver being called
152
+ arguments: The event's arguments, by GraphQL name
153
+ converter: The router's name converter
154
+
155
+ Returns:
156
+ The keyword arguments, by Python name
157
+
158
+ Raises:
159
+ ArgumentError: If an argument is unknown, missing, or fails validation
160
+ """
161
+ specs = _argument_specs(resolver, converter)
162
+ unknown = sorted(arguments.keys() - specs.keys())
163
+ if unknown:
164
+ raise ArgumentError(f"Unknown argument(s): {', '.join(unknown)}")
165
+
166
+ kwargs = {}
167
+ for graphql_name, spec in specs.items():
168
+ value = arguments.get(graphql_name)
169
+
170
+ # Omitted and null arguments fall back to the default, or to None
171
+ if value is None:
172
+ if spec.argument.has_default and not (
173
+ spec.nullable and graphql_name in arguments
174
+ ):
175
+ continue
176
+ if not spec.nullable:
177
+ raise ArgumentError(f"Argument {graphql_name!r} is required")
178
+ kwargs[spec.python_name] = None
179
+ continue
180
+
181
+ # Decode GraphQL's representation, then validate by Python field names
182
+ try:
183
+ decoded = _decode(value, spec.argument.annotation, converter)
184
+ kwargs[spec.python_name] = spec.adapter.validate_python(
185
+ decoded, by_alias=False, by_name=True
186
+ )
187
+ except ArgumentError as error:
188
+ raise ArgumentError(f"Argument {graphql_name!r}: {error}") from error
189
+ except pydantic.ValidationError as error:
190
+ raise ArgumentError(f"Argument {graphql_name!r}: {error}") from error
191
+ return kwargs
192
+
193
+
194
+ def _selection_tree(selection_set_list: list[str]) -> Selection:
195
+ """Build a selection tree from AppSync's `selectionSetList`.
196
+
197
+ E.g. `["name", "posts", "posts/content"]` is
198
+ `{"name": {}, "posts": {"content": {}}}`.
199
+ """
200
+ tree: Selection = {}
201
+ for path in selection_set_list:
202
+ node = tree
203
+ for name in path.split("/"):
204
+ node = node.setdefault(name, {})
205
+ return tree
206
+
207
+
208
+ def _jsonable(value: Any) -> Any:
209
+ """Make an `AWSJSON` value serialisable, keeping numbers as numbers.
210
+
211
+ DynamoDB returns numbers as `Decimal`, which `json` can't serialise and pydantic
212
+ would turn into strings.
213
+ """
214
+ if isinstance(value, Mapping):
215
+ return {str(key): _jsonable(entry) for key, entry in value.items()}
216
+ if isinstance(value, (list, tuple, set, frozenset)):
217
+ return [_jsonable(entry) for entry in value]
218
+ if isinstance(value, decimal.Decimal):
219
+ # Whole numbers stay integers, so `1` isn't returned as `1.0`
220
+ return int(value) if value == value.to_integral_value() else float(value)
221
+ return pydantic_core.to_jsonable_python(value)
222
+
223
+
224
+ def _encode(
225
+ value: Any, annotation: Any, selection: Selection, converter: NameConverter
226
+ ) -> Any:
227
+ """Convert a value into JSON for AppSync, reading only the selected fields.
228
+
229
+ Raises:
230
+ TypeError: If a model field holds something other than that model
231
+ """
232
+ if value is None:
233
+ return None
234
+ annotation, _ = unwrap_annotation(annotation)
235
+ origin = typing.get_origin(annotation)
236
+
237
+ # Lists are encoded item by item, with the same selection
238
+ if origin in (list, set, frozenset):
239
+ (item,) = typing.get_args(annotation)
240
+ return [_encode(entry, item, selection, converter) for entry in value]
241
+
242
+ if annotation is dict or origin is dict:
243
+ return _jsonable(value)
244
+
245
+ # Scalars that JSON can't represent directly
246
+ if isinstance(value, decimal.Decimal):
247
+ return float(value)
248
+ if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
249
+ return value.isoformat()
250
+
251
+ if not isinstance(annotation, type):
252
+ return value
253
+
254
+ # GraphQL enum values are member names; accept a raw value from `use_enum_values`
255
+ if issubclass(annotation, enum.Enum):
256
+ member = value if isinstance(value, annotation) else annotation(value)
257
+ return member.name
258
+
259
+ # Objects are read field by field, so unselected properties never run
260
+ if issubclass(annotation, pydantic.BaseModel):
261
+ # A generic model may be returned unparametrised, e.g. `Page` for `Page[User]`
262
+ origin_model = annotation.__pydantic_generic_metadata__["origin"] or annotation
263
+ if not isinstance(value, origin_model):
264
+ raise TypeError(
265
+ f"Expected {annotation.__name__}, got {type(value).__name__}"
266
+ )
267
+ fields = _fields(annotation, converter, False)
268
+ encoded = {}
269
+ for name, subselection in selection.items():
270
+ # Names AppSync resolves itself, such as __typename, aren't fields
271
+ if name not in fields:
272
+ continue
273
+ field = fields[name]
274
+ encoded[name] = _encode(
275
+ getattr(value, field.python_name),
276
+ field.annotation,
277
+ subselection,
278
+ converter,
279
+ )
280
+ return encoded
281
+
282
+ return value
283
+
284
+
285
+ def encode_result(
286
+ value: Any,
287
+ annotation: Any,
288
+ selection_set_list: list[str],
289
+ converter: NameConverter,
290
+ ) -> Any:
291
+ """Convert what a resolver returned into the JSON AppSync expects.
292
+
293
+ Args:
294
+ value: The resolver's return value
295
+ annotation: The resolver's return annotation
296
+ selection_set_list: The event's `info.selectionSetList`
297
+ converter: The router's name converter
298
+
299
+ Raises:
300
+ TypeError: If a model field holds something other than that model
301
+ """
302
+ selection = _selection_tree(selection_set_list)
303
+ return _encode(value, annotation, selection, converter)
pynamo/api/errors.py ADDED
@@ -0,0 +1,25 @@
1
+ """Exceptions raised while building a GraphQL schema or resolving an AppSync event.
2
+
3
+ AppSync reports an exception raised by a direct Lambda resolver to the client with the
4
+ exception's class name as the `errorType`, so these names are part of the API's contract.
5
+ """
6
+
7
+
8
+ class GraphQLApiError(Exception):
9
+ """Base class for every error raised by this package."""
10
+
11
+
12
+ class SchemaError(GraphQLApiError):
13
+ """A resolver or model can't be represented in a GraphQL schema.
14
+
15
+ Raised when the schema is built, e.g. for an unsupported annotation or a missing
16
+ return annotation, so mistakes surface at deploy time rather than per request.
17
+ """
18
+
19
+
20
+ class ResolverNotFoundError(GraphQLApiError):
21
+ """An event names a type and field that no resolver is registered for."""
22
+
23
+
24
+ class ArgumentError(GraphQLApiError):
25
+ """An event's arguments don't match the resolver's signature."""
pynamo/api/events.py ADDED
@@ -0,0 +1,87 @@
1
+ """Typed shapes of the events AppSync sends to a Lambda function used as a direct resolver.
2
+
3
+ AppSync invokes the function once per resolved field with an `AppSyncEvent`. The event
4
+ says which field is being resolved (`info`), the arguments it was given, the caller's
5
+ `identity` and, for fields on a type other than `Query` or `Mutation`, the parent object
6
+ (`source`). What the function returns becomes the field's value.
7
+ """
8
+
9
+ from typing import Any, NotRequired, TypedDict
10
+
11
+
12
+ class CognitoIdentity(TypedDict):
13
+ """The caller of an API authorised by a Cognito user pool."""
14
+
15
+ sub: str
16
+ issuer: str
17
+ username: str
18
+ claims: dict[str, Any]
19
+ sourceIp: list[str]
20
+ defaultAuthStrategy: str
21
+ groups: list[str] | None
22
+
23
+
24
+ class OidcIdentity(TypedDict):
25
+ """The caller of an API authorised by an OpenID Connect provider."""
26
+
27
+ sub: str
28
+ issuer: str
29
+ claims: dict[str, Any]
30
+
31
+
32
+ class IamIdentity(TypedDict):
33
+ """The caller of an API authorised by AWS IAM."""
34
+
35
+ accountId: str
36
+ cognitoIdentityPoolId: str | None
37
+ cognitoIdentityId: str | None
38
+ sourceIp: list[str]
39
+ username: str
40
+ userArn: str
41
+ cognitoIdentityAuthType: str | None
42
+ cognitoIdentityAuthProvider: str | None
43
+
44
+
45
+ class LambdaIdentity(TypedDict):
46
+ """The caller of an API authorised by a Lambda authoriser."""
47
+
48
+ resolverContext: dict[str, Any]
49
+
50
+
51
+ type Identity = CognitoIdentity | OidcIdentity | IamIdentity | LambdaIdentity
52
+ """The caller, in the form of the API's authorisation mode; API key callers have none."""
53
+
54
+
55
+ class AppSyncInfo(TypedDict):
56
+ """Which field is being resolved and what the request selected from it."""
57
+
58
+ parentTypeName: str
59
+ fieldName: str
60
+ variables: dict[str, Any]
61
+ selectionSetList: list[str]
62
+ selectionSetGraphQL: str
63
+
64
+
65
+ class AppSyncRequest(TypedDict):
66
+ """The HTTP request the GraphQL operation arrived in."""
67
+
68
+ headers: dict[str, str]
69
+ domainName: NotRequired[str | None]
70
+
71
+
72
+ class PreviousResult(TypedDict):
73
+ """The result of the previous function in a pipeline resolver."""
74
+
75
+ result: Any
76
+
77
+
78
+ class AppSyncEvent(TypedDict):
79
+ """The event AppSync invokes a direct Lambda resolver with, for a single field."""
80
+
81
+ arguments: dict[str, Any]
82
+ identity: Identity | None
83
+ source: dict[str, Any] | None
84
+ request: AppSyncRequest
85
+ info: AppSyncInfo
86
+ prev: PreviousResult | None
87
+ stash: dict[str, Any]