Events 3.7.2 + Website 1.6.1: no duplicate events after a reseed; "Events site" in the header

A reseed gives every event a new id without listing the old ones in the
feed's `deleted`, and consumers only fetched ?updatedSince= after the first
sync, so the old copies stayed beside the new ones.

- Both: the 15-minute feed poll and "Sync now" fetch the whole list and
  drop copies that aren't in it; the fetch after event.changed stays
  incremental.
- Events set-demo.js keeps FeedEntry and marks its live entries removed,
  resets the links' lastGoodAt, then publishes the new feed, sends
  event.changed and fetches the linked products' events back in.
- Website loadDemo lists the old published events in FeedRemoval and sends
  event.changed after publishing.
- Website header: links to the church's other sites read "Events site"
  with an external-link icon, not a second "Events".

Checked: Website backend tests (133), Events backend tests (802), both
typechecks, Website frontend build. set-demo.js not run end to end (no
local database).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 15:35:38 +02:00
co-authored by Claude Opus 5.5
parent a75d2f7b46
commit 7f681c9e81
24 changed files with 211 additions and 29 deletions
+5 -1
View File
@@ -63,9 +63,13 @@ previous demo and creates it again.
| The admin account, including its login history, trusted devices and 2FA | Every other user |
| Migration history | Registrations, payments, tickets, scans, coupons, waitlists, consents, cabins, feedback, analytics, audit log |
| Uploaded files on disk (`public/uploads`) | Queued scheduled emails/WhatsApps (`data/scheduled-emails.json`) |
| Links to the church's other products (Accounts, the Website) | Copies of the linked products' events (fetched again straight away) |
| The event feed's history: the old events are listed as removed | |
The wipe and the new data are written in one database transaction. If that fails,
nothing changes. The past events' cashups run straight afterwards, through the same
nothing changes. Since 3.7.2 the script then publishes the new events in the event feed and
tells the linked products (the Church Website), so their next page load shows the new events
and not the old ones, and fetches the linked products' events back in. The past events' cashups run straight afterwards, through the same
code as the cashup screen. If one of those fails, re-run the script.
---
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.7.1",
"version": "3.7.2",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+42
View File
@@ -79,6 +79,9 @@ const KEEP_TABLES = new Set([
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
// its link nobody can sign in). Their feeds are data and go.
'ProductLink', 'LinkNonce',
// 3.7.2: what the feed last published. Its live entries are marked removed instead (clearData),
// so linked products are told the old events are gone, not left showing them beside the new.
'FeedEntry',
]);
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
@@ -1823,6 +1826,10 @@ async function clearData(tx) {
await tx.$executeRawUnsafe(`UPDATE "User" SET ${[...new Set(userRefs.map(r => `"${r.column}" = NULL`))].join(', ')}`);
for (const table of deleteInstead) await tx.$executeRawUnsafe(`DELETE FROM "${table}"`);
}
// 3.7.2: every event the feed published goes into its `deleted` list, and the copies of linked
// products' events (truncated above) are fetched again in full.
await tx.feedEntry.updateMany({ where: { removedAt: null }, data: { removedAt: new Date() } });
await tx.productLink.updateMany({ data: { lastGoodAt: null } });
// Their password resets, 2FA codes and trusted devices go with them (onDelete: Cascade).
const { count } = await tx.user.deleteMany({ where: { id: { not: admin.id } } });
await tx.securityEvent.deleteMany({ where: { OR: [{ userId: null }, { userId: { not: admin.id } }] } });
@@ -1911,6 +1918,7 @@ async function main() {
clearScheduledEmails();
const pastFinancials = await closePastEvents();
const accounts = await demoAccounts(oldSubs);
const feed = await demoFeed();
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
@@ -1963,6 +1971,40 @@ async function main() {
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
}
if (feed && feed.links) console.log(`Connected products: ${feed.told} of ${feed.links} told the events changed${feed.failed ? `; ${feed.failed} couldn't be fetched from (the next poll catches up)` : ''}.`);
}
/**
* The backend's own code: the compiled code (dist/) on a server, the TypeScript through tsx in
* development. With dist/, its database client is a second one, disconnected at the end.
*/
function backendModule(rel) {
const dist = path.join(__dirname, '..', 'dist', `${rel}.js`);
if (fs.existsSync(dist)) {
accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db'));
return require(dist);
}
require('tsx/cjs');
return require(`../src/${rel}.ts`);
}
/**
* 3.7.2: the new events published in the feed straight away, linked products (the Website) told,
* so their next page load shows the new events without the old (marked removed in clearData), and
* their events fetched back in. Never fails the demo: the jobs catch up within 15 minutes.
*/
async function demoFeed() {
try {
const { refreshAndNotify } = backendModule('feed/notify');
const { syncAll } = backendModule('feed/sync');
const { told } = await refreshAndNotify(new Date());
const synced = await syncAll(new Date());
const links = await prisma.productLink.count();
return { links, told, failed: synced.failed };
} catch (e) {
console.warn(`[warn] The feed couldn't be refreshed now (${e.message}); the backend's feed jobs catch up within 15 minutes.`);
return null;
}
}
/**
+8 -3
View File
@@ -23,9 +23,14 @@ type Link = { installId: string; product: string; url: string; showEvents: boole
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; skipped?: number; error?: string };
export async function syncLink(link: Link, now = new Date()): Promise<SyncResult> {
/**
* `full` asks for the whole list and drops copies no longer in it: a sibling that loses events
* without listing them in `deleted` (a reseed, a restore) would otherwise leave stale copies
* beside the new ones for good.
*/
export async function syncLink(link: Link, now = new Date(), { full = false }: { full?: boolean } = {}): Promise<SyncResult> {
if (!link.showEvents) return { installId: link.installId, ok: true, imported: 0, deleted: 0 };
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
const since = !full && link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(link.url, FEED_PATHS.events, since ? { updatedSince: since.toISOString() } : {});
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
@@ -62,7 +67,7 @@ async function upsert(linkId: string, e: CrosscodeEvent) {
export async function syncAll(now = new Date()): Promise<{ links: number; failed: number }> {
const links: Link[] = await prisma.productLink.findMany({ where: { showEvents: true } });
let failed = 0;
for (const link of links) if (!(await syncLink(link, now)).ok) failed++;
for (const link of links) if (!(await syncLink(link, now, { full: true })).ok) failed++;
return { links: links.length, failed };
}
@@ -207,7 +207,7 @@ export const syncNow = defineRoute({
async handler({ params }) {
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
if (!link) throw notFound('That connected product');
await syncLink(link);
await syncLink(link, new Date(), { full: true });
return { data: await overview() };
},
});
@@ -399,6 +399,16 @@ describe('events from a linked product', () => {
expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince=');
});
test('a full fetch (the poll) drops copies of events the source lost without saying (a reseed)', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
db.t.importedEvent.set('website:old', { key: 'website:old', linkId: WEBSITE_ID });
const e = sample();
answer(feedOf([e]));
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW, { full: true });
expect(String(global.fetch.mock.calls[0][0])).not.toContain('updatedSince=');
expect([...db.t.importedEvent.keys()]).toEqual([`website:${e.id}`]);
});
test('deleted events go; never re-published in this site\'s own feed', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
const e = sample();