feat(integrations): add manual sync for Oura, Polar, Strava and Nightscout

These four were the only connected providers with no way to ask for a
sync; they ran on their scheduled pass and nothing else. Each gets a POST
sync route on the hardened Fitbit and Google Health template: session auth,
a 5-per-minute per-user bucket, and a fixed 502 on failure. No body and no
full-sync flag, because none of the four entry points has a full-history
arm to call. Polar goes through the shared legs entry point so both legs
run with the attribution rules built for them.

The Nightscout error arm is the one that matters: a base URL carries the
API token as a query parameter, so the caught message can hold the user's
secret and never reaches the response body. The classified failure is
already on the ledger, recorded with the provider's own redaction.

Connecting also starts the first sync now. The poll handler has accepted a
single-user payload since it was written and never had a producer, so a
fresh connection sat empty for up to an hour waiting for the schedule. The
Oura and Polar callbacks and the Nightscout connect route enqueue one
targeted job each, best effort, with the hourly tick still the safety net.
Strava needs none: its callback already enqueues the history backfill,
which covers the recent window.

The four poll-queue names move into their own module so a request-path
caller can name a queue without dragging the whole worker handler graph
into the request bundle, following the backfill-queue precedent. Creation,
scheduling and handler binding stay in the registrar, and the dead-queue
guard follows the declarations.
This commit is contained in:
Marc-André Bombeck committed 2026-07-25 04:43:06 +02:00
1 parent 9bbbeb805c
commit a9f1629f82
17 files changed
+874 -21

No files matched your search

@@ -0,0 +1,104 @@
/**
* v1.32.28 — manual Oura sync. Until now Oura only ran on its hourly tick.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
import type * as ApiHandlerModule from "@/lib/api-handler";
vi.mock("@/lib/api-handler", async () => {
const actual =
await vi.importActual<typeof ApiHandlerModule>("@/lib/api-handler");
return {
...actual,
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
};
});
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(async () => ({ allowed: true })),
}));
vi.mock("@/lib/oura/sync", () => ({ syncUserOura: vi.fn() }));
import { POST } from "../route";
import { HttpError, requireAuth } from "@/lib/api-handler";
import { checkRateLimit } from "@/lib/rate-limit";
import { syncUserOura } from "@/lib/oura/sync";
function request(): NextRequest {
return new NextRequest("http://localhost/api/oura/sync", { method: "POST" });
}
// The route takes no arguments (no body, no flags); the alias keeps the
// direct invoke typed while still handing apiHandler a real request.
const post = POST as unknown as (r: NextRequest) => Promise<Response>;
async function envelope(response: Response) {
return (await response.json()) as {
data: { imported?: number } | null;
error: string | null;
meta?: { errorCode?: string };
};
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(requireAuth).mockResolvedValue({
user: { id: "u1" },
} as never);
});
describe("POST /api/oura/sync", () => {
it("syncs the session user and answers with the imported count", async () => {
vi.mocked(syncUserOura).mockResolvedValue(12);
const response = await post(request());
expect(response.status).toBe(200);
expect(await envelope(response)).toEqual({
data: { imported: 12 },
error: null,
});
// The id comes from the session, never from the request.
expect(syncUserOura).toHaveBeenCalledWith("u1");
});
it("refuses an unauthenticated caller before syncing anything", async () => {
vi.mocked(requireAuth).mockRejectedValue(
new HttpError(401, "Not authenticated"),
);
const response = await post(request());
expect(response.status).toBe(401);
expect(syncUserOura).not.toHaveBeenCalled();
});
it("refuses past the per-user rate limit without touching the sync", async () => {
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: false } as never);
const response = await post(request());
const body = await envelope(response);
expect(response.status).toBe(429);
expect(body.meta?.errorCode).toBe("rate_limited_self");
expect(syncUserOura).not.toHaveBeenCalled();
expect(checkRateLimit).toHaveBeenCalledWith("oura-sync:u1", 5, 60_000);
});
it("answers 502 generically when the sync throws", async () => {
vi.mocked(syncUserOura).mockRejectedValue(
new Error("oura said: token abc123 is invalid"),
);
const response = await post(request());
const body = await envelope(response);
expect(response.status).toBe(502);
expect(body.error).toBe("Oura sync failed");
expect(JSON.stringify(body)).not.toContain("abc123");
});
});
+42
View File
@@ -0,0 +1,42 @@
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess, apiError } from "@/lib/api-response";
import { checkRateLimit } from "@/lib/rate-limit";
import { annotate } from "@/lib/logging/context";
import { syncUserOura } from "@/lib/oura/sync";
/**
* Manually trigger an Oura sync for the current user (v1.32.28).
*
* Until now Oura only ever synced on its hourly cron tick, so a user who could
* see something was behind had no way to ask for a fresh pull.
*
* No body and no `fullSync` flag: `syncUserOura` has no full-history arm, and
* the window is not the caller's to choose — the sync derives it from the
* newest row it already holds, which is what makes a catch-up honest. Accepting
* a `lookbackDays` here would hand an unvalidated cost knob to the client.
*
* Rate-limited 5/60s per user, matching the hardened Fitbit / Google Health
* routes; a sync is a fan-out of upstream requests plus a batched write, so a
* tight retry loop must not be able to pin Prisma or burn the Oura budget.
*/
export const POST = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "oura.sync" } });
const rl = await checkRateLimit(`oura-sync:${user.id}`, 5, 60_000);
if (!rl.allowed) {
return apiError("Too many sync requests", 429, {
errorCode: "rate_limited_self",
});
}
try {
const imported = await syncUserOura(user.id);
return apiSuccess({ imported });
} catch {
// The failure is already on the `oura` ledger, classified by the provider
// that owns the error shape. Answer generically — an upstream message can
// carry detail that has no business in a response body.
return apiError("Oura sync failed", 502);
}
});