nsh-o11y 0.1.0 · NSH 0.7+

Documentation

Observability charts for Native Shell: metrics, logs, traces and profiles, written in TSX and drawn on NSH's native <Canvas>, with an optional Rust backend for very large series. They run on every NSH platform: iOS, Android, desktop and the web.

Install

nsh-o11y is an nshm, an NSH module published as a crate. Add it to an app with the nsh CLI. Run this in the app's directory (or below it); it needs NSH 0.7 or later.

nsh add nsh-o11y

That lists "nsh-o11y": "^0.1.0" under "dependencies" in the app's nsh.json and pins the resolved version in nsh.lock. Pin a version, or take it from Git instead:

nsh add nsh-o11y@0.1                        # a version range from crates.io
nsh add github:JetSquirrel/nsh-o11y         # the newest version tag on GitHub
nsh add --path ../nsh-o11y                  # a local checkout, while you work on it
nsh upgrade nsh-o11y                        # the newest version nsh.json accepts
nsh --version                               # 0.7.0 or later; `nsh update` if not

The crate carries Rust (the optional backend), so the app builds with the Rust toolchain from then on. If you don't register the backend, the charts run on TypeScript alone and that Rust code isn't called.

Quick start

A live latency chart with three percentiles, an SLO line and a deploy marker:

import { mount, View } from "nsh";
import { TimeSeriesChart, createChartSync, createTimeSeries } from "nsh-o11y";

const latency = createTimeSeries({ series: 3, maxPoints: 100_000 });
setInterval(() => latency.append(Date.now(), [p50(), p95(), p99()]), 1000);

function App() {
  const sync = createChartSync();
  return (
    <View style={{ flex: 1, gap: 12, padding: 16 }}>
      <TimeSeriesChart
        title="Latency"
        data={latency}
        series={[{ label: "p50" }, { label: "p95" }, { label: "p99", width: 1 }]}
        unit="ms"
        softMin={0}
        window={15 * 60_000}
        thresholds={[{ value: 250, label: "SLO", color: "#e34948" }]}
        annotations={[{ time: deployedAt, label: "deploy v2.14" }]}
        sync={sync}
        style={{ flex: 1 }}
      />
    </View>
  );
}

mount(App);

Run it with nsh run, or nsh run --target web for the browser. The live demo is the repo's example/ app: a service dashboard with every component on this page.

Concepts

  • Stores and views. Data lives in a store (createTimeSeries, LogStore, HeatmapStore) that you append to. A component given the store redraws when it changes. Every store is plain TypeScript with no NSH imports, so it also works headless.
  • Times are milliseconds, usually Date.now(). Span times can be epoch or relative, since only differences are shown.
  • Level of detail. A time series keeps a min/max pyramid, and each frame draws the first, min, max and last sample of every pixel column. A frame costs about the same for 10 million samples as for 10 thousand, and one-sample spikes are never lost.
  • Two layers. Each chart draws its data on one canvas and its crosshair, hover and selection on another, so moving the pointer never redraws the data.
  • Shared look. Every component takes its colors from NSH's theme tokens, so light and dark mode follow the app. Override them with colors, fontFamily and fontSize (see Colors and fonts).
  • Accessible. Each chart has a screen-reader label that reads what is under the cursor, and keyboard navigation. Press a chart to give it the keyboard. The series palette is checked for color blindness.

All components also take the usual view props: style, class and testID (and most take accessibilityLabel). Those are left out of the tables below.

TimeSeriesChart

A line chart over time for metrics: millions of points, zooming, live data, many synced panels. data takes a store from createTimeSeries or plain arrays. Times are milliseconds and must not decrease, and NaN is a missing value.

<TimeSeriesChart
  data={{ x: times, ys: [cpu, mem] }}
  series={[{ label: "cpu", unit: "percent" }, { label: "memory", unit: "bytes", axis: "right" }]}
  unit="percent"
  y2={{ unit: "bytes", softMin: 0 }}
/>

Props

PropDefaultDescription
datarequiredA store from createTimeSeries (appended to live), or { x, ys } arrays.
seriesrequiredOne SeriesOptions per y column.
titleA title over the chart.
unit"short"The unit of the values, used on the axis and in the legend. See Units.
yMin / yMaxautoFixed ends of the y range (null: auto).
softMin / softMaxValues the auto range always includes: softMin={0} for rates and counts.
y2A second y axis on the right for series with axis: "right": { unit?, min?, max?, softMin?, softMax? }. It shows when a series is on it.
windowall dataLive: show the last window ms, following new samples.
thresholds{ value, color?, label?, dash?, axis? }[]: horizontal lines for SLOs and alert thresholds. dash defaults to [4, 4]; [] is solid.
annotations{ time, end?, label?, color? }[]: moments (deploys), or spans of time with end (incidents).
timeZone"local"Or "utc".
legendtrueA legend with each series' value at the cursor (or the newest). Pressing a series toggles it.
dragMode"zoom"What a mouse drag does: "zoom" (a box) or "pan". Shift-drag pans either way, and touch always pans.
syncA ChartSync for a shared crosshair and zoom.
controllerA ChartController to zoom, reset and export from code.
colors, fontFamily, fontSizetheme, "system-ui", 11See Colors and fonts.
onCursor(info)The cursor moved to a sample ({ index, time, values }) or left the chart (null).
onRangeChange(range)[x0, x1] after a zoom or pan; null when the chart follows the data again.

SeriesOptions

FieldDefaultDescription
labelrequiredThe series' name in the legend and readout.
colorpaletteThe palette's next color when unset.
width1.5Line width in points.
fillnoneFill under the line at this opacity (0 to 1); true is 0.12.
dashA dash pattern, as setLineDash takes it.
stepfalseHold each value until the next sample: counters, states.
spanGapsfalseDraw across missing values (NaN) instead of leaving a gap.
showtrueShown at first. The legend toggles it.
unitits axis'sIts own unit in the readout.
axis"left""right" puts it on the second axis, scaled by y2.

Interaction

drag
Zoom to the range drawn (or pan, with Shift or dragMode="pan")
wheel / pinch
Zoom around the pointer
Shift+wheel / swipe
Pan
double-click
Reset the zoom and follow the data again
← →
Step the cursor
+ -
Zoom in and out
Backspace
Go back one zoom
0
Reset

Time series stores

createTimeSeries makes a store. It is backed by Rust when the backend is registered, and by TypeScript otherwise; both have the same interface.

const ts = createTimeSeries({ series: 2, maxPoints: 1_000_000 });
ts.append(t, [a, b]);              // one sample
ts.append(times, [as, bs]);        // a batch: arrays or typed arrays
ts.setData(times, [as, bs]);       // replace everything
ts.clear();

ts.length();  ts.x(i);  ts.y(s, i);
ts.nearest(t);                     // index of the sample closest to t
ts.extent(s, i0, i1);              // min and max of series s over a range
ts.trace(s, { x0, x1, y0, y1, left, top, width, height });  // SVG path data for a viewport
OptionDefaultDescription
series1How many y columns.
capacitySamples to make room for at the start.
maxPointsunlimitedKeep at most this many samples, dropping the oldest. Drops happen in batches that shift the pyramid instead of rebuilding it, so the length can run up to an eighth over.

The TypeScript store fits about 2 million samples in NSH's 256 MB JS heap. The Rust store holds hundreds of millions.

Sync and controller

createChartSync

Pass one ChartSync to several charts (and heatmaps) to share the crosshair and, by default, the zoom.

const sync = createChartSync();                 // { zoom: false } shares only the crosshair
<TimeSeriesChart sync={sync} ... />
<Heatmap sync={sync} ... />
sync.reset();                                   // every linked chart back to following

createChartController

An imperative handle for one chart. Its getters are reactive signals.

const chart = createChartController();
// <TimeSeriesChart controller={chart} ... />

chart.range();  chart.following();  chart.cursor();   // reactive
chart.setRange(t0, t1);
chart.zoom(2);          // factor > 1 zooms in
chart.back();           // the previous zoom
chart.reset();
chart.toggleSeries(1);
const png = await chart.toImage({ scale: 2 });         // a Blob

toImage takes { width?, height?, scale?, background? }. The size defaults to the chart's own size, the scale (pixel density) to 2 and the background to the theme's. Lines are thinned per output pixel, so a 2× export keeps its detail.

Heatmap

A latency distribution over time. When p99 rises, percentile lines only show that it rose; a heatmap shows whether a second band of slow requests appeared or everything shifted up.

import { Heatmap, HeatmapStore } from "nsh-o11y";

const latency = new HeatmapStore({ step: 1000, min: 5, max: 5000, buckets: 48, maxColumns: 600 });
latency.add(Date.now(), requestDurationMs);       // one observation, or an array of them
latency.addExemplar({ time, value, id: traceId, error: true });

<Heatmap data={latency} unit="ms" window={5 * 60_000} sync={sync}
  onExemplarClick={(ex) => openTrace(ex.id)} style={{ flex: 1 }} />

Each column covers step ms. Each row is a bucket of values, log-spaced by default so milliseconds and seconds get equal room. A cell's color is its count on a log scale. Hover a cell to see its count, its share of the column and the column's percentiles. Columns narrower than 2 points are summed, so an hour of 1 s columns stays quick.

HeatmapStore

OptionDefaultDescription
step1000Column width in ms.
min / max1 / 10000The value range of the buckets. Values outside it go to the first or last bucket.
scale"log"Or "linear".
buckets40How many buckets.
maxColumnsunlimitedKeep at most this many columns, dropping the oldest.

Methods: add(t, values), addCounts(t, counts) for pre-bucketed histograms, addExemplar(ex), quantile(column, q), column(i), length(), clear().

Exemplars link cells to traces. An exemplar is { time, value, id, error?, attributes? }, and the store keeps the newest one per cell. Each shows as a diamond, red for errors. Where many would overlap, the errors and the slowest are kept, at least 12 points apart.

Props

PropDefaultDescription
datarequiredA HeatmapStore.
title
unit"ms"See Units.
windowallLive: the last window ms.
percentiles[0.5, 0.99]Lines over the cells at these quantiles; [] for none.
rampthemeThe color ramp's three stops, faint to strong.
legendtrueThe ramp and percentile key under the plot.
timeZone"local"
syncShares the crosshair with linked charts and follows their zoom.
exemplarstrueDraw the store's exemplars.
onExemplarClick(ex)An exemplar was pressed: open its trace.
colors, fontFamily, fontSizeSee Colors and fonts.

LogView

A log explorer: level toggles with counts, a search box, a stacked histogram of volume per level, and the lines in a virtualized list.

import { LogStore, LogView } from "nsh-o11y";

const logs = new LogStore({ maxEntries: 50_000 });
logs.append({ time: Date.now(), level: "error", message: "charge failed", service: "payment", traceId });

<LogView data={logs} window={5 * 60_000} onTraceClick={(id) => openTrace(id)} style={{ flex: 1 }} />

Drag across the histogram or tap a bar to narrow the list to that time, and double-tap to show everything again. Press a line to see its attributes and its trace link. The search matches the message, service and attributes, ignoring case. Lines can arrive slightly out of order, and the oldest are dropped past maxEntries. Live frames don't rescan the lines: level counts and histogram buckets are kept as running totals.

LogEntry

interface LogEntry {
  time: number;                                   // ms
  level: "trace" | "debug" | "info" | "warn" | "error" | "fatal";
  message: string;
  service?: string;
  traceId?: string;  spanId?: string;            // link the line to a trace
  attributes?: Record<string, string | number | boolean>;
}

Props

PropDefaultDescription
datarequiredA LogStore (appended to live) or a LogEntry[].
title
levelsallThe levels shown at first.
searchThe search text at first.
toolbartrueLevel toggles and the search box.
histogramtrueThe volume histogram.
histogramHeight96Its height in points.
order"newest"Newest line first, or "oldest".
windowallLive: the histogram shows the last window ms.
timeZone"local"
levelColorsColors per level, over the defaults (LOG_LEVEL_COLORS).
colors, fontFamily, fontSizeSee Colors and fonts.
onSelect(entry)A line was opened, or closed (null).
onTraceClick(traceId, entry)The trace link of an opened line was pressed.
onRangeChange(range)The list was narrowed to [t0, t1], or widened again (null).

LogStore

const logs = new LogStore({ maxEntries: 50_000 });
logs.append(entry);  logs.append(entries);  logs.setEntries(entries);  logs.clear();
const filter = { levels: ["warn", "error"], text: "timeout", from: t0, to: t1 };
logs.query(filter);                         // indexes of the matching lines, in time order
logs.levelCounts(filter);                   // { trace, debug, info, warn, error, fatal }
logs.histogram(t0, t1, 10_000, filter);     // { t0, step, buckets, counts[level], max }

TraceWaterfall

One trace's spans as a tree of bars over time.

import { TraceWaterfall, type Span } from "nsh-o11y";

const spans: Span[] = [
  { spanId: "a", name: "POST /checkout", service: "frontend", start: 0, duration: 84 },
  { spanId: "b", parentId: "a", name: "PaymentService.Charge", service: "payment", start: 31, duration: 41, status: "error" },
];
<TraceWaterfall spans={spans} onSelect={(span) => showDetails(span)} style={{ flex: 1 }} />

Each span gets a row, indented under its parent, with a bar colored by service. Error spans have a red edge, the critical path is underlined, and span events show as diamonds (red for exceptions). Above the time axis, an overview shows the whole trace with the visible range outlined. Only the rows in view are drawn, so a 50,000-span trace scrolls in about 3 ms a frame.

Span

interface Span {
  spanId: string;
  parentId?: string;                  // missing, or not in the trace: a root
  name: string;
  service: string;
  start: number;                      // ms, epoch or relative
  duration: number;                   // ms
  status?: "ok" | "error" | "unset";
  kind?: "server" | "client" | "internal" | "producer" | "consumer";
  attributes?: Record<string, string | number | boolean>;
  events?: { time: number; name: string; attributes?: Record<string, string | number | boolean> }[];
}

OpenTelemetry spans map onto this directly. Events named exception, or with "error" or "fail" in the name, are drawn red.

Props

PropDefaultDescription
spansrequiredA Span[], or a TraceModel made from them.
rowHeight22Row height in points.
labelWidth280The name column's width (at most 45% of the view).
minimaptrueThe trace overview above the time axis.
criticalPathtrueUnderline the critical path.
collapsedSpan ids folded at first.
selectedThe selected span id (controlled). Its row scrolls into view.
colors, fontFamily, fontSizeSee Colors and fonts.
onSelect(span)A span was selected, or the selection cleared (null).

Interaction

press a row
Select it; press its triangle to fold its children
drag the timeline
Zoom to the range drawn
Ctrl/⌘ + scroll
Zoom
scroll / Shift + scroll
Scroll the rows / pan
overview
Drag across it to zoom; tap to move there
double-click
Zoom out
↑ ↓
Select the previous or next span
← →
Fold or unfold
0
Zoom out

TraceComparison

Two traces of the same operation, compared call by call: a slow or failed trace next to a healthy one.

<TraceComparison a={healthySpans} b={slowSpans} aLabel="healthy" bLabel="this trace"
  onSelect={(row) => open(row.b)} style={{ flex: 1 }} />

Spans are matched by their position in the tree: the chain of service and name from the root, with repeated calls paired in order, so retries line up. Each row shows the baseline's bar in grey above the other trace's bar. The bar is red where the call got slower or is new, and blue where it got faster or is gone. Changes under 1 ms or 10% count as unchanged. The summary counts slower, faster, new and gone calls. "Changed calls only" in the legend hides the calls that stayed the same, unless something below them changed.

PropDefaultDescription
arequiredThe baseline: a healthy trace (Span[] or TraceModel).
brequiredThe trace to explain.
aLabel / bLabel"baseline" / "this trace"What the legend calls them.
rowHeightRow height in points.
labelWidth300The name column's width (at most 40% of the view).
changedOnlyfalseStart with only the changed calls (and the calls above them) shown.
colors, fontFamily, fontSizeSee Colors and fonts.
onSelect(row)A row was pressed: { a?, b?, depth, name, service, delta, ratio }.

Keyboard: ↑ ↓ walk the rows, Home and End go to the ends, ← → jump to the previous or next changed call, and Enter opens the row.

ServiceMap

The services that many traces pass through, and the calls between them.

<ServiceMap traces={recentTraces} selected={service()}
  onSelectedChange={({ selected }) => filterBy(selected)} style={{ flex: 1 }} />

A call from A to B is a span in service B whose parent is in service A. Services are laid out left to right: entry services first, each callee one column right of its deepest caller, and each column ordered to cross as few calls as possible. A call back to an earlier column (a cycle) is dashed and routed under the boxes. Each box shows the service's request rate, p95 latency and share of failures. An edge's width follows its call count. Services and calls whose failure share reaches errorThreshold are drawn in the error color.

PropDefaultDescription
tracesrequiredAn iterable of traces (each a Span[] or TraceModel), or a graph from serviceGraph(), built once.
selectedThe selected service by name (controlled); null for none.
errorThreshold0.01The failure share at which a service or edge turns red.
edgeLabelstrueWrite each edge's call rate on it where there is room.
colors, fontFamily, fontSizecolors.error sets the failure color.
onSelectedChange({ selected })A service was selected, or the selection cleared.

Keyboard: → goes to the busiest callee, ← to the busiest caller, ↑ ↓ move through the column, Home and End go to the first and last service, and Esc clears the selection. Hover a service to highlight its callers and callees; on touch screens, a tap shows its numbers.

FlameGraph

A CPU or allocation profile. Each frame is as wide as the samples spent in it and in the functions it calls.

import { FlameGraph, profileFromFolded } from "nsh-o11y";

const profile = profileFromFolded("main;handle;parse 42\nmain;handle;render 17\n");  // flamegraph.pl's format
<FlameGraph profile={profile} unit="short" style={{ flex: 1 }} />

// A diff: red where a frame's share grew since the baseline, blue where it shrank
<FlameGraph profile={after} baseline={before} />

Frames are colored by module, with the root at the top. Press a frame to zoom to it; its callers stay above, dimmed. Use the breadcrumbs, Esc or a double-click to zoom back out. Searching greys out frames that don't match and shows the share of samples that do. Frames narrower than a third of a point are never laid out, so very large profiles stay quick.

PropDefaultDescription
profilerequiredA ProfileNode, folded-stack text, or a nested { name, value?, children? } tree.
baselineA profile to compare with. Changes under a quarter of a point stay neutral (sampling noise), and the tooltip gives both shares.
unit"short""short" for samples, "ns" or "ms" for time, "bytes" for allocations.
direction"down"Root at the top (an icicle), or "up" for a classic flame.
rowHeight18Frame height in points.
colorBy"module"Or "name".
toolbartrueThe search box and the breadcrumbs to the zoomed frame.
highlightPick out frames whose name contains this text (controlled).
colors, fontFamily, fontSizeSee Colors and fonts.
onSelect(node)A frame was zoomed to (the root means zoomed out).

Keyboard: the arrows walk the frames (up to the caller, down to the biggest callee, sideways along a row), Enter zooms to the outlined frame, and Backspace goes up a level.

Loading profiles

profileFromFolded(text)                         // "a;b;c 42" lines
await profileFromFoldedAsync(text, { onProgress: (n) => ... })   // in slices, for huge files
profileFromStacks([{ frames: ["main", "handle"], value: 3 }])
profileFromTree({ name: "all", children: [...] })
diffProfiles(before, after)                     // what `baseline` does
topFunctions(root, 20)                          // self and total per function, recursion counted once
matchedValue(root, "parse")                     // samples in frames matching a search

NSH stops a single call into JS after 2 s. profileFromFoldedAsync parses in slices with a pause between them, so a profile too big for one call still loads.

SandwichView

One function between its callers and its callees. The callers are drawn as a flame growing up into the function, merged from every call site; the callees are its subtrees from every call, merged. Frames scattered across the full graph read as two trees.

<SandwichView profile={profile} fn="runtime.mallocgc" style={{ flex: 1 }} />
PropDefaultDescription
profilerequiredThe whole profile, as FlameGraph takes it.
fnrequiredThe function in the middle, by its frame name.
unit, rowHeight, colorByAs for FlameGraph.
colors, fontFamily, fontSizeSee Colors and fonts.
onSelect(node)A frame in either half was zoomed to.

sandwichProfile(root, name) returns both halves ({ callers, callees }) without drawing them.

Units

The unit prop formats axis labels, legends and tooltips.

UnitExampleFor
"none"1235Raw numbers
"short"1.23k, 3.4MCounts (SI prefixes)
"percent"42%Values from 0 to 100
"percentunit"42%Values from 0 to 1
"bytes"1.5 MiBMemory (IEC)
"decbytes"1.5 MBDisk and network (SI)
"bits"12 MbBandwidth
"ms", "s", "ns"250 ms, 1.2 sDurations
"reqps"120 req/sRequest rates
"ops"3.4k ops/sOperation rates
(v) => stringAnything else

formatValue(v, unit), formatTime and formatTimeFull are exported, so your own UI can match the charts.

Colors and fonts

Every component reads NSH's theme tokens, so light and dark mode follow the app. To override, pass colors:

<TimeSeriesChart
  colors={{ background: "#0b0d10", grid: "#1f242b", palette: ["#4cc9f0", "#f72585", "#b5e48c"] }}
  fontFamily="JetBrains Mono" fontSize={12}
  ... />
FieldDescription
backgroundFill behind the plot. Default transparent.
textTitles and values.
mutedAxis labels.
gridGrid lines.
cursorThe crosshair.
selectionThe drag-to-zoom box.
errorFailed calls and services. Default: the theme's destructive token.
paletteSeries colors in order. The defaults are PALETTE_LIGHT and PALETTE_DARK, checked for color blindness.

Rust backend

Register the backend once at startup, and every store made after that keeps its samples in Rust. Samples cross into Rust once, when they are appended, and each frame returns one SVG path per series.

import * as native from "nsh-o11y/native";
import { setNativeBackend, type NativeBackend } from "nsh-o11y";

setNativeBackend(native as unknown as NativeBackend);

Frames on big series get about 8× faster than with the TypeScript store in NSH's interpreted JS, and the store gets past the 256 MB JS heap. In NSH, a full view of 10 million samples takes 4.4 ms with Rust; the TypeScript store runs out of memory at that size. Both stores draw identical paths, and the tests check that.

As with any nshm, the crate builds with the app's dev profile. For an optimized build, copy the repo's .cargo/config.toml into your app.

Headless APIs

The data models and engines are plain TypeScript with no NSH imports. Use them in tests, on a server, or with any Canvas 2D context.

APIWhat it gives you
TimeSeries, ChartEngineThe store and the chart's viewport, auto-scale, zoom history and cursor.
renderPlot, renderOverlayDraw a chart onto any Ctx2D.
timeTicks, valueTicks, niceRangeAxis ticks on calendar-friendly steps.
LogStoreQueries, level counts and volume histograms.
new TraceModel(spans)Waterfall rows, each span's self time and the critical path.
compareTraces(a, b)The rows of a TraceComparison, from two TraceModels.
serviceGraph(traces)Services and edges with rates, p95 and failures.
HeatmapStoreBucketed observations and their quantiles.
profileFrom*, topFunctions, diffProfiles, sandwichProfileCall trees and their summaries.
import { TraceModel, compareTraces, serviceGraph } from "nsh-o11y";

const rows = compareTraces(new TraceModel(healthy), new TraceModel(slow));
const worst = rows.filter((r) => r.delta > 0).sort((x, y) => y.delta - x.delta)[0];
console.log(`${worst.service} ${worst.name}: +${worst.delta.toFixed(1)} ms`);

const graph = serviceGraph(lastHourOfTraces);   // pass to <ServiceMap traces={graph} /> to draw it

Performance numbers, the comparison with uPlot, ECharts, Chart.js, Plotly and Dygraphs, and how the engine works are on the home page and in the README.