trails/apps/journal/app/routes/activities.$id.server.ts
Ullrich Schäfer b96bef91a9 feat(journal): outbox-poll ingestion of remote trails activities (§7)
Tasks 7.1–7.3, 7.5 (+7.4 pacing; Retry-After-duration backoff noted as
remaining). Resolves the activities.owner_id open question.

Schema (design decision from the open question):
- activities.owner_id nullable + check constraint enforcing exactly
  one of (owner_id, remote_actor_iri) — the follows pattern again.
- remote_published_at carries the origin's publish time for the §8
  feed sort; index on remote_actor_iri for the feed join.
- Compiler-audited fallout: notification fan-out, the Note object
  dispatcher, and the activity detail loader explicitly skip/404
  remote rows (their canonical page is the origin; feed links there).
  Every other surface joins users on owner_id and excludes remote rows
  structurally.

Ingestion:
- federation-ingest.server.ts: parseOutboxItem targets exactly our own
  outgoing Create(Note) shape (PropertyValue stats, first-paragraph
  name, audience from to/cc); unknown items skipped, never fatal.
- ingestRemoteActivities: replay-safe via unique remote_origin_iri,
  conflict-streak early exit (outboxes are newest-first).
- pollRemoteActor: signed fetch (Authorized Fetch via a local
  follower's key), outbox resolution via remote_actors cache with
  actor-doc fallback (which refreshes the cache), 1 req/5 s per-host
  pacing, last_polled_at stamping. Network + pacing injectable.

Jobs: poll-remote-actor (per-actor; the §4 Accept listener already
enqueues it as the first poll) + poll-remote-outboxes (5-min cron
sweep over accepted remote follows not polled within the hour).

Tests: parse-shape units; integration suite for ingestion provenance,
audience→visibility mirroring, replay safety, the DB author invariant,
poll flow (actor-doc → collection → page), signer requirement, and
due-polling selection.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:27:10 +02:00

99 lines
3.7 KiB
TypeScript

// Server-only loader/action for /activities/:id. See `home.server.ts`.
import { data, redirect } from "react-router";
import { canView } from "~/lib/auth.server";
import { getSessionUser, requireSessionUser } from "~/lib/auth/session.server";
import {
getActivity,
deleteActivity,
linkActivityToRoute,
createRouteFromActivity,
updateActivityVisibility,
} from "~/lib/activities.server";
import { deleteImportByActivity } from "~/lib/sync/imports.server";
import { listRoutes } from "~/lib/routes.server";
import type { Visibility } from "@trails-cool/db/schema/journal";
const VISIBILITY_VALUES = new Set<Visibility>(["private", "unlisted", "public"]);
export async function loadActivityDetail(request: Request, id: string | undefined) {
const fetched = await getActivity(id ?? "");
if (!fetched) throw data({ error: "Activity not found" }, { status: 404 });
// Remote-ingested activities have no local detail page — their
// canonical page lives on the origin instance; the feed links there.
if (fetched.ownerId === null) throw data({ error: "Activity not found" }, { status: 404 });
const activity = { ...fetched, ownerId: fetched.ownerId };
const user = await getSessionUser(request);
const isOwner = user?.id === activity.ownerId;
// Visibility gate — public always, unlisted on direct link, private owner-only.
// 404 (not 403) to avoid leaking existence.
if (!canView(activity, user, { asDirectLink: true })) {
throw data({ error: "Activity not found" }, { status: 404 });
}
const userRoutes = isOwner && user ? await listRoutes(user.id) : [];
return {
activity: {
id: activity.id,
name: activity.name,
description: activity.description,
distance: activity.distance,
elevationGain: activity.elevationGain,
elevationLoss: activity.elevationLoss,
duration: activity.duration,
routeId: activity.routeId,
hasGpx: !!activity.gpx,
geojson: activity.geojson ?? null,
startedAt: activity.startedAt?.toISOString() ?? null,
visibility: activity.visibility,
createdAt: activity.createdAt.toISOString(),
importSource: activity.importSource,
},
isOwner,
routes: userRoutes.map((r) => ({ id: r.id, name: r.name })),
};
}
export async function activityDetailAction(request: Request, id: string | undefined) {
const user = await requireSessionUser(request);
const activityId = id ?? "";
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "link-route") {
const routeId = formData.get("routeId") as string;
if (routeId) {
await linkActivityToRoute(activityId, routeId, user.id);
}
return redirect(`/activities/${activityId}`);
}
if (intent === "create-route") {
const routeId = await createRouteFromActivity(activityId, user.id);
if (routeId) return redirect(`/routes/${routeId}`);
return data({ error: "No GPX data to create route from" }, { status: 400 });
}
if (intent === "delete") {
await deleteImportByActivity(activityId);
const deleted = await deleteActivity(activityId, user.id);
if (deleted) return redirect("/activities");
return data({ error: "Activity not found" }, { status: 404 });
}
if (intent === "set-visibility") {
const raw = formData.get("visibility") as string | null;
if (!raw || !VISIBILITY_VALUES.has(raw as Visibility)) {
return data({ error: "Invalid visibility" }, { status: 400 });
}
const ok = await updateActivityVisibility(activityId, user.id, raw as Visibility);
if (!ok) return data({ error: "Activity not found" }, { status: 404 });
return redirect(`/activities/${activityId}`);
}
return data({ error: "Unknown action" }, { status: 400 });
}