feat(workouts): accept an optional HR series on the batch contract

Extend POST /api/workouts/batch with an optional per-workout `samples`
array — a route-independent heart-rate series so indoor workouts still
yield a strain-relevant signal. Each entry is `{ t, hr?, speedMs?,
power?, cadence? }`; the array is capped at 30 000 points
(MAX_WORKOUT_HR_SAMPLES), covering a long endurance session sampled at
1 Hz while bounding the largest new workout-side write stream the same
way the 20 000-point route cap bounds the geometry.

Persistence rides the existing route-attachment path: the freshly
written workout id is resolved once (by composite key, or the manual
tuple), then both the route geometry and the HR series attach by FK
with skipDuplicates so a re-submitted batch stays idempotent. A workout
may carry both a GPS route and a canonical HR series, or just one.

GET /api/workouts/{id} returns the series alongside the route. OpenAPI
regenerated.

`samples` keeps first-write-wins/overwrite parity with the workout row
it hangs off: the 1:1 FK plus skipDuplicates means a re-ingest of an
existing workout never duplicates or mutates its series.
This commit is contained in:
Marc-André Bombeck committed 2026-06-02 22:02:46 +02:00
1 parent d247f6966a
commit 30be0c4e0d
8 files changed
+463 -13

No files matched your search

@@ -4,7 +4,9 @@ import {
createWorkoutSchema,
geoJsonLineStringSchema,
MAX_ROUTE_POINTS,
MAX_WORKOUT_HR_SAMPLES,
MAX_WORKOUTS_PER_BATCH,
workoutHrSamplesSchema,
workoutRouteSamplesSchema,
workoutSportTypeEnum,
type CreateWorkoutInput,
@@ -111,6 +113,61 @@ describe("workoutRouteSamplesSchema", () => {
});
});
describe("workoutHrSamplesSchema", () => {
it("accepts a route-independent HR series with optional channels", () => {
const parsed = workoutHrSamplesSchema.parse([
{ t: "2026-05-14T07:00:00.000Z", hr: 142 },
{ t: "2026-05-14T07:00:05.000Z", hr: 145, speedMs: 3.1 },
{ t: "2026-05-14T07:00:10.000Z", hr: 150, power: 220, cadence: 88 },
]);
expect(parsed).toHaveLength(3);
});
it("accepts a bare-timestamp entry (sparse series)", () => {
expect(
workoutHrSamplesSchema.parse([{ t: "2026-05-14T07:00:00.000Z" }]),
).toHaveLength(1);
});
it("rejects an empty series", () => {
expect(() => workoutHrSamplesSchema.parse([])).toThrow();
});
it("rejects an out-of-range heart rate", () => {
expect(() =>
workoutHrSamplesSchema.parse([
{ t: "2026-05-14T07:00:00.000Z", hr: 5 },
]),
).toThrow();
});
it("rejects a series above the per-workout sample cap", () => {
const oversized = Array.from(
{ length: MAX_WORKOUT_HR_SAMPLES + 1 },
(_v, i) => ({
t: new Date(Date.UTC(2026, 4, 14, 7, 0, 0) + i * 1000).toISOString(),
hr: 140,
}),
);
expect(() => workoutHrSamplesSchema.parse(oversized)).toThrow(
/sample.*cap/i,
);
});
it("accepts a series exactly at the cap", () => {
const atCap = Array.from(
{ length: MAX_WORKOUT_HR_SAMPLES },
(_v, i) => ({
t: new Date(Date.UTC(2026, 4, 14, 7, 0, 0) + i * 1000).toISOString(),
hr: 140,
}),
);
expect(workoutHrSamplesSchema.parse(atCap)).toHaveLength(
MAX_WORKOUT_HR_SAMPLES,
);
});
});
describe("createWorkoutSchema", () => {
const minimalRun: Record<string, unknown> = {
sportType: "running",
@@ -261,6 +318,40 @@ describe("createWorkoutSchema", () => {
});
expect(parsed.route?.sampleTimestamps).toHaveLength(2);
});
it("accepts a route-independent HR series on an indoor workout (no route)", () => {
const parsed = createWorkoutSchema.parse({
sportType: "strength",
startedAt: "2026-05-14T06:30:00.000Z",
endedAt: "2026-05-14T07:15:00.000Z",
source: "APPLE_HEALTH",
externalId: "indoor-1",
samples: [
{ t: "2026-05-14T06:30:00.000Z", hr: 110 },
{ t: "2026-05-14T06:30:05.000Z", hr: 118 },
],
});
expect(parsed.route).toBeUndefined();
expect(parsed.samples).toHaveLength(2);
});
it("accepts both a GPS route and a canonical HR series on one workout", () => {
const parsed = createWorkoutSchema.parse({
...minimalRun,
route: {
geometry: {
type: "LineString",
coordinates: [
[11.077, 49.452],
[11.078, 49.453],
],
},
},
samples: [{ t: "2026-05-14T06:30:00.000Z", hr: 142 }],
});
expect(parsed.route?.geometry.coordinates).toHaveLength(2);
expect(parsed.samples).toHaveLength(1);
});
});
describe("createBatchWorkoutSchema", () => {
+54
View File
@@ -91,6 +91,51 @@ export const workoutRouteSamplesSchema = z.array(
export type WorkoutRouteSamples = z.infer<typeof workoutRouteSamplesSchema>;
/**
* Upper bound on per-workout heart-rate samples. HealthKit emits a HR
* sample roughly every 5 s during a workout — a 6-hour ultra at that
* cadence lands at ~4 320 points, and even a 1 Hz reconstruction of
* that session is ~21 600. 30 000 covers any realistic single session
* (including long endurance events sampled at 1 Hz) while still
* rejecting pathological payloads. The series is the largest new
* workout-side write stream, so the cap keeps each workout's payload —
* and the total request body — bounded the same way `MAX_ROUTE_POINTS`
* bounds the route geometry. iOS should downsample to ≤ this many
* points (e.g. 1-min buckets for very long sessions) before posting.
*/
export const MAX_WORKOUT_HR_SAMPLES = 30_000;
/**
* Route-INDEPENDENT per-workout heart-rate series — the
* `WorkoutSamples.samples` shape. Mirrors `workoutRouteSamplesSchema`
* but carries no geometry coupling, so an indoor workout (no GPS) can
* still ship its HR signal for the training-strain engine.
*
* `t` is the per-sample ISO timestamp; `hr` beats/min. `speedMs` /
* `power` / `cadence` are optional companion channels HealthKit may
* report (cycling power meters, running cadence). Every channel is
* optional EXCEPT `t` so a sparse series (HR only) is valid; an entry
* with no signal channel at all is still permitted (a bare timestamp)
* but carries no analytical value.
*/
export const workoutHrSamplesSchema = z
.array(
z.object({
t: z.iso.datetime({ offset: true }),
hr: z.number().int().min(20).max(300).optional(),
speedMs: z.number().min(0).max(50).optional(),
power: z.number().min(0).max(3000).optional(),
cadence: z.number().min(0).max(400).optional(),
}),
)
.min(1, "samples requires at least 1 point")
.max(
MAX_WORKOUT_HR_SAMPLES,
`samples exceeds the ${MAX_WORKOUT_HR_SAMPLES}-point cap`,
);
export type WorkoutHrSamples = z.infer<typeof workoutHrSamplesSchema>;
/**
* Workout insert payload — the shape `POST /api/workouts/batch` accepts.
* Defined here so the iOS Swift session can generate its DTO against the
@@ -131,6 +176,15 @@ export const createWorkoutSchema = z
sampleTimestamps: workoutRouteSamplesSchema.optional(),
})
.optional(),
/**
* Route-independent per-workout heart-rate series. Persisted to the
* `WorkoutSamples` child so an indoor workout (no GPS route) still
* yields a strain-relevant HR signal. Independent of `route` — a
* GPS workout MAY carry both (`route.sampleTimestamps` for the
* geometry-aligned series, `samples` for the canonical HR series);
* an indoor workout carries only `samples`.
*/
samples: workoutHrSamplesSchema.optional(),
})
.superRefine((value, ctx) => {
if (value.endedAt.getTime() <= value.startedAt.getTime()) {