Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@ tmp/
.idea
.DS_Store
logo/logo.af~lock~

# Playwright MCP scratch (browser snapshots/screenshots)
.playwright-mcp/

# Grill/design glossary (kept local, not tracked)
CONTEXT.md
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions docs/adr/0014-metrics-rollup-table.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 5 additions & 1 deletion e2e/godog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,12 @@ func TestMain(m *testing.M) {
}

// InitializeTestSuite wires suite-level lifecycle hooks. The shared headless
// Chrome process is torn down after every scenario has run.
// Chrome process is warmed up before the first scenario and torn down after the
// last one has run.
func InitializeTestSuite(ctx *godog.TestSuiteContext) {
ctx.BeforeSuite(func() {
warmUpBrowser()
})
ctx.AfterSuite(func() {
shutdownAllocator()
})
Expand Down
17 changes: 17 additions & 0 deletions e2e/world_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,23 @@ func shutdownAllocator() {
}
}

// warmUpBrowser launches the shared headless Chrome process and performs a
// trivial navigation before any scenario runs. The first Chrome launch on a cold
// CI runner can take well over a minute; paying that one-time cost here — outside
// any scenario's browserTimeout budget — keeps it from being charged to the
// first scenario, where it has caused flaky "context deadline exceeded" failures
// during sign-in. Errors are intentionally ignored: if warmup fails, the first
// scenario simply pays the cold start as before, so this can only help.
func warmUpBrowser() {
tabCtx, tabCancel := chromedp.NewContext(sharedAllocator())
defer tabCancel()
// A generous, one-time budget — deliberately larger than browserTimeout so the
// cold start itself never trips a deadline here.
timedCtx, timeoutCancel := context.WithTimeout(tabCtx, 3*time.Minute)
defer timeoutCancel()
_ = chromedp.Run(timedCtx, chromedp.Navigate("about:blank"))
}

// world is the per-scenario state shared between steps. A fresh world is created
// for every scenario, so there is no cross-scenario leakage.
type world struct {
Expand Down
180 changes: 180 additions & 0 deletions frontend/css/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
31 changes: 31 additions & 0 deletions frontend/js/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }`;
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions frontend/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions frontend/js/components/command-palette.js
Original file line number Diff line number Diff line change
Expand Up @@ -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")}`,
Expand Down
Loading
Loading