User settings events¶
User settings are event-sourced. Every change publishes one UserSettingsUpdatedEvent, and current settings are rebuilt from the latest snapshot plus the events after it, one field at a time. The settings themselves are a UserSettingsDocument, the same type for a stored snapshot and for a rebuilt result. UserSettingsService in app/services/user_settings_service.py owns all of it.
The event¶
There's one event type for every kind of change, theme, editor, notifications or custom keys alike:
class UserSettingsUpdatedEvent(BaseEvent):
model_config = ConfigDict(extra="allow")
event_type: Literal[EventType.USER_SETTINGS_UPDATED] = EventType.USER_SETTINGS_UPDATED
user_id: str
changed_fields: list[str] = Field(default_factory=list)
reason: str | None = None
The changed values aren't declared fields. The model has extra="allow", and _publish_settings_event() validates a dict that holds the changes next to the declared fields, so theme, editor and the rest ride along as top-level fields. They stay top level on Kafka and in the events collection, since EventDocument allows extras too (see Event Storage). changed_fields lists the keys. The aggregate id and the Kafka key are both user_settings_{user_id}.
Updating¶
async def update_user_settings(
self, user_id: str, changes: UserSettingsChanges, reason: str | None = None
) -> UserSettingsDocument:
"""Publish the changed fields as one event and apply it to the current settings."""
current = await self.get_user_settings(user_id)
if not changes:
return current
event = await self._publish_settings_event(user_id, changes, reason)
self._apply_event(
current,
DomainUserSettingsChangedEvent(
event_id=event.event_id,
event_type=event.event_type,
timestamp=event.timestamp,
user_id=user_id,
changed_fields=event.changed_fields,
reason=reason,
**changes,
),
)
current.version += 1
if (await self.repository.count_events_since_snapshot(user_id)) >= 10:
await self.repository.create_snapshot(current)
return current
changes is a UserSettingsChanges, a TypedDict that holds only the fields the request set. The route builds it with exclude_none=True, since the settings page sends null for the sections it didn't change. A notifications or editor update replaces the whole object. After publishing, the service applies the same change to the current settings with _apply_event(), the code a rebuild runs, and bumps version.
Once there are 10 or more events since the last snapshot, the service writes a snapshot to the user_settings collection.
Rebuilding¶
async def get_user_settings(self, user_id: str) -> UserSettingsDocument:
"""Rebuild settings from the latest snapshot and the events after it.
Not cached: each API worker process would keep its own copy, stale after another worker's update.
"""
snapshot = await self.repository.get_snapshot(user_id)
event_types = [EventType.USER_SETTINGS_UPDATED]
if snapshot:
settings = snapshot
events = await self.repository.get_settings_events(user_id, event_types, since=snapshot.updated_at)
else:
settings = UserSettingsDocument(user_id=user_id)
events = await self.repository.get_settings_events(user_id, event_types)
for event in events:
self._apply_event(settings, event)
return settings
graph TB
A[get_user_settings] --> D[Load snapshot or defaults]
D --> E[Load user_settings_updated events after it]
E --> F[_apply_event for each]
F --> G[Return the result]
Every read rebuilds, which costs two MongoDB queries and at most ten events, since a snapshot follows every ten. There's no cache. The API runs several worker processes, and a per-process cache served the old settings for up to 5 minutes whenever an update had gone through another worker.
UserSettingsRepository.get_settings_events() reads events by aggregate id and validates each into a DomainUserSettingsChangedEvent with a TypeAdapter. The adapter also turns the stored notification and editor dicts back into their dataclasses. _apply_event() sets each field the event carries and moves updated_at to the event's timestamp:
def _apply_event(self, settings: UserSettingsDocument, event: DomainUserSettingsChangedEvent) -> None:
"""Set the fields a settings update event carries."""
if event.theme is not None:
settings.theme = event.theme
if event.timezone is not None:
settings.timezone = event.timezone
if event.date_format is not None:
settings.date_format = event.date_format
if event.time_format is not None:
settings.time_format = event.time_format
if event.notifications is not None:
settings.notifications = event.notifications
if event.editor is not None:
settings.editor = event.editor
if event.custom_settings is not None:
settings.custom_settings = event.custom_settings
settings.updated_at = event.timestamp
History and restore¶
async def get_settings_history(self, user_id: str, limit: int = 50) -> list[DomainSettingsHistoryEntry]:
"""Get history from changed fields recorded in the newest events, newest first."""
events = await self.repository.get_settings_events(
user_id, [EventType.USER_SETTINGS_UPDATED], limit=limit, newest_first=True
)
history: list[DomainSettingsHistoryEntry] = []
for event in events:
for fld in event.changed_fields:
history.append(
DomainSettingsHistoryEntry(
timestamp=event.timestamp,
event_type=event.event_type,
field=f"/{fld}",
old_value=None,
new_value=getattr(event, fld, None),
reason=event.reason,
)
)
return history
GET /api/v1/user/settings/history returns one entry per changed field. new_value is read off the event, and old_value is always None. It reads the newest limit events (default 50) and returns them newest first.
POST /api/v1/user/settings/restore replays events up to the given timestamp onto defaults, saves the result as a snapshot, and publishes a UserSettingsUpdatedEvent with empty changed_fields and the restore as its reason. The snapshot's updated_at is the restore event's timestamp, so a later rebuild from that snapshot skips everything up to the restore and applies only changes made after it.
The replay only sees events that still exist, and events expire 30 days after they're stored (Event Storage). A field whose last change before the restore point has already expired comes back as its default, and nothing reports it.