-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathchecks.ts
More file actions
403 lines (354 loc) · 12.9 KB
/
checks.ts
File metadata and controls
403 lines (354 loc) · 12.9 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import chalk from 'chalk'
import logSymbols from 'log-symbols'
import type { Check } from '../rest/checks'
import type { CheckStatus } from '../rest/check-statuses'
import type { CheckResult } from '../rest/check-results'
import type { ErrorGroup } from '../rest/error-groups'
import {
type OutputFormat,
type DetailField,
type ColumnDef,
truncateToWidth,
visWidth,
formatFrequency,
formatCheckType,
formatMs,
timeAgo,
stripAnsi,
truncateError,
resolveResultStatus,
renderDetailFields,
renderTable,
} from './render'
export { formatFrequency, formatCheckType } from './render'
export type CheckWithStatus = Check & { status?: CheckStatus }
export interface PaginationInfo {
page: number
limit: number
total: number
}
export function resolveStatus (check: CheckWithStatus, format: OutputFormat): string {
if (!check.activated) return format === 'terminal' ? chalk.dim('inactive') : 'inactive'
if (!check.status) return format === 'terminal' ? chalk.dim('-') : 'unknown'
const failing = check.status.hasFailures || check.status.hasErrors
const degraded = check.status.isDegraded
const muted = check.muted
if (format === 'md') {
const label = failing ? 'failing' : degraded ? 'degraded' : 'passing'
return muted ? `${label} (muted)` : label
}
if (failing) return muted ? chalk.dim('failing') : chalk.red('failing')
if (degraded) return muted ? chalk.dim('degraded') : chalk.yellow('degraded')
return muted ? chalk.dim('passing') : chalk.green('passing')
}
function boolSymbol (value: boolean, format: OutputFormat): string {
if (format === 'md') return value ? 'yes' : '-'
return value ? chalk.green('yes') : chalk.dim('-')
}
// --- Summary bar (terminal only) ---
export function getActivatedStatuses (checks: Check[], statuses: CheckStatus[]): CheckStatus[] {
const activated = new Set(checks.filter(c => c.activated).map(c => c.id))
return statuses.filter(s => activated.has(s.checkId))
}
export function formatSummaryBar (checks: Check[], statuses: CheckStatus[]): string {
const activated = getActivatedStatuses(checks, statuses)
const passing = activated.filter(s => !s.hasFailures && !s.hasErrors && !s.isDegraded).length
const degraded = activated.filter(s => s.isDegraded && !s.hasFailures && !s.hasErrors).length
const failing = activated.filter(s => s.hasFailures || s.hasErrors).length
const inactive = checks.filter(c => !c.activated).length
const parts: string[] = []
if (passing > 0) parts.push(chalk.green(`${logSymbols.success} ${passing} passing`))
if (degraded > 0) parts.push(chalk.yellow(`${logSymbols.warning} ${degraded} degraded`))
if (failing > 0) parts.push(chalk.red(`${logSymbols.error} ${failing} failing`))
if (inactive > 0) parts.push(chalk.dim(`⊘ ${inactive} inactive`))
if (parts.length === 0) return ''
return chalk.dim('Account wide:') + ' ' + parts.join(' ')
}
// --- Type breakdown (terminal only) ---
export function formatTypeBreakdown (checks: Check[], activeCheckIds?: Set<string>): string {
const filtered = activeCheckIds ? checks.filter(c => activeCheckIds.has(c.id)) : checks
const counts = new Map<string, number>()
for (const check of filtered) {
counts.set(check.checkType, (counts.get(check.checkType) || 0) + 1)
}
const parts = [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.map(([type, count]) => `${type}: ${count}`)
return chalk.dim(parts.join(' '))
}
// --- Pagination info (terminal only) ---
export function formatPaginationInfo (pagination: PaginationInfo): string {
const { page, limit, total } = pagination
const start = (page - 1) * limit + 1
const end = Math.min(page * limit, total)
const totalPages = Math.ceil(total / limit)
return chalk.dim(`Showing ${start}-${end} of ${total} checks (page ${page}/${totalPages})`)
}
// --- Navigation hints (terminal only) ---
export function formatNavigationHints (pagination: PaginationInfo, activeFilters: string[]): string {
const { page, limit, total } = pagination
const totalPages = Math.ceil(total / limit)
const lines: string[] = []
if (page < totalPages) {
lines.push(` ${chalk.dim('Next page:')} checkly checks list --page ${page + 1}`)
}
if (page > 1) {
lines.push(` ${chalk.dim('Prev page:')} checkly checks list --page ${page - 1}`)
}
lines.push(` ${chalk.dim('View check:')} checkly checks get <id>`)
if (activeFilters.length === 0) {
lines.push(` ${chalk.dim('Filter:')} checkly checks list --tag <tag> --type <type> --status <status> --search <name>`)
}
return lines.join('\n')
}
// --- Check detail fields ---
export const checkDetailFields: DetailField<CheckWithStatus>[] = [
{ label: 'Type', value: c => formatCheckType(c.checkType) },
{
label: 'Description',
value: (c, fmt) => {
if (c.description == null) return fmt === 'terminal' ? null : '-'
return c.description
},
},
{ label: 'Status', value: (c, fmt) => resolveStatus(c, fmt) },
{ label: 'Active', value: (c, fmt) => boolSymbol(c.activated, fmt) },
{ label: 'Muted', value: (c, fmt) => boolSymbol(c.muted, fmt) },
{ label: 'Frequency', value: c => `Every ${formatFrequency(c.frequency)}` },
{
label: 'Locations',
value: (c, fmt) => {
const locations = [
...(c.locations || []),
...(c.privateLocations || []).map(l => `${l} (private)`),
]
if (locations.length === 0) return fmt === 'terminal' ? chalk.dim('-') : '-'
return locations.join(', ')
},
},
{
label: 'Tags',
value: (c, fmt) => {
if (c.tags.length === 0) return fmt === 'terminal' ? chalk.dim('-') : '-'
return c.tags.join(', ')
},
},
{
label: 'Source',
value: (c, fmt) => {
if (fmt === 'md') return null
if (c.scriptPath) return `${chalk.cyan('code')} ${chalk.dim('→')} ${c.scriptPath}`
return chalk.dim('UI')
},
},
{
label: 'URL',
value: (c, fmt) => {
if (fmt === 'md') return null
return c.request?.url ?? null
},
},
{
label: 'SSL',
value: (c, fmt) => {
if (c.status?.sslDaysRemaining == null) {
return fmt === 'md' ? '-' : null
}
const ssl = c.status.sslDaysRemaining
const display = `${ssl} days remaining`
if (fmt === 'md') return display
return ssl <= 14 ? chalk.red(display) : ssl <= 30 ? chalk.yellow(display) : chalk.green(display)
},
},
{
label: 'Deployed',
value: (c, fmt) => {
if (!c.updated_at) return fmt === 'md' ? '-' : null
return new Date(c.updated_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
},
},
{
label: 'Group',
value: (c, fmt) => c.groupId != null ? String(c.groupId) : (fmt === 'terminal' ? chalk.dim('-') : '-'),
},
{
label: 'Created',
value: (c, fmt) => {
if (!c.created_at) return fmt === 'terminal' ? chalk.dim('-') : '-'
return new Date(c.created_at).toISOString().slice(0, 10)
},
},
{ label: 'ID', value: c => c.id },
]
export function formatCheckDetail (check: CheckWithStatus, format: OutputFormat): string {
return renderDetailFields(check.name, checkDetailFields, check, format)
}
// --- Checks table ---
export interface TableOptions {
showId?: boolean
}
function buildCheckColumns (
checks: CheckWithStatus[], format: OutputFormat, options: TableOptions = {},
): ColumnDef<CheckWithStatus>[] {
if (format === 'md') {
return [
{ header: 'Name', value: c => c.name },
{ header: 'Description', value: c => c.description ?? '-' },
{ header: 'Type', value: c => formatCheckType(c.checkType) },
{ header: 'Status', value: (c, fmt) => resolveStatus(c, fmt) },
{ header: 'Freq', value: c => formatFrequency(c.frequency) },
{ header: 'Tags', value: c => c.tags.length > 0 ? c.tags.join(', ') : '-' },
{ header: 'ID', value: c => c.id },
]
}
const { showId = false } = options
const termWidth = process.stdout.columns || 120
const fixedWidth = 12 + 10 + 6
const idReserve = showId ? 38 : 0
const hasDescriptions = checks.some(c => c.description)
const available = termWidth - fixedWidth - idReserve
const longestName = Math.max(4, ...checks.map(c => visWidth(c.name)))
const nameWidth = Math.min(longestName + 2, 42)
const flexSpace = Math.max(8, available - nameWidth)
const descWidth = hasDescriptions ? Math.min(30, Math.floor(flexSpace * 0.4)) : 0
const tagWidth = flexSpace - descWidth
const columns: ColumnDef<CheckWithStatus>[] = [
{
header: 'Name',
width: nameWidth,
value: c => truncateToWidth(c.name, nameWidth - 2),
},
]
if (hasDescriptions) {
columns.push({
header: 'Description',
width: descWidth,
value: c => {
if (!c.description) return chalk.dim('-')
return truncateToWidth(c.description, descWidth - 2)
},
})
}
columns.push(
{
header: 'Type',
width: 12,
value: c => formatCheckType(c.checkType),
},
{
header: 'Status',
width: 10,
value: (c, fmt) => resolveStatus(c, fmt),
},
{
header: 'Freq',
width: 6,
value: c => formatFrequency(c.frequency),
},
)
columns.push({
header: 'Tags',
...(showId && { width: tagWidth }),
value: c => {
const tags = c.tags.length > 0 ? c.tags.join(', ') : chalk.dim('-')
return truncateToWidth(tags, tagWidth - 2)
},
})
if (showId) {
columns.push({ header: 'ID', value: c => chalk.dim(c.id) })
}
return columns
}
export function formatChecks (
checks: CheckWithStatus[], format: OutputFormat,
options: TableOptions & { pagination?: PaginationInfo } = {},
): string {
const columns = buildCheckColumns(checks, format, options)
let result = renderTable(columns, checks, format)
if (format === 'md' && options.pagination) {
const { page, limit, total } = options.pagination
const totalPages = Math.ceil(total / limit)
result += `\n\n*Showing page ${page}/${totalPages} (${total} total checks)*`
}
return result
}
// --- Results table ---
function buildResultColumns (format: OutputFormat): ColumnDef<CheckResult>[] {
if (format === 'md') {
return [
{ header: 'Time', value: r => r.startedAt },
{ header: 'Location', value: r => r.runLocation },
{ header: 'Status', value: (r, fmt) => resolveResultStatus(r, fmt) },
{ header: 'Response Time', value: r => formatMs(r.responseTime) },
{ header: 'ID', value: r => r.id },
]
}
return [
{ header: 'Time', width: 14, value: r => timeAgo(r.startedAt) },
{ header: 'Location', width: 16, value: r => r.runLocation },
{ header: 'Status', width: 10, value: (r, fmt) => resolveResultStatus(r, fmt) },
{ header: 'Response Time', width: 16, value: r => formatMs(r.responseTime) },
{ header: 'Result ID', value: r => chalk.dim(r.id) },
]
}
export function formatResults (results: CheckResult[], format: OutputFormat): string {
return renderTable(buildResultColumns(format), results, format)
}
// --- Error groups ---
function buildErrorGroupColumns (format: OutputFormat): ColumnDef<ErrorGroup>[] {
if (format === 'md') {
return [
{
header: 'Error',
value: eg => {
const msg = stripAnsi(eg.cleanedErrorMessage).replace(/\n/g, ' ').replace(/\s+/g, ' ').trim()
return msg.length > 80 ? msg.substring(0, 79) + '…' : msg
},
},
{ header: 'First Seen', value: eg => eg.firstSeen },
{ header: 'Last Seen', value: eg => eg.lastSeen },
{ header: 'RCA', value: eg => (eg.rootCauseAnalyses?.length ?? 0) > 0 ? 'Yes' : '-' },
{ header: 'ID', value: eg => eg.id },
]
}
return [
{
header: 'Error',
width: 60,
value: eg => chalk.red(truncateError(eg.cleanedErrorMessage, 58)),
},
{
header: 'First Seen',
width: 14,
value: eg => chalk.dim(timeAgo(eg.firstSeen)),
},
{
header: 'Last Seen',
width: 14,
value: eg => chalk.dim(timeAgo(eg.lastSeen)),
},
{
header: 'RCA',
width: 6,
value: eg => (eg.rootCauseAnalyses?.length ?? 0) > 0 ? chalk.cyan('Yes') : chalk.dim('-'),
},
{ header: 'Error Group ID', value: eg => chalk.dim(eg.id) },
]
}
export function formatErrorGroups (errorGroups: ErrorGroup[], format: OutputFormat): string {
const active = errorGroups.filter(eg => !eg.archivedUntilNextEvent)
if (active.length === 0) return ''
const columns = buildErrorGroupColumns(format)
const title = format === 'md'
? '## Error Groups\n\n'
: chalk.bold('ERROR GROUPS') + '\n'
const table = title + renderTable(columns, active, format)
if (format !== 'terminal') return table
const withoutRca = active.filter(eg => (eg.rootCauseAnalyses?.length ?? 0) === 0)
if (withoutRca.length === 0) return table
const hint = withoutRca.length === 1
? `\n\n ${chalk.dim('Run root cause analysis:')} checkly rca run -e ${withoutRca[0].id} -w`
: `\n\n ${chalk.dim('Run root cause analysis on an error group without one:')}\n`
+ withoutRca.map(eg => ` checkly rca run -e ${eg.id} -w`).join('\n')
return table + hint
}