chore(release): v1.30.14 — server-prefetch the workouts list; correct the aggregated heart-rate bucket docs

Move the workouts list read into a shared cached module so the RSC
wrapper and GET /api/workouts share one deduplicated projection pass,
and dehydrate it under the client cell's exact query key so the page
paints its rows instead of a loading skeleton.

Correct the aggregated heart-rate externalId documentation: the example
and the min/max field notes still described the original hourly bucket,
while the accepted contract has been 10-minute buckets since v1.30.7.
This commit is contained in:
Marc-André Bombeck committed 2026-07-18 22:42:23 +02:00
1 parent 521f5d354c
commit 5b464b26de
10 files changed
+586 -267

No files matched your search

+8 -185
View File
@@ -57,187 +57,15 @@
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { apiSuccess } from "@/lib/api-response";
import { pickCanonicalWorkoutRows } from "@/lib/measurements/pick-canonical-workout-rows";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { readWorkoutsListCached } from "@/lib/workouts/list-read";
import { requireModuleEnabled } from "@/lib/modules/gate";
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 200;
interface WorkoutsParams {
readonly limit: number;
readonly offset: number;
readonly since: string | null;
readonly until: string | null;
readonly sportType: string | null;
}
type WorkoutFilterParams = Pick<
WorkoutsParams,
"since" | "until" | "sportType"
>;
interface CanonicalWorkoutRow {
id: string;
source: string;
externalId: string | null;
sportType: string | null;
startedAt: Date | null;
endedAt: Date | null;
durationSec: number | null;
totalDistanceM: number | null;
totalEnergyKcal: number | null;
avgHeartRate: number | null;
maxHeartRate: number | null;
createdAt: Date;
// #67 list glyphs — cheap relation-id selects so the list can flag
// which sessions open into a rich detail (map / HR curve).
route: { id: string } | null;
samples: { sampleCount: number } | null;
}
/** The cached, deduped, most-recent-first row set for one filter combination. */
interface WorkoutsProjection {
canonical: CanonicalWorkoutRow[];
rawCount: number;
}
interface WorkoutsResult {
workouts: Array<{
id: string;
sportType: string | null;
startedAt: Date | null;
endedAt: Date | null;
durationSec: number | null;
distanceM: number | null;
activeEnergyKcal: number | null;
avgHr: number | null;
maxHr: number | null;
source: string;
externalId: string | null;
hasRoute: boolean;
hasHrSeries: boolean;
}>;
meta: {
total: number;
limit: number;
offset: number;
droppedDuplicates: number;
};
}
async function buildWorkoutsProjection(
userId: string,
params: WorkoutFilterParams,
): Promise<WorkoutsProjection> {
const { since, until, sportType } = params;
const where: Record<string, unknown> = { userId };
if (since || until) {
const range: Record<string, Date> = {};
if (since) {
const d = new Date(since);
if (!Number.isNaN(d.getTime())) range.gte = d;
}
if (until) {
const d = new Date(until);
if (!Number.isNaN(d.getTime())) range.lte = d;
}
if (Object.keys(range).length > 0) {
where.startedAt = range;
}
}
if (sportType) {
where.sportType = sportType;
}
// Independent reads — the sourcePriorityJson lookup doesn't depend on the
// row read, so run them concurrently rather than paying two sequential
// round trips.
const [rows, userRow] = await Promise.all([
prisma.workout.findMany({
where,
orderBy: [{ startedAt: "desc" }, { id: "asc" }],
select: {
id: true,
source: true,
externalId: true,
sportType: true,
startedAt: true,
endedAt: true,
durationSec: true,
totalDistanceM: true,
totalEnergyKcal: true,
avgHeartRate: true,
maxHeartRate: true,
createdAt: true,
route: { select: { id: true } },
samples: { select: { sampleCount: true } },
},
}),
prisma.user.findUnique({
where: { id: userId },
select: { sourcePriorityJson: true },
}),
]);
const canonical = pickCanonicalWorkoutRows(
rows,
userRow?.sourcePriorityJson ?? null,
);
// `pickCanonicalWorkoutRows` re-sorts its output to `startedAt ASC` (its
// documented contract for the rollup callers). This surface is a
// most-recent-first list, so the DB `orderBy startedAt desc` must be
// re-established AFTER the pick — otherwise `offset`/`limit` slice the
// OLDEST page and a user with a long history never sees recent workouts.
canonical.sort((a, b) => {
const delta = (b.startedAt?.getTime() ?? 0) - (a.startedAt?.getTime() ?? 0);
if (delta !== 0) return delta;
return a.id.localeCompare(b.id);
});
return { canonical, rawCount: rows.length };
}
function sliceWorkoutsProjection(
projection: WorkoutsProjection,
limit: number,
offset: number,
): WorkoutsResult {
const page = projection.canonical
.slice(offset, offset + limit)
.map((row) => ({
id: row.id,
sportType: row.sportType,
startedAt: row.startedAt,
endedAt: row.endedAt,
durationSec: row.durationSec,
distanceM: row.totalDistanceM,
activeEnergyKcal: row.totalEnergyKcal,
avgHr: row.avgHeartRate,
maxHr: row.maxHeartRate,
source: row.source,
externalId: row.externalId,
hasRoute: row.route != null,
hasHrSeries: row.samples != null && row.samples.sampleCount > 0,
}));
return {
workouts: page,
meta: {
total: projection.canonical.length,
limit,
offset,
droppedDuplicates: projection.rawCount - projection.canonical.length,
},
};
}
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "workouts.list" } });
@@ -266,18 +94,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
const until = searchParams.get("until");
const sportType = searchParams.get("sportType");
// Deliberately excludes `limit`/`offset` — every page of one filter
// combination shares this cached projection (see the docblock above).
const projectionKey = `${user.id}|${since ?? ""}|${until ?? ""}|${sportType ?? ""}`;
const projection = await cached(
caches.workouts as ServerCache<WorkoutsProjection>,
projectionKey,
() => buildWorkoutsProjection(user.id, { since, until, sportType }),
annotate,
);
const result = sliceWorkoutsProjection(projection, limit, offset);
const result = await readWorkoutsListCached(user.id, {
limit,
offset,
since,
until,
sportType,
});
return apiSuccess(result);
});