python-ship 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.
python_ship/release.py ADDED
@@ -0,0 +1,175 @@
1
+ """Plan unique production images and assemble Docker-only releases."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import shlex
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+ from typing import Any
15
+
16
+ from . import __version__
17
+ from .compose import render
18
+ from .config import ConfigError, ShipConfig, command_text
19
+
20
+ TAG_PATTERN = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}"
21
+
22
+
23
+ def plan_images(model: dict[str, Any], tag: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
24
+ """Give identical build definitions one image tag, one build owner and one archive."""
25
+ planned = deepcopy(model)
26
+ services = planned["services"]
27
+ groups: dict[str, list[str]] = {}
28
+ for name, service in services.items():
29
+ if "build" in service:
30
+ signature = json.dumps(service["build"], sort_keys=True, separators=(",", ":"))
31
+ groups.setdefault(signature, []).append(name)
32
+ images = []
33
+ aliases = {}
34
+ for members in groups.values():
35
+ members = sorted(members)
36
+ # The app owns its group; processes share its image.
37
+ owner = next((name for name in members if not services[name].get("stop_grace_period")), members[0])
38
+ image = f"{planned['name']}-{owner}:{tag}"
39
+ for name in members:
40
+ old_image = services[name].get("image")
41
+ if old_image:
42
+ aliases[old_image] = image
43
+ services[name]["image"] = image
44
+ images.append({"image": image, "owner": owner, "services": members})
45
+ for service in services.values():
46
+ if "build" not in service and service.get("image") in aliases:
47
+ service["image"] = aliases[service["image"]]
48
+ # Processes reuse the app's image without building it; list every service that runs each image.
49
+ for entry in images:
50
+ entry["services"] = sorted(name for name, service in services.items() if service.get("image") == entry["image"])
51
+ return planned, sorted(images, key=lambda entry: entry["owner"])
52
+
53
+
54
+ def _run(command: list[str], root: Path) -> subprocess.CompletedProcess[str]:
55
+ result = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False)
56
+ if result.returncode != 0:
57
+ raise ConfigError(f"`{' '.join(command[:3])}` failed: {result.stderr.strip() or result.stdout.strip()}")
58
+ return result
59
+
60
+
61
+ def release_model(model: dict[str, Any]) -> dict[str, Any]:
62
+ """The production model with every build: removed and .env as the required env file."""
63
+ release = deepcopy(model)
64
+ for service in release["services"].values():
65
+ service.pop("build", None)
66
+ for env_file in service.get("env_file", []):
67
+ if isinstance(env_file, dict) and env_file.get("path") == ".env.production":
68
+ env_file["path"] = ".env"
69
+ env_file["required"] = True
70
+ return release
71
+
72
+
73
+ def deploy_script(config: ShipConfig, model: dict[str, Any]) -> str:
74
+ """Start infrastructure, wait for it, then run each deploy command once in a fresh app container."""
75
+ app = config.app_service
76
+ # Everything except the containers running the app's own image (the app, processes, Celery).
77
+ app_services = set(model.get("x-ship", {}).get("app_services", [app, *config.processes]))
78
+ infrastructure = sorted(set(model["services"]) - app_services)
79
+ lines = [
80
+ "#!/bin/sh",
81
+ "# Generated by python-ship. Runs once per deploy, before `docker compose up -d`.",
82
+ "set -eu",
83
+ 'cd "$(dirname "$0")"',
84
+ ]
85
+ if infrastructure:
86
+ lines.append("docker compose up -d --wait " + " ".join(map(shlex.quote, infrastructure)))
87
+ for command in config.deploy_commands:
88
+ lines.append(f"echo {shlex.quote('ship: ' + command_text(command))}")
89
+ if isinstance(command, str):
90
+ lines.append(f"docker compose run --rm --no-deps {shlex.quote(app)} sh -c {shlex.quote(command)}")
91
+ else:
92
+ lines.append(f"docker compose run --rm --no-deps {shlex.quote(app)} {shlex.join(command)}")
93
+ return "\n".join(lines) + "\n"
94
+
95
+
96
+ def _git_commit(root: Path) -> str | None:
97
+ try:
98
+ result = subprocess.run(["git", "rev-parse", "HEAD"], cwd=root, capture_output=True, text=True, check=False)
99
+ except OSError:
100
+ return None
101
+ return result.stdout.strip() if result.returncode == 0 else None
102
+
103
+
104
+ def _sha256(path: Path) -> str:
105
+ digest = hashlib.sha256()
106
+ with path.open("rb") as stream:
107
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
108
+ digest.update(chunk)
109
+ return digest.hexdigest()
110
+
111
+
112
+ def assemble_release(root: Path, config: ShipConfig, model: dict[str, Any], tag: str) -> Path:
113
+ """Export every image and publish the artifact only after every step succeeds."""
114
+ source_env = root / ".env.production"
115
+ if not source_env.is_file():
116
+ raise ConfigError("ship release requires .env.production, even when no selected service needs credentials.")
117
+ parent = root / "dist" / "ship"
118
+ parent.mkdir(parents=True, exist_ok=True)
119
+ stage = Path(tempfile.mkdtemp(prefix=".release-", dir=parent))
120
+ destination = parent / tag
121
+ try:
122
+ if os.name != "nt":
123
+ stage.chmod(0o700)
124
+ images_dir = stage / "images"
125
+ images_dir.mkdir()
126
+ compose = release_model(model)
127
+ (stage / "docker-compose.yml").write_text(render(compose), encoding="utf-8")
128
+ shutil.copyfile(source_env, stage / ".env")
129
+ if os.name != "nt":
130
+ (stage / ".env").chmod(0o600)
131
+ by_image: dict[str, list[str]] = {}
132
+ for name, service in compose["services"].items():
133
+ image = service.get("image")
134
+ if not isinstance(image, str) or not image:
135
+ raise ConfigError(f"Release service {name!r} has no image.")
136
+ by_image.setdefault(image, []).append(name)
137
+ images = []
138
+ for image, members in sorted(by_image.items()):
139
+ if subprocess.run(["docker", "image", "inspect", image], cwd=root, capture_output=True).returncode != 0:
140
+ _run(["docker", "pull", image], root)
141
+ archive = f"images/{sorted(members)[0]}.tar"
142
+ _run(["docker", "save", "-o", str(stage / archive), image], root)
143
+ images.append({"image": image, "file": archive, "sha256": _sha256(stage / archive), "services": sorted(members)})
144
+ if config.deploy_commands:
145
+ script = stage / "deploy-commands.sh"
146
+ script.write_text(deploy_script(config, compose), encoding="utf-8", newline="\n")
147
+ if os.name != "nt":
148
+ script.chmod(0o700)
149
+ instructions = [
150
+ f"# Release {tag}", "",
151
+ "Built by python-ship. From this directory, on a machine with Docker and Compose v2:", "",
152
+ "```sh",
153
+ *[f"docker load -i {entry['file']}" for entry in images],
154
+ *(["sh deploy-commands.sh"] if config.deploy_commands else []),
155
+ "docker compose up -d",
156
+ "```", "",
157
+ "`.env` holds production secrets; keep this directory private.", "",
158
+ ]
159
+ (stage / "README.md").write_text("\n".join(instructions), encoding="utf-8")
160
+ manifest = {
161
+ "tag": tag,
162
+ "ship": {"package": "python-ship", "version": __version__},
163
+ "git_commit": _git_commit(root),
164
+ "images": images,
165
+ }
166
+ (stage / "release.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
167
+ if destination.is_symlink():
168
+ raise ConfigError(f"Release destination {destination} is a symlink; remove it before retrying.")
169
+ if destination.exists():
170
+ shutil.rmtree(destination)
171
+ stage.replace(destination)
172
+ return destination
173
+ finally:
174
+ if stage.exists():
175
+ shutil.rmtree(stage)
python_ship/runtime.py ADDED
@@ -0,0 +1,83 @@
1
+ """Verify that `docker compose up` produced a usable development stack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import subprocess
8
+ import time
9
+ from typing import Any
10
+
11
+ from .config import ConfigError
12
+
13
+
14
+ def records(output: str) -> dict[str, dict[str, Any]]:
15
+ """`docker compose ps --format json` output keyed by service; Compose versions differ in shape."""
16
+ try:
17
+ parsed = [json.loads(line) for line in output.splitlines() if line.strip()]
18
+ except json.JSONDecodeError as exc:
19
+ raise ConfigError(f"Could not read Docker Compose container status: {exc}") from exc
20
+ if len(parsed) == 1 and isinstance(parsed[0], list):
21
+ parsed = parsed[0]
22
+ return {record["Service"]: record for record in parsed if isinstance(record, dict) and "Service" in record}
23
+
24
+
25
+ def status(found: dict[str, dict[str, Any]], expected: set[str], app: str = "app") -> tuple[list[str], list[str], int | None]:
26
+ """Fatal problems, still-pending services, and the app's published host port."""
27
+ fatal = []
28
+ pending = []
29
+ for name in sorted(expected):
30
+ record = found.get(name)
31
+ if record is None:
32
+ pending.append(f"{name} has no container")
33
+ continue
34
+ state = record.get("State", "unknown")
35
+ health = record.get("Health", "")
36
+ if state in {"exited", "dead", "restarting"} or health == "unhealthy":
37
+ fatal.append(f"{name} is {state} (health: {health or 'none'}, exit code: {record.get('ExitCode', '?')})")
38
+ elif state != "running" or health == "starting":
39
+ pending.append(f"{name} is {state} (health: {health or 'none'})")
40
+ port = None
41
+ for publisher in (found.get(app) or {}).get("Publishers") or []:
42
+ if str(publisher.get("TargetPort")) == "8000" and publisher.get("Protocol", "tcp") == "tcp" and publisher.get("PublishedPort"):
43
+ port = int(publisher["PublishedPort"])
44
+ break
45
+ if app in expected and port is None:
46
+ pending.append(f"{app} port 8000 is not published")
47
+ return fatal, pending, port
48
+
49
+
50
+ def wait_for_stack(prefix: list[str], expected: set[str], app: str = "app", timeout: float = 180.0) -> int | None:
51
+ """Wait for every container, healthcheck and the app port; raise with the reason on failure."""
52
+ deadline = time.monotonic() + timeout
53
+ last_pending: list[str] = []
54
+ while time.monotonic() < deadline:
55
+ result = subprocess.run(prefix + ["ps", "--all", "--format", "json"], capture_output=True, text=True, check=False)
56
+ if result.returncode != 0:
57
+ raise ConfigError(f"Could not inspect the stack: {result.stderr.strip()}")
58
+ fatal, pending, port = status(records(result.stdout), expected, app)
59
+ if fatal:
60
+ raise ConfigError("; ".join(fatal) + ". Run `ship logs SERVICE` to see why.")
61
+ if not pending and port is not None:
62
+ if responds(port):
63
+ return port
64
+ pending.append(f"{app} is not answering HTTP on port {port} yet")
65
+ last_pending = pending
66
+ time.sleep(1)
67
+ raise ConfigError("The stack did not become ready: " + "; ".join(last_pending) + ". Run `ship logs` to see why.")
68
+
69
+
70
+ def responds(port: int) -> bool:
71
+ """Whether the app answers HTTP at all; any status counts, even an error page.
72
+
73
+ A bare TCP connect isn't enough: Docker's port proxy accepts connections
74
+ before the server in the container is listening.
75
+ """
76
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=3)
77
+ try:
78
+ connection.request("GET", "/", headers={"User-Agent": "python-ship"})
79
+ return connection.getresponse().status > 0
80
+ except (OSError, http.client.HTTPException):
81
+ return False
82
+ finally:
83
+ connection.close()
@@ -0,0 +1,69 @@
1
+ """The oldest CPython release per branch that Ship builds an image on.
2
+
3
+ The generated Compose models pass this to ``ship/Dockerfile`` as the
4
+ ``SHIP_PYTHON_FLOOR`` build argument, and the Dockerfile fails the build when
5
+ the image's actual Python is older. ship.json's ``python`` is normally a bare
6
+ branch (``"3.13"``), so a stale, locally cached ``python:3.13-slim`` would
7
+ otherwise keep building on a vulnerable patch release indefinitely. A branch
8
+ older than every entry here is past end of life and is refused too.
9
+
10
+ Raise these whenever python.org ships a security release; see
11
+ https://www.python.org/downloads/ and https://blog.python.org/.
12
+ """
13
+
14
+ import re
15
+
16
+ # Branch -> first patched release.
17
+ #
18
+ # Current floor: the expedited security releases of 2026-10-21 and 2026-10-26,
19
+ # which fixed the bundled pip certificate-chain problem, tarfile link handling
20
+ # (CVE-2026-114583), and the bundled Expat vulnerabilities (CVE-2026-77214,
21
+ # CVE-2026-102633).
22
+ MINIMUM_PATCHED = {
23
+ "3.11": "3.11.18",
24
+ "3.12": "3.12.16",
25
+ "3.13": "3.13.18",
26
+ "3.14": "3.14.10",
27
+ "3.15": "3.15.2",
28
+ }
29
+
30
+ DEFAULT_PYTHON = "3.13"
31
+
32
+ _VERSION = re.compile(r"(\d+)\.(\d+)(?:\.(\d+))?")
33
+
34
+
35
+ def _parts(version: str) -> tuple[int, ...]:
36
+ return tuple(int(part) for part in version.split("."))
37
+
38
+
39
+ def build_arg() -> str:
40
+ """Space-separated, oldest branch first, for the Dockerfile build argument."""
41
+ return " ".join(MINIMUM_PATCHED.values())
42
+
43
+
44
+ def problem_with(version: str) -> str | None:
45
+ """Why ``version`` is unsafe to build on, or ``None`` when it is acceptable.
46
+
47
+ A bare branch (``"3.13"``) is acceptable while the branch is supported; the
48
+ Dockerfile checks the resolved patch release. A pinned release
49
+ (``"3.13.4"``) is compared against the floor here.
50
+ """
51
+ match = _VERSION.fullmatch(version)
52
+ if match is None:
53
+ return f"Python version {version!r} must be a branch such as \"3.13\" or a release such as \"3.13.18\"."
54
+ branch = f"{match.group(1)}.{match.group(2)}"
55
+ oldest = next(iter(MINIMUM_PATCHED))
56
+ if _parts(branch) < _parts(oldest):
57
+ return (
58
+ f"Python {branch} is past end of life and gets no security fixes. "
59
+ f"Use Python {oldest} or newer."
60
+ )
61
+ minimum = MINIMUM_PATCHED.get(branch)
62
+ if minimum is None or match.group(3) is None:
63
+ return None
64
+ if _parts(version) < _parts(minimum):
65
+ return (
66
+ f"Python {version} has known security vulnerabilities. Use {minimum} or newer, "
67
+ f"or just \"{branch}\" to always build on its latest patch release."
68
+ )
69
+ return None
python_ship/servers.py ADDED
@@ -0,0 +1,72 @@
1
+ """Built-in web servers. Server choice is independent of the framework adapter,
2
+ but has to match the app's interface: ASGI or WSGI."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from .contracts import Interface
7
+
8
+ # Exact pins keep production images reproducible; Renovate proposes upgrades.
9
+
10
+
11
+ class UvicornServer:
12
+ key = "uvicorn"
13
+ label = "Uvicorn (ASGI)"
14
+ requirement = "uvicorn==0.54.0"
15
+ interfaces: tuple[Interface, ...] = ("asgi",)
16
+
17
+ def development_command(self, target: str, interface: Interface) -> list[str]:
18
+ return ["python", "-m", "uvicorn", target, "--host", "0.0.0.0", "--port", "8000", "--reload"]
19
+
20
+ def production_command(self, target: str, interface: Interface) -> list[str]:
21
+ # Reads WEB_CONCURRENCY (workers) and FORWARDED_ALLOW_IPS (trusted proxies) from the environment.
22
+ return ["python", "-m", "uvicorn", target, "--host", "0.0.0.0", "--port", "8000", "--proxy-headers"]
23
+
24
+
25
+ class HypercornServer:
26
+ key = "hypercorn"
27
+ label = "Hypercorn (ASGI)"
28
+ requirement = "hypercorn==0.18.0"
29
+ interfaces: tuple[Interface, ...] = ("asgi",)
30
+
31
+ def development_command(self, target: str, interface: Interface) -> list[str]:
32
+ return ["python", "-m", "hypercorn", target, "--bind", "0.0.0.0:8000", "--reload"]
33
+
34
+ def production_command(self, target: str, interface: Interface) -> list[str]:
35
+ return ["python", "-m", "hypercorn", target, "--bind", "0.0.0.0:8000"]
36
+
37
+
38
+ class GunicornServer:
39
+ key = "gunicorn"
40
+ label = "Gunicorn (WSGI)"
41
+ requirement = "gunicorn==27.0.1"
42
+ interfaces: tuple[Interface, ...] = ("wsgi",)
43
+
44
+ def development_command(self, target: str, interface: Interface) -> list[str]:
45
+ return ["python", "-m", "gunicorn", "--bind", "0.0.0.0:8000", "--reload", "--access-logfile", "-", target]
46
+
47
+ def production_command(self, target: str, interface: Interface) -> list[str]:
48
+ # Reads WEB_CONCURRENCY (workers) and FORWARDED_ALLOW_IPS (trusted proxies) from the environment.
49
+ return ["python", "-m", "gunicorn", "--bind", "0.0.0.0:8000", "--access-logfile", "-", target]
50
+
51
+
52
+ class GranianServer:
53
+ key = "granian"
54
+ label = "Granian (ASGI and WSGI)"
55
+ requirement = "granian[reload]==2.8.8"
56
+ interfaces: tuple[Interface, ...] = ("asgi", "wsgi")
57
+
58
+ def development_command(self, target: str, interface: Interface) -> list[str]:
59
+ return ["python", "-m", "granian", "--interface", interface, "--host", "0.0.0.0", "--port", "8000", "--reload", target]
60
+
61
+ def production_command(self, target: str, interface: Interface) -> list[str]:
62
+ # Reads GRANIAN_WORKERS and the other GRANIAN_* settings from the environment.
63
+ return ["python", "-m", "granian", "--interface", interface, "--host", "0.0.0.0", "--port", "8000", target]
64
+
65
+
66
+ BUILTIN_SERVERS = {server.key: server for server in (UvicornServer(), HypercornServer(), GunicornServer(), GranianServer())}
67
+
68
+ # What `ship init` suggests, best first, for each interface.
69
+ RECOMMENDED: dict[Interface, tuple[str, ...]] = {
70
+ "asgi": ("uvicorn", "granian", "hypercorn"),
71
+ "wsgi": ("gunicorn", "granian"),
72
+ }