Publish my events: the Website's simple events as crosscode.event/1 (GET /api/feed/v1/events, updatedSince, removals in deleted for 90 days) and a signed event.changed to linked siblings. Show events from: each sibling's feed every 15 minutes and at once on its signed event.changed; read-only copies of only that sibling's events, one bad event skipped, the last good copy kept. Admin: Linked products. church.changed from Accounts refreshes the profile at once. Plan: the video hero, more blocks and more pages move to website@1.1.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
10 KiB
TypeScript
174 lines
10 KiB
TypeScript
/**
|
|
* The event feed (WEBSITE-1.0-PLAN §8, ROADMAP-v3 §4), both ways, as Cross Events 2.4:
|
|
*
|
|
* - **Publish my events** (AppSetting `feed_publish`, on by default): the Website's published simple
|
|
* events as `crosscode.event/1` at `GET /api/feed/v1/events?updatedSince=`, with removed ones in
|
|
* `deleted` for 90 days. Only events it made itself, never ones it imported (no loops).
|
|
* - **Show events from** each linked sibling (`ProductLink.showEvents`): fetched every 15 minutes and
|
|
* at once on its signed `event.changed`; read-only copies, the last good copy kept when a fetch
|
|
* fails, one bad event skipped without holding up the rest, and only events that really come
|
|
* from that sibling.
|
|
* - Linked siblings are told (`event.changed`) when one of the Website's events changes.
|
|
*/
|
|
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventSchema, FEED_PATHS, parseEventFeed, type CrosscodeEvent, type EventChanged, type EventFeed } from '@crosscode/contracts';
|
|
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
|
import type { Ctx } from '../context.js';
|
|
import { callSibling, siblingUrl } from '../links/http.js';
|
|
import { imageOf } from '../site/snapshot.js';
|
|
|
|
const DAY = 864e5;
|
|
export const ENDED_KEEP_DAYS = 30;
|
|
export const REMOVED_KEEP_DAYS = 90;
|
|
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
|
|
const OVERLAP_MS = 5 * 60 * 1000;
|
|
|
|
export const publishOn = (ctx: Ctx) => ctx.settings.bool('feed_publish', true);
|
|
|
|
type SimpleRow = {
|
|
id: string; slug: string; title: string; startsAt: Date; endsAt: Date | null; allDay: boolean; timezone: string; location: string | null;
|
|
description: string | null; imageId: string | null; link: string | null; cancelled: boolean; updatedAt: Date;
|
|
};
|
|
|
|
/** One of the Website's simple events as `crosscode.event/1`. */
|
|
export function toCrosscodeEvent(ctx: Ctx, e: SimpleRow, installId: string, imageUrl: string | null): CrosscodeEvent {
|
|
const url = `${ctx.config.publicUrl}/events/${e.slug}`;
|
|
const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3));
|
|
return {
|
|
schema: EVENT_SCHEMA,
|
|
id: e.id,
|
|
origin: { product: 'website', installId, url },
|
|
status: e.cancelled ? 'cancelled' : 'published',
|
|
updatedAt: e.updatedAt.toISOString(),
|
|
title: e.title.slice(0, 200),
|
|
summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 300) : null,
|
|
description: e.description,
|
|
imageUrl,
|
|
timezone: e.timezone,
|
|
startsAt: e.startsAt.toISOString(),
|
|
endsAt: ends.toISOString(),
|
|
allDay: e.allDay,
|
|
sessions: [],
|
|
location: e.location ? { name: e.location.slice(0, 200), address: null, onlineUrl: null } : null,
|
|
campus: null,
|
|
series: null,
|
|
tags: [],
|
|
// Only Cross Events takes registrations: a link, or nothing (roadmap decision 4).
|
|
registration: e.link ? { mode: 'external', url: e.link, status: 'open', opensAt: null, closesAt: null, priceFrom: null } : { mode: 'none', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null },
|
|
} as CrosscodeEvent;
|
|
}
|
|
|
|
/** `GET /api/feed/v1/events`: what changed since `since` (everything when null). */
|
|
export async function buildFeed(ctx: Ctx, since: Date | null): Promise<EventFeed> {
|
|
const now = ctx.now();
|
|
const installId = (await ctx.settings.get('hub_install_id'))!;
|
|
const [rows, media, removals] = await Promise.all([
|
|
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, startsAt: { gte: new Date(now.getTime() - (ENDED_KEEP_DAYS + 30) * DAY) } }, orderBy: { startsAt: 'asc' } }),
|
|
ctx.db.mediaAsset.findMany(),
|
|
ctx.db.feedRemoval.findMany({ where: { removedAt: { gte: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY), ...(since ? { gt: since } : {}) } } }),
|
|
]);
|
|
const byId = new Map(media.map((m) => [m.id, m]));
|
|
const events: CrosscodeEvent[] = [];
|
|
for (const row of rows) {
|
|
const ends = row.endsAt ?? row.startsAt;
|
|
if (ends.getTime() < now.getTime() - ENDED_KEEP_DAYS * DAY) continue;
|
|
if (since && row.updatedAt <= since) continue;
|
|
const m = row.imageId ? byId.get(row.imageId) : null;
|
|
const e = toCrosscodeEvent(ctx, row, installId, m ? `${ctx.config.publicUrl}${imageOf(m).url}` : null);
|
|
// Never publish something the contract refuses.
|
|
if (eventSchema.safeParse(e).success) events.push(e);
|
|
}
|
|
return { schema: EVENT_FEED_SCHEMA, generatedAt: now.toISOString(), events, deleted: removals.map((r) => ({ id: r.eventId, deletedAt: r.removedAt.toISOString() })) };
|
|
}
|
|
|
|
/** A simple event left the feed: siblings drop their copy. Back on it (published again): no longer removed. */
|
|
export async function markRemoved(ctx: Ctx, eventId: string, removed: boolean) {
|
|
if (removed) await ctx.db.feedRemoval.upsert({ where: { eventId }, create: { eventId, removedAt: ctx.now() }, update: { removedAt: ctx.now() } });
|
|
else await ctx.db.feedRemoval.deleteMany({ where: { eventId } });
|
|
}
|
|
|
|
/** Tells every linked sibling (not Accounts) that these events changed. One try; their poll catches up. */
|
|
export async function notifyLinks(ctx: Ctx, eventIds: string[]): Promise<{ told: number; failed: number }> {
|
|
if (!eventIds.length || !(await publishOn(ctx))) return { told: 0, failed: 0 };
|
|
const senderId = await ctx.settings.get('hub_install_id');
|
|
if (!senderId) return { told: 0, failed: 0 };
|
|
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
|
|
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: ctx.now().toISOString(), eventIds: eventIds.slice(0, 100) };
|
|
const raw = JSON.stringify(body);
|
|
let told = 0;
|
|
let failed = 0;
|
|
await Promise.all(links.map(async (link) => {
|
|
try {
|
|
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: ctx.secrets.decrypt(link.secret), rawBody: raw });
|
|
await callSibling(await siblingUrl(ctx, link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
|
|
told++;
|
|
} catch (e) {
|
|
failed++;
|
|
console.warn(`[feed] event.changed to ${link.url} failed (its poll will catch up):`, (e as Error).message);
|
|
}
|
|
}));
|
|
return { told, failed };
|
|
}
|
|
|
|
type LinkRow = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
|
|
|
|
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string };
|
|
|
|
/** Fetches one sibling's feed into read-only copies. */
|
|
export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
|
|
if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 };
|
|
if (!link.showEvents) {
|
|
const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count;
|
|
return { installId: link.installId, ok: true, imported: 0, deleted: gone };
|
|
}
|
|
const now = ctx.now();
|
|
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
|
|
try {
|
|
const url = await siblingUrl(ctx, link.url, FEED_PATHS.events);
|
|
if (since) url.searchParams.set('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, 2).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}`})`);
|
|
// Only events that really come from this sibling: one product can't speak for another.
|
|
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
|
|
for (const e of theirs) {
|
|
const data = { linkId: link.installId, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), data: e as never, syncedAt: now };
|
|
const existing = await ctx.db.importedEvent.findFirst({ where: { originProduct: e.origin.product, originId: e.id } });
|
|
if (existing) await ctx.db.importedEvent.update({ where: { id: existing.id }, data });
|
|
else await ctx.db.importedEvent.create({ data: { ...data, originProduct: e.origin.product, originId: e.id } });
|
|
}
|
|
let deleted = 0;
|
|
for (const d of feed.deleted) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: d.id } })).count;
|
|
// A full fetch is the whole list: anything not in it is gone.
|
|
if (!since) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: { notIn: theirs.map((e) => e.id) } } })).count;
|
|
await ctx.db.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 };
|
|
} catch (e) {
|
|
const error = String((e as Error)?.message || e).slice(0, 500);
|
|
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
|
|
return { installId: link.installId, ok: false, error };
|
|
}
|
|
}
|
|
|
|
/** Every linked sibling, one after another; one failing never stops the rest. */
|
|
export async function syncAll(ctx: Ctx) {
|
|
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
|
|
let failed = 0;
|
|
for (const link of links) if (!(await syncLink(ctx, link)).ok) failed++;
|
|
return { links: links.length, failed };
|
|
}
|
|
|
|
/** Every 15 minutes (ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback"). */
|
|
export function startFeedSync(ctx: Ctx): () => void {
|
|
if (!ctx.config.jobsEnabled) return () => {};
|
|
const run = () => syncAll(ctx).catch((e) => console.warn('[feed]', (e as Error).message));
|
|
const first = setTimeout(run, 20_000);
|
|
const timer = setInterval(run, 15 * 60 * 1000);
|
|
first.unref?.();
|
|
timer.unref?.();
|
|
return () => { clearTimeout(first); clearInterval(timer); };
|
|
}
|