diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index a1bda5378..5b543d350 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -17416,6 +17416,51 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "429": *a12 + /api/labs/fhir-batch: + post: + tags: + - Labs + summary: Ingest lab results from Apple Health's Health Records + description: "Maps each FHIR lab result (DSTU2 or R4 Observation) to a lab reading and writes it: final results only + (`final`, `amended`, `corrected`), the laboratory category, numeric values in their unit (UCUM codes are read), + a value with a comparator (`<0.5 mg/L`) kept as text as printed, string and coded values as text, the report's + own reference range, and the panel's name for its members. The name resolves to the caller's marker by its own + name, an alias, or the catalog analyte its LOINC code names; a new analyte gets a new marker; a reading in + another unit is converted when the conversion is known and refused otherwise. The identity is a digest of + `sourceURL` and `identifier`, the same one an Apple Health export import builds, so a result already imported + from an export is a `duplicate` here, and sending a batch again is safe. First write wins: an amended result + under a held identity is a duplicate. Owner-only: a cookie session or a full-scope login token. The body is + capped at 1 MiB (413 past it): a client splits a large sync by size as well as by count. Rate limit 60 batches a + minute; Idempotency-Key supported. A response carrying `write_failed` is `Cache-Control: no-store` and is not + replayed for its key. Audits as `labs.fhir.batch` with counts only." + parameters: + - *a6 + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/FhirLabBatchRequest" + responses: + "200": + description: Batch processed; one result per record. `outcome` reads `inserted` against `failed` (skips and duplicates + are information, not failure). + content: + application/json: + schema: + $ref: "#/components/schemas/FhirLabBatchEnvelope" + "401": *a1 + "403": *a9 + "409": *a7 + "422": + description: "Nothing was written. `meta.errorCode` = `labs.fhir_batch.invalid`: no records, more than 200, a record + without a `resource` object, an over-long HealthKit field, or a field the request does not define (every + issue under `details.issues`)." + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "429": *a5 /api/labs/overview: get: tags: @@ -35147,6 +35192,47 @@ components: optional `source` records provenance: `"OCR"` for an on-device-OCR capture (the raw image never reaches the server on this path), defaulting to `"MANUAL"` when omitted. The optional `encounterId` files the reading against a visit the caller owns — always optional, and a link that could not be made never fails the reading.' + FhirLabBatchRequest: + type: object + properties: + records: + minItems: 1 + maxItems: 200 + type: array + items: + type: object + properties: + resource: + type: object + propertyNames: + type: string + additionalProperties: {} + description: The FHIR resource as JSON (`HKFHIRResource.data`), DSTU2 or R4. Only Observations of the laboratory + category are kept. + fhirVersion: + description: "`HKFHIRResource.fhirVersion` (e.g. `4.0.1`)." + type: string + maxLength: 16 + identifier: + description: "`HKFHIRResource.identifier`, the resource's id at its source." + type: string + maxLength: 256 + sourceURL: + description: "`HKFHIRResource.sourceURL`, the issuing institution's FHIR base." + type: string + maxLength: 2048 + sourceName: + description: The institution as the Health app names it (`sourceRevision.source.name`). + type: string + maxLength: 200 + required: + - resource + required: + - records + additionalProperties: false + description: "1 to 200 Health Records lab results (`HKClinicalTypeIdentifierLabResultRecord`), each the FHIR resource as + JSON plus the HealthKit fields its identity is built from. Send a panel and its members in the same batch so the + members carry the panel's name. No `userId`: the owner is the caller." UpdateLabResultRequest: type: object properties: @@ -39820,12 +39906,12 @@ components: insights.generate.scopeChanged; labs — labs.biomarker.alias.taken, labs.biomarker.create.invalid, labs.biomarker.duplicate, labs.biomarker.merge.invalid, labs.biomarker.merge.unitMismatch, labs.biomarker.notFound, labs.biomarker.update.invalid, labs.biomarker.update.referenceRangeInvalid, - labs.create.invalid, labs.series.invalid, labs.link.invalid, labs.ocr.budgetExceeded, - labs.ocr.extractFailed, labs.ocr.fileTooLarge, labs.ocr.fileType, labs.ocr.localOcrDisabled, - labs.ocr.outputLimit, labs.ocr.pdfRendererUnavailable, labs.ocr.providerUnsupported, - labs.ocr.rateLimited, labs.ocr.tooLarge, labs.restore.invalid, labs.result.notFound, labs.unit.mismatch, - labs.update.invalid, labs.update.linkedFieldsImmutable, labs.update.numericExpected, - labs.update.qualitativeExpected, labs.update.referenceRangeInvalid, + labs.create.invalid, labs.fhir_batch.invalid, labs.series.invalid, labs.link.invalid, + labs.ocr.budgetExceeded, labs.ocr.extractFailed, labs.ocr.fileTooLarge, labs.ocr.fileType, + labs.ocr.localOcrDisabled, labs.ocr.outputLimit, labs.ocr.pdfRendererUnavailable, + labs.ocr.providerUnsupported, labs.ocr.rateLimited, labs.ocr.tooLarge, labs.restore.invalid, + labs.result.notFound, labs.unit.mismatch, labs.update.invalid, labs.update.linkedFieldsImmutable, + labs.update.numericExpected, labs.update.qualitativeExpected, labs.update.referenceRangeInvalid, labs.update.sourceReferenceRangeInvalid; life_event — life_event.invalid, life_event.not_found; managed_profile — managed_profile.guardian.duplicate, managed_profile.guardian.managed_invitee, managed_profile.guardian.required, managed_profile.handover.no_pending, @@ -44664,6 +44750,12 @@ components: source: type: string minLength: 1 + externalId: + anyOf: + - type: string + minLength: 1 + maxLength: 128 + - type: "null" biomarkerName: type: - string @@ -76677,9 +76769,10 @@ components: type: string additionalProperties: {} - type: "null" - description: The worker's outcome summary, null until it finishes. Free-form except for `ecg`, whose five counters - (`discovered` / `imported` / `updated` / `skipped` / `failed`) are normalised to bounded non-negative - integers before serving. + description: "The worker's outcome summary, null until it finishes. Free-form except for `ecg` and `labs`, whose five + counters each (`ecg`: `discovered` / `imported` / `updated` / `skipped` / `failed`; `labs`, the lab + results from Health Records: `discovered` / `imported` / `duplicate` / `skipped` / `failed`) are + normalised to bounded non-negative integers before serving." failureReason: description: Free text on `failed`; null otherwise. type: @@ -77225,6 +77318,9 @@ components: type: string source: type: string + description: "Where the reading came from: `MANUAL` (typed), `OCR` (a scanned report), `DOCUMENT` (a document import), + `IMPORT` (a lab CSV) or `APPLE_HEALTH` (Apple Health's Health Records, from an export or `POST + /api/labs/fhir-batch`). Open-ended: render an unknown value as-is." hasNote: type: boolean rangeStatus: @@ -77319,6 +77415,105 @@ components: - data - error additionalProperties: false + FhirLabBatchEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/FhirLabBatchResponse" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + FhirLabBatchResponse: + type: object + properties: + results: + type: array + items: + $ref: "#/components/schemas/FhirLabRecordResult" + inserted: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + duplicate: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + skipped: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + failed: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + outcome: + type: string + enum: + - empty + - failed + - partial + - success + required: + - results + - inserted + - duplicate + - skipped + - failed + - outcome + additionalProperties: false + FhirLabRecordResult: + type: object + properties: + index: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + status: + type: string + enum: + - inserted + - duplicate + - skipped + - failed + reason: + type: string + enum: + - not_observation + - not_lab + - not_final + - withdrawn + - panel_header + - no_value + - unsupported_value + - no_date + - future_date + - invalid_date + - too_large + - missing_unit + - unit_mismatch + - text_too_long + - write_failed + required: + - index + - status + additionalProperties: false + description: "One record's outcome, by its position in the request. `inserted`: written. `duplicate`: the record already + holds it, under the same identity (deleted readings included, so a deleted result stays deleted) or as the same + reading on the same day from another source. `skipped`: not a reading HealthLog keeps, with `reason` + `not_observation` | `not_lab` | `not_final` (preliminary; it is taken once final) | `withdrawn` | `panel_header` + | `no_value` | `unsupported_value` | `no_date` | `future_date` | `invalid_date` | `too_large` (a resource over + 256 KiB). `failed`: a reading that could not be stored, with `reason` `missing_unit` | `unit_mismatch` (the + account's marker is in a unit this one does not convert into) | `text_too_long` | `write_failed` (transient: + send it again)." LabOverviewEnvelope: type: object properties: @@ -77555,6 +77750,9 @@ components: type: string source: type: string + description: "Where the reading came from: `MANUAL` (typed), `OCR` (a scanned report), `DOCUMENT` (a document import), + `IMPORT` (a lab CSV) or `APPLE_HEALTH` (Apple Health's Health Records, from an export or `POST + /api/labs/fhir-batch`). Open-ended: render an unknown value as-is." rangeStatus: $ref: "#/components/schemas/LabReferenceRangeStatus" createdAt: diff --git a/src/__tests__/write-rate-limit-guard.test.ts b/src/__tests__/write-rate-limit-guard.test.ts index ca11ecad3..01d670d82 100644 --- a/src/__tests__/write-rate-limit-guard.test.ts +++ b/src/__tests__/write-rate-limit-guard.test.ts @@ -82,6 +82,8 @@ const OWN_BUCKET: Record = { "The cycle HealthKit sweep sends 500-day slices in sequence; the route's own bulk bucket meters it.", "app/api/nutrients/batch/route.ts": "The nutrient sync sends 500-row batches in sequence; the route's own batch bucket meters it.", + "app/api/labs/fhir-batch/route.ts": + "The Health Records lab sync sends 200-record batches in sequence on a first sync; the route's own 60-a-minute batch bucket meters it.", "app/api/insights/chat/route.ts": "A Coach turn is metered by the Coach's own buckets: 20 turns a minute (`coach-chat`) and one turn slot at a time.", "app/api/insights/chat/fenced/route.ts": diff --git a/src/app/api/labs/fhir-batch/route.ts b/src/app/api/labs/fhir-batch/route.ts new file mode 100644 index 000000000..07da889e6 --- /dev/null +++ b/src/app/api/labs/fhir-batch/route.ts @@ -0,0 +1,183 @@ +/** + * `POST /api/labs/fhir-batch` — lab results from Apple Health's Health + * Records, sent by the iOS app (#1400). + * + * Each record is one FHIR resource as HealthKit hands it over. The batch is + * mapped with the same mapper the export import uses + * (`src/lib/labs/fhir-import/map-observation.ts`), panel members are given + * their panel's name within the batch, and the readings are written with the + * shared writer, so a result reads the same whichever way it came in and a + * result that already arrived through an export is a duplicate here. + * + * Sending a batch again is safe: a result already held under its identity is + * `duplicate`, a result the person deleted stays deleted, and an amended + * result arriving under the same identity is a duplicate (first write wins). + * + * Owner-only: a cookie session or a full-scope login token; a narrow token is + * refused by `requireAuth()`'s default arm. No module gate: labs is a data + * layer (see `src/app/api/labs/route.ts`). Metered by its own bulk bucket. + * Only counts and closed reasons reach the response, the audit row and the + * wide event; nothing from a resource does. + */ +import { NextRequest } from "next/server"; + +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { apiError, apiSuccess, getClientIp } from "@/lib/api-response"; +import { parseJsonBody } from "@/lib/api/body"; +import { auditLog } from "@/lib/auth/audit"; +import { withIdempotency } from "@/lib/idempotency"; +import { afterLabReadingsWritten } from "@/lib/labs/fhir-import/after-write"; +import { + assignPanels, + mapFhirLabRecord, + type FhirLabMapping, +} from "@/lib/labs/fhir-import/map-observation"; +import type { + FhirLabFailureReason, + FhirLabSkipReason, + MappedFhirLab, +} from "@/lib/labs/fhir-import/types"; +import { writeFhirLabReadings } from "@/lib/labs/fhir-import/write"; +import { annotate } from "@/lib/logging/context"; +import { classifyWrittenOutcome } from "@/lib/outcome/written-outcome"; +import { checkRateLimit } from "@/lib/rate-limit"; +import { resolveUserTimezone } from "@/lib/tz/resolver"; +import { + fhirLabBatchSchema, + MAX_FHIR_LAB_RESOURCE_BYTES, +} from "@/lib/validations/labs-fhir"; + +const BATCH_RATE_LIMIT_MAX = 60; +const BATCH_RATE_LIMIT_WINDOW_MS = 60 * 1000; +/** The proxy's body ceiling: the route stays inside the proxy matcher. */ +const MAX_BODY_BYTES = 1024 * 1024; + +type RecordResult = + | { index: number; status: "inserted" | "duplicate" } + | { index: number; status: "skipped"; reason: FhirLabSkipReason } + | { index: number; status: "failed"; reason: FhirLabFailureReason }; + +export const POST = apiHandler(withIdempotency<[NextRequest]>(postBatch)); + +async function postBatch(request: NextRequest): Promise { + const { user } = await requireAuth(undefined, { writeBucket: "own" }); + annotate({ action: { name: "labs.fhir_batch.ingest" } }); + + const rl = await checkRateLimit( + `labs:fhir-batch:${user.id}`, + BATCH_RATE_LIMIT_MAX, + BATCH_RATE_LIMIT_WINDOW_MS, + ); + if (!rl.allowed) { + return apiError("Too many batch submissions, try again later", 429); + } + + const parsed = await parseJsonBody(request, fhirLabBatchSchema, { + maxBytes: MAX_BODY_BYTES, + action: "labs.fhir_batch.validation-failed", + countIssues: true, + errorCode: "labs.fhir_batch.invalid", + }); + if (!parsed.ok) return parsed.error; + const { records } = parsed.data; + + // 1. Map every record; nothing is written yet. + const results: RecordResult[] = new Array(records.length); + const mapped: Array<{ index: number; mapping: FhirLabMapping }> = []; + const now = new Date(); + for (let index = 0; index < records.length; index += 1) { + const record = records[index]; + if ( + Buffer.byteLength(JSON.stringify(record.resource)) > + MAX_FHIR_LAB_RESOURCE_BYTES + ) { + results[index] = { index, status: "skipped", reason: "too_large" }; + continue; + } + const mapping = mapFhirLabRecord( + { + resource: record.resource, + fhirVersion: record.fhirVersion, + identifier: record.identifier, + sourceURL: record.sourceURL, + sourceName: record.sourceName, + }, + now, + ); + mapped.push({ index, mapping }); + if (mapping.kind === "skip") { + results[index] = { index, status: "skipped", reason: mapping.reason }; + } else if (mapping.kind === "fail") { + results[index] = { index, status: "failed", reason: mapping.reason }; + } + } + + // 2. A panel and its members arrive in one batch. + assignPanels(mapped.map((m) => m.mapping)); + const readings: MappedFhirLab[] = []; + const readingIndex: number[] = []; + for (const { index, mapping } of mapped) { + if (mapping.kind !== "reading") continue; + readings.push(mapping.reading); + readingIndex.push(index); + } + + // 3. Write. + const tz = await resolveUserTimezone(user.id); + const written = await writeFhirLabReadings({ + userId: user.id, + tz, + readings, + }); + written.statuses.forEach((status, i) => { + const index = readingIndex[i]; + results[index] = + status.status === "failed" + ? { index, status: "failed", reason: status.reason } + : { index, status: status.status }; + }); + afterLabReadingsWritten({ + userId: user.id, + inserted: written.inserted, + newestTakenAt: written.newestTakenAt, + source: "fhir_batch", + }); + + const counts = { inserted: 0, duplicate: 0, skipped: 0, failed: 0 }; + let writeFailed = false; + for (const result of results) { + counts[result.status] += 1; + if (result.status === "failed" && result.reason === "write_failed") { + writeFailed = true; + } + } + + await auditLog("labs.fhir.batch", { + userId: user.id, + ipAddress: getClientIp(request), + details: { records: records.length, ...counts }, + }); + annotate({ + meta: { + records: records.length, + inserted: counts.inserted, + duplicate: counts.duplicate, + skipped: counts.skipped, + failed: counts.failed, + }, + }); + + const response = apiSuccess({ + results, + ...counts, + outcome: classifyWrittenOutcome({ + written: counts.inserted, + skipped: counts.failed, + }), + }); + // `write_failed` is transient: nothing was stored for those records and the + // client sends them again. `no-store` keeps the idempotency layer from + // replaying this answer to the retry. + if (writeFailed) response.headers.set("Cache-Control", "private, no-store"); + return response; +} diff --git a/src/lib/apple-health/clinical-record-ref.ts b/src/lib/apple-health/clinical-record-ref.ts index f8326d7c5..9ce2bb4dc 100644 --- a/src/lib/apple-health/clinical-record-ref.ts +++ b/src/lib/apple-health/clinical-record-ref.ts @@ -33,7 +33,7 @@ const CAPS = { fhirVersion: 16, } as const; -function capped(raw: string | undefined, max: number): string | null { +function withinCap(raw: string | undefined, max: number): string | null { if (raw === undefined) return null; const trimmed = raw.trim(); if (trimmed === "" || trimmed.length > max) return null; @@ -51,11 +51,11 @@ export function routeClinicalRecord( ): boolean { if (!onLab || attrs.type !== HK_LAB_RESULT_RECORD) return false; onLab({ - path: capped(attrs.resourceFilePath, CAPS.path), - identifier: capped(attrs.identifier, CAPS.identifier), - sourceURL: capped(attrs.sourceURL, CAPS.sourceURL), - sourceName: capped(attrs.sourceName, CAPS.sourceName), - fhirVersion: capped(attrs.fhirVersion, CAPS.fhirVersion), + path: withinCap(attrs.resourceFilePath, CAPS.path), + identifier: withinCap(attrs.identifier, CAPS.identifier), + sourceURL: withinCap(attrs.sourceURL, CAPS.sourceURL), + sourceName: withinCap(attrs.sourceName, CAPS.sourceName), + fhirVersion: withinCap(attrs.fhirVersion, CAPS.fhirVersion), }); return true; } diff --git a/src/lib/openapi/error-codes.ts b/src/lib/openapi/error-codes.ts index 411c355a1..b87bc59bc 100644 --- a/src/lib/openapi/error-codes.ts +++ b/src/lib/openapi/error-codes.ts @@ -289,6 +289,7 @@ export const ERROR_CODE_CATALOGUE: Readonly> = "labs.biomarker.update.invalid", "labs.biomarker.update.referenceRangeInvalid", "labs.create.invalid", + "labs.fhir_batch.invalid", "labs.series.invalid", "labs.link.invalid", "labs.ocr.budgetExceeded", diff --git a/src/lib/openapi/routes/import.ts b/src/lib/openapi/routes/import.ts index 053cb10a8..78bd8ed9e 100644 --- a/src/lib/openapi/routes/import.ts +++ b/src/lib/openapi/routes/import.ts @@ -748,7 +748,7 @@ export const importPaths: NonNullable = { .record(z.string(), z.unknown()) .nullable() .describe( - "The worker's outcome summary, null until it finishes. Free-form except for `ecg`, whose five counters (`discovered` / `imported` / `updated` / `skipped` / `failed`) are normalised to bounded non-negative integers before serving.", + "The worker's outcome summary, null until it finishes. Free-form except for `ecg` and `labs`, whose five counters each (`ecg`: `discovered` / `imported` / `updated` / `skipped` / `failed`; `labs`, the lab results from Health Records: `discovered` / `imported` / `duplicate` / `skipped` / `failed`) are normalised to bounded non-negative integers before serving.", ), failureReason: z .string() diff --git a/src/lib/openapi/routes/labs.ts b/src/lib/openapi/routes/labs.ts index f0ef1f760..6dd124e3b 100644 --- a/src/lib/openapi/routes/labs.ts +++ b/src/lib/openapi/routes/labs.ts @@ -19,6 +19,11 @@ import { listLabResultsSchema, updateLabResultSchema, } from "@/lib/validations/labs"; +import { + FHIR_LAB_FAILURE_REASONS, + FHIR_LAB_SKIP_REASONS, +} from "@/lib/labs/fhir-import/types"; +import { fhirLabBatchSchema } from "@/lib/validations/labs-fhir"; import { dataEnvelope, @@ -88,7 +93,10 @@ const labResultRow = z referenceOrigin: referenceOriginEnum, referenceDivergesFromCatalog: z.boolean(), takenAt: z.string(), - source: z.string(), + source: z.string().meta({ + description: + "Where the reading came from: `MANUAL` (typed), `OCR` (a scanned report), `DOCUMENT` (a document import), `IMPORT` (a lab CSV) or `APPLE_HEALTH` (Apple Health's Health Records, from an export or `POST /api/labs/fhir-batch`). Open-ended: render an unknown value as-is.", + }), hasNote: z.boolean(), rangeStatus: rangeStatusEnum, createdAt: z.string(), @@ -180,6 +188,37 @@ export const labOverviewResponse = z }) .meta({ id: "LabOverviewResponse" }); +const fhirLabBatchRequest = fhirLabBatchSchema.meta({ + id: "FhirLabBatchRequest", + description: + "1 to 200 Health Records lab results (`HKClinicalTypeIdentifierLabResultRecord`), each the FHIR resource as JSON plus the HealthKit fields its identity is built from. Send a panel and its members in the same batch so the members carry the panel's name. No `userId`: the owner is the caller.", +}); + +const fhirLabRecordResult = z + .object({ + index: z.number().int(), + status: z.enum(["inserted", "duplicate", "skipped", "failed"]), + reason: z + .enum([...FHIR_LAB_SKIP_REASONS, ...FHIR_LAB_FAILURE_REASONS]) + .optional(), + }) + .meta({ + id: "FhirLabRecordResult", + description: + "One record's outcome, by its position in the request. `inserted`: written. `duplicate`: the record already holds it, under the same identity (deleted readings included, so a deleted result stays deleted) or as the same reading on the same day from another source. `skipped`: not a reading HealthLog keeps, with `reason` `not_observation` | `not_lab` | `not_final` (preliminary; it is taken once final) | `withdrawn` | `panel_header` | `no_value` | `unsupported_value` | `no_date` | `future_date` | `invalid_date` | `too_large` (a resource over 256 KiB). `failed`: a reading that could not be stored, with `reason` `missing_unit` | `unit_mismatch` (the account's marker is in a unit this one does not convert into) | `text_too_long` | `write_failed` (transient: send it again).", + }); + +const fhirLabBatchResponse = z + .object({ + results: z.array(fhirLabRecordResult), + inserted: z.number().int(), + duplicate: z.number().int(), + skipped: z.number().int(), + failed: z.number().int(), + outcome: z.enum(["empty", "failed", "partial", "success"]), + }) + .meta({ id: "FhirLabBatchResponse" }); + const notFound = { "404": { description: "Lab result not found (or owned by another user).", @@ -239,6 +278,40 @@ export const labsPaths: NonNullable = { }, }, }, + "/api/labs/fhir-batch": { + post: { + tags: ["Labs"], + summary: "Ingest lab results from Apple Health's Health Records", + description: + "Maps each FHIR lab result (DSTU2 or R4 Observation) to a lab reading and writes it: final results only (`final`, `amended`, `corrected`), the laboratory category, numeric values in their unit (UCUM codes are read), a value with a comparator (`<0.5 mg/L`) kept as text as printed, string and coded values as text, the report's own reference range, and the panel's name for its members. The name resolves to the caller's marker by its own name, an alias, or the catalog analyte its LOINC code names; a new analyte gets a new marker; a reading in another unit is converted when the conversion is known and refused otherwise. The identity is a digest of `sourceURL` and `identifier`, the same one an Apple Health export import builds, so a result already imported from an export is a `duplicate` here, and sending a batch again is safe. First write wins: an amended result under a held identity is a duplicate. Owner-only: a cookie session or a full-scope login token. The body is capped at 1 MiB (413 past it): a client splits a large sync by size as well as by count. Rate limit 60 batches a minute; Idempotency-Key supported. A response carrying `write_failed` is `Cache-Control: no-store` and is not replayed for its key. Audits as `labs.fhir.batch` with counts only.", + parameters: [idempotencyKeyParameter], + requestBody: { + required: true, + content: { "application/json": { schema: fhirLabBatchRequest } }, + }, + responses: { + ...idempotentWrite(), + "200": { + description: + "Batch processed; one result per record. `outcome` reads `inserted` against `failed` (skips and duplicates are information, not failure).", + content: { + "application/json": { + schema: dataEnvelope( + fhirLabBatchResponse, + "FhirLabBatchEnvelope", + ), + }, + }, + }, + ...stdResponses, + "422": { + description: + "Nothing was written. `meta.errorCode` = `labs.fhir_batch.invalid`: no records, more than 200, a record without a `resource` object, an over-long HealthKit field, or a field the request does not define (every issue under `details.issues`).", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, "/api/labs/overview": { get: { tags: ["Labs"], diff --git a/src/lib/validations/labs-fhir.ts b/src/lib/validations/labs-fhir.ts new file mode 100644 index 000000000..52e9edc2b --- /dev/null +++ b/src/lib/validations/labs-fhir.ts @@ -0,0 +1,48 @@ +/** + * `POST /api/labs/fhir-batch` (#1400): lab results from Apple Health's Health + * Records, as the iOS app reads them from HealthKit (`HKClinicalRecord` → + * `HKFHIRResource`). Each record carries the FHIR resource as parsed JSON and + * the four HealthKit fields the identity is built from. The resource itself is + * checked by the mapper, not here: an unknown shape is a per-record skip, not + * a refusal of the batch. + * + * No `userId` field: the owner is the authenticated caller. + */ +import { z } from "zod/v4"; + +export const MAX_FHIR_LAB_RECORDS_PER_BATCH = 200; +/** A serialised resource past this is skipped as `too_large`. */ +export const MAX_FHIR_LAB_RESOURCE_BYTES = 256 * 1024; + +export const fhirLabRecordSchema = z.object({ + resource: z.record(z.string(), z.unknown()).meta({ + description: + "The FHIR resource as JSON (`HKFHIRResource.data`), DSTU2 or R4. Only Observations of the laboratory category are kept.", + }), + fhirVersion: z.string().max(16).optional().meta({ + description: "`HKFHIRResource.fhirVersion` (e.g. `4.0.1`).", + }), + identifier: z.string().max(256).optional().meta({ + description: + "`HKFHIRResource.identifier`, the resource's id at its source.", + }), + sourceURL: z.string().max(2048).optional().meta({ + description: + "`HKFHIRResource.sourceURL`, the issuing institution's FHIR base.", + }), + sourceName: z.string().max(200).optional().meta({ + description: + "The institution as the Health app names it (`sourceRevision.source.name`).", + }), +}); + +export const fhirLabBatchSchema = z + .object({ + records: z + .array(fhirLabRecordSchema) + .min(1) + .max(MAX_FHIR_LAB_RECORDS_PER_BATCH), + }) + .strict(); + +export type FhirLabBatchBody = z.infer;