Skip to content

Huawei API integration - #204

Open
yatharthranjan wants to merge 69 commits into
devfrom
claude/huawei-api-integration-hxdqtl
Open

yatharthranjan wants to merge 69 commits into
devfrom
claude/huawei-api-integration-hxdqtl

Conversation

@yatharthranjan

@yatharthranjan yatharthranjan commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Initial implementation of a Huawei Health Kit source connector (huawei-library + kafka-connect-huawei-source), modelled on the Oura connector.

What it does

  • 56 data types from the RADAR-Schemas radar-huawei-connector spec (released in radar-schemas-commons 0.9.1), each with huawei.<key>.enabled / huawei.<key>.topic settings generated from one route registry (HuaweiRouteFactory).
  • Four request shapes: sampleSet:polymerize (sample points), sampleSet:dailyPolymerize (per-UTC-day statistics), healthRecords (ECG, sleep, blood pressure, alerts, menstrual cycle) and activityRecords.
  • Users from rest-source-authorizer (default) or local YAML files with token refresh.
  • huawei.api.url sets the Health Kit API host (default https://hihealthbase-dre.things.dbankcloud.cn).

Offsets and history

  • Time windows without data only count as collected once older than huawei.late.sync.window (default P14D), since devices sync late. Their offset is stored through an empty record on huawei.heartbeat.topic (default connect_huawei_heartbeat, create it compacted), because Kafka Connect only stores offsets along with records.
  • huawei.max.history (ISO-8601 period, e.g. P1Y) limits how far back data is requested, counted from the user's authorization time (authorizedAt if the authorizer provides it, else createdAt). Windows Huawei still rejects with 403 "The query time is out of range." step the offset forward a day at a time.
  • Huawei error 121001 (site cross: user and app in different Huawei regions) backs off all routes of that user for 24h.

Tooling

scripts/huawei-api-probe.sh sends the connector's exact request for each route against a live account, for checking response shapes (DAYS, ENDED_DAYS_AGO, HUAWEI_API_URL, route filters).
scripts/huawei-response-fixtures.py trims its output into converter test fixtures, replacing device and record identifiers. HuaweiRecordedResponseTest converts 27 recorded routes (including activity, ECG and sleep records) and compares every field against a snapshot.

Before leaving draft

claude added 9 commits July 14, 2026 10:25
…erns

Captures the two connector generations (generic kafka-connect-rest-source
framework used by Fitbit vs. the newer oura-library + thin Connect glue
split used by Oura), the runtime polling/auth/conversion flow, config and
Docker/CI setup, and a checklist for adding a new vendor integration such
as Huawei following the Oura pattern.
Registers the two new Gradle modules, pins radar-schemas-commons
0.9.0-SNAPSHOT (huawei_schemas branch not yet released) as a separate
version-catalog entry so existing modules keep the stable release, and
adds the user/UserRepository domain types mirroring oura-library's
pattern.
Adds the domain logic for the Huawei Health Kit connector, mirroring
oura-library's split of pure-Kotlin logic from Kafka Connect glue:

- request/: RestRequest, RequestGenerator, HuaweiRequestGenerator (offset
  tracking, per-route backoff on 401/403/429/etc), HuaweiResult/HuaweiError.
- route/: HuaweiRoute base (OAuth2-authorized GET/POST + time-range
  chunking), three concrete route kinds covering the Health Kit Data API's
  endpoints - HuaweiSampleSetRoute (POST sampleSet:polymerize, raw or
  groupByTime-aggregated), HuaweiHealthRecordRoute (GET healthRecords),
  HuaweiActivityRecordRoute (GET activityRecords) - and HuaweiRouteFactory,
  a single registry mapping all ~54 Huawei data types from the
  radar-huawei-connector schema spec to their endpoint, dataTypeName, and
  Avro record builder.
- converter/: FieldValues (typed accessor for Huawei's field-value sample
  point format) and generic converters that turn API responses into
  TopicData for the registered Avro records.

Field-value key names are best-effort (Huawei HiHealth Field naming
convention); this was verified to compile against a locally-published
radar-schemas-commons 0.9.0-SNAPSHOT (huawei_schemas branch) since none of
the real snapshot hosts are reachable from this sandbox - flagged in
comments for verification against a live API response.
Mirrors kafka-connect-oura-source: HuaweiSourceConnector (periodic user
refresh + task reconfiguration), HuaweiSourceTask (round-robin polling
across routes, JSON->Avro->SourceRecord conversion via AvroData),
KafkaOffsetManager, and HuaweiServiceUserRepository (Ktor-based
rest-source-authorizer client with OAuth2 client-credentials auth and
cached user/token lookups).

HuaweiRestSourceConnectorConfig is written in Kotlin and loop-generates
its ~110 per-data-type `huawei.<key>.enabled`/`huawei.<key>.topic`
ConfigDef entries from huawei-library's HuaweiRouteFactory.definitions
registry, rather than hand-duplicating a static field per topic as
Fitbit/Oura do - the same registry also drives which routes
HuaweiSourceTask actually builds, so the connector config and the set of
polled routes can never drift out of sync.

Could not compile this module in this sandbox: packages.confluent.io
(needed for kafka-connect-api/kafka-connect-avro-converter) is blocked by
the sandbox's egress policy - confirmed this is pre-existing and applies
equally to kafka-connect-oura-source, not something introduced here.
huawei-library (the part of this change with real logic to verify) does
compile cleanly against a locally-published radar-schemas-commons
0.9.0-SNAPSHOT.
Adds docker/source-huawei.properties.template, a radar-huawei-connector
docker-compose service, a README section, and registers the
kafka-connect-huawei-source image in both CI workflow matrices. Updates
ARCHITECTURE.md to document the Huawei module and the route-registry
config-generation pattern it introduces for connectors with a large
number of data types.
huawei-library tests (verified passing in this sandbox against a locally
published radar-schemas-commons 0.9.0-SNAPSHOT):
- FieldValuesTest: typed-value array and flattened-object parsing.
- HuaweiRouteFactoryTest: builds every one of the ~54 registered route
  definitions, feeds each a fixture payload shaped for its endpoint kind,
  and asserts the converter produces exactly one record on the expected
  topic without throwing - this caught two real bugs during development
  (a bad endTime field on HuaweiCgmBloodGlucose, and a private extension
  function shadowing HuaweiDataConverter's).

kafka-connect-huawei-source gets a config test mirroring the existing
*RestSourceConnectorConfigTest convention, plus checks that
enabledTopics() reflects the shared HuaweiRouteFactory.definitions
registry and honors per-type huawei.<key>.enabled overrides. Could not
run this one in-sandbox (see prior commit: packages.confluent.io is
blocked here for every kafka-connect-*-source module, pre-existing and
unrelated to this change).

Also switches huawei-library's JUnit integration from kotlin-test-junit
(JUnit4) to kotlin-test-junit5, since oura-library's copy-pasted
dependency block conflicts with the JUnit Platform the radar-kotlin
Gradle plugin configures the test task with - previously unnoticed only
because no *-library module had tests yet.
`./gradlew check` runs ktlint over every module; auto-formatted the
mechanical issues (semicolons, wrapping) and manually split a handful of
lines ktlint couldn't auto-correct. huawei-library:check is now fully
green (ktlint + all 5 tests) in this sandbox.
ktlint is static analysis and doesn't need dependency resolution to run,
so this module's Kotlin sources could be linted even though they can't
be compiled in this sandbox. Wraps long ConfigDef.define() calls and
doc-string constants, and simplifies the getUserRepository()/
initialize() flow slightly in the process.
Adds yatharthranjan@onsentia.com alongside the existing KCL address in
the Huawei Docker image label and CI workflow author fields.
@yatharthranjan
yatharthranjan marked this pull request as draft July 14, 2026 13:16
@yatharthranjan yatharthranjan changed the title [WiP] Claude/huawei api integration hxdqtl [WiP] Huawei API integration Jul 14, 2026
claude added 5 commits July 14, 2026 13:45
- Wrap the okhttp3.HttpUrl from getHuaweiUserRepositoryUrl() in
  URLBuilder(...).build() before passing it as createClient's Ktor
  Url parameter, matching how the token URL was already handled
  (and how OuraServiceUserRepository does it).
- Throwable.message is nullable; fall back to a default string before
  passing it to UserNotAuthorizedException's non-null constructor.

These only surfaced in real CI since packages.confluent.io is blocked in
this sandbox, so kafka-connect-huawei-source couldn't be compiled here -
verified via ktlint (which needs no dependency resolution) that the fix
introduces no new style issues.
ktlintKotlinScriptCheck also lints .gradle.kts files; wraps the two
GitHub Packages credential lines that exceeded 100 chars.
Applies a standard Apache-2.0 copyright header (Copyright 2026 Onsentia)
to every .kt/.java file in huawei-library and kafka-connect-huawei-source
- the two modules added for the Huawei Health Kit integration. Files
that had copied The Hyve's 2018 header from the Oura pattern get it
replaced; files with no header get one prepended. Pre-existing
Fitbit/Oura files are left untouched since their copyright belongs to
their original authors.
Was still copied from Oura's Dockerfile (Copyright 2018 The Hyve);
updates to match the Onsentia header applied to the rest of this
module's files.
Adds an @author yatharthranjan KDoc/Javadoc tag to the primary
class/interface/object of every .kt/.java file in huawei-library and
kafka-connect-huawei-source: appended to existing class-level doc
comments where present, added as a new minimal doc comment otherwise.
claude added 11 commits July 28, 2026 13:25
Lets the Huawei connector run against per-user YAML credential files
under huawei.user.dir, mirroring Fitbit's YamlUserRepository, so it can
be tested locally without a rest-source-authorizer webservice. Adds a
docker/huawei-user.yml.template and README instructions for the flow.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
isAuthorizedOverride was mapped to the same JSON key ("isAuthorized")
as the isAuthorized computed property, causing Jackson to fail with
"Conflicting getter definitions" when reading user YAML files. Rename
the manual-override field's JSON key to "authorized".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
The 400/401/403 branches previously logged only a hardcoded generic
message, discarding the real error body Huawei's API returned. This
made it impossible to diagnose the actual cause of a failed request
(e.g. wrong client/app, invalid scope) from the logs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
HuaweiHealthRecordRoute sent the health record type identifier under
a "subDataTypeName" query parameter, but Huawei's healthRecords API
expects it under "dataTypeName" - the API was silently rejecting every
health_record_* request with "DataTypeName is null" since it never
received the parameter it actually looks for. Renamed the parameter
(and the route/factory field) to dataTypeName throughout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
Per Huawei's official "Querying Health Records of a Data Type" spec:
- The endpoint is on API version v2, not v1.
- The data type query parameter is named "dataType", not "dataTypeName"
  (and not "subDataTypeName" as it was before that).
- startTime/endTime, both in the request and in each returned record,
  are in nanoseconds since the epoch, not milliseconds.

This was causing every health_record_* request to fail with
"DataTypeName is null", and would have produced wildly wrong
timestamps for any record that did come back.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
The generic error branch (405/409/500/502/503/590, and anything else
not explicitly handled) hardcoded its HuaweiGenericError's code to
"500" regardless of the actual response status, which was misleading
for diagnostics.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
Per the official Health Kit REST API reference (Postman "HMS Core"
collection, "Querying Sampling Data Statistics of Multiple Days"), the
groupByTime-aggregated variant of a data type is obtained by polymerizing
the underlying *raw* dataTypeName with groupByTime, not by sending a
literal "*.statistics"-suffixed dataTypeName - that suffix is only
RADAR-Schemas'/this connector's own label for "the daily-aggregated
route", not a real Huawei data type identifier. Sending it verbatim is
exactly why Huawei's API had no dataCollector for e.g.
"com.huawei.continuous.heart_rate.statistics", "com.huawei.vo2max.statistics",
"com.huawei.resting_calories.statistics", etc. - across every single
statistics route built via sampleSetDefinition().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
…erize

Huawei's live API confirmed the root cause behind most "no default
dataCollector found"/"Invalid dataTypeName" errors on statistics routes:
sampleSet:polymerize does not support a groupByTime-aggregated query for
every data type (confirmed live: "com.huawei.resting_calories does not
support the query mode, please use dailyPolymerize API"). Per the
official REST API reference for "Querying Sampling Data Statistics of
Multiple Days", the day-aggregated variant of a data type must instead
go through the dedicated POST /healthkit/v2/sampleSet:dailyPolymerize
endpoint, which takes a startDay/endDay (yyyyMMdd) + timeZone request
body and returns a differently-shaped, doubly-nested
group[].sampleSet[].samplePoints[] response (with group-level times in
milliseconds but sample-point times in nanoseconds).

Adds HuaweiDailyPolymerizeRoute/HuaweiDailyPolymerizeConverter and
routes every "*.statistics" definition through it instead of
HuaweiSampleSetRoute, which now only handles raw (non-statistics) data
types and has had its now-dead groupByTime support removed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
Per Huawei's "Querying Created Exercise Records" spec:
- The endpoint is on API version v2, not v1.
- The response's array of records is under the key "activityRecord"
  (singular), not "activityRecords" - we were reading the wrong key,
  so every activity_record request was silently producing zero
  records regardless of what the API actually returned, with no error
  logged.
- Each record's description field is "desc", not "description".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
"com.huawei.daily_activity_summary" is not a real sampleSet
dataTypeName (confirmed live: "no default dataCollector found"). The
goal fields this route maps to actually belong to a separate endpoint
(GET /healthkit/v2/sampleConfigs?type=9002&id=<...>, "Querying Activity
Goals" - one call per goal type), while the achieved-value fields
would need to come from the existing continuous/statistics routes.
That needs a route that issues multiple requests and merges them,
which is a real design decision rather than an endpoint/field-name
fix like the other routes touched this session, so disable it by
default (huawei.daily_activity_summary.enabled=false) rather than
leave it erroring or guess at a composite implementation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
"*.total" is never a valid Huawei request dataTypeName (confirmed
live: "no default dataCollector found for: com.huawei.continuous.steps.total"),
matching the official dailyPolymerize doc's own example: it requests
"com.huawei.continuous.steps.delta" and gets back a response labelled
"com.huawei.continuous.steps.total". Adds queryDataTypeSuffix/
useDailyPolymerize overrides to sampleSetDefinition() and points
continuous_steps_total, continuous_distance_total, and
continuous_calories_burnt_total at their sibling raw/delta data type
through the dailyPolymerize endpoint instead of requesting the
".total" name directly via plain polymerize.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
this-Aditya and others added 9 commits October 27, 2026 18:39
- Store the offset of time windows without data once they are older
  than huawei.late.sync.window (default P14D), by writing an empty
  record to huawei.heartbeat.topic: Kafka Connect only stores offsets
  along with records, so restarts re-requested every empty stretch.
- Add huawei.max.history (ISO-8601 period): data before the user's
  authorization time minus this period is not requested, matching
  Huawei's history limit. Uses an optional authorizedAt from the user
  repository, falling back to createdAt.
- Detect Huawei error 121001 (site cross) and back off all routes of
  that user for 24h with a clear log message.
- Use huawei.user.poll.interval (default now 1800s) as the re-poll
  interval of caught-up routes; drop the unused rest.source.base.url
  and rest.source.poll.interval.ms settings.
- Remove the unreachable TooManyRequestsException catch.

Claude-Session: https://claude.ai/code/session_01PeNFs67cbLTGQ6xKiyDHdC
- Parse activity records through FieldValues, so non-numeric text
  becomes null instead of 0 like in the other converters.
- Move the shared route toString into HuaweiRoute, drop unused open
  modifiers, and name the statistics type tables with a data class.
- Wrap lines longer than the .editorconfig limit of 100 characters.

Claude-Session: https://claude.ai/code/session_01PeNFs67cbLTGQ6xKiyDHdC
Document the late sync window, history limit, heartbeat topic and
poll interval settings and the multi-device late sync limitation,
point to the released schemas, and bring the architecture notes in
line with the four Huawei route kinds and current tests.

Claude-Session: https://claude.ai/code/session_01PeNFs67cbLTGQ6xKiyDHdC
Huawei rejects windows before its history limit (counted from when the
user authorized access) with 403 "The query time is out of range.".
Move the offset forward a day at a time on that error, so the route
reaches the limit without losing data of a window that only partly
precedes it. Found by probing a live account with the new
ENDED_DAYS_AGO option of the probe script.

Claude-Session: https://claude.ai/code/session_01PeNFs67cbLTGQ6xKiyDHdC
Probing the live Health Kit API showed three converters reading paths
Huawei doesn't send:
- Activity records: the device is under deviceInfo (manufacturer,
  deviceCode) and pace under activitySummary.paceSummary, so manufacturer,
  device type and all pace fields were always null. deviceType now holds
  deviceInfo.deviceCode.
- ECG records: detail samples come as subData, an object of sample sets
  keyed by detail data type, not a subDataDetails list, so voltageData
  was always null.
- Exercise intensity v2 statistics: the map field is intensity_map, not
  intensity, so intensityMap was always null.

Converter tests now run on trimmed responses recorded from the live API
(huawei-library/src/test/resources/huawei-responses), with device and
record identifiers replaced by scripts/huawei-response-fixtures.py.
HuaweiRecordedResponseTest compares every converted record with a
snapshot, and the remaining unit tests use the live envelopes and value
shapes.

Claude-Session: https://claude.ai/code/session_01PeNFs67cbLTGQ6xKiyDHdC
GLOSSARY.md defines the collection terms used across the connectors
(Route, User, Offset, Late sync, Settled window, Authorization time,
History limit) and the Huawei data shapes. The ADR records why empty
windows only advance the stored offset once settled, why that offset is
persisted through a heartbeat record, and why the history limit counts
from authorization time. ARCHITECTURE.md already links to the ADR.

Claude-Session: https://claude.ai/code/session_01PeNFs67cbLTGQ6xKiyDHdC
- Add huawei.api.url (default https://hihealthbase-dre.things.dbankcloud.cn).
  Routes build <apiUrl>/healthkit/<version>/<path>; the probe script takes
  HUAWEI_API_URL.
- Skip points of other data types in polymerize responses: the sleep fragment
  response also carries the night's sleep record point, which became a bogus
  fragment with a null sleep state.
- Skip body fat statistics days that only have a weight: Huawei returns the
  weight statistics without any body fat fields, which produced all-null
  records.
- Regenerate recorded-response fixtures and snapshots from a two-day probe,
  adding sleep fragment, sleep record and on/off bed responses, and keep the
  first two points per data type.
@yatharthranjan
yatharthranjan marked this pull request as ready for review November 23, 2026 13:32
master's Gradle 9.6 bump makes each Dockerfile create the directories of
the projects it doesn't copy, since Gradle 9 refuses to configure an
included project whose directory is missing. Add the Huawei modules to
the Oura and Fitbit lists, add the other modules to the Huawei
Dockerfile, and move its builder image to gradle:9.6.0-jdk17 like the
others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w6G3vGzKQ4ogcLgtWwzun
@mpgxvii
mpgxvii changed the base branch from master to dev December 1, 2026 14:17
@yatharthranjan yatharthranjan changed the title [WiP] Huawei API integration Huawei API integration Dec 1, 2026
The live Health Kit API sends the 24-hour blood pressure plan id as
planID, so planId was always null. Accept both spellings.
poll() iterated every user's requests in one call and slept up to a
minute between rounds while idle. Kafka Connect calls stop() only after
poll() returns, so stopping a task exceeded
task.shutdown.graceful.timeout.ms (5 seconds): the task was cancelled and
its final offset commit skipped, re-sending records on restart.

poll() now resumes a pending request iterator across calls, returns
after at most one second, and waits for the next round in slices of at
most one second, returning early when the task is stopped.
After refreshing a token, the YAML user repository wrote isAuthorized,
observationKey and versionedId into the user file. Reading the file
again failed with "Not an array" on observationKey, so the user could no
longer be loaded. Ignore the derived properties when writing.
The connector logged every task config at INFO, including
huawei.api.secret and the user repository client secret. Log the number
of tasks and their users instead.
In standalone mode the connector stores offsets under
/var/lib/kafka-connect-huawei-source/logs. The directory did not exist in
the image, so Docker created the volume owned by root and appuser could
not write the offsets file. Create it owned by appuser.

Also ignore docker/source-huawei.properties, which holds the Huawei
client credentials, like the Fitbit and Oura properties.
Daily statistics are requested for whole UTC days, so for users outside
UTC they cover a different period than the Huawei Health app's day.
Document this and where the device time zone is kept.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

3 participants