abysshub 1.0.1.dev9__tar.gz → 1.0.1.dev10__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.
Files changed (26) hide show
  1. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/pyproject.toml +1 -1
  3. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_command.py +153 -30
  4. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_command.py +19 -0
  5. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/.gitignore +0 -0
  6. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/LICENSE +0 -0
  7. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/README.md +0 -0
  8. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/__init__.py +0 -0
  9. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/__main__.py +0 -0
  10. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_async_client.py +0 -0
  11. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_client.py +0 -0
  12. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_error.py +0 -0
  13. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_files.py +0 -0
  14. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_http.py +0 -0
  15. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_run.py +0 -0
  16. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/_types.py +0 -0
  17. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/src/abysshub/py.typed +0 -0
  18. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/caller.py +0 -0
  19. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/conftest.py +0 -0
  20. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/fake_server.py +0 -0
  21. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_client.py +0 -0
  22. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_files.py +0 -0
  23. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_http.py +0 -0
  24. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_package.py +0 -0
  25. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_replay.py +0 -0
  26. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev10}/tests/test_timeout.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: abysshub
3
- Version: 1.0.1.dev9
3
+ Version: 1.0.1.dev10
4
4
  Summary: Run a hosted tool, an Abyss Widget, from your own Python code and get its result and files. The official library for the Abyss API.
5
5
  Project-URL: Homepage, https://abysshub.com/docs#api
6
6
  Project-URL: Documentation, https://abysshub.com/docs
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "abysshub"
7
- version = "1.0.1.dev9"
7
+ version = "1.0.1.dev10"
8
8
  description = "Run a hosted tool, an Abyss Widget, from your own Python code and get its result and files. The official library for the Abyss API."
9
9
  keywords = [
10
10
  "abyss",
@@ -7,11 +7,12 @@ import argparse
7
7
  import json
8
8
  import os
9
9
  import sys
10
+ from dataclasses import dataclass
10
11
  from fnmatch import fnmatchcase
11
12
  from pathlib import Path
12
13
  from typing import Any
13
14
 
14
- from ._client import Abyss, _expect, _has_ended, _is_upload, _is_widget
15
+ from ._client import Abyss, _expect, _has_ended, _is_key, _is_upload, _is_widget
15
16
  from ._error import AbyssError
16
17
  from ._files import file
17
18
  from ._types import parse_upload
@@ -23,6 +24,8 @@ ROOT_ENV = (".env", ".env.*")
23
24
  """A root ``.env`` and its variants: never content, whatever the Junk list says."""
24
25
  LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_runs")
25
26
  """The Listing Fields the Publish File holds, beside its thumbnail."""
27
+ IMAGES = (".png", ".jpg", ".jpeg", ".webp", ".gif")
28
+ """The extensions a thumbnail may have: an image's."""
26
29
  JSON = {"Content-Type": "application/json"}
27
30
 
28
31
 
@@ -38,37 +41,149 @@ def main(argv: list[str] | None = None) -> int:
38
41
  )
39
42
  publish_verb.add_argument("folder", type=Path)
40
43
  args = parser.parse_args(argv)
44
+ widget_folder, faults = _read_folder(args.folder)
41
45
  try:
42
- with Abyss() as abyss:
43
- print(publish(abyss, args.folder))
46
+ abyss = Abyss()
44
47
  except AbyssError as error:
45
- print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
46
- if error.request_id:
47
- print(f"request_id: {error.request_id}", file=sys.stderr)
48
- return 1
49
- except OSError as error:
50
- # A file the folder names, such as the thumbnail or a Test Input, is missing or unreadable.
51
- print(f"abysshub: stopped: file_unreadable: {error}", file=sys.stderr)
52
- return 1
48
+ return _stop([*faults, (error.code, error.message)])
49
+ with abyss:
50
+ faults.extend(_key_faults(abyss))
51
+ if faults:
52
+ return _stop(faults)
53
+ try:
54
+ print(publish(abyss, args.folder, widget_folder))
55
+ except AbyssError as error:
56
+ print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
57
+ if error.request_id:
58
+ print(f"request_id: {error.request_id}", file=sys.stderr)
59
+ return 1
60
+ except OSError as error:
61
+ # A file the folder names changed or became unreadable after the check.
62
+ print(f"abysshub: stopped: file_unreadable: {error}", file=sys.stderr)
63
+ return 1
53
64
  return 0
54
65
 
55
66
 
56
- def publish(abyss: Abyss, folder: Path) -> str:
67
+ @dataclass
68
+ class _Folder:
69
+ """A Widget folder as the command read it, before it sent anything."""
70
+
71
+ publish_file: dict[str, Any]
72
+ interface: list[Any] | None
73
+ test_input: dict[str, Any]
74
+ """The Test Run's input: the Test Inputs, and the default of each Field they leave out."""
75
+
76
+
77
+ def _stop(faults: list[tuple[str, str]]) -> int:
78
+ """Prints every fault, one line each with its code, and answers the exit code."""
79
+ for code, message in faults:
80
+ print(f"abysshub: stopped: {code}: {message}", file=sys.stderr)
81
+ return 1
82
+
83
+
84
+ def _read_folder(folder: Path) -> tuple[_Folder, list[tuple[str, str]]]:
85
+ """Reads the folder and finds every fault it shows on its own, all of them and not
86
+ only the first, without a request: a publish takes minutes, a fault stops it now."""
87
+ faults: list[tuple[str, str]] = []
88
+ for name, code in (("run.py", "run_py_missing"), ("requirements.txt", "requirements_missing")):
89
+ if not (folder / name).is_file():
90
+ faults.append((code, f"The folder has no {name}."))
91
+ publish_file = _read_json(folder / PUBLISH_FILE, "publish_file", dict, faults)
92
+ if publish_file is not None:
93
+ _check_listing(folder, publish_file, faults)
94
+ has_interface = (folder / INTERFACE).is_file()
95
+ interface = _read_json(folder / INTERFACE, "interface", list, faults) if has_interface else None
96
+ test_inputs = _read_json(folder / TEST_INPUTS, "test_inputs", dict, faults) if (folder / TEST_INPUTS).is_file() else {}
97
+ test_input: dict[str, Any] = {}
98
+ # An invalid interface.json skips the Field checks rather than calling every Test Input unknown.
99
+ if test_inputs is not None and (interface is not None or not has_interface):
100
+ test_input = _check_test_inputs(folder, interface or [], test_inputs, faults)
101
+ return _Folder(publish_file or {}, interface, test_input), faults
102
+
103
+
104
+ def _check_listing(folder: Path, publish_file: dict[str, Any], faults: list[tuple[str, str]]) -> None:
105
+ """The Publish File's faults: no title, no tag, and a thumbnail that is missing on a
106
+ first publish or names no image file in the folder."""
107
+ block = publish_file.get("widget") or {}
108
+ if not isinstance(block, dict):
109
+ faults.append(("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object."))
110
+ title = publish_file.get("title")
111
+ if not isinstance(title, str) or not title.strip():
112
+ faults.append(("title_missing", f"{PUBLISH_FILE} has no title."))
113
+ tags = publish_file.get("tags")
114
+ if not isinstance(tags, list) or not any(isinstance(tag, str) and tag.strip() for tag in tags):
115
+ faults.append(("tag_missing", f"{PUBLISH_FILE} has no tag in tags."))
116
+ thumbnail = publish_file.get("thumbnail")
117
+ if not thumbnail:
118
+ if not (isinstance(block, dict) and "version" in block):
119
+ faults.append(("thumbnail_missing", f"A first publish needs a thumbnail, and {PUBLISH_FILE} names none."))
120
+ elif not (isinstance(thumbnail, str) and Path(thumbnail).suffix.lower() in IMAGES and _names_file(folder, thumbnail)):
121
+ faults.append(
122
+ ("thumbnail_not_image", f"The thumbnail {thumbnail!r} names no image file ({', '.join(IMAGES)}) in the folder.")
123
+ )
124
+
125
+
126
+ def _check_test_inputs(
127
+ folder: Path, interface: list[Any], test_inputs: dict[str, Any], faults: list[tuple[str, str]]
128
+ ) -> dict[str, Any]:
129
+ """The Test Inputs' faults against ``interface.json``: a name that is no Field, a
130
+ required Field with no value and no default, and a file Field's value that names no
131
+ file in the folder. Answers the Test Run's input, with the defaults filled in."""
132
+ fields = {
133
+ field["name"]: field for field in interface if isinstance(field, dict) and isinstance(field.get("name"), str)
134
+ }
135
+ for name in test_inputs:
136
+ if name not in fields:
137
+ faults.append(("test_input_unknown", f"{TEST_INPUTS} names {name!r}, which {INTERFACE} has no Field for."))
138
+ defaults = {name: field["default"] for name, field in fields.items() if "default" in field}
139
+ test_input = {**defaults, **test_inputs}
140
+ for name, field in fields.items():
141
+ value = test_input.get(name)
142
+ if value is None:
143
+ # A Field without isRequired counts as required.
144
+ if field.get("isRequired", True) is not False:
145
+ faults.append(("test_input_missing", f"The required Field {name!r} has no value in {TEST_INPUTS} and no default."))
146
+ elif field.get("type") == "file":
147
+ for path in value if isinstance(value, list) else [value]:
148
+ if not _names_file(folder, path):
149
+ faults.append(("test_input_file_missing", f"The file Field {name!r} names {path!r}, no file inside the folder."))
150
+ return test_input
151
+
152
+
153
+ def _key_faults(abyss: Abyss) -> list[tuple[str, str]]:
154
+ """The key's fault, read with ``GET /v1/key``: it is refused, or it does not manage Widgets."""
155
+ try:
156
+ key = abyss._get(abyss._start(None), f"{abyss.base_url}/v1/key", _is_key, "The key answered without a key.")
157
+ except AbyssError as error:
158
+ return [(error.code, error.message)]
159
+ if key.get("manage_widgets") is not True:
160
+ return [
161
+ (
162
+ "manage_widgets_required",
163
+ f"The key {key.get('key')} does not manage Widgets. Make a new key in your Cave, under Your API keys, "
164
+ "with Create a key and Manage Widgets switched on: a key is never given it after it is made.",
165
+ )
166
+ ]
167
+ return []
168
+
169
+
170
+ def _names_file(folder: Path, path: Any) -> bool:
171
+ """Whether ``path`` names a file inside the folder."""
172
+ if not isinstance(path, str) or not path:
173
+ return False
174
+ target = (folder / path).resolve()
175
+ return target.is_file() and folder.resolve() in target.parents
176
+
177
+
178
+ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder) -> str:
57
179
  """Publishes a folder that was never published, and answers the Widget's link.
58
180
 
59
181
  A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
60
182
  number once committed, so a publish that stops is taken up again on the same Draft.
61
183
  """
62
- publish_file = _read_json(folder / PUBLISH_FILE, "publish_file_invalid")
63
- if not isinstance(publish_file, dict):
64
- raise AbyssError("publish_file_invalid", f"{PUBLISH_FILE} is not a JSON object.")
65
- test_inputs = _read_json(folder / TEST_INPUTS, "test_inputs_invalid") if (folder / TEST_INPUTS).is_file() else {}
66
- if not isinstance(test_inputs, dict):
67
- raise AbyssError("test_inputs_invalid", f"{TEST_INPUTS} is not a JSON object.")
68
- interface = _read_json(folder / INTERFACE, "interface_invalid") if (folder / INTERFACE).is_file() else None
184
+ publish_file = widget_folder.publish_file
185
+ interface = widget_folder.interface
69
186
  block = publish_file.get("widget") or {}
70
- if not isinstance(block, dict):
71
- raise AbyssError("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object.")
72
187
  if "version" in block:
73
188
  raise AbyssError(
74
189
  "widget_published",
@@ -115,7 +230,7 @@ def publish(abyss: Abyss, folder: Path) -> str:
115
230
  _write_block(folder, publish_file, {"id": widget, "candidate": candidate["version"]})
116
231
 
117
232
  print(f"Test Run of version {candidate['version']}...")
118
- run = _test_run(abyss, folder, widget, candidate["version"], test_inputs, interface)
233
+ run = _test_run(abyss, folder, widget, candidate["version"], widget_folder.test_input, interface)
119
234
  if run["status"] == "failed":
120
235
  _print_logs(run.get("logs"))
121
236
  error = run.get("error") or {}
@@ -180,10 +295,10 @@ def _test_run(
180
295
  folder: Path,
181
296
  widget: str,
182
297
  version: int,
183
- test_inputs: dict[str, Any],
298
+ test_input: dict[str, Any],
184
299
  interface: list[Any] | None,
185
300
  ) -> dict[str, Any]:
186
- """Makes the Test Run of the Candidate from the Test Inputs and waits for its ending,
301
+ """Makes the Test Run of the Candidate from its input and waits for its ending,
187
302
  as ``run()`` waits. A file Field's value is a path in the folder, uploaded for that
188
303
  Candidate. Answers the run, failed or not."""
189
304
  file_fields = {
@@ -197,7 +312,7 @@ def _test_run(
197
312
  return [file(str(folder / path)) if isinstance(path, str) else path for path in item]
198
313
  return file(str(folder / item)) if isinstance(item, str) else item
199
314
 
200
- input = {name: value(name, item) for name, item in test_inputs.items()}
315
+ input = {name: value(name, item) for name, item in test_input.items()}
201
316
  call = abyss._start(None)
202
317
  press = abyss._press(call, widget, input, None, None, hold=True, version=version)
203
318
  reply = press if _has_ended(press) else abyss._hold(call, abyss._wait_url(press), _has_ended)
@@ -233,13 +348,21 @@ def _save_listing(abyss: Abyss, folder: Path, widget: str, publish_file: dict[st
233
348
  )
234
349
 
235
350
 
236
- def _read_json(path: Path, code: str) -> Any:
351
+ def _read_json(path: Path, kind: str, shape: type, faults: list[tuple[str, str]]) -> Any:
352
+ """Reads a JSON file of the folder, or adds its fault and answers None: ``<kind>_missing``
353
+ when it is absent, ``<kind>_invalid`` when it is not JSON of that shape."""
237
354
  try:
238
- return json.loads(path.read_text("utf-8"))
355
+ value = json.loads(path.read_text("utf-8"))
239
356
  except FileNotFoundError:
240
- raise AbyssError(code, f"{path} is missing.") from None
241
- except ValueError as error:
242
- raise AbyssError(code, f"{path} is not valid JSON: {error}") from None
357
+ faults.append((f"{kind}_missing", f"The folder has no {path.name}."))
358
+ return None
359
+ except (OSError, ValueError) as error:
360
+ faults.append((f"{kind}_invalid", f"{path.name} is not valid JSON: {error}"))
361
+ return None
362
+ if not isinstance(value, shape):
363
+ faults.append((f"{kind}_invalid", f"{path.name} is not a JSON {'object' if shape is dict else 'array'}."))
364
+ return None
365
+ return value
243
366
 
244
367
 
245
368
  def _write_block(folder: Path, publish_file: dict[str, Any], block: dict[str, Any]) -> None:
@@ -36,3 +36,22 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
36
36
  assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
37
37
  finally:
38
38
  server.close()
39
+
40
+
41
+ def test_publish_without_a_key_prints_every_fault_and_sends_nothing(
42
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
43
+ ) -> None:
44
+ server = Replay({"exchanges": []}, KEY)
45
+ try:
46
+ with with_files({"run.py": "print('words')\n", "requirements.txt": "\n"}) as dir:
47
+ monkeypatch.delenv("ABYSS_API_KEY", raising=False)
48
+ monkeypatch.setenv("ABYSS_BASE_URL", server.base)
49
+ exit = main(["publish", str(dir)])
50
+ printed = capsys.readouterr()
51
+
52
+ assert server.problems == []
53
+ assert exit == 1
54
+ assert "publish_file_missing" in printed.err
55
+ assert "invalid_api_key" in printed.err
56
+ finally:
57
+ server.close()
File without changes
File without changes
File without changes