refactor(server): delete trips.bridge via leaf membership reads and prompt relocation

This commit is contained in:
jubnl
2026-08-11 20:28:49 +02:00
parent e1162c1c07
commit 079064fdcd
20 changed files with 249 additions and 269 deletions
+4 -5
View File
@@ -17,13 +17,10 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
vi.mock('../../../src/nest/trips/trips.bridge', () => ({
listTripsForUser: vi.fn(() => [{ id: 1 }, { id: 2 }]),
}));
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
/** Trip 1 belongs to user 42, cost 5 sits on it, and the addon is on unless said otherwise. */
@@ -44,7 +41,9 @@ function build(opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean }
{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => opts.addonOn ?? true) } as unknown as AddonsService,
);
const rpc = new CostsRpc(budget, db, realtime, guards);
// The leaf membership read replaced the deleted trips.bridge for listMine.
const membership = { listAccessibleTripIds: vi.fn(() => [1, 2]) } as unknown as TripMembershipService;
const rpc = new CostsRpc(budget, db, realtime, guards, membership);
const host = (...grants: string[]) =>
new PluginRpcHost('p', new Set(grants.length ? grants : ['db:read:costs', 'db:write:costs']), makeDeps(), createTestPluginRegistry([rpc]));
return { budget, realtime, host };
+11 -12
View File
@@ -54,12 +54,8 @@ const addonsStub = {
const { mockGetTripSummary } = vi.hoisted(() => ({
mockGetTripSummary: vi.fn(),
}));
// prompts.ts consumes getTripSummary via the trips bridge since the trip fold.
vi.mock('../../../src/nest/trips/trips.bridge', () => ({
getTripSummary: mockGetTripSummary,
getTripOwner: vi.fn(),
listMembers: vi.fn(() => ({ members: [] })),
}));
// The prompts read the summary through the injected read model (readModelStub
// below wraps the same controllable mock) — trips.bridge is deleted.
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
@@ -68,6 +64,8 @@ import { createUser, createTrip, addTripMember, createPackingItem, createBudgetI
import { createTestRegistry } from '@trek/nest-mcp';
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../../src/mcp/nest-mcp-policy';
import { TripsMcp } from '../../../src/nest/trips/trips.mcp';
import { TripPromptsMcp } from '../../../src/nest/trips/trip-prompts.mcp';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { PackingMcp } from '../../../src/nest/packing/packing.mcp';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { BudgetMcp } from '../../../src/nest/budget/budget.mcp';
@@ -112,18 +110,19 @@ const tripsMcp = new TripsMcp(
// in-memory DB so the cases below keep asserting real rows.
const promptDbs = () => new DatabaseService(testDb);
const authStub = { isDemoUser: () => false } as unknown as AuthService;
const packingMcp = new PackingMcp(
new PackingService(promptDbs(), new PermissionsService(promptDbs()), new RealtimeService(), notificationsStub()),
authStub,
addonsStub,
);
const promptPackingService = new PackingService(promptDbs(), new PermissionsService(promptDbs()), new RealtimeService(), notificationsStub());
const packingMcp = new PackingMcp(promptPackingService, authStub, addonsStub);
const budgetMcp = new BudgetMcp(
new BudgetService(promptDbs(), new PermissionsService(promptDbs()), new ExchangeRatesService(), new RealtimeService()),
new ExchangeRatesService(),
promptDbs(),
new RuntimeEnvService(),
new TripMembershipService(promptDbs()),
addonsStub,
);
// The packing-list / budget-overview prompts live here since the trips.bridge
// fold; the summary rides the same readModelStub the trip-summary prompt uses.
const tripPromptsMcp = new TripPromptsMcp(tripsStub, readModelStub, promptPackingService, addonsStub);
const authMcp = new AuthMcp();
beforeAll(() => {
@@ -177,7 +176,7 @@ function buildServer(userId: number, opts: { isStaticToken?: boolean } = {}): Mc
const server = new McpServer({ name: 'trek-test', version: '1.0.0' });
// Every prompt is DI-discovered now; attach them the way registerTools does in
// production, including the isStaticToken flag the notice's `when` gate reads.
createTestRegistry([tripsMcp, packingMcp, budgetMcp, authMcp], { accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess })
createTestRegistry([tripsMcp, tripPromptsMcp, packingMcp, budgetMcp, authMcp], { accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess })
.attach(server, { userId, scopes: null, isStaticToken: opts.isStaticToken ?? false });
return server;
}
@@ -83,7 +83,7 @@ const KML_FIXTURE = path.join(__dirname, '../../fixtures/test.kml');
const dbs = new DatabaseService(testDb);
/**
* Same collaborator set the container hands PlacesService (see trips.bridge.ts),
* Same collaborator set the container hands PlacesService,
* built once here so the two construction sites cannot drift apart again. The
* journey domain is a real instance on the same in-memory DB rather than a stub:
* its place hooks are fire-and-forget behind a catch, so a missing one would have
@@ -68,3 +68,42 @@ describe('joinTripAsMember', () => {
expect(r.joined).toBe(false);
});
});
// The leaf reads that replaced trips.bridge for BudgetMcp/CostsRpc — see the
// service docblock for why they live on this dependency-free module.
describe('leaf membership reads', () => {
const svc = () => new TripMembershipService(new DatabaseService(testDb));
it('TRIP-READ-001: getOwnerId answers the owner and null for a missing trip', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(svc().getOwnerId(trip.id)).toBe(owner.id);
expect(svc().getOwnerId(999999)).toBeNull();
});
it('TRIP-READ-002: listMemberUserIds excludes the owner and follows added_at order', () => {
const { user: owner } = createUser(testDb);
const { user: m1 } = createUser(testDb);
const { user: m2 } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
testDb.prepare("INSERT INTO trip_members (trip_id, user_id, added_at) VALUES (?, ?, '2026-01-02')").run(trip.id, m2.id);
testDb.prepare("INSERT INTO trip_members (trip_id, user_id, added_at) VALUES (?, ?, '2026-01-01')").run(trip.id, m1.id);
expect(svc().listMemberUserIds(trip.id)).toEqual([m1.id, m2.id]);
expect(svc().listMemberUserIds(999999)).toEqual([]);
});
it('TRIP-READ-003: listAccessibleTripIds unions owned and member trips, newest first', () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const owned = createTrip(testDb, user.id);
const memberOf = createTrip(testDb, other.id);
const foreign = createTrip(testDb, other.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(memberOf.id, user.id);
// Distinct created_at so the ORDER BY is actually asserted, not assumed.
testDb.prepare("UPDATE trips SET created_at = '2026-01-01' WHERE id = ?").run(owned.id);
testDb.prepare("UPDATE trips SET created_at = '2026-01-02' WHERE id = ?").run(memberOf.id);
const ids = svc().listAccessibleTripIds(user.id);
expect(ids).toEqual([memberOf.id, owned.id]);
expect(ids).not.toContain(foreign.id);
});
});
@@ -80,7 +80,7 @@ import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repos
const dbs = () => new DatabaseService(testDb);
const budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs()), new ExchangeRatesService(), new RealtimeService());
const daysSvc = new DaysService(dbs(), new PermissionsService(dbs()), new RealtimeService(), new QueryHelpersService(dbs()));
// One shared cache instance, as in trips.bridge.ts: the in-flight dedup in
// One shared cache instance (the PlacePhotoCacheService rule): the in-flight dedup in
// PlacePhotoCacheService only works while both consumers hold the same object.
const photoCache = new PlacePhotoCacheService(dbs(), new RuntimeEnvService());
const placesSvc = new PlacesService(
+3 -25
View File
@@ -2,8 +2,8 @@
* Unit tests for the DI-native TripsService — TRIP-SVC-001 through TRIP-SVC-058
* (001–038 moved 1:1 from the legacy tests/unit/services/tripService.test.ts;
* the exportICS cases that duplicated the generateDays 010–012 numbering were
* renumbered to 024–026 with the post-fold quirk-fix commit; 040–041 pin the
* trips.bridge delegation; 042–050 cover the folded
* renumbered to 024–026 with the post-fold quirk-fix commit; 040–041 pinned
* the deleted trips.bridge and died with it; 042–050 cover the folded
* summary/list/create/delete/copy SQL; 051–053 pin the post-fold quirk fixes
* (transactional deletes, owner display_name)). Uses a real in-memory SQLite
* DB so SQL logic is exercised faithfully.
@@ -78,7 +78,6 @@ import { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-pho
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { getTripOwner, listMembers as bridgeListMembers } from '../../../src/nest/trips/trips.bridge';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import fs from 'fs';
import { notificationsStub } from '../../helpers/notifications';
@@ -89,7 +88,7 @@ import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.se
const dbs = () => new DatabaseService(testDb);
const budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs()), new ExchangeRatesService(), new RealtimeService());
const daysSvc = new DaysService(dbs(), new PermissionsService(dbs()), new RealtimeService(), new QueryHelpersService(dbs()));
// Same collaborator set the container hands PlacesService (see trips.bridge.ts).
// Same collaborator set the container hands PlacesService (see places.service.test.ts).
// Only the read-model aggregation reaches into places here, but the photo cache,
// Unsplash and journey domain are real instances over the same in-memory DB
// rather than casts: the place hooks are fire-and-forget behind a catch, so a
@@ -641,27 +640,6 @@ describe('guest members (#1362)', () => {
});
});
// ── trips.bridge delegation (coverage gate) ───────────────────────────────────
describe('trips.bridge delegation', () => {
it('TRIP-SVC-040: getTripOwner delegates 1:1', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getTripOwner(trip.id)).toEqual({ user_id: user.id });
expect(getTripOwner(99999)).toBeUndefined();
});
it('TRIP-SVC-041: listMembers delegates 1:1', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const result = bridgeListMembers(trip.id, owner.id);
expect(result.owner.id).toBe(owner.id);
expect(result.members.map(m => m.id)).toEqual([member.id]);
});
});
// ── Folded CRUD SQL (summary / list / create / delete / copy) ─────────────────
describe('folded trip CRUD', () => {
@@ -26,8 +26,6 @@ import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
vi.mock('../../../src/nest/trips/trips.bridge', () => ({ listTripsForUser: vi.fn(() => [{ id: 1 }]) }));
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
/** Records every service call, so "the service was never touched" is checkable. */
@@ -67,7 +65,7 @@ function build(addonOn: boolean) {
new VacayRpc(spyService(calls, 'vacay'), guards),
new JournalRpc(spyService(calls, 'journey'), guards),
new CollectionsRpc(spyService(calls, 'collections'), guards),
new CostsRpc(spyService(calls, 'budget'), db, { broadcast: vi.fn() } as never, guards),
new CostsRpc(spyService(calls, 'budget'), db, { broadcast: vi.fn() } as never, guards, spyService(calls, 'membership')),
]);
const granted = new Set([
'db:read:collab', 'db:write:collab', 'db:read:journal', 'db:write:journal',