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
+37 -3
View File
@@ -1,7 +1,7 @@
// vi.unmock must run before the module is imported (tests/setup.ts mocks it globally)
vi.unmock('./websocket')
// FE-WSCORE-001 to FE-WSCORE-016
// FE-WSCORE-001 to FE-WSCORE-018
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
@@ -135,18 +135,52 @@ describe('websocket > reconnect refetch hook', () => {
)
})
it('FE-WSCORE-005: with no joined trips onopen sends nothing and skips the refetch', async () => {
it('FE-WSCORE-005: with no joined trips onopen sends only its presence and skips the refetch', async () => {
const refetch = vi.fn((_tripId: string) => {})
setRefetchCallback(refetch)
const sock = await openSocket()
sock.onopen!()
expect(sock.send).not.toHaveBeenCalled()
expect(sock.send.mock.calls.map(([raw]) => JSON.parse(raw).type)).toEqual(['presence'])
expect(refetch).not.toHaveBeenCalled()
})
})
describe('websocket > presence', () => {
function presences(sock: MockWebSocket): unknown[] {
return sock.send.mock.calls.map(([raw]) => JSON.parse(raw)).filter(m => m.type === 'presence').map(m => m.visible)
}
function setVisibility(state: 'visible' | 'hidden'): void {
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state })
document.dispatchEvent(new Event('visibilitychange'))
}
afterEach(() => {
delete (document as { visibilityState?: unknown }).visibilityState
})
it('FE-WSCORE-017: tells the server on open and on every change whether the tab is in front', async () => {
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' })
const sock = await openSocket()
sock.onopen!()
setVisibility('hidden')
setVisibility('visible')
expect(presences(sock)).toEqual([true, false, true])
})
it('FE-WSCORE-018: stops telling it once logged out', async () => {
const sock = await openSocket()
sock.onopen!()
disconnect()
setVisibility('hidden')
expect(presences(sock)).toHaveLength(1)
})
})
describe('websocket > connection lifecycle', () => {
it('FE-WSCORE-006: connect() is a no-op while a socket is still CONNECTING', async () => {
const sock = await openSocket()
+14
View File
@@ -129,6 +129,7 @@ async function connectInternal(_isReconnect = false): Promise<void> {
socket.onopen = () => {
reconnectDelay = 1000
sendPresence()
activeBooks.forEach(journeyId => {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'book:join', journeyId }))
@@ -173,6 +174,17 @@ async function connectInternal(_isReconnect = false): Promise<void> {
}
}
/**
* Tells the server whether this tab is in front. Online, in the admin's user
* list, means a tab someone is looking at, not one left open in the
* background, and while one is in front the server keeps the account's
* last activity current.
*/
function sendPresence(): void {
if (!socket || socket.readyState !== WebSocket.OPEN || typeof document === 'undefined') return
socket.send(JSON.stringify({ type: 'presence', visible: document.visibilityState === 'visible' }))
}
/**
* The network came back or the tab became visible: a socket waiting out its
* backoff (up to 30 s) reconnects now. Does nothing while logged out or while
@@ -186,6 +198,7 @@ export function reconnectNow(): void {
export function connect(): void {
shouldReconnect = true
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', sendPresence)
reconnectDelay = 1000
if (reconnectTimer) {
clearTimeout(reconnectTimer)
@@ -196,6 +209,7 @@ export function connect(): void {
export function disconnect(): void {
shouldReconnect = false
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', sendPresence)
generation++
if (reconnectTimer) {
clearTimeout(reconnectTimer)
@@ -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);
}
+98 -16
View File
@@ -1,5 +1,6 @@
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import type { UserSessionsRepository } from '../../../src/db/repositories/UserSessions.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { logError } from '../../../src/nest/audit/audit-log.logger';
import type { EphemeralTokenService } from '../../../src/nest/auth-core/ephemeral-token.service';
@@ -18,6 +19,7 @@ import {
joinRoom,
registerSocket,
setServer,
setSocketVisible,
userOf,
type TrekWebSocket,
} from '../../../src/nest/realtime/ws-state';
@@ -86,6 +88,9 @@ const appSettings = {
),
} as unknown as AppSettingsRepository;
const touchLastSeen = vi.fn(async (_session: string, _now: string) => undefined);
const sessions = { touchLastSeen } as unknown as UserSessionsRepository;
const consumeWithMeta = vi.fn();
const tokens = { consumeWithMeta } as unknown as EphemeralTokenService;
@@ -94,7 +99,7 @@ const canAccessJourney = vi.fn((journeyId: number) => (journeyId === 4 ? null :
const journeys = { canAccessJourney } as unknown as JourneyDomainService;
async function connect(url: string) {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
await gw.handleConnection(ws, { url } as never);
return { gw, ws };
@@ -164,7 +169,7 @@ describe('RealtimeGateway handshake', () => {
});
it('WSGW-007b: survives an upgrade request with no url, rather than throwing at it', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
await expect(gw.handleConnection(ws, {} as never)).resolves.not.toThrow();
expect(ws.closedWith).toEqual([4001, 'Authentication required']);
@@ -206,7 +211,7 @@ describe('RealtimeGateway handshake', () => {
throw new Error('db exploded');
},
} as unknown as UsersRepository;
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, throwingUsers, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, throwingUsers, appSettings, sessions);
const ws = socket();
await gw.handleConnection(ws, { url: '/ws?token=x' } as never);
@@ -221,7 +226,7 @@ describe('RealtimeGateway handshake', () => {
throw 'db string';
}, // non-Error throw, pinning the ternary's String(err) fallback
} as unknown as UsersRepository;
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, throwingUsers, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, throwingUsers, appSettings, sessions);
const ws = socket();
await gw.handleConnection(ws, { url: '/ws?token=x' } as never);
@@ -266,7 +271,7 @@ describe('RealtimeGateway heartbeat', () => {
alive.isAlive = true;
const stale = socket();
stale.isAlive = false;
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
gw.afterInit({ clients: new Set([alive, stale]) } as never);
vi.advanceTimersByTime(30_000);
@@ -287,7 +292,7 @@ describe('RealtimeGateway heartbeat', () => {
try {
const ws = socket();
ws.isAlive = true;
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
gw.afterInit({ clients: new Set([ws]) } as never);
gw.onModuleDestroy();
@@ -426,7 +431,7 @@ describe('book rooms', () => {
/** A gateway and a registered socket that has not joined any book yet. */
function bookSocket() {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
registerSocket(ws, { id: 3, username: 'm' } as User);
return { gw, ws };
@@ -447,7 +452,7 @@ describe('book rooms', () => {
/* Same shape as the trip room's refusal, and for the same reason. */
it('WSGW-BOOK-002: refuses a journey the user cannot see, and adds nobody', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
registerSocket(ws, { id: 3, username: 'm' } as User);
@@ -508,7 +513,7 @@ describe('book pointers', () => {
async function pair() {
const journeyId = nextJourney++;
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const mine = socket();
const theirs = socket();
registerSocket(mine, { id: 3, username: 'm' } as User);
@@ -573,7 +578,7 @@ describe('book messages that are refused', () => {
let nextJourney = 300;
it('WSGW-BOOK-006: a join without a journey id is ignored', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
registerSocket(ws, { id: 3, username: 'm' } as User);
@@ -583,7 +588,7 @@ describe('book messages that are refused', () => {
/* An unauthenticated socket never got as far as the registry. */
it('WSGW-BOOK-007: a join from a socket with no user is ignored', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const j = nextJourney++;
expect(await gw.handleBookJoin({ journeyId: j }, socket())).toBeUndefined();
@@ -591,7 +596,7 @@ describe('book messages that are refused', () => {
});
it('WSGW-BOOK-008: a journey id that is not a number is refused, not joined', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
registerSocket(ws, { id: 3, username: 'm' } as User);
@@ -602,7 +607,7 @@ describe('book messages that are refused', () => {
});
it('WSGW-BOOK-009: a leave without a journey id is ignored', () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
registerSocket(ws, { id: 3, username: 'm' } as User);
@@ -611,7 +616,7 @@ describe('book messages that are refused', () => {
/* Leaving a room nobody is in must not create one on the way out. */
it('WSGW-BOOK-010: leaving a book that was never joined does nothing', () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const ws = socket();
registerSocket(ws, { id: 3, username: 'm' } as User);
const j = nextJourney++;
@@ -621,7 +626,7 @@ describe('book messages that are refused', () => {
});
it('WSGW-CUR-005: a pointer without a journey id reaches nobody', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const mine = socket();
const theirs = socket();
registerSocket(mine, { id: 3, username: 'm' } as User);
@@ -636,7 +641,7 @@ describe('book messages that are refused', () => {
});
it('WSGW-CUR-006: a pointer from a socket with no user reaches nobody', async () => {
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings);
const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
const theirs = socket();
registerSocket(theirs, { id: 4, username: 'o' } as User);
const j = nextJourney++;
@@ -729,3 +734,80 @@ describe('book rooms with unusable sockets in them', () => {
expect(() => leaveBook(ws, nextJourney++)).not.toThrow();
});
});
/*
* Presence: who has TREK in front of them. Online in the admin's user list is
* a visible tab, not one left open in the background, and a tab in front keeps
* its session's last activity current without any request.
*/
describe('RealtimeGateway presence', () => {
const gateway = () => new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
it('WSGW-PRES-001: a tab in the background is not online, one in front is, one that never said is', async () => {
const hidden = socket();
const front = socket();
const silent = socket();
registerSocket(hidden, { id: 11, username: 'h' } as User);
registerSocket(front, { id: 12, username: 'f' } as User);
registerSocket(silent, { id: 13, username: 's' } as User);
setServer({ clients: new Set([hidden, front, silent]) } as never);
const gw = gateway();
await gw.handlePresence({ visible: false }, hidden);
await gw.handlePresence({ visible: true }, front);
expect(getOnlineUserIds()).toEqual(new Set([12, 13]));
setServer(null);
});
it('WSGW-PRES-002: a tab coming to the front writes its session as active, at most once per interval', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-11-29T09:00:00Z'));
const ws = socket();
registerSocket(ws, { id: 14, username: 'p' } as User, 'sess-p');
const gw = gateway();
await gw.handlePresence({ visible: true }, ws);
await gw.handlePresence({ visible: true }, ws);
vi.setSystemTime(new Date('2026-11-29T09:06:00Z'));
await gw.handlePresence({ visible: true }, ws);
expect(touchLastSeen.mock.calls).toEqual([
['sess-p', '2026-11-29 09:00:00'],
['sess-p', '2026-11-29 09:06:00'],
]);
vi.useRealTimers();
});
it('WSGW-PRES-003: a hidden tab, a socket without a session and an unknown socket write nothing', async () => {
const hidden = socket();
const noSession = socket();
registerSocket(hidden, { id: 15, username: 'h' } as User, 'sess-h');
registerSocket(noSession, { id: 16, username: 'n' } as User);
const gw = gateway();
await gw.handlePresence({ visible: false }, hidden);
await gw.handlePresence({ visible: true }, noSession);
await gw.handlePresence({ visible: true }, socket());
expect(touchLastSeen).not.toHaveBeenCalled();
});
it('WSGW-PRES-004: the heartbeat keeps a tab in front active, and a failed write is logged, not thrown', async () => {
vi.useFakeTimers();
const ws = socket();
ws.isAlive = true;
registerSocket(ws, { id: 17, username: 'b' } as User, 'sess-b');
setSocketVisible(ws, true);
touchLastSeen.mockRejectedValueOnce(new Error('busy'));
const gw = gateway();
gw.afterInit({ clients: new Set([ws]) } as never);
await vi.advanceTimersByTimeAsync(30_000);
expect(touchLastSeen).toHaveBeenCalledWith('sess-b', expect.any(String));
expect(logError).toHaveBeenCalledWith(expect.stringContaining('ws presence touch failed'));
gw.onModuleDestroy();
vi.useRealTimers();
});
});
@@ -288,7 +288,15 @@ describe('the gateway asks again from inside the room', () => {
it('WSREV-015: a trip join whose access ended while the first answer was on its way is refused', async () => {
const findAccessible = vi.fn().mockResolvedValueOnce({ id: 5 }).mockResolvedValueOnce(undefined);
const trips = { findAccessible } as unknown as TripAccessService;
const gw = new RealtimeGateway(trips, tokens, { canAccessJourney: vi.fn() }, users, appSettings, rooms);
const gw = new RealtimeGateway(
trips,
tokens,
{ canAccessJourney: vi.fn() },
users,
appSettings,
{ touchLastSeen: vi.fn() } as never,
rooms,
);
const ws = open(1);
expect(await gw.handleJoin({ tripId: 5 }, ws)).toEqual({ type: 'error', message: 'Access denied' });
@@ -298,7 +306,15 @@ describe('the gateway asks again from inside the room', () => {
it('WSREV-016: so is a book join', async () => {
const canAccessJourney = vi.fn().mockResolvedValueOnce({ id: 9 }).mockResolvedValueOnce(null);
const trips = { findAccessible: vi.fn() } as unknown as TripAccessService;
const gw = new RealtimeGateway(trips, tokens, { canAccessJourney }, users, appSettings, rooms);
const gw = new RealtimeGateway(
trips,
tokens,
{ canAccessJourney },
users,
appSettings,
{ touchLastSeen: vi.fn() } as never,
rooms,
);
const ws = open(1);
expect(await gw.handleBookJoin({ journeyId: 9 }, ws)).toEqual({ type: 'error', message: 'Access denied' });