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>
133 lines
4.1 KiB
TypeScript
133 lines
4.1 KiB
TypeScript
// Contract tests for the Wahoo WebhookReceiver capability adapter.
|
|
//
|
|
// Seam: parseWebhook(body) -> WebhookEvent | null
|
|
// handle(event) -> void (creates an activity if file present, dedups via sync_imports)
|
|
|
|
import { describe, it, expect, beforeEach, vi } from "vitest";
|
|
|
|
const fetchSpy = vi.fn();
|
|
const mockCreateActivity = vi.fn();
|
|
const mockIsAlreadyImported = vi.fn();
|
|
const mockRecordImport = vi.fn();
|
|
const mockGetServiceByProviderUser = vi.fn();
|
|
const mockWithFreshCredentials = vi.fn();
|
|
|
|
vi.mock("../../../activities.server.ts", () => ({
|
|
createActivity: mockCreateActivity,
|
|
}));
|
|
vi.mock("../../../sync/imports.server.ts", () => ({
|
|
isAlreadyImported: mockIsAlreadyImported,
|
|
recordImport: mockRecordImport,
|
|
}));
|
|
vi.mock("../../manager.ts", () => ({
|
|
getServiceByProviderUser: mockGetServiceByProviderUser,
|
|
withFreshCredentials: mockWithFreshCredentials,
|
|
}));
|
|
|
|
beforeEach(() => {
|
|
fetchSpy.mockReset();
|
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
|
mockCreateActivity.mockReset();
|
|
mockIsAlreadyImported.mockReset();
|
|
mockRecordImport.mockReset();
|
|
mockGetServiceByProviderUser.mockReset();
|
|
mockWithFreshCredentials.mockReset();
|
|
});
|
|
|
|
const { wahooWebhook } = await import("./webhook.ts");
|
|
|
|
describe("wahooWebhook.parseWebhook", () => {
|
|
it("returns a WebhookEvent for workout_summary payloads", () => {
|
|
const event = wahooWebhook.parseWebhook({
|
|
event_type: "workout_summary",
|
|
user: { id: 7 },
|
|
workout_summary: {
|
|
workout: { id: 42 },
|
|
file: { url: "https://cdn.example/42.fit" },
|
|
},
|
|
});
|
|
expect(event).toEqual({
|
|
eventType: "workout_summary",
|
|
providerUserId: "7",
|
|
workoutId: "42",
|
|
fileUrl: "https://cdn.example/42.fit",
|
|
});
|
|
});
|
|
|
|
it("returns null for unrecognized event types", () => {
|
|
expect(wahooWebhook.parseWebhook({ event_type: "other" })).toBeNull();
|
|
});
|
|
|
|
it("returns null when user.id is missing", () => {
|
|
expect(
|
|
wahooWebhook.parseWebhook({ event_type: "workout_summary", user: {} }),
|
|
).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("wahooWebhook.handle", () => {
|
|
it("creates an activity and records the import for a known user", async () => {
|
|
mockGetServiceByProviderUser.mockResolvedValue({
|
|
id: "svc-1",
|
|
userId: "u1",
|
|
provider: "wahoo",
|
|
});
|
|
mockIsAlreadyImported.mockResolvedValue(false);
|
|
mockCreateActivity.mockResolvedValue("act-1");
|
|
// withFreshCredentials passes the credentials to fn — we don't need to
|
|
// download a file to assert the basic flow; pass a no-op file URL test
|
|
// via parseWebhook output containing fileUrl undefined to skip download.
|
|
mockWithFreshCredentials.mockImplementation(
|
|
async (_id: string, fn: (creds: unknown) => Promise<unknown>) =>
|
|
fn({
|
|
access_token: "a",
|
|
refresh_token: "r",
|
|
expires_at: new Date(Date.now() + 3600_000).toISOString(),
|
|
}),
|
|
);
|
|
|
|
await wahooWebhook.handle({
|
|
eventType: "workout_summary",
|
|
providerUserId: "7",
|
|
workoutId: "42",
|
|
// no fileUrl — the activity is created without GPX
|
|
});
|
|
|
|
expect(mockCreateActivity).toHaveBeenCalledWith(
|
|
"u1",
|
|
expect.objectContaining({ name: expect.stringContaining("Wahoo") }),
|
|
);
|
|
expect(mockRecordImport).toHaveBeenCalledWith("u1", "wahoo", "42", "act-1");
|
|
});
|
|
|
|
it("silently skips when the providerUserId is unknown (no leak)", async () => {
|
|
mockGetServiceByProviderUser.mockResolvedValue(null);
|
|
|
|
await wahooWebhook.handle({
|
|
eventType: "workout_summary",
|
|
providerUserId: "999",
|
|
workoutId: "42",
|
|
});
|
|
|
|
expect(mockCreateActivity).not.toHaveBeenCalled();
|
|
expect(mockRecordImport).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("silently skips when the workout was already imported (idempotency)", async () => {
|
|
mockGetServiceByProviderUser.mockResolvedValue({
|
|
id: "svc-1",
|
|
userId: "u1",
|
|
provider: "wahoo",
|
|
});
|
|
mockIsAlreadyImported.mockResolvedValue(true);
|
|
|
|
await wahooWebhook.handle({
|
|
eventType: "workout_summary",
|
|
providerUserId: "7",
|
|
workoutId: "42",
|
|
});
|
|
|
|
expect(mockCreateActivity).not.toHaveBeenCalled();
|
|
expect(mockRecordImport).not.toHaveBeenCalled();
|
|
});
|
|
});
|