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:
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* An event as `crosscode.event/1` (docs/EVENTS-2.4-PLAN.md §3): what the feed publishes and what
|
||||
* the event page's JSON-LD is built from (@crosscode/seo).
|
||||
*
|
||||
* `buildCrosscodeEvent` is pure (the event, what's left of each ticket and the site's details in,
|
||||
* the payload out) so it can be tested without a database; `loadForFeed` reads what it needs.
|
||||
*
|
||||
* Never in here: the event's contact person, kids check-in and volunteer tickets, staff prices,
|
||||
* the attendee form. Only what the public event page already shows.
|
||||
*/
|
||||
import type { CrosscodeEvent } from '@crosscode/contracts';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS utils */
|
||||
const sessionsUtil = require('../utils/sessions') as {
|
||||
activeSessions<S extends { cancelledAt?: Date | string | null; startsAt: Date | string }>(sessions: S[]): S[];
|
||||
registrationClosesAt(event: object, sessions: object[]): Date;
|
||||
isPickOption(event: object, option: object): boolean;
|
||||
};
|
||||
const { publicOptions } = require('../utils/volunteers') as { publicOptions<O>(event: object): O[] };
|
||||
const { getEffectiveUnitPrice } = require('../utils/pricing') as { getEffectiveUnitPrice(option: object, ref: Date | null, at: Date): number };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export type FeedContext = {
|
||||
/** This install's Hub id (origin.installId). */
|
||||
installId: string;
|
||||
/** The site's address, without a trailing slash. */
|
||||
baseUrl: string;
|
||||
timezone: string;
|
||||
/** Campuses switched on (otherwise every event is for the whole church). */
|
||||
campusesOn: boolean;
|
||||
now: Date;
|
||||
};
|
||||
|
||||
export type FeedOption = {
|
||||
id: string;
|
||||
price: number;
|
||||
isMainTicket: boolean;
|
||||
stockLimit: number;
|
||||
sessionMode?: string;
|
||||
earlyBirdTiers?: { deadline: Date | string; price: number; order?: number | null }[];
|
||||
variants?: { price: number | null }[];
|
||||
};
|
||||
|
||||
export type FeedEventRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
goLiveAt: Date | null;
|
||||
registrationDeadline: Date | null;
|
||||
picture: string | null;
|
||||
location: string | null;
|
||||
requiresRegistration: boolean;
|
||||
waitlistEnabled: boolean;
|
||||
scheduleType: string;
|
||||
attendanceMode: string;
|
||||
lateJoinEnabled: boolean;
|
||||
lateJoinUntilSessionId: string | null;
|
||||
kidsOptionId?: string | null;
|
||||
volunteerOptionId?: string | null;
|
||||
campus: { slug: string; name: string } | null;
|
||||
series: { id: string; name: string } | null;
|
||||
sessions: { id: string; label: string | null; startsAt: Date; endsAt: Date; location: string | null; cancelledAt: Date | null }[];
|
||||
eventOptions: FeedOption[];
|
||||
};
|
||||
|
||||
/** Places left per option (`null` = no limit). Missing options count as unlimited. */
|
||||
export type Availability = Map<string, number | null>;
|
||||
|
||||
export type BuiltEvent = {
|
||||
event: CrosscodeEvent;
|
||||
/** The event's own lowest and highest current prices, for its JSON-LD (`null` when free). */
|
||||
priceRangeCents: { lowCents: number; highCents: number } | null;
|
||||
};
|
||||
|
||||
const cut = (s: string | null | undefined, max: number): string | null => {
|
||||
const t = String(s ?? '').trim();
|
||||
return t ? (t.length > max ? `${t.slice(0, max - 1)}…` : t) : null;
|
||||
};
|
||||
|
||||
/** "/uploads/…" (as stored) → an absolute address on the site, served under /api (2.2.0). */
|
||||
export function absolute(baseUrl: string, raw: string | null | undefined): string | null {
|
||||
const v = String(raw ?? '').trim();
|
||||
if (!v) return null;
|
||||
if (/^https?:\/\//i.test(v)) return v;
|
||||
const path = v.startsWith('/') ? v : `/${v}`;
|
||||
return `${baseUrl}${/^\/uploads\//.test(path) ? `/api${path}` : path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plain text as markdown that reads the same: markdown characters escaped, line breaks kept
|
||||
* (Events descriptions are plain text shown with their line breaks).
|
||||
*/
|
||||
export function plainToMarkdown(text: string | null | undefined): string | null {
|
||||
const t = String(text ?? '').replace(/\r\n?/g, '\n').trim();
|
||||
if (!t) return null;
|
||||
const lines = t.split('\n').map((line) => line
|
||||
.replace(/[\\`*_[\]<>|~]/g, (c) => `\\${c}`)
|
||||
// A line that would start a heading, a list, a quote or a numbered list.
|
||||
.replace(/^(\s*)([#>+-])/, '$1\\$2')
|
||||
.replace(/^(\s*\d+)([.)])(\s)/, '$1\\$2$3'));
|
||||
// A hard break between lines of the same paragraph (two spaces), blank lines stay paragraphs.
|
||||
return lines.map((l, i) => (i < lines.length - 1 && l.trim() && lines[i + 1]!.trim() ? `${l} ` : l)).join('\n').slice(0, 20000);
|
||||
}
|
||||
|
||||
/** Today's price of each ticket (early-bird when one is open, else each variant's or the base price), in rand. */
|
||||
function currentPrices(options: FeedOption[], now: Date): number[] {
|
||||
const prices: number[] = [];
|
||||
for (const o of options) {
|
||||
if (o.variants && o.variants.length > 0) {
|
||||
for (const v of o.variants) prices.push(v.price ?? o.price);
|
||||
continue;
|
||||
}
|
||||
prices.push(getEffectiveUnitPrice(o, null, now));
|
||||
}
|
||||
return prices.filter((p) => Number.isFinite(p) && p >= 0);
|
||||
}
|
||||
|
||||
function registration(row: FeedEventRow, options: FeedOption[], available: Availability, ctx: FeedContext, pageUrl: string): CrosscodeEvent['registration'] {
|
||||
const closes = sessionsUtil.registrationClosesAt(row, row.sessions);
|
||||
const closesAt = closes && Number.isFinite(closes.getTime()) ? closes.toISOString() : null;
|
||||
if (!row.requiresRegistration) {
|
||||
// Contact-only events: no tickets; the description says how to take part.
|
||||
return { mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null };
|
||||
}
|
||||
const main = options.filter((o) => o.isMainTicket);
|
||||
const priced = main.length > 0 ? main : options;
|
||||
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
|
||||
const low = prices.length > 0 ? Math.min(...prices) : 0;
|
||||
|
||||
let status: CrosscodeEvent['registration']['status'] = 'open';
|
||||
if (row.goLiveAt && ctx.now < row.goLiveAt) status = 'not_open';
|
||||
else if (closesAt && ctx.now >= new Date(closesAt)) status = 'closed';
|
||||
else if (main.length > 0 && main.every((o) => o.stockLimit > 0 && (available.get(o.id) ?? 1) <= 0)) status = row.waitlistEnabled ? 'waitlist' : 'full';
|
||||
|
||||
return {
|
||||
mode: 'origin',
|
||||
url: pageUrl,
|
||||
status,
|
||||
opensAt: row.goLiveAt && ctx.now < row.goLiveAt ? row.goLiveAt.toISOString() : null,
|
||||
closesAt,
|
||||
priceFrom: low > 0 ? { amountCents: low, currency: 'ZAR' } : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCrosscodeEvent(row: FeedEventRow, available: Availability, ctx: FeedContext): BuiltEvent {
|
||||
const pageUrl = `${ctx.baseUrl}/events/${row.id}`;
|
||||
const options = publicOptions<FeedOption>(row);
|
||||
const live = sessionsUtil.activeSessions(row.sessions);
|
||||
const multi = row.scheduleType === 'sessions' && row.sessions.length > 0;
|
||||
// startsAt / endsAt are the first start and last end of the sessions that still run.
|
||||
const startsAt = multi && live.length > 0 ? live[0]!.startsAt : row.startDate;
|
||||
const endsAt = multi && live.length > 0 ? live.reduce((m, s) => (s.endsAt > m ? s.endsAt : m), live[0]!.endsAt) : row.endDate;
|
||||
const place = cut(row.location, 200);
|
||||
const online = place && /^https?:\/\//i.test(place) ? place : null;
|
||||
|
||||
const reg = registration(row, options, available, ctx, pageUrl);
|
||||
const priced = options.filter((o) => o.isMainTicket).length > 0 ? options.filter((o) => o.isMainTicket) : options;
|
||||
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
|
||||
const priceRangeCents = row.requiresRegistration && prices.some((p) => p > 0) ? { lowCents: Math.min(...prices), highCents: Math.max(...prices) } : null;
|
||||
|
||||
const event: CrosscodeEvent = {
|
||||
schema: 'crosscode.event/1',
|
||||
id: row.id,
|
||||
origin: { product: 'events', installId: ctx.installId, url: pageUrl },
|
||||
status: 'published',
|
||||
// The feed puts the time it last changed here (feed/entries.ts).
|
||||
updatedAt: ctx.now.toISOString(),
|
||||
title: cut(row.title, 200) ?? 'Event',
|
||||
summary: null,
|
||||
description: plainToMarkdown(row.description),
|
||||
imageUrl: absolute(ctx.baseUrl, row.picture),
|
||||
timezone: ctx.timezone,
|
||||
startsAt: new Date(startsAt).toISOString(),
|
||||
endsAt: new Date(endsAt).toISOString(),
|
||||
allDay: false,
|
||||
sessions: multi
|
||||
? [...row.sessions]
|
||||
.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime())
|
||||
.slice(0, 500)
|
||||
.map((s) => ({
|
||||
id: s.id,
|
||||
label: cut(s.label, 200),
|
||||
startsAt: new Date(s.startsAt).toISOString(),
|
||||
endsAt: new Date(s.endsAt).toISOString(),
|
||||
location: cut(s.location, 300),
|
||||
cancelled: !!s.cancelledAt,
|
||||
}))
|
||||
: [],
|
||||
location: place ? (online ? { name: null, address: null, onlineUrl: online } : { name: place, address: null, onlineUrl: null }) : null,
|
||||
campus: ctx.campusesOn && row.campus ? { slug: row.campus.slug, name: cut(row.campus.name, 200) ?? row.campus.slug } : null,
|
||||
series: row.series ? { id: row.series.id, name: cut(row.series.name, 200) ?? 'Series' } : null,
|
||||
tags: [],
|
||||
registration: reg,
|
||||
};
|
||||
return { event, priceRangeCents };
|
||||
}
|
||||
|
||||
/** What `loadForFeed` selects (and the e2e/unit fixtures build). */
|
||||
export const FEED_EVENT_SELECT = {
|
||||
id: true, title: true, description: true, startDate: true, endDate: true, goLiveAt: true, registrationDeadline: true,
|
||||
picture: true, location: true, requiresRegistration: true, waitlistEnabled: true, scheduleType: true, attendanceMode: true,
|
||||
lateJoinEnabled: true, lateJoinUntilSessionId: true, kidsOptionId: true, volunteerOptionId: true, updatedAt: true,
|
||||
campus: { select: { slug: true, name: true } },
|
||||
series: { select: { id: true, name: true } },
|
||||
sessions: { select: { id: true, label: true, startsAt: true, endsAt: true, location: true, cancelledAt: true } },
|
||||
eventOptions: { select: { id: true, price: true, isMainTicket: true, stockLimit: true, sessionMode: true, earlyBirdTiers: true, variants: { select: { price: true } } } },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Places left on each limited main ticket. "Pick sessions" tickets have places per session; they
|
||||
* count as sold out only when every session that still runs is.
|
||||
*/
|
||||
export async function availabilityFor(row: FeedEventRow): Promise<Availability> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { takenCount } = require('../utils/stock') as { takenCount(where: object): Promise<number> };
|
||||
const out: Availability = new Map();
|
||||
for (const o of publicOptions<FeedOption>(row)) {
|
||||
if (!o.isMainTicket || !(o.stockLimit > 0)) continue;
|
||||
if (sessionsUtil.isPickOption(row, o)) {
|
||||
let left = 0;
|
||||
for (const s of sessionsUtil.activeSessions(row.sessions)) left += Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id, sessionId: s.id }));
|
||||
out.set(o.id, left);
|
||||
} else {
|
||||
out.set(o.id, Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id })));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One event as `crosscode.event/1`, for its own page's JSON-LD (whether or not it's public: a
|
||||
* hidden event's page is reachable by its link). `null` when there's no such event.
|
||||
*/
|
||||
export async function crosscodeEventFor(eventId: string, now = new Date()): Promise<BuiltEvent | null> {
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { feedContext } = require('./context') as typeof import('./context');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
const row = (await prisma.event.findUnique({ where: { id: eventId }, select: FEED_EVENT_SELECT })) as FeedEventRow | null;
|
||||
if (!row) return null;
|
||||
return buildCrosscodeEvent(row, await availabilityFor(row), await feedContext(now));
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* What every part of the feed and of Linked products needs to know about this site: its Hub id,
|
||||
* its address, its timezone and whether campuses and publishing are on.
|
||||
*/
|
||||
import type { FeedContext } from './build';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { getSetting } = require('../utils/settingsCache') as { getSetting(key: string, fallback?: string): Promise<string> };
|
||||
const { campusesEnabled } = require('../utils/campuses') as { campusesEnabled(): Promise<boolean> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
/** Setting: "Publish my events" (on unless set to "false"). */
|
||||
export const PUBLISH_KEY = 'feed_publish';
|
||||
|
||||
export async function publishOn(): Promise<boolean> {
|
||||
return String(await getSetting(PUBLISH_KEY, 'true')).toLowerCase() !== 'false';
|
||||
}
|
||||
|
||||
/** The site's address, as it tells the Hub (hub/report.js installInfo). */
|
||||
export async function siteUrl(): Promise<string> {
|
||||
const url = await getSetting('app_base_url', process.env.FRONTEND_URL || '');
|
||||
return String(url || process.env.FRONTEND_URL || '').split(',')[0]!.trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export async function hubInstallId(): Promise<string | null> {
|
||||
const row = await prisma.appSetting.findUnique({ where: { key: 'hub_install_id' } });
|
||||
return row?.value || null;
|
||||
}
|
||||
|
||||
/** Placeholder id for a site not connected to the Hub (its JSON-LD still works; it has no feed). */
|
||||
export const NO_INSTALL_ID = '00000000-0000-4000-8000-000000000000';
|
||||
|
||||
export async function feedContext(now = new Date()): Promise<FeedContext & { connected: boolean }> {
|
||||
const [installId, baseUrl, campusesOn] = await Promise.all([hubInstallId(), siteUrl(), campusesEnabled().catch(() => false)]);
|
||||
return {
|
||||
installId: installId || NO_INSTALL_ID,
|
||||
connected: !!installId,
|
||||
baseUrl,
|
||||
timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||
campusesOn,
|
||||
now,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* The published feed (docs/EVENTS-2.4-PLAN.md §3): `FeedEntry` holds what was last published for
|
||||
* each event, so `?updatedSince=` is right even when an event changes without its row changing
|
||||
* (it goes live, registration closes, it sells out) and when it stops being public (Events never
|
||||
* deletes an event, it deactivates it).
|
||||
*
|
||||
* `refreshFeed` builds every event that is public and ended at most 30 days ago, and moves an
|
||||
* entry's `changedAt` only when its payload changed. Run by the `feed` job (every 5 minutes),
|
||||
* shortly after any change to events, tickets or registrations (`changedSoon`), and before the
|
||||
* feed is served when the last run is more than a minute old.
|
||||
*/
|
||||
import crypto from 'crypto';
|
||||
import { canonicalJson, eventSchema, EVENT_FEED_SCHEMA, type CrosscodeEvent, type EventFeed } from '@crosscode/contracts';
|
||||
import { availabilityFor, buildCrosscodeEvent, FEED_EVENT_SELECT, type FeedEventRow } from './build';
|
||||
import { feedContext } from './context';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { publicEventWhere } = require('../utils/series') as { publicEventWhere(now: Date): object };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
/** Ended events stay in a full fetch this long. */
|
||||
export const ENDED_KEEP_DAYS = 30;
|
||||
/** Entries of events that stopped being public are kept (as `deleted`) this long. */
|
||||
export const REMOVED_KEEP_DAYS = 90;
|
||||
|
||||
/** The hash of what a sibling sees (without `updatedAt`, which is the entry's `changedAt`). */
|
||||
export function payloadHash(event: CrosscodeEvent): string {
|
||||
const { updatedAt: _ignored, ...rest } = event;
|
||||
return crypto.createHash('sha256').update(canonicalJson(rest)).digest('hex');
|
||||
}
|
||||
|
||||
export type RefreshResult = { changed: string[]; removed: string[]; skipped: { id: string; reason: string }[] };
|
||||
|
||||
let lastRefreshAt = 0;
|
||||
let running: Promise<RefreshResult> | null = null;
|
||||
|
||||
export async function refreshFeed(now = new Date(), db = prisma): Promise<RefreshResult> {
|
||||
const ctx = await feedContext(now);
|
||||
const result: RefreshResult = { changed: [], removed: [], skipped: [] };
|
||||
// Without a Hub install id there's no origin to publish under.
|
||||
if (!ctx.connected) return result;
|
||||
|
||||
const rows = (await db.event.findMany({
|
||||
where: { AND: [publicEventWhere(now), { endDate: { gte: new Date(now.getTime() - ENDED_KEEP_DAYS * DAY) } }] },
|
||||
select: FEED_EVENT_SELECT,
|
||||
})) as FeedEventRow[];
|
||||
const entries: { eventId: string; hash: string; removedAt: Date | null }[] = await db.feedEntry.findMany({ select: { eventId: true, hash: true, removedAt: true } });
|
||||
const byId = new Map(entries.map((e) => [e.eventId, e]));
|
||||
const current = new Set<string>();
|
||||
|
||||
for (const row of rows) {
|
||||
const built = buildCrosscodeEvent(row, await availabilityFor(row), ctx);
|
||||
const check = eventSchema.safeParse(built.event);
|
||||
if (!check.success) {
|
||||
// Never publish something the contract refuses; the next change may fix it.
|
||||
result.skipped.push({ id: row.id, reason: check.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ') });
|
||||
continue;
|
||||
}
|
||||
current.add(row.id);
|
||||
const hash = payloadHash(built.event);
|
||||
const prev = byId.get(row.id);
|
||||
if (prev && prev.hash === hash && !prev.removedAt) continue;
|
||||
await db.feedEntry.upsert({
|
||||
where: { eventId: row.id },
|
||||
create: { eventId: row.id, hash, payload: built.event, changedAt: now, removedAt: null },
|
||||
update: { hash, payload: built.event, changedAt: now, removedAt: null },
|
||||
});
|
||||
result.changed.push(row.id);
|
||||
}
|
||||
|
||||
// Entries no longer built: an event that stopped being public goes into `deleted`; one that
|
||||
// only ended long enough ago drops out quietly (siblings keep their copy).
|
||||
const gone = entries.filter((e) => !e.removedAt && !current.has(e.eventId)).map((e) => e.eventId);
|
||||
if (gone.length > 0) {
|
||||
const stillPublic = new Set<string>(
|
||||
(await db.event.findMany({ where: { AND: [{ id: { in: gone } }, publicEventWhere(now)] }, select: { id: true } })).map((e: { id: string }) => e.id),
|
||||
);
|
||||
const skipped = new Set(result.skipped.map((s) => s.id));
|
||||
for (const id of gone) {
|
||||
if (skipped.has(id)) continue;
|
||||
if (stillPublic.has(id)) await db.feedEntry.delete({ where: { eventId: id } });
|
||||
else {
|
||||
await db.feedEntry.update({ where: { eventId: id }, data: { removedAt: now } });
|
||||
result.removed.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
await db.feedEntry.deleteMany({ where: { removedAt: { lt: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY) } } });
|
||||
// Wall-clock time of the run (not `now`, which tests and catch-up runs may set).
|
||||
lastRefreshAt = Date.now();
|
||||
return result;
|
||||
}
|
||||
|
||||
/** One refresh at a time in this process; the job, `changedSoon` and the feed share it. */
|
||||
export function refreshOnce(now = new Date()): Promise<RefreshResult> {
|
||||
if (!running) running = refreshFeed(now).finally(() => { running = null; });
|
||||
return running;
|
||||
}
|
||||
|
||||
export function lastRefresh(): number {
|
||||
return lastRefreshAt;
|
||||
}
|
||||
|
||||
/** The feed answer (`crosscode.event-feed/1`). */
|
||||
export async function feedResponse(updatedSince: Date | null, now = new Date(), db = prisma): Promise<EventFeed> {
|
||||
const live = await db.feedEntry.findMany({
|
||||
where: { removedAt: null, ...(updatedSince ? { changedAt: { gt: updatedSince } } : {}) },
|
||||
orderBy: { changedAt: 'asc' },
|
||||
});
|
||||
const deleted = updatedSince
|
||||
? await db.feedEntry.findMany({ where: { removedAt: { gt: updatedSince } }, orderBy: { removedAt: 'asc' }, select: { eventId: true, removedAt: true } })
|
||||
: [];
|
||||
return {
|
||||
schema: EVENT_FEED_SCHEMA,
|
||||
generatedAt: now.toISOString(),
|
||||
events: live.map((e: { payload: CrosscodeEvent; changedAt: Date }) => ({ ...e.payload, updatedAt: e.changedAt.toISOString() })),
|
||||
deleted: deleted.map((d: { eventId: string; removedAt: Date }) => ({ id: d.eventId, deletedAt: d.removedAt.toISOString() })),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── After a change ────────────────────────────────────────────────────────────
|
||||
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
|
||||
/**
|
||||
* Something that can change the feed was written (config/db.js): refresh a few seconds later
|
||||
* (one refresh for a burst of writes) and tell connected siblings. Never throws.
|
||||
*/
|
||||
export function changedSoon(delayMs = 5000): void {
|
||||
if (timer) return;
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
(require('./notify') as typeof import('./notify')).refreshAndNotify().catch((e: unknown) => console.warn('[feed] refresh failed:', (e as Error)?.message || e));
|
||||
}, delayMs);
|
||||
timer.unref?.();
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Telling connected siblings the feed changed (`event.changed`, signed with each link's secret),
|
||||
* so they fetch straight away instead of at their next 15-minute poll. One try, and one more a
|
||||
* minute later; after that the poll catches up, so a sibling that's down misses nothing.
|
||||
*/
|
||||
import { EVENT_FEED_SCHEMA, FEED_PATHS, type EventChanged } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { hubInstallId, publishOn } from './context';
|
||||
import { refreshOnce, type RefreshResult } from './entries';
|
||||
import { callSibling, siblingUrl } from '../links/http';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const RETRY_MS = 60 * 1000;
|
||||
|
||||
type LinkRow = { installId: string; url: string; secret: string };
|
||||
|
||||
export async function sendChanged(link: LinkRow, eventIds: string[], senderId: string, now = new Date()): Promise<void> {
|
||||
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: now.toISOString(), eventIds: eventIds.slice(0, 100) };
|
||||
const raw = JSON.stringify(body);
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: decrypt(link.secret), rawBody: raw });
|
||||
await callSibling(await siblingUrl(link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
|
||||
}
|
||||
|
||||
/** Tells every connected sibling; failures are retried once, then left to the sibling's poll. */
|
||||
export async function notifyLinks(eventIds: string[]): Promise<{ told: number; failed: number }> {
|
||||
if (eventIds.length === 0 || !(await publishOn())) return { told: 0, failed: 0 };
|
||||
const senderId = await hubInstallId();
|
||||
if (!senderId) return { told: 0, failed: 0 };
|
||||
const links: LinkRow[] = await prisma.productLink.findMany({ select: { installId: true, url: true, secret: true } });
|
||||
let told = 0;
|
||||
let failed = 0;
|
||||
await Promise.all(links.map(async (link) => {
|
||||
try {
|
||||
await sendChanged(link, eventIds, senderId);
|
||||
told++;
|
||||
} catch (e) {
|
||||
failed++;
|
||||
console.warn(`[feed] event.changed to ${link.url} failed, trying once more in a minute:`, (e as Error)?.message || e);
|
||||
setTimeout(() => {
|
||||
sendChanged(link, eventIds, senderId).catch((err) => console.warn(`[feed] event.changed to ${link.url} failed again (its poll will catch up):`, (err as Error)?.message || err));
|
||||
}, RETRY_MS).unref?.();
|
||||
}
|
||||
}));
|
||||
return { told, failed };
|
||||
}
|
||||
|
||||
/** The `feed` job: refresh what's published and tell siblings what changed. */
|
||||
export async function refreshAndNotify(now = new Date()): Promise<RefreshResult & { told: number }> {
|
||||
const result = await refreshOnce(now);
|
||||
const { told } = await notifyLinks([...result.changed, ...result.removed]);
|
||||
return { ...result, told };
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user