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/__init__.py +3 -0
- python_ship/__main__.py +3 -0
- python_ship/adapters.py +270 -0
- python_ship/cli.py +588 -0
- python_ship/compose.py +439 -0
- python_ship/config.py +368 -0
- python_ship/contracts.py +234 -0
- python_ship/init.py +369 -0
- python_ship/mutagen.py +89 -0
- python_ship/plugins.py +149 -0
- python_ship/production.py +69 -0
- python_ship/py.typed +0 -0
- python_ship/release.py +175 -0
- python_ship/runtime.py +83 -0
- python_ship/security.py +69 -0
- python_ship/servers.py +72 -0
- python_ship/services.py +353 -0
- python_ship/storage.py +151 -0
- python_ship/stubs.py +149 -0
- python_ship/templates/Dockerfile +52 -0
- python_ship/templates/check-python-security-floor.py +49 -0
- python_ship/templates/garage/Dockerfile +7 -0
- python_ship/templates/garage/garage.toml +15 -0
- python_ship/uv.py +76 -0
- python_ship-0.1.0.dist-info/METADATA +936 -0
- python_ship-0.1.0.dist-info/RECORD +30 -0
- python_ship-0.1.0.dist-info/WHEEL +5 -0
- python_ship-0.1.0.dist-info/entry_points.txt +2 -0
- python_ship-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- python_ship-0.1.0.dist-info/top_level.txt +1 -0
python_ship/config.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""Project configuration stored in ship.json.
|
|
2
|
+
|
|
3
|
+
Field names follow PHP Ship's ship.json so a team using both reads one format:
|
|
4
|
+
``services``, ``additionalServices``, ``serviceNames``, ``externalNetwork``,
|
|
5
|
+
``publishPorts``, ``deployCommands``, ``processes``, ``siloImage``,
|
|
6
|
+
``hostUser``, ``name`` and ``extensions`` mean the same thing in both. The
|
|
7
|
+
Python-specific fields are ``framework``, ``app``, ``python``, ``server``,
|
|
8
|
+
``nodeAssets`` and ``djangoCollectstatic``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
import json
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
import re
|
|
17
|
+
import shlex
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from .security import DEFAULT_PYTHON, problem_with
|
|
21
|
+
|
|
22
|
+
# Alternative spellings accepted in ship.json, normalized on read. PHP Ship and Python Ship
|
|
23
|
+
# both accept "pgsql" and "postgres" for PostgreSQL, and both write "postgres".
|
|
24
|
+
SERVICE_ALIASES = {"pgsql": "postgres"}
|
|
25
|
+
SCHEMA_URL = "https://raw.githubusercontent.com/ship-ecosystem/python-ship/main/schema/ship.schema.json"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def canonical_service(key: str) -> str:
|
|
29
|
+
return SERVICE_ALIASES.get(key, key)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ConfigError(ValueError):
|
|
33
|
+
"""A project configuration is missing or invalid."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
SERVICE_NAME = re.compile(r"[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*")
|
|
37
|
+
INSTANCE_NAME = re.compile(r"[a-z][a-z0-9_]*")
|
|
38
|
+
NETWORK_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*")
|
|
39
|
+
SILO_IMAGES = ("standard", "distroless")
|
|
40
|
+
# Groups where a second, named instance is a coherent idea. A second app runtime,
|
|
41
|
+
# frontend toolchain or browser driver is not.
|
|
42
|
+
GROUPS_SUPPORTING_ADDITIONAL_INSTANCES = ("database", "cache", "storage", "search", "mail")
|
|
43
|
+
# Ship's own commands; a process or a framework console command can't take these names.
|
|
44
|
+
RESERVED_COMMANDS = frozenset({
|
|
45
|
+
"init", "up", "down", "exec", "shell", "logs", "db", "config:test", "build", "release",
|
|
46
|
+
"npm", "uv", "doctor",
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
FIELDS = (
|
|
50
|
+
"$schema", "framework", "app", "python", "server", "services", "additionalServices", "serviceNames",
|
|
51
|
+
"externalNetwork", "extensions", "name", "siloImage", "publishPorts", "hostUser",
|
|
52
|
+
"processes", "deployCommands", "nodeAssets", "djangoCollectstatic",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
Command = str | list[str]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def command_argv(command: Command) -> list[str]:
|
|
59
|
+
"""A process or deploy command as an argument list; a string runs through ``sh -c``."""
|
|
60
|
+
return ["sh", "-c", command] if isinstance(command, str) else list(command)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def command_text(command: Command) -> str:
|
|
64
|
+
return command if isinstance(command, str) else shlex.join(command)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class AdditionalService:
|
|
69
|
+
group: str
|
|
70
|
+
service: str
|
|
71
|
+
name: str
|
|
72
|
+
|
|
73
|
+
def as_json(self) -> dict[str, str]:
|
|
74
|
+
return {"group": self.group, "service": self.service, "name": self.name}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class ShipConfig:
|
|
79
|
+
framework: str = "generic"
|
|
80
|
+
app: str = "main:app"
|
|
81
|
+
python: str = DEFAULT_PYTHON
|
|
82
|
+
server: str | None = None
|
|
83
|
+
services: dict[str, str] = field(default_factory=dict)
|
|
84
|
+
additional_services: list[AdditionalService] = field(default_factory=list)
|
|
85
|
+
service_names: dict[str, str] = field(default_factory=dict)
|
|
86
|
+
external_network: str | None = None
|
|
87
|
+
extensions: list[str] = field(default_factory=list)
|
|
88
|
+
name: str | None = None
|
|
89
|
+
silo_image: str = "standard"
|
|
90
|
+
publish_ports: bool = False
|
|
91
|
+
host_user: bool = True
|
|
92
|
+
processes: dict[str, Command] = field(default_factory=dict)
|
|
93
|
+
deploy_commands: list[Command] = field(default_factory=list)
|
|
94
|
+
node_assets: bool = False
|
|
95
|
+
django_collectstatic: bool = False
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def app_service(self) -> str:
|
|
99
|
+
"""The app's Compose service name, after any ``serviceNames`` rename."""
|
|
100
|
+
return self.service_names.get("app", "app")
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def read(cls, project_root: Path) -> ShipConfig:
|
|
104
|
+
config, problems = cls.inspect(project_root)
|
|
105
|
+
if problems:
|
|
106
|
+
raise ConfigError(" ".join(problems))
|
|
107
|
+
assert config is not None
|
|
108
|
+
return config
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def inspect(cls, project_root: Path) -> tuple[ShipConfig | None, list[str]]:
|
|
112
|
+
"""Read ship.json, collecting every independent problem instead of stopping at the first."""
|
|
113
|
+
data, problems = _load(project_root / "ship.json")
|
|
114
|
+
if data is None:
|
|
115
|
+
return None, problems
|
|
116
|
+
config, problems = cls.from_data(data)
|
|
117
|
+
return config, problems
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def lenient(cls, project_root: Path) -> ShipConfig | None:
|
|
121
|
+
"""The readable fields of an existing ship.json, so one bad field doesn't discard the rest.
|
|
122
|
+
|
|
123
|
+
``ship init`` uses this to carry over everything it doesn't prompt for.
|
|
124
|
+
"""
|
|
125
|
+
data, _ = _load(project_root / "ship.json")
|
|
126
|
+
if data is None:
|
|
127
|
+
return None
|
|
128
|
+
values: dict[str, Any] = {}
|
|
129
|
+
for key in FIELDS:
|
|
130
|
+
if key not in data or key == "$schema":
|
|
131
|
+
continue
|
|
132
|
+
# djangoCollectstatic is only valid together with its framework.
|
|
133
|
+
probe = {"app": "main:app", "framework": "django"} if key == "djangoCollectstatic" else {"app": "main:app"}
|
|
134
|
+
config, problems = cls.from_data({**probe, key: data[key]})
|
|
135
|
+
if not problems and config is not None:
|
|
136
|
+
attribute = _ATTRIBUTES[key]
|
|
137
|
+
values[attribute] = getattr(config, attribute)
|
|
138
|
+
return cls(**values)
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def from_data(cls, data: dict[str, Any]) -> tuple[ShipConfig | None, list[str]]:
|
|
142
|
+
problems: list[str] = []
|
|
143
|
+
unknown = sorted(set(data) - set(FIELDS))
|
|
144
|
+
if unknown:
|
|
145
|
+
problems.append(f"ship.json has unknown fields: {', '.join(unknown)}.")
|
|
146
|
+
|
|
147
|
+
framework = data.get("framework", "generic")
|
|
148
|
+
if not isinstance(framework, str) or not SERVICE_NAME.fullmatch(framework):
|
|
149
|
+
problems.append("ship.json \"framework\" must be an adapter key such as \"django\".")
|
|
150
|
+
app = data.get("app")
|
|
151
|
+
if not isinstance(app, str) or not app:
|
|
152
|
+
problems.append("ship.json requires \"app\", an ASGI target such as \"main:app\".")
|
|
153
|
+
python = data.get("python", DEFAULT_PYTHON)
|
|
154
|
+
if not isinstance(python, str):
|
|
155
|
+
problems.append("ship.json \"python\" must be a string such as \"3.13\".")
|
|
156
|
+
else:
|
|
157
|
+
python_problem = problem_with(python)
|
|
158
|
+
if python_problem:
|
|
159
|
+
problems.append(f"ship.json \"python\": {python_problem}")
|
|
160
|
+
server = data.get("server")
|
|
161
|
+
if server is not None and (not isinstance(server, str) or not SERVICE_NAME.fullmatch(server)):
|
|
162
|
+
problems.append("ship.json \"server\" must be a web server key such as \"uvicorn\" or \"gunicorn\".")
|
|
163
|
+
|
|
164
|
+
services = data.get("services", {})
|
|
165
|
+
if not isinstance(services, dict) or any(
|
|
166
|
+
not isinstance(group, str) or not isinstance(key, str) or not key for group, key in services.items()
|
|
167
|
+
):
|
|
168
|
+
problems.append("ship.json \"services\" must map each group to one service key.")
|
|
169
|
+
services = {}
|
|
170
|
+
|
|
171
|
+
additional: list[AdditionalService] = []
|
|
172
|
+
raw_additional = data.get("additionalServices", [])
|
|
173
|
+
if not isinstance(raw_additional, list):
|
|
174
|
+
problems.append("ship.json \"additionalServices\" must be a list of {group, service, name} objects.")
|
|
175
|
+
else:
|
|
176
|
+
seen: set[str] = set()
|
|
177
|
+
for index, entry in enumerate(raw_additional):
|
|
178
|
+
where = f"ship.json \"additionalServices\"[{index}]"
|
|
179
|
+
if not isinstance(entry, dict):
|
|
180
|
+
problems.append(f"{where} must be an object with group, service and name.")
|
|
181
|
+
continue
|
|
182
|
+
extra = sorted(set(entry) - {"group", "service", "name"})
|
|
183
|
+
if extra:
|
|
184
|
+
problems.append(f"{where} has unknown fields: {', '.join(map(str, extra))}.")
|
|
185
|
+
group, service, name = entry.get("group"), entry.get("service"), entry.get("name")
|
|
186
|
+
if not isinstance(group, str) or not group or not isinstance(service, str) or not service:
|
|
187
|
+
problems.append(f"{where} requires a group and a service.")
|
|
188
|
+
continue
|
|
189
|
+
if group not in GROUPS_SUPPORTING_ADDITIONAL_INSTANCES:
|
|
190
|
+
problems.append(
|
|
191
|
+
f"{where}: the {group!r} group doesn't support additional instances; "
|
|
192
|
+
f"only {', '.join(GROUPS_SUPPORTING_ADDITIONAL_INSTANCES)} do."
|
|
193
|
+
)
|
|
194
|
+
if not isinstance(name, str) or not INSTANCE_NAME.fullmatch(name):
|
|
195
|
+
problems.append(
|
|
196
|
+
f"{where} name {name!r} must use lowercase letters, digits and underscores, "
|
|
197
|
+
"starting with a letter (e.g. \"analytics\")."
|
|
198
|
+
)
|
|
199
|
+
continue
|
|
200
|
+
if name in seen:
|
|
201
|
+
problems.append(f"ship.json \"additionalServices\" uses the name {name!r} twice.")
|
|
202
|
+
seen.add(name)
|
|
203
|
+
additional.append(AdditionalService(group, canonical_service(service), name))
|
|
204
|
+
|
|
205
|
+
service_names = data.get("serviceNames", {})
|
|
206
|
+
if not isinstance(service_names, dict) or any(
|
|
207
|
+
not isinstance(old, str) or not isinstance(new, str) or not SERVICE_NAME.fullmatch(new)
|
|
208
|
+
for old, new in service_names.items()
|
|
209
|
+
):
|
|
210
|
+
problems.append(
|
|
211
|
+
"ship.json \"serviceNames\" must map default Compose service names to new lowercase names."
|
|
212
|
+
)
|
|
213
|
+
service_names = {}
|
|
214
|
+
elif len(set(service_names.values())) != len(service_names):
|
|
215
|
+
problems.append("ship.json \"serviceNames\" renames two services to the same name.")
|
|
216
|
+
|
|
217
|
+
external_network = data.get("externalNetwork")
|
|
218
|
+
if external_network is not None and (
|
|
219
|
+
not isinstance(external_network, str) or not NETWORK_NAME.fullmatch(external_network)
|
|
220
|
+
):
|
|
221
|
+
problems.append("ship.json \"externalNetwork\" must be the name of an existing Docker network.")
|
|
222
|
+
|
|
223
|
+
extensions = data.get("extensions", [])
|
|
224
|
+
if not isinstance(extensions, list) or any(not isinstance(item, str) or not item for item in extensions):
|
|
225
|
+
problems.append("ship.json \"extensions\" must be a list of entry point names.")
|
|
226
|
+
extensions = []
|
|
227
|
+
elif len(extensions) != len(set(extensions)):
|
|
228
|
+
problems.append("ship.json \"extensions\" lists the same entry point twice.")
|
|
229
|
+
|
|
230
|
+
name = data.get("name")
|
|
231
|
+
if name is not None and (not isinstance(name, str) or not SERVICE_NAME.fullmatch(name)):
|
|
232
|
+
problems.append(
|
|
233
|
+
"ship.json \"name\" must start with a lowercase letter and use single - or _ "
|
|
234
|
+
"separators between lowercase letters and digits."
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
silo_image = data.get("siloImage", "standard")
|
|
238
|
+
if silo_image not in SILO_IMAGES:
|
|
239
|
+
problems.append("ship.json \"siloImage\" must be \"standard\" or \"distroless\".")
|
|
240
|
+
|
|
241
|
+
booleans = {}
|
|
242
|
+
for key in ("publishPorts", "hostUser", "nodeAssets", "djangoCollectstatic"):
|
|
243
|
+
value = data.get(key, key == "hostUser")
|
|
244
|
+
if not isinstance(value, bool):
|
|
245
|
+
problems.append(f"ship.json \"{key}\" must be true or false.")
|
|
246
|
+
booleans[key] = value
|
|
247
|
+
if booleans["djangoCollectstatic"] is True and framework != "django":
|
|
248
|
+
problems.append("ship.json \"djangoCollectstatic\" requires \"framework\": \"django\".")
|
|
249
|
+
|
|
250
|
+
processes = data.get("processes", {})
|
|
251
|
+
if not isinstance(processes, dict):
|
|
252
|
+
problems.append("ship.json \"processes\" must map process names to commands.")
|
|
253
|
+
processes = {}
|
|
254
|
+
else:
|
|
255
|
+
for process, command in processes.items():
|
|
256
|
+
if not isinstance(process, str) or not SERVICE_NAME.fullmatch(process):
|
|
257
|
+
problems.append(f"ship.json process name {process!r} must be a lowercase Compose service name.")
|
|
258
|
+
elif process == "app" or process in RESERVED_COMMANDS:
|
|
259
|
+
problems.append(f"ship.json process name {process!r} is reserved.")
|
|
260
|
+
if not _valid_command(command):
|
|
261
|
+
problems.append(
|
|
262
|
+
f"ship.json process {process!r} must be a shell command string or a nonempty argument list."
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
deploy_commands = data.get("deployCommands", [])
|
|
266
|
+
if not isinstance(deploy_commands, list) or any(not _valid_command(item) for item in deploy_commands):
|
|
267
|
+
problems.append(
|
|
268
|
+
"ship.json \"deployCommands\" must be a list of shell command strings or argument lists."
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
if problems:
|
|
272
|
+
return None, problems
|
|
273
|
+
return cls(
|
|
274
|
+
framework=framework,
|
|
275
|
+
app=str(app),
|
|
276
|
+
python=python,
|
|
277
|
+
server=server,
|
|
278
|
+
services={group: canonical_service(key) for group, key in services.items()},
|
|
279
|
+
additional_services=additional,
|
|
280
|
+
service_names={canonical_service(old): new for old, new in service_names.items()},
|
|
281
|
+
external_network=external_network,
|
|
282
|
+
extensions=list(extensions),
|
|
283
|
+
name=name,
|
|
284
|
+
silo_image=silo_image,
|
|
285
|
+
publish_ports=booleans["publishPorts"],
|
|
286
|
+
host_user=booleans["hostUser"],
|
|
287
|
+
processes=dict(processes),
|
|
288
|
+
deploy_commands=list(deploy_commands),
|
|
289
|
+
node_assets=booleans["nodeAssets"],
|
|
290
|
+
django_collectstatic=booleans["djangoCollectstatic"],
|
|
291
|
+
), []
|
|
292
|
+
|
|
293
|
+
def to_json(self) -> dict[str, Any]:
|
|
294
|
+
payload: dict[str, Any] = {
|
|
295
|
+
"$schema": SCHEMA_URL,
|
|
296
|
+
"framework": self.framework,
|
|
297
|
+
"app": self.app,
|
|
298
|
+
"python": self.python,
|
|
299
|
+
}
|
|
300
|
+
if self.server is not None:
|
|
301
|
+
payload["server"] = self.server
|
|
302
|
+
payload["services"] = dict(self.services)
|
|
303
|
+
if self.additional_services:
|
|
304
|
+
payload["additionalServices"] = [entry.as_json() for entry in self.additional_services]
|
|
305
|
+
if self.service_names:
|
|
306
|
+
payload["serviceNames"] = dict(self.service_names)
|
|
307
|
+
if self.external_network is not None:
|
|
308
|
+
payload["externalNetwork"] = self.external_network
|
|
309
|
+
payload["extensions"] = list(self.extensions)
|
|
310
|
+
if self.name is not None:
|
|
311
|
+
payload["name"] = self.name
|
|
312
|
+
if self.silo_image != "standard":
|
|
313
|
+
payload["siloImage"] = self.silo_image
|
|
314
|
+
if self.publish_ports:
|
|
315
|
+
payload["publishPorts"] = True
|
|
316
|
+
if not self.host_user:
|
|
317
|
+
payload["hostUser"] = False
|
|
318
|
+
if self.processes:
|
|
319
|
+
payload["processes"] = dict(self.processes)
|
|
320
|
+
if self.deploy_commands:
|
|
321
|
+
payload["deployCommands"] = list(self.deploy_commands)
|
|
322
|
+
if self.node_assets:
|
|
323
|
+
payload["nodeAssets"] = True
|
|
324
|
+
if self.django_collectstatic:
|
|
325
|
+
payload["djangoCollectstatic"] = True
|
|
326
|
+
return payload
|
|
327
|
+
|
|
328
|
+
def write(self, project_root: Path) -> None:
|
|
329
|
+
(project_root / "ship.json").write_text(json.dumps(self.to_json(), indent=4) + "\n", encoding="utf-8")
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
_ATTRIBUTES = {
|
|
333
|
+
"$schema": "", "framework": "framework", "app": "app", "python": "python", "server": "server",
|
|
334
|
+
"services": "services", "additionalServices": "additional_services",
|
|
335
|
+
"serviceNames": "service_names", "externalNetwork": "external_network",
|
|
336
|
+
"extensions": "extensions", "name": "name", "siloImage": "silo_image",
|
|
337
|
+
"publishPorts": "publish_ports", "hostUser": "host_user", "processes": "processes",
|
|
338
|
+
"deployCommands": "deploy_commands", "nodeAssets": "node_assets",
|
|
339
|
+
"djangoCollectstatic": "django_collectstatic",
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _valid_command(command: object) -> bool:
|
|
344
|
+
if isinstance(command, str):
|
|
345
|
+
return bool(command.strip())
|
|
346
|
+
return isinstance(command, list) and bool(command) and all(isinstance(part, str) and part for part in command)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _load(path: Path) -> tuple[dict[str, Any] | None, list[str]]:
|
|
350
|
+
def unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
351
|
+
result: dict[str, Any] = {}
|
|
352
|
+
for key, value in pairs:
|
|
353
|
+
if key in result:
|
|
354
|
+
raise ConfigError(f"ship.json has a duplicate key {key!r}.")
|
|
355
|
+
result[key] = value
|
|
356
|
+
return result
|
|
357
|
+
|
|
358
|
+
try:
|
|
359
|
+
data = json.loads(path.read_text(encoding="utf-8-sig"), object_pairs_hook=unique)
|
|
360
|
+
except FileNotFoundError:
|
|
361
|
+
return None, ["No ship.json found; run `ship init` first."]
|
|
362
|
+
except json.JSONDecodeError as exc:
|
|
363
|
+
return None, [f"ship.json is not valid JSON: {exc}"]
|
|
364
|
+
except ConfigError as exc:
|
|
365
|
+
return None, [str(exc)]
|
|
366
|
+
if not isinstance(data, dict):
|
|
367
|
+
return None, ["ship.json must contain a JSON object."]
|
|
368
|
+
return data, []
|
python_ship/contracts.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Public extension contracts.
|
|
2
|
+
|
|
3
|
+
Three kinds of extension plug into Ship, each registered under its own Python
|
|
4
|
+
entry point group and selected by name in ship.json's ``extensions`` list:
|
|
5
|
+
|
|
6
|
+
- ``python_ship.services``: a :class:`ServiceDefinition`, one optional piece of
|
|
7
|
+
infrastructure (a database, a cache, object storage, ...).
|
|
8
|
+
- ``python_ship.adapters``: a :class:`FrameworkAdapter`, which keeps
|
|
9
|
+
framework-specific knowledge (Django's ``manage.py``) out of the core.
|
|
10
|
+
- ``python_ship.servers``: a :class:`WebServer`, which serves an adapter's
|
|
11
|
+
ASGI or WSGI target (Uvicorn, Hypercorn, Gunicorn and Granian are built in).
|
|
12
|
+
|
|
13
|
+
These protocols are the stable public API; everything else in the package is
|
|
14
|
+
an implementation detail.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from enum import StrEnum
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from .config import ShipConfig
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# A fragment entry holding this key becomes a container of the app's own image: its build,
|
|
29
|
+
# environment, networks and (in development) code, running the given command.
|
|
30
|
+
APP_PROCESS = "x-ship-app-process"
|
|
31
|
+
|
|
32
|
+
Interface = Literal["asgi", "wsgi"]
|
|
33
|
+
"""The calling convention of an app: ASGI (async) or WSGI (sync)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ShipEnvironment(StrEnum):
|
|
37
|
+
"""Which Compose model is being generated."""
|
|
38
|
+
|
|
39
|
+
DEVELOPMENT = "development"
|
|
40
|
+
PRODUCTION = "production"
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def is_development(self) -> bool:
|
|
44
|
+
return self is ShipEnvironment.DEVELOPMENT
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def is_production(self) -> bool:
|
|
48
|
+
return self is ShipEnvironment.PRODUCTION
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class ServiceContext:
|
|
53
|
+
"""Everything a service needs to build its fragment for one selection.
|
|
54
|
+
|
|
55
|
+
``instance_name`` is ``None`` for the default selection in ship.json's
|
|
56
|
+
``services`` and the entry's name for an ``additionalServices`` entry.
|
|
57
|
+
``service_name`` is the final Compose service name, after any
|
|
58
|
+
``serviceNames`` rename, so hostnames a service injects into the app must
|
|
59
|
+
use it. ``resource_name`` stays stable across renames and is meant for
|
|
60
|
+
named volumes, so renaming a service never orphans its data.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
environment: ShipEnvironment
|
|
64
|
+
config: ShipConfig
|
|
65
|
+
project_root: Path
|
|
66
|
+
key: str
|
|
67
|
+
instance_name: str | None
|
|
68
|
+
service_name: str
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def production(self) -> bool:
|
|
72
|
+
return self.environment.is_production
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def env_prefix(self) -> str:
|
|
76
|
+
"""``""`` for the default instance, ``"ANALYTICS_"`` for one named analytics."""
|
|
77
|
+
return f"{self.instance_name.upper()}_" if self.instance_name else ""
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def resource_name(self) -> str:
|
|
81
|
+
return f"{self.key}-{self.instance_name}" if self.instance_name else self.key
|
|
82
|
+
|
|
83
|
+
def credential(self, name: str, development_default: str) -> str:
|
|
84
|
+
"""A Compose expression for a secret: a default in development, required in production."""
|
|
85
|
+
variable = self.env_prefix + name
|
|
86
|
+
if self.production:
|
|
87
|
+
return f"${{{variable}:?{variable} is required in .env.production}}"
|
|
88
|
+
return f"${{{variable}:-{development_default}}}"
|
|
89
|
+
|
|
90
|
+
def app_process(self, command: list[str], **settings: Any) -> dict[str, Any]:
|
|
91
|
+
"""A fragment entry that runs ``command`` in a container of the app's image.
|
|
92
|
+
|
|
93
|
+
It shares the app's build, environment, networks and dependencies (and, in
|
|
94
|
+
development, its bind mount), gets a 60s stop grace period, and publishes no
|
|
95
|
+
ports. Extra Compose ``settings`` are merged in. Write ``$$`` for a literal
|
|
96
|
+
``$``, as anywhere else in a fragment.
|
|
97
|
+
"""
|
|
98
|
+
return {APP_PROCESS: list(command), **settings}
|
|
99
|
+
|
|
100
|
+
def setting(self, name: str, default: str) -> str:
|
|
101
|
+
"""A Compose expression for a non-secret value with a default in every environment."""
|
|
102
|
+
variable = self.env_prefix + name
|
|
103
|
+
return f"${{{variable}:-{default}}}"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@runtime_checkable
|
|
107
|
+
class ServiceDefinition(Protocol):
|
|
108
|
+
"""One optional piece of the stack, selected per group in ship.json."""
|
|
109
|
+
|
|
110
|
+
key: str
|
|
111
|
+
"""Unique key used in ship.json, such as ``"postgres"``."""
|
|
112
|
+
|
|
113
|
+
label: str
|
|
114
|
+
"""Human-readable name shown by ``ship init``."""
|
|
115
|
+
|
|
116
|
+
group: str
|
|
117
|
+
"""The group this service belongs to (database, cache, storage, ...)."""
|
|
118
|
+
|
|
119
|
+
def compose_fragment(self, context: ServiceContext) -> dict[str, dict[str, Any]]:
|
|
120
|
+
"""Compose services this selection contributes, keyed by Compose service name.
|
|
121
|
+
|
|
122
|
+
The fragment must define ``context.service_name``. It may also extend
|
|
123
|
+
the ``app`` service; values are merged, never silently overwritten.
|
|
124
|
+
Return ``{}`` to leave the service out of that environment entirely, as
|
|
125
|
+
development-only services (Mailpit, browsers) do in production; the app
|
|
126
|
+
then receives none of its environment variables either.
|
|
127
|
+
"""
|
|
128
|
+
...
|
|
129
|
+
|
|
130
|
+
def app_environment(self, context: ServiceContext) -> dict[str, str]:
|
|
131
|
+
"""Environment variables injected into the app, such as ``DB_HOST``.
|
|
132
|
+
|
|
133
|
+
For a named instance, prefix every variable with ``context.env_prefix``.
|
|
134
|
+
"""
|
|
135
|
+
...
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@runtime_checkable
|
|
139
|
+
class ProvidesDatabaseShell(Protocol):
|
|
140
|
+
"""Optional: lets ``ship db`` open this database's interactive client."""
|
|
141
|
+
|
|
142
|
+
def database_shell(self, context: ServiceContext) -> list[str]:
|
|
143
|
+
"""The command run inside ``context.service_name`` by ``ship db``."""
|
|
144
|
+
...
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@runtime_checkable
|
|
148
|
+
class ValidatesConfiguration(Protocol):
|
|
149
|
+
"""Optional: report problems before Docker is invoked."""
|
|
150
|
+
|
|
151
|
+
def validate(self, context: ServiceContext) -> list[str]:
|
|
152
|
+
...
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@runtime_checkable
|
|
156
|
+
class FrameworkAdapter(Protocol):
|
|
157
|
+
"""Framework knowledge that the core package deliberately lacks."""
|
|
158
|
+
|
|
159
|
+
key: str
|
|
160
|
+
"""Unique key used as ship.json's ``framework``, such as ``"django"``."""
|
|
161
|
+
|
|
162
|
+
label: str
|
|
163
|
+
"""Human-readable name shown by ``ship init``."""
|
|
164
|
+
|
|
165
|
+
def detect(self, project_root: Path) -> bool:
|
|
166
|
+
"""Whether this adapter applies to the project, used to suggest a default in ``ship init``."""
|
|
167
|
+
...
|
|
168
|
+
|
|
169
|
+
def default_app(self, project_root: Path) -> str | None:
|
|
170
|
+
"""The ASGI target ``ship init`` suggests, such as ``"project.asgi:application"``."""
|
|
171
|
+
...
|
|
172
|
+
|
|
173
|
+
def validate(self, config: ShipConfig, project_root: Path) -> list[str]:
|
|
174
|
+
"""Problems with the project or config; an empty list when it is usable."""
|
|
175
|
+
...
|
|
176
|
+
|
|
177
|
+
def interface(self, config: ShipConfig, project_root: Path) -> Interface:
|
|
178
|
+
"""Whether the app is ``"asgi"`` or ``"wsgi"``; decides which servers can run it."""
|
|
179
|
+
...
|
|
180
|
+
|
|
181
|
+
def server_target(self, config: ShipConfig) -> str:
|
|
182
|
+
"""The ``module:callable`` target the selected server serves."""
|
|
183
|
+
...
|
|
184
|
+
|
|
185
|
+
def console_commands(self) -> dict[str, list[str]]:
|
|
186
|
+
"""Proxy commands this adapter adds, such as ``{"manage": ["python", "manage.py"]}``.
|
|
187
|
+
|
|
188
|
+
Each becomes ``ship <name> ARGS...``, run in the app container with the
|
|
189
|
+
arguments forwarded unchanged. Names must not clash with Ship's own commands.
|
|
190
|
+
"""
|
|
191
|
+
...
|
|
192
|
+
|
|
193
|
+
def release_commands(self, config: ShipConfig) -> list[list[str]]:
|
|
194
|
+
"""Commands run at every production container boot, before the server starts.
|
|
195
|
+
|
|
196
|
+
For checks and cache warming that need real environment values, such as
|
|
197
|
+
Django's ``check --deploy``. Never put migrations here: every container
|
|
198
|
+
would run them at once. Use ship.json's ``deployCommands`` for those.
|
|
199
|
+
"""
|
|
200
|
+
...
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@runtime_checkable
|
|
204
|
+
class ProvidesAppEnvironment(Protocol):
|
|
205
|
+
"""Optional adapter hook: variables the framework needs in every app container."""
|
|
206
|
+
|
|
207
|
+
def app_environment(self, config: ShipConfig) -> dict[str, str]:
|
|
208
|
+
"""Such as Flask's ``FLASK_APP``, so ``ship flask ...`` finds the app."""
|
|
209
|
+
...
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@runtime_checkable
|
|
213
|
+
class WebServer(Protocol):
|
|
214
|
+
"""A web server Ship installs in the app image and runs the target with."""
|
|
215
|
+
|
|
216
|
+
key: str
|
|
217
|
+
"""Unique key used as ship.json's ``server``, such as ``"uvicorn"``."""
|
|
218
|
+
|
|
219
|
+
label: str
|
|
220
|
+
"""Human-readable name shown by ``ship init``."""
|
|
221
|
+
|
|
222
|
+
requirement: str
|
|
223
|
+
"""One PEP 508 requirement installed into the image, such as ``"uvicorn==0.54.0"``."""
|
|
224
|
+
|
|
225
|
+
interfaces: tuple[Interface, ...]
|
|
226
|
+
"""The app interfaces it can serve: ``("asgi",)``, ``("wsgi",)`` or both."""
|
|
227
|
+
|
|
228
|
+
def development_command(self, target: str, interface: Interface) -> list[str]:
|
|
229
|
+
"""Serve ``target`` on 0.0.0.0:8000 with reload."""
|
|
230
|
+
...
|
|
231
|
+
|
|
232
|
+
def production_command(self, target: str, interface: Interface) -> list[str]:
|
|
233
|
+
"""Serve ``target`` on 0.0.0.0:8000 for production."""
|
|
234
|
+
...
|