Let each user pick the timezone timestamps are displayed in
Everything stays UTC: ingest still records Unix nanoseconds, ClickHouse
still stores UTC, every API response is still RFC3339 with a Z, and
queries are evaluated exactly as before. This changes only how those
instants are written on screen, so two people in two timezones looking
at one log line see the same instant written two ways -- never two
different lines, and never a different sort order.
Where the preference lives differs by deployment, and the three cases
are genuinely different products rather than one with fallbacks:
- Local login: server-side per named user (display_timezone on users,
PUT /auth/timezone), so it follows the person across browsers and
survives logout. Self-service at the RoleViewer floor, same as the
password change -- a viewer is the role most likely to be *only*
reading logs, so gating it higher would make it useless.
- Public demo: sessionStorage, so every new session starts at UTC. A
shared account's visitors have nothing to do with each other.
- Neither: localStorage, since there's no per-user record to write to.
api/cmd/api/main.go now imports time/tzdata. The image is
distroless/static with no /usr/share/zoneinfo, so LoadLocation would
otherwise reject every real zone name and the validation would refuse
every valid input.
Two details worth knowing when reading $lib/time.ts. Sub-second digits
are copied verbatim from the source string rather than round-tripped
through a JS Date, which is millisecond-precision and would silently
drop six digits of a ClickHouse nanosecond timestamp; expanding a result
row shows the localized value and the full-precision UTC original
together. And chart axes format their own labels, because ECharts'
type: 'time' axis renders in the browser's zone with no override --
which today puts a chart's clock out of step with the table beside it.
Timestamps are detected by value, not by column name: query output is
arbitrary, so a column called "timestamp" holding something else must
not be mangled, and `stats max(timestamp) as newest` must still be
formatted.
Verified against real zones including both sides of a DST boundary
(America/New_York at -05:00 in January, -04:00 in July), a half-hour
offset, and date rollover.
This commit is contained in:
@@ -11,6 +11,8 @@
|
||||
// column whose JSON got cut off).
|
||||
import Table from '$lib/components/ui/Table.svelte';
|
||||
import SeverityBadge from '$lib/components/ui/SeverityBadge.svelte';
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { formatTimestamp, isTimestamp, zoneLabel } from '$lib/time';
|
||||
|
||||
let {
|
||||
columns,
|
||||
@@ -23,9 +25,27 @@
|
||||
function formatCell(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'object') return JSON.stringify(value);
|
||||
// Timestamps are rendered in the reader's chosen zone; everything
|
||||
// else is passed through untouched. Detection is per *value*, not
|
||||
// per column name, because query output is arbitrary -- `stats
|
||||
// max(timestamp) as newest` names the column whatever it likes,
|
||||
// and an attribute called "timestamp" that holds something else
|
||||
// shouldn't be mangled. See $lib/time.ts.
|
||||
if (isTimestamp(value)) return formatTimestamp(value, getTimezone());
|
||||
return String(value);
|
||||
}
|
||||
|
||||
// Which columns hold timestamps, judged from the first row -- the
|
||||
// header gets a zone suffix so a table read on its own (or
|
||||
// screenshotted) still says which offset its times are in. Sampling
|
||||
// one row is enough: a column is one type in practice, and the cost
|
||||
// of being wrong is a missing label, not a wrong time.
|
||||
let timestampCols = $derived.by(() => {
|
||||
const first = rows[0];
|
||||
if (!first) return new Set<number>();
|
||||
return new Set(columns.map((_, i) => i).filter((i) => isTimestamp(first[i])));
|
||||
});
|
||||
|
||||
let sortCol = $state<number | null>(null);
|
||||
let sortDir = $state<1 | -1>(1);
|
||||
|
||||
@@ -87,7 +107,9 @@
|
||||
{#each columns as col, i (col)}
|
||||
<th style:width={widths[i] ? `${widths[i]}px` : undefined}>
|
||||
<button type="button" class="sort-btn" onclick={() => toggleSort(i)}>
|
||||
{col}
|
||||
{col}{#if timestampCols.has(i)}<span class="zone-tag" title="Timestamps are stored in UTC and shown in your display timezone"
|
||||
>· {zoneLabel(getTimezone())}</span
|
||||
>{/if}
|
||||
{#if sortCol === i}<span class="sort-ind">{sortDir === 1 ? '▲' : '▼'}</span>{/if}
|
||||
</button>
|
||||
<span
|
||||
@@ -137,7 +159,16 @@
|
||||
<dl>
|
||||
{#each columns as col, j (col)}
|
||||
<dt>{col}</dt>
|
||||
<dd>{formatCell(row[j])}</dd>
|
||||
<dd>
|
||||
{formatCell(row[j])}
|
||||
{#if isTimestamp(row[j])}
|
||||
<!-- The full-precision UTC original: the cell above is
|
||||
rendered in the reader's zone and truncated to
|
||||
milliseconds, and a log's nanosecond ordering is
|
||||
sometimes exactly what's being investigated. -->
|
||||
<span class="raw-utc">{row[j]}</span>
|
||||
{/if}
|
||||
</dd>
|
||||
{/each}
|
||||
</dl>
|
||||
</td>
|
||||
@@ -165,6 +196,19 @@
|
||||
.chevron.open {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
.zone-tag {
|
||||
margin-left: var(--space-1);
|
||||
color: var(--color-text-faint);
|
||||
font-weight: var(--font-weight-normal);
|
||||
text-transform: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.raw-utc {
|
||||
display: block;
|
||||
color: var(--color-text-faint);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
.sort-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
|
||||
+24
-1
@@ -430,7 +430,17 @@ export function injectTimeRange(query: string, earliest: string, latest: string)
|
||||
|
||||
// --- local login (single-tenant mode, see api/localauth) --------------
|
||||
|
||||
export type LocalSession = { user_id: string; tenant_id: string; username: string; role: string };
|
||||
export type LocalSession = {
|
||||
user_id: string;
|
||||
tenant_id: string;
|
||||
username: string;
|
||||
role: string;
|
||||
// The user's stored display-timezone preference (IANA name).
|
||||
// Optional: absent on deployments whose api predates the setting, and
|
||||
// on the login response, which doesn't carry it -- both mean "UTC".
|
||||
timezone?: string;
|
||||
};
|
||||
|
||||
|
||||
export function login(username: string, password: string): Promise<LocalSession & { token: string }> {
|
||||
return request('/auth/login', {
|
||||
@@ -440,6 +450,19 @@ export function login(username: string, password: string): Promise<LocalSession
|
||||
});
|
||||
}
|
||||
|
||||
// Stores the caller's own display-timezone preference. Display only --
|
||||
// it changes nothing about what any query returns (see
|
||||
// metadata/migrations/0042_add_user_display_timezone.sql). Available to
|
||||
// every role, including Viewer, since it's a setting about the reader
|
||||
// rather than about the data.
|
||||
export function setDisplayTimezone(timezone: string): Promise<void> {
|
||||
return request('/auth/timezone', {
|
||||
method: 'PUT',
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ timezone })
|
||||
});
|
||||
}
|
||||
|
||||
export function logout(): Promise<void> {
|
||||
return request('/auth/logout', { method: 'POST', credentials: 'include' });
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
import EChart from './EChart.svelte';
|
||||
import { readChartTokens, baseOption, SERIES_PALETTE } from './theme';
|
||||
import { pivot } from './pivot';
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { axisTimeLabel, formatTimestamp } from '$lib/time';
|
||||
import type { QueryResult } from '$lib/api';
|
||||
import type { EChartsOption } from './setup';
|
||||
|
||||
@@ -32,16 +34,55 @@
|
||||
seriesColumn: config.series_column
|
||||
});
|
||||
const multi = p.series.length > 1;
|
||||
const zone = getTimezone();
|
||||
// Span drives label granularity; measured across every series,
|
||||
// since one may cover a wider range than another.
|
||||
const xs = p.series.flatMap((s) => s.data.map((d) => Number(d[0]))).filter((n) => !Number.isNaN(n));
|
||||
const spanMs = xs.length > 1 ? Math.max(...xs) - Math.min(...xs) : 0;
|
||||
|
||||
return {
|
||||
...baseOption(t),
|
||||
color: SERIES_PALETTE,
|
||||
legend: multi ? { ...baseOption(t).legend, show: true } : { show: false },
|
||||
xAxis: {
|
||||
...baseOption(t).xAxis,
|
||||
type: p.isTime ? 'time' : 'category',
|
||||
data: p.isTime ? undefined : p.categories
|
||||
},
|
||||
// Built as two concrete axes rather than one object with a
|
||||
// conditional `type`: a time axis and a category axis are
|
||||
// different option types, and merging them into one shape is
|
||||
// what TypeScript (correctly) refuses.
|
||||
xAxis: p.isTime
|
||||
? {
|
||||
...baseOption(t).xAxis,
|
||||
type: 'time' as const,
|
||||
axisLabel: {
|
||||
...baseOption(t).xAxis.axisLabel,
|
||||
formatter: (value: number) => axisTimeLabel(value, zone, spanMs)
|
||||
}
|
||||
}
|
||||
: { ...baseOption(t).xAxis, type: 'category' as const, data: p.categories },
|
||||
tooltip: p.isTime
|
||||
? {
|
||||
...baseOption(t).tooltip,
|
||||
trigger: 'axis' as const,
|
||||
// Same reason as the axis labels: ECharts' default
|
||||
// tooltip header is the browser's zone, which would
|
||||
// disagree with everything else on the page.
|
||||
formatter: (params: unknown) => {
|
||||
const rows = Array.isArray(params) ? params : [params];
|
||||
const first = rows[0] as { value?: [number, number] };
|
||||
const at = first?.value?.[0];
|
||||
const head =
|
||||
at === undefined
|
||||
? ''
|
||||
: `${formatTimestamp(new Date(at).toISOString(), zone)} ${zone}`;
|
||||
const body = rows
|
||||
.map((r) => {
|
||||
const s = r as { marker?: string; seriesName?: string; value?: [number, number] };
|
||||
return `${s.marker ?? ''}${s.seriesName ?? ''} ${s.value?.[1] ?? ''}`;
|
||||
})
|
||||
.join('<br/>');
|
||||
return [head, body].filter(Boolean).join('<br/>');
|
||||
}
|
||||
}
|
||||
: baseOption(t).tooltip,
|
||||
yAxis: { ...baseOption(t).yAxis, type: 'value' },
|
||||
dataZoom: p.isTime
|
||||
? [
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
// for "a timeline view of an alert's state history rather than just
|
||||
// a flat delivery log" (Phase 5 task 7); this is the same
|
||||
// DeliveryLogEntry list the old flat table read, framed differently.
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { formatTimestamp } from '$lib/time';
|
||||
import type { DeliveryLogEntry } from '$lib/api';
|
||||
|
||||
let { deliveries }: { deliveries: DeliveryLogEntry[] } = $props();
|
||||
@@ -33,7 +35,7 @@
|
||||
<div class="entry">
|
||||
<div class="entry-head">
|
||||
<span class="event {tierFor(d)}">{d.event_type}</span>
|
||||
<time>{new Date(d.created_at).toLocaleString()}</time>
|
||||
<time title={d.created_at}>{formatTimestamp(d.created_at, getTimezone())}</time>
|
||||
</div>
|
||||
<div class="entry-body">
|
||||
<span class:danger={d.status === 'failed'}>{statusLabel(d)}</span>
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
// Timestamp rendering. Pure functions, no state -- the caller passes the
|
||||
// zone in, and $lib/timezone.svelte.ts owns where that zone comes from.
|
||||
//
|
||||
// The contract this whole feature rests on: nothing here ever changes
|
||||
// *which* instant a value refers to, only how it's written down. The
|
||||
// data stays UTC end to end (ingest records Unix nanoseconds, ClickHouse
|
||||
// stores UTC, the API emits RFC3339 with a Z), queries are still
|
||||
// evaluated in UTC, and two users in two zones looking at one log line
|
||||
// see the same instant rendered two ways -- never two different lines,
|
||||
// and never a different sort order.
|
||||
|
||||
// Deliberately narrow, matching what this system's own APIs emit:
|
||||
// RFC3339/ISO-8601 with a date, a T (or space) separator, and a time.
|
||||
// A fractional part and a zone suffix are both optional because the two
|
||||
// sources differ -- ClickHouse query results come back like
|
||||
// "2026-08-22T21:30:06.090041211Z" (nanoseconds), Postgres-backed JSON
|
||||
// like "2026-08-22T21:30:06.477115Z" (microseconds).
|
||||
//
|
||||
// Being narrow is the point: ResultsTable runs this over every cell of
|
||||
// every column, and a looser pattern would start reformatting values
|
||||
// that merely resemble dates (a version string, an ID with dashes) and
|
||||
// silently corrupt them.
|
||||
const isoTimestamp = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/;
|
||||
|
||||
export function isTimestamp(value: unknown): value is string {
|
||||
return typeof value === 'string' && isoTimestamp.test(value);
|
||||
}
|
||||
|
||||
// Intl.DateTimeFormat construction is expensive enough to matter when
|
||||
// it's called once per cell on a 5,000-row result; the zone rarely
|
||||
// changes, so one formatter per zone is cached for the page's lifetime.
|
||||
const formatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
function formatterFor(zone: string): Intl.DateTimeFormat {
|
||||
let f = formatters.get(zone);
|
||||
if (!f) {
|
||||
f = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: zone,
|
||||
hourCycle: 'h23',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
});
|
||||
formatters.set(zone, f);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
// 'en-CA' yields YYYY-MM-DD natively, but only formatToParts is
|
||||
// guaranteed to give the pieces without a locale-specific separator
|
||||
// sneaking in, so the string is assembled by hand.
|
||||
function parts(value: Date, zone: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const p of formatterFor(zone).formatToParts(value)) out[p.type] = p.value;
|
||||
return out;
|
||||
}
|
||||
|
||||
export type TimestampPrecision = 'seconds' | 'millis' | 'full';
|
||||
|
||||
/**
|
||||
* Renders an ISO timestamp in `zone` as `YYYY-MM-DD HH:mm:ss[.fff]`.
|
||||
*
|
||||
* Anything that isn't a recognizable timestamp comes back untouched --
|
||||
* this runs over unknown query output, where guessing wrong is worse
|
||||
* than doing nothing.
|
||||
*
|
||||
* Sub-second digits are taken verbatim from the source string rather
|
||||
* than from the parsed Date: JS Dates are millisecond-precision, so
|
||||
* round-tripping a ClickHouse nanosecond timestamp through one would
|
||||
* silently drop six digits of a log's ordering information.
|
||||
*/
|
||||
export function formatTimestamp(
|
||||
value: unknown,
|
||||
zone: string,
|
||||
precision: TimestampPrecision = 'millis'
|
||||
): string {
|
||||
if (!isTimestamp(value)) return value === null || value === undefined ? '' : String(value);
|
||||
const ms = Date.parse(value);
|
||||
if (Number.isNaN(ms)) return value;
|
||||
|
||||
const p = parts(new Date(ms), zone);
|
||||
const base = `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
|
||||
if (precision === 'seconds') return base;
|
||||
|
||||
const fraction = isoTimestamp.exec(value)?.[7] ?? '';
|
||||
if (!fraction) return base;
|
||||
return base + (precision === 'full' ? fraction : fraction.slice(0, 4));
|
||||
}
|
||||
|
||||
/** Date only, for created-at style columns where the time of day is noise. */
|
||||
export function formatDate(value: unknown, zone: string): string {
|
||||
if (!isTimestamp(value)) return value === null || value === undefined ? '' : String(value);
|
||||
const p = parts(new Date(Date.parse(value)), zone);
|
||||
return `${p.year}-${p.month}-${p.day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The UTC offset `zone` is at for a given instant, as `+HH:MM`.
|
||||
*
|
||||
* Computed for a specific moment, not for the zone in general, because
|
||||
* half the world's zones have two answers depending on the date -- a
|
||||
* label that says -08:00 in July for America/Los_Angeles is a lie, and
|
||||
* the whole point of storing a zone name rather than a fixed offset is
|
||||
* that the rules are what matter.
|
||||
*/
|
||||
export function offsetLabel(zone: string, at: Date = new Date()): string {
|
||||
// 'longOffset' gives "GMT+11:00" directly. The arithmetic
|
||||
// alternative -- formatting the same instant in two zones and
|
||||
// subtracting -- means re-parsing a locale-formatted string, which is
|
||||
// implementation-defined; this asks the platform the question
|
||||
// outright instead.
|
||||
const name = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' })
|
||||
.formatToParts(at)
|
||||
.find((p) => p.type === 'timeZoneName')?.value;
|
||||
// Zero-offset zones format as a bare "GMT", with no numeric part.
|
||||
return /GMT([+-]\d{2}:\d{2})/.exec(name ?? '')?.[1] ?? '+00:00';
|
||||
}
|
||||
|
||||
/**
|
||||
* The same offset as a signed number of minutes, for arithmetic --
|
||||
* `+05:30` is +330. Kept next to offsetLabel so the two can't disagree
|
||||
* about what a zone's offset is.
|
||||
*/
|
||||
export function offsetMinutes(zone: string, at: Date = new Date()): number {
|
||||
const [, sign, hh, mm] = /^([+-])(\d{2}):(\d{2})$/.exec(offsetLabel(zone, at)) ?? [];
|
||||
if (!sign) return 0;
|
||||
return (sign === '-' ? -1 : 1) * (Number(hh) * 60 + Number(mm));
|
||||
}
|
||||
|
||||
/** "UTC" / "America/New_York +11:00" -- what a column header or picker shows. */
|
||||
export function zoneLabel(zone: string, at: Date = new Date()): string {
|
||||
return zone === 'UTC' ? 'UTC' : `${zone} ${offsetLabel(zone, at)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Relative age ("3m ago"). Zone-independent by construction -- the gap
|
||||
* between two instants is the same number everywhere on earth -- so it
|
||||
* takes no zone argument, and pages that show only relative times need
|
||||
* no timezone plumbing at all.
|
||||
*/
|
||||
export function relativeTime(value: string, now: number = Date.now()): string {
|
||||
const ms = now - Date.parse(value);
|
||||
if (Number.isNaN(ms)) return '';
|
||||
if (ms < 60_000) return `${Math.max(0, Math.round(ms / 1000))}s ago`;
|
||||
if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;
|
||||
if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h ago`;
|
||||
return `${Math.round(ms / 86_400_000)}d ago`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact axis label for a time-series chart, rendered in `zone`.
|
||||
*
|
||||
* ECharts' own `type: 'time'` axis formats in the *browser's* zone with
|
||||
* no way to tell it otherwise, which would put a chart's clock an hour
|
||||
* or ten out of step with the table right beside it. Every time axis in
|
||||
* this app therefore formats its own labels through here.
|
||||
*
|
||||
* The shape of the label follows the visible span, the way any chart's
|
||||
* does: a few hours wants the time of day, a week wants the date.
|
||||
*/
|
||||
export function axisTimeLabel(ms: number, zone: string, spanMs: number): string {
|
||||
const full = formatTimestamp(new Date(ms).toISOString(), zone, 'seconds');
|
||||
if (spanMs > 5 * 86_400_000) return full.slice(0, 10); // YYYY-MM-DD
|
||||
if (spanMs > 86_400_000) return full.slice(5, 16); // MM-DD HH:mm
|
||||
return full.slice(11, 16); // HH:mm
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Which timezone the UI renders timestamps in. Display only -- see
|
||||
// $lib/time.ts's header for why that distinction is the whole feature.
|
||||
//
|
||||
// Where the choice is *stored* depends on the deployment, and the three
|
||||
// cases are genuinely different products rather than one with fallbacks:
|
||||
//
|
||||
// - A public demo (isPublicDemo) keeps it in sessionStorage, so every
|
||||
// new session starts at UTC again. A shared demo account is used by
|
||||
// strangers who have nothing to do with each other; one visitor's
|
||||
// choice following the next one around would be a bug, not a
|
||||
// feature.
|
||||
// - A deployment with local login stores it server-side, per named
|
||||
// user (PUT /auth/timezone), so it follows that person across
|
||||
// browsers and survives logout -- the setting belongs to the
|
||||
// account, not the machine.
|
||||
// - Anything else (SSO-only, or no auth configured) has no per-user
|
||||
// record to write to, so it falls back to localStorage: still
|
||||
// persistent, just per-browser.
|
||||
import { browser } from '$app/environment';
|
||||
import { isPublicDemo, localAuthEnabled, setDisplayTimezone } from '$lib/api';
|
||||
|
||||
export const DEFAULT_ZONE = 'UTC';
|
||||
|
||||
const STORAGE_KEY = 'cairnobs.timezone';
|
||||
|
||||
type Persistence = 'session' | 'account' | 'browser';
|
||||
|
||||
export function persistence(): Persistence {
|
||||
if (isPublicDemo) return 'session';
|
||||
return localAuthEnabled ? 'account' : 'browser';
|
||||
}
|
||||
|
||||
function storage(): Storage | null {
|
||||
if (!browser) return null;
|
||||
try {
|
||||
return persistence() === 'session' ? sessionStorage : localStorage;
|
||||
} catch {
|
||||
// Storage can throw outright in some privacy modes, not just come
|
||||
// back empty.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readStored(): string | null {
|
||||
try {
|
||||
return storage()?.getItem(STORAGE_KEY) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let zone = $state<string>(DEFAULT_ZONE);
|
||||
|
||||
// Account-mode deployments learn the real value from GET /auth/session,
|
||||
// which the layout's route guard already fetches on every navigation --
|
||||
// so this is initialized from that response rather than by issuing a
|
||||
// second request of its own.
|
||||
export function initTimezone(fromSession?: string | null) {
|
||||
if (persistence() === 'account') {
|
||||
zone = fromSession || DEFAULT_ZONE;
|
||||
return;
|
||||
}
|
||||
zone = readStored() || DEFAULT_ZONE;
|
||||
}
|
||||
|
||||
export function getTimezone(): string {
|
||||
return zone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a zone immediately and persists it wherever this deployment
|
||||
* keeps it. The UI updates on the local assignment, not on the server
|
||||
* round trip: a failed PUT shouldn't leave someone staring at a control
|
||||
* that appears not to respond, and the consequence of the failure is
|
||||
* only that the choice won't survive their next login.
|
||||
*/
|
||||
export async function setTimezone(tz: string): Promise<void> {
|
||||
zone = tz;
|
||||
if (persistence() === 'account') {
|
||||
await setDisplayTimezone(tz);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
storage()?.setItem(STORAGE_KEY, tz);
|
||||
} catch {
|
||||
// Storage unavailable -- the choice just won't outlive the page.
|
||||
}
|
||||
}
|
||||
|
||||
/** The zone this browser thinks it's in, e.g. "Europe/Berlin". */
|
||||
export function browserTimezone(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || DEFAULT_ZONE;
|
||||
} catch {
|
||||
return DEFAULT_ZONE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every IANA zone the browser knows, straight from Intl -- no bundled
|
||||
* zone list to go stale as the tz database changes a few times a year.
|
||||
* UTC is forced to the front because it's this system's baseline and
|
||||
* shouldn't have to be hunted for alphabetically.
|
||||
*/
|
||||
export function timezoneOptions(): string[] {
|
||||
let all: string[] = [];
|
||||
try {
|
||||
all = Intl.supportedValuesOf('timeZone');
|
||||
} catch {
|
||||
// Older engines without supportedValuesOf: offer the two zones
|
||||
// that can be named without a list -- the baseline and this
|
||||
// browser's own -- rather than nothing.
|
||||
all = [browserTimezone()];
|
||||
}
|
||||
return [DEFAULT_ZONE, ...all.filter((z) => z !== DEFAULT_ZONE)];
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
import CommandPalette from '$lib/components/CommandPalette.svelte';
|
||||
import { page } from '$app/state';
|
||||
import { getLocalSession } from '$lib/api';
|
||||
import { initTimezone } from '$lib/timezone.svelte';
|
||||
|
||||
let { children } = $props();
|
||||
let paletteOpen = $state(false);
|
||||
@@ -41,6 +42,12 @@
|
||||
// mid-use redirects without re-blanking an already-rendered page (a
|
||||
// full navigation to /login is already underway by the time that'd
|
||||
// matter anyway).
|
||||
// Storage-backed timezone modes (demo, and deployments without local
|
||||
// login) can resolve immediately; account mode learns the real value
|
||||
// from the session response below. Both run before any timestamp is
|
||||
// rendered, since nothing renders until the guard resolves.
|
||||
initTimezone();
|
||||
|
||||
$effect(() => {
|
||||
if (isLoginPage) {
|
||||
authorized = true;
|
||||
@@ -48,6 +55,7 @@
|
||||
return;
|
||||
}
|
||||
getLocalSession().then((session) => {
|
||||
if (session !== null && session !== 'disabled') initTimezone(session.timezone);
|
||||
if (session === null) {
|
||||
const next = encodeURIComponent(page.url.pathname + page.url.search);
|
||||
window.location.href = `/login?next=${next}`;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { relativeTime, formatTimestamp, zoneLabel } from '$lib/time';
|
||||
import { listAgents, type Agent } from '$lib/api';
|
||||
import { Badge, EmptyState, Skeleton, Table } from '$lib/components/ui';
|
||||
|
||||
@@ -31,13 +33,6 @@
|
||||
return Date.now() - new Date(a.last_seen_at).getTime() > thresholdMs;
|
||||
}
|
||||
|
||||
function relativeTime(iso: string): string {
|
||||
const ms = Date.now() - new Date(iso).getTime();
|
||||
if (ms < 60_000) return `${Math.max(0, Math.round(ms / 1000))}s ago`;
|
||||
if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;
|
||||
if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h ago`;
|
||||
return `${Math.round(ms / 86_400_000)}d ago`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<main>
|
||||
@@ -77,7 +72,7 @@
|
||||
<td><a href={`/agents/${encodeURIComponent(a.host)}`}>{a.host}</a></td>
|
||||
<td>{a.service}</td>
|
||||
<td>{a.agent_version || '—'}</td>
|
||||
<td>{relativeTime(a.last_seen_at)}</td>
|
||||
<td title={`${formatTimestamp(a.last_seen_at, getTimezone())} ${zoneLabel(getTimezone())}`}>{relativeTime(a.last_seen_at)}</td>
|
||||
<td>
|
||||
{#if isStale(a)}
|
||||
<Badge tone="danger">stale</Badge>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { relativeTime, formatTimestamp, zoneLabel } from '$lib/time';
|
||||
import { page } from '$app/state';
|
||||
import { getAgent, setAgentConfig, clearAgentConfig, issueAgentCommand, type Agent } from '$lib/api';
|
||||
import { Badge, Button, Input, Skeleton } from '$lib/components/ui';
|
||||
@@ -174,13 +176,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function relativeTime(iso: string): string {
|
||||
const ms = Date.now() - new Date(iso).getTime();
|
||||
if (ms < 60_000) return `${Math.max(0, Math.round(ms / 1000))}s ago`;
|
||||
if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;
|
||||
if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h ago`;
|
||||
return `${Math.round(ms / 86_400_000)}d ago`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<main>
|
||||
@@ -202,9 +197,9 @@
|
||||
<dt>Source</dt>
|
||||
<dd>{agent.source_kind}{agent.source_detail ? ` (${agent.source_detail})` : ''}</dd>
|
||||
<dt>First seen</dt>
|
||||
<dd>{relativeTime(agent.first_seen_at)}</dd>
|
||||
<dd title={`${formatTimestamp(agent.first_seen_at, getTimezone())} ${zoneLabel(getTimezone())}`}>{relativeTime(agent.first_seen_at)}</dd>
|
||||
<dt>Last seen</dt>
|
||||
<dd>{relativeTime(agent.last_seen_at)}</dd>
|
||||
<dd title={`${formatTimestamp(agent.last_seen_at, getTimezone())} ${zoneLabel(getTimezone())}`}>{relativeTime(agent.last_seen_at)}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { relativeTime, formatTimestamp, zoneLabel } from '$lib/time';
|
||||
import { page } from '$app/state';
|
||||
import { getHostMetrics, type HostMetrics } from '$lib/api';
|
||||
import { Card, Skeleton } from '$lib/components/ui';
|
||||
@@ -34,13 +36,6 @@
|
||||
return Math.min(100, Math.max(0, (used / total) * 100));
|
||||
}
|
||||
|
||||
function relativeTime(iso: string): string {
|
||||
const ms = Date.now() - new Date(iso).getTime();
|
||||
if (ms < 60_000) return `${Math.max(0, Math.round(ms / 1000))}s ago`;
|
||||
if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;
|
||||
if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h ago`;
|
||||
return `${Math.round(ms / 86_400_000)}d ago`;
|
||||
}
|
||||
|
||||
function formatUptime(seconds: number): string {
|
||||
if (seconds <= 0) return '—';
|
||||
@@ -64,7 +59,7 @@
|
||||
{:else if !metrics}
|
||||
<p class="hint">No metrics samples for this host yet.</p>
|
||||
{:else}
|
||||
<p class="hint">Last sample {relativeTime(metrics.timestamp)}.</p>
|
||||
<p class="hint" title={`${formatTimestamp(metrics.timestamp, getTimezone())} ${zoneLabel(getTimezone())}`}>Last sample {relativeTime(metrics.timestamp)}.</p>
|
||||
|
||||
<section class="system">
|
||||
<dl>
|
||||
|
||||
@@ -18,6 +18,15 @@
|
||||
} from '$lib/api';
|
||||
import { getTheme, setTheme, type Theme } from '$lib/theme.svelte';
|
||||
import { getDensity, setDensity, type Density } from '$lib/density.svelte';
|
||||
import {
|
||||
getTimezone,
|
||||
setTimezone,
|
||||
browserTimezone,
|
||||
timezoneOptions,
|
||||
persistence,
|
||||
DEFAULT_ZONE
|
||||
} from '$lib/timezone.svelte';
|
||||
import { formatTimestamp, zoneLabel } from '$lib/time';
|
||||
import Skeleton from '$lib/components/ui/Skeleton.svelte';
|
||||
|
||||
let loading = $state(true);
|
||||
@@ -222,14 +231,12 @@
|
||||
return `${t.host}/${t.service}`;
|
||||
}
|
||||
|
||||
// The deletion cutoff is the one timestamp on this page where getting
|
||||
// the zone wrong has consequences -- it's the boundary someone is
|
||||
// about to permanently delete data before -- so it renders in the
|
||||
// same zone as everything else, with the zone spelled out.
|
||||
function formatCutoff(iso: string): string {
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
});
|
||||
return `${formatTimestamp(iso, getTimezone(), 'seconds')} ${zoneLabel(getTimezone())}`;
|
||||
}
|
||||
|
||||
const themeOptions: { value: Theme; label: string; hint: string }[] = [
|
||||
@@ -241,6 +248,37 @@
|
||||
{ value: 'comfortable', label: 'Comfortable', hint: 'Dashboards, forms' },
|
||||
{ value: 'compact', label: 'Compact', hint: 'Log tables, results' }
|
||||
];
|
||||
|
||||
// --- display timezone (see $lib/timezone.svelte.ts) ---
|
||||
const zones = timezoneOptions();
|
||||
let tzError = $state('');
|
||||
let tzSaving = $state(false);
|
||||
// Ticks once a second so the sample below is a live clock -- the
|
||||
// quickest way for someone to confirm they picked the right zone is
|
||||
// to see the current time in it and recognize it.
|
||||
let now = $state(new Date());
|
||||
$effect(() => {
|
||||
const id = setInterval(() => (now = new Date()), 1000);
|
||||
return () => clearInterval(id);
|
||||
});
|
||||
|
||||
const persistenceNote: Record<ReturnType<typeof persistence>, string> = {
|
||||
account: 'Saved to your account, so it follows you to any browser you sign in from.',
|
||||
session: 'Kept for this browser session only — this demo resets it every time you come back.',
|
||||
browser: 'Saved in this browser only, since this deployment has no per-user accounts.'
|
||||
};
|
||||
|
||||
async function chooseTimezone(tz: string) {
|
||||
tzError = '';
|
||||
tzSaving = true;
|
||||
try {
|
||||
await setTimezone(tz);
|
||||
} catch (e) {
|
||||
tzError = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
tzSaving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<main>
|
||||
@@ -278,6 +316,54 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Display timezone</h2>
|
||||
<p class="note">
|
||||
Timestamps are stored and queried in UTC everywhere in Cairn OBS. This setting only changes
|
||||
how they're written on screen — searches, dashboards, and alerts all keep returning exactly
|
||||
the same records, so two people in two timezones are always looking at the same log line.
|
||||
</p>
|
||||
|
||||
<div class="tz-row">
|
||||
<label class="tz-label" for="tz-select">Show times in</label>
|
||||
<select
|
||||
id="tz-select"
|
||||
value={getTimezone()}
|
||||
disabled={tzSaving}
|
||||
onchange={(e) => chooseTimezone((e.currentTarget as HTMLSelectElement).value)}
|
||||
>
|
||||
{#each zones as z (z)}
|
||||
<option value={z}>{z}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if getTimezone() !== browserTimezone()}
|
||||
<button type="button" class="tz-detect" disabled={tzSaving} onclick={() => chooseTimezone(browserTimezone())}>
|
||||
Use browser timezone ({browserTimezone()})
|
||||
</button>
|
||||
{/if}
|
||||
{#if getTimezone() !== DEFAULT_ZONE}
|
||||
<button type="button" class="tz-detect" disabled={tzSaving} onclick={() => chooseTimezone(DEFAULT_ZONE)}>
|
||||
Back to UTC
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<p class="tz-sample">
|
||||
<span class="tz-sample-label">Now</span>
|
||||
<span class="tz-sample-value">{formatTimestamp(now.toISOString(), getTimezone(), 'seconds')}</span>
|
||||
<span class="tz-sample-zone">{zoneLabel(getTimezone(), now)}</span>
|
||||
{#if getTimezone() !== DEFAULT_ZONE}
|
||||
<span class="tz-sample-utc">= {formatTimestamp(now.toISOString(), DEFAULT_ZONE, 'seconds')} UTC</span>
|
||||
{/if}
|
||||
</p>
|
||||
<p class="note">{persistenceNote[persistence()]}</p>
|
||||
<p class="note">
|
||||
Time ranges you type into a query (<code>earliest=</code>/<code>latest=</code>) are still read
|
||||
as UTC.
|
||||
</p>
|
||||
{#if tzError}<p class="error">Couldn't save timezone: {tzError}</p>{/if}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Core</h2>
|
||||
<p>Single-tenant deployment settings live here. Nothing configurable yet.</p>
|
||||
@@ -484,6 +570,71 @@
|
||||
.note a {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
.tz-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
margin: var(--space-4) 0 var(--space-3);
|
||||
}
|
||||
.tz-label {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.tz-row select {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-base);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
min-width: 16rem;
|
||||
}
|
||||
.tz-detect {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-accent);
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tz-detect:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.6;
|
||||
}
|
||||
/* The live sample is the part that makes the setting self-evident,
|
||||
so it gets the surface treatment rather than sitting in body copy. */
|
||||
.tz-sample {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: var(--space-3);
|
||||
margin: 0 0 var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
.tz-sample-label {
|
||||
font-size: var(--text-xs);
|
||||
font-weight: var(--font-weight-bold);
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
.tz-sample-value {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-md);
|
||||
color: var(--color-text);
|
||||
}
|
||||
.tz-sample-zone,
|
||||
.tz-sample-utc {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.option-group {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getTimezone } from '$lib/timezone.svelte';
|
||||
import { formatDate as formatDateInZone } from '$lib/time';
|
||||
import {
|
||||
localAuthEnabled,
|
||||
getLocalSession,
|
||||
@@ -181,8 +183,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Rendered in the reader's display timezone like every other
|
||||
// timestamp -- a date is just a timestamp with the time cut off, and
|
||||
// near midnight the two zones genuinely disagree about which day it
|
||||
// was. See $lib/time.ts.
|
||||
function formatDate(iso: string): string {
|
||||
return new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
|
||||
return formatDateInZone(iso, getTimezone());
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user