shared-pre-deployment 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.
@@ -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
+ )
@@ -0,0 +1,64 @@
1
+ """
2
+ Environment variable validation check.
3
+ Verifies that all required configuration variables are set and non-empty.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from typing import Mapping, Optional, Sequence
10
+
11
+ from shared_pre_deployment.checks import BaseCheck, CheckResult, CheckStatus
12
+
13
+
14
+ class EnvCheck(BaseCheck):
15
+ """
16
+ Validates that a designated list of environment variables are set and non-empty.
17
+ Allows injecting a custom environment mapping for testing or alternate sources.
18
+ """
19
+
20
+ name = "Environment Variables Validation"
21
+
22
+ def __init__(
23
+ self,
24
+ required_vars: Sequence[str],
25
+ env: Optional[Mapping[str, str]] = None,
26
+ name: Optional[str] = None,
27
+ ) -> None:
28
+ super().__init__(name=name)
29
+ self.required_vars = list(required_vars)
30
+ self.env = env
31
+
32
+ async def execute(self) -> CheckResult:
33
+ source_env = self.env if self.env is not None else os.environ
34
+
35
+ missing: list[str] = []
36
+ empty: list[str] = []
37
+
38
+ for var in self.required_vars:
39
+ val = source_env.get(var)
40
+ if val is None:
41
+ missing.append(var)
42
+ elif not str(val).strip():
43
+ empty.append(var)
44
+
45
+ if missing or empty:
46
+ err_parts = []
47
+ if missing:
48
+ err_parts.append(f"missing: {', '.join(missing)}")
49
+ if empty:
50
+ err_parts.append(f"empty: {', '.join(empty)}")
51
+ msg = f"Environment validation failed ({'; '.join(err_parts)})."
52
+ return CheckResult(
53
+ name=self.name,
54
+ status=CheckStatus.FAILED,
55
+ message=msg,
56
+ details={"missing": missing, "empty": empty},
57
+ )
58
+
59
+ return CheckResult(
60
+ name=self.name,
61
+ status=CheckStatus.PASSED,
62
+ message=f"Environment validation: all {len(self.required_vars)} required configuration variables are present.",
63
+ details={"checked": self.required_vars},
64
+ )
@@ -0,0 +1,97 @@
1
+ """
2
+ PostgreSQL database connectivity check.
3
+ Verifies asynchronous connection and basic query execution against PostgreSQL.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import os
10
+ from typing import Optional
11
+
12
+ from sqlalchemy import text
13
+ from sqlalchemy.engine import make_url
14
+ from sqlalchemy.ext.asyncio import create_async_engine
15
+
16
+ from shared_pre_deployment.checks import BaseCheck, CheckResult, CheckStatus
17
+ from shared_pre_deployment.logging import mask_url_password
18
+
19
+
20
+ class PostgresCheck(BaseCheck):
21
+ """
22
+ Validates PostgreSQL connectivity asynchronously using SQLAlchemy.
23
+ Executes a simple 'SELECT 1' test query within a specified timeout.
24
+ Safely sanitizes connection strings to prevent credential exposure in logs.
25
+ """
26
+
27
+ name = "PostgreSQL Connectivity Check"
28
+
29
+ def __init__(
30
+ self,
31
+ db_url: Optional[str] = None,
32
+ env_var: str = "DATABASE_URL",
33
+ timeout_seconds: float = 5.0,
34
+ name: Optional[str] = None,
35
+ ) -> None:
36
+ super().__init__(name=name)
37
+ self.db_url = db_url
38
+ self.env_var = env_var
39
+ self.timeout_seconds = timeout_seconds
40
+
41
+ def _resolve_url(self) -> tuple[Optional[str], str, str]:
42
+ """Resolve database URL and compute safe display representations."""
43
+ raw_url = self.db_url or os.environ.get(self.env_var)
44
+ if not raw_url:
45
+ return None, "unconfigured", ""
46
+
47
+ try:
48
+ parsed = make_url(raw_url)
49
+ target = f"{parsed.host or 'localhost'}:{parsed.port or 5432}/{parsed.database or ''}"
50
+ safe_url = parsed.render_as_string(hide_password=True)
51
+ except Exception:
52
+ safe_url = mask_url_password(raw_url)
53
+ target = "configured database"
54
+
55
+ return raw_url, target, safe_url
56
+
57
+ async def execute(self) -> CheckResult:
58
+ raw_url, target, safe_url = self._resolve_url()
59
+
60
+ if not raw_url:
61
+ return CheckResult(
62
+ name=self.name,
63
+ status=CheckStatus.FAILED,
64
+ message=f"Database check failed: neither db_url nor environment variable '{self.env_var}' is set.",
65
+ details={"env_var": self.env_var},
66
+ )
67
+
68
+ engine = None
69
+ try:
70
+ engine = create_async_engine(raw_url)
71
+ async with asyncio.timeout(self.timeout_seconds):
72
+ async with engine.connect() as conn:
73
+ await conn.execute(text("SELECT 1"))
74
+
75
+ return CheckResult(
76
+ name=self.name,
77
+ status=CheckStatus.PASSED,
78
+ message=f"PostgreSQL connectivity verified successfully ({target}).",
79
+ details={"target": target, "safe_url": safe_url},
80
+ )
81
+ except TimeoutError:
82
+ return CheckResult(
83
+ name=self.name,
84
+ status=CheckStatus.FAILED,
85
+ message=f"PostgreSQL connection timed out after {self.timeout_seconds}s for target '{target}' ({safe_url}).",
86
+ details={"target": target, "timeout": self.timeout_seconds},
87
+ )
88
+ except Exception as exc:
89
+ return CheckResult(
90
+ name=self.name,
91
+ status=CheckStatus.FAILED,
92
+ message=f"PostgreSQL connection failed for target '{target}' ({safe_url}): {exc}",
93
+ details={"target": target, "error": str(exc)},
94
+ )
95
+ finally:
96
+ if engine is not None:
97
+ await engine.dispose()
@@ -0,0 +1,95 @@
1
+ """
2
+ Redis cache connectivity check.
3
+ Verifies asynchronous connection and PING response from Redis.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import os
10
+ from typing import Optional
11
+
12
+ import redis.asyncio as aioredis
13
+
14
+ from shared_pre_deployment.checks import BaseCheck, CheckResult, CheckStatus
15
+ from shared_pre_deployment.logging import mask_url_password
16
+
17
+
18
+ class RedisCheck(BaseCheck):
19
+ """
20
+ Validates Redis connectivity asynchronously using redis.asyncio.
21
+ Executes a PING command within a specified timeout.
22
+ Safely sanitizes connection strings to prevent credential exposure in logs.
23
+ """
24
+
25
+ name = "Redis Connectivity Check"
26
+
27
+ def __init__(
28
+ self,
29
+ redis_url: Optional[str] = None,
30
+ env_var: str = "REDIS_URL",
31
+ timeout_seconds: float = 5.0,
32
+ name: Optional[str] = None,
33
+ ) -> None:
34
+ super().__init__(name=name)
35
+ self.redis_url = redis_url
36
+ self.env_var = env_var
37
+ self.timeout_seconds = timeout_seconds
38
+
39
+ def _resolve_url(self) -> tuple[Optional[str], str]:
40
+ """Resolve Redis URL and compute safe display target."""
41
+ raw_url = self.redis_url or os.environ.get(self.env_var)
42
+ if not raw_url:
43
+ return None, "unconfigured"
44
+ safe_url = mask_url_password(raw_url)
45
+ return raw_url, safe_url
46
+
47
+ async def execute(self) -> CheckResult:
48
+ raw_url, safe_url = self._resolve_url()
49
+
50
+ if not raw_url:
51
+ return CheckResult(
52
+ name=self.name,
53
+ status=CheckStatus.FAILED,
54
+ message=f"Redis check failed: neither redis_url nor environment variable '{self.env_var}' is set.",
55
+ details={"env_var": self.env_var},
56
+ )
57
+
58
+ client = None
59
+ target = "configured redis"
60
+ try:
61
+ client = aioredis.from_url(raw_url)
62
+ kw = getattr(client.connection_pool, "connection_kwargs", {})
63
+ host = kw.get("host", "localhost")
64
+ port = kw.get("port", 6379)
65
+ db = kw.get("db", 0)
66
+ target = f"{host}:{port}/{db}"
67
+
68
+ async with asyncio.timeout(self.timeout_seconds):
69
+ ping_res = await client.ping()
70
+ if not ping_res:
71
+ raise RuntimeError("Redis PING returned non-truthy response")
72
+
73
+ return CheckResult(
74
+ name=self.name,
75
+ status=CheckStatus.PASSED,
76
+ message=f"Redis connectivity verified successfully ({target}).",
77
+ details={"target": target, "safe_url": safe_url},
78
+ )
79
+ except TimeoutError:
80
+ return CheckResult(
81
+ name=self.name,
82
+ status=CheckStatus.FAILED,
83
+ message=f"Redis connection timed out after {self.timeout_seconds}s for target '{target}'.",
84
+ details={"target": target, "timeout": self.timeout_seconds},
85
+ )
86
+ except Exception as exc:
87
+ return CheckResult(
88
+ name=self.name,
89
+ status=CheckStatus.FAILED,
90
+ message=f"Redis connection failed for target '{target}': {exc}",
91
+ details={"target": target, "error": str(exc)},
92
+ )
93
+ finally:
94
+ if client is not None:
95
+ await client.aclose()
@@ -0,0 +1,182 @@
1
+ """
2
+ Command-line interface for shared-pre-deployment.
3
+ Enables running pre-deployment gate checks directly from shell scripts or CI/CD pipelines.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Optional, Sequence
12
+
13
+ import click
14
+
15
+ from shared_pre_deployment import __version__
16
+ from shared_pre_deployment.checks.command import CommandCheck
17
+ from shared_pre_deployment.checks.env import EnvCheck
18
+ from shared_pre_deployment.checks.postgres import PostgresCheck
19
+ from shared_pre_deployment.checks.redis import RedisCheck
20
+ from shared_pre_deployment.runner import PreDeploymentRunner
21
+
22
+
23
+ def _load_env_file(path: Optional[str]) -> None:
24
+ """Manually parse a simple .env file without requiring external dotenv dependencies."""
25
+ target_path = Path(path) if path else Path(".env")
26
+ if not target_path.is_file():
27
+ return
28
+
29
+ try:
30
+ with open(target_path, "r", encoding="utf-8") as f:
31
+ for line in f:
32
+ line = line.strip()
33
+ if not line or line.startswith("#") or "=" not in line:
34
+ continue
35
+ k, v = line.split("=", 1)
36
+ k = k.strip()
37
+ v = v.strip().strip("'\"")
38
+ if k not in os.environ:
39
+ os.environ[k] = v
40
+ except Exception as exc:
41
+ print(f"[WARN] Failed to load .env file '{target_path}': {exc}", file=sys.stderr)
42
+
43
+
44
+ @click.command(context_settings={"help_option_names": ["-h", "--help"]})
45
+ @click.version_option(version=__version__, prog_name="shared-pre-deployment")
46
+ @click.option(
47
+ "--title",
48
+ default="Pre-Deployment Safety Gate Validation",
49
+ show_default=True,
50
+ help="Title banner displayed during execution.",
51
+ )
52
+ @click.option(
53
+ "--env-file",
54
+ type=click.Path(exists=False, dir_okay=False),
55
+ default=None,
56
+ help="Optional path to a .env file to load before running checks.",
57
+ )
58
+ @click.option(
59
+ "--require-env",
60
+ "require_env",
61
+ multiple=True,
62
+ help="Required environment variable(s). Can be specified multiple times or as comma-separated values.",
63
+ )
64
+ @click.option(
65
+ "--check-postgres/--no-check-postgres",
66
+ default=False,
67
+ help="Enable or disable PostgreSQL connectivity verification.",
68
+ )
69
+ @click.option(
70
+ "--postgres-url",
71
+ default=None,
72
+ help="PostgreSQL connection URL. Defaults to DATABASE_URL environment variable.",
73
+ )
74
+ @click.option(
75
+ "--postgres-env-var",
76
+ default="DATABASE_URL",
77
+ show_default=True,
78
+ help="Environment variable name holding the PostgreSQL connection URL.",
79
+ )
80
+ @click.option(
81
+ "--check-redis/--no-check-redis",
82
+ default=False,
83
+ help="Enable or disable Redis connectivity verification.",
84
+ )
85
+ @click.option(
86
+ "--redis-url",
87
+ default=None,
88
+ help="Redis connection URL. Defaults to REDIS_URL environment variable.",
89
+ )
90
+ @click.option(
91
+ "--redis-env-var",
92
+ default="REDIS_URL",
93
+ show_default=True,
94
+ help="Environment variable name holding the Redis connection URL.",
95
+ )
96
+ @click.option(
97
+ "--command",
98
+ "commands",
99
+ multiple=True,
100
+ help="Shell command(s) to execute as gate checks. Can be specified multiple times.",
101
+ )
102
+ @click.option(
103
+ "--timeout",
104
+ default=5.0,
105
+ show_default=True,
106
+ type=float,
107
+ help="Default timeout in seconds for network/database checks.",
108
+ )
109
+ @click.option(
110
+ "--fail-fast/--no-fail-fast",
111
+ default=True,
112
+ show_default=True,
113
+ help="Stop on first failure.",
114
+ )
115
+ def main(
116
+ title: str,
117
+ env_file: Optional[str],
118
+ require_env: Sequence[str],
119
+ check_postgres: bool,
120
+ postgres_url: Optional[str],
121
+ postgres_env_var: str,
122
+ check_redis: bool,
123
+ redis_url: Optional[str],
124
+ redis_env_var: str,
125
+ commands: Sequence[str],
126
+ timeout: float,
127
+ fail_fast: bool,
128
+ ) -> None:
129
+ """
130
+ Run pre-deployment safety gate verification checks.
131
+ Exits with code 0 if all checks pass, or 1 if any check fails.
132
+ """
133
+ # Load .env file if specified or default exists
134
+ _load_env_file(env_file)
135
+
136
+ runner = PreDeploymentRunner(title=title, fail_fast=fail_fast)
137
+
138
+ # 1. Environment Variable Validation
139
+ if require_env:
140
+ parsed_vars: list[str] = []
141
+ for item in require_env:
142
+ for v in item.split(","):
143
+ clean = v.strip()
144
+ if clean:
145
+ parsed_vars.append(clean)
146
+ if parsed_vars:
147
+ runner.add_check(EnvCheck(required_vars=parsed_vars))
148
+
149
+ # 2. PostgreSQL Check
150
+ if check_postgres or postgres_url:
151
+ runner.add_check(
152
+ PostgresCheck(
153
+ db_url=postgres_url,
154
+ env_var=postgres_env_var,
155
+ timeout_seconds=timeout,
156
+ )
157
+ )
158
+
159
+ # 3. Redis Check
160
+ if check_redis or redis_url:
161
+ runner.add_check(
162
+ RedisCheck(
163
+ redis_url=redis_url,
164
+ env_var=redis_env_var,
165
+ timeout_seconds=timeout,
166
+ )
167
+ )
168
+
169
+ # 4. Command Checks
170
+ for cmd in commands:
171
+ runner.add_check(CommandCheck(command=cmd, timeout_seconds=timeout * 10))
172
+
173
+ if not runner.checks:
174
+ click.echo("[WARN] No checks were configured to run.", err=True)
175
+ sys.exit(0)
176
+
177
+ exit_code = runner.run_sync()
178
+ sys.exit(exit_code)
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
@@ -0,0 +1,67 @@
1
+ """
2
+ Logging and output formatting utilities for shared-pre-deployment.
3
+ Provides standardized tagging, credential masking, and clean terminal formatting.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import sys
10
+ from typing import Any
11
+
12
+ # Regex to safely mask passwords in URLs (e.g. postgresql://user:pass@host:port/db or redis://:pass@host:port/db)
13
+ PASSWORD_REGEX = re.compile(r"://([^:]*):([^@]+)@")
14
+
15
+
16
+ def mask_url_password(url: str) -> str:
17
+ """
18
+ Mask password in a database or service URL for safe logging.
19
+
20
+ Example:
21
+ postgresql+asyncpg://admin:secret123@localhost:5432/mydb ->
22
+ postgresql+asyncpg://admin:***@localhost:5432/mydb
23
+ """
24
+ if not url:
25
+ return ""
26
+ return PASSWORD_REGEX.sub(r"://\1:***@", url)
27
+
28
+
29
+ class Logger:
30
+ """Standard console logger formatting pre-deployment gate output."""
31
+
32
+ @staticmethod
33
+ def header(title: str) -> None:
34
+ border = "=" * max(65, len(title) + 4)
35
+ print(f"\n{border}")
36
+ print(f" {title}")
37
+ print(f"{border}\n")
38
+
39
+ @staticmethod
40
+ def info(msg: str) -> None:
41
+ print(f"[PRE-DEPLOYMENT] {msg}")
42
+
43
+ @staticmethod
44
+ def pass_(msg: str) -> None:
45
+ print(f"[PASS] {msg}")
46
+
47
+ @staticmethod
48
+ def fail(msg: str) -> None:
49
+ print(f"[FAIL] {msg}", file=sys.stderr)
50
+
51
+ @staticmethod
52
+ def warn(msg: str) -> None:
53
+ print(f"[WARN] {msg}")
54
+
55
+ @staticmethod
56
+ def summary_success(msg: str = "All pre-deployment safety gates passed successfully!") -> None:
57
+ border = "=" * 65
58
+ print(f"\n{border}")
59
+ print(f"[PASS] {msg}")
60
+ print(f"{border}\n")
61
+
62
+ @staticmethod
63
+ def summary_failure(failed_count: int, total_count: int) -> None:
64
+ border = "=" * 65
65
+ print(f"\n{border}", file=sys.stderr)
66
+ print(f"[FAIL] Pre-deployment verification failed: {failed_count}/{total_count} check(s) failed.", file=sys.stderr)
67
+ print(f"{border}\n", file=sys.stderr)
@@ -0,0 +1,155 @@
1
+ """
2
+ Pre-deployment gate orchestrator and runner.
3
+ Coordinates check execution, formats log outputs, and manages exit statuses.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ from typing import Callable, Optional, Sequence
10
+
11
+ from shared_pre_deployment.checks import BaseCheck, CheckResult, CheckStatus
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
18
+
19
+
20
+ class PreDeploymentRunner:
21
+ """
22
+ Orchestrates the execution of pre-deployment gate checks.
23
+ Provides clear logging, execution metrics, fail-fast capabilities, and exit codes.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ title: str = "Pre-Deployment Safety Gate Validation",
29
+ fail_fast: bool = True,
30
+ logger: Optional[Logger] = None,
31
+ ) -> None:
32
+ self.title = title
33
+ self.fail_fast = fail_fast
34
+ self.logger = logger or Logger()
35
+ self.checks: list[BaseCheck] = []
36
+ self.results: list[CheckResult] = []
37
+
38
+ def add_check(self, check: BaseCheck) -> PreDeploymentRunner:
39
+ """Register a validation check instance."""
40
+ self.checks.append(check)
41
+ return self
42
+
43
+ def register_env_check(
44
+ self,
45
+ required_vars: Sequence[str],
46
+ name: Optional[str] = None,
47
+ ) -> PreDeploymentRunner:
48
+ """Convenience method to register an environment variable check."""
49
+ return self.add_check(EnvCheck(required_vars=required_vars, name=name))
50
+
51
+ def register_postgres_check(
52
+ self,
53
+ db_url: Optional[str] = None,
54
+ env_var: str = "DATABASE_URL",
55
+ timeout_seconds: float = 5.0,
56
+ name: Optional[str] = None,
57
+ ) -> PreDeploymentRunner:
58
+ """Convenience method to register a PostgreSQL connectivity check."""
59
+ return self.add_check(
60
+ PostgresCheck(
61
+ db_url=db_url,
62
+ env_var=env_var,
63
+ timeout_seconds=timeout_seconds,
64
+ name=name,
65
+ )
66
+ )
67
+
68
+ def register_redis_check(
69
+ self,
70
+ redis_url: Optional[str] = None,
71
+ env_var: str = "REDIS_URL",
72
+ timeout_seconds: float = 5.0,
73
+ name: Optional[str] = None,
74
+ ) -> PreDeploymentRunner:
75
+ """Convenience method to register a Redis connectivity check."""
76
+ return self.add_check(
77
+ RedisCheck(
78
+ redis_url=redis_url,
79
+ env_var=env_var,
80
+ timeout_seconds=timeout_seconds,
81
+ name=name,
82
+ )
83
+ )
84
+
85
+ def register_command_check(
86
+ self,
87
+ command: str | Sequence[str],
88
+ name: Optional[str] = None,
89
+ timeout_seconds: Optional[float] = None,
90
+ cwd: Optional[str] = None,
91
+ ) -> PreDeploymentRunner:
92
+ """Convenience method to register an arbitrary command execution check."""
93
+ return self.add_check(
94
+ CommandCheck(
95
+ command=command,
96
+ name=name,
97
+ timeout_seconds=timeout_seconds,
98
+ cwd=cwd,
99
+ )
100
+ )
101
+
102
+ def register_callback_check(
103
+ self,
104
+ func: Callable[[], any],
105
+ name: str = "Custom Validation",
106
+ timeout_seconds: Optional[float] = None,
107
+ ) -> PreDeploymentRunner:
108
+ """Convenience method to register a custom callable check."""
109
+ return self.add_check(
110
+ CallbackCheck(
111
+ func=func,
112
+ name=name,
113
+ timeout_seconds=timeout_seconds,
114
+ )
115
+ )
116
+
117
+ async def run(self) -> bool:
118
+ """
119
+ Execute all registered checks in sequence.
120
+ Returns True if all checks passed, False otherwise.
121
+ """
122
+ self.results.clear()
123
+ self.logger.header(self.title)
124
+
125
+ all_passed = True
126
+
127
+ for index, check in enumerate(self.checks, 1):
128
+ self.logger.info(f"Running check {index}/{len(self.checks)}: {check.name}...")
129
+ result = await check.run()
130
+ self.results.append(result)
131
+
132
+ if result.passed:
133
+ self.logger.pass_(f"{result.message} ({result.execution_time}s)")
134
+ else:
135
+ self.logger.fail(f"{result.message} ({result.execution_time}s)")
136
+ all_passed = False
137
+ if self.fail_fast:
138
+ self.logger.warn("Fail-fast enabled: aborting remaining checks.")
139
+ break
140
+
141
+ failed_count = sum(1 for r in self.results if not r.passed)
142
+ if all_passed:
143
+ self.logger.summary_success()
144
+ return True
145
+ else:
146
+ self.logger.summary_failure(failed_count=failed_count, total_count=len(self.checks))
147
+ return False
148
+
149
+ def run_sync(self) -> int:
150
+ """
151
+ Synchronous execution entrypoint.
152
+ Returns 0 on success, 1 on failure.
153
+ """
154
+ success = asyncio.run(self.run())
155
+ return 0 if success else 1
@@ -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,14 @@
1
+ shared_pre_deployment/__init__.py,sha256=HqhcfXNR1WD00a_NSRCGtvR-yImUUpdNRzWp7Hu1ETE,936
2
+ shared_pre_deployment/cli.py,sha256=QGTvJrG9kIzQSlp_yOoZ4jdFuoiqdusaSGyS5iU_Orw,5275
3
+ shared_pre_deployment/logging.py,sha256=KJoZLwW0G4G1ZZcy8XZe90wL_lUOQ47GBwv4pN3vD88,1952
4
+ shared_pre_deployment/runner.py,sha256=Lrl0bVpo9PaK5rPQKpM6mnX-N3UCQFdV0OweIVoH2kc,5141
5
+ shared_pre_deployment/checks/__init__.py,sha256=rvkEeq6mn2AuBDm_KlggQ-XUmp-99CAAHDQk2D3Ekyo,1849
6
+ shared_pre_deployment/checks/callback.py,sha256=WFSuzSkNjgfnWUP-h2MWS6mMy3a86WWXrAUfE7j6QL8,2720
7
+ shared_pre_deployment/checks/command.py,sha256=HYfwS4X0xChEBTQVUWW6cgudx2v6AmuTvPLYw6DXpU4,3820
8
+ shared_pre_deployment/checks/env.py,sha256=vguUzuTt2DFre8SqgUQy3gGE5qiVelBJJhrQPDxDSO4,2031
9
+ shared_pre_deployment/checks/postgres.py,sha256=jt5FpF6Se_4Ztno5nQwYN1-va9NjeO7D_QA0k8SctUg,3493
10
+ shared_pre_deployment/checks/redis.py,sha256=Q5RG3DoZ3CH_HxvmuValuVg2kzYx-32mMVllwdGZe98,3315
11
+ shared_pre_deployment-0.1.0.dist-info/METADATA,sha256=4f0r1w_ZKdmhl80PINZZW9N73FvyTTBsIZdYS2NvFX4,3127
12
+ shared_pre_deployment-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ shared_pre_deployment-0.1.0.dist-info/entry_points.txt,sha256=4lUidThtGc6GMSYOcBmJKh9qTW0BvdmuFVpDLp0JBS8,128
14
+ shared_pre_deployment-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pre-deployment-runner = shared_pre_deployment.cli:main
3
+ shared-pre-deployment = shared_pre_deployment.cli:main