@lntrn/web
v0.5.3
Published
Browser telemetry for Xeonr consoles: errors, reachability, web vitals and RPC spans as OTLP/HTTP JSON to Lantern's client ingest, and a reader for a client project's own telemetry (./read). Replaces Sentry.
Readme
@lntrn/web
Browser telemetry for Xeonr consoles, sent to Lantern's client ingest,
https://in.lntrn.dev (never a telemetry. host: those are on browser block
lists and home DNS filters). Published as @xeonr/telemetry-web up to 0.2.2
and as @lntrn/web from 0.3.0, with the same API; earlier versions defaulted
to https://in.prod.wtf (0.1.1–0.2.1) and telemetry.xeonr.io (0.1.0), which
Lantern has retired (LAN-326). It replaces Sentry: uncaught errors, failed and
timed-out requests, web vitals and one span per RPC, as OTLP/HTTP JSON, with
an offline buffer so a console that cannot reach us still reports once it
can. No runtime dependencies; the browser entry is ~9 KiB min+gzip.
Every console that mounts @xeonr/console-shell ≥ 0.7 already has it — the
shell's ConsoleProvider starts it. Use this package directly on a page
without the shell, or for the extra pieces below (your own Connect clients,
the Vite plugin).
Design: fleet observability plan §10.2; wire contract:
lantern/docs/WAVE4-client-ingest.md §7 (both in platform-docs).
Already on OpenTelemetry? Add this
Keep your SDK. @lntrn/web/otel gives the stock OpenTelemetry web SDK what
init() has: the ingest's preflight-free transport, the hide-time beacon,
the offline buffer, and the error, vitals and request instrumentation that
Lantern's Issues screen groups on.
import { context, logs, trace } from "@opentelemetry/api";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
import { LoggerProvider, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { LanternWeb } from "@lntrn/web/otel";
import { wrapFetch } from "@lntrn/web";
import { telemetryInterceptor } from "@lntrn/web/connect";
const lantern = new LanternWeb({ service: "functions-ui", namespace: "functions" }); // release: <meta name="lantern-release">
const resource = resourceFromAttributes(lantern.resourceAttributes());
const tracerProvider = new TracerProvider({
resource,
spanProcessors: [lantern.processor, new SimpleSpanProcessor({ exporter: lantern.spanExporter })],
});
const loggerProvider = new LoggerProvider({
resource,
processors: [lantern.processor, new SimpleLogRecordProcessor({ exporter: lantern.logRecordExporter })],
});
trace.setGlobalTracerProvider(tracerProvider);
logs.setGlobalLoggerProvider(loggerProvider);
registerInstrumentations({ instrumentations: lantern.instrumentations() }); // errors, web vitals
// Requests and RPCs as CLIENT spans from the global tracer, with traceparent
// on same-origin calls and client.request.failed records on failure:
const api = wrapFetch(fetch, lantern);
const transport = createConnectTransport({ baseUrl, interceptors: [telemetryInterceptor(lantern)] });
router.subscribe((path) => lantern.trackRoute(path)); // url.path, route_change, breadcrumbsWhat each piece is:
lantern.spanExporter/lantern.logRecordExporter(LanternSpanExporter,LanternLogRecordExporter): stockSpanExporterandLogRecordExporter.- They send as
init()does:?service=,text/plainwith no CORS preflight,credentials: "omit", keepalive,sendBeaconwhen the page is hidden, and the localStorage buffer while offline or refused. - They queue and batch themselves, so put a Simple processor in front of them, not a batching one.
- A record exported while the page is hidden is beaconed at once.
- They send as
lantern.processor(LanternProcessor): aSpanProcessorandLogRecordProcessor. It stampssession.id,url.pathand anything passed tolantern.setAttributes()on every span and record. A value the record already has is kept.lantern.instrumentations():LanternErrorInstrumentationandLanternWebVitalsInstrumentation.- The error instrumentation turns uncaught errors and unhandled rejections into
exceptionrecords, with the breadcrumb trail and top frame. - The vitals instrumentation sends LCP, INP, CLS, FCP and TTFB as
web_vitalrecords, pluspage_view. - Both satisfy the stock
Instrumentationinterface.
- The error instrumentation turns uncaught errors and unhandled rejections into
lanternitself is aTelemetryClient, so the package'swrapFetch, Connect interceptor and<TelemetryErrorBoundary client={lantern}>report through it. Its requests are OTel CLIENT spans from the global tracer, and propagation is the global propagator. Register a W3C one, as the stockregister()helpers do.lantern.resourceAttributes()is the resourceinit()sends: service name, version and namespace;service.instance.id, one per browser install; the repository and commit (vcs.repository.url.full,vcs.ref.head.revision), from therepositoryUrl/revisionoptions or the<meta>tags@lntrn/web/vitewrites from CI; and the browser.
@lntrn/web/otel imports only @opentelemetry/api at runtime. It is an optional peer dependency and the app's own copy is used. Everything else from OpenTelemetry is yours: @opentelemetry/sdk-trace and sdk-logs 3.0, resources 3.0, instrumentation 0.300. init() and the default entry stay SDK-free (pnpm size fails if that changes). The OTel path is opt-in for apps that already pay for the SDK.
Or use the stock exporters as they are. The ingest speaks plain OTLP/HTTP, so a stock OTLPTraceExporter({ url: "https://in.lntrn.dev/v1/traces?service=my-ui" }) works from a page whose Origin is on one of the client project's public-origin keys. It sends JSON, and the ingest answers the preflight. You get none of the above.
The parts of this package that don't depend on either client:
@lntrn/web/vite, the release and source-map plugin;@lntrn/web/read, the reader;traceIdFrom/TRACE_HEADER.
Install
pnpm add @lntrn/webStart it
import { init } from "@lntrn/web";
init({
service: "functions-ui", // the Lantern client project; default <meta name="lantern-service">
namespace: "functions", // service.namespace: the owning Lantern sub-team's (or team's) slug
// (`product` is its deprecated alias until 0.6.0)
// release: default <meta name="lantern-release">, else "dev"
// repositoryUrl: vcs.repository.url.full; default <meta name="lantern-repository">
// revision: vcs.ref.head.revision; default <meta name="lantern-revision">
// endpoint: default https://in.lntrn.dev
// sampleRate: 0..1 for RPC spans and web vitals; errors and reachability always go
// route: url.path until the first trackRoute, in place of location.pathname —
// the route pattern ("/@:handle") when the path carries something personal
// enabled: default on, except on localhost/*.localhost/*.test and under
// <meta name="lantern-telemetry" content="off">
// urlPath: "location" (default): url.path is the last trackRoute, else
// location.pathname. "tracked": only what trackRoute is given
// (a route template, /:owner/:module), never the address bar
// (Plumb obs.no-pii); console-shell sets it.
});Once per page: a second init returns the first client. Nothing the SDK does
ever throws into the page, and it never reports its own sends.
Authentication is the public-origin model: every request goes to
<endpoint>/v1/logs?service=<service> (or /v1/traces), credentials: "omit",
as text/plain so no request needs a preflight. The ingest accepts it only
from an origin on the project's allow-list.
What it sends
| Record | When | Key attributes |
|---|---|---|
| exception (ERROR) | window error, unhandled rejection, the React boundary, captureException, a kit error toast | exception.type/message/stacktrace (raw stack — Lantern symbolicates), exception.mechanism, code.filepath/lineno/column, url.path, http.response.header.x-trace-id, app.breadcrumbs |
| client.request.failed (WARN) | a request through wrapFetch or the interceptor that got no answer, timed out, or failed server-side | server.address, rpc.method, error.type = timeout\|http_5xx\|cors\|network\|aborted, client.online, client.since_last_success_ms |
| web_vital (INFO, sampled) | LCP, INP, CLS (on hide), FCP, TTFB | web_vital.name/value/delta/rating |
| page_view, route_change (INFO) | load (under urlPath: "tracked", once the first trackRoute lands, at most 5 s later); trackRoute(path) | url.path, document_load.* |
| CLIENT span (sampled) | every RPC / wrapped fetch | named by the procedure; rpc.method, server.address, rpc.response.status_code |
LCP is sent once, the first time the page is hidden. CLS and INP are sent then
and again on every later hide where they have changed — a console is hidden
and shown many times — with web_vital.delta the change since the page's last
report: a page's value is its last report's value, or the sum of its deltas
(never the sum of its values).
Every record carries session.id (per tab session); the resource carries
service.instance.id (per browser install), telemetry.sdk.* and browser.*.
Breadcrumbs are the last 20 route changes and request outcomes — procedure and
code, never a payload. Messages lose URL query strings, email addresses and
bearer-looking secrets before they leave; stack frames are sent untouched.
A browser cannot tell DNS from TLS from a refused connection: fetch rejects
with the same TypeError for all of them. Offline is network; a same-origin
failure is network; a cross-origin one is cors if a no-cors probe of the
same URL gets an answer, else network. dns and tls are never sent from a
browser.
Delivery: batches every 5 s or at 50 records. A send that gets no answer, a
408, a 429 or a 5xx moves its records to localStorage (at most 200 records /
256 KiB, oldest non-errors dropped first) and waits for Retry-After or a
backoff; the next page load replays them. On pagehide / hidden, whatever is
left goes by navigator.sendBeacon.
Errors
import { captureException, traceIdFrom } from "@lntrn/web";
try { await save(); } catch (err) {
captureException(err, { extra: { "app.form": "schedule" } }); // route and X-Trace-Id are filled in
showError(err, traceIdFrom(err)); // "trace 1a2b3c4d… [copy]"
}traceIdFrom(errOrResponse) reads X-Trace-Id from a ConnectError's
metadata, a fetch Response's headers, or a traceId (and from their
cause). The kit's TraceRef renders it.
React
import { TelemetryErrorBoundary } from "@lntrn/web/react";
<TelemetryErrorBoundary resetKeys={[pathname]} fallback={({ error, traceId, reset }) => <Oops traceId={traceId} onRetry={reset} />}>
<App />
</TelemetryErrorBoundary>Requests
// ConnectRPC: first in the list, so it times what the others do.
import { telemetryInterceptor } from "@lntrn/web/connect";
createConnectTransport({ baseUrl, interceptors: [telemetryInterceptor(), ...yours] });
// fetch
import { wrapFetch } from "@lntrn/web";
const api = wrapFetch(); // wraps the global fetch; or wrapFetch(myFetch)A server-streaming call (a log tail, a watch) is one span from the request to
the end of the stream, and fails if the stream does — a dropped connection
mid-way is a client.request.failed record like a unary call's.
A same-origin call carries a W3C traceparent, so the browser span parents the
server's trace at the edge. A cross-origin API gets none unless you say so —
its CORS policy has to allow the header first:
init({ service: "x-ui", getTraceHeaders: (url, { traceparent }) => url.hostname === "api.x.xeonr.io" ? { traceparent } : undefined });Releases and source maps (Vite)
// vite.config.ts
import { lanternTelemetry } from "@lntrn/web/vite";
export default defineConfig({
plugins: [react(), lanternTelemetry({ service: "functions-ui" })],
});The plugin:
- writes
<meta name="lantern-service">and<meta name="lantern-release">intoindex.html— the release isVERSION, elseVITE_APP_VERSION, elsedev— so the SDK needs no configuration for either. When the build knows where it came from, it also writes<meta name="lantern-repository">and<meta name="lantern-revision">, whichinit()andLanternWebsend asvcs.repository.url.fullandvcs.ref.head.revision, so Lantern can tell which commit a release runs. They come from therepositoryUrl/revisionoptions, elseLNTRN_VCS_REPOSITORY_URL/LNTRN_VCS_REVISION, else GitLab CI'sCI_PROJECT_URL/CI_COMMIT_SHA. The URL loses any credentials, a trailing/and.git; - forces
build.sourcemap = "hidden"for the browser's build (maps are written, no bundle links them). A server environment (SSR, a Worker) writes none unless its ownenvironments.<name>.build.sourcemapasks for them; - after the browser's build, with credentials (below), registers the release (
POST /v1/releases) and uploads every**/*.mapin that build's outDir (gzipped) to/v1/sourcemaps?service=&release=&path=keyed by the.jsit belongs to. A map with emptymappings(an empty chunk's) is skipped.LANTERN_INGEST_URLmoves the endpoint. A failed upload warns; it never fails the build; - deletes the
.mapfiles from that outDir, so they are never served.
Credentials, in this order (LAN-356):
LANTERN_RELEASE_KEY, sent asauthorization: Bearer <key>. If it is set it is always used, from any CI, and needs no binding.LANTERN_WORKLOAD_TOKEN, sent asauthorization: Bearer <token>: a branchd CI workload token (branchd-credential lanternin a job that declarescredentials: [lantern]). The ingest takes it from a protected run only, for a client project whose owner granted the repository (the console's CI grants) or, in the repository's own team, that lists its branchd path among its CI projects. Pass it to an image build as a build arg (ARG LANTERN_WORKLOAD_TOKEN) besideVERSION.CI_JOB_TOKEN, sent asJOB-TOKEN, only whenCI_SERVER_HOSTisgit.prod.wtfor unset (unset, as in a Docker build that is passed the token alone, counts as git.prod.wtf). The token must come from a GitLab project listed in the Lantern client project's CI projects (LAN-136). A job token from gitlab.com or any other GitLab is never sent: setLANTERN_RELEASE_KEYthere.- None of them: nothing is uploaded, and the build log says why.
Vite 6+ environment builds (React Router framework mode, SSR, Workers)
Vite calls the plugin once per environment. Only the client environment's
build is a browser's, so the upload reads that environment's own outDir
(build/client in React Router), never the top-level dist nothing writes,
and the server's build is left alone. There is no index.html to put the
tags in, so render them from the values the plugin defines:
// root.tsx
<meta name="lantern-service" content={import.meta.env.VITE_LANTERN_SERVICE} />
<meta name="lantern-release" content={import.meta.env.VITE_LANTERN_RELEASE} />
{import.meta.env.VITE_LANTERN_REPOSITORY && <meta name="lantern-repository" content={import.meta.env.VITE_LANTERN_REPOSITORY} />}
{import.meta.env.VITE_LANTERN_REVISION && <meta name="lantern-revision" content={import.meta.env.VITE_LANTERN_REVISION} />}The k8s pipeline already passes CI_JOB_TOKEN and VERSION to every image
build. It passes CI_PROJECT_URL and CI_COMMIT_SHA only when the project
sets DOCKER_BUILD_ARGS: "CI_PROJECT_URL=$CI_PROJECT_URL CI_COMMIT_SHA=$CI_COMMIT_SHA"
(LAN-598). Declare them in the builder stage, before vite build:
FROM node:24-slim AS builder
WORKDIR /src
RUN corepack enable
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
COPY . .
ARG CI_JOB_TOKEN
ARG VERSION
ARG CI_PROJECT_URL CI_COMMIT_SHA # optional: the repository and commit tags
RUN pnpm run build # vite build: meta tags, hidden maps, upload, maps deleted
FROM nginx:alpine
COPY --from=builder /src/dist /usr/share/nginx/htmlThe ARGs sit after the install so a new version or token does not bust the
dependency layer, and they never reach the final stage.
Reading telemetry back (./read)
A product that shows its own customers their devices' logs (an admin "Logs" pane, a TV's session log) reads them from Lantern with a client token: a device token minted from one of the client project's device keys with a read grant, by the product's backend. The grant is the whole authorization; lantern-ingest ANDs its filters onto every read, so the page can narrow and never widen.
import { createReader } from "@lntrn/web/read";
const reader = createReader({ token: () => api.mintTelemetryReadToken(scope) });
// History, newest first, cursor-paged.
const { records, nextCursor } = await reader.listLogs(
{ minSeverity: "warn", filters: [{ key: "attr:session_id", values: [sessionId] }] },
{ limit: 200 },
);
// Events, facets and a timeline.
await reader.listEvents({ from });
await reader.facets("logs", ["severity", "service.instance.id"], { from });
await reader.timeline("logs", { from }, "severity");
// Live: records as they land. Reconnects by itself (a stream lasts 30
// minutes, and the token function is called again each time); "refused"
// is a verdict and stops it.
const tail = reader.tail({ onRecords: (rs) => append(rs), onStatus: (s, why) => show(s, why) });
tail.close();Filter keys are service.instance.id (the device, install or tab),
service.version, severity, body, event.name, trace_id, span_id
and attr:<key> for a record's own attribute. It is the Connect protocol
over JSON with no dependencies, so React Native can use it too, except
tail(), which needs a streaming fetch body. Poll listLogs there. The
service is lantern.api.v1.ClientReadService (xeonr/protocol
modules/lantern-api).
Testing against it
createClient(options, env) builds a client against an injected environment
(fetch, storage, timers, events) instead of the page's, without touching the
page-wide singleton.
