mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
fix(release): harden v1.31 arrival contracts
This commit is contained in:
1 parent
44add3bc1e
commit
4591899657
98 files changed
+5560
-1600
No files matched your search
@@ -14,7 +14,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
const { findManyMock, createManyMock, updateMock, addWarningMock } = vi.hoisted(
|
||||
() => ({
|
||||
findManyMock: vi.fn(async () => [] as unknown[]),
|
||||
createManyMock: vi.fn(async () => ({ count: 0 })),
|
||||
createManyMock: vi.fn<
|
||||
() => Promise<
|
||||
Array<{ id: string; type: "DAILY_STEPS"; measuredAt: Date }>
|
||||
>
|
||||
>(async () => []),
|
||||
updateMock: vi.fn(async () => ({})),
|
||||
addWarningMock: vi.fn(),
|
||||
}),
|
||||
@@ -24,7 +28,7 @@ vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: {
|
||||
findMany: findManyMock,
|
||||
createMany: createManyMock,
|
||||
createManyAndReturn: createManyMock,
|
||||
update: updateMock,
|
||||
},
|
||||
},
|
||||
@@ -67,7 +71,7 @@ const STEPS_READING = {
|
||||
|
||||
beforeEach(() => {
|
||||
findManyMock.mockReset().mockResolvedValue([]);
|
||||
createManyMock.mockReset().mockResolvedValue({ count: 0 });
|
||||
createManyMock.mockReset().mockResolvedValue([]);
|
||||
updateMock.mockReset().mockResolvedValue({});
|
||||
addWarningMock.mockReset();
|
||||
});
|
||||
@@ -118,7 +122,9 @@ describe("upsertFitbitMeasurements — tombstones resurrect", () => {
|
||||
});
|
||||
|
||||
it("still creates a genuinely fresh key", async () => {
|
||||
createManyMock.mockResolvedValue({ count: 1 });
|
||||
createManyMock.mockResolvedValue([
|
||||
{ id: "inserted-1", type: "DAILY_STEPS", measuredAt: new Date() },
|
||||
]);
|
||||
const { imported } = await upsertFitbitMeasurements(
|
||||
"user-1",
|
||||
[STEPS_READING],
|
||||
@@ -218,7 +224,9 @@ describe("upsertFitbitMeasurements — natural-key migration rescue", () => {
|
||||
|
||||
it("creates normally when no natural-key twin exists", async () => {
|
||||
findManyMock.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
createManyMock.mockResolvedValue({ count: 1 });
|
||||
createManyMock.mockResolvedValue([
|
||||
{ id: "inserted-1", type: "DAILY_STEPS", measuredAt: new Date() },
|
||||
]);
|
||||
const { imported } = await upsertFitbitMeasurements(
|
||||
"user-1",
|
||||
[STEPS_READING],
|
||||
@@ -236,7 +244,9 @@ describe("upsertFitbitMeasurements — natural-key migration rescue", () => {
|
||||
findManyMock
|
||||
.mockResolvedValueOnce([]) // externalId probe
|
||||
.mockRejectedValueOnce(new Error("db down")); // natural-key rescue probe
|
||||
createManyMock.mockResolvedValue({ count: 1 });
|
||||
createManyMock.mockResolvedValue([
|
||||
{ id: "inserted-1", type: "DAILY_STEPS", measuredAt: new Date() },
|
||||
]);
|
||||
|
||||
const { imported } = await upsertFitbitMeasurements(
|
||||
"user-1",
|
||||
|
||||
@@ -44,9 +44,12 @@ vi.mock("@/lib/db", () => ({
|
||||
fitbitConnection: { findUnique, update },
|
||||
measurement: {
|
||||
findMany: vi.fn(async () => []),
|
||||
createMany: vi.fn(async (arg: { data: unknown[] }) => ({
|
||||
count: arg.data.length,
|
||||
})),
|
||||
createManyAndReturn: vi.fn(async (arg: { data: unknown[] }) =>
|
||||
arg.data.map((row, index) => ({
|
||||
...(row as Record<string, unknown>),
|
||||
id: `inserted-${index}`,
|
||||
})),
|
||||
),
|
||||
update: vi.fn(async () => ({})),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const {
|
||||
createManyAndReturn,
|
||||
update,
|
||||
emitInsertedWorkoutArrival,
|
||||
fetchActivityList,
|
||||
getValidToken,
|
||||
mapWorkout,
|
||||
readActivityList,
|
||||
} = vi.hoisted(() => ({
|
||||
createManyAndReturn: vi.fn(),
|
||||
update: vi.fn(),
|
||||
emitInsertedWorkoutArrival: vi.fn(async () => {}),
|
||||
fetchActivityList: vi.fn(),
|
||||
getValidToken: vi.fn(),
|
||||
mapWorkout: vi.fn(),
|
||||
readActivityList: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { workout: { createManyAndReturn, update } },
|
||||
}));
|
||||
vi.mock("@/lib/arrivals/workout-emit", () => ({
|
||||
emitInsertedWorkoutArrival,
|
||||
}));
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: () => ({ addWarning: vi.fn() }),
|
||||
}));
|
||||
vi.mock("@/lib/tz/resolver", () => ({
|
||||
resolveUserTimezone: vi.fn(async () => "UTC"),
|
||||
}));
|
||||
vi.mock("../client", () => ({
|
||||
fetchActivityList,
|
||||
mapWorkout,
|
||||
readActivityList,
|
||||
}));
|
||||
vi.mock("../sync", () => ({
|
||||
getValidToken,
|
||||
handleCollectionFetchError: vi.fn(),
|
||||
}));
|
||||
|
||||
import { syncUserWorkout } from "../sync-workout";
|
||||
|
||||
const startedAt = new Date("2026-07-19T08:00:00.000Z");
|
||||
const mapped = {
|
||||
externalId: "fitbit-1",
|
||||
sportType: "running",
|
||||
startedAt,
|
||||
endedAt: new Date("2026-07-19T09:00:00.000Z"),
|
||||
durationSec: 3600,
|
||||
totalEnergyKcal: 500,
|
||||
totalDistanceM: 10_000,
|
||||
avgHeartRate: 145,
|
||||
maxHeartRate: 170,
|
||||
minHeartRate: 90,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
getValidToken.mockResolvedValue({ accessToken: "token" });
|
||||
fetchActivityList.mockResolvedValue({});
|
||||
readActivityList.mockReturnValue([{}]);
|
||||
mapWorkout.mockReturnValue(mapped);
|
||||
update.mockResolvedValue({ id: "existing" });
|
||||
});
|
||||
|
||||
describe("syncUserWorkout — exact inserted identity", () => {
|
||||
it("emits the exact row returned by the insert statement", async () => {
|
||||
const inserted = { id: "new-workout", startedAt };
|
||||
createManyAndReturn.mockResolvedValue([inserted]);
|
||||
|
||||
await expect(syncUserWorkout("user-1")).resolves.toBe(1);
|
||||
|
||||
expect(emitInsertedWorkoutArrival).toHaveBeenCalledWith(
|
||||
"user-1",
|
||||
inserted,
|
||||
"fitbit",
|
||||
);
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates and counts an existing workout without emitting", async () => {
|
||||
createManyAndReturn.mockResolvedValue([]);
|
||||
|
||||
await expect(syncUserWorkout("user-1")).resolves.toBe(1);
|
||||
|
||||
expect(update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
userId_source_externalId: {
|
||||
userId: "user-1",
|
||||
source: "FITBIT",
|
||||
externalId: "fitbit-1",
|
||||
},
|
||||
},
|
||||
data: expect.objectContaining({
|
||||
sportType: "running",
|
||||
startedAt,
|
||||
totalDistanceM: 10_000,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(emitInsertedWorkoutArrival).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats a duplicate-race short return as an update, never an insert", async () => {
|
||||
createManyAndReturn.mockResolvedValue([]);
|
||||
update.mockResolvedValue({ id: "concurrent-winner" });
|
||||
|
||||
await expect(syncUserWorkout("user-1")).resolves.toBe(1);
|
||||
|
||||
expect(createManyAndReturn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ skipDuplicates: true }),
|
||||
);
|
||||
expect(update).toHaveBeenCalledTimes(1);
|
||||
expect(emitInsertedWorkoutArrival).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a successful insert when arrival dispatch fails", async () => {
|
||||
createManyAndReturn.mockResolvedValue([{ id: "new-workout", startedAt }]);
|
||||
emitInsertedWorkoutArrival.mockRejectedValueOnce(new Error("queue down"));
|
||||
|
||||
await expect(syncUserWorkout("user-1")).resolves.toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -20,11 +20,11 @@ const { prismaMock, refreshAccessTokenMock, recordSyncFailure } = vi.hoisted(
|
||||
findMany: vi.fn<(arg: Record<string, unknown>) => Promise<unknown[]>>(
|
||||
async () => [],
|
||||
),
|
||||
createMany: vi.fn<
|
||||
(arg: Record<string, unknown>) => Promise<{ count: number }>
|
||||
>(async (arg) => ({
|
||||
count: (arg.data as unknown[]).length,
|
||||
})),
|
||||
createManyAndReturn: vi.fn(async (arg: Record<string, unknown>) =>
|
||||
(arg.data as Array<{ type: string; measuredAt: Date }>).map(
|
||||
(row, index) => ({ ...row, id: `inserted-${index}` }),
|
||||
),
|
||||
),
|
||||
update: vi.fn<(arg: Record<string, unknown>) => Promise<unknown>>(
|
||||
async () => ({}),
|
||||
),
|
||||
@@ -267,7 +267,8 @@ describe("upsertFitbitMeasurements — batched write, tombstones resurrect", ()
|
||||
});
|
||||
expect(probeArg.where).not.toHaveProperty("deletedAt");
|
||||
|
||||
const createArg = prismaMock.measurement.createMany.mock.calls[0]![0] as {
|
||||
const createArg = prismaMock.measurement.createManyAndReturn.mock
|
||||
.calls[0]![0] as {
|
||||
data: Record<string, unknown>[];
|
||||
skipDuplicates: boolean;
|
||||
};
|
||||
@@ -301,7 +302,7 @@ describe("upsertFitbitMeasurements — batched write, tombstones resurrect", ()
|
||||
|
||||
expect(imported).toBe(1);
|
||||
// No fresh insert — the live row was overwritten in place.
|
||||
expect(prismaMock.measurement.createMany).not.toHaveBeenCalled();
|
||||
expect(prismaMock.measurement.createManyAndReturn).not.toHaveBeenCalled();
|
||||
const updateArg = prismaMock.measurement.update.mock.calls[0]![0] as {
|
||||
where: { id: string };
|
||||
data: { value: number; syncVersion: unknown };
|
||||
@@ -331,7 +332,7 @@ describe("upsertFitbitMeasurements — batched write, tombstones resurrect", ()
|
||||
]);
|
||||
|
||||
expect(imported).toBe(1);
|
||||
expect(prismaMock.measurement.createMany).not.toHaveBeenCalled();
|
||||
expect(prismaMock.measurement.createManyAndReturn).not.toHaveBeenCalled();
|
||||
const updateArg = prismaMock.measurement.update.mock.calls[0]![0] as {
|
||||
where: { id: string };
|
||||
data: Record<string, unknown>;
|
||||
@@ -368,7 +369,8 @@ describe("upsertFitbitMeasurements — batched write, tombstones resurrect", ()
|
||||
expect(prismaMock.measurement.update.mock.calls[0]![0]).toMatchObject({
|
||||
where: { id: "m-live" },
|
||||
});
|
||||
const createArg = prismaMock.measurement.createMany.mock.calls[0]![0] as {
|
||||
const createArg = prismaMock.measurement.createManyAndReturn.mock
|
||||
.calls[0]![0] as {
|
||||
data: Record<string, unknown>[];
|
||||
};
|
||||
expect(createArg.data).toHaveLength(1);
|
||||
@@ -384,7 +386,8 @@ describe("upsertFitbitMeasurements — batched write, tombstones resurrect", ()
|
||||
{ type: "WEIGHT", value: 9, unit: "kg", measuredAt, externalId: "dup" },
|
||||
]);
|
||||
|
||||
const createArg = prismaMock.measurement.createMany.mock.calls[0]![0] as {
|
||||
const createArg = prismaMock.measurement.createManyAndReturn.mock
|
||||
.calls[0]![0] as {
|
||||
data: Record<string, unknown>[];
|
||||
};
|
||||
expect(createArg.data).toHaveLength(1);
|
||||
@@ -422,7 +425,7 @@ describe("upsertFitbitMeasurements — batched write, tombstones resurrect", ()
|
||||
const { imported } = await upsertFitbitMeasurements("user1", []);
|
||||
expect(imported).toBe(0);
|
||||
expect(prismaMock.measurement.findMany).not.toHaveBeenCalled();
|
||||
expect(prismaMock.measurement.createMany).not.toHaveBeenCalled();
|
||||
expect(prismaMock.measurement.createManyAndReturn).not.toHaveBeenCalled();
|
||||
expect(prismaMock.measurement.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,18 +73,20 @@ export async function syncUserSleep(
|
||||
}
|
||||
}
|
||||
|
||||
const imported = (
|
||||
await upsertFitbitMeasurements(userId, readings, {
|
||||
const { imported, inserted } = await upsertFitbitMeasurements(
|
||||
userId,
|
||||
readings,
|
||||
{
|
||||
deferRollup: opts.deferRollup,
|
||||
})
|
||||
).imported;
|
||||
},
|
||||
);
|
||||
// `markSynced` is owned by the orchestrator (`syncUserFitbit`).
|
||||
|
||||
// S4 — trigger the debounced morning refresh on a last-night segment landing
|
||||
// (mirrors the Withings / WHOOP / Apple seams).
|
||||
void maybeEnqueueMorningRefresh(
|
||||
userId,
|
||||
readings
|
||||
inserted
|
||||
.filter((r) => r.type === "SLEEP_DURATION")
|
||||
.map((r) => r.measuredAt),
|
||||
).catch(() => {});
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
type FitbitResourceSyncOptions,
|
||||
} from "./sync";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { emitWorkoutArrivalIfCreated } from "@/lib/arrivals/workout-emit";
|
||||
import { emitInsertedWorkoutArrival } from "@/lib/arrivals/workout-emit";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { resolveUserTimezone } from "@/lib/tz/resolver";
|
||||
|
||||
@@ -76,50 +76,44 @@ export async function syncUserWorkout(
|
||||
const w: FitbitMappedWorkout | null = mapWorkout(entry, tz);
|
||||
if (!w) continue; // no usable time span — not a workout
|
||||
|
||||
const data = {
|
||||
sportType: w.sportType,
|
||||
startedAt: w.startedAt,
|
||||
endedAt: w.endedAt,
|
||||
durationSec: w.durationSec,
|
||||
totalEnergyKcal: w.totalEnergyKcal,
|
||||
totalDistanceM: w.totalDistanceM,
|
||||
avgHeartRate: w.avgHeartRate,
|
||||
maxHeartRate: w.maxHeartRate,
|
||||
minHeartRate: w.minHeartRate,
|
||||
};
|
||||
try {
|
||||
const saved = await prisma.workout.upsert({
|
||||
where: {
|
||||
userId_source_externalId: {
|
||||
userId,
|
||||
source: "FITBIT",
|
||||
externalId: w.externalId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
const [inserted] = await prisma.workout.createManyAndReturn({
|
||||
data: {
|
||||
userId,
|
||||
source: "FITBIT",
|
||||
externalId: w.externalId,
|
||||
sportType: w.sportType,
|
||||
startedAt: w.startedAt,
|
||||
endedAt: w.endedAt,
|
||||
durationSec: w.durationSec,
|
||||
totalEnergyKcal: w.totalEnergyKcal,
|
||||
totalDistanceM: w.totalDistanceM,
|
||||
avgHeartRate: w.avgHeartRate,
|
||||
maxHeartRate: w.maxHeartRate,
|
||||
minHeartRate: w.minHeartRate,
|
||||
},
|
||||
update: {
|
||||
sportType: w.sportType,
|
||||
startedAt: w.startedAt,
|
||||
endedAt: w.endedAt,
|
||||
durationSec: w.durationSec,
|
||||
totalEnergyKcal: w.totalEnergyKcal,
|
||||
totalDistanceM: w.totalDistanceM,
|
||||
avgHeartRate: w.avgHeartRate,
|
||||
maxHeartRate: w.maxHeartRate,
|
||||
minHeartRate: w.minHeartRate,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
startedAt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
...data,
|
||||
},
|
||||
skipDuplicates: true,
|
||||
select: { id: true, startedAt: true },
|
||||
});
|
||||
// v1.31.0 — data-arrival spine. Only a genuinely NEW workout reacts; a
|
||||
// re-sync of an already-stored session is not news.
|
||||
void emitWorkoutArrivalIfCreated(userId, saved, "fitbit").catch(() => {});
|
||||
if (inserted) {
|
||||
void emitInsertedWorkoutArrival(userId, inserted, "fitbit").catch(
|
||||
() => {},
|
||||
);
|
||||
} else {
|
||||
await prisma.workout.update({
|
||||
where: {
|
||||
userId_source_externalId: {
|
||||
userId,
|
||||
source: "FITBIT",
|
||||
externalId: w.externalId,
|
||||
},
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
imported++;
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning(`fitbit: failed to upsert workout: ${err}`);
|
||||
|
||||
+21
-5
@@ -23,6 +23,7 @@ import { prisma } from "@/lib/db";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { encrypt, decrypt } from "@/lib/crypto";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { emitInsertedMeasurementArrivals } from "@/lib/arrivals/measurement-emit";
|
||||
import {
|
||||
isReauthRequired,
|
||||
recordSyncFailure,
|
||||
@@ -415,8 +416,13 @@ export async function upsertFitbitMeasurements(
|
||||
): Promise<{
|
||||
imported: number;
|
||||
touched: Array<{ type: MeasurementType; measuredAt: Date }>;
|
||||
inserted: Array<{
|
||||
id: string;
|
||||
type: MeasurementType;
|
||||
measuredAt: Date;
|
||||
}>;
|
||||
}> {
|
||||
if (readings.length === 0) return { imported: 0, touched: [] };
|
||||
if (readings.length === 0) return { imported: 0, touched: [], inserted: [] };
|
||||
|
||||
// Probe EVERY existing row (live AND tombstoned) for the batch's externalIds
|
||||
// in a single query. The full unique index guarantees at most one row per
|
||||
@@ -591,6 +597,11 @@ export async function upsertFitbitMeasurements(
|
||||
}
|
||||
|
||||
let imported = 0;
|
||||
const insertedRows: Array<{
|
||||
id: string;
|
||||
type: MeasurementType;
|
||||
measuredAt: Date;
|
||||
}> = [];
|
||||
|
||||
// Fresh inserts: chunked `createMany` (server-owned rows, field-by-field).
|
||||
// `skipDuplicates` guards the partial-unique index in the rare race where a
|
||||
@@ -598,7 +609,7 @@ export async function upsertFitbitMeasurements(
|
||||
for (let i = 0; i < toCreate.length; i += FITBIT_CREATE_CHUNK) {
|
||||
const chunk = toCreate.slice(i, i + FITBIT_CREATE_CHUNK);
|
||||
try {
|
||||
const res = await prisma.measurement.createMany({
|
||||
const inserted = await prisma.measurement.createManyAndReturn({
|
||||
data: chunk.map((c) => ({
|
||||
userId,
|
||||
type: c.type,
|
||||
@@ -610,8 +621,13 @@ export async function upsertFitbitMeasurements(
|
||||
sleepStage: c.sleepStage,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
select: { id: true, type: true, measuredAt: true },
|
||||
});
|
||||
imported += res.count;
|
||||
imported += inserted.length;
|
||||
insertedRows.push(...inserted);
|
||||
void emitInsertedMeasurementArrivals(userId, inserted, "fitbit").catch(
|
||||
() => {},
|
||||
);
|
||||
for (const c of chunk) {
|
||||
touched.push({ type: c.type, measuredAt: c.measuredAt });
|
||||
}
|
||||
@@ -666,7 +682,7 @@ export async function upsertFitbitMeasurements(
|
||||
if (tracker) {
|
||||
for (const t of touched) tracker.keys.push(t);
|
||||
}
|
||||
return { imported, touched };
|
||||
return { imported, touched, inserted: insertedRows };
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -688,7 +704,7 @@ export async function upsertFitbitMeasurements(
|
||||
);
|
||||
}
|
||||
|
||||
return { imported, touched };
|
||||
return { imported, touched, inserted: insertedRows };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user