Files
silo-server/internal/userstore/store.go
9aab2ead57 feat(settings): add user-facing device settings (#527)
* feat(settings): let users manage device settings across their devices

Adds the server half of the user-facing device settings screen: a viewer can
see the devices they watch on and change settings for any of them from
whichever device they are holding, and the household parent can do the same for
everyone on the account.

No schema change. user_devices and user_setting_values are already keyed
(user_id, profile_id, device_id), and both list queries are already
account-wide, so this is authorization plus routes.

Two identity widenings on the canonical settings API, each behind a guard:

- A caller may name a device_id other than the request's own. Authorized
  against user_devices for that profile, which is why DeviceExists lands
  first: completeIdentity validated an identity's shape but never that the
  device belonged to the caller, safe only while the id came from the header.
- A household parent may name a profile_id other than their own. Guarded by
  canManageHousehold, extracted from ProfileHandler so profile management and
  settings management cannot drift apart. Existence resolves through the
  caller's own store, so a foreign profile is 404 and the cross-account
  boundary holds for free.

Both default to today's behavior when the parameter is absent, so existing
clients need no change.

New self-service routes: GET /devices, DELETE /devices/{id}, and
DELETE /devices/{id}/settings. The list filters to the calling profile in the
handler — ListDevices is account-wide by construction in both backends (no
WHERE at all in the per-user SQLite), so a passthrough would have shown every
household member's devices to everyone. ?scope=household is opt-in and guarded.

Also fixes a bug the widening exposed: registerWritingDevice fired on every
device write, so writing to another device — or on another profile's behalf —
would have registered the actor's browser under the target, inventing a device
nobody holds.

Cross-profile and admin mutations are audited. The record carries identity
only, never the value, for the same reason user_settings.changed does: admins
receive other accounts' events. Ordinary self-service writes are not audited —
a trail that records everything answers nothing.

Part of #215

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(settings): add the user-facing device settings screen

Adds "Your devices" under Settings: a searchable device list and an editable
detail pane, so someone can fix how Silo behaves on any device they watch on
without borrowing that device. The household parent gets an "Everyone" switch
covering every profile on the account.

Layout is master-detail, and holds at eleven devices: fixed-height rows
carrying a name, when it was last used, and the one number that matters — how
many settings differ there. A device with nothing changed shows a dash rather
than a zero, so "which one did I change?" is answerable by scanning. Rows group
by recency, or by person in the household view.

Settings are grouped by what they affect — Picture, Sound, Subtitles,
Episodes — rather than in manifest order, and no raw key is ever shown: labels,
descriptions, controls, bounds and options all come from the contract. A test
asserts every device-scoped key lands in exactly one group or is deliberately
hidden, so a key added to the manifest cannot silently vanish from the screen.

Values round-trip as typed JSON rather than through strings, unlike the admin
console: a slider re-parsed from text is a hazard on a screen a viewer drives.

Policy caps are explained rather than hidden. A capped setting renders only the
permitted options and says which value the household limit displaced; a locked
one says so instead of presenting a disabled control with no reason.

Acting for someone else is stated, never implied — a persistent banner, and
reset actions that name the person ("Use Robin's setting"). The household view
also states what it does not show: this is how Silo is set up per device, not
what anyone watched.

Two fixes the work turned up:

- effectiveSettingsQueryKey was namespaced by active profile only, so reading
  another device's values would have collided with the current device's cache
  entry and served one device's settings as another's.
- The settings shell caps content at max-w-3xl, which is right for a single
  column of rows and squeezes a two-pane page. Pages that manage their own
  layout now opt out.

Part of #215

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(settings): filter the household device list by profile

Adds profile chips above the device list in the household view: Everyone, then
one per person, each with a device count. Picking a person narrows the list to
their devices; picking the active chip again clears it.

The chips only appear in the household view, where more than one profile is on
screen. A viewer looking at their own devices has exactly one profile, so a
filter with a single option would be chrome that explains nothing.

Three details the interaction needs to be honest:

- Counts come from the unfiltered list, so a chip keeps saying how many devices
  it would reveal instead of collapsing to zero once another chip is active.
- Grouping falls back to recency once a person is chosen, because a person
  heading would only repeat the chip above it.
- The detail pane follows the filter. Leaving someone else's device open while
  the list shows another person would make the list and the pane disagree about
  whose settings are being edited — the one thing this screen cannot be vague
  about. Leaving the household view clears the filter for the same reason.

The chip's count sits in its own element, so its accessible name is set
explicitly: without it a screen reader announces "Everyone3".

Part of #215

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(settings): lead the profile filter with the viewer's own chip

Seeding a realistic eight-profile household made the ordering problem obvious:
chips were in device-arrival order, which put the person actually using the
screen last. Their own profile now comes first and the rest sort by name, so a
chip stays where it was last seen rather than moving as devices are used.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(settings): make the device screen work on a phone

The screen was built two-pane and stacked those panes vertically on narrow
viewports, which is the wrong shape for a phone: the device list ran past a
thousand pixels before the first setting, so reaching "turn HDR off" meant
scrolling through every other device to get there. The whole page measured 4726
CSS pixels — 5.6 screens — for four devices.

Below xl the list and the settings are now two screens rather than two panes.
Picking a device swaps to it and a back control returns; the page header and
scope switch belong to the list screen, and the detail screen's own header says
which device it is about. The list page is 1050px, and scroll position resets on
each swap so a tap does not land mid-settings.

Touch targets were 32-36px throughout. Rows, chips, the scope switch, the reset
link and the header actions now clear 44px on a phone and keep their compact
desktop sizing from xl. Device rows carry a chevron below xl, because there they
navigate rather than select in place. The device search input goes to 16px on
mobile — iOS Safari zooms the viewport for anything smaller and does not zoom
back out.

Profile chips wrapped to three lines at eight profiles and pushed the list off
screen; they scroll horizontally on one line instead, the same trade the
settings shell's own mobile tab bar makes. Switches now sit beside their labels
rather than below, saving a row on each of ~18 toggles, while selects and
sliders still take the full width they need.

Two fixes the pass turned up, neither mobile-specific:

- playback.max_bitrate_kbps is declared as an integer range with a select
  control and no members, so it rendered as a dropdown with one blank entry —
  unusable, and silent about the value it was storing. It now offers real
  bandwidth choices bounded by the definition's own range, and keeps a
  non-preset stored value selectable.
- Select triggers had no accessible name, announcing as bare comboboxes.

Forget is destructive and rare, so it no longer sits as a full-width sibling of
the common action.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(settings): keep the device list usable at hundreds of devices

A real account carries 260 devices; the test fixtures had 14. Every browser
profile, private window, reinstall and test build registers a device identity
and nothing prunes them, so the list grew without limit — 13,681 CSS pixels,
sixteen screens, and the settings themselves never came into view. That is the
same failure the mobile pass just fixed, at a scale the fixtures never showed.

Three changes:

- The list is a bounded scroll area rather than an unbounded column. The page
  is now ~1,300px whatever the device count, and section headings stick while
  scrolling so the recency or person grouping stays legible.
- Devices nobody has used for 90 days that carry no settings of their own
  collapse behind "Show N unused devices". Over half of the real fleet is that:
  one-off sessions that never changed anything. The current device and anything
  with settings always stay visible, however old.
- Search spans everything including the hidden tail, because searching means
  looking for something specific and hiding a device from its own name would
  read as the device having vanished.

The 90-day threshold matches the settings contract's own rule for removing
empty device records, which is specified but not yet implemented server-side —
until it is, this keeps the screen usable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(settings): offer the whole bandwidth range the contract allows

The bandwidth cap stopped at 40 Mbps because the ladder behind it was a
hardcoded list I wrote, not anything the contract said. The definition allows
up to 200,000 kbps, and remuxed 4K HDR or an untouched Blu-ray rip needs well
past 40 — so the picker was silently capping people below what their own server
could already send them.

The ladder now runs to the definition's own ceiling. Its low end mirrors the
in-player quality switcher, so a cap chosen here lines up with what the player
offers mid-playback, and entries outside a definition's declared range are
filtered out as before.

Also stops duplicating the label format a third time: the player's
formatQualityBitrate is now exported and reused, since both surfaces pick from
the same ladder and should not disagree about how to spell a number.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* style(settings): use the app's overlay scrollbar in the device list

The bounded device list kept the browser's default scrollbar, which reads as a
heavy grey slab against a rounded dark panel. The app already has
.overlay-scroll for exactly this — a thin, low-contrast thumb over a
transparent track — and it now sits in the panel's gutter rather than flush
against the rounded edge.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* perf(settings): stop effective-values from stalling on live catalog language scans

GET /settings/values/effective computed suggested language values with
three sequential full-catalog scans on every request. On a 439k-item
deployment that took ~25s, dominated by the subtitle listing whose UNION
deduplicated ~5M unnested track rows.

- Deduplicate each subtitle arm before merging (UNION ALL of two
  DISTINCT arms instead of UNION across all rows) and bound the result
  with the facet LIMIT: 22.8s -> ~8.5s of per-arm work on that catalog.
- Cache the observed lists per (list kind, access scope) for 15 minutes
  and collapse concurrent misses with singleflight.
- Run the three lookups concurrently, and cap a cold-cache wait at 2s:
  the response ships with the contract floor while the detached scan
  finishes and fills the cache for the next request.

Part of the device settings screen work; the regression itself shipped
in #526.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(settings): replace track-language catalog scans with picker free entry

Deployment-observed suggestions now decorate catalog.metadata_language
only — original_language is one indexed DISTINCT scan (~0.2s on a 439k
item catalog) and feeds the metadata-exceptions panel, where observed
data is load-bearing. The audio and subtitle track listings (up to tens
of seconds of media-file walking) are no longer queried for settings at
all, which also removes the TTL cache and singleflight added to manage
them.

Those pickers keep the contract's authored floor and gain an explicit
escape hatch instead: a shared LanguageSelect with an "Other…" entry
that accepts a BCP 47 tag, previews the resolved language name, and
refuses invalid tags. The settings are open language_tag values, so a
typed tag needs no server change, and a stored off-floor value already
renders through the current-value merge. The device screen hides the
free entry when policy pins permitted_values.

The browse facet queries keep the subtitle UNION ALL rewrite from the
previous commit; catalog browse still lists observed track languages.

suggested_values on playback.audio_language and
playback.subtitle_language now returns only the contract floor plus the
stored value — Android and Apple pickers need the same free-entry
affordance as follow-up.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 11:00:15 -04:00

247 lines
17 KiB
Go

package userstore
import (
"context"
"encoding/json"
"errors"
"time"
)
var ErrCollectionGroupNotFound = errors.New("collection group not found")
// PreferenceSettingsWriter is the subset of the user store that participates
// in legacy-preference/canonical-setting synchronization. Implementations pass
// a transaction-scoped writer to WithPreferenceSettingsTransaction so callers
// can commit the legacy row and every canonical row as one unit.
type PreferenceSettingsWriter interface {
CreateProfile(ctx context.Context, profile Profile) error
ListSettings(ctx context.Context) ([]SettingEntry, error)
// ListProfileIDs reads the current household membership inside the same
// transaction as a legacy account-setting mutation. This closes the
// create/write window where a newly committed profile could miss fan-out.
ListProfileIDs(ctx context.Context) ([]string, error)
// UpdateProfile writes the legacy profile preference columns that shipped
// clients still mutate during the canonical-settings cutover.
UpdateProfile(ctx context.Context, id string, u UpdateProfileInput) error
SetSubtitlePreference(ctx context.Context, pref SubtitlePreference) error
DeleteSubtitlePreference(ctx context.Context, profileID, seriesID string) error
SetAudioPreference(ctx context.Context, pref AudioPreference) error
DeleteAudioPreference(ctx context.Context, profileID, seriesID string) error
UpsertLibraryPlaybackPreference(ctx context.Context, pref LibraryPlaybackPreference) error
DeleteLibraryPlaybackPreference(ctx context.Context, profileID string, libraryID int) error
SetSetting(ctx context.Context, key, value string) error
DeleteSetting(ctx context.Context, key string) error
SetDeviceSetting(ctx context.Context, entry DeviceSettingEntry) error
DeleteDeviceSetting(ctx context.Context, profileID, deviceID, key string) error
// UpsertSettingValue writes one explicit value and increments its revision.
UpsertSettingValue(ctx context.Context, id SettingIdentity, value json.RawMessage) (*SettingValue, error)
// DeleteSettingValue removes one explicit value and reports whether it existed.
DeleteSettingValue(ctx context.Context, id SettingIdentity) (bool, error)
}
// PreferenceSettingsTransactioner is implemented by stores that can atomically
// synchronize a shipped legacy preference row with its canonical values.
type PreferenceSettingsTransactioner interface {
WithPreferenceSettingsTransaction(ctx context.Context, fn func(PreferenceSettingsWriter) error) error
}
// UserStore defines the interface for per-user data storage.
// Both SQLite and Postgres backends implement this interface.
type UserStore interface {
// Profiles
CreateProfile(ctx context.Context, p Profile) error
GetProfile(ctx context.Context, id string) (*Profile, error)
ListProfiles(ctx context.Context) ([]Profile, error)
UpdateProfile(ctx context.Context, id string, u UpdateProfileInput) error
DeleteProfile(ctx context.Context, id string) error
VerifyPIN(ctx context.Context, profileID, pin string) (bool, error)
// Progress
UpdateProgress(ctx context.Context, profileID, mediaItemID string, position, duration float64, thresholds ProgressThresholds) error
SetProgress(ctx context.Context, profileID, mediaItemID string, position, duration float64, thresholds ProgressThresholds) error
SetProgressAt(ctx context.Context, profileID, mediaItemID string, position, duration float64, completed bool, updatedAt time.Time) error
SetProgressIfNewer(ctx context.Context, profileID, mediaItemID string, position, duration float64, completed bool, updatedAt time.Time) (bool, error)
UpdateProgressHints(ctx context.Context, profileID, mediaItemID string, hints VersionHints) error
MarkWatched(ctx context.Context, profileID, mediaItemID string, duration float64) error
MarkProgressBatch(ctx context.Context, profileID string, mediaItemIDs []string, updatedAt time.Time) error
ClearProgressBatch(ctx context.Context, profileID string, mediaItemIDs []string, updatedAt time.Time) error
ClearProgress(ctx context.Context, profileID, mediaItemID string) error
GetProgress(ctx context.Context, profileID, mediaItemID string) (*WatchProgress, error)
ListProgress(ctx context.Context, profileID, status string, limit, offset int) ([]WatchProgress, error)
// ListProgressFiltered is ListProgress with an additional SQL pre-filter on
// the backing catalog item's type and/or library, so the watched-items path
// no longer scans the whole status set before discarding non-matching rows.
// types is matched case-insensitively against media_items.type ("episode"
// resolves through the separate episodes table); a nil libraryID drops the
// library predicate, and an empty types + nil libraryID degrades to the
// plain status listing. It is a coarse pre-filter: callers still apply
// access/parental exclusions over the returned rows.
ListProgressFiltered(ctx context.Context, profileID, status string, types []string, libraryID *int, limit, offset int) ([]WatchProgress, error)
ListProgressByMediaItems(ctx context.Context, profileID string, mediaItemIDs []string) (map[string]WatchProgress, error)
// ListProgressSince returns rows whose server cursor exceeds the opaque
// cursor token (empty = full delta), in cursor order, with the next cursor.
// Cross-device delta delivery depends only on the server-assigned synced_seq.
ListProgressSince(ctx context.Context, profileID, cursor string) ([]WatchProgress, string, error)
AddHistory(ctx context.Context, entry WatchHistoryEntry) error
AddHistoryIfMissing(ctx context.Context, entry WatchHistoryEntry) (bool, error)
ListHistory(ctx context.Context, profileID string, limit, offset int) ([]WatchHistoryEntry, error)
ListCompletedHistory(ctx context.Context, query CompletedHistoryQuery) ([]WatchHistoryEntry, error)
ListCompletedHistoryItems(ctx context.Context, query CompletedHistoryItemQuery) ([]CompletedHistoryItem, error)
RemoveHistoryItems(ctx context.Context, profileID string, mediaItemIDs []string, removedAt time.Time) error
DeleteHistoryBySource(ctx context.Context, profileID string, mediaItemIDs []string, source WatchHistorySource) error
ListHomeDismissals(ctx context.Context, profileID, surface string) ([]HomeItemDismissal, error)
UpsertHomeDismissal(ctx context.Context, dismissal HomeItemDismissal) error
DeleteHomeDismissal(ctx context.Context, profileID, surface, mediaItemID string) error
// Favorites & Watchlist
AddFavorite(ctx context.Context, profileID, mediaItemID string) error
AddFavoriteAt(ctx context.Context, profileID, mediaItemID string, addedAt time.Time) (bool, error)
RemoveFavorite(ctx context.Context, profileID, mediaItemID string) error
ListFavorites(ctx context.Context, profileID string, limit, offset int) ([]Favorite, error)
ListFavoritesByMediaItems(ctx context.Context, profileID string, mediaItemIDs []string) (map[string]bool, error)
IsFavorite(ctx context.Context, profileID, mediaItemID string) (bool, error)
AddToWatchlist(ctx context.Context, profileID, mediaItemID string) error
AddToWatchlistAt(ctx context.Context, profileID, mediaItemID string, addedAt time.Time) (bool, error)
RemoveFromWatchlist(ctx context.Context, profileID, mediaItemID string) error
// ReplaceWatchlistOrder mirrors a provider's watchlist order: the given ids
// get sort_index 0..N-1 in order; all other rows reset to added_at ordering.
ReplaceWatchlistOrder(ctx context.Context, profileID string, orderedMediaItemIDs []string) error
ListWatchlist(ctx context.Context, profileID string, limit, offset int) ([]WatchlistEntry, error)
ListWatchlistByMediaItems(ctx context.Context, profileID string, mediaItemIDs []string) (map[string]bool, error)
InWatchlist(ctx context.Context, profileID, mediaItemID string) (bool, error)
// RemoveWatchedFromWatchlist reports the profile's preference for pruning
// fully-watched entries from the watchlist (defaults true): movies are
// removed outright on completion, while fully-watched series are only
// hidden from display so they reappear when new episodes are added.
RemoveWatchedFromWatchlist(ctx context.Context, profileID string) (bool, error)
// Collections
CreateCollection(ctx context.Context, input CreateCollectionInput) (*Collection, error)
GetCollection(ctx context.Context, id string) (*Collection, error)
ListCollections(ctx context.Context, profileID string) ([]Collection, error)
UpdateCollection(ctx context.Context, input UpdateCollectionInput) error
DeleteCollection(ctx context.Context, id string) error
AddCollectionItem(ctx context.Context, collectionID, mediaItemID string, position int) error
RemoveCollectionItem(ctx context.Context, collectionID, mediaItemID string) error
ListCollectionItems(ctx context.Context, collectionID string) ([]CollectionItem, error)
ReplaceCollectionItems(ctx context.Context, collectionID string, items []CollectionItemReplacement) error
ReorderCollectionItems(ctx context.Context, collectionID string, orderedMediaItemIDs []string) error
// ReorderCollections scopes to the supplied group_id. A nil groupID means
// the implicit Ungrouped bucket.
ReorderCollections(ctx context.Context, profileID string, groupID *string, orderedIDs []string) error
UpdateCollectionSyncState(ctx context.Context, input UpdateCollectionSyncStateInput) error
ListCollectionGroups(ctx context.Context) ([]CollectionGroup, error)
EnsureCollectionGroup(ctx context.Context, id string) error
CreateCollectionGroup(ctx context.Context, name, slug string, defaultSortMode GroupSortMode) (*CollectionGroup, error)
UpdateCollectionGroup(ctx context.Context, id string, name *string, slug *string, defaultSortMode *GroupSortMode) (*CollectionGroup, error)
DeleteCollectionGroup(ctx context.Context, id string) error
ReorderCollectionGroups(ctx context.Context, orderedIDs []string) error
// Section Overrides
ListSectionOverrides(ctx context.Context, profileID, scope, libraryID string) ([]SectionOverride, error)
SaveSectionOverrides(ctx context.Context, profileID, scope, libraryID string, overrides []SectionOverride) error
ResetSectionOverrides(ctx context.Context, profileID, scope, libraryID string) error
// Settings & Preferences
GetSetting(ctx context.Context, key string) (string, error)
SetSetting(ctx context.Context, key, value string) error
DeleteSetting(ctx context.Context, key string) error
ListSettings(ctx context.Context) ([]SettingEntry, error)
GetDeviceSetting(ctx context.Context, profileID, deviceID, key string) (*DeviceSettingEntry, error)
SetDeviceSetting(ctx context.Context, entry DeviceSettingEntry) error
DeleteDeviceSetting(ctx context.Context, profileID, deviceID, key string) error
DeleteAllDeviceSettings(ctx context.Context, profileID, deviceID string) error
DeleteDeviceSettingsByKey(ctx context.Context, key string) error
ListDeviceSettings(ctx context.Context, key string) ([]DeviceSettingEntry, error)
ListAllDeviceSettings(ctx context.Context) ([]DeviceSettingEntry, error)
SetSubtitlePreference(ctx context.Context, pref SubtitlePreference) error
GetSubtitlePreference(ctx context.Context, profileID, seriesID string) (*SubtitlePreference, error)
DeleteSubtitlePreference(ctx context.Context, profileID, seriesID string) error
SetAudioPreference(ctx context.Context, pref AudioPreference) error
GetAudioPreference(ctx context.Context, profileID, seriesID string) (*AudioPreference, error)
DeleteAudioPreference(ctx context.Context, profileID, seriesID string) error
SetSeriesPlaybackPreference(ctx context.Context, pref SeriesPlaybackPreference) error
GetSeriesPlaybackPreference(ctx context.Context, profileID, seriesID string) (*SeriesPlaybackPreference, error)
DeleteSeriesPlaybackPreference(ctx context.Context, profileID, seriesID string) error
GetLibraryPlaybackPreference(ctx context.Context, profileID string, libraryID int) (*LibraryPlaybackPreference, error)
ListLibraryPlaybackPreferences(ctx context.Context, profileID string) ([]LibraryPlaybackPreference, error)
UpsertLibraryPlaybackPreference(ctx context.Context, pref LibraryPlaybackPreference) error
DeleteLibraryPlaybackPreference(ctx context.Context, profileID string, libraryID int) error
// Onboarding
GetOnboardingState(ctx context.Context, profileID, tourID string) (*OnboardingState, error)
UpsertOnboardingState(ctx context.Context, state OnboardingState) error
// Jellyfin DisplayPreferences blobs, keyed by (prefs id, client) per user.
// They are the jellycompat subsystem's storage rather than user settings —
// the contract neither validates nor resolves them — so they live in the
// dedicated jellycompat_displayprefs table and hold opaque Jellyfin client
// JSON verbatim. Get returns "" when nothing is stored.
GetJellycompatDisplayPrefs(ctx context.Context, prefsID, client string) (string, error)
SetJellycompatDisplayPrefs(ctx context.Context, prefsID, client, value string) error
// Canonical typed setting values (contracts/settings/v1).
//
// These back the settings contract's storage layer. The manifest remains
// the schema; the store holds validated JSON keyed by scope identity, and
// knows nothing about definitions, defaults or resolution order.
// GetSettingValue returns the explicit value at exactly one scope, or nil
// when that identity is unset. It does not resolve fallbacks.
GetSettingValue(ctx context.Context, id SettingIdentity) (*SettingValue, error)
// ListSettingValuesForResolution returns every candidate row for one
// resolution request in a single query, unranked. The resolver applies each
// definition's resolution order in Go; issuing one lookup per scope is a
// rejected implementation.
ListSettingValuesForResolution(ctx context.Context, query SettingResolutionQuery) ([]SettingValue, error)
// ListAllSettingValues returns every explicit value this user has stored,
// across all scopes, in a stable (key, scope, identity) order. It serves
// the admin inspection surface; resolution reads keep going through
// ListSettingValuesForResolution.
ListAllSettingValues(ctx context.Context) ([]SettingValue, error)
// UpsertSettingValue writes the explicit value at one scope and increments
// that row's revision. Concurrent writes to one identity are
// last-write-wins in server receipt order; there is no compare-and-set
// precondition in v1.
UpsertSettingValue(ctx context.Context, id SettingIdentity, value json.RawMessage) (*SettingValue, error)
// DeleteSettingValue removes the explicit value at one scope — the `unset`
// operation — and reports whether a row existed.
DeleteSettingValue(ctx context.Context, id SettingIdentity) (bool, error)
// The scoped deletes below are application-enforced cleanup for identities
// this table cannot reference: the per-user SQLite store declares no foreign
// keys, and libraries, series and devices are not FK targets in Postgres
// either. Each removes only the rows scoped to the named entity.
DeleteSettingValuesForProfile(ctx context.Context, profileID string) (int64, error)
DeleteSettingValuesForDevice(ctx context.Context, profileID, deviceID string) (int64, error)
DeleteSettingValuesForLibrary(ctx context.Context, libraryID int) (int64, error)
DeleteSettingValuesForSeries(ctx context.Context, seriesID string) (int64, error)
// GetSettingMutation returns a recorded idempotency receipt, or nil.
GetSettingMutation(ctx context.Context, mutationID string) (*SettingMutationRecord, error)
// PutSettingMutation records a receipt without ever overwriting one. When
// the id is already recorded it returns the stored record with
// inserted=false, so the caller compares request hashes and answers
// already_applied or mutation_id_conflict.
PutSettingMutation(ctx context.Context, record SettingMutationRecord) (SettingMutationRecord, bool, error)
// DeleteExpiredSettingMutations removes receipts that expired before the
// given instant and reports how many. expires_at is not self-enforcing.
DeleteExpiredSettingMutations(ctx context.Context, before time.Time) (int64, error)
}
// DeviceRegistry is implemented by stores that track observed devices even
// when they do not currently have any device-scoped overrides.
type DeviceRegistry interface {
RegisterDevice(ctx context.Context, entry DeviceEntry) error
ListDevices(ctx context.Context) ([]DeviceEntry, error)
// DeviceExists reports whether one device is registered to one profile. It
// exists so a write naming a device can be authorized without scanning the
// whole account's registry: ListDevices is account-wide by construction, so
// filtering its result per write would read every household member's rows.
DeviceExists(ctx context.Context, profileID, deviceID string) (bool, error)
// ForgetDevice removes one profile's registry row for a device. Settings
// are deleted separately through the scoped setting deletes, so forgetting
// a device shared by two profiles leaves the other profile's row intact.
ForgetDevice(ctx context.Context, profileID, deviceID string) error
}