|
| 1 | +import { Args, Flags } from '@oclif/core' |
| 2 | +import { AuthCommand } from '../authCommand' |
| 3 | +import { outputFlag } from '../../helpers/flags' |
| 4 | +import * as api from '../../rest/api' |
| 5 | +import { batchQuickRangeValues, type BatchQuickRange } from '../../rest/batch-analytics' |
| 6 | +import type { CheckWithStatus, PaginationInfo } from '../../formatters/checks' |
| 7 | +import { formatSummaryBar, formatPaginationInfo } from '../../formatters/checks' |
| 8 | +import type { OutputFormat } from '../../formatters/render' |
| 9 | +import type { StatsRow } from '../../formatters/batch-stats' |
| 10 | +import { formatBatchStats, formatBatchStatsNavigationHints } from '../../formatters/batch-stats' |
| 11 | +import { allCheckTypes } from '../../constants' |
| 12 | + |
| 13 | +const MAX_BATCH_SIZE = 100 |
| 14 | + |
| 15 | +export default class ChecksStats extends AuthCommand { |
| 16 | + static hidden = false |
| 17 | + static readOnly = true |
| 18 | + static idempotent = true |
| 19 | + static description = 'Show analytics stats for your checks.' |
| 20 | + |
| 21 | + static args = { |
| 22 | + checkIds: Args.string({ |
| 23 | + description: 'One or more check IDs to get stats for.', |
| 24 | + required: false, |
| 25 | + }), |
| 26 | + } |
| 27 | + |
| 28 | + static strict = false |
| 29 | + |
| 30 | + static flags = { |
| 31 | + range: Flags.string({ |
| 32 | + char: 'r', |
| 33 | + description: 'Time range for stats.', |
| 34 | + options: batchQuickRangeValues, |
| 35 | + default: 'last24Hours', |
| 36 | + }), |
| 37 | + limit: Flags.integer({ |
| 38 | + char: 'l', |
| 39 | + description: 'Number of checks to return (1-100).', |
| 40 | + default: 25, |
| 41 | + }), |
| 42 | + page: Flags.integer({ |
| 43 | + char: 'p', |
| 44 | + description: 'Page number.', |
| 45 | + default: 1, |
| 46 | + }), |
| 47 | + tag: Flags.string({ |
| 48 | + char: 't', |
| 49 | + description: 'Filter by tag. Can be specified multiple times.', |
| 50 | + multiple: true, |
| 51 | + }), |
| 52 | + search: Flags.string({ |
| 53 | + char: 's', |
| 54 | + description: 'Filter checks by name (case-insensitive).', |
| 55 | + }), |
| 56 | + type: Flags.string({ |
| 57 | + description: 'Filter by check type.', |
| 58 | + options: allCheckTypes, |
| 59 | + }), |
| 60 | + output: outputFlag({ default: 'table' }), |
| 61 | + } |
| 62 | + |
| 63 | + async run (): Promise<void> { |
| 64 | + const { flags, argv } = await this.parse(ChecksStats) |
| 65 | + this.style.outputFormat = flags.output |
| 66 | + const range = flags.range as BatchQuickRange |
| 67 | + const { page, limit } = flags |
| 68 | + |
| 69 | + try { |
| 70 | + // Collect explicit check IDs from positional args |
| 71 | + const explicitIds = (argv as string[]).filter(a => !a.startsWith('-')) |
| 72 | + |
| 73 | + let checksWithStatus: CheckWithStatus[] |
| 74 | + let totalChecks: number |
| 75 | + |
| 76 | + if (explicitIds.length > 0) { |
| 77 | + // Fetch all checks (paginate through all pages), filter to requested IDs |
| 78 | + const [allChecks, statuses] = await Promise.all([ |
| 79 | + api.checks.fetchAll(), |
| 80 | + api.checkStatuses.fetchAll().catch(() => []), |
| 81 | + ]) |
| 82 | + const statusMap = new Map(statuses.map(s => [s.checkId, s])) |
| 83 | + const idSet = new Set(explicitIds) |
| 84 | + checksWithStatus = allChecks |
| 85 | + .filter(c => idSet.has(c.id)) |
| 86 | + .map(c => ({ ...c, status: statusMap.get(c.id) })) |
| 87 | + totalChecks = checksWithStatus.length |
| 88 | + } else { |
| 89 | + // Paginated fetch with filters |
| 90 | + const [paginated, statuses] = await Promise.all([ |
| 91 | + api.checks.getAllPaginated({ |
| 92 | + limit, |
| 93 | + page, |
| 94 | + tag: flags.tag, |
| 95 | + checkType: flags.type, |
| 96 | + search: flags.search, |
| 97 | + }), |
| 98 | + api.checkStatuses.fetchAll().catch(() => []), |
| 99 | + ]) |
| 100 | + const statusMap = new Map(statuses.map(s => [s.checkId, s])) |
| 101 | + checksWithStatus = paginated.checks.map(c => ({ ...c, status: statusMap.get(c.id) })) |
| 102 | + totalChecks = paginated.total |
| 103 | + } |
| 104 | + |
| 105 | + if (checksWithStatus.length === 0) { |
| 106 | + if (flags.output === 'json') { |
| 107 | + const totalPages = 0 |
| 108 | + this.log(JSON.stringify({ |
| 109 | + data: [], |
| 110 | + pagination: { page, limit, total: 0, totalPages }, |
| 111 | + range, |
| 112 | + }, null, 2)) |
| 113 | + } else { |
| 114 | + this.log('No checks found.') |
| 115 | + } |
| 116 | + return |
| 117 | + } |
| 118 | + |
| 119 | + // Fetch batch analytics, chunking if > 100 |
| 120 | + const checkIds = checksWithStatus.map(c => c.id) |
| 121 | + const analyticsResults = await this.fetchBatchAnalytics(checkIds, range) |
| 122 | + const analyticsMap = new Map(analyticsResults.map(a => [a.checkId, a])) |
| 123 | + |
| 124 | + // Merge into stats rows |
| 125 | + const rows: StatsRow[] = checksWithStatus.map(c => ({ |
| 126 | + ...c, |
| 127 | + analytics: analyticsMap.get(c.id), |
| 128 | + })) |
| 129 | + |
| 130 | + const pagination: PaginationInfo = { page, limit, total: totalChecks } |
| 131 | + |
| 132 | + // JSON output |
| 133 | + if (flags.output === 'json') { |
| 134 | + const totalPages = Math.ceil(totalChecks / limit) |
| 135 | + this.log(JSON.stringify({ |
| 136 | + data: rows.map(r => ({ |
| 137 | + checkId: r.id, |
| 138 | + name: r.name, |
| 139 | + checkType: r.checkType, |
| 140 | + activated: r.activated, |
| 141 | + status: r.status ? (r.status.hasFailures || r.status.hasErrors ? 'failing' : r.status.isDegraded ? 'degraded' : 'passing') : null, |
| 142 | + availability: r.analytics?.availability ?? null, |
| 143 | + responseTime_avg: r.analytics?.responseTime_avg ?? null, |
| 144 | + responseTime_p95: r.analytics?.responseTime_p95 ?? null, |
| 145 | + latency_avg: r.analytics?.latency_avg ?? null, |
| 146 | + packetLoss_avg: r.analytics?.packetLoss_avg ?? null, |
| 147 | + })), |
| 148 | + pagination: { page, limit, total: totalChecks, totalPages }, |
| 149 | + range, |
| 150 | + }, null, 2)) |
| 151 | + return |
| 152 | + } |
| 153 | + |
| 154 | + const fmt: OutputFormat = flags.output === 'md' ? 'md' : 'terminal' |
| 155 | + |
| 156 | + // Markdown output |
| 157 | + if (fmt === 'md') { |
| 158 | + this.log(formatBatchStats(rows, range, fmt)) |
| 159 | + return |
| 160 | + } |
| 161 | + |
| 162 | + // Terminal output |
| 163 | + const output: string[] = [] |
| 164 | + const statuses = checksWithStatus |
| 165 | + .map(c => c.status) |
| 166 | + .filter((s): s is NonNullable<typeof s> => s != null) |
| 167 | + const activeCheckIds = new Set(checksWithStatus.map(c => c.id)) |
| 168 | + output.push(formatSummaryBar(statuses, totalChecks, activeCheckIds)) |
| 169 | + output.push('') |
| 170 | + output.push(formatBatchStats(rows, range, fmt)) |
| 171 | + output.push('') |
| 172 | + output.push(formatPaginationInfo(pagination)) |
| 173 | + output.push('') |
| 174 | + |
| 175 | + // Build active filters for display |
| 176 | + const activeFilters: string[] = [] |
| 177 | + if (flags.tag) activeFilters.push(...flags.tag.map(t => `tag=${t}`)) |
| 178 | + if (flags.search) activeFilters.push(`search="${flags.search}"`) |
| 179 | + if (flags.type) activeFilters.push(`type=${flags.type}`) |
| 180 | + |
| 181 | + output.push(formatBatchStatsNavigationHints(pagination, range, activeFilters)) |
| 182 | + |
| 183 | + this.log(output.join('\n')) |
| 184 | + } catch (err: any) { |
| 185 | + this.style.longError('Failed to get check stats.', err) |
| 186 | + process.exitCode = 1 |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + private async fetchBatchAnalytics (checkIds: string[], range: BatchQuickRange) { |
| 191 | + const chunks: string[][] = [] |
| 192 | + for (let i = 0; i < checkIds.length; i += MAX_BATCH_SIZE) { |
| 193 | + chunks.push(checkIds.slice(i, i + MAX_BATCH_SIZE)) |
| 194 | + } |
| 195 | + |
| 196 | + const results = await Promise.all( |
| 197 | + chunks.map(chunk => api.batchAnalytics.get(chunk, range).then(r => r.data)), |
| 198 | + ) |
| 199 | + |
| 200 | + return results.flat() |
| 201 | + } |
| 202 | +} |
0 commit comments