Skip to content

Garmin Connect API reference

Garmin Connect linking and sync. See Integrations for how it behaves for users.

Routes

Garmin Connect routes: account linking, MFA, and activity, gear and health sync.

garminconnect_link(request, response, garmin_user, token_user_id, mfa_codes, link_states)

Start linking a Garmin Connect account and return at once.

The login runs in the background. Poll GET /jobs/{job_id}: when it reports mfa_required, submit the code to POST /garmin/mfa and keep polling until it reports succeeded or failed. A second request while one is running is answered 409 with a Content-Location naming that job.

Source code in backend/app/modules/garmin/router.py
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
@router.post(
    "/link",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=garmin_schema.GarminLinkStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def garminconnect_link(
    request: Request,
    response: Response,
    garmin_user: garmin_schema.GarminLogin,
    token_user_id: auth_dependencies.CurrentUserId,
    mfa_codes: garmin_dependencies.GarminMFACodeStoreDep,
    link_states: garmin_dependencies.GarminLinkStateStoreDep,
) -> garmin_schema.GarminLinkStatus:
    """Start linking a Garmin Connect account and return at once.

    The login runs in the background. Poll ``GET /jobs/{job_id}``: when it reports
    ``mfa_required``, submit the code to ``POST /garmin/mfa`` and keep polling until it
    reports ``succeeded`` or ``failed``. A second request while one is running is answered 409 with a
    ``Content-Location`` naming that job.
    """
    link_status = garmin_link_service.start_link(token_user_id, garmin_user, mfa_codes, link_states)
    core_location.set_job_location(response, request, link_status.id, garmin_constants.LINK_POLL_SECONDS)
    return link_status

garminconnect_mfa_code

garminconnect_mfa_code(request, mfa_request, token_user_id, mfa_codes, link_states)

Hand the MFA code to the Garmin Connect login waiting for it.

Source code in backend/app/modules/garmin/router.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@router.post(
    "/mfa",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def garminconnect_mfa_code(
    request: Request,
    mfa_request: garmin_schema.MFARequest,
    token_user_id: auth_dependencies.CurrentUserId,
    mfa_codes: garmin_dependencies.GarminMFACodeStoreDep,
    link_states: garmin_dependencies.GarminLinkStateStoreDep,
) -> None:
    """Hand the MFA code to the Garmin Connect login waiting for it."""
    garmin_link_service.submit_mfa_code(token_user_id, mfa_request.mfa_code, mfa_codes, link_states)

garminconnect_retrieve_activities_days

garminconnect_retrieve_activities_days(request, response, start_date, end_date, token_user_id, db, storage)

Queue a Garmin Connect sync of an explicit date range.

Returns 202 with a job handle; poll GET /jobs/{job_id} for the outcome. The range is fetched by a background job, never on this request or an API worker thread.

Source code in backend/app/modules/garmin/router.py
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
@router.post(
    "/activities",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=activity_ingestion_schema.ActivityIngestionJobRead,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["activities:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.PROVIDER_SYNC)
def garminconnect_retrieve_activities_days(
    request: Request,
    response: Response,
    start_date: date,
    end_date: date,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    storage: core_dependencies.Storage,
) -> activity_ingestion_schema.ActivityIngestionJobRead:
    """Queue a Garmin Connect sync of an explicit date range.

    Returns ``202`` with a job handle; poll ``GET /jobs/{job_id}``
    for the outcome. The range is fetched by a background job, never on this
    request or an API worker thread.
    """
    core_date_range.refuse_reversed_range(start_date, end_date)
    job = garmin_sync_service.request_activities_sync(token_user_id, start_date, end_date, storage, db)
    core_location.set_job_location(response, request, job.id, activity_ingestion_constants.job_poll_seconds(job.kind))
    return job

garminconnect_retrieve_gear

garminconnect_retrieve_gear(request, response, token_user_id, db, sync_states, rate_limits)

Queue a sync of the user's Garmin Connect gear; a background job runs it.

Poll GET /jobs/{job_id} for the outcome. A second request while one is pending is answered 409.

Source code in backend/app/modules/garmin/router.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@router.post(
    "/gear",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=garmin_schema.GarminSyncStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["gears:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.PROVIDER_SYNC)
def garminconnect_retrieve_gear(
    request: Request,
    response: Response,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    sync_states: garmin_dependencies.GarminSyncStateStoreDep,
    rate_limits: garmin_dependencies.GarminRateLimitStoreDep,
) -> garmin_schema.GarminSyncStatus:
    """Queue a sync of the user's Garmin Connect gear; a background job runs it.

    Poll ``GET /jobs/{job_id}`` for the outcome. A second request while one is
    pending is answered 409.
    """
    sync = garmin_sync_service.request_gear_sync(token_user_id, sync_states, rate_limits, db)
    core_location.set_job_location(response, request, sync.id, garmin_constants.SYNC_POLL_SECONDS)
    return sync

garminconnect_retrieve_health_days

garminconnect_retrieve_health_days(request, response, start_date, end_date, token_user_id, db, sync_states, rate_limits)

Queue a sync of the user's Garmin Connect health data for a date range.

The range must not exceed 31 days; a background job runs it. Poll GET /jobs/{job_id} for the outcome. A second request while one is pending is answered 409.

Source code in backend/app/modules/garmin/router.py
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
@router.post(
    "/health",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=garmin_schema.GarminSyncStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.PROVIDER_SYNC)
def garminconnect_retrieve_health_days(
    request: Request,
    response: Response,
    start_date: date,
    end_date: date,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    sync_states: garmin_dependencies.GarminSyncStateStoreDep,
    rate_limits: garmin_dependencies.GarminRateLimitStoreDep,
) -> garmin_schema.GarminSyncStatus:
    """Queue a sync of the user's Garmin Connect health data for a date range.

    The range must not exceed 31 days; a background job runs it. Poll
    ``GET /jobs/{job_id}`` for the outcome. A second request while one is pending is
    answered 409.
    """
    core_date_range.refuse_reversed_range(start_date, end_date)
    sync = garmin_sync_service.request_health_sync(token_user_id, start_date, end_date, sync_states, rate_limits, db)
    core_location.set_job_location(response, request, sync.id, garmin_constants.SYNC_POLL_SECONDS)
    return sync
garminconnect_unlink(request, body, token_user_id, verify_step_up, db)

Unlink the user's Garmin Connect account after the user's step-up verification.

It needs a signed-in session: an API key cannot step up.

Source code in backend/app/modules/garmin/router.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@router.post(
    "/unlink",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def garminconnect_unlink(
    request: Request,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    verify_step_up: auth_dependencies.StepUpVerifierDep,
    db: core_dependencies.DbSession,
) -> None:
    """Unlink the user's Garmin Connect account after the user's step-up verification.

    It needs a signed-in session: an API key cannot step up.
    """
    garmin_service.unlink_account(token_user_id, body.step_up, verify_step_up, db)

Account linking

Linking a Garmin Connect account: the background login, the MFA hand-off and the link job.

Owns the dedicated login threads. Unlinking and the sessions a linked account's syncs use live in :mod:modules.garmin.service.

link_garminconnect(user_id, job_id, email, password, mfa_codes, link_states, is_cn=False)

Log in to Garmin Connect, store the token and record the outcome in the link state.

Blocking; call it through :func:start_link. It never raises: every outcome, including a failure, ends as the recorded state.

Parameters:

Name Type Description Default
user_id UUID

The user linking Garmin Connect.

required
job_id UUID

The link job this run records its state against.

required
email str

Garmin Connect username.

required
password str

Garmin Connect password.

required
mfa_codes GarminMFACodeStore

Shared store the submitted MFA code lands in.

required
link_states GarminLinkStateStore

Shared store of the link attempt's state.

required
is_cn bool

Whether to authenticate against Garmin's China region.

False
Source code in backend/app/modules/garmin/link_service.py
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
def link_garminconnect(
    user_id: uuid.UUID,
    job_id: uuid.UUID,
    email: str,
    password: str,
    mfa_codes: garmin_mfa_code_store.GarminMFACodeStore,
    link_states: garmin_link_state_store.GarminLinkStateStore,
    is_cn: bool = False,
) -> None:
    """Log in to Garmin Connect, store the token and record the outcome in the link state.

    Blocking; call it through :func:`start_link`. It never raises: every outcome, including a
    failure, ends as the recorded state.

    Args:
        user_id: The user linking Garmin Connect.
        job_id: The link job this run records its state against.
        email: Garmin Connect username.
        password: Garmin Connect password.
        mfa_codes: Shared store the submitted MFA code lands in.
        link_states: Shared store of the link attempt's state.
        is_cn: Whether to authenticate against Garmin's China region.
    """
    # A code left by an earlier attempt must not answer this one's prompt.
    mfa_codes.delete_code(user_id)
    mfa_prompted = False
    mfa_timed_out = False

    def prompt_mfa() -> str:
        """Mark the login as prompted and wait for the user's MFA code.

        Returns:
            The submitted code.

        Raises:
            _MfaCodeTimeoutError: When none arrived in time; the library's login may rewrap it, so the
                timeout is also flagged for :func:`link_garminconnect`.
        """
        nonlocal mfa_prompted, mfa_timed_out
        mfa_prompted = True
        try:
            return wait_for_mfa_code(user_id, job_id, mfa_codes, link_states)
        except _MfaCodeTimeoutError:
            mfa_timed_out = True
            raise

    try:
        garmin = garminconnect.Garmin(email=email, password=password, is_cn=is_cn, prompt_mfa=prompt_mfa)
        garmin.login()

        if not garmin.client.di_token:
            raise garminconnect.GarminConnectAuthenticationError("Garmin Connect returned no token")

        with core_database.SessionLocal() as db:
            user_integrations_integration.link_garminconnect_account(
                user_id,
                garmin_token_utils.serialize_garmin_token(garmin.client, is_cn),
                db,
            )
            jasil_audit.stage(
                db,
                garmin_audit_actions.ACCOUNT_LINK,
                target_type="user",
                target_id=str(user_id),
                target_owner_id=str(user_id),
            )
            db.commit()
    except garminconnect.GarminConnectAuthenticationError:
        # The library raises this for a refused password and for a refused MFA code alike.
        reason = (
            garmin_constants.LinkFailure.INCORRECT_MFA
            if mfa_prompted
            else garmin_constants.LinkFailure.INVALID_CREDENTIALS
        )
        logger.warning(
            "Garmin Connect refused the link attempt",
            extra=core_logger.context(user_id=user_id, reason=reason),
        )
        link_states.set_status(user_id, job_id, core_job_status.JobState.FAILED, reason)
        _record_refused_link(user_id, garmin_audit_actions.LinkFailureReason(reason))
    except garminconnect.GarminConnectTooManyRequestsError:
        logger.warning(
            "Garmin Connect refused the link attempt: too many requests",
            extra=core_logger.context(user_id=user_id),
        )
        link_states.set_status(
            user_id, job_id, core_job_status.JobState.FAILED, garmin_constants.LinkFailure.TOO_MANY_REQUESTS
        )
        _record_refused_link(user_id, garmin_audit_actions.LinkFailureReason.TOO_MANY_REQUESTS)
    except Exception as err:
        if mfa_timed_out:
            # The library rewraps the timeout, so it is told apart by the flag. Recorded as an incorrect
            # code, the reason that covers a code that did not arrive in time.
            logger.warning(
                "Garmin Connect link abandoned: no MFA code arrived in time",
                exc_info=err,
                extra=core_logger.context(user_id=user_id),
            )
            link_states.set_status(
                user_id, job_id, core_job_status.JobState.FAILED, garmin_constants.LinkFailure.INCORRECT_MFA
            )
            _record_refused_link(user_id, garmin_audit_actions.LinkFailureReason.INCORRECT_MFA)
        else:
            logger.error(
                "Internal error while linking Garmin Connect",
                exc_info=err,
                extra=core_logger.context(user_id=user_id),
            )
            link_states.set_status(
                user_id, job_id, core_job_status.JobState.FAILED, garmin_constants.LinkFailure.INTERNAL
            )
    else:
        link_states.set_status(user_id, job_id, core_job_status.JobState.SUCCEEDED)
    finally:
        mfa_codes.delete_code(user_id)
shutdown_link_pool(*, wait=False)

Stop accepting link attempts and release the login threads.

Parameters:

Name Type Description Default
wait bool

Whether to wait for logins still running.

False
Source code in backend/app/modules/garmin/link_service.py
38
39
40
41
42
43
44
def shutdown_link_pool(*, wait: bool = False) -> None:
    """Stop accepting link attempts and release the login threads.

    Args:
        wait: Whether to wait for logins still running.
    """
    _link_pool.shutdown(wait=wait)
start_link(user_id, login, mfa_codes, link_states)

Start linking a Garmin Connect account on a dedicated worker thread and return at once.

The outcome is recorded in the shared link state. The credentials stay in this process's memory and are never stored, which is why this is not a durable job.

Parameters:

Name Type Description Default
user_id UUID

The user linking Garmin Connect.

required
login GarminLogin

The Garmin Connect credentials.

required
mfa_codes GarminMFACodeStore

Shared store the submitted MFA code lands in.

required
link_states GarminLinkStateStore

Shared store of the link attempt's state.

required

Returns:

Type Description
GarminLinkStatus

The attempt's initial status.

Raises:

Type Description
ConflictError

When an attempt for this user is already running.

PoolFullError

When every login thread of this process is busy.

Source code in backend/app/modules/garmin/link_service.py
 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
def start_link(
    user_id: uuid.UUID,
    login: garmin_schema.GarminLogin,
    mfa_codes: garmin_mfa_code_store.GarminMFACodeStore,
    link_states: garmin_link_state_store.GarminLinkStateStore,
) -> garmin_schema.GarminLinkStatus:
    """Start linking a Garmin Connect account on a dedicated worker thread and return at once.

    The outcome is recorded in the shared link state. The credentials stay in this
    process's memory and are never stored, which is why this is not a durable job.

    Args:
        user_id: The user linking Garmin Connect.
        login: The Garmin Connect credentials.
        mfa_codes: Shared store the submitted MFA code lands in.
        link_states: Shared store of the link attempt's state.

    Returns:
        The attempt's initial status.

    Raises:
        ConflictError: When an attempt for this user is already running.
        PoolFullError: When every login thread of this process is busy.
    """
    # Checked before the attempt is recorded, so a refused login leaves no pending state to poll.
    _link_pool.require_capacity()
    job = core_sync_runner.start_claimed(
        lambda: link_states.begin(user_id, conflict="A Garmin Connect link is already in progress"),
        lambda job: _link_pool.submit(
            link_garminconnect,
            user_id,
            job.id,
            login.username,
            login.password.get_secret_value(),
            mfa_codes,
            link_states,
            login.is_cn,
        ),
        lambda job: link_states.release(user_id),
    )
    return garmin_schema.GarminLinkStatus.model_validate({**job.envelope(), "status": core_job_status.JobState.RUNNING})
submit_mfa_code(user_id, mfa_code, mfa_codes, link_states)

Hand the user's MFA code to the login waiting for it.

Parameters:

Name Type Description Default
user_id UUID

The user linking Garmin Connect.

required
mfa_code str

The code the user entered.

required
mfa_codes GarminMFACodeStore

Shared store the code lands in.

required
link_states GarminLinkStateStore

Shared store of the link attempt's state.

required

Raises:

Type Description
ConflictError

When no login is waiting for a code.

Source code in backend/app/modules/garmin/link_service.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def submit_mfa_code(
    user_id: uuid.UUID,
    mfa_code: str,
    mfa_codes: garmin_mfa_code_store.GarminMFACodeStore,
    link_states: garmin_link_state_store.GarminLinkStateStore,
) -> None:
    """Hand the user's MFA code to the login waiting for it.

    Args:
        user_id: The user linking Garmin Connect.
        mfa_code: The code the user entered.
        mfa_codes: Shared store the code lands in.
        link_states: Shared store of the link attempt's state.

    Raises:
        ConflictError: When no login is waiting for a code.
    """
    state = link_states.get(user_id)
    if state is None or not state.mfa_required:
        raise core_exceptions.ConflictError("No Garmin Connect login is waiting for an MFA code")
    mfa_codes.add_code(user_id, mfa_code)
wait_for_mfa_code(user_id, job_id, mfa_codes, link_states)

Ask for an MFA code through the shared link state and wait for the user to submit it.

The prompt is the mfa_required state the browser polls, so it reaches the user on whichever replica answers the poll. The code arrives through the shared code store the same way.

Parameters:

Name Type Description Default
user_id UUID

The user linking Garmin Connect.

required
job_id UUID

The link job waiting for the code.

required
mfa_codes GarminMFACodeStore

Shared store the submitted code lands in.

required
link_states GarminLinkStateStore

Shared store of the link attempt's state.

required

Returns:

Type Description
str

The submitted code.

Raises:

Type Description
_MfaCodeTimeoutError

When no code arrived within MFA_WAIT_SECONDS.

Source code in backend/app/modules/garmin/link_service.py
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
def wait_for_mfa_code(
    user_id: uuid.UUID,
    job_id: uuid.UUID,
    mfa_codes: garmin_mfa_code_store.GarminMFACodeStore,
    link_states: garmin_link_state_store.GarminLinkStateStore,
) -> str:
    """Ask for an MFA code through the shared link state and wait for the user to submit it.

    The prompt is the ``mfa_required`` state the browser polls, so it reaches the user on
    whichever replica answers the poll. The code arrives through the shared code store the
    same way.

    Args:
        user_id: The user linking Garmin Connect.
        job_id: The link job waiting for the code.
        mfa_codes: Shared store the submitted code lands in.
        link_states: Shared store of the link attempt's state.

    Returns:
        The submitted code.

    Raises:
        _MfaCodeTimeoutError: When no code arrived within ``MFA_WAIT_SECONDS``.
    """
    link_states.set_status(user_id, job_id, core_job_status.JobState.RUNNING, mfa_required=True)
    job = link_states.current_job(user_id)
    if job is not None:
        websocket_integration.push_job_changed(user_id, job.id, job.kind)
    for _ in range(garmin_constants.MFA_WAIT_SECONDS):
        code = mfa_codes.get_code(user_id)
        if code is not None:
            link_states.set_status(user_id, job_id, core_job_status.JobState.RUNNING)
            return code
        time.sleep(1)
    raise _MfaCodeTimeoutError

Sync requests

Queue Garmin Connect activity, gear and health syncs so they never run on an API thread.

On the durable profile (JOBS_ENABLED) the request stages a garmin.sync_requested event and a worker runs it, surviving a restart. Otherwise the same body runs on a small in-process pool that is not the request threadpool. Either way a gear or health sync is recorded in the shared sync state, which the client polls and which stops a user queueing the same sync twice.

close_dead_lettered_sync

close_dead_lettered_sync(payload, states)

Close a sync the runner gave up on, so the user can queue another.

Runs however the last attempt ended, including a lease that expired or a worker that died, where :func:run_sync never got to record it. A sync that already finished, or whose state has expired, is left as it is, and so is a newer sync that took its claim.

Parameters:

Name Type Description Default
payload SyncRequestedPayload

What was to be synced.

required
states GarminSyncStateStore

Shared store of the sync's state.

required
Source code in backend/app/modules/garmin/sync_service.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def close_dead_lettered_sync(
    payload: garmin_events.SyncRequestedPayload, states: garmin_sync_state_store.GarminSyncStateStore
) -> None:
    """Close a sync the runner gave up on, so the user can queue another.

    Runs however the last attempt ended, including a lease that expired or a worker that died, where
    :func:`run_sync` never got to record it. A sync that already finished, or whose state has expired,
    is left as it is, and so is a newer sync that took its claim.

    Args:
        payload: What was to be synced.
        states: Shared store of the sync's state.
    """
    core_sync_runner.close_dead_lettered(states, payload.user_id, payload.kind, payload.job_id, "Garmin Connect")

request_activities_sync

request_activities_sync(user_id, start_date, end_date, storage, db)

Queue a Garmin Connect sync of an explicit date range.

The range is fetched by a background job, never on the request or an API worker thread. It is capped, so a first sync that reaches back years is made in several requests.

Parameters:

Name Type Description Default
user_id UUID

The user to sync.

required
start_date date

First day of the range.

required
end_date date

Last day of the range.

required
storage StorageProvider

The platform storage provider.

required
db Session

Database session.

required

Returns:

Type Description
ActivityIngestionJobRead

The queued job's handle.

Raises:

Type Description
InvalidInputError

When end_date is in the future or the range is longer than MAX_ACTIVITIES_RANGE_DAYS.

Source code in backend/app/modules/garmin/sync_service.py
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
def request_activities_sync(
    user_id: uuid.UUID,
    start_date: date,
    end_date: date,
    storage: platform_providers.StorageProvider,
    db: Session,
) -> activity_ingestion_schema.ActivityIngestionJobRead:
    """Queue a Garmin Connect sync of an explicit date range.

    The range is fetched by a background job, never on the request or an API worker thread. It is
    capped, so a first sync that reaches back years is made in several requests.

    Args:
        user_id: The user to sync.
        start_date: First day of the range.
        end_date: Last day of the range.
        storage: The platform storage provider.
        db: Database session.

    Returns:
        The queued job's handle.

    Raises:
        InvalidInputError: When ``end_date`` is in the future or the
            range is longer than ``MAX_ACTIVITIES_RANGE_DAYS``.
    """
    return activity_ingestion_integration.request_range_sync(
        garmin_constants.PROVIDER_NAME, user_id, start_date, end_date, storage, db
    )

request_gear_sync

request_gear_sync(user_id, states, rate_limits, db)

Queue a sync of the user's Garmin Connect gear.

Parameters:

Name Type Description Default
user_id UUID

The user to sync.

required
states GarminSyncStateStore

Shared store of the sync's state.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required
db Session

Database session.

required

Returns:

Type Description
GarminSyncStatus

The sync's initial status.

Source code in backend/app/modules/garmin/sync_service.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def request_gear_sync(
    user_id: uuid.UUID,
    states: garmin_sync_state_store.GarminSyncStateStore,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
    db: Session,
) -> garmin_schema.GarminSyncStatus:
    """Queue a sync of the user's Garmin Connect gear.

    Args:
        user_id: The user to sync.
        states: Shared store of the sync's state.
        rate_limits: The shared Garmin Connect rate-limit state.
        db: Database session.

    Returns:
        The sync's initial status.
    """
    return _queue(user_id, garmin_constants.SyncKind.GEAR, None, None, states, rate_limits, db)

request_health_sync

request_health_sync(user_id, start_date, end_date, states, rate_limits, db)

Queue a sync of the user's Garmin Connect health data for a range of days.

Parameters:

Name Type Description Default
user_id UUID

The user to sync.

required
start_date date

First day of the range.

required
end_date date

Last day of the range.

required
states GarminSyncStateStore

Shared store of the sync's state.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required
db Session

Database session.

required

Returns:

Type Description
GarminSyncStatus

The sync's initial status.

Raises:

Type Description
InvalidInputError

When end_date is in the future or the range is longer than MAX_HEALTH_RANGE_DAYS.

Source code in backend/app/modules/garmin/sync_service.py
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
def request_health_sync(
    user_id: uuid.UUID,
    start_date: date,
    end_date: date,
    states: garmin_sync_state_store.GarminSyncStateStore,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
    db: Session,
) -> garmin_schema.GarminSyncStatus:
    """Queue a sync of the user's Garmin Connect health data for a range of days.

    Args:
        user_id: The user to sync.
        start_date: First day of the range.
        end_date: Last day of the range.
        states: Shared store of the sync's state.
        rate_limits: The shared Garmin Connect rate-limit state.
        db: Database session.

    Returns:
        The sync's initial status.

    Raises:
        InvalidInputError: When ``end_date`` is in the future or the
            range is longer than ``MAX_HEALTH_RANGE_DAYS``.
    """
    core_sync_runner.validate_range(
        start_date,
        end_date,
        garmin_constants.MAX_HEALTH_RANGE_DAYS,
        users_integration.local_today(user_id, db),
    )
    return _queue(user_id, garmin_constants.SyncKind.HEALTH, start_date, end_date, states, rate_limits, db)

run_sync

run_sync(payload, states, rate_limits, *, will_retry=False)

Run one queued sync and record its outcome. Blocking; call it from a worker, never a request.

A sync that could not run because the account is not linked, Garmin Connect rejected its token or Garmin Connect is rate limiting the account is recorded as failed and not raised: a retry would meet the same answer.

A sync that raised and will be retried by a durable worker stays QUEUED with its claim held: releasing the claim would let a second sync start beside the retry. A sync nothing will retry, because there is no worker or this was the last attempt, is FAILED and its claim is released.

Parameters:

Name Type Description Default
payload SyncRequestedPayload

What to sync.

required
states GarminSyncStateStore

Shared store of the sync's state.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required
will_retry bool

Whether a durable worker runs this again if it raises.

False

Raises:

Type Description
Exception

Whatever the sync raised, after recording its state, so a durable worker retries it.

Source code in backend/app/modules/garmin/sync_service.py
 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
def run_sync(
    payload: garmin_events.SyncRequestedPayload,
    states: garmin_sync_state_store.GarminSyncStateStore,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
    *,
    will_retry: bool = False,
) -> None:
    """Run one queued sync and record its outcome. Blocking; call it from a worker, never a request.

    A sync that could not run because the account is not linked, Garmin Connect rejected its
    token or Garmin Connect is rate limiting the account is recorded as failed and not raised: a
    retry would meet the same answer.

    A sync that raised and will be retried by a durable worker stays ``QUEUED`` with its claim held:
    releasing the claim would let a second sync start beside the retry. A sync nothing will retry,
    because there is no worker or this was the last attempt, is ``FAILED`` and its claim is released.

    Args:
        payload: What to sync.
        states: Shared store of the sync's state.
        rate_limits: The shared Garmin Connect rate-limit state.
        will_retry: Whether a durable worker runs this again if it raises.

    Raises:
        Exception: Whatever the sync raised, after recording its state, so a durable worker retries it.
    """

    def work() -> bool:
        """Run the gear or health sync the payload asks for.

        Returns:
            Whether the sync did anything.
        """
        if payload.kind == garmin_constants.SyncKind.GEAR:
            return garmin_gear_service.get_user_gear(payload.user_id, rate_limits)
        if payload.start_date is not None and payload.end_date is not None:
            return garmin_health_service.sync_health_for_dates(
                payload.start_date, payload.end_date, payload.user_id, rate_limits
            )
        return False

    def record_refusal(err: Exception) -> None:
        """Record a Garmin Connect rate limit for every process.

        Args:
            err: The error that made Garmin Connect or the rate-limit state refuse the sync.
        """
        if isinstance(err, garminconnect.GarminConnectTooManyRequestsError):
            # Recorded for every process, so the next sync waits out the cooldown instead of meeting the limit again.
            garmin_service.rate_limit_error(err, payload.user_id, rate_limits)

    synced = core_sync_runner.run_recorded(
        states,
        payload.user_id,
        payload.kind,
        payload.job_id,
        work,
        will_retry=will_retry,
        refusals=(garminconnect.GarminConnectTooManyRequestsError, core_exceptions.TooManyRequestsError),
        on_refused=record_refusal,
    )
    if synced:
        # Best effort: the synced rows are already committed, so a lost hint only delays the refresh.
        websocket_integration.push_to_user(
            payload.user_id,
            {
                "message": websocket_constants.GEARS_CHANGED_MESSAGE
                if payload.kind == garmin_constants.SyncKind.GEAR
                else websocket_constants.HEALTH_CHANGED_MESSAGE
            },
        )

shutdown_sync_pool

shutdown_sync_pool(*, wait=False)

Stop accepting syncs and release the pool threads.

Parameters:

Name Type Description Default
wait bool

Whether to wait for syncs still running.

False
Source code in backend/app/modules/garmin/sync_service.py
44
45
46
47
48
49
50
def shutdown_sync_pool(*, wait: bool = False) -> None:
    """Stop accepting syncs and release the pool threads.

    Args:
        wait: Whether to wait for syncs still running.
    """
    _sync_pool.shutdown(wait=wait)

sync_recent_health

sync_recent_health(states, rate_limits)

Sync the last day of Garmin Connect health stats for every linked user.

Each user's sync is queued, for a worker with durable jobs or for the in-process pool without them, so users are isolated and never run on this thread. Linked users are read a page at a time in short sessions, and one user failing does not stop the rest. Without durable jobs a full pool is waited on; if it stays full the pass stops, and the next run starts over.

Parameters:

Name Type Description Default
states GarminSyncStateStore

Shared store of the syncs' state.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required
Source code in backend/app/modules/garmin/sync_service.py
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
def sync_recent_health(
    states: garmin_sync_state_store.GarminSyncStateStore,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
) -> None:
    """Sync the last day of Garmin Connect health stats for every linked user.

    Each user's sync is queued, for a worker with durable jobs or for the in-process pool without
    them, so users are isolated and never run on this thread. Linked users are read a page at a
    time in short sessions, and one user failing does not stop the rest. Without durable jobs a
    full pool is waited on; if it stays full the pass stops, and the next run starts over.

    Args:
        states: Shared store of the syncs' state.
        rate_limits: The shared Garmin Connect rate-limit state.
    """
    after_id: uuid.UUID | None = None
    while True:
        user_ids = garmin_service.linked_user_ids(after_id, _USERS_PAGE_SIZE)
        if not user_ids:
            return
        for user_id in user_ids:
            try:
                _sync_recent_health_for_user(user_id, states, rate_limits)
            except core_local_pool.PoolFullError:
                logger.warning(
                    "Garmin Connect health pull stopped: the in-process pool stayed full",
                    extra=core_logger.context(user_id=user_id),
                )
                return
            except Exception as err:
                logger.error(
                    "Error syncing recent Garmin Connect health data for user",
                    exc_info=err,
                    extra=core_logger.context(user_id=user_id),
                )
        after_id = user_ids[-1]

Activity sync

Garmin Connect activity sync: fetch the window, download each file and hand it to ingestion.

fetch_and_process_activities_by_dates

fetch_and_process_activities_by_dates(session, start_date, end_date, user_id, rate_limits)

Fetch a user's Garmin Connect activities in a window and store the new ones.

Runs on a worker thread. Garmin round trips run with no session open; the duplicate check and the store each open a short one. An activity failing does not stop the rest of the window, but the first failure is raised once the window is done, so the refresh job fails and is retried, as for any provider. A file ingestion refuses is logged by ingestion and skipped, and does not fail the window.

Parameters:

Name Type Description Default
session GarminSession

The user's authenticated Garmin Connect session.

required
start_date datetime

Start of the window.

required
end_date datetime

End of the window.

required
user_id UUID

The user the activities belong to.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Returns:

Type Description
list[ActivityRead] | None

The stored activities, or None when there were none.

Raises:

Type Description
TooManyRequestsError

When Garmin Connect rate limits the window; the refresh is deferred.

Exception

The first failure of the window fetch or of an activity.

Source code in backend/app/modules/garmin/activity_service.py
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
def fetch_and_process_activities_by_dates(
    session: garmin_service.GarminSession,
    start_date: datetime,
    end_date: datetime,
    user_id: uuid.UUID,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
) -> list[activity_schema.ActivityRead] | None:
    """Fetch a user's Garmin Connect activities in a window and store the new ones.

    Runs on a worker thread. Garmin round trips run with no session open; the
    duplicate check and the store each open a short one. An activity failing does
    not stop the rest of the window, but the first failure is raised once the
    window is done, so the refresh job fails and is retried, as for any provider. A file ingestion
    refuses is logged by ingestion and skipped, and does not fail the window.

    Args:
        session: The user's authenticated Garmin Connect session.
        start_date: Start of the window.
        end_date: End of the window.
        user_id: The user the activities belong to.
        rate_limits: The shared Garmin Connect rate-limit state.

    Returns:
        The stored activities, or ``None`` when there were none.

    Raises:
        TooManyRequestsError: When Garmin Connect rate limits the window; the refresh is deferred.
        Exception: The first failure of the window fetch or of an activity.
    """
    try:
        garmin_activities = session.client.get_activities_by_date(
            str(start_date.date()),
            str(end_date.date()),
        )
    except garminconnect.GarminConnectAuthenticationError as err:
        garmin_service.handle_rejected_token(user_id, session, err)
        return None
    except garminconnect.GarminConnectTooManyRequestsError as err:
        raise garmin_service.rate_limit_error(err, user_id, rate_limits) from err

    if garmin_activities is None:
        logger.debug(
            "No new Garmin Connect activities found",
            extra=core_logger.context(user_id=user_id, start_date=start_date.date(), end_date=end_date.date()),
        )
        return None

    stored = activity_ingestion_integration.run_provider_window(
        garmin_activities,
        lambda activity: _process_listed_activity(session, activity, user_id, rate_limits),
        provider=garmin_constants.PROVIDER_NAME,
        user_id=user_id,
        describe=lambda activity: {"activity_id": activity["activityId"]},
        propagate=(core_exceptions.TooManyRequestsError,),
    )
    parsed_activities = [parsed for activity_result in stored for parsed in activity_result]
    return parsed_activities if parsed_activities else None

get_user_garminconnect_activities_by_dates

get_user_garminconnect_activities_by_dates(user_id, start_date, end_date, rate_limits)

Fetch and store one user's Garmin Connect activities recorded in a window.

Parameters:

Name Type Description Default
user_id UUID

The user to sync.

required
start_date datetime

Start of the window.

required
end_date datetime

End of the window.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Returns:

Type Description
list[ActivityRead] | None

The stored activities, or None when Garmin Connect is not linked or

list[ActivityRead] | None

nothing new came back.

Raises:

Type Description
TooManyRequestsError

When Garmin Connect rate limits the account.

Exception

Whatever the sync raised, so the refresh job fails and is retried.

Source code in backend/app/modules/garmin/activity_service.py
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
def get_user_garminconnect_activities_by_dates(
    user_id: uuid.UUID,
    start_date: datetime,
    end_date: datetime,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
) -> list[activity_schema.ActivityRead] | None:
    """Fetch and store one user's Garmin Connect activities recorded in a window.

    Args:
        user_id: The user to sync.
        start_date: Start of the window.
        end_date: End of the window.
        rate_limits: The shared Garmin Connect rate-limit state.

    Returns:
        The stored activities, or ``None`` when Garmin Connect is not linked or
        nothing new came back.

    Raises:
        TooManyRequestsError: When Garmin Connect rate limits the account.
        Exception: Whatever the sync raised, so the refresh job fails and is retried.
    """
    with garmin_service.linked_session(user_id, rate_limits) as session:
        if session is None:
            return None

        logger.info(
            "Started Garmin Connect activities processing for date range to",
            extra=core_logger.context(user_id=user_id, start_date=start_date.date(), end_date=end_date.date()),
        )
        processed = fetch_and_process_activities_by_dates(session, start_date, end_date, user_id, rate_limits)
        logger.info(
            "Garmin Connect activities processed",
            extra=core_logger.context(user_id=user_id, count=len(processed) if processed else 0),
        )
        return processed

Gear sync

Garmin Connect gear sync: store the user's gear and assign it to their activities.

fetch_and_process_gear

fetch_and_process_gear(garminconnect_client, user_id)

Fetch the user's Garmin Connect gear and store the pieces not stored yet.

Garmin is called with no session open; the gear is stored in one short one.

Parameters:

Name Type Description Default
garminconnect_client Garmin

A client authenticated as the user.

required
user_id UUID

The gear's owner.

required

Returns:

Type Description
int

The number of gear pieces that were not stored yet.

Source code in backend/app/modules/garmin/gear_service.py
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
def fetch_and_process_gear(garminconnect_client: garminconnect.Garmin, user_id: uuid.UUID) -> int:
    """Fetch the user's Garmin Connect gear and store the pieces not stored yet.

    Garmin is called with no session open; the gear is stored in one short one.

    Args:
        garminconnect_client: A client authenticated as the user.
        user_id: The gear's owner.

    Returns:
        The number of gear pieces that were not stored yet.
    """
    last_used_device = garminconnect_client.get_device_last_used()
    gears = gear_list(garminconnect_client.get_gear(last_used_device["userProfileNumber"]))

    with core_database.SessionLocal() as db:
        new_gears = [new_gear for gear in gears if (new_gear := process_gear(gear, user_id, db)) is not None]
        gears_integration.create_multiple_gears(new_gears, user_id, db)
        db.commit()

    logger.info(
        "Garmin Connect gear processed",
        extra=core_logger.context(user_id=user_id, count=len(new_gears)),
    )
    return len(new_gears)

gear_list

gear_list(answer)

Return the gear Garmin Connect answered with.

garminconnect types its gear answers as a JSON object, but Garmin answers with a list of gear pieces.

Parameters:

Name Type Description Default
answer object

What garminconnect returned for a gear request.

required

Returns:

Type Description
list[dict[str, Any]]

The gear pieces.

Raises:

Type Description
DependencyFailedError

When Garmin Connect answered with something other than a list.

Source code in backend/app/modules/garmin/gear_service.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def gear_list(answer: object) -> list[dict[str, Any]]:
    """Return the gear Garmin Connect answered with.

    garminconnect types its gear answers as a JSON object, but Garmin answers with a list of gear pieces.

    Args:
        answer: What garminconnect returned for a gear request.

    Returns:
        The gear pieces.

    Raises:
        DependencyFailedError: When Garmin Connect answered with something other than a list.
    """
    if not isinstance(answer, list):
        raise core_exceptions.DependencyFailedError("Garmin Connect answered a gear request in an unexpected shape")
    return answer

get_user_gear

get_user_gear(user_id, rate_limits)

Fetch a user's Garmin Connect gear, store it and assign it to their activities.

An expired token unlinks the account and notifies the user. Gear sync is switched on only once the gear was fetched.

Parameters:

Name Type Description Default
user_id UUID

The user to sync.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Returns:

Type Description
bool

True when the gear was synced, False when the account is not linked, was unlinked, or

bool

Garmin Connect rejected its token.

Source code in backend/app/modules/garmin/gear_service.py
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
def get_user_gear(user_id: uuid.UUID, rate_limits: garmin_rate_limit_store.GarminRateLimitStore) -> bool:
    """Fetch a user's Garmin Connect gear, store it and assign it to their activities.

    An expired token unlinks the account and notifies the user. Gear sync is switched on only
    once the gear was fetched.

    Args:
        user_id: The user to sync.
        rate_limits: The shared Garmin Connect rate-limit state.

    Returns:
        True when the gear was synced, False when the account is not linked, was unlinked, or
        Garmin Connect rejected its token.
    """
    logger.info(
        "Started Garmin Connect gear processing",
        extra=core_logger.context(user_id=user_id),
    )

    with garmin_service.linked_session(user_id, rate_limits) as session:
        if session is None:
            return False
        try:
            fetch_and_process_gear(session.client, user_id)
        except garminconnect.GarminConnectAuthenticationError as err:
            garmin_service.handle_rejected_token(user_id, session, err)
            return False

    with core_database.SessionLocal() as db:
        # The account may have been unlinked while the gear was being fetched
        if garmin_service.get_linked_user_integrations(user_id, db) is None:
            logger.info("Garmin Connect unlinked during the gear sync", extra=core_logger.context(user_id=user_id))
            return False
        user_integrations_integration.set_garminconnect_sync_gear(user_id, True, db)
        db.commit()
        logger.info(
            "Will parse current activities and set gear if applicable",
            extra=core_logger.context(user_id=user_id),
        )
        num_gear_activities_set = set_activities_gear(user_id, db)

    logger.info(
        "Activities where gear was set",
        extra=core_logger.context(user_id=user_id, count=num_gear_activities_set),
    )
    return True

match_gear_for_activity

match_gear_for_activity(activity, gears)

Return the local gear ID matching this activity's Garmin gear, else None.

Source code in backend/app/modules/garmin/gear_service.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def match_gear_for_activity(
    activity: activity_contracts.ActivityGarminGearRef,
    gears: list[gears_schema.GearRead],
) -> uuid.UUID | None:
    """Return the local gear ID matching this activity's Garmin gear, else None."""
    if activity.garminconnect_gear_id is None:
        return None
    for gear in gears:
        if activity.garminconnect_gear_id == gear.garminconnect_gear_id:
            logger.debug(
                "Gear found",
                extra=core_logger.context(gear_nickname=gear.nickname),
            )
            return gear.id
    return None

process_gear

process_gear(gear, user_id, db)

Build the local gear for a Garmin Connect gear piece.

Parameters:

Name Type Description Default
gear dict[str, Any]

The Garmin Connect gear payload.

required
user_id UUID

The gear's owner.

required
db Session

Database session.

required

Returns:

Type Description
GearCreate | None

The gear to create, or None when it is already stored.

Source code in backend/app/modules/garmin/gear_service.py
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
def process_gear(gear: dict[str, Any], user_id: uuid.UUID, db: Session) -> gears_schema.GearCreate | None:
    """Build the local gear for a Garmin Connect gear piece.

    Args:
        gear: The Garmin Connect gear payload.
        user_id: The gear's owner.
        db: Database session.

    Returns:
        The gear to create, or ``None`` when it is already stored.
    """
    # Get the gear by garminconnect uuid from user id
    gear_db = gears_integration.get_gear_by_garminconnect_id(gear["uuid"], user_id, db)

    # Skip existing gear
    if gear_db:
        return None

    new_gear = gears_schema.GearCreate(
        brand=gear["gearMakeName"] if gear["gearMakeName"] else None,
        model=gear["gearModelName"] if gear["gearModelName"] else None,
        nickname=(gear["displayName"] if gear["displayName"] else gear["customMakeModel"]),
        gear_type=(gears_schema.GearType.BIKE if gear["gearTypeName"] == "Bike" else gears_schema.GearType.SHOES),
        user_id=user_id,
        active=gear["gearStatusName"] == "active",
        garminconnect_gear_id=gear["uuid"],
    )

    return new_gear

resolve_synced_gear_id

resolve_synced_gear_id(user_id, garminconnect_gear, db)

Resolve a downloaded activity's Garmin gear to a local gear ID.

Resolved here, before the file reaches ingestion, so the ingestion seam never has to ask a provider module whether gear sync is on or which local gear a Garmin UUID maps to.

Parameters:

Name Type Description Default
user_id UUID

Owner user ID.

required
garminconnect_gear list[dict[str, Any]] | None

Garmin gear metadata ([{"uuid": ...}, ...]) from the activity download, when the activity has any.

required
db Session

Database session.

required

Returns:

Type Description
UUID | None

The local gear ID, or None when gear sync is off, the account's token is

UUID | None

invalid, the activity has no gear, or no local gear matches.

Source code in backend/app/modules/garmin/gear_service.py
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
def resolve_synced_gear_id(
    user_id: uuid.UUID, garminconnect_gear: list[dict[str, Any]] | None, db: Session
) -> uuid.UUID | None:
    """Resolve a downloaded activity's Garmin gear to a local gear ID.

    Resolved here, before the file reaches ingestion, so the ingestion seam never
    has to ask a provider module whether gear sync is on or which local gear a
    Garmin UUID maps to.

    Args:
        user_id: Owner user ID.
        garminconnect_gear: Garmin gear metadata (``[{"uuid": ...}, ...]``) from
            the activity download, when the activity has any.
        db: Database session.

    Returns:
        The local gear ID, or None when gear sync is off, the account's token is
        invalid, the activity has no gear, or no local gear matches.
    """
    if not garminconnect_gear:
        return None
    user_integrations = garmin_service.get_linked_user_integrations(user_id, db)
    if user_integrations is None or not user_integrations.garminconnect_sync_gear:
        return None
    gear = gears_integration.get_gear_by_garminconnect_id(garminconnect_gear[0]["uuid"], user_id, db)
    return gear.id if gear is not None else None

set_activities_gear

set_activities_gear(user_id, db)

Assign local gear to the user's activities that carry a Garmin Connect gear id.

Parameters:

Name Type Description Default
user_id UUID

The activities' owner.

required
db Session

Database session.

required

Returns:

Type Description
int

The number of activities whose gear was set.

Source code in backend/app/modules/garmin/gear_service.py
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
def set_activities_gear(user_id: uuid.UUID, db: Session) -> int:
    """Assign local gear to the user's activities that carry a Garmin Connect gear id.

    Args:
        user_id: The activities' owner.
        db: Database session.

    Returns:
        The number of activities whose gear was set.
    """
    gears = gears_integration.get_gear_user(user_id, db)

    assigned = 0
    after_id: uuid.UUID | None = None
    while page := activity_integration.list_garminconnect_gear_activity_refs(user_id, db, after_id=after_id):
        after_id = page[-1].id
        # {activity_id: gear_id} for the page's activities that have a match
        gear_assignments = {
            activity.id: matched_gear_id
            for activity in page
            if (matched_gear_id := match_gear_for_activity(activity, gears)) is not None
        }
        if gear_assignments:
            activity_integration.bulk_set_activities_gear(user_id, gear_assignments, db)
            assigned += len(gear_assignments)
        # Ends the read transaction, so a long history never holds one open
        db.commit()

    logger.debug(
        "Garmin Connect gear set on activities",
        extra=core_logger.context(user_id=user_id, count=assigned),
    )
    return assigned

Health sync

Garmin Connect health sync: body composition, daily steps and sleep.

fetch_and_process_bc_by_dates

fetch_and_process_bc_by_dates(garminconnect_client, start_date, end_date, user_id)

Fetch and store body composition from Garmin Connect.

Parameters:

Name Type Description Default
garminconnect_client Garmin

Authenticated Garmin Connect client.

required
start_date datetime

Start date for the retrieval.

required
end_date datetime

End date for the retrieval.

required
user_id UUID

The records' owner.

required

Returns:

Type Description
int

Number of body composition records stored; a day whose record another source wrote is skipped.

Source code in backend/app/modules/garmin/health_service.py
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
def fetch_and_process_bc_by_dates(
    garminconnect_client: garminconnect.Garmin,
    start_date: datetime,
    end_date: datetime,
    user_id: uuid.UUID,
) -> int:
    """Fetch and store body composition from Garmin Connect.

    Args:
        garminconnect_client: Authenticated Garmin Connect client.
        start_date: Start date for the retrieval.
        end_date: End date for the retrieval.
        user_id: The records' owner.

    Returns:
        Number of body composition records stored; a day whose record another source wrote is skipped.
    """
    garmin_bc = garminconnect_client.get_body_composition(str(start_date.date()), str(end_date.date()))

    if not garmin_bc or not garmin_bc.get("dateWeightList"):
        logger.info(
            "No new Garmin Connect body composition found",
            extra=core_logger.context(user_id=user_id, start_date=start_date.date(), end_date=end_date.date()),
        )
        return 0

    keep_existing = _keep_other_source(
        health_weight_integration.get_health_weight_by_date, health_weight_schema.Source.GARMIN
    )
    count_processed = 0
    for bc in garmin_bc["dateWeightList"]:
        if bc["weight"] is None:
            continue

        # A metabolic age outside 1-150 years is a bad reading
        metabolic_age = bc.get("metabolicAge")
        if metabolic_age is not None and (metabolic_age < 1 or metabolic_age > 150):
            metabolic_age = None

        health_weight = health_weight_schema.HealthWeightImport(
            date=bc["calendarDate"],
            weight_kg=bc["weight"] / 1000,
            bmi=bc["bmi"],
            body_fat_percent=bc["bodyFat"],
            body_water_percent=bc["bodyWater"],
            bone_mass_kg=(bc["boneMass"] / 1000 if bc["boneMass"] is not None else None),
            muscle_mass_kg=(bc["muscleMass"] / 1000 if bc["muscleMass"] is not None else None),
            physique_rating=bc["physiqueRating"],
            visceral_fat=bc["visceralFat"],
            metabolic_age=metabolic_age,
            source=health_weight_schema.Source.GARMIN,
        )
        stored = _store(
            user_id,
            health_weight,
            label="Body composition",
            upsert=health_weight_integration.upsert_health_weight,
            keep_existing=keep_existing,
        )
        count_processed += stored
    return count_processed

fetch_and_process_ds_by_dates

fetch_and_process_ds_by_dates(garminconnect_client, start_date, end_date, user_id)

Fetch and store daily steps from Garmin Connect.

Parameters:

Name Type Description Default
garminconnect_client Garmin

Authenticated Garmin Connect client.

required
start_date datetime

Start date for the retrieval.

required
end_date datetime

End date for the retrieval.

required
user_id UUID

The records' owner.

required

Returns:

Type Description
int

Number of daily steps records stored; a day whose record another source wrote is skipped.

Source code in backend/app/modules/garmin/health_service.py
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
def fetch_and_process_ds_by_dates(
    garminconnect_client: garminconnect.Garmin,
    start_date: datetime,
    end_date: datetime,
    user_id: uuid.UUID,
) -> int:
    """Fetch and store daily steps from Garmin Connect.

    Args:
        garminconnect_client: Authenticated Garmin Connect client.
        start_date: Start date for the retrieval.
        end_date: End date for the retrieval.
        user_id: The records' owner.

    Returns:
        Number of daily steps records stored; a day whose record another source wrote is skipped.
    """
    garmin_ds = garminconnect_client.get_daily_steps(str(start_date.date()), str(end_date.date()))

    if not garmin_ds:
        logger.info(
            "No new Garmin Connect daily steps found",
            extra=core_logger.context(user_id=user_id, start_date=start_date.date(), end_date=end_date.date()),
        )
        return 0

    keep_existing = _keep_other_source(
        health_steps_integration.get_health_steps_by_date, health_steps_schema.Source.GARMIN
    )
    count_processed = 0
    for ds in garmin_ds:
        if ds["totalSteps"] is None:
            continue

        health_steps = health_steps_schema.HealthStepsImport(
            date=ds["calendarDate"],
            steps=ds["totalSteps"],
            source=health_steps_schema.Source.GARMIN,
        )
        stored = _store(
            user_id,
            health_steps,
            label="Daily steps",
            upsert=health_steps_integration.upsert_health_steps,
            keep_existing=keep_existing,
        )
        count_processed += stored
    return count_processed

fetch_and_process_sleep_by_dates

fetch_and_process_sleep_by_dates(garminconnect_client, start_date, end_date, user_id)

Fetch and process sleep data from Garmin Connect.

Parameters:

Name Type Description Default
garminconnect_client Garmin

Authenticated Garmin Connect client.

required
start_date datetime

Start date for sleep data retrieval.

required
end_date datetime

End date for sleep data retrieval.

required
user_id UUID

ID of the user to process sleep data for.

required

Returns:

Type Description
int

Number of sleep records processed.

Source code in backend/app/modules/garmin/health_service.py
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
def fetch_and_process_sleep_by_dates(
    garminconnect_client: garminconnect.Garmin,
    start_date: datetime,
    end_date: datetime,
    user_id: uuid.UUID,
) -> int:
    """Fetch and process sleep data from Garmin Connect.

    Args:
        garminconnect_client: Authenticated Garmin Connect client.
        start_date: Start date for sleep data retrieval.
        end_date: End date for sleep data retrieval.
        user_id: ID of the user to process sleep data for.

    Returns:
        Number of sleep records processed.
    """
    count_processed = 0

    # get_sleep_data only supports a single date
    for day in _each_day(start_date, end_date):
        garmin_sleep = garminconnect_client.get_sleep_data(day.isoformat())

        sleep_dto = garmin_sleep.get("dailySleepDTO") if garmin_sleep else None
        # For a date without sleep Garmin still returns a DTO whose fields are all null
        if not sleep_dto or not sleep_dto.get("id") or not sleep_dto.get("sleepTimeSeconds"):
            logger.debug(
                "No Garmin Connect sleep data found",
                extra=core_logger.context(user_id=user_id, date=day),
            )
            continue

        stored = _store(
            user_id,
            _build_sleep(garmin_sleep, sleep_dto),
            label="Sleep data",
            upsert=health_sleep_integration.upsert_health_sleep,
            keep_existing=_is_other_source_sleep,
        )
        count_processed += stored

    return count_processed

get_user_garminconnect_health_by_dates

get_user_garminconnect_health_by_dates(start_date, end_date, user_id, rate_limits)

Fetch and store one user's Garmin Connect health data for a window.

No session is open while Garmin is being called; each record is stored in its own short one. An expired token unlinks the account and notifies the user. Any other failure propagates, so a durable worker retries the sync.

Parameters:

Name Type Description Default
start_date datetime

Start of the window.

required
end_date datetime

End of the window.

required
user_id UUID

The user to sync.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Returns:

Type Description
bool

True when the data was synced, False when the account is not linked or Garmin Connect

bool

rejected its token.

Source code in backend/app/modules/garmin/health_service.py
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
def get_user_garminconnect_health_by_dates(
    start_date: datetime,
    end_date: datetime,
    user_id: uuid.UUID,
    rate_limits: garmin_rate_limit_store.GarminRateLimitStore,
) -> bool:
    """Fetch and store one user's Garmin Connect health data for a window.

    No session is open while Garmin is being called; each record is stored in its own short
    one. An expired token unlinks the account and notifies the user. Any other failure
    propagates, so a durable worker retries the sync.

    Args:
        start_date: Start of the window.
        end_date: End of the window.
        user_id: The user to sync.
        rate_limits: The shared Garmin Connect rate-limit state.

    Returns:
        True when the data was synced, False when the account is not linked or Garmin Connect
        rejected its token.
    """
    with garmin_service.linked_session(user_id, rate_limits) as session:
        if session is None:
            return False

        logger.info(
            "Started Garmin Connect health processing for date range",
            extra=core_logger.context(user_id=user_id, start_date=start_date.date(), end_date=end_date.date()),
        )
        counts: dict[str, int] = {}
        try:
            for what, fetch in (
                ("body_composition", fetch_and_process_bc_by_dates),
                ("daily_steps", fetch_and_process_ds_by_dates),
                ("sleep_data", fetch_and_process_sleep_by_dates),
            ):
                counts[what] = fetch(session.client, start_date, end_date, user_id)
                logger.debug(
                    "Garmin Connect health data processed",
                    extra=core_logger.context(user_id=user_id, what=what, count=counts[what]),
                )
            logger.info(
                "Garmin Connect health processing finished",
                extra=core_logger.context(counts, user_id=user_id),
            )
        except garminconnect.GarminConnectAuthenticationError as err:
            garmin_service.handle_rejected_token(user_id, session, err)
            return False
    return True

sync_health_for_dates

sync_health_for_dates(start_date, end_date, user_id, rate_limits)

Fetch and store one user's Garmin Connect health data for whole days.

Parameters:

Name Type Description Default
start_date date

First day to fetch.

required
end_date date

Last day to fetch, inclusive.

required
user_id UUID

The user to sync.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Returns:

Type Description
bool

True when the data was synced, False when the account is not linked or was rejected.

Source code in backend/app/modules/garmin/health_service.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def sync_health_for_dates(
    start_date: date, end_date: date, user_id: uuid.UUID, rate_limits: garmin_rate_limit_store.GarminRateLimitStore
) -> bool:
    """Fetch and store one user's Garmin Connect health data for whole days.

    Args:
        start_date: First day to fetch.
        end_date: Last day to fetch, inclusive.
        user_id: The user to sync.
        rate_limits: The shared Garmin Connect rate-limit state.

    Returns:
        True when the data was synced, False when the account is not linked or was rejected.
    """
    return get_user_garminconnect_health_by_dates(
        datetime.combine(start_date, datetime.min.time(), tzinfo=UTC),
        datetime.combine(end_date, datetime.max.time(), tzinfo=UTC),
        user_id,
        rate_limits,
    )

Session and account

Unlinking a Garmin Connect account and the authenticated sessions its syncs use.

Linking lives in :mod:modules.garmin.link_service. The activity, gear and health syncs live in :mod:modules.garmin.activity_service, :mod:modules.garmin.gear_service and :mod:modules.garmin.health_service.

GarminSession

Bases: NamedTuple

A linked user's authenticated client and the stored token it was restored from.

Attributes:

Name Type Description
client Garmin

The authenticated Garmin Connect client.

token dict[str, Any]

The token as stored when the client was restored, so a rejection can be told apart from a later re-link.

Source code in backend/app/modules/garmin/service.py
 99
100
101
102
103
104
105
106
107
108
109
class GarminSession(NamedTuple):
    """A linked user's authenticated client and the stored token it was restored from.

    Attributes:
        client: The authenticated Garmin Connect client.
        token: The token as stored when the client was restored, so a rejection can be
            told apart from a later re-link.
    """

    client: garminconnect.Garmin
    token: dict[str, Any]

fresh_session

fresh_session(user_id, session, claims)

Return a session whose token is not about to expire, refreshing it under the user's shared claim.

The client would otherwise refresh the token itself in the middle of a call, and two syncs of one user doing so at once can invalidate each other's refresh token. Only the holder of the claim refreshes; a caller that finds it held waits for the holder, then restores the token it stored.

Parameters:

Name Type Description Default
user_id UUID

The user the session belongs to.

required
session GarminSession

The session as restored from the stored token.

required
claims GarminRateLimitStore

The shared Garmin Connect state holding the refresh claim.

required

Returns:

Type Description
GarminSession | None

A session that needs no refresh, or None when the account was unlinked meanwhile.

Raises:

Type Description
TooManyRequestsError

When another process still holds the refresh claim after the wait.

Source code in backend/app/modules/garmin/service.py
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
def fresh_session(
    user_id: uuid.UUID, session: GarminSession, claims: garmin_rate_limit_store.GarminRateLimitStore
) -> GarminSession | None:
    """Return a session whose token is not about to expire, refreshing it under the user's shared claim.

    The client would otherwise refresh the token itself in the middle of a call, and two syncs of one
    user doing so at once can invalidate each other's refresh token. Only the holder of the claim
    refreshes; a caller that finds it held waits for the holder, then restores the token it stored.

    Args:
        user_id: The user the session belongs to.
        session: The session as restored from the stored token.
        claims: The shared Garmin Connect state holding the refresh claim.

    Returns:
        A session that needs no refresh, or ``None`` when the account was unlinked meanwhile.

    Raises:
        TooManyRequestsError: When another process still holds the refresh claim after the wait.
    """
    deadline = time.monotonic() + garmin_constants.TOKEN_REFRESH_WAIT_SECONDS
    current: GarminSession | None = session
    while current is not None and garmin_token_utils.expires_soon(current.client.client):
        if _claim_refresh(user_id, claims):
            try:
                return _refresh_under_claim(user_id)
            finally:
                _release_refresh(user_id, claims)
        if time.monotonic() >= deadline:
            logger.warning(
                "Another process is refreshing the Garmin Connect token", extra=core_logger.context(user_id=user_id)
            )
            raise core_exceptions.TooManyRequestsError(
                "Another process is refreshing the Garmin Connect token",
                scope=core_exceptions.TooManyRequestsScope.PROVIDER,
                retry_at=datetime.now(UTC) + timedelta(seconds=garmin_constants.TOKEN_REFRESH_CLAIM_TTL_SECONDS),
            )
        time.sleep(garmin_constants.TOKEN_REFRESH_POLL_SECONDS)
        with core_database.SessionLocal() as db:
            current = get_user_garminconnect_session(user_id, db)
    return current

get_linked_user_integrations

get_linked_user_integrations(user_id, db)

Return a user's integrations when Garmin Connect is linked.

Parameters:

Name Type Description Default
user_id UUID

The user to look up.

required
db Session

Database session.

required

Returns:

Type Description
UserIntegrationsRead | None

The user's integrations, or None when Garmin Connect is not linked.

Raises:

Type Description
NotFoundError

When the user has no integrations record.

Source code in backend/app/modules/garmin/service.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def get_linked_user_integrations(
    user_id: uuid.UUID, db: Session
) -> user_integrations_schema.UserIntegrationsRead | None:
    """Return a user's integrations when Garmin Connect is linked.

    Args:
        user_id: The user to look up.
        db: Database session.

    Returns:
        The user's integrations, or ``None`` when Garmin Connect is not linked.

    Raises:
        NotFoundError: When the user has no integrations record.
    """
    user_integrations = user_integrations_integration.get_user_integrations(user_id, db)

    if user_integrations is None:
        raise core_exceptions.NotFoundError("User information not found")

    if user_integrations.garminconnect_token is None:
        return None

    return user_integrations

get_user_garminconnect_session

get_user_garminconnect_session(user_id, db)

Restore the session of a linked user from the token stored for them.

Parameters:

Name Type Description Default
user_id UUID

The user whose Garmin Connect account to use.

required
db Session

Database session.

required

Returns:

Type Description
GarminSession | None

The session, or None when Garmin Connect is not linked or the stored session is rejected.

Raises:

Type Description
UndecryptableError

When the stored token cannot be decrypted with the configured key. The account stays linked: the fault is the key, not the token.

Source code in backend/app/modules/garmin/service.py
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
def get_user_garminconnect_session(user_id: uuid.UUID, db: Session) -> GarminSession | None:
    """Restore the session of a linked user from the token stored for them.

    Args:
        user_id: The user whose Garmin Connect account to use.
        db: Database session.

    Returns:
        The session, or ``None`` when Garmin Connect is not linked or the stored session is rejected.

    Raises:
        UndecryptableError: When the stored token cannot be decrypted with the configured key. The
            account stays linked: the fault is the key, not the token.
    """
    try:
        user_integrations = get_linked_user_integrations(user_id, db)
    except core_exceptions.NotFoundError:
        logger.debug("Garmin Connect user has no integrations record", extra=core_logger.context(user_id=user_id))
        return None

    token = user_integrations.garminconnect_token if user_integrations is not None else None
    if token is None:
        logger.debug(
            "Garmin Connect not linked",
            extra=core_logger.context(user_id=user_id),
        )
        return None

    client = garmin_token_utils.login_garminconnect_using_tokens(token)
    return GarminSession(client, token) if client is not None else None

handle_rejected_token

handle_rejected_token(user_id, session, err)

Unlink an account whose token Garmin Connect rejected during a sync, and tell the user.

Parameters:

Name Type Description Default
user_id UUID

The user whose sync was rejected.

required
session GarminSession

The session the sync used.

required
err Exception

The authentication error Garmin Connect raised.

required
Source code in backend/app/modules/garmin/service.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def handle_rejected_token(user_id: uuid.UUID, session: GarminSession, err: Exception) -> None:
    """Unlink an account whose token Garmin Connect rejected during a sync, and tell the user.

    Args:
        user_id: The user whose sync was rejected.
        session: The session the sync used.
        err: The authentication error Garmin Connect raised.
    """
    logger.warning(
        "Garmin Connect token expired. Unlinking account. User must re-link",
        exc_info=err,
        extra=core_logger.context(user_id=user_id),
    )
    with core_database.SessionLocal() as db:
        unlink_expired_account(user_id, session.token, db)

linked_session

linked_session(user_id, rate_limits)

Yield a linked user's session with no database session open, then store its refreshed token.

The token is stored whether the body succeeds or raises, so the next sync restores a live one. Rejection by Garmin Connect is the body's to handle, as what follows it differs per sync.

Parameters:

Name Type Description Default
user_id UUID

The user whose Garmin Connect account to use.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state, checked before the session is restored.

required

Yields:

Type Description
Generator[GarminSession | None]

The session, or None when Garmin Connect is not linked or the stored session is rejected.

Raises:

Type Description
TooManyRequestsError

When the account is rate limited, or another process keeps refreshing the token.

Source code in backend/app/modules/garmin/service.py
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
@contextmanager
def linked_session(
    user_id: uuid.UUID, rate_limits: garmin_rate_limit_store.GarminRateLimitStore
) -> Generator[GarminSession | None]:
    """Yield a linked user's session with no database session open, then store its refreshed token.

    The token is stored whether the body succeeds or raises, so the next sync restores a live one.
    Rejection by Garmin Connect is the body's to handle, as what follows it differs per sync.

    Args:
        user_id: The user whose Garmin Connect account to use.
        rate_limits: The shared Garmin Connect rate-limit state, checked before the session is restored.

    Yields:
        The session, or ``None`` when Garmin Connect is not linked or the stored session is rejected.

    Raises:
        TooManyRequestsError: When the account is rate limited, or another process keeps refreshing the token.
    """
    raise_if_rate_limited(user_id, rate_limits)
    with core_database.SessionLocal() as db:
        session = get_user_garminconnect_session(user_id, db)
    if session is not None:
        session = fresh_session(user_id, session, rate_limits)
    if session is None:
        yield None
        return
    try:
        yield session
    finally:
        save_refreshed_token(user_id, session)

linked_user_ids

linked_user_ids(after_id, limit)

Page through the users who have linked Garmin Connect, in a short session of its own.

Parameters:

Name Type Description Default
after_id UUID | None

Return only users with an id greater than this.

required
limit int

Maximum number of user ids to return.

required

Returns:

Type Description
list[UUID]

The linked user ids, ascending.

Source code in backend/app/modules/garmin/service.py
315
316
317
318
319
320
321
322
323
324
325
326
def linked_user_ids(after_id: uuid.UUID | None, limit: int) -> list[uuid.UUID]:
    """Page through the users who have linked Garmin Connect, in a short session of its own.

    Args:
        after_id: Return only users with an id greater than this.
        limit: Maximum number of user ids to return.

    Returns:
        The linked user ids, ascending.
    """
    with core_database.SessionLocal() as db:
        return user_integrations_integration.list_user_ids_with_garminconnect_linked(after_id, limit, db)

raise_if_rate_limited

raise_if_rate_limited(user_id, rate_limits)

Refuse a Garmin Connect call while the user's account is rate limited.

Parameters:

Name Type Description Default
user_id UUID

The user about to be synced.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Raises:

Type Description
TooManyRequestsError

When the account is rate limited, carrying when the limit clears.

Source code in backend/app/modules/garmin/service.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def raise_if_rate_limited(user_id: uuid.UUID, rate_limits: garmin_rate_limit_store.GarminRateLimitStore) -> None:
    """Refuse a Garmin Connect call while the user's account is rate limited.

    Args:
        user_id: The user about to be synced.
        rate_limits: The shared Garmin Connect rate-limit state.

    Raises:
        TooManyRequestsError: When the account is rate limited, carrying when the limit clears.
    """
    retry_at = rate_limits.rate_limited_until(user_id)
    if retry_at is not None:
        logger.debug("Garmin Connect rate limit active, skipping the call", extra=core_logger.context(user_id=user_id))
        raise core_exceptions.TooManyRequestsError(
            "Garmin Connect rate limit exceeded. Please try again later.",
            scope=core_exceptions.TooManyRequestsScope.PROVIDER,
            retry_at=retry_at,
        )

rate_limit_error

rate_limit_error(err, user_id, rate_limits)

Record that Garmin Connect refused a call as rate limited, and build the error for it.

Garmin Connect reports no reset time, so the account is left alone for one cooldown, in every process, and the refresh waits that long before it tries again.

Parameters:

Name Type Description Default
err Exception

The rate-limit error Garmin Connect raised.

required
user_id UUID

The user whose account was limited.

required
rate_limits GarminRateLimitStore

The shared Garmin Connect rate-limit state.

required

Returns:

Type Description
TooManyRequestsError

The error to raise, carrying when the refresh may run again.

Source code in backend/app/modules/garmin/service.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def rate_limit_error(
    err: Exception, user_id: uuid.UUID, rate_limits: garmin_rate_limit_store.GarminRateLimitStore
) -> core_exceptions.TooManyRequestsError:
    """Record that Garmin Connect refused a call as rate limited, and build the error for it.

    Garmin Connect reports no reset time, so the account is left alone for one cooldown, in every
    process, and the refresh waits that long before it tries again.

    Args:
        err: The rate-limit error Garmin Connect raised.
        user_id: The user whose account was limited.
        rate_limits: The shared Garmin Connect rate-limit state.

    Returns:
        The error to raise, carrying when the refresh may run again.
    """
    logger.warning("Garmin Connect rate limit hit", exc_info=err, extra=core_logger.context(user_id=user_id))
    return core_exceptions.TooManyRequestsError(
        "Garmin Connect rate limit exceeded. Please try again later.",
        scope=core_exceptions.TooManyRequestsScope.PROVIDER,
        retry_at=rate_limits.mark_rate_limited(user_id),
    )

save_refreshed_token

save_refreshed_token(user_id, session)

Store the token a sync's client refreshed, so the next sync restores a live one.

Garmin Connect may rotate the refresh token, in which case the stored one stops working. A failure is logged, not raised: the sync itself has already finished.

Parameters:

Name Type Description Default
user_id UUID

The user the session belongs to.

required
session GarminSession

The session the sync used.

required
Source code in backend/app/modules/garmin/service.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def save_refreshed_token(user_id: uuid.UUID, session: GarminSession) -> None:
    """Store the token a sync's client refreshed, so the next sync restores a live one.

    Garmin Connect may rotate the refresh token, in which case the stored one stops working.
    A failure is logged, not raised: the sync itself has already finished.

    Args:
        user_id: The user the session belongs to.
        session: The session the sync used.
    """
    try:
        token = garmin_token_utils.refreshed_token(session.token, session.client.client)
        if token is None:
            return
        with core_database.SessionLocal() as db:
            if user_integrations_integration.replace_garminconnect_token_if_token(user_id, session.token, token, db):
                db.commit()
                logger.debug("Garmin Connect token refreshed", extra=core_logger.context(user_id=user_id))
    except (sqlalchemy.exc.SQLAlchemyError, core_exceptions.CryptographyError) as err:
        logger.error(
            "Failed to store the refreshed Garmin Connect token",
            exc_info=err,
            extra=core_logger.context(user_id=user_id),
        )
unlink_account(user_id, step_up, verify_step_up, db)

Unlink a user's Garmin Connect account after the user's step-up.

The step-up is verified before anything is changed, and committed with the unlink.

Parameters:

Name Type Description Default
user_id UUID

The user unlinking Garmin Connect.

required
step_up StepUpVerification

The user's step-up verification.

required
verify_step_up StepUpVerifier

Verifies the step-up for the calling user.

required
db Session

Database session.

required

Raises:

Type Description
StepUpFailedError

If the step-up does not verify.

Source code in backend/app/modules/garmin/service.py
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
def unlink_account(
    user_id: uuid.UUID,
    step_up: auth_schema.StepUpVerification,
    verify_step_up: identity_providers_contracts.StepUpVerifier,
    db: Session,
) -> None:
    """Unlink a user's Garmin Connect account after the user's step-up.

    The step-up is verified before anything is changed, and committed with the unlink.

    Args:
        user_id: The user unlinking Garmin Connect.
        step_up: The user's step-up verification.
        verify_step_up: Verifies the step-up for the calling user.
        db: Database session.

    Raises:
        StepUpFailedError: If the step-up does not verify.
    """
    verify_step_up(step_up, identity_providers_constants.StepUpAction.GARMIN_UNLINK)
    user_integrations_integration.unlink_garminconnect_account(user_id, db)
    jasil_audit.stage(
        db,
        garmin_audit_actions.ACCOUNT_UNLINK,
        target_type="user",
        target_id=str(user_id),
        target_owner_id=str(user_id),
    )
    db.commit()
    logger.info(
        "Garmin Connect unlinked",
        extra=core_logger.context(user_id=user_id),
    )
unlink_expired_account(user_id, token, db)

Unlink an account whose Garmin Connect token expired and tell the user.

The unlink and the notification row commit together; the live push is published after. Nothing happens when the stored token is no longer token: the user re-linked, or another job already unlinked it and told them.

Parameters:

Name Type Description Default
user_id UUID

The user whose account to unlink.

required
token dict[str, Any]

The stored token that Garmin Connect rejected.

required
db Session

The caller's session, which this commits.

required
Source code in backend/app/modules/garmin/service.py
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
def unlink_expired_account(user_id: uuid.UUID, token: dict[str, Any], db: Session) -> None:
    """Unlink an account whose Garmin Connect token expired and tell the user.

    The unlink and the notification row commit together; the live push is published after.
    Nothing happens when the stored token is no longer ``token``: the user re-linked, or
    another job already unlinked it and told them.

    Args:
        user_id: The user whose account to unlink.
        token: The stored token that Garmin Connect rejected.
        db: The caller's session, which this commits.
    """
    if not user_integrations_integration.unlink_garminconnect_account_if_token(user_id, token, db):
        db.rollback()
        logger.info(
            "Garmin Connect token changed since it expired; account left linked",
            extra=core_logger.context(user_id=user_id),
        )
        return
    notification, ws_message = notifications_integration.create_garmin_token_expired_notification(user_id, db)
    jasil_audit.stage(
        db,
        garmin_audit_actions.ACCOUNT_REVOKE,
        target_type="user",
        target_id=str(user_id),
        target_owner_id=str(user_id),
    )
    db.commit()
    notifications_integration.push_notification(user_id, notification, ws_message)
    logger.info(
        "Expired Garmin Connect account unlinked",
        extra=core_logger.context(user_id=user_id),
    )

Rate limits

Garmin Connect's shared rate-limit state: a per-user flag over the platform StateProvider.

Garmin Connect throttles an account, not an application, and reports no reset time, so a limit is recorded for one cooldown. Every process and replica reads the same flag, so a sync that was refused is not repeated by another replica's scheduled pull. The same state holds the claim on refreshing a user's token. See :class:core.provider_rate_limit.ProviderRateLimitStore.

GarminRateLimitStore

Garmin Connect rate-limit flags and token-refresh claims, keyed by user.

Attributes:

Name Type Description
_limits

The shared flag storage.

_state

The platform state provider, which holds the refresh claims.

Source code in backend/app/modules/garmin/rate_limit_store.py
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
class GarminRateLimitStore:
    """Garmin Connect rate-limit flags and token-refresh claims, keyed by user.

    Attributes:
        _limits: The shared flag storage.
        _state: The platform state provider, which holds the refresh claims.
    """

    def __init__(self, state: platform_providers.StateProvider) -> None:
        """Bind the store to a state provider.

        Args:
            state: The platform state provider.
        """
        self._state = state
        self._limits = core_provider_rate_limit.ProviderRateLimitStore(state, garmin_constants.PROVIDER_NAME)

    def mark_rate_limited(self, user_id: uuid.UUID) -> datetime:
        """Record that Garmin Connect rate limited a user's account, for one cooldown.

        Args:
            user_id: The user whose account was limited.

        Returns:
            When the limit is taken to clear.
        """
        expires_at = datetime.now(UTC) + timedelta(seconds=garmin_constants.RATE_LIMIT_COOLDOWN_SECONDS)
        self._limits.mark(str(user_id), expires_at)
        return expires_at

    def rate_limited_until(self, user_id: uuid.UUID) -> datetime | None:
        """Return when a user's active rate limit clears.

        Fails open when the shared state is unreachable.

        Args:
            user_id: The user about to be synced.

        Returns:
            When the limit clears, or ``None`` when none is active or the state is unreachable.
        """
        return self._limits.expiry(str(user_id))

    def claim_token_refresh(self, user_id: uuid.UUID) -> bool:
        """Claim the right to refresh a user's Garmin Connect token.

        Args:
            user_id: The user whose token is about to be refreshed.

        Returns:
            True when this caller may refresh, False when another already is.

        Raises:
            StateBackendUnavailableError: When the shared state is unreachable; the caller decides whether to
                refresh anyway.
        """
        return self._state.set_if_absent(
            _refresh_claim_key(user_id), b"1", garmin_constants.TOKEN_REFRESH_CLAIM_TTL_SECONDS
        )

    def release_token_refresh(self, user_id: uuid.UUID) -> None:
        """Release the claim on refreshing a user's token once the refresh is over.

        Args:
            user_id: The user whose token was refreshed.

        Raises:
            StateBackendUnavailableError: When the shared state is unreachable; the claim then expires on its own.
        """
        self._state.delete(_refresh_claim_key(user_id))

__init__

__init__(state)

Bind the store to a state provider.

Parameters:

Name Type Description Default
state StateProvider

The platform state provider.

required
Source code in backend/app/modules/garmin/rate_limit_store.py
27
28
29
30
31
32
33
34
def __init__(self, state: platform_providers.StateProvider) -> None:
    """Bind the store to a state provider.

    Args:
        state: The platform state provider.
    """
    self._state = state
    self._limits = core_provider_rate_limit.ProviderRateLimitStore(state, garmin_constants.PROVIDER_NAME)

claim_token_refresh

claim_token_refresh(user_id)

Claim the right to refresh a user's Garmin Connect token.

Parameters:

Name Type Description Default
user_id UUID

The user whose token is about to be refreshed.

required

Returns:

Type Description
bool

True when this caller may refresh, False when another already is.

Raises:

Type Description
StateBackendUnavailableError

When the shared state is unreachable; the caller decides whether to refresh anyway.

Source code in backend/app/modules/garmin/rate_limit_store.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def claim_token_refresh(self, user_id: uuid.UUID) -> bool:
    """Claim the right to refresh a user's Garmin Connect token.

    Args:
        user_id: The user whose token is about to be refreshed.

    Returns:
        True when this caller may refresh, False when another already is.

    Raises:
        StateBackendUnavailableError: When the shared state is unreachable; the caller decides whether to
            refresh anyway.
    """
    return self._state.set_if_absent(
        _refresh_claim_key(user_id), b"1", garmin_constants.TOKEN_REFRESH_CLAIM_TTL_SECONDS
    )

mark_rate_limited

mark_rate_limited(user_id)

Record that Garmin Connect rate limited a user's account, for one cooldown.

Parameters:

Name Type Description Default
user_id UUID

The user whose account was limited.

required

Returns:

Type Description
datetime

When the limit is taken to clear.

Source code in backend/app/modules/garmin/rate_limit_store.py
36
37
38
39
40
41
42
43
44
45
46
47
def mark_rate_limited(self, user_id: uuid.UUID) -> datetime:
    """Record that Garmin Connect rate limited a user's account, for one cooldown.

    Args:
        user_id: The user whose account was limited.

    Returns:
        When the limit is taken to clear.
    """
    expires_at = datetime.now(UTC) + timedelta(seconds=garmin_constants.RATE_LIMIT_COOLDOWN_SECONDS)
    self._limits.mark(str(user_id), expires_at)
    return expires_at

rate_limited_until

rate_limited_until(user_id)

Return when a user's active rate limit clears.

Fails open when the shared state is unreachable.

Parameters:

Name Type Description Default
user_id UUID

The user about to be synced.

required

Returns:

Type Description
datetime | None

When the limit clears, or None when none is active or the state is unreachable.

Source code in backend/app/modules/garmin/rate_limit_store.py
49
50
51
52
53
54
55
56
57
58
59
60
def rate_limited_until(self, user_id: uuid.UUID) -> datetime | None:
    """Return when a user's active rate limit clears.

    Fails open when the shared state is unreachable.

    Args:
        user_id: The user about to be synced.

    Returns:
        When the limit clears, or ``None`` when none is active or the state is unreachable.
    """
    return self._limits.expiry(str(user_id))

release_token_refresh

release_token_refresh(user_id)

Release the claim on refreshing a user's token once the refresh is over.

Parameters:

Name Type Description Default
user_id UUID

The user whose token was refreshed.

required

Raises:

Type Description
StateBackendUnavailableError

When the shared state is unreachable; the claim then expires on its own.

Source code in backend/app/modules/garmin/rate_limit_store.py
79
80
81
82
83
84
85
86
87
88
def release_token_refresh(self, user_id: uuid.UUID) -> None:
    """Release the claim on refreshing a user's token once the refresh is over.

    Args:
        user_id: The user whose token was refreshed.

    Raises:
        StateBackendUnavailableError: When the shared state is unreachable; the claim then expires on its own.
    """
    self._state.delete(_refresh_claim_key(user_id))

Schemas

Garmin Connect request and response shapes.

GarminLinkStatus

Bases: JobStatus

Where a Garmin Connect link attempt is.

Attributes:

Name Type Description
kind Literal['garmin_link']

Always garmin_link.

mfa_required bool

true while the login waits for a code the user submits through POST /garmin/mfa; status is running then.

error_code LinkFailure | None

Why the attempt failed; set only when status is failed.

Source code in backend/app/modules/garmin/schema.py
37
38
39
40
41
42
43
44
45
46
47
48
49
class GarminLinkStatus(core_job_status.JobStatus):
    """Where a Garmin Connect link attempt is.

    Attributes:
        kind: Always ``garmin_link``.
        mfa_required: ``true`` while the login waits for a code the user submits through ``POST /garmin/mfa``;
            ``status`` is ``running`` then.
        error_code: Why the attempt failed; set only when ``status`` is ``failed``.
    """

    kind: Literal["garmin_link"]
    mfa_required: bool = Field(default=False, description="The login waits for an MFA code")
    error_code: garmin_constants.LinkFailure | None = Field(default=None, description="Why the attempt failed")

GarminLogin

Bases: BaseModel

Credentials a user submits to link Garmin Connect.

Source code in backend/app/modules/garmin/schema.py
11
12
13
14
15
16
17
18
class GarminLogin(BaseModel):
    """Credentials a user submits to link Garmin Connect."""

    username: str = Field(min_length=1, max_length=250)
    password: SecretStr = Field(min_length=1, max_length=250)
    is_cn: bool = False

    model_config = ConfigDict(extra="forbid")

GarminSyncStatus

Bases: JobStatusOpenFailure

Where a queued Garmin Connect gear or health sync is.

Attributes:

Name Type Description
kind Literal['garmin_sync_gear', 'garmin_sync_health']

What the sync pulls, as its job kind.

Source code in backend/app/modules/garmin/schema.py
52
53
54
55
56
57
58
59
class GarminSyncStatus(core_job_status.JobStatusOpenFailure):
    """Where a queued Garmin Connect gear or health sync is.

    Attributes:
        kind: What the sync pulls, as its job kind.
    """

    kind: Literal["garmin_sync_gear", "garmin_sync_health"]

MFARequest

Bases: BaseModel

The MFA code a user submits to finish a link attempt.

Source code in backend/app/modules/garmin/schema.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class MFARequest(BaseModel):
    """The MFA code a user submits to finish a link attempt."""

    mfa_code: str = Field(min_length=1, max_length=32, pattern=r"^[A-Za-z0-9]+$")

    model_config = ConfigDict(extra="forbid")

    @field_validator("mfa_code", mode="before")
    @classmethod
    def _strip_separators(cls, value: object) -> object:
        """Drop the whitespace and dashes a code is pasted or autofilled with, such as ``123 456``."""
        if isinstance(value, str):
            return "".join(value.split()).replace("-", "")
        return value