diff --git a/cspell.json b/cspell.json index 23fe22ac8c..8fd296c527 100644 --- a/cspell.json +++ b/cspell.json @@ -83,6 +83,7 @@ "whoop", "garmin", "garminconnect", + "thegarth", "peloton", "fitbit", "strava", diff --git a/packages/garmin-connect/src/client.test.ts b/packages/garmin-connect/src/client.test.ts index 12cd8b3dcf..5d95fe2d30 100644 --- a/packages/garmin-connect/src/client.test.ts +++ b/packages/garmin-connect/src/client.test.ts @@ -365,6 +365,92 @@ describe("GarminConnectClient.fromTokens", () => { "Failed to fetch OAuth consumer credentials", ); }); + + it("reuses the cached OAuth consumer across fromTokens calls", async () => { + const tokens = makeGarminTokens({ expires_at: Math.floor(Date.now() / 1000) + 3600 }); + const fetchFn = vi.fn().mockImplementation((url: string | URL) => { + if (String(url).includes("oauth_consumer.json")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ + consumer_key: "test-consumer-key", + consumer_secret: "test-consumer-secret", + }), + }); + } + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ + displayName: "testuser", + userName: "testuser", + }), + }); + }); + + await GarminConnectClient.fromTokens(tokens, "garmin.com", fetchFn); + await GarminConnectClient.fromTokens(tokens, "garmin.com", fetchFn); + + const consumerFetches = fetchFn.mock.calls.filter(([url]) => + String(url).includes("oauth_consumer.json"), + ); + expect(consumerFetches).toHaveLength(1); + }); + + it("throws when OAuth consumer response is not a JSON object", async () => { + const tokens = makeGarminTokens(); + const fetchFn = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: () => Promise.resolve("not-an-object"), + }); + + await expect(GarminConnectClient.fromTokens(tokens, "garmin.com", fetchFn)).rejects.toThrow( + GarminAuthError, + ); + }); + + it("throws when OAuth consumer response is null", async () => { + const tokens = makeGarminTokens(); + const fetchFn = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: () => Promise.resolve(null), + }); + + await expect(GarminConnectClient.fromTokens(tokens, "garmin.com", fetchFn)).rejects.toThrow( + GarminAuthError, + ); + }); + + it("throws when OAuth consumer response is missing keys", async () => { + const tokens = makeGarminTokens(); + const fetchFn = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: () => Promise.resolve({ consumer_secret: "x" }), + }); + + await expect(GarminConnectClient.fromTokens(tokens, "garmin.com", fetchFn)).rejects.toThrow( + GarminAuthError, + ); + }); + + it("throws when consumer_key is not a string", async () => { + const tokens = makeGarminTokens(); + const fetchFn = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: () => Promise.resolve({ consumer_key: 123, consumer_secret: "x" }), + }); + + await expect(GarminConnectClient.fromTokens(tokens, "garmin.com", fetchFn)).rejects.toThrow( + GarminAuthError, + ); + }); }); describe("GarminConnectClient API methods", () => { diff --git a/packages/garmin-connect/src/client.ts b/packages/garmin-connect/src/client.ts index 694bf4207b..92d8844c9f 100644 --- a/packages/garmin-connect/src/client.ts +++ b/packages/garmin-connect/src/client.ts @@ -42,8 +42,19 @@ const USER_AGENT = "com.garmin.android.apps.connectmobile"; const API_USER_AGENT = "GCM-iOS-5.19.1.2"; /** Minimum delay between consecutive Connect API requests (ms). - * Garmin's unofficial API rate limits aggressively; 3s keeps bursts under control. */ -export const GARMIN_CONNECT_THROTTLE_MS = 3_000; + * Garmin's unofficial API rate limits aggressively; 5s keeps bursts under control. */ +export const GARMIN_CONNECT_THROTTLE_MS = 5_000; + +/** Cache OAuth consumer by fetch function reference. + * Production always uses globalThis.fetch (same ref → one fetch). + * Tests use fresh vi.fn() per test → natural isolation. */ +const consumerCache = new WeakMap(); + +function isOAuthConsumer(data: unknown): data is OAuthConsumer { + if (typeof data !== "object" || data === null) return false; + if (!("consumer_key" in data) || !("consumer_secret" in data)) return false; + return typeof data.consumer_key === "string" && typeof data.consumer_secret === "string"; +} const CSRF_RE = /name="_csrf"\s+value="(.+?)"/; const TITLE_RE = /(.+?)<\/title>/; @@ -213,12 +224,24 @@ export class GarminConnectClient { } async #loadConsumer(): Promise<void> { + if (this.#consumer) return; + + const cached = consumerCache.get(this.#fetchFn); + if (cached) { + this.#consumer = cached; + return; + } + const response = await this.#fetchFn(OAUTH_CONSUMER_URL); if (!response.ok) { throw new GarminAuthError("Failed to fetch OAuth consumer credentials"); } - const consumer: OAuthConsumer = await response.json(); - this.#consumer = consumer; + const data = await response.json(); + if (!isOAuthConsumer(data)) { + throw new GarminAuthError("Invalid OAuth consumer response from S3"); + } + this.#consumer = data; + consumerCache.set(this.#fetchFn, data); } async #getOAuth1Token(ticket: string): Promise<OAuth1Token> { diff --git a/packages/provider-http/src/adaptive-rate-limit.test.ts b/packages/provider-http/src/adaptive-rate-limit.test.ts index d12e41834a..e113a8cdd1 100644 --- a/packages/provider-http/src/adaptive-rate-limit.test.ts +++ b/packages/provider-http/src/adaptive-rate-limit.test.ts @@ -25,7 +25,7 @@ import { describe("defaultThrottleMs", () => { it("returns provider-specific defaults", () => { expect(defaultThrottleMs("strava")).toBe(10_000); - expect(defaultThrottleMs("garmin")).toBe(3_000); + expect(defaultThrottleMs("garmin")).toBe(5_000); expect(defaultThrottleMs("whoop")).toBe(1_000); expect(defaultThrottleMs("unknown")).toBe(1_000); }); diff --git a/packages/provider-http/src/adaptive-rate-limit.ts b/packages/provider-http/src/adaptive-rate-limit.ts index 9a7ef67c93..1c7ad4f0de 100644 --- a/packages/provider-http/src/adaptive-rate-limit.ts +++ b/packages/provider-http/src/adaptive-rate-limit.ts @@ -19,7 +19,7 @@ export const ADAPTIVE_MIN_REQUESTS_FOR_BUDGET_LEARNING = 8; export const DEFAULT_PROVIDER_THROTTLE_MS: Readonly<Record<string, number>> = { strava: 10_000, - garmin: 3_000, + garmin: 5_000, whoop: 1_000, }; @@ -37,7 +37,8 @@ export const DEFAULT_HTTP_REQUESTS_PER_SYNC_JOB: Readonly<Record<string, number> /** Seed inferred budgets for step-chain providers before the first 429 observation. */ export const DEFAULT_PROVIDER_INFERRED_BUDGET: Readonly<Record<string, number>> = { - garmin: ADAPTIVE_DEFAULT_INFERRED_BUDGET, + // Garmin's unofficial API is IP-based; keep the default budget conservative. + garmin: 20, whoop: ADAPTIVE_DEFAULT_INFERRED_BUDGET, }; diff --git a/src/jobs/enqueue-sync-job.test.ts b/src/jobs/enqueue-sync-job.test.ts index 7ed65787d8..de291eeb19 100644 --- a/src/jobs/enqueue-sync-job.test.ts +++ b/src/jobs/enqueue-sync-job.test.ts @@ -71,6 +71,7 @@ describe("enqueueSyncJob", () => { userId: null, expiresAt: new Date("2026-06-02T12:10:00Z"), }; + mockGetActive.mockResolvedValue(cooldown); const retryAt = await scheduleDelayedSyncJob( { @@ -98,6 +99,35 @@ describe("enqueueSyncJob", () => { ); }); + it("returns the existing delayed cooldown job instead of enqueueing a duplicate", async () => { + const cooldown = { + providerId: "garmin", + scope: "provider" as const, + userId: null, + expiresAt: new Date("2026-06-02T12:10:00Z"), + }; + mockGetActive.mockResolvedValue(cooldown); + const existingJob = { + id: "rate-limit-delayed-job", + getState: vi.fn().mockResolvedValue("delayed"), + }; + mockGetJob.mockResolvedValue(existingJob); + + await scheduleDelayedSyncJob( + { + userId: "user-1", + providerId: "garmin", + sinceIso: "2026-06-01T00:00:00.000Z", + untilIso: "2026-06-02T23:59:59.999Z", + checkpoint: { phase: "api", stepIndex: 2 }, + }, + cooldown, + ); + + expect(mockProviderQueueAdd).not.toHaveBeenCalled(); + expect(mockGetJob).toHaveBeenCalledWith("rate-limit-delayed-job"); + }); + it("returns default retry options when no cooldown is active", async () => { await expect(syncJobOptionsWithRateLimitCooldown("garmin", "user-1")).resolves.toEqual( expect.objectContaining({ attempts: 288 }), diff --git a/src/jobs/enqueue-sync-job.ts b/src/jobs/enqueue-sync-job.ts index b644469150..d8c616a0fb 100644 --- a/src/jobs/enqueue-sync-job.ts +++ b/src/jobs/enqueue-sync-job.ts @@ -51,14 +51,17 @@ export async function scheduleDelayedSyncJob( cooldown: ProviderRateLimitCooldown, ): Promise<string> { const providerId = jobData.providerId ?? cooldown.providerId; - const nextData: SyncJobData = { - ...jobData, + const queue = getProviderSyncQueue(providerId); + await enqueueSyncJobWithRequestDedup( providerId, - }; - await getProviderSyncQueue(providerId).add("sync", nextData, { - ...SYNC_JOB_RETRY_OPTIONS, - delay: providerRateLimitDelayMs(cooldown), - jobId: providerRateLimitCooldownJobId(cooldown, jobData.userId), - }); + { ...jobData, providerId }, + { + ...SYNC_JOB_RETRY_OPTIONS, + delay: providerRateLimitDelayMs(cooldown), + jobId: providerRateLimitCooldownJobId(cooldown, jobData.userId ?? ""), + }, + (name, data, opts) => queue.add(name, data, opts), + (jobId) => queue.getJob(jobId), + ); return cooldown.expiresAt.toISOString(); } diff --git a/src/jobs/process-scheduled-sync-job.test.ts b/src/jobs/process-scheduled-sync-job.test.ts index 06a0acde9f..06f5e39062 100644 --- a/src/jobs/process-scheduled-sync-job.test.ts +++ b/src/jobs/process-scheduled-sync-job.test.ts @@ -1,7 +1,17 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; /** Per-provider mock queues keyed by provider ID */ -const providerQueues = new Map<string, { add: ReturnType<typeof vi.fn> }>(); +const providerQueues = new Map< + string, + { + add: ReturnType<typeof vi.fn>; + getJobs: ReturnType<typeof vi.fn>; + getJob: ReturnType<typeof vi.fn>; + getActive: ReturnType<typeof vi.fn>; + getWaiting: ReturnType<typeof vi.fn>; + getDelayed: ReturnType<typeof vi.fn>; + } +>(); const mockLoggerInfo = vi.fn(); const mockGetActiveCooldown = vi.fn(); @@ -13,6 +23,9 @@ function getMockQueue(providerId: string) { add: vi.fn((..._args: unknown[]) => Promise.resolve({ id: "job-1" })), getJobs: vi.fn(async () => []), getJob: vi.fn(async () => undefined), + getActive: vi.fn(async () => []), + getWaiting: vi.fn(async () => []), + getDelayed: vi.fn(async () => []), }; providerQueues.set(providerId, queue); return queue; @@ -185,4 +198,31 @@ describe("processScheduledSyncJob", () => { "[scheduled-sync] Enqueued 0 sync jobs for 1 users (1 skipped due to rate-limit cooldown)", ); }); + + it("skips enqueue when a step-chain provider already has pending sync jobs", async () => { + const garminQueue = getMockQueue("garmin"); + garminQueue.getActive = vi.fn().mockResolvedValue([ + { + data: { + userId: "user-1", + providerId: "garmin", + checkpoint: { phase: "api", stepIndex: 2 }, + }, + }, + ]); + + const db = { + execute: vi.fn().mockResolvedValue([{ user_id: "user-1", provider_id: "garmin" }]), + }; + + await Reflect.apply(processScheduledSyncJob, undefined, [{}, db]); + + expect(garminQueue.add).not.toHaveBeenCalled(); + expect(mockLoggerInfo).toHaveBeenCalledWith( + "[scheduled-sync] Skipping garmin for user-1: 1 sync job(s) already queued", + ); + expect(mockLoggerInfo).toHaveBeenCalledWith( + "[scheduled-sync] Enqueued 0 sync jobs for 1 users (1 skipped due to in-flight sync)", + ); + }); }); diff --git a/src/jobs/process-scheduled-sync-job.ts b/src/jobs/process-scheduled-sync-job.ts index f9dab3fbc5..91a250c6d0 100644 --- a/src/jobs/process-scheduled-sync-job.ts +++ b/src/jobs/process-scheduled-sync-job.ts @@ -1,6 +1,8 @@ +import { isStepChainSyncProvider } from "@dofek/provider-http/adaptive-rate-limit"; import type { Job } from "bullmq"; import { sql } from "drizzle-orm"; import type { SyncDatabase } from "../db/index.ts"; +import { listProviderSyncJobsForUser } from "../lib/sync-request-queue.ts"; import { logger } from "../logger.ts"; import { getProvider, isSyncEligibleProvider } from "../providers/index.ts"; import { enqueueSyncJob } from "./enqueue-sync-job.ts"; @@ -36,6 +38,7 @@ export async function processScheduledSyncJob(_job: Job<ScheduledSyncJobData>, d let jobCount = 0; let skippedDueToCooldown = 0; + let skippedDueToInFlight = 0; for (const [userId, providerIds] of userProviders) { for (const providerId of providerIds) { @@ -45,6 +48,17 @@ export async function processScheduledSyncJob(_job: Job<ScheduledSyncJobData>, d continue; } + if (isStepChainSyncProvider(providerId)) { + const pendingJobs = await listProviderSyncJobsForUser(providerId, userId); + if (pendingJobs.length > 0) { + skippedDueToInFlight++; + logger.info( + `[scheduled-sync] Skipping ${providerId} for ${userId}: ${pendingJobs.length} sync job(s) already queued`, + ); + continue; + } + } + const jobData = { userId, providerId, @@ -67,6 +81,7 @@ export async function processScheduledSyncJob(_job: Job<ScheduledSyncJobData>, d `[scheduled-sync] Enqueued ${jobCount} sync jobs for ${userProviders.size} users` + (skippedDueToCooldown > 0 ? ` (${skippedDueToCooldown} skipped due to rate-limit cooldown)` - : ""), + : "") + + (skippedDueToInFlight > 0 ? ` (${skippedDueToInFlight} skipped due to in-flight sync)` : ""), ); } diff --git a/src/jobs/process-sync-job.test.ts b/src/jobs/process-sync-job.test.ts index a631536f9e..46357d3152 100644 --- a/src/jobs/process-sync-job.test.ts +++ b/src/jobs/process-sync-job.test.ts @@ -333,7 +333,7 @@ describe("processSyncJob", () => { expect.objectContaining({ attempts: 288, delay: 600_000, - jobId: "provider-rate-limit-garmin-provider-user-1-1780402200000", + jobId: "provider-rate-limit-garmin-provider-1780402200000", }), ); expect(mockCaptureException).not.toHaveBeenCalledWith( @@ -461,7 +461,7 @@ describe("processSyncJob", () => { }), expect.objectContaining({ delay: 600_000, - jobId: "provider-rate-limit-garmin-provider-user-1-1780402200000", + jobId: "provider-rate-limit-garmin-provider-1780402200000", }), ); expect(mockCaptureException).not.toHaveBeenCalled(); @@ -504,7 +504,7 @@ describe("processSyncJob", () => { }), expect.objectContaining({ delay: 600_000, - jobId: "provider-rate-limit-garmin-provider-user-1-1780402200000", + jobId: "provider-rate-limit-garmin-provider-1780402200000", }), ); expect(mockLogSync).not.toHaveBeenCalled(); diff --git a/src/jobs/provider-queue-config.test.ts b/src/jobs/provider-queue-config.test.ts index 50333744bd..94fce90693 100644 --- a/src/jobs/provider-queue-config.test.ts +++ b/src/jobs/provider-queue-config.test.ts @@ -56,7 +56,7 @@ describe("getProviderQueueConfig", () => { const config = getProviderQueueConfig("garmin"); expect(config.syncTier).toBe("frequent"); expect(config.concurrency).toBe(1); - expect(config.limiter).toEqual({ max: 1, duration: 1_000 }); + expect(config.limiter).toEqual({ max: 1, duration: 5_000 }); }); it("returns frequent tier for whoop with step-chain job limiter", () => { diff --git a/src/jobs/provider-queue-config.ts b/src/jobs/provider-queue-config.ts index 0394eaf510..41f9ac2284 100644 --- a/src/jobs/provider-queue-config.ts +++ b/src/jobs/provider-queue-config.ts @@ -76,7 +76,7 @@ const PROVIDER_QUEUE_CONFIGS: ReadonlyMap<string, ProviderQueueConfig> = new Map // ── Frequent tier ── // Garmin sync is step-chained: one BullMQ job per sync phase (activities, sleep, etc.). // Job limiter paces phases; adaptive fetch paces individual HTTP calls. - ["garmin", frequentProvider(1, { max: 1, duration: 1_000 })], + ["garmin", frequentProvider(1, { max: 1, duration: 5_000 })], // WHOOP sync is step-chained: one BullMQ job ≈ one API step (~3 HTTP calls with auth). // Job limiter paces steps; adaptive fetch paces individual HTTP calls. ["whoop", frequentProvider(1, { max: 1, duration: 1_000 })], diff --git a/src/jobs/provider-rate-limit-cooldown.test.ts b/src/jobs/provider-rate-limit-cooldown.test.ts index 7ec965e335..a6a238ec7b 100644 --- a/src/jobs/provider-rate-limit-cooldown.test.ts +++ b/src/jobs/provider-rate-limit-cooldown.test.ts @@ -199,7 +199,7 @@ describe("ProviderRateLimitCooldownStore", () => { } expect(cooldown.consecutiveHits).toBe(3); - expect(cooldown.expiresAt).toEqual(new Date("2026-06-02T19:00:00Z")); + expect(cooldown.expiresAt).toEqual(new Date("2026-06-02T22:00:00Z")); vi.useRealTimers(); }); @@ -227,7 +227,7 @@ describe("ProviderRateLimitCooldownStore", () => { "user-1", ); - expect(cooldown.expiresAt).toEqual(new Date("2026-06-02T13:00:00Z")); + expect(cooldown.expiresAt).toEqual(new Date("2026-06-02T14:00:00Z")); vi.useRealTimers(); }); @@ -237,12 +237,12 @@ describe("ProviderRateLimitCooldownStore", () => { const first = await store.record(rateLimitError({ providerId: "garmin" }), "user-1"); expect(first.consecutiveHits).toBe(1); - expect(first.expiresAt).toEqual(new Date("2026-06-02T13:00:00Z")); + expect(first.expiresAt).toEqual(new Date("2026-06-02T14:00:00Z")); - vi.setSystemTime(new Date("2026-06-02T13:00:00Z")); + vi.setSystemTime(new Date("2026-06-02T14:00:00Z")); const second = await store.record(rateLimitError({ providerId: "garmin" }), "user-1"); expect(second.consecutiveHits).toBe(2); - expect(second.expiresAt).toEqual(new Date("2026-06-02T15:00:00Z")); + expect(second.expiresAt).toEqual(new Date("2026-06-02T18:00:00Z")); vi.useRealTimers(); }); @@ -251,7 +251,7 @@ describe("ProviderRateLimitCooldownStore", () => { const store = new InMemoryProviderRateLimitCooldownStore(); await store.record(rateLimitError({ providerId: "garmin" }), "user-1"); - vi.setSystemTime(new Date("2026-06-02T15:00:01Z")); + vi.setSystemTime(new Date("2026-06-02T16:00:01Z")); const second = await store.record(rateLimitError({ providerId: "garmin" }), "user-1"); expect(second.consecutiveHits).toBe(1); @@ -263,7 +263,7 @@ describe("ProviderRateLimitCooldownStore", () => { const store = new InMemoryProviderRateLimitCooldownStore(); await store.record(rateLimitError({ providerId: "garmin" }), "user-1"); - vi.setSystemTime(new Date("2026-06-02T15:00:00Z")); + vi.setSystemTime(new Date("2026-06-02T16:00:00Z")); const second = await store.record(rateLimitError({ providerId: "garmin" }), "user-1"); expect(second.consecutiveHits).toBe(2); @@ -305,7 +305,7 @@ describe("ProviderRateLimitCooldownStore", () => { "user-1", ); - expect(cooldown.expiresAt).toEqual(new Date("2026-06-02T13:00:00Z")); + expect(cooldown.expiresAt).toEqual(new Date("2026-06-02T14:00:00Z")); vi.useRealTimers(); }); @@ -705,6 +705,6 @@ describe("provider rate-limit scheduling helpers", () => { const jobId = providerRateLimitCooldownJobId(cooldown, "user-1"); - expect(jobId).toBe("provider-rate-limit-garmin-provider-user-1-1780402200000"); + expect(jobId).toBe("provider-rate-limit-garmin-provider-1780402200000"); }); }); diff --git a/src/jobs/provider-rate-limit-cooldown.ts b/src/jobs/provider-rate-limit-cooldown.ts index fdb400d5bd..70ef7c23a9 100644 --- a/src/jobs/provider-rate-limit-cooldown.ts +++ b/src/jobs/provider-rate-limit-cooldown.ts @@ -43,7 +43,9 @@ function fallbackCooldownSeconds(providerId: string): number { ["strava", 15 * 60], ["withings", 60], ["fitbit", 60 * 60], - ["garmin", 60 * 60], + // Garmin omits Retry-After; use a cooldown longer than the 30-minute scheduled sync + // interval so delayed retries are not immediately followed by a fresh scheduled fan-out. + ["garmin", 2 * 60 * 60], ["whoop", 60 * 60], ]); return providerFallbackCooldownSeconds.get(providerId) ?? DEFAULT_FALLBACK_COOLDOWN_SECONDS; @@ -335,5 +337,6 @@ export function providerRateLimitCooldownJobId( cooldown: ProviderRateLimitCooldown, jobUserId: string, ): string { - return `${KEY_PREFIX}-${cooldown.providerId}-${cooldown.scope}-${cooldown.userId ?? jobUserId}-${cooldown.expiresAt.getTime()}`; + const suffix = cooldown.scope === "provider" ? "" : `-${cooldown.userId ?? jobUserId}`; + return `${KEY_PREFIX}-${cooldown.providerId}-${cooldown.scope}${suffix}-${cooldown.expiresAt.getTime()}`; } diff --git a/src/jobs/sync-request-job.test.ts b/src/jobs/sync-request-job.test.ts index 19a5f9491b..62887e783e 100644 --- a/src/jobs/sync-request-job.test.ts +++ b/src/jobs/sync-request-job.test.ts @@ -296,4 +296,24 @@ describe("enqueueSyncJobWithRequestDedup", () => { ); expect(result).toBe(newJob); }); + + it("returns an existing cooldown-delayed job without enqueueing a duplicate", async () => { + const existing = { getState: vi.fn(), remove: vi.fn() }; + existing.getState.mockResolvedValue("delayed"); + const addJob = vi.fn(); + const getJob = vi.fn(); + getJob.mockResolvedValue(existing); + + const result = await enqueueSyncJobWithRequestDedup( + "garmin", + jobData, + { jobId: "rate-limit-delayed-job", delay: 600_000 }, + addJob, + getJob, + ); + + expect(getJob).toHaveBeenCalledWith("rate-limit-delayed-job"); + expect(addJob).not.toHaveBeenCalled(); + expect(result).toBe(existing); + }); }); diff --git a/src/jobs/sync-request-job.ts b/src/jobs/sync-request-job.ts index 6ae75d8cf9..74c5c868fe 100644 --- a/src/jobs/sync-request-job.ts +++ b/src/jobs/sync-request-job.ts @@ -14,8 +14,11 @@ export async function enqueueSyncJobWithRequestDedup( const requestQuery = resolveSyncRequestQuery(providerId, jobData); const nextOptions: JobsOptions = { ...jobOptions }; - if (requestQuery && nextOptions.jobId == null) { + if (nextOptions.jobId == null && requestQuery) { nextOptions.jobId = buildSyncRequestJobId(providerId, jobData.userId, requestQuery); + } + + if (nextOptions.jobId != null) { const existing = await getJob(nextOptions.jobId); if (existing) { const state = await existing.getState(); diff --git a/src/lib/sync-request-queue.test.ts b/src/lib/sync-request-queue.test.ts index a84bd410cd..7324d5497e 100644 --- a/src/lib/sync-request-queue.test.ts +++ b/src/lib/sync-request-queue.test.ts @@ -1,9 +1,15 @@ -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import type { SyncJobData } from "../jobs/queues.ts"; -const mockGetJobs = vi.fn(); +const mockGetActive = vi.fn(); +const mockGetWaiting = vi.fn(); +const mockGetDelayed = vi.fn(); vi.mock("../jobs/queues.ts", () => ({ - getProviderSyncQueue: vi.fn(() => ({ getJobs: mockGetJobs })), + getProviderSyncQueue: vi.fn(() => ({ + getActive: mockGetActive, + getWaiting: mockGetWaiting, + getDelayed: mockGetDelayed, + })), })); const mockSyncApiQueryKey = vi.fn(); @@ -21,27 +27,30 @@ const { listProviderSyncJobsForUser, listPendingSyncRequestQueryKeys } = await i "./sync-request-queue.ts" ); -const PENDING_SYNC_JOB_STATES = ["active", "waiting", "delayed"]; - function job(data: Partial<SyncJobData>) { return { data: { userId: "user-1", ...data } }; } describe("listProviderSyncJobsForUser", () => { - it("calls getJobs with pending states", async () => { - mockGetJobs.mockResolvedValue([]); + beforeEach(() => { + vi.clearAllMocks(); + mockGetActive.mockResolvedValue([]); + mockGetWaiting.mockResolvedValue([]); + mockGetDelayed.mockResolvedValue([]); + }); + it("fetches from active, waiting, and delayed queues", async () => { await listProviderSyncJobsForUser("garmin", "user-1"); - expect(mockGetJobs).toHaveBeenCalledWith([...PENDING_SYNC_JOB_STATES]); + expect(mockGetActive).toHaveBeenCalledOnce(); + expect(mockGetWaiting).toHaveBeenCalledOnce(); + expect(mockGetDelayed).toHaveBeenCalledWith(); }); - it("filters jobs by userId", async () => { - mockGetJobs.mockResolvedValue([ - job({ userId: "user-1" }), - job({ userId: "user-2" }), - job({ userId: "user-1" }), - ]); + it("filters jobs by userId across all job states", async () => { + mockGetActive.mockResolvedValue([job({ userId: "user-1" })]); + mockGetWaiting.mockResolvedValue([job({ userId: "user-2" })]); + mockGetDelayed.mockResolvedValue([job({ userId: "user-1" })]); const result = await listProviderSyncJobsForUser("garmin", "user-1"); @@ -50,16 +59,12 @@ describe("listProviderSyncJobsForUser", () => { }); it("returns empty array when no jobs match userId", async () => { - mockGetJobs.mockResolvedValue([job({ userId: "user-2" }), job({ userId: "user-3" })]); - const result = await listProviderSyncJobsForUser("garmin", "user-1"); expect(result).toHaveLength(0); }); it("returns empty array when queue has no jobs", async () => { - mockGetJobs.mockResolvedValue([]); - const result = await listProviderSyncJobsForUser("garmin", "user-1"); expect(result).toHaveLength(0); @@ -67,8 +72,14 @@ describe("listProviderSyncJobsForUser", () => { }); describe("listPendingSyncRequestQueryKeys", () => { + beforeEach(() => { + mockGetActive.mockResolvedValue([]); + mockGetWaiting.mockResolvedValue([]); + mockGetDelayed.mockResolvedValue([]); + }); + it("collects query keys for jobs with queries", async () => { - mockGetJobs.mockResolvedValue([ + mockGetActive.mockResolvedValue([ job({ userId: "user-1", sinceIso: "2026-01-01T00:00:00Z" }), job({ userId: "user-1", sinceIso: "2026-02-01T00:00:00Z" }), ]); @@ -89,7 +100,7 @@ describe("listPendingSyncRequestQueryKeys", () => { }); it("deduplicates identical query keys", async () => { - mockGetJobs.mockResolvedValue([ + mockGetActive.mockResolvedValue([ job({ userId: "user-1", sinceIso: "2026-01-01T00:00:00Z" }), job({ userId: "user-1", sinceIso: "2026-01-01T00:00:00Z" }), ]); @@ -108,7 +119,7 @@ describe("listPendingSyncRequestQueryKeys", () => { }); it("skips jobs where resolveSyncRequestQuery returns null", async () => { - mockGetJobs.mockResolvedValue([job({ userId: "user-1", sinceIso: "2026-01-01T00:00:00Z" })]); + mockGetActive.mockResolvedValue([job({ userId: "user-1", sinceIso: "2026-01-01T00:00:00Z" })]); mockResolveSyncRequestQuery.mockReturnValue(null); @@ -118,7 +129,9 @@ describe("listPendingSyncRequestQueryKeys", () => { }); it("returns empty set when queue has no jobs", async () => { - mockGetJobs.mockResolvedValue([]); + mockGetActive.mockResolvedValue([]); + mockGetWaiting.mockResolvedValue([]); + mockGetDelayed.mockResolvedValue([]); const result = await listPendingSyncRequestQueryKeys("garmin", "user-1"); diff --git a/src/lib/sync-request-queue.ts b/src/lib/sync-request-queue.ts index c32ca59130..1f46ac1589 100644 --- a/src/lib/sync-request-queue.ts +++ b/src/lib/sync-request-queue.ts @@ -3,18 +3,17 @@ import { getProviderSyncQueue, type SyncJobData } from "../jobs/queues.ts"; import { syncApiQueryKey } from "./sync-api-query.ts"; import { resolveSyncRequestQuery } from "./sync-request-query.ts"; -const PENDING_SYNC_JOB_STATES = ["active", "waiting", "delayed"] as const; - -type PendingSyncJobState = (typeof PENDING_SYNC_JOB_STATES)[number]; - export async function listProviderSyncJobsForUser( providerId: string, userId: string, - states: readonly PendingSyncJobState[] = PENDING_SYNC_JOB_STATES, ): Promise<Job<SyncJobData>[]> { - // TODO: getJobs fetches ALL pending jobs across all users for this provider, - // filtering in memory. Profile if the queue grows large for shared providers. - const jobs = await getProviderSyncQueue(providerId).getJobs([...states]); + const queue = getProviderSyncQueue(providerId); + const [active, waiting, delayed] = await Promise.all([ + queue.getActive(), + queue.getWaiting(), + queue.getDelayed(), + ]); + const jobs = [...active, ...waiting, ...delayed]; return jobs.filter((job) => job.data.userId === userId); } diff --git a/src/providers/garmin.test.ts b/src/providers/garmin.test.ts index 8b19bafb0c..c543f27c3a 100644 --- a/src/providers/garmin.test.ts +++ b/src/providers/garmin.test.ts @@ -592,6 +592,77 @@ describe("GarminProvider.authSetup()", () => { expect(err.retryAfterSeconds).toBeNull(); } }); + + async function getAuthFetchSetup(response?: Response) { + const customFetch = vi.fn<typeof globalThis.fetch>(); + customFetch.mockResolvedValue(response ?? new Response("ok")); + const provider = new GarminProvider(customFetch); + const setup = provider.authSetup(); + mocks.signIn.mockResolvedValue({ tokens: fakeGarminTokens() }); + if (!setup.automatedLogin) throw new Error("expected automatedLogin"); + await setup.automatedLogin("user@test.com", "pass123"); + const forwardedFetch = mocks.signIn.mock.calls[0]?.[3]; + if (typeof forwardedFetch !== "function") throw new Error("expected forwarded fetch function"); + return { customFetch, forwardedFetch }; + } + + it("bypasses rate limiting for OAuth consumer requests", async () => { + const { customFetch, forwardedFetch } = await getAuthFetchSetup( + new Response("rate limited", { status: 429 }), + ); + + const oauthUrl = "https://thegarth.s3.amazonaws.com/consumer-data"; + const response = await forwardedFetch(oauthUrl); + expect(response.status).toBe(429); + expect(customFetch).toHaveBeenCalledWith(oauthUrl); + }); + + it("bypasses rate limiting for OAuth consumer URL objects", async () => { + const { customFetch, forwardedFetch } = await getAuthFetchSetup(); + + const oauthUrl = new URL("https://thegarth.s3.amazonaws.com/consumer-data"); + await forwardedFetch(oauthUrl); + expect(customFetch).toHaveBeenCalledWith(oauthUrl); + }); + + it("bypasses rate limiting for OAuth consumer Request objects", async () => { + // When resolveRequestUrl returns null for a Request object (mutant), + // the Request goes through the rate-limited path which throws on 429. + // The original code correctly resolves the URL and bypasses. + const { customFetch, forwardedFetch } = await getAuthFetchSetup( + new Response("rate limited", { status: 429 }), + ); + + const oauthRequest = new Request("https://thegarth.s3.amazonaws.com/consumer-data"); + const response = await forwardedFetch(oauthRequest); + expect(response.status).toBe(429); + expect(customFetch).toHaveBeenCalledWith(oauthRequest); + }); + + it("forwards init to baseFetchFn for OAuth consumer bypass", async () => { + const { customFetch, forwardedFetch } = await getAuthFetchSetup(); + + const oauthUrl = "https://thegarth.s3.amazonaws.com/consumer-data"; + const init = { method: "POST" }; + await forwardedFetch(oauthUrl, init); + expect(customFetch).toHaveBeenCalledWith(oauthUrl, init); + }); + + it("forwards init through rate-limited path for non-OAuth requests", async () => { + const { customFetch, forwardedFetch } = await getAuthFetchSetup(); + + const nonOauthUrl = "https://connect.garmin.com/api/data"; + const init = { method: "POST" }; + await forwardedFetch(nonOauthUrl, init); + expect(customFetch).toHaveBeenCalledWith(nonOauthUrl, init); + }); + + it("handles invalid URLs passed to the forwarded fetch", async () => { + const { forwardedFetch } = await getAuthFetchSetup(); + + const result = await forwardedFetch("not-a-valid-url"); + expect(result).toBeInstanceOf(Response); + }); }); // ============================================================ @@ -645,20 +716,17 @@ describe("GarminProvider.sync()", () => { ); }); - it("passes user-scoped rate-limit options to createProviderRateLimitFetch", async () => { + it("passes provider-scoped rate-limit options to createProviderRateLimitFetch", async () => { const { createProviderRateLimitFetch } = await import("../lib/provider-rate-limit-fetch.ts"); await syncProvider(provider, db, new Date()); const mock = vi.mocked(createProviderRateLimitFetch); - expect(mock).toHaveBeenCalledWith( - "garmin", - expect.any(Function), - expect.objectContaining({ scope: "user" }), - ); + expect(mock).toHaveBeenCalledWith("garmin", expect.any(Function), expect.any(Object)); const options = mock.mock.calls.find(([id]) => id === "garmin")?.[2]; - expect(options?.userId).toBe("00000000-0000-0000-0000-000000000001"); + expect(options?.scope).toBeUndefined(); + expect(options?.userId).toBeUndefined(); const createRateLimitError = options?.createRateLimitError; const error = createRateLimitError?.(new Response("too fast", { status: 429 }), "too fast"); @@ -666,6 +734,40 @@ describe("GarminProvider.sync()", () => { if (error instanceof GarminRateLimitError) { expect(error.message).toBe("Rate limit exceeded (429): too fast"); expect(error.retryAfterSeconds).toBeNull(); + expect(error.scope).toBe("provider"); + } + }); + + it("sync createRateLimitError handles null headers and missing get method", async () => { + const { createProviderRateLimitFetch } = await import("../lib/provider-rate-limit-fetch.ts"); + + await syncProvider(provider, db, new Date()); + + const mock = vi.mocked(createProviderRateLimitFetch); + const options = mock.mock.calls.find(([id]) => id === "garmin")?.[2]; + const createRateLimitError = options?.createRateLimitError; + if (!createRateLimitError) throw new Error("expected createRateLimitError"); + + const nullHeadersResponse = new Response("", { status: 429 }); + Object.defineProperty(nullHeadersResponse, "headers", { + value: null, + configurable: true, + }); + const err1 = createRateLimitError(nullHeadersResponse, "body"); + expect(err1).toBeInstanceOf(GarminRateLimitError); + if (err1 instanceof GarminRateLimitError) { + expect(err1.retryAfterSeconds).toBeNull(); + } + + const noGetResponse = new Response("", { status: 429 }); + Object.defineProperty(noGetResponse, "headers", { + value: {}, + configurable: true, + }); + const err2 = createRateLimitError(noGetResponse, ""); + expect(err2).toBeInstanceOf(GarminRateLimitError); + if (err2 instanceof GarminRateLimitError) { + expect(err2.retryAfterSeconds).toBeNull(); } }); diff --git a/src/providers/garmin/provider.ts b/src/providers/garmin/provider.ts index 780620e893..7517ad31d8 100644 --- a/src/providers/garmin/provider.ts +++ b/src/providers/garmin/provider.ts @@ -48,6 +48,43 @@ async function saveSyncCursor(db: SyncDatabase, cursor: string, userId?: string) }); } +const OAUTH_CONSUMER_HOST = "thegarth.s3.amazonaws.com"; + +function resolveRequestUrl(input: RequestInfo | URL): URL | null { + try { + if (input instanceof URL) { + return input; + } + if (typeof input === "string") { + return new URL(input); + } + if (input instanceof Request) { + return new URL(input.url); + } + return new URL(String(input)); + } catch { + return null; + } +} + +function isGarminOAuthConsumerRequest(input: RequestInfo | URL): boolean { + const url = resolveRequestUrl(input); + return url?.hostname === OAUTH_CONSUMER_HOST; +} + +/** Routes static OAuth consumer fetches around adaptive rate limiting. */ +function createGarminConnectFetch( + baseFetchFn: typeof globalThis.fetch, + rateLimitedFetchFn: typeof globalThis.fetch, +): typeof globalThis.fetch { + return async (input, init) => { + if (isGarminOAuthConsumerRequest(input)) { + return init === undefined ? baseFetchFn(input) : baseFetchFn(input, init); + } + return init === undefined ? rateLimitedFetchFn(input) : rateLimitedFetchFn(input, init); + }; +} + function throwIfProviderSyncAbortError(error: unknown): void { if (isRetryableInfraError(error) || error instanceof GarminRateLimitError) throw error; } @@ -72,14 +109,17 @@ export class GarminProvider implements SyncProvider { authSetup(_options?: { host?: string }): ProviderAuthSetup { return { automatedLogin: async (email: string, password: string): Promise<TokenSet> => { - const authFetch = createProviderRateLimitFetch("garmin", this.#baseFetchFn, { - createRateLimitError: (response, responseBody) => - new GarminRateLimitError( - `Rate limit exceeded (${response.status}): ${responseBody}`, - responseBody, - response.headers?.get?.("Retry-After"), - ), - }); + const authFetch = createGarminConnectFetch( + this.#baseFetchFn, + createProviderRateLimitFetch("garmin", this.#baseFetchFn, { + createRateLimitError: (response, responseBody) => + new GarminRateLimitError( + `Rate limit exceeded (${response.status}): ${responseBody}`, + responseBody, + response.headers?.get?.("Retry-After"), + ), + }), + ); const { tokens } = await GarminConnectClient.signIn( email, password, @@ -126,17 +166,19 @@ export class GarminProvider implements SyncProvider { const start = Date.now(); const scopedUserId = resolveScopedUserId(options.userId); - const fetchFn = createProviderRateLimitFetch("garmin", this.#baseFetchFn, { - scope: "user", - userId: scopedUserId, - createRateLimitError: (response, responseBody) => - new GarminRateLimitError( - `Rate limit exceeded (${response.status}): ${responseBody}`, - responseBody, - response.headers?.get?.("Retry-After"), - scopedUserId, - ), - }); + // Garmin's unofficial Connect API rate-limits by egress IP, not per account. + // Use provider-scoped admission so concurrent users share one throttle budget. + const fetchFn = createGarminConnectFetch( + this.#baseFetchFn, + createProviderRateLimitFetch("garmin", this.#baseFetchFn, { + createRateLimitError: (response, responseBody) => + new GarminRateLimitError( + `Rate limit exceeded (${response.status}): ${responseBody}`, + responseBody, + response.headers?.get?.("Retry-After"), + ), + }), + ); let internalTokens: GarminTokens; try {