fractal-io-server 0.1.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,4 @@
1
+ node_modules/
2
+ dist/
3
+ __pycache__/
4
+ .venv/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: fractal-io-server
3
+ Version: 0.1.0
4
+ Summary: Fractal IO server SDK: resolve templates into screens, read action messages and build responses.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: jsonschema>=4.18
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest>=8; extra == 'dev'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # fractal-io-server
14
+
15
+ Fractal IO server SDK for Python (3.10 or later). Import name: `fractal_server`.
16
+
17
+ **Status: draft 0.1.0.** The schemas it carries are those of `@fractal-io-technology/spec` 2.2.1.
18
+
19
+ ```
20
+ pip install fractal-io-server
21
+ ```
22
+
23
+ ## Use
24
+
25
+ ```python
26
+ from fractal_server import FractalBindError, error, navigate, parse_action, resolve, respond, screen
27
+
28
+ # GET /screens/booking: bind the request's data to the template.
29
+ booking = resolve(template, {"flight": {"code": "UA-402"}, "passenger": {"name": "Alex Rosario"}})
30
+
31
+ # POST /actions: read what the user did and answer.
32
+ action = parse_action(request.json())
33
+ if action["name"] == "confirm_booking":
34
+ seat = book(action.get("context", {}).get("flight"), action.get("values", {}).get("passenger_name"))
35
+ return respond(navigate("confirmation")) if seat else respond(error("sold_out", "No seats left"))
36
+ ```
37
+
38
+ | Function | Returns | Raises |
39
+ | --- | --- | --- |
40
+ | `resolve(template, data)` | the screen document | `FractalBindError`, with `code` `BIND_PATH_NOT_FOUND` (and `bind_path`) or `BIND_TYPE_MISMATCH` |
41
+ | `parse_action(body)` | the action: `name`, `event_type`, `timestamp`, and when present `screen_id`, `source_block_id`, `context`, `values` | `FractalActionError`, with `issues` |
42
+ | `respond(*messages)` | `{"fractal": "1.0", "messages": [...]}` | `FractalResponseError`, with `issues` |
43
+ | `screen(document)`, `navigate(screen_id)`, `error(code, message)` | one message for `respond` | |
44
+
45
+ `resolve` never returns a partial screen: a missing path or a value of the wrong type fails the whole call, and nothing is omitted or coerced. Documents are plain `dict` / `list` values as `json.loads` gives them; `body` is the parsed JSON, not the raw string.
46
+
47
+ ## Getting the template
48
+
49
+ The template comes from the composer: the published revision of a screen, downloaded with the project's server key (created in the project's settings).
50
+
51
+ ```python
52
+ import os
53
+ from fractal_server import FractalTemplateError, TemplateClient, resolve
54
+
55
+ templates = TemplateClient("https://composer.example", os.environ["FRACTAL_SERVER_KEY"])
56
+
57
+ fetched = templates.get_template("booking")
58
+ booking = resolve(fetched.template, {"flight": {"code": "UA-402"}})
59
+ ```
60
+
61
+ Create the client once and reuse it (it is safe to share between threads). Every call asks the composer whether the published revision changed and downloads the template only when it did, so publishing a new revision reaches the backend on its next request. It uses the standard library (`urllib`), with a 10 second timeout.
62
+
63
+ `get_template` raises `FractalTemplateError` with a `code` and, when the composer answered, its HTTP `status`:
64
+
65
+ | `code` | Meaning |
66
+ | --- | --- |
67
+ | `unauthorized` | The server key is missing, malformed, regenerated or revoked |
68
+ | `template_not_found` | No such screen in the key's project, or nothing published for it |
69
+ | `invalid_response` | The answer was not the template route's (a proxy page, a redirect) |
70
+ | `network_error` | No answer; `__cause__` has the underlying error |
71
+
72
+ The server key is only sent over https (http is accepted for `localhost`), redirects are not followed, and the key never appears in an error or in the client's `repr`.
73
+
74
+ ## The copies of the spec
75
+
76
+ Python cannot install the spec's npm package, so this package carries copies of its files:
77
+
78
+ - `src/fractal_server/spec/1.0/*.json`: the JSON Schemas, shipped in the package.
79
+ - `tests/cases/1.0/*.json`: the conformance cases, used by the tests only.
80
+
81
+ Never edit them. `python scripts/sync_spec.py` copies them from a `fractal-spec` checkout (`FRACTAL_SPEC_DIR`, or `../../fractal-spec` next to this repository), and `python scripts/sync_spec.py --check` fails when a copy is out of date. CI runs the check against the spec release the TypeScript package installs, so both SDKs target one version: sync from a checkout of that release's tag.
82
+
83
+ ## Development
84
+
85
+ ```
86
+ uv venv .venv && uv pip install -p .venv -e ".[dev]"
87
+ python scripts/sync_spec.py --check
88
+ .venv/bin/pytest -q
89
+ ```
90
+
91
+ The tests run every bind, action and response case of the spec through the public functions, plus every block and screen case, to prove this package's validator gives the verdicts of the reference one.
92
+
93
+ ## License
94
+
95
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,83 @@
1
+ # fractal-io-server
2
+
3
+ Fractal IO server SDK for Python (3.10 or later). Import name: `fractal_server`.
4
+
5
+ **Status: draft 0.1.0.** The schemas it carries are those of `@fractal-io-technology/spec` 2.2.1.
6
+
7
+ ```
8
+ pip install fractal-io-server
9
+ ```
10
+
11
+ ## Use
12
+
13
+ ```python
14
+ from fractal_server import FractalBindError, error, navigate, parse_action, resolve, respond, screen
15
+
16
+ # GET /screens/booking: bind the request's data to the template.
17
+ booking = resolve(template, {"flight": {"code": "UA-402"}, "passenger": {"name": "Alex Rosario"}})
18
+
19
+ # POST /actions: read what the user did and answer.
20
+ action = parse_action(request.json())
21
+ if action["name"] == "confirm_booking":
22
+ seat = book(action.get("context", {}).get("flight"), action.get("values", {}).get("passenger_name"))
23
+ return respond(navigate("confirmation")) if seat else respond(error("sold_out", "No seats left"))
24
+ ```
25
+
26
+ | Function | Returns | Raises |
27
+ | --- | --- | --- |
28
+ | `resolve(template, data)` | the screen document | `FractalBindError`, with `code` `BIND_PATH_NOT_FOUND` (and `bind_path`) or `BIND_TYPE_MISMATCH` |
29
+ | `parse_action(body)` | the action: `name`, `event_type`, `timestamp`, and when present `screen_id`, `source_block_id`, `context`, `values` | `FractalActionError`, with `issues` |
30
+ | `respond(*messages)` | `{"fractal": "1.0", "messages": [...]}` | `FractalResponseError`, with `issues` |
31
+ | `screen(document)`, `navigate(screen_id)`, `error(code, message)` | one message for `respond` | |
32
+
33
+ `resolve` never returns a partial screen: a missing path or a value of the wrong type fails the whole call, and nothing is omitted or coerced. Documents are plain `dict` / `list` values as `json.loads` gives them; `body` is the parsed JSON, not the raw string.
34
+
35
+ ## Getting the template
36
+
37
+ The template comes from the composer: the published revision of a screen, downloaded with the project's server key (created in the project's settings).
38
+
39
+ ```python
40
+ import os
41
+ from fractal_server import FractalTemplateError, TemplateClient, resolve
42
+
43
+ templates = TemplateClient("https://composer.example", os.environ["FRACTAL_SERVER_KEY"])
44
+
45
+ fetched = templates.get_template("booking")
46
+ booking = resolve(fetched.template, {"flight": {"code": "UA-402"}})
47
+ ```
48
+
49
+ Create the client once and reuse it (it is safe to share between threads). Every call asks the composer whether the published revision changed and downloads the template only when it did, so publishing a new revision reaches the backend on its next request. It uses the standard library (`urllib`), with a 10 second timeout.
50
+
51
+ `get_template` raises `FractalTemplateError` with a `code` and, when the composer answered, its HTTP `status`:
52
+
53
+ | `code` | Meaning |
54
+ | --- | --- |
55
+ | `unauthorized` | The server key is missing, malformed, regenerated or revoked |
56
+ | `template_not_found` | No such screen in the key's project, or nothing published for it |
57
+ | `invalid_response` | The answer was not the template route's (a proxy page, a redirect) |
58
+ | `network_error` | No answer; `__cause__` has the underlying error |
59
+
60
+ The server key is only sent over https (http is accepted for `localhost`), redirects are not followed, and the key never appears in an error or in the client's `repr`.
61
+
62
+ ## The copies of the spec
63
+
64
+ Python cannot install the spec's npm package, so this package carries copies of its files:
65
+
66
+ - `src/fractal_server/spec/1.0/*.json`: the JSON Schemas, shipped in the package.
67
+ - `tests/cases/1.0/*.json`: the conformance cases, used by the tests only.
68
+
69
+ Never edit them. `python scripts/sync_spec.py` copies them from a `fractal-spec` checkout (`FRACTAL_SPEC_DIR`, or `../../fractal-spec` next to this repository), and `python scripts/sync_spec.py --check` fails when a copy is out of date. CI runs the check against the spec release the TypeScript package installs, so both SDKs target one version: sync from a checkout of that release's tag.
70
+
71
+ ## Development
72
+
73
+ ```
74
+ uv venv .venv && uv pip install -p .venv -e ".[dev]"
75
+ python scripts/sync_spec.py --check
76
+ .venv/bin/pytest -q
77
+ ```
78
+
79
+ The tests run every bind, action and response case of the spec through the public functions, plus every block and screen case, to prove this package's validator gives the verdicts of the reference one.
80
+
81
+ ## License
82
+
83
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ # 1.27 is the first hatchling that writes the license expression and files of PEP 639.
3
+ requires = ["hatchling>=1.27"]
4
+ build-backend = "hatchling.build"
5
+
6
+ [project]
7
+ name = "fractal-io-server"
8
+ version = "0.1.0"
9
+ description = "Fractal IO server SDK: resolve templates into screens, read action messages and build responses."
10
+ readme = "README.md"
11
+ requires-python = ">=3.10"
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+ dependencies = ["jsonschema>=4.18"]
15
+
16
+ [project.optional-dependencies]
17
+ dev = ["pytest>=8"]
18
+
19
+ [tool.hatch.build.targets.wheel]
20
+ packages = ["src/fractal_server"]
21
+
22
+ [tool.pytest.ini_options]
23
+ testpaths = ["tests"]
@@ -0,0 +1,67 @@
1
+ """Copies the protocol's schemas and conformance cases from a fractal-spec checkout.
2
+
3
+ Python cannot install the spec's npm package, so this package carries copies:
4
+
5
+ - schema/<version>/*.json -> src/fractal_server/spec/<version>/ (shipped in the package)
6
+ - conformance/<version>/*-cases.json and cases.json -> tests/cases/<version>/ (tests only)
7
+
8
+ Usage:
9
+ python scripts/sync_spec.py copy
10
+ python scripts/sync_spec.py --check exit 1 when a copy differs from the spec
11
+
12
+ The checkout is read from FRACTAL_SPEC_DIR, or from ../../fractal-spec next to this repository.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ VERSION = "1.0"
22
+ PACKAGE_DIR = Path(__file__).resolve().parent.parent
23
+ SCHEMAS = ("action.json", "block.json", "response.json", "screen.json")
24
+ CASES = ("action-cases.json", "bind-cases.json", "cases.json", "response-cases.json", "screen-cases.json")
25
+
26
+
27
+ def spec_dir() -> Path:
28
+ configured = os.environ.get("FRACTAL_SPEC_DIR")
29
+ return Path(configured).resolve() if configured else PACKAGE_DIR.parent.parent / "fractal-spec"
30
+
31
+
32
+ def copies(spec: Path) -> list[tuple[Path, Path]]:
33
+ schemas = [
34
+ (spec / "schema" / VERSION / name, PACKAGE_DIR / "src" / "fractal_server" / "spec" / VERSION / name)
35
+ for name in SCHEMAS
36
+ ]
37
+ cases = [
38
+ (spec / "conformance" / VERSION / name, PACKAGE_DIR / "tests" / "cases" / VERSION / name) for name in CASES
39
+ ]
40
+ return schemas + cases
41
+
42
+
43
+ def main(argv: list[str]) -> int:
44
+ check = "--check" in argv
45
+ spec = spec_dir()
46
+ stale = []
47
+ for source, target in copies(spec):
48
+ if not source.is_file():
49
+ print(f"missing in the spec checkout: {source}", file=sys.stderr)
50
+ return 1
51
+ if target.is_file() and target.read_bytes() == source.read_bytes():
52
+ continue
53
+ stale.append(target.relative_to(PACKAGE_DIR))
54
+ if not check:
55
+ target.parent.mkdir(parents=True, exist_ok=True)
56
+ target.write_bytes(source.read_bytes())
57
+ if check and stale:
58
+ print("out of date with the spec, run `python scripts/sync_spec.py`:", file=sys.stderr)
59
+ for path in stale:
60
+ print(f" {path}", file=sys.stderr)
61
+ return 1
62
+ print(f"{'checked' if check else 'synced'} {len(copies(spec))} files against {spec}" + (f", {len(stale)} updated" if stale and not check else ""))
63
+ return 0
64
+
65
+
66
+ if __name__ == "__main__":
67
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,191 @@
1
+ """Fractal IO server SDK.
2
+
3
+ What a backend does with Fractal, in four operations:
4
+
5
+ - ``TemplateClient(...).get_template(screen_id)``: download the screen's
6
+ published template from the composer.
7
+ - ``resolve(template, data)``: turn a template and the request's data into the
8
+ screen document the app renders.
9
+ - ``parse_action(body)``: read the action message a renderer posts when the user
10
+ acts on a screen.
11
+ - ``respond(*messages)``: build the response to that action.
12
+
13
+ The rules are the protocol's (fractal-spec); every one is pinned by the spec's
14
+ conformance cases, which this package's tests run.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import copy
20
+ import re
21
+ from dataclasses import dataclass
22
+ from typing import Any
23
+
24
+ from ._schema import SPEC_VERSION, validator
25
+ from .templates import FetchedTemplate, FractalTemplateError, TemplateClient
26
+
27
+ __all__ = [
28
+ "BIND_KEY",
29
+ "FractalActionError",
30
+ "FractalBindError",
31
+ "FetchedTemplate",
32
+ "FractalResponseError",
33
+ "FractalTemplateError",
34
+ "TemplateClient",
35
+ "Issue",
36
+ "error",
37
+ "navigate",
38
+ "parse_action",
39
+ "resolve",
40
+ "respond",
41
+ "screen",
42
+ ]
43
+
44
+ BIND_KEY = "$bind"
45
+
46
+ _ARRAY_INDEX = re.compile(r"(0|[1-9][0-9]*)\Z")
47
+ _NOT_FOUND = object()
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Issue:
52
+ """One place where a document breaks the protocol. ``path`` is ``/``-separated (``action/name``)."""
53
+
54
+ path: str
55
+ message: str
56
+
57
+
58
+ class FractalBindError(Exception):
59
+ """``resolve`` could not produce a screen. ``code`` says why; nothing was resolved partially."""
60
+
61
+ def __init__(self, code: str, message: str, bind_path: str | None = None) -> None:
62
+ super().__init__(f"{code}: {message}")
63
+ self.code = code
64
+ #: The ``$bind`` path with no value in the data (``BIND_PATH_NOT_FOUND`` only).
65
+ self.bind_path = bind_path
66
+
67
+
68
+ class _InvalidDocument(Exception):
69
+ _what = "document"
70
+
71
+ def __init__(self, issues: list[Issue]) -> None:
72
+ first = issues[0] if issues else None
73
+ detail = f"{first.path or '/'} {first.message}" if first else "unknown problem"
74
+ super().__init__(f"Invalid {self._what}: {detail}")
75
+ self.issues = issues
76
+
77
+
78
+ class FractalActionError(_InvalidDocument):
79
+ """The request body is not a valid action message."""
80
+
81
+ _what = "action message"
82
+
83
+
84
+ class FractalResponseError(_InvalidDocument):
85
+ """The messages given to ``respond`` do not make a valid response."""
86
+
87
+ _what = "response"
88
+
89
+
90
+ def _issues(schema_name: str, document: Any) -> list[Issue]:
91
+ errors = sorted(validator(schema_name).iter_errors(document), key=lambda found: list(map(str, found.absolute_path)))
92
+ return [Issue("/".join(map(str, found.absolute_path)), found.message) for found in errors]
93
+
94
+
95
+ def _bind_path(node: Any) -> str | None:
96
+ """The path of a binding: an object whose only key is ``$bind`` and whose value is a string."""
97
+ if isinstance(node, dict) and len(node) == 1:
98
+ path = node.get(BIND_KEY)
99
+ if isinstance(path, str):
100
+ return path
101
+ return None
102
+
103
+
104
+ def _lookup(data: Any, path: str) -> Any:
105
+ current = data
106
+ for segment in path.split("."):
107
+ if isinstance(current, list):
108
+ if not _ARRAY_INDEX.match(segment) or int(segment) >= len(current):
109
+ return _NOT_FOUND
110
+ current = current[int(segment)]
111
+ elif isinstance(current, dict) and segment in current:
112
+ current = current[segment]
113
+ else:
114
+ return _NOT_FOUND
115
+ return current
116
+
117
+
118
+ def _substitute(node: Any, data: Any) -> Any:
119
+ path = _bind_path(node)
120
+ if path is not None:
121
+ value = _lookup(data, path)
122
+ if value is _NOT_FOUND:
123
+ raise FractalBindError("BIND_PATH_NOT_FOUND", f'No value at "{path}" in the data.', path)
124
+ # Inserted as it is: not coerced and not scanned for bindings again.
125
+ return copy.deepcopy(value)
126
+ if isinstance(node, list):
127
+ return [_substitute(item, data) for item in node]
128
+ if isinstance(node, dict):
129
+ return {key: _substitute(value, data) for key, value in node.items()}
130
+ return node
131
+
132
+
133
+ def resolve(template: Any, data: Any) -> dict:
134
+ """Replaces every ``{"$bind": "<path>"}`` of the template with the value at that path in ``data``.
135
+
136
+ Returns the screen document. Neither argument is modified.
137
+
138
+ Raises:
139
+ FractalBindError: ``BIND_PATH_NOT_FOUND`` when a path has no value,
140
+ ``BIND_TYPE_MISMATCH`` when the result is not a valid screen. No value
141
+ is omitted or coerced.
142
+ """
143
+ document = _substitute(template, data)
144
+ issues = _issues("screen", document)
145
+ if issues:
146
+ first = issues[0]
147
+ raise FractalBindError(
148
+ "BIND_TYPE_MISMATCH",
149
+ f"The resolved document is not a valid screen at {first.path or '/'}: {first.message}",
150
+ )
151
+ return document
152
+
153
+
154
+ def parse_action(body: Any) -> dict:
155
+ """Validates the parsed JSON body a renderer posted and returns its action.
156
+
157
+ Raises:
158
+ FractalActionError: when the body is not a valid action message.
159
+ """
160
+ issues = _issues("action", body)
161
+ if issues:
162
+ raise FractalActionError(issues)
163
+ return body["action"]
164
+
165
+
166
+ def screen(document: dict) -> dict:
167
+ """A message that replaces the current screen with ``document``."""
168
+ return {"screen": document}
169
+
170
+
171
+ def navigate(screen_id: str) -> dict:
172
+ """A message that sends the app to another screen."""
173
+ return {"navigate": {"screen_id": screen_id}}
174
+
175
+
176
+ def error(code: str, message: str) -> dict:
177
+ """A message that tells the app the action failed, with a code it can branch on."""
178
+ return {"error": {"code": code, "message": message}}
179
+
180
+
181
+ def respond(*messages: dict) -> dict:
182
+ """Builds the response to an action from one or more messages.
183
+
184
+ Raises:
185
+ FractalResponseError: when there is no message or one is malformed.
186
+ """
187
+ document = {"fractal": SPEC_VERSION, "messages": list(messages)}
188
+ issues = _issues("response", document)
189
+ if issues:
190
+ raise FractalResponseError(issues)
191
+ return document