diff --git a/bin/adf_codec/convert.py b/bin/adf_codec/convert.py index 4bc4b482..a0e86cc7 100644 --- a/bin/adf_codec/convert.py +++ b/bin/adf_codec/convert.py @@ -2,14 +2,18 @@ It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means. """ +import contextlib import dataclasses import hashlib import json +import os import pathlib import subprocess +import sys import typing from failure import Failure +from machine_load.slots import HELD, slot_count, slot_folder, usable_cpus, waited_slot SHIM = pathlib.Path(__file__).resolve().parent / "node_shim" SHIM_FILES = ("Dockerfile", "package.json", "package-lock.json", "shim.mjs") @@ -31,6 +35,15 @@ class Ran: Run = typing.Callable[[str, str], Ran | Failure] # Runs a docker command line on a text, in at most the given seconds, or fails to run it. Docker = typing.Callable[[list[str], str, int], Ran | Failure] +# Holds one of the machine's heavy slots for a with block, or yields why none could be taken. +Slot = typing.Callable[[], typing.ContextManager[Failure | None]] + + +@dataclasses.dataclass(frozen=True) +class Refused: + """adf-codec refused the document at index of those handed to adfs_to_markdown.""" + index: int + failure: Failure def image_tag(shim: pathlib.Path) -> str: @@ -55,17 +68,54 @@ def docker(args: list[str], text: str, seconds: int, call: typing.Callable[..., return Ran(done.returncode, done.stdout, done.stderr) -def ensure_image(shim: pathlib.Path, run_docker: Docker = docker) -> str | Failure: - """The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag.""" +@contextlib.contextmanager +def heavy_slot(env: typing.Mapping[str, str] = os.environ, slots: int | None = None) -> typing.Iterator[Failure | None]: + """Holds one of the machine's heavy slots, which run-heavy shares, for the with block; under run-heavy the process already holds one, so it waits for none.""" + if HELD in env: + yield None + return + folder = slot_folder(env, pathlib.Path.home()) + count = slot_count(usable_cpus()) if slots is None else slots + try: + folder.mkdir(parents=True, exist_ok=True) + _, fd = waited_slot(folder, count, lambda: print(f"adf-codec: waiting for a heavy slot, of {count} on this machine, to build the shim's image", file=sys.stderr, flush=True)) + except OSError as failure: + yield Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}") + return + try: + yield None + finally: + os.close(fd) + + +def ensure_image(shim: pathlib.Path, run_docker: Docker = docker, slot: Slot = heavy_slot) -> str | Failure: + """The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag. + + The build waits for a heavy slot, since `docker build` is heavy. Once the slot is held it looks again, as another process may have built the image meanwhile.""" tag = image_tag(shim) + found = image_found(tag, run_docker) + if found is not False: + return tag if found is True else found + with slot() as refused: + if refused is not None: + return refused + found = image_found(tag, run_docker) + if found is not False: + return tag if found is True else found + return build_image(shim, tag, run_docker) + + +def image_found(tag: str, run_docker: Docker) -> bool | Failure: found = run_docker(["docker", "image", "inspect", tag], "", RUN_SECONDS) - if isinstance(found, Failure) or found.status == 0: - return found if isinstance(found, Failure) else tag - built = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS) - if isinstance(built, Failure): - return built - if built.status != 0: - return Failure(f"building the adf-codec shim's image failed with exit {built.status}: {built.err.strip()}") + return found if isinstance(found, Failure) else found.status == 0 + + +def build_image(shim: pathlib.Path, tag: str, run_docker: Docker) -> str | Failure: + ran = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS) + if isinstance(ran, Failure): + return ran + if ran.status != 0: + return Failure(f"building the adf-codec shim's image failed with exit {ran.status}: {ran.err.strip()}") return tag @@ -76,8 +126,8 @@ def container_run(mode: str, text: str, run_docker: Docker = docker, shim: pathl return run_docker(docker_args(image, mode), text, RUN_SECONDS) -def answer(mode: str, text: str, run: Run) -> str | Failure: - """What the shim printed for text, or a Failure saying why it gave no answer.""" +def answer(mode: str, text: str, run: Run) -> str | Refused | Failure: + """What the shim printed for text, or why it gave no answer: a Refused where it named the refused document's index.""" ran = run(mode, text) if isinstance(ran, Failure): return ran @@ -88,18 +138,22 @@ def answer(mode: str, text: str, run: Run) -> str | Failure: return Failure(f"the adf-codec shim failed with exit {ran.status}: {ran.err.strip()}") -def refusal(out: str) -> Failure: +def refusal(out: str) -> Refused | Failure: try: - error = json.loads(out)["error"] + refused = json.loads(out) + error = refused["error"] where = f"line {error['position']['line']}" if "position" in error else ".".join(str(step) for step in error["path"]) or "the document" - return Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})") - except (ValueError, KeyError, TypeError): + failure = Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})") + return Refused(refused["index"], failure) if isinstance(refused.get("index"), int) else failure + except (ValueError, KeyError, TypeError, AttributeError): return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}") def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure: """The ADF document for the markdown.""" out = answer("to-adf", markdown, run) + if isinstance(out, Refused): + return out.failure if isinstance(out, Failure): return out try: @@ -109,6 +163,27 @@ def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing return document +def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure: + """The markdown for each ADF document, in their order, from one container run, so a caller with many documents pays one container start.""" + if not documents: + return [] + out = answer("to-markdown", json.dumps(documents), run) + if isinstance(out, Refused) and not 0 <= out.index < len(documents): + return Failure(f"the adf-codec shim refused document {out.index} of the {len(documents)} handed to it, counting from 0") + if isinstance(out, Refused | Failure): + return out + try: + texts = json.loads(out) + except ValueError: + texts = None + if not isinstance(texts, list) or len(texts) != len(documents) or not all(isinstance(text, str) for text in texts): + return Failure(f"the adf-codec shim printed output that is not a JSON array of {len(documents)} texts: {out.strip()}") + return texts + + def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure: """The markdown for the ADF document.""" - return answer("to-markdown", json.dumps(document), run) + texts = adfs_to_markdown([document], run) + if isinstance(texts, Refused): + return texts.failure + return texts if isinstance(texts, Failure) else texts[0] diff --git a/bin/adf_codec/node_shim/shim.mjs b/bin/adf_codec/node_shim/shim.mjs index 6c889399..eeb0b601 100644 --- a/bin/adf_codec/node_shim/shim.mjs +++ b/bin/adf_codec/node_shim/shim.mjs @@ -1,7 +1,8 @@ // Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument: // to-adf stdin is markdown, stdout is the ADF document as JSON -// to-markdown stdin is an ADF document as JSON, stdout is markdown -// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}. +// to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order +// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}, +// with "index", the refused document's place in the array, beside "error" in to-markdown. // Exit 1: the shim could not run, and stderr says why. import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec' @@ -13,19 +14,33 @@ async function readStdin() { return Buffer.concat(chunks).toString('utf8') } -function finish(result, render) { - if (result.ok) { - process.stdout.write(render(result.value)) - return 0 - } - process.stdout.write(JSON.stringify({ error: result.error })) +function refuse(refusal) { + process.stdout.write(JSON.stringify(refusal)) return REFUSED } +function toAdf(markdown) { + const result = portableMarkdownToAdf(markdown) + if (!result.ok) return refuse({ error: result.error }) + process.stdout.write(JSON.stringify(result.value)) + return 0 +} + +function toMarkdown(documents) { + const texts = [] + for (const [index, document] of documents.entries()) { + const result = adfToPortableMarkdown(document) + if (!result.ok) return refuse({ index, error: result.error }) + texts.push(result.value) + } + process.stdout.write(JSON.stringify(texts)) + return 0 +} + async function main(mode) { const input = await readStdin() - if (mode === 'to-adf') return finish(portableMarkdownToAdf(input), (doc) => JSON.stringify(doc)) - if (mode === 'to-markdown') return finish(adfToPortableMarkdown(JSON.parse(input)), (markdown) => markdown) + if (mode === 'to-adf') return toAdf(input) + if (mode === 'to-markdown') return toMarkdown(JSON.parse(input)) throw new Error(`mode must be to-adf or to-markdown, not ${mode}`) } diff --git a/bin/adf_codec/test_adf_codec.py b/bin/adf_codec/test_adf_codec.py index 470b288f..c1a78b36 100644 --- a/bin/adf_codec/test_adf_codec.py +++ b/bin/adf_codec/test_adf_codec.py @@ -1,4 +1,6 @@ +import contextlib import json +import os import shutil import subprocess @@ -6,6 +8,7 @@ import pytest from adf_codec import convert from failure import Failure +from machine_load import slots DOC = {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hi"}]}]} @@ -27,10 +30,40 @@ def test_markdown_to_adf_returns_the_document_the_shim_printed(): assert run.calls == [("to-adf", "Hi\n")] -def test_adf_to_markdown_sends_the_document_as_json_and_returns_the_text(): - run = fake(0, "Hi\n") +def test_adfs_to_markdown_sends_every_document_in_one_run_and_returns_the_texts_in_order(): + run = fake(0, json.dumps(["Hi\n", "Yo\n"])) + assert convert.adfs_to_markdown([DOC, DOC], run) == ["Hi\n", "Yo\n"] + assert run.calls == [("to-markdown", json.dumps([DOC, DOC]))] + + +def test_adfs_to_markdown_of_no_documents_runs_no_container(): + run = fake(1) + assert convert.adfs_to_markdown([], run) == [] + assert run.calls == [] + + +def test_a_refused_document_names_its_index(): + refusal = {"index": 1, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}} + refused = convert.adfs_to_markdown([DOC, DOC], fake(2, json.dumps(refusal))) + assert refused == convert.Refused(1, Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)")) + + +def test_a_refusal_naming_no_document_handed_in_becomes_a_failure(): + refusal = {"index": 2, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}} + failure = convert.adfs_to_markdown([DOC, DOC], fake(2, json.dumps(refusal))) + assert failure == Failure("the adf-codec shim refused document 2 of the 2 handed to it, counting from 0") + + +def test_texts_that_do_not_match_the_documents_become_a_failure(): + for out in ("not json", json.dumps(["Hi\n"]), json.dumps({"0": "Hi\n"}), json.dumps(["Hi\n", 7])): + failure = convert.adfs_to_markdown([DOC, DOC], fake(0, out)) + assert failure == Failure(f"the adf-codec shim printed output that is not a JSON array of 2 texts: {out}"), out + + +def test_adf_to_markdown_returns_the_text_of_its_one_document(): + run = fake(0, json.dumps(["Hi\n"])) assert convert.adf_to_markdown(DOC, run) == "Hi\n" - assert run.calls == [("to-markdown", json.dumps(DOC))] + assert run.calls == [("to-markdown", json.dumps([DOC]))] def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message(): @@ -40,7 +73,7 @@ def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message(): def test_a_refusal_without_a_position_names_the_path(): - refusal = {"error": {"code": "unsupported-node-shape", "message": "bad node", "path": ["content", 0]}} + refusal = {"index": 0, "error": {"code": "unsupported-node-shape", "message": "bad node", "path": ["content", 0]}} failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal))) assert failure == Failure("adf-codec refused the input with unsupported-node-shape: bad node (at content.0)") @@ -87,7 +120,7 @@ def test_the_container_command_line_is_exactly_this(): def test_a_refusal_at_the_root_says_the_document(): - refusal = {"error": {"code": "not-an-adf-document", "message": "no type", "path": []}} + refusal = {"index": 0, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}} failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal))) assert failure == Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)") @@ -143,24 +176,74 @@ def test_an_image_that_exists_is_not_built(tmp_path): assert run_docker.lines == [(["docker", "image", "inspect", tag], "", convert.RUN_SECONDS)] -def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit(tmp_path): +class Slot: + """Stands in for a heavy slot: records the docker lines run while it is held, or yields the given Failure.""" + def __init__(self, run_docker, failure: Failure | None = None): + self.run_docker, self.failure, self.held_lines = run_docker, failure, None + + @contextlib.contextmanager + def __call__(self): + before = len(self.run_docker.lines) + yield self.failure + self.held_lines = self.run_docker.lines[before:] + + +def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit_inside_a_heavy_slot(tmp_path): + missing = convert.Ran(1, "", "") + run_docker = scripted(missing, missing, convert.Ran(0, "", "")) + slot = Slot(run_docker) + tag = convert.image_tag(shim_dir(tmp_path)) + assert convert.ensure_image(tmp_path, run_docker, slot) == tag + inspect = (["docker", "image", "inspect", tag], "", convert.RUN_SECONDS) + build = (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS) + assert run_docker.lines == [inspect, inspect, build] + assert slot.held_lines == [inspect, build] + + +def test_an_image_another_process_built_while_this_one_waited_for_a_slot_is_not_built_again(tmp_path): run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(0, "", "")) tag = convert.image_tag(shim_dir(tmp_path)) - assert convert.ensure_image(tmp_path, run_docker) == tag - assert run_docker.lines[1] == (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS) + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == tag + assert len(run_docker.lines) == 2 + + +def test_a_heavy_slot_that_cannot_be_taken_fails_before_the_build(tmp_path): + run_docker = scripted(convert.Ran(1, "", "")) + shim_dir(tmp_path) + down = Failure("cannot take a heavy slot in /x: Permission denied") + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker, down)) == down + assert len(run_docker.lines) == 1 def test_a_failed_build_becomes_a_failure_with_its_stderr(tmp_path): - run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n")) + run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n")) shim_dir(tmp_path) - assert convert.ensure_image(tmp_path, run_docker) == Failure("building the adf-codec shim's image failed with exit 5: no network") + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == Failure("building the adf-codec shim's image failed with exit 5: no network") def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path): shim_dir(tmp_path) - down = Failure("docker is not installed") - assert convert.ensure_image(tmp_path, scripted(down)) == down - assert convert.ensure_image(tmp_path, scripted(convert.Ran(1, "", ""), down)) == down + down, missing = Failure("docker is not installed"), convert.Ran(1, "", "") + for answers in ((down,), (missing, down), (missing, missing, down)): + run_docker = scripted(*answers) + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == down, answers + + +def test_a_heavy_slot_is_held_until_the_block_ends_and_waits_for_none_under_run_heavy(tmp_path): + env = {"XDG_STATE_HOME": str(tmp_path)} + with convert.heavy_slot(env, 1) as held: + assert held is None + assert slots.taken_slot(tmp_path / "run-heavy", 1) is None + slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1) + with convert.heavy_slot(env | {slots.HELD: "0"}, 1) as held: + assert held is None + os.close(fd) + + +def test_a_heavy_slot_folder_that_cannot_be_made_yields_a_failure(tmp_path): + (tmp_path / "run-heavy").write_text("a file where the folder goes") + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held: + assert isinstance(held, Failure) and held.reason.startswith(f"cannot take a heavy slot in {tmp_path / 'run-heavy'}: ") def test_container_run_runs_the_image_on_the_text(tmp_path): @@ -182,5 +265,8 @@ def test_round_trip_through_the_real_container(): assert isinstance(markdown, str) and markdown.startswith("# Title") and "**bold**" in markdown refused = convert.adf_to_markdown({"type": "nope"}) assert isinstance(refused, Failure) and "not-an-adf-document" in refused.reason + assert convert.adfs_to_markdown([doc, doc]) == [markdown, markdown] + second = convert.adfs_to_markdown([doc, {"type": "nope"}]) + assert isinstance(second, convert.Refused) and second.index == 1 and "not-an-adf-document" in second.failure.reason crashed = convert.answer("to-markdown", "not json", convert.container_run) assert isinstance(crashed, Failure) and crashed.reason.startswith("the adf-codec shim failed with exit 1: ") diff --git a/bin/machine_load/slots.py b/bin/machine_load/slots.py index c8424608..749ae80d 100644 --- a/bin/machine_load/slots.py +++ b/bin/machine_load/slots.py @@ -8,6 +8,8 @@ import typing CPUS_PER_SLOT = 4 # Seconds between tries while every slot is held; a slot frees as its command exits. POLL_SECONDS = 1 +# The environment variable that tells a process it already holds a slot, which run-heavy sets for its command, so a step of a gate it runs doesn't wait on the gate's own slot. +HELD = "RUN_HEAVY_SLOT" def usable_cpus() -> int | None: diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index 470dff78..81383554 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -4,13 +4,12 @@ An item is an open child issue. Its ID is the issue's number, so every child mus The store only reads so far: every write is a Failure.""" import base64 -import concurrent.futures import dataclasses import pathlib import re import typing -from adf_codec.convert import adf_to_markdown +from adf_codec.convert import adfs_to_markdown, Refused from plan_store.markdown_edits import bold_cell from project_config.settings import Epic from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE @@ -30,13 +29,11 @@ TIMEOUT = 30 PAGE = 100 # The pages one read asks for at most, so an answer that never names a last page ends the read. MAX_PAGES = 100 -# The adf-codec containers run at once, each converting one description: one heavy slot's CPUs. -CONVERSIONS = 4 READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira" # Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none. Http = typing.Callable[[str, str, str, object], object] -ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure] +ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure] def http_json(method: str, url: str, authorization: str, body: object) -> object: @@ -75,7 +72,7 @@ class JiraPlan: epic: Epic env_file: pathlib.Path http: Http = http_json - to_markdown: ToMarkdown = adf_to_markdown + to_markdown: ToMarkdown = adfs_to_markdown @property def label(self) -> str: @@ -164,8 +161,8 @@ def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | items = [item(issue, project, ids) for issue in issues] if failed := next((found for found in items if isinstance(found, Failure)), None): return failed - # The descriptions convert last, since each costs a container run, which a read that fails doesn't need. - texts = details(issues, to_markdown) + # The descriptions convert last, since that costs a container run, which a read that fails doesn't need. + texts = details(issues, epic, to_markdown) if isinstance(texts, Failure): return texts return Plan([dataclasses.replace(found, detail=texts.get(found.id, "")) for found in items if isinstance(found, Item)]) @@ -175,19 +172,15 @@ def number(key: str) -> int: return int(key.rpartition("-")[2]) -def details(issues: list[Issue], to_markdown: ToMarkdown) -> dict[int, str] | Failure: - """Each described issue's description as markdown, under the issue's number. The first converts alone, since that run builds the codec's image where the machine has none; the rest convert CONVERSIONS at a time.""" +def details(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> dict[int, str] | Failure: + """Each described issue's description as markdown, under the issue's number, all converted at once.""" described = [(issue, issue.description) for issue in issues if issue.description is not None] - texts: list[str | Failure] = [to_markdown(description) for _, description in described[:1]] - if not any(isinstance(text, Failure) for text in texts): - with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool: - texts += pool.map(to_markdown, [description for _, description in described[1:]]) - found = {} - for (issue, _), text in zip(described, texts): - if isinstance(text, Failure): - return Failure(f"{issue.key}'s description: {text.reason}") - found[issue.number] = text.strip() - return found + texts = to_markdown([description for _, description in described]) + if isinstance(texts, Refused): + return Failure(f"{described[texts.index][0].key}'s description: {texts.failure.reason}") + if isinstance(texts, Failure): + return Failure(f"cannot convert the descriptions of {epic.key}'s children to markdown: {texts.reason}") + return {issue.number: text.strip() for (issue, _), text in zip(described, texts)} def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure: diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index f05e009a..7d233c33 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -2,8 +2,6 @@ import base64 import pathlib import sys import tempfile -import threading -import time import unittest import unittest.mock @@ -13,6 +11,7 @@ from project_config.settings import Epic from failure import Failure from plan_store import jira_epic from plan_store.stores import Plan +from adf_codec.convert import Refused from release_plan.release import release_of EPIC = Epic("https://acme.atlassian.net", "ABC-12") @@ -48,7 +47,7 @@ class JiraPlan(unittest.TestCase): self.calls: list[tuple[str, str, str, object]] = [] self.epic: object = {"key": "ABC-12"} self.epic_calls: list[tuple[str, str, str, object]] = [] - self.converted: list[object] = [] + self.converted: list[list[dict[str, object]]] = [] def http(self, method: str, url: str, authorization: str, body: object) -> object: """Stands in for Jira: answers self.epic to the request for the epic, and the next of self.pages to each search.""" @@ -58,9 +57,9 @@ class JiraPlan(unittest.TestCase): self.calls.append((method, url, authorization, body)) return self.pages[len(self.calls) - 1] - def to_markdown(self, document: dict[str, object]) -> str | Failure: - self.converted.append(document) - return text_of(document) + def to_markdown(self, documents: list[dict[str, object]]) -> list[str] | Refused | Failure: + self.converted.append(documents) + return [text_of(document) for document in documents] def store(self) -> jira_epic.JiraPlan: return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown) @@ -167,22 +166,6 @@ class JiraPlan(unittest.TestCase): with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 2): self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages")) - def test_converts_at_most_four_descriptions_at_once(self): - lock, running, most = threading.Lock(), [0], [0] - - def slow(document: dict[str, object]) -> str: - with lock: - running[0] += 1 - most[0] = max(most[0], running[0]) - time.sleep(0.02) - with lock: - running[0] -= 1 - return "text" - - self.pages = [{"issues": [issue(f"ABC-{number}", description=adf("Why.")) for number in range(1, 41)]}] - self.assertIsInstance(jira_epic.JiraPlan(EPIC, self.env, self.http, slow).read(), Plan) - self.assertLessEqual(most[0], 4) - def test_an_issue_in_another_shape_fails_the_read_naming_it(self): good = issue("ABC-1") for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator] @@ -191,22 +174,20 @@ class JiraPlan(unittest.TestCase): self.assertIsInstance(failure, Failure) self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr] - def test_converts_each_description_once_and_none_for_an_issue_without_one(self): + def test_converts_every_description_in_one_run_and_none_for_an_issue_without_one(self): found = self.items(issue("ABC-1", description=adf("One.")), issue("ABC-2"), issue("ABC-3", description=adf("Three.")), issue("ABC-4", description=adf("Four."))) self.assertEqual([item.detail for item in found], ["One.", "", "Three.", "Four."]) - self.assertEqual(len(self.converted), 3) - - def test_a_first_description_the_codec_refuses_converts_no_other(self): - calls: list[object] = [] - store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: calls.append(document) or Failure("no docker")) # type: ignore[func-returns-value] - self.pages = [{"issues": [issue("ABC-1", description=adf("One.")), issue("ABC-2", description=adf("Two."))]}] - self.assertEqual(store.read(), Failure("ABC-1's description: no docker")) - self.assertEqual(len(calls), 1) + self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]]) def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self): - store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused")) + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused"))) + self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}] + self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused")) + + def test_a_codec_that_cannot_run_fails_the_read(self): + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed")) self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}] - self.assertEqual(store.read(), Failure("ABC-34's description: adf-codec refused")) + self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed")) def test_an_env_file_without_the_credentials_fails_before_any_request(self): self.env.write_text("ATLASSIAN_EMAIL=me@example.com\n") diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py index 4f4ad6b4..27e7a965 100644 --- a/bin/run_heavy/main.py +++ b/bin/run_heavy/main.py @@ -36,11 +36,10 @@ import typing from run_heavy.capped_docker import CANNOT_RUN, NOT_FOUND, PATH_ENTRY, SHARE_VARIABLE, without_path_entry from failure import Failure +from machine_load.slots import HELD, slot_count, slot_folder, waited_slot from machine_load.memory import Memory -from machine_load.slots import slot_count, slot_folder, waited_slot OWN_FAILURE = 125 -HELD = "RUN_HEAVY_SLOT" USAGE = "usage: run-heavy [...]"