Skip to content

Convert Withings, Oura and Google Health records - #165

Open
PSchmiedmayer wants to merge 11 commits into
fhir-measurement-catalogfrom
provider-fhir-conversion
Open

PSchmiedmayer wants to merge 11 commits into
fhir-measurement-catalogfrom
provider-fhir-conversion

Conversation

@PSchmiedmayer

@PSchmiedmayer PSchmiedmayer commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

♻️ Current situation & Problem

This PR builds on #161.

The grove-fhir guide defines profiles, a source catalog and identity rules for connected providers (Withings, Oura and the Google Health API), and GroveFHIRContract implements the shared identity, Device and Provenance infrastructure they build on. Grove had no provider converter, so a study server had to write its own conversion against the guide. Trove's server connects participants' provider accounts and needs that conversion on Linux, with stable identities so a retried conversion produces the same record version, and with an explicit statement of every source element it does not convert.

GroveProviderFHIR converts typed provider records the caller has already acquired. It does not fetch or resample data, and it never substitutes the retrieval time for a missing source time.

⚙️ Release Notes

  • New product GroveProviderFHIR for Apple platforms and Linux, depending only on GroveFHIRContract, FHIRModelsExtensions and ModelsR4.

  • ProviderFHIRConverter.convert(_:context:) takes a WithingsMeasureGroup, WithingsSummary, OuraRecord, GoogleHealthDataPoint or ProviderNativeRecording. Each ProviderConversionResult holds at most one complete ExchangeRecord and the omissions that name each element left out and why (notYetImplemented, notAdmitted, missingRequiredEvidence). Withings inputs return one result per source token.

    let context = ProviderConversionContext(
        producer: producer,
        scope: .account(withingsAccount),
        instant: persistedConversionInstant,
        sourceTimeZone: TimeZone(identifier: "Europe/Berlin")!
    )
    for result in try ProviderFHIRConverter.convert(group, context: context) {
        if let record = result.record { try upload(record) }
        for omission in result.omissions { log(omission.sourceToken, omission.element, omission.reason) }
    }
  • ProviderConversionContext holds the facts a retry reuses: producer, key space, persisted instant, source time zone and optional recording device. The key space is checked: .account(_:) for Withings and Google Health, .global(_:) for Oura, otherwise invalidScope. sourceIdentity(provider:sourceType:nativeRecordID:) exposes the identity for the caller's bookkeeping.

  • Withings: a diastolic and systolic pair in one group forms one blood pressure panel, and a lone half is omitted. Values are scaled by their base-ten exponent as Decimal without a binary floating-point step. A type stated twice throws conflictingMeasurement(_:). Each populated summary field converts under its own token, and an absent field is never zero.

  • Oura: an activity day runs from 04:00 to 04:00 in the day's time zone, so a day across a clock change keeps its real length. A sleep document without bedtime bounds produces no record.

  • Google Health: all admitted fields of one data point share one record, and SI inputs convert to the contract's units as exact decimals.

  • A workout without an evidenced activity code from the pinned contract produces no Observation, so no workout is reported as other.

  • Exact source times: Oura and Google Health times are ProviderTimestamp and ProviderInterval, which keep the RFC 3339 spelling, offset and up to nine fractional digits, and compare instants to the nanosecond. Withings times stay Date and are written in the source time zone.

    let bedtime = try ProviderInterval(
        start: ProviderTimestamp("2026-03-07T23:12:04.250+01:00"),
        end: ProviderTimestamp("2026-03-08T07:03:10+01:00")
    )
    var sleep = OuraSleepRecord(id: documentID, bedtime: bedtime)
    sleep.totalSleepDuration = 25_230
    let result = try ProviderFHIRConverter.convert(.sleep(sleep), context: ouraContext)
    // effectivePeriod.start is "2026-03-07T23:12:04.250+01:00"; total sleep is 7.0083 h
  • Durations are stated in their contract's UCUM time unit and rounded half to even at four decimal places. A value outside its domain throws invalidQuantity(_:) naming the measurement, and a source that does not match its contract throws invalidContract(_:).

  • ProviderNativeRecording holds exact provider JSON in a RecordingFile for the four streams the guide admits as recordings. It validates the JSON within a byte limit (at most 64 MiB), requires a relative attachment path and a RecordingPayloadAdmission, and keeps each provider's period representation. The DocumentReference states the file's SHA-1 and byte count.

  • ProviderCapabilities.sources(for:) lists every catalog row of a provider with its guide status, output profiles, conversionSupport and effective form, so a client can build its collection options from it.

  • generate-grove-fhir-swift-contract.py generates ProviderImplementationStatus and the internal ProviderContract from the guide's provider catalog, and Canonicals exposes the provider extension URLs.

📚 Documentation

A new GroveProviderFHIR DocC catalog covers identity and retries, structured values and native recording files. Every public type has symbol documentation, and .spi.yml lists the new module.

✅ Testing

New test target GroveProviderFHIRTests, added to the GroveFHIR test plan:

  • WithingsFHIRTests, OuraFHIRTests and GoogleHealthAPIFHIRTests: every advertised structured source has a positive fixture. They also cover decimal scaling and overflow, blood pressure pairing, omissions, civil days and 04:00 activity days across clock changes, missing sleep bounds, a wrong key space, and exact unit conversion.
  • OuraExactTimeTests and ProviderTimestampTests: source offsets and spellings survive daylight-saving transitions, ordering is exact across offsets and nanoseconds, and malformed or over-precise times are refused.
  • ProviderUnitConversionTests: every unit conversion, domain errors, duration units and rounding.
  • ProviderWorkoutTests: workouts without an evidenced activity emit nothing.
  • ProviderRecordingFHIRTests: native streams keep their exact payload and identity; malformed JSON, duplicate members, path traversal and an exceeded limit are refused; recording periods keep their source representation.
  • The generator script test covers the provider catalog fields.

Code of Conduct & Contributing Guidelines

By creating and submitting this pull request, you agree to follow our Code of Conduct and Contributing Guidelines:

@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4ae6b49c-14a7-4b49-a9ac-3eb4bd75d3e9

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@PSchmiedmayer
PSchmiedmayer added this pull request to stack #166 November 18, 2026 16:52
GroveProviderFHIR converts typed connected-provider records into exchange
records with the shared identity, Device and conversion Provenance
infrastructure. ProviderFHIRConverter converts Withings measure groups
and summaries, Oura documents, Google Health data points and native
provider recordings, each into one complete record or explicit
omissions. ProviderCapabilities states the conversion support of every
source token of the pinned provider catalog, with its generated
ProviderImplementationStatus.

Oura and Google Health times are ProviderTimestamp and ProviderInterval
values, so outputs state the source's exact spelling, UTC offset and
fractional digits; Withings epoch-second times use Date. The module
builds on Linux, and the generated contract adds the provider catalog.
Withings, Oura and Google Health sleep-stage durations were converted to
hours but stated under the stage contracts' `min` unit. One helper now
converts a duration into the time unit its contract names, so total sleep is
stated in hours and each stage in minutes. Tests assert the value, code and
unit of every unit conversion of the three providers.
`ProviderNativeRecording.interval` states an Oura or Google Health period as
a `ProviderInterval`, so the document keeps the source's UTC offset and
digits, while a Withings period stays a `DateInterval`. The initializer
throws only `ValidationError` besides cancellation, and `ProviderCivilDay`
throws only `ProviderConversionError`. The product and documentation entries
now sit next to GroveFHIR, and a test checks that every native recording
stream is advertised as its provider's native recording token.
A duration that doesn't divide evenly into its contract's unit, such as
25,230 seconds in hours, is rounded half to even at four decimal places
instead of stating a 38-digit repeating decimal. The unit tests cover a
non-divisible duration and the identity mappings (oxygen saturation,
temperature, heart rate variability and respiratory rate), the Google Health
tests use a connection of their own, the native recording token test moves to
the recording tests, and the recording interval check reads plainly.
A `switch` expression takes `try` on each case, not in front of the switch.
`ProviderConversionError.invalidQuantity` always carries the identifier of the
measurement or measurement component, where a value outside a quantity's
domain carried its unit code before. The documentation calls identifiers
stable and custody persistent.
ValidationError.invalidPath names every case the shared relative
attachment path check refuses.
@PSchmiedmayer
PSchmiedmayer removed this pull request from stack #166 November 28, 2026 00:16
@PSchmiedmayer
PSchmiedmayer force-pushed the provider-fhir-conversion branch from b59b3dc to 3b160e7 Compare November 28, 2026 00:17
@PSchmiedmayer
PSchmiedmayer changed the base branch from healthkit-food to fhir-measurement-catalog November 28, 2026 00:17
@PSchmiedmayer
PSchmiedmayer marked this pull request as ready for review December 6, 2026 06:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant