seampact-codegen 1.0.0__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.
Files changed (76) hide show
  1. seampact/codegen/__init__.py +2 -0
  2. seampact/codegen/boot_check_hooks.py +38 -0
  3. seampact/codegen/contract_module.py +146 -0
  4. seampact/codegen/credentials_classes.py +99 -0
  5. seampact/codegen/handler_forms.py +132 -0
  6. seampact/codegen/input_schemas.py +130 -0
  7. seampact/codegen/kept_forms.py +522 -0
  8. seampact/codegen/matrix_row.py +23 -0
  9. seampact/codegen/names.py +146 -0
  10. seampact/codegen/native_docs_file.py +169 -0
  11. seampact/codegen/operation_types.py +425 -0
  12. seampact/codegen/placement_lines.py +79 -0
  13. seampact/codegen/printer.py +196 -0
  14. seampact/codegen/py.typed +0 -0
  15. seampact/codegen/pydantic_forms.py +53 -0
  16. seampact/codegen/pydantic_layout.py +178 -0
  17. seampact/codegen/pydantic_models.py +405 -0
  18. seampact/codegen/redacted_members.py +47 -0
  19. seampact/codegen/refusals.py +84 -0
  20. seampact/codegen/request_deadline.py +68 -0
  21. seampact/codegen/response_header_forms.py +73 -0
  22. seampact/codegen/restricted_sort_keys.py +18 -0
  23. seampact/codegen/route_helpers.py +109 -0
  24. seampact/codegen/routes.py +139 -0
  25. seampact/codegen/runtime/__init__.py +7 -0
  26. seampact/codegen/runtime/access_kinds.py +24 -0
  27. seampact/codegen/runtime/access_steps.py +520 -0
  28. seampact/codegen/runtime/body_reader.py +64 -0
  29. seampact/codegen/runtime/cache_headers.py +89 -0
  30. seampact/codegen/runtime/contract.py +232 -0
  31. seampact/codegen/runtime/cors_preflight.py +20 -0
  32. seampact/codegen/runtime/deadline.py +72 -0
  33. seampact/codegen/runtime/digests.py +98 -0
  34. seampact/codegen/runtime/failures.py +33 -0
  35. seampact/codegen/runtime/field_rights.py +193 -0
  36. seampact/codegen/runtime/framework_routes.py +36 -0
  37. seampact/codegen/runtime/framework_versions.py +91 -0
  38. seampact/codegen/runtime/handler_call.py +31 -0
  39. seampact/codegen/runtime/handler_reply.py +148 -0
  40. seampact/codegen/runtime/hinted_values.py +48 -0
  41. seampact/codegen/runtime/hook_check.py +77 -0
  42. seampact/codegen/runtime/idempotency.py +279 -0
  43. seampact/codegen/runtime/input_decoding.py +226 -0
  44. seampact/codegen/runtime/ir_view.py +47 -0
  45. seampact/codegen/runtime/native_docs.py +130 -0
  46. seampact/codegen/runtime/page_facts.py +33 -0
  47. seampact/codegen/runtime/page_reply.py +396 -0
  48. seampact/codegen/runtime/pattern.py +69 -0
  49. seampact/codegen/runtime/principal_members.py +41 -0
  50. seampact/codegen/runtime/public_origin.py +102 -0
  51. seampact/codegen/runtime/pydantic/__init__.py +165 -0
  52. seampact/codegen/runtime/pydantic/checked_input.py +52 -0
  53. seampact/codegen/runtime/pydantic/contract_input.py +183 -0
  54. seampact/codegen/runtime/pydantic/issues.py +142 -0
  55. seampact/codegen/runtime/raw_target.py +103 -0
  56. seampact/codegen/runtime/replies.py +144 -0
  57. seampact/codegen/runtime/reply_verdict.py +215 -0
  58. seampact/codegen/runtime/requirement_params.py +170 -0
  59. seampact/codegen/runtime/response_header_entries.py +226 -0
  60. seampact/codegen/runtime/response_headers.py +114 -0
  61. seampact/codegen/runtime/route_match.py +88 -0
  62. seampact/codegen/runtime/run_settings.py +35 -0
  63. seampact/codegen/runtime/signature_header.py +92 -0
  64. seampact/codegen/runtime/sync_driver.py +35 -0
  65. seampact/codegen/runtime/templates.py +132 -0
  66. seampact/codegen/runtime/uuid_text.py +7 -0
  67. seampact/codegen/runtime/value_rules.py +218 -0
  68. seampact/codegen/runtime/version.py +59 -0
  69. seampact/codegen/runtime/version_token.py +108 -0
  70. seampact/codegen/runtime/wire_codec.py +229 -0
  71. seampact/codegen/runtime/wire_values.py +260 -0
  72. seampact/codegen/source_lines.py +35 -0
  73. seampact_codegen-1.0.0.dist-info/METADATA +18 -0
  74. seampact_codegen-1.0.0.dist-info/RECORD +76 -0
  75. seampact_codegen-1.0.0.dist-info/WHEEL +4 -0
  76. seampact_codegen-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,226 @@
1
+ """The entries a success's derived response headers are written from (ADR 0004 section 7), resolved from the IR: the
2
+ Deprecation and Sunset dates and the successor `Link` of a deprecated operation, and the item field the strong `ETag`
3
+ of an item versioned by `If-Match` names (grammar section 6), or why the boundary cannot write a header. The contract
4
+ resolves them once per process, and the generators refuse, by name, each header that has a problem."""
5
+
6
+ import re
7
+ from collections.abc import Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from datetime import UTC, datetime
10
+ from enum import Enum
11
+ from typing import Final
12
+
13
+ from seampact.codegen.runtime.ir_view import IrMap, ir_list, ir_map, ir_string
14
+
15
+ _CONCURRENCY_DERIVATION: Final = "concurrency.version"
16
+ _HEADER_SOURCE: Final = "header"
17
+ _DEPRECATION: Final = "deprecation"
18
+ _SUNSET: Final = "sunset"
19
+ _SUCCESSOR_LINK: Final = "successorLink"
20
+ _CALENDAR_DATE: Final = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
21
+ _WEEKDAYS: Final = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
22
+ _MONTHS: Final = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
23
+ _EPOCH: Final = datetime(1970, 1, 1, tzinfo=UTC)
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class TextHeader:
28
+ """A fixed text: a deprecation or sunset date."""
29
+
30
+ name: str
31
+ value: str
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class SuccessorLinkHeader:
36
+ """The successor's link: `path` the successor's mounted path with `{name}` params, each the request's own."""
37
+
38
+ name: str
39
+ path: str
40
+ rel: str
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class EntityTagHeader:
45
+ """The strong entity tag of the item's version `field`."""
46
+
47
+ name: str
48
+ field: str
49
+
50
+
51
+ type HeaderEntry = TextHeader | SuccessorLinkHeader | EntityTagHeader
52
+
53
+
54
+ class ProblemKind(Enum):
55
+ """Whether a header the boundary cannot write waits for a later release, or breaks a rule the compiler keeps."""
56
+
57
+ WAITING = "waiting"
58
+ INCONSISTENT = "inconsistent"
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class HeaderProblem:
63
+ """Why the boundary cannot write a response header: `code` the form or the IR rule, `description` the header."""
64
+
65
+ kind: ProblemKind
66
+ code: str
67
+ description: str
68
+
69
+
70
+ def response_header_entry(
71
+ api_id: str, mount: str, operations: Sequence[IrMap], operation: IrMap, header: IrMap
72
+ ) -> HeaderEntry | HeaderProblem | None:
73
+ """The entry the boundary writes `header` of `operation`'s response from, or why it cannot; None for a header
74
+ another step writes."""
75
+ semantic = ir_string(header, "semantic")
76
+ name = (ir_string(header, "name") or "").lower()
77
+
78
+ if semantic in (_DEPRECATION, _SUNSET, _SUCCESSOR_LINK):
79
+ return _deprecation_entry(api_id, mount, operations, operation, name, semantic)
80
+
81
+ derived_from = ir_map(header, "derivedFrom")
82
+
83
+ if ir_string(derived_from, "derivation") != _CONCURRENCY_DERIVATION:
84
+ return None
85
+
86
+ origins = ir_list(derived_from, "from")
87
+
88
+ return _entity_tag_entry(operations, operation, name, origins[0] if origins else None)
89
+
90
+
91
+ def deprecation_value(day: datetime) -> str:
92
+ """RFC 9745: `@` and the unix seconds of the day at 00:00:00 UTC."""
93
+ return f"@{int((day - _EPOCH).total_seconds())}"
94
+
95
+
96
+ def sunset_value(day: datetime) -> str:
97
+ """RFC 8594 and RFC 9110 section 5.6.7: the IMF-fixdate of the day at 00:00:00 GMT."""
98
+ weekday, month = _WEEKDAYS[day.weekday()], _MONTHS[day.month - 1]
99
+
100
+ return f"{weekday}, {day.day:02d} {month} {day.year:04d} 00:00:00 GMT"
101
+
102
+
103
+ def _deprecation_entry(
104
+ api_id: str, mount: str, operations: Sequence[IrMap], operation: IrMap, name: str, semantic: str
105
+ ) -> HeaderEntry | HeaderProblem:
106
+ deprecated = ir_map(operation, "deprecated")
107
+
108
+ if not deprecated:
109
+ return HeaderProblem(
110
+ ProblemKind.INCONSISTENT,
111
+ "ir.deprecation.headers",
112
+ f"A {semantic} header on an operation that is not deprecated",
113
+ )
114
+
115
+ if semantic == _SUCCESSOR_LINK:
116
+ return _successor_link_entry(api_id, mount, operations, deprecated, name)
117
+
118
+ date = ir_string(deprecated, "since" if semantic == _DEPRECATION else semantic)
119
+ day = None if date is None else _calendar_day(date)
120
+
121
+ if day is None:
122
+ return HeaderProblem(
123
+ ProblemKind.INCONSISTENT, "ir.deprecation.since", f"The {semantic} header's date is not a calendar date"
124
+ )
125
+
126
+ return TextHeader(name, deprecation_value(day) if semantic == _DEPRECATION else sunset_value(day))
127
+
128
+
129
+ def _successor_link_entry(
130
+ api_id: str, mount: str, operations: Sequence[IrMap], deprecated: IrMap, name: str
131
+ ) -> HeaderEntry | HeaderProblem:
132
+ successor = ir_map(deprecated, "successor")
133
+ successor_id = ir_string(successor, "id")
134
+ rel = ir_string(deprecated, "successorRel")
135
+
136
+ if successor_id is None or rel is None:
137
+ return HeaderProblem(
138
+ ProblemKind.INCONSISTENT,
139
+ "ir.deprecation.headers",
140
+ "A successor link header on an operation without its successor and relation",
141
+ )
142
+
143
+ successor_api = ir_string(successor, "api")
144
+
145
+ if successor_api != api_id:
146
+ return HeaderProblem(
147
+ ProblemKind.WAITING,
148
+ "deprecated.successor.otherApi",
149
+ f"The successor link to operation '{successor_id}' of api '{successor_api}'",
150
+ )
151
+
152
+ successor_operation = next((item for item in operations if ir_string(item, "id") == successor_id), None)
153
+
154
+ if successor_operation is None:
155
+ return HeaderProblem(
156
+ ProblemKind.INCONSISTENT,
157
+ "ir.deprecation.successor",
158
+ f"The successor '{successor_id}' is no operation of the api",
159
+ )
160
+
161
+ return SuccessorLinkHeader(name, mount + (ir_string(successor_operation, "path") or ""), rel)
162
+
163
+
164
+ def _calendar_day(date: str) -> datetime | None:
165
+ if _CALENDAR_DATE.fullmatch(date) is None:
166
+ return None
167
+
168
+ try:
169
+ return datetime.fromisoformat(date).replace(tzinfo=UTC)
170
+ except ValueError:
171
+ return None
172
+
173
+
174
+ def _entity_tag_entry(
175
+ operations: Sequence[IrMap], operation: IrMap, name: str, resource_origin: object
176
+ ) -> HeaderEntry | HeaderProblem:
177
+ """The tag's field: the operation's own `If-Match` version, else that of the `If-Match` writes of the resource the
178
+ tag is derived from (a read has no `concurrency` of its own)."""
179
+ own_field = _if_match_field(operation)
180
+
181
+ if own_field is not None:
182
+ return EntityTagHeader(name, own_field)
183
+
184
+ fields = {
185
+ field
186
+ for candidate in operations
187
+ if (field := _if_match_field(candidate)) is not None
188
+ and _same_origin(ir_list(ir_map(ir_map(candidate, "concurrency"), "derivedFrom"), "from"), resource_origin)
189
+ }
190
+
191
+ if len(fields) == 1:
192
+ return EntityTagHeader(name, next(iter(fields)))
193
+
194
+ if fields:
195
+ return HeaderProblem(
196
+ ProblemKind.INCONSISTENT,
197
+ "concurrency.etag.field",
198
+ "The If-Match writes of the resource this ETag is derived from compare different fields",
199
+ )
200
+
201
+ return HeaderProblem(
202
+ ProblemKind.WAITING,
203
+ "concurrency.etag.withoutWrite",
204
+ "An ETag of a resource whose If-Match writes are not operations of this api",
205
+ )
206
+
207
+
208
+ def _if_match_field(operation: IrMap) -> str | None:
209
+ concurrency = ir_map(operation, "concurrency")
210
+
211
+ if ir_string(ir_map(concurrency, "version"), "in") != _HEADER_SOURCE:
212
+ return None
213
+
214
+ return ir_string(concurrency, "field")
215
+
216
+
217
+ def _same_origin(write_origins: Sequence[object], resource_origin: object) -> bool:
218
+ if not write_origins or not isinstance(resource_origin, Mapping):
219
+ return False
220
+
221
+ write_origin = write_origins[0]
222
+
223
+ if not isinstance(write_origin, Mapping):
224
+ return False
225
+
226
+ return all(write_origin.get(key) == resource_origin.get(key) for key in ("layer", "pointer"))
@@ -0,0 +1,114 @@
1
+ """The response headers a success writes from its response's entries (ADR 0004 section 7): the Deprecation and Sunset
2
+ dates and the successor `Link` of a deprecated operation, and the strong `ETag` of an item versioned by `If-Match`
3
+ (grammar section 6). The idempotency replay, `cache.etag` and the paging headers are written by their own steps."""
4
+
5
+ import re
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass
8
+ from typing import Final
9
+ from urllib.parse import quote
10
+
11
+ from seampact.codegen.runtime.contract import ApiContract
12
+ from seampact.codegen.runtime.failures import BoundaryFailureError
13
+ from seampact.codegen.runtime.ir_view import IrMap, ir_int
14
+ from seampact.codegen.runtime.replies import Reply
15
+ from seampact.codegen.runtime.response_header_entries import (
16
+ EntityTagHeader,
17
+ HeaderProblem,
18
+ SuccessorLinkHeader,
19
+ TextHeader,
20
+ )
21
+ from seampact.codegen.runtime.value_rules import MAX_SAFE_INTEGER
22
+ from seampact.codegen.runtime.wire_values import decoded_segment
23
+
24
+ _PATH_PARAM: Final = re.compile(r"\{([^}]+)\}")
25
+ # RFC 9110 section 8.8.3 `etagc`: a version whose text holds another character makes no strong entity tag.
26
+ _ENTITY_TAG_TEXT: Final = re.compile(r"[\x21\x23-\x7e]*")
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class DerivedHeaders:
31
+ """A success's derived headers: those of a success, and the entity tag, which a 304 keeps too."""
32
+
33
+ success_headers: tuple[tuple[str, str], ...]
34
+ entity_tag: tuple[str, str] | None
35
+
36
+
37
+ def derived_response_headers(
38
+ contract: ApiContract, operation_id: str, response: IrMap, item: object, raw_parameters: Mapping[str, str]
39
+ ) -> DerivedHeaders:
40
+ """The derived headers of `response` for the handler's item in wire names, from the entries the contract resolved
41
+ once. Raises `BoundaryFailureError` for an item whose version field is no safe integer or entity tag text, or a
42
+ header the generator should have refused."""
43
+ success_headers: list[tuple[str, str]] = []
44
+ entity_tag: tuple[str, str] | None = None
45
+
46
+ for entry in contract.response_header_entries(operation_id, ir_int(response, "status") or 0):
47
+ if isinstance(entry, HeaderProblem):
48
+ raise BoundaryFailureError(
49
+ f"seampact: operation '{operation_id}' cannot write {entry.description} ({entry.code}); regenerate "
50
+ "the api."
51
+ )
52
+
53
+ if isinstance(entry, TextHeader):
54
+ success_headers.append((entry.name, entry.value))
55
+ elif isinstance(entry, SuccessorLinkHeader):
56
+ success_headers.append((entry.name, successor_link(entry.path, entry.rel, raw_parameters)))
57
+ elif isinstance(entry, EntityTagHeader):
58
+ entity_tag = (entry.name, _version_entity_tag(operation_id, entry.field, item))
59
+
60
+ return DerivedHeaders(tuple(success_headers), entity_tag)
61
+
62
+
63
+ def successor_link(path: str, rel: str, raw_parameters: Mapping[str, str]) -> str:
64
+ """RFC 8288: `<target>; rel="<rel>"`, each param of the successor's path the request's param of the same name, its
65
+ decoded value encoded as one path segment, so a value never breaks out of the link."""
66
+
67
+ def segment(placeholder: re.Match[str]) -> str:
68
+ name = placeholder.group(1)
69
+ raw = raw_parameters.get(name)
70
+ decoded = None if raw is None else decoded_segment(raw)
71
+
72
+ if decoded is None:
73
+ raise BoundaryFailureError(
74
+ f"seampact: the successor path '{path}' names the param '{name}', which the request has not as UTF-8 "
75
+ "text; regenerate the api."
76
+ )
77
+
78
+ # Every byte outside RFC 3986 `unreserved` is percent-encoded, as every target writes the link.
79
+ return quote(decoded, safe="")
80
+
81
+ return f'<{_PATH_PARAM.sub(segment, path)}>; rel="{rel}"'
82
+
83
+
84
+ def _version_entity_tag(operation_id: str, field: str, item: object) -> str:
85
+ """The item's version as a strong entity tag, `"7"`: the field's integer or text, as the client sends it back."""
86
+ version = item.get(field) if isinstance(item, Mapping) else None
87
+ text = str(version) if _is_safe_integer(version) else version
88
+
89
+ if not isinstance(text, str) or _ENTITY_TAG_TEXT.fullmatch(text) is None:
90
+ raise BoundaryFailureError(
91
+ f"seampact: the handler of '{operation_id}' returned an item whose version field '{field}' is no safe "
92
+ "integer or entity tag text, so its ETag cannot be written; return the item with its version."
93
+ )
94
+
95
+ return f'"{text}"'
96
+
97
+
98
+ # A version beyond 2^53 - 1 is no ETag: a JavaScript client could not hold it exactly, so every target refuses it.
99
+ def _is_safe_integer(version: object) -> bool:
100
+ return isinstance(version, int) and not isinstance(version, bool) and abs(version) <= MAX_SAFE_INTEGER
101
+
102
+
103
+ def with_entity_tag(headers: tuple[tuple[str, str], ...], derived: DerivedHeaders) -> tuple[tuple[str, str], ...]:
104
+ """`headers` and the item's entity tag, which `cache.etag` then uses (grammar section 6)."""
105
+ return headers if derived.entity_tag is None else (*headers, derived.entity_tag)
106
+
107
+
108
+ def with_success_headers(reply: Reply, derived: DerivedHeaders, success_status: int) -> Reply:
109
+ """`reply` with the success headers; the cache's 304 for a `success_status` reply is no success, so it keeps only
110
+ its entity tag (ADR 0004 section 7)."""
111
+ if reply.status != success_status or not derived.success_headers:
112
+ return reply
113
+
114
+ return Reply(reply.status, (*reply.headers, *derived.success_headers), reply.body)
@@ -0,0 +1,88 @@
1
+ """The contract's operations as the boundary matches them against the raw path: each route's method and template
2
+ split into segments, literal segments compared undecoded, and the most specific template tried first."""
3
+
4
+ import re
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ from functools import cmp_to_key
8
+ from typing import Final
9
+ from urllib.parse import unquote_to_bytes
10
+
11
+ _PARAMETER: Final = re.compile(r"\{([^{}]+)\}")
12
+ _DOT_SEGMENTS: Final = frozenset({b".", b".."})
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class TemplateSegment:
17
+ literal: bool
18
+ text: str
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class ContractRoute:
23
+ operation_id: str
24
+ method: str
25
+ segments: tuple[TemplateSegment, ...]
26
+ base_path: str
27
+
28
+ @classmethod
29
+ def of(cls, operation_id: str, method: str, template: str, base_path: str) -> "ContractRoute":
30
+ """`template` is the mounted contract path, such as `/v1/tasks/{taskId}`."""
31
+ segments = []
32
+
33
+ for segment in template.split("/")[1:]:
34
+ parameter = _PARAMETER.fullmatch(segment)
35
+ segments.append(TemplateSegment(False, parameter.group(1)) if parameter else TemplateSegment(True, segment))
36
+
37
+ return cls(operation_id, method.upper(), tuple(segments), base_path)
38
+
39
+ def match(self, raw_segments: Sequence[str]) -> dict[str, str] | None:
40
+ """The raw path parameters when the segments match: a literal segment matches its text exactly, undecoded;
41
+ a parameter matches a segment that is not empty, holds no raw `;` (ADR 0026 "Routes"; an encoded `%3B` is
42
+ data), and is no dot segment once decoded."""
43
+ if len(raw_segments) != len(self.segments):
44
+ return None
45
+
46
+ parameters: dict[str, str] = {}
47
+
48
+ for segment, raw in zip(self.segments, raw_segments, strict=True):
49
+ if segment.literal:
50
+ if raw != segment.text:
51
+ return None
52
+ continue
53
+
54
+ decoded = unquote_to_bytes(raw)
55
+
56
+ if raw == "" or ";" in raw or decoded in _DOT_SEGMENTS:
57
+ return None
58
+
59
+ parameters[segment.text] = raw
60
+
61
+ return parameters
62
+
63
+
64
+ @dataclass(frozen=True, slots=True)
65
+ class RouteMatch:
66
+ """The operation a raw path matched with its raw parameters; `operation_id` None for a path under one of the
67
+ api's base paths that no contract route serves with this method (the api's `notFound`)."""
68
+
69
+ operation_id: str | None
70
+ raw_parameters: dict[str, str]
71
+
72
+
73
+ def most_specific_first(routes: Sequence[ContractRoute]) -> list[ContractRoute]:
74
+ """Literal segments sort before parameters at the first segment where two templates differ."""
75
+ return sorted(routes, key=cmp_to_key(_compare_specificity))
76
+
77
+
78
+ def _compare_specificity(first: ContractRoute, second: ContractRoute) -> int:
79
+ for index, segment in enumerate(first.segments):
80
+ if index >= len(second.segments):
81
+ return 1
82
+
83
+ other = second.segments[index]
84
+
85
+ if segment.literal != other.literal:
86
+ return -1 if segment.literal else 1
87
+
88
+ return len(first.segments) - len(second.segments)
@@ -0,0 +1,35 @@
1
+ """The run-time settings and generated types every Pydantic target's `bind_<api>()` hands its runtime: the settings
2
+ the app gives in code, per api and per operation, and the generated types of each operation."""
3
+
4
+ from collections.abc import Mapping
5
+ from dataclasses import dataclass
6
+
7
+ from seampact.codegen.runtime.reply_verdict import ResponsesMode
8
+
9
+
10
+ @dataclass(frozen=True, slots=True, kw_only=True)
11
+ class OperationSettings:
12
+ """The run-time settings of one operation, which win over the api's."""
13
+
14
+ responses: ResponsesMode | None = None
15
+
16
+
17
+ @dataclass(frozen=True, slots=True, kw_only=True)
18
+ class RunSettings:
19
+ """The run-time settings `bind_<api>()` takes from the app's own settings; None keeps the target option."""
20
+
21
+ responses: ResponsesMode | None
22
+ body_validation: bool | None
23
+ operations: Mapping[str, OperationSettings]
24
+ public_origin: str | None
25
+
26
+
27
+ @dataclass(frozen=True, slots=True, kw_only=True)
28
+ class OperationTypes:
29
+ """The generated types of one operation the runtime builds and reads: its request, its success classes by status,
30
+ its errors class, and the model of its body's rule proofs when it has some."""
31
+
32
+ request: type
33
+ responses: tuple[tuple[int, type], ...]
34
+ errors: type
35
+ proofs: type | None = None
@@ -0,0 +1,92 @@
1
+ """A template scheme's signature header parsed by its format (ADR 0013 "Test vectors"), as every target parses it:
2
+ comma-separated `name=value` pairs (`t={ts},v1={sig}`), each slot read from its pair and a repeated signature pair
3
+ adding a candidate, or a literal prefix before `{sig}` (`sha256={sig}`)."""
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from typing import ClassVar, Final
8
+
9
+ from seampact.hooks._redaction import RedactedRepr
10
+
11
+ _TIMESTAMP_SLOT: Final = "{ts}"
12
+ _SIGNATURE_SLOT: Final = "{sig}"
13
+ _DIGITS: Final = re.compile(r"[0-9]+")
14
+ _PAIR_FORMAT: Final = re.compile(r"[A-Za-z0-9_-]+=\{(ts|sig)\}(,[A-Za-z0-9_-]+=\{(ts|sig)\})*")
15
+
16
+
17
+ @dataclass(frozen=True, slots=True, repr=False)
18
+ class SignatureHeader(RedactedRepr):
19
+ """The signed timestamp text when the format has one, and every signature the header carries, still encoded."""
20
+
21
+ _REDACTED_FIELDS: ClassVar[frozenset[str]] = frozenset({"candidate_signatures"})
22
+
23
+ timestamp: str | None
24
+ candidate_signatures: tuple[str, ...]
25
+
26
+
27
+ def parsed_signature_header(format_: str, header: str | None) -> SignatureHeader | None:
28
+ """None for a missing or malformed header: no signature, a timestamp that is not digits, a repeated timestamp,
29
+ or a pair that is not `name=value`."""
30
+ if header is None or header.strip() == "":
31
+ return None
32
+
33
+ if _PAIR_FORMAT.fullmatch(format_) is None:
34
+ return _prefixed(format_, header)
35
+
36
+ timestamp_name: str | None = None
37
+ signature_name: str | None = None
38
+
39
+ for pair in format_.split(","):
40
+ name, _, slot = pair.partition("=")
41
+
42
+ if slot == _TIMESTAMP_SLOT:
43
+ timestamp_name = name
44
+ elif slot == _SIGNATURE_SLOT:
45
+ signature_name = name
46
+
47
+ if signature_name is None:
48
+ return None
49
+
50
+ return _pairs(header, timestamp_name, signature_name)
51
+
52
+
53
+ def _pairs(header: str, timestamp_name: str | None, signature_name: str) -> SignatureHeader | None:
54
+ timestamp: str | None = None
55
+ candidates: list[str] = []
56
+
57
+ for pair in header.split(","):
58
+ separator = pair.find("=")
59
+
60
+ if separator <= 0:
61
+ return None
62
+
63
+ name = pair[:separator].strip()
64
+ value = pair[separator + 1 :].strip()
65
+
66
+ if name == timestamp_name:
67
+ if timestamp is not None or _DIGITS.fullmatch(value) is None:
68
+ return None
69
+
70
+ timestamp = value
71
+ elif name == signature_name:
72
+ if value == "":
73
+ return None
74
+
75
+ candidates.append(value)
76
+
77
+ if not candidates or (timestamp_name is not None and timestamp is None):
78
+ return None
79
+
80
+ return SignatureHeader(timestamp, tuple(candidates))
81
+
82
+
83
+ def _prefixed(format_: str, header: str) -> SignatureHeader | None:
84
+ if not format_.endswith(_SIGNATURE_SLOT):
85
+ return None
86
+
87
+ prefix = format_[: -len(_SIGNATURE_SLOT)]
88
+
89
+ if not header.startswith(prefix) or len(header) == len(prefix):
90
+ return None
91
+
92
+ return SignatureHeader(None, (header[len(prefix) :],))
@@ -0,0 +1,35 @@
1
+ """Runs a step written as a coroutine from sync code (a WSGI placement): the step must finish without suspending,
2
+ since there is no event loop to resume it; a suspension is the boundary's own failure, answered with the api's 500."""
3
+
4
+ import inspect
5
+ from collections.abc import Awaitable, Callable, Coroutine
6
+
7
+ from seampact.codegen.runtime.failures import BoundaryFailureError
8
+
9
+
10
+ def run_without_suspension[T](step: Coroutine[object, object, T]) -> T:
11
+ """Raises `BoundaryFailureError` when the step suspends, naming the awaitable it waited on."""
12
+ try:
13
+ awaited = step.send(None)
14
+ except StopIteration as finished:
15
+ result: T = finished.value
16
+ return result
17
+
18
+ step.close()
19
+
20
+ raise BoundaryFailureError(
21
+ f"seampact: a boundary step suspended on {awaited!r} under a sync placement; a hook or handler the sync "
22
+ "placement calls must be a plain def, or run the app under ASGI."
23
+ )
24
+
25
+
26
+ async def call_without_suspension[A, T](method: Callable[[A], T | Awaitable[T]], argument: A, /) -> T:
27
+ """The hook caller of a sync placement: a `def` answers at once, an `async def` is awaited in the same step, and
28
+ `run_without_suspension` refuses it by name when it suspends."""
29
+ answer = method(argument)
30
+
31
+ if inspect.isawaitable(answer):
32
+ awaited: T = await answer
33
+ return awaited
34
+
35
+ return answer