Skip to content

Strava API reference

Strava linking, sync and bulk export import. See Integrations and Importing data.

Routes

Strava routes: account linking, activity and gear sync, and gear CSV import.

import_gear_from_strava_export

import_gear_from_strava_export(request, file, gear_type, token_user_id, db)

Create the gear listed in an uploaded Strava bikes.csv or shoes.csv and report how many.

Source code in backend/app/modules/strava/router.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@router.post(
    "/import/gear",
    response_model=strava_schema.StravaGearImportResult,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["gears:write"])],
    openapi_extra=core_middleware_body_limit.upload_limit(strava_constants.GEAR_CSV_MAX_BYTES),
)
@core_rate_limit.limiter.limit(core_rate_limit.UPLOAD)
def import_gear_from_strava_export(
    request: Request,
    file: UploadFile,
    gear_type: Annotated[strava_schema.StravaGearImportType, Query(description="Which Strava export file is uploaded")],
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
) -> strava_schema.StravaGearImportResult:
    """Create the gear listed in an uploaded Strava ``bikes.csv`` or ``shoes.csv`` and report how many."""
    return strava_schema.StravaGearImportResult(
        imported=strava_gear_service.import_gear(file, token_user_id, gears_schema.GearType[gear_type.name], db)
    )

strava_begin_state

strava_begin_state(request, token_user_id, oauth_states)

Issue the one-time state that correlates the OAuth callback with the user.

Replaces any state the user issued earlier.

Source code in backend/app/modules/strava/router.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
@router.post(
    "/state",
    status_code=status.HTTP_201_CREATED,
    response_model=strava_schema.StravaState,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def strava_begin_state(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    oauth_states: strava_dependencies.StravaOAuthStateStoreDep,
) -> strava_schema.StravaState:
    """Issue the one-time state that correlates the OAuth callback with the user.

    Replaces any state the user issued earlier.
    """
    return strava_schema.StravaState(state=strava_service.begin_state(token_user_id, oauth_states))
strava_link(request, response, link, token_user_id, oauth_states, sync_states)

Queue the exchange of a Strava authorization code for tokens.

Send the state, code and scope Strava put on the callback. scope is the comma-separated list of permissions the user granted; a link whose grant lacks read, profile:read_all or activity:read_all is refused with 400 and urn:endurain:error:provider-scope-insufficient before the code is exchanged. Poll GET /jobs/{job_id} for the outcome. A second request while one is pending is answered 409.

Source code in backend/app/modules/strava/router.py
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
@router.post(
    "/link",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=strava_schema.StravaSyncStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def strava_link(
    request: Request,
    response: Response,
    link: strava_schema.StravaLinkRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    oauth_states: strava_dependencies.StravaOAuthStateStoreDep,
    sync_states: strava_dependencies.StravaSyncStateStoreDep,
) -> strava_schema.StravaSyncStatus:
    """Queue the exchange of a Strava authorization code for tokens.

    Send the ``state``, ``code`` and ``scope`` Strava put on the callback. ``scope`` is the comma-separated
    list of permissions the user granted; a link whose grant lacks ``read``, ``profile:read_all`` or
    ``activity:read_all`` is refused with 400 and ``urn:endurain:error:provider-scope-insufficient`` before
    the code is exchanged. Poll ``GET /jobs/{job_id}`` for the outcome. A second request while one is
    pending is answered 409.
    """
    sync = strava_link_service.start_link(token_user_id, link, oauth_states, sync_states)
    core_location.set_job_location(
        response, request, sync.id, strava_constants.SYNC_POLL_SECONDS[strava_constants.SyncKind.LINK]
    )
    return sync

strava_retrieve_activities_days

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

Queue a Strava 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/strava/router.py
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
@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 strava_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 Strava 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 = strava_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

strava_retrieve_gear

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

Queue a sync of the user's Strava 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/strava/router.py
 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
@router.post(
    "/gear",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=strava_schema.StravaSyncStatus,
    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 strava_retrieve_gear(
    request: Request,
    response: Response,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    sync_states: strava_dependencies.StravaSyncStateStoreDep,
    rate_limits: strava_dependencies.StravaRateLimitStoreDep,
) -> strava_schema.StravaSyncStatus:
    """Queue a sync of the user's Strava 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 = strava_sync_service.request_gear_sync(token_user_id, sync_states, rate_limits, db)
    core_location.set_job_location(
        response, request, sync.id, strava_constants.SYNC_POLL_SECONDS[strava_constants.SyncKind.GEAR]
    )
    return sync

strava_set_user_client

strava_set_user_client(request, client, token_user_id, verify_step_up, db, response, if_match)

Store the user's Strava API client id and secret, after the user's step-up verification in step_up.

Replacing the client changes which Strava application the account is linked through. It needs a signed-in session: an API key cannot step up. Send the integrations_version the client read in If-Match.

Source code in backend/app/modules/strava/router.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@router.put(
    "/client",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    responses={204: {"headers": core_openapi_contract.ETAG_HEADERS}},
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def strava_set_user_client(
    request: Request,
    client: strava_schema.StravaClientCredentials,
    token_user_id: auth_dependencies.CurrentUserId,
    verify_step_up: auth_dependencies.StepUpVerifierDep,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> None:
    """Store the user's Strava API client id and secret, after the user's step-up verification in `step_up`.

    Replacing the client changes which Strava application the account is linked through. It needs a signed-in
    session: an API key cannot step up. Send the `integrations_version` the client read in `If-Match`.
    """
    version = strava_service.set_client(token_user_id, client, verify_step_up, db, if_match=if_match)
    core_etag.set_etag(response, version)
strava_unlink(request, response, body, token_user_id, verify_step_up, db, sync_states, rate_limits)

Queue the disconnection of the user's Strava account after the user's step-up verification; a job runs it.

The job revokes the authorization with Strava and deletes the activities and gear imported from it. It needs a signed-in session: an API key cannot step up. Poll GET /jobs/{job_id} for the outcome.

Source code in backend/app/modules/strava/router.py
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
@router.post(
    "/unlink",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=strava_schema.StravaSyncStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:integrations"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def strava_unlink(
    request: Request,
    response: Response,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    verify_step_up: auth_dependencies.StepUpVerifierDep,
    db: core_dependencies.DbSession,
    sync_states: strava_dependencies.StravaSyncStateStoreDep,
    rate_limits: strava_dependencies.StravaRateLimitStoreDep,
) -> strava_schema.StravaSyncStatus:
    """Queue the disconnection of the user's Strava account after the user's step-up verification; a job runs it.

    The job revokes the authorization with Strava and deletes the activities and gear
    imported from it. It needs a signed-in session: an API key cannot step up. Poll
    ``GET /jobs/{job_id}`` for the outcome.
    """
    sync = strava_sync_service.request_unlink(token_user_id, body.step_up, verify_step_up, sync_states, rate_limits, db)
    core_location.set_job_location(
        response, request, sync.id, strava_constants.SYNC_POLL_SECONDS[strava_constants.SyncKind.UNLINK]
    )
    return sync

Account linking

Strava account linking: the OAuth state and client, the code exchange and unlinking.

begin_state

begin_state(user_id, oauth_states)

Issue the one-time state that correlates the OAuth callback with the user.

Parameters:

Name Type Description Default
user_id UUID

The authenticated user.

required
oauth_states StravaOAuthStateStore

The one-time OAuth state store.

required

Returns:

Type Description
str

The opaque state, to be sent to Strava and handed back with the authorization code.

Source code in backend/app/modules/strava/service.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def begin_state(user_id: uuid.UUID, oauth_states: strava_oauth_state_store.StravaOAuthStateStore) -> str:
    """Issue the one-time state that correlates the OAuth callback with the user.

    Args:
        user_id: The authenticated user.
        oauth_states: The one-time OAuth state store.

    Returns:
        The opaque state, to be sent to Strava and handed back with the authorization code.
    """
    state = secrets.token_urlsafe(strava_constants.OAUTH_STATE_BYTES)
    oauth_states.begin(user_id, state)
    logger.debug("Strava state stored", extra=core_logger.context(user_id=user_id))
    return state

delete_revoked_data

delete_revoked_data(user_id)

Delete a user's Strava data once the grace period after a revocation has passed.

Runs on a worker. Nothing is asked of Strava: the access is already gone. The user's own Strava export uploads, which carry no Strava activity id, stay, and so do the client id and secret. The revocation mark is cleared, the user told and the deletion audited in the transaction that deletes the gear.

Parameters:

Name Type Description Default
user_id UUID

The user whose access was revoked.

required

Returns:

Type Description
bool

True when the data was deleted, False when the user relinked or the grace period has not passed.

Source code in backend/app/modules/strava/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
def delete_revoked_data(user_id: uuid.UUID) -> bool:
    """Delete a user's Strava data once the grace period after a revocation has passed.

    Runs on a worker. Nothing is asked of Strava: the access is already gone. The user's own Strava export
    uploads, which carry no Strava activity id, stay, and so do the client id and secret. The revocation mark is
    cleared, the user told and the deletion audited in the transaction that deletes the gear.

    Args:
        user_id: The user whose access was revoked.

    Returns:
        True when the data was deleted, False when the user relinked or the grace period has not passed.
    """
    cutoff = datetime.now(UTC) - timedelta(days=user_integrations_constants.STRAVA_REVOKED_DATA_GRACE_DAYS)
    with core_database.SessionLocal() as db:
        user_integrations = user_integrations_integration.get_user_integrations(user_id, db)
    if (
        user_integrations is None
        or user_integrations.strava_revoked_at is None
        or user_integrations.strava_revoked_at >= cutoff
        or user_integrations.strava_token is not None
    ):
        logger.debug("Strava data not due for deletion", extra=core_logger.context(user_id=user_id))
        return False

    def finish(deleted_activities: int, db: Session) -> tuple[notifications_schema.NotificationRead, str]:
        user_integrations_integration.clear_strava_revoked_at(user_id, db)
        jasil_audit.stage(
            db,
            strava_audit_actions.DATA_DELETE,
            target_type="user",
            target_id=str(user_id),
            target_owner_id=str(user_id),
            details=strava_audit_actions.DataDeleteDetails(activity_count=deleted_activities),
        )
        return notifications_integration.create_strava_data_deleted_notification(user_id, db)

    deleted, (notification, ws_message) = _delete_strava_data(user_id, finish)
    notifications_integration.push_notification(user_id, notification, ws_message)
    logger.info(
        "Strava data deleted after revocation", extra=core_logger.context(user_id=user_id, deleted_activities=deleted)
    )
    return True

linked_user_ids

linked_user_ids(after_id, limit)

Page through the users who have linked Strava, 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/strava/service.py
264
265
266
267
268
269
270
271
272
273
274
275
def linked_user_ids(after_id: uuid.UUID | None, limit: int) -> list[uuid.UUID]:
    """Page through the users who have linked Strava, 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_strava_linked(after_id, limit, db)

revoked_user_ids_due

revoked_user_ids_due(after_id, limit)

Page through the users whose Strava data is due for deletion, 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 user ids whose access was revoked longer ago than the grace period, ascending.

Source code in backend/app/modules/strava/service.py
249
250
251
252
253
254
255
256
257
258
259
260
261
def revoked_user_ids_due(after_id: uuid.UUID | None, limit: int) -> list[uuid.UUID]:
    """Page through the users whose Strava data is due for deletion, 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 user ids whose access was revoked longer ago than the grace period, ascending.
    """
    cutoff = datetime.now(UTC) - timedelta(days=user_integrations_constants.STRAVA_REVOKED_DATA_GRACE_DAYS)
    with core_database.SessionLocal() as db:
        return user_integrations_integration.list_user_ids_with_strava_revoked_before(cutoff, after_id, limit, db)

set_client

set_client(user_id, credentials, verify_step_up, db, *, if_match)

Store the user's Strava API client id and secret after the user's step-up, and commit.

The step-up is verified, and committed so a spent backup code stays spent, before the client is touched.

Parameters:

Name Type Description Default
user_id UUID

The authenticated user.

required
credentials StravaClientCredentials

The Strava application's client id and secret, and the user's step-up.

required
verify_step_up StepUpVerifier

Verifies the step-up for the calling user.

required
db Session

Database session.

required
if_match str

The If-Match precondition.

required

Returns:

Type Description
int

The integrations' new version, which a later write echoes in If-Match.

Raises:

Type Description
StepUpFailedError

If the step-up does not verify.

NotFoundError

If the user has no integrations.

PreconditionFailedError

If the integrations changed since the client read them.

Source code in backend/app/modules/strava/service.py
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
def set_client(
    user_id: uuid.UUID,
    credentials: strava_schema.StravaClientCredentials,
    verify_step_up: identity_providers_contracts.StepUpVerifier,
    db: Session,
    *,
    if_match: str,
) -> int:
    """Store the user's Strava API client id and secret after the user's step-up, and commit.

    The step-up is verified, and committed so a spent backup code stays spent, before the client is touched.

    Args:
        user_id: The authenticated user.
        credentials: The Strava application's client id and secret, and the user's step-up.
        verify_step_up: Verifies the step-up for the calling user.
        db: Database session.
        if_match: The ``If-Match`` precondition.

    Returns:
        The integrations' new version, which a later write echoes in ``If-Match``.

    Raises:
        StepUpFailedError: If the step-up does not verify.
        NotFoundError: If the user has no integrations.
        PreconditionFailedError: If the integrations changed since the client read them.
    """
    verify_step_up(credentials.step_up, identity_providers_constants.StepUpAction.STRAVA_CLIENT_SET)
    db.commit()
    with core_etag.refuse_stale_write(
        db,
        "Strava client",
        lambda: user_integrations_integration.get_user_integrations(user_id, db) is not None,
        "User integrations not found",
    ):
        user_integrations_integration.set_strava_client(
            user_id, str(credentials.client_id), credentials.client_secret.get_secret_value(), db, if_match=if_match
        )
        jasil_audit.stage(
            db,
            strava_audit_actions.CLIENT_UPDATE,
            target_type="user",
            target_id=str(user_id),
            target_owner_id=str(user_id),
        )
        db.commit()
    logger.info("Strava client stored", extra=core_logger.context(user_id=user_id))
    integrations = user_integrations_integration.get_user_integrations(user_id, db)
    return integrations.version if integrations is not None else 1
unlink_account(user_id, rate_limits)

Disconnect the user's Strava account and delete what was imported from it.

Runs on a worker, never a request. The access token is refreshed first when it has expired or is about to, because Strava refuses to deauthorize with an expired one and the app would stay authorized in the user's Strava settings. Strava is then asked to revoke the authorization, with no database session open. A grant Strava already refused has nothing to revoke, and a refresh or deauthorization that fails otherwise is logged: the account is unlinked locally anyway. A rate-limited refresh is the exception, as it stops the unlink with nothing changed, so the account stays linked and a later attempt can still revoke it. The imported activities are deleted in batches, one transaction each, and the gear and the unlink then commit together last, so an interrupted unlink still finds the account linked and finishes when it runs again.

Parameters:

Name Type Description Default
user_id UUID

The user to unlink.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
bool

True once unlinked, False when Strava was not linked.

Raises:

Type Description
NotFoundError

When the user has no integrations row.

TooManyRequestsError

When Strava's rate limit is active, or another process is refreshing the token, so the unlink is deferred.

Source code in backend/app/modules/strava/service.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def unlink_account(user_id: uuid.UUID, rate_limits: strava_rate_limit_store.StravaRateLimitStore) -> bool:
    """Disconnect the user's Strava account and delete what was imported from it.

    Runs on a worker, never a request. The access token is refreshed first when it has expired or is about
    to, because Strava refuses to deauthorize with an expired one and the app would stay authorized in the
    user's Strava settings. Strava is then asked to revoke the authorization, with no database session
    open. A grant Strava already refused has nothing to revoke, and a refresh or deauthorization that fails
    otherwise is logged: the account is unlinked locally anyway. A rate-limited refresh is the exception, as
    it stops the unlink with nothing changed, so the account stays linked and a later attempt can still
    revoke it. The imported activities are deleted in batches, one transaction each, and the gear and the
    unlink then commit together last, so an interrupted unlink still finds the account linked and finishes
    when it runs again.

    Args:
        user_id: The user to unlink.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        True once unlinked, False when Strava was not linked.

    Raises:
        NotFoundError: When the user has no integrations row.
        TooManyRequestsError: When Strava's rate limit is active, or another process is refreshing the
            token, so the unlink is deferred.
    """
    with core_database.SessionLocal() as db:
        user_integrations = strava_client_service.fetch_user_integrations_and_validate_token(user_id, db)

    if user_integrations is None:
        logger.debug("Strava not linked, nothing to unlink", extra=core_logger.context(user_id=user_id))
        return False

    try:
        strava_client_service.refresh_user_strava_token(user_id, rate_limits)
        with core_database.SessionLocal() as db:
            refreshed = strava_client_service.fetch_user_integrations_and_validate_token(user_id, db)
        if refreshed is not None:
            strava_client_service.create_strava_client(refreshed).deauthorize()
    except strava_client_service.StravaTokenRejectedError:
        logger.info(
            "Strava already revoked the authorization, unlinking locally", extra=core_logger.context(user_id=user_id)
        )
    except (requests.RequestException, core_exceptions.CryptographyError, core_exceptions.DependencyFailedError) as err:
        logger.warning(
            "Strava refused the deauthorization, unlinking locally anyway",
            extra=core_logger.context(user_id=user_id),
            exc_info=err,
        )

    deleted, _ = _delete_strava_data(
        user_id, lambda _deleted, db: user_integrations_integration.unlink_strava_account(user_id, db)
    )
    logger.info("Strava unlinked", extra=core_logger.context(user_id=user_id, deleted_activities=deleted))
    return True

Activity sync

Strava activity sync: fetch a window, parse each activity with its streams and laps, and store it.

ParsedStravaActivity

Bases: TypedDict

A Strava activity converted for storage.

Attributes:

Name Type Description
activity_to_store ActivityCore

The activity to store.

stream_data list[StravaStreamEntry]

Its streams.

laps list[StravaLap] | None

Its laps, or None when Strava has none for it.

Source code in backend/app/modules/strava/activity_service.py
111
112
113
114
115
116
117
118
119
120
121
122
class ParsedStravaActivity(TypedDict):
    """A Strava activity converted for storage.

    Attributes:
        activity_to_store: The activity to store.
        stream_data: Its streams.
        laps: Its laps, or ``None`` when Strava has none for it.
    """

    activity_to_store: activity_contracts.ActivityCore
    stream_data: list[StravaStreamEntry]
    laps: list[StravaLap] | None

StravaLap

Bases: TypedDict

A Strava lap converted to the fields a stored lap has.

Attributes:

Name Type Description
start_time str

When the lap started, in local time, as YYYY-MM-DDTHH:MM:SS.

start_position_lat float | None

Latitude of the lap's first waypoint.

start_position_long float | None

Longitude of the lap's first waypoint.

end_position_lat float | None

Latitude of the lap's last waypoint.

end_position_long float | None

Longitude of the lap's last waypoint.

total_elapsed_time int | None

Elapsed time, in seconds.

total_timer_time int | None

Moving time, in seconds.

total_distance float | None

Distance, in meters.

avg_heart_rate int | None

Average heart rate.

max_heart_rate int | None

Maximum heart rate.

avg_cadence int | None

Average cadence, from the lap's cadence stream.

max_cadence int | None

Maximum cadence, from the lap's cadence stream.

avg_power int | None

Average power, from the lap's power stream.

max_power int | None

Maximum power, from the lap's power stream.

total_ascent int | None

Elevation gain, in meters, from the lap's elevation stream.

total_descent int | None

Elevation loss, in meters, from the lap's elevation stream.

normalized_power int | None

Normalized power, from the lap's power stream.

enhanced_avg_pace float | None

Average pace, in seconds per meter.

enhanced_avg_speed float | None

Average speed, in meters per second.

enhanced_max_pace float | None

Pace at the maximum speed, in seconds per meter.

enhanced_max_speed float | None

Maximum speed, in meters per second.

Source code in backend/app/modules/strava/activity_service.py
 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
class StravaLap(TypedDict):
    """A Strava lap converted to the fields a stored lap has.

    Attributes:
        start_time: When the lap started, in local time, as ``YYYY-MM-DDTHH:MM:SS``.
        start_position_lat: Latitude of the lap's first waypoint.
        start_position_long: Longitude of the lap's first waypoint.
        end_position_lat: Latitude of the lap's last waypoint.
        end_position_long: Longitude of the lap's last waypoint.
        total_elapsed_time: Elapsed time, in seconds.
        total_timer_time: Moving time, in seconds.
        total_distance: Distance, in meters.
        avg_heart_rate: Average heart rate.
        max_heart_rate: Maximum heart rate.
        avg_cadence: Average cadence, from the lap's cadence stream.
        max_cadence: Maximum cadence, from the lap's cadence stream.
        avg_power: Average power, from the lap's power stream.
        max_power: Maximum power, from the lap's power stream.
        total_ascent: Elevation gain, in meters, from the lap's elevation stream.
        total_descent: Elevation loss, in meters, from the lap's elevation stream.
        normalized_power: Normalized power, from the lap's power stream.
        enhanced_avg_pace: Average pace, in seconds per meter.
        enhanced_avg_speed: Average speed, in meters per second.
        enhanced_max_pace: Pace at the maximum speed, in seconds per meter.
        enhanced_max_speed: Maximum speed, in meters per second.
    """

    start_time: str
    start_position_lat: float | None
    start_position_long: float | None
    end_position_lat: float | None
    end_position_long: float | None
    total_elapsed_time: int | None
    total_timer_time: int | None
    total_distance: float | None
    avg_heart_rate: int | None
    max_heart_rate: int | None
    avg_cadence: int | None
    max_cadence: int | None
    avg_power: int | None
    max_power: int | None
    total_ascent: int | None
    total_descent: int | None
    normalized_power: int | None
    enhanced_avg_pace: float | None
    enhanced_avg_speed: float | None
    enhanced_max_pace: float | None
    enhanced_max_speed: float | None

fetch_and_process_activities_by_dates

fetch_and_process_activities_by_dates(strava_client, start_date, end_date, user_id, user_integrations, rate_limits)

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

Runs on a worker thread. The Strava round trips happen with no database session open; each activity then opens a short session of its own for the duplicate check, the lookups and the store.

Parameters:

Name Type Description Default
strava_client Client

A client authenticated as the user.

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
user_integrations UserIntegrationsRead

The user's integration settings.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
list[ActivityRead] | None

The activities stored from the window, or None when Strava returned nothing or the user is rate

list[ActivityRead] | None

limited.

Raises:

Type Description
DomainError

When Strava rejects the request, or the user or their privacy settings are missing.

Exception

The first failure of an activity, once the rest of the window was processed.

Source code in backend/app/modules/strava/activity_service.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def fetch_and_process_activities_by_dates(
    strava_client: Client,
    start_date: datetime,
    end_date: datetime,
    user_id: uuid.UUID,
    user_integrations: user_integrations_schema.UserIntegrationsRead,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> list[activity_schema.ActivityRead] | None:
    """Fetch a user's Strava activities in a window and store the new ones.

    Runs on a worker thread. The Strava round trips happen with no database
    session open; each activity then opens a short session of its own for the
    duplicate check, the lookups and the store.

    Args:
        strava_client: A client authenticated as the user.
        start_date: Start of the window.
        end_date: End of the window.
        user_id: The user the activities belong to.
        user_integrations: The user's integration settings.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        The activities stored from the window, or ``None`` when Strava returned nothing or the user is rate
        limited.

    Raises:
        DomainError: When Strava rejects the request, or the user or their privacy settings are missing.
        Exception: The first failure of an activity, once the rest of the window was processed.
    """
    client_id = strava_client_service.get_client_id(user_integrations)
    strava_client_service.raise_if_rate_limit_active(client_id, user_id, rate_limits)

    try:
        strava_activities = strava_client_service.call_strava(
            lambda client: list(client.get_activities(after=start_date, before=end_date)),
            strava_client,
            user_id,
            user_integrations,
            rate_limits,
        )
    except core_exceptions.DomainError:
        raise
    except Exception as err:
        strava_client_service.raise_if_rate_limited(err, client_id, rate_limits)
        logger.warning("Error fetching Strava activities", extra=core_logger.context(user_id=user_id), exc_info=err)
        raise core_exceptions.DependencyFailedError("Not able to fetch Strava activities") from err

    if not strava_activities:
        logger.debug(
            "No new Strava activities found", extra=core_logger.context(user_id=user_id, start_date=start_date)
        )
        return None

    with core_database.SessionLocal() as db:
        user = users_integration.get_user(user_id, db)
        if user is None:
            raise core_exceptions.NotFoundError("User not found")
        user_privacy_settings = users_privacy_settings_integration.get_privacy_settings(user.id, db)
        if user_privacy_settings is None:
            raise core_exceptions.NotFoundError("User privacy settings not found")
    # Fallback for activities with no GPS track (indoor rides, treadmill runs): prefer
    # the athlete's own timezone over the server's, which is meaningless on another continent.
    timezone = user.timezone or core_config.settings.TZ

    processed = activity_ingestion_integration.run_provider_window(
        strava_activities,
        lambda activity: process_activity(
            activity, user_id, user_privacy_settings, timezone, strava_client, user_integrations, rate_limits
        ),
        provider=strava_constants.PROVIDER_NAME,
        user_id=user_id,
        describe=lambda activity: {"strava_activity_id": activity.id},
        propagate=(core_exceptions.TooManyRequestsError, strava_client_service.StravaTokenRejectedError),
    )
    # An activity that was already stored is processed as None.
    return [stored for stored in processed if stored is not None]

fetch_and_process_activity_laps

fetch_and_process_activity_laps(strava_client, strava_activity_id, user_id, stream_data, user_integrations, rate_limits)

Fetch an activity's laps from Strava and derive each lap's metrics.

Parameters:

Name Type Description Default
strava_client Client

A client authenticated as the user.

required
strava_activity_id int

The Strava activity id.

required
user_id UUID

The user the activity belongs to.

required
stream_data list[StravaStreamEntry]

(is_set, stream_type, waypoints) tuples the lap metrics are cut from.

required
user_integrations UserIntegrationsRead

The user's integration settings.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
list[StravaLap] | None

The converted laps, or None when Strava has none for the activity.

Raises:

Type Description
TooManyRequestsError

When Strava's rate limit is active or was just hit.

DependencyFailedError

When Strava cannot return the laps.

Source code in backend/app/modules/strava/activity_service.py
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def fetch_and_process_activity_laps(
    strava_client: Client,
    strava_activity_id: int,
    user_id: uuid.UUID,
    stream_data: list[StravaStreamEntry],
    user_integrations: user_integrations_schema.UserIntegrationsRead,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> list[StravaLap] | None:
    """Fetch an activity's laps from Strava and derive each lap's metrics.

    Args:
        strava_client: A client authenticated as the user.
        strava_activity_id: The Strava activity id.
        user_id: The user the activity belongs to.
        stream_data: ``(is_set, stream_type, waypoints)`` tuples the lap metrics are cut from.
        user_integrations: The user's integration settings.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        The converted laps, or ``None`` when Strava has none for the activity.

    Raises:
        TooManyRequestsError: When Strava's rate limit is active or was just hit.
        DependencyFailedError: When Strava cannot return the laps.
    """
    client_id = strava_client_service.get_client_id(user_integrations)
    strava_client_service.raise_if_rate_limit_active(client_id, user_id, rate_limits)

    try:
        laps = strava_client_service.call_strava(
            lambda client: client.get_activity_laps(strava_activity_id),
            strava_client,
            user_id,
            user_integrations,
            rate_limits,
        )
    except core_exceptions.DomainError:
        raise
    except Exception as err:
        strava_client_service.raise_if_rate_limited(err, client_id, rate_limits)
        # Laps don't exist for some activities; import the activity without them.
        if strava_client_service.is_strava_not_found_error(err):
            logger.debug(
                "No laps found for Strava activity, continuing without laps",
                extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
            )
            return None
        raise core_exceptions.DependencyFailedError("Not able to fetch Strava activity laps") from err

    # Create an array to store the processed laps
    laps_processed: list[StravaLap] = []

    # Process the laps
    for lap in laps:
        # A lap is stored at its start time, so one Strava sent without it is left out.
        if lap.start_date_local is None:
            logger.warning(
                "Strava lap has no start time, skipping it",
                extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
            )
            continue

        cad_avg, cad_max = None, None
        power_avg, power_max = None, None
        np = None
        ele_gain, ele_loss = None, None

        # The stream indexes cut the lap out of the activity's streams; a lap without them has no stream metrics.
        filtered_stream_data: list[StravaStreamEntry] = (
            [
                (enabled, stream_id, waypoints[lap.start_index : lap.end_index + 1])
                for enabled, stream_id, waypoints in stream_data
                if enabled
            ]
            if lap.start_index is not None and lap.end_index is not None
            else []
        )

        lat_lon_stream = _lap_stream(filtered_stream_data, activity_streams_constants.STREAM_TYPE_MAP)

        cad_stream = _lap_stream(filtered_stream_data, activity_streams_constants.STREAM_TYPE_CADENCE)

        if cad_stream:
            avg, peak = activities_computation.calculate_avg_and_max(cad_stream, "cad")
            cad_avg, cad_max = round(avg), round(peak)

        power_stream = _lap_stream(filtered_stream_data, activity_streams_constants.STREAM_TYPE_POWER)

        if power_stream:
            avg, peak = activities_computation.calculate_avg_and_max(power_stream, "power")
            power_avg, power_max = round(avg), round(peak)
            np = activities_computation.calculate_np(power_stream)

        ele_stream = _lap_stream(filtered_stream_data, activity_streams_constants.STREAM_TYPE_ELEVATION)

        if ele_stream:
            ele_gain, ele_loss = activities_computation.compute_elevation_gain_and_loss(ele_stream)

        laps_processed.append(
            {
                "start_time": lap.start_date_local.strftime("%Y-%m-%dT%H:%M:%S"),
                "start_position_lat": (lat_lon_stream[0]["lat"] if lat_lon_stream else None),
                "start_position_long": (lat_lon_stream[0]["lon"] if lat_lon_stream else None),
                "end_position_lat": (lat_lon_stream[-1]["lat"] if lat_lon_stream else None),
                "end_position_long": (lat_lon_stream[-1]["lon"] if lat_lon_stream else None),
                "total_elapsed_time": lap.elapsed_time,
                "total_timer_time": lap.moving_time,
                "total_distance": lap.distance,
                "avg_heart_rate": (round(lap.average_heartrate) if lap.average_heartrate else None),
                "max_heart_rate": (round(lap.max_heartrate) if lap.max_heartrate else None),
                "avg_cadence": cad_avg,
                "max_cadence": cad_max,
                "avg_power": power_avg,
                "max_power": power_max,
                "total_ascent": round(ele_gain) if ele_gain is not None else None,
                "total_descent": round(ele_loss) if ele_loss is not None else None,
                "normalized_power": round(np) if np else None,
                "enhanced_avg_pace": (
                    1 / lap.average_speed if lap.average_speed != 0 and lap.average_speed is not None else None
                ),
                "enhanced_avg_speed": lap.average_speed,
                "enhanced_max_pace": (1 / lap.max_speed if lap.max_speed != 0 and lap.max_speed is not None else None),
                "enhanced_max_speed": lap.max_speed,
            }
        )

    # Return the processed laps
    return laps_processed

fetch_and_process_activity_streams

fetch_and_process_activity_streams(strava_client, strava_activity_id, user_id, user_integrations, rate_limits)

Fetch an activity's streams from Strava and convert them to waypoint lists.

Parameters:

Name Type Description Default
strava_client Client

A client authenticated as the user.

required
strava_activity_id int

The Strava activity id.

required
user_id UUID

The user the activity belongs to.

required
user_integrations UserIntegrationsRead

The user's integration settings.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
StravaStreams

A flat tuple of each stream's waypoints and whether it is present, ending

StravaStreams

with the pace waypoints. All empty when the activity has no streams.

Raises:

Type Description
TooManyRequestsError

When Strava's rate limit is active or was just hit.

DependencyFailedError

When Strava cannot return the streams.

Source code in backend/app/modules/strava/activity_service.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def fetch_and_process_activity_streams(
    strava_client: Client,
    strava_activity_id: int,
    user_id: uuid.UUID,
    user_integrations: user_integrations_schema.UserIntegrationsRead,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> StravaStreams:
    """Fetch an activity's streams from Strava and convert them to waypoint lists.

    Args:
        strava_client: A client authenticated as the user.
        strava_activity_id: The Strava activity id.
        user_id: The user the activity belongs to.
        user_integrations: The user's integration settings.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        A flat tuple of each stream's waypoints and whether it is present, ending
        with the pace waypoints. All empty when the activity has no streams.

    Raises:
        TooManyRequestsError: When Strava's rate limit is active or was just hit.
        DependencyFailedError: When Strava cannot return the streams.
    """
    client_id = strava_client_service.get_client_id(user_integrations)
    strava_client_service.raise_if_rate_limit_active(client_id, user_id, rate_limits)

    try:
        streams = strava_client_service.call_strava(
            lambda client: client.get_activity_streams(
                strava_activity_id,
                types=[
                    "latlng",
                    "altitude",
                    "time",
                    "heartrate",
                    "cadence",
                    "watts",
                    "velocity_smooth",
                ],
            ),
            strava_client,
            user_id,
            user_integrations,
            rate_limits,
        )
    except core_exceptions.DomainError:
        raise
    except Exception as err:
        strava_client_service.raise_if_rate_limited(err, client_id, rate_limits)
        # Streams simply don't exist for some activities (e.g. manually added ones from
        # Apple Health have no GPS/sensor streams); import the activity without them.
        if strava_client_service.is_strava_not_found_error(err):
            logger.debug(
                "No streams found for Strava activity (no sensor data), continuing without streams",
                extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
            )
            return ([], False, [], False, [], False, [], False, [], False, [], False, [])
        raise core_exceptions.DependencyFailedError("Not able to fetch Strava activity streams") from err

    def stream_data(name: str) -> list[float]:
        """Return a stream's values, or an empty list when Strava sent no such stream.

        Args:
            name: The stream's name, one whose values are numbers.

        Returns:
            The stream's values.
        """
        return list(streams[name].data or []) if name in streams else []

    time = stream_data("time")

    def waypoints(name: str, key: str) -> list[StravaWaypoint]:
        """Pair a stream's values with the time stream.

        Args:
            name: The stream's name, one whose values are numbers.
            key: The waypoint key each value is stored under.

        Returns:
            The waypoints, one per timestamp that has a value.
        """
        # A stream longer than the time stream has no timestamp for its extra points.
        return [{"time": t, key: value} for t, value in zip(time, stream_data(name), strict=False)]

    # Each ``latlng`` value is a ``[lat, lon]`` pair rather than a number.
    lat_lon_values: list[list[float]] = list(streams["latlng"].data or []) if "latlng" in streams else []
    lat_lon_waypoints: list[StravaWaypoint] = [
        {"time": t, "lat": value[0], "lon": value[1]} for t, value in zip(time, lat_lon_values, strict=False)
    ]
    ele_waypoints = waypoints("altitude", "ele")
    hr_waypoints = waypoints("heartrate", "hr")
    cad_waypoints = waypoints("cadence", "cad")
    power_waypoints = waypoints("watts", "power")
    vel_waypoints = waypoints("velocity_smooth", "vel")
    # Pace is derived from velocity; a standstill has pace 0.
    pace_waypoints: list[StravaWaypoint] = [
        {"time": point["time"], "pace": 1 / point["vel"] if point["vel"] != 0 else 0} for point in vel_waypoints
    ]

    return (
        lat_lon_waypoints,
        bool(lat_lon_waypoints),
        ele_waypoints,
        bool(ele_waypoints),
        hr_waypoints,
        bool(hr_waypoints),
        cad_waypoints,
        bool(cad_waypoints),
        power_waypoints,
        bool(power_waypoints),
        vel_waypoints,
        bool(vel_waypoints),
        pace_waypoints,
    )

get_user_strava_activities_by_dates

get_user_strava_activities_by_dates(user_id, start_date, end_date, rate_limits)

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

Refreshes the user's access token first when it is about to expire, so the scheduled per-user refresh also keeps tokens current and no separate pass over every user is needed.

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 StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
list[ActivityRead] | None

The activities stored from the window, or None when Strava is not linked or nothing came back.

Raises:

Type Description
DomainError

When Strava rejects the request or the account is missing.

Source code in backend/app/modules/strava/activity_service.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
def get_user_strava_activities_by_dates(
    user_id: uuid.UUID,
    start_date: datetime,
    end_date: datetime,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> list[activity_schema.ActivityRead] | None:
    """Fetch and store one user's Strava activities recorded in a window.

    Refreshes the user's access token first when it is about to expire, so the
    scheduled per-user refresh also keeps tokens current and no separate pass over
    every user is needed.

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

    Returns:
        The activities stored from the window, or ``None`` when Strava is not linked or nothing came back.

    Raises:
        DomainError: When Strava rejects the request or the account is missing.
    """
    strava_client_service.refresh_user_strava_token(user_id, rate_limits)

    with core_database.SessionLocal() as db:
        user_integrations = strava_client_service.fetch_user_integrations_and_validate_token(user_id, db)

    if user_integrations is None:
        logger.debug("Strava not linked", extra=core_logger.context(user_id=user_id))
        return None

    logger.info("Started Strava activities processing", extra=core_logger.context(user_id=user_id))
    strava_client = strava_client_service.create_strava_client(user_integrations)
    processed = fetch_and_process_activities_by_dates(
        strava_client, start_date, end_date, user_id, user_integrations, rate_limits
    )

    logger.info(
        "Strava activities processed",
        extra=core_logger.context(user_id=user_id, count=len(processed or [])),
    )
    return processed

parse_activity

parse_activity(activity, user_id, user_privacy_settings, timezone, strava_client, user_integrations, rate_limits)

Fetch one Strava activity in detail and convert it for storage.

Parameters:

Name Type Description Default
activity SummaryActivity

The Strava summary activity.

required
user_id UUID

The user the activity belongs to.

required
user_privacy_settings UserPrivacySettingsRead

The user's privacy defaults.

required
timezone str

The timezone for an activity with no GPS track.

required
strava_client Client

A client authenticated as the user.

required
user_integrations UserIntegrationsRead

The user's integration settings.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
ParsedStravaActivity

The activity to store, its stream data and its laps.

Raises:

Type Description
TooManyRequestsError

When Strava's rate limit is active or was just hit.

DependencyFailedError

When Strava cannot return the activity, or returns it without an id, start date, sport type or elapsed time.

Source code in backend/app/modules/strava/activity_service.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
def parse_activity(
    activity: SummaryActivity,
    user_id: uuid.UUID,
    user_privacy_settings: users_privacy_settings_schema.UserPrivacySettingsRead,
    timezone: str,
    strava_client: Client,
    user_integrations: user_integrations_schema.UserIntegrationsRead,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> ParsedStravaActivity:
    """Fetch one Strava activity in detail and convert it for storage.

    Args:
        activity: The Strava summary activity.
        user_id: The user the activity belongs to.
        user_privacy_settings: The user's privacy defaults.
        timezone: The timezone for an activity with no GPS track.
        strava_client: A client authenticated as the user.
        user_integrations: The user's integration settings.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        The activity to store, its stream data and its laps.

    Raises:
        TooManyRequestsError: When Strava's rate limit is active or was just hit.
        DependencyFailedError: When Strava cannot return the activity, or returns it without an id, start date,
            sport type or elapsed time.
    """
    strava_activity_id = _strava_activity_id(activity, user_id)
    client_id = strava_client_service.get_client_id(user_integrations)
    strava_client_service.raise_if_rate_limit_active(client_id, user_id, rate_limits)

    try:
        detailed_activity = strava_client_service.call_strava(
            lambda client: client.get_activity(strava_activity_id),
            strava_client,
            user_id,
            user_integrations,
            rate_limits,
        )
    except core_exceptions.DomainError:
        raise
    except Exception as err:
        strava_client_service.raise_if_rate_limited(err, client_id, rate_limits)
        raise core_exceptions.DependencyFailedError("Not able to fetch Strava activity") from err

    # Parse start and end dates
    start_date_parsed = core_timezone.to_utc_second(detailed_activity.start_date)
    if start_date_parsed is None:
        # stravalib types start_date as optional; without it there is nothing to
        # anchor the activity to, and every downstream consumer (dedup by start
        # time, end-time derivation) requires it.
        logger.warning(
            "Strava activity has no start date, skipping",
            extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
        )
        raise core_exceptions.DependencyFailedError("Strava activity has no start date")

    # stravalib types sport_type as optional too; without it the activity has no type to be stored as.
    if detailed_activity.sport_type is None:
        logger.warning(
            "Strava activity has no sport type, skipping",
            extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
        )
        raise core_exceptions.DependencyFailedError("Strava activity has no sport type")
    sport_type = detailed_activity.sport_type.root

    # Without an elapsed time the activity has no end to be stored with.
    if detailed_activity.elapsed_time is None:
        logger.warning(
            "Strava activity has no elapsed time, skipping",
            extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
        )
        raise core_exceptions.DependencyFailedError("Strava activity has no elapsed time")

    # Ensure activity.elapsed_time is a numerical value
    total_elapsed_time = (
        detailed_activity.elapsed_time.total_seconds()
        if isinstance(detailed_activity.elapsed_time, timedelta)
        else detailed_activity.elapsed_time
    )

    total_timer_time = (
        detailed_activity.moving_time.total_seconds()
        if isinstance(detailed_activity.moving_time, timedelta)
        else detailed_activity.moving_time
    )

    end_date_parsed = start_date_parsed + timedelta(seconds=total_elapsed_time)

    # Initialize location variables
    city, town, country = None, None, None
    if detailed_activity.location_city is not None:
        city = detailed_activity.location_city
    if detailed_activity.location_state is not None:
        town = detailed_activity.location_state
    if detailed_activity.location_country is not None:
        country = detailed_activity.location_country

    # Fetch and process activity streams
    (
        lat_lon_waypoints,
        is_lat_lon_set,
        ele_waypoints,
        is_elevation_set,
        hr_waypoints,
        is_heart_rate_set,
        cad_waypoints,
        is_cadence_set,
        power_waypoints,
        is_power_set,
        vel_waypoints,
        is_velocity_set,
        pace_waypoints,
    ) = fetch_and_process_activity_streams(
        strava_client,
        strava_activity_id,
        user_id,
        user_integrations,
        rate_limits,
    )

    ele_gain, ele_loss = None, None
    # Calculate elevation gain and loss
    if ele_waypoints:
        ele_gain, ele_loss = activities_computation.compute_elevation_gain_and_loss(ele_waypoints)

        if detailed_activity.total_elevation_gain is not None:
            ele_gain = round(detailed_activity.total_elevation_gain)

    # Get average and max speed
    avg_speed = None
    if detailed_activity.average_speed is not None:
        avg_speed = detailed_activity.average_speed

    max_speed = None
    if detailed_activity.max_speed is not None:
        max_speed = detailed_activity.max_speed

    # Calculate average pace
    average_pace = 1 / avg_speed if avg_speed else None

    avg_hr, max_hr = None, None
    # Get average and max heart rate
    if detailed_activity.average_heartrate is not None:
        avg_hr = detailed_activity.average_heartrate

    if detailed_activity.max_heartrate is not None:
        max_hr = detailed_activity.max_heartrate

    avg_cadence, max_cadence = None, None
    # Calculate average and maximum cadence
    if cad_waypoints:
        avg_cadence, max_cadence = activities_computation.calculate_avg_and_max(cad_waypoints, "cad")

        if detailed_activity.average_cadence is not None:
            avg_cadence = detailed_activity.average_cadence

    activity_type = activity_constants.define_activity_type(sport_type)
    if activity_constants.is_running_cadence_type(activity_type):
        avg_cadence = activities_computation.double_running_cadence(avg_cadence)
        max_cadence = activities_computation.double_running_cadence(max_cadence)
        cad_waypoints = [{**point, "cad": round(point["cad"] * 2)} for point in cad_waypoints]

    # Get average and max power
    avg_power = None
    if detailed_activity.average_watts is not None:
        avg_power = detailed_activity.average_watts

    max_power = None
    if detailed_activity.max_watts is not None:
        max_power = detailed_activity.max_watts

    # Calculate normalized power
    np = None
    if power_waypoints:
        np = activities_computation.calculate_np(power_waypoints)

    # List of conditions, stream types, and corresponding waypoints
    stream_data: list[StravaStreamEntry] = [
        (is_heart_rate_set, activity_streams_constants.STREAM_TYPE_HR, hr_waypoints),
        (is_power_set, activity_streams_constants.STREAM_TYPE_POWER, power_waypoints),
        (is_cadence_set, activity_streams_constants.STREAM_TYPE_CADENCE, cad_waypoints),
        (is_elevation_set, activity_streams_constants.STREAM_TYPE_ELEVATION, ele_waypoints),
        (is_velocity_set, activity_streams_constants.STREAM_TYPE_SPEED, vel_waypoints),
        (is_velocity_set, activity_streams_constants.STREAM_TYPE_PACE, pace_waypoints),
        (detailed_activity.start_latlng is not None, activity_streams_constants.STREAM_TYPE_MAP, lat_lon_waypoints),
    ]

    gear_id: uuid.UUID | None = None

    if user_integrations.strava_sync_gear and detailed_activity.gear_id is not None:
        # set the gear id for the activity
        with core_database.SessionLocal() as db:
            gear = gears_integration.get_gear_by_strava_id(detailed_activity.gear_id, user_id, db)

        # set the gear id for the activity
        if gear is not None:
            gear_id = gear.id

    if gear_id is None:
        with core_database.SessionLocal() as db:
            gear_id = users_default_gear_integration.get_default_gear_for_activity_type(user_id, activity_type, db)

    if activity_type != 3 and activity_type != 7 and is_lat_lon_set:
        timezone = core_timezone.from_lat_lon(
            lat_lon_waypoints[0]["lat"],
            lat_lon_waypoints[0]["lon"],
            timezone,
        )

    # Create the activity object
    activity_to_store = activity_contracts.ActivityCore(
        user_id=user_id,
        name=detailed_activity.name or activity_constants.DEFAULT_ACTIVITY_NAME,
        distance=round(detailed_activity.distance) if detailed_activity.distance else 0,
        description=detailed_activity.description,
        activity_type=activity_constants.ActivityType.from_stored(activity_type),
        start_time=start_date_parsed,
        end_time=end_date_parsed,
        timezone=timezone,
        total_elapsed_time=total_elapsed_time,
        total_timer_time=total_timer_time,
        city=city,
        town=town,
        country=country,
        elevation_gain=round(ele_gain) if ele_gain else None,
        elevation_loss=round(ele_loss) if ele_loss else None,
        pace=average_pace,
        average_speed=avg_speed,
        max_speed=max_speed,
        average_power=round(avg_power) if avg_power else None,
        max_power=max_power,
        normalized_power=round(np) if np else None,
        average_hr=round(avg_hr) if avg_hr else None,
        max_hr=max_hr,
        average_cad=round(avg_cadence) if avg_cadence else None,
        max_cad=round(max_cadence) if max_cadence else None,
        calories=round(detailed_activity.calories) if detailed_activity.calories is not None else None,
        gear_id=gear_id,
        strava_gear_id=detailed_activity.gear_id,
        strava_activity_id=strava_activity_id,
        visibility=users_privacy_settings_integration.resolve_visibility(
            user_privacy_settings.default_activity_visibility
        ),
        hide_start_time=user_privacy_settings.hide_activity_start_time or False,
        hide_location=user_privacy_settings.hide_activity_location or False,
        hide_map=user_privacy_settings.hide_activity_map or False,
        hide_hr=user_privacy_settings.hide_activity_hr or False,
        hide_power=user_privacy_settings.hide_activity_power or False,
        hide_cadence=user_privacy_settings.hide_activity_cadence or False,
        hide_elevation=user_privacy_settings.hide_activity_elevation or False,
        hide_speed=user_privacy_settings.hide_activity_speed or False,
        hide_pace=user_privacy_settings.hide_activity_pace or False,
        hide_laps=user_privacy_settings.hide_activity_laps or False,
        hide_workout_sets_steps=user_privacy_settings.hide_activity_workout_sets_steps or False,
        hide_gear=user_privacy_settings.hide_activity_gear or False,
    )

    # Fetch and process activity laps
    laps = fetch_and_process_activity_laps(
        strava_client,
        strava_activity_id,
        user_id,
        stream_data,
        user_integrations,
        rate_limits,
    )

    # Return the activity and stream data
    return {
        "activity_to_store": activity_to_store,
        "stream_data": stream_data,
        "laps": laps,
    }

process_activity

process_activity(activity, user_id, user_privacy_settings, timezone, strava_client, user_integrations, rate_limits)

Parse one Strava activity and store it, unless it is already stored.

The Strava calls inside :func:parse_activity run with no session open. The duplicate check and the store each use a short session, and the store publishes activity.created on this worker thread, where its subscribers run inline without touching the request path. The store is idempotent on the activity's dedup_key, so two workers racing on one activity store it once.

Parameters:

Name Type Description Default
activity SummaryActivity

The Strava summary activity.

required
user_id UUID

The user the activity belongs to.

required
user_privacy_settings UserPrivacySettingsRead

The user's privacy defaults.

required
timezone str

The timezone for an activity with no GPS track.

required
strava_client Client

A client authenticated as the user.

required
user_integrations UserIntegrationsRead

The user's integration settings.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
ActivityRead | None

The stored activity, or None when it was already stored.

Raises:

Type Description
DependencyFailedError

When Strava sent the activity without an id.

Source code in backend/app/modules/strava/activity_service.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def process_activity(
    activity: SummaryActivity,
    user_id: uuid.UUID,
    user_privacy_settings: users_privacy_settings_schema.UserPrivacySettingsRead,
    timezone: str,
    strava_client: Client,
    user_integrations: user_integrations_schema.UserIntegrationsRead,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> activity_schema.ActivityRead | None:
    """Parse one Strava activity and store it, unless it is already stored.

    The Strava calls inside :func:`parse_activity` run with no session open. The
    duplicate check and the store each use a short session, and the store
    publishes ``activity.created`` on this worker thread, where its subscribers
    run inline without touching the request path. The store is idempotent on the
    activity's ``dedup_key``, so two workers racing on one activity store it once.

    Args:
        activity: The Strava summary activity.
        user_id: The user the activity belongs to.
        user_privacy_settings: The user's privacy defaults.
        timezone: The timezone for an activity with no GPS track.
        strava_client: A client authenticated as the user.
        user_integrations: The user's integration settings.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        The stored activity, or ``None`` when it was already stored.

    Raises:
        DependencyFailedError: When Strava sent the activity without an id.
    """
    strava_activity_id = _strava_activity_id(activity, user_id)
    with core_database.SessionLocal() as db:
        already_stored = activity_integration.get_activity_by_strava_id(strava_activity_id, user_id, db) is not None
    if already_stored:
        logger.debug(
            "Strava activity already exists, skipping",
            extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
        )
        return None

    logger.debug(
        "Strava activity will be processed",
        extra=core_logger.context(user_id=user_id, strava_activity_id=strava_activity_id),
    )

    parsed_activity = parse_activity(
        activity, user_id, user_privacy_settings, timezone, strava_client, user_integrations, rate_limits
    )

    with core_database.SessionLocal() as db:
        return save_activity_streams_laps(
            parsed_activity["activity_to_store"],
            parsed_activity["stream_data"],
            parsed_activity["laps"],
            db,
        )

save_activity_streams_laps

save_activity_streams_laps(activity, stream_data, laps, db)

Persist a Strava-parsed activity through the canonical ingestion seam.

Strava is a thin adapter: it builds the format-agnostic :class:~modules.activities.activity.schema.ParsedActivity from the parse result and delegates persistence + activity.created publication to :func:~modules.activities.activity.activity_integration.store_parsed_activity, instead of calling create_activity and the stream/lap CRUD directly. The notification, thumbnail, and HR-zone subscribers react to the published event.

Parameters:

Name Type Description Default
activity ActivityCore

The parsed Strava activity to persist.

required
stream_data list[StravaStreamEntry]

(is_set, stream_type, waypoints) tuples; only set streams are persisted.

required
laps list[StravaLap] | None

Parsed lap dicts, or None when the activity has no laps.

required
db Session

Database session.

required

Returns:

Type Description
ActivityRead

The created activity schema.

Source code in backend/app/modules/strava/activity_service.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
def save_activity_streams_laps(
    activity: activity_contracts.ActivityCore,
    stream_data: list[StravaStreamEntry],
    laps: list[StravaLap] | None,
    db: Session,
) -> activity_schema.ActivityRead:
    """Persist a Strava-parsed activity through the canonical ingestion seam.

    Strava is a thin adapter: it builds the
    format-agnostic :class:`~modules.activities.activity.schema.ParsedActivity`
    from the parse result and delegates persistence + ``activity.created``
    publication to
    :func:`~modules.activities.activity.activity_integration.store_parsed_activity`,
    instead of calling ``create_activity`` and the stream/lap CRUD directly. The
    notification, thumbnail, and HR-zone subscribers react to the published event.

    Args:
        activity: The parsed Strava activity to persist.
        stream_data: ``(is_set, stream_type, waypoints)`` tuples; only set streams
            are persisted.
        laps: Parsed lap dicts, or ``None`` when the activity has no laps.
        db: Database session.

    Returns:
        The created activity schema.
    """
    parsed_streams = [
        activity_streams_contracts.ParsedStream(
            stream_type=stream_type,
            stream_waypoints=(
                activities_computation.smooth_elevation_stream(waypoints)
                if stream_type == activity_streams_constants.STREAM_TYPE_ELEVATION
                else waypoints
            ),
        )
        for is_set, stream_type, waypoints in (stream_data or [])
        if is_set
    ]
    parsed = activity_contracts.ParsedActivity(
        activity=activity,
        components={"streams": parsed_streams, "laps": laps},
        source=activity_contracts.ImportSource(
            kind="strava",
            provider_activity_id=activity.strava_activity_id,
            dedup_key=(f"strava:{activity.strava_activity_id}" if activity.strava_activity_id is not None else None),
        ),
    )

    # Persist + publish ``activity.created`` via the canonical seam. The seam marks
    # duplicate start times hidden and forwards that to the notification subscriber.
    stored = activity_integration.store_parsed_activity(parsed, db)
    db.commit()
    logger.debug(
        "Strava activity stored",
        extra=core_logger.context(user_id=activity.user_id, strava_activity_id=activity.strava_activity_id),
    )
    return stored

Gear sync

Strava gear: syncing the athlete's gear and importing a Strava export's gear CSVs.

get_user_gear

get_user_gear(user_id, rate_limits)

Import the user's Strava gear and assign it to their activities.

Runs on a worker. The Strava round trips happen with no database session open; the new gear, the gear-sync preference and the activity assignments are then written in one short transaction, so a failed sync leaves nothing half done.

Parameters:

Name Type Description Default
user_id UUID

The user whose gear to import.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
bool

True once synced, False when Strava is not linked.

Raises:

Type Description
TooManyRequestsError

When Strava's rate limit is active or was just hit.

DependencyFailedError

When Strava cannot return the gear, or returns a piece without an id or name.

Source code in backend/app/modules/strava/gear_service.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def get_user_gear(user_id: uuid.UUID, rate_limits: strava_rate_limit_store.StravaRateLimitStore) -> bool:
    """Import the user's Strava gear and assign it to their activities.

    Runs on a worker. The Strava round trips happen with no database session open;
    the new gear, the gear-sync preference and the activity assignments are then
    written in one short transaction, so a failed sync leaves nothing half done.

    Args:
        user_id: The user whose gear to import.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        True once synced, False when Strava is not linked.

    Raises:
        TooManyRequestsError: When Strava's rate limit is active or was just hit.
        DependencyFailedError: When Strava cannot return the gear, or returns a piece without an id or name.
    """
    strava_client_service.refresh_user_strava_token(user_id, rate_limits)

    with core_database.SessionLocal() as db:
        user_integrations = strava_client_service.fetch_user_integrations_and_validate_token(user_id, db)
    if user_integrations is None:
        logger.debug("Strava not linked, skipping the gear sync", extra=core_logger.context(user_id=user_id))
        return False

    logger.info("Started Strava gear processing", extra=core_logger.context(user_id=user_id))
    client_id = strava_client_service.get_client_id(user_integrations)
    strava_client: Client = strava_client_service.create_strava_client(user_integrations)

    athlete = _call_strava(
        lambda client: client.get_athlete(),
        strava_client,
        "Strava athlete",
        client_id,
        user_id,
        user_integrations,
        rate_limits,
    )
    summaries = [(gears_schema.GearType.BIKE, _strava_gear_id(gear, user_id)) for gear in athlete.bikes or []] + [
        (gears_schema.GearType.SHOES, _strava_gear_id(gear, user_id)) for gear in athlete.shoes or []
    ]

    with core_database.SessionLocal() as db:
        new_summaries = [
            (gear_type, gear_id)
            for gear_type, gear_id in summaries
            if gears_integration.get_gear_by_strava_id(gear_id, user_id, db) is None
        ]

    new_gear = []
    for gear_type, strava_gear_id in new_summaries:
        strava_gear = _call_strava(
            functools.partial(_get_gear, strava_gear_id),
            strava_client,
            "Strava gear",
            client_id,
            user_id,
            user_integrations,
            rate_limits,
        )
        # stravalib types the name as optional too; without it the gear has no nickname to be stored with.
        if strava_gear.name is None:
            logger.warning("Strava gear has no name", extra=core_logger.context(user_id=user_id))
            raise core_exceptions.DependencyFailedError("Strava gear has no name")
        new_gear.append(
            gears_schema.GearCreate(
                brand=strava_gear.brand_name,
                model=strava_gear.model_name,
                nickname=strava_gear.name,
                gear_type=gear_type,
                user_id=user_id,
                active=True,
                strava_gear_id=strava_gear_id,
            )
        )

    with core_database.SessionLocal() as db:
        gears_integration.create_multiple_gears(new_gear, user_id, db)
        user_integrations_integration.set_strava_sync_gear(user_id, True, db)
        assigned = set_activities_gear(user_id, db)
        db.commit()

    logger.info(
        "Strava gear processed",
        extra=core_logger.context(user_id=user_id, created=len(new_gear), activities_assigned=assigned),
    )
    return True

import_gear

import_gear(file, user_id, gear_type, db)

Create the bikes or shoes listed in an uploaded Strava gear CSV.

Parameters:

Name Type Description Default
file UploadFile

The uploaded CSV.

required
user_id UUID

The user the gear belongs to.

required
gear_type GearType

Which export file it is: bikes or shoes.

required
db Session

Database session.

required

Returns:

Type Description
int

The number of gear entries handed to the gear module.

Raises:

Type Description
InvalidInputError

When the file cannot be parsed or lacks the required columns.

Source code in backend/app/modules/strava/gear_service.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def import_gear(file: UploadFile, user_id: uuid.UUID, gear_type: gears_schema.GearType, db: Session) -> int:
    """Create the bikes or shoes listed in an uploaded Strava gear CSV.

    Args:
        file: The uploaded CSV.
        user_id: The user the gear belongs to.
        gear_type: Which export file it is: bikes or shoes.
        db: Database session.

    Returns:
        The number of gear entries handed to the gear module.

    Raises:
        InvalidInputError: When the file cannot be parsed or lacks the required columns.
    """
    work_dir, path = _save_gear_csv(file)
    try:
        rows = parse_gear_csv(path, gear_type)
        if gear_type == gears_schema.GearType.BIKE:
            gears = transform_csv_bike_gear_to_schema_gear(rows, user_id)
        else:
            gears = transform_csv_shoe_gear_to_schema_gear(rows, user_id, db)
        if gears:
            gears_integration.create_multiple_gears(gears, user_id, db)
            jasil_audit.stage(
                db,
                strava_audit_actions.GEAR_IMPORT,
                target_type="user",
                target_id=str(user_id),
                target_owner_id=str(user_id),
                details=strava_audit_actions.GearImportDetails(gear_type=_IMPORT_TYPES[gear_type], count=len(gears)),
            )
            db.commit()
        logger.info("Strava gear import complete", extra=core_logger.context(gear_type=gear_type, count=len(gears)))
        return len(gears)
    finally:
        work_dir.cleanup()

match_gear_for_activity

match_gear_for_activity(activity, gears)

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

Source code in backend/app/modules/strava/gear_service.py
126
127
128
129
130
131
132
133
134
135
136
def match_gear_for_activity(
    activity: activity_schema.ActivityRead,
    gears: list[gears_schema.GearRead],
) -> uuid.UUID | None:
    """Return the local gear ID matching this activity's Strava gear, else None."""
    if activity.strava_gear_id is None:
        return None
    for gear in gears:
        if activity.strava_gear_id == gear.strava_gear_id:
            return gear.id
    return None

parse_gear_csv

parse_gear_csv(path, gear_type)

Read a Strava gear CSV and check it has the columns its gear type needs.

Parameters:

Name Type Description Default
path str

Path of the uploaded CSV.

required
gear_type GearType

Which export file it is: bikes or shoes.

required

Returns:

Type Description
list[dict[str, str]]

One dictionary per data row, keyed by column header.

Raises:

Type Description
InvalidInputError

When the file cannot be parsed or lacks the required columns.

Source code in backend/app/modules/strava/gear_service.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def parse_gear_csv(path: str, gear_type: gears_schema.GearType) -> list[dict[str, str]]:
    """Read a Strava gear CSV and check it has the columns its gear type needs.

    Args:
        path: Path of the uploaded CSV.
        gear_type: Which export file it is: bikes or shoes.

    Returns:
        One dictionary per data row, keyed by column header.

    Raises:
        InvalidInputError: When the file cannot be parsed or lacks the required columns.
    """
    try:
        rows = list(core_text_imports.read_bounded_csv(path))
    except (csv.Error, UnicodeDecodeError) as err:
        logger.debug("Unreadable Strava gear CSV", extra=core_logger.context(gear_type=gear_type), exc_info=err)
        raise core_exceptions.InvalidInputError("The Strava gear CSV could not be parsed") from err

    required = _CSV_COLUMNS[gear_type]
    if rows and not set(required) <= rows[0].keys():
        logger.debug(
            "Strava gear import refused: required columns missing",
            extra=core_logger.context(gear_type=gear_type, required=required),
        )
        raise core_exceptions.InvalidInputError(f"Invalid file. Required columns not found: {', '.join(required)}")
    logger.info("Strava gear CSV parsed", extra=core_logger.context(gear_type=gear_type, row_count=len(rows)))
    return rows

set_activities_gear

set_activities_gear(user_id, db)

Stage the assignment of the user's Strava-linked activities to the matching local gear.

Parameters:

Name Type Description Default
user_id UUID

The user whose activities to update.

required
db Session

Database session; the caller commits.

required

Returns:

Type Description
int

The number of activities that were given gear.

Source code in backend/app/modules/strava/gear_service.py
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
def set_activities_gear(user_id: uuid.UUID, db: Session) -> int:
    """Stage the assignment of the user's Strava-linked activities to the matching local gear.

    Args:
        user_id: The user whose activities to update.
        db: Database session; the caller commits.

    Returns:
        The number of activities that were given gear.
    """
    gears = gears_integration.get_gear_user(user_id, db)
    if not gears:
        return 0

    # A page at a time, so a long history is never held in memory; only the matched ids are kept.
    gear_assignments: dict[uuid.UUID, uuid.UUID | None] = {}
    page_number = 1
    while page := activity_integration.list_user_activities_page(
        user_id, db, page_number=page_number, num_records=_ACTIVITY_PAGE_SIZE
    ):
        for activity in page:
            matched_gear_id = match_gear_for_activity(activity, gears)
            if matched_gear_id is not None:
                gear_assignments[activity.id] = matched_gear_id
        if len(page) < _ACTIVITY_PAGE_SIZE:
            break
        page_number += 1
    if not gear_assignments:
        return 0

    activity_integration.bulk_set_activities_gear(user_id, gear_assignments, db)
    logger.debug("Strava activities gear set", extra=core_logger.context(user_id=user_id, count=len(gear_assignments)))
    return len(gear_assignments)

transform_csv_bike_gear_to_schema_gear

transform_csv_bike_gear_to_schema_gear(rows, user_id)

Turn parsed bikes CSV rows into gear to create.

A bike is identified by its name, so the last of several rows with one name wins and a row without a name is skipped.

Parameters:

Name Type Description Default
rows list[dict[str, str]]

Parsed bikes.csv rows.

required
user_id UUID

The user the bikes belong to.

required

Returns:

Type Description
list[GearCreate]

The bikes to create.

Source code in backend/app/modules/strava/gear_service.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def transform_csv_bike_gear_to_schema_gear(
    rows: list[dict[str, str]], user_id: uuid.UUID
) -> list[gears_schema.GearCreate]:
    """Turn parsed bikes CSV rows into gear to create.

    A bike is identified by its name, so the last of several rows with one name wins
    and a row without a name is skipped.

    Args:
        rows: Parsed ``bikes.csv`` rows.
        user_id: The user the bikes belong to.

    Returns:
        The bikes to create.
    """
    name_column, brand_column, model_column = _CSV_COLUMNS[gears_schema.GearType.BIKE]
    by_name = {}
    for row in rows:
        name = _clean(row[name_column])
        if name is None:
            logger.warning("Skipping a bike without a name", extra=core_logger.context(user_id=user_id))
            continue
        by_name[name] = row
    return [
        gears_schema.GearCreate(
            user_id=user_id,
            brand=_clean(row[brand_column]),
            model=_clean(row[model_column]),
            nickname=name,
            gear_type=gears_schema.GearType.BIKE,
            active=True,
            strava_gear_id=None,
        )
        for name, row in by_name.items()
    ]

transform_csv_shoe_gear_to_schema_gear

transform_csv_shoe_gear_to_schema_gear(rows, user_id, db)

Turn parsed shoes CSV rows into gear to create.

Strava allows nameless shoes and Endurain does not, so each one gets the default name plus the next number not taken by the user's gear or an earlier shoe.

Parameters:

Name Type Description Default
rows list[dict[str, str]]

Parsed shoes.csv rows.

required
user_id UUID

The user the shoes belong to.

required
db Session

Database session.

required

Returns:

Type Description
list[GearCreate]

The shoes to create.

Source code in backend/app/modules/strava/gear_service.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def transform_csv_shoe_gear_to_schema_gear(
    rows: list[dict[str, str]], user_id: uuid.UUID, db: Session
) -> list[gears_schema.GearCreate]:
    """Turn parsed shoes CSV rows into gear to create.

    Strava allows nameless shoes and Endurain does not, so each one gets the default
    name plus the next number not taken by the user's gear or an earlier shoe.

    Args:
        rows: Parsed ``shoes.csv`` rows.
        user_id: The user the shoes belong to.
        db: Database session.

    Returns:
        The shoes to create.
    """
    name_column, brand_column, model_column = _CSV_COLUMNS[gears_schema.GearType.SHOES]
    taken = {gear.nickname for gear in gears_integration.get_gear_user(user_id, db)}
    next_number = 1
    renamed = 0
    shoes = []
    for row in rows:
        raw_name = row[name_column] or ""
        name = _clean(raw_name) if raw_name.replace("+", " ").strip() else None
        if name is None:
            while f"{strava_constants.UNNAMED_SHOE_NICKNAME_PREFIX}{next_number}" in taken:
                next_number += 1
            name = f"{strava_constants.UNNAMED_SHOE_NICKNAME_PREFIX}{next_number}"
            taken.add(name)
            renamed += 1
            logger.debug("Shoe name was blank, it has been renamed", extra=core_logger.context(nickname=name))
        shoes.append(
            gears_schema.GearCreate(
                user_id=user_id,
                brand=_clean(row[brand_column]),
                model=_clean(row[model_column]),
                nickname=name,
                gear_type=gears_schema.GearType.SHOES,
                active=True,
                strava_gear_id=None,
            )
        )
    if renamed:
        logger.info("Nameless Strava shoes were renamed", extra=core_logger.context(count=renamed))
    return shoes

Bulk import

The Strava-export specialisation of the bulk-import source, and its archive layout.

A Strava export is a folder of activity files plus an activities.csv manifest and a media directory. Three things follow from that, and all three are facts about Strava rather than about bulk import:

  • the manifest supplies names, descriptions and gear the exported files omit,
  • it lists a multi-activity .fit once per activity inside it, so importing every activity from every listing multiplies them (a 5-activity file becomes 25),
  • the photos ship next to the files rather than inside them.

Activities knows nothing about Strava: this module registers a :class:BulkImportFormat that says where the activity files are, where the user drops them, and how to build the source that answers those three questions.

StravaBulkImportSource dataclass

Bases: BulkImportSource

A file from a Strava bulk export.

Attributes:

Name Type Description
strava_activities StravaActivitiesManifest | None

Parsed Strava activities.csv, keyed by filename.

gear_nickname_to_id dict[str, list[UUID]] | None

Gear nickname -> internal gear id, used to resolve the gear named in the CSV.

read_member ArchiveMemberReader | None

Reads a member of the archive by name, to reach the photos.

Source code in backend/app/modules/strava/bulk_import_service.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
@dataclass(frozen=True)
class StravaBulkImportSource(activity_ingestion_integration.BulkImportSource):
    """A file from a Strava bulk export.

    Attributes:
        strava_activities: Parsed Strava ``activities.csv``, keyed by filename.
        gear_nickname_to_id: Gear nickname -> internal gear id, used to resolve
            the gear named in the CSV.
        read_member: Reads a member of the archive by name, to reach the photos.
    """

    strava_activities: StravaActivitiesManifest | None = None
    gear_nickname_to_id: dict[str, list[uuid.UUID]] | None = None
    read_member: activity_ingestion_integration.ArchiveMemberReader | None = None

    def metadata_for(self, file_base_name: str) -> dict[str, Any]:
        """Build the supplemental metadata from the matching ``activities.csv`` row.

        Args:
            file_base_name: The original (pre-decompression) base filename, which
                is the key into the ``activities.csv`` data.

        Returns:
            The metadata dict, empty when the import carries no start timestamp.
        """
        if not self.import_initiated_time:
            return {}
        if not self.strava_activities:
            return super().metadata_for(file_base_name)
        return build_metadata_dict(
            file_base_name,
            self.strava_activities,
            self.import_initiated_time,
            self.gear_nickname_to_id,
        )

    def should_import(
        self,
        activity: activity_contracts.ActivityCore,
        activity_metadata: dict[str, Any],
        *,
        activities_in_file: int,
    ) -> bool:
        """Whether one activity parsed from a multi-activity file should be imported.

        The ``activities.csv`` row identifies which activity inside the file this
        listing refers to, by start time; the others are duplicates of listings
        handled elsewhere in the run.

        Args:
            activity: The parsed activity under consideration.
            activity_metadata: Metadata from :meth:`metadata_for`.
            activities_in_file: How many activities the file yielded.

        Returns:
            ``True`` to import, ``False`` to skip as a duplicate listing.
        """
        if activities_in_file <= 1 or not self.strava_activities:
            return True
        if activity_metadata.get("metadata_found_in_csv") is not True:
            return True
        try:
            if does_activity_start_time_match_the_data_in_strava_activities_csv(activity, activity_metadata):
                return True
        except ValueError:
            # A date written in another language cannot be compared; importing may duplicate, skipping loses data.
            logger.warning(
                "Bulk file import: unreadable start date in activities.csv, importing the activity",
                extra=core_logger.context(console=True),
            )
            return True
        logger.debug(
            "Bulk activity import of multi-activity .fit file: skipping likely duplicate import. "
            "Start time does not align with start time for this .fit file in the Strava activities.csv file.",
            extra=core_logger.context(console=True),
        )
        return False

    def import_side_artifacts(
        self,
        created_activities: list[activity_schema.ActivityRead],
        file_base_name: str,
        db: Session,
    ) -> None:
        """Attach the photos the export ships alongside the activity file.

        Even a multi-activity ``.fit`` is handled correctly by attaching to the
        last created activity — a Strava export's activity directory holds one
        imported activity per file.

        Args:
            created_activities: Activities persisted from the file, in order.
            file_base_name: The file's original base name (the ``activities.csv``
                lookup key).
            db: Database session.
        """
        if not self.strava_activities or not created_activities or self.read_member is None:
            return
        import_media_from_strava_bulk_export(
            self.strava_activities,
            created_activities[-1],
            file_base_name,
            self.read_member,
            db,
        )

import_side_artifacts

import_side_artifacts(created_activities, file_base_name, db)

Attach the photos the export ships alongside the activity file.

Even a multi-activity .fit is handled correctly by attaching to the last created activity — a Strava export's activity directory holds one imported activity per file.

Parameters:

Name Type Description Default
created_activities list[ActivityRead]

Activities persisted from the file, in order.

required
file_base_name str

The file's original base name (the activities.csv lookup key).

required
db Session

Database session.

required
Source code in backend/app/modules/strava/bulk_import_service.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def import_side_artifacts(
    self,
    created_activities: list[activity_schema.ActivityRead],
    file_base_name: str,
    db: Session,
) -> None:
    """Attach the photos the export ships alongside the activity file.

    Even a multi-activity ``.fit`` is handled correctly by attaching to the
    last created activity — a Strava export's activity directory holds one
    imported activity per file.

    Args:
        created_activities: Activities persisted from the file, in order.
        file_base_name: The file's original base name (the ``activities.csv``
            lookup key).
        db: Database session.
    """
    if not self.strava_activities or not created_activities or self.read_member is None:
        return
    import_media_from_strava_bulk_export(
        self.strava_activities,
        created_activities[-1],
        file_base_name,
        self.read_member,
        db,
    )

metadata_for

metadata_for(file_base_name)

Build the supplemental metadata from the matching activities.csv row.

Parameters:

Name Type Description Default
file_base_name str

The original (pre-decompression) base filename, which is the key into the activities.csv data.

required

Returns:

Type Description
dict[str, Any]

The metadata dict, empty when the import carries no start timestamp.

Source code in backend/app/modules/strava/bulk_import_service.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def metadata_for(self, file_base_name: str) -> dict[str, Any]:
    """Build the supplemental metadata from the matching ``activities.csv`` row.

    Args:
        file_base_name: The original (pre-decompression) base filename, which
            is the key into the ``activities.csv`` data.

    Returns:
        The metadata dict, empty when the import carries no start timestamp.
    """
    if not self.import_initiated_time:
        return {}
    if not self.strava_activities:
        return super().metadata_for(file_base_name)
    return build_metadata_dict(
        file_base_name,
        self.strava_activities,
        self.import_initiated_time,
        self.gear_nickname_to_id,
    )

should_import

should_import(activity, activity_metadata, *, activities_in_file)

Whether one activity parsed from a multi-activity file should be imported.

The activities.csv row identifies which activity inside the file this listing refers to, by start time; the others are duplicates of listings handled elsewhere in the run.

Parameters:

Name Type Description Default
activity ActivityCore

The parsed activity under consideration.

required
activity_metadata dict[str, Any]

Metadata from :meth:metadata_for.

required
activities_in_file int

How many activities the file yielded.

required

Returns:

Type Description
bool

True to import, False to skip as a duplicate listing.

Source code in backend/app/modules/strava/bulk_import_service.py
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
def should_import(
    self,
    activity: activity_contracts.ActivityCore,
    activity_metadata: dict[str, Any],
    *,
    activities_in_file: int,
) -> bool:
    """Whether one activity parsed from a multi-activity file should be imported.

    The ``activities.csv`` row identifies which activity inside the file this
    listing refers to, by start time; the others are duplicates of listings
    handled elsewhere in the run.

    Args:
        activity: The parsed activity under consideration.
        activity_metadata: Metadata from :meth:`metadata_for`.
        activities_in_file: How many activities the file yielded.

    Returns:
        ``True`` to import, ``False`` to skip as a duplicate listing.
    """
    if activities_in_file <= 1 or not self.strava_activities:
        return True
    if activity_metadata.get("metadata_found_in_csv") is not True:
        return True
    try:
        if does_activity_start_time_match_the_data_in_strava_activities_csv(activity, activity_metadata):
            return True
    except ValueError:
        # A date written in another language cannot be compared; importing may duplicate, skipping loses data.
        logger.warning(
            "Bulk file import: unreadable start date in activities.csv, importing the activity",
            extra=core_logger.context(console=True),
        )
        return True
    logger.debug(
        "Bulk activity import of multi-activity .fit file: skipping likely duplicate import. "
        "Start time does not align with start time for this .fit file in the Strava activities.csv file.",
        extra=core_logger.context(console=True),
    )
    return False

build_import_dictionary

build_import_dictionary(file_base_name, import_initiated_time, strava_row=None)

Creates the "import_info" dictionary that is added to all activities that are imported from files.

Functions both for Strava imports and generic bulk imports, depending on whether strava_row is given.

Parameters:

Name Type Description Default
file_base_name str

The base filename being processed, named in the log of an invalid Strava activity id.

required
import_initiated_time str

ISO timestamp of when the bulk import was initiated.

required
strava_row dict[str, str] | None

The file's activities.csv row in a Strava export import, or None for a generic import.

None

Returns:

Type Description
dict[str, Any]

The import record stored on the activity as its import_info.

Source code in backend/app/modules/strava/bulk_import_service.py
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
def build_import_dictionary(
    file_base_name: str,
    import_initiated_time: str,
    strava_row: dict[str, str] | None = None,
) -> dict[str, Any]:
    """Creates the "import_info" dictionary that is added to all activities that are imported from files.

    Functions both for Strava imports and generic bulk imports, depending on whether ``strava_row`` is given.

    Args:
        file_base_name: The base filename being processed, named in the log of an invalid Strava activity id.
        import_initiated_time: ISO timestamp of when the bulk import was initiated.
        strava_row: The file's ``activities.csv`` row in a Strava export import, or ``None`` for a generic import.

    Returns:
        The import record stored on the activity as its ``import_info``.
    """
    if strava_row is None:
        return activity_ingestion_integration.build_import_record(import_initiated_time)

    import_dict = activity_ingestion_integration.build_import_record(import_initiated_time, "Strava bulk import")
    activity_id_value = strava_row.get("Activity ID", "")
    if activity_id_value:
        try:
            import_dict["strava_activity_id"] = int(activity_id_value)
        except (TypeError, ValueError):
            logger.warning(
                "Bulk file import: ignoring invalid Strava activity id",
                extra=core_logger.context(console=True, file_name=file_base_name),
            )
    return import_dict

build_metadata_dict

build_metadata_dict(file_base_name, strava_activities, import_initiated_time, users_existing_gear_nickname_to_id=None)

Creates a dictionary with metadata information pulled from a Strava activities file.

metadata_found_in_csv tells whether the activities.csv file had an entry for this activity.

Parameters:

Name Type Description Default
file_base_name str

The base filename being processed, also the key into strava_activities.

required
strava_activities StravaActivitiesManifest | None

The parsed activities.csv rows keyed by filename, then by column header.

required
import_initiated_time str

ISO timestamp of when the bulk import was initiated.

required
users_existing_gear_nickname_to_id dict[str, list[UUID]] | None

The user's gear ids by nickname, to resolve the gear the CSV names.

None

Returns:

Type Description
dict[str, Any]

The metadata found for the activity, always including its import_dict.

Source code in backend/app/modules/strava/bulk_import_service.py
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
def build_metadata_dict(
    file_base_name: str,
    strava_activities: StravaActivitiesManifest | None,
    import_initiated_time: str,
    users_existing_gear_nickname_to_id: dict[str, list[uuid.UUID]] | None = None,
) -> dict[str, Any]:
    """Creates a dictionary with metadata information pulled from a Strava activities file.

    ``metadata_found_in_csv`` tells whether the ``activities.csv`` file had an entry for this activity.

    Args:
        file_base_name: The base filename being processed, also the key into ``strava_activities``.
        strava_activities: The parsed ``activities.csv`` rows keyed by filename, then by column header.
        import_initiated_time: ISO timestamp of when the bulk import was initiated.
        users_existing_gear_nickname_to_id: The user's gear ids by nickname, to resolve the gear the CSV names.

    Returns:
        The metadata found for the activity, always including its ``import_dict``.
    """
    strava_activity_metadata: dict[str, Any] = {}
    row = strava_activities.get(file_base_name) if isinstance(strava_activities, dict) else None
    if not row:
        # In a Strava import but with no data on the file: just the basic import record.
        strava_activity_metadata["metadata_found_in_csv"] = False
        strava_activity_metadata["import_dict"] = build_import_dictionary(file_base_name, import_initiated_time)
        logger.debug(
            "Bulk file import: no data in activities.csv for activity",
            extra=core_logger.context(console=True, file_name=file_base_name),
        )
        return strava_activity_metadata

    # Importing the Strava activity id into ``strava_activity_id`` would make Endurain think the activity is
    # linked to Strava by the active linking mechanism, so it only goes in the import record. Media is
    # attached after the activity exists.
    strava_activity_metadata["name"] = row["Activity Name"]
    strava_activity_metadata["description"] = row["Activity Description"]
    strava_activity_metadata["activity type"] = row["Activity Type"]
    # Needed for checking for duplicates within multi-file .fit file Strava bulk imports
    strava_activity_metadata["activity date"] = row["Activity Date"]

    # Gear names in Endurain have all +'s swapped to spaces, thus the CSV's name needs the same.
    activity_gear = (row["Activity Gear"] or "").replace("+", " ").strip()
    gear_ids = (users_existing_gear_nickname_to_id or {}).get(activity_gear) if activity_gear else None
    strava_activity_metadata["gear_id"] = gear_ids[0] if gear_ids else None
    if activity_gear and not gear_ids:
        logger.debug(
            "Bulk file import: gear named in activities.csv not found, not adding gear to activity",
            extra=core_logger.context(console=True, file_name=file_base_name, gear=activity_gear),
        )

    strava_activity_metadata["import_dict"] = build_import_dictionary(file_base_name, import_initiated_time, row)
    strava_activity_metadata["metadata_found_in_csv"] = True
    logger.debug(
        "Bulk file import: activities.csv metadata extracted",
        extra=core_logger.context(console=True, file_name=file_base_name),
    )
    return strava_activity_metadata

create_activity_media_from_strava_bulk_import

create_activity_media_from_strava_bulk_import(activity_id, media_strava_filename, data, db)

Attaches a media file from a Strava export to an activity that was just imported.

The bytes are validated as an image through the unified upload pipeline before they are stored and become servable; a rejected file is logged and skipped so one bad photo does not fail the activity. A database or storage failure is not the photo's, so it propagates to the caller.

Parameters:

Name Type Description Default
activity_id UUID

The imported activity.

required
media_strava_filename str

The file's name in the export.

required
data bytes

The file's bytes.

required
db Session

Database session.

required
Source code in backend/app/modules/strava/bulk_import_service.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def create_activity_media_from_strava_bulk_import(
    activity_id: uuid.UUID,
    media_strava_filename: str,
    data: bytes,
    db: Session,
) -> None:
    """Attaches a media file from a Strava export to an activity that was just imported.

    The bytes are validated as an image through the unified upload pipeline before
    they are stored and become servable; a rejected file is logged and skipped so
    one bad photo does not fail the activity. A database or storage failure is not the
    photo's, so it propagates to the caller.

    Args:
        activity_id: The imported activity.
        media_strava_filename: The file's name in the export.
        data: The file's bytes.
        db: Database session.
    """
    try:
        with tempfile.TemporaryDirectory(prefix="strava-media-") as work_dir:
            path = os.path.join(work_dir, "media")
            with open(path, "wb") as handle:
                handle.write(data)
            try:
                file_uploads.validate_local_file_sync(
                    path, kind=file_uploads.UploadKind.IMAGE, filename=media_strava_filename
                )
            except core_exceptions.DomainError as err:
                logger.warning(
                    "Bulk file import: rejecting media file that failed image validation",
                    extra=core_logger.context(console=True, file_name=media_strava_filename, detail=err.detail),
                )
                return

        # The media module owns the storage key and area; this only supplies the
        # validated bytes, which keeps the photo reachable on object storage and
        # only through the token-gated route.
        activity_media_integration.attach_media_bytes(activity_id, media_strava_filename, data, db)
        logger.debug(
            "Bulk file import: media file imported",
            extra=core_logger.context(console=True, file_name=media_strava_filename),
        )
    except core_exceptions.DomainError as err:
        logger.warning(
            "Bulk file import: rejecting media file the media module refused",
            extra=core_logger.context(console=True, file_name=media_strava_filename, detail=err.detail),
        )

create_gear_dictionary_for_bulk_import

create_gear_dictionary_for_bulk_import(user_id, db)

Creates a dictionary that links gear nicknames in Endurain to their Endurain gear IDs.

The dictionary includes both base Endurain gear nickname and the gear name smoosh ("{brand} {model} {name}") that Strava uses for its shoe gear listing in activities.csv

Parameters:

Name Type Description Default
user_id UUID

The importing user.

required
db Session

Database session.

required

Returns:

Type Description
dict[str, list[UUID]]

Dictionary that uses the gear name as a key to look up the gear ID; empty

dict[str, list[UUID]]

when the user has no gear, which only means no activity is linked to one.

Source code in backend/app/modules/strava/bulk_import_service.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def create_gear_dictionary_for_bulk_import(user_id: uuid.UUID, db: Session) -> dict[str, list[uuid.UUID]]:
    """Creates a dictionary that links gear nicknames in Endurain to their Endurain gear IDs.

    The dictionary includes both base Endurain gear nickname and the gear name smoosh
    ("{brand} {model} {name}") that Strava uses for its shoe gear listing in activities.csv

    Args:
        user_id: The importing user.
        db: Database session.

    Returns:
        Dictionary that uses the gear name as a key to look up the gear ID; empty
        when the user has no gear, which only means no activity is linked to one.
    """
    gear_by_name: dict[str, list[uuid.UUID]] = {}
    for item in gears_integration.get_gear_user(user_id, db) or []:
        gear_by_name[item.nickname] = [item.id]
        # Strava apparently exports shoe names as a smoosh of "{brand} {model} {name}", so adding that as a
        # second key for each gear item
        strava_name_smoosh = " ".join(
            part
            for part in [
                (item.brand or "").strip(),
                (item.model or "").strip(),
                (item.nickname or "").strip(),
            ]
            if part
        )
        gear_by_name.setdefault(strava_name_smoosh, [item.id])
    return gear_by_name

does_activity_start_time_match_the_data_in_strava_activities_csv

does_activity_start_time_match_the_data_in_strava_activities_csv(activity, activity_metadata_dict)

Strava includes each multi-activity .fit file once for each activity inside the fit file.

Thus, run without filtering, a 5-activity fit file is imported 5 times for 25 activities imported.

So, to find out which activity goes with which file, we check if start time of activity aligns with start time of the activity's strava activities.csv file data. If it does import.

Formatting of times in the two files

Activity start time - from Endurain activity parser: 2023-10-21T07:41:47 Activity start time - from Strava activities.csv: Oct 21, 2023, 8:13:28 AM

Returns: True if the start times match. False if they do not.

Source code in backend/app/modules/strava/bulk_import_service.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def does_activity_start_time_match_the_data_in_strava_activities_csv(
    activity: activity_contracts.ActivityCore,  # A parsed activity about to be added to Endurain
    # A dictionary containing parsed information from a Strava activities.csv file
    activity_metadata_dict: dict[str, Any],
) -> bool:
    """Strava includes each multi-activity .fit file once for each activity inside the fit file.

    Thus, run without filtering, a 5-activity fit file is imported 5 times for 25 activities imported.

    So, to find out which activity goes with which file, we check if start time of activity aligns with
    start time of the activity's strava activities.csv file data.  If it does import.

    Formatting of times in the two files:
        Activity start time - from Endurain activity parser: 2023-10-21T07:41:47
        Activity start time - from Strava activities.csv: Oct 21, 2023, 8:13:28 AM

    Returns: True if the start times match.  False if they do not.
    """
    # ``ActivityCore`` normalizes start_time to an aware UTC datetime at
    # construction, but accepts a string — go through the shared coercion rather
    # than assuming either. Parsing this as a string unconditionally raised
    # TypeError once the contract started coercing, which failed the whole file
    # and sent every multi-activity .fit in a Strava export to the error dir.
    endurain_parsed_file_start_date = core_timezone.to_utc_aware(activity.start_time)
    if endurain_parsed_file_start_date is None:
        return False
    strava_csv_start_date = datetime.strptime(activity_metadata_dict["activity date"], _STRAVA_CSV_DATE_FORMAT)
    # Ensure both are tz-aware (or both naive) for comparison
    if strava_csv_start_date.tzinfo is None:
        strava_csv_start_date = strava_csv_start_date.replace(tzinfo=UTC)
    return endurain_parsed_file_start_date == strava_csv_start_date

drop_directory_for

drop_directory_for(user_id)

Return the directory one user drops their Strava export in.

Per user, so an import never ingests another user's export and attributes it to whoever started it.

Parameters:

Name Type Description Default
user_id UUID

The owning user's id. A UUID, so the value can only ever be a single path segment.

required

Returns:

Type Description
str

Absolute path of that user's Strava-export directory.

Source code in backend/app/modules/strava/bulk_import_service.py
566
567
568
569
570
571
572
573
574
575
576
577
def drop_directory_for(user_id: uuid.UUID) -> str:
    """Return the directory one user drops their Strava export in.

    Per user, so an import never ingests another user's export and attributes it to whoever started it.

    Args:
        user_id: The owning user's id. A UUID, so the value can only ever be a single path segment.

    Returns:
        Absolute path of that user's Strava-export directory.
    """
    return f"{core_config.settings.FILES_DIR}/{strava_constants.BULK_IMPORT_DIR_NAME}/{user_id}"

import_media_from_strava_bulk_export

import_media_from_strava_bulk_export(strava_activities, created_activity, file_base_name, read_member, db)

Import media files associated with a Strava bulk export activity.

Reads the pipe-separated media list from the Strava activities.csv entry for the given file, then attaches each referenced image found in the export's media folder.

Parameters:

Name Type Description Default
strava_activities StravaActivitiesManifest

Strava bulk-import metadata dict keyed by filename, then by activities.csv column header.

required
created_activity ActivityRead

The newly created activity object to which media will be attached.

required
file_base_name str

Base filename of the activity file, used as the lookup key in strava_activities.

required
read_member Callable[[str], bytes | None]

Reads a member of the archive being imported by name.

required
db Session

SQLAlchemy database session.

required
Source code in backend/app/modules/strava/bulk_import_service.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def import_media_from_strava_bulk_export(
    strava_activities: StravaActivitiesManifest,
    created_activity: activity_schema.ActivityRead,
    file_base_name: str,
    read_member: Callable[[str], bytes | None],
    db: Session,
) -> None:
    """Import media files associated with a Strava bulk export activity.

    Reads the pipe-separated media list from the Strava ``activities.csv`` entry
    for the given file, then attaches each referenced image found in the export's
    ``media`` folder.

    Args:
        strava_activities: Strava bulk-import metadata dict keyed by filename,
            then by activities.csv column header.
        created_activity: The newly created activity object to which media will
            be attached.
        file_base_name: Base filename of the activity file, used as the lookup key
            in strava_activities.
        read_member: Reads a member of the archive being imported by name.
        db: SQLAlchemy database session.
    """
    if created_activity.id is None:
        logger.warning(
            "Bulk file import: cannot import media, created activity has no id",
            extra=core_logger.context(console=True, file_name=file_base_name),
        )
        return
    row = strava_activities.get(file_base_name)
    if not row:
        return
    media_string = (row.get("Media") or "").strip()
    if not media_string:
        logger.debug(
            "Bulk file import: no media list in activities.csv",
            extra=core_logger.context(console=True, file_name=file_base_name),
        )
        return
    for media_item in media_string.split("|"):
        media_file_base_name = os.path.basename(media_item)
        if not media_file_base_name:
            continue
        data = read_member(f"{MEDIA_FOLDER}/{media_file_base_name}")
        if data is None:
            logger.warning(
                "Bulk file import: media file is not in the export, skipping it",
                extra=core_logger.context(console=True, file_name=media_file_base_name),
            )
            continue
        create_activity_media_from_strava_bulk_import(created_activity.id, media_file_base_name, data, db)

parse_activities_manifest

parse_activities_manifest(manifest_path)

Parses a Strava activities.csv manifest.

Parameters:

Name Type Description Default
manifest_path str

Path of the manifest file.

required

Returns:

Type Description
StravaActivitiesManifest | None

Dictionary of the manifest's rows keyed by each activity's filename, or

StravaActivitiesManifest | None

None when the file cannot be parsed, lacks the required headers or has a row

StravaActivitiesManifest | None

without a filename.

Source code in backend/app/modules/strava/bulk_import_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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def parse_activities_manifest(manifest_path: str) -> StravaActivitiesManifest | None:
    """Parses a Strava ``activities.csv`` manifest.

    Args:
        manifest_path: Path of the manifest file.

    Returns:
        Dictionary of the manifest's rows keyed by each activity's filename, or
        ``None`` when the file cannot be parsed, lacks the required headers or has a row
        without a filename.
    """
    strava_activities_file_name = os.path.basename(manifest_path)
    try:
        strava_activities_dict: StravaActivitiesManifest = {}
        for row in core_text_imports.read_bounded_csv(manifest_path):
            # Check to see if file has headers that will be used during parsing of the file.
            missing_headers = _STRAVA_ACTIVITIES_HEADERS - row.keys()
            if missing_headers:
                logger.warning(
                    "Aborting Strava bulk activities import: required headers missing",
                    extra=core_logger.context(
                        console=True, file_name=strava_activities_file_name, missing=sorted(missing_headers)
                    ),
                )
                return None
            if row["Filename"] is None:
                # DictReader leaves the fields a short row lacks as None.
                logger.warning(
                    "Aborting Strava bulk activities import: a row has no filename",
                    extra=core_logger.context(console=True, file_name=strava_activities_file_name),
                )
                return None
            _, strava_act_file_name = os.path.split(row["Filename"])  # strips path, returns filename with extension.
            strava_activities_dict[strava_act_file_name] = row
        logger.info(
            "Strava bulk import: activities.csv parsed",
            extra=core_logger.context(console=True, row_count=len(strava_activities_dict)),
        )
        return strava_activities_dict
    except (core_exceptions.PayloadTooLargeError, csv.Error, UnicodeDecodeError) as err:
        # An oversized, malformed or non-text manifest is the user's file, not a server failure.
        logger.warning(
            "Strava activities CSV parsing aborted",
            extra=core_logger.context(console=True, file_name=strava_activities_file_name, detail=str(err)),
        )
        return None
    except core_exceptions.DomainError as err:
        # ``read_bounded_csv`` raises 424 when the file cannot be stat'd or opened.
        logger.error(
            "Strava activities CSV parsing aborted", extra=core_logger.context(console=True, detail=err.detail)
        )
        return None

register_bulk_import_format

register_bulk_import_format()

Register the Strava export layout with activity ingestion.

Source code in backend/app/modules/strava/bulk_import_service.py
580
581
582
583
584
585
586
587
588
589
590
def register_bulk_import_format() -> None:
    """Register the Strava export layout with activity ingestion."""
    activity_ingestion_integration.register_bulk_import_format(
        activity_ingestion_integration.BulkImportFormat(
            name=strava_constants.BULK_IMPORT_FORMAT_NAME,
            is_activity_member=_is_activity_member,
            is_export_member=_is_export_member,
            drop_directory=drop_directory_for,
            build_source=_build_source,
        )
    )

Client and token handling

Strava API access: the client, its token refresh and the rate-limit checks.

StravaTokenRejectedError

Bases: DependencyFailedError

Raised when Strava rejected the user's token and the account was unlinked, so a sync must stop.

Source code in backend/app/modules/strava/client_service.py
48
49
class StravaTokenRejectedError(core_exceptions.DependencyFailedError):
    """Raised when Strava rejected the user's token and the account was unlinked, so a sync must stop."""

call_strava

call_strava(call, strava_client, user_id, user_integrations, rate_limits)

Make one Strava call, confirming a 401 with the token endpoint instead of trusting it.

A 401 can mean the access token expired or that the user withdrew Endurain's access on Strava. So the stored refresh token is used once, through :func:refresh_user_strava_token, and the call is made again with the new token. Only Strava refusing the refresh token, or refusing the new access token as well, is a revocation. A refresh that fails for any other reason leaves the tokens and the data alone and stops the sync, which tries again on its next run. Failures other than a 401 are the caller's to handle.

Parameters:

Name Type Description Default
call Callable[[Client], T]

Makes the Strava call with the client it is given.

required
strava_client Client

A client authenticated as the user.

required
user_id UUID

The user the call is for.

required
user_integrations UserIntegrationsRead

The integration settings strava_client was built from.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Returns:

Type Description
T

What call returned.

Raises:

Type Description
StravaTokenRejectedError

When Strava refused the refresh token or the new access token, so the account was unlinked as revoked; or when the account is no longer linked.

TooManyRequestsError

When Strava's rate limit is active or another process is refreshing the token.

DependencyFailedError

When the refresh failed without Strava refusing the refresh token.

Source code in backend/app/modules/strava/client_service.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def call_strava[T](
    call: Callable[[StravaClient], T],
    strava_client: StravaClient,
    user_id: uuid.UUID,
    user_integrations: user_integrations_schema.UserIntegrationsRead,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
) -> T:
    """Make one Strava call, confirming a 401 with the token endpoint instead of trusting it.

    A 401 can mean the access token expired or that the user withdrew Endurain's access on Strava. So the
    stored refresh token is used once, through :func:`refresh_user_strava_token`, and the call is made again
    with the new token. Only Strava refusing the refresh token, or refusing the new access token as well, is a
    revocation. A refresh that fails for any other reason leaves the tokens and the data alone and stops the
    sync, which tries again on its next run. Failures other than a 401 are the caller's to handle.

    Args:
        call: Makes the Strava call with the client it is given.
        strava_client: A client authenticated as the user.
        user_id: The user the call is for.
        user_integrations: The integration settings ``strava_client`` was built from.
        rate_limits: The shared Strava rate-limit state.

    Returns:
        What ``call`` returned.

    Raises:
        StravaTokenRejectedError: When Strava refused the refresh token or the new access token, so the account
            was unlinked as revoked; or when the account is no longer linked.
        TooManyRequestsError: When Strava's rate limit is active or another process is refreshing the token.
        DependencyFailedError: When the refresh failed without Strava refusing the refresh token.
    """
    try:
        return call(strava_client)
    except Exception as err:
        if not is_strava_unauthorized_error(err):
            raise
        logger.info(
            "Strava answered 401, confirming it with a token refresh", extra=core_logger.context(user_id=user_id)
        )

    if user_integrations.strava_refresh_token is None:
        raise StravaTokenRejectedError("Strava is not linked. Please reconnect your Strava account.")
    refresh_user_strava_token(user_id, rate_limits, rejected_refresh_token=user_integrations.strava_refresh_token)
    with core_database.SessionLocal() as db:
        refreshed = fetch_user_integrations_and_validate_token(user_id, db)
    if refreshed is None:
        raise StravaTokenRejectedError("Strava is not linked. Please reconnect your Strava account.")
    try:
        return call(create_strava_client(refreshed))
    except Exception as err:
        if not is_strava_unauthorized_error(err):
            raise
        handle_rejected_token(user_id, refreshed.strava_refresh_token, err, revoked=True)
        raise StravaTokenRejectedError("Strava authentication failed. Please reconnect your Strava account.") from err

create_strava_client

create_strava_client(user_integrations)

Build a Strava client from a user's stored tokens.

stravalib's own rate limiting is replaced by a no-op: it would block the thread for minutes or hours when a limit is hit, and the shared rate-limit state decides instead.

Parameters:

Name Type Description Default
user_integrations UserIntegrationsRead

The user's integration settings.

required

Returns:

Type Description
Client

A client authenticated as the user.

Raises:

Type Description
UndecryptableError

When a stored token cannot be decrypted with the configured key.

Source code in backend/app/modules/strava/client_service.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def create_strava_client(
    user_integrations: user_integrations_schema.UserIntegrationsRead,
) -> StravaClient:
    """Build a Strava client from a user's stored tokens.

    stravalib's own rate limiting is replaced by a no-op: it would block the thread
    for minutes or hours when a limit is hit, and the shared rate-limit state decides
    instead.

    Args:
        user_integrations: The user's integration settings.

    Returns:
        A client authenticated as the user.

    Raises:
        UndecryptableError: When a stored token cannot be decrypted with the configured key.
    """
    epoch_time = (
        calendar.timegm(user_integrations.strava_token_expires_at.utctimetuple())
        if user_integrations.strava_token_expires_at
        else None
    )

    client = StravaClient(
        access_token=(
            core_cryptography.decrypt_token_fernet(user_integrations.strava_token)
            if user_integrations.strava_token
            else None
        ),
        refresh_token=(
            core_cryptography.decrypt_token_fernet(user_integrations.strava_refresh_token)
            if user_integrations.strava_refresh_token
            else None
        ),
        token_expires=epoch_time,
        rate_limit_requests=False,
        requests_session=_TimeoutSession(),
    )
    client.protocol.rate_limiter = _noop_rate_limiter
    return client

fetch_user_integrations_and_validate_token

fetch_user_integrations_and_validate_token(user_id, db)

Return a user's integrations when Strava 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 Strava is not linked.

Raises:

Type Description
NotFoundError

When the user has no integrations row.

Source code in backend/app/modules/strava/client_service.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
def fetch_user_integrations_and_validate_token(
    user_id: uuid.UUID, db: Session
) -> user_integrations_schema.UserIntegrationsRead | None:
    """Return a user's integrations when Strava is linked.

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

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

    Raises:
        NotFoundError: When the user has no integrations row.
    """
    user_integrations = user_integrations_integration.require_user_integrations(user_id, db)
    if user_integrations.strava_token_expires_at is None:
        return None
    return user_integrations

get_client_id

get_client_id(user_integrations)

Get the Strava application (client ID) a user's integration belongs to.

It is the scope of Strava's rate limits, so every call that checks or records one needs it.

Parameters:

Name Type Description Default
user_integrations UserIntegrationsRead

The user's integration settings.

required

Returns:

Type Description
str

The decrypted client ID.

Raises:

Type Description
DependencyFailedError

When the user has no Strava client ID stored.

Source code in backend/app/modules/strava/client_service.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def get_client_id(user_integrations: user_integrations_schema.UserIntegrationsRead) -> str:
    """Get the Strava application (client ID) a user's integration belongs to.

    It is the scope of Strava's rate limits, so every call that checks or records
    one needs it.

    Args:
        user_integrations: The user's integration settings.

    Returns:
        The decrypted client ID.

    Raises:
        DependencyFailedError: When the user has no Strava client ID stored.
    """
    if user_integrations.strava_client_id is None:
        raise core_exceptions.DependencyFailedError(
            "Strava client ID not configured. Please reconnect your Strava account."
        )
    return core_cryptography.decrypt_token_fernet(user_integrations.strava_client_id)

get_client_secret

get_client_secret(user_integrations)

Get the secret of the Strava application a user's integration belongs to.

Parameters:

Name Type Description Default
user_integrations UserIntegrationsRead

The user's integration settings.

required

Returns:

Type Description
str

The decrypted client secret.

Raises:

Type Description
DependencyFailedError

When the user has no Strava client secret stored.

Source code in backend/app/modules/strava/client_service.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def get_client_secret(user_integrations: user_integrations_schema.UserIntegrationsRead) -> str:
    """Get the secret of the Strava application a user's integration belongs to.

    Args:
        user_integrations: The user's integration settings.

    Returns:
        The decrypted client secret.

    Raises:
        DependencyFailedError: When the user has no Strava client secret stored.
    """
    if user_integrations.strava_client_secret is None:
        raise core_exceptions.DependencyFailedError(
            "Strava client secret not configured. Please reconnect your Strava account."
        )
    return core_cryptography.decrypt_token_fernet(user_integrations.strava_client_secret)

handle_rejected_token

handle_rejected_token(user_id, refresh_token, err, *, revoked=False)

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

The tokens are cleared and the notification row committed together; the live push is published after. The client id and secret stay, so relinking is one step. Nothing happens when the stored refresh token is no longer refresh_token: the user relinked, or another job already unlinked it and told them. When revoked is set the user withdrew Endurain's access on Strava: the time is stored with the tokens, the data stays for the grace period, and the notice names the day it is deleted unless the user relinks.

Parameters:

Name Type Description Default
user_id UUID

The user whose sync was rejected.

required
refresh_token str | None

The stored (encrypted) refresh token that Strava rejected.

required
err Exception

The unauthorized error Strava raised.

required
revoked bool

Whether Strava refused the refresh token, or an access token it had just issued from it.

False
Source code in backend/app/modules/strava/client_service.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def handle_rejected_token(
    user_id: uuid.UUID, refresh_token: str | None, err: Exception, *, revoked: bool = False
) -> None:
    """Unlink an account whose token Strava rejected during a sync, and tell the user.

    The tokens are cleared and the notification row committed together; the live push is
    published after. The client id and secret stay, so relinking is one step. Nothing happens
    when the stored refresh token is no longer ``refresh_token``: the user relinked, or
    another job already unlinked it and told them. When ``revoked`` is set the user withdrew Endurain's
    access on Strava: the time is stored with the tokens, the data stays for the grace period, and the notice
    names the day it is deleted unless the user relinks.

    Args:
        user_id: The user whose sync was rejected.
        refresh_token: The stored (encrypted) refresh token that Strava rejected.
        err: The unauthorized error Strava raised.
        revoked: Whether Strava refused the refresh token, or an access token it had just issued from it.
    """
    logger.warning(
        "Strava token rejected. Unlinking account. User must re-link",
        exc_info=err,
        extra=core_logger.context(user_id=user_id, revoked=revoked),
    )
    if refresh_token is None:
        return
    revoked_at = datetime.now(UTC) if revoked else None
    delete_on = (
        (revoked_at + timedelta(days=user_integrations_constants.STRAVA_REVOKED_DATA_GRACE_DAYS)).date()
        if revoked_at
        else None
    )
    with core_database.SessionLocal() as db:
        if not user_integrations_integration.unlink_strava_tokens_if_refresh_token(
            user_id, refresh_token, db, revoked_at=revoked_at
        ):
            db.rollback()
            logger.info(
                "Strava token changed since it was rejected; account left linked",
                extra=core_logger.context(user_id=user_id),
            )
            return
        notification, ws_message = notifications_integration.create_strava_token_expired_notification(
            user_id, db, delete_on=delete_on
        )
        jasil_audit.stage(
            db,
            strava_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("Rejected Strava account unlinked", extra=core_logger.context(user_id=user_id, revoked=revoked))

is_strava_client_error

is_strava_client_error(err)

Check if an exception is Strava refusing a request with a 4xx answer.

Parameters:

Name Type Description Default
err Exception

The exception to check.

required

Returns:

Type Description
bool

True if the error is a response with a 4xx status.

Source code in backend/app/modules/strava/client_service.py
119
120
121
122
123
124
125
126
127
128
129
def is_strava_client_error(err: Exception) -> bool:
    """Check if an exception is Strava refusing a request with a 4xx answer.

    Args:
        err: The exception to check.

    Returns:
        True if the error is a response with a 4xx status.
    """
    status = _fault_status(err)
    return status is not None and 400 <= status < 500

is_strava_not_found_error

is_strava_not_found_error(err)

Check if an exception is a Strava 404 Not Found error.

This occurs for activities that have no streams, such as those manually added via Apple Health and imported into Strava.

Parameters:

Name Type Description Default
err Exception

The exception to check.

required

Returns:

Type Description
bool

True if the error is a 404 not-found response.

Source code in backend/app/modules/strava/client_service.py
132
133
134
135
136
137
138
139
140
141
142
143
144
def is_strava_not_found_error(err: Exception) -> bool:
    """Check if an exception is a Strava 404 Not Found error.

    This occurs for activities that have no streams, such as
    those manually added via Apple Health and imported into Strava.

    Args:
        err: The exception to check.

    Returns:
        True if the error is a 404 not-found response.
    """
    return isinstance(err, ObjectNotFound) or _fault_status(err) == 404

is_strava_rate_limit_error

is_strava_rate_limit_error(err)

Check if an exception is a Strava rate limit error.

Parameters:

Name Type Description Default
err Exception

The exception to check.

required

Returns:

Type Description
bool

True if the error is a 429 rate limit response.

Source code in backend/app/modules/strava/client_service.py
107
108
109
110
111
112
113
114
115
116
def is_strava_rate_limit_error(err: Exception) -> bool:
    """Check if an exception is a Strava rate limit error.

    Args:
        err: The exception to check.

    Returns:
        True if the error is a 429 rate limit response.
    """
    return isinstance(err, RateLimitExceeded) or _fault_status(err) == 429

is_strava_unauthorized_error

is_strava_unauthorized_error(err)

Check if an exception is Strava rejecting the user's access token.

Parameters:

Name Type Description Default
err Exception

The exception to check.

required

Returns:

Type Description
bool

True if the error is a 401 unauthorized response.

Source code in backend/app/modules/strava/client_service.py
147
148
149
150
151
152
153
154
155
156
def is_strava_unauthorized_error(err: Exception) -> bool:
    """Check if an exception is Strava rejecting the user's access token.

    Args:
        err: The exception to check.

    Returns:
        True if the error is a 401 unauthorized response.
    """
    return isinstance(err, AccessUnauthorized) or _fault_status(err) == 401

raise_if_rate_limit_active

raise_if_rate_limit_active(client_id, user_id, rate_limits)

Refuse a Strava call while the application's rate limit is active.

Parameters:

Name Type Description Default
client_id str

The Strava application (client ID) about to be called.

required
user_id UUID

The user the call is for, for the log.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Raises:

Type Description
TooManyRequestsError

When the application is rate limited.

Source code in backend/app/modules/strava/client_service.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def raise_if_rate_limit_active(
    client_id: str, user_id: uuid.UUID, rate_limits: strava_rate_limit_store.StravaRateLimitStore
) -> None:
    """Refuse a Strava call while the application's rate limit is active.

    Args:
        client_id: The Strava application (client ID) about to be called.
        user_id: The user the call is for, for the log.
        rate_limits: The shared Strava rate-limit state.

    Raises:
        TooManyRequestsError: When the application is rate limited.
    """
    if rate_limits.is_rate_limited(client_id):
        logger.debug("Strava rate limit active, skipping the call", extra=core_logger.context(user_id=user_id))
        raise core_exceptions.TooManyRequestsError(
            "Strava API rate limit exceeded. Please try again later.",
            scope=core_exceptions.TooManyRequestsScope.PROVIDER,
            retry_at=rate_limits.rate_limited_until(client_id),
        )

raise_if_rate_limited

raise_if_rate_limited(err, client_id, rate_limits)

Record a Strava rate limit and refuse the call when err is one.

Parameters:

Name Type Description Default
err Exception

The exception a Strava call raised.

required
client_id str

The Strava application (client ID) that made the call.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required

Raises:

Type Description
TooManyRequestsError

When err is a Strava rate limit error.

Source code in backend/app/modules/strava/client_service.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def raise_if_rate_limited(
    err: Exception, client_id: str, rate_limits: strava_rate_limit_store.StravaRateLimitStore
) -> None:
    """Record a Strava rate limit and refuse the call when ``err`` is one.

    Args:
        err: The exception a Strava call raised.
        client_id: The Strava application (client ID) that made the call.
        rate_limits: The shared Strava rate-limit state.

    Raises:
        TooManyRequestsError: When ``err`` is a Strava rate limit error.
    """
    if not is_strava_rate_limit_error(err):
        return
    retry_at = rate_limits.mark_rate_limited(client_id, is_long_term=_daily_limit_reached(err))
    raise core_exceptions.TooManyRequestsError(
        "Strava API rate limit exceeded. Please try again later.",
        scope=core_exceptions.TooManyRequestsScope.PROVIDER,
        retry_at=retry_at,
    ) from err

refresh_user_strava_token

refresh_user_strava_token(user_id, rate_limits, *, rejected_refresh_token=None)

Refresh a user's Strava access token when it is about to expire, or when Strava rejected it.

Called at the start of the user's own sync job, so tokens are kept current without a separate pass over every user. Strava rotates the refresh token, so only one process refreshes a user at a time: the claim is taken first, released when the refresh is over, and the integration is read again under it, in case another process just finished. The new tokens are stored only while the refresh token is still the one they were refreshed from. The integration is read in short sessions, the Strava call runs with none open, and the new tokens are written in another. A failure is logged and left to the sync that follows, which will fail visibly if the token really is unusable.

A token that has already expired is never handed to a sync unrefreshed: Strava would answer 401 and the sync would unlink an account that is only waiting for its refresh. Only the token endpoint refusing the refresh token counts as the user revoking access: the account is unlinked as a revocation and the sync stops.

With rejected_refresh_token the refresh is asked for, whatever the token's expiry, because Strava answered 401 to the access token. Nothing is then left to the sync that follows: when the refresh cannot be done, or Strava's answer cannot be read as a refusal, an error stops the sync with the tokens kept. A refresh token that is no longer rejected_refresh_token was replaced by another process, so nothing is refreshed again.

Parameters:

Name Type Description Default
user_id UUID

The user whose token to refresh.

required
rate_limits StravaRateLimitStore

The shared Strava rate-limit state.

required
rejected_refresh_token str | None

The stored (encrypted) refresh token whose access token Strava rejected, when the refresh is a confirmation of that rejection.

None

Raises:

Type Description
TooManyRequestsError

When the token has expired or a refresh was asked for, and another process holds the refresh or the application is rate limited; the work is deferred.

DependencyFailedError

When the token has expired or a refresh was asked for, and Strava could not refresh it.

StravaTokenRejectedError

When Strava refused the refresh token, so the account was unlinked.

Source code in backend/app/modules/strava/client_service.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def refresh_user_strava_token(
    user_id: uuid.UUID,
    rate_limits: strava_rate_limit_store.StravaRateLimitStore,
    *,
    rejected_refresh_token: str | None = None,
) -> None:
    """Refresh a user's Strava access token when it is about to expire, or when Strava rejected it.

    Called at the start of the user's own sync job, so tokens are kept current
    without a separate pass over every user. Strava rotates the refresh token, so
    only one process refreshes a user at a time: the claim is taken first, released when the
    refresh is over, and the integration is read again under it, in case another process just finished.
    The new tokens are stored only while the refresh token is still the one they were refreshed from. The
    integration is read in short sessions, the Strava call runs with none open, and
    the new tokens are written in another. A failure is logged and left to the sync
    that follows, which will fail visibly if the token really is unusable.

    A token that has already expired is never handed to a sync unrefreshed: Strava would answer 401
    and the sync would unlink an account that is only waiting for its refresh. Only the token endpoint
    refusing the refresh token counts as the user revoking access: the account is unlinked as a revocation
    and the sync stops.

    With ``rejected_refresh_token`` the refresh is asked for, whatever the token's expiry, because Strava
    answered 401 to the access token. Nothing is then left to the sync that follows: when the refresh cannot
    be done, or Strava's answer cannot be read as a refusal, an error stops the sync with the tokens kept. A
    refresh token that is no longer ``rejected_refresh_token`` was replaced by another process, so nothing
    is refreshed again.

    Args:
        user_id: The user whose token to refresh.
        rate_limits: The shared Strava rate-limit state.
        rejected_refresh_token: The stored (encrypted) refresh token whose access token Strava rejected, when
            the refresh is a confirmation of that rejection.

    Raises:
        TooManyRequestsError: When the token has expired or a refresh was asked for, and another process
            holds the refresh or the application is rate limited; the work is deferred.
        DependencyFailedError: When the token has expired or a refresh was asked for, and Strava could not
            refresh it.
        StravaTokenRejectedError: When Strava refused the refresh token, so the account was unlinked.
    """
    forced = rejected_refresh_token is not None
    with core_database.SessionLocal() as db:
        linked = _linked_token(user_integrations_integration.get_user_integrations(user_id, db))

    if linked is None or not _refresh_wanted(linked, rejected_refresh_token):
        logger.debug("No Strava token refresh due", extra=core_logger.context(user_id=user_id))
        return

    client_id = get_client_id(linked.integrations)
    if rate_limits.is_rate_limited(client_id):
        logger.debug("Strava rate limit active, skipping token refresh", extra=core_logger.context(user_id=user_id))
        if forced:
            raise core_exceptions.TooManyRequestsError(
                "Strava API rate limit exceeded. Please try again later.",
                scope=core_exceptions.TooManyRequestsScope.PROVIDER,
                retry_at=rate_limits.rate_limited_until(client_id),
            )
        return

    if not rate_limits.claim_token_refresh(user_id):
        logger.debug("Another process is refreshing the Strava token", extra=core_logger.context(user_id=user_id))
        if forced or _token_expired(linked):
            raise core_exceptions.TooManyRequestsError(
                "Another process is refreshing the Strava token",
                scope=core_exceptions.TooManyRequestsScope.PROVIDER,
                retry_at=datetime.now(UTC) + timedelta(seconds=strava_constants.TOKEN_REFRESH_CLAIM_TTL_SECONDS),
            )
        return

    try:
        _refresh_under_claim(user_id, client_id, rate_limits, rejected_refresh_token)
    finally:
        rate_limits.release_token_refresh(user_id)

Rate limits

Strava API shared state: the rate-limit flags and the token-refresh claim.

StravaRateLimitStore

Tracks Strava API rate limit state and token-refresh claims over a platform StateProvider.

The limits are Strava's, per application, so every process and replica has to see the same answer: a process-local flag would let each worker keep hammering an API another one was already told to back off from. Every user brings their own Strava application, so the flags are keyed by client ID: one application hitting its limit must not pause the others. The flags are TTL keys in the state provider (in-process under the local profile, Redis when distributed), so they expire on their own. Strava rotates the refresh token on every refresh, so two replicas refreshing one user at once would invalidate each other; a claim lets only one of them refresh. The claim is never released: it expires, because the state has no owner-checked delete and an early release could free a claim another replica took after expiry. A refreshed token is no longer due, so nothing waits on the release, and a failed refresh backs off until the claim expires.

Source code in backend/app/modules/strava/rate_limit_store.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class StravaRateLimitStore:
    """Tracks Strava API rate limit state and token-refresh claims over a platform ``StateProvider``.

    The limits are Strava's, per application, so every process and replica has to
    see the same answer: a process-local flag would let each worker keep
    hammering an API another one was already told to back off from. Every user
    brings their own Strava application, so the flags are keyed by client ID: one
    application hitting its limit must not pause the others. The flags are TTL keys
    in the state provider (in-process under the ``local`` profile, Redis when
    distributed), so they expire on their own. Strava rotates the refresh token on
    every refresh, so two replicas refreshing one user at once would invalidate each
    other; a claim lets only one of them refresh. The claim is never released: it expires,
    because the state has no owner-checked delete and an early release could free a claim
    another replica took after expiry. A refreshed token is no longer due, so nothing waits
    on the release, and a failed refresh backs off until the claim expires.
    """

    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, "strava")

    def mark_rate_limited(self, client_id: str, is_long_term: bool = False) -> datetime:
        """Record that a rate limit was hit.

        The flag's value is the instant it expires, so a sync that stops here can wait for exactly that long.

        Args:
            client_id: The Strava application (client ID) that hit the limit.
            is_long_term: True for the daily limit (resets at UTC midnight),
                False for the 15-minute limit.

        Returns:
            When the limit clears.
        """
        now = datetime.now(UTC)
        if is_long_term:
            expires_at = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
            logger.warning(
                "Strava daily rate limit hit, skipping until it resets",
                extra=core_logger.context(client_id=client_id, resets_at=expires_at),
            )
        else:
            expires_at = now + timedelta(seconds=SHORT_TERM_COOLDOWN_SECONDS)
            logger.warning(
                "Strava 15-minute rate limit hit, skipping for the cooldown",
                extra=core_logger.context(client_id=client_id, cooldown_seconds=SHORT_TERM_COOLDOWN_SECONDS),
            )
        self._limits.mark(
            _LONG_TERM_SUBJECT.format(client_id=client_id)
            if is_long_term
            else _SHORT_TERM_SUBJECT.format(client_id=client_id),
            expires_at,
        )
        return expires_at

    def is_rate_limited(self, client_id: str) -> bool:
        """Check if Strava API calls should be skipped for an application.

        Fails open when the shared state is unreachable.

        Args:
            client_id: The Strava application (client ID) about to be called.

        Returns:
            True if currently rate-limited.
        """
        return self.rate_limited_until(client_id) is not None

    def rate_limited_until(self, client_id: str) -> datetime | None:
        """Return when an application's active rate limit clears.

        Args:
            client_id: The Strava application (client ID).

        Returns:
            The later expiry of the active limits, or ``None`` when none is active or the state is unreachable.
        """
        expiries = [
            expiry
            for subject in (_LONG_TERM_SUBJECT, _SHORT_TERM_SUBJECT)
            if (expiry := self._limits.expiry(subject.format(client_id=client_id))) is not None
        ]
        return max(expiries) if expiries else None

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

        Fails open when the shared state is unreachable: a refresh that races is
        recoverable by relinking, whereas failing closed would stop every refresh
        for as long as the state store is down.

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

        Returns:
            True when this caller may refresh, False when another already is.
        """
        try:
            return self._state.set_if_absent(
                _REFRESH_CLAIM_KEY.format(user_id=user_id), b"1", strava_constants.TOKEN_REFRESH_CLAIM_TTL_SECONDS
            )
        except platform_providers.StateBackendUnavailableError as err:
            logger.warning("Could not claim the Strava token refresh; refreshing anyway", exc_info=err)
            return True

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

        Without it a second refresh, such as one that confirms a 401, would wait for the claim to expire.

        Args:
            user_id: The user whose token was refreshed.
        """
        try:
            self._state.delete(_REFRESH_CLAIM_KEY.format(user_id=user_id))
        except platform_providers.StateBackendUnavailableError as err:
            logger.warning("Could not release the Strava token refresh claim; it expires on its own", exc_info=err)

__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/strava/rate_limit_store.py
39
40
41
42
43
44
45
46
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, "strava")

claim_token_refresh

claim_token_refresh(user_id)

Claim the right to refresh a user's Strava token.

Fails open when the shared state is unreachable: a refresh that races is recoverable by relinking, whereas failing closed would stop every refresh for as long as the state store is down.

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.

Source code in backend/app/modules/strava/rate_limit_store.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def claim_token_refresh(self, user_id: uuid.UUID) -> bool:
    """Claim the right to refresh a user's Strava token.

    Fails open when the shared state is unreachable: a refresh that races is
    recoverable by relinking, whereas failing closed would stop every refresh
    for as long as the state store is down.

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

    Returns:
        True when this caller may refresh, False when another already is.
    """
    try:
        return self._state.set_if_absent(
            _REFRESH_CLAIM_KEY.format(user_id=user_id), b"1", strava_constants.TOKEN_REFRESH_CLAIM_TTL_SECONDS
        )
    except platform_providers.StateBackendUnavailableError as err:
        logger.warning("Could not claim the Strava token refresh; refreshing anyway", exc_info=err)
        return True

is_rate_limited

is_rate_limited(client_id)

Check if Strava API calls should be skipped for an application.

Fails open when the shared state is unreachable.

Parameters:

Name Type Description Default
client_id str

The Strava application (client ID) about to be called.

required

Returns:

Type Description
bool

True if currently rate-limited.

Source code in backend/app/modules/strava/rate_limit_store.py
82
83
84
85
86
87
88
89
90
91
92
93
def is_rate_limited(self, client_id: str) -> bool:
    """Check if Strava API calls should be skipped for an application.

    Fails open when the shared state is unreachable.

    Args:
        client_id: The Strava application (client ID) about to be called.

    Returns:
        True if currently rate-limited.
    """
    return self.rate_limited_until(client_id) is not None

mark_rate_limited

mark_rate_limited(client_id, is_long_term=False)

Record that a rate limit was hit.

The flag's value is the instant it expires, so a sync that stops here can wait for exactly that long.

Parameters:

Name Type Description Default
client_id str

The Strava application (client ID) that hit the limit.

required
is_long_term bool

True for the daily limit (resets at UTC midnight), False for the 15-minute limit.

False

Returns:

Type Description
datetime

When the limit clears.

Source code in backend/app/modules/strava/rate_limit_store.py
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
def mark_rate_limited(self, client_id: str, is_long_term: bool = False) -> datetime:
    """Record that a rate limit was hit.

    The flag's value is the instant it expires, so a sync that stops here can wait for exactly that long.

    Args:
        client_id: The Strava application (client ID) that hit the limit.
        is_long_term: True for the daily limit (resets at UTC midnight),
            False for the 15-minute limit.

    Returns:
        When the limit clears.
    """
    now = datetime.now(UTC)
    if is_long_term:
        expires_at = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
        logger.warning(
            "Strava daily rate limit hit, skipping until it resets",
            extra=core_logger.context(client_id=client_id, resets_at=expires_at),
        )
    else:
        expires_at = now + timedelta(seconds=SHORT_TERM_COOLDOWN_SECONDS)
        logger.warning(
            "Strava 15-minute rate limit hit, skipping for the cooldown",
            extra=core_logger.context(client_id=client_id, cooldown_seconds=SHORT_TERM_COOLDOWN_SECONDS),
        )
    self._limits.mark(
        _LONG_TERM_SUBJECT.format(client_id=client_id)
        if is_long_term
        else _SHORT_TERM_SUBJECT.format(client_id=client_id),
        expires_at,
    )
    return expires_at

rate_limited_until

rate_limited_until(client_id)

Return when an application's active rate limit clears.

Parameters:

Name Type Description Default
client_id str

The Strava application (client ID).

required

Returns:

Type Description
datetime | None

The later expiry of the active limits, or None when none is active or the state is unreachable.

Source code in backend/app/modules/strava/rate_limit_store.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def rate_limited_until(self, client_id: str) -> datetime | None:
    """Return when an application's active rate limit clears.

    Args:
        client_id: The Strava application (client ID).

    Returns:
        The later expiry of the active limits, or ``None`` when none is active or the state is unreachable.
    """
    expiries = [
        expiry
        for subject in (_LONG_TERM_SUBJECT, _SHORT_TERM_SUBJECT)
        if (expiry := self._limits.expiry(subject.format(client_id=client_id))) is not None
    ]
    return max(expiries) if expiries else None

release_token_refresh

release_token_refresh(user_id)

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

Without it a second refresh, such as one that confirms a 401, would wait for the claim to expire.

Parameters:

Name Type Description Default
user_id UUID

The user whose token was refreshed.

required
Source code in backend/app/modules/strava/rate_limit_store.py
132
133
134
135
136
137
138
139
140
141
142
143
def release_token_refresh(self, user_id: uuid.UUID) -> None:
    """Release the claim on refreshing a user's Strava token once the refresh is over.

    Without it a second refresh, such as one that confirms a 401, would wait for the claim to expire.

    Args:
        user_id: The user whose token was refreshed.
    """
    try:
        self._state.delete(_REFRESH_CLAIM_KEY.format(user_id=user_id))
    except platform_providers.StateBackendUnavailableError as err:
        logger.warning("Could not release the Strava token refresh claim; it expires on its own", exc_info=err)

Schemas

Strava request and response shapes.

StravaClientCredentials

Bases: BaseModel

A user's Strava API application credentials.

Attributes:

Name Type Description
client_id int

The Strava application's client id.

client_secret SecretStr

The Strava application's client secret.

step_up StepUpVerification

The caller's step-up verification, which replacing the client needs.

Source code in backend/app/modules/strava/schema.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class StravaClientCredentials(BaseModel):
    """A user's Strava API application credentials.

    Attributes:
        client_id: The Strava application's client id.
        client_secret: The Strava application's client secret.
        step_up: The caller's step-up verification, which replacing the client needs.
    """

    model_config = ConfigDict(extra="forbid")

    client_id: int = Field(gt=0)
    client_secret: SecretStr = Field(min_length=1, max_length=255)
    step_up: auth_schema.StepUpVerification = Field(..., description="Step-up verification authorising the change")

StravaGearImportResult

Bases: BaseModel

What a Strava gear CSV import created.

Attributes:

Name Type Description
imported int

How many gear entries the upload produced.

Source code in backend/app/modules/strava/schema.py
67
68
69
70
71
72
73
74
class StravaGearImportResult(BaseModel):
    """What a Strava gear CSV import created.

    Attributes:
        imported: How many gear entries the upload produced.
    """

    imported: int

StravaGearImportType

Bases: StrEnum

The gear types a Strava export file carries; the values are the GearType wire values.

Attributes:

Name Type Description
BIKE

bikes.csv.

SHOES

shoes.csv.

Source code in backend/app/modules/strava/schema.py
55
56
57
58
59
60
61
62
63
64
class StravaGearImportType(StrEnum):
    """The gear types a Strava export file carries; the values are the ``GearType`` wire values.

    Attributes:
        BIKE: ``bikes.csv``.
        SHOES: ``shoes.csv``.
    """

    BIKE = "bike"
    SHOES = "shoes"

StravaLinkRequest

Bases: BaseModel

The OAuth callback values that complete a Strava link.

Attributes:

Name Type Description
state str

The one-time state stored before the OAuth round-trip.

code str

The authorization code Strava returned.

scope str

The comma-separated scopes Strava reports as granted.

Source code in backend/app/modules/strava/schema.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class StravaLinkRequest(BaseModel):
    """The OAuth callback values that complete a Strava link.

    Attributes:
        state: The one-time state stored before the OAuth round-trip.
        code: The authorization code Strava returned.
        scope: The comma-separated scopes Strava reports as granted.
    """

    model_config = ConfigDict(extra="forbid")

    state: str = Field(min_length=strava_constants.OAUTH_STATE_MIN_LENGTH, max_length=128)
    code: str = Field(min_length=1, max_length=255)
    scope: str = Field(min_length=1, max_length=255)

StravaState

Bases: BaseModel

The one-time state the browser round-trips through Strava.

Attributes:

Name Type Description
state str

The opaque state, to be sent to Strava and handed back with the authorization code.

Source code in backend/app/modules/strava/schema.py
45
46
47
48
49
50
51
52
class StravaState(BaseModel):
    """The one-time state the browser round-trips through Strava.

    Attributes:
        state: The opaque state, to be sent to Strava and handed back with the authorization code.
    """

    state: str

StravaSyncStatus

Bases: JobStatusOpenFailure

Where a queued Strava link, gear sync or unlink is.

Attributes:

Name Type Description
kind Literal['strava_link', 'strava_gear', 'strava_unlink']

The job kind: strava_link, strava_gear or strava_unlink.

Source code in backend/app/modules/strava/schema.py
77
78
79
80
81
82
83
84
class StravaSyncStatus(core_job_status.JobStatusOpenFailure):
    """Where a queued Strava link, gear sync or unlink is.

    Attributes:
        kind: The job kind: ``strava_link``, ``strava_gear`` or ``strava_unlink``.
    """

    kind: Literal["strava_link", "strava_gear", "strava_unlink"]