trails/apps/journal/app/lib/federation-delivery.server.ts
Ullrich Schäfer bc233e03e5 feat(journal): federation outbox + push delivery to remote followers
social-federation tasks 5.1–5.6. Completes the inbound-federation
story: a Mastodon follower now receives a trails user's new public
activities in their home timeline.

Outbox (5.1/5.2):
- /users/:username/outbox — paginated OrderedCollection of public
  activities as Create(Note), newest first; unlisted/private never
  federate. Private-user 404 enforced at the route layer because
  Fedify builds collection-level responses from counter/cursors
  without consulting the page dispatcher.
- Note shape: HTML content (escaped name/description/stats + link to
  the activity page) with structured PropertyValue attachments
  (distance-m, elevation-gain-m, duration-s) — Mastodon renders the
  text, trails consumers read the structured fields. Resolves the
  design open question toward Create(Note).
- Authorized Fetch: signed and unsigned outbox fetches deliberately
  see the same (public-only) content until locked accounts exist.

Push delivery (5.3–5.6):
- createActivity / updateActivityVisibility(→public) enqueue one
  deliver-activity job per accepted remote follower; flips away from
  public and hard deletes enqueue Delete(Tombstone) retractions
  (enqueued before the row disappears).
- deliver-activity job: re-reads the row at delivery time (skips if
  gone or no longer public), resolves the recipient inbox via the
  remote_actors cache with actor-document fetch fallback (priming the
  cache), HTTP-signs via the owner's key, and POSTs. retryLimit 8 +
  exponential backoff at enqueue time; outbound paced at 1 req/s per
  remote host.
- Actor objects now advertise the outbox IRI.
- @js-temporal/polyfill added (same range Fedify uses) for published
  timestamps; Fedify's types want the global esnext.temporal namespace,
  bridged with a documented cast.

Tests: 9 unit tests for the AS mapping (escaping, stats, attachments,
published fallback, stable ids, tombstones), 4 outbox integration
tests (collection count, page shape/visibility filtering, private-404,
delivery audience query).

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

115 lines
3.9 KiB
TypeScript

// Push delivery of local public activities to accepted remote
// followers (spec: social-federation, "Push delivery on local activity
// create"). Enqueue side lives here; the actual signed POST happens in
// jobs/deliver-activity.ts.
import { and, eq, isNotNull } from "drizzle-orm";
import { follows, remoteActors, users } from "@trails-cool/db/schema/journal";
import { getDb } from "./db.ts";
import { federationEnabled } from "./federation.server.ts";
import { enqueueOptional } from "./boss.server.ts";
import { activityObjectIri } from "./federation-objects.server.ts";
export type DeliveryAction = "create" | "delete";
export interface DeliveryPayload {
action: DeliveryAction;
/** Present for `create` — the job re-reads the row at delivery time. */
activityId?: string;
/** Object IRI; for `delete` this is all that's left of the activity. */
objectIri: string;
ownerUsername: string;
recipientActorIri: string;
}
/** Accepted remote followers of a local user (the delivery audience). */
export async function listAcceptedRemoteFollowers(ownerId: string): Promise<string[]> {
const db = getDb();
const rows = await db
.select({ actorIri: follows.followerActorIri })
.from(follows)
.where(
and(
eq(follows.followedUserId, ownerId),
isNotNull(follows.followerActorIri),
isNotNull(follows.acceptedAt),
),
);
return rows.map((r) => r.actorIri).filter((iri): iri is string => iri !== null);
}
/**
* Fan out one delivery job per accepted remote follower (spec 5.3: a
* job per follower, each with its own retry/backoff lifecycle). No-op
* when federation is off or the user has no remote followers — the
* common case stays a single SELECT.
*/
export async function enqueueActivityDeliveries(
ownerId: string,
activityId: string,
action: DeliveryAction,
): Promise<void> {
if (!federationEnabled()) return;
const recipients = await listAcceptedRemoteFollowers(ownerId);
if (recipients.length === 0) return;
const db = getDb();
const [owner] = await db
.select({ username: users.username, profileVisibility: users.profileVisibility })
.from(users)
.where(eq(users.id, ownerId))
.limit(1);
// Private profiles don't federate — suppress push delivery entirely
// (spec 9.3: flipping to private stops federation).
if (!owner || owner.profileVisibility !== "public") return;
for (const recipientActorIri of recipients) {
const payload: DeliveryPayload = {
action,
activityId: action === "create" ? activityId : undefined,
objectIri: activityObjectIri(activityId),
ownerUsername: owner.username,
recipientActorIri,
};
await enqueueOptional(
"deliver-activity",
payload,
{ source: "enqueueActivityDeliveries", action },
// Spec 5.4: exponential backoff on failure, bounded retry budget.
// 8 retries with backoff spans roughly a day before permanent fail.
{ retryLimit: 8, retryBackoff: true },
);
}
}
export interface CachedRemoteActor {
actorIri: string;
inboxUrl: string | null;
}
/** Read the remote actor cache; null when we've never seen the actor. */
export async function getCachedRemoteActor(actorIri: string): Promise<CachedRemoteActor | null> {
const db = getDb();
const [row] = await db
.select({ actorIri: remoteActors.actorIri, inboxUrl: remoteActors.inboxUrl })
.from(remoteActors)
.where(eq(remoteActors.actorIri, actorIri))
.limit(1);
return row ?? null;
}
/** Upsert the fields delivery learns about a remote actor. */
export async function upsertRemoteActor(fields: {
actorIri: string;
inboxUrl?: string | null;
displayName?: string | null;
username?: string | null;
domain?: string | null;
}): Promise<void> {
const db = getDb();
const { actorIri, ...rest } = fields;
await db
.insert(remoteActors)
.values({ actorIri, ...rest })
.onConflictDoUpdate({ target: remoteActors.actorIri, set: rest });
}