mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
fix(ci): presence through the sessions domain, warm bags taken once, a slimmer planner page
Server lint: the realtime gateway injected the user_sessions repository, a table the sessions domain owns; it now asks SessionsService. The presence tests reuse the handshake's gateway instead of building one more by hand (test-new-service ratchet). Client tests: the packing bags kept per trip leaked from one test (and one list) into the next; bags read ahead are now taken once as the list's first state, and only while bag tracking is on. The planner hook hands the page planMapKept, tourMapKept and the tour stage's class, so page tests that mock the hook keep working and TripPlannerPage is back at its size baseline (1127); the B4A wiring test reads the new condition. Client lint: max-depth in src is down to 19, the baseline follows; the new websocket tests call onopen with ?. instead of a non-null assertion.
This commit is contained in:
@@ -22,7 +22,7 @@
|
||||
"trek/no-window-globals": 41,
|
||||
"react-refresh/only-export-components": 44,
|
||||
"unused-disable-directive": 5,
|
||||
"max-depth": 21,
|
||||
"max-depth": 19,
|
||||
"react-hooks/void-use-memo": 1,
|
||||
"@typescript-eslint/no-unused-expressions": 2,
|
||||
"react-hooks/purity": 1,
|
||||
|
||||
@@ -164,7 +164,7 @@ describe('websocket > presence', () => {
|
||||
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!()
|
||||
sock.onopen?.()
|
||||
setVisibility('hidden')
|
||||
setVisibility('visible')
|
||||
|
||||
@@ -173,7 +173,7 @@ describe('websocket > presence', () => {
|
||||
|
||||
it('FE-WSCORE-018: stops telling it once logged out', async () => {
|
||||
const sock = await openSocket()
|
||||
sock.onopen!()
|
||||
sock.onopen?.()
|
||||
disconnect()
|
||||
setVisibility('hidden')
|
||||
|
||||
|
||||
@@ -14,17 +14,24 @@ interface Toaster {
|
||||
}
|
||||
|
||||
/**
|
||||
* The last bags read per trip in this tab. A list opened again, or opened after
|
||||
* the trip read them ahead (warmPackingBags), starts with them instead of
|
||||
* drawing the list first and the bag sidebar a moment later; the read that
|
||||
* follows only refreshes them.
|
||||
* Bags a trip read ahead while it sat open (warmPackingBags), waiting for the
|
||||
* packing list to open. The list takes them once as its first state, so it
|
||||
* opens with its bag sidebar in place instead of drawing it a moment later;
|
||||
* its own read follows and refreshes them. Taken, not kept: a list opened
|
||||
* later reads afresh rather than starting from an old answer.
|
||||
*/
|
||||
const keptBags = new Map<number, { bags: PackingBag[]; unassigned: number | null }>();
|
||||
const warmBags = new Map<number, { bags: PackingBag[]; unassigned: number | null }>();
|
||||
|
||||
/** Reads a trip's bags ahead, while it sits open, for the list to start with. */
|
||||
/** Reads a trip's bags ahead, while it sits open, for the packing list to start with. */
|
||||
export async function warmPackingBags(tripId: number): Promise<void> {
|
||||
const r = await packingApi.listBags(tripId);
|
||||
keptBags.set(tripId, { bags: r.bags || [], unassigned: r.unassigned_weight_grams ?? null });
|
||||
warmBags.set(tripId, { bags: r.bags || [], unassigned: r.unassigned_weight_grams ?? null });
|
||||
}
|
||||
|
||||
function takeWarmBags(tripId: number, enabled: boolean): { bags: PackingBag[]; unassigned: number | null } {
|
||||
const warm = enabled ? warmBags.get(tripId) : undefined;
|
||||
warmBags.delete(tripId);
|
||||
return warm ?? { bags: [], unassigned: null };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,16 +50,10 @@ export function usePackingBags({
|
||||
t: Translate;
|
||||
toast: Toaster;
|
||||
}) {
|
||||
const [bags, setBags] = useState<PackingBag[]>(() => keptBags.get(tripId)?.bags ?? []);
|
||||
const [warm] = useState(() => takeWarmBags(tripId, bagTrackingEnabled));
|
||||
const [bags, setBags] = useState<PackingBag[]>(warm.bags);
|
||||
/** Server-summed weight of everything in no bag (#2191); null until the first load. */
|
||||
const [unassignedWeightGrams, setUnassignedWeightGrams] = useState<number | null>(
|
||||
() => keptBags.get(tripId)?.unassigned ?? null
|
||||
);
|
||||
|
||||
// What the list shows now is what it starts with next time.
|
||||
useEffect(() => {
|
||||
keptBags.set(tripId, { bags, unassigned: unassignedWeightGrams });
|
||||
}, [tripId, bags, unassignedWeightGrams]);
|
||||
const [unassignedWeightGrams, setUnassignedWeightGrams] = useState<number | null>(warm.unassigned);
|
||||
|
||||
const reloadBags = useCallback(async () => {
|
||||
if (!bagTrackingEnabled) return;
|
||||
|
||||
@@ -73,7 +73,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
dawarichEnabled, dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates,
|
||||
followTrack, roadtripViaCounts,
|
||||
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
|
||||
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, keptMapTabs,
|
||||
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, planMapKept, tourMapKept, tourStageClass,
|
||||
leftWidth, rightWidth,
|
||||
leftHidden, rightHidden, toggleLeft, toggleRight,
|
||||
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,
|
||||
@@ -259,11 +259,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
plugins with a tab here, floating bottom overlay for the rest. */}
|
||||
<TripWarningsBanner tripId={tripId} onOpenPluginTab={(pid) => handleTabChange(`plugin:${pid}`)} />
|
||||
|
||||
{/* Plan and the tour planner each keep their map once opened, hidden while
|
||||
another tab shows, so switching back does not start a map again. Not on
|
||||
a narrow screen, where the plan tab puts its own controls over the page. */}
|
||||
{(activeTab === 'plan' || (keptMapTabs.has('plan') && !isMobile)) && (
|
||||
<div style={{ position: 'absolute', inset: 0, visibility: activeTab === 'plan' ? undefined : 'hidden' }}>
|
||||
{(activeTab === 'plan' || planMapKept) && (
|
||||
<div className={activeTab === 'plan' ? undefined : 'invisible'} style={{ position: 'absolute', inset: 0 }}>
|
||||
<PlanMapStage
|
||||
tripId={tripId} trip={trip} can={can} days={days} places={places} reservations={reservations} isMobile={isMobile}
|
||||
selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedPlace={selectedPlace} showDayDetail={showDayDetail} handleSelectDay={handleSelectDay}
|
||||
@@ -620,8 +617,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(activeTab === 'tour-planner' || keptMapTabs.has('tour-planner')) && enabledAddons.tours && !isMobile && (
|
||||
<TourGpxDropZone gpxImport={tourGpxImport} canEdit={canPlaceEdit} className={activeTab === 'tour-planner' ? 'absolute inset-0' : 'invisible absolute inset-0'}>
|
||||
{(activeTab === 'tour-planner' || tourMapKept) && enabledAddons.tours && !isMobile && (
|
||||
<TourGpxDropZone gpxImport={tourGpxImport} canEdit={canPlaceEdit} className={tourStageClass}>
|
||||
<TourPlannerMapStage
|
||||
tripId={tripId} mapTileUrl={mapTileUrl} leftHidden={leftHidden} rightHidden={rightHidden} t={t}
|
||||
tourPlanner={tourPlanner} tourMap={tourMap} locationSearch={locationSearch} canPlaceEdit={canPlaceEdit}
|
||||
|
||||
@@ -105,7 +105,7 @@ test('B4A Tours tab is readable, desktop-only off a large screen, and absent wit
|
||||
assert.match(branch.whenTrue.getText(hook), /desktopOnly: tourTab\.desktopOnly/)
|
||||
assert.doesNotMatch(tabs.getText(hook), /\bcan\b|canPlaceEdit|canDayEdit/)
|
||||
assert.match(hookText, /!validTabIds\.includes\(activeTab\)[\s\S]*?setActiveTab\('plan'\)/)
|
||||
assert.match(pageText, /activeTab === 'tour-planner' && enabledAddons\.tours && !isMobile/)
|
||||
assert.match(pageText, /\(activeTab === 'tour-planner' \|\| tourMapKept\) && enabledAddons\.tours && !isMobile/)
|
||||
// The app counts as a phone shell on an iPad too: the workspace follows its tab, not the phone test.
|
||||
assert.equal(initializer(workspace, 'workspaceUp').getText(workspace), "activeTab === 'tour-planner' && (!isMobile || largeTouch)")
|
||||
assert.doesNotMatch(workspaceText, /!isMobile(?! \|\| largeTouch)/)
|
||||
|
||||
@@ -783,7 +783,10 @@ export function useTripPlanner() {
|
||||
dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates, dawarichEnabled: !!enabledAddons.dawarich,
|
||||
followTrack, roadtripViaCounts,
|
||||
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
|
||||
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, keptMapTabs, tabLink,
|
||||
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, tabLink,
|
||||
// Not on a narrow screen, where the plan tab portals its own controls over the page.
|
||||
planMapKept: keptMapTabs.has('plan') && !isMobile, tourMapKept: keptMapTabs.has('tour-planner'),
|
||||
tourStageClass: activeTab === 'tour-planner' ? 'absolute inset-0' : 'invisible absolute inset-0',
|
||||
leftWidth, rightWidth, viewportWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed,
|
||||
leftHidden, rightHidden, toggleLeft, toggleRight, narrowPanels,
|
||||
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
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';
|
||||
import { DatabaseLifecycle } from '../database/database-lifecycle.service';
|
||||
import { SessionsModule } from '../sessions/sessions.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { RealtimeGateway } from './realtime.gateway';
|
||||
import { closeSockets, processRooms, RoomRegistry, roomsSlot } from './ws-state';
|
||||
@@ -36,7 +36,8 @@ import { Module, type OnModuleDestroy } from '@nestjs/common';
|
||||
TripMembershipModule,
|
||||
EphemeralTokenModule,
|
||||
DatabaseLifecycleModule,
|
||||
MikroOrmModule.forFeature([Users, AppSettings, Trips, UserSessions]),
|
||||
SessionsModule,
|
||||
MikroOrmModule.forFeature([Users, AppSettings, Trips]),
|
||||
],
|
||||
// The room registry is the process-wide in-memory one; the constructor
|
||||
// below hands whichever one the container resolved to the broadcast
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
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';
|
||||
@@ -12,6 +10,7 @@ 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 { SessionsService } from '../sessions/sessions.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { JOURNEY_ACCESS, type JourneyAccess } from './journey-access.types';
|
||||
import {
|
||||
@@ -87,8 +86,9 @@ 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,
|
||||
// A tab in front keeps its session's last activity current (presence below),
|
||||
// written through the sessions domain that owns the table.
|
||||
private readonly sessions: SessionsService,
|
||||
// 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.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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';
|
||||
@@ -23,6 +22,7 @@ import {
|
||||
userOf,
|
||||
type TrekWebSocket,
|
||||
} from '../../../src/nest/realtime/ws-state';
|
||||
import type { SessionsService } from '../../../src/nest/sessions/sessions.service';
|
||||
import { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';
|
||||
import { emitPluginEvent } from '../../../src/plugin-event-sink';
|
||||
import type { User } from '../../../src/types';
|
||||
@@ -89,7 +89,7 @@ const appSettings = {
|
||||
} as unknown as AppSettingsRepository;
|
||||
|
||||
const touchLastSeen = vi.fn(async (_session: string, _now: string) => undefined);
|
||||
const sessions = { touchLastSeen } as unknown as UserSessionsRepository;
|
||||
const sessions = { touchLastSeen } as unknown as SessionsService;
|
||||
|
||||
const consumeWithMeta = vi.fn();
|
||||
const tokens = { consumeWithMeta } as unknown as EphemeralTokenService;
|
||||
@@ -741,7 +741,8 @@ describe('book rooms with unusable sockets in them', () => {
|
||||
* its session's last activity current without any request.
|
||||
*/
|
||||
describe('RealtimeGateway presence', () => {
|
||||
const gateway = () => new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings, sessions);
|
||||
// The gateway a handshake built; its own socket stays out of the server's client list.
|
||||
const gateway = async () => (await connect('/ws?token=x')).gw;
|
||||
|
||||
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();
|
||||
@@ -751,7 +752,7 @@ describe('RealtimeGateway presence', () => {
|
||||
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();
|
||||
const gw = await gateway();
|
||||
|
||||
await gw.handlePresence({ visible: false }, hidden);
|
||||
await gw.handlePresence({ visible: true }, front);
|
||||
@@ -765,7 +766,7 @@ describe('RealtimeGateway presence', () => {
|
||||
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();
|
||||
const gw = await gateway();
|
||||
|
||||
await gw.handlePresence({ visible: true }, ws);
|
||||
await gw.handlePresence({ visible: true }, ws);
|
||||
@@ -784,7 +785,7 @@ describe('RealtimeGateway presence', () => {
|
||||
const noSession = socket();
|
||||
registerSocket(hidden, { id: 15, username: 'h' } as User, 'sess-h');
|
||||
registerSocket(noSession, { id: 16, username: 'n' } as User);
|
||||
const gw = gateway();
|
||||
const gw = await gateway();
|
||||
|
||||
await gw.handlePresence({ visible: false }, hidden);
|
||||
await gw.handlePresence({ visible: true }, noSession);
|
||||
@@ -800,7 +801,7 @@ describe('RealtimeGateway presence', () => {
|
||||
registerSocket(ws, { id: 17, username: 'b' } as User, 'sess-b');
|
||||
setSocketVisible(ws, true);
|
||||
touchLastSeen.mockRejectedValueOnce(new Error('busy'));
|
||||
const gw = gateway();
|
||||
const gw = await gateway();
|
||||
gw.afterInit({ clients: new Set([ws]) } as never);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
|
||||
Reference in New Issue
Block a user