From 3b1cdd7a1f980540c41c41d4ab048679c0d61f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Wed, 21 Oct 2026 12:51:19 +0200 Subject: [PATCH] fix(strava): keep a rate-limited run's progress and a summary-only row's calories A 429 in the middle of the activity walk threw out of it before the upsert, so everything the run had read was discarded and the next run started over. The walk now ends where the limit hit: what was read lands, the cursor moves only as far as an oldest-first walk proves, the failure is booked transient, and the run reports the wait Strava's X-RateLimit / X-ReadRateLimit headers name (next quarter hour, or midnight UTC once the daily count is spent). The backfill waits that long before its next run. `walkPages` learns an `interrupted` page for this, reported truncated like a walk cut off at its ceiling. An update mapped from the summary alone (detail budget spent, or the detail read failed) wrote a null over the calories an earlier detail read had stored, and over its heart rate and description too. Those detail-only fields are now kept unless this run read the detail. --- src/lib/integrations/page-walk.ts | 12 +- src/lib/jobs/strava-backfill.ts | 23 +- .../strava/__tests__/sync-rate-limit.test.ts | 279 ++++++++++++++++++ src/lib/strava/client.ts | 51 ++++ src/lib/strava/response-classifier.ts | 16 +- src/lib/strava/sync.ts | 140 +++++++-- 6 files changed, 491 insertions(+), 30 deletions(-) create mode 100644 src/lib/strava/__tests__/sync-rate-limit.test.ts diff --git a/src/lib/integrations/page-walk.ts b/src/lib/integrations/page-walk.ts index b8b92f451..e05e8cf89 100644 --- a/src/lib/integrations/page-walk.ts +++ b/src/lib/integrations/page-walk.ts @@ -49,6 +49,13 @@ import { annotate } from "@/lib/logging/context"; export interface WalkPage { items: readonly T[]; next: C | null | undefined; + /** + * The provider refused to go on for now (a rate limit) with history left. + * The walk ends here with what it read, reported `truncated` like a walk + * cut off at its ceiling, so a backfill resumes later instead of stamping + * a history it did not finish. + */ + interrupted?: boolean; } /** What the walk came to. */ @@ -78,6 +85,9 @@ export async function walkPages( for (let page = 0; page < maxPages; page += 1) { const result = await fetchPage(cursor, page); items.push(...result.items); + if (result.interrupted) { + return truncated(label, items, page + 1, "interrupted"); + } const next = result.next; if (next === null || next === undefined || next === "") { return { items, pages: page + 1, truncated: false }; @@ -93,7 +103,7 @@ function truncated( label: string, items: T[], pages: number, - reason: "ceiling" | "repeat", + reason: "ceiling" | "repeat" | "interrupted", ): PageWalk { annotate({ action: { name: "integration.page_walk.truncated" }, diff --git a/src/lib/jobs/strava-backfill.ts b/src/lib/jobs/strava-backfill.ts index 5c36fc905..10bb6dd21 100644 --- a/src/lib/jobs/strava-backfill.ts +++ b/src/lib/jobs/strava-backfill.ts @@ -93,7 +93,7 @@ export async function runStravaBackfillForUser( const { result, truncated } = await withPageWalkLedger(() => syncStravaHistory(userId, before), ); - const { imported, oldestStart } = result; + const { imported, oldestStart, retryAfterSeconds } = result; // A failure has already thrown; what is left to decide is whether the walk // reached the beginning of the history. if (backfillVerdict({ failed: false, truncated }) === "incomplete") { @@ -111,7 +111,18 @@ export async function runStravaBackfillForUser( data: { stravaBackfillResumeBefore: resumeBefore }, }); } - const continued = progressed && (await sendNextRun(userId, slice)); + // A run Strava's rate limit ended goes on once the window it named has + // reset, progress or not: the limit is the app's, and passes. + const continued = + (progressed || retryAfterSeconds !== undefined) && + (await sendNextRun( + userId, + slice, + Math.max( + STRAVA_BACKFILL_CONTINUATION_DELAY_SECONDS, + retryAfterSeconds ?? 0, + ), + )); annotate({ action: { name: "strava.backfill.truncated", @@ -143,7 +154,11 @@ export async function runStravaBackfillForUser( return { imported, continued: false }; } -async function sendNextRun(userId: string, slice: number): Promise { +async function sendNextRun( + userId: string, + slice: number, + delaySeconds: number, +): Promise { const boss = getGlobalBoss(); if (!boss) return false; const sent = await enqueueIntegrationBackfillAdmission( @@ -152,7 +167,7 @@ async function sendNextRun(userId: string, slice: number): Promise { kind: "strava-backfill", data: { userId, enqueuedAt: new Date().toISOString(), slice: slice + 1 }, }, - STRAVA_BACKFILL_CONTINUATION_DELAY_SECONDS, + delaySeconds, ); return Boolean(sent); } diff --git a/src/lib/strava/__tests__/sync-rate-limit.test.ts b/src/lib/strava/__tests__/sync-rate-limit.test.ts new file mode 100644 index 000000000..08e5aede8 --- /dev/null +++ b/src/lib/strava/__tests__/sync-rate-limit.test.ts @@ -0,0 +1,279 @@ +/** + * Strava's rate limit and its detail budget. + * + * - A 429 mid-walk used to discard everything the run had read: the error + * threw out of the walk before the upsert. The activities read before it + * land now, the cursor moves only as far as an oldest-first walk proves + * safe, the failure is booked as transient, and the backfill waits for + * the window Strava's headers name before it goes on. + * - An update mapped from the summary alone (detail budget spent, or a + * detail read that failed) wrote `totalEnergyKcal: null` over the + * calories an earlier detail read had stored. The fields only the detail + * carries are kept when this run did not read it. + */ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + fetchActivities: vi.fn(), + fetchActivityById: vi.fn(), + annotate: vi.fn(), + findUser: vi.fn(), + updateUser: vi.fn(), + updateManyUser: vi.fn(async (_arg: unknown) => ({ count: 1 })), + createManyAndReturn: vi.fn(), + updateWorkout: vi.fn(async (_arg: { data: Record }) => ({})), + findWorkout: vi.fn(), + recordSyncFailure: vi.fn(async () => {}), + recordSyncSuccess: vi.fn(async () => {}), + isReauthRequired: vi.fn(async () => false), + send: vi.fn(async (..._args: unknown[]) => "job-next"), +})); + +vi.mock("@/lib/db", () => ({ + prisma: { + user: { + findUnique: mocks.findUser, + updateMany: mocks.updateManyUser, + update: mocks.updateUser, + }, + workout: { + createManyAndReturn: mocks.createManyAndReturn, + update: mocks.updateWorkout, + findUnique: mocks.findWorkout, + }, + }, +})); +vi.mock("@/lib/arrivals/workout-emit", () => ({ + emitInsertedWorkoutArrival: vi.fn(async () => {}), +})); +vi.mock("@/lib/cache/invalidate", () => ({ + invalidateUserMeasurements: vi.fn(), +})); +vi.mock("@/lib/logging/context", () => ({ + annotate: mocks.annotate, + getEvent: () => ({ addWarning: vi.fn(), addExternalCall: vi.fn() }), +})); +vi.mock("@/lib/integrations/status", async (importOriginal) => ({ + ...(await importOriginal()), + recordSyncFailure: mocks.recordSyncFailure, + recordSyncSuccess: mocks.recordSyncSuccess, + isReauthRequired: mocks.isReauthRequired, +})); +vi.mock("../credentials", () => ({ + getStravaConnection: vi.fn(async () => ({ + accessToken: "access-token", + refreshToken: "refresh-token", + refreshTokenCiphertext: Buffer.from("ciphertext"), + })), + getStravaClientCredentials: vi.fn(), + storeStravaTokens: vi.fn(), +})); +vi.mock("../client", async (importOriginal) => ({ + ...(await importOriginal()), + fetchActivities: mocks.fetchActivities, + fetchActivityById: mocks.fetchActivityById, +})); +vi.mock("@/lib/jobs/boss-instance", () => ({ + getGlobalBoss: vi.fn(() => ({ send: mocks.send })), +})); + +import { runStravaBackfillForUser } from "@/lib/jobs/strava-backfill"; +import { StravaApiError } from "../response-classifier"; +import { stravaRateLimitRetryAfterSeconds } from "../client"; +import { syncUserStrava } from "../sync"; + +const HOUR = 3_600_000; +const T0 = Date.UTC(2026, 9, 1); + +function activity(id: number) { + return { + id, + sport_type: "Run", + start_date: new Date(T0 + id * HOUR).toISOString(), + moving_time: 1800, + elapsed_time: 1900, + average_heartrate: 140, + }; +} + +function rateLimited(retryAfterSeconds: number): StravaApiError { + return new StravaApiError({ + verb: "fetchActivities", + classification: "transient", + httpStatus: 429, + reason: "http_429", + retryAfterSeconds, + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.findUser.mockResolvedValue({ + stravaLastActivityAt: new Date(T0), + stravaBackfillResumeBefore: null, + }); + mocks.createManyAndReturn.mockImplementation( + async ({ data }: { data: { externalId: string; startedAt: Date } }) => [ + { id: `w-${data.externalId}`, startedAt: data.startedAt }, + ], + ); + mocks.fetchActivityById.mockImplementation( + async (_t: string, id: number) => ({ + ...activity(id), + calories: 300, + }), + ); +}); + +describe("a 429 in the middle of a walk", () => { + it("keeps what was read, moves the cursor an oldest-first walk proves, and books it transient", async () => { + // An incremental walk (`after` set): Strava answers oldest first. Three + // activities read, then the detail read of the fourth is refused. + mocks.fetchActivities.mockResolvedValue([1, 2, 3, 4, 5].map(activity)); + mocks.fetchActivityById.mockImplementation( + async (_t: string, id: number) => { + if (id === 4) throw rateLimited(600); + return { ...activity(id), calories: 300 }; + }, + ); + + await expect(syncUserStrava("user-1")).resolves.toBe(3); + + expect(mocks.createManyAndReturn).toHaveBeenCalledTimes(3); + expect(mocks.updateManyUser).toHaveBeenCalledWith( + expect.objectContaining({ + data: { stravaLastActivityAt: new Date(T0 + 3 * HOUR) }, + }), + ); + expect(mocks.recordSyncFailure).toHaveBeenCalledWith( + expect.objectContaining({ kind: "transient", errorCode: "429" }), + ); + expect(mocks.recordSyncSuccess).not.toHaveBeenCalled(); + }); + + it("does not move the cursor past a newest-first walk it did not finish", async () => { + mocks.fetchActivities.mockResolvedValue([9, 8, 7].map(activity)); + mocks.fetchActivityById.mockImplementation( + async (_t: string, id: number) => { + if (id === 7) throw rateLimited(600); + return { ...activity(id), calories: 300 }; + }, + ); + + await expect(syncUserStrava("user-1")).resolves.toBe(2); + expect(mocks.updateManyUser).not.toHaveBeenCalled(); + }); + + it("sends the next backfill run after the window Strava named", async () => { + // A history walk (no `after`): newest first, refused on the second page. + mocks.fetchActivities.mockImplementation( + async (_t: string, q: { page: number }) => { + if (q.page === 2) throw rateLimited(5400); + return Array.from({ length: 100 }, (_, i) => activity(500 - i)); + }, + ); + + const run = await runStravaBackfillForUser("user-1"); + + expect(run).toEqual({ imported: 100, continued: true }); + expect(mocks.updateUser).toHaveBeenCalledWith({ + where: { id: "user-1" }, + data: { + stravaBackfillResumeBefore: new Date(T0 + 401 * HOUR + 1000), + }, + }); + const [, , options] = mocks.send.mock.calls[0] as unknown as [ + string, + unknown, + { startAfter?: number }, + ]; + expect(options.startAfter).toBe(5400); + expect(mocks.updateUser).not.toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + stravaBackfillCompletedAt: expect.any(Date), + }), + }), + ); + }); +}); + +describe("an update without the detail read", () => { + it("keeps the stored calories, heart rate and description", async () => { + // The row exists already; this run reads only the summary (no HR on it) + // because the detail read failed. + mocks.createManyAndReturn.mockResolvedValue([]); + mocks.fetchActivities.mockResolvedValue([ + { ...activity(1), average_heartrate: undefined }, + ]); + mocks.fetchActivityById.mockRejectedValue(new Error("detail down")); + mocks.findWorkout.mockResolvedValue({ + metadata: { stravaName: "old", stravaDescription: "Hill reps" }, + }); + + await syncUserStrava("user-1"); + + const data = mocks.updateWorkout.mock.calls[0]![0].data as Record< + string, + unknown + >; + expect(data).not.toHaveProperty("totalEnergyKcal"); + expect(data).not.toHaveProperty("avgHeartRate"); + expect(data).not.toHaveProperty("maxHeartRate"); + expect(data.metadata).toMatchObject({ stravaDescription: "Hill reps" }); + expect(data.durationSec).toBe(1800); + }); + + it("writes what a detail read returned, nulls included", async () => { + mocks.createManyAndReturn.mockResolvedValue([]); + mocks.fetchActivities.mockResolvedValue([activity(1)]); + mocks.fetchActivityById.mockResolvedValue({ + ...activity(1), + calories: null, + }); + + await syncUserStrava("user-1"); + + const data = mocks.updateWorkout.mock.calls[0]![0].data as Record< + string, + unknown + >; + expect(data.totalEnergyKcal).toBeNull(); + expect(mocks.findWorkout).not.toHaveBeenCalled(); + }); +}); + +describe("stravaRateLimitRetryAfterSeconds", () => { + const at = new Date("2026-10-21T10:07:30Z"); + + it("waits for the next quarter hour when the short window is spent", () => { + const headers = new Headers({ + "X-RateLimit-Limit": "200,2000", + "X-RateLimit-Usage": "200,950", + }); + expect(stravaRateLimitRetryAfterSeconds(headers, at)).toBe(450); + }); + + it("waits for midnight UTC when the daily limit is spent", () => { + const headers = new Headers({ + "X-ReadRateLimit-Limit": "100,1000", + "X-ReadRateLimit-Usage": "40,1000", + }); + expect(stravaRateLimitRetryAfterSeconds(headers, at)).toBe( + 13 * 3600 + 52 * 60 + 30, + ); + }); + + it("honours a Retry-After header when one is sent", () => { + expect( + stravaRateLimitRetryAfterSeconds( + new Headers({ "Retry-After": "120" }), + at, + ), + ).toBe(120); + }); + + it("falls back to the next quarter hour without any header", () => { + expect(stravaRateLimitRetryAfterSeconds(new Headers(), at)).toBe(450); + }); +}); diff --git a/src/lib/strava/client.ts b/src/lib/strava/client.ts index a5407f915..3bc4d1f5d 100644 --- a/src/lib/strava/client.ts +++ b/src/lib/strava/client.ts @@ -258,11 +258,54 @@ async function stravaGet( classification: verdict.classification, httpStatus: verdict.httpStatus, reason: verdict.reason, + ...(res.status === 429 + ? { retryAfterSeconds: stravaRateLimitRetryAfterSeconds(res.headers) } + : {}), }); } return (await res.json().catch(() => null)) as T; } +const QUARTER_HOUR_MS = 15 * 60 * 1000; +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * How long to wait after a 429, from the response's own headers. Strava sends + * no `Retry-After` (one is honoured should it appear); it sends + * `X-RateLimit-Limit` / `X-RateLimit-Usage` and, for reads, + * `X-ReadRateLimit-Limit` / `X-ReadRateLimit-Usage`, each `<15-min>,`. + * The 15-minute window resets at :00, :15, :30 and :45, the daily one at + * midnight UTC (developers.strava.com/docs/rate-limits). A spent daily count + * waits for midnight; anything else, the next quarter hour. + */ +export function stravaRateLimitRetryAfterSeconds( + headers: Headers, + now: Date = new Date(), +): number { + const retryAfter = Number(headers.get("retry-after")); + if (Number.isFinite(retryAfter) && retryAfter > 0) { + return Math.ceil(retryAfter); + } + const pair = (name: string): [number, number] | null => { + const parts = (headers.get(name) ?? "").split(",").map(Number); + return parts.length === 2 && parts.every(Number.isFinite) + ? [parts[0]!, parts[1]!] + : null; + }; + const dailySpent = (limitName: string, usageName: string): boolean => { + const limit = pair(limitName); + const usage = pair(usageName); + return limit !== null && usage !== null && usage[1] >= limit[1]; + }; + const nowMs = now.getTime(); + const resetAt = + dailySpent("x-ratelimit-limit", "x-ratelimit-usage") || + dailySpent("x-readratelimit-limit", "x-readratelimit-usage") + ? Math.floor(nowMs / DAY_MS) * DAY_MS + DAY_MS + : Math.floor(nowMs / QUARTER_HOUR_MS) * QUARTER_HOUR_MS + QUARTER_HOUR_MS; + return Math.max(1, Math.ceil((resetAt - nowMs) / 1000)); +} + /** One page of the athlete's activities (newest first). */ export async function fetchActivities( accessToken: string, @@ -312,6 +355,13 @@ export interface StravaWorkoutRow { maxHeartRate: number | null; elevationM: number | null; metadata: Prisma.InputJsonValue; + /** + * True when the row was mapped from the summary alone. The calories, the + * description and (when the summary lacks it) the heart rate exist only on + * the detail read, so an update from such a row must not write their + * absence over what an earlier detail read stored. + */ + summaryOnly?: boolean; } function nonNegInt(n: number | null | undefined): number | null { @@ -414,6 +464,7 @@ export function mapActivity( summary.total_elevation_gain ?? detail?.total_elevation_gain, ), metadata, + summaryOnly: detail == null, }; } diff --git a/src/lib/strava/response-classifier.ts b/src/lib/strava/response-classifier.ts index 57f5c81fc..bae3bcf70 100644 --- a/src/lib/strava/response-classifier.ts +++ b/src/lib/strava/response-classifier.ts @@ -28,18 +28,32 @@ export function classifyStravaResponse( } export class StravaApiError extends IntegrationApiError { + /** + * On a 429: how long Strava's own headers say to wait before asking again + * (`stravaRateLimitRetryAfterSeconds`). Undefined on every other failure. + */ + readonly retryAfterSeconds: number | undefined; + constructor(opts: { verb: string; classification: IntegrationClassification; httpStatus: number | undefined; reason: string; upstreamError?: string; + retryAfterSeconds?: number; }) { - super({ vendor: "Strava", ...opts }); + const { retryAfterSeconds, ...rest } = opts; + super({ vendor: "Strava", ...rest }); this.name = "StravaApiError"; + this.retryAfterSeconds = retryAfterSeconds; } } +/** True for Strava's rate-limit refusal. */ +export function isStravaRateLimited(err: unknown): err is StravaApiError { + return err instanceof StravaApiError && err.httpStatus === 429; +} + /** * True when a caught error is an OAuth `invalid_grant` on the token endpoint — * the canonical revoked / rotated-away refresh-token signal. Lifts a 400 diff --git a/src/lib/strava/sync.ts b/src/lib/strava/sync.ts index 7405530d0..35752d1b3 100644 --- a/src/lib/strava/sync.ts +++ b/src/lib/strava/sync.ts @@ -21,10 +21,14 @@ * Rate limits: 200 req / 15 min + 2000 / day per app. The walk is page-bounded * (`walkPages`, which reports a walk cut off at its ceiling instead of * passing it off as the whole history) and the per-activity detail fetch (for `calories`, absent from the summary) - * is budget-capped; a 429 mid-walk records a transient failure and the next - * cron tick resumes from the cursor. + * is budget-capped. A 429 mid-walk ends the walk where it stands: what was + * read lands, the cursor moves only as far as an oldest-first walk proves, the + * failure is booked transient, and the run reports how long Strava's headers + * say to wait (`retryAfterSeconds`), which the backfill waits out before its + * next run. It used to throw out of the walk and discard everything read. */ import { prisma } from "@/lib/db"; +import type { Prisma } from "@/generated/prisma/client"; import { emitInsertedWorkoutArrival } from "@/lib/arrivals/workout-emit"; import { invalidateUserMeasurements } from "@/lib/cache/invalidate"; import { annotate, getEvent } from "@/lib/logging/context"; @@ -50,7 +54,11 @@ import { getStravaConnection, storeStravaTokens, } from "./credentials"; -import { StravaApiError, classifyStravaError } from "./response-classifier"; +import { + StravaApiError, + classifyStravaError, + isStravaRateLimited, +} from "./response-classifier"; /** Default first-incremental lookback (days) when no cursor exists yet. */ export const STRAVA_SYNC_LOOKBACK_DAYS = 30; @@ -115,6 +123,8 @@ export interface StravaHistoryRun { * expect. */ oldestStart: Date | null; + /** Set when Strava's rate limit ended the run: seconds until it resets. */ + retryAfterSeconds?: number; } /** @@ -203,6 +213,9 @@ async function runStravaSync( let oldestStart: Date | null = null; let previousStart: number | null = null; let newestFirst = true; + // Assigned inside the page callback; the cast keeps the compiler from + // narrowing it to its initial `null` after the walk. + let rateLimited = null as StravaApiError | null; try { // Strava pages by number; a short page is the last one. A walk that @@ -213,29 +226,37 @@ async function runStravaSync( maxPages, async (cursor) => { const page = cursor ?? 1; - const activities = await authed((t) => - fetchActivities(t, { - after: afterEpoch, - before: beforeEpoch, - page, - perPage: PER_PAGE, - }), - ); + let activities: Awaited>; + try { + activities = await authed((t) => + fetchActivities(t, { + after: afterEpoch, + before: beforeEpoch, + page, + perPage: PER_PAGE, + }), + ); + } catch (err) { + if (!isStravaRateLimited(err)) throw err; + rateLimited = err; + return { items: [], next: null, interrupted: true }; + } const mapped: StravaWorkoutRow[] = []; for (const a of activities) { // Fetch detail only to fill `calories` (absent from the summary), // and only while the budget allows. When the summary already lacks // HR we also let the detail top it up. A detail failure is - // non-fatal — map from the summary — but a 429 aborts the whole - // walk (transient). + // non-fatal — map from the summary — but a 429 ends the walk here, + // keeping the activities before this one. let detail: StravaDetailedActivity | null = null; if (detailBudget > 0) { try { detail = await authed((t) => fetchActivityById(t, a.id)); detailBudget -= 1; } catch (err) { - if (err instanceof StravaApiError && err.httpStatus === 429) { - throw err; + if (isStravaRateLimited(err)) { + rateLimited = err; + return { items: mapped, next: null, interrupted: true }; } getEvent()?.addWarning( `strava: activity detail fetch failed for ${a.id}: ${err}`, @@ -277,6 +298,12 @@ async function runStravaSync( throw markSyncFailureRecorded(err); } + // A walk the rate limit ended is a prefix of the pages in the order Strava + // served them. Oldest first (an incremental walk), every activity up to the + // newest one read is in; newest first, older ones are still missing, and + // moving the cursor would skip them for good. + const cursorSafe = rateLimited === null || !newestFirst; + let imported: number; try { imported = await upsertStravaWorkouts(userId, rows); @@ -284,7 +311,7 @@ async function runStravaSync( // Advance the incremental cursor to the newest activity start we saw, but // never move it backwards (a bounded backfill page-walk may not reach the // very newest activity in one pass). - if (newestStart) { + if (newestStart && cursorSafe) { await prisma.user.updateMany({ where: { id: userId, @@ -301,6 +328,26 @@ async function runStravaSync( throw markSyncFailureRecorded(err); } + if (rateLimited) { + // Not finished, so no success; booked transient, the next run goes on. + await recordStravaFailure(userId, rateLimited); + if (imported > 0) invalidateUserMeasurements(userId); + annotate({ + action: { + name: "strava.sync.rate_limited", + details: { + imported, + retry_after_seconds: rateLimited.retryAfterSeconds ?? null, + }, + }, + }); + return { + imported, + oldestStart: newestFirst ? oldestStart : null, + retryAfterSeconds: rateLimited.retryAfterSeconds, + }; + } + await recordSyncSuccess(userId, "strava"); // Background-sync posture: sweep the workouts cache and mark the analytics @@ -316,6 +363,42 @@ async function runStravaSync( return { imported, oldestStart: newestFirst ? oldestStart : null }; } +/** + * The update for a row mapped from the summary alone. Calories, the + * description and (when the summary has none) the heart rate come only from + * the detail read, so their absence here says nothing: the stored values stay. + * A detail read that did run is written as it came, nulls included. + */ +async function summaryOnlyUpdate< + D extends { + totalEnergyKcal: number | null; + avgHeartRate: number | null; + maxHeartRate: number | null; + metadata: Prisma.InputJsonValue; + }, +>(data: D, stored: { metadata: Prisma.JsonValue } | null) { + const { totalEnergyKcal, avgHeartRate, maxHeartRate, metadata, ...rest } = + data; + const storedMeta = + stored?.metadata && typeof stored.metadata === "object" + ? (stored.metadata as Record) + : {}; + const description = storedMeta.stravaDescription; + return { + ...rest, + ...(totalEnergyKcal != null ? { totalEnergyKcal } : {}), + ...(avgHeartRate != null ? { avgHeartRate } : {}), + ...(maxHeartRate != null ? { maxHeartRate } : {}), + metadata: + typeof description === "string" + ? ({ + ...(metadata as Record), + stravaDescription: description, + } as Prisma.InputJsonValue) + : metadata, + }; +} + /** * Upsert a batch of mapped Strava activities into `Workout`, keyed on * `(userId, source = STRAVA, externalId)` so a re-fetch overwrites in place. @@ -362,15 +445,24 @@ export async function upsertStravaWorkouts( () => {}, ); } else { - await prisma.workout.update({ - where: { - userId_source_externalId: { - userId, - source: "STRAVA", - externalId: r.externalId, - }, + const where = { + userId_source_externalId: { + userId, + source: "STRAVA" as const, + externalId: r.externalId, }, - data, + }; + await prisma.workout.update({ + where, + data: r.summaryOnly + ? await summaryOnlyUpdate( + data, + await prisma.workout.findUnique({ + where, + select: { metadata: true }, + }), + ) + : data, }); } imported += 1;