fherma-runner 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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 2026 FairMath
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,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: fherma-runner
3
+ Version: 0.2.0
4
+ Summary: Takes measurement jobs from a FHERMA platform and reports what happened
5
+ Author: FairMath
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://fherma.io
8
+ Project-URL: Source, https://github.com/fairmath/fherma-runner
9
+ Keywords: fhe,cryptography,benchmarking,kernels,runner
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security :: Cryptography
22
+ Classifier: Topic :: Software Development :: Testing
23
+ Classifier: Topic :: System :: Distributed Computing
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # fherma-runner
30
+
31
+ Takes measurement jobs from a [FHERMA](https://fherma.io) platform and reports
32
+ what happened.
33
+
34
+ ```shell
35
+ uv tool install fherma-runner # or: pipx install fherma-runner
36
+ fherma-runner --api https://fherma.io --name bench-01 --token fhr_...
37
+ ```
38
+
39
+ A command line tool belongs in an environment of its own, and on macOS it has
40
+ no choice: the system Python has no `pip` on the path at all, and Homebrew's is
41
+ marked externally managed so installing into it is refused. `uv tool` and
42
+ `pipx` both make that environment and leave `fherma-runner` on the path, which
43
+ is the part `pip install --user` does not do.
44
+
45
+ Neither installed? One line, and nothing else on the machine changes:
46
+
47
+ ```shell
48
+ curl -LsSf https://astral.sh/uv/install.sh | sh
49
+ ```
50
+
51
+ Check what you got:
52
+
53
+ ```console
54
+ $ fherma-runner --version
55
+ fherma-runner 0.2.0 · python 3.13.4
56
+ ```
57
+
58
+ The token comes from the platform, is good for an hour and is spent once: the
59
+ first start exchanges it for this machine's own key and keeps that in
60
+ `~/.fherma-runner`. Every start after the first needs no token.
61
+
62
+ Every start says what the machine is now, so a server that was re-provisioned is
63
+ matched on what it is rather than on what it was.
64
+
65
+ ## What it needs
66
+
67
+ An interpreter and `docker`. There are no dependencies: everything here ships
68
+ with Python, and docker is called as a command.
69
+
70
+ ## What it declares
71
+
72
+ Hardware, and only hardware — cores, memory, architecture, CPU features, an
73
+ accelerator and its driver. It does not declare libraries or images, because
74
+ the environment a job runs in is not a property of a machine: it arrives with
75
+ the job, pinned to a digest.
76
+
77
+ ```
78
+ fherma-runner --describe
79
+ ```
80
+
81
+ prints what it would report, and stops.
82
+
83
+ ## What it does with a job
84
+
85
+ ```
86
+ jobs/<id>/
87
+ ├── bundle/ the specification's bundle, unpacked
88
+ ├── solution/ the repository at the commit, and its build
89
+ └── points/
90
+ └── p000/ one point at a time, deleted once reported
91
+ ```
92
+
93
+ Per point: the bundle makes the cases, the solution answers them, the bundle
94
+ judges the answers. Three containers, and the solution is never given the
95
+ directory holding the expected answers.
96
+
97
+ ## Options
98
+
99
+ ```
100
+ --api where the platform is FHERMA_API
101
+ --name what to call this machine FHERMA_RUNNER_NAME
102
+ --token an invitation, spent once for a key
103
+ --interval seconds between polls 3
104
+ --once take one assignment, then stop
105
+ --describe print what this machine is, and stop
106
+ --version what is installed, and on what
107
+ --re-register forget the key and join again
108
+ ```
109
+
110
+ The `--speed`, `--fail-rate`, `--build-seconds` and `--point-seconds` options
111
+ belong to the half that is still pretended, and go away with it.
112
+
113
+ ## Stopping
114
+
115
+ The platform stops a runner by refusing its heartbeat. It then drops
116
+ everything at once and sends nothing: finishing the work and reporting it would
117
+ be reporting into a result somebody else now owns.
118
+
119
+ If a runner goes quiet instead, its lease lapses, the run is marked expired and
120
+ the job goes to another machine.
121
+
122
+ ## Licence
123
+
124
+ Apache-2.0.
@@ -0,0 +1,96 @@
1
+ # fherma-runner
2
+
3
+ Takes measurement jobs from a [FHERMA](https://fherma.io) platform and reports
4
+ what happened.
5
+
6
+ ```shell
7
+ uv tool install fherma-runner # or: pipx install fherma-runner
8
+ fherma-runner --api https://fherma.io --name bench-01 --token fhr_...
9
+ ```
10
+
11
+ A command line tool belongs in an environment of its own, and on macOS it has
12
+ no choice: the system Python has no `pip` on the path at all, and Homebrew's is
13
+ marked externally managed so installing into it is refused. `uv tool` and
14
+ `pipx` both make that environment and leave `fherma-runner` on the path, which
15
+ is the part `pip install --user` does not do.
16
+
17
+ Neither installed? One line, and nothing else on the machine changes:
18
+
19
+ ```shell
20
+ curl -LsSf https://astral.sh/uv/install.sh | sh
21
+ ```
22
+
23
+ Check what you got:
24
+
25
+ ```console
26
+ $ fherma-runner --version
27
+ fherma-runner 0.2.0 · python 3.13.4
28
+ ```
29
+
30
+ The token comes from the platform, is good for an hour and is spent once: the
31
+ first start exchanges it for this machine's own key and keeps that in
32
+ `~/.fherma-runner`. Every start after the first needs no token.
33
+
34
+ Every start says what the machine is now, so a server that was re-provisioned is
35
+ matched on what it is rather than on what it was.
36
+
37
+ ## What it needs
38
+
39
+ An interpreter and `docker`. There are no dependencies: everything here ships
40
+ with Python, and docker is called as a command.
41
+
42
+ ## What it declares
43
+
44
+ Hardware, and only hardware — cores, memory, architecture, CPU features, an
45
+ accelerator and its driver. It does not declare libraries or images, because
46
+ the environment a job runs in is not a property of a machine: it arrives with
47
+ the job, pinned to a digest.
48
+
49
+ ```
50
+ fherma-runner --describe
51
+ ```
52
+
53
+ prints what it would report, and stops.
54
+
55
+ ## What it does with a job
56
+
57
+ ```
58
+ jobs/<id>/
59
+ ├── bundle/ the specification's bundle, unpacked
60
+ ├── solution/ the repository at the commit, and its build
61
+ └── points/
62
+ └── p000/ one point at a time, deleted once reported
63
+ ```
64
+
65
+ Per point: the bundle makes the cases, the solution answers them, the bundle
66
+ judges the answers. Three containers, and the solution is never given the
67
+ directory holding the expected answers.
68
+
69
+ ## Options
70
+
71
+ ```
72
+ --api where the platform is FHERMA_API
73
+ --name what to call this machine FHERMA_RUNNER_NAME
74
+ --token an invitation, spent once for a key
75
+ --interval seconds between polls 3
76
+ --once take one assignment, then stop
77
+ --describe print what this machine is, and stop
78
+ --version what is installed, and on what
79
+ --re-register forget the key and join again
80
+ ```
81
+
82
+ The `--speed`, `--fail-rate`, `--build-seconds` and `--point-seconds` options
83
+ belong to the half that is still pretended, and go away with it.
84
+
85
+ ## Stopping
86
+
87
+ The platform stops a runner by refusing its heartbeat. It then drops
88
+ everything at once and sends nothing: finishing the work and reporting it would
89
+ be reporting into a result somebody else now owns.
90
+
91
+ If a runner goes quiet instead, its lease lapses, the run is marked expired and
92
+ the job goes to another machine.
93
+
94
+ ## Licence
95
+
96
+ Apache-2.0.
@@ -0,0 +1,8 @@
1
+ """A FHERMA runner: takes measurement jobs and reports what happened.
2
+
3
+ Nothing here imports anything that does not ship with Python, and docker is
4
+ called as a command rather than through a library. Installing this on a server
5
+ is copying a directory.
6
+ """
7
+
8
+ __version__ = "0.2.0"
@@ -0,0 +1,129 @@
1
+ """The command line, and the loop that outlives everything under it.
2
+
3
+ fherma-runner --api https://fherma.io --name bench-01
4
+ fherma-runner --once one assignment, then stop
5
+ fherma-runner --re-register forget the key and join again
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ import sys
13
+ import time
14
+ from importlib import metadata
15
+
16
+ from . import job, machine
17
+ from .api import Api, Refused, Unreachable
18
+ from .session import KEYFILE, describe, identify
19
+
20
+
21
+ def version() -> str:
22
+ """What is installed, asked of the installation rather than hardcoded."""
23
+ try:
24
+ return metadata.version("fherma-runner")
25
+ except metadata.PackageNotFoundError:
26
+ return "unknown (running from a checkout)"
27
+
28
+
29
+ def parse(argv: list[str] | None = None) -> argparse.Namespace:
30
+ parser = argparse.ArgumentParser(
31
+ prog="fherma-runner",
32
+ description="Takes measurement jobs from a FHERMA platform and reports what happened.",
33
+ )
34
+ parser.add_argument("--api", default=os.environ.get("FHERMA_API", "http://localhost:4000"))
35
+ parser.add_argument("--name", default=os.environ.get("FHERMA_RUNNER_NAME", "runner"))
36
+ parser.add_argument("--interval", type=float, default=3.0, help="seconds between polls")
37
+ parser.add_argument("--once", action="store_true", help="one assignment, then stop")
38
+ parser.add_argument("--token", help="an invitation, exchanged once for this machine's key")
39
+ parser.add_argument("--re-register", action="store_true", help="forget the key and join again")
40
+ parser.add_argument("--describe", action="store_true", help="print what this machine is, and stop")
41
+ # The first question anybody asks after an install that may not have worked.
42
+ # One line rather than three, because argparse reflows the text it prints
43
+ # and a newline here comes out as a space.
44
+ parser.add_argument(
45
+ "--version",
46
+ action="version",
47
+ version=f"fherma-runner {version()} · python {sys.version.split()[0]}",
48
+ )
49
+
50
+ limits = parser.add_argument_group(
51
+ "limits",
52
+ "What a solution's container may take. The platform sets the time limits; "
53
+ "these are the machine's own.",
54
+ )
55
+ limits.add_argument("--memory", default=os.environ.get("FHERMA_MEMORY", "8g"))
56
+ limits.add_argument("--cpus", default=os.environ.get("FHERMA_CPUS"))
57
+
58
+ return parser.parse_args(argv)
59
+
60
+
61
+ def main(argv: list[str] | None = None) -> int:
62
+ options = parse(argv)
63
+
64
+ if options.describe:
65
+ for name, value in machine.describe().items():
66
+ print(f"{name:12} {value}")
67
+ print(f"{'can':12} {', '.join(one['name'] for one in machine.capabilities()) or 'nothing'}")
68
+ return 0
69
+
70
+ if options.re_register and KEYFILE.exists():
71
+ KEYFILE.unlink()
72
+
73
+ api = Api(options.api)
74
+
75
+ while True:
76
+ try:
77
+ api.key = identify(api, options.name, options.token)
78
+ break
79
+ except Refused as failure:
80
+ print(f"could not register: {failure}", file=sys.stderr)
81
+ return 1
82
+ except Unreachable as failure:
83
+ # A runner boots when its machine boots, which may be before the
84
+ # platform is up. Waiting is the correct answer; exiting would need
85
+ # somebody to notice and start it again.
86
+ print(f"waiting for {options.api}: {failure}", file=sys.stderr)
87
+ time.sleep(options.interval)
88
+
89
+ try:
90
+ describe(api)
91
+ except Refused as failure:
92
+ if failure.status in (401, 403):
93
+ print("the key was refused — try --re-register", file=sys.stderr)
94
+ return 1
95
+ raise
96
+ except Unreachable as failure:
97
+ print(f"could not describe this machine: {failure}", file=sys.stderr)
98
+
99
+ print(f"polling {options.api} every {options.interval}s — ctrl-c to stop")
100
+
101
+ while True:
102
+ try:
103
+ did = job.take(api, options)
104
+ except Refused as failure:
105
+ # A lapsed lease is the ordinary case: stop working on it and ask
106
+ # again rather than reporting into a result somebody else now owns.
107
+ print(f" refused ({failure.status}) — dropping this one", file=sys.stderr)
108
+ did = False
109
+ except Unreachable as failure:
110
+ print(f" cannot reach {options.api}: {failure}", file=sys.stderr)
111
+ did = False
112
+
113
+ if did and options.once:
114
+ return 0
115
+ if not did:
116
+ print(".", end="", flush=True)
117
+ time.sleep(options.interval)
118
+
119
+
120
+ def run() -> None:
121
+ """The console entry point. Ctrl-C is an ending, not a crash."""
122
+ try:
123
+ raise SystemExit(main())
124
+ except KeyboardInterrupt:
125
+ print()
126
+
127
+
128
+ if __name__ == "__main__":
129
+ run()
@@ -0,0 +1,80 @@
1
+ """Talking to the platform, and the three ways it can go wrong.
2
+
3
+ The runner is the only one of the three programs on a machine that speaks to
4
+ the platform at all. The bundle is handed a directory; the solution is handed a
5
+ directory; neither has a key and neither has a network.
6
+
7
+ Nothing here is imported that does not ship with Python. A machine that runs
8
+ this needs nothing installed beyond an interpreter and docker.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import urllib.error
15
+ import urllib.request
16
+
17
+
18
+ class Refused(Exception):
19
+ """The platform answered, and the answer was no."""
20
+
21
+ def __init__(self, status: int, detail: str) -> None:
22
+ super().__init__(f"{status}: {detail}")
23
+ self.status = status
24
+ self.detail = detail
25
+
26
+
27
+ class Unreachable(Exception):
28
+ """The platform did not answer. Says nothing about the work."""
29
+
30
+
31
+ class Dropped(Exception):
32
+ """This assignment is no longer ours. Stop, and send nothing."""
33
+
34
+
35
+ class Api:
36
+ """The calls a runner makes, and the one that gets it a key.
37
+
38
+ Errors are not swallowed. A runner that carries on after a refusal is a
39
+ runner reporting into somebody else's result, and the refusals here mean
40
+ exactly that: the lease lapsed, the assignment went elsewhere.
41
+ """
42
+
43
+ def __init__(self, base: str, key: str | None = None, timeout: float = 30) -> None:
44
+ self.base = base.rstrip("/")
45
+ self.key = key
46
+ self.timeout = timeout
47
+
48
+ def call(self, method: str, path: str, body: dict | None = None) -> dict:
49
+ raw = self._request(method, path, body)
50
+ return json.loads(raw) if raw else {}
51
+
52
+ def download(self, path: str) -> bytes:
53
+ """A file rather than a document — the bundle archive, and only that."""
54
+ return self._request("GET", path, None, decode=False)
55
+
56
+ def _request(self, method: str, path: str, body: dict | None, decode: bool = True):
57
+ request = urllib.request.Request(
58
+ f"{self.base}/api{path}",
59
+ method=method,
60
+ data=json.dumps(body).encode() if body is not None else None,
61
+ headers={
62
+ "content-type": "application/json",
63
+ **({"x-fherma-runner": self.key} if self.key else {}),
64
+ },
65
+ )
66
+
67
+ try:
68
+ with urllib.request.urlopen(request, timeout=self.timeout) as answer:
69
+ raw = answer.read()
70
+ return raw.decode() if decode else raw
71
+ except urllib.error.HTTPError as failure:
72
+ detail = failure.read().decode()[:300]
73
+ raise Refused(failure.code, detail) from None
74
+ except OSError as failure:
75
+ # Refused connections arrive as URLError; a read that times out
76
+ # half-way through arrives as a bare TimeoutError, and a platform
77
+ # restarting mid-request produces both. They mean one thing to a
78
+ # runner — nobody answered — and a machine meant to sit in a rack
79
+ # for weeks must not die of any of them.
80
+ raise Unreachable(str(getattr(failure, "reason", None) or failure)) from None