-
Notifications
You must be signed in to change notification settings - Fork 464
Expand file tree
/
Copy pathdata_247.py
More file actions
1055 lines (950 loc) · 38.2 KB
/
Copy pathdata_247.py
File metadata and controls
1055 lines (950 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Whoop 247 Data implementation for sleep, recovery, cycle, and activity samples."""
from contextlib import suppress
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from typing import Any
from uuid import UUID, uuid4
from app.config import settings
from app.database import DbSession
from app.models import DataPointSeries, DataSource, EventRecord
from app.repositories import EventRecordRepository, UserConnectionRepository
from app.repositories.data_source_repository import DataSourceRepository
from app.schemas.enums import HealthScoreCategory, ProviderName, SeriesType, get_series_type_id
from app.schemas.model_crud.activities import (
EventRecordCreate,
EventRecordDetailCreate,
HealthScoreCreate,
ScoreComponent,
TimeSeriesSampleCreate,
)
from app.services.event_record_service import event_record_service
from app.services.health_score_service import health_score_service
from app.services.providers.api_client import make_authenticated_request
from app.services.providers.templates.base_247_data import Base247DataTemplate
from app.services.providers.templates.base_oauth import BaseOAuthTemplate
from app.services.raw_payload_storage import store_raw_payload
from app.services.timeseries_service import timeseries_service
from app.utils.structured_logging import log_structured
class Whoop247Data(Base247DataTemplate):
"""Whoop implementation for 247 data (sleep, recovery, cycles, activity)."""
def __init__(
self,
provider_name: str,
api_base_url: str,
oauth: BaseOAuthTemplate,
) -> None:
super().__init__(provider_name, api_base_url, oauth)
self.event_record_repo = EventRecordRepository(EventRecord)
self.data_source_repo = DataSourceRepository(DataSource)
self.connection_repo = UserConnectionRepository()
def _make_api_request(
self,
db: DbSession,
user_id: UUID,
endpoint: str,
params: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> Any:
"""Make authenticated request to Whoop API."""
log_structured(
self.logger,
"debug",
f"Making API request to {endpoint}",
provider="whoop",
endpoint=endpoint,
params=params,
)
return make_authenticated_request(
db=db,
user_id=user_id,
connection_repo=self.connection_repo,
oauth=self.oauth,
api_base_url=self.api_base_url,
provider_name=self.provider_name,
endpoint=endpoint,
method="GET",
params=params,
headers=headers,
)
def _get_paginated_records(
self,
db: DbSession,
user_id: UUID,
endpoint: str,
start_time: datetime,
end_time: datetime,
task: str,
) -> list[dict[str, Any]]:
"""Fetch all records from a paginated Whoop v2 collection endpoint."""
all_records: list[dict[str, Any]] = []
next_token = None
max_limit = 25 # Whoop API limit
# Convert datetimes to ISO 8601 strings
start_iso = start_time.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
end_iso = end_time.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
while True:
params: dict[str, Any] = {
"start": start_iso,
"end": end_iso,
"limit": max_limit,
}
if next_token:
params["nextToken"] = next_token
try:
response = self._make_api_request(db, user_id, endpoint, params=params)
store_raw_payload(
source="api_response",
provider="whoop",
payload=response,
user_id=str(user_id),
trace_id=endpoint,
)
# Extract records from response
records = response.get("records", []) if isinstance(response, dict) else []
all_records.extend(records)
# Check for next page
next_token = response.get("next_token") if isinstance(response, dict) else None
# Stop if no more records or no next token
if not records or not next_token:
break
except Exception as e:
log_structured(
self.logger,
"error",
f"Error fetching Whoop data from {endpoint}: {e}",
provider="whoop",
task=task,
user_id=str(user_id),
)
# If we got some data, return what we have; otherwise re-raise
if all_records:
log_structured(
self.logger,
"warning",
f"Returning partial data from {endpoint} due to error: {e}",
provider="whoop",
task=task,
user_id=str(user_id),
)
break
raise
return all_records
# -------------------------------------------------------------------------
# Sleep Data - Whoop /v2/activity/sleep
# -------------------------------------------------------------------------
def get_sleep_data(
self,
db: DbSession,
user_id: UUID,
start_time: datetime,
end_time: datetime,
) -> list[dict[str, Any]]:
"""Fetch sleep data from Whoop API via v2 endpoint with pagination."""
return self._get_paginated_records(db, user_id, "/v2/activity/sleep", start_time, end_time, "get_sleep_data")
def _normalize_sleep_health_score(
self,
normalized: dict[str, Any],
user_id: UUID,
) -> HealthScoreCreate | None:
"""Build a HealthScoreCreate for Whoop sleep score."""
if normalized.get("score_state") != "SCORED":
return None
performance = normalized.get("sleep_performance_percentage")
timestamp = normalized.get("timestamp")
if performance is None or timestamp is None:
return None
if isinstance(timestamp, str):
try:
timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
except (ValueError, AttributeError):
return None
components = {
k: ScoreComponent(value=v)
for k, v in {
"sleep_consistency_percentage": normalized.get("sleep_consistency_percentage"),
"sleep_efficiency_percentage": normalized.get("sleep_efficiency_percentage"),
"respiratory_rate": normalized.get("respiratory_rate"),
}.items()
if v is not None
}
return HealthScoreCreate(
id=uuid4(),
user_id=user_id,
provider=ProviderName.WHOOP,
category=HealthScoreCategory.SLEEP,
value=performance,
recorded_at=timestamp,
components=components or None,
)
def normalize_sleep(
self,
raw_sleep: dict[str, Any],
user_id: UUID,
) -> tuple[dict[str, Any], HealthScoreCreate | None]: # ty:ignore[invalid-method-override]
"""Normalize Whoop sleep data to our schema."""
# Extract basic fields
sleep_id = raw_sleep.get("id")
start_time = raw_sleep.get("start")
end_time = raw_sleep.get("end")
nap = raw_sleep.get("nap", False)
cycle_id = raw_sleep.get("cycle_id")
zone_offset = raw_sleep.get("zone_offset")
# Extract score data (may be None if not scored yet)
score = raw_sleep.get("score", {}) or {}
stage_summary = score.get("stage_summary", {}) or {}
# Time conversions: Whoop provides durations in milliseconds
# Convert to seconds for our schema
total_in_bed_ms = stage_summary.get("total_in_bed_time_milli", 0)
total_awake_ms = stage_summary.get("total_awake_time_milli", 0)
total_light_ms = stage_summary.get("total_light_sleep_time_milli", 0)
total_slow_wave_ms = stage_summary.get("total_slow_wave_sleep_time_milli", 0)
total_rem_ms = stage_summary.get("total_rem_sleep_time_milli", 0)
# Convert milliseconds to seconds
duration_seconds = int(total_in_bed_ms / 1000) if total_in_bed_ms else 0
deep_seconds = int(total_slow_wave_ms / 1000) if total_slow_wave_ms else 0
light_seconds = int(total_light_ms / 1000) if total_light_ms else 0
rem_seconds = int(total_rem_ms / 1000) if total_rem_ms else 0
awake_seconds = int(total_awake_ms / 1000) if total_awake_ms else 0
# If duration is 0 but we have start/end times, calculate from timestamps
if duration_seconds == 0 and start_time and end_time:
try:
start_dt = datetime.fromisoformat(start_time.replace("Z", "+00:00"))
end_dt = datetime.fromisoformat(end_time.replace("Z", "+00:00"))
duration_seconds = int((end_dt - start_dt).total_seconds())
except (ValueError, AttributeError):
pass
# Efficiency percentage
efficiency = score.get("sleep_efficiency_percentage")
# Generate UUID for our internal ID (use Whoop ID if it's a valid UUID string)
internal_id = uuid4()
if sleep_id:
with suppress(ValueError, TypeError):
internal_id = UUID(sleep_id)
normalized = {
"id": internal_id,
"user_id": user_id,
"provider": self.provider_name,
"timestamp": start_time or end_time,
"start_time": start_time,
"end_time": end_time,
"zone_offset": zone_offset,
"duration_seconds": duration_seconds,
"efficiency_percent": float(efficiency) if efficiency is not None else None,
"is_nap": nap,
"stages": {
"deep_seconds": deep_seconds,
"light_seconds": light_seconds,
"rem_seconds": rem_seconds,
"awake_seconds": awake_seconds,
},
"whoop_sleep_id": sleep_id,
"whoop_cycle_id": cycle_id,
"score_state": raw_sleep.get("score_state"),
"sleep_performance_percentage": score.get("sleep_performance_percentage"),
"sleep_consistency_percentage": score.get("sleep_consistency_percentage"),
"sleep_efficiency_percentage": efficiency,
"respiratory_rate": score.get("respiratory_rate"),
"raw": raw_sleep, # Keep raw for debugging
}
return normalized, self._normalize_sleep_health_score(normalized, user_id)
def save_sleep_data(
self,
db: DbSession,
user_id: UUID,
normalized_sleep: dict[str, Any],
) -> None:
"""Save normalized sleep data to database as EventRecord with SleepDetails."""
sleep_id = normalized_sleep["id"]
# Parse start and end times
start_dt = None
end_dt = None
if normalized_sleep.get("start_time"):
start_time = normalized_sleep["start_time"]
if isinstance(start_time, str):
start_dt = datetime.fromisoformat(start_time.replace("Z", "+00:00"))
elif isinstance(start_time, datetime):
start_dt = start_time
if normalized_sleep.get("end_time"):
end_time = normalized_sleep["end_time"]
if isinstance(end_time, str):
end_dt = datetime.fromisoformat(end_time.replace("Z", "+00:00"))
elif isinstance(end_time, datetime):
end_dt = end_time
if not start_dt or not end_dt:
log_structured(
self.logger,
"warning",
f"Skipping sleep record {sleep_id}: missing start/end time",
provider="whoop",
task="save_sleep_data",
user_id=str(user_id),
)
return
# Create EventRecord for sleep
record = EventRecordCreate(
id=sleep_id,
category="sleep",
type="sleep_session",
source_name="Whoop",
device_model=None,
duration_seconds=normalized_sleep.get("duration_seconds"),
start_datetime=start_dt,
end_datetime=end_dt,
zone_offset=normalized_sleep.get("zone_offset"),
external_id=str(normalized_sleep.get("whoop_sleep_id")) if normalized_sleep.get("whoop_sleep_id") else None,
source=self.provider_name,
user_id=user_id,
)
# Create detail with sleep-specific fields
stages = normalized_sleep.get("stages", {})
# Calculate total sleep time (deep + light + REM)
total_sleep_seconds = (
stages.get("deep_seconds", 0) + stages.get("light_seconds", 0) + stages.get("rem_seconds", 0)
)
total_sleep_minutes = total_sleep_seconds // 60
# Time in bed (total duration)
time_in_bed_minutes = normalized_sleep.get("duration_seconds", 0) // 60
detail = EventRecordDetailCreate(
record_id=sleep_id,
sleep_total_duration_minutes=total_sleep_minutes,
sleep_time_in_bed_minutes=time_in_bed_minutes,
sleep_efficiency_score=Decimal(str(normalized_sleep.get("efficiency_percent", 0)))
if normalized_sleep.get("efficiency_percent") is not None
else None,
sleep_deep_minutes=stages.get("deep_seconds", 0) // 60,
sleep_light_minutes=stages.get("light_seconds", 0) // 60,
sleep_rem_minutes=stages.get("rem_seconds", 0) // 60,
sleep_awake_minutes=stages.get("awake_seconds", 0) // 60,
is_nap=normalized_sleep.get("is_nap", False),
)
try:
event_record_service.create_or_merge_sleep(db, user_id, record, detail, settings.sleep_end_gap_minutes)
except Exception as e:
log_structured(
self.logger,
"error",
f"Error saving sleep record {sleep_id}: {e}",
provider="whoop",
task="save_sleep_data",
user_id=str(user_id),
)
def get_sleep_record(
self,
db: DbSession,
user_id: UUID,
sleep_id: str,
) -> dict[str, Any]:
"""Fetch a single sleep record by its Whoop ID from /v2/activity/sleep/{id}."""
response = self._make_api_request(db, user_id, f"/v2/activity/sleep/{sleep_id}")
store_raw_payload(
source="api_response",
provider="whoop",
payload=response,
user_id=str(user_id),
trace_id=f"/v2/activity/sleep/{sleep_id}",
)
return response if isinstance(response, dict) else {}
def load_single_sleep(
self,
db: DbSession,
user_id: UUID,
sleep_id: str,
) -> int:
"""Fetch a single sleep record by ID, normalize, and save to database."""
raw = self.get_sleep_record(db, user_id, sleep_id)
if not raw:
return 0
try:
normalized, health_score = self.normalize_sleep(raw, user_id)
self.save_sleep_data(db, user_id, normalized)
if health_score:
health_score_service.create(db, health_score)
return 1
except Exception as e:
log_structured(
self.logger,
"warning",
f"Failed to save sleep record {sleep_id}: {e}",
provider="whoop",
task="load_single_sleep",
)
return 0
def load_and_save_sleep(
self,
db: DbSession,
user_id: UUID,
start_time: datetime,
end_time: datetime,
) -> int:
"""Load sleep data from API and save to database."""
raw_data = self.get_sleep_data(db, user_id, start_time, end_time)
count = 0
health_scores: list[HealthScoreCreate] = []
for item in raw_data:
try:
normalized, health_score = self.normalize_sleep(item, user_id)
self.save_sleep_data(db, user_id, normalized)
count += 1
if health_score:
health_scores.append(health_score)
except Exception as e:
db.rollback()
log_structured(
self.logger,
"warning",
f"Failed to save sleep data: {e}",
provider="whoop",
task="load_and_save_sleep",
user_id=str(user_id),
)
if health_scores:
health_score_service.bulk_create(db, health_scores)
db.commit()
return count
def load_and_save_all(
self,
db: DbSession,
user_id: UUID,
start_time: datetime | str | None = None,
end_time: datetime | str | None = None,
is_first_sync: bool = False,
) -> dict[str, int]:
"""Load and save all 247 data types (sleep, recovery, cycles, activity).
Args:
db: Database session
user_id: User UUID
start_time: Start of date range (defaults to 30 days ago)
end_time: End of date range (defaults to now)
is_first_sync: Whether this is the first sync (unused, for API compatibility)
"""
# Handle date defaults (last 30 days if not specified)
if isinstance(start_time, str):
start_time = datetime.fromisoformat(start_time.replace("Z", "+00:00"))
if isinstance(end_time, str):
end_time = datetime.fromisoformat(end_time.replace("Z", "+00:00"))
if not start_time:
start_time = datetime.now() - timedelta(days=30)
if not end_time:
end_time = datetime.now()
results = {
"sleep_sessions_synced": 0,
"recovery_samples_synced": 0,
"cycle_scores_synced": 0,
"activity_samples_synced": 0,
"body_measurement_samples_synced": 0,
}
try:
results["sleep_sessions_synced"] = self.load_and_save_sleep(db, user_id, start_time, end_time)
except Exception as e:
db.rollback()
log_structured(
self.logger,
"error",
f"Failed to sync sleep data: {e}",
provider="whoop",
task="load_and_save_all",
user_id=str(user_id),
)
try:
results["recovery_samples_synced"] = self.load_and_save_recovery(db, user_id, start_time, end_time)
except Exception as e:
db.rollback()
log_structured(
self.logger,
"error",
f"Failed to sync recovery data: {e}",
provider="whoop",
task="load_and_save_all",
user_id=str(user_id),
)
try:
results["cycle_scores_synced"] = self.load_and_save_cycles(db, user_id, start_time, end_time)
except Exception as e:
db.rollback()
log_structured(
self.logger,
"error",
f"Failed to sync cycle data: {e}",
provider="whoop",
task="load_and_save_all",
user_id=str(user_id),
)
try:
results["body_measurement_samples_synced"] = self.load_and_save_body_measurement(db, user_id)
except Exception as e:
db.rollback()
log_structured(
self.logger,
"error",
f"Failed to sync body measurement data: {e}",
provider="whoop",
task="load_and_save_all",
user_id=str(user_id),
)
return results
# -------------------------------------------------------------------------
# Body Measurement Data (Height/Weight)
# -------------------------------------------------------------------------
def get_body_measurement(
self,
db: DbSession,
user_id: UUID,
) -> dict[str, Any]:
"""Fetch body measurements from Whoop API.
Returns height_meter, weight_kilogram, and max_heart_rate.
See: https://developer.whoop.com/api/#tag/Body-Measurement
"""
try:
response = self._make_api_request(db, user_id, "/v2/user/measurement/body")
store_raw_payload(
source="api_response",
provider="whoop",
payload=response,
user_id=str(user_id),
trace_id="/v2/user/measurement/body",
)
return response if isinstance(response, dict) else {}
except Exception as e:
log_structured(
self.logger,
"error",
f"Error fetching Whoop body measurement: {e}",
provider="whoop",
task="get_body_measurement",
user_id=str(user_id),
)
return {}
def _get_latest_value(
self,
db: DbSession,
user_id: UUID,
series_type: SeriesType,
) -> Decimal | None:
"""Get the most recent value for a series type for this user/provider."""
type_id = get_series_type_id(series_type)
result = (
db.query(DataPointSeries.value)
.join(DataSource, DataPointSeries.data_source_id == DataSource.id)
.filter(
DataSource.user_id == user_id,
DataSource.source == self.provider_name,
DataPointSeries.series_type_definition_id == type_id,
)
.order_by(DataPointSeries.recorded_at.desc())
.first()
)
return result[0] if result else None
def load_and_save_body_measurement(
self,
db: DbSession,
user_id: UUID,
) -> int:
"""Fetch body measurements and save height/weight to data_point_series.
Only saves if the value has changed from the most recent entry.
Returns the number of samples saved.
"""
body = self.get_body_measurement(db, user_id)
if not body:
return 0
recorded_at = datetime.now(timezone.utc)
samples_to_create: list[TimeSeriesSampleCreate] = []
# Save height (convert meters to centimeters) if changed
height_meter = body.get("height_meter")
if height_meter is not None:
try:
height_cm = Decimal(str(height_meter)) * 100
latest_height = self._get_latest_value(db, user_id, SeriesType.height)
if latest_height is None or abs(latest_height - height_cm) > Decimal("0.01"):
samples_to_create.append(
TimeSeriesSampleCreate(
id=uuid4(),
user_id=user_id,
source=self.provider_name,
recorded_at=recorded_at,
value=height_cm,
series_type=SeriesType.height,
)
)
except Exception as e:
log_structured(
self.logger,
"warning",
f"Failed to build height sample: {e}",
provider="whoop",
task="load_and_save_body_measurement",
user_id=str(user_id),
)
# Save weight (already in kilograms) if changed
weight_kg = body.get("weight_kilogram")
if weight_kg is not None:
try:
weight = Decimal(str(weight_kg))
latest_weight = self._get_latest_value(db, user_id, SeriesType.weight)
if latest_weight is None or abs(latest_weight - weight) > Decimal("0.01"):
samples_to_create.append(
TimeSeriesSampleCreate(
id=uuid4(),
user_id=user_id,
source=self.provider_name,
recorded_at=recorded_at,
value=weight,
series_type=SeriesType.weight,
)
)
except Exception as e:
log_structured(
self.logger,
"warning",
f"Failed to build weight sample: {e}",
provider="whoop",
task="load_and_save_body_measurement",
user_id=str(user_id),
)
if samples_to_create:
timeseries_service.bulk_create_samples(db, samples_to_create)
db.commit()
return len(samples_to_create)
# -------------------------------------------------------------------------
# Recovery Data
# -------------------------------------------------------------------------
def get_recovery_data(
self,
db: DbSession,
user_id: UUID,
start_time: datetime,
end_time: datetime,
) -> list[dict[str, Any]]:
"""Fetch recovery data from Whoop API via v2 endpoint with pagination.
Returns list of recovery records containing recovery_score, resting_heart_rate,
hrv_rmssd_milli, spo2_percentage, and skin_temp_celsius.
"""
return self._get_paginated_records(db, user_id, "/v2/recovery", start_time, end_time, "get_recovery_data")
def _normalize_recovery_health_score(
self,
normalized: dict[str, Any],
user_id: UUID,
) -> HealthScoreCreate | None:
"""Build a HealthScoreCreate for Whoop recovery score."""
recovery_score = normalized.get("recovery_score")
timestamp = normalized.get("timestamp")
if recovery_score is None or timestamp is None:
return None
components = {
k: ScoreComponent(value=normalized.get(k))
for k in ("resting_heart_rate", "hrv_rmssd_milli", "spo2_percentage", "skin_temp_celsius")
if normalized.get(k) is not None
}
return HealthScoreCreate(
id=uuid4(),
user_id=user_id,
provider=ProviderName.WHOOP,
category=HealthScoreCategory.RECOVERY,
value=recovery_score,
recorded_at=timestamp,
components=components or None,
)
def normalize_recovery(
self,
raw_recovery: dict[str, Any],
user_id: UUID,
) -> tuple[dict[str, Any], HealthScoreCreate | None]: # ty:ignore[invalid-method-override]
"""Normalize Whoop recovery data to our schema.
Extracts recovery metrics from the score object:
- recovery_score (0-100)
- resting_heart_rate (bpm)
- hrv_rmssd_milli (ms)
- spo2_percentage (%)
- skin_temp_celsius (°C)
"""
cycle_id = raw_recovery.get("cycle_id")
sleep_id = raw_recovery.get("sleep_id")
created_at = raw_recovery.get("created_at")
score_state = raw_recovery.get("score_state")
# Extract score data (may be None if not scored yet)
score = raw_recovery.get("score", {}) or {}
# Only process scored records
if score_state != "SCORED":
return {}, None
# Parse timestamp
timestamp = None
if created_at:
try:
timestamp = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
except (ValueError, AttributeError):
timestamp = datetime.now(timezone.utc)
normalized = {
"user_id": user_id,
"provider": self.provider_name,
"timestamp": timestamp,
"cycle_id": cycle_id,
"sleep_id": sleep_id,
"recovery_score": score.get("recovery_score"),
"resting_heart_rate": score.get("resting_heart_rate"),
"hrv_rmssd_milli": score.get("hrv_rmssd_milli"),
"spo2_percentage": score.get("spo2_percentage"),
"skin_temp_celsius": score.get("skin_temp_celsius"),
"raw": raw_recovery,
}
return normalized, self._normalize_recovery_health_score(normalized, user_id)
def save_recovery_data(
self,
db: DbSession,
user_id: UUID,
normalized_recovery: dict[str, Any],
) -> int:
"""Save normalized recovery data to database as DataPointSeries.
Saves up to 5 metrics per recovery record:
- recovery_score
- resting_heart_rate
- heart_rate_variability_rmssd (from hrv_rmssd_milli)
- oxygen_saturation (from spo2_percentage)
- skin_temperature (from skin_temp_celsius)
Returns the number of samples saved.
"""
if not normalized_recovery:
return 0
timestamp = normalized_recovery.get("timestamp")
if not timestamp:
return 0
# Map WHOOP fields to SeriesType
metrics = [
("resting_heart_rate", SeriesType.resting_heart_rate),
("hrv_rmssd_milli", SeriesType.heart_rate_variability_rmssd),
("spo2_percentage", SeriesType.oxygen_saturation),
("skin_temp_celsius", SeriesType.skin_temperature),
]
samples_to_create: list[TimeSeriesSampleCreate] = []
for field_name, series_type in metrics:
value = normalized_recovery.get(field_name)
if value is not None:
try:
samples_to_create.append(
TimeSeriesSampleCreate(
id=uuid4(),
user_id=user_id,
source=self.provider_name,
recorded_at=timestamp,
value=Decimal(str(value)),
series_type=series_type,
)
)
except Exception as e:
log_structured(
self.logger,
"warning",
f"Failed to build recovery sample {field_name}: {e}",
provider="whoop",
task="save_recovery_data",
user_id=str(user_id),
)
if samples_to_create:
timeseries_service.bulk_create_samples(db, samples_to_create)
db.commit()
return len(samples_to_create)
def get_recovery_record(
self,
db: DbSession,
user_id: UUID,
cycle_id: str,
) -> dict[str, Any]:
"""Fetch a single recovery record by cycle_id from /v2/recovery/{cycle_id}."""
response = self._make_api_request(db, user_id, f"/v2/recovery/{cycle_id}")
store_raw_payload(
source="api_response",
provider="whoop",
payload=response,
user_id=str(user_id),
trace_id=f"/v2/recovery/{cycle_id}",
)
return response if isinstance(response, dict) else {}
def load_single_recovery(
self,
db: DbSession,
user_id: UUID,
cycle_id: str,
) -> int:
"""Fetch a single recovery record by cycle_id, normalize, and save to database."""
raw = self.get_recovery_record(db, user_id, cycle_id)
if not raw:
return 0
try:
normalized, health_score = self.normalize_recovery(raw, user_id)
if not normalized:
return 0
count = self.save_recovery_data(db, user_id, normalized)
if health_score:
health_score_service.create(db, health_score)
return count
except Exception as e:
log_structured(
self.logger,
"warning",
f"Failed to save recovery record {cycle_id}: {e}",
provider="whoop",
task="load_single_recovery",
)
return 0
def load_and_save_recovery(
self,
db: DbSession,
user_id: UUID,
start_time: datetime,
end_time: datetime,
) -> int:
"""Load recovery data from API and save to database.
Returns the total number of data point samples saved.
"""
raw_data = self.get_recovery_data(db, user_id, start_time, end_time)
total_count = 0
health_scores: list[HealthScoreCreate] = []
for item in raw_data:
try:
normalized, health_score = self.normalize_recovery(item, user_id)
if normalized: # Skip unscored records
total_count += self.save_recovery_data(db, user_id, normalized)
if health_score:
health_scores.append(health_score)
except Exception as e:
db.rollback()
log_structured(
self.logger,
"warning",
f"Failed to save recovery data: {e}",
provider="whoop",
task="load_and_save_recovery",
user_id=str(user_id),
)
if health_scores:
health_score_service.bulk_create(db, health_scores)
db.commit()
return total_count
# -------------------------------------------------------------------------
# Cycle Data - Whoop /v2/cycle
# -------------------------------------------------------------------------
def get_cycle_data(
self,
db: DbSession,
user_id: UUID,
start_time: datetime,
end_time: datetime,
) -> list[dict[str, Any]]:
"""Fetch cycle (daily strain) data from Whoop API via v2 endpoint with pagination.
Returns list of cycle records containing strain, kilojoule,
average_heart_rate, and max_heart_rate.
"""
return self._get_paginated_records(db, user_id, "/v2/cycle", start_time, end_time, "get_cycle_data")
def normalize_cycle(
self,
raw_cycle: dict[str, Any],
user_id: UUID,
) -> HealthScoreCreate | None:
"""Normalize a Whoop cycle record to a daily strain HealthScoreCreate.
Cycles without an end time are still in progress and their strain is
provisional; they are skipped so the unique-constraint dedupe does not
lock in a partial value.
"""
if raw_cycle.get("score_state") != "SCORED":
return None
if not raw_cycle.get("end"):
return None
score = raw_cycle.get("score") or {}
strain = score.get("strain")
start = raw_cycle.get("start")
if strain is None or not start:
return None
try:
recorded_at = datetime.fromisoformat(start.replace("Z", "+00:00"))
except (ValueError, AttributeError):
return None
components = {
k: ScoreComponent(value=v)
for k, v in {
"kilojoule": score.get("kilojoule"),
"average_heart_rate": score.get("average_heart_rate"),
"max_heart_rate": score.get("max_heart_rate"),
}.items()
if v is not None
}
return HealthScoreCreate(
id=uuid4(),
user_id=user_id,
provider=ProviderName.WHOOP,
category=HealthScoreCategory.STRAIN,
# Whoop also emits per-workout strain scores (workouts.py); the qualifier
# separates the day-level cycle strain from those.
qualifier="daily",
value=strain,
recorded_at=recorded_at,
zone_offset=raw_cycle.get("timezone_offset"),
components=components or None,
)
def load_and_save_cycles(
self,
db: DbSession,
user_id: UUID,
start_time: datetime,
end_time: datetime,
) -> int:
"""Load cycle data from API and save daily strain health scores.
Returns the number of cycle records normalized into health scores;
rows already present in the database are not re-inserted (dedupe via
the unique constraint) and are still counted here.
"""
raw_data = self.get_cycle_data(db, user_id, start_time, end_time)
health_scores: list[HealthScoreCreate] = []
for item in raw_data:
try:
health_score = self.normalize_cycle(item, user_id)
if health_score:
health_scores.append(health_score)
except Exception as e:
log_structured(
self.logger,
"warning",