Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"whoop",
"garmin",
"garminconnect",
"thegarth",
"peloton",
"fitbit",
"strava",
Expand Down
36 changes: 36 additions & 0 deletions packages/garmin-connect/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
GarminConnectClient,
GarminMfaRequiredError,
GarminRateLimitError,
resetGarminConnectTestCaches,
} from "./client.ts";
import type { GarminTokens, OAuth2Token } from "./types.ts";

Expand Down Expand Up @@ -36,6 +37,7 @@ function makeGarminTokens(overrides: Partial<OAuth2Token> = {}): GarminTokens {

afterEach(() => {
vi.useRealTimers();
resetGarminConnectTestCaches();
});

/**
Expand Down Expand Up @@ -365,6 +367,40 @@ 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);
});
});

describe("GarminConnectClient API methods", () => {
Expand Down
37 changes: 30 additions & 7 deletions packages/garmin-connect/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,17 @@ 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;

let cachedOAuthConsumer: OAuthConsumer | null = null;
let oauthConsumerLoadPromise: Promise<OAuthConsumer> | null = null;

/** Clears the module-level OAuth consumer cache (test helper). */
export function resetGarminConnectTestCaches(): void {
cachedOAuthConsumer = null;
oauthConsumerLoadPromise = null;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const CSRF_RE = /name="_csrf"\s+value="(.+?)"/;
const TITLE_RE = /<title>(.+?)<\/title>/;
Expand Down Expand Up @@ -213,12 +222,26 @@ export class GarminConnectClient {
}

async #loadConsumer(): Promise<void> {
const response = await this.#fetchFn(OAUTH_CONSUMER_URL);
if (!response.ok) {
throw new GarminAuthError("Failed to fetch OAuth consumer credentials");
if (this.#consumer) return;

if (!cachedOAuthConsumer) {
if (!oauthConsumerLoadPromise) {
oauthConsumerLoadPromise = (async () => {
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();
cachedOAuthConsumer = consumer;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return consumer;
})().finally(() => {
oauthConsumerLoadPromise = null;
});
}
cachedOAuthConsumer = await oauthConsumerLoadPromise;
}
const consumer: OAuthConsumer = await response.json();
this.#consumer = consumer;

this.#consumer = cachedOAuthConsumer;
}

async #getOAuth1Token(ticket: string): Promise<OAuth1Token> {
Expand Down
2 changes: 1 addition & 1 deletion packages/provider-http/src/adaptive-rate-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
5 changes: 3 additions & 2 deletions packages/provider-http/src/adaptive-rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

Expand All @@ -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,
};

Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/pages/ProviderDetailPage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, renderHook, screen } from "@testing-library/react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { formatCellValue, formatColumnName, RecordDetailModal } from "./ProviderDetailPage";
Expand Down
30 changes: 30 additions & 0 deletions src/jobs/enqueue-sync-job.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ describe("enqueueSyncJob", () => {
userId: null,
expiresAt: new Date("2026-06-02T12:10:00Z"),
};
mockGetActive.mockResolvedValue(cooldown);

const retryAt = await scheduleDelayedSyncJob(
{
Expand Down Expand Up @@ -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 }),
Expand Down
19 changes: 11 additions & 8 deletions src/jobs/enqueue-sync-job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
42 changes: 41 additions & 1 deletion src/jobs/process-scheduled-sync-job.test.ts
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -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;
Expand Down Expand Up @@ -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)",
);
});
});
17 changes: 16 additions & 1 deletion src/jobs/process-scheduled-sync-job.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand All @@ -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,
Expand All @@ -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)` : ""),
);
}
6 changes: 3 additions & 3 deletions src/jobs/process-sync-job.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/jobs/provider-queue-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
2 changes: 1 addition & 1 deletion src/jobs/provider-queue-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })],
Expand Down
Loading
Loading