trails/apps/journal/app/jobs/notifications-fanout.ts
Ullrich Schäfer b17685d58c feat(journal): federation inbox — Mastodon follows land here
social-federation tasks 3.1–3.4, 4.1–4.8. With this, a Mastodon user
can follow a public trails user: WebFinger → actor fetch → signed
Follow → recorded + Accept(Follow) pushed back.

Identity surface (section 3):
- Actor objects now carry the user's public key (publicKey +
  assertionMethods via Fedify key pairs dispatcher; keys generated
  lazily as a fallback to the backfill) and an inbox IRI; url uses
  localActorIri (3.1).
- Software discovery shipped as standard NodeInfo
  (/.well-known/nodeinfo + /nodeinfo/2.1, software.name trails-cool)
  instead of the originally-sketched custom AS actor field — Fedify's
  typed vocab can't emit arbitrary actor props and NodeInfo is what
  the fediverse reads. Artifacts updated accordingly (3.4).

Inbox (section 4):
- /users/:username/inbox resource route; HTTP Signatures verified by
  Fedify before any listener runs (4.1). Rate-limited 60 req/5 min per
  source instance (host from Signature keyId) BEFORE verification so
  hostile instances can't burn CPU on key fetches (4.8).
- Listeners: Follow → auto-accept for public profiles + Accept pushed
  back (4.2); Undo(Follow) → row removed (4.3); Accept(Follow) →
  Pending settled + first outbox poll enqueued (4.4); Reject(Follow) →
  Pending dropped (4.5; UI notice deferred to 6.6). Unhandled types
  are acknowledged + dropped by Fedify (4.6).
- Replay protection via Fedify's KvStore, now Postgres-backed
  (journal.federation_kv + daily sweep job) so dedupe survives
  restarts (4.7).

Schema (discovered requirement):
- follows.follower_id relaxed to nullable + follows.follower_actor_iri
  for inbound remote followers — the proposal's 'follows is already
  federation-ready' only held for outbound. Check constraint enforces
  exactly one follower identity; partial unique index dedupes remote
  follows. Notification fan-out + approve flow now filter local
  followers explicitly. Design/proposal updated.

Tests: 7 inbox integration tests (accept/refuse/idempotence/undo/
settle/reject/check-constraint), 6 KvStore integration tests, 2 unit
tests for source-host extraction. All against real Postgres, gated on
FEDERATION_INTEGRATION=1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 14:33:43 +02:00

101 lines
3.3 KiB
TypeScript

import type { JobDefinition } from "@trails-cool/jobs";
import { and, eq, isNotNull } from "drizzle-orm";
import { getDb } from "../lib/db.ts";
import { activities, follows, users } from "@trails-cool/db/schema/journal";
import { createNotification } from "../lib/notifications.server.ts";
import { logger } from "../lib/logger.server.ts";
interface FanoutData {
activityId: string;
}
/**
* Fan out an `activity_published` notification to every accepted
* follower of the activity's owner. Idempotent at the DB level via the
* `(recipient_user_id, type, subject_id)` unique partial index — a
* retry after partial failure won't double-insert.
*/
export const notificationsFanoutJob: JobDefinition = {
name: "notifications-fanout",
retryLimit: 3,
expireInSeconds: 300,
async handler(job) {
// pg-boss v12: `job` may be an array (batch) per its docs; we
// process whichever shape we get.
const batch = Array.isArray(job) ? job : [job];
for (const item of batch) {
const data = item.data as FanoutData;
await fanout(data.activityId);
}
},
};
export async function fanout(activityId: string): Promise<void> {
const db = getDb();
// Load the activity + owner info needed for the payload snapshot.
const [row] = await db
.select({
id: activities.id,
name: activities.name,
visibility: activities.visibility,
ownerId: activities.ownerId,
ownerUsername: users.username,
ownerDisplayName: users.displayName,
})
.from(activities)
.innerJoin(users, eq(activities.ownerId, users.id))
.where(eq(activities.id, activityId));
if (!row) {
logger.warn({ activityId }, "fanout: activity not found, skipping");
return;
}
// Defense in depth — the create-side guard already filters this, but
// recheck here so the job doesn't mistakenly fan out a row that was
// later flipped to private/unlisted before the job ran.
if (row.visibility !== "public") {
logger.info({ activityId, visibility: row.visibility }, "fanout: skipping non-public activity");
return;
}
// Find every accepted *local* follower of the owner. Remote
// followers (follower_id NULL, follower_actor_iri set) get the
// activity via federation push delivery, not via notifications.
const recipients = await db
.select({ followerId: follows.followerId })
.from(follows)
.where(
and(
eq(follows.followedUserId, row.ownerId),
isNotNull(follows.acceptedAt),
isNotNull(follows.followerId),
),
);
let inserted = 0;
for (const r of recipients) {
// Don't notify the owner about their own activity if they happen
// to follow themselves (shouldn't happen — followUser refuses
// self-follow — but defense in depth).
if (r.followerId === row.ownerId || r.followerId === null) continue;
const created = await createNotification({
type: "activity_published",
recipientUserId: r.followerId,
actorUserId: row.ownerId,
subjectId: row.id,
payload: {
activityId: row.id,
activityName: row.name,
ownerUsername: row.ownerUsername,
ownerDisplayName: row.ownerDisplayName,
},
});
if (created) inserted += 1;
}
logger.info(
{ activityId, recipients: recipients.length, inserted },
"notifications-fanout completed",
);
}