feat(admin): online means a tab in front, and keeps last activity current

Online in the user list meant any open socket, so a tab left in the background showed as online for days while its last activity stood still. The client now sends a presence frame on connect and on every visibility change; only sockets whose tab is visible count as online (one that never sent the frame still counts, so older clients are unchanged). While a tab is in front, the gateway writes its session's last_seen_at at most every five minutes, on the frame and on the heartbeat, so last activity follows the online state.
This commit is contained in:
Maurice
2026-11-29 10:04:15 +01:00
parent 467287f138
commit 5401728c41
7 changed files with 244 additions and 23 deletions
@@ -1,5 +1,6 @@
import { AppSettings } from '../../db/entities/AppSettings.entity';
import { Trips } from '../../db/entities/Trips.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { Users } from '../../db/entities/Users.entity';
import { EphemeralTokenModule } from '../auth-core/ephemeral-token.module';
import { DatabaseLifecycleModule } from '../database/database-lifecycle.module';
@@ -35,7 +36,7 @@ import { Module, type OnModuleDestroy } from '@nestjs/common';
TripMembershipModule,
EphemeralTokenModule,
DatabaseLifecycleModule,
MikroOrmModule.forFeature([Users, AppSettings, Trips]),
MikroOrmModule.forFeature([Users, AppSettings, Trips, UserSessions]),
],
// The room registry is the process-wide in-memory one; the constructor
// below hands whichever one the container resolved to the broadcast
@@ -1,11 +1,15 @@
import { runningVersion } from '../../app-config';
import { AppSettings } from '../../db/entities/AppSettings.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { Users } from '../../db/entities/Users.entity';
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { dbNow } from '../../db/types/db-timestamp.type';
import { User } from '../../types';
import { logError } from '../audit/audit-log.logger';
import { EphemeralTokenService } from '../auth-core/ephemeral-token.service';
import { SESSION_TOUCH_INTERVAL_MS } from '../auth-core/jwt-verify';
import { readAppSetting } from '../common/app-settings.registry';
import { toRowId } from '../common/row-id';
import { TripAccessService } from '../trip-membership/trip-access.service';
@@ -19,7 +23,10 @@ import {
RoomRegistry,
roomsSlot,
sessionClosed,
sessionOf,
setSocketVisible,
socketIdOf,
socketVisible,
userOf,
type RoomAccess,
type TrekWebSocket,
@@ -80,6 +87,8 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
@Inject(JOURNEY_ACCESS) private readonly journeys: JourneyAccess,
@InjectRepository(Users) private readonly users: UsersRepository,
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
// A tab in front keeps its session's last activity current (presence below).
@InjectRepository(UserSessions) private readonly sessions: UserSessionsRepository,
// Room membership, behind its port. The container's provider, which
// RealtimeGatewayModule also installs for the broadcast functions in
// ws-state.ts; a hand-built gateway takes the installed one.
@@ -95,6 +104,9 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
book: async (journeyId, userId) => !!(await this.journeys.canAccessJourney(journeyId, userId)),
};
/** When each socket last wrote its session's activity, so a tab in front writes once per interval, not per beat. */
private readonly touchedAt = new WeakMap<TrekWebSocket, number>();
afterInit(server: WebSocketServer): void {
this.heartbeat = setInterval(() => {
server.clients.forEach((ws) => {
@@ -102,6 +114,7 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
if (tws.isAlive === false) return tws.terminate();
tws.isAlive = false;
tws.ping();
void this.touchSession(tws);
});
}, HEARTBEAT_INTERVAL);
this.heartbeat.unref?.();
@@ -195,6 +208,40 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
for (const journeyId of this.rooms.leaveAllBooks(socket)) this.announcePeers(journeyId);
}
/**
* The client says whether its tab is in front. Only such a tab counts as
* online in the admin's user list, and while one is, its session's last
* activity moves on with it, as a request would move it: someone reading a
* trip without clicking is still using TREK.
*/
@SubscribeMessage('presence')
async handlePresence(
@MessageBody() message: { visible?: unknown },
@ConnectedSocket() socket: TrekWebSocket,
): Promise<undefined> {
if (!userOf(socket)) return undefined;
setSocketVisible(socket, message?.visible !== false);
await this.touchSession(socket);
return undefined;
}
/**
* Writes the socket's session as active now, for a tab in front, at most
* once per SESSION_TOUCH_INTERVAL_MS (the same pace the request check keeps).
*/
private async touchSession(socket: TrekWebSocket, now = Date.now()): Promise<void> {
const session = sessionOf(socket);
if (!session || !socketVisible(socket) || socket.readyState !== 1) return;
if (now - (this.touchedAt.get(socket) ?? 0) < SESSION_TOUCH_INTERVAL_MS) return;
this.touchedAt.set(socket, now);
try {
await this.sessions.touchLastSeen(session, dbNow(new Date(now)));
} catch (err) {
// Bookkeeping for the user list only: a busy database must not cost the socket.
logError(`ws presence touch failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
@SubscribeMessage('join')
async handleJoin(
@MessageBody() message: { tripId?: number | string },
+28 -1
View File
@@ -144,6 +144,12 @@ const socketUser = new WeakMap<TrekWebSocket, User>();
const socketId = new WeakMap<TrekWebSocket, number>();
/** The session (`user_sessions.id`) the socket's ws token was minted under, where the request that minted it had one. */
const socketSession = new WeakMap<TrekWebSocket, string>();
/**
* Sockets whose tab said it is in the background (a `presence` frame). A
* socket that never said anything counts as in front, so a client from before
* the frame existed keeps showing as online.
*/
const hiddenSockets = new WeakSet<TrekWebSocket>();
/**
* Sessions whose sockets were just closed, by the time it happened. A ws token
@@ -194,6 +200,22 @@ export function userOf(ws: TrekWebSocket): User | undefined {
return socketUser.get(ws);
}
/** The session the socket belongs to, when its token named one. */
export function sessionOf(ws: TrekWebSocket): string | undefined {
return socketSession.get(ws);
}
/** Records whether the socket's tab is in front, as its last `presence` frame said. */
export function setSocketVisible(ws: TrekWebSocket, visible: boolean): void {
if (visible) hiddenSockets.delete(ws);
else hiddenSockets.add(ws);
}
/** Whether the socket's tab is in front (true until it says otherwise). */
export function socketVisible(ws: TrekWebSocket): boolean {
return !hiddenSockets.has(ws);
}
export function joinRoom(ws: TrekWebSocket, tripId: number): void {
roomsSlot.get().join(ws, tripId);
}
@@ -303,12 +325,17 @@ export function broadcastToUser(userId: number, payload: Record<string, unknown>
}
}
/**
* Who has TREK in front of them right now: an open socket whose tab is
* visible. A tab left open in the background does not count, or anyone who
* never closes a tab would show as online for days.
*/
export function getOnlineUserIds(): Set<number> {
const ids = new Set<number>();
if (!wss) return ids;
for (const ws of wss.clients) {
const tws = ws as TrekWebSocket;
if (tws.readyState !== 1) continue;
if (tws.readyState !== 1 || !socketVisible(tws)) continue;
const user = socketUser.get(tws);
if (user) ids.add(user.id);
}