feat(sites): one install, many networks (v0.24.0-beta)
Closes #130. Multi-site, not multi-tenancy: a site is a named collection of devices whose clients, events, topology and dashboards are viewed separately. Sites separate what you see, not who you are — the admin/manage/read-only roles are unchanged and every user sees every site. Per-site permissions would have multiplied the work for a need nobody stated. Two measurements decided the design. Every device-derived table hangs off devices(id) — 25 of 50 tables, 35 foreign keys — so a single site_id column on devices scopes clients, events, topology, backups and the rest transitively. No other table needed one. The frontend has 162 useQuery call sites across 57 files. Threading a site through each would be a large change that leaves a permanent trap: every future query another chance to forget. The site is injected in the existing axios interceptor instead, beside the auth token, so a new query is scoped by default. Only 23 collection routes needed filtering; the 131 per-device routes are already scoped by their device. Existing installs are untouched. Migration creates one "Default Site", adopts every device into it, and a single-site install never meets the concept. An absent X-Site-Id header means unscoped, so existing API tokens and scripts behave exactly as before. Polling stays fleet-wide. Sites are a view over data already gathered, not a change to how it is gathered — a device does not stop being monitored because you are looking elsewhere. Rogue-AP detection scopes the scans but keeps the "these are ours" BSSID set fleet-wide, or your own AP in another site reads as an evil twin. Bulk actions do obey the selector: an operation that silently spanned two customers is the blast radius the wave guards exist to contain. Four rounds of defects came out of testing the UI rather than the API, and the first is the one worth recording. Switching sites called queryClient.clear(), which empties the cache and reviews as correct. It isn't: clear() destroys each query but a *mounted* observer keeps its own reference and last result, so every rendered page went on showing the previous site's data. The QueryClient is now keyed on the site, which remounts the tree against an empty cache. Three tests pin the old behaviour down so the shortcut cannot return. The others: an unscoped fallback path behind the Connected Clients chart; Config Health, TX retries and the activity feed reading fleet-wide; and site_id added to the device list query but none of the other four that build a device payload, so the Site field could not read its own value and appeared to reject every change while the writes were landing. That last one is now structural — DEVICE_BASE_COLUMNS is shared by all five, with a test that fails when a device payload is hand-rolled, and which found two further instances while being written. Frontend tests were never run by CI despite vitest being configured and six suites existing; they now run in both the workflow and ci-preflight. Verified against a live four-device fleet: the migration left every figure identical, an empty site returns zero from every read endpoint, moving a device carries its history with it, and deleting a site with devices is refused. Minor bump rather than patch: sites change the shape of the product rather than adding to it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
e47819e232
commit
7b994ad935
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { fleetStatus } from './fleetStatus';
|
||||
|
||||
describe('fleetStatus', () => {
|
||||
// The reported bug: switching site remounts with no summary, and the header
|
||||
// interpolated it straight into the string.
|
||||
it('reports loading rather than "undefined devices unreachable"', () => {
|
||||
for (const absent of [undefined, null]) {
|
||||
const s = fleetStatus(absent);
|
||||
expect(s.kind).toBe('loading');
|
||||
expect(s.headline).not.toMatch(/undefined|NaN/);
|
||||
expect(s.sentence).not.toMatch(/undefined|NaN/);
|
||||
}
|
||||
});
|
||||
|
||||
// Defaulting the missing summary to 0 would have swapped one wrong claim for
|
||||
// another: an unheard-from fleet is not a healthy one.
|
||||
it('does not claim health while loading', () => {
|
||||
expect(fleetStatus(undefined).tone).toBe('neutral');
|
||||
expect(fleetStatus(undefined).kind).not.toBe('healthy');
|
||||
});
|
||||
|
||||
it('distinguishes an empty site from a healthy one', () => {
|
||||
const empty = fleetStatus({ total: 0, online: 0, offline: 0 });
|
||||
expect(empty.kind).toBe('empty');
|
||||
expect(empty.sentence).toBe('No devices in this site yet.');
|
||||
|
||||
const healthy = fleetStatus({ total: 3, online: 3, offline: 0 });
|
||||
expect(healthy.kind).toBe('healthy');
|
||||
expect(healthy.tone).toBe('good');
|
||||
});
|
||||
|
||||
it('counts and pluralises unreachable devices', () => {
|
||||
expect(fleetStatus({ total: 4, online: 3, offline: 1 }).headline)
|
||||
.toBe('1 device unreachable');
|
||||
expect(fleetStatus({ total: 4, online: 2, offline: 2 }).sentence)
|
||||
.toBe('2 devices unreachable.');
|
||||
expect(fleetStatus({ total: 4, online: 2, offline: 2 }).tone).toBe('warn');
|
||||
});
|
||||
|
||||
it('never emits undefined or NaN for any input', () => {
|
||||
const cases = [
|
||||
undefined, null,
|
||||
{ total: 0, online: 0, offline: 0 },
|
||||
{ total: 1, online: 0, offline: 1 },
|
||||
{ total: 9, online: 9, offline: 0 },
|
||||
];
|
||||
for (const c of cases) {
|
||||
const s = fleetStatus(c);
|
||||
expect(`${s.headline} ${s.sentence}`).not.toMatch(/undefined|NaN|null/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Resolves the dashboard's headline device status.
|
||||
*
|
||||
* Exists because the summary can legitimately be *absent* rather than zero, and
|
||||
* the two are not the same claim. Switching site remounts the tree against an
|
||||
* empty cache (see SiteScopedQueryProvider), so there is always a moment with no
|
||||
* summary — which rendered "undefined device(s) unreachable". Substituting 0
|
||||
* would have been just as wrong in the other direction: reporting a healthy
|
||||
* fleet we have not heard from yet.
|
||||
*
|
||||
* A site with no devices is a third distinct state, and one multi-site makes
|
||||
* ordinary: "0 devices unreachable" is technically true and reads as nonsense.
|
||||
*/
|
||||
|
||||
export interface FleetSummaryDevices {
|
||||
total: number;
|
||||
online: number;
|
||||
offline: number;
|
||||
}
|
||||
|
||||
export type FleetStatusKind = 'loading' | 'empty' | 'healthy' | 'degraded';
|
||||
|
||||
export interface FleetStatus {
|
||||
kind: FleetStatusKind;
|
||||
/** Compact label for the summary header. */
|
||||
headline: string;
|
||||
/** Sentence form for the operations hero. */
|
||||
sentence: string;
|
||||
tone: 'neutral' | 'good' | 'warn';
|
||||
}
|
||||
|
||||
export function fleetStatus(devices?: FleetSummaryDevices | null): FleetStatus {
|
||||
if (!devices) {
|
||||
return { kind: 'loading', headline: 'Checking…', sentence: 'Checking…', tone: 'neutral' };
|
||||
}
|
||||
if (devices.total === 0) {
|
||||
return {
|
||||
kind: 'empty',
|
||||
headline: 'No devices yet',
|
||||
sentence: 'No devices in this site yet.',
|
||||
tone: 'neutral',
|
||||
};
|
||||
}
|
||||
if (devices.offline === 0) {
|
||||
return {
|
||||
kind: 'healthy',
|
||||
headline: 'All systems nominal',
|
||||
sentence: "Everything's running.",
|
||||
tone: 'good',
|
||||
};
|
||||
}
|
||||
const n = devices.offline;
|
||||
const noun = `device${n === 1 ? '' : 's'}`;
|
||||
return {
|
||||
kind: 'degraded',
|
||||
headline: `${n} ${noun} unreachable`,
|
||||
sentence: `${n} ${noun} unreachable.`,
|
||||
tone: 'warn',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Address → coordinates via Nominatim.
|
||||
*
|
||||
* Extracted from DeviceLocationSection so device locations and site locations
|
||||
* share one implementation (issue #130). Callers must check the `maps_enabled`
|
||||
* setting before calling: geocoding is a third-party request that discloses
|
||||
* where your hardware is, and issue #106 exists to let operators refuse it.
|
||||
*/
|
||||
export async function geocodeAddress(address: string): Promise<{ lat: number; lng: number } | null> {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(address)}&format=json&limit=1`,
|
||||
{ headers: { Accept: 'application/json' } }
|
||||
);
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
return { lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon) };
|
||||
}
|
||||
} catch {
|
||||
// Geocoding is best-effort: a site without coordinates simply has no pin.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The tile source used by every map in the app, so attribution stays consistent. */
|
||||
export const OSM_TILE_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
export const OSM_ATTRIBUTION =
|
||||
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
|
||||
Reference in New Issue
Block a user