-
Notifications
You must be signed in to change notification settings - Fork 58
feat: Add health check endpoints for deployment verification #948
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f18a28f
feat: Add health check endpoints for deployment verification
cfsmp3 883bc3f
fix: Add type annotations to fix mypy errors
cfsmp3 1917bae
fix: Correct mock paths and config handling in health tests
cfsmp3 7f26810
fix: Address review comments - don't expose exception details
cfsmp3 bf783e0
fix: Use current_app.logger instead of g.log
cfsmp3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Health check module for deployment verification.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| """Health check endpoints for deployment verification and monitoring.""" | ||
|
|
||
| from datetime import datetime | ||
| from typing import Any, Dict, Tuple | ||
|
|
||
| from flask import Blueprint, current_app, jsonify | ||
|
|
||
| mod_health = Blueprint('health', __name__) | ||
|
|
||
|
|
||
| def check_database() -> Dict[str, Any]: | ||
| """ | ||
| Check database connectivity. | ||
|
|
||
| :return: Dictionary with status and optional error message | ||
| :rtype: Dict[str, Any] | ||
| """ | ||
| try: | ||
| from database import create_session | ||
| db = create_session(current_app.config['DATABASE_URI']) | ||
| db.execute('SELECT 1') | ||
| # remove() returns the scoped session's connection to the pool | ||
| db.remove() | ||
| return {'status': 'ok'} | ||
| except Exception: | ||
| current_app.logger.exception('Health check database connection failed') | ||
| return {'status': 'error', 'message': 'Database connection failed'} | ||
|
|
||
|
|
||
| def check_config() -> Dict[str, Any]: | ||
| """ | ||
| Check that required configuration is loaded. | ||
|
|
||
| :return: Dictionary with status and optional error message | ||
| :rtype: Dict[str, Any] | ||
| """ | ||
| required_keys = [ | ||
| 'DATABASE_URI', | ||
| 'GITHUB_TOKEN', | ||
| 'GITHUB_OWNER', | ||
| 'GITHUB_REPOSITORY', | ||
| ] | ||
|
|
||
| missing = [key for key in required_keys if not current_app.config.get(key)] | ||
|
|
||
| if missing: | ||
| return {'status': 'error', 'message': f'Missing config keys: {missing}'} | ||
| return {'status': 'ok'} | ||
|
|
||
|
|
||
| @mod_health.route('/health') | ||
| def health_check() -> Tuple[Any, int]: | ||
| """ | ||
| Health check endpoint for deployment verification. | ||
|
|
||
| Returns 200 if all critical checks pass, 503 if any fail. | ||
| Used by deployment pipeline to verify successful deployment. | ||
|
|
||
| :return: JSON response with health status and HTTP status code | ||
| :rtype: Tuple[Any, int] | ||
| """ | ||
| check_results: Dict[str, Dict[str, Any]] = {} | ||
| all_healthy = True | ||
|
|
||
| # Check 1: Database connectivity | ||
| db_check = check_database() | ||
| check_results['database'] = db_check | ||
| if db_check['status'] != 'ok': | ||
| all_healthy = False | ||
|
|
||
| # Check 2: Configuration loaded | ||
| config_check = check_config() | ||
| check_results['config'] = config_check | ||
| if config_check['status'] != 'ok': | ||
| all_healthy = False | ||
|
|
||
| checks: Dict[str, Any] = { | ||
| 'status': 'healthy' if all_healthy else 'unhealthy', | ||
| 'timestamp': datetime.utcnow().isoformat() + 'Z', | ||
| 'checks': check_results | ||
| } | ||
|
|
||
| return jsonify(checks), 200 if all_healthy else 503 | ||
|
|
||
|
|
||
| @mod_health.route('/health/live') | ||
| def liveness_check() -> Tuple[Any, int]: | ||
| """ | ||
| Liveness check endpoint. | ||
|
|
||
| Minimal check, just returns 200 if Flask is responding. | ||
| Useful for load balancers and container orchestration. | ||
|
|
||
| :return: JSON response with alive status | ||
| :rtype: Tuple[Any, int] | ||
| """ | ||
| return jsonify({ | ||
| 'status': 'alive', | ||
| 'timestamp': datetime.utcnow().isoformat() + 'Z' | ||
| }), 200 | ||
|
|
||
|
|
||
| @mod_health.route('/health/ready') | ||
| def readiness_check() -> Tuple[Any, int]: | ||
| """ | ||
| Readiness check endpoint. | ||
|
|
||
| Same as health check but can be extended for more checks. | ||
| Useful for Kubernetes readiness probes. | ||
|
|
||
| :return: JSON response with readiness status | ||
| :rtype: Tuple[Any, int] | ||
| """ | ||
| return health_check() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Contains tests for mod_health.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| """Tests for the health check endpoints.""" | ||
|
|
||
| import json | ||
| from unittest import mock | ||
|
|
||
| from tests.base import BaseTestCase | ||
|
|
||
|
|
||
| class TestHealthEndpoints(BaseTestCase): | ||
| """Test health check endpoints.""" | ||
|
|
||
| @mock.patch('mod_health.controllers.check_config') | ||
| @mock.patch('mod_health.controllers.check_database') | ||
| def test_health_endpoint_returns_200_when_healthy(self, mock_db, mock_config): | ||
| """Test that /health returns 200 when all checks pass.""" | ||
| mock_db.return_value = {'status': 'ok'} | ||
| mock_config.return_value = {'status': 'ok'} | ||
|
|
||
| response = self.app.test_client().get('/health') | ||
| self.assertEqual(response.status_code, 200) | ||
|
|
||
| data = json.loads(response.data) | ||
| self.assertEqual(data['status'], 'healthy') | ||
| self.assertIn('timestamp', data) | ||
| self.assertIn('checks', data) | ||
| self.assertEqual(data['checks']['database']['status'], 'ok') | ||
| self.assertEqual(data['checks']['config']['status'], 'ok') | ||
|
|
||
| @mock.patch('mod_health.controllers.check_config') | ||
| @mock.patch('mod_health.controllers.check_database') | ||
| def test_health_endpoint_returns_503_when_database_fails(self, mock_db, mock_config): | ||
| """Test that /health returns 503 when database check fails.""" | ||
| mock_db.return_value = {'status': 'error', 'message': 'Connection failed'} | ||
| mock_config.return_value = {'status': 'ok'} | ||
|
|
||
| response = self.app.test_client().get('/health') | ||
| self.assertEqual(response.status_code, 503) | ||
|
|
||
| data = json.loads(response.data) | ||
| self.assertEqual(data['status'], 'unhealthy') | ||
| self.assertEqual(data['checks']['database']['status'], 'error') | ||
|
|
||
| @mock.patch('mod_health.controllers.check_config') | ||
| @mock.patch('mod_health.controllers.check_database') | ||
| def test_health_endpoint_returns_503_when_config_fails(self, mock_db, mock_config): | ||
| """Test that /health returns 503 when config check fails.""" | ||
| mock_db.return_value = {'status': 'ok'} | ||
| mock_config.return_value = {'status': 'error', 'message': 'Missing keys'} | ||
|
|
||
| response = self.app.test_client().get('/health') | ||
| self.assertEqual(response.status_code, 503) | ||
|
|
||
| data = json.loads(response.data) | ||
| self.assertEqual(data['status'], 'unhealthy') | ||
| self.assertEqual(data['checks']['config']['status'], 'error') | ||
|
|
||
| def test_liveness_endpoint_returns_200(self): | ||
| """Test that /health/live always returns 200.""" | ||
| response = self.app.test_client().get('/health/live') | ||
| self.assertEqual(response.status_code, 200) | ||
|
|
||
| data = json.loads(response.data) | ||
| self.assertEqual(data['status'], 'alive') | ||
| self.assertIn('timestamp', data) | ||
|
|
||
| @mock.patch('mod_health.controllers.check_config') | ||
| @mock.patch('mod_health.controllers.check_database') | ||
| def test_readiness_endpoint_returns_200_when_healthy(self, mock_db, mock_config): | ||
| """Test that /health/ready returns 200 when healthy.""" | ||
| mock_db.return_value = {'status': 'ok'} | ||
| mock_config.return_value = {'status': 'ok'} | ||
|
|
||
| response = self.app.test_client().get('/health/ready') | ||
| self.assertEqual(response.status_code, 200) | ||
|
|
||
| data = json.loads(response.data) | ||
| self.assertEqual(data['status'], 'healthy') | ||
|
|
||
| @mock.patch('mod_health.controllers.check_config') | ||
| @mock.patch('mod_health.controllers.check_database') | ||
| def test_readiness_endpoint_returns_503_when_unhealthy(self, mock_db, mock_config): | ||
| """Test that /health/ready returns 503 when unhealthy.""" | ||
| mock_db.return_value = {'status': 'error', 'message': 'Connection failed'} | ||
| mock_config.return_value = {'status': 'ok'} | ||
|
|
||
| response = self.app.test_client().get('/health/ready') | ||
| self.assertEqual(response.status_code, 503) | ||
|
|
||
| data = json.loads(response.data) | ||
| self.assertEqual(data['status'], 'unhealthy') | ||
|
|
||
|
|
||
| class TestHealthCheckFunctions(BaseTestCase): | ||
| """Test individual health check functions.""" | ||
|
|
||
| def test_check_database_success(self): | ||
| """Test check_database returns ok when database is accessible.""" | ||
| from mod_health.controllers import check_database | ||
| with self.app.app_context(): | ||
| result = check_database() | ||
| self.assertEqual(result['status'], 'ok') | ||
|
|
||
| def test_check_database_failure(self): | ||
| """Test check_database returns error when database fails.""" | ||
| from mod_health.controllers import check_database | ||
| with self.app.app_context(): | ||
| # Mock at the source module where it's imported from | ||
| with mock.patch('database.create_session') as mock_session: | ||
| mock_session.side_effect = Exception('Connection refused') | ||
| result = check_database() | ||
| self.assertEqual(result['status'], 'error') | ||
| # Generic message returned (actual exception logged server-side) | ||
| self.assertEqual(result['message'], 'Database connection failed') | ||
|
|
||
| def test_check_config_success(self): | ||
| """Test check_config returns ok when config is complete.""" | ||
| from mod_health.controllers import check_config | ||
| with self.app.app_context(): | ||
| # Set required config values for test | ||
| self.app.config['GITHUB_TOKEN'] = 'test_token' | ||
| result = check_config() | ||
| self.assertEqual(result['status'], 'ok') | ||
|
|
||
| def test_check_config_missing_keys(self): | ||
| """Test check_config returns error when keys are missing.""" | ||
| from mod_health.controllers import check_config | ||
| with self.app.app_context(): | ||
| # Ensure GITHUB_TOKEN is empty to trigger error | ||
| self.app.config['GITHUB_TOKEN'] = '' | ||
| result = check_config() | ||
| self.assertEqual(result['status'], 'error') | ||
| self.assertIn('GITHUB_TOKEN', result['message']) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.