diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index a3d7119aa5..50b010418f 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -12880,3 +12880,58 @@ Drizzle schema and runtime Zod schemas. Findings and remediations: summary rebuild still exceeds the local ClickHouse 3 GiB memory limit on the recursive activity de-duplication CTE, so hosted CI remains the source of truth for the full Stryker matrix. + +## 2026-07-13 — Garmin Dump Import Stalled After Worker OOM + +- **Symptoms:** BullMQ import job `5`, name `garmin-dump`, failed with + `job stalled more than allowable limit`. +- **User impact:** The Garmin account export import did not complete. Prior + Garmin dump import jobs `2`, `3`, and `4` had the same BullMQ failure reason. +- **Evidence:** Redis stream `bull:import:events` showed job `5` added and made + active at `2026-07-13T20:54:30.592Z`, stalled at + `2026-07-13T21:05:04.748Z`, became active again, then stalled and failed at + `2026-07-13T21:15:24.496Z`; Redis documents `XRANGE` as the command for + reading stream entries by ID range + ([Redis XRANGE](https://redis.io/docs/latest/commands/xrange/)). The worker container + `dofek_worker.1.0exqzy2t768r9kfpmtbar0c0a` ran from + `2026-07-13T20:59:55.719Z` to `2026-07-13T21:05:09.463Z` with + `Exit=137` and `OOMKilled=true`, as reported by `docker inspect` + ([Docker inspect CLI](https://docs.docker.com/reference/cli/docker/inspect/)). The uploaded Garmin dump ZIP remained in + `/app/job-files`, was about 48 MiB, had 111 top-level entries and about + 78.5 MiB top-level uncompressed data, and contained two + `DI_CONNECT/DI-Connect-Uploaded-Files/*Part1.zip` nested ZIPs. Each nested ZIP + contained 7,887 FIT files totaling about 44 MiB uncompressed. +- **Root cause:** `src/providers/garmin-dump.ts` previously read the full uploaded ZIP + into memory, recursively buffered every extracted entry into arrays, including + unrelated Garmin account-export payloads and both large nested uploaded-file + ZIPs, and only extended the BullMQ import-job lock with a one-shot 10-minute + extension. The 48 MiB export expanded into thousands of buffered FIT entries + inside the 400 MiB worker container while the same process was also running + other provider workers. The first attempt was OOM-killed, which stopped lock + renewal. The retry again exceeded the one-shot lock window and BullMQ failed + the job after the second stall; BullMQ documents that jobs rely on worker lock + renewal and can be marked stalled, retried, and eventually failed when the + lock is not renewed + ([BullMQ stalled jobs](https://docs.bullmq.io/guide/workers/stalled-jobs)). +- **Fix / mitigation:** Updated Garmin dump parsing to open ZIP files from the + filesystem, skip irrelevant Garmin export entries before opening their + streams, spill selected summary entries to temporary files under the job-files + volume, and create a BullMQ flow for selected FIT files. The flow uses a + generic ZIP-entry extraction job to materialize entry paths to files, ZIP- + agnostic FIT import child jobs to process those files, and a batch parent job + to aggregate child results. The import job lock is now renewed periodically + during the long-running import instead of relying only on a one-shot 10-minute + extension. BullMQ documents flows as parent-child job trees where parent jobs + wait for child jobs to finish before processing + ([BullMQ flows](https://docs.bullmq.io/guide/flows)). +- **Validation:** Docker inspect confirmed the OOM kill, Redis import events + confirmed the two-stall/fail timeline, queue inspection showed no + `fit-file-import` jobs were active/failed at investigation time, and ZIP + inspection confirmed the nested uploaded-file FIT volume. Regression coverage + now verifies selective filesystem-backed Garmin parsing, one-flow FIT fan-out, + generic nested ZIP-entry extraction, FIT import resolution from flow child + results, batch result aggregation, queue resource caching, and worker + registration for the new queues. +- **Remaining risk / follow-up:** Medium until deployed and tested against the + original production Garmin dump. Increasing the worker memory limit alone + would still be a mitigation knob, not the root fix. diff --git a/src/jobs/process-fit-file-import-batch-job.test.ts b/src/jobs/process-fit-file-import-batch-job.test.ts new file mode 100644 index 0000000000..9991515b25 --- /dev/null +++ b/src/jobs/process-fit-file-import-batch-job.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { processFitFileImportBatchJob } from "./process-fit-file-import-batch-job.ts"; + +describe("processFitFileImportBatchJob", () => { + it("aggregates records and errors from child FIT import jobs", async () => { + const result = await processFitFileImportBatchJob({ + getChildrenValues: async () => ({ + "bull:fit-file-import:1": { recordsSynced: 2, errors: [] }, + "bull:fit-file-import:2": { + recordsSynced: 1, + errors: [{ message: "bad fit" }], + }, + }), + }); + + expect(result).toEqual({ + recordsSynced: 3, + errors: [{ message: "bad fit" }], + }); + }); + + it("returns an empty result when the batch has no child values", async () => { + const result = await processFitFileImportBatchJob({ + getChildrenValues: async () => ({}), + }); + + expect(result).toEqual({ recordsSynced: 0, errors: [] }); + }); + + it("rejects malformed child results", async () => { + await expect( + processFitFileImportBatchJob({ + getChildrenValues: async () => ({ + "bull:fit-file-import:1": { recordsSynced: "2", errors: [] }, + }), + }), + ).rejects.toThrow(); + }); +}); diff --git a/src/jobs/process-fit-file-import-batch-job.ts b/src/jobs/process-fit-file-import-batch-job.ts new file mode 100644 index 0000000000..cab62c5ad1 --- /dev/null +++ b/src/jobs/process-fit-file-import-batch-job.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; +import type { FitFileImportJobResult } from "./process-fit-file-import-job.ts"; + +interface FitFileImportBatchJob { + getChildrenValues: () => Promise>; +} + +const fitFileImportJobResultSchema = z.object({ + recordsSynced: z.number(), + errors: z.array(z.object({ message: z.string() })), +}); + +export async function processFitFileImportBatchJob( + job: FitFileImportBatchJob, +): Promise { + const childValues = await job.getChildrenValues(); + const results = Object.values(childValues).map((value) => + fitFileImportJobResultSchema.parse(value), + ); + + return { + recordsSynced: results.reduce((total, result) => total + result.recordsSynced, 0), + errors: results.flatMap((result) => result.errors), + }; +} diff --git a/src/jobs/process-fit-file-import-job.test.ts b/src/jobs/process-fit-file-import-job.test.ts index 61ec48c5ce..2d66f575cd 100644 --- a/src/jobs/process-fit-file-import-job.test.ts +++ b/src/jobs/process-fit-file-import-job.test.ts @@ -162,42 +162,94 @@ describe("processFitFileImportJob", () => { ); }); - it("rejects invalid queue payloads before reading a file", async () => { - await expect( - processFitFileImportJob( - createFitFileImportJob({ - originalPath: "DI_CONNECT/activity.fit", - userId: "user-1", - providerId: "garmin-dump", - sourceName: "Garmin Dump", - }), - mockDb, - ), - ).rejects.toThrow(); + it("returns an error result for jobs without a file path or extraction child", async () => { + const result = await processFitFileImportJob( + createFitFileImportJob({ + originalPath: "DI_CONNECT/activity.fit", + userId: "user-1", + providerId: "garmin-dump", + sourceName: "Garmin Dump", + }), + mockDb, + ); + expect(result).toEqual({ + recordsSynced: 0, + errors: [ + { + message: + "Failed to import FIT file DI_CONNECT/activity.fit: FIT import job is missing filePath and has no child extraction result", + }, + ], + }); expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); expect(mockUpsertProviderActivity).not.toHaveBeenCalled(); + expect(mockCaptureException).toHaveBeenCalledWith(expect.any(Error), { + tags: { fitImportStep: "process" }, + extra: { originalPath: "DI_CONNECT/activity.fit" }, + }); }); - it("cleans up temp files when queue payload validation fails", async () => { + it("cleans up temp files when queue payload validation returns an error result", async () => { const filePath = await writeTempFit(createActivityFit()); - await expect( - processFitFileImportJob( - createFitFileImportJob({ - filePath, - originalPath: "DI_CONNECT/activity.fit", - userId: "user-1", - providerId: "garmin-dump", - }), - mockDb, - ), - ).rejects.toThrow(); + const result = await processFitFileImportJob( + createFitFileImportJob({ + filePath, + originalPath: "DI_CONNECT/activity.fit", + userId: "user-1", + providerId: "garmin-dump", + }), + mockDb, + ); + expect(result.recordsSynced).toBe(0); + expect(result.errors[0]?.message).toContain( + "Failed to import FIT file DI_CONNECT/activity.fit:", + ); expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); await expect(readFile(filePath)).rejects.toThrow(); }); + it("reports cleanup failures to Sentry", async () => { + const directory = await mkdtemp(join(tmpdir(), "fit-file-import-cleanup-failure-test-")); + createdDirectories.push(directory); + + const result = await processFitFileImportJob( + createFitFileImportJob({ + filePath: directory, + originalPath: "DI_CONNECT/activity.fit", + userId: "user-1", + providerId: "garmin-dump", + sourceName: "Garmin Dump", + }), + mockDb, + ); + + expect(result.recordsSynced).toBe(0); + expect(result.errors[0]?.message).toContain( + "Failed to import FIT file DI_CONNECT/activity.fit:", + ); + expect(mockCaptureException).toHaveBeenCalledWith(expect.any(Error), { + tags: { fitImportStep: "cleanup" }, + extra: { path: directory }, + }); + }); + + it("keeps originalPath for error messages when job data has extra fields", async () => { + const result = await processFitFileImportJob( + createFitFileImportJob({ + originalPath: "DI_CONNECT/activity.fit", + ignored: "extra", + }), + mockDb, + ); + + expect(result.errors[0]?.message).toContain( + "Failed to import FIT file DI_CONNECT/activity.fit:", + ); + }); + it("imports an activity FIT file with a parent summary and replaces sensor samples", async () => { const filePath = await writeTempFit(createActivityFit()); @@ -321,6 +373,86 @@ describe("processFitFileImportJob", () => { ); }); + it("imports a FIT file from a flow child extraction result", async () => { + const filePath = await writeTempFit(createActivityFit()); + const getChildrenValues = vi.fn().mockResolvedValue({ + "bull:zip-entry-extract:1": { filePath }, + }); + + const result = await processFitFileImportJob( + { + data: { + originalPath: "DI_CONNECT/asher@example.com_activity.fit", + userId: "user-1", + providerId: "garmin-dump", + sourceName: "Garmin Dump", + }, + getChildrenValues, + updateProgress: vi.fn().mockResolvedValue(undefined), + }, + mockDb, + ); + + expect(result).toEqual({ recordsSynced: 1, errors: [] }); + expect(getChildrenValues).toHaveBeenCalledOnce(); + expect(mockUpsertProviderActivity).toHaveBeenCalledOnce(); + await expect(readFile(filePath)).rejects.toThrow(); + }); + + it("cleans up flow child extraction files when job data validation fails", async () => { + const filePath = await writeTempFit(createActivityFit()); + + const result = await processFitFileImportJob( + { + data: { + originalPath: "DI_CONNECT/asher@example.com_activity.fit", + userId: "user-1", + sourceName: "Garmin Dump", + }, + getChildrenValues: async () => ({ + "bull:zip-entry-extract:1": { filePath }, + }), + updateProgress: vi.fn().mockResolvedValue(undefined), + }, + mockDb, + ); + + expect(result.recordsSynced).toBe(0); + expect(result.errors[0]?.message).toContain( + "Failed to import FIT file DI_CONNECT/asher@example.com_activity.fit:", + ); + await expect(readFile(filePath)).rejects.toThrow(); + }); + + it("returns an error result for FIT flow jobs with multiple extraction results", async () => { + const result = await processFitFileImportJob( + { + data: { + originalPath: "DI_CONNECT/asher@example.com_activity.fit", + userId: "user-1", + providerId: "garmin-dump", + sourceName: "Garmin Dump", + }, + getChildrenValues: async () => ({ + "bull:zip-entry-extract:1": { filePath: "/tmp/one.fit" }, + "bull:zip-entry-extract:2": { filePath: "/tmp/two.fit" }, + }), + updateProgress: vi.fn().mockResolvedValue(undefined), + }, + mockDb, + ); + + expect(result).toEqual({ + recordsSynced: 0, + errors: [ + { + message: + "Failed to import FIT file DI_CONNECT/asher@example.com_activity.fit: FIT import job expected 1 child extraction result, got 2", + }, + ], + }); + }); + it("extracts numeric activity IDs from FIT file names", async () => { const filePath = await writeTempFit(createActivityFit()); @@ -611,22 +743,30 @@ describe("processFitFileImportJob", () => { expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); }); - it("fails invalid FIT files before attempting activity parsing", async () => { + it("returns an error result for invalid FIT files before attempting activity parsing", async () => { const filePath = await writeTempFit(Buffer.from("not a fit file")); - await expect( - processFitFileImportJob( - createFitFileImportJob({ - filePath, - originalPath: "DI_CONNECT/broken.fit", - userId: "user-1", - providerId: "garmin-dump", - sourceName: "Garmin Dump", - }), - mockDb, - ), - ).rejects.toThrow("FIT decoder reported"); + const result = await processFitFileImportJob( + createFitFileImportJob({ + filePath, + originalPath: "DI_CONNECT/broken.fit", + userId: "user-1", + providerId: "garmin-dump", + sourceName: "Garmin Dump", + }), + mockDb, + ); + expect(result).toEqual({ + recordsSynced: 0, + errors: [ + expect.objectContaining({ + message: expect.stringContaining( + "Failed to import FIT file DI_CONNECT/broken.fit: FIT decoder reported", + ), + }), + ], + }); expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); await expect(readFile(filePath)).rejects.toThrow(); }); diff --git a/src/jobs/process-fit-file-import-job.ts b/src/jobs/process-fit-file-import-job.ts index 5a5f187de8..ab67572b9b 100644 --- a/src/jobs/process-fit-file-import-job.ts +++ b/src/jobs/process-fit-file-import-job.ts @@ -17,6 +17,7 @@ import { type FitFileImportJobData, fitFileImportJobDataSchema } from "./queues. interface FitFileImportJob { data: unknown; + getChildrenValues?: () => Promise>; updateProgress: (data: FitFileImportProgressInfo) => Promise; } @@ -72,15 +73,57 @@ const decodedFitSchema = z.object({ messages: fitMessagesSchema.optional(), }); +const zipEntryExtractJobResultSchema = z.object({ + filePath: z.string(), +}); + const fitFileImportCleanupPathSchema = z.object({ filePath: z.string(), }); +const fitFileImportErrorPathSchema = z.looseObject({ + originalPath: z.string().optional(), +}); + +type ResolvedFitFileImportJobData = FitFileImportJobData & { filePath: string }; + function cleanupPathFromJobData(data: unknown): string | null { const parsed = fitFileImportCleanupPathSchema.safeParse(data); return parsed.success ? parsed.data.filePath : null; } +async function cleanupPathsFromChildResults(job: FitFileImportJob): Promise { + if (!job.getChildrenValues) return []; + const childrenValues = await job.getChildrenValues(); + return Object.values(childrenValues).flatMap((value) => { + const parsed = zipEntryExtractJobResultSchema.safeParse(value); + return parsed.success ? [parsed.data.filePath] : []; + }); +} + +function originalPathFromJobData(data: unknown): string { + const parsed = fitFileImportErrorPathSchema.safeParse(data); + return parsed.success ? (parsed.data.originalPath ?? "unknown FIT file") : "unknown FIT file"; +} + +function fitFileImportErrorResult(data: unknown, error: unknown): FitFileImportJobResult { + const originalPath = originalPathFromJobData(data); + Sentry.captureException(error, { + tags: { fitImportStep: "process" }, + extra: { originalPath }, + }); + return { + recordsSynced: 0, + errors: [ + { + message: `Failed to import FIT file ${originalPath}: ${ + error instanceof Error ? error.message : String(error) + }`, + }, + ], + }; +} + async function updateFitFileImportProgress( job: FitFileImportJob, info: FitFileImportProgressInfo, @@ -155,7 +198,7 @@ function isWeightFit(messages: z.infer): boolean { async function importWeightFit( db: SyncDatabase, - data: FitFileImportJobData, + data: ResolvedFitFileImportJobData, messages: z.infer, ): Promise { const rows = messages.weightScaleMesgs ?? []; @@ -186,7 +229,7 @@ async function importWeightFit( async function importActivityFit( db: SyncDatabase, - data: FitFileImportJobData, + data: ResolvedFitFileImportJobData, buffer: Buffer, onProgress: (info: FitFileImportProgressInfo) => Promise, ): Promise { @@ -243,17 +286,46 @@ async function importActivityFit( return { recordsSynced: summary ? 0 : 1, errors: [] }; } +async function resolveFlowChildFilePath(job: FitFileImportJob): Promise { + if (!job.getChildrenValues) { + throw new Error("FIT import job is missing filePath and has no child extraction result"); + } + const childrenValues = await job.getChildrenValues(); + const extractResults = Object.values(childrenValues).map((value) => + zipEntryExtractJobResultSchema.parse(value), + ); + const [extractResult] = extractResults; + if (!extractResult || extractResults.length !== 1) { + throw new Error( + `FIT import job expected 1 child extraction result, got ${extractResults.length}`, + ); + } + return extractResult.filePath; +} + +async function resolveFitFileImportJobData( + job: FitFileImportJob, +): Promise { + const data = fitFileImportJobDataSchema.parse(job.data); + return { ...data, filePath: data.filePath ?? (await resolveFlowChildFilePath(job)) }; +} + export async function processFitFileImportJob( job: FitFileImportJob, db: SyncDatabase, ): Promise { + const pathsToClean = new Set(); const cleanupFilePath = cleanupPathFromJobData(job.data); + if (cleanupFilePath) { + pathsToClean.add(cleanupFilePath); + } try { await updateFitFileImportProgress(job, { percentage: 0, message: "Starting FIT file import...", }); - const data = fitFileImportJobDataSchema.parse(job.data); + const data = await resolveFitFileImportJobData(job); + pathsToClean.add(data.filePath); await updateFitFileImportProgress(job, { percentage: 10, message: "Reading FIT file..." }); const buffer = await readFile(data.filePath); await updateFitFileImportProgress(job, { percentage: 25, message: "Decoding FIT file..." }); @@ -283,10 +355,26 @@ export async function processFitFileImportJob( message: "FIT file import complete.", }); return result; + } catch (error) { + return fitFileImportErrorResult(job.data, error); } finally { - if (cleanupFilePath) { - await unlink(cleanupFilePath).catch((error: unknown) => { - logger.warn("Failed to clean up FIT import file %s: %s", cleanupFilePath, error); + if (pathsToClean.size === 0) { + await cleanupPathsFromChildResults(job) + .then((childPaths) => { + for (const childPath of childPaths) { + pathsToClean.add(childPath); + } + }) + .catch((error: unknown) => { + logger.warn("Failed to discover FIT import child cleanup paths: %s", error); + Sentry.captureException(error, { tags: { fitImportStep: "cleanupDiscovery" } }); + }); + } + + for (const path of pathsToClean) { + await unlink(path).catch((error: unknown) => { + logger.warn("Failed to clean up FIT import file %s: %s", path, error); + Sentry.captureException(error, { tags: { fitImportStep: "cleanup" }, extra: { path } }); }); } } diff --git a/src/jobs/process-zip-entry-extract-job.test.ts b/src/jobs/process-zip-entry-extract-job.test.ts new file mode 100644 index 0000000000..b0949e520f --- /dev/null +++ b/src/jobs/process-zip-entry-extract-job.test.ts @@ -0,0 +1,372 @@ +import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import archiver from "archiver"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Options as YauzlOptions, ZipFile } from "yauzl"; +import yauzl from "yauzl"; +import { processZipEntryExtractJob } from "./process-zip-entry-extract-job.ts"; + +const createdDirectories: string[] = []; +type YauzlOpenCallback = (error: Error | null, zipFile: ZipFile) => void; + +async function createTempDirectory(): Promise { + const directory = await mkdtemp(join(tmpdir(), "zip-entry-extract-test-")); + createdDirectories.push(directory); + return directory; +} + +async function createZip(entries: Record): Promise { + const archive = archiver("zip", { zlib: { level: 1 } }); + const stream = new PassThrough(); + const chunks: Buffer[] = []; + stream.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + const finished = new Promise((resolve, reject) => { + stream.on("close", () => resolve(Buffer.concat(chunks))); + stream.on("error", reject); + archive.on("error", reject); + }); + archive.pipe(stream); + for (const [path, data] of Object.entries(entries)) { + archive.append(data, { name: path }); + } + await archive.finalize(); + return finished; +} + +describe("processZipEntryExtractJob", () => { + afterEach(async () => { + vi.restoreAllMocks(); + await Promise.all( + createdDirectories + .splice(0) + .map((directory) => rm(directory, { recursive: true, force: true })), + ); + }); + + it("extracts a top-level ZIP entry to a filesystem path", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/activity.fit": "fit-bytes", + }), + ); + + const result = await processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + }, + }); + + await expect(readFile(result.filePath, "utf8")).resolves.toBe("fit-bytes"); + }); + + it("replaces an existing deterministic output path on replay", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/activity.fit": "first-fit-bytes", + }), + ); + + const firstResult = await processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + }, + }); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/activity.fit": "replayed-fit-bytes", + }), + ); + + const replayResult = await processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + }, + }); + + expect(replayResult.filePath).toBe(firstResult.filePath); + await expect(readFile(replayResult.filePath, "utf8")).resolves.toBe("replayed-fit-bytes"); + }); + + it("preserves an existing deterministic output path when a replay extraction fails", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/activity.fit": "original-fit-bytes", + }), + ); + + const firstResult = await processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + }, + }); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/activity.fit": "oversized-replay-fit-bytes", + }), + ); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + maxBytes: 3, + }, + }), + ).rejects.toThrow("ZIP entry DI_CONNECT/activity.fit exceeds maximum size of 3 bytes"); + + await expect(readFile(firstResult.filePath, "utf8")).resolves.toBe("original-fit-bytes"); + const directoryEntries = await readdir(directory); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); + + it("extracts an entry from a nested ZIP chain", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + const nestedZip = await createZip({ + "asher@example.com_12345.fit": "nested-fit-bytes", + }); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip": nestedZip, + }), + ); + + const result = await processZipEntryExtractJob({ + data: { + archivePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip", + "asher@example.com_12345.fit", + ], + outputExtension: "fit", + }, + }); + + await expect(readFile(result.filePath, "utf8")).resolves.toBe("nested-fit-bytes"); + }); + + it("allows nested ZIP archives to be larger than the final extracted entry limit", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + const nestedZip = await createZip({ + "padding.txt": "padding that makes the nested archive larger than the final FIT limit", + "asher@example.com_12345.fit": "fit", + }); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip": nestedZip, + }), + ); + + const result = await processZipEntryExtractJob({ + data: { + archivePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip", + "asher@example.com_12345.fit", + ], + outputExtension: "fit", + maxBytes: 3, + nestedArchiveMaxBytes: nestedZip.length, + }, + }); + + await expect(readFile(result.filePath, "utf8")).resolves.toBe("fit"); + }); + + it("rejects final entries larger than the configured maxBytes and removes partial files", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/activity.fit": "fit-bytes", + }), + ); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + maxBytes: 3, + }, + }), + ).rejects.toThrow("ZIP entry DI_CONNECT/activity.fit exceeds maximum size of 3 bytes"); + + const directoryEntries = await readdir(directory); + expect(directoryEntries.filter((entryName) => entryName.endsWith(".fit"))).toEqual([]); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); + + it("rejects nested ZIP archives larger than the configured nested archive limit", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + const nestedZip = await createZip({ + "asher@example.com_12345.fit": "nested-fit-bytes", + }); + await writeFile( + archivePath, + await createZip({ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip": nestedZip, + }), + ); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip", + "asher@example.com_12345.fit", + ], + outputExtension: "fit", + maxBytes: 1024, + nestedArchiveMaxBytes: 3, + }, + }), + ).rejects.toThrow( + "ZIP entry DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip exceeds maximum size of 3 bytes", + ); + + const directoryEntries = await readdir(directory); + expect(directoryEntries.filter((entryName) => entryName.endsWith(".fit"))).toEqual([]); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); + + it("rejects malformed ZIP archives and removes the extraction temp directory", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile(archivePath, "not a zip"); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + }, + }), + ).rejects.toThrow("End of central directory record signature not found"); + + const directoryEntries = await readdir(directory); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); + + it("rejects when the ZIP library returns no opened file", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile(archivePath, await createZip({ "DI_CONNECT/activity.fit": "fit-bytes" })); + function openWithoutZipFile( + _filePath: string, + _options: YauzlOptions, + callback?: YauzlOpenCallback, + ): void; + function openWithoutZipFile(_filePath: string, callback?: YauzlOpenCallback): void; + function openWithoutZipFile( + _filePath: string, + optionsOrCallback?: YauzlOptions | YauzlOpenCallback, + callback?: YauzlOpenCallback, + ): void { + const openCallback = typeof optionsOrCallback === "function" ? optionsOrCallback : callback; + if (!openCallback) { + throw new Error("Expected ZIP open callback"); + } + Reflect.apply(openCallback, undefined, [null, undefined]); + } + vi.spyOn(yauzl, "open").mockImplementation(openWithoutZipFile); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["DI_CONNECT/activity.fit"], + outputExtension: "fit", + }, + }), + ).rejects.toThrow(`ZIP file could not be opened: ${archivePath}`); + + const directoryEntries = await readdir(directory); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); + + it("rejects missing entries", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile(archivePath, await createZip({ "other.fit": "fit-bytes" })); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: ["missing.fit"], + outputExtension: "fit", + }, + }), + ).rejects.toThrow("ZIP entry not found: missing.fit"); + + const directoryEntries = await readdir(directory); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); + + it("rejects empty ZIP entry path segments", async () => { + const directory = await createTempDirectory(); + const archivePath = join(directory, "export.zip"); + await writeFile(archivePath, await createZip({ "DI_CONNECT/activity.fit": "fit-bytes" })); + + await expect( + processZipEntryExtractJob({ + data: { + archivePath, + entryPath: [""], + outputExtension: "fit", + }, + }), + ).rejects.toThrow("ZIP entry path cannot be empty"); + + const directoryEntries = await readdir(directory); + expect( + directoryEntries.filter((entryName) => entryName.startsWith(".zip-entry-extract-")), + ).toEqual([]); + }); +}); diff --git a/src/jobs/process-zip-entry-extract-job.ts b/src/jobs/process-zip-entry-extract-job.ts new file mode 100644 index 0000000000..1138a2b879 --- /dev/null +++ b/src/jobs/process-zip-entry-extract-job.ts @@ -0,0 +1,204 @@ +import { createHash } from "node:crypto"; +import { createWriteStream } from "node:fs"; +import { mkdtemp, rename, rm } from "node:fs/promises"; +import { basename, dirname, join } from "node:path"; +import type { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import yauzl from "yauzl"; +import { zipEntryExtractJobDataSchema } from "./queues.ts"; + +interface ZipEntryExtractJob { + data: unknown; +} + +export interface ZipEntryExtractJobResult { + filePath: string; +} + +const DEFAULT_MAX_EXTRACTED_BYTES = 1024 * 1024 * 1024; + +function openZipFromPath(filePath: string): Promise { + return new Promise((resolve, reject) => { + yauzl.open(filePath, { lazyEntries: true }, (error, zipFile) => { + if (error) { + reject(error); + return; + } + if (!zipFile) { + reject(new Error(`ZIP file could not be opened: ${filePath}`)); + return; + } + resolve(zipFile); + }); + }); +} + +function openReadStream(zipFile: yauzl.ZipFile, entry: yauzl.Entry): Promise { + return new Promise((resolve, reject) => { + zipFile.openReadStream(entry, (error, stream) => { + if (error) { + reject(error); + return; + } + if (!stream) { + reject(new Error(`ZIP entry could not be read: ${entry.fileName}`)); + return; + } + resolve(stream); + }); + }); +} + +function readNextZipEntry(zipFile: yauzl.ZipFile): Promise { + return new Promise((resolve, reject) => { + const onEntry = (entry: yauzl.Entry) => { + cleanup(); + resolve(entry); + }; + const onEnd = () => { + cleanup(); + resolve(null); + }; + const onError = (error: Error) => { + cleanup(); + reject(error); + }; + const cleanup = () => { + zipFile.off("entry", onEntry); + zipFile.off("end", onEnd); + zipFile.off("error", onError); + }; + + zipFile.once("entry", onEntry); + zipFile.once("end", onEnd); + zipFile.once("error", onError); + zipFile.readEntry(); + }); +} + +async function findZipEntry( + zipPath: string, + entryPath: string, +): Promise<{ + zipFile: yauzl.ZipFile; + entry: yauzl.Entry; +}> { + const zipFile = await openZipFromPath(zipPath); + let found = false; + try { + while (true) { + const entry = await readNextZipEntry(zipFile); + if (!entry) { + throw new Error(`ZIP entry not found: ${entryPath}`); + } + if (entry.fileName === entryPath) { + found = true; + return { zipFile, entry }; + } + } + } finally { + if (!found) { + zipFile.close(); + } + } +} + +async function streamToFile( + stream: Readable, + filePath: string, + maxBytes: number, + description: string, +): Promise { + let bytesRead = 0; + await pipeline( + stream, + async function* limitBytes(source) { + for await (const chunk of source) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + bytesRead += buffer.length; + if (bytesRead > maxBytes) { + throw new Error(`${description} exceeds maximum size of ${maxBytes} bytes`); + } + yield buffer; + } + }, + createWriteStream(filePath, { flags: "wx" }), + ); +} + +async function extractEntryChain( + archivePath: string, + entryPath: string[], + outputPath: string, + maxBytes: number, + nestedArchiveMaxBytes: number, + tempDirectory: string, +): Promise { + const [headEntryPath, ...tailEntryPath] = entryPath; + if (!headEntryPath) { + throw new Error("ZIP entry path cannot be empty"); + } + + const { zipFile, entry } = await findZipEntry(archivePath, headEntryPath); + try { + const stream = await openReadStream(zipFile, entry); + if (tailEntryPath.length === 0) { + await streamToFile(stream, outputPath, maxBytes, `ZIP entry ${headEntryPath}`); + return; + } + + const nestedZipPath = join( + tempDirectory, + `${createHash("sha256").update(entryPath.join("\n")).digest("hex")}.zip`, + ); + await streamToFile(stream, nestedZipPath, nestedArchiveMaxBytes, `ZIP entry ${headEntryPath}`); + await extractEntryChain( + nestedZipPath, + tailEntryPath, + outputPath, + maxBytes, + nestedArchiveMaxBytes, + tempDirectory, + ); + } finally { + zipFile.close(); + } +} + +export async function processZipEntryExtractJob( + job: ZipEntryExtractJob, +): Promise { + const data = zipEntryExtractJobDataSchema.parse(job.data); + const tempDirectory = await mkdtemp(join(dirname(data.archivePath), ".zip-entry-extract-")); + const outputPath = join( + dirname(data.archivePath), + `${basename(data.archivePath)}-${createHash("sha256") + .update(data.entryPath.join("\n")) + .digest("hex")}.${data.outputExtension}`, + ); + const publishPath = join( + tempDirectory, + `${createHash("sha256").update(`${outputPath}\n${Date.now()}`).digest("hex")}.${data.outputExtension}`, + ); + + let extracted = false; + try { + await extractEntryChain( + data.archivePath, + data.entryPath, + publishPath, + data.maxBytes ?? DEFAULT_MAX_EXTRACTED_BYTES, + data.nestedArchiveMaxBytes ?? DEFAULT_MAX_EXTRACTED_BYTES, + tempDirectory, + ); + await rename(publishPath, outputPath); + extracted = true; + } finally { + if (!extracted) { + await rm(publishPath, { force: true }); + } + await rm(tempDirectory, { recursive: true, force: true }); + } + + return { filePath: outputPath }; +} diff --git a/src/jobs/queues.test.ts b/src/jobs/queues.test.ts index f6b097693e..11ee4c3b77 100644 --- a/src/jobs/queues.test.ts +++ b/src/jobs/queues.test.ts @@ -8,8 +8,12 @@ const MockQueue = vi.fn(() => mockQueueInstance); const mockQueueEventsClose = vi.fn().mockResolvedValue(undefined); const mockQueueEventsInstance = { name: "mock-queue-events", close: mockQueueEventsClose }; const MockQueueEvents = vi.fn(() => mockQueueEventsInstance); +const mockFlowProducerClose = vi.fn().mockResolvedValue(undefined); +const mockFlowProducerInstance = { name: "mock-flow-producer", close: mockFlowProducerClose }; +const MockFlowProducer = vi.fn(() => mockFlowProducerInstance); vi.mock("bullmq", () => ({ + FlowProducer: MockFlowProducer, Queue: MockQueue, QueueEvents: MockQueueEvents, })); @@ -21,6 +25,7 @@ describe("queues", () => { mockQueueAdd.mockResolvedValue(undefined); mockQueueClose.mockResolvedValue(undefined); mockQueueEventsClose.mockResolvedValue(undefined); + mockFlowProducerClose.mockResolvedValue(undefined); }); describe("constants", () => { @@ -28,15 +33,19 @@ describe("queues", () => { const { ACTIVITY_DELETE_ANALYTICS_QUEUE, EXPORT_QUEUE, + FIT_FILE_IMPORT_BATCH_QUEUE, FIT_FILE_IMPORT_QUEUE, IMPORT_QUEUE, POST_SYNC_QUEUE, SCHEDULED_SYNC_QUEUE, SYNC_QUEUE, + ZIP_ENTRY_EXTRACT_QUEUE, } = await import("./queues.ts"); expect(SYNC_QUEUE).toBe("sync"); expect(IMPORT_QUEUE).toBe("import"); expect(FIT_FILE_IMPORT_QUEUE).toBe("fit-file-import"); + expect(FIT_FILE_IMPORT_BATCH_QUEUE).toBe("fit-file-import-batch"); + expect(ZIP_ENTRY_EXTRACT_QUEUE).toBe("zip-entry-extract"); expect(EXPORT_QUEUE).toBe("export"); expect(SCHEDULED_SYNC_QUEUE).toBe("scheduled-sync"); expect(POST_SYNC_QUEUE).toBe("post-sync"); @@ -171,6 +180,80 @@ describe("queues", () => { }); }); + describe("createFitFileImportBatchQueue", () => { + it("creates a Queue with the FIT file import batch queue name", async () => { + const { createFitFileImportBatchQueue, FIT_FILE_IMPORT_BATCH_QUEUE } = await import( + "./queues.ts" + ); + + createFitFileImportBatchQueue({ host: "test", port: 8642 }); + + expect(MockQueue).toHaveBeenCalledWith(FIT_FILE_IMPORT_BATCH_QUEUE, { + connection: { host: "test", port: 8642 }, + }); + }); + }); + + describe("createZipEntryExtractQueue", () => { + it("creates a Queue with the ZIP entry extract queue name", async () => { + const { createZipEntryExtractQueue, ZIP_ENTRY_EXTRACT_QUEUE } = await import("./queues.ts"); + + createZipEntryExtractQueue({ host: "test", port: 9753 }); + + expect(MockQueue).toHaveBeenCalledWith(ZIP_ENTRY_EXTRACT_QUEUE, { + connection: { host: "test", port: 9753 }, + }); + }); + }); + + describe("zipEntryExtractJobDataSchema", () => { + it("accepts nested alphanumeric output extensions", async () => { + const { zipEntryExtractJobDataSchema } = await import("./queues.ts"); + + expect( + zipEntryExtractJobDataSchema.parse({ + archivePath: "/tmp/export.zip", + entryPath: ["DI_CONNECT/files.zip", "activity.fit"], + outputExtension: "fit2", + maxBytes: 1024, + nestedArchiveMaxBytes: 2048, + }), + ).toEqual({ + archivePath: "/tmp/export.zip", + entryPath: ["DI_CONNECT/files.zip", "activity.fit"], + outputExtension: "fit2", + maxBytes: 1024, + nestedArchiveMaxBytes: 2048, + }); + }); + + it("rejects empty entry paths and non-alphanumeric output extensions", async () => { + const { zipEntryExtractJobDataSchema } = await import("./queues.ts"); + + expect(() => + zipEntryExtractJobDataSchema.parse({ + archivePath: "/tmp/export.zip", + entryPath: [], + outputExtension: "fit", + }), + ).toThrow(); + expect(() => + zipEntryExtractJobDataSchema.parse({ + archivePath: "/tmp/export.zip", + entryPath: ["activity.fit"], + outputExtension: "fit.gz", + }), + ).toThrow(); + expect(() => + zipEntryExtractJobDataSchema.parse({ + archivePath: "/tmp/export.zip", + entryPath: ["activity.fit"], + outputExtension: ".fit", + }), + ).toThrow(); + }); + }); + describe("ImportJobData", () => { it("allows kaya-export as an import job type", () => { const jobData = { @@ -232,30 +315,73 @@ describe("queues", () => { }); }); + describe("getFitFileImportBatchQueueEvents", () => { + it("reuses one FIT file import batch queue events instance", async () => { + process.env.REDIS_URL = "redis://localhost:6379"; + const { getFitFileImportBatchQueueEvents, FIT_FILE_IMPORT_BATCH_QUEUE } = await import( + "./queues.ts" + ); + + const first = getFitFileImportBatchQueueEvents(); + const second = getFitFileImportBatchQueueEvents(); + + expect(first).toBe(second); + expect(MockQueueEvents).toHaveBeenCalledTimes(1); + expect(MockQueueEvents).toHaveBeenCalledWith(FIT_FILE_IMPORT_BATCH_QUEUE, { + connection: expect.objectContaining({ host: "localhost", port: 6379 }), + }); + }); + }); + + describe("getFlowProducer", () => { + it("reuses one flow producer instance", async () => { + process.env.REDIS_URL = "redis://localhost:6379"; + const { getFlowProducer } = await import("./queues.ts"); + + const first = getFlowProducer(); + const second = getFlowProducer(); + + expect(first).toBe(second); + expect(MockFlowProducer).toHaveBeenCalledTimes(1); + expect(MockFlowProducer).toHaveBeenCalledWith({ + connection: expect.objectContaining({ host: "localhost", port: 6379 }), + }); + }); + }); + describe("closeFitFileImportQueueResources", () => { it("closes cached FIT file import queue resources and clears the cache", async () => { process.env.REDIS_URL = "redis://localhost:6379"; const { closeFitFileImportQueueResources, + getFitFileImportBatchQueueEvents, getFitFileImportQueue, getFitFileImportQueueEvents, + getFlowProducer, } = await import("./queues.ts"); getFitFileImportQueue(); getFitFileImportQueueEvents(); + getFitFileImportBatchQueueEvents(); + getFlowProducer(); const queueConstructorCallsBeforeClose = MockQueue.mock.calls.length; const queueEventsConstructorCallsBeforeClose = MockQueueEvents.mock.calls.length; + const flowProducerConstructorCallsBeforeClose = MockFlowProducer.mock.calls.length; await closeFitFileImportQueueResources(); expect(mockQueueClose).toHaveBeenCalledOnce(); - expect(mockQueueEventsClose).toHaveBeenCalledOnce(); + expect(mockQueueEventsClose).toHaveBeenCalledTimes(2); + expect(mockFlowProducerClose).toHaveBeenCalledOnce(); getFitFileImportQueue(); getFitFileImportQueueEvents(); + getFitFileImportBatchQueueEvents(); + getFlowProducer(); expect(MockQueue).toHaveBeenCalledTimes(queueConstructorCallsBeforeClose + 1); - expect(MockQueueEvents).toHaveBeenCalledTimes(queueEventsConstructorCallsBeforeClose + 1); + expect(MockQueueEvents).toHaveBeenCalledTimes(queueEventsConstructorCallsBeforeClose + 2); + expect(MockFlowProducer).toHaveBeenCalledTimes(flowProducerConstructorCallsBeforeClose + 1); }); }); diff --git a/src/jobs/queues.ts b/src/jobs/queues.ts index 93f8fe59f4..d875d25168 100644 --- a/src/jobs/queues.ts +++ b/src/jobs/queues.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { CANONICAL_ACTIVITY_TYPES } from "@dofek/training/training"; import type { ConnectionOptions, JobsOptions } from "bullmq"; -import { Queue, QueueEvents } from "bullmq"; +import { FlowProducer, Queue, QueueEvents } from "bullmq"; import { z } from "zod"; import type { ProviderSyncTier } from "./provider-queue-config.ts"; @@ -45,7 +45,7 @@ export const fitFileImportActivitySummarySchema = z.object({ }); export const fitFileImportJobDataSchema = z.object({ - filePath: z.string(), + filePath: z.string().optional(), originalPath: z.string(), userId: z.string(), providerId: z.string(), @@ -56,6 +56,20 @@ export const fitFileImportJobDataSchema = z.object({ export type FitFileImportActivitySummary = z.infer; export type FitFileImportJobData = z.infer; +export const zipEntryExtractJobDataSchema = z.object({ + archivePath: z.string(), + entryPath: z.array(z.string()).min(1), + outputExtension: z.string().regex(/^[A-Za-z0-9]+$/), + maxBytes: z.number().int().positive().optional(), + nestedArchiveMaxBytes: z.number().int().positive().optional(), +}); + +export type ZipEntryExtractJobData = z.infer; + +export interface FitFileImportBatchJobData { + type: "fit-file-import-batch"; +} + export interface ExportJobData { exportId: string; userId: string; @@ -112,6 +126,8 @@ export const SYNC_QUEUE = "sync"; export const SYNC_QUEUE_PREFIX = "sync"; export const IMPORT_QUEUE = "import"; export const FIT_FILE_IMPORT_QUEUE = "fit-file-import"; +export const FIT_FILE_IMPORT_BATCH_QUEUE = "fit-file-import-batch"; +export const ZIP_ENTRY_EXTRACT_QUEUE = "zip-entry-extract"; export const EXPORT_QUEUE = "export"; export const SCHEDULED_SYNC_QUEUE = "scheduled-sync"; export const POST_SYNC_QUEUE = "post-sync"; @@ -203,6 +219,28 @@ export function createFitFileImportQueueEvents(connection?: ConnectionOptions): return new QueueEvents(FIT_FILE_IMPORT_QUEUE, { connection: connection ?? getRedisConnection() }); } +export function createFitFileImportBatchQueue( + connection?: ConnectionOptions, +): Queue { + return new Queue(FIT_FILE_IMPORT_BATCH_QUEUE, { connection: connection ?? getRedisConnection() }); +} + +export function createFitFileImportBatchQueueEvents(connection?: ConnectionOptions): QueueEvents { + return new QueueEvents(FIT_FILE_IMPORT_BATCH_QUEUE, { + connection: connection ?? getRedisConnection(), + }); +} + +export function createZipEntryExtractQueue( + connection?: ConnectionOptions, +): Queue { + return new Queue(ZIP_ENTRY_EXTRACT_QUEUE, { connection: connection ?? getRedisConnection() }); +} + +export function createFlowProducer(connection?: ConnectionOptions): FlowProducer { + return new FlowProducer({ connection: connection ?? getRedisConnection() }); +} + export function createExportQueue(connection?: ConnectionOptions): Queue { return new Queue(EXPORT_QUEUE, { connection: connection ?? getRedisConnection() }); } @@ -230,6 +268,8 @@ let cachedActivityDeleteAnalyticsQueue: Queue | null = let cachedImportQueue: Queue | null = null; let cachedFitFileImportQueue: Queue | null = null; let cachedFitFileImportQueueEvents: QueueEvents | null = null; +let cachedFitFileImportBatchQueueEvents: QueueEvents | null = null; +let cachedFlowProducer: FlowProducer | null = null; export function getImportQueue(): Queue { if (!cachedImportQueue) { @@ -252,9 +292,25 @@ export function getFitFileImportQueueEvents(): QueueEvents { return cachedFitFileImportQueueEvents; } +export function getFitFileImportBatchQueueEvents(): QueueEvents { + if (!cachedFitFileImportBatchQueueEvents) { + cachedFitFileImportBatchQueueEvents = createFitFileImportBatchQueueEvents(); + } + return cachedFitFileImportBatchQueueEvents; +} + +export function getFlowProducer(): FlowProducer { + if (!cachedFlowProducer) { + cachedFlowProducer = createFlowProducer(); + } + return cachedFlowProducer; +} + export async function closeFitFileImportQueueResources(): Promise { const queue = cachedFitFileImportQueue; const queueEvents = cachedFitFileImportQueueEvents; + const batchQueueEvents = cachedFitFileImportBatchQueueEvents; + const flowProducer = cachedFlowProducer; const closeOperations: Array> = []; if (queue) { @@ -263,10 +319,18 @@ export async function closeFitFileImportQueueResources(): Promise { if (queueEvents) { closeOperations.push(queueEvents.close()); } + if (batchQueueEvents) { + closeOperations.push(batchQueueEvents.close()); + } + if (flowProducer) { + closeOperations.push(flowProducer.close()); + } await Promise.all(closeOperations); cachedFitFileImportQueue = null; cachedFitFileImportQueueEvents = null; + cachedFitFileImportBatchQueueEvents = null; + cachedFlowProducer = null; } export function getPostSyncQueue(): Queue { diff --git a/src/jobs/worker.test.ts b/src/jobs/worker.test.ts index bc559ee202..16adcebd3b 100644 --- a/src/jobs/worker.test.ts +++ b/src/jobs/worker.test.ts @@ -37,6 +37,14 @@ vi.mock("./process-fit-file-import-job.ts", () => ({ processFitFileImportJob: vi.fn(), })); +vi.mock("./process-fit-file-import-batch-job.ts", () => ({ + processFitFileImportBatchJob: vi.fn(), +})); + +vi.mock("./process-zip-entry-extract-job.ts", () => ({ + processZipEntryExtractJob: vi.fn(), +})); + vi.mock("./process-sync-job.ts", () => ({ processSyncJob: vi.fn(), })); @@ -75,6 +83,8 @@ vi.mock("./queues.ts", () => ({ providerSyncQueueName: vi.fn((id: string) => `sync-${id}`), IMPORT_QUEUE: "import-queue", FIT_FILE_IMPORT_QUEUE: "fit-file-import-queue", + FIT_FILE_IMPORT_BATCH_QUEUE: "fit-file-import-batch-queue", + ZIP_ENTRY_EXTRACT_QUEUE: "zip-entry-extract-queue", SYNC_QUEUE: "sync-queue", EXPORT_QUEUE: "export-queue", SCHEDULED_SYNC_QUEUE: "scheduled-sync-queue", @@ -115,9 +125,11 @@ describe("worker module", () => { await import("./worker.ts"); }); - // 2 per-provider workers (strava, garmin) + 1 legacy sync + 1 import + 1 FIT import + 1 export + 1 scheduled-sync + 1 post-sync + 1 activity-delete-analytics = 9 + // 2 per-provider workers (strava, garmin) + 1 legacy sync + 1 import + 1 FIT import + // + 1 FIT batch + 1 ZIP extract + 1 export + 1 scheduled-sync + 1 post-sync + // + 1 activity-delete-analytics = 11 // Training export is handled by the standalone Python BullMQ worker (packages/ml). - const EXPECTED_WORKER_COUNT = 9; + const EXPECTED_WORKER_COUNT = 11; it("creates per-provider workers plus standard workers", async () => { const { Worker } = await import("bullmq"); @@ -134,6 +146,16 @@ describe("worker module", () => { expect.any(Function), expect.objectContaining({ concurrency: 2 }), ); + expect(Worker).toHaveBeenCalledWith( + "fit-file-import-batch-queue", + expect.any(Function), + expect.objectContaining({ concurrency: 1 }), + ); + expect(Worker).toHaveBeenCalledWith( + "zip-entry-extract-queue", + expect.any(Function), + expect.objectContaining({ concurrency: 2 }), + ); expect(Worker).toHaveBeenCalledWith("export-queue", expect.any(Function), expect.any(Object)); expect(Worker).toHaveBeenCalledWith( "scheduled-sync-queue", @@ -468,6 +490,28 @@ describe("worker module", () => { expect(processFitFileImportJob).toHaveBeenCalled(); }); + it("FIT file import batch processor delegates to processFitFileImportBatchJob", async () => { + const { processFitFileImportBatchJob } = await import("./process-fit-file-import-batch-job.ts"); + vi.mocked(processFitFileImportBatchJob).mockClear(); + + await invokeProcessor("fit-file-import-batch-queue", { type: "fit-file-import-batch" }); + + expect(processFitFileImportBatchJob).toHaveBeenCalled(); + }); + + it("ZIP entry extract processor delegates to processZipEntryExtractJob", async () => { + const { processZipEntryExtractJob } = await import("./process-zip-entry-extract-job.ts"); + vi.mocked(processZipEntryExtractJob).mockClear(); + + await invokeProcessor("zip-entry-extract-queue", { + archivePath: "/tmp/archive.zip", + entryPath: ["activity.fit"], + outputExtension: "fit", + }); + + expect(processZipEntryExtractJob).toHaveBeenCalled(); + }); + it("scheduled-sync processor delegates to processScheduledSyncJob", async () => { const { processScheduledSyncJob } = await import("./process-scheduled-sync-job.ts"); vi.mocked(processScheduledSyncJob).mockClear(); diff --git a/src/jobs/worker.ts b/src/jobs/worker.ts index ac634b88dc..f067e2d132 100644 --- a/src/jobs/worker.ts +++ b/src/jobs/worker.ts @@ -7,18 +7,22 @@ import { createRefitSensorStore } from "../db/refit-sensor-store.ts"; import { jobContext, logger } from "../logger.ts"; import { processActivityDeleteAnalyticsJob } from "./process-activity-delete-analytics-job.ts"; import { processExportJob } from "./process-export-job.ts"; +import { processFitFileImportBatchJob } from "./process-fit-file-import-batch-job.ts"; import { processFitFileImportJob } from "./process-fit-file-import-job.ts"; import { processImportJob } from "./process-import-job.ts"; import { processPostSyncJob } from "./process-post-sync-job.ts"; import { processScheduledSyncJob } from "./process-scheduled-sync-job.ts"; import { processSyncJob } from "./process-sync-job.ts"; +import { processZipEntryExtractJob } from "./process-zip-entry-extract-job.ts"; import { getConfiguredProviderIds, getProviderQueueConfig } from "./provider-queue-config.ts"; import { ACTIVITY_DELETE_ANALYTICS_QUEUE, type ActivityAnalyticsJobData, EXPORT_QUEUE, type ExportJobData, + FIT_FILE_IMPORT_BATCH_QUEUE, FIT_FILE_IMPORT_QUEUE, + type FitFileImportBatchJobData, type FitFileImportJobData, getRedisConnection, IMPORT_QUEUE, @@ -30,6 +34,8 @@ import { type ScheduledSyncJobData, SYNC_QUEUE, type SyncJobData, + ZIP_ENTRY_EXTRACT_QUEUE, + type ZipEntryExtractJobData, } from "./queues.ts"; import { setupScheduledSync } from "./scheduled-sync.ts"; @@ -116,6 +122,16 @@ const fitFileImportWorker = new Worker( (job) => jobContext.run(job, () => processFitFileImportJob(job, db)), { autorun: false, connection, concurrency: 2 }, ); +const fitFileImportBatchWorker = new Worker( + FIT_FILE_IMPORT_BATCH_QUEUE, + (job) => jobContext.run(job, () => processFitFileImportBatchJob(job)), + { autorun: false, connection, concurrency: 1 }, +); +const zipEntryExtractWorker = new Worker( + ZIP_ENTRY_EXTRACT_QUEUE, + (job) => jobContext.run(job, () => processZipEntryExtractJob(job)), + { autorun: false, connection, concurrency: 2 }, +); const scheduledSyncWorker = new Worker( SCHEDULED_SYNC_QUEUE, (job) => jobContext.run(job, () => processScheduledSyncJob(job, db)), @@ -193,6 +209,8 @@ const allWorkers: Worker[] = [ importWorker, exportWorker, fitFileImportWorker, + fitFileImportBatchWorker, + zipEntryExtractWorker, scheduledSyncWorker, postSyncWorker, activityDeleteAnalyticsWorker, diff --git a/src/providers/garmin-dump.test.ts b/src/providers/garmin-dump.test.ts index eea674c840..59205c092b 100644 --- a/src/providers/garmin-dump.test.ts +++ b/src/providers/garmin-dump.test.ts @@ -1,4 +1,5 @@ -import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { PassThrough } from "node:stream"; @@ -57,19 +58,31 @@ vi.mock("../db/provider-activity-sync.ts", () => ({ upsertProviderActivity: (...args: unknown[]) => mockUpsertProviderActivity(...args), })); -const fitQueueMock = vi.hoisted(() => { +interface FlowJobForTest { + name: string; + queueName: string; + data: unknown; + opts?: unknown; + children?: FlowJobForTest[]; +} + +const flowMock = vi.hoisted(() => { const waitUntilFinished = vi.fn(); const queueEvents = {}; - const add = vi.fn(async (_name: string, data: unknown) => ({ - id: "fit-job-1", - waitUntilFinished: () => waitUntilFinished(data), + const add = vi.fn(async (flow: FlowJobForTest) => ({ + job: { + waitUntilFinished: () => waitUntilFinished(flow), + }, })); return { add, queueEvents, waitUntilFinished }; }); vi.mock("../jobs/queues.ts", () => ({ - getFitFileImportQueue: () => ({ add: fitQueueMock.add }), - getFitFileImportQueueEvents: () => fitQueueMock.queueEvents, + FIT_FILE_IMPORT_BATCH_QUEUE: "fit-file-import-batch", + FIT_FILE_IMPORT_QUEUE: "fit-file-import", + ZIP_ENTRY_EXTRACT_QUEUE: "zip-entry-extract", + getFitFileImportBatchQueueEvents: () => flowMock.queueEvents, + getFlowProducer: () => ({ add: flowMock.add }), })); const mockReplaceMetricStreamBatch = vi.fn().mockResolvedValue(undefined); @@ -237,14 +250,14 @@ describe("Garmin dump provider", () => { mockReplaceMetricStreamBatch.mockResolvedValue(undefined); mockWriteMetricStreamBatch.mockResolvedValue(undefined); mockEnsureProvider.mockResolvedValue(undefined); - fitQueueMock.add.mockReset(); - fitQueueMock.waitUntilFinished.mockReset(); - fitQueueMock.add.mockImplementation(async (_name: string, data: unknown) => ({ - id: "fit-job-1", - waitUntilFinished: () => fitQueueMock.waitUntilFinished(data), + flowMock.add.mockImplementation(async (flow: FlowJobForTest) => ({ + job: { + waitUntilFinished: () => flowMock.waitUntilFinished(flow), + }, })); - fitQueueMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 0, errors: [] }); + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 0, errors: [] }); mockCaptureException.mockClear(); + mockLoggerWarn.mockClear(); mockParseFitFile.mockResolvedValue({ session: { sport: "cycling", @@ -298,6 +311,22 @@ describe("Garmin dump provider", () => { ); }); + function latestFlow(): FlowJobForTest { + const flow = flowMock.add.mock.calls.at(-1)?.[0]; + if (!flow) { + throw new Error("Expected a BullMQ flow to be created"); + } + return flow; + } + + function latestFitFlowChildren(): FlowJobForTest[] { + return latestFlow().children ?? []; + } + + function expectedFlowHash(input: string): string { + return createHash("sha256").update(input).digest("hex"); + } + it("is an import-only provider", () => { const provider = new GarminDumpProvider(); @@ -330,6 +359,22 @@ describe("Garmin dump provider", () => { expect(parsed.weightFitFiles.map((entry) => entry.path)).toEqual([ "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_999_weight.fit", ]); + expect(parsed.fitFiles[0]).toEqual({ + path: "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_12345.fit", + archivePath: filePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip", + "asher@example.com_12345.fit", + ], + }); + expect(parsed.weightFitFiles[0]).toEqual({ + path: "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_999_weight.fit", + archivePath: filePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip", + "asher@example.com_999_weight.fit", + ], + }); }); it("parses extracted Garmin dump directories recursively", async () => { @@ -362,6 +407,33 @@ describe("Garmin dump provider", () => { ]); }); + it("parses nested uploaded ZIP files inside extracted Garmin dump directories", async () => { + const directory = await createTempDirectory(); + const nestedDirectory = join(directory, "DI_CONNECT", "DI-Connect-Uploaded-Files"); + await mkdir(nestedDirectory, { recursive: true }); + const nestedZipPath = join(nestedDirectory, "UploadedFiles_0-_Part1.zip"); + await writeFile( + nestedZipPath, + await createZip({ + "asher@example.com_12345.fit": "fit-bytes", + "ignored.txt": "ignored", + }), + ); + + const parsed = await parseGarminDumpFile(directory); + + expect(parsed.errors).toEqual([]); + expect(parsed.fitFiles).toEqual([ + { + path: "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_12345.fit", + archivePath: nestedZipPath, + entryPath: ["asher@example.com_12345.fit"], + }, + ]); + expect(parsed.weightFitFiles).toEqual([]); + expect(parsed.tempDirectories).toHaveLength(1); + }); + it("reports malformed summarized activity files without dropping valid FIT files", async () => { const zip = await createZip({ "DI_CONNECT/DI-Connect-Fitness/asher_0_summarizedActivities.json": "{broken", @@ -381,6 +453,34 @@ describe("Garmin dump provider", () => { expect(parsed.errors[0]?.message).toContain("Failed to parse Garmin summarized activities"); }); + it("skips irrelevant nested zip entries instead of buffering them", async () => { + const zip = await createZip({ + "DI_CONNECT/DI-Connect-Fitness/asher_0_summarizedActivities.json": JSON.stringify([ + { + summarizedActivitiesExport: [ + { + activityId: 12345, + activityType: "cycling", + startTimeGmt: Date.parse("2026-07-01T12:00:00.000Z"), + duration: 1800000, + }, + ], + }, + ]), + "DI_CONNECT/DI-Connect-Routing/courses.zip": "not a zip", + }); + const directory = await createTempDirectory(); + const filePath = join(directory, "garmin-export.zip"); + await writeFile(filePath, zip); + + const parsed = await parseGarminDumpFile(filePath); + + expect(parsed.errors).toEqual([]); + expect(parsed.summaries.map((summary) => summary.activityId)).toEqual([12345]); + expect(parsed.fitFiles).toEqual([]); + expect(parsed.weightFitFiles).toEqual([]); + }); + it("rejects oversized Garmin dump files before reading them", async () => { const directory = await createTempDirectory(); const filePath = join(directory, "too-large.zip"); @@ -409,6 +509,19 @@ describe("Garmin dump provider", () => { ); }); + it("removes temporary extraction directories when ZIP parsing fails", async () => { + const directory = await createTempDirectory(); + const filePath = join(directory, "garmin-export.zip"); + await writeFile(filePath, "not a zip"); + + await expect(parseGarminDumpFile(filePath)).rejects.toThrow(); + + const remainingEntries = await readdir(directory); + expect( + remainingEntries.filter((entryName) => entryName.startsWith("garmin-export.zip-extract-")), + ).toEqual([]); + }); + it("imports summaries and fans out matching FIT files", async () => { const filePath = await createGarminDumpZip(); @@ -438,37 +551,104 @@ describe("Garmin dump provider", () => { name: "Morning Ride", }), ); - expect(fitQueueMock.add).toHaveBeenCalledTimes(2); - expect(fitQueueMock.add).toHaveBeenCalledWith( - "fit-file-import", + expect(flowMock.add).toHaveBeenCalledOnce(); + expect(latestFlow()).toEqual( expect.objectContaining({ - originalPath: - "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_999_weight.fit", - userId: "user-1", - providerId: GARMIN_DUMP_PROVIDER_ID, - sourceName: "Garmin Dump", + name: "fit-file-import-batch", + queueName: "fit-file-import-batch", + data: { type: "fit-file-import-batch" }, + opts: { + jobId: `garmin-dump-fit-batch:garmin-export.zip:${expectedFlowHash( + [ + "user-1", + filePath, + [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_999_weight.fit", + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_12345.fit", + ].join("\n"), + ].join("\n"), + )}`, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, + }, }), + ); + const fitChildren = latestFitFlowChildren(); + expect(fitChildren).toHaveLength(2); + expect(fitChildren[0]).toEqual( expect.objectContaining({ - removeOnComplete: { age: 86_400, count: 1_000 }, - removeOnFail: { age: 604_800, count: 1_000 }, + name: "fit-file-import", + queueName: "fit-file-import", + data: expect.objectContaining({ + originalPath: + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_999_weight.fit", + userId: "user-1", + providerId: GARMIN_DUMP_PROVIDER_ID, + sourceName: "Garmin Dump", + }), + opts: expect.objectContaining({ + jobId: `garmin-dump-fit:${expectedFlowHash( + [ + "user-1", + filePath, + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_999_weight.fit", + ].join("\n"), + )}`, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, + }), + children: [ + expect.objectContaining({ + name: "zip-entry-extract", + queueName: "zip-entry-extract", + data: expect.objectContaining({ + archivePath: filePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip", + "asher@example.com_999_weight.fit", + ], + outputExtension: "fit", + maxBytes: 128 * 1024 * 1024, + nestedArchiveMaxBytes: 1024 * 1024 * 1024, + }), + opts: { + ignoreDependencyOnFailure: true, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, + }, + }), + ], }), ); - expect(fitQueueMock.add).toHaveBeenCalledWith( - "fit-file-import", + expect(fitChildren[1]).toEqual( expect.objectContaining({ - originalPath: - "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_12345.fit", - userId: "user-1", - providerId: GARMIN_DUMP_PROVIDER_ID, - sourceName: "Garmin Dump", - activitySummary: expect.objectContaining({ - externalId: "12345", - activityType: "cycling", - name: "Morning Ride", - raw: expect.objectContaining({ activityId: 12345 }), + name: "fit-file-import", + queueName: "fit-file-import", + data: expect.objectContaining({ + originalPath: + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_12345.fit", + userId: "user-1", + providerId: GARMIN_DUMP_PROVIDER_ID, + sourceName: "Garmin Dump", + activitySummary: expect.objectContaining({ + externalId: "12345", + activityType: "cycling", + name: "Morning Ride", + raw: expect.objectContaining({ activityId: 12345 }), + }), + }), + opts: expect.objectContaining({ + jobId: `garmin-dump-fit:${expectedFlowHash( + [ + "user-1", + filePath, + "DI_CONNECT/DI-Connect-Uploaded-Files/UploadedFiles_0-_Part1.zip/asher@example.com_12345.fit", + ].join("\n"), + )}`, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, }), }), - expect.any(Object), ); expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); expect(mockParseFitFile).not.toHaveBeenCalled(); @@ -482,40 +662,90 @@ describe("Garmin dump provider", () => { }); it("fans out Garmin weight FIT files to child FIT import jobs", async () => { - fitQueueMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); const zip = await createZip({ - "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_20260701_weight.fit": createWeightFit(), }); const directory = await createTempDirectory(); const filePath = join(directory, "garmin-export.zip"); await writeFile(filePath, zip); - const onProgress = vi.fn(); - const result = await importGarminDumpFile(mockDb, filePath, "user-1", { onProgress }); + const result = await importGarminDumpFile(mockDb, filePath, "user-1"); - expect(result.recordsSynced).toBe(2); + expect(result.recordsSynced).toBe(1); expect(result.errors).toEqual([]); - expect(onProgress).toHaveBeenCalledWith({ - percentage: 25, - message: "Found 0 activity summaries and 2 FIT files.", - }); - expect(fitQueueMock.add).toHaveBeenCalledWith( - "fit-file-import", + expect(latestFitFlowChildren()).toEqual([ expect.objectContaining({ - originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_20260701_weight.fit", - userId: "user-1", - providerId: GARMIN_DUMP_PROVIDER_ID, - sourceName: "Garmin Dump", + name: "fit-file-import", + queueName: "fit-file-import", + data: expect.objectContaining({ + originalPath: + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_20260701_weight.fit", + userId: "user-1", + providerId: GARMIN_DUMP_PROVIDER_ID, + sourceName: "Garmin Dump", + }), + children: [ + expect.objectContaining({ + queueName: "zip-entry-extract", + data: expect.objectContaining({ + archivePath: filePath, + entryPath: [ + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_20260701_weight.fit", + ], + }), + }), + ], }), - expect.any(Object), - ); + ]); expect(mockWriteMetricStreamBatch).not.toHaveBeenCalled(); expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); }); - it("extends the import job lock before parsing FIT files", async () => { + it("uses distinct flow job IDs for uploads with the same archive basename", async () => { + const firstDirectory = await createTempDirectory(); + const secondDirectory = await createTempDirectory(); + const zip = await createZip({ + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", + }); + const firstFilePath = join(firstDirectory, "garmin-export.zip"); + const secondFilePath = join(secondDirectory, "garmin-export.zip"); + await writeFile(firstFilePath, zip); + await writeFile(secondFilePath, zip); + + await importGarminDumpFile(mockDb, firstFilePath, "user-1"); + const firstFlow = latestFlow(); + await importGarminDumpFile(mockDb, secondFilePath, "user-1"); + const secondFlow = latestFlow(); + + expect(firstFlow.opts).not.toEqual(secondFlow.opts); + expect(firstFlow.children?.[0]?.opts).not.toEqual(secondFlow.children?.[0]?.opts); + }); + + it("passes extracted directory FIT files directly to child FIT import jobs", async () => { + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + const directory = await createTempDirectory(); + const nestedDirectory = join(directory, "DI_CONNECT", "DI-Connect-Uploaded-Files"); + await mkdir(nestedDirectory, { recursive: true }); + const extractedFitPath = join(nestedDirectory, "asher@example.com_20260701_weight.fit"); + await writeFile(extractedFitPath, createWeightFit()); + + await importGarminDumpFile(mockDb, directory, "user-1"); + + expect(latestFitFlowChildren()).toEqual([ + expect.objectContaining({ + data: expect.objectContaining({ + filePath: extractedFitPath, + originalPath: + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_20260701_weight.fit", + }), + }), + ]); + expect(latestFitFlowChildren()[0]?.children).toBeUndefined(); + }); + + it("extends the import job lock before creating the FIT import flow", async () => { const filePath = await createGarminDumpZip(); const extendLock = vi.fn().mockResolvedValue(undefined); @@ -523,12 +753,12 @@ describe("Garmin dump provider", () => { expect(extendLock).toHaveBeenCalledWith(600_000); expect(extendLock.mock.invocationCallOrder[0]).toBeLessThan( - fitQueueMock.add.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER, + flowMock.add.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER, ); }); - it("reports progress while importing Garmin dump FIT child jobs", async () => { - fitQueueMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + it("reports progress while importing Garmin dump FIT flow jobs", async () => { + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 2, errors: [] }); const zip = await createZip({ "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_67890.fit": "fit-bytes", @@ -556,18 +786,15 @@ describe("Garmin dump provider", () => { percentage: 45, message: "Importing Garmin FIT files (0/2)...", }); - expect(onProgress).toHaveBeenCalledWith({ - percentage: 70, - message: "Importing Garmin FIT files (1/2)...", - }); expect(onProgress).toHaveBeenCalledWith({ percentage: 95, message: "Garmin dump import complete.", }); + expect(mockCaptureException).not.toHaveBeenCalled(); }); it("continues Garmin dump import when progress callbacks fail", async () => { - fitQueueMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 2, errors: [] }); const progressError = new Error("redis down"); const filePath = await createGarminDumpZip(); const onProgress = vi.fn().mockRejectedValue(progressError); @@ -575,14 +802,59 @@ describe("Garmin dump provider", () => { const result = await importGarminDumpFile(mockDb, filePath, "user-1", { onProgress }); expect(result.recordsSynced).toBe(3); - expect(fitQueueMock.add).toHaveBeenCalledTimes(2); + expect(flowMock.add).toHaveBeenCalledOnce(); expect(mockCaptureException).toHaveBeenCalledWith(progressError, { tags: { garminDumpStep: "progress" }, }); }); + it("reports a lock renewal failure that happens while waiting for the FIT flow", async () => { + const filePath = await createGarminDumpZip(); + let rejectRenewal: (error: Error) => void = () => undefined; + const deferredRenewal = new Promise((_, reject) => { + rejectRenewal = reject; + }); + const extendLock = vi + .fn() + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined) + .mockReturnValueOnce(deferredRenewal); + let renewalCallback: (() => void) | undefined; + const intervalHandle = setInterval(() => undefined, 60_000); + intervalHandle.unref?.(); + const setIntervalSpy = vi.spyOn(globalThis, "setInterval").mockImplementation((callback) => { + if (typeof callback !== "function") { + throw new Error("Expected lock renewal interval callback to be a function"); + } + renewalCallback = () => callback(); + return intervalHandle; + }); + const clearIntervalSpy = vi.spyOn(globalThis, "clearInterval").mockImplementation(() => {}); + flowMock.waitUntilFinished.mockImplementation(async () => { + renewalCallback?.(); + setTimeout(() => rejectRenewal(new Error("lost lock")), 0); + return { recordsSynced: 1, errors: [] }; + }); + + try { + const result = await importGarminDumpFile(mockDb, filePath, "user-1", { extendLock }); + + expect(result.recordsSynced).toBe(1); + expect(result.errors).toEqual([ + expect.objectContaining({ + message: "Failed to process Garmin FIT import jobs: lost lock", + }), + ]); + expect(clearIntervalSpy).toHaveBeenCalledWith(intervalHandle); + } finally { + setIntervalSpy.mockRestore(); + clearIntervalSpy.mockRestore(); + clearInterval(intervalHandle); + } + }); + it("keeps parse errors in import results and imports FIT-only activities", async () => { - fitQueueMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); const zip = await createZip({ "DI_CONNECT/DI-Connect-Fitness/asher_0_summarizedActivities.json": "{broken", "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_activity.fit": "fit-bytes", @@ -590,19 +862,18 @@ describe("Garmin dump provider", () => { const directory = await createTempDirectory(); const filePath = join(directory, "garmin-export.zip"); await writeFile(filePath, zip); - const onProgress = vi.fn(); - const result = await importGarminDumpFile(mockDb, filePath, "user-1", { onProgress }); + const result = await importGarminDumpFile(mockDb, filePath, "user-1"); expect(result.recordsSynced).toBe(1); expect(result.errors[0]?.message).toContain("Failed to parse Garmin summarized activities"); - expect(fitQueueMock.add).toHaveBeenCalledWith( - "fit-file-import", + expect(latestFitFlowChildren()).toEqual([ expect.objectContaining({ - originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_activity.fit", + data: expect.objectContaining({ + originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_activity.fit", + }), }), - expect.any(Object), - ); + ]); expect(mockUpsertProviderActivity).not.toHaveBeenCalled(); }); @@ -623,21 +894,86 @@ describe("Garmin dump provider", () => { const directory = await createTempDirectory(); const filePath = join(directory, "garmin-export.zip"); await writeFile(filePath, zip); - const onProgress = vi.fn(); - const result = await importGarminDumpFile(mockDb, filePath, "user-1", { onProgress }); + const result = await importGarminDumpFile(mockDb, filePath, "user-1"); expect(result.recordsSynced).toBe(0); expect(result.errors).toEqual([ { message: "Garmin activity 12345 is missing a valid start time" }, ]); expect(mockUpsertProviderActivity).not.toHaveBeenCalled(); - expect(fitQueueMock.add).not.toHaveBeenCalled(); + expect(flowMock.add).not.toHaveBeenCalled(); expect(mockParseFitFile).not.toHaveBeenCalled(); }); + it("records invalid activity summaries again when matching FIT files cannot receive metadata", async () => { + const zip = await createZip({ + "DI_CONNECT/DI-Connect-Fitness/asher_0_summarizedActivities.json": JSON.stringify([ + { + summarizedActivitiesExport: [ + { + activityId: 12345, + activityType: "cycling", + }, + ], + }, + ]), + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", + }); + const directory = await createTempDirectory(); + const filePath = join(directory, "garmin-export.zip"); + await writeFile(filePath, zip); + + const result = await importGarminDumpFile(mockDb, filePath, "user-1"); + + expect(result.recordsSynced).toBe(0); + expect(result.errors).toEqual([ + { message: "Garmin activity 12345 is missing a valid start time" }, + { message: "Garmin activity 12345 is missing a valid start time" }, + ]); + expect(flowMock.add).not.toHaveBeenCalled(); + }); + + it("matches summarized activities to FIT files with Garmin suffixes after the activity ID", async () => { + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + const zip = await createZip({ + "DI_CONNECT/DI-Connect-Fitness/asher_0_summarizedActivities.json": JSON.stringify([ + { + summarizedActivitiesExport: [ + { + activityId: 12345, + name: "Suffix Ride", + activityType: "cycling", + startTimeGmt: Date.parse("2026-07-01T12:00:00.000Z"), + duration: 1800000, + }, + ], + }, + ]), + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345_extra.fit": "fit-bytes", + }); + const directory = await createTempDirectory(); + const filePath = join(directory, "garmin-export.zip"); + await writeFile(filePath, zip); + + const result = await importGarminDumpFile(mockDb, filePath, "user-1"); + + expect(result.recordsSynced).toBe(2); + expect(latestFitFlowChildren()).toEqual([ + expect.objectContaining({ + data: expect.objectContaining({ + originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345_extra.fit", + activitySummary: expect.objectContaining({ + externalId: "12345", + name: "Suffix Ride", + }), + }), + }), + ]); + }); + it("fans out repeated FIT files to one child job per file", async () => { - fitQueueMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 1, errors: [] }); + flowMock.waitUntilFinished.mockResolvedValue({ recordsSynced: 2, errors: [] }); const zip = await createZip({ "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", "DI_CONNECT/DI-Connect-Uploaded-Files/copy/asher@example.com_12345_extra.fit": "fit-bytes", @@ -649,24 +985,21 @@ describe("Garmin dump provider", () => { const result = await importGarminDumpFile(mockDb, filePath, "user-1"); expect(result.recordsSynced).toBe(2); - expect(fitQueueMock.add).toHaveBeenCalledTimes(2); - expect(fitQueueMock.add.mock.calls.map((call) => call[1])).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit", - }), - expect.objectContaining({ - originalPath: - "DI_CONNECT/DI-Connect-Uploaded-Files/copy/asher@example.com_12345_extra.fit", - }), - ]), - ); + expect(flowMock.add).toHaveBeenCalledOnce(); + expect(latestFitFlowChildren().map((child) => child.data)).toEqual([ + expect.objectContaining({ + originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit", + }), + expect.objectContaining({ + originalPath: "DI_CONNECT/DI-Connect-Uploaded-Files/copy/asher@example.com_12345_extra.fit", + }), + ]); expect(mockParseFitFileInWorkerThread).not.toHaveBeenCalled(); expect(mockParseFitFile).not.toHaveBeenCalled(); expect(mockUpsertProviderActivity).not.toHaveBeenCalled(); }); - it("queues every child FIT job before waiting for child completion", async () => { + it("creates one flow containing every child FIT job before waiting for batch completion", async () => { const fitEntries = Object.fromEntries( Array.from({ length: 17 }, (_, activityIndex) => [ `DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_${activityIndex + 1}.fit`, @@ -677,25 +1010,22 @@ describe("Garmin dump provider", () => { const directory = await createTempDirectory(); const filePath = join(directory, "garmin-export.zip"); await writeFile(filePath, zip); - const pendingResolutions: Array<(result: { recordsSynced: number; errors: [] }) => void> = []; - fitQueueMock.waitUntilFinished.mockImplementation( + let resolveBatch: + | ((result: { recordsSynced: number; errors: Array<{ message: string }> }) => void) + | undefined; + flowMock.waitUntilFinished.mockImplementation( () => new Promise((resolve) => { - pendingResolutions.push(resolve); + resolveBatch = resolve; }), ); const importPromise = importGarminDumpFile(mockDb, filePath, "user-1"); - await waitUntil(() => expect(fitQueueMock.add).toHaveBeenCalledTimes(17)); - expect(pendingResolutions).toHaveLength(16); - - for (const resolvePending of pendingResolutions.splice(0)) { - resolvePending({ recordsSynced: 1, errors: [] }); - } - - await waitUntil(() => expect(pendingResolutions).toHaveLength(1)); - pendingResolutions[0]?.({ recordsSynced: 1, errors: [] }); + await waitUntil(() => expect(flowMock.add).toHaveBeenCalledOnce()); + expect(latestFitFlowChildren()).toHaveLength(17); + expect(resolveBatch).toBeDefined(); + resolveBatch?.({ recordsSynced: 17, errors: [] }); const result = await importPromise; @@ -703,10 +1033,11 @@ describe("Garmin dump provider", () => { expect(result.errors).toEqual([]); }); - it("aggregates child FIT errors without dropping successful child results", async () => { - fitQueueMock.waitUntilFinished - .mockRejectedValueOnce(new Error("bad first copy")) - .mockResolvedValueOnce({ recordsSynced: 1, errors: [] }); + it("aggregates child FIT errors from the batch parent result", async () => { + flowMock.waitUntilFinished.mockResolvedValue({ + recordsSynced: 1, + errors: [{ message: "Failed to import Garmin FIT file copy: bad first copy" }], + }); const zip = await createZip({ "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", "DI_CONNECT/DI-Connect-Uploaded-Files/copy/asher@example.com_12345_extra.fit": "fit-bytes", @@ -714,31 +1045,20 @@ describe("Garmin dump provider", () => { const directory = await createTempDirectory(); const filePath = join(directory, "garmin-export.zip"); await writeFile(filePath, zip); - const onProgress = vi.fn(); - const result = await importGarminDumpFile(mockDb, filePath, "user-1", { onProgress }); + const result = await importGarminDumpFile(mockDb, filePath, "user-1"); expect(result.recordsSynced).toBe(1); expect(result.errors).toEqual([ expect.objectContaining({ - message: - "Failed to import Garmin FIT file DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit: bad first copy", + message: "Failed to import Garmin FIT file copy: bad first copy", }), ]); - expect(fitQueueMock.add).toHaveBeenCalledTimes(2); - expect(onProgress).toHaveBeenCalledWith({ - percentage: 70, - message: "Importing Garmin FIT files (1/2)...", - }); - expect(onProgress).toHaveBeenCalledWith({ - percentage: 95, - message: "Importing Garmin FIT files (2/2)...", - }); - expect(mockCaptureException).not.toHaveBeenCalled(); + expect(latestFitFlowChildren()).toHaveLength(2); }); - it("reports malformed child FIT results to Sentry", async () => { - fitQueueMock.waitUntilFinished.mockResolvedValueOnce({ recordsSynced: "one", errors: [] }); + it("reports FIT flow failures", async () => { + flowMock.waitUntilFinished.mockRejectedValue(new Error("bad fit")); const zip = await createZip({ "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", }); @@ -751,32 +1071,30 @@ describe("Garmin dump provider", () => { expect(result.recordsSynced).toBe(0); expect(result.errors).toEqual([ expect.objectContaining({ - message: - "Failed to import Garmin FIT file DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit: unexpected result shape from FIT import job", + message: "Failed to process Garmin FIT import jobs: bad fit", }), ]); expect(mockCaptureException).toHaveBeenCalledWith(expect.any(Error), { - tags: { garminDumpStep: "fit-child-import-result" }, + tags: { garminDumpStep: "fit-flow" }, }); + expect(mockCaptureException.mock.calls[0]?.[0]).toEqual(new Error("bad fit")); }); - it("reports FIT child job failures with the extracted file path", async () => { - fitQueueMock.waitUntilFinished.mockRejectedValue(new Error("bad fit")); - const zip = await createZip({ - "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", - }); + it("removes temporary extraction directories after importing a ZIP dump", async () => { const directory = await createTempDirectory(); const filePath = join(directory, "garmin-export.zip"); - await writeFile(filePath, zip); + await writeFile( + filePath, + await createZip({ + "DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit": "fit-bytes", + }), + ); - const result = await importGarminDumpFile(mockDb, filePath, "user-1"); + await importGarminDumpFile(mockDb, filePath, "user-1"); - expect(result.recordsSynced).toBe(0); - expect(result.errors).toEqual([ - expect.objectContaining({ - message: - "Failed to import Garmin FIT file DI_CONNECT/DI-Connect-Uploaded-Files/asher@example.com_12345.fit: bad fit", - }), - ]); + const remainingEntries = await readdir(directory); + expect( + remainingEntries.filter((entryName) => entryName.startsWith("garmin-export.zip-extract-")), + ).toEqual([]); }); }); diff --git a/src/providers/garmin-dump.ts b/src/providers/garmin-dump.ts index ebe2c3c0d8..75ffc265e9 100644 --- a/src/providers/garmin-dump.ts +++ b/src/providers/garmin-dump.ts @@ -1,21 +1,26 @@ import { createHash } from "node:crypto"; -import { mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { createWriteStream } from "node:fs"; +import { mkdtemp, readdir, readFile, rm, stat } from "node:fs/promises"; import { basename, dirname, join, relative } from "node:path"; import type { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; import type { CanonicalActivityType } from "@dofek/training/training"; import * as Sentry from "@sentry/node"; +import type { FlowChildJob } from "bullmq"; import yauzl from "yauzl"; import { z } from "zod"; import type { SyncDatabase } from "../db/index.ts"; import { upsertProviderActivity } from "../db/provider-activity-sync.ts"; import { ensureProvider } from "../db/tokens.ts"; -import { fitExternalId } from "../fit/external-id.ts"; import type { ParsedFitSession } from "../fit/parser.ts"; import type { FitFileImportJobResult } from "../jobs/process-fit-file-import-job.ts"; import { + FIT_FILE_IMPORT_BATCH_QUEUE, + FIT_FILE_IMPORT_QUEUE, type FitFileImportJobData, - getFitFileImportQueue, - getFitFileImportQueueEvents, + getFitFileImportBatchQueueEvents, + getFlowProducer, + ZIP_ENTRY_EXTRACT_QUEUE, } from "../jobs/queues.ts"; import { logger } from "../logger.ts"; import type { ImportProvider, SyncError, SyncResult } from "./types.ts"; @@ -27,7 +32,6 @@ const MAX_GARMIN_DUMP_ENTRY_BYTES = 128 * 1024 * 1024; const MAX_GARMIN_DUMP_NESTED_ZIP_BYTES = 1024 * 1024 * 1024; const MAX_GARMIN_DUMP_EXTRACTED_BYTES = 4 * 1024 * 1024 * 1024; const GARMIN_DUMP_IMPORT_LOCK_EXTENSION_MS = 10 * 60 * 1000; -const FIT_FILE_IMPORT_BATCH_SIZE = 16; const summarizedActivitySchema = z .object({ @@ -55,7 +59,9 @@ const summarizedActivitiesSuffix = `_${"summarized"}${"activities"}.json`; interface GarminDumpEntry { path: string; - data: Buffer; + archivePath?: string; + entryPath?: string[]; + filePath?: string; } interface ParsedGarminDump { @@ -63,6 +69,7 @@ interface ParsedGarminDump { fitFiles: GarminDumpEntry[]; weightFitFiles: GarminDumpEntry[]; errors: SyncError[]; + tempDirectories: string[]; } interface GarminDumpExtractionState { @@ -84,6 +91,11 @@ const fitFileImportJobResultSchema = z.object({ errors: z.array(z.object({ message: z.string() })), }); +const GARMIN_DUMP_LOCK_RENEWAL_INTERVAL_MS = 4 * 60 * 1000; +const FIT_FILE_IMPORT_JOB_NAME = "fit-file-import"; +const FIT_FILE_IMPORT_BATCH_JOB_NAME = "fit-file-import-batch"; +const ZIP_ENTRY_EXTRACT_JOB_NAME = "zip-entry-extract"; + const GARMIN_ACTIVITY_TYPE_MAP: Readonly> = { cycling: "cycling", road_biking: "cycling", @@ -148,6 +160,12 @@ function isGarminWeightFitPath(path: string): boolean { return /_weights?\.fit$/i.test(path); } +function fitExternalIdFromPath(path: string): string | null { + const fileName = path.split("/").pop() ?? path; + const match = fileName.match(/_(\d+)(?:_[^/]*)?\.fit$/i); + return match?.[1] ?? null; +} + function assertGarminDumpSize(byteCount: number, maxBytes: number, description: string): void { if (byteCount > maxBytes) { throw new Error(`${description} exceeds maximum size of ${maxBytes} bytes`); @@ -185,28 +203,33 @@ function countExtractedBytes( ); } -async function streamToBuffer( +async function streamToFile( stream: Readable, + filePath: string, maxBytes: number, description: string, -): Promise { - const chunks: Buffer[] = []; +): Promise { let bytesRead = 0; - for await (const chunk of stream) { - const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); - bytesRead += buffer.length; - if (bytesRead > maxBytes) { - stream.destroy(new Error(`${description} exceeds maximum size of ${maxBytes} bytes`)); - throw new Error(`${description} exceeds maximum size of ${maxBytes} bytes`); - } - chunks.push(buffer); - } - return Buffer.concat(chunks); + await pipeline( + stream, + async function* limitBytes(source) { + for await (const chunk of source) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + bytesRead += buffer.length; + if (bytesRead > maxBytes) { + throw new Error(`${description} exceeds maximum size of ${maxBytes} bytes`); + } + yield buffer; + } + }, + createWriteStream(filePath, { flags: "wx" }), + ); + return bytesRead; } -function openZipFromBuffer(buffer: Buffer): Promise { +function openZipFromPath(filePath: string): Promise { return new Promise((resolve, reject) => { - yauzl.fromBuffer(buffer, { lazyEntries: true }, (error, zipFile) => { + yauzl.open(filePath, { lazyEntries: true }, (error, zipFile) => { if (error) { reject(error); return; @@ -220,6 +243,12 @@ function openZipFromBuffer(buffer: Buffer): Promise { }); } +function shouldReadGarminDumpEntry(lowerPath: string): boolean { + if (lowerPath.endsWith(".fit")) return true; + if (lowerPath.endsWith(summarizedActivitiesSuffix)) return true; + return lowerPath.endsWith(".zip") && lowerPath.includes("/di-connect-uploaded-files/"); +} + function openReadStream(zipFile: yauzl.ZipFile, entry: yauzl.Entry): Promise { return new Promise((resolve, reject) => { zipFile.openReadStream(entry, (error, stream) => { @@ -264,11 +293,14 @@ function readNextZipEntry(zipFile: yauzl.ZipFile): Promise { } async function collectZipEntries( - buffer: Buffer, + rootArchivePath: string, + zipPath: string, + extractionDirectory: string, prefix = "", + entryPathPrefix: string[] = [], state: GarminDumpExtractionState = { extractedBytes: 0 }, ): Promise { - const zipFile = await openZipFromBuffer(buffer); + const zipFile = await openZipFromPath(zipPath); const entries: GarminDumpEntry[] = []; try { @@ -279,26 +311,80 @@ async function collectZipEntries( const path = `${prefix}${entry.fileName}`; const lowerPath = path.toLowerCase(); + if (!shouldReadGarminDumpEntry(lowerPath)) continue; + const maxEntryBytes = lowerPath.endsWith(".zip") ? MAX_GARMIN_DUMP_NESTED_ZIP_BYTES : MAX_GARMIN_DUMP_ENTRY_BYTES; assertGarminDumpSize(entry.uncompressedSize, maxEntryBytes, `Garmin dump entry ${path}`); - const stream = await openReadStream(zipFile, entry); - const data = await streamToBuffer(stream, maxEntryBytes, `Garmin dump entry ${path}`); - countExtractedBytes(state, data.length, path); if (lowerPath.endsWith(".zip")) { - entries.push(...(await collectZipEntries(data, `${path}/`, state))); - } else { - entries.push({ path, data }); + const nestedEntryPath = [...entryPathPrefix, entry.fileName]; + const stream = await openReadStream(zipFile, entry); + const nestedZipPath = join( + extractionDirectory, + `${createHash("sha256").update(path).digest("hex")}.zip`, + ); + const bytesRead = await streamToFile( + stream, + nestedZipPath, + maxEntryBytes, + `Garmin dump entry ${path}`, + ); + countExtractedBytes(state, bytesRead, path); + entries.push( + ...(await collectZipEntries( + rootArchivePath, + nestedZipPath, + extractionDirectory, + `${path}/`, + nestedEntryPath, + state, + )), + ); + await rm(nestedZipPath, { force: true }); + continue; + } + + if (lowerPath.endsWith(summarizedActivitiesSuffix)) { + const filePath = join( + extractionDirectory, + `${createHash("sha256").update(path).digest("hex")}.json`, + ); + const stream = await openReadStream(zipFile, entry); + const bytesRead = await streamToFile( + stream, + filePath, + maxEntryBytes, + `Garmin dump entry ${path}`, + ); + countExtractedBytes(state, bytesRead, path); + entries.push({ + path, + filePath, + archivePath: rootArchivePath, + entryPath: [...entryPathPrefix, entry.fileName], + }); + continue; } + + countExtractedBytes(state, entry.uncompressedSize, path); + entries.push({ + path, + archivePath: rootArchivePath, + entryPath: [...entryPathPrefix, entry.fileName], + }); } } finally { zipFile.close(); } } -async function collectDirectoryEntries(rootPath: string): Promise { +async function collectDirectoryEntries(rootPath: string): Promise<{ + entries: GarminDumpEntry[]; + tempDirectories: string[]; +}> { const entries: GarminDumpEntry[] = []; + const tempDirectories: string[] = []; const state: GarminDumpExtractionState = { extractedBytes: 0 }; async function visit(directoryPath: string): Promise { @@ -314,22 +400,34 @@ async function collectDirectoryEntries(rootPath: string): Promise { @@ -340,45 +438,65 @@ export async function parseGarminDumpFile(filePath: string): Promise rm(directory, { recursive: true, force: true })), + ); + throw error; + } } function garminSummaryToFitJobSummary( @@ -399,100 +517,120 @@ function garminSummaryToFitJobSummary( }; } -async function enqueueFitFileImportJobs( - entries: Array<{ entry: GarminDumpEntry; data: Omit }>, +function fitFileImportFlowChild( uploadPath: string, - onJobFinished: (completedCount: number, totalCount: number) => void | Promise, -): Promise { - if (entries.length === 0) return []; + userId: string, + entry: GarminDumpEntry, + data: Omit, +): FlowChildJob { + const fitImportData: FitFileImportJobData = entry.filePath + ? { ...data, filePath: entry.filePath } + : data; + const children = + entry.archivePath && entry.entryPath + ? [ + { + name: ZIP_ENTRY_EXTRACT_JOB_NAME, + queueName: ZIP_ENTRY_EXTRACT_QUEUE, + data: { + archivePath: entry.archivePath, + entryPath: entry.entryPath, + outputExtension: "fit", + maxBytes: MAX_GARMIN_DUMP_ENTRY_BYTES, + nestedArchiveMaxBytes: MAX_GARMIN_DUMP_NESTED_ZIP_BYTES, + }, + opts: { + ignoreDependencyOnFailure: true, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, + }, + }, + ] + : undefined; - const tempDirectory = await mkdtemp(join(dirname(uploadPath), `${basename(uploadPath)}-fit-`)); - const queue = getFitFileImportQueue(); - const queueEvents = getFitFileImportQueueEvents(); + return { + name: FIT_FILE_IMPORT_JOB_NAME, + queueName: FIT_FILE_IMPORT_QUEUE, + data: fitImportData, + opts: { + jobId: `garmin-dump-fit:${createHash("sha256") + .update(`${userId}\n${uploadPath}\n${entry.path}`) + .digest("hex")}`, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, + }, + ...(children ? { children } : {}), + }; +} - try { - const jobs: Array<{ - entry: GarminDumpEntry; - job: Awaited>; - }> = []; - for ( - let startIndex = 0; - startIndex < entries.length; - startIndex += FIT_FILE_IMPORT_BATCH_SIZE - ) { - const batch = entries.slice(startIndex, startIndex + FIT_FILE_IMPORT_BATCH_SIZE); - jobs.push( - ...(await Promise.all( - batch.map(async ({ entry, data }, entryIndex) => { - const absoluteEntryIndex = startIndex + entryIndex; - const filePath = join( - tempDirectory, - `${absoluteEntryIndex}-${createHash("sha256").update(entry.path).digest("hex")}.fit`, - ); - await writeFile(filePath, entry.data); - const job = await queue.add( - "fit-file-import", - { ...data, filePath }, - { - removeOnComplete: { age: 86_400, count: 1_000 }, - removeOnFail: { age: 604_800, count: 1_000 }, - }, - ); - return { entry, job }; - }), - )), - ); - } +async function enqueueFitFileImportFlow( + entries: Array<{ entry: GarminDumpEntry; data: Omit }>, + uploadPath: string, + userId: string, +): Promise { + if (entries.length === 0) return { recordsSynced: 0, errors: [] }; + + const flow = await getFlowProducer().add({ + name: FIT_FILE_IMPORT_BATCH_JOB_NAME, + queueName: FIT_FILE_IMPORT_BATCH_QUEUE, + data: { type: "fit-file-import-batch" }, + opts: { + jobId: `garmin-dump-fit-batch:${basename(uploadPath)}:${createHash("sha256") + .update(`${userId}\n${uploadPath}\n${entries.map(({ entry }) => entry.path).join("\n")}`) + .digest("hex")}`, + removeOnComplete: { age: 86_400, count: 1_000 }, + removeOnFail: { age: 604_800, count: 1_000 }, + }, + children: entries.map(({ entry, data }) => + fitFileImportFlowChild(uploadPath, userId, entry, data), + ), + }); - const results: FitFileImportJobResult[] = []; - let completedCount = 0; - for (let startIndex = 0; startIndex < jobs.length; startIndex += FIT_FILE_IMPORT_BATCH_SIZE) { - const batch = jobs.slice(startIndex, startIndex + FIT_FILE_IMPORT_BATCH_SIZE); - results.push( - ...(await Promise.all( - batch.map(async ({ entry, job }) => { - let result: FitFileImportJobResult; - try { - const jobResult = await job.waitUntilFinished(queueEvents); - const parsedResult = fitFileImportJobResultSchema.safeParse(jobResult); - if (parsedResult.success) { - result = parsedResult.data; - } else { - Sentry.captureException(parsedResult.error, { - tags: { garminDumpStep: "fit-child-import-result" }, - }); - result = { - recordsSynced: 0, - errors: [ - { - message: `Failed to import Garmin FIT file ${entry.path}: unexpected result shape from FIT import job`, - }, - ], - }; - } - } catch (error) { - result = { - recordsSynced: 0, - errors: [ - { - message: `Failed to import Garmin FIT file ${entry.path}: ${ - error instanceof Error ? error.message : String(error) - }`, - }, - ], - }; - } - completedCount++; - await onJobFinished(completedCount, jobs.length); - return result; - }), - )), - ); - } - return results; - } finally { - await rm(tempDirectory, { recursive: true, force: true }); + return fitFileImportJobResultSchema.parse( + await flow.job.waitUntilFinished(getFitFileImportBatchQueueEvents()), + ); +} + +function startGarminDumpImportLockRenewal(options: GarminDumpImportOptions): { + stop: () => Promise; + throwIfFailed: () => Promise; +} { + if (!options.extendLock) { + return { + stop: async () => undefined, + throwIfFailed: async () => undefined, + }; } + + const extendLock = options.extendLock; + let renewalError: unknown; + let activeRenewal: Promise | null = null; + const renewLock = (): Promise => { + if (activeRenewal) return activeRenewal; + activeRenewal = extendLock(GARMIN_DUMP_IMPORT_LOCK_EXTENSION_MS) + .catch((error: unknown) => { + renewalError = error; + }) + .finally(() => { + activeRenewal = null; + }); + return activeRenewal; + }; + const interval = setInterval(() => { + void renewLock(); + }, GARMIN_DUMP_LOCK_RENEWAL_INTERVAL_MS); + interval.unref?.(); + + return { + stop: async () => { + clearInterval(interval); + await activeRenewal; + }, + throwIfFailed: async () => { + await activeRenewal; + if (renewalError) throw renewalError; + }, + }; } export async function importGarminDumpFile( @@ -504,127 +642,135 @@ export async function importGarminDumpFile( const start = Date.now(); await reportGarminDumpProgress(options, 0, "Starting Garmin dump import..."); await extendGarminDumpImportLock(options); - await reportGarminDumpProgress(options, 5, "Reading Garmin dump..."); - const parsedDump = await parseGarminDumpFile(filePath); - const totalFitFileCount = parsedDump.fitFiles.length + parsedDump.weightFitFiles.length; - await reportGarminDumpProgress( - options, - 25, - `Found ${parsedDump.summaries.length} activity summaries and ${totalFitFileCount} FIT files.`, - ); - const errors: SyncError[] = [...parsedDump.errors]; + const lockRenewal = startGarminDumpImportLockRenewal(options); + const errors: SyncError[] = []; let recordsSynced = 0; + let parsedDump: ParsedGarminDump | null = null; const summaryByExternalId = new Map(); - await ensureProvider(db, GARMIN_DUMP_PROVIDER_ID, GARMIN_DUMP_PROVIDER_NAME, undefined, userId); + try { + await reportGarminDumpProgress(options, 5, "Reading Garmin dump..."); + parsedDump = await parseGarminDumpFile(filePath); + await lockRenewal.throwIfFailed(); + errors.push(...parsedDump.errors); + const totalFitFileCount = parsedDump.fitFiles.length + parsedDump.weightFitFiles.length; + await reportGarminDumpProgress( + options, + 25, + `Found ${parsedDump.summaries.length} activity summaries and ${totalFitFileCount} FIT files.`, + ); - for (const summary of parsedDump.summaries) { - const externalId = String(summary.activityId); - summaryByExternalId.set(externalId, summary); - const startedAt = timestampFromSummary(summary); - if (!startedAt) { - errors.push({ message: `Garmin activity ${externalId} is missing a valid start time` }); - continue; + await ensureProvider(db, GARMIN_DUMP_PROVIDER_ID, GARMIN_DUMP_PROVIDER_NAME, undefined, userId); + + for (const summary of parsedDump.summaries) { + const externalId = String(summary.activityId); + summaryByExternalId.set(externalId, summary); + const startedAt = timestampFromSummary(summary); + if (!startedAt) { + errors.push({ message: `Garmin activity ${externalId} is missing a valid start time` }); + continue; + } + + const activityType = mapGarminDumpActivityType(summary.activityType, summary.sportType); + const name = summary.name ?? `Garmin ${activityType.replace(/_/g, " ")}`; + const endedAt = new Date(startedAt.getTime() + durationMilliseconds(summary)); + await upsertProviderActivity( + db, + { + providerId: GARMIN_DUMP_PROVIDER_ID, + userId, + externalId, + activityType, + startedAt, + endedAt, + name, + sourceName: GARMIN_DUMP_PROVIDER_NAME, + raw: summary, + }, + { + activityType, + startedAt, + endedAt, + name, + sourceName: GARMIN_DUMP_PROVIDER_NAME, + raw: summary, + }, + ); + recordsSynced++; } - const activityType = mapGarminDumpActivityType(summary.activityType, summary.sportType); - const name = summary.name ?? `Garmin ${activityType.replace(/_/g, " ")}`; - const endedAt = new Date(startedAt.getTime() + durationMilliseconds(summary)); - await upsertProviderActivity( - db, - { - providerId: GARMIN_DUMP_PROVIDER_ID, + const fitJobEntries: Array<{ + entry: GarminDumpEntry; + data: Omit; + }> = parsedDump.weightFitFiles.map((entry) => ({ + entry, + data: { + originalPath: entry.path, userId, - externalId, - activityType, - startedAt, - endedAt, - name, - sourceName: GARMIN_DUMP_PROVIDER_NAME, - raw: summary, - }, - { - activityType, - startedAt, - endedAt, - name, + providerId: GARMIN_DUMP_PROVIDER_ID, sourceName: GARMIN_DUMP_PROVIDER_NAME, - raw: summary, }, - ); - recordsSynced++; - } + })); - const fitJobEntries: Array<{ - entry: GarminDumpEntry; - data: Omit; - }> = parsedDump.weightFitFiles.map((entry) => ({ - entry, - data: { - originalPath: entry.path, - userId, - providerId: GARMIN_DUMP_PROVIDER_ID, - sourceName: GARMIN_DUMP_PROVIDER_NAME, - }, - })); - - for (const fitFile of parsedDump.fitFiles) { - const externalId = fitExternalId(fitFile.path, fitFile.data); - if (summaryByExternalId.size > 0 && !summaryByExternalId.has(externalId)) { - continue; - } - const summary = summaryByExternalId.get(externalId); - const activitySummary = summary ? garminSummaryToFitJobSummary(summary) : undefined; - if (summary && !activitySummary) { - errors.push({ message: `Garmin activity ${externalId} is missing a valid start time` }); - continue; - } - const jobData: Omit = { - originalPath: fitFile.path, - userId, - providerId: GARMIN_DUMP_PROVIDER_ID, - sourceName: GARMIN_DUMP_PROVIDER_NAME, - }; - if (activitySummary) { - jobData.activitySummary = activitySummary; + for (const fitFile of parsedDump.fitFiles) { + const externalId = fitExternalIdFromPath(fitFile.path); + if (summaryByExternalId.size > 0 && (!externalId || !summaryByExternalId.has(externalId))) { + continue; + } + const summary = externalId ? summaryByExternalId.get(externalId) : undefined; + const activitySummary = summary ? garminSummaryToFitJobSummary(summary) : undefined; + if (summary && !activitySummary) { + errors.push({ message: `Garmin activity ${externalId} is missing a valid start time` }); + continue; + } + const jobData: Omit = { + originalPath: fitFile.path, + userId, + providerId: GARMIN_DUMP_PROVIDER_ID, + sourceName: GARMIN_DUMP_PROVIDER_NAME, + }; + if (activitySummary) { + jobData.activitySummary = activitySummary; + } + fitJobEntries.push({ + entry: fitFile, + data: jobData, + }); } - fitJobEntries.push({ - entry: fitFile, - data: jobData, - }); - } - try { - await extendGarminDumpImportLock(options); - await reportGarminDumpProgress( - options, - 45, - `Importing Garmin FIT files (0/${fitJobEntries.length})...`, - ); - const fitResults = await enqueueFitFileImportJobs( - fitJobEntries, - filePath, - async (completedCount, totalCount) => { - await reportGarminDumpProgress( - options, - Math.floor(45 + (completedCount / totalCount) * 50), - `Importing Garmin FIT files (${completedCount}/${totalCount})...`, - ); - }, - ); - for (const result of fitResults) { - recordsSynced += result.recordsSynced; - for (const error of result.errors) { + try { + await extendGarminDumpImportLock(options); + await reportGarminDumpProgress( + options, + 45, + `Importing Garmin FIT files (0/${fitJobEntries.length})...`, + ); + const fitResults = await enqueueFitFileImportFlow(fitJobEntries, filePath, userId); + await lockRenewal.throwIfFailed(); + recordsSynced += fitResults.recordsSynced; + for (const error of fitResults.errors) { errors.push(error); } + } catch (error) { + Sentry.captureException(error, { + tags: { garminDumpStep: "fit-flow" }, + }); + errors.push({ + message: `Failed to process Garmin FIT import jobs: ${ + error instanceof Error ? error.message : String(error) + }`, + cause: error, + }); + } + } finally { + await lockRenewal.stop(); + if (parsedDump) { + await Promise.all( + parsedDump.tempDirectories.map((directory) => + rm(directory, { recursive: true, force: true }), + ), + ); } - } catch (error) { - errors.push({ - message: `Failed to process Garmin FIT import jobs: ${ - error instanceof Error ? error.message : String(error) - }`, - cause: error, - }); } await reportGarminDumpProgress(options, 95, "Garmin dump import complete.");