mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
fix(realtime): road trip vias and day boundaries send the same events everywhere
This commit is contained in:
@@ -15,6 +15,7 @@ import { RoadtripPreferences } from '../../../src/db/entities/RoadtripPreference
|
||||
import { RoadtripVias } from '../../../src/db/entities/RoadtripVias.entity';
|
||||
import { DEMO_EMAIL_PRIMARY } from '../../../src/nest/common/demo';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { FakeRealtimeService } from '../../helpers/fake-realtime';
|
||||
import { createUser, createTrip, createDay, createPlace } from '../../helpers/factories';
|
||||
import { addTripMember } from '../../helpers/factories';
|
||||
import { countRows, findRow, updateRows } from '../../helpers/factories/rows';
|
||||
@@ -31,6 +32,8 @@ vi.mock('../../../src/db/database', async () => {
|
||||
});
|
||||
|
||||
let orm: TestOrm;
|
||||
// Every tool here broadcasts through this one, so a case can read what went out.
|
||||
const realtime = new FakeRealtimeService();
|
||||
|
||||
// The permissions cache is module-scoped, so a write through any instance is
|
||||
// what the tool's own check reads back.
|
||||
@@ -46,6 +49,7 @@ beforeAll(async () => {
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
realtime.reset();
|
||||
// resetTestDb leaves the addons table alone, so each run restates it. The
|
||||
// addon ships disabled, which is why the tools were invisible before.
|
||||
setAddonEnabled(testDb, ADDON_IDS.ROADTRIP, true);
|
||||
@@ -57,7 +61,7 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
|
||||
const h = await createMcpHarness({ userId, withResources: false, scopes: null });
|
||||
const h = await createMcpHarness({ realtime, userId, withResources: false, scopes: null });
|
||||
try {
|
||||
await fn(h);
|
||||
} finally {
|
||||
@@ -394,6 +398,30 @@ describe('road-trip MCP tools', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('MCP-ROADTRIP-015: adding a via tells the trip once, with the day id as text and no socket left out', async () => {
|
||||
// G8: the tool used to send the day id as a number where the route sent text. It now runs
|
||||
// the same use case through the MCP writer, so the payload matches the route's.
|
||||
const { user, trip, day } = await scenario();
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const added = await h.client.callTool({
|
||||
name: 'add_route_via',
|
||||
arguments: { tripId: trip.id, dayId: day.id, after_order_index: 0, lat: 53, lng: 10 },
|
||||
});
|
||||
expect(added.isError).toBeFalsy();
|
||||
const { via } = parseToolResult(added) as { via: { id: number } };
|
||||
|
||||
const sent = realtime.broadcastMock.mock.calls.filter(([, event]) => event === 'roadtripVia:changed');
|
||||
expect(sent).toHaveLength(1);
|
||||
// Three arguments: room-wide, with no socket to leave out.
|
||||
expect(sent[0]).toHaveLength(3);
|
||||
const [tripId, , payload] = sent[0];
|
||||
expect(String(tripId)).toBe(String(trip.id));
|
||||
expect(payload).toMatchObject({ dayId: String(day.id), _source: 'mcp' });
|
||||
expect((payload.vias as { id: number }[]).map((v) => v.id)).toEqual([via.id]);
|
||||
});
|
||||
});
|
||||
|
||||
it('MCP-ROADTRIP-009: removing one that is not on the day is refused, not silently ignored', async () => {
|
||||
const { user, trip, day } = await scenario();
|
||||
|
||||
|
||||
@@ -157,9 +157,18 @@ it('MCP checks demo, trip access and edit permission before saving', async () =>
|
||||
s.guards.hasTripPermission.mockReturnValue(false);
|
||||
await s.mcp.save(request, ctx);
|
||||
expect(await s.service.list(s.tripA.id)).toEqual([]);
|
||||
// A refused call tells nobody anything.
|
||||
expect(s.realtime.broadcast).not.toHaveBeenCalled();
|
||||
s.guards.hasTripPermission.mockReturnValue(true);
|
||||
await s.mcp.save(request, ctx);
|
||||
expect(await s.service.list(s.tripA.id)).toEqual([boundary]);
|
||||
// Clearing a boundary goes through `remove`, which the parity case never runs, so the
|
||||
// event it sends is pinned here: once, with the list as it is now.
|
||||
s.realtime.broadcast.mockClear();
|
||||
await s.mcp.save({ ...request, boundary: null }, ctx);
|
||||
expect(await s.service.list(s.tripA.id)).toEqual([]);
|
||||
expect(s.realtime.broadcast).toHaveBeenCalledTimes(1);
|
||||
expect(s.realtime.broadcast).toHaveBeenCalledWith(String(s.tripA.id), 'roadtripBoundary:changed', {
|
||||
boundaries: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -496,11 +496,11 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
it('checks visit editing permission and ownership before moving a via', async () => {
|
||||
const service = {
|
||||
dayExists: vi.fn(() => true),
|
||||
move: vi.fn(() => ({ id: 4 })),
|
||||
listForDay: () => [],
|
||||
broadcast: vi.fn(),
|
||||
moveVia: vi.fn(() => ({ id: 4 })),
|
||||
};
|
||||
const guards = { hasTripPermission: vi.fn(() => false) };
|
||||
// The move and what it tells the trip are the service's; the tool hands it the MCP writer.
|
||||
const writer = { userId: 5, surface: 'mcp' };
|
||||
const guards = { hasTripPermission: vi.fn(() => false), tripWriter: vi.fn(async () => writer) };
|
||||
const mcp = new RoadtripMcp(
|
||||
service as never,
|
||||
{ findAccessible: () => true } as never,
|
||||
@@ -509,15 +509,15 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
);
|
||||
const input = { tripId: 1, dayId: 2, viaId: 4, lat: 48, lng: 10 };
|
||||
await mcp.updateVia(input, ctx);
|
||||
expect(service.move).not.toHaveBeenCalled();
|
||||
expect(service.moveVia).not.toHaveBeenCalled();
|
||||
guards.hasTripPermission.mockReturnValue(true);
|
||||
service.dayExists.mockReturnValue(false);
|
||||
await mcp.updateVia(input, ctx);
|
||||
expect(service.move).not.toHaveBeenCalled();
|
||||
expect(service.moveVia).not.toHaveBeenCalled();
|
||||
service.dayExists.mockReturnValue(true);
|
||||
await mcp.updateVia(input, ctx);
|
||||
expect(service.move).toHaveBeenCalledWith(4, 2, 48, 10, undefined);
|
||||
expect(service.broadcast).toHaveBeenCalled();
|
||||
expect(guards.tripWriter).toHaveBeenCalledWith(1, 5);
|
||||
expect(service.moveVia).toHaveBeenCalledWith(2, 4, { lat: 48, lng: 10, after_order_index: undefined }, writer);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -534,15 +534,14 @@ describe('RoadtripMcp — non-member refusal, one case per tool (Plan 3d Task 7
|
||||
listForTrip: vi.fn(async () => []),
|
||||
tracksForTrip: vi.fn(async () => []),
|
||||
trackExists: vi.fn(async () => true),
|
||||
create: vi.fn(async () => ({ id: 1 })),
|
||||
createMany: vi.fn(async () => []),
|
||||
reanchor: vi.fn(async () => []),
|
||||
remove: vi.fn(async () => true),
|
||||
move: vi.fn(async () => ({ id: 1 })),
|
||||
broadcast: vi.fn(),
|
||||
addVia: vi.fn(async () => ({ id: 1 })),
|
||||
addVias: vi.fn(async () => []),
|
||||
reanchorVias: vi.fn(async () => []),
|
||||
removeVia: vi.fn(async () => true),
|
||||
moveVia: vi.fn(async () => ({ id: 1 })),
|
||||
};
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => findAccessible) };
|
||||
const guards = { hasTripPermission: vi.fn(async () => true) };
|
||||
const guards = { hasTripPermission: vi.fn(async () => true), tripWriter: vi.fn(async () => ({ userId: 5 })) };
|
||||
const mcp = new RoadtripMcp(service as never, tripsRepo as never, guards as never, {} as never);
|
||||
return { mcp, service, tripsRepo };
|
||||
}
|
||||
@@ -559,28 +558,28 @@ describe('RoadtripMcp — non-member refusal, one case per tool (Plan 3d Task 7
|
||||
const { mcp, service } = build(false);
|
||||
const res = await mcp.addVia({ tripId: 10, dayId: 1, after_order_index: 0, lat: 48, lng: 10 }, ctx);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(service.create).not.toHaveBeenCalled();
|
||||
expect(service.addVia).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('add_route_vias refuses a non-member trip', async () => {
|
||||
const { mcp, service } = build(false);
|
||||
const res = await mcp.addVias({ tripId: 10, dayId: 1, vias: [] }, ctx);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(service.createMany).not.toHaveBeenCalled();
|
||||
expect(service.addVias).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reanchor_route_vias refuses a non-member trip', async () => {
|
||||
const { mcp, service } = build(false);
|
||||
const res = await mcp.reanchorVias({ tripId: 10, dayId: 1, vias: [] }, ctx);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(service.reanchor).not.toHaveBeenCalled();
|
||||
expect(service.reanchorVias).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('remove_route_via refuses a non-member trip', async () => {
|
||||
const { mcp, service } = build(false);
|
||||
const res = await mcp.removeVia({ tripId: 10, dayId: 1, viaId: 4 }, ctx);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(service.remove).not.toHaveBeenCalled();
|
||||
expect(service.removeVia).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -13,18 +13,27 @@
|
||||
* AddonGuard again. `@RequireAddon` is metadata and does nothing on its own, so
|
||||
* dropping the guard from the list is a silent regression that opens all seven
|
||||
* routes on an instance that switched the addon off.
|
||||
*
|
||||
* What a write tells the trip is the service's (RoadtripService.addVia and its
|
||||
* siblings, pinned in roadtrip.service.test.ts); here only that every write
|
||||
* hands it the REST writer of this trip, user and socket.
|
||||
*/
|
||||
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
|
||||
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import type { TripWriter } from '../../../src/nest/common/trip-writer';
|
||||
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import { RoadtripController } from '../../../src/nest/roadtrip/roadtrip.controller';
|
||||
import type { RoadtripService } from '../../../src/nest/roadtrip/roadtrip.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
const VIA = { id: 5, day_id: 4, after_order_index: 0, sequence: 0, lat: 53, lng: 10 };
|
||||
const USER = { id: 3, role: 'user' } as User;
|
||||
/** The writer restWriter hands back, as the use cases receive it. */
|
||||
const WRITER = { userId: 3, role: 'user', surface: 'rest' } as TripWriter;
|
||||
|
||||
function svc(o: Partial<RoadtripService> = {}): RoadtripService {
|
||||
return {
|
||||
@@ -33,13 +42,12 @@ function svc(o: Partial<RoadtripService> = {}): RoadtripService {
|
||||
listForDay: vi.fn().mockReturnValue([VIA]),
|
||||
listForTrip: vi.fn().mockReturnValue([VIA]),
|
||||
tracksForTrip: vi.fn().mockReturnValue([]),
|
||||
create: vi.fn().mockReturnValue(VIA),
|
||||
createMany: vi.fn().mockReturnValue([VIA]),
|
||||
reanchor: vi.fn().mockReturnValue([VIA]),
|
||||
move: vi.fn().mockReturnValue(VIA),
|
||||
remove: vi.fn().mockReturnValue(true),
|
||||
// Every write announces the day's new shape to the trip's other clients.
|
||||
broadcast: vi.fn(),
|
||||
restWriter: vi.fn().mockReturnValue(WRITER),
|
||||
addVia: vi.fn().mockReturnValue(VIA),
|
||||
addVias: vi.fn().mockReturnValue([VIA]),
|
||||
reanchorVias: vi.fn().mockReturnValue([VIA]),
|
||||
moveVia: vi.fn().mockReturnValue(VIA),
|
||||
removeVia: vi.fn().mockReturnValue(true),
|
||||
...o,
|
||||
} as unknown as RoadtripService;
|
||||
}
|
||||
@@ -101,9 +109,9 @@ describe('RoadtripController — writes', () => {
|
||||
|
||||
it('ROADTRIP-CTL-005: creating one checks the day first', async () => {
|
||||
const s = svc();
|
||||
expect(await new RoadtripController(s).create('7', '4', body)).toEqual({ via: VIA });
|
||||
expect(await new RoadtripController(s).create(USER, '7', '4', body)).toEqual({ via: VIA });
|
||||
expect(s.dayExists).toHaveBeenCalledWith('4', '7');
|
||||
expect(s.create).toHaveBeenCalledWith('4', body);
|
||||
expect(s.addVia).toHaveBeenCalledWith('4', body, WRITER);
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-006: every write refuses a day from another trip', async () => {
|
||||
@@ -111,25 +119,25 @@ describe('RoadtripController — writes', () => {
|
||||
const c = new RoadtripController(s);
|
||||
const notFound = { status: 404, body: { error: 'Day not found' } };
|
||||
|
||||
expect(await thrown(() => c.create('7', '999', body))).toEqual(notFound);
|
||||
expect(await thrown(() => c.createMany('7', '999', { vias: [body] }))).toEqual(notFound);
|
||||
expect(await thrown(() => c.reanchor('7', '999', { vias: [] }))).toEqual(notFound);
|
||||
expect(await thrown(() => c.update('7', '999', '5', { lat: 1, lng: 2 }))).toEqual(notFound);
|
||||
expect(await thrown(() => c.remove('7', '999', '5'))).toEqual(notFound);
|
||||
expect(await thrown(() => c.create(USER, '7', '999', body))).toEqual(notFound);
|
||||
expect(await thrown(() => c.createMany(USER, '7', '999', { vias: [body] }))).toEqual(notFound);
|
||||
expect(await thrown(() => c.reanchor(USER, '7', '999', { vias: [] }))).toEqual(notFound);
|
||||
expect(await thrown(() => c.update(USER, '7', '999', '5', { lat: 1, lng: 2 }))).toEqual(notFound);
|
||||
expect(await thrown(() => c.remove(USER, '7', '999', '5'))).toEqual(notFound);
|
||||
|
||||
// None of them reached the service.
|
||||
expect(s.create).not.toHaveBeenCalled();
|
||||
expect(s.createMany).not.toHaveBeenCalled();
|
||||
expect(s.reanchor).not.toHaveBeenCalled();
|
||||
expect(s.move).not.toHaveBeenCalled();
|
||||
expect(s.remove).not.toHaveBeenCalled();
|
||||
expect(s.addVia).not.toHaveBeenCalled();
|
||||
expect(s.addVias).not.toHaveBeenCalled();
|
||||
expect(s.reanchorVias).not.toHaveBeenCalled();
|
||||
expect(s.moveVia).not.toHaveBeenCalled();
|
||||
expect(s.removeVia).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-007: a batch lays the whole chain in one call', async () => {
|
||||
const s = svc();
|
||||
const batch = { vias: [body, body], replace_legs: [0] };
|
||||
expect(await new RoadtripController(s).createMany('7', '4', batch)).toEqual({ vias: [VIA] });
|
||||
expect(s.createMany).toHaveBeenCalledWith('4', batch);
|
||||
expect(await new RoadtripController(s).createMany(USER, '7', '4', batch)).toEqual({ vias: [VIA] });
|
||||
expect(s.addVias).toHaveBeenCalledWith('7', '4', batch, WRITER);
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-008: a track from another trip cannot become this day label', async () => {
|
||||
@@ -138,14 +146,16 @@ describe('RoadtripController — writes', () => {
|
||||
// would become a label that can never be drawn.
|
||||
const s = svc({ trackExists: vi.fn().mockReturnValue(false) });
|
||||
expect(
|
||||
await thrown(() => new RoadtripController(s).createMany('7', '4', { vias: [body], track: { place_id: 3 } })),
|
||||
await thrown(() =>
|
||||
new RoadtripController(s).createMany(USER, '7', '4', { vias: [body], track: { place_id: 3 } }),
|
||||
),
|
||||
).toEqual({ status: 404, body: { error: 'Track not found' } });
|
||||
expect(s.createMany).not.toHaveBeenCalled();
|
||||
expect(s.addVias).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-009: the track check runs against the trip, not the day', async () => {
|
||||
const s = svc();
|
||||
await new RoadtripController(s).createMany('7', '4', { vias: [body], track: { place_id: 3 } });
|
||||
await new RoadtripController(s).createMany(USER, '7', '4', { vias: [body], track: { place_id: 3 } });
|
||||
expect(s.trackExists).toHaveBeenCalledWith(3, '7');
|
||||
});
|
||||
|
||||
@@ -154,7 +164,7 @@ describe('RoadtripController — writes', () => {
|
||||
// check the existence of. Treating it as one would refuse the only way to
|
||||
// detach a track.
|
||||
const s = svc({ trackExists: vi.fn().mockReturnValue(false) });
|
||||
expect(await new RoadtripController(s).createMany('7', '4', { vias: [body], track: null })).toEqual({
|
||||
expect(await new RoadtripController(s).createMany(USER, '7', '4', { vias: [body], track: null })).toEqual({
|
||||
vias: [VIA],
|
||||
});
|
||||
expect(s.trackExists).not.toHaveBeenCalled();
|
||||
@@ -163,27 +173,27 @@ describe('RoadtripController — writes', () => {
|
||||
it('ROADTRIP-CTL-011: re-anchoring goes through as one batch', async () => {
|
||||
const s = svc();
|
||||
const plan = { vias: [{ id: 5, after_order_index: 1 }], remove: [6] };
|
||||
expect(await new RoadtripController(s).reanchor('7', '4', plan)).toEqual({ vias: [VIA] });
|
||||
expect(s.reanchor).toHaveBeenCalledWith('4', plan);
|
||||
expect(await new RoadtripController(s).reanchor(USER, '7', '4', plan)).toEqual({ vias: [VIA] });
|
||||
expect(s.reanchorVias).toHaveBeenCalledWith('4', plan, WRITER);
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-012: moving a via reports where it went', async () => {
|
||||
const s = svc();
|
||||
expect(await new RoadtripController(s).update('7', '4', '5', { lat: 54, lng: 11 })).toEqual({ via: VIA });
|
||||
// Undefined anchor, explicitly: a drag that stayed between the same two stops sends
|
||||
// no new one, and the service must leave the existing pin alone rather than clear it.
|
||||
expect(s.move).toHaveBeenCalledWith('5', '4', 54, 11, undefined);
|
||||
expect(await new RoadtripController(s).update(USER, '7', '4', '5', { lat: 54, lng: 11 })).toEqual({ via: VIA });
|
||||
// No anchor, explicitly: a drag that stayed between the same two stops sends no new
|
||||
// one, and the service must leave the existing pin alone rather than clear it.
|
||||
expect(s.moveVia).toHaveBeenCalledWith('4', '5', { lat: 54, lng: 11 }, WRITER);
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-015: a new anchor is passed on, so a via dragged past a stop is re-pinned', async () => {
|
||||
const s = svc();
|
||||
await new RoadtripController(s).update('7', '4', '5', { lat: 54, lng: 11, after_order_index: 2 });
|
||||
expect(s.move).toHaveBeenCalledWith('5', '4', 54, 11, 2);
|
||||
await new RoadtripController(s).update(USER, '7', '4', '5', { lat: 54, lng: 11, after_order_index: 2 });
|
||||
expect(s.moveVia).toHaveBeenCalledWith('4', '5', { lat: 54, lng: 11, after_order_index: 2 }, WRITER);
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-013: a via that is not on this day is a 404, not a silent no-op', async () => {
|
||||
const s = svc({ move: vi.fn().mockReturnValue(null) });
|
||||
expect(await thrown(() => new RoadtripController(s).update('7', '4', '999', { lat: 1, lng: 2 }))).toEqual({
|
||||
const s = svc({ moveVia: vi.fn().mockReturnValue(null) });
|
||||
expect(await thrown(() => new RoadtripController(s).update(USER, '7', '4', '999', { lat: 1, lng: 2 }))).toEqual({
|
||||
status: 404,
|
||||
body: { error: 'Via not found' },
|
||||
});
|
||||
@@ -191,13 +201,13 @@ describe('RoadtripController — writes', () => {
|
||||
|
||||
it('ROADTRIP-CTL-014: removing one reports success', async () => {
|
||||
const s = svc();
|
||||
expect(await new RoadtripController(s).remove('7', '4', '5')).toEqual({ success: true });
|
||||
expect(s.remove).toHaveBeenCalledWith('5', '4');
|
||||
expect(await new RoadtripController(s).remove(USER, '7', '4', '5')).toEqual({ success: true });
|
||||
expect(s.removeVia).toHaveBeenCalledWith('4', '5', WRITER);
|
||||
});
|
||||
|
||||
it('ROADTRIP-CTL-015: removing a via that is not there is a 404', async () => {
|
||||
const s = svc({ remove: vi.fn().mockReturnValue(false) });
|
||||
expect(await thrown(() => new RoadtripController(s).remove('7', '4', '999'))).toEqual({
|
||||
it('ROADTRIP-CTL-016: removing a via that is not there is a 404', async () => {
|
||||
const s = svc({ removeVia: vi.fn().mockReturnValue(false) });
|
||||
expect(await thrown(() => new RoadtripController(s).remove(USER, '7', '4', '999'))).toEqual({
|
||||
status: 404,
|
||||
body: { error: 'Via not found' },
|
||||
});
|
||||
@@ -206,43 +216,28 @@ describe('RoadtripController — writes', () => {
|
||||
/**
|
||||
* Two people planning one road trip look at the same line on the same map, and a
|
||||
* reshaped drive moves every arrival time after it. These routes used to write in
|
||||
* silence, which left the other side reading a route nobody could see change.
|
||||
* silence, which left the other side reading a route nobody could see change. What
|
||||
* each write sends is the service's; the route decides who sends it.
|
||||
*/
|
||||
describe('telling the trip', () => {
|
||||
it('SRV-ROADTRIP-020: every write announces the new shape of the day', async () => {
|
||||
const cases: [string, (c: RoadtripController) => unknown][] = [
|
||||
['create', (c) => c.create('7', '4', { after_order_index: 0, lat: 1, lng: 2 }, 'sock')],
|
||||
['createMany', (c) => c.createMany('7', '4', { vias: [{ after_order_index: 0, lat: 1, lng: 2 }] }, 'sock')],
|
||||
['reanchor', (c) => c.reanchor('7', '4', { vias: [] }, 'sock')],
|
||||
['update', (c) => c.update('7', '4', '9', { lat: 1, lng: 2 }, 'sock')],
|
||||
['remove', (c) => c.remove('7', '4', '9', 'sock')],
|
||||
it('SRV-ROADTRIP-020: every write hands its use case the writer of this trip, user and socket', async () => {
|
||||
const cases: [string, keyof RoadtripService, (c: RoadtripController) => unknown][] = [
|
||||
['create', 'addVia', (c) => c.create(USER, '7', '4', { after_order_index: 0, lat: 1, lng: 2 }, 'sock')],
|
||||
[
|
||||
'createMany',
|
||||
'addVias',
|
||||
(c) => c.createMany(USER, '7', '4', { vias: [{ after_order_index: 0, lat: 1, lng: 2 }] }, 'sock'),
|
||||
],
|
||||
['reanchor', 'reanchorVias', (c) => c.reanchor(USER, '7', '4', { vias: [] }, 'sock')],
|
||||
['update', 'moveVia', (c) => c.update(USER, '7', '4', '9', { lat: 1, lng: 2 }, 'sock')],
|
||||
['remove', 'removeVia', (c) => c.remove(USER, '7', '4', '9', 'sock')],
|
||||
];
|
||||
for (const [name, run] of cases) {
|
||||
for (const [name, useCase, run] of cases) {
|
||||
const s = svc();
|
||||
await run(new RoadtripController(s));
|
||||
expect(s.broadcast, name).toHaveBeenCalledWith('7', 'roadtripVia:changed', { dayId: '4', vias: [VIA] }, 'sock');
|
||||
expect(s.restWriter, name).toHaveBeenCalledWith('7', USER, 'sock');
|
||||
expect(vi.mocked(s[useCase]).mock.lastCall?.at(-1), name).toBe(WRITER);
|
||||
}
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-021: the day list is read back, not assembled from the write', async () => {
|
||||
// A reanchor rewrites the whole set and a batch may clear legs before filling them,
|
||||
// so what the write returned is not what the day now holds.
|
||||
const s = svc({ reanchor: vi.fn().mockReturnValue([]) } as Partial<RoadtripService>);
|
||||
await new RoadtripController(s).reanchor('7', '4', { vias: [] }, 'sock');
|
||||
expect(s.broadcast).toHaveBeenCalledWith('7', 'roadtripVia:changed', { dayId: '4', vias: [VIA] }, 'sock');
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-022: laying a track down says which track the day now follows', async () => {
|
||||
const track = { day_id: 4, place_id: 3, name: 'B96' };
|
||||
const s = svc({ tracksForTrip: vi.fn().mockReturnValue([track]) } as Partial<RoadtripService>);
|
||||
await new RoadtripController(s).createMany('7', '4', { vias: [], track: { place_id: 3 } }, 'sock');
|
||||
expect(s.broadcast).toHaveBeenCalledWith('7', 'roadtripTrack:changed', { dayId: '4', track }, 'sock');
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-023: a refused write announces nothing', async () => {
|
||||
const s = svc({ remove: vi.fn().mockReturnValue(false) } as Partial<RoadtripService>);
|
||||
await expect(new RoadtripController(s).remove('7', '4', '9', 'sock')).rejects.toThrow();
|
||||
expect(s.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,15 +2,18 @@ import { Days } from '../../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { RoadtripDayTracks } from '../../../src/db/entities/RoadtripDayTracks.entity';
|
||||
import { RoadtripVias } from '../../../src/db/entities/RoadtripVias.entity';
|
||||
import type { TripWriter } from '../../../src/nest/common/trip-writer';
|
||||
import { RoadtripService } from '../../../src/nest/roadtrip/roadtrip.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { createDay, createPlace, createTrip, createUser } from '../../helpers/factories';
|
||||
import { updateRows } from '../../helpers/factories/rows';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { createTestUnitOfWork } from '../../helpers/test-uow';
|
||||
import type { RoadtripVia } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* Via points and tracks, against real rows through
|
||||
@@ -32,9 +35,9 @@ afterAll(async () => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
async function makeService() {
|
||||
async function makeService(realtime: { broadcast: (...args: unknown[]) => void } = { broadcast: () => {} }) {
|
||||
return new RoadtripService(
|
||||
{ broadcast: () => {} } as never,
|
||||
realtime as never,
|
||||
await createTestUnitOfWork(testDb),
|
||||
t.repo(Days),
|
||||
t.repo(Places),
|
||||
@@ -374,3 +377,124 @@ describe('RoadtripService', () => {
|
||||
expect(rows.map((r) => r.sequence).sort((a, b) => a - b)).toEqual([0, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
interface Sent {
|
||||
event: string;
|
||||
payload: { dayId?: unknown; vias?: RoadtripVia[]; track?: unknown };
|
||||
all: boolean;
|
||||
}
|
||||
|
||||
/** A writer that keeps what a use case sends, in order, as a TripEventSink receives it. */
|
||||
function recordingWriter(): { sent: Sent[]; writer: TripWriter } {
|
||||
const sent: Sent[] = [];
|
||||
const keep = (event: string, payload: unknown, all: boolean) => {
|
||||
sent.push({ event, payload: payload as Sent['payload'], all });
|
||||
};
|
||||
const writer: TripWriter = {
|
||||
userId: 1,
|
||||
role: 'user',
|
||||
surface: 'mcp',
|
||||
events: {
|
||||
emit: (event, payload) => keep(event, payload, false),
|
||||
emitAll: (event, payload) => keep(event, payload, true),
|
||||
},
|
||||
};
|
||||
return { sent, writer };
|
||||
}
|
||||
|
||||
/**
|
||||
* Two people planning one road trip look at the same line on the same map, and a reshaped
|
||||
* drive moves every arrival time after it. Each via write is one use case for the routes
|
||||
* and the tools alike, and tells the trip what the day runs through now once it is written.
|
||||
*/
|
||||
describe('RoadtripService: telling the trip', () => {
|
||||
let service: RoadtripService;
|
||||
let f: Awaited<ReturnType<typeof fixture>>;
|
||||
beforeEach(async () => {
|
||||
service = await makeService();
|
||||
f = await fixture();
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-021: every via write sends the day read back after it, with the day id as text', async () => {
|
||||
const { sent, writer } = recordingWriter();
|
||||
const first = await service.addVia(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 }, writer);
|
||||
const second = await service.addVia(String(f.dayA1.id), { after_order_index: 1, lat: 54, lng: 11 }, writer);
|
||||
const moved = await service.moveVia(f.dayA1.id, first.id, { lat: 53.5, lng: 10.5 }, writer);
|
||||
// The reanchor answers nothing it was asked to move: what goes out is the day as it is now.
|
||||
await service.reanchorVias(f.dayA1.id, { vias: [], remove: [second.id] }, writer);
|
||||
await service.removeVia(f.dayA1.id, first.id, writer);
|
||||
|
||||
expect(sent.map((s) => s.event)).toEqual(Array(5).fill('roadtripVia:changed'));
|
||||
expect(sent.some((s) => s.all)).toBe(false);
|
||||
// G8: the routes always sent the day id as the path spelled it; a tool sends it the same way.
|
||||
expect(sent.map((s) => s.payload.dayId)).toEqual(Array(5).fill(String(f.dayA1.id)));
|
||||
expect(sent.map((s) => s.payload.vias?.map((v) => v.id))).toEqual([
|
||||
[first.id],
|
||||
[first.id, second.id],
|
||||
[first.id, second.id],
|
||||
[first.id],
|
||||
[],
|
||||
]);
|
||||
expect(sent[2]?.payload.vias?.[0]).toEqual(moved);
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-022: a chain says which track the day follows now, after its vias', async () => {
|
||||
const { sent, writer } = recordingWriter();
|
||||
const chain = { vias: [{ after_order_index: 0, lat: 53, lng: 10 }], track: { place_id: f.track.id, stray_km: 2 } };
|
||||
const made = await service.addVias(f.tripA.id, f.dayA1.id, chain, writer);
|
||||
// Left out, the track stays; the event still says which one the day follows.
|
||||
await service.addVias(f.tripA.id, f.dayA1.id, { vias: [] }, writer);
|
||||
await service.addVias(f.tripA.id, f.dayA1.id, { vias: [], track: null }, writer);
|
||||
|
||||
const followed = { day_id: f.dayA1.id, place_id: f.track.id, stray_km: 2 };
|
||||
expect(sent.map((s) => [s.event, s.payload])).toEqual([
|
||||
['roadtripVia:changed', { dayId: String(f.dayA1.id), vias: made }],
|
||||
['roadtripTrack:changed', { dayId: String(f.dayA1.id), track: followed }],
|
||||
['roadtripVia:changed', { dayId: String(f.dayA1.id), vias: made }],
|
||||
['roadtripTrack:changed', { dayId: String(f.dayA1.id), track: followed }],
|
||||
['roadtripVia:changed', { dayId: String(f.dayA1.id), vias: made }],
|
||||
['roadtripTrack:changed', { dayId: String(f.dayA1.id), track: null }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-023: a via that is not on the day changes nothing and tells nobody', async () => {
|
||||
const { sent, writer } = recordingWriter();
|
||||
const other = await service.create(f.dayA2.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
expect(await service.moveVia(f.dayA1.id, other.id, { lat: 1, lng: 2 }, writer)).toBeNull();
|
||||
expect(await service.removeVia(f.dayA1.id, other.id, writer)).toBe(false);
|
||||
expect(sent).toEqual([]);
|
||||
expect(await service.listForDay(f.dayA2.id)).toEqual([other]);
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-024: the REST writer sends to the trip and leaves out the socket that made the change', async () => {
|
||||
const calls: unknown[][] = [];
|
||||
const rest = await makeService({ broadcast: (...args) => calls.push(args) });
|
||||
const user = { id: 1, role: 'user' } as User;
|
||||
const tripId = String(f.tripA.id);
|
||||
const dayId = String(f.dayA1.id);
|
||||
|
||||
const via = await rest.addVia(
|
||||
dayId,
|
||||
{ after_order_index: 0, lat: 53, lng: 10 },
|
||||
rest.restWriter(tripId, user, 'sock'),
|
||||
);
|
||||
|
||||
expect(calls).toEqual([[tripId, 'roadtripVia:changed', { dayId, vias: [via] }, 'sock']]);
|
||||
});
|
||||
|
||||
it('SRV-ROADTRIP-025: a read that fails after the commit is logged, and the write still answers', async () => {
|
||||
const { sent, writer } = recordingWriter();
|
||||
vi.spyOn(service, 'listForDay').mockRejectedValueOnce(new Error('read failed'));
|
||||
const via = await service.addVia(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 }, writer);
|
||||
expect(sent).toEqual([]);
|
||||
|
||||
// The chain's track read fails on its own: the via event has gone, the track event is skipped.
|
||||
vi.spyOn(service, 'tracksForTrip').mockRejectedValueOnce(new Error('read failed'));
|
||||
const vias = await service.addVias(f.tripA.id, f.dayA1.id, { vias: [] }, writer);
|
||||
expect(sent.map((s) => s.event)).toEqual(['roadtripVia:changed']);
|
||||
|
||||
expect(vias).toEqual([via]);
|
||||
expect(await service.listForDay(f.dayA1.id)).toEqual([via]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user