diff --git a/scripts/release-cache-stage.sh b/scripts/release-cache-stage.sh index fcedc1bb..e37a46b9 100644 --- a/scripts/release-cache-stage.sh +++ b/scripts/release-cache-stage.sh @@ -169,14 +169,34 @@ for name in canino_backend_stage canino_frontend_stage; do image=$(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.Image}}' "$name") [[ $(timeout --foreground --kill-after=2s 10 docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$image") == "$DEPLOY_SHA" ]] path=/ - [[ $name != canino_backend_stage ]] || path=/api + [[ $name != canino_backend_stage ]] || path='/api/blogs?page=1&limit=1' ready=false for attempt in {1..12}; do [[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.State.Running}} {{.RestartCount}}' "$name") == 'true 0' ]] || { printf 'Container stopped or restarted: %s\n' "$name" >&2; exit 1; } if timeout --foreground --kill-after=2s 10 docker exec "$name" node -e ' const http = require("http"); const req = http.get({host: "127.0.0.1", port: 3000, path: process.argv[1]}, res => { - res.resume(); process.exit(res.statusCode === 200 ? 0 : 1); + if (res.statusCode !== 200) { res.resume(); process.exit(1); } + if (process.argv[1] === "/") { res.resume(); process.exit(0); } + // Existing public DB-backed contract; one row, no new health endpoint. + if (!(res.headers["content-type"] || "").includes("application/json")) process.exit(1); + let body = ""; + res.setEncoding("utf8"); + res.on("data", chunk => { + body += chunk; + if (Buffer.byteLength(body) > 2 * 1024 * 1024) process.exit(1); + }); + res.on("error", () => process.exit(1)); + res.on("end", () => { + try { + const {data, meta} = JSON.parse(body); + const valid = Array.isArray(data) && data.length <= 1 && meta && + meta.page === 1 && meta.limit === 1 && + Number.isInteger(meta.total) && meta.total >= data.length && + Number.isInteger(meta.lastPage) && meta.lastPage >= 1; + process.exit(valid ? 0 : 1); + } catch { process.exit(1); } + }); }); req.setTimeout(5000, () => req.destroy(new Error("readiness timeout"))); req.on("error", () => process.exit(1)); diff --git a/scripts/tests/test_stage_readiness.py b/scripts/tests/test_stage_readiness.py new file mode 100644 index 00000000..519a513c --- /dev/null +++ b/scripts/tests/test_stage_readiness.py @@ -0,0 +1,91 @@ +"""Run the release readiness shell and Node probe against a local HTTP server.""" +import http.server +import json +import os +from pathlib import Path +import subprocess +import tempfile +import threading +import unittest + +SCRIPT = Path(__file__).resolve().parents[1] / 'release-cache-stage.sh' + + +class StageReadinessTests(unittest.TestCase): + def probe(self, status=200, body=None, content_type='application/json'): + if body is None: + body = json.dumps({'data': [], 'meta': {'page': 1, 'limit': 1, 'total': 0, 'lastPage': 1}}) + paths = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + paths.append(self.path) + # Reproduce CI1322: no backend root or health route exists. + code = status if self.path == '/api/blogs?page=1&limit=1' else 404 + self.send_response(code) + self.send_header('Content-Type', content_type) + self.end_headers() + self.wfile.write(body.encode()) + + def log_message(self, format, *args): + pass + + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + docker = root / 'docker' + docker.write_text('''#!/usr/bin/env python3 +import os, subprocess, sys +args = sys.argv[1:] +if args[0] == 'exec': + code = args[4].replace('port: 3000', 'port: ' + os.environ['PROBE_PORT']) + sys.exit(subprocess.run(['node', '-e', code, *args[5:]]).returncode) +if args[0] == 'image' or 'release.sha' in args[2]: print('a' * 40) +elif args[2] == '{{.Image}}': print('sha256:fixture') +else: print('true 0') +''') + docker.chmod(0o755) + (root / 'sleep').write_text('#!/bin/sh\nexit 0\n') + (root / 'sleep').chmod(0o755) + source = SCRIPT.read_text() + block = source[source.index('for name in canino_backend_stage'):source.index("printf 'Code-only Stage release complete")] + block = block.replace('canino_backend_stage canino_frontend_stage;', 'canino_backend_stage;') + result = subprocess.run(['bash', '-c', 'set -euo pipefail\n' + block], + env={**os.environ, 'PATH': str(root) + ':' + os.environ['PATH'], + 'DEPLOY_SHA': 'a' * 40, 'PROBE_PORT': str(server.server_port)}, + capture_output=True, text=True, timeout=20) + return result, paths + finally: + server.shutdown() + server.server_close() + thread.join() + + def test_existing_paginated_blogs_route_is_ready_even_when_empty(self): + result, paths = self.probe() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(paths, ['/api/blogs?page=1&limit=1']) + + def test_status_200_without_paginated_json_is_not_ready(self): + for body, content_type in [ + ('fallback', 'text/html'), + ('not-json', 'application/json'), + ('{}', 'application/json'), + (json.dumps({'data': [], 'meta': {'page': 1, 'limit': 10, 'total': 0}}), 'application/json'), + ]: + with self.subTest(body=body): + result, paths = self.probe(body=body, content_type=content_type) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(len(paths), 12) + + def test_not_found_never_counts_as_ready(self): + result, paths = self.probe(status=404) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(len(paths), 12) + self.assertIn('Readiness timed out: canino_backend_stage', result.stderr) + + +if __name__ == '__main__': + unittest.main()