|
| 1 | +const https = require('https'); |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | + |
| 5 | +const OTA_REPO = 'AlphaDroid-devices/OTA'; |
| 6 | +const API_BASE = `https://api.github.com/repos/${OTA_REPO}`; |
| 7 | +const TOKEN = process.env.GITHUB_TOKEN; |
| 8 | +const CHECK_TYPE = process.env.CHECK_TYPE || 'full'; |
| 9 | + |
| 10 | +const opts = { |
| 11 | + headers: { |
| 12 | + 'User-Agent': 'AlphaDroid-Health-Bot/1.0', |
| 13 | + 'Accept': 'application/vnd.github.v3+json', |
| 14 | + ...(TOKEN ? { 'Authorization': `token ${TOKEN}` } : {}) |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +function get(url) { |
| 19 | + return new Promise((resolve, reject) => { |
| 20 | + // Mock for local test since we don't want to hit API really, and we are testing data freshness |
| 21 | + if (url.includes('api.github.com')) { |
| 22 | + resolve({ statusCode: 200, headers: {}, body: {} }); // Mock response |
| 23 | + return; |
| 24 | + } |
| 25 | + const request = https.get(url, opts, response => { |
| 26 | + let body = ''; |
| 27 | + response.on('data', chunk => body += chunk); |
| 28 | + response.on('end', () => { |
| 29 | + if (response.statusCode >= 200 && response.statusCode < 300) { |
| 30 | + resolve({ |
| 31 | + statusCode: response.statusCode, |
| 32 | + headers: response.headers, |
| 33 | + body: JSON.parse(body) |
| 34 | + }); |
| 35 | + } else { |
| 36 | + reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`)); |
| 37 | + } |
| 38 | + }); |
| 39 | + }); |
| 40 | + |
| 41 | + request.on('error', reject); |
| 42 | + request.setTimeout(10000, () => { |
| 43 | + request.destroy(); |
| 44 | + reject(new Error('Request timeout')); |
| 45 | + }); |
| 46 | + }); |
| 47 | +} |
| 48 | + |
| 49 | +async function checkApiStatus() { |
| 50 | + console.log('🔍 Checking GitHub API status...'); |
| 51 | + // Mocked for local test |
| 52 | + return { status: 'healthy', lastCommit: 'mock', repoSize: 0, defaultBranch: 'main' }; |
| 53 | +} |
| 54 | + |
| 55 | +async function checkDataFreshness() { |
| 56 | + console.log('📊 Checking data freshness...'); |
| 57 | + |
| 58 | + const devicesPath = path.join('data', 'devices.json'); |
| 59 | + if (!fs.existsSync(devicesPath)) { |
| 60 | + return { |
| 61 | + status: 'missing', |
| 62 | + error: 'devices.json file not found' |
| 63 | + }; |
| 64 | + } |
| 65 | + |
| 66 | + try { |
| 67 | + const data = JSON.parse(fs.readFileSync(devicesPath, 'utf8')); |
| 68 | + const metadata = data.metadata || {}; |
| 69 | + const fetchedAt = metadata.fetchedAt; |
| 70 | + |
| 71 | + if (!fetchedAt) { |
| 72 | + return { |
| 73 | + status: 'unknown', |
| 74 | + error: 'No fetch timestamp in metadata' |
| 75 | + }; |
| 76 | + } |
| 77 | + |
| 78 | + const fetchTime = new Date(fetchedAt); |
| 79 | + const now = new Date(); // Simulating current time |
| 80 | + // For testing, let's assume 'now' is indeed now. |
| 81 | + |
| 82 | + const ageMinutes = Math.floor((now - fetchTime) / (1000 * 60)); |
| 83 | + const ageHours = Math.floor(ageMinutes / 60); |
| 84 | + const ageDays = Math.floor(ageHours / 24); |
| 85 | + |
| 86 | + let status = 'fresh'; |
| 87 | + let warning = null; |
| 88 | + |
| 89 | + if (ageMinutes > 13 * 60) { |
| 90 | + status = 'stale'; |
| 91 | + warning = `Data is ${Math.floor(ageMinutes / 60)} hours old (expected < 13h)`; |
| 92 | + } |
| 93 | + if (ageHours > 25) { |
| 94 | + status = 'old'; |
| 95 | + warning = `Data is ${ageHours} hours old (expected < 25h)`; |
| 96 | + } |
| 97 | + if (ageDays > 3) { |
| 98 | + status = 'very_old'; |
| 99 | + warning = `Data is ${ageDays} days old`; |
| 100 | + } |
| 101 | + |
| 102 | + return { |
| 103 | + status, |
| 104 | + fetchedAt, |
| 105 | + ageMinutes, |
| 106 | + ageHours, |
| 107 | + ageDays, |
| 108 | + warning, |
| 109 | + deviceCount: data.devices?.length || 0, |
| 110 | + lastTrigger: metadata.trigger || 'unknown' |
| 111 | + }; |
| 112 | + } catch (error) { |
| 113 | + return { |
| 114 | + status: 'corrupt', |
| 115 | + error: error.message |
| 116 | + }; |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +async function checkWebsiteStatus() { |
| 121 | + return { status: 'healthy', checks: {}, missingFiles: [] }; // Mock |
| 122 | +} |
| 123 | + |
| 124 | +async function checkWorkflowStatus() { |
| 125 | + return { status: 'healthy', workflows: {}, missingWorkflows: [] }; // Mock |
| 126 | +} |
| 127 | + |
| 128 | +async function performHealthCheck() { |
| 129 | + console.log(`🏥 Starting ${CHECK_TYPE} health check...`); |
| 130 | + const startTime = Date.now(); |
| 131 | + |
| 132 | + const results = { |
| 133 | + timestamp: new Date().toISOString(), |
| 134 | + checkType: CHECK_TYPE, |
| 135 | + overallStatus: 'healthy', |
| 136 | + checks: {}, |
| 137 | + warnings: [], |
| 138 | + errors: [] |
| 139 | + }; |
| 140 | + |
| 141 | + try { |
| 142 | + // API Status Check |
| 143 | + if (CHECK_TYPE === 'full' || CHECK_TYPE === 'api_status') { |
| 144 | + results.checks.apiStatus = await checkApiStatus(); |
| 145 | + if (results.checks.apiStatus.status !== 'healthy') { |
| 146 | + results.overallStatus = 'degraded'; |
| 147 | + results.errors.push(`API Status: ${results.checks.apiStatus.error}`); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // Data Freshness Check |
| 152 | + if (CHECK_TYPE === 'full' || CHECK_TYPE === 'data_freshness') { |
| 153 | + results.checks.dataFreshness = await checkDataFreshness(); |
| 154 | + if (results.checks.dataFreshness.status === 'missing' || |
| 155 | + results.checks.dataFreshness.status === 'corrupt') { |
| 156 | + results.overallStatus = 'unhealthy'; |
| 157 | + results.errors.push(`Data Status: ${results.checks.dataFreshness.error}`); |
| 158 | + } else if (results.checks.dataFreshness.warning) { |
| 159 | + results.overallStatus = 'degraded'; |
| 160 | + results.warnings.push(`Data Freshness: ${results.checks.dataFreshness.warning}`); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + // Website Status Check |
| 165 | + if (CHECK_TYPE === 'full' || CHECK_TYPE === 'website_status') { |
| 166 | + results.checks.websiteStatus = await checkWebsiteStatus(); |
| 167 | + if (results.checks.websiteStatus.status !== 'healthy') { |
| 168 | + results.overallStatus = 'unhealthy'; |
| 169 | + results.errors.push(`Website Status: Missing files: ${results.checks.websiteStatus.missingFiles.join(', ')}`); |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + // Workflow Status Check |
| 174 | + if (CHECK_TYPE === 'full') { |
| 175 | + results.checks.workflowStatus = await checkWorkflowStatus(); |
| 176 | + if (results.checks.workflowStatus.status !== 'healthy') { |
| 177 | + results.overallStatus = 'degraded'; |
| 178 | + results.warnings.push(`Workflow Status: Missing workflows: ${results.checks.workflowStatus.missingWorkflows.join(', ')}`); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + results.duration = Date.now() - startTime; |
| 183 | + |
| 184 | + // Write health check results |
| 185 | + const resultsPath = 'health-check-results-test.json'; |
| 186 | + fs.writeFileSync(resultsPath, JSON.stringify(results, null, 2)); |
| 187 | + |
| 188 | + console.log(`\n🏥 Health Check Results:`); |
| 189 | + console.log(`Overall Status: ${results.overallStatus.toUpperCase()}`); |
| 190 | + console.log(`Duration: ${results.duration}ms`); |
| 191 | + |
| 192 | + if (results.errors.length > 0) { |
| 193 | + console.log(`\n❌ Errors:`); |
| 194 | + results.errors.forEach(error => console.log(` - ${error}`)); |
| 195 | + } |
| 196 | + |
| 197 | + if (results.warnings.length > 0) { |
| 198 | + console.log(`\n⚠️ Warnings:`); |
| 199 | + results.warnings.forEach(warning => console.log(` - ${warning}`)); |
| 200 | + } |
| 201 | + |
| 202 | + if (results.overallStatus === 'healthy' && results.warnings.length === 0) { |
| 203 | + console.log(`\n✅ All systems healthy!`); |
| 204 | + } |
| 205 | + |
| 206 | + return results; |
| 207 | + |
| 208 | + } catch (error) { |
| 209 | + console.error('Health check failed:', error.message); |
| 210 | + return { |
| 211 | + timestamp: new Date().toISOString(), |
| 212 | + checkType: CHECK_TYPE, |
| 213 | + overallStatus: 'error', |
| 214 | + error: error.message, |
| 215 | + duration: Date.now() - startTime |
| 216 | + }; |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +performHealthCheck() |
| 221 | + .then(results => { |
| 222 | + // Write results to file for next step |
| 223 | + fs.writeFileSync('health-results-test.json', JSON.stringify(results)); |
| 224 | + |
| 225 | + if (results.overallStatus === 'healthy' || results.overallStatus === 'degraded') { |
| 226 | + console.log(`Health check completed successfully (Status: ${results.overallStatus})`); |
| 227 | + process.exit(0); |
| 228 | + } else { |
| 229 | + console.log(`Health check failed with status: ${results.overallStatus}`); |
| 230 | + process.exit(1); |
| 231 | + } |
| 232 | + }) |
| 233 | + .catch(error => { |
| 234 | + console.error('Unexpected error during health check:', error); |
| 235 | + process.exit(1); |
| 236 | + }); |
0 commit comments