feat(wireless): reconstruct per-client roaming history from AP logs (v0.23.11-beta)

Closes #105.

RouterOS narrates the whole life of an association in its log — association, every
band or AP change, and the disconnect — each line carrying the signal at that
moment. Nothing else in the platform can see any of it: roaming happens between
polls, so a poll only ever observes where a client ended up, never that it moved.

Sessions are now rebuilt from those lines and shown on the client detail page: the
path across radios, signal at each step, duration, and RouterOS's own disconnect
reason. Sessions averaging six or more roams an hour are flagged, since a client
bouncing between radios is usually a roaming-threshold problem rather than a faulty
client.

No new collection and no new storage. It reads the events already gathered, so it
works retroactively over whatever log history exists.

Two things came out of testing against real logs rather than the samples in the
issue, and both were wrong in ways the samples could not have shown:

  Ordering. RouterOS log timestamps are second-granular, so a reassociation emits
  its disconnect and reconnect inside the same logged second, and collection
  assigns sub-second values in whichever order they were read — observed on a live
  AP as both `.849/.849` and `.096/.097` for the same kind of pair. Sorting on the
  raw timestamp attached the disconnect to the session the connect had just opened,
  so every reassociation reconstructed as a 0-second session while the real one
  disappeared. On one IoT client that was 255 phantom sessions out of 422. Events
  are now ordered by whole second and ties broken by meaning: a disconnect closes
  what came before, a connect opens what comes after. The same client now shows its
  real behaviour — 900s, 840s and 930s sessions, reassociating every 15 minutes.

  Signal sanity. Real logs contain `signal strength 91`. dBm is negative, so a
  positive reading is not a measurement; recording it would draw a client with an
  impossibly perfect signal. Treated as unknown.

21 tests, including the full ping-pong trace quoted in the issue — which the
reconstruction correctly identifies as flapping — plus both timestamp-collision
shapes seen in production.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2GT-Rich
2026-08-22 21:27:14 -07:00
co-authored by Claude Opus 5
parent 37887d38c2
commit 57d650c159
11 changed files with 820 additions and 4 deletions
+52
View File
@@ -5,6 +5,7 @@ import { requireAuth, requireAdmin, requireWrite } from '../middleware/auth';
import { PollerService } from '../services/PollerService';
import { getQueryApi, bucket } from '../config/influxdb';
import { fingerprintClient, DEVICE_CATEGORIES, DeviceCategory } from '../utils/clientFingerprint';
import { parseRoamLine, buildSessions, flappingSessions } from '../utils/roaming';
// Effective category: the user's override wins; otherwise the fingerprint.
function withCategory<T extends Record<string, unknown>>(row: T): T & { device_category: string; auto_category: string } {
@@ -23,6 +24,57 @@ router.use(requireAuth);
let pollerService: PollerService | null = null;
export function setPollerService(p: PollerService): void { pollerService = p; }
/**
* GET /api/clients/:mac/roaming — reconstruct this client's wireless sessions.
*
* Built from log lines already collected into `events`, so it needs no new
* collection and works retroactively over whatever history exists. Roaming happens
* between polls, so the log is the only place it is visible at all (issue #105).
*/
router.get('/:mac/roaming', async (req: Request, res: Response) => {
const mac = String(req.params.mac).toUpperCase();
if (!/^[0-9A-F:]{17}$/.test(mac)) return res.status(400).json({ error: 'Invalid MAC address' });
const range = String(req.query.range || '24h');
const hours = range === '7d' ? 168 : range === '30d' ? 720 : range === '1h' ? 1 : 24;
// Time-bounded first so the scan stays small — most of an events table is login
// noise. Both message shapes are matched: wireless lines start with the MAC,
// DHCP lines carry it mid-string.
const rows = await query<{ event_time: string; message: string; device_name: string | null }>(
`SELECT e.event_time, e.message, d.name AS device_name
FROM events e
LEFT JOIN devices d ON d.id = e.device_id
WHERE e.event_time > NOW() - ($2 || ' hours')::interval
AND (e.message ILIKE $1 || '@%' OR e.message ILIKE '%for ' || $1 || '%')
ORDER BY e.event_time ASC
LIMIT 5000`,
[mac, String(hours)]
);
const events = rows
.map((r) => parseRoamLine(r.message, new Date(r.event_time).toISOString(), r.device_name))
.filter((e): e is NonNullable<typeof e> => e !== null && e.mac === mac);
const sessions = buildSessions(events);
const flapping = flappingSessions(sessions);
res.json({
mac,
range,
sessions: [...sessions].reverse(), // newest first for display
totalRoams: sessions.reduce((n, s) => n + s.hops.length, 0),
flappingSessions: flapping.length,
/** Radios this client has been seen on, most-used first. */
radios: Object.entries(
sessions.flatMap((s) => s.path).reduce<Record<string, number>>((acc, i) => {
acc[i] = (acc[i] ?? 0) + 1;
return acc;
}, {})
).sort((a, b) => b[1] - a[1]).map(([name, count]) => ({ name, count })),
});
});
// GET /api/clients
router.get('/', async (req: Request, res: Response) => {
const {