Trim comments to the non-obvious why
Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+15
-65
@@ -13,18 +13,8 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Package handlers holds the REST endpoints and the shared Store that every
|
||||
// request handler — and, through graph.Resolver, every GraphQL resolver —
|
||||
// depends on.
|
||||
//
|
||||
// Store is the backend's dependency container: it is built once in main and
|
||||
// passed around by pointer, so the caches on it are shared process-wide.
|
||||
//
|
||||
// Concurrency note: the third-party caches below are read and written by
|
||||
// concurrent requests, so every access goes through cacheMu and the accessor
|
||||
// methods at the bottom of this file. Do not touch the cache fields directly
|
||||
// — an unsynchronised read of one of them is a data race, not merely a stale
|
||||
// value.
|
||||
// Store is the dependency container shared by every handler and resolver.
|
||||
// Cache fields are guarded by cacheMu: use the accessors, never the fields.
|
||||
type Store struct {
|
||||
DB *gorm.DB
|
||||
SpotifyAuth *spotifyauth.Authenticator
|
||||
@@ -33,63 +23,43 @@ type Store struct {
|
||||
Notes *services.Notes
|
||||
LoginLimiter *services.RateLimiter
|
||||
|
||||
// Base URL of the Python service on the Docker network, no trailing
|
||||
// slash. Used for the calls that bypass Caddy, all through
|
||||
// services.CallPython: reading a rowing display photo (handle_rowing.go).
|
||||
// The Python service on the Docker network, no trailing slash.
|
||||
PythonURL string
|
||||
|
||||
// Stores uploaded files and says where they are served
|
||||
// (services.Uploads.Save). Used by the Upload handler.
|
||||
Uploads *services.Uploads
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
// cacheMu guards every cache field below (and only those). One mutex for
|
||||
// all of them keeps the locking obvious; the critical sections are just
|
||||
// field copies, never network calls, so there is no contention worth
|
||||
// splitting it up for.
|
||||
cacheMu sync.RWMutex
|
||||
|
||||
RecentSongs *[]spotify.RecentlyPlayedItem
|
||||
RecentSongsFetchedAt time.Time
|
||||
|
||||
// Cached latest Gitea activity entry, 1 minute TTL.
|
||||
// 1 minute TTL.
|
||||
GiteaHost string
|
||||
GiteaPort string
|
||||
GiteaFeed *services.GiteaFeedResponse
|
||||
GiteaFeedFetchedAt time.Time
|
||||
|
||||
// Cached Steam status and recent games, 5 minute TTL.
|
||||
// 5 minute TTL.
|
||||
SteamAPIKey string
|
||||
SteamID string
|
||||
SteamRecentGames []services.SteamRecentGame
|
||||
SteamOnline bool
|
||||
SteamFetchedAt time.Time
|
||||
|
||||
// spotifyStates holds the one-shot CSRF nonces handed out by
|
||||
// GET /spotify/auth, mapped to their creation time. In-memory is enough:
|
||||
// there is one backend instance, and losing them on restart only means
|
||||
// restarting an OAuth flow that takes seconds.
|
||||
// One-shot OAuth CSRF nonces. In memory: a lost nonce only restarts a
|
||||
// seconds-long flow.
|
||||
spotifyStatesMu sync.Mutex
|
||||
spotifyStates map[string]time.Time
|
||||
|
||||
// spotifyNilLoggedAt rate-limits the "Spotify not authenticated" log line:
|
||||
// every page visit hits spotifyRecent, so an unauthenticated backend would
|
||||
// otherwise write a flood of identical lines. nil means "recently logged".
|
||||
// Every page visit would otherwise log "Spotify not authenticated".
|
||||
spotifyNilLoggedMu sync.Mutex
|
||||
spotifyNilLoggedAt time.Time
|
||||
}
|
||||
|
||||
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
|
||||
// enough to log in at Spotify and approve the scopes, short enough that a
|
||||
// leaked authorisation URL is not reusable later.
|
||||
const spotifyStateTTL = 10 * time.Minute
|
||||
|
||||
// NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation
|
||||
// URL and remembers it. Expired entries are pruned on the way through, which
|
||||
// is the only cleanup there is — the map is otherwise unbounded, and only an
|
||||
// admin can add to it.
|
||||
// NewSpotifyState mints a nonce. Pruning here is the only cleanup; only an
|
||||
// admin can add entries.
|
||||
func (s *Store) NewSpotifyState() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
@@ -112,9 +82,7 @@ func (s *Store) NewSpotifyState() (string, error) {
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// ConsumeSpotifyState checks a nonce returned by Spotify's redirect and
|
||||
// removes it, so a replayed callback fails. An unknown or expired nonce
|
||||
// returns false, which the callback must treat as a rejected request.
|
||||
// ConsumeSpotifyState removes the nonce, so a replayed callback fails.
|
||||
func (s *Store) ConsumeSpotifyState(state string) bool {
|
||||
if state == "" {
|
||||
return false
|
||||
@@ -131,15 +99,7 @@ func (s *Store) ConsumeSpotifyState(state string) bool {
|
||||
return time.Since(created) <= spotifyStateTTL
|
||||
}
|
||||
|
||||
// The cache accessors below are the only supported way to touch the cache
|
||||
// fields. Each "Cached..." method returns the value plus a bool that is true
|
||||
// only when the entry is present and inside its TTL; each "Set..." method
|
||||
// stores a value and stamps it.
|
||||
|
||||
// LogSpotifyUnauthenticated logs that the Spotify OAuth flow has never been
|
||||
// completed (or a stored token stopped working), with a where hint. It is
|
||||
// rate-limited to one line per hour — see spotifyNilLoggedAt — because
|
||||
// spotifyRecent is hit by every home-page visit.
|
||||
// LogSpotifyUnauthenticated logs at most once an hour.
|
||||
func (s *Store) LogSpotifyUnauthenticated(where string) {
|
||||
s.spotifyNilLoggedMu.Lock()
|
||||
defer s.spotifyNilLoggedMu.Unlock()
|
||||
@@ -150,9 +110,7 @@ func (s *Store) LogSpotifyUnauthenticated(where string) {
|
||||
log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where)
|
||||
}
|
||||
|
||||
// CachedRecentSongs returns the cached Spotify recently-played list if it is
|
||||
// within its one-minute TTL. An empty list counts as stale, so an empty
|
||||
// listening history is re-fetched every time (unchanged behaviour).
|
||||
// CachedRecentSongs treats an empty list as stale.
|
||||
func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
|
||||
s.cacheMu.RLock()
|
||||
defer s.cacheMu.RUnlock()
|
||||
@@ -166,7 +124,6 @@ func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
|
||||
return *s.RecentSongs, true
|
||||
}
|
||||
|
||||
// SetRecentSongs replaces the cached recently-played list.
|
||||
func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
|
||||
s.cacheMu.Lock()
|
||||
defer s.cacheMu.Unlock()
|
||||
@@ -175,9 +132,6 @@ func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
|
||||
s.RecentSongsFetchedAt = time.Now()
|
||||
}
|
||||
|
||||
// CachedGiteaFeed returns the cached Gitea activity entry if it is within its
|
||||
// one-minute TTL. A nil cache is never fresh, so the first request always hits
|
||||
// Gitea.
|
||||
func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
|
||||
s.cacheMu.RLock()
|
||||
defer s.cacheMu.RUnlock()
|
||||
@@ -188,7 +142,6 @@ func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
|
||||
return s.GiteaFeed, true
|
||||
}
|
||||
|
||||
// SetGiteaFeed replaces the cached Gitea feed entry.
|
||||
func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
|
||||
s.cacheMu.Lock()
|
||||
defer s.cacheMu.Unlock()
|
||||
@@ -197,10 +150,8 @@ func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
|
||||
s.GiteaFeedFetchedAt = time.Now()
|
||||
}
|
||||
|
||||
// CachedSteam returns the cached Steam recent games and online flag if they
|
||||
// are within their five-minute TTL. As before, freshness is judged only on the
|
||||
// games list: if Steam legitimately returns no recent games the cache never
|
||||
// registers as fresh and every request re-queries the API.
|
||||
// CachedSteam judges freshness on the games list only, so an empty list is
|
||||
// always re-fetched.
|
||||
func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) {
|
||||
s.cacheMu.RLock()
|
||||
defer s.cacheMu.RUnlock()
|
||||
@@ -211,7 +162,6 @@ func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok
|
||||
return s.SteamRecentGames, s.SteamOnline, true
|
||||
}
|
||||
|
||||
// SetSteam replaces the cached Steam data.
|
||||
func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) {
|
||||
s.cacheMu.Lock()
|
||||
defer s.cacheMu.Unlock()
|
||||
|
||||
Reference in New Issue
Block a user