shared-pre-deployment 0.1.0__tar.gz
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.
- shared_pre_deployment-0.1.0/.gitignore +47 -0
- shared_pre_deployment-0.1.0/PKG-INFO +83 -0
- shared_pre_deployment-0.1.0/README.md +53 -0
- shared_pre_deployment-0.1.0/pyproject.toml +54 -0
- shared_pre_deployment-0.1.0/release.py +169 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/__init__.py +35 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/checks/__init__.py +66 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/checks/callback.py +76 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/checks/command.py +106 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/checks/env.py +64 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/checks/postgres.py +97 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/checks/redis.py +95 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/cli.py +182 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/logging.py +67 -0
- shared_pre_deployment-0.1.0/src/shared_pre_deployment/runner.py +155 -0
- shared_pre_deployment-0.1.0/tests/conftest.py +49 -0
- shared_pre_deployment-0.1.0/tests/test_checks.py +237 -0
- shared_pre_deployment-0.1.0/tests/test_cli.py +68 -0
- shared_pre_deployment-0.1.0/tests/test_logging.py +58 -0
- shared_pre_deployment-0.1.0/tests/test_runner.py +96 -0
- shared_pre_deployment-0.1.0/uv.lock +583 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Environment variables
|
|
2
|
+
.env
|
|
3
|
+
.env.*
|
|
4
|
+
*.env
|
|
5
|
+
!.env.example
|
|
6
|
+
|
|
7
|
+
# Databases
|
|
8
|
+
*.db
|
|
9
|
+
*.sqlite
|
|
10
|
+
*.sqlite3
|
|
11
|
+
|
|
12
|
+
# Python bytecode & cache
|
|
13
|
+
__pycache__/
|
|
14
|
+
*.py[cod]
|
|
15
|
+
*$py.class
|
|
16
|
+
*.so
|
|
17
|
+
.Python
|
|
18
|
+
|
|
19
|
+
# Virtual environments
|
|
20
|
+
.venv/
|
|
21
|
+
venv/
|
|
22
|
+
ENV/
|
|
23
|
+
env/
|
|
24
|
+
|
|
25
|
+
# Testing & Linting
|
|
26
|
+
.pytest_cache/
|
|
27
|
+
.ruff_cache/
|
|
28
|
+
.coverage
|
|
29
|
+
htmlcov/
|
|
30
|
+
|
|
31
|
+
# Node / Frontend
|
|
32
|
+
node_modules/
|
|
33
|
+
.next/
|
|
34
|
+
out/
|
|
35
|
+
build/
|
|
36
|
+
dist/
|
|
37
|
+
.npm
|
|
38
|
+
npm-debug.log*
|
|
39
|
+
yarn-debug.log*
|
|
40
|
+
yarn-error.log*
|
|
41
|
+
pnpm-debug.log*
|
|
42
|
+
|
|
43
|
+
# Operating System & IDE
|
|
44
|
+
.DS_Store
|
|
45
|
+
Thumbs.db
|
|
46
|
+
.vscode/
|
|
47
|
+
.idea/
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: shared-pre-deployment
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modular pre-deployment verification gate and orchestration runner for services.
|
|
5
|
+
Author-email: Film Review Platform Engineering <dev@example.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: deployment,devops,gate,healthcheck,pre-deployment,validation
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
18
|
+
Classifier: Topic :: Software Development :: Testing
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: asyncpg>=0.28.0
|
|
21
|
+
Requires-Dist: click>=8.1.0
|
|
22
|
+
Requires-Dist: greenlet>=3.0.0
|
|
23
|
+
Requires-Dist: redis>=4.5.0
|
|
24
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.0.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest-mock>=3.14.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# shared-pre-deployment
|
|
32
|
+
|
|
33
|
+
A modular, extensible pre-deployment verification gate and orchestration runner for modern Python applications and microservices.
|
|
34
|
+
|
|
35
|
+
## Features
|
|
36
|
+
|
|
37
|
+
- **Environment Variable Validation**: Verify all required environment variables are set and non-empty.
|
|
38
|
+
- **PostgreSQL Connectivity Check**: Verify database reachability via `SELECT 1` with configurable timeouts and automatic credential masking in logs.
|
|
39
|
+
- **Redis Connectivity Check**: Verify Redis reachability via `PING` with configurable timeouts and target inspection.
|
|
40
|
+
- **Command / Subprocess Gate**: Run test suites (e.g. `pytest`), linters, or arbitrary validation scripts.
|
|
41
|
+
- **Custom Callbacks**: Inject custom synchronous or asynchronous validation functions.
|
|
42
|
+
- **Orchestration & CLI**: Easy-to-use Python API and command-line interface (`shared-pre-deployment` / `pre-deployment-runner`) with clear `[PASS]`/`[FAIL]` logging and strict non-zero exit codes.
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install shared-pre-deployment
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Quick Start (Python API)
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import asyncio
|
|
54
|
+
from shared_pre_deployment import PreDeploymentRunner, EnvCheck, PostgresCheck, RedisCheck, CommandCheck
|
|
55
|
+
|
|
56
|
+
async def main():
|
|
57
|
+
runner = PreDeploymentRunner(title="My Service - Pre-Deployment Gate")
|
|
58
|
+
runner.add_check(EnvCheck(required_vars=["DATABASE_URL", "REDIS_URL", "API_KEY"]))
|
|
59
|
+
runner.add_check(PostgresCheck(timeout_seconds=5.0))
|
|
60
|
+
runner.add_check(RedisCheck(timeout_seconds=5.0))
|
|
61
|
+
runner.add_check(CommandCheck("pytest tests/unit", name="Unit Tests"))
|
|
62
|
+
|
|
63
|
+
success = await runner.run()
|
|
64
|
+
if not success:
|
|
65
|
+
raise SystemExit(1)
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
asyncio.run(main())
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Quick Start (CLI)
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pre-deployment-runner \
|
|
75
|
+
--require-env "DATABASE_URL,REDIS_URL,API_KEY" \
|
|
76
|
+
--check-postgres \
|
|
77
|
+
--check-redis \
|
|
78
|
+
--command "pytest -v"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# shared-pre-deployment
|
|
2
|
+
|
|
3
|
+
A modular, extensible pre-deployment verification gate and orchestration runner for modern Python applications and microservices.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Environment Variable Validation**: Verify all required environment variables are set and non-empty.
|
|
8
|
+
- **PostgreSQL Connectivity Check**: Verify database reachability via `SELECT 1` with configurable timeouts and automatic credential masking in logs.
|
|
9
|
+
- **Redis Connectivity Check**: Verify Redis reachability via `PING` with configurable timeouts and target inspection.
|
|
10
|
+
- **Command / Subprocess Gate**: Run test suites (e.g. `pytest`), linters, or arbitrary validation scripts.
|
|
11
|
+
- **Custom Callbacks**: Inject custom synchronous or asynchronous validation functions.
|
|
12
|
+
- **Orchestration & CLI**: Easy-to-use Python API and command-line interface (`shared-pre-deployment` / `pre-deployment-runner`) with clear `[PASS]`/`[FAIL]` logging and strict non-zero exit codes.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install shared-pre-deployment
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick Start (Python API)
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import asyncio
|
|
24
|
+
from shared_pre_deployment import PreDeploymentRunner, EnvCheck, PostgresCheck, RedisCheck, CommandCheck
|
|
25
|
+
|
|
26
|
+
async def main():
|
|
27
|
+
runner = PreDeploymentRunner(title="My Service - Pre-Deployment Gate")
|
|
28
|
+
runner.add_check(EnvCheck(required_vars=["DATABASE_URL", "REDIS_URL", "API_KEY"]))
|
|
29
|
+
runner.add_check(PostgresCheck(timeout_seconds=5.0))
|
|
30
|
+
runner.add_check(RedisCheck(timeout_seconds=5.0))
|
|
31
|
+
runner.add_check(CommandCheck("pytest tests/unit", name="Unit Tests"))
|
|
32
|
+
|
|
33
|
+
success = await runner.run()
|
|
34
|
+
if not success:
|
|
35
|
+
raise SystemExit(1)
|
|
36
|
+
|
|
37
|
+
if __name__ == "__main__":
|
|
38
|
+
asyncio.run(main())
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick Start (CLI)
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pre-deployment-runner \
|
|
45
|
+
--require-env "DATABASE_URL,REDIS_URL,API_KEY" \
|
|
46
|
+
--check-postgres \
|
|
47
|
+
--check-redis \
|
|
48
|
+
--command "pytest -v"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## License
|
|
52
|
+
|
|
53
|
+
MIT
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "shared-pre-deployment"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A modular pre-deployment verification gate and orchestration runner for services."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "Film Review Platform Engineering", email = "dev@example.com" },
|
|
13
|
+
]
|
|
14
|
+
keywords = ["deployment", "pre-deployment", "validation", "gate", "healthcheck", "devops"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
26
|
+
"Topic :: Software Development :: Testing",
|
|
27
|
+
]
|
|
28
|
+
requires-python = ">=3.10"
|
|
29
|
+
dependencies = [
|
|
30
|
+
"click>=8.1.0",
|
|
31
|
+
"sqlalchemy[asyncio]>=2.0.0",
|
|
32
|
+
"greenlet>=3.0.0",
|
|
33
|
+
"asyncpg>=0.28.0",
|
|
34
|
+
"redis>=4.5.0",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[project.scripts]
|
|
38
|
+
shared-pre-deployment = "shared_pre_deployment.cli:main"
|
|
39
|
+
pre-deployment-runner = "shared_pre_deployment.cli:main"
|
|
40
|
+
|
|
41
|
+
[project.optional-dependencies]
|
|
42
|
+
dev = [
|
|
43
|
+
"pytest>=8.0.0",
|
|
44
|
+
"pytest-asyncio>=0.24.0",
|
|
45
|
+
"pytest-mock>=3.14.0",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/shared_pre_deployment"]
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
testpaths = ["tests"]
|
|
53
|
+
asyncio_mode = "auto"
|
|
54
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Release gate workflow script for shared-pre-deployment.
|
|
3
|
+
Enforces strict test-before-build and test-before-publish ordering.
|
|
4
|
+
|
|
5
|
+
Execution Steps:
|
|
6
|
+
1. Run pytest test suite. Stop immediately on test failure.
|
|
7
|
+
2. Clean old distribution artifacts in dist/.
|
|
8
|
+
3. Build wheel (.whl) and source distribution (.tar.gz) using uv build.
|
|
9
|
+
4. Inspect and verify generated distribution artifacts.
|
|
10
|
+
5. Publish to PyPI (if --publish is passed) using uv publish.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tarfile
|
|
21
|
+
import zipfile
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def log_step(step_num: int, title: str) -> None:
|
|
28
|
+
print(f"\n{'=' * 65}")
|
|
29
|
+
print(f" [RELEASE GATE STEP {step_num}] {title}")
|
|
30
|
+
print(f"{'=' * 65}\n")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def run_tests() -> bool:
|
|
34
|
+
"""Step 1: Execute package test suite. Fails fast if any test fails."""
|
|
35
|
+
log_step(1, "Running package test suite (pytest)")
|
|
36
|
+
cmd = ["uv", "run", "pytest", "-v"]
|
|
37
|
+
print(f"Executing: {' '.join(cmd)}")
|
|
38
|
+
res = subprocess.run(cmd, cwd=PACKAGE_DIR)
|
|
39
|
+
if res.returncode != 0:
|
|
40
|
+
print(
|
|
41
|
+
f"\n[RELEASE GATE BLOCKED] Tests failed with exit code {res.returncode}. "
|
|
42
|
+
"Build and publish aborted.",
|
|
43
|
+
file=sys.stderr,
|
|
44
|
+
)
|
|
45
|
+
return False
|
|
46
|
+
print("\n[RELEASE GATE PASS] All tests passed.")
|
|
47
|
+
return True
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_artifacts() -> bool:
|
|
51
|
+
"""Step 2 & 3: Clean dist/ and build wheel & sdist."""
|
|
52
|
+
log_step(2, "Building wheel and source distributions (uv build)")
|
|
53
|
+
dist_dir = PACKAGE_DIR / "dist"
|
|
54
|
+
if dist_dir.exists():
|
|
55
|
+
shutil.rmtree(dist_dir)
|
|
56
|
+
|
|
57
|
+
cmd = ["uv", "build"]
|
|
58
|
+
print(f"Executing: {' '.join(cmd)}")
|
|
59
|
+
res = subprocess.run(cmd, cwd=PACKAGE_DIR)
|
|
60
|
+
if res.returncode != 0:
|
|
61
|
+
print(f"\n[RELEASE GATE BLOCKED] Build failed with exit code {res.returncode}.", file=sys.stderr)
|
|
62
|
+
return False
|
|
63
|
+
print("\n[RELEASE GATE PASS] Build completed successfully.")
|
|
64
|
+
return True
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def verify_artifacts() -> bool:
|
|
68
|
+
"""Step 4: Inspect artifacts in dist/ to verify wheel and sdist integrity."""
|
|
69
|
+
log_step(3, "Inspecting and verifying built distribution artifacts")
|
|
70
|
+
dist_dir = PACKAGE_DIR / "dist"
|
|
71
|
+
if not dist_dir.exists():
|
|
72
|
+
print("[FAIL] dist/ directory not found.", file=sys.stderr)
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
wheels = list(dist_dir.glob("*.whl"))
|
|
76
|
+
sdists = list(dist_dir.glob("*.tar.gz"))
|
|
77
|
+
|
|
78
|
+
if not wheels:
|
|
79
|
+
print("[FAIL] No wheel (.whl) artifact found in dist/.", file=sys.stderr)
|
|
80
|
+
return False
|
|
81
|
+
if not sdists:
|
|
82
|
+
print("[FAIL] No source distribution (.tar.gz) artifact found in dist/.", file=sys.stderr)
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
whl = wheels[0]
|
|
86
|
+
sdist = sdists[0]
|
|
87
|
+
|
|
88
|
+
print(f"[FOUND] Wheel: {whl.name} ({whl.stat().st_size} bytes)")
|
|
89
|
+
print(f"[FOUND] Source Distribution: {sdist.name} ({sdist.stat().st_size} bytes)")
|
|
90
|
+
|
|
91
|
+
# Verify wheel contents
|
|
92
|
+
with zipfile.ZipFile(whl, "r") as z:
|
|
93
|
+
names = z.namelist()
|
|
94
|
+
required_whl_files = [
|
|
95
|
+
"shared_pre_deployment/__init__.py",
|
|
96
|
+
"shared_pre_deployment/runner.py",
|
|
97
|
+
"shared_pre_deployment/cli.py",
|
|
98
|
+
"shared_pre_deployment/checks/env.py",
|
|
99
|
+
"shared_pre_deployment/checks/postgres.py",
|
|
100
|
+
"shared_pre_deployment/checks/redis.py",
|
|
101
|
+
]
|
|
102
|
+
for req in required_whl_files:
|
|
103
|
+
if not any(req in n for n in names):
|
|
104
|
+
print(f"[FAIL] Missing {req} in wheel archive.", file=sys.stderr)
|
|
105
|
+
return False
|
|
106
|
+
print(f"[PASS] Wheel archive verified ({len(names)} entries).")
|
|
107
|
+
|
|
108
|
+
# Verify sdist contents
|
|
109
|
+
with tarfile.open(sdist, "r:gz") as t:
|
|
110
|
+
sdist_names = t.getnames()
|
|
111
|
+
if not any("pyproject.toml" in n for n in sdist_names):
|
|
112
|
+
print("[FAIL] Missing pyproject.toml in source distribution archive.", file=sys.stderr)
|
|
113
|
+
return False
|
|
114
|
+
print(f"[PASS] Source distribution archive verified ({len(sdist_names)} entries).")
|
|
115
|
+
|
|
116
|
+
return True
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def publish_artifacts() -> bool:
|
|
120
|
+
"""Step 5: Publish distribution artifacts to PyPI."""
|
|
121
|
+
log_step(4, "Publishing artifacts to PyPI (uv publish)")
|
|
122
|
+
token = os.environ.get("UV_PUBLISH_TOKEN")
|
|
123
|
+
if not token:
|
|
124
|
+
print(
|
|
125
|
+
"[ERROR] UV_PUBLISH_TOKEN environment variable is not set. Cannot publish.",
|
|
126
|
+
file=sys.stderr,
|
|
127
|
+
)
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
cmd = ["uv", "publish"]
|
|
131
|
+
print("Executing: uv publish [token masked]")
|
|
132
|
+
res = subprocess.run(cmd, cwd=PACKAGE_DIR)
|
|
133
|
+
if res.returncode != 0:
|
|
134
|
+
print(f"\n[FAIL] uv publish failed with exit code {res.returncode}.", file=sys.stderr)
|
|
135
|
+
return False
|
|
136
|
+
print("\n[SUCCESS] Successfully published to PyPI!")
|
|
137
|
+
return True
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def main() -> None:
|
|
141
|
+
parser = argparse.ArgumentParser(description="Release gate workflow for shared-pre-deployment.")
|
|
142
|
+
parser.add_argument("--publish", action="store_true", help="Publish to PyPI after successful test and build.")
|
|
143
|
+
args = parser.parse_args()
|
|
144
|
+
|
|
145
|
+
# 1. Test Gate
|
|
146
|
+
if not run_tests():
|
|
147
|
+
sys.exit(1)
|
|
148
|
+
|
|
149
|
+
# 2. Build Gate
|
|
150
|
+
if not build_artifacts():
|
|
151
|
+
sys.exit(1)
|
|
152
|
+
|
|
153
|
+
# 3. Verification Gate
|
|
154
|
+
if not verify_artifacts():
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
|
|
157
|
+
# 4. Optional Publish Gate
|
|
158
|
+
if args.publish:
|
|
159
|
+
if not publish_artifacts():
|
|
160
|
+
sys.exit(1)
|
|
161
|
+
else:
|
|
162
|
+
print(
|
|
163
|
+
"\n[GATE PASS] Build and verification complete. "
|
|
164
|
+
"Artifacts are verified and ready for publication (pass --publish to upload)."
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
if __name__ == "__main__":
|
|
169
|
+
main()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""
|
|
2
|
+
shared-pre-deployment: A modular pre-deployment verification gate and orchestration runner.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from shared_pre_deployment.checks import (
|
|
8
|
+
BaseCheck,
|
|
9
|
+
CheckResult,
|
|
10
|
+
CheckStatus,
|
|
11
|
+
)
|
|
12
|
+
from shared_pre_deployment.checks.callback import CallbackCheck
|
|
13
|
+
from shared_pre_deployment.checks.command import CommandCheck
|
|
14
|
+
from shared_pre_deployment.checks.env import EnvCheck
|
|
15
|
+
from shared_pre_deployment.checks.postgres import PostgresCheck
|
|
16
|
+
from shared_pre_deployment.checks.redis import RedisCheck
|
|
17
|
+
from shared_pre_deployment.logging import Logger, mask_url_password
|
|
18
|
+
from shared_pre_deployment.runner import PreDeploymentRunner
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"__version__",
|
|
24
|
+
"BaseCheck",
|
|
25
|
+
"CheckResult",
|
|
26
|
+
"CheckStatus",
|
|
27
|
+
"CallbackCheck",
|
|
28
|
+
"CommandCheck",
|
|
29
|
+
"EnvCheck",
|
|
30
|
+
"PostgresCheck",
|
|
31
|
+
"RedisCheck",
|
|
32
|
+
"Logger",
|
|
33
|
+
"mask_url_password",
|
|
34
|
+
"PreDeploymentRunner",
|
|
35
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base interfaces and data structures for pre-deployment checks.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import time
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any, Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CheckStatus(str, Enum):
|
|
15
|
+
"""Execution status for a gate check."""
|
|
16
|
+
PASSED = "PASSED"
|
|
17
|
+
FAILED = "FAILED"
|
|
18
|
+
SKIPPED = "SKIPPED"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class CheckResult:
|
|
23
|
+
"""Result data structure returned by a pre-deployment check."""
|
|
24
|
+
name: str
|
|
25
|
+
status: CheckStatus
|
|
26
|
+
message: str
|
|
27
|
+
details: dict[str, Any] = field(default_factory=dict)
|
|
28
|
+
execution_time: float = 0.0
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def passed(self) -> bool:
|
|
32
|
+
"""Convenience property indicating whether check succeeded."""
|
|
33
|
+
return self.status == CheckStatus.PASSED
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class BaseCheck(ABC):
|
|
37
|
+
"""Abstract base class for all pre-deployment validation checks."""
|
|
38
|
+
|
|
39
|
+
name: str
|
|
40
|
+
|
|
41
|
+
def __init__(self, name: Optional[str] = None) -> None:
|
|
42
|
+
if name:
|
|
43
|
+
self.name = name
|
|
44
|
+
|
|
45
|
+
@abstractmethod
|
|
46
|
+
async def execute(self) -> CheckResult:
|
|
47
|
+
"""
|
|
48
|
+
Execute check logic asynchronously.
|
|
49
|
+
Must return a CheckResult without raising unhandled exceptions.
|
|
50
|
+
"""
|
|
51
|
+
...
|
|
52
|
+
|
|
53
|
+
async def run(self) -> CheckResult:
|
|
54
|
+
"""Run the check with execution timing and guard against unhandled exceptions."""
|
|
55
|
+
start_time = time.perf_counter()
|
|
56
|
+
try:
|
|
57
|
+
result = await self.execute()
|
|
58
|
+
except Exception as exc:
|
|
59
|
+
result = CheckResult(
|
|
60
|
+
name=self.name,
|
|
61
|
+
status=CheckStatus.FAILED,
|
|
62
|
+
message=f"Unhandled exception during check execution: {exc}",
|
|
63
|
+
details={"exception": str(exc)},
|
|
64
|
+
)
|
|
65
|
+
result.execution_time = round(time.perf_counter() - start_time, 4)
|
|
66
|
+
return result
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom callback validation check.
|
|
3
|
+
Allows applications to plug arbitrary sync or async Python validation functions into the runner.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import inspect
|
|
10
|
+
from typing import Any, Awaitable, Callable, Optional, Union
|
|
11
|
+
|
|
12
|
+
from shared_pre_deployment.checks import BaseCheck, CheckResult, CheckStatus
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CallbackCheck(BaseCheck):
|
|
16
|
+
"""
|
|
17
|
+
Validates a condition using a custom Python callable (function or coroutine).
|
|
18
|
+
If the function returns False or raises an exception, the check is considered FAILED.
|
|
19
|
+
If the function returns True, a CheckResult, or None without raising, it is PASSED.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
func: Callable[[], Union[bool, CheckResult, None, Awaitable[Union[bool, CheckResult, None]]]],
|
|
25
|
+
name: str = "Custom Validation Callback",
|
|
26
|
+
timeout_seconds: Optional[float] = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(name=name)
|
|
29
|
+
self.func = func
|
|
30
|
+
self.timeout_seconds = timeout_seconds
|
|
31
|
+
|
|
32
|
+
async def execute(self) -> CheckResult:
|
|
33
|
+
try:
|
|
34
|
+
if inspect.iscoroutinefunction(self.func):
|
|
35
|
+
if self.timeout_seconds:
|
|
36
|
+
async with asyncio.timeout(self.timeout_seconds):
|
|
37
|
+
res = await self.func()
|
|
38
|
+
else:
|
|
39
|
+
res = await self.func()
|
|
40
|
+
else:
|
|
41
|
+
loop = asyncio.get_running_loop()
|
|
42
|
+
if self.timeout_seconds:
|
|
43
|
+
async with asyncio.timeout(self.timeout_seconds):
|
|
44
|
+
res = await loop.run_in_executor(None, self.func)
|
|
45
|
+
else:
|
|
46
|
+
res = await loop.run_in_executor(None, self.func)
|
|
47
|
+
|
|
48
|
+
if isinstance(res, CheckResult):
|
|
49
|
+
return res
|
|
50
|
+
|
|
51
|
+
if res is False:
|
|
52
|
+
return CheckResult(
|
|
53
|
+
name=self.name,
|
|
54
|
+
status=CheckStatus.FAILED,
|
|
55
|
+
message=f"Callback '{self.name}' returned False.",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
return CheckResult(
|
|
59
|
+
name=self.name,
|
|
60
|
+
status=CheckStatus.PASSED,
|
|
61
|
+
message=f"Callback '{self.name}' completed successfully.",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
except TimeoutError:
|
|
65
|
+
return CheckResult(
|
|
66
|
+
name=self.name,
|
|
67
|
+
status=CheckStatus.FAILED,
|
|
68
|
+
message=f"Callback '{self.name}' timed out after {self.timeout_seconds}s.",
|
|
69
|
+
)
|
|
70
|
+
except Exception as exc:
|
|
71
|
+
return CheckResult(
|
|
72
|
+
name=self.name,
|
|
73
|
+
status=CheckStatus.FAILED,
|
|
74
|
+
message=f"Callback '{self.name}' raised an error: {exc}",
|
|
75
|
+
details={"error": str(exc)},
|
|
76
|
+
)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command / subprocess validation check.
|
|
3
|
+
Executes an arbitrary shell or CLI command (e.g. test runner, linter) as a pre-deployment gate.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
import shlex
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from typing import Mapping, Optional, Sequence, Union
|
|
14
|
+
|
|
15
|
+
from shared_pre_deployment.checks import BaseCheck, CheckResult, CheckStatus
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CommandCheck(BaseCheck):
|
|
19
|
+
"""
|
|
20
|
+
Executes a shell command or executable array.
|
|
21
|
+
Validates that the command exits with code 0 within an optional timeout.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
name = "Command Execution Gate"
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
command: Union[str, Sequence[str]],
|
|
29
|
+
name: Optional[str] = None,
|
|
30
|
+
cwd: Optional[str] = None,
|
|
31
|
+
env: Optional[Mapping[str, str]] = None,
|
|
32
|
+
timeout_seconds: Optional[float] = None,
|
|
33
|
+
capture_output: bool = False,
|
|
34
|
+
) -> None:
|
|
35
|
+
cmd_display = command if isinstance(command, str) else " ".join(command)
|
|
36
|
+
super().__init__(name=name or f"Command ({cmd_display})")
|
|
37
|
+
self.command = command
|
|
38
|
+
self.cwd = cwd
|
|
39
|
+
self.env = env
|
|
40
|
+
self.timeout_seconds = timeout_seconds
|
|
41
|
+
self.capture_output = capture_output
|
|
42
|
+
|
|
43
|
+
async def execute(self) -> CheckResult:
|
|
44
|
+
cmd_str = self.command if isinstance(self.command, str) else " ".join(self.command)
|
|
45
|
+
run_env = dict(os.environ)
|
|
46
|
+
if self.env:
|
|
47
|
+
run_env.update(self.env)
|
|
48
|
+
|
|
49
|
+
stdout_dest = subprocess.PIPE if self.capture_output else None
|
|
50
|
+
stderr_dest = subprocess.PIPE if self.capture_output else None
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
# Run in a background thread or async subprocess
|
|
54
|
+
loop = asyncio.get_running_loop()
|
|
55
|
+
|
|
56
|
+
def _run_sync() -> subprocess.CompletedProcess[str]:
|
|
57
|
+
return subprocess.run(
|
|
58
|
+
self.command,
|
|
59
|
+
shell=isinstance(self.command, str),
|
|
60
|
+
cwd=self.cwd,
|
|
61
|
+
env=run_env,
|
|
62
|
+
stdout=stdout_dest,
|
|
63
|
+
stderr=stderr_dest,
|
|
64
|
+
text=True,
|
|
65
|
+
timeout=self.timeout_seconds,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
proc = await loop.run_in_executor(None, _run_sync)
|
|
69
|
+
|
|
70
|
+
if proc.returncode == 0:
|
|
71
|
+
return CheckResult(
|
|
72
|
+
name=self.name,
|
|
73
|
+
status=CheckStatus.PASSED,
|
|
74
|
+
message=f"Command '{cmd_str}' passed successfully.",
|
|
75
|
+
details={
|
|
76
|
+
"returncode": 0,
|
|
77
|
+
"stdout": proc.stdout if self.capture_output else None,
|
|
78
|
+
"stderr": proc.stderr if self.capture_output else None,
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
else:
|
|
82
|
+
return CheckResult(
|
|
83
|
+
name=self.name,
|
|
84
|
+
status=CheckStatus.FAILED,
|
|
85
|
+
message=f"Command '{cmd_str}' failed with exit code {proc.returncode}.",
|
|
86
|
+
details={
|
|
87
|
+
"returncode": proc.returncode,
|
|
88
|
+
"stdout": proc.stdout if self.capture_output else None,
|
|
89
|
+
"stderr": proc.stderr if self.capture_output else None,
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
except subprocess.TimeoutExpired:
|
|
94
|
+
return CheckResult(
|
|
95
|
+
name=self.name,
|
|
96
|
+
status=CheckStatus.FAILED,
|
|
97
|
+
message=f"Command '{cmd_str}' timed out after {self.timeout_seconds}s.",
|
|
98
|
+
details={"timeout": self.timeout_seconds},
|
|
99
|
+
)
|
|
100
|
+
except Exception as exc:
|
|
101
|
+
return CheckResult(
|
|
102
|
+
name=self.name,
|
|
103
|
+
status=CheckStatus.FAILED,
|
|
104
|
+
message=f"Command '{cmd_str}' execution failed: {exc}",
|
|
105
|
+
details={"error": str(exc)},
|
|
106
|
+
)
|