Events 2.4.0 backend: protocol v2, Linked products, the event feed

- Hub client: register and heartbeat on protocol v2 with the site's
  Ed25519 key (sent on the heartbeat until the Hub has it); falls back to
  v1 for a day if the Hub refuses v2, so the licence always refreshes.
- crosscode.link/1 Connect / Disconnect, both directions, trusted through
  the Hub's cached linkedProducts (ProductLink, LinkNonce).
- GET /api/feed/v1/events from FeedEntry (go-live, closing and selling
  out are changes; deactivated events go in deleted), event.changed to
  connected products, and showing their events (ImportedEvent).
- /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains
  crosscodeEvent and priceRangeCents for the JSON-LD.
- Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 12:24:29 +02:00
co-authored by Claude Opus 5.5
parent 390b80e56e
commit 8a930d07c6
30 changed files with 5874 additions and 17 deletions
+74
View File
@@ -0,0 +1,74 @@
/**
* 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 };
export async function syncLink(link: Link, now = new Date()): 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;
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)).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);
}