-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathci_validate.py
More file actions
331 lines (267 loc) · 10.2 KB
/
ci_validate.py
File metadata and controls
331 lines (267 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
Pre-deployment CI validation suite for IssueCompass.
Run from the backend/ directory:
python -m scripts.ci_validate
Environment must have DATABASE_URL set (pointing to a running PostgreSQL).
Other env vars (SECRET_KEY, GITHUB_TOKEN, etc.) should also be set for
realistic config validation.
Exit codes:
0 — all checks passed
1 — one or more checks failed
"""
import asyncio
import logging
import os
import sys
# Configure logging before any app imports
logging.basicConfig(
level=logging.INFO,
format="%(levelname)-7s %(name)s %(message)s",
)
logger = logging.getLogger("ci_validate")
# Suppress noisy app-level logs during validation
logging.getLogger("app").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy").setLevel(logging.WARNING)
# ── Helpers ────────────────────────────────────────────────────────────────
def _mask_db_url(raw: str) -> str:
if "@" in raw:
return raw.split("@")[0].split("://")[0] + "://****@" + raw.split("@", 1)[1]
return raw
def _ok(label: str, detail: str = "") -> None:
msg = f"[PASS] {label}"
if detail:
msg += f" -- {detail}"
print(msg)
def _fail(label: str, detail: str = "") -> None:
msg = f"[FAIL] {label}"
if detail:
msg += f" -- {detail}"
print(msg, file=sys.stderr)
# ── Checks ─────────────────────────────────────────────────────────────────
async def check_network() -> int:
"""Validate DNS resolution and TCP reachability for the database host."""
import socket
failed = 0
print("\n--- 0. Database Network Diagnostics ---")
db_url = os.environ.get("DATABASE_URL", "")
if not db_url:
_fail("network", "DATABASE_URL is not set")
return 1
# Parse hostname and port from URL
from urllib.parse import urlparse
parsed = urlparse(db_url.replace("+asyncpg", ""))
host = parsed.hostname or "unknown"
port = parsed.port or 5432
print(f" Target: {_mask_db_url(db_url)}")
print(f" Host: {host}")
print(f" Port: {port}")
# DNS resolution
try:
addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
has_ipv4 = any(a[0] == socket.AF_INET for a in addrs)
has_ipv6 = any(a[0] == socket.AF_INET6 for a in addrs)
print(f" DNS: {len(addrs)} address(es) [IPv4={has_ipv4} IPv6={has_ipv6}]")
for a in addrs:
family = "IPv6" if a[0] == socket.AF_INET6 else "IPv4"
print(f" {family}: {a[4][0]}")
if not has_ipv4:
print(" WARN: No IPv4 A record — connection will fail on IPv4-only networks")
except socket.gaierror as e:
_fail("DNS resolution", f"cannot resolve {host}: {e}")
return 1
# TCP connectivity (via IPv4 fallback if available)
connected = False
for family, af_label in [(socket.AF_INET, "IPv4"), (socket.AF_INET6, "IPv6")]:
try:
family_addrs = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
except socket.gaierror:
continue
for addr in family_addrs:
s = socket.socket(family, socket.SOCK_STREAM)
s.settimeout(5)
try:
s.connect(addr[4])
print(f" TCP: {af_label} connected to {addr[4]}")
connected = True
s.close()
break
except OSError as e:
print(f" TCP: {af_label} {addr[4][0]} — {e}")
s.close()
if connected:
break
if not connected:
_fail("TCP connectivity", "could not connect to database host on any address family")
return 1
_ok("network", f"DNS + TCP reachable — host={host} port={port}")
return failed
async def check_async_engine() -> int:
"""Validate async engine creation and basic connectivity."""
failed = 0
print("\n--- 1. Async Engine + PgBouncer Compatibility ---")
from app.core.database import PGCONN_ARGS, AsyncSessionLocal, engine, get_pool_status
from sqlalchemy import text
# Verify engine exists
if engine is None:
_fail("engine", "engine is None")
return 1
_ok("engine", f"engine created, target={_mask_db_url(str(engine.url))}")
# Verify PgBouncer-safe connect_args from the engine's configuration
try:
if PGCONN_ARGS.get("statement_cache_size") != 0:
_fail("PgBouncer", "statement_cache_size is not 0")
failed += 1
elif "prepared_statement_cache_size" in PGCONN_ARGS:
_fail("PgBouncer", "prepared_statement_cache_size present but asyncpg does not accept this param")
failed += 1
else:
_ok("PgBouncer", "statement_cache_size=0 (prepared_statement_cache_size is not a valid asyncpg param)")
except Exception as e:
_fail("PgBouncer", f"could not inspect PGCONN_ARGS: {e}")
failed += 1
# Verify NullPool is used (PgBouncer-compatible)
try:
poolclass_name = type(engine.pool).__name__
if poolclass_name != "NullPool":
_fail("Pool class", f"expected NullPool, got {poolclass_name}")
failed += 1
else:
_ok("Pool class", "NullPool — session pooler compatible")
except Exception as e:
_fail("Pool class", str(e))
failed += 1
# Test SELECT 1
try:
async with engine.connect() as conn:
r = await conn.execute(text("SELECT 1"))
val = r.scalar()
assert val == 1, f"expected 1, got {val}"
_ok("connectivity", "SELECT 1 OK")
except Exception as e:
_fail("connectivity", f"SELECT 1 failed: {e}")
failed += 1
# Test pool introspection — NullPool expected
try:
status = await get_pool_status()
assert isinstance(status, dict), f"expected dict, got {type(status)}"
assert status.get("poolclass") == "NullPool", f"expected NullPool, got {status}"
_ok("pool status", "NullPool — no pooling")
except Exception as e:
_fail("pool status", str(e))
failed += 1
# Test concurrent sessions
try:
for label in ("session-1", "session-2"):
async with AsyncSessionLocal() as s:
r = await s.execute(text("SELECT 1 AS a"))
assert r.scalar() == 1
_ok(label)
except Exception as e:
_fail("concurrent sessions", str(e))
failed += 1
return failed
async def check_db_reconcile() -> int:
"""Validate db_reconcile script handles fresh DB gracefully."""
failed = 0
print("\n--- 2. db_reconcile (fresh DB) ---")
exit_code = os.system(f"{sys.executable} -m scripts.db_reconcile")
if exit_code != 0:
_fail("db_reconcile", f"exit code {exit_code}")
failed += 1
else:
_ok("db_reconcile", "fresh database handled correctly")
return failed
async def check_alembic() -> int:
"""Validate Alembic migrations run cleanly."""
failed = 0
print("\n--- 3. Alembic Migrations ---")
import subprocess
# Check current state
r = subprocess.run(
[sys.executable, "-m", "alembic", "current"],
capture_output=True, text=True,
)
print(r.stdout)
if r.returncode != 0:
_fail("alembic current", r.stderr.strip())
failed += 1
else:
_ok("alembic current")
# Run migrations
r = subprocess.run(
[sys.executable, "-m", "alembic", "upgrade", "head"],
capture_output=True, text=True,
)
print(r.stdout)
if r.returncode != 0:
_fail("alembic upgrade head", r.stderr.strip())
failed += 1
else:
_ok("alembic upgrade head")
# Verify final state
r = subprocess.run(
[sys.executable, "-m", "alembic", "current"],
capture_output=True, text=True,
)
print(r.stdout)
if r.returncode != 0:
_fail("alembic current (post-upgrade)", r.stderr.strip())
failed += 1
else:
_ok("alembic current (post-upgrade)")
return failed
async def check_schema() -> int:
"""Validate schema introspection finds expected tables."""
failed = 0
print("\n--- 4. Schema Introspection ---")
from app.core.database import engine
from sqlalchemy import text
try:
async with engine.connect() as conn:
r = await conn.execute(text(
"SELECT table_name FROM information_schema.tables "
"WHERE table_schema='public' ORDER BY table_name"
))
tables = [row[0] for row in r]
print(f" Tables ({len(tables)}): {tables}")
expected = {
"users", "repositories", "issues",
"saved_searches", "alembic_version",
}
missing = expected - set(tables)
if missing:
_fail("schema", f"missing tables: {missing}")
failed += 1
else:
_ok("schema", f"{len(tables)} tables, all expected present")
except Exception as e:
_fail("schema", str(e))
failed += 1
return failed
# ── Main ───────────────────────────────────────────────────────────────────
async def main() -> int:
total = 0
print("=" * 55)
print("IssueCompass — Pre-Deployment CI Validation")
print("=" * 55)
print(f"Python: {sys.version.split()[0]}")
print(f"Database URL: {_mask_db_url(os.environ.get('DATABASE_URL', 'NOT SET'))}")
print()
total += await check_network()
total += await check_async_engine()
total += await check_db_reconcile()
total += await check_alembic()
total += await check_schema()
print()
print("=" * 55)
if total == 0:
print("ALL CHECKS PASSED")
else:
print(f"{total} CHECK(S) FAILED")
print("=" * 55)
return 0 if total == 0 else 1
def cli():
exit_code = asyncio.run(main())
sys.exit(exit_code)
if __name__ == "__main__":
cli()