mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
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:
1 parent
9bbbeb805c
commit
a9f1629f82
17 files changed
+874
-21
No files matched your search
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* v1.32.28 — manual Strava sync. Incremental by nature (Strava carries a real
|
||||
* cursor); no full-history arm is exposed here, that stays with the backfill.
|
||||
*/
|
||||
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/strava/sync", () => ({ syncUserStrava: vi.fn() }));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { HttpError, requireAuth } from "@/lib/api-handler";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { syncUserStrava } from "@/lib/strava/sync";
|
||||
|
||||
function request(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/strava/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/strava/sync", () => {
|
||||
it("syncs the session user and answers with the imported count", async () => {
|
||||
vi.mocked(syncUserStrava).mockResolvedValue(4);
|
||||
|
||||
const response = await post(request());
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await envelope(response)).toEqual({
|
||||
data: { imported: 4 },
|
||||
error: null,
|
||||
});
|
||||
expect(syncUserStrava).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(syncUserStrava).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(syncUserStrava).not.toHaveBeenCalled();
|
||||
expect(checkRateLimit).toHaveBeenCalledWith("strava-sync:u1", 5, 60_000);
|
||||
});
|
||||
|
||||
it("answers 502 generically when the sync throws", async () => {
|
||||
vi.mocked(syncUserStrava).mockRejectedValue(
|
||||
new Error("strava said: token abc123 is invalid"),
|
||||
);
|
||||
|
||||
const response = await post(request());
|
||||
const body = await envelope(response);
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(body.error).toBe("Strava sync failed");
|
||||
expect(JSON.stringify(body)).not.toContain("abc123");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
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 { syncUserStrava } from "@/lib/strava/sync";
|
||||
|
||||
/**
|
||||
* Manually trigger a Strava sync for the current user (v1.32.28).
|
||||
*
|
||||
* Incremental by nature: Strava already carries a real cursor
|
||||
* (`stravaLastActivityAt` minus an overlap), so a manual run picks up wherever
|
||||
* the last one stopped. No `fullSync` flag — deep history belongs to the
|
||||
* connect-time backfill queue, which is self-converging and already gated.
|
||||
*
|
||||
* Rate-limited 5/60s per user, matching the hardened Fitbit / Google Health
|
||||
* routes; Strava's 200-req / 15-min cap leaves no room for a retry loop.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "strava.sync" } });
|
||||
|
||||
const rl = await checkRateLimit(`strava-sync:${user.id}`, 5, 60_000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Too many sync requests", 429, {
|
||||
errorCode: "rate_limited_self",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const imported = await syncUserStrava(user.id);
|
||||
return apiSuccess({ imported });
|
||||
} catch {
|
||||
// Already recorded on the `strava` ledger with its classification. Answer
|
||||
// generically so no upstream detail rides the response body.
|
||||
return apiError("Strava sync failed", 502);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user