trails/apps/journal/app/lib/connected-services/providers/wahoo/webhook.ts
Ullrich Schäfer 8e5b6d6fe9
Wahoo capability adapters + caller migration (groups 3-5)
Implements tasks 1.3, 3.2-3.3, 4.1-4.4, 5.1-5.6, 6.1 of
deepen-connected-services. Built TDD: contract test red, adapter green
for each capability seam.

Capability adapters (providers/wahoo/):
- importer.ts: Importer seam — listImportable + importOne against
  Wahoo /v1/workouts. Filters fitness_app_id >= 1000 (Wahoo doesn't
  share third-party data). 2 contract tests green.
- pusher.ts: RoutePusher seam — pushRoute(ctx, input) -> {remoteId,
  version}. FIT-Course conversion, route:<id> external_id, PUT-vs-POST
  decision, PUT->POST-on-404 fallback all internal to the adapter
  (per ADR-0003). Idempotency via sync_pushes preserved. 4 contract
  tests green.
- webhook.ts: WebhookReceiver seam — parseWebhook + handle. Routes
  events to local users via provider_user_id; unknown user returns
  silently. 6 contract tests green.
- manifest.ts: declares credential_kind=oauth, OAuth config, scopes,
  buildAuthUrl, exchangeCode, and references each capability adapter.

Module shape:
- connected-services/index.ts: side-effect imports providers/index.ts
  to register manifests, then re-exports manager + registry + types.
- connected-services/providers/index.ts: barrel that calls
  registerManifest(wahooManifest).
- connected-services/oauth-state.server.ts: OAuth state encode/decode
  (extracted from legacy pushes.server.ts).
- connected-services/push-action.server.ts: orchestration above the
  RoutePusher seam — load route, ownership check, scope check, build
  RoutePushInput, invoke pusher, return PushOutcome union. Replaces
  the legacy pushRouteToProvider in lib/sync/pushes.server.ts.

Caller migration (group 5):
- api.sync.connect.$provider.ts -> manifest.buildAuthUrl
- api.sync.callback.$provider.ts -> manifest.exchangeCode + link()
- api.sync.disconnect.$provider.ts -> unlinkByUserProvider (calls
  best-effort revoke via the credential adapter, then deletes locally)
- api.sync.webhook.$provider.ts -> manifest.webhookReceiver dispatch
- api.sync.push.$provider.$routeId.ts -> push-action.pushRouteToProvider
- sync.import.$provider.tsx -> manifest.importer.listImportable +
  inline FIT->GPX in the action (form-supplied metadata bypasses the
  Importer seam which is reserved for automatic / webhook imports)
- routes.$id.tsx -> getService instead of getConnection
- settings.connections.tsx -> getAllManifests instead of legacy registry

Legacy lib/sync/ deleted except imports.server.ts (which manages the
sync_imports table, untouched by this change).

DB migration verified locally (task 1.3): pnpm db:migrate-data renamed
the table and backfilled credentials JSONB; pnpm db:push then dropped
the legacy access_token/refresh_token/expires_at columns. Final shape
matches the schema; check constraints + unique index in place.

Test status (task 6.1):
- pnpm typecheck: green across all 15 workspaces
- pnpm lint: green
- @trails-cool/journal: 112 passed, 31 skipped — 12 fewer tests than
  before because pushes.server.test.ts and the legacy wahoo.test.ts
  were deleted. Their coverage is replaced by the new contract tests
  (importer/pusher/webhook) plus manager.test.ts + oauth.test.ts.

Remaining: 6.2 (e2e), 6.3-6.4 (manual smoke + staging migration test),
7.1-7.3 (followups + spec deltas at archive).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 01:25:33 +02:00

100 lines
3.6 KiB
TypeScript

// Wahoo WebhookReceiver capability adapter.
//
// Wahoo posts `workout_summary` events to /api/sync/webhook/wahoo when a
// workout completes. We route the event to the right local user via
// provider_user_id, deduplicate via sync_imports, then download + convert
// the FIT file (if present) and create an activity.
import FitParser from "fit-file-parser";
import { generateGpx } from "@trails-cool/gpx";
import { createActivity } from "../../../activities.server.ts";
import { isAlreadyImported, recordImport } from "../../../sync/imports.server.ts";
import { getServiceByProviderUser, withFreshCredentials } from "../../manager.ts";
import type { OAuthCredentials } from "../../types.ts";
import type { WebhookEvent, WebhookReceiver } from "../../registry.ts";
interface WahooWebhookBody {
event_type?: string;
user?: { id?: number };
workout_summary?: {
id?: number;
workout?: { id?: number };
file?: { url?: string };
};
}
async function fitToGpx(buffer: Buffer): Promise<string | null> {
const parsed = await new Promise<Record<string, unknown>>((resolve, reject) => {
const parser = new FitParser({ force: true });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
parser.parse(buffer as any, (error: unknown, data: any) => {
if (error) reject(error);
else resolve(data ?? {});
});
});
const records = (parsed.records ?? []) as Array<{
position_lat?: number;
position_long?: number;
altitude?: number;
timestamp?: string | Date;
}>;
const trackPoints = records
.filter((r) => r.position_lat != null && r.position_long != null)
.map((r) => ({
lat: r.position_lat!,
lon: r.position_long!,
ele: r.altitude,
time: r.timestamp instanceof Date ? r.timestamp.toISOString() : r.timestamp,
}));
if (trackPoints.length < 2) return null;
return generateGpx({ name: "Wahoo workout", tracks: [trackPoints] });
}
export const wahooWebhook: WebhookReceiver = {
parseWebhook(body: unknown): WebhookEvent | null {
const payload = body as WahooWebhookBody;
if (payload.event_type !== "workout_summary" || !payload.user?.id) return null;
return {
eventType: payload.event_type,
providerUserId: String(payload.user.id),
workoutId: String(
payload.workout_summary?.workout?.id ?? payload.workout_summary?.id ?? "",
),
fileUrl: payload.workout_summary?.file?.url,
};
},
async handle(event: WebhookEvent): Promise<void> {
// Match incoming webhooks to local users via provider_user_id.
// Unknown users return silently — no leak.
const service = await getServiceByProviderUser("wahoo", event.providerUserId);
if (!service) return;
if (await isAlreadyImported(service.userId, "wahoo", event.workoutId)) return;
let gpx: string | null = null;
if (event.fileUrl) {
// Wahoo CDN URLs are pre-signed; no auth header needed. We still go
// through withFreshCredentials so the manager has a chance to refresh
// a near-expired credential before any subsequent Wahoo call this
// handler might make.
const buffer = await withFreshCredentials(service.id, async (_creds) => {
void (_creds as unknown as OAuthCredentials);
const resp = await fetch(event.fileUrl!);
if (!resp.ok) throw new Error(`Wahoo file download failed: ${resp.status}`);
return Buffer.from(await resp.arrayBuffer());
});
gpx = await fitToGpx(buffer);
}
const activityId = await createActivity(service.userId, {
name: `Wahoo workout`,
gpx: gpx ?? undefined,
});
await recordImport(service.userId, "wahoo", event.workoutId, activityId);
},
};