feat(offline): detect update conflicts on the server for places and packing

Update handlers accept an optional X-Base-Updated-At token and reject a stale overwrite with 409, returning the current server row. An absent token keeps the existing last-write-wins behaviour, so older clients are unaffected. packing_items gains an updated_at column (migration + stamped on every insert) so it can take part in conflict detection too.
This commit is contained in:
Maurice
2026-06-30 09:52:44 +02:00
committed by Maurice
parent 5fd66f4833
commit c552472b63
15 changed files with 243 additions and 23 deletions
+14
View File
@@ -3093,6 +3093,20 @@ function runMigrations(db: Database.Database): void {
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_trips_feed_token ON trips(feed_token) WHERE feed_token IS NOT NULL');
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_users_feed_token ON users(feed_token) WHERE feed_token IS NOT NULL');
},
// Optimistic-concurrency token for offline conflict detection (#1135).
// packing_items had only created_at, so an offline edit could not be checked
// against a concurrent server change. SQLite forbids a non-constant DEFAULT on
// ALTER ADD COLUMN, so add it nullable and backfill from created_at; new rows
// set it explicitly (packingService). Additive: a request without the
// X-Base-Updated-At header keeps the old last-write-wins behaviour.
() => {
try {
db.exec('ALTER TABLE packing_items ADD COLUMN updated_at DATETIME');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
db.exec('UPDATE packing_items SET updated_at = COALESCE(updated_at, created_at, CURRENT_TIMESTAMP) WHERE updated_at IS NULL');
},
];
if (currentVersion < migrations.length) {
+1 -1
View File
@@ -66,7 +66,7 @@ function seedExampleTrips(db: Database.Database, adminId: number, demoId: number
const insertDay = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)');
const insertPlace = db.prepare('INSERT INTO places (trip_id, name, lat, lng, address, category_id, place_time, duration_minutes, notes, image_url, google_place_id, website, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
const insertAssignment = db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, ?)');
const insertPacking = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, ?, ?, ?)');
const insertPacking = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order, updated_at) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const insertBudget = db.prepare('INSERT INTO budget_items (trip_id, category, name, total_price, persons, note) VALUES (?, ?, ?, ?, ?, ?)');
const insertReservation = db.prepare('INSERT INTO reservations (trip_id, day_id, title, reservation_time, confirmation_number, status, type, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
@@ -13,6 +13,7 @@ import {
} from '@nestjs/common';
import type { User } from '../../types';
import { PackingService } from './packing.service';
import { isUpdateConflict } from '../../services/conflictResult';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -109,14 +110,19 @@ export class PackingController {
@Param('id') id: string,
@Body() body: Record<string, unknown>,
@Headers('x-socket-id') socketId?: string,
@Headers('x-base-updated-at') ifMatch?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const { name, checked, category, weight_grams, bag_id, quantity } = body as Record<string, never>;
const updated = this.packing.updateItem(tripId, id, { name, checked, category, weight_grams, bag_id, quantity }, Object.keys(body));
const updated = this.packing.updateItem(tripId, id, { name, checked, category, weight_grams, bag_id, quantity }, Object.keys(body), ifMatch);
if (!updated) {
throw new HttpException({ error: 'Item not found' }, 404);
}
// Stale offline overwrite — surface the conflict for client-side resolution (#1135).
if (isUpdateConflict(updated)) {
throw new HttpException({ error: 'conflict', server: updated.server }, 409);
}
this.packing.broadcast(tripId, 'packing:updated', { item: updated }, socketId);
return { item: updated };
}
+2 -2
View File
@@ -35,8 +35,8 @@ export class PackingService {
return svc.createItem(tripId, data);
}
updateItem(tripId: string, id: string, data: Parameters<typeof svc.updateItem>[2], changedKeys: string[]) {
return svc.updateItem(tripId, id, data, changedKeys);
updateItem(tripId: string, id: string, data: Parameters<typeof svc.updateItem>[2], changedKeys: string[], ifMatch?: string) {
return svc.updateItem(tripId, id, data, changedKeys, ifMatch);
}
deleteItem(tripId: string, id: string): boolean {
+10 -2
View File
@@ -18,6 +18,7 @@ import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import type { User } from '../../types';
import { PlacesService } from './places.service';
import { isUpdateConflict } from '../../services/conflictResult';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -288,14 +289,21 @@ export class PlacesController {
@Param('id') id: string,
@Body() body: Record<string, unknown>,
@Headers('x-socket-id') socketId?: string,
@Headers('x-base-updated-at') ifMatch?: string,
) {
const trip = this.requireTrip(tripId, user);
validateLengths(body);
this.requireEdit(trip, user);
const place = this.places.update(tripId, id, body as never);
if (!place) {
const result = this.places.update(tripId, id, body as never, ifMatch);
if (!result) {
throw new HttpException({ error: 'Place not found' }, 404);
}
// The offline edit was based on a now-stale version — let the client resolve
// it (#1135) instead of silently overwriting the newer server state.
if (isUpdateConflict(result)) {
throw new HttpException({ error: 'conflict', server: result.server }, 409);
}
const place = result;
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
this.places.onUpdated(place.id);
return { place };
+2 -2
View File
@@ -40,8 +40,8 @@ export class PlacesService {
return svc.createPlace(tripId, data);
}
update(tripId: string, id: string, data: Parameters<typeof svc.updatePlace>[2]) {
return svc.updatePlace(tripId, id, data);
update(tripId: string, id: string, data: Parameters<typeof svc.updatePlace>[2], ifMatch?: string) {
return svc.updatePlace(tripId, id, data, ifMatch);
}
remove(tripId: string, id: string): boolean {
+17
View File
@@ -0,0 +1,17 @@
/**
* Optimistic-concurrency result shared by the entity update services (#1135).
*
* When a client replays an offline edit it may send `X-Base-Updated-At` — the
* `updated_at` the edit was based on. If the row has moved on since, the update
* service returns this sentinel instead of overwriting, and the controller turns
* it into a 409 carrying the server's current version so the client can let the
* user resolve the conflict. Absent token => unconditional update (back-compat).
*/
export interface UpdateConflict {
conflict: true;
server: unknown;
}
export function isUpdateConflict(result: unknown): result is UpdateConflict {
return !!result && typeof result === 'object' && (result as { conflict?: unknown }).conflict === true;
}
+16 -7
View File
@@ -1,5 +1,6 @@
import { db } from '../db/database';
import { avatarUrl } from './authService';
import type { UpdateConflict } from './conflictResult';
const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b'];
@@ -19,7 +20,7 @@ export function createItem(tripId: string | number, data: { name: string; catego
const qty = Math.max(1, Math.min(999, Number(data.quantity) || 1));
const result = db.prepare(
'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity) VALUES (?, ?, ?, ?, ?, ?)'
'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity, updated_at) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)'
).run(tripId, data.name, data.checked ? 1 : 0, data.category || 'Allgemein', sortOrder, qty);
return db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid);
@@ -29,11 +30,18 @@ export function updateItem(
tripId: string | number,
id: string | number,
data: { name?: string; checked?: number; category?: string; weight_grams?: number | null; bag_id?: number | null; quantity?: number },
bodyKeys: string[]
) {
const item = db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId);
bodyKeys: string[],
ifMatch?: string,
): unknown | UpdateConflict | null {
const item = db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as { updated_at?: string | null } | undefined;
if (!item) return null;
// Optimistic concurrency (#1135): reject a stale offline overwrite. Absent
// token => unconditional update (back-compat with older clients).
if (ifMatch !== undefined && item.updated_at != null && String(item.updated_at) !== ifMatch) {
return { conflict: true, server: db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id) };
}
db.prepare(`
UPDATE packing_items SET
name = COALESCE(?, name),
@@ -41,7 +49,8 @@ export function updateItem(
category = COALESCE(?, category),
weight_grams = CASE WHEN ? THEN ? ELSE weight_grams END,
bag_id = CASE WHEN ? THEN ? ELSE bag_id END,
quantity = CASE WHEN ? THEN ? ELSE quantity END
quantity = CASE WHEN ? THEN ? ELSE quantity END,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`).run(
data.name || null,
@@ -83,7 +92,7 @@ export function bulkImport(tripId: string | number, items: ImportItem[]) {
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null };
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const stmt = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, weight_grams, bag_id, sort_order, quantity) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
const stmt = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, weight_grams, bag_id, sort_order, quantity, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const created: any[] = [];
const insertAll = db.transaction(() => {
@@ -225,7 +234,7 @@ export function applyTemplate(tripId: string | number, templateId: string | numb
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null };
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const insert = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, 0, ?, ?)');
const insert = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order, updated_at) VALUES (?, ?, 0, ?, ?, CURRENT_TIMESTAMP)');
const added: any[] = [];
for (const ti of templateItems) {
const result = insert.run(tripId, ti.name, ti.category, sortOrder++);
+15 -4
View File
@@ -16,6 +16,7 @@ import {
import { enrichImportedPlaces, type EnrichablePlace } from './placeEnrichment';
import * as placePhotoCache from './placePhotoCache';
import { searchUnsplashPhotos } from './unsplashService';
import { type UpdateConflict, isUpdateConflict } from './conflictResult';
// Reclaim a deleted place's cached marker photo if nothing else references it.
// The cache key is the Google place_id, or — for coordinate-only places — the
@@ -179,10 +180,18 @@ export function updatePlace(
google_place_id?: string; google_ftid?: string; osm_id?: string; website?: string; phone?: string;
transport_mode?: string; tags?: number[];
},
) {
ifMatch?: string,
): ReturnType<typeof getPlaceWithTags> | UpdateConflict | null {
const existingPlace = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId) as Place | undefined;
if (!existingPlace) return null;
// Optimistic concurrency (#1135): when the caller sent the version it based its
// edit on and the row has moved on since, reject instead of clobbering. Absent
// token => unconditional update (back-compat — old clients keep last-write-wins).
if (ifMatch !== undefined && existingPlace.updated_at != null && String(existingPlace.updated_at) !== ifMatch) {
return { conflict: true, server: getPlaceWithTags(placeId) };
}
const {
name, description, lat, lng, address, category_id, price, currency,
place_time, end_time,
@@ -298,13 +307,15 @@ export function updatePlacesMany(
tripId: string,
ids: number[],
body: Parameters<typeof updatePlace>[2],
): NonNullable<ReturnType<typeof updatePlace>>[] {
): NonNullable<ReturnType<typeof getPlaceWithTags>>[] {
if (ids.length === 0) return [];
const updated: NonNullable<ReturnType<typeof updatePlace>>[] = [];
const updated: NonNullable<ReturnType<typeof getPlaceWithTags>>[] = [];
const run = db.transaction((list: number[]) => {
for (const id of list) {
// Bulk update sends no If-Match, so updatePlace never returns a conflict
// here; the guard keeps the types honest.
const place = updatePlace(tripId, String(id), body);
if (place) updated.push(place);
if (place && !isUpdateConflict(place)) updated.push(place);
}
});
run(ids);
+2 -2
View File
@@ -758,8 +758,8 @@ export function copyTripById(sourceTripId: string | number, newOwnerId: number,
const oldPacking = db.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(sourceTripId) as any[];
const insertPacking = db.prepare(`
INSERT INTO packing_items (trip_id, name, checked, category, sort_order, weight_grams, bag_id)
VALUES (?, ?, 0, ?, ?, ?, ?)
INSERT INTO packing_items (trip_id, name, checked, category, sort_order, weight_grams, bag_id, updated_at)
VALUES (?, ?, 0, ?, ?, ?, ?, CURRENT_TIMESTAMP)
`);
for (const p of oldPacking) {
insertPacking.run(newTripId, p.name, p.category, p.sort_order, p.weight_grams,
@@ -119,9 +119,20 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
const broadcast = vi.fn();
const svc = makeService({ updateItem, broadcast } as Partial<PackingService>);
new PackingController(svc).update(user, '5', '9', { name: 'X', checked: true }, 'sock');
expect(updateItem).toHaveBeenCalledWith('5', '9', expect.objectContaining({ name: 'X', checked: true }), ['name', 'checked']);
expect(updateItem).toHaveBeenCalledWith('5', '9', expect.objectContaining({ name: 'X', checked: true }), ['name', 'checked'], undefined);
expect(broadcast).toHaveBeenCalledWith('5', 'packing:updated', { item: { id: 9, name: 'X' } }, 'sock');
});
it('forwards the X-Base-Updated-At token and 409s on a conflict (#1135)', () => {
const updateItem = vi.fn().mockReturnValue({ conflict: true, server: { id: 9, name: 'Theirs' } });
const broadcast = vi.fn();
const svc = makeService({ updateItem, broadcast } as Partial<PackingService>);
expect(thrown(() => new PackingController(svc).update(user, '5', '9', { name: 'Mine' }, 'sock', '2026-01-01 00:00:00'))).toEqual({
status: 409, body: { error: 'conflict', server: { id: 9, name: 'Theirs' } },
});
expect(updateItem).toHaveBeenCalledWith('5', '9', expect.objectContaining({ name: 'Mine' }), ['name'], '2026-01-01 00:00:00');
expect(broadcast).not.toHaveBeenCalled();
});
});
describe('PUT /reorder', () => {
@@ -49,7 +49,7 @@ describe('PackingService (wrapper delegation + helpers)', () => {
s.verifyTripAccess('5', 1); expect(pk.verifyTripAccess).toHaveBeenCalledWith('5', 1);
s.listItems('5'); expect(pk.listItems).toHaveBeenCalledWith('5');
s.createItem('5', { name: 'a' }); expect(pk.createItem).toHaveBeenCalledWith('5', { name: 'a' });
s.updateItem('5', '2', { name: 'b' } as never, ['name']); expect(pk.updateItem).toHaveBeenCalledWith('5', '2', { name: 'b' }, ['name']);
s.updateItem('5', '2', { name: 'b' } as never, ['name']); expect(pk.updateItem).toHaveBeenCalledWith('5', '2', { name: 'b' }, ['name'], undefined);
s.deleteItem('5', '2'); expect(pk.deleteItem).toHaveBeenCalledWith('5', '2');
s.bulkImport('5', [{ name: 'x' }] as never); expect(pk.bulkImport).toHaveBeenCalledWith('5', [{ name: 'x' }]);
s.reorderItems('5', [3, 1] as never); expect(pk.reorderItems).toHaveBeenCalledWith('5', [3, 1]);
@@ -236,6 +236,18 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
expect(onUpdated).toHaveBeenCalledWith(9);
});
it('PUT /:id forwards the base-version token and 409s on a conflict (#1135)', () => {
const update = vi.fn().mockReturnValue({ conflict: true, server: { id: 9, name: 'Theirs' } });
const onUpdated = vi.fn(); const broadcast = vi.fn();
const s = svc({ update, onUpdated, broadcast } as Partial<PlacesService>);
expect(thrown(() => new PlacesController(s).update(user, '5', '9', { name: 'Mine' }, 'sock', '2026-01-01 00:00:00'))).toEqual({
status: 409, body: { error: 'conflict', server: { id: 9, name: 'Theirs' } },
});
expect(update).toHaveBeenCalledWith('5', '9', expect.objectContaining({ name: 'Mine' }), '2026-01-01 00:00:00');
expect(broadcast).not.toHaveBeenCalled();
expect(onUpdated).not.toHaveBeenCalled();
});
it('DELETE /:id fires the hook then 404 / success', () => {
const onDeleted = vi.fn();
expect(thrown(() => new PlacesController(svc({ remove: vi.fn().mockReturnValue(false), onDeleted } as Partial<PlacesService>)).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Place not found' } });
@@ -0,0 +1,129 @@
/**
* Optimistic-concurrency / 409 conflict tests (#1135) for the place + packing
* update services. A matching If-Match token (or none) updates as before; a
* stale token returns the conflict sentinel carrying the server's current row.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
function getPlaceWithTags(placeId: number | string) {
const p = db.prepare('SELECT * FROM places WHERE id = ?').get(placeId);
if (!p) return null;
return { ...(p as object), category: null, tags: [] };
}
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { updatePlace, createPlace } from '../../../src/services/placeService';
import { createItem, updateItem } from '../../../src/services/packingService';
import { isUpdateConflict } from '../../../src/services/conflictResult';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
function freshPlace(tripId: number) {
const place = createPlace(String(tripId), { name: 'Original' }) as { id: number; updated_at: string };
return place;
}
describe('updatePlace — optimistic concurrency', () => {
it('updates normally when no If-Match token is sent (back-compat)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Edited' });
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
it('updates when the If-Match token matches the current updated_at', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
it('returns a conflict (with the server row) when the token is stale', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
expect(isUpdateConflict(result)).toBe(true);
if (isUpdateConflict(result)) {
expect((result.server as { name: string }).name).toBe('Original');
}
// The row must NOT have been overwritten.
const row = testDb.prepare('SELECT name FROM places WHERE id = ?').get(place.id) as { name: string };
expect(row.name).toBe('Original');
});
it('returns null for a place that does not exist', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlace(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
});
});
describe('updateItem (packing) — optimistic concurrency', () => {
it('migration added updated_at and createItem stamps it', () => {
const cols = testDb.prepare("PRAGMA table_info('packing_items')").all() as { name: string }[];
expect(cols.map(c => c.name)).toContain('updated_at');
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string | null };
expect(item.updated_at).toBeTruthy();
});
it('returns a conflict when the packing token is stale', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string };
const stale = updateItem(trip.id, item.id, { name: 'Mine' }, ['name'], '1999-01-01 00:00:00');
expect(isUpdateConflict(stale)).toBe(true);
const fresh = updateItem(trip.id, item.id, { name: 'Edited' }, ['name'], item.updated_at);
expect(isUpdateConflict(fresh)).toBe(false);
expect((fresh as { name: string }).name).toBe('Edited');
});
})
+3
View File
@@ -30,6 +30,9 @@ export const packingItemSchema = z.object({
bag_id: z.number().nullable().optional(),
quantity: z.number().optional(),
created_at: z.string().optional(),
// Optimistic-concurrency token for offline conflict detection (#1135). Added
// by migration 98; older rows backfill from created_at.
updated_at: z.string().nullable().optional(),
});
export type PackingItem = z.infer<typeof packingItemSchema>;