From 2e5bdcd49460558682096c496629d6048daa49d7 Mon Sep 17 00:00:00 2001 From: dimiro1 Date: Thu, 4 Jun 2026 23:46:14 +0200 Subject: [PATCH 1/4] feat: add per-function execution metrics dashboard Add a Metrics tab showing execution count, error rate, and average/max duration trended over time, backed by a pre-aggregated hourly rollup table that outlives the short execution-retention window. - store: execution_metrics table (migration 000012) with SQL backfill from existing executions; IncrementMetricBucket / GetFunctionMetrics / DeleteOldMetricBuckets on both the SQLite and in-memory stores - engine: best-effort hourly bucket increment on execution completion - housekeeping: METRICS_RETENTION_DAYS cleanup pass (default 365) - graphql: lazy Function.metrics(from, to, granularity) with server-computed error rate and average duration - frontend: Metrics tab with hand-rolled SVG components (MetricCard, BarChart, Sparkline), command-palette entry, preview gallery, i18n (en/pt-BR) - docs: CONTEXT.md glossary, ADR-0014, README feature bullet + screenshot No new dependencies. --- .gitignore | 3 + CONTEXT.md | 34 + README.md | 5 + docs/adr/0014-metrics-rollup-table.md | 48 + frontend/css/styles.css | 180 ++++ frontend/js/api.js | 31 + frontend/js/app.js | 9 + frontend/js/components/command-palette.js | 9 + frontend/js/components/metrics.js | 165 ++++ frontend/js/i18n/locales/en.js | 28 + frontend/js/i18n/locales/pt-BR.js | 28 + frontend/js/routes.js | 14 + frontend/js/utils.js | 5 + frontend/js/views/function-metrics.js | 321 +++++++ frontend/js/views/preview.js | 77 ++ frontend/test/SpecRunner.html | 1 + frontend/test/spec/components/metrics.spec.js | 90 ++ frontend/test/spec/utils.spec.js | 5 +- gqlgen.yml | 2 + internal/config/config.go | 4 + internal/engine/engine.go | 9 + internal/graph/generated.go | 881 +++++++++++++++++- internal/graph/metrics.resolvers.go | 18 + internal/graph/metrics_test.go | 122 +++ internal/graph/model/models_gen.go | 95 ++ internal/graph/resolver.go | 67 ++ internal/graph/schema/metrics.graphqls | 59 ++ internal/housekeeping/module.go | 5 +- internal/housekeeping/scheduler.go | 41 +- internal/housekeeping/scheduler_test.go | 12 +- .../000012_add_execution_metrics.down.sql | 2 + .../000012_add_execution_metrics.up.sql | 34 + internal/store/memory.go | 88 +- internal/store/sqlite.go | 77 ++ internal/store/sqlite_metrics_test.go | 111 +++ internal/store/store.go | 16 + internal/store/types.go | 14 + shots/metrics.png | Bin 0 -> 56729 bytes 38 files changed, 2672 insertions(+), 38 deletions(-) create mode 100644 CONTEXT.md create mode 100644 docs/adr/0014-metrics-rollup-table.md create mode 100644 frontend/js/components/metrics.js create mode 100644 frontend/js/views/function-metrics.js create mode 100644 frontend/test/spec/components/metrics.spec.js create mode 100644 internal/graph/metrics.resolvers.go create mode 100644 internal/graph/metrics_test.go create mode 100644 internal/graph/schema/metrics.graphqls create mode 100644 internal/migrate/migrations/000012_add_execution_metrics.down.sql create mode 100644 internal/migrate/migrations/000012_add_execution_metrics.up.sql create mode 100644 internal/store/sqlite_metrics_test.go create mode 100644 shots/metrics.png diff --git a/.gitignore b/.gitignore index 3eb44a9..e87c261 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,6 @@ tmp/ .idea .DS_Store logo/logo.af~lock~ + +# Playwright MCP scratch (browser snapshots/screenshots) +.playwright-mcp/ diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..7029a68 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,34 @@ +# Lunar + +Lunar is a self-hosted, single-binary platform for writing and running small +functions (in Lua or Starlark) triggered over HTTP or by cron. This glossary +fixes the language used across the codebase, GraphQL API, and UI. + +## Language + +**Function**: +A named, versioned unit of code that runs in response to a trigger. The +top-level thing a user manages. +_Avoid_: Lambda, script, handler, endpoint. + +**Function Version**: +A specific revision of a function's source code. One version of a function is +active at a time and is what executions run. +_Avoid_: Revision, snapshot, deployment. + +**Execution**: +A single run of a function. Records its outcome (success/error), wall-clock +duration, trigger, and timestamp. Subject to per-function retention, so old +executions are eventually deleted. +_Avoid_: Invocation, run, call, request. + +**Trigger**: +What caused an execution — `http` (an inbound request) or `cron` (a schedule). +_Avoid_: Source, cause, event type. + +**Metric**: +An aggregate measure derived from many executions over a time window — e.g. +execution count, error rate, or average duration. Unlike an execution, a metric +outlives retention: it is stored as a pre-aggregated rollup so history survives +after the underlying executions are deleted. +_Avoid_: Stat, measurement, telemetry, gauge. diff --git a/README.md b/README.md index f6ee478..0de1141 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ A lightweight, self-hosted Function-as-a-Service platform written in Go with Lua * **Email Integration** - Send emails via Resend with scheduling support * **Version Control** - Track and manage function versions * **Execution History** - Monitor function executions and logs +* **Metrics Dashboard** - Per-function execution count, error rate, and average/max duration, trended over time * **Beautiful Error Messages** - Human-friendly error messages with code context, line numbers, and actionable suggestions * **Web Dashboard** - Manage functions through a clean web interface * **GraphQL API** - Typed, introspectable management API with a GraphiQL playground at `/graphql` @@ -43,6 +44,9 @@ A lightweight, self-hosted Function-as-a-Service platform written in Go with Lua ### Execution History ![Executions](shots/executions.png) +### Function Metrics +![Function Metrics](shots/metrics.png) + ### Version Management ![Versions](shots/versions.png) @@ -281,6 +285,7 @@ DATA_DIR=./data # Data directory for SQLite database (default: ./data) EXECUTION_TIMEOUT=300 # Function execution timeout in seconds (default: 300) API_KEY=your-key-here # API key for authentication (auto-generated if not set) BASE_URL=http://localhost:3000 # Base URL for the deployment (auto-detected if not set) +METRICS_RETENTION_DAYS=365 # How long aggregated function metrics are kept (default: 365) ``` ### Authentication diff --git a/docs/adr/0014-metrics-rollup-table.md b/docs/adr/0014-metrics-rollup-table.md new file mode 100644 index 0000000..dceff60 --- /dev/null +++ b/docs/adr/0014-metrics-rollup-table.md @@ -0,0 +1,48 @@ +# Per-function metrics via a pre-aggregated rollup table + +## Context + +We want a per-function metrics dashboard (execution count, error rate, average +and max duration, trended over time). Every execution already writes a row to +`executions` with `status`, `duration_ms`, and `created_at`, so the metrics +*could* be computed on read by aggregating that table directly. But executions +are deleted by per-function retention — **default 7 days** — so on-read +aggregation can only ever show the last week. We want metrics to survive much +longer than the raw executions they came from. + +## Decision + +Store metrics as a **pre-aggregated rollup table**, `execution_metrics`, keyed +by `(function_id, bucket_hour)` (one row per function per UTC hour), holding +`count`, `error_count`, `sum_duration_ms`, and `max_duration_ms`. Buckets are +updated by a **best-effort** SQLite UPSERT at execution completion (alongside the +existing `UpdateExecution` write); they are kept for `METRICS_RETENTION_DAYS` +(default 365) and cleaned up by the existing housekeeping scheduler. The +GraphQL API exposes a lazy `Function.metrics(from, to, granularity)` field that +returns server-computed derived values (`errorRate`, `avgDurationMs`) and +downsamples hourly buckets to daily for long ranges. The table-creation +migration backfills buckets from existing executions. + +## Considered Options + +- **Compute-on-read from `executions` (no new table).** Rejected: cannot show + history beyond the 7-day execution-retention window, and aggregates scan many + rows per dashboard load for high-volume functions. +- **In-memory counters.** Rejected: lost on restart and inconsistent with the + SQLite-everything datastore (ADR-0008). +- **Transactional (exact) bucket writes.** Rejected in favour of best-effort to + keep the execution write path simple and never let a metrics write roll back a + real execution record. See consequences. +- **Percentile latency (p50/p95).** Deferred: percentiles cannot be recovered + from sums and counts; true percentiles would require per-bucket histograms. + v1 ships average and max duration only. + +## Consequences + +- The rollup is **durable but approximate**: a crash or a failed UPSERT can + permanently undercount a bucket, and because the source executions are + eventually deleted, buckets can never be reconciled. These counts are an + observability signal, not exact accounting. +- Adding breakdown dimensions later (by trigger, by version) or percentiles + (histograms) is an additive migration — the v1 schema deliberately carries + neither. diff --git a/frontend/css/styles.css b/frontend/css/styles.css index 2ce9f38..95b35ca 100644 --- a/frontend/css/styles.css +++ b/frontend/css/styles.css @@ -3471,3 +3471,183 @@ pre { flex-direction: column; gap: 0; } + +/* Metrics Tab */ +.metrics-tab-container { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.metrics-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; +} + +.metrics-toolbar__title { + font-size: var(--text-lg); + font-weight: 600; + color: var(--color-text); + margin: 0; +} + +/* Range selector (segmented control) */ +.metrics-range { + display: inline-flex; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + overflow: hidden; +} + +.metrics-range__btn { + appearance: none; + background: transparent; + border: none; + border-right: 1px solid var(--color-border); + color: var(--color-subtle); + padding: 0.4rem 0.85rem; + font-size: var(--text-sm); + font-family: var(--font-mono); + cursor: pointer; + transition: background-color 0.15s, color 0.15s; +} + +.metrics-range__btn:last-child { + border-right: none; +} + +.metrics-range__btn:hover { + color: var(--color-text); + background: var(--color-surface); +} + +.metrics-range__btn--active { + background: var(--color-accent); + color: #fff; +} + +.metrics-range__btn--active:hover { + background: var(--color-accent); + color: #fff; +} + +/* Summary cards */ +.metrics-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 1rem; +} + +.metric-card { + display: flex; + flex-direction: column; + gap: 0.35rem; + padding: 1rem 1.25rem; + border: 1px solid var(--color-border); + border-radius: 8px; + background: var(--color-surface); +} + +.metric-card__label { + font-size: var(--text-xs); + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--color-text-muted); +} + +.metric-card__value { + font-size: var(--text-2xl); + font-weight: 600; + font-family: var(--font-mono); + color: var(--color-text); + line-height: 1.1; +} + +.metric-card__sub { + font-size: var(--text-xs); + color: var(--color-subtle); +} + +.metric-card--danger .metric-card__value { + color: var(--color-danger); +} + +.metric-card--success .metric-card__value { + color: var(--color-success); +} + +/* Charts (hand-rolled SVG) */ +.chart { + width: 100%; +} + +.chart__svg { + display: block; + width: 100%; + height: 180px; +} + +.bar-chart__bar--success { + fill: var(--color-accent); +} + +.bar-chart__bar--error { + fill: var(--color-danger); +} + +.bar-chart__hit, +.sparkline__hit { + fill: transparent; +} + +.bar-chart__group:hover .bar-chart__bar { + opacity: 0.75; +} + +.sparkline__line { + fill: none; + stroke: var(--color-accent); + stroke-width: 2px; +} + +.sparkline__area { + fill: var(--color-accent); + opacity: 0.12; +} + +/* Chart legend */ +.chart__legend { + display: flex; + gap: 1.25rem; + margin-top: 0.75rem; + font-size: var(--text-xs); + color: var(--color-text-muted); +} + +.chart__legend-item { + display: flex; + align-items: center; + gap: 0.4rem; +} + +.chart__legend-swatch { + width: 10px; + height: 10px; + border-radius: 2px; +} + +.chart__legend-swatch--success { + background: var(--color-accent); +} + +.chart__legend-swatch--error { + background: var(--color-danger); +} + +.metrics-empty { + text-align: center; + color: var(--color-text-muted); + padding: 2rem 1rem; +} diff --git a/frontend/js/api.js b/frontend/js/api.js index 3997c14..c85f95b 100644 --- a/frontend/js/api.js +++ b/frontend/js/api.js @@ -283,6 +283,11 @@ const EMAIL_REQUEST_FIELDS = ` `; const NEXT_RUN_FIELDS = `hasSchedule cronSchedule cronStatus isPaused nextRun nextRunHuman`; +const METRICS_FIELDS = ` + summary { count errorCount errorRate avgDurationMs maxDurationMs } + buckets { bucketStart count errorCount avgDurationMs maxDurationMs } + granularity +`; const TOKEN_FIELDS = `id name createdAt lastUsed revoked`; const DIFF_FIELDS = `oldVersion newVersion lines { lineType oldLine newLine content }`; @@ -459,6 +464,32 @@ export const API = { pagination: data.executions.pageInfo, })), + /** + * Gets a function (header fields) together with its aggregated execution + * metrics over the half-open window [from, to) (unix seconds) in one + * round-trip. Used by the metrics view on load and on range changes. + * @param {string} id - Function ID + * @param {number} from - Window start (unix seconds, inclusive) + * @param {number} to - Window end (unix seconds, exclusive) + * @param {"hour"|"day"} granularity - Bucket granularity + * @returns {Promise<{func: LunarFunction, metrics: Object}>} + */ + getWithMetrics: (id, from, to, granularity) => + gqlRequest( + `query ($id: ID!, $from: Int!, $to: Int!, $granularity: MetricGranularity!) { + function(id: $id) { + ${FUNCTION_SUMMARY_FIELDS} + metrics(from: $from, to: $to, granularity: $granularity) { + ${METRICS_FIELDS} + } + } + }`, + { id, from, to, granularity }, + ).then((data) => ({ + func: mapFunction(data.function), + metrics: data.function ? data.function.metrics : null, + })), + /** * Creates a new function. * @param {Object} data - Function data diff --git a/frontend/js/app.js b/frontend/js/app.js index e744be4..5afceca 100644 --- a/frontend/js/app.js +++ b/frontend/js/app.js @@ -16,6 +16,7 @@ import { FunctionCreate } from "./views/function-create.js"; import { FunctionCode } from "./views/function-code.js"; import { FunctionVersions } from "./views/function-versions.js"; import { FunctionExecutions } from "./views/function-executions.js"; +import { FunctionMetrics } from "./views/function-metrics.js"; import { FunctionSettings } from "./views/function-settings.js"; import { FunctionTest } from "./views/function-test.js"; import { FunctionData } from "./views/function-data.js"; @@ -108,6 +109,14 @@ m.route(document.getElementById("app"), "/functions", { m(FunctionExecutions, { ...vnode.attrs, key: vnode.attrs.id }), ), }, + "/functions/:id/metrics": { + render: (vnode) => + m( + Layout, + { breadcrumbKey: "tabs.metrics" }, + m(FunctionMetrics, { ...vnode.attrs, key: vnode.attrs.id }), + ), + }, "/functions/:id/settings": { render: (vnode) => m( diff --git a/frontend/js/components/command-palette.js b/frontend/js/components/command-palette.js index b6b246e..56ec154 100644 --- a/frontend/js/components/command-palette.js +++ b/frontend/js/components/command-palette.js @@ -212,6 +212,15 @@ export const CommandPalette = { id: func.id, disabled: func.disabled, }); + functionItems.push({ + type: "action", + label: `${func.name} → ${t("tabs.metrics")}`, + description: t("commandPalette.actions.viewMetrics"), + path: paths.functionMetrics(func.id), + icon: "chartBar", + id: func.id, + disabled: func.disabled, + }); functionItems.push({ type: "action", label: `${func.name} → ${t("tabs.settings")}`, diff --git a/frontend/js/components/metrics.js b/frontend/js/components/metrics.js new file mode 100644 index 0000000..d8c8b91 --- /dev/null +++ b/frontend/js/components/metrics.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Metric visualization components for the function metrics + * dashboard. All charts are hand-rolled inline SVG (rendered through Mithril's + * hyperscript) so the dashboard needs no charting dependency. They are + * intentionally small and presentational — callers pass already-aggregated, + * display-ready data. + */ + +/** + * A single summary statistic: a big number with a label and optional sublabel. + * @type {Object} + */ +export const MetricCard = { + /** + * @param {Object} vnode - Mithril vnode + * @param {string} vnode.attrs.label - Stat label (e.g. "Total executions") + * @param {string|number} vnode.attrs.value - The headline value + * @param {string} [vnode.attrs.sublabel] - Optional secondary line + * @param {"default"|"success"|"danger"} [vnode.attrs.variant="default"] - Accent + * @returns {Object} Mithril vnode + */ + view(vnode) { + const { label, value, sublabel, variant = "default" } = vnode.attrs; + return m(`.metric-card.metric-card--${variant}`, [ + m(".metric-card__label", label), + m(".metric-card__value", String(value)), + sublabel ? m(".metric-card__sub", sublabel) : null, + ]); + }, +}; + +// Shared chart geometry. The SVG uses an abstract coordinate space and is +// stretched to its container width via CSS (preserveAspectRatio="none"), so the +// absolute numbers here only set proportions, not pixels. +const CHART_HEIGHT = 100; +const STEP = 10; // horizontal space allotted to each data point +const BAR_WIDTH = 7; + +/** + * A vertical bar chart of execution volume over time. Each bar is split into a + * success portion (bottom) and an error portion (top) so volume and error + * spikes both read at a glance. Hovering a bar shows its native SVG tooltip. + * @type {Object} + */ +export const BarChart = { + /** + * @param {Object} vnode - Mithril vnode + * @param {Array<{count:number,errorCount:number,title:string}>} vnode.attrs.bars + * @returns {Object} Mithril vnode + */ + view(vnode) { + const bars = vnode.attrs.bars || []; + const maxCount = Math.max(1, ...bars.map((b) => b.count)); + const width = Math.max(bars.length * STEP, STEP); + + return m(".chart.bar-chart", [ + m( + "svg.chart__svg", + { + viewBox: `0 0 ${width} ${CHART_HEIGHT}`, + preserveAspectRatio: "none", + role: "img", + }, + bars.map((b, i) => { + const totalH = (b.count / maxCount) * CHART_HEIGHT; + const errorH = (b.errorCount / maxCount) * CHART_HEIGHT; + const successH = totalH - errorH; + const x = i * STEP + (STEP - BAR_WIDTH) / 2; + return m("g.bar-chart__group", [ + // Success portion (bottom of the bar). + successH > 0 + ? m("rect.bar-chart__bar.bar-chart__bar--success", { + x, + y: CHART_HEIGHT - successH, + width: BAR_WIDTH, + height: successH, + }) + : null, + // Error portion, stacked on top. + errorH > 0 + ? m("rect.bar-chart__bar.bar-chart__bar--error", { + x, + y: CHART_HEIGHT - totalH, + width: BAR_WIDTH, + height: errorH, + }) + : null, + // Invisible full-height hit area so the tooltip works even for + // empty buckets and tiny bars. + m("rect.bar-chart__hit", { + x: i * STEP, + y: 0, + width: STEP, + height: CHART_HEIGHT, + }, m("title", b.title)), + ]); + }), + ), + ]); + }, +}; + +/** + * A compact line chart (sparkline) of a single series over time, e.g. average + * duration. Uses a non-scaling stroke so the line stays crisp regardless of how + * far the SVG is stretched. + * @type {Object} + */ +export const Sparkline = { + /** + * @param {Object} vnode - Mithril vnode + * @param {Array<{value:number,title:string}>} vnode.attrs.points + * @returns {Object} Mithril vnode + */ + view(vnode) { + const points = vnode.attrs.points || []; + const maxVal = Math.max(1, ...points.map((p) => p.value)); + const width = Math.max((points.length - 1) * STEP, STEP); + + const coords = points.map((p, i) => { + const x = i * STEP; + const y = CHART_HEIGHT - (p.value / maxVal) * CHART_HEIGHT; + return [x, y]; + }); + + const line = coords.map(([x, y]) => `${x},${y}`).join(" "); + // Close the area down to the baseline for a subtle fill. + const area = coords.length > 0 + ? `${coords[0][0]},${CHART_HEIGHT} ${line} ${ + coords[coords.length - 1][0] + },${CHART_HEIGHT}` + : ""; + + return m(".chart.sparkline", [ + m( + "svg.chart__svg", + { + viewBox: `0 0 ${width} ${CHART_HEIGHT}`, + preserveAspectRatio: "none", + role: "img", + }, + [ + coords.length > 0 + ? m("polygon.sparkline__area", { points: area }) + : null, + coords.length > 0 + ? m("polyline.sparkline__line", { + points: line, + "vector-effect": "non-scaling-stroke", + }) + : null, + // Per-point hover targets for tooltips. + points.map((p, i) => + m("rect.sparkline__hit", { + x: i * STEP - STEP / 2, + y: 0, + width: STEP, + height: CHART_HEIGHT, + }, m("title", p.title)) + ), + ], + ), + ]); + }, +}; diff --git a/frontend/js/i18n/locales/en.js b/frontend/js/i18n/locales/en.js index 81cd945..a927b0c 100644 --- a/frontend/js/i18n/locales/en.js +++ b/frontend/js/i18n/locales/en.js @@ -72,6 +72,7 @@ export default { code: "Code", versions: "Versions", executions: "Executions", + metrics: "Metrics", settings: "Settings", test: "Test", data: "KV Store", @@ -201,6 +202,32 @@ export default { }, }, + // Metrics dashboard + metrics: { + title: "Metrics", + rangeLabel: "Time range", + range: { + "24h": "24h", + "7d": "7d", + "30d": "30d", + }, + totalExecutions: "Total executions", + errorRate: "Error rate", + errorCount: "{{count}} errored", + avgDuration: "Avg duration", + maxDuration: "Max duration", + volumeTitle: "Executions over time", + durationTitle: "Average duration over time", + legend: { + success: "Success", + error: "Error", + }, + bucketTooltip: "{{time}} · {{count}} executions, {{errors}} errors", + durationTooltip: "{{time}} · {{value}}", + emptyState: + "No metrics in this range yet. Once this function runs, its metrics will appear here.", + }, + // Test page test: { response: "Response", @@ -226,6 +253,7 @@ export default { goToCode: "Go to Code", viewVersions: "View version history", viewExecutions: "View execution logs", + viewMetrics: "View metrics", configureFunction: "Configure function", testFunction: "Test function", viewClients: "View connected clients", diff --git a/frontend/js/i18n/locales/pt-BR.js b/frontend/js/i18n/locales/pt-BR.js index 4247c06..8d47d7b 100644 --- a/frontend/js/i18n/locales/pt-BR.js +++ b/frontend/js/i18n/locales/pt-BR.js @@ -73,6 +73,7 @@ export default { code: "Código", versions: "Versões", executions: "Execuções", + metrics: "Métricas", settings: "Configurações", test: "Teste", data: "Dados Chave-Valor", @@ -203,6 +204,32 @@ export default { }, }, + // Metrics dashboard + metrics: { + title: "Métricas", + rangeLabel: "Período", + range: { + "24h": "24h", + "7d": "7d", + "30d": "30d", + }, + totalExecutions: "Total de execuções", + errorRate: "Taxa de erro", + errorCount: "{{count}} com erro", + avgDuration: "Duração média", + maxDuration: "Duração máxima", + volumeTitle: "Execuções ao longo do tempo", + durationTitle: "Duração média ao longo do tempo", + legend: { + success: "Sucesso", + error: "Erro", + }, + bucketTooltip: "{{time}} · {{count}} execuções, {{errors}} erros", + durationTooltip: "{{time}} · {{value}}", + emptyState: + "Nenhuma métrica neste período ainda. Assim que esta função executar, suas métricas aparecerão aqui.", + }, + // Test page test: { response: "Resposta", @@ -228,6 +255,7 @@ export default { goToCode: "Ir para Código", viewVersions: "Ver histórico de versões", viewExecutions: "Ver logs de execução", + viewMetrics: "Ver métricas", configureFunction: "Configurar função", testFunction: "Testar função", viewClients: "Ver clientes conectados", diff --git a/frontend/js/routes.js b/frontend/js/routes.js index 642f8cc..77f1651 100644 --- a/frontend/js/routes.js +++ b/frontend/js/routes.js @@ -45,6 +45,13 @@ export const routes = { */ functionExecutions: (id) => `#!/functions/${id}/executions`, + /** + * Function metrics page. + * @param {string} id - Function ID + * @returns {string} Route URL + */ + functionMetrics: (id) => `#!/functions/${id}/metrics`, + /** * Function settings page. * @param {string} id - Function ID @@ -156,6 +163,13 @@ export const paths = { */ functionExecutions: (id) => `/functions/${id}/executions`, + /** + * Function metrics page. + * @param {string} id - Function ID + * @returns {string} Path + */ + functionMetrics: (id) => `/functions/${id}/metrics`, + /** * Function settings page. * @param {string} id - Function ID diff --git a/frontend/js/utils.js b/frontend/js/utils.js index 1650aed..8c07464 100644 --- a/frontend/js/utils.js +++ b/frontend/js/utils.js @@ -29,6 +29,11 @@ export const getFunctionTabs = (funcId) => [ label: t("tabs.executions"), href: routes.functionExecutions(funcId), }, + { + id: "metrics", + label: t("tabs.metrics"), + href: routes.functionMetrics(funcId), + }, { id: "data", label: t("tabs.data"), href: routes.functionData(funcId) }, { id: "test", label: t("tabs.test"), href: routes.functionTest(funcId) }, { diff --git a/frontend/js/views/function-metrics.js b/frontend/js/views/function-metrics.js new file mode 100644 index 0000000..239726c --- /dev/null +++ b/frontend/js/views/function-metrics.js @@ -0,0 +1,321 @@ +/** + * @fileoverview Function metrics view: a per-function dashboard of execution + * count, error rate, and duration, trended over a selectable time range. Data + * comes from pre-aggregated metric buckets (see the GraphQL Function.metrics + * field), so it survives the much shorter execution-retention window. + */ + +import { icons } from "../icons.js"; +import { API } from "../api.js"; +import { formatUnixTimestamp, getFunctionTabs } from "../utils.js"; +import { routes } from "../routes.js"; +import { BackButton } from "../components/button.js"; +import { Card, CardContent, CardHeader } from "../components/card.js"; +import { + Badge, + BadgeSize, + BadgeVariant, + IDBadge, + StatusBadge, +} from "../components/badge.js"; +import { TabContent, Tabs } from "../components/tabs.js"; +import { BarChart, MetricCard, Sparkline } from "../components/metrics.js"; +import { t } from "../i18n/index.js"; + +/** + * @typedef {import('../types.js').LunarFunction} LunarFunction + */ + +const DAY = 24 * 60 * 60; +const HOUR = 60 * 60; + +/** + * Selectable time ranges. Each maps to a window length, the granularity the + * buckets are aggregated at, and the bucket size in seconds (used both for the + * GraphQL query and for zero-filling gaps in the series client-side). + * @type {Object.} + */ +const RANGES = { + "24h": { rangeSeconds: 24 * HOUR, granularity: "hour", bucketSeconds: HOUR }, + "7d": { rangeSeconds: 7 * DAY, granularity: "day", bucketSeconds: DAY }, + "30d": { rangeSeconds: 30 * DAY, granularity: "day", bucketSeconds: DAY }, +}; + +/** Formats a millisecond duration for display. */ +const formatMs = (ms) => { + if (ms == null) return t("common.na"); + if (ms >= 1000) return `${(ms / 1000).toFixed(2)} s`; + return `${Math.round(ms)} ms`; +}; + +/** Formats a 0–1 ratio as a percentage. */ +const formatPct = (rate) => `${(rate * 100).toFixed(1)}%`; + +/** Formats an integer with thousands separators. */ +const formatInt = (n) => Number(n || 0).toLocaleString(); + +/** + * Function metrics view component. + * @type {Object} + */ +export const FunctionMetrics = { + /** @type {LunarFunction|null} */ + func: null, + /** @type {Object|null} Raw metrics payload from the API. */ + metrics: null, + /** @type {Array} Zero-filled time series for the charts. */ + series: [], + /** @type {boolean} */ + loading: true, + /** @type {string} Active range key into RANGES. */ + range: "7d", + + oninit: (vnode) => { + FunctionMetrics.loadData(vnode.attrs.id); + }, + + /** + * Loads the function and its metrics for the active range. + * @param {string} id - Function ID + * @returns {Promise} + */ + loadData: async (id) => { + FunctionMetrics.loading = true; + const preset = RANGES[FunctionMetrics.range]; + const now = Math.floor(Date.now() / 1000); + // Align the window start to a bucket boundary so the from/to we query match + // the keys the server groups by (integer division of unix seconds). + const from = + Math.floor((now - preset.rangeSeconds) / preset.bucketSeconds) * + preset.bucketSeconds; + try { + const { func, metrics } = await API.functions.getWithMetrics( + id, + from, + now, + preset.granularity, + ); + FunctionMetrics.func = func; + FunctionMetrics.metrics = metrics; + FunctionMetrics.series = FunctionMetrics.buildSeries( + metrics, + from, + now, + preset.bucketSeconds, + ); + } catch (e) { + console.error("Failed to load metrics:", e); + } finally { + FunctionMetrics.loading = false; + m.redraw(); + } + }, + + /** + * Expands the sparse bucket list returned by the API into a dense, ordered + * series covering every bucket in [from, to), filling gaps (hours/days with no + * executions) with zeros so the charts have a continuous time axis. + * @param {Object} metrics - API metrics payload + * @param {number} from - Window start (unix seconds, bucket-aligned) + * @param {number} to - Window end (unix seconds) + * @param {number} bucketSeconds - Bucket size + * @returns {Array} Dense series, oldest first + */ + buildSeries: (metrics, from, to, bucketSeconds) => { + const byStart = {}; + ((metrics && metrics.buckets) || []).forEach((b) => { + byStart[b.bucketStart] = b; + }); + const series = []; + for (let s = from; s < to; s += bucketSeconds) { + const b = byStart[s]; + series.push({ + start: s, + count: b ? b.count : 0, + errorCount: b ? b.errorCount : 0, + avgDurationMs: b ? b.avgDurationMs : 0, + }); + } + return series; + }, + + /** + * Switches the active range and reloads. + * @param {string} range - Range key into RANGES + */ + selectRange: (range) => { + if (range === FunctionMetrics.range) return; + FunctionMetrics.range = range; + FunctionMetrics.loadData(FunctionMetrics.func.id); + }, + + /** + * Renders the range selector segmented control. + * @returns {Object} Mithril vnode + */ + rangeSelector: () => + m( + ".metrics-range", + { role: "group", "aria-label": t("metrics.rangeLabel") }, + Object.keys(RANGES).map((key) => + m( + "button.metrics-range__btn", + { + class: key === FunctionMetrics.range + ? "metrics-range__btn--active" + : "", + onclick: () => FunctionMetrics.selectRange(key), + }, + t(`metrics.range.${key}`), + ) + ), + ), + + /** + * Renders the function metrics view. + * @returns {Object} Mithril vnode + */ + view: () => { + if (FunctionMetrics.loading && !FunctionMetrics.func) { + return m(".loading", [ + m.trust(icons.spinner()), + m("p", t("functions.loadingFunction")), + ]); + } + + if (!FunctionMetrics.func) { + return m( + ".fade-in", + m(Card, m(CardContent, t("common.functionNotFound"))), + ); + } + + const func = FunctionMetrics.func; + const metrics = FunctionMetrics.metrics; + const summary = (metrics && metrics.summary) || { + count: 0, + errorCount: 0, + errorRate: 0, + avgDurationMs: 0, + maxDurationMs: 0, + }; + const granularity = (metrics && metrics.granularity) || + RANGES[FunctionMetrics.range].granularity; + const tsFormat = granularity === "hour" ? "datetime" : "date"; + const hasData = summary.count > 0; + + return m(".fade-in", [ + // Header (mirrors the other function detail tabs). + m(".function-details-header", [ + m(".function-details-left", [ + m(BackButton, { href: routes.functions() }), + m(".function-details-divider"), + m(".function-details-info", [ + m("h1.function-details-title", [ + func.name, + m(IDBadge, { id: func.id }), + m( + Badge, + { + variant: BadgeVariant.OUTLINE, + size: BadgeSize.SM, + mono: true, + }, + `v${func.active_version.version}`, + ), + ]), + m( + "p.function-details-description", + func.description || t("common.noDescription"), + ), + ]), + ]), + m(".function-details-actions", [ + m(StatusBadge, { enabled: !func.disabled, glow: true }), + ]), + ]), + + m(Tabs, { tabs: getFunctionTabs(func.id), activeTab: "metrics" }), + + m(TabContent, [ + m(".metrics-tab-container", [ + // Range selector. + m(".metrics-toolbar", [ + m("h2.metrics-toolbar__title", t("metrics.title")), + FunctionMetrics.rangeSelector(), + ]), + + // Summary cards. + m(".metrics-summary", [ + m(MetricCard, { + label: t("metrics.totalExecutions"), + value: formatInt(summary.count), + }), + m(MetricCard, { + label: t("metrics.errorRate"), + value: formatPct(summary.errorRate), + sublabel: t("metrics.errorCount", { count: summary.errorCount }), + variant: summary.errorCount > 0 ? "danger" : "success", + }), + m(MetricCard, { + label: t("metrics.avgDuration"), + value: formatMs(summary.avgDurationMs), + }), + m(MetricCard, { + label: t("metrics.maxDuration"), + value: formatMs(summary.maxDurationMs), + }), + ]), + + // Charts, or an empty state when nothing has run in the window. + hasData + ? [ + m(Card, [ + m(CardHeader, { title: t("metrics.volumeTitle") }), + m(CardContent, [ + m(BarChart, { + bars: FunctionMetrics.series.map((b) => ({ + count: b.count, + errorCount: b.errorCount, + title: t("metrics.bucketTooltip", { + time: formatUnixTimestamp(b.start, tsFormat), + count: b.count, + errors: b.errorCount, + }), + })), + }), + m(".chart__legend", [ + m(".chart__legend-item", [ + m(".chart__legend-swatch.chart__legend-swatch--success"), + t("metrics.legend.success"), + ]), + m(".chart__legend-item", [ + m(".chart__legend-swatch.chart__legend-swatch--error"), + t("metrics.legend.error"), + ]), + ]), + ]), + ]), + m(Card, [ + m(CardHeader, { title: t("metrics.durationTitle") }), + m(CardContent, [ + m(Sparkline, { + points: FunctionMetrics.series.map((b) => ({ + value: b.avgDurationMs, + title: t("metrics.durationTooltip", { + time: formatUnixTimestamp(b.start, tsFormat), + value: formatMs(b.avgDurationMs), + }), + })), + }), + ]), + ]), + ] + : m(Card, [ + m(CardContent, m(".metrics-empty", t("metrics.emptyState"))), + ]), + ]), + ]), + ]); + }, +}; diff --git a/frontend/js/views/preview.js b/frontend/js/views/preview.js index 68aa314..8daa396 100644 --- a/frontend/js/views/preview.js +++ b/frontend/js/views/preview.js @@ -75,6 +75,7 @@ import { AIRequestViewer } from "../components/ai-request-viewer.js"; import { EmailRequestViewer } from "../components/email-request-viewer.js"; import { CodeEditor } from "../components/code-editor.js"; import { CodeDisplay } from "../components/code-display.js"; +import { BarChart, MetricCard, Sparkline } from "../components/metrics.js"; /** * @typedef {import('../components/env-editor.js').EnvVar} EnvVar @@ -182,6 +183,7 @@ export const Preview = { "ai-request-viewer", "email-request-viewer", "code-display", + "metrics", ], /** @@ -267,6 +269,8 @@ export const Preview = { return Preview.renderEmailRequestViewer(); case "code-display": return Preview.renderCodeDisplay(); + case "metrics": + return Preview.renderMetrics(); default: return m("p", "Component not found"); } @@ -1307,4 +1311,77 @@ end`; ]), ]); }, + + /** + * Renders metric visualization component previews (the function metrics + * dashboard primitives). + * @returns {Object} Mithril vnode + */ + renderMetrics: () => { + const bars = [ + { count: 120, errorCount: 2, title: "Mon · 120 executions, 2 errors" }, + { count: 98, errorCount: 0, title: "Tue · 98 executions, 0 errors" }, + { count: 140, errorCount: 9, title: "Wed · 140 executions, 9 errors" }, + { count: 0, errorCount: 0, title: "Thu · 0 executions, 0 errors" }, + { count: 76, errorCount: 1, title: "Fri · 76 executions, 1 error" }, + { count: 110, errorCount: 3, title: "Sat · 110 executions, 3 errors" }, + { count: 134, errorCount: 0, title: "Sun · 134 executions, 0 errors" }, + ]; + const points = [ + { value: 41, title: "Mon · 41 ms" }, + { value: 38, title: "Tue · 38 ms" }, + { value: 55, title: "Wed · 55 ms" }, + { value: 0, title: "Thu · 0 ms" }, + { value: 47, title: "Fri · 47 ms" }, + { value: 52, title: "Sat · 52 ms" }, + { value: 44, title: "Sun · 44 ms" }, + ]; + + return m(".preview-section", [ + m("h3", "Metric Cards"), + m(".metrics-summary", { style: "margin-bottom: 1.5rem;" }, [ + m(MetricCard, { label: "Total executions", value: "12,403" }), + m(MetricCard, { + label: "Error rate", + value: "1.8%", + sublabel: "224 errored", + variant: "danger", + }), + m(MetricCard, { + label: "Success rate", + value: "98.2%", + sublabel: "12,179 succeeded", + variant: "success", + }), + m(MetricCard, { label: "Avg duration", value: "43 ms" }), + ]), + + m("h3", "Bar Chart (volume with errors)"), + m("p.preview-description", "Hover a bar to see its tooltip."), + m(Card, { style: "max-width: 600px; margin-bottom: 1.5rem;" }, [ + m(CardHeader, { title: "Executions over time" }), + m(CardContent, [ + m(BarChart, { bars }), + m(".chart__legend", [ + m(".chart__legend-item", [ + m(".chart__legend-swatch.chart__legend-swatch--success"), + "Success", + ]), + m(".chart__legend-item", [ + m(".chart__legend-swatch.chart__legend-swatch--error"), + "Error", + ]), + ]), + ]), + ]), + + m("h3", "Sparkline (average duration)"), + m(Card, { style: "max-width: 600px;" }, [ + m(CardHeader, { title: "Average duration over time" }), + m(CardContent, [ + m(Sparkline, { points }), + ]), + ]), + ]); + }, }; diff --git a/frontend/test/SpecRunner.html b/frontend/test/SpecRunner.html index f9460c4..c928089 100644 --- a/frontend/test/SpecRunner.html +++ b/frontend/test/SpecRunner.html @@ -167,6 +167,7 @@ +