diff --git a/CHANGELOG.md b/CHANGELOG.md index fa5ed74..1073580 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ Quick links: ## [Unreleased] +### Added + +- **Database Health is now a visual dashboard.** The Database Health action opens a panel with status tiles (cache hit ratio, transaction ID age, connections, longest open transaction, size), a short "What to do" list ordered by severity, and one card per check (table bloat, unused indexes, foreign keys without an index, blocking locks, slowest statements) with bars and one-click Copy SQL. Status always shows a word and a symbol as well as a colour. A check that cannot run (for example a missing permission) is shown as unavailable while the others still load. *Open as notebook* in the header gives the previous step-by-step notebook report. + ### Changed - **Info and one-off actions open in a temporary notebook.** The database health report, schema, table and object operations, properties views, table profile / activity / index usage / definition, column statistics, maintenance, list views, and the Create / Edit / Drop / Truncate / Quick Clone helpers now open in a new untitled notebook instead of appending to your saved notebook for that database. Close the tab to discard it (VS Code may ask whether to save; choose Don't Save). Query Tool, New Notebook, View Data, Call Function / Procedure, Insert / Update Data and every Scripts submenu entry still go to your saved notebook. Note that *Drop Database* from the Scripts submenu now opens in a temporary notebook too, because it is the same command as the top-level Drop Database. diff --git a/src/activation/commandSpecs.ts b/src/activation/commandSpecs.ts index f38b581..212aad4 100644 --- a/src/activation/commandSpecs.ts +++ b/src/activation/commandSpecs.ts @@ -14,7 +14,7 @@ import { cmdImportConnectionFromDatabaseUrl } from '../commands/importConnection import { cmdSmartPasteConnection } from '../commands/smartPasteConnection'; import { showIndexProperties, copyIndexName, generateDropIndexScript, generateReindexScript, generateScriptCreate, analyzeIndexUsage, generateAlterIndexScript, addIndexComment, cmdIndexOperations, cmdAddIndex } from '../commands/indexes'; import { cmdAddObjectInDatabase, cmdCreateDatabase, cmdDatabaseOperations, cmdDeleteDatabase, cmdDisconnectDatabase as cmdDisconnectDatabaseLegacy, cmdGenerateCreateScript, cmdMaintenanceDatabase, cmdPsqlTool, cmdQueryTool, cmdScriptAlterDatabase, cmdShowConfiguration } from '../commands/database'; -import { cmdDatabaseHealth } from '../commands/health'; +import { DatabaseHealthPanel } from '../providers/DatabaseHealthPanel'; import { cmdDropExtension, cmdEnableExtension, cmdExtensionOperations, cmdRefreshExtension } from '../commands/extensions'; import { cmdCreateForeignTable, cmdDropForeignTable, cmdEditForeignTable, cmdForeignTableOperations, cmdRefreshForeignTable, cmdShowForeignTableProperties, cmdViewForeignTableData } from '../commands/foreignTables'; import { cmdForeignDataWrapperOperations, cmdShowForeignDataWrapperProperties, cmdCreateForeignServer, cmdForeignServerOperations, cmdShowForeignServerProperties, cmdDropForeignServer, cmdCreateUserMapping, cmdUserMappingOperations, cmdShowUserMappingProperties, cmdDropUserMapping, cmdRefreshForeignDataWrapper, cmdRefreshForeignServer, cmdRefreshUserMapping } from '../commands/foreignDataWrappers'; @@ -757,7 +757,7 @@ export function getCommandSpecs( }, { command: 'postgres-explorer.databaseHealth', - callback: async (item: DatabaseTreeItem) => await cmdDatabaseHealth(item, context) + callback: async (item: DatabaseTreeItem) => await DatabaseHealthPanel.open(item, context) }, { command: 'postgres-explorer.queryTool', diff --git a/src/commands/sql/health.ts b/src/commands/sql/health.ts index 3623ecc..448fe9d 100644 --- a/src/commands/sql/health.ts +++ b/src/commands/sql/health.ts @@ -27,6 +27,32 @@ function schemaPredicate(column: string, schema?: string): string { } export const HealthSQL = { + /** + * One row of typed numbers for the Health dashboard: size, connections, cache hit ratio, + * transaction ID age and the longest open transaction. Unlike overview(), nothing is pre-formatted. + */ + summary(): string { + return `SELECT current_database()::text AS db_name, + pg_database_size(current_database())::bigint AS db_size_bytes, + (SELECT count(*) FROM pg_stat_activity WHERE datname = current_database())::int AS connections_total, + (SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND state = 'active' AND pid <> pg_backend_pid())::int AS connections_active, + (SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND state LIKE 'idle in transaction%')::int AS idle_in_transaction, + current_setting('max_connections')::int AS max_connections, + (SELECT round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) + FROM pg_stat_database WHERE datname = current_database()) AS cache_hit_pct, + (SELECT age(datfrozenxid) FROM pg_database WHERE datname = current_database())::bigint AS xid_age, + (SELECT round(100.0 * age(datfrozenxid) / 2147483647, 2) + FROM pg_database WHERE datname = current_database()) AS xid_pct, + (SELECT extract(epoch FROM now() - min(xact_start)) + FROM pg_stat_activity + WHERE datname = current_database() AND xact_start IS NOT NULL AND pid <> pg_backend_pid()) AS longest_xact_seconds, + (SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND xact_start IS NOT NULL AND pid <> pg_backend_pid() + ORDER BY xact_start LIMIT 1)::int AS longest_pid;`; + }, + /** One row per metric: database size, connections by state, cache hit ratio, XID age, longest transaction. */ overview(): string { return `SELECT metric, value, detail @@ -92,7 +118,8 @@ LIMIT 25;`; s.indexrelname AS index_name, s.idx_scan AS scans, pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size, - pg_get_indexdef(s.indexrelid) AS definition + pg_get_indexdef(s.indexrelid) AS definition, + pg_relation_size(s.indexrelid)::bigint AS index_bytes FROM pg_stat_user_indexes s JOIN pg_index i ON i.indexrelid = s.indexrelid WHERE s.idx_scan = 0 diff --git a/src/features/health/healthHtml.ts b/src/features/health/healthHtml.ts new file mode 100644 index 0000000..a99cc9c --- /dev/null +++ b/src/features/health/healthHtml.ts @@ -0,0 +1,267 @@ +/** + * Database Health dashboard HTML. + * + * Pure: a view model goes in, a complete HTML document comes out. No VS Code API is touched, so + * the output can be unit tested and rendered in the design-system demo. All interactivity is + * delegated to a small script that posts `refresh`, `openNotebook` and `copy` messages. + */ +import { BarItem, HealthFinding, HealthLevel, HealthSection, HealthTile, HealthViewModel } from './healthModel'; + +export function escapeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +/** Status words and glyphs: colour is never the only cue (high-contrast themes, colour blindness). */ +const LEVEL_TEXT: Record = { + ok: { word: 'Healthy', glyph: '✓' }, + watch: { word: 'Watch', glyph: '!' }, + act: { word: 'Act now', glyph: '✕' }, + unknown: { word: 'Unknown', glyph: '–' }, +}; + +const OVERALL_TEXT: Record = { + ok: 'Healthy: nothing needs attention', + watch: 'A few things are worth a look', + act: 'Needs attention now', + unknown: 'Not enough data to judge', +}; + +function chip(level: HealthLevel, text?: string): string { + const t = LEVEL_TEXT[level]; + return `${escapeHtml(text ?? t.word)}`; +} + +function renderTile(t: HealthTile): string { + const gauge = + t.gauge === undefined + ? '' + : ``; + return `
+
${escapeHtml(t.label)}
+
${escapeHtml(t.value)}
+ ${gauge} +
${escapeHtml(t.sub)}
+ ${t.level === 'unknown' ? '' : `
${chip(t.level)}
`} +
`; +} + +function renderFinding(f: HealthFinding): string { + return `
  • + ${chip(f.level)} +
    ${escapeHtml(f.title)}
    ${escapeHtml(f.action)}
    + Details +
  • `; +} + +function renderBar(item: BarItem): string { + const copy = item.copy + ? `` + : ''; + return `
  • +
    +
    ${escapeHtml(item.label)}
    + ${item.sublabel ? `
    ${escapeHtml(item.sublabel)}
    ` : ''} +
    +
    +
    ${escapeHtml(item.value)}
    + ${copy} +
  • `; +} + +function renderSection(sec: HealthSection, vm: HealthViewModel): string { + let body: string; + if (sec.error) { + body = `

    Could not load this check: ${escapeHtml(sec.error)}

    `; + } else if (sec.key === 'locks' && vm.blocked.length > 0) { + body = vm.blocked + .map( + b => `
    +
    Blocked
    pid ${escapeHtml(b.blockedPid)}, waiting ${escapeHtml(b.blockedFor)} for ${escapeHtml(b.waitingOn)}
    ${escapeHtml(b.blockedQuery)}
    + +
    Blocking
    pid ${escapeHtml(b.blockingPid)}, ${escapeHtml(b.blockingState)}, open ${escapeHtml(b.blockingAge)}
    ${escapeHtml(b.blockingQuery)}
    +
    +
    ` + ) + .join('\n'); + } else if (sec.items.length === 0) { + body = `

    ${escapeHtml(sec.empty)}

    `; + } else { + body = ``; + } + const more = sec.more > 0 ? `

    And ${sec.more} more. Open as notebook to see all rows.

    ` : ''; + const guidance = sec.guidance.length + ? `
    How to read this
      ${sec.guidance.map(g => `
    • ${escapeHtml(g)}
    • `).join('')}
    ` + : ''; + // Sections that need action start open; healthy ones start collapsed to keep the page short. + const open = sec.level === 'act' || sec.level === 'watch' || sec.error ? ' open' : ''; + return `
    + ${escapeHtml(sec.title)}${escapeHtml(sec.headline)}${chip(sec.level)} +
    ${body}${more}${guidance}
    +
    `; +} + +const CSS = ` +:root { + --ok: var(--vscode-testing-iconPassed, #3fb27f); + --watch: var(--vscode-editorWarning-foreground, #cca700); + --act: var(--vscode-editorError-foreground, #f14c4c); + --unknown: var(--vscode-descriptionForeground, #8b8b8b); + --surface: var(--vscode-sideBar-background, var(--vscode-editor-background)); + --line: var(--vscode-widget-border, var(--vscode-panel-border, rgba(128,128,128,.35))); + --mono: var(--vscode-editor-font-family, ui-monospace, Menlo, Consolas, monospace); +} +*, *::before, *::after { box-sizing: border-box; } +body { margin: 0; padding: 0 0 32px; background: var(--vscode-editor-background); color: var(--vscode-editor-foreground); + font-family: var(--vscode-font-family); font-size: var(--vscode-font-size, 13px); line-height: 1.5; } +.wrap { max-width: 1040px; margin: 0 auto; padding: 0 20px; } +header { border-top: 2px solid var(--pg-brand-accent); border-bottom: 1px solid var(--line); background: var(--surface); padding: 14px 0; } +header .wrap { display: flex; flex-wrap: wrap; gap: 12px 20px; align-items: center; justify-content: space-between; } +h1 { margin: 0; font-size: 1.25em; font-weight: 600; } +.sub { opacity: .7; font-size: .9em; margin-top: 2px; } +.actions { display: flex; gap: 8px; } +button, .linkbtn { font: inherit; cursor: pointer; border-radius: 4px; padding: 4px 12px; border: 1px solid var(--line); + background: transparent; color: inherit; } +button.primary { background: var(--vscode-button-background); color: var(--vscode-button-foreground); border-color: transparent; } +button:hover { background: var(--vscode-toolbar-hoverBackground, rgba(128,128,128,.15)); } +button.primary:hover { background: var(--vscode-button-hoverBackground); } +button:focus-visible, summary:focus-visible, a:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: 2px; } +.verdict { display: flex; align-items: center; gap: 12px; margin: 20px 0 16px; padding: 14px 16px; border: 1px solid var(--line); + border-left-width: 4px; border-radius: 6px; background: var(--surface); font-size: 1.1em; font-weight: 600; } +.chip { display: inline-flex; align-items: center; gap: 5px; padding: 1px 9px; border-radius: 999px; border: 1px solid currentColor; + font-size: .82em; font-weight: 600; white-space: nowrap; } +.chip .glyph { font-weight: 700; } +.lvl-ok { color: var(--ok); } .lvl-watch { color: var(--watch); } .lvl-act { color: var(--act); } .lvl-unknown { color: var(--unknown); } +.lvl-ok-edge { border-left: 3px solid var(--ok); } .lvl-watch-edge { border-left: 3px solid var(--watch); } +.lvl-act-edge { border-left: 3px solid var(--act); } .lvl-unknown-edge { border-left: 3px solid var(--unknown); } +.verdict.lvl-ok { border-left-color: var(--ok); } .verdict.lvl-watch { border-left-color: var(--watch); } +.verdict.lvl-act { border-left-color: var(--act); } .verdict.lvl-unknown { border-left-color: var(--unknown); } +.verdict .word { color: var(--vscode-editor-foreground); } +.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 24px; } +.tile { padding: 12px 14px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); display: flex; flex-direction: column; gap: 4px; } +.tile-label { font-size: .8em; text-transform: uppercase; letter-spacing: .05em; opacity: .7; } +.tile-value { font-size: 1.7em; font-weight: 600; line-height: 1.15; font-variant-numeric: tabular-nums; } +.tile-sub { font-size: .85em; opacity: .75; min-height: 1.3em; } +.tile-status { margin-top: 2px; } +.gauge { height: 6px; border-radius: 3px; background: color-mix(in srgb, currentColor 14%, transparent); overflow: hidden; } +.gauge-fill, .bar-fill { height: 100%; border-radius: 3px; background: currentColor; } +h2 { font-size: .85em; text-transform: uppercase; letter-spacing: .06em; opacity: .75; margin: 28px 0 10px; font-weight: 600; } +.findings { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.finding { display: flex; gap: 12px; align-items: flex-start; padding: 10px 12px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); } +.finding-body { flex: 1; min-width: 0; } +.finding-title { font-weight: 600; } +.finding-action { opacity: .8; font-size: .92em; } +.jump { color: var(--vscode-textLink-foreground); text-decoration: none; font-size: .9em; white-space: nowrap; } +.jump:hover { text-decoration: underline; } +.allclear { padding: 12px 14px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); opacity: .85; } +.card { border: 1px solid var(--line); border-radius: 6px; background: var(--surface); margin-bottom: 10px; } +.card > summary { display: flex; align-items: center; gap: 12px; padding: 10px 14px; cursor: pointer; list-style: none; } +.card > summary::-webkit-details-marker { display: none; } +.card > summary::before { content: '▸'; opacity: .6; width: 1em; } +.card[open] > summary::before { content: '▾'; } +.card-title { font-weight: 600; } +.card-headline { flex: 1; opacity: .75; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.card-body { padding: 4px 14px 14px; border-top: 1px solid var(--line); } +.bars { list-style: none; margin: 8px 0 0; padding: 0; } +.bar-row { display: grid; grid-template-columns: minmax(140px, 1.4fr) minmax(80px, 1fr) 84px auto; gap: 12px; align-items: center; padding: 6px 0; border-bottom: 1px solid color-mix(in srgb, var(--line) 50%, transparent); } +.bar-row:last-child { border-bottom: none; } +.bar-label { font-family: var(--mono); font-size: .92em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bar-sub { font-size: .8em; opacity: .65; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bar-track { height: 8px; border-radius: 4px; background: color-mix(in srgb, var(--unknown) 18%, transparent); overflow: hidden; } +.bar-fill.lvl-ok { color: var(--ok); } .bar-fill.lvl-watch { color: var(--watch); } .bar-fill.lvl-act { color: var(--act); } +.bar-value { text-align: right; font-variant-numeric: tabular-nums; font-family: var(--mono); font-size: .9em; } +.copy { font-size: .8em; padding: 1px 8px; } +.note { margin: 12px 0 0; padding: 8px 12px; border-radius: 4px; background: color-mix(in srgb, var(--unknown) 12%, transparent); } +.more { margin: 8px 0 0; opacity: .65; font-size: .88em; } +.guidance { margin-top: 12px; } +.guidance summary { cursor: pointer; opacity: .75; font-size: .9em; } +.guidance ul { margin: 6px 0 0; padding-left: 20px; opacity: .85; } +.lock-card { display: grid; grid-template-columns: 1fr auto 1fr; gap: 12px; align-items: start; margin-top: 10px; padding: 10px; border: 1px solid var(--line); border-radius: 6px; } +.lock-role { font-weight: 600; } .lock-meta { font-size: .85em; opacity: .75; } +.lock-arrow { align-self: center; opacity: .6; font-size: 1.3em; } +pre { margin: 6px 0; padding: 8px; max-height: 120px; overflow: auto; font-family: var(--mono); font-size: .85em; white-space: pre-wrap; word-break: break-word; background: var(--vscode-textCodeBlock-background, rgba(128,128,128,.12)); border-radius: 4px; } +footer { margin-top: 24px; opacity: .55; font-size: .85em; } +body.vscode-high-contrast .tile, body.vscode-high-contrast .card, body.vscode-high-contrast .finding, body.vscode-high-contrast .verdict { border-color: var(--vscode-contrastBorder, currentColor); } +@media (max-width: 640px) { + .bar-row { grid-template-columns: 1fr 70px; } .bar-track { grid-column: 1 / -1; order: 3; } .bar-row .copy { grid-column: 1 / -1; justify-self: start; } + .lock-card { grid-template-columns: 1fr; } .lock-arrow { display: none; } +} +@media (prefers-reduced-motion: no-preference) { .gauge-fill, .bar-fill { transition: width .35s ease; } } +`; + +const SCRIPT = ` +const vscode = acquireVsCodeApi(); +document.addEventListener('click', (e) => { + const el = e.target instanceof Element ? e.target.closest('[data-action],[data-copy],[data-jump]') : null; + if (!el) { return; } + if (el.hasAttribute('data-action')) { vscode.postMessage({ type: el.getAttribute('data-action') }); } + else if (el.hasAttribute('data-copy')) { + vscode.postMessage({ type: 'copy', text: el.getAttribute('data-copy') }); + const old = el.textContent; el.textContent = 'Copied'; setTimeout(() => { el.textContent = old; }, 1200); + } else if (el.hasAttribute('data-jump')) { + e.preventDefault(); + const t = document.getElementById('sec-' + el.getAttribute('data-jump')); + if (t) { t.open = true; t.scrollIntoView({ behavior: 'smooth', block: 'start' }); } + } +}); +`; + +export interface RenderOptions { + nonce: string; + cspSource: string; + /** CSS for the brand tokens (PANEL_BRAND_TOKENS_CSS), injected so this module stays free of other imports. */ + brandCss?: string; +} + +export function renderHealthHtml(vm: HealthViewModel, opts: RenderOptions): string { + const when = vm.generatedAt.toLocaleString(); + const findings = vm.findings.length + ? `` + : `
    No issues found. Nothing to fix right now.
    `; + return ` + + + + + +Database Health: ${escapeHtml(vm.database)} + + + +
    +

    Database Health

    ${escapeHtml(vm.database)} · checked ${escapeHtml(when)}
    +
    + + +
    +
    +
    +
    ${chip(vm.overall)}${escapeHtml(OVERALL_TEXT[vm.overall])}
    +
    ${vm.tiles.map(renderTile).join('\n')}
    +

    What to do

    + ${findings} +

    Checks

    + ${vm.sections.map(s => renderSection(s, vm)).join('\n')} +
    Read-only checkup. Statistics reset on restart, so unused-index and dead-row results are most meaningful on a server that has run under normal load for a while.
    +
    + + +`; +} + +/** Minimal page shown while the first load is running or when it failed outright. */ +export function renderHealthMessageHtml(title: string, message: string, opts: RenderOptions & { retry?: boolean }): string { + return ` + + +${escapeHtml(title)} + +

    ${escapeHtml(title)}

    +

    ${escapeHtml(message)}

    +${opts.retry ? '

    ' : ''}
    +`; +} diff --git a/src/features/health/healthModel.ts b/src/features/health/healthModel.ts new file mode 100644 index 0000000..5e6db31 --- /dev/null +++ b/src/features/health/healthModel.ts @@ -0,0 +1,598 @@ +/** + * Database Health dashboard view model. + * + * Pure functions (no VS Code or pg dependencies): raw rows from the HealthSQL templates go in, + * a status-coded view model comes out. The webview HTML is rendered from this model, so every + * threshold and sentence the dashboard shows is testable here. + */ + +export type HealthLevel = 'ok' | 'watch' | 'act' | 'unknown'; + +export type HealthSectionKey = 'summary' | 'bloat' | 'unusedIndexes' | 'fkNoIndex' | 'locks' | 'statements'; + +type Row = Record; + +/** Raw query results. A section that failed to load carries its message in `errors` instead of rows. */ +export interface HealthRaw { + database: string; + generatedAt: Date; + summary?: Row | null; + bloat?: Row[]; + unusedIndexes?: Row[]; + fkNoIndex?: Row[]; + locks?: Row[]; + statements?: { installed: boolean; rows: Row[] }; + errors?: Partial>; +} + +export interface HealthTile { + key: string; + label: string; + /** Headline value, already formatted. */ + value: string; + /** One short line under the value. */ + sub: string; + level: HealthLevel; + /** 0-100 fill for the gauge bar; undefined for tiles without one. */ + gauge?: number; +} + +export interface HealthFinding { + level: Exclude; + title: string; + /** What to do, one sentence. */ + action: string; + section: HealthSectionKey; +} + +export interface BarItem { + label: string; + sublabel?: string; + /** Bar fill, 0-100. */ + pct: number; + /** Text shown at the end of the row. */ + value: string; + level: HealthLevel; + /** Text offered by the row's copy button. */ + copy?: string; +} + +export interface HealthSection { + key: HealthSectionKey; + title: string; + level: HealthLevel; + /** Short status line shown in the header, for example "3 tables over 20% dead". */ + headline: string; + items: BarItem[]; + /** Rows beyond the ones shown. */ + more: number; + /** Set when the section could not be loaded. */ + error?: string; + /** Shown when there is nothing to list. */ + empty: string; + /** Short guidance, rendered inside a collapsed fold. */ + guidance: string[]; +} + +export interface BlockedSession { + blockedPid: string; + blockedFor: string; + waitingOn: string; + blockedQuery: string; + blockingPid: string; + blockingState: string; + blockingAge: string; + blockingQuery: string; +} + +export interface HealthViewModel { + database: string; + generatedAt: Date; + overall: HealthLevel; + tiles: HealthTile[]; + findings: HealthFinding[]; + sections: HealthSection[]; + blocked: BlockedSession[]; +} + +const SHOWN = 8; + +// --------------------------------------------------------------------------- +// Formatting helpers +// --------------------------------------------------------------------------- + +export function toNumber(value: unknown): number | undefined { + if (value === null || value === undefined || value === '') { + return undefined; + } + const n = typeof value === 'number' ? value : Number(value); + return Number.isFinite(n) ? n : undefined; +} + +export function formatBytes(bytes: number | undefined): string { + if (bytes === undefined) { + return 'n/a'; + } + const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; + let v = Math.max(0, bytes); + let i = 0; + while (v >= 1024 && i < units.length - 1) { + v /= 1024; + i++; + } + const digits = i === 0 || v >= 100 ? 0 : v >= 10 ? 1 : 2; + return `${v.toFixed(digits)} ${units[i]}`; +} + +export function formatDuration(seconds: number | undefined): string { + if (seconds === undefined) { + return 'none'; + } + const s = Math.max(0, Math.round(seconds)); + if (s < 60) { + return `${s}s`; + } + if (s < 3600) { + return `${Math.floor(s / 60)}m ${s % 60}s`; + } + if (s < 86400) { + return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`; + } + return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h`; +} + +export function formatCount(n: number | undefined): string { + return n === undefined ? 'n/a' : n.toLocaleString('en-US'); +} + +function plural(n: number, one: string, many = `${one}s`): string { + return `${n} ${n === 1 ? one : many}`; +} + +/** + * node-pg parses `interval` columns into an object (years, months, days, hours, minutes, seconds, + * milliseconds) and the text protocol gives a string. Accept both and show a short duration. + */ +export function formatInterval(value: unknown): string { + if (value === null || value === undefined) { + return ''; + } + if (typeof value === 'object') { + const v = value as Record; + const n = (k: string) => toNumber(v[k]) ?? 0; + const seconds = n('years') * 31536000 + n('months') * 2592000 + n('days') * 86400 + n('hours') * 3600 + n('minutes') * 60 + n('seconds') + n('milliseconds') / 1000; + return formatDuration(seconds); + } + return String(value).replace(/\.\d+$/, ''); +} + +function str(value: unknown): string { + return value === null || value === undefined ? '' : String(value); +} + +function clampPct(n: number): number { + return Math.max(0, Math.min(100, n)); +} + +const SEVERITY: Record = { unknown: 0, ok: 1, watch: 2, act: 3 }; + +export function worstLevel(levels: HealthLevel[]): HealthLevel { + let worst: HealthLevel = 'unknown'; + for (const l of levels) { + if (SEVERITY[l] > SEVERITY[worst]) { + worst = l; + } + } + return worst; +} + +// --------------------------------------------------------------------------- +// Thresholds +// --------------------------------------------------------------------------- + +/** Cache hit ratio, percent. Higher is better. */ +export function levelForCacheHit(pct: number | undefined): HealthLevel { + if (pct === undefined) { + return 'unknown'; + } + return pct >= 99 ? 'ok' : pct >= 95 ? 'watch' : 'act'; +} + +/** Transaction ID age as a percent of the 2.1 billion wraparound limit. */ +export function levelForXidAge(pct: number | undefined): HealthLevel { + if (pct === undefined) { + return 'unknown'; + } + return pct < 50 ? 'ok' : pct < 75 ? 'watch' : 'act'; +} + +/** Connections in use as a percent of max_connections. */ +export function levelForConnections(pct: number | undefined): HealthLevel { + if (pct === undefined) { + return 'unknown'; + } + return pct < 70 ? 'ok' : pct < 90 ? 'watch' : 'act'; +} + +/** Age of the longest open transaction, in seconds. Undefined means none is open. */ +export function levelForLongestTxn(seconds: number | undefined): HealthLevel { + if (seconds === undefined) { + return 'ok'; + } + return seconds < 300 ? 'ok' : seconds < 3600 ? 'watch' : 'act'; +} + +export function levelForIdleInTxn(count: number | undefined): HealthLevel { + if (count === undefined) { + return 'unknown'; + } + return count === 0 ? 'ok' : count <= 5 ? 'watch' : 'act'; +} + +/** Dead tuples as a percent of all tuples. */ +export function levelForDeadPct(pct: number): HealthLevel { + return pct < 20 ? 'ok' : pct < 50 ? 'watch' : 'act'; +} + +/** Tables with fewer dead rows than this are ignored: a high percentage on a tiny table is noise. */ +export const BLOAT_MIN_DEAD_ROWS = 1000; + +// --------------------------------------------------------------------------- +// Builders +// --------------------------------------------------------------------------- + +function buildTiles(summary: Row | null | undefined, error: string | undefined): HealthTile[] { + if (!summary) { + const reason = error ?? 'No data returned'; + return [ + { key: 'cache', label: 'Cache hit ratio', value: 'n/a', sub: reason, level: 'unknown' }, + { key: 'xid', label: 'Transaction ID age', value: 'n/a', sub: reason, level: 'unknown' }, + { key: 'connections', label: 'Connections', value: 'n/a', sub: reason, level: 'unknown' }, + { key: 'txn', label: 'Longest open transaction', value: 'n/a', sub: reason, level: 'unknown' }, + { key: 'size', label: 'Database size', value: 'n/a', sub: reason, level: 'unknown' }, + ]; + } + + const cache = toNumber(summary.cache_hit_pct); + const xidPct = toNumber(summary.xid_pct); + const xidAge = toNumber(summary.xid_age); + const total = toNumber(summary.connections_total); + const max = toNumber(summary.max_connections); + const active = toNumber(summary.connections_active); + const idleTxn = toNumber(summary.idle_in_transaction); + const longest = toNumber(summary.longest_xact_seconds); + const size = toNumber(summary.db_size_bytes); + + const connPct = total !== undefined && max !== undefined && max > 0 ? (total / max) * 100 : undefined; + const connLevel = worstLevel([levelForConnections(connPct), levelForIdleInTxn(idleTxn)]); + const idleNote = idleTxn ? `, ${idleTxn} idle in transaction` : ''; + + return [ + { + key: 'cache', + label: 'Cache hit ratio', + value: cache === undefined ? 'n/a' : `${cache.toFixed(1)}%`, + sub: cache === undefined ? 'No reads recorded yet' : 'Aim for 99% or more', + level: levelForCacheHit(cache), + gauge: cache === undefined ? undefined : clampPct(cache), + }, + { + key: 'xid', + label: 'Transaction ID age', + value: xidPct === undefined ? 'n/a' : `${xidPct.toFixed(1)}%`, + sub: xidAge === undefined ? 'of the wraparound limit' : `${formatCount(xidAge)} of 2.1 billion`, + level: levelForXidAge(xidPct), + gauge: xidPct === undefined ? undefined : clampPct(xidPct), + }, + { + key: 'connections', + label: 'Connections', + value: total === undefined || max === undefined ? 'n/a' : `${total} / ${max}`, + sub: `${active ?? 0} active${idleNote}`, + level: connLevel, + gauge: connPct === undefined ? undefined : clampPct(connPct), + }, + { + key: 'txn', + label: 'Longest open transaction', + value: formatDuration(longest), + sub: longest === undefined ? 'No open transactions' : str(summary.longest_pid) ? `pid ${str(summary.longest_pid)}` : 'Oldest open session', + level: levelForLongestTxn(longest), + }, + { + key: 'size', + label: 'Database size', + value: formatBytes(size), + sub: str(summary.db_name), + level: 'unknown', + }, + ]; +} + +const GUIDANCE: Record, string[]> = { + bloat: [ + 'dead_pct above about 20% on a large table means autovacuum is falling behind. Run VACUUM (ANALYZE) on it and consider a lower autovacuum_vacuum_scale_factor for that table.', + 'Plain VACUUM makes space reusable but rarely shrinks the file. Only VACUUM FULL or pg_repack return space to the OS, and VACUUM FULL takes an exclusive lock.', + ], + unusedIndexes: [ + 'Unused indexes slow every INSERT, UPDATE and DELETE and use disk space.', + 'Before dropping one, confirm statistics cover a full business cycle (month-end jobs, reports) and check replicas, since scans there are counted separately.', + 'Drop safely with DROP INDEX CONCURRENTLY schema.index_name;', + ], + fkNoIndex: [ + 'Deleting or updating a parent row scans the whole child table when no index starts with the referencing columns, and joins on the key are slow.', + 'Prioritise large tables. A missing index on a tiny lookup table rarely matters. Create the index with CREATE INDEX CONCURRENTLY to avoid blocking writes.', + ], + locks: [ + 'Look at the blocking query first. It is often an idle-in-transaction session or a long migration.', + 'To stop a blocker, try pg_cancel_backend(pid) before pg_terminate_backend(pid). Long term, keep transactions short and set lock_timeout and idle_in_transaction_session_timeout.', + ], + statements: [ + 'A high total with a low mean is a cheap query called very often. Cache it or batch it.', + 'A high mean is a slow individual query. Run EXPLAIN (ANALYZE, BUFFERS) on it.', + 'A low cache hit means the query reads from disk a lot.', + ], +}; + +function sectionBase(key: Exclude, title: string, empty: string, error?: string): HealthSection { + return { + key, + title, + level: error ? 'unknown' : 'ok', + headline: error ? 'Could not load' : '', + items: [], + more: 0, + error, + empty, + guidance: GUIDANCE[key], + }; +} + +function buildBloat(rows: Row[] | undefined, error: string | undefined, findings: HealthFinding[]): HealthSection { + const sec = sectionBase('bloat', 'Table bloat', 'No tables have dead rows.', error); + if (error || !rows) { + return sec; + } + const significant = rows.filter(r => (toNumber(r.dead_rows) ?? 0) >= BLOAT_MIN_DEAD_ROWS); + const levels = significant.map(r => levelForDeadPct(toNumber(r.dead_pct) ?? 0)); + const flagged = significant.filter(r => levelForDeadPct(toNumber(r.dead_pct) ?? 0) !== 'ok'); + sec.level = worstLevel(levels.length ? levels : ['ok']); + sec.headline = flagged.length + ? `${plural(flagged.length, 'table')} over 20% dead rows` + : significant.length + ? 'Dead rows are under control' + : 'No meaningful bloat'; + const shown = (significant.length ? significant : rows).slice(0, SHOWN); + sec.items = shown.map(r => { + const pct = toNumber(r.dead_pct) ?? 0; + return { + label: `${str(r.schema)}.${str(r.table_name)}`, + sublabel: `${formatCount(toNumber(r.dead_rows))} dead of ${formatCount((toNumber(r.live_rows) ?? 0) + (toNumber(r.dead_rows) ?? 0))} rows, ${str(r.total_size)}`, + pct: clampPct(pct), + value: `${pct.toFixed(1)}%`, + level: (toNumber(r.dead_rows) ?? 0) >= BLOAT_MIN_DEAD_ROWS ? levelForDeadPct(pct) : 'ok', + copy: `VACUUM (ANALYZE) ${str(r.schema)}.${str(r.table_name)};`, + } satisfies BarItem; + }); + sec.more = Math.max(0, (significant.length ? significant : rows).length - shown.length); + if (flagged.length) { + const top = flagged[0]; + findings.push({ + level: sec.level === 'act' ? 'act' : 'watch', + title: `${plural(flagged.length, 'table')} with more than 20% dead rows`, + action: `Start with ${str(top.schema)}.${str(top.table_name)}: run VACUUM (ANALYZE) and check that autovacuum keeps up.`, + section: 'bloat', + }); + } + return sec; +} + +function buildUnusedIndexes(rows: Row[] | undefined, error: string | undefined, findings: HealthFinding[]): HealthSection { + const sec = sectionBase('unusedIndexes', 'Unused indexes', 'Every secondary index has been scanned.', error); + if (error || !rows) { + return sec; + } + const totalBytes = rows.reduce((sum, r) => sum + (toNumber(r.index_bytes) ?? 0), 0); + const maxBytes = Math.max(1, ...rows.map(r => toNumber(r.index_bytes) ?? 0)); + sec.level = rows.length === 0 ? 'ok' : 'watch'; + sec.headline = rows.length === 0 ? 'No unused indexes' : `${plural(rows.length, 'index', 'indexes')}, ${formatBytes(totalBytes)} reclaimable`; + const shown = rows.slice(0, SHOWN); + sec.items = shown.map(r => { + const bytes = toNumber(r.index_bytes) ?? 0; + return { + label: str(r.index_name), + sublabel: `on ${str(r.schema)}.${str(r.table_name)}`, + pct: clampPct((bytes / maxBytes) * 100), + value: str(r.index_size) || formatBytes(bytes), + level: 'watch', + copy: `DROP INDEX CONCURRENTLY ${str(r.schema)}.${str(r.index_name)};`, + } satisfies BarItem; + }); + sec.more = Math.max(0, rows.length - shown.length); + if (rows.length > 0) { + findings.push({ + level: 'watch', + title: `${plural(rows.length, 'unused index', 'unused indexes')} (${formatBytes(totalBytes)})`, + action: 'Confirm statistics cover a full business cycle and check replicas, then drop with DROP INDEX CONCURRENTLY.', + section: 'unusedIndexes', + }); + } + return sec; +} + +function buildFkNoIndex(rows: Row[] | undefined, error: string | undefined, findings: HealthFinding[]): HealthSection { + const sec = sectionBase('fkNoIndex', 'Foreign keys without an index', 'Every foreign key has a supporting index.', error); + if (error || !rows) { + return sec; + } + sec.level = rows.length === 0 ? 'ok' : 'watch'; + sec.headline = rows.length === 0 ? 'All foreign keys are indexed' : `${plural(rows.length, 'foreign key')} missing an index`; + const shown = rows.slice(0, SHOWN); + sec.items = shown.map(r => ({ + label: `${str(r.table_name)} (${str(r.columns)})`, + sublabel: `${str(r.constraint_name)} references ${str(r.references_table)}`, + pct: 100, + value: str(r.table_size), + level: 'watch' as HealthLevel, + copy: str(r.suggested_index) ? `${str(r.suggested_index)};` : undefined, + })); + sec.more = Math.max(0, rows.length - shown.length); + if (rows.length > 0) { + findings.push({ + level: 'watch', + title: `${plural(rows.length, 'foreign key')} without a supporting index`, + action: 'Create the suggested index on the largest tables first, using CREATE INDEX CONCURRENTLY.', + section: 'fkNoIndex', + }); + } + return sec; +} + +function buildLocks(rows: Row[] | undefined, error: string | undefined, findings: HealthFinding[]): { section: HealthSection; blocked: BlockedSession[] } { + const sec = sectionBase('locks', 'Blocking locks', 'Nothing is blocked right now.', error); + if (error || !rows) { + return { section: sec, blocked: [] }; + } + sec.level = rows.length === 0 ? 'ok' : 'act'; + sec.headline = rows.length === 0 ? 'Nothing is blocked' : `${plural(rows.length, 'session')} waiting on a lock`; + const blocked = rows.slice(0, SHOWN).map(r => ({ + blockedPid: str(r.blocked_pid), + blockedFor: formatInterval(r.blocked_for), + waitingOn: str(r.waiting_on), + blockedQuery: str(r.blocked_query), + blockingPid: str(r.blocking_pid), + blockingState: str(r.blocking_state), + blockingAge: formatInterval(r.blocking_txn_age), + blockingQuery: str(r.blocking_query), + })); + sec.more = Math.max(0, rows.length - blocked.length); + if (rows.length > 0) { + findings.push({ + level: 'act', + title: `${plural(rows.length, 'session')} blocked by a lock`, + action: `Look at the blocking query on pid ${str(rows[0].blocking_pid)}. Cancel it with pg_cancel_backend if it is safe to.`, + section: 'locks', + }); + } + return { section: sec, blocked }; +} + +function buildStatements( + data: { installed: boolean; rows: Row[] } | undefined, + error: string | undefined, +): HealthSection { + const sec = sectionBase('statements', 'Slowest statements', 'No statements recorded yet.', error); + if (error || !data) { + return sec; + } + if (!data.installed) { + sec.level = 'unknown'; + sec.headline = 'pg_stat_statements is not installed'; + sec.empty = + 'Add pg_stat_statements to shared_preload_libraries, restart PostgreSQL, then run CREATE EXTENSION pg_stat_statements; to enable this check.'; + return sec; + } + const rows = data.rows; + const maxTotal = Math.max(1, ...rows.map(r => toNumber(r.total_ms) ?? 0)); + sec.level = 'ok'; + sec.headline = rows.length ? `Top ${Math.min(rows.length, SHOWN)} by total time` : 'No statements recorded yet'; + const shown = rows.slice(0, SHOWN); + sec.items = shown.map(r => { + const total = toNumber(r.total_ms) ?? 0; + const mean = toNumber(r.mean_ms); + return { + label: str(r.query), + sublabel: `${formatCount(toNumber(r.calls))} calls, mean ${mean === undefined ? 'n/a' : `${mean.toFixed(1)} ms`}`, + pct: clampPct((total / maxTotal) * 100), + value: formatDuration(total / 1000), + level: 'ok', + copy: str(r.query), + } satisfies BarItem; + }); + sec.more = Math.max(0, rows.length - shown.length); + return sec; +} + +/** Turn raw query results into the dashboard view model. */ +export function buildHealthViewModel(raw: HealthRaw): HealthViewModel { + const errors = raw.errors ?? {}; + const findings: HealthFinding[] = []; + + const tiles = buildTiles(raw.summary, errors.summary); + + // Tile findings, in the order the tiles appear. + for (const t of tiles) { + if (t.level !== 'watch' && t.level !== 'act') { + continue; + } + const level = t.level; + switch (t.key) { + case 'cache': + findings.push({ + level, + title: `Cache hit ratio is ${t.value}`, + action: 'Too little memory (shared_buffers) or heavy sequential scans. Check the biggest tables and missing indexes.', + section: 'summary', + }); + break; + case 'xid': + findings.push({ + level, + title: `Transaction ID age is ${t.value} of the wraparound limit`, + action: 'Check that autovacuum is running and not blocked. Near 100% PostgreSQL forces a shutdown.', + section: 'summary', + }); + break; + case 'connections': + { + const total = toNumber(raw.summary?.connections_total); + const max = toNumber(raw.summary?.max_connections); + const idle = toNumber(raw.summary?.idle_in_transaction) ?? 0; + const pct = total !== undefined && max ? (total / max) * 100 : undefined; + const crowded = levelForConnections(pct) !== 'ok'; + findings.push({ + level, + title: crowded + ? `${t.value} connections in use (${pct!.toFixed(0)}% of the limit)` + : `${plural(idle, 'session')} idle in transaction`, + action: crowded + ? 'Use a connection pooler, and look for applications that leave transactions open.' + : 'Idle-in-transaction sessions hold locks and block vacuum. Find the application that forgets to commit, and set idle_in_transaction_session_timeout.', + section: 'summary', + }); + } + break; + case 'txn': + findings.push({ + level, + title: `A transaction has been open for ${t.value}`, + action: 'It holds back vacuum and can bloat tables. Find out why it is open, then commit, roll back or terminate it.', + section: 'summary', + }); + break; + default: + break; + } + } + + const bloat = buildBloat(raw.bloat, errors.bloat, findings); + const unused = buildUnusedIndexes(raw.unusedIndexes, errors.unusedIndexes, findings); + const fk = buildFkNoIndex(raw.fkNoIndex, errors.fkNoIndex, findings); + const { section: locks, blocked } = buildLocks(raw.locks, errors.locks, findings); + const statements = buildStatements(raw.statements, errors.statements); + + findings.sort((a, b) => SEVERITY[b.level] - SEVERITY[a.level]); + + const sections = [bloat, unused, fk, locks, statements]; + const overall = worstLevel([...tiles.map(t => t.level), ...sections.map(s => s.level)].filter(l => l !== 'unknown')); + + return { + database: raw.database, + generatedAt: raw.generatedAt, + overall: overall === 'unknown' ? 'unknown' : overall, + tiles, + findings, + sections, + blocked, + }; +} diff --git a/src/providers/DatabaseHealthPanel.ts b/src/providers/DatabaseHealthPanel.ts new file mode 100644 index 0000000..28f85c1 --- /dev/null +++ b/src/providers/DatabaseHealthPanel.ts @@ -0,0 +1,166 @@ +import * as vscode from 'vscode'; +import { DatabaseTreeItem } from './DatabaseTreeProvider'; +import { cmdDatabaseHealth } from '../commands/health'; +import { getDatabaseConnection } from '../commands/helper'; +import { validateCategoryItem } from '../commands/connection'; +import { HealthSQL } from '../commands/sql/health'; +import { queryServerVersionNum } from '../lib/postgresServerVersion'; +import { getNonce } from '../lib/template-loader'; +import { PANEL_BRAND_TOKENS_CSS } from '../common/htmlStyles'; +import { disposePooledOwner, WebviewPool } from '../utils/WebviewPool'; +import { buildHealthViewModel, HealthRaw, HealthSectionKey } from '../features/health/healthModel'; +import { renderHealthHtml, renderHealthMessageHtml } from '../features/health/healthHtml'; + +type Queryable = { query: (sql: string) => Promise<{ rows: any[] }> }; + +/** + * Database Health dashboard: status tiles, a short "what to do" list and one card per check. + * Read-only. The same checks are available as a notebook through "Open as notebook". + */ +export class DatabaseHealthPanel { + public static readonly viewType = 'pgStudio.databaseHealth'; + + private static _panels = new Map(); + + public readonly _panel: vscode.WebviewPanel; + private _disposables: vscode.Disposable[] = []; + private _loading = false; + + private constructor( + panel: vscode.WebviewPanel, + private readonly item: DatabaseTreeItem, + private readonly context: vscode.ExtensionContext | undefined, + ) { + this._panel = panel; + this._disposables.push( + panel.webview.onDidReceiveMessage(msg => void this.onMessage(msg)), + ); + } + + public dispose(isRecycling = false): void { + const key = [...DatabaseHealthPanel._panels.entries()].find(([, v]) => v === this)?.[0]; + if (key) { + DatabaseHealthPanel._panels.delete(key); + } + if (!isRecycling) { + this._panel.dispose(); + } + for (const d of this._disposables) { + d.dispose(); + } + this._disposables = []; + } + + public static async open(item: DatabaseTreeItem, context?: vscode.ExtensionContext): Promise { + validateCategoryItem(item); + const database = item.databaseName ?? String(item.label); + const panelKey = `health:${item.connectionId}:${database}`; + + const existing = DatabaseHealthPanel._panels.get(panelKey); + if (existing) { + existing._panel.reveal(vscode.ViewColumn.Active); + void existing.refresh(); + return; + } + + const { panel, commit } = WebviewPool.getInstance().getOrCreate( + DatabaseHealthPanel.viewType, + panelKey, + `Health: ${database}`, + vscode.ViewColumn.Active, + { enableScripts: true, retainContextWhenHidden: true }, + { + onDispose: () => disposePooledOwner(DatabaseHealthPanel._panels, panel, false), + onRecycle: recycled => disposePooledOwner(DatabaseHealthPanel._panels, recycled.panel, true), + }, + ); + const owner = new DatabaseHealthPanel(panel, item, context); + DatabaseHealthPanel._panels.set(panelKey, owner); + commit?.(); + await owner.refresh(); + } + + private get database(): string { + return this.item.databaseName ?? String(this.item.label); + } + + private render(html: (nonce: string) => string): void { + this._panel.webview.html = html(getNonce()); + } + + private async onMessage(msg: { type?: string; text?: string }): Promise { + switch (msg?.type) { + case 'refresh': + await this.refresh(); + break; + case 'openNotebook': + await cmdDatabaseHealth(this.item, this.context); + break; + case 'copy': + if (typeof msg.text === 'string') { + await vscode.env.clipboard.writeText(msg.text); + } + break; + } + } + + public async refresh(): Promise { + if (this._loading) { + return; + } + this._loading = true; + const opts = { cspSource: this._panel.webview.cspSource, brandCss: PANEL_BRAND_TOKENS_CSS }; + this.render(nonce => renderHealthMessageHtml(`Database Health: ${this.database}`, 'Running checks…', { ...opts, nonce })); + + let dbConn: Awaited> | undefined; + try { + dbConn = await getDatabaseConnection(this.item, validateCategoryItem); + const raw = await collectHealth(dbConn.client as unknown as Queryable, this.database); + const vm = buildHealthViewModel(raw); + this.render(nonce => renderHealthHtml(vm, { ...opts, nonce })); + } catch (err: any) { + this.render(nonce => + renderHealthMessageHtml(`Database Health: ${this.database}`, `Could not run the checks: ${err?.message ?? err}`, { + ...opts, + nonce, + retry: true, + }), + ); + } finally { + dbConn?.release?.(); + this._loading = false; + } + } +} + +/** + * Run every check on one connection. A failing check is reported in `errors` and the others still run, + * so one missing permission does not blank the whole dashboard. + */ +export async function collectHealth(client: Queryable, database: string): Promise { + const raw: HealthRaw = { database, generatedAt: new Date(), errors: {} }; + const errors = raw.errors!; + const attempt = async (key: HealthSectionKey, fn: () => Promise): Promise => { + try { + return await fn(); + } catch (err: any) { + errors[key] = String(err?.message ?? err); + return undefined; + } + }; + + raw.summary = (await attempt('summary', async () => (await client.query(HealthSQL.summary())).rows[0])) ?? null; + raw.bloat = await attempt('bloat', async () => (await client.query(HealthSQL.tableBloat())).rows); + raw.unusedIndexes = await attempt('unusedIndexes', async () => (await client.query(HealthSQL.unusedIndexes())).rows); + raw.fkNoIndex = await attempt('fkNoIndex', async () => (await client.query(HealthSQL.foreignKeysWithoutIndex())).rows); + raw.locks = await attempt('locks', async () => (await client.query(HealthSQL.blockingLocks())).rows); + raw.statements = await attempt('statements', async () => { + const check = await client.query(HealthSQL.statementsExtensionCheck()); + if (check.rows?.[0]?.installed !== true) { + return { installed: false, rows: [] }; + } + const versionNum = await queryServerVersionNum(client as any); + return { installed: true, rows: (await client.query(HealthSQL.slowStatements(versionNum))).rows }; + }); + return raw; +} diff --git a/src/test/unit/HealthDashboard.test.ts b/src/test/unit/HealthDashboard.test.ts new file mode 100644 index 0000000..e8b3163 --- /dev/null +++ b/src/test/unit/HealthDashboard.test.ts @@ -0,0 +1,277 @@ +import { expect } from 'chai'; +import { + buildHealthViewModel, + formatBytes, + formatDuration, + formatInterval, + levelForCacheHit, + levelForConnections, + levelForDeadPct, + levelForLongestTxn, + levelForXidAge, + HealthRaw, +} from '../../features/health/healthModel'; +import { escapeHtml, renderHealthHtml, renderHealthMessageHtml } from '../../features/health/healthHtml'; +import { collectHealth } from '../../providers/DatabaseHealthPanel'; + +const healthySummary = { + db_name: 'shop', + db_size_bytes: '5368709120', + connections_total: 12, + connections_active: 2, + idle_in_transaction: 0, + max_connections: 100, + cache_hit_pct: '99.62', + xid_age: '12000000', + xid_pct: '0.56', + longest_xact_seconds: null, + longest_pid: null, +}; + +function raw(over: Partial = {}): HealthRaw { + return { + database: 'shop', + generatedAt: new Date('2026-01-01T00:00:00Z'), + summary: healthySummary, + bloat: [], + unusedIndexes: [], + fkNoIndex: [], + locks: [], + statements: { installed: true, rows: [] }, + errors: {}, + ...over, + }; +} + +describe('Health dashboard model', () => { + describe('formatters', () => { + it('formats bytes', () => { + expect(formatBytes(undefined)).to.equal('n/a'); + expect(formatBytes(512)).to.equal('512 B'); + expect(formatBytes(5368709120)).to.equal('5.00 GB'); + }); + it('formats durations', () => { + expect(formatDuration(undefined)).to.equal('none'); + expect(formatDuration(42)).to.equal('42s'); + expect(formatDuration(125)).to.equal('2m 5s'); + expect(formatDuration(7500)).to.equal('2h 5m'); + expect(formatDuration(200000)).to.equal('2d 7h'); + }); + it('formats intervals from node-pg objects and strings', () => { + expect(formatInterval({ hours: 1, minutes: 5 })).to.equal('1h 5m'); + expect(formatInterval({ seconds: 3 })).to.equal('3s'); + expect(formatInterval('00:00:03.123456')).to.equal('00:00:03'); + expect(formatInterval(null)).to.equal(''); + }); + }); + + describe('thresholds', () => { + it('cache hit', () => { + expect(levelForCacheHit(99.5)).to.equal('ok'); + expect(levelForCacheHit(97)).to.equal('watch'); + expect(levelForCacheHit(90)).to.equal('act'); + expect(levelForCacheHit(undefined)).to.equal('unknown'); + }); + it('xid age', () => { + expect(levelForXidAge(10)).to.equal('ok'); + expect(levelForXidAge(60)).to.equal('watch'); + expect(levelForXidAge(80)).to.equal('act'); + }); + it('connections', () => { + expect(levelForConnections(50)).to.equal('ok'); + expect(levelForConnections(80)).to.equal('watch'); + expect(levelForConnections(95)).to.equal('act'); + }); + it('longest transaction', () => { + expect(levelForLongestTxn(undefined)).to.equal('ok'); + expect(levelForLongestTxn(60)).to.equal('ok'); + expect(levelForLongestTxn(600)).to.equal('watch'); + expect(levelForLongestTxn(7200)).to.equal('act'); + }); + it('dead rows', () => { + expect(levelForDeadPct(5)).to.equal('ok'); + expect(levelForDeadPct(30)).to.equal('watch'); + expect(levelForDeadPct(60)).to.equal('act'); + }); + }); + + describe('buildHealthViewModel', () => { + it('reports a clean database as healthy with no findings', () => { + const vm = buildHealthViewModel(raw()); + expect(vm.overall).to.equal('ok'); + expect(vm.findings).to.have.length(0); + expect(vm.tiles.map(t => t.key)).to.deep.equal(['cache', 'xid', 'connections', 'txn', 'size']); + expect(vm.tiles[0].value).to.equal('99.6%'); + expect(vm.tiles[2].value).to.equal('12 / 100'); + expect(vm.tiles[3].sub).to.equal('No open transactions'); + }); + + it('flags a low cache hit ratio and a stale transaction', () => { + const vm = buildHealthViewModel( + raw({ summary: { ...healthySummary, cache_hit_pct: '92.1', longest_xact_seconds: 7300, longest_pid: 4242 } }), + ); + expect(vm.overall).to.equal('act'); + expect(vm.findings.map(f => f.section)).to.deep.equal(['summary', 'summary']); + expect(vm.tiles[3].sub).to.equal('pid 4242'); + expect(vm.findings.every(f => f.level === 'act')).to.equal(true); + }); + + it('ignores high dead percentages on tiny tables', () => { + const vm = buildHealthViewModel( + raw({ bloat: [{ schema: 'public', table_name: 'tiny', live_rows: 1, dead_rows: 5, dead_pct: '83.3', total_size: '8 kB' }] }), + ); + const bloat = vm.sections.find(s => s.key === 'bloat')!; + expect(bloat.level).to.equal('ok'); + expect(vm.findings).to.have.length(0); + }); + + it('turns a bloated table into a finding with a vacuum command', () => { + const vm = buildHealthViewModel( + raw({ bloat: [{ schema: 'public', table_name: 'orders', live_rows: 40000, dead_rows: 60000, dead_pct: '60.0', total_size: '1 GB' }] }), + ); + const bloat = vm.sections.find(s => s.key === 'bloat')!; + expect(bloat.level).to.equal('act'); + expect(bloat.items[0].copy).to.equal('VACUUM (ANALYZE) public.orders;'); + expect(vm.findings[0].section).to.equal('bloat'); + expect(vm.findings[0].action).to.contain('public.orders'); + }); + + it('sums unused index sizes and offers a drop command', () => { + const vm = buildHealthViewModel( + raw({ + unusedIndexes: [ + { schema: 'public', table_name: 'a', index_name: 'a_idx', index_size: '2 MB', index_bytes: '2097152' }, + { schema: 'public', table_name: 'b', index_name: 'b_idx', index_size: '1 MB', index_bytes: '1048576' }, + ], + }), + ); + const sec = vm.sections.find(s => s.key === 'unusedIndexes')!; + expect(sec.headline).to.equal('2 indexes, 3.00 MB reclaimable'); + expect(sec.items[0].pct).to.equal(100); + expect(sec.items[0].copy).to.equal('DROP INDEX CONCURRENTLY public.a_idx;'); + }); + + it('caps shown rows and reports how many more exist', () => { + const rows = Array.from({ length: 12 }, (_, i) => ({ + constraint_name: `fk${i}`, table_name: `t${i}`, columns: 'x', references_table: 'p', table_size: '1 MB', suggested_index: `CREATE INDEX ON t${i} (x)`, + })); + const sec = buildHealthViewModel(raw({ fkNoIndex: rows })).sections.find(s => s.key === 'fkNoIndex')!; + expect(sec.items).to.have.length(8); + expect(sec.more).to.equal(4); + expect(sec.items[0].copy).to.equal('CREATE INDEX ON t0 (x);'); + }); + + it('treats blocking locks as act-now and keeps both sides', () => { + const vm = buildHealthViewModel( + raw({ + locks: [{ blocked_pid: 1, blocked_for: { seconds: 30 }, waiting_on: 'Lock:relation', blocked_query: 'UPDATE t', blocking_pid: 2, blocking_state: 'idle in transaction', blocking_txn_age: { minutes: 10 }, blocking_query: 'SELECT 1' }], + }), + ); + expect(vm.overall).to.equal('act'); + expect(vm.blocked[0].blockedFor).to.equal('30s'); + expect(vm.blocked[0].blockingAge).to.equal('10m 0s'); + expect(vm.findings[0].title).to.equal('1 session blocked by a lock'); + }); + + it('explains a missing pg_stat_statements instead of failing', () => { + const sec = buildHealthViewModel(raw({ statements: { installed: false, rows: [] } })).sections.find(s => s.key === 'statements')!; + expect(sec.level).to.equal('unknown'); + expect(sec.empty).to.contain('shared_preload_libraries'); + }); + + it('marks a failed section unknown without hiding the others', () => { + const vm = buildHealthViewModel(raw({ bloat: undefined, errors: { bloat: 'permission denied' } })); + const bloat = vm.sections.find(s => s.key === 'bloat')!; + expect(bloat.error).to.equal('permission denied'); + expect(bloat.level).to.equal('unknown'); + expect(vm.overall).to.equal('ok'); + }); + + it('shows n/a tiles when the summary query failed', () => { + const vm = buildHealthViewModel(raw({ summary: null, errors: { summary: 'boom' } })); + expect(vm.tiles.every(t => t.level === 'unknown' && t.value === 'n/a')).to.equal(true); + }); + + it('orders findings most severe first', () => { + const vm = buildHealthViewModel( + raw({ + fkNoIndex: [{ constraint_name: 'fk', table_name: 't', columns: 'x', references_table: 'p', table_size: '1 MB' }], + locks: [{ blocked_pid: 1, blocking_pid: 2 }], + }), + ); + expect(vm.findings.map(f => f.level)).to.deep.equal(['act', 'watch']); + }); + }); +}); + +describe('Health dashboard HTML', () => { + const opts = { nonce: 'n0nce', cspSource: 'vscode-resource:' }; + + it('escapes HTML special characters', () => { + expect(escapeHtml(`&'`)).to.equal('<a href="x">&''); + }); + + it('never emits raw query text from the database', () => { + const vm = buildHealthViewModel( + raw({ statements: { installed: true, rows: [{ query: '', calls: 1, total_ms: 5, mean_ms: 5 }] } }), + ); + const html = renderHealthHtml(vm, opts); + expect(html).to.not.contain(''); + expect(html).to.contain('<script>alert(1)</script>'); + }); + + it('sets a nonce-based CSP and includes the actions', () => { + const html = renderHealthHtml(buildHealthViewModel(raw()), opts); + expect(html).to.contain("script-src 'nonce-n0nce'"); + expect(html).to.contain('data-action="refresh"'); + expect(html).to.contain('data-action="openNotebook"'); + }); + + it('uses words and glyphs, not colour alone, for status', () => { + const html = renderHealthHtml(buildHealthViewModel(raw({ locks: [{ blocked_pid: 1, blocking_pid: 2 }] })), opts); + expect(html).to.contain('Act now'); + expect(html).to.contain('✕'); + expect(html).to.contain('Needs attention now'); + }); + + it('says so when there is nothing to fix', () => { + const html = renderHealthHtml(buildHealthViewModel(raw()), opts); + expect(html).to.contain('No issues found'); + }); + + it('opens sections that need action and collapses healthy ones', () => { + const html = renderHealthHtml(buildHealthViewModel(raw({ locks: [{ blocked_pid: 1, blocking_pid: 2 }] })), opts); + expect(html).to.match(/
    /); + expect(html).to.match(/
    /); + }); + + it('renders the message page with a retry button', () => { + const html = renderHealthMessageHtml('Health', 'oops ', { ...opts, retry: true }); + expect(html).to.contain('oops <b>'); + expect(html).to.contain('Try again'); + }); +}); + +describe('collectHealth', () => { + it('keeps going when one check fails and records the error', async () => { + const client = { + query: async (sql: string) => { + if (sql.includes('pg_stat_user_tables')) { + throw new Error('permission denied for view pg_stat_user_tables'); + } + if (sql.includes('pg_extension')) { + return { rows: [{ installed: false }] }; + } + if (sql.includes('db_size_bytes')) { + return { rows: [healthySummary] }; + } + return { rows: [] }; + }, + }; + const r = await collectHealth(client as any, 'shop'); + expect(r.errors!.bloat).to.contain('permission denied'); + expect(r.summary).to.deep.equal(healthySummary); + expect(r.statements).to.deep.equal({ installed: false, rows: [] }); + expect(r.locks).to.deep.equal([]); + }); +}); diff --git a/src/test/unit/HealthSQL.test.ts b/src/test/unit/HealthSQL.test.ts index 0a191b0..543d6f8 100644 --- a/src/test/unit/HealthSQL.test.ts +++ b/src/test/unit/HealthSQL.test.ts @@ -2,6 +2,7 @@ import { expect } from 'chai'; import { HealthSQL, quoteLiteral, PG_VERSION_13 } from '../../commands/sql/health'; const allTemplates: Array<[string, string]> = [ + ['summary', HealthSQL.summary()], ['overview', HealthSQL.overview()], ['tableBloat', HealthSQL.tableBloat()], ['unusedIndexes', HealthSQL.unusedIndexes()],