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/compose.py ADDED
@@ -0,0 +1,439 @@
1
+ """Generate the development and production Compose models from ship.json."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from dataclasses import dataclass
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ import shlex
12
+ import sys
13
+ from typing import Any
14
+
15
+ from . import __version__
16
+ from .config import ConfigError, ShipConfig, command_argv
17
+ from .contracts import APP_PROCESS, Interface, ServiceContext, ServiceDefinition, ShipEnvironment, WebServer
18
+ from .mutagen import enabled as mutagen_enabled
19
+ from .plugins import Registry, load_extensions
20
+ from .security import build_arg as python_floor
21
+ from .services import BROWSER_APP_HOST
22
+
23
+ # The development bind mount; under Mutagen every service with it is synced instead.
24
+ PROJECT_MOUNT = ".:/app"
25
+
26
+ DEVELOPMENT_FILE = "docker-compose.generated.yml"
27
+ PRODUCTION_FILE = "docker-compose.production.yml"
28
+ SERVICE_NAME = re.compile(r"[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*")
29
+ PROCESS_STOP_GRACE = "60s"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Selection:
34
+ """One selected service: the default of its group, or a named additional instance."""
35
+
36
+ service: ServiceDefinition
37
+ group: str
38
+ instance_name: str | None
39
+ service_name: str
40
+
41
+ def context(self, config: ShipConfig, root: Path, environment: ShipEnvironment) -> ServiceContext:
42
+ return ServiceContext(environment, config, root, self.service.key, self.instance_name, self.service_name)
43
+
44
+
45
+ def resolve_selections(config: ShipConfig, registry: Registry) -> list[Selection]:
46
+ """Every selected service with its final Compose name, rejecting unknown or colliding ones."""
47
+ problems = selection_problems(config, registry)
48
+ if problems:
49
+ raise ConfigError(" ".join(problems))
50
+ return _selections(config, registry)
51
+
52
+
53
+ def _selections(config: ShipConfig, registry: Registry) -> list[Selection]:
54
+ selections = []
55
+ for group, key in config.services.items():
56
+ service = registry.services.get(key)
57
+ if service is not None and service.group == group:
58
+ selections.append(Selection(service, group, None, config.service_names.get(key, key)))
59
+ for entry in config.additional_services:
60
+ service = registry.services.get(entry.service)
61
+ if service is not None and service.group == entry.group:
62
+ selections.append(Selection(service, entry.group, entry.name, f"{entry.service}-{entry.name}"))
63
+ return selections
64
+
65
+
66
+ def selection_problems(config: ShipConfig, registry: Registry) -> list[str]:
67
+ problems = []
68
+ for group, key in config.services.items():
69
+ service = registry.services.get(key)
70
+ if service is None:
71
+ problems.append(f"Unknown service {key!r} in group {group!r}.")
72
+ elif service.group != group:
73
+ problems.append(f"Service {key!r} belongs to the {service.group!r} group, not {group!r}.")
74
+ for entry in config.additional_services:
75
+ service = registry.services.get(entry.service)
76
+ if service is None:
77
+ problems.append(f"Unknown service {entry.service!r} in additional instance {entry.name!r}.")
78
+ elif service.group != entry.group:
79
+ problems.append(
80
+ f"Additional instance {entry.name!r}: {entry.service!r} belongs to the "
81
+ f"{service.group!r} group, not {entry.group!r}."
82
+ )
83
+ renamable = {"app", *config.services.values()}
84
+ for old in config.service_names:
85
+ if old not in renamable:
86
+ problems.append(
87
+ f"ship.json \"serviceNames\" renames {old!r}, which is not \"app\" or a selected service."
88
+ )
89
+ names: dict[str, str] = {config.app_service: "the app"}
90
+ for selection in _selections(config, registry):
91
+ owner = names.get(selection.service_name)
92
+ if owner is not None:
93
+ problems.append(f"Compose service name {selection.service_name!r} is used by both {owner} and {selection.service.key!r}.")
94
+ names[selection.service_name] = repr(selection.service.key)
95
+ for process in config.processes:
96
+ if process in names:
97
+ problems.append(f"Process {process!r} conflicts with the Compose service of {names[process]}.")
98
+ return problems
99
+
100
+
101
+ def _merge(base: dict[str, Any], fragment: dict[str, Any], location: str) -> None:
102
+ """Add a fragment's values without silently discarding existing settings."""
103
+ if not isinstance(fragment, dict):
104
+ raise ConfigError(f"{location} must be a Compose object.")
105
+ for key, value in fragment.items():
106
+ path = f"{location}.{key}"
107
+ if key not in base:
108
+ base[key] = deepcopy(value)
109
+ elif isinstance(base[key], dict) and isinstance(value, dict):
110
+ _merge(base[key], value, path)
111
+ elif isinstance(base[key], list) and isinstance(value, list):
112
+ base[key].extend(deepcopy(item) for item in value if item not in base[key])
113
+ elif base[key] != value:
114
+ raise ConfigError(f"Conflicting Compose value at {path}.")
115
+
116
+
117
+ def _local_ports(ports: list[Any], service_name: str) -> list[Any]:
118
+ """Development ports bind 127.0.0.1 unless a host address is given explicitly."""
119
+ localized: list[Any] = []
120
+ for port in ports:
121
+ if isinstance(port, dict):
122
+ localized.append({"host_ip": "127.0.0.1", **port})
123
+ elif isinstance(port, int):
124
+ localized.append({"target": port, "host_ip": "127.0.0.1"})
125
+ elif isinstance(port, str):
126
+ endpoint, separator, protocol = port.partition("/")
127
+ if endpoint.count(":") == 1 and not endpoint.startswith("["):
128
+ endpoint = "127.0.0.1:" + endpoint
129
+ elif endpoint.isdigit():
130
+ localized.append({"target": int(endpoint), "host_ip": "127.0.0.1",
131
+ **({"protocol": protocol} if separator else {})})
132
+ continue
133
+ localized.append(endpoint + (separator + protocol if separator else ""))
134
+ else:
135
+ raise ConfigError(f"Compose service {service_name!r} has an invalid port entry.")
136
+ return localized
137
+
138
+
139
+ def project_name(config: ShipConfig, project_root: Path) -> str:
140
+ """``name`` from ship.json, or a sanitized form of the project directory's name."""
141
+ if config.name:
142
+ return config.name
143
+ name = re.sub(r"[^a-z0-9]+", "-", project_root.resolve().name.lower()).strip("-")
144
+ if not name or not name[0].isalpha():
145
+ name = "ship-" + name if name else "ship"
146
+ return name
147
+
148
+
149
+ def _command_list(value: Any, what: str) -> list[str]:
150
+ if not isinstance(value, list) or not value or any(not isinstance(part, str) or not part for part in value):
151
+ raise ConfigError(f"{what} must be a nonempty list of strings.")
152
+ return value
153
+
154
+
155
+ def _escape_dollars(argv: list[str]) -> list[str]:
156
+ # Compose interpolates $VAR in a service's command; a shell variable meant for the container
157
+ # would otherwise be blanked out silently.
158
+ return [part.replace("$", "$$") for part in argv]
159
+
160
+
161
+ def _app_command(config: ShipConfig, root: Path, registry: Registry, environment: ShipEnvironment) -> list[str]:
162
+ adapter = registry.adapter(config)
163
+ interface = app_interface(config, root, registry)
164
+ server = registry.server(config, interface)
165
+ try:
166
+ target = adapter.server_target(config)
167
+ except Exception as exc:
168
+ raise ConfigError(f"Adapter {adapter.key!r} could not provide a server target: {exc}") from exc
169
+ if not isinstance(target, str) or not target:
170
+ raise ConfigError(f"Adapter {adapter.key!r} returned an invalid server target.")
171
+ try:
172
+ if environment.is_production:
173
+ command = server.production_command(target, interface)
174
+ else:
175
+ command = server.development_command(target, interface)
176
+ except Exception as exc:
177
+ raise ConfigError(f"Web server {server.key!r} command failed: {exc}") from exc
178
+ command = _command_list(command, f"Web server {server.key!r} command")
179
+ if environment.is_production:
180
+ try:
181
+ release = adapter.release_commands(config)
182
+ except Exception as exc:
183
+ raise ConfigError(f"Adapter {adapter.key!r} release commands failed: {exc}") from exc
184
+ if not isinstance(release, list):
185
+ raise ConfigError(f"Adapter {adapter.key!r} release_commands() must return a list.")
186
+ steps = [shlex.join(_command_list(step, f"Adapter {adapter.key!r} release command")) for step in release]
187
+ if steps:
188
+ command = ["sh", "-c", " && ".join([*steps, "exec " + shlex.join(command)]).replace("$", "$$")]
189
+ return command
190
+
191
+
192
+ def app_interface(config: ShipConfig, root: Path, registry: Registry) -> Interface:
193
+ """ASGI or WSGI, as the selected adapter sees the app."""
194
+ adapter = registry.adapter(config)
195
+ try:
196
+ interface = adapter.interface(config, root)
197
+ except Exception as exc:
198
+ raise ConfigError(f"Adapter {adapter.key!r} could not tell the app's interface: {exc}") from exc
199
+ if interface not in ("asgi", "wsgi"):
200
+ raise ConfigError(f"Adapter {adapter.key!r} returned an invalid interface {interface!r}.")
201
+ return interface
202
+
203
+
204
+ def server_for(config: ShipConfig, root: Path, registry: Registry | None = None) -> WebServer:
205
+ """The server that will run the app: the configured one, or the recommended one."""
206
+ registry = registry or load_extensions(config)
207
+ return registry.server(config, app_interface(config, root, registry))
208
+
209
+
210
+ def adapter_problems(config: ShipConfig, root: Path, registry: Registry) -> list[str]:
211
+ try:
212
+ adapter = registry.adapter(config)
213
+ except ConfigError as exc:
214
+ return [str(exc)]
215
+ try:
216
+ problems = adapter.validate(config, root)
217
+ except Exception as exc:
218
+ return [f"Adapter {adapter.key!r} validation failed: {exc}"]
219
+ if not isinstance(problems, list) or any(not isinstance(problem, str) for problem in problems):
220
+ return [f"Adapter {adapter.key!r} returned invalid validation results."]
221
+ return problems
222
+
223
+
224
+ def build_compose(config: ShipConfig, project_root: Path, *, production: bool = False,
225
+ registry: Registry | None = None) -> dict[str, Any]:
226
+ environment = ShipEnvironment.PRODUCTION if production else ShipEnvironment.DEVELOPMENT
227
+ registry = registry or load_extensions(config)
228
+ problems = adapter_problems(config, project_root, registry)
229
+ if problems:
230
+ raise ConfigError(" ".join(problems))
231
+ selections = resolve_selections(config, registry)
232
+ server = server_for(config, project_root, registry)
233
+ name = project_name(config, project_root)
234
+ if production:
235
+ name += "-production"
236
+ app_name = config.app_service
237
+
238
+ app: dict[str, Any] = {
239
+ "build": {
240
+ "context": ".",
241
+ "dockerfile": "ship/Dockerfile",
242
+ "target": environment.value,
243
+ "args": {
244
+ "PYTHON_VERSION": config.python,
245
+ "SHIP_PYTHON_FLOOR": python_floor(),
246
+ "SHIP_SERVER_REQUIREMENT": server.requirement,
247
+ },
248
+ },
249
+ "command": _app_command(config, project_root, registry, environment),
250
+ "working_dir": "/app",
251
+ "env_file": [{"path": ".env.production" if production else ".env", "required": False}],
252
+ "environment": {},
253
+ "restart": "unless-stopped",
254
+ }
255
+ if production:
256
+ # Never build a release on a stale, locally cached base image.
257
+ app["build"]["pull"] = True
258
+ if config.publish_ports:
259
+ app["ports"] = ["${APP_PORT:-8000}:8000"]
260
+ else:
261
+ app["volumes"] = [PROJECT_MOUNT]
262
+ app["ports"] = ["127.0.0.1:${APP_PORT:-8000}:8000"]
263
+ # Lets a debugger in the container (debugpy) reach the IDE on the host.
264
+ app["extra_hosts"] = ["host.docker.internal:host-gateway"]
265
+ user = host_user(config)
266
+ if user:
267
+ app["user"] = user
268
+
269
+ hook = getattr(registry.adapter(config), "app_environment", None)
270
+ if hook is not None:
271
+ try:
272
+ adapter_environment = hook(config)
273
+ except Exception as exc:
274
+ raise ConfigError(f"Adapter {config.framework!r} app environment failed: {exc}") from exc
275
+ if not isinstance(adapter_environment, dict) or any(
276
+ not isinstance(key, str) or not isinstance(value, str) for key, value in adapter_environment.items()
277
+ ):
278
+ raise ConfigError(f"Adapter {config.framework!r} app_environment() must return a dict of strings.")
279
+ app["environment"].update(adapter_environment)
280
+
281
+ services: dict[str, Any] = {app_name: app}
282
+ compose: dict[str, Any] = {"name": name, "services": services}
283
+ app_processes: list[tuple[str, dict[str, Any]]] = []
284
+ volumes: dict[str, None] = {}
285
+
286
+ for selection in selections:
287
+ context = selection.context(config, project_root, environment)
288
+ service = selection.service
289
+ validate = getattr(service, "validate", None)
290
+ if validate is not None:
291
+ try:
292
+ issues = validate(context)
293
+ except Exception as exc:
294
+ raise ConfigError(f"Service {service.key!r} validation failed: {exc}") from exc
295
+ if issues:
296
+ raise ConfigError(" ".join(issues))
297
+ try:
298
+ fragment = service.compose_fragment(context)
299
+ variables = service.app_environment(context) if fragment else {}
300
+ except Exception as exc:
301
+ raise ConfigError(f"Service {service.key!r} failed to build its Compose fragment: {exc}") from exc
302
+ if not isinstance(fragment, dict) or not isinstance(variables, dict):
303
+ raise ConfigError(f"Service {service.key!r} must return a Compose mapping and an environment mapping.")
304
+ if not fragment:
305
+ continue # Absent in this environment, as development-only services are in production.
306
+ if selection.service_name not in fragment:
307
+ raise ConfigError(f"Service {service.key!r} did not define its Compose service {selection.service_name!r}.")
308
+ for service_name, model in deepcopy(fragment).items():
309
+ target_name = app_name if service_name == "app" else service_name
310
+ if not isinstance(service_name, str) or not SERVICE_NAME.fullmatch(service_name):
311
+ raise ConfigError(f"Invalid Compose service name {service_name!r} from {service.key!r}.")
312
+ if not isinstance(model, dict):
313
+ raise ConfigError(f"Compose service {service_name!r} must be an object.")
314
+ if APP_PROCESS in model:
315
+ # Runs from the app's image, with its environment; built once the app is complete.
316
+ if target_name in services or any(name == target_name for name, _ in app_processes):
317
+ raise ConfigError(f"Duplicate Compose service {target_name!r}.")
318
+ app_processes.append((target_name, model))
319
+ continue
320
+ if "ports" in model:
321
+ if not isinstance(model["ports"], list):
322
+ raise ConfigError(f"Compose service {service_name!r} ports must be a list.")
323
+ if environment.is_development:
324
+ model["ports"] = _local_ports(model["ports"], service_name)
325
+ elif not config.publish_ports:
326
+ model.pop("ports")
327
+ mounts = model.get("volumes", [])
328
+ if not isinstance(mounts, list):
329
+ raise ConfigError(f"Compose service {service_name!r} volumes must be a list.")
330
+ for mount in mounts:
331
+ if isinstance(mount, str):
332
+ source = mount.split(":", 1)[0]
333
+ if not source.startswith((".", "/", "~", "$")):
334
+ volumes[source] = None
335
+ if target_name == app_name:
336
+ try:
337
+ _merge(app, model, f"services.{app_name}")
338
+ except ConfigError as exc:
339
+ raise ConfigError(f"{exc} (set by the {service.key!r} service)") from exc
340
+ continue
341
+ if target_name in services:
342
+ raise ConfigError(f"Duplicate Compose service {target_name!r}.")
343
+ services[target_name] = {"restart": "unless-stopped"}
344
+ _merge(services[target_name], model, f"services.{target_name}")
345
+ condition = "service_healthy" if "healthcheck" in model else "service_started"
346
+ _merge(app, {"depends_on": {target_name: {"condition": condition}}}, f"services.{app_name}")
347
+ try:
348
+ _merge(app["environment"], variables, f"services.{app_name}.environment")
349
+ except ConfigError as exc:
350
+ raise ConfigError(f"{exc} (set by the {service.key!r} service)") from exc
351
+
352
+ if config.external_network:
353
+ _merge(app, {"networks": ["default", config.external_network]}, f"services.{app_name}")
354
+ compose["networks"] = {"default": {}, config.external_network: {"external": True}}
355
+
356
+ if environment.is_development and any(selection.group == "testing" for selection in selections):
357
+ networks = app.get("networks", ["default"])
358
+ if isinstance(networks, list):
359
+ networks = {network: {} for network in networks}
360
+ aliases = networks.setdefault("default", {}).setdefault("aliases", [])
361
+ if BROWSER_APP_HOST not in aliases:
362
+ aliases.append(BROWSER_APP_HOST)
363
+ app["networks"] = networks
364
+
365
+ processes = [(process, {APP_PROCESS: _escape_dollars(command_argv(command))}) for process, command in config.processes.items()]
366
+ processes += app_processes
367
+ if processes:
368
+ app["image"] = f"{name}-{app_name}:{'local' if production else 'development'}"
369
+ for process, settings in processes:
370
+ if process in services:
371
+ raise ConfigError(f"Process {process!r} conflicts with another Compose service.")
372
+ model = deepcopy(app)
373
+ for key in ("build", "ports", "healthcheck", "extra_hosts"):
374
+ model.pop(key, None)
375
+ if isinstance(model.get("networks"), dict):
376
+ model["networks"]["default"].pop("aliases", None)
377
+ extra = dict(settings)
378
+ model["command"] = _command_list(extra.pop(APP_PROCESS), f"Process {process!r} command")
379
+ model["stop_grace_period"] = PROCESS_STOP_GRACE
380
+ _merge(model, extra, f"services.{process}")
381
+ services[process] = model
382
+ # Every container that runs the app's code, for Mutagen sync and the deploy script.
383
+ compose["x-ship"] = {"app_services": [app_name, *(process for process, _ in processes)]}
384
+ if not production:
385
+ # Every container that sees the project at /app (the app, its processes, Node for Vite).
386
+ synced = [service_name for service_name, model in services.items() if PROJECT_MOUNT in model.get("volumes", [])]
387
+ compose["x-ship"]["sync_services"] = synced
388
+ if mutagen_enabled():
389
+ for service_name in synced:
390
+ mounts = [mount for mount in services[service_name]["volumes"] if mount != PROJECT_MOUNT]
391
+ if mounts:
392
+ services[service_name]["volumes"] = mounts
393
+ else:
394
+ del services[service_name]["volumes"]
395
+
396
+ if production:
397
+ for service_name, model in services.items():
398
+ for mount in model.get("volumes", []):
399
+ bind = (isinstance(mount, str) and mount.split(":", 1)[0].startswith((".", "/", "~"))) or (
400
+ isinstance(mount, dict) and mount.get("type") == "bind"
401
+ )
402
+ if bind:
403
+ raise ConfigError(f"Production service {service_name!r} cannot use a host bind mount.")
404
+ if "build" in model:
405
+ model["build"].setdefault("pull", True)
406
+ model.setdefault("image", f"{name}-{service_name}:local")
407
+ if volumes:
408
+ compose["volumes"] = volumes
409
+ return compose
410
+
411
+
412
+ def host_user(config: ShipConfig) -> str | None:
413
+ """The host UID:GID the development app runs as, or None where it doesn't apply."""
414
+ if not config.host_user or mutagen_enabled() or not sys.platform.startswith("linux"):
415
+ return None
416
+ getuid = getattr(os, "getuid", None)
417
+ getgid = getattr(os, "getgid", None)
418
+ if getuid is None or getgid is None or getuid() == 0:
419
+ return None
420
+ return f"{getuid()}:{getgid()}"
421
+
422
+
423
+ def compose_path(project_root: Path, *, production: bool = False) -> Path:
424
+ return project_root / "ship" / (PRODUCTION_FILE if production else DEVELOPMENT_FILE)
425
+
426
+
427
+ def render(model: dict[str, Any]) -> str:
428
+ # JSON is valid YAML, so the file needs no YAML library and Compose reads it unchanged.
429
+ header = f"# Generated by python-ship {__version__} from ship.json. Edits are overwritten.\n"
430
+ return header + json.dumps(model, indent=2) + "\n"
431
+
432
+
433
+ def write_compose(config: ShipConfig, project_root: Path, *, production: bool = False,
434
+ model: dict[str, Any] | None = None) -> Path:
435
+ model = build_compose(config, project_root, production=production) if model is None else model
436
+ destination = compose_path(project_root, production=production)
437
+ destination.parent.mkdir(exist_ok=True)
438
+ destination.write_text(render(model), encoding="utf-8")
439
+ return destination