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

@@ -8,6 +8,8 @@ const {
registerUserMock,
getCredsMock,
markReconnectedMock,
bossSend,
bossMock,
} = vi.hoisted(() => ({
stateMatchesCookieMock: vi.fn(),
verifySignedStateMock: vi.fn(),
@@ -16,6 +18,8 @@ const {
registerUserMock: vi.fn(),
getCredsMock: vi.fn(),
markReconnectedMock: vi.fn(),
bossSend: vi.fn(),
bossMock: vi.fn(),
}));
vi.mock("@/lib/api-handler", () => ({
@@ -24,7 +28,11 @@ vi.mock("@/lib/api-handler", () => ({
vi.mock("@/lib/db", () => ({ prisma: { user: { update: vi.fn() } } }));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
getEvent: () => ({ setAuth: vi.fn(), setError: vi.fn() }),
getEvent: () => ({
setAuth: vi.fn(),
setError: vi.fn(),
addWarning: vi.fn(),
}),
}));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc:${s}` }));
@@ -44,6 +52,7 @@ vi.mock("@/lib/oauth/signed-state", () => ({
vi.mock("@/lib/integrations/status", () => ({
markReconnected: markReconnectedMock,
}));
vi.mock("@/lib/jobs/boss-instance", () => ({ getGlobalBoss: bossMock }));
import { GET } from "../route";
@@ -68,6 +77,8 @@ beforeEach(() => {
getSessionMock.mockResolvedValue(null);
getCredsMock.mockResolvedValue({ clientId: "c", clientSecret: "s" });
exchangeCodeMock.mockResolvedValue({ access_token: "tok", x_user_id: 42 });
bossSend.mockResolvedValue("job-1");
bossMock.mockReturnValue({ send: bossSend });
registerUserMock.mockResolvedValue(undefined);
});
@@ -100,3 +111,35 @@ describe("GET /api/polar/callback", () => {
expect(registerUserMock).not.toHaveBeenCalled();
});
});
/**
* v1.32.28 — connecting starts a sync straight away instead of leaving the card
* empty until the next hourly tick. The poll handler has accepted a single-user
* payload since it was written; this callback is the producer that was missing.
*/
describe("GET /api/polar/callback — connect-time first sync", () => {
it("enqueues exactly one targeted polar-sync job for the connecting user", async () => {
const res = await run(makeReq());
expect(res.headers.get("location")).toContain("polar=connected");
expect(bossSend).toHaveBeenCalledTimes(1);
expect(bossSend).toHaveBeenCalledWith("polar-sync", { userId: "u1" });
});
it("still connects when no boss instance is available", async () => {
bossMock.mockReturnValue(null);
const res = await run(makeReq());
expect(res.headers.get("location")).toContain("polar=connected");
expect(bossSend).not.toHaveBeenCalled();
});
it("still connects when the enqueue itself rejects", async () => {
bossSend.mockRejectedValue(new Error("queue unreachable"));
const res = await run(makeReq());
expect(res.headers.get("location")).toContain("polar=connected");
});
});
+15
View File
@@ -12,6 +12,8 @@ import {
verifySignedState,
} from "@/lib/oauth/signed-state";
import { markReconnected } from "@/lib/integrations/status";
import { POLAR_SYNC_QUEUE } from "@/lib/jobs/integration-poll-queues";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import { NextRequest, NextResponse } from "next/server";
/**
@@ -102,6 +104,19 @@ export const GET = apiHandler(async (request: NextRequest) => {
await auditLog("polar.connect", { userId });
await markReconnected(userId, "polar");
// Start the first sync now instead of leaving the user staring at an empty
// card until the next hourly tick. Best-effort by design: the hourly cron
// remains the safety net, so a missing boss instance must never strand the
// redirect.
const boss = getGlobalBoss();
if (boss) {
await boss
.send(POLAR_SYNC_QUEUE, { userId })
.catch((err) =>
getEvent()?.addWarning(`polar-sync connect enqueue failed: ${err}`),
);
}
const response = NextResponse.redirect(
new URL(
"/settings/integrations?polar=connected",