trails/apps/journal/app/lib/boss.server.ts
Ullrich Schäfer e61179ab27 Implement notifications + supporting fixes
Adds the notifications system end-to-end (4 types, payload-versioned
JSONB, SSE-based live unread badge, /notifications page, mark-read API,
fan-out job for activity_published, daily 90-day retention purge).
Bell icon in the navbar with unread badge.

Side-findings from exercising the change:
- Add 6-digit magic code to registration (mirrors login UX, mobile
  paste-friendly), with `[Register Magic Link]` console line in dev so
  the code is reachable without a real email transport.
- Manual passkey/magic-link toggle on the register form (login already
  had it).
- Restrict ALPN to http/1.1 in HTTPS dev so React Router's
  singleFetchAction CSRF check (Origin vs. Host) passes — Node doesn't
  synthesize Host from h2's :authority. Plain HTTP dev unaffected.
- Followers/Following routes now use the locked-account rule from the
  profile route (owner + accepted followers see the list; others 404).
  Profile page renders the count chips as plain spans for viewers who
  can't see the lists, so private profiles don't surface dead links.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 01:28:55 +02:00

51 lines
1.7 KiB
TypeScript

// Module-level pg-boss singleton. server.ts initializes the boss + starts
// the worker; feature code (e.g., activities.server.ts) calls `getBoss()`
// to enqueue jobs against the same instance. The singleton's lifecycle
// is bound to the Node process — startWorker calls boss.start(); the
// SIGTERM handler stops it.
// Structurally typed (we only need `send`) so we don't have to pull
// pg-boss into the journal app's dep graph just for the typedef.
interface BossLike {
send(queueName: string, data: unknown): Promise<string | null>;
}
let _boss: BossLike | null = null;
/** Set by server.ts once the boss is created + started. */
export function setBoss(boss: BossLike): void {
_boss = boss;
}
/**
* Get the started pg-boss instance. Throws if called before
* server.ts has initialized it (i.e., outside a running Journal
* server context).
*/
export function getBoss(): BossLike {
if (!_boss) {
throw new Error("pg-boss not initialized — getBoss called before server bootstrap");
}
return _boss;
}
/**
* Best-effort enqueue: log + swallow errors so a downstream queue
* outage doesn't fail the user-visible request that triggered the
* fan-out. Use this for "fire and forget" notifications work.
*/
export async function enqueueOptional(
queue: string,
data: unknown,
ctx: Record<string, unknown> = {},
): Promise<void> {
try {
const boss = getBoss();
await boss.send(queue, data);
} catch (err) {
// Lazy import to avoid cycles in test environments where logger.server
// pulls in env-dependent setup.
const { logger } = await import("./logger.server.ts");
logger.warn({ err, queue, ...ctx }, "boss.send failed; continuing");
}
}