Hand the feeds calendar parts instead of a document to re-parse

The all-trips feed merges many trips into one calendar. It did that by
generating each trip's finished ICS and then scanning the text back apart:
one pass for the VEVENTs, one for the VTIMEZONEs, plus a string replace to
splice the refresh hints into the header. The scans had to be structural
rather than regexes, because a user-supplied SUMMARY can legitimately
contain the literal 'END:VEVENT' and a lazy match would truncate the event
there.

CalendarService now returns the parts - calendar name, filename, VTIMEZONE
blocks keyed by TZID, and the VEVENT blocks - and exportICS serialises them.
Both scanners are gone.

CAL-010 pins the whole serialised document as a snapshot, with DTSTAMP and
the UID counter normalised so it pins the calendar rather than the minute it
ran in. It is what proves this changed no bytes: it was taken before the
model went in and still matches.

Two tests still pointed at the health controller deleted in d37af204:
health.di.test.ts loses its only subject, and the AppModule wiring test now
resolves FeaturesController instead - it is the one test that builds the
whole container, so it should resolve something that still exists.
This commit is contained in:
Maurice
2026-08-10 09:05:20 +02:00
committed by Maurice
parent 5a9ded6676
commit 7f5c537ad6
6 changed files with 219 additions and 142 deletions
+30 -23
View File
@@ -8,8 +8,9 @@
* valid token → 200 text/calendar with the injected REFRESH-INTERVAL / X-PUBLISHED-TTL
* hints, unknown token → 404, all-trips feed excludes archived + >90-day-old trips
*
* exportICS is mocked so the test owns the ICS payload and can assert which trips
* the all-trips feed pulled in without seeding the full trip/day/reservation schema.
* buildTripCalendar is mocked so the test owns the calendar parts and can assert
* which trips the all-trips feed pulled in without seeding the full
* trip/day/reservation schema.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import request from 'supertest';
@@ -35,16 +36,19 @@ const { db } = vi.hoisted(() => {
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
// Own the ICS payload so we control the events and can assert which trips were pulled.
const SAMPLE_ICS =
'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//TREK//Travel Planner//EN\r\nCALSCALE:GREGORIAN\r\n' +
'METHOD:PUBLISH\r\nX-WR-CALNAME:Sample\r\n' +
// Own the calendar parts so we control the events and can assert which trips were pulled.
const SAMPLE_EVENT =
'BEGIN:VEVENT\r\nUID:trek-trip-x@trek\r\nDTSTAMP:20260101T000000Z\r\n' +
'DTSTART;VALUE=DATE:20260101\r\nDTEND;VALUE=DATE:20260102\r\nSUMMARY:Sample\r\nEND:VEVENT\r\n' +
'END:VCALENDAR\r\n';
'DTSTART;VALUE=DATE:20260101\r\nDTEND;VALUE=DATE:20260102\r\nSUMMARY:Sample\r\nEND:VEVENT\r\n';
const sampleCalendar = () => ({
calName: 'Sample',
filename: 'sample.ics',
timezones: new Map<string, string>(),
events: [SAMPLE_EVENT],
});
// FeedsService injects CalendarService — the mock is a spy on the container
// singleton (created in beforeAll, after build()).
const exportICS = vi.fn();
const buildTripCalendar = vi.fn();
import { FeedsModule } from '../../src/nest/feeds/feeds.module';
import { CalendarService } from '../../src/nest/calendar/calendar.service';
@@ -73,13 +77,13 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
seedUser(db as never, { id: 1, username: 'e2e-user' });
seedUser(db as never, { id: 2, username: 'other-user', email: 'other@example.test' });
app = await build();
vi.spyOn(app.get(CalendarService), 'exportICS').mockImplementation(exportICS as never);
vi.spyOn(app.get(CalendarService), 'buildTripCalendar').mockImplementation(buildTripCalendar as never);
server = app.getHttpServer();
});
beforeEach(() => {
exportICS.mockReset();
exportICS.mockReturnValue({ ics: SAMPLE_ICS, filename: 'sample.ics' });
buildTripCalendar.mockReset();
buildTripCalendar.mockImplementation(() => sampleCalendar());
// Reset feed tokens + trips between tests for isolation.
db.exec('DELETE FROM trips; DELETE FROM trip_members; UPDATE users SET feed_token = NULL;');
db.prepare("INSERT INTO trips (id, user_id, title, is_archived, start_date, end_date) VALUES (5, 1, 'Owned', 0, '2026-01-01', '2099-01-01')").run();
@@ -166,7 +170,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
expect(res.text).toContain('REFRESH-INTERVAL;VALUE=DURATION:PT1H');
expect(res.text).toContain('X-PUBLISHED-TTL:PT1H');
expect(res.text).toContain('BEGIN:VEVENT');
expect(exportICS).toHaveBeenCalledWith(5);
expect(buildTripCalendar).toHaveBeenCalledWith(5);
});
it('public trip feed: 404 for an unknown token', async () => {
@@ -197,7 +201,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
expect(res.text).toContain('REFRESH-INTERVAL;VALUE=DURATION:PT1H');
expect(res.text).toContain('X-WR-CALNAME:e2e-user');
const calledIds = exportICS.mock.calls.map((c) => c[0]).sort();
const calledIds = buildTripCalendar.mock.calls.map((c) => c[0]).sort();
expect(calledIds).toEqual([5]); // only the active, recent trip — not 6 (archived) or 7 (old)
});
@@ -213,7 +217,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
const res = await request(server).get(`/api/feed/user/${token}.ics`);
expect(res.status).toBe(200);
const calledIds = exportICS.mock.calls.map((c) => c[0]).sort();
const calledIds = buildTripCalendar.mock.calls.map((c) => c[0]).sort();
expect(calledIds).toEqual([5, 8]); // owned trip 5 AND member trip 8
});
@@ -224,15 +228,18 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
it('all-trips feed carries VTIMEZONE blocks so TZID references resolve (#1453)', async () => {
// A per-trip calendar whose event references a zone via TZID and defines it.
const ZONED_ICS =
'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//TREK//Travel Planner//EN\r\nCALSCALE:GREGORIAN\r\n' +
'METHOD:PUBLISH\r\nX-WR-CALNAME:Zoned\r\n' +
const PARIS_VTIMEZONE =
'BEGIN:VTIMEZONE\r\nTZID:Europe/Paris\r\nBEGIN:STANDARD\r\nDTSTART:19700101T000000\r\n' +
'TZOFFSETFROM:+0100\r\nTZOFFSETTO:+0100\r\nTZNAME:Europe/Paris\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n' +
'BEGIN:VEVENT\r\nUID:trek-res-1@trek\r\nDTSTAMP:20260101T000000Z\r\n' +
'DTSTART;TZID=Europe/Paris:20260602T090000\r\nSUMMARY:Flight\r\nEND:VEVENT\r\n' +
'END:VCALENDAR\r\n';
exportICS.mockReturnValue({ ics: ZONED_ICS, filename: 'zoned.ics' });
'TZOFFSETFROM:+0100\r\nTZOFFSETTO:+0100\r\nTZNAME:Europe/Paris\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n';
buildTripCalendar.mockImplementation(() => ({
calName: 'Zoned',
filename: 'zoned.ics',
timezones: new Map([['Europe/Paris', PARIS_VTIMEZONE]]),
events: [
'BEGIN:VEVENT\r\nUID:trek-res-1@trek\r\nDTSTAMP:20260101T000000Z\r\n' +
'DTSTART;TZID=Europe/Paris:20260602T090000\r\nSUMMARY:Flight\r\nEND:VEVENT\r\n',
],
}));
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(1));
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
@@ -379,6 +379,86 @@ describe('folded quirk branches', () => {
});
// The snapshot below was taken from the implementation as it stood when the code
// moved out of TripsService, before the calendar grew a structured model. It is
// the parity net for any change to how the calendar is assembled: the 20 cases
// above pin individual lines, this one pins the whole document including the
// order of the VTIMEZONE blocks and the folding.
describe('serialised output', () => {
it('CAL-010: a trip with a zoned assignment, a note day and a flight serialises byte for byte', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, {
title: 'Golden Trip',
description: 'Line one',
start_date: '2026-05-01',
end_date: '2026-05-01',
});
const day = createDay(testDb, trip.id, { date: '2026-05-01' });
const place = createPlace(testDb, trip.id, { name: 'Tokyo Tower', address: 'Minato', lat: 35.6586, lng: 139.7454 });
const assignment = createDayAssignment(testDb, day.id, place.id);
testDb.prepare('UPDATE day_assignments SET assignment_time=?, assignment_end_time=? WHERE id=?')
.run('09:00', '10:30', assignment.id);
createDayNote(testDb, day.id, trip.id, { text: 'Bring the tickets', time: '08:00' });
createReservation(testDb, trip.id, {
title: 'NH 203',
type: 'flight',
reservation_time: '2026-05-01T06:15',
confirmation_number: 'ABC123',
location: 'HND',
});
// DTSTAMP is the wall clock and the UID numbers are autoincrement state shared
// with every case above, so both are normalised: this pins the document, not
// the minute it ran in or its position in the file.
const ics = svc.exportICS(trip.id).ics
.replace(/DTSTAMP:\d{8}T\d{6}Z/g, 'DTSTAMP:<stamp>')
.replace(/UID:trek-([a-z]+)-\d+@trek/g, 'UID:trek-$1-<n>@trek');
expect(ics).toMatchInlineSnapshot(`
"BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//TREK//Travel Planner//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Golden Trip
BEGIN:VTIMEZONE
TZID:Asia/Tokyo
BEGIN:STANDARD
DTSTART:19700101T000000
TZOFFSETFROM:+0900
TZOFFSETTO:+0900
TZNAME:Asia/Tokyo
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:trek-trip-<n>@trek
DTSTAMP:<stamp>
DTSTART;VALUE=DATE:20260501
DTEND;VALUE=DATE:20260502
SUMMARY:Golden Trip
DESCRIPTION:Line one
END:VEVENT
BEGIN:VEVENT
UID:trek-assign-<n>@trek
DTSTAMP:<stamp>
DTSTART;TZID=Asia/Tokyo:20260501T090000
DTEND;TZID=Asia/Tokyo:20260501T103000
SUMMARY:Tokyo Tower
END:VEVENT
BEGIN:VEVENT
UID:trek-day-<n>@trek
DTSTAMP:<stamp>
DTSTART;VALUE=DATE:20260501
DTEND;VALUE=DATE:20260502
SUMMARY:Day 2
DESCRIPTION:Notes:\\n08:00 — Bring the tickets
END:VEVENT
END:VCALENDAR
"
`);
});
});
describe('CalendarService wiring', () => {
it('CAL-001: the module registers the service, so injection cannot silently fail', () => {
expectRegisteredProvider(CalendarModule, CalendarService);
-25
View File
@@ -1,25 +0,0 @@
import { describe, it, expect } from 'vitest';
import { Test } from '@nestjs/testing';
import { HealthController } from '../../../src/nest/health/health.controller';
import { HealthService } from '../../../src/nest/health/health.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
describe('Nest dependency injection (vitest + swc)', () => {
it('injects HealthService + DatabaseService into HealthController by type', async () => {
const moduleRef = await Test.createTestingModule({
controllers: [HealthController],
providers: [
HealthService,
{ provide: DatabaseService, useValue: { get: () => ({ n: 7 }) } },
],
}).compile();
const controller = moduleRef.get(HealthController);
expect(controller.getHealth()).toEqual({
ok: true,
runtime: 'nestjs',
diInjected: true,
userCount: 7,
});
});
});
+4 -2
View File
@@ -3,7 +3,7 @@ import { HttpException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { db } from '../../../src/db/database';
import { AppModule } from '../../../src/nest/app.module';
import { HealthController } from '../../../src/nest/health/health.controller';
import { FeaturesController } from '../../../src/nest/health/features.controller';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AdminGuard } from '../../../src/nest/auth/admin.guard';
@@ -17,7 +17,9 @@ describe('AppModule wiring', () => {
.overrideProvider(DatabaseService)
.useValue({ get: () => ({ n: 0 }) })
.compile();
expect(moduleRef.get(HealthController)).toBeInstanceOf(HealthController);
// The one test that builds the whole AppModule: resolving a controller out of
// it proves every module in the graph compiled, not just this one.
expect(moduleRef.get(FeaturesController)).toBeInstanceOf(FeaturesController);
});
});