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>
80 lines
5.0 KiB
TypeScript
80 lines
5.0 KiB
TypeScript
/**
|
|
* Showing events from linked products (docs/EVENTS-2.4-PLAN.md §4): each link with "Show events
|
|
* from this product" on is fetched every 15 minutes (`feed-sync` job) and straight away on a
|
|
* valid `event.changed` (`feed-sync-link` task). Its events are kept as read-only copies
|
|
* (`ImportedEvent`), keyed by origin product + id, and never published again.
|
|
*
|
|
* - The last good copy stays: a failed fetch only records the error.
|
|
* - One bad event is skipped and logged (parseEventFeed); it never holds up the rest.
|
|
* - Only events that really come from that sibling are taken (origin.installId and product
|
|
* must match the link), so one product can't put words in another's mouth.
|
|
*/
|
|
import { eventKey, FEED_PATHS, parseEventFeed, type CrosscodeEvent } from '@crosscode/contracts';
|
|
import { callSibling, siblingUrl } from '../links/http';
|
|
|
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
|
const prisma = require('../config/db');
|
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
|
|
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
|
|
const OVERLAP_MS = 5 * 60 * 1000;
|
|
|
|
type Link = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
|
|
|
|
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; skipped?: number; error?: string };
|
|
|
|
/**
|
|
* `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 = !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' }));
|
|
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1: ${parsed.error.issues.slice(0, 3).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`);
|
|
const { feed, rejected } = parsed;
|
|
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`}):`, r.issues.slice(0, 3).map((i) => `${i.path.join('.')} ${i.message}`).join('; '));
|
|
|
|
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
|
|
const skipped = feed.events.length - theirs.length;
|
|
for (const e of theirs) await upsert(link.installId, e);
|
|
const deletedKeys = feed.deleted.map((d) => `${link.product}:${d.id}`);
|
|
let deleted = deletedKeys.length ? (await prisma.importedEvent.deleteMany({ where: { linkId: link.installId, key: { in: deletedKeys } } })).count : 0;
|
|
// A full fetch is the whole list: anything not in it is gone (or ended a while ago).
|
|
if (!since) deleted += (await prisma.importedEvent.deleteMany({ where: { linkId: link.installId, key: { notIn: theirs.map(eventKey) } } })).count;
|
|
|
|
await prisma.productLink.update({
|
|
where: { installId: link.installId },
|
|
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
|
|
});
|
|
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length, skipped };
|
|
} catch (e) {
|
|
const error = String((e as Error)?.message || e).slice(0, 500);
|
|
await prisma.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
|
|
return { installId: link.installId, ok: false, error };
|
|
}
|
|
}
|
|
|
|
async function upsert(linkId: string, e: CrosscodeEvent) {
|
|
const data = { linkId, payload: e, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), campusSlug: e.campus?.slug ?? null, updatedAt: new Date(e.updatedAt) };
|
|
await prisma.importedEvent.upsert({ where: { key: eventKey(e) }, create: { key: eventKey(e), ...data }, update: data });
|
|
}
|
|
|
|
/** The `feed-sync` job: every link that shows events, one after another (one failing never stops the rest). */
|
|
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, { full: true })).ok) failed++;
|
|
return { links: links.length, failed };
|
|
}
|
|
|
|
/** The `feed-sync-link` task (after an `event.changed`). */
|
|
export async function syncOne(installId: string): Promise<SyncResult | { skipped: string }> {
|
|
const link: Link | null = await prisma.productLink.findUnique({ where: { installId } });
|
|
if (!link) return { skipped: 'no such link' };
|
|
return syncLink(link);
|
|
}
|