fix(sync): surface poll-cohort sync failures that previously vanished

Introduce a recorded-marker primitive on the integration ledger so a provider
that records-then-rethrows a sync failure is not recorded a second time at the
poll-cohort boundary, while an unrecorded escape (an Oura or Polar write-path
throw, or any future path) lands on the ledger exactly once, correctly
classified and redacted by the source that owns it. Without the marker a
boundary-blind recorder would double-count the failure streak and could persist
a Nightscout token-bearing URL into the stored error.

Give the poll-cohort factory a required per-provider failure recorder and wire
one for Oura, Polar, Nightscout, and Strava.

Nightscout now counts only freshly inserted readings instead of insert plus
re-confirm (the inflated count fired the reminder trigger every tick), records a
transient failure and skips the success stamp when some rows fail to write, and
emits the measurement-arrival spine for its inserts. Correct the docstring that
promised a far-history backfill that does not exist: the hourly window imports
about 48 hours and nothing deeper.

Strava now enqueues its history backfill at connect time, mirroring the WHOOP
and Fitbit callbacks, so deep history imports within the hour instead of waiting
for the next worker restart.
This commit is contained in:
Marc-André Bombeck committed 2026-07-24 20:05:23 +02:00
1 parent cf755d32af
commit 8be7458c7a
20 files changed
+686 -68

No files matched your search

@@ -0,0 +1,109 @@
/**
* S-1 — the Strava OAuth callback enqueues the self-converging history backfill
* at connect time (mirroring the WHOOP / Fitbit callbacks) so deep history
* lands within the hour instead of waiting for the next worker reboot. A missing
* boss instance is a warning, never a failure — boot discovery is the net.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const {
bossSend,
getGlobalBossMock,
exchangeCodeMock,
getCredsMock,
userFindUnique,
userUpdate,
markReconnectedMock,
} = vi.hoisted(() => ({
bossSend: vi.fn(async () => "job-id"),
getGlobalBossMock: vi.fn(),
exchangeCodeMock: vi.fn(),
getCredsMock: vi.fn(),
userFindUnique: vi.fn(),
userUpdate: vi.fn(async () => ({})),
markReconnectedMock: vi.fn(async () => {}),
}));
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
}));
vi.mock("@/lib/db", () => ({
prisma: { user: { findUnique: userFindUnique, update: userUpdate } },
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn(async () => null) }));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
getEvent: () => ({
setAuth: vi.fn(),
setError: vi.fn(),
addWarning: vi.fn(),
}),
}));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn(async () => {}) }));
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc(${s})` }));
vi.mock("@/lib/strava/client", () => ({ exchangeCode: exchangeCodeMock }));
vi.mock("@/lib/strava/credentials", () => ({
getStravaClientCredentials: getCredsMock,
}));
vi.mock("@/lib/oauth/signed-state", () => ({
oauthStateCookieName: () => "strava_oauth_state",
stateMatchesCookie: () => true,
verifySignedState: () => ({ userId: "u1" }),
}));
vi.mock("@/lib/integrations/status", () => ({
markReconnected: markReconnectedMock,
}));
vi.mock("@/lib/jobs/strava-backfill", () => ({
STRAVA_BACKFILL_QUEUE: "strava-backfill",
}));
vi.mock("@/lib/jobs/boss-instance", () => ({
getGlobalBoss: getGlobalBossMock,
}));
import { GET } from "../route";
process.env.NEXT_PUBLIC_APP_URL = "https://app.example";
function callback(): Promise<{ headers: { get(k: string): string | null } }> {
const req = new NextRequest(
"http://localhost/api/strava/callback?code=abc&state=signed-state",
{ headers: { cookie: "strava_oauth_state=signed-state" } },
);
return (GET as unknown as (r: NextRequest) => Promise<never>)(req);
}
beforeEach(() => {
vi.clearAllMocks();
getCredsMock.mockResolvedValue({ clientId: "c", clientSecret: "s" });
exchangeCodeMock.mockResolvedValue({
access_token: "at",
refresh_token: "rt",
athlete: { id: 42 },
});
userFindUnique.mockResolvedValue({ stravaAthleteId: null });
getGlobalBossMock.mockReturnValue({ send: bossSend });
});
describe("GET /api/strava/callback — S-1 backfill enqueue", () => {
it("enqueues one STRAVA_BACKFILL_QUEUE job for the connecting user", async () => {
const res = await callback();
expect(res.headers.get("location")).toContain("strava=connected");
expect(markReconnectedMock).toHaveBeenCalledWith("u1", "strava");
expect(bossSend).toHaveBeenCalledTimes(1);
expect(bossSend).toHaveBeenCalledWith(
"strava-backfill",
expect.objectContaining({ userId: "u1" }),
);
});
it("still connects when the boss instance is unavailable (warning, not failure)", async () => {
getGlobalBossMock.mockReturnValue(null);
const res = await callback();
expect(res.headers.get("location")).toContain("strava=connected");
expect(bossSend).not.toHaveBeenCalled();
});
});
+20
View File
@@ -12,6 +12,8 @@ import {
verifySignedState,
} from "@/lib/oauth/signed-state";
import { markReconnected } from "@/lib/integrations/status";
import { STRAVA_BACKFILL_QUEUE } from "@/lib/jobs/strava-backfill";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import { NextRequest, NextResponse } from "next/server";
/**
@@ -107,6 +109,24 @@ export const GET = apiHandler(async (request: NextRequest) => {
await auditLog("strava.connect", { userId });
await markReconnected(userId, "strava");
// Enqueue the self-converging history backfill at connect time so deep
// history lands within the hour instead of waiting for the next worker
// reboot. Best-effort: the boot-time discovery query
// (`stravaBackfillCompletedAt IS NULL`) is the safety net, so a missing
// boss instance here never strands the connection. Mirrors the WHOOP /
// Fitbit callback enqueue.
const boss = getGlobalBoss();
if (boss) {
await boss
.send(STRAVA_BACKFILL_QUEUE, {
userId,
enqueuedAt: new Date().toISOString(),
})
.catch((err) =>
getEvent()?.addWarning(`strava-backfill enqueue failed: ${err}`),
);
}
const response = NextResponse.redirect(
new URL(
"/settings/integrations?strava=connected",