fractal-io-server 0.1.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.
- fractal_io_server-0.1.0.dist-info/METADATA +95 -0
- fractal_io_server-0.1.0.dist-info/RECORD +11 -0
- fractal_io_server-0.1.0.dist-info/WHEEL +4 -0
- fractal_io_server-0.1.0.dist-info/licenses/LICENSE +202 -0
- fractal_server/__init__.py +191 -0
- fractal_server/_schema.py +54 -0
- fractal_server/spec/1.0/action.json +109 -0
- fractal_server/spec/1.0/block.json +5886 -0
- fractal_server/spec/1.0/response.json +91 -0
- fractal_server/spec/1.0/screen.json +22 -0
- fractal_server/templates.py +165 -0
|
@@ -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,11 @@
|
|
|
1
|
+
fractal_server/__init__.py,sha256=PrONp74q70g4pbhvsLJzkX8JCSyw7cDjZMkz4EoZspw,6035
|
|
2
|
+
fractal_server/_schema.py,sha256=WJXxmMv2OQp-Q2f8gZnH-sb_3d9acdKABTBfFz7Gxv8,2203
|
|
3
|
+
fractal_server/templates.py,sha256=bDeB6XM3HO5sD5c7DOHouRLy7DAXq7_vmaE1PIVJe8k,6784
|
|
4
|
+
fractal_server/spec/1.0/action.json,sha256=0L6lKsv_2VDIn5urPqqlhoZi0psoFAOlFpVTnX1C2Fg,3629
|
|
5
|
+
fractal_server/spec/1.0/block.json,sha256=QbennC5Nl3_Ty6oZOllZrlTufBNKNy36tQGq-MmGbuE,218972
|
|
6
|
+
fractal_server/spec/1.0/response.json,sha256=s1I6IGrJmdR3jvoc2i5ufmYY6XvXPdolnBUJ9O3Gg9w,3149
|
|
7
|
+
fractal_server/spec/1.0/screen.json,sha256=J5xj-w4SCONcjU3fCpzKkKlpopaTc8GlCVwww9aY4U0,884
|
|
8
|
+
fractal_io_server-0.1.0.dist-info/METADATA,sha256=fCr18-z2Zrl0JmsI7ZEt8hf3cb0AfoRPecjP3zEw6Ec,4597
|
|
9
|
+
fractal_io_server-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
fractal_io_server-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
fractal_io_server-0.1.0.dist-info/RECORD,,
|
|
@@ -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,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
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""The protocol's JSON Schemas (copies of fractal-spec, see scripts/sync_spec.py) and their validators."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from functools import cache
|
|
8
|
+
from importlib import resources
|
|
9
|
+
from typing import Any, Iterator
|
|
10
|
+
|
|
11
|
+
from jsonschema import Draft202012Validator, ValidationError, validators
|
|
12
|
+
from referencing import Registry, Resource
|
|
13
|
+
from referencing.jsonschema import DRAFT202012
|
|
14
|
+
|
|
15
|
+
SPEC_VERSION = "1.0"
|
|
16
|
+
_SCHEMA_NAMES = ("action", "block", "response", "screen")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _pattern(validator: Any, pattern: str, instance: Any, schema: Any) -> Iterator[ValidationError]:
|
|
20
|
+
"""JSON Schema `pattern` with ECMAScript's `$`.
|
|
21
|
+
|
|
22
|
+
Python's `$` also matches before a final newline, so `"1.0\\n"` would pass a
|
|
23
|
+
pattern the reference validator rejects. `\\Z` only matches at the very end.
|
|
24
|
+
"""
|
|
25
|
+
if not isinstance(instance, str):
|
|
26
|
+
return
|
|
27
|
+
anchored = pattern[:-1] + r"\Z" if pattern.endswith("$") and not pattern.endswith(r"\$") else pattern
|
|
28
|
+
if not re.search(anchored, instance):
|
|
29
|
+
yield ValidationError(f"{instance!r} does not match {pattern!r}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_Validator = validators.extend(Draft202012Validator, {"pattern": _pattern})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@cache
|
|
36
|
+
def _schemas() -> dict[str, dict]:
|
|
37
|
+
directory = resources.files("fractal_server") / "spec" / SPEC_VERSION
|
|
38
|
+
schemas = {name: json.loads((directory / f"{name}.json").read_text(encoding="utf-8")) for name in _SCHEMA_NAMES}
|
|
39
|
+
# Following a `$ref` into a schema that declares `$schema` makes jsonschema switch to the stock
|
|
40
|
+
# validator of that dialect, which drops the `pattern` rule above. Without the declaration it
|
|
41
|
+
# keeps this module's validator; all four schemas are Draft 2020-12, which `_Validator` extends.
|
|
42
|
+
for schema in schemas.values():
|
|
43
|
+
schema.pop("$schema", None)
|
|
44
|
+
return schemas
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@cache
|
|
48
|
+
def validator(name: str) -> Any:
|
|
49
|
+
"""The validator of `screen`, `action` or `response`, with the schemas they reference by `$id`."""
|
|
50
|
+
schemas = _schemas()
|
|
51
|
+
registry = Registry().with_resources(
|
|
52
|
+
(schema["$id"], Resource.from_contents(schema, default_specification=DRAFT202012)) for schema in schemas.values()
|
|
53
|
+
)
|
|
54
|
+
return _Validator(schemas[name], registry=registry)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "urn:fractal-io:schema:action:1.0",
|
|
4
|
+
"title": "Fractal IO action message",
|
|
5
|
+
"description": "An action message of protocol version 1.x: what a renderer posts to the backend when a block event fires. Other top-level keys are transport data, not protocol; renderers may send them and backends ignore them.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": [
|
|
8
|
+
"fractal",
|
|
9
|
+
"action"
|
|
10
|
+
],
|
|
11
|
+
"properties": {
|
|
12
|
+
"fractal": {
|
|
13
|
+
"description": "Protocol version the renderer speaks, as MAJOR.MINOR. A backend rejects an action message whose major version it does not support and accepts a higher minor of a supported major.",
|
|
14
|
+
"type": "string",
|
|
15
|
+
"pattern": "^1\\.(0|[1-9][0-9]*)$"
|
|
16
|
+
},
|
|
17
|
+
"action": {
|
|
18
|
+
"description": "The event that fired and the state of the screen it fired on.",
|
|
19
|
+
"type": "object",
|
|
20
|
+
"properties": {
|
|
21
|
+
"name": {
|
|
22
|
+
"type": "string",
|
|
23
|
+
"minLength": 1,
|
|
24
|
+
"description": "The action the backend handles. The renderer copies it from the `event_id` of the block event that fired."
|
|
25
|
+
},
|
|
26
|
+
"screen_id": {
|
|
27
|
+
"description": "Identifier of the screen the event fired on, supplied by the renderer when it knows one. A screen document carries no id, so the key is optional.",
|
|
28
|
+
"type": "string"
|
|
29
|
+
},
|
|
30
|
+
"source_block_id": {
|
|
31
|
+
"description": "The `id` of the block whose event fired. Absent when that block has no `id`.",
|
|
32
|
+
"type": "string"
|
|
33
|
+
},
|
|
34
|
+
"event_type": {
|
|
35
|
+
"type": "string",
|
|
36
|
+
"enum": [
|
|
37
|
+
"on_tap",
|
|
38
|
+
"on_large_tap",
|
|
39
|
+
"on_double_tap",
|
|
40
|
+
"on_change",
|
|
41
|
+
"on_complete"
|
|
42
|
+
],
|
|
43
|
+
"description": "The gesture or change that fired the event. The renderer copies it from the `event_type` of the block event."
|
|
44
|
+
},
|
|
45
|
+
"timestamp": {
|
|
46
|
+
"type": "string",
|
|
47
|
+
"pattern": "^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?Z$",
|
|
48
|
+
"description": "When the event fired, read from the renderer's clock: ISO 8601 in UTC, ending in `Z`, with optional fractional seconds."
|
|
49
|
+
},
|
|
50
|
+
"context": {
|
|
51
|
+
"description": "The `event_data` of the block event that fired, unchanged. Absent when the event has no `event_data`.",
|
|
52
|
+
"type": "object",
|
|
53
|
+
"propertyNames": {
|
|
54
|
+
"type": "string"
|
|
55
|
+
},
|
|
56
|
+
"additionalProperties": {
|
|
57
|
+
"$ref": "#/$defs/__schema0"
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"values": {
|
|
61
|
+
"description": "The current value of every input block that has an `id`, keyed by that `id`, read from the screen when the event fires.",
|
|
62
|
+
"type": "object",
|
|
63
|
+
"propertyNames": {
|
|
64
|
+
"type": "string"
|
|
65
|
+
},
|
|
66
|
+
"additionalProperties": {
|
|
67
|
+
"$ref": "#/$defs/__schema0"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"required": [
|
|
72
|
+
"name",
|
|
73
|
+
"event_type",
|
|
74
|
+
"timestamp"
|
|
75
|
+
],
|
|
76
|
+
"additionalProperties": false
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"$defs": {
|
|
80
|
+
"__schema0": {
|
|
81
|
+
"anyOf": [
|
|
82
|
+
{
|
|
83
|
+
"type": "string"
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
"type": "number"
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"type": "boolean"
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
"type": "array",
|
|
93
|
+
"items": {
|
|
94
|
+
"$ref": "#/$defs/__schema0"
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
"type": "object",
|
|
99
|
+
"propertyNames": {
|
|
100
|
+
"type": "string"
|
|
101
|
+
},
|
|
102
|
+
"additionalProperties": {
|
|
103
|
+
"$ref": "#/$defs/__schema0"
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
]
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|