Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 69 additions & 41 deletions tooling/extension-bindings/ci/publish-maven.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
throwaway local repository so that a package finds the selected packages it depends on. A real run signs each
package and uploads it with manual release: the Portal validates the upload, and nothing is public until someone
presses Publish on the deployment. With --auto-publish, the Portal publishes each upload once it passes
validation, and the script waits until Maven Central serves it before uploading a package that depends on it.
validation. The packages go up in waves: a wave holds every package whose selected dependencies came in earlier
waves, all of its uploads go up one after another, and then the script waits for the whole wave at once until
Maven Central serves it. So the long wait for Central happens once per wave, not once per package.
Versions already on Maven Central are never uploaded again.
"""

Expand Down Expand Up @@ -154,6 +156,23 @@ def visit(coordinate: Coordinate) -> None:
return ordered


def publication_waves(packages: dict[Coordinate, dict]) -> list[list[Coordinate]]:
"""Group the selected packages so each wave depends only on selected packages in earlier waves."""
by_name = {(group, artifact): (group, artifact, version) for group, artifact, version in packages}
level: dict[Coordinate, int] = {}
for coordinate in publication_order(packages):
needs = [
level[selected]
for group, artifact, spec in packages[coordinate]["dependencies"]
if (selected := by_name.get((group, artifact))) is not None and in_range(selected[2], spec)
]
level[coordinate] = 1 + max(needs, default=-1)
waves: list[list[Coordinate]] = [[] for _ in range(1 + max(level.values(), default=-1))]
for coordinate in publication_order(packages):
waves[level[coordinate]].append(coordinate)
return waves


def run(command: list[str], cwd: Path) -> subprocess.CompletedProcess:
return subprocess.run(command, cwd=cwd, check=True, text=True)

Expand All @@ -170,25 +189,24 @@ def check_dependencies(coordinate: Coordinate, dependencies: list[Coordinate]) -


def auto_publish_settings(pom_text: str) -> str:
"""The release settings with automatic publishing: the plugin publishes a validated deployment and waits for it."""
for old, new in (
("<autoPublish>false</autoPublish>", "<autoPublish>true</autoPublish>"),
("<waitUntil>validated</waitUntil>", "<waitUntil>published</waitUntil>"),
):
if old not in pom_text:
raise ValueError(f"the release profile has no {old}; cannot publish automatically")
pom_text = pom_text.replace(old, new)
return pom_text
"""The release settings with automatic publishing. The plugin still waits only until the upload is validated,
so a bad upload fails at once; the Portal then publishes it while the next package uploads."""
for required in ("<autoPublish>false</autoPublish>", "<waitUntil>validated</waitUntil>"):
if required not in pom_text:
raise ValueError(f"the release profile has no {required}; cannot publish automatically")
return pom_text.replace("<autoPublish>false</autoPublish>", "<autoPublish>true</autoPublish>")


def wait_until_public(
coordinate: Coordinate, timeout: float = 3600, poll: float = 60, sleep=time.sleep, clock=time.monotonic
coordinates: list[Coordinate], timeout: float = 3600, poll: float = 60, sleep=time.sleep, clock=time.monotonic
) -> None:
"""Wait until Maven Central serves a published version, so packages that depend on it can be built."""
"""Wait until Maven Central serves every given version, checking all of them on each poll."""
deadline = clock() + timeout
while not already_published(coordinate):
pending = list(coordinates)
while pending := [coordinate for coordinate in pending if not already_published(coordinate)]:
if clock() > deadline:
raise ValueError(f"{':'.join(coordinate)} was published but is not on Maven Central after {int(timeout)}s")
names = ", ".join(":".join(coordinate) for coordinate in pending)
raise ValueError(f"{names} published but not on Maven Central after {int(timeout)}s")
sleep(poll)


Expand All @@ -208,38 +226,48 @@ def publish(root: Path, targets: list[Target], execute: bool, auto: bool = False
package = read_pom(root, catalog, target)
packages[package["coordinate"]] = package
done = []
# A real run with auto publishing waits for Central once per wave; otherwise one wave holds every package.
waves = publication_waves(packages) if execute and auto else [publication_order(packages)]
with tempfile.TemporaryDirectory(prefix="maven-bindings-") as name:
workspace = Path(name)
local_repository = workspace / "repository"
for coordinate in publication_order(packages):
label = ":".join(coordinate)
if already_published(coordinate):
summarize(f"{label} is already on Maven Central; skipped.")
continue
copy = workspace / "sources" / coordinate[1]
shutil.copytree(packages[coordinate]["directory"], copy, ignore=shutil.ignore_patterns("target"))
if execute:
check_dependencies(coordinate, packages[coordinate]["dependencies"])
if auto:
# Only this temporary copy changes; the committed package keeps manual publishing.
pom_file = copy / "pom.xml"
pom_file.write_text(auto_publish_settings(pom_file.read_text(encoding="utf-8")), encoding="utf-8")
run(["mvn", "-B", "-Prelease", "deploy"], copy)
if auto:
wait_until_public(coordinate)
summarize(f"Uploaded and published {label}; it is on Maven Central.")
for wave in waves:
uploaded: list[Coordinate] = []
for coordinate in wave:
label = ":".join(coordinate)
if already_published(coordinate):
summarize(f"{label} is already on Maven Central; skipped.")
continue
copy = workspace / "sources" / coordinate[1]
shutil.copytree(packages[coordinate]["directory"], copy, ignore=shutil.ignore_patterns("target"))
if execute:
check_dependencies(coordinate, packages[coordinate]["dependencies"])
if auto:
# Only this temporary copy changes; the committed package keeps manual publishing.
pom_file = copy / "pom.xml"
pom_file.write_text(
auto_publish_settings(pom_file.read_text(encoding="utf-8")), encoding="utf-8"
)
run(["mvn", "-B", "-Prelease", "deploy"], copy)
if auto:
uploaded.append(coordinate)
summarize(f"Uploaded {label}; it passed validation and the Portal is publishing it.")
else:
summarize(
f"Uploaded {label} to the Central Portal and it passed validation. It is not public "
f"until someone presses Publish on the deployment at {DEPLOYMENTS}."
)
else:
summarize(
f"Uploaded {label} to the Central Portal and it passed validation. It is not public until "
f"someone presses Publish on the deployment at {DEPLOYMENTS}."
run(
["mvn", "-B", "-Prelease", "-Dgpg.skip=true", f"-Dmaven.repo.local={local_repository}", "install"],
copy,
)
else:
run(
["mvn", "-B", "-Prelease", "-Dgpg.skip=true", f"-Dmaven.repo.local={local_repository}", "install"],
copy,
)
summarize(f"Built and checked {label}, with sources and Javadoc jars; dry run, nothing was uploaded.")
done.append(label)
summarize(f"Built and checked {label}, with sources and Javadoc jars; dry run, nothing was uploaded.")
done.append(label)
if uploaded:
# One wait for the whole wave; the next wave depends on these being on Central.
wait_until_public(uploaded)
summarize("On Maven Central: " + ", ".join(":".join(coordinate) for coordinate in uploaded) + ".")
summarize(("Uploaded: " if execute else "Would upload: ") + (", ".join(done) if done else "nothing new."))
return len(done)

Expand Down
68 changes: 64 additions & 4 deletions tooling/extension-bindings/ci/test_publish_maven.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,9 @@ def test_the_dependent_is_uploaded_once_its_dependency_is_on_central(self) -> No
def test_auto_publish_turns_on_publishing_in_the_release_settings(self) -> None:
settings = "<autoPublish>false</autoPublish><waitUntil>validated</waitUntil>"
self.assertEqual(
script.auto_publish_settings(settings), "<autoPublish>true</autoPublish><waitUntil>published</waitUntil>"
script.auto_publish_settings(settings),
"<autoPublish>true</autoPublish><waitUntil>validated</waitUntil>",
"the plugin waits only for validation; the script waits for Central once per wave",
)
with self.assertRaisesRegex(ValueError, "cannot publish automatically"):
script.auto_publish_settings("<project/>")
Expand All @@ -215,7 +217,7 @@ def test_auto_publish_uploads_a_dependent_once_its_dependency_is_public(self) ->
def deploy(command, directory):
text = (directory / "pom.xml").read_text(encoding="utf-8")
self.assertIn("<autoPublish>true</autoPublish>", text)
self.assertIn("<waitUntil>published</waitUntil>", text)
self.assertIn("<waitUntil>validated</waitUntil>", text)
uploaded.append(directory.name)
public.add(directory.name)

Expand All @@ -231,11 +233,69 @@ def deploy(command, directory):
def test_waiting_for_central_gives_up_after_the_timeout(self) -> None:
ticks = iter(range(0, 10000, 100))
with patch.object(script, "already_published", return_value=False), self.assertRaisesRegex(
ValueError, "is not on Maven Central after 300s"
ValueError, "addon:0.1.0 published but not on Maven Central after 300s"
):
script.wait_until_public((GROUP, "addon", "0.1.0"), timeout=300, poll=1, sleep=lambda _: None,
script.wait_until_public([(GROUP, "addon", "0.1.0")], timeout=300, poll=1, sleep=lambda _: None,
clock=lambda: next(ticks))

def test_waves_hold_packages_whose_selected_dependencies_came_earlier(self) -> None:
a, b, c, d = ((GROUP, name, "0.1.0") for name in "abcd")
packages = {
a: {"dependencies": []},
b: {"dependencies": []},
c: {"dependencies": [(GROUP, "a", "0.1.0")]},
d: {"dependencies": [(GROUP, "c", "0.1.0"), (GROUP, "elsewhere", "1.0.0")]},
}
self.assertEqual(script.publication_waves(packages), [[a, b], [c], [d]])

def test_waiting_checks_every_pending_version_on_each_poll(self) -> None:
a, b = (GROUP, "a", "0.1.0"), (GROUP, "b", "0.1.0")
public: set[str] = set()
polls = []

def sleep(_):
polls.append(sorted(public))
public.add("a" if len(polls) == 1 else "b")

with patch.object(script, "already_published", side_effect=lambda coordinate: coordinate[1] in public):
script.wait_until_public([a, b], poll=1, sleep=sleep)
self.assertEqual(polls, [[], ["a"]], "both versions are checked together, not one after the other")

def auto_release(self, dependencies: dict[str, list[str] | None]) -> list:
release = "<profiles><autoPublish>false</autoPublish><waitUntil>validated</waitUntil></profiles></project>"
for key, needs in dependencies.items():
self.write(f"bindings/{key}/java/pom.xml", pom(key, dependencies=needs).replace("</project>", release))
events: list = []
public: set[str] = set()

def deploy(command, directory):
events.append(("upload", directory.name))

def wait(coordinates, **_):
events.append(("wait", sorted(coordinate[1] for coordinate in coordinates)))
public.update(coordinate[1] for coordinate in coordinates)

def on_central(coordinate):
return coordinate[1] in public

with patch.object(script, "run", side_effect=deploy), patch.object(
script, "wait_until_public", side_effect=wait
), patch.object(script, "already_published", side_effect=on_central), patch.object(
script, "available", side_effect=on_central
):
script.publish(self.root, self.targets, True, auto=True)
return events

def test_independent_packages_upload_first_and_wait_together(self) -> None:
events = self.auto_release({"addon": None, "owner": None})
self.assertEqual(events, [("upload", "addon"), ("upload", "owner"), ("wait", ["addon", "owner"])])

def test_a_dependent_waits_only_for_the_wave_before_it(self) -> None:
events = self.auto_release({"addon": None, "owner": ["addon"]})
self.assertEqual(
events, [("upload", "addon"), ("wait", ["addon"]), ("upload", "owner"), ("wait", ["owner"])]
)

def test_other_languages_are_not_published(self) -> None:
targets = select_targets(self.catalog, "owner:go")
with patch.object(script, "run") as run:
Expand Down