diff --git a/AGENTS.md b/AGENTS.md index b6f064d..34ee627 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ go vet ./... # type-check | Packages | Owner | |----------|-------| | `internal/logger`, `internal/ui`, `internal/ui/components`, `internal/mpris`, `internal/player` | Shared by pine and spruce | -| `internal/abs`, `internal/app`, `internal/cache`, `internal/captions`, `internal/config`, `internal/db`, `internal/screens` | pine | +| `internal/abs`, `internal/app`, `internal/cache`, `internal/captions`, `internal/config`, `internal/db`, `internal/screens`, `internal/systemsleep` | pine | | `internal/spruce/app`, `internal/spruce/buildinfo`, `internal/spruce/config`, `internal/spruce/jellyfin`, `internal/spruce/screens` | spruce | Rules: @@ -82,7 +82,7 @@ The Architecture Map below describes pine and the shared packages. | Screen | Key files | Notes | |--------|-----------|-------| | `login` | model.go, view.go | 3-field form (server, username, password), tab navigation | -| `home` | model.go, view.go | Personalized shelves: continue-listening + recently-added. Library switching with tab. Item/recent caches per library. Skeleton loading with 500ms reveal delay. | +| `home` | model.go, view.go | Personalized shelves: continue-listening + recently-added. Library switching with tab. Item/recent caches per library. Skeleton loading with 500ms reveal delay. At start and on a tab switch, `fetchPersonalizedCmd(false, true)` reads only the local cache, expired entries included, and the answer has `cached`. The answer of the server for the same load replaces it. A cached answer applies until the server answers the load with no error (`serverAnswered`), so it also applies after a fast error of the server. A load that reads the library list, at the start or with `RefreshCmd`, has `refreshed`: its answer replaces the list and selects the library by its ID, so the list of the server replaces an old cached list. A failed load keeps the shown shelves of the selected library and goes to the log. A 401 opens the login screen: the root model checks `PersonalizedMsg.Err` with `checkUnauthorized` before the home screen gets the message. | | `library` | model.go, view.go | Paginated item list (50/page), infinite scroll prefetch at 80%, per-library page cache shared with search cache. Library switching with tab. | | `detail` | model.go, view.go | Viewport-scrollable content: description, series row, episodes list (podcasts), bookmarks list, inline bookmark editing, item deletion. Tab cycles focus between sections. | | `metadataedit` | model.go, view.go | Inline metadata editor for books and podcast episodes. | @@ -95,9 +95,9 @@ The Architecture Map below describes pine and the shared packages. | File | Responsibility | |------|---------------| -| `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly. On a miss, it fetches from the API in the command of the caller and stores the result. Each cached method calls `cached(c, key, ttl, fetch)`, which returns the data of the server. A cache read or write error goes to the log and does not fail the request. A fetch that started before an invalidation does not store its value (`generation`, under `mu`). `Invalidate` calls `OnInvalidate` also when the store is nil. | +| `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly. On a miss, it fetches from the API in the command of the caller and stores the result. Each cached method calls `cached(ctx, c, key, ttl, fetch)`, which returns the data of the server. With a `CachedOnly(ctx)` context, `cached` answers from the cache, also from an expired entry, sends no request, and returns `ErrNotCached` if the cache has no entry. A cache read or write error goes to the log and does not fail the request. A fetch that started before an invalidation does not store its value (`generation`, under `mu`). `Invalidate` calls `OnInvalidate` also when the store is nil. | | `keys.go` | The names of all cache keys. Code outside the package uses `ItemKey`, `PersonalizedKey`, `SeriesContentsKey`, `BookmarksKey`, and `SearchSnapshotKey`, not key strings. A key has no account, so a login (`LoginSuccessMsg`) clears the persistent cache with `ClearAll`. | -| `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v2-`). Raise it when the type of a cached value changes. | +| `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v2-`). Raise it when the type of a cached value changes. `Get` misses an expired entry. `GetStale` reads an entry until `keepExpired` (30 days) after it expires, and `EvictExpired` deletes it after that time. `Expire` makes a fresh entry expired now. A stop expires the home shelves of the library with it (`evictProgressCaches`), so that the next start can show them from the cache. | ### MPRIS (internal/mpris/, shared) @@ -110,6 +110,12 @@ The Architecture Map below describes pine and the shared packages. The server is written from the MPRIS 2.2 specification. The Go MPRIS server library that exists is GPL-3.0, and a GPL module makes the release binaries GPL. Do not add a module with a copyleft license. +### System sleep (internal/systemsleep/) + +`Start(who, prepare)` connects to the system bus and holds a logind sleep delay inhibitor. On `PrepareForSleep(true)`, it calls `prepare(release)` in a goroutine, and it releases the inhibitor when `prepare` calls `release`, or after 10 s, the timeout of an `abs.Client` request. After the wake, it takes a new inhibitor. It waits at most 3 s (`inhibitTimeout`) for an answer to `Inhibit`, and without an answer it runs with no inhibitor. Without a system bus (macOS, Windows), `Start` logs the cause and returns nil, and a nil `Monitor` is valid. The name keeps the package apart from the sleep timer. + +`main.go` sends `SystemSleepMsg` to the program. `handleSystemSleep` in `playback.go` stops the playback with `stopPlayback` and calls `Release` after the stop commands in a `tea.Sequence`. pine does not play on after the wake, and the next play takes the position of the server. A start or a change of the track can be in progress with no session yet: `handleSystemSleep` raises `sleepEpoch`, each command that asks for a play session stamps the `PlaySessionMsg` with the epoch of its creation, and `Update` closes a session of an earlier epoch with `closeRestoredSessionCmd` and does not play it. A change of the track (`restartPlaybackAt`) keeps `itemID` with no session, so `handleSystemSleep` also stops then, and quits mpv. NetworkManager can take the network down before the requests end, so the position since the last sync can be lost. + ### API (internal/abs/) | File | Responsibility | @@ -174,6 +180,8 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - `internal/mpris/mpris_test.go` for `RootAdapter` and the server properties, and `bridge_test.go` for the bridge - `internal/mpris/server_linux_test.go` starts the MPRIS server on a private session bus and checks it as an MPRIS client. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead. CI and `scripts/release.sh` set that variable. - `internal/app/mpris_linux_test.go` starts the MPRIS server of the pine model on a private session bus and checks the Seeked signals. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead. +- `internal/systemsleep/systemsleep_linux_test.go` runs a fake logind on a private session bus. Each inhibitor is the write end of a pipe, so the test sees the release as EOF on the read end. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead. +- `runCmdToEnd` in `internal/app/playback_test.go` runs a command as the Bubble Tea program does, also a `tea.Sequence`. `feedCmd` and `executeBatchCmds` run only batches. - `internal/screens/metadataedit/model_test.go` for the metadata editor - Screen models have individual `*_test.go` files - `internal/player/libmpv_test.go`, `mpv_test.go`, and `group_test.go` play audio through the real libmpv with `ao=null`. They skip if libmpv is absent. With `PINE_REQUIRE_LIBMPV=1` they fail instead. `scripts/release.sh` sets that variable. diff --git a/README.md b/README.md index 409a247..a283449 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ The remaining sections describe pine. For spruce, see [docs/spruce/README.md](do - In-place filtering (`/`) on home, library, and series lists - Metadata editor for books and episodes - MPRIS media-key support on Linux +- Stop of the playback before the system sleeps, on Linux with logind, so that pine is silent after the wake - Bookmarks — create, edit, navigate to, and delete - Listening sessions (`R`) — see where each device stopped, and play from that position - Sleep timer diff --git a/internal/app/messages.go b/internal/app/messages.go index 8b5bdc9..67b84e4 100644 --- a/internal/app/messages.go +++ b/internal/app/messages.go @@ -57,6 +57,9 @@ type PlaySessionMsg struct { Session PlaySessionData StreamURL string AuthToken string + // SleepEpoch is the sleepEpoch of the model when the command asked for + // the session. A session from before a system sleep does not play. + SleepEpoch uint64 } // PlaySessionData carries the data returned from ABS when starting a session. @@ -89,6 +92,13 @@ type SyncTickMsg struct { Generation uint64 } +// SystemSleepMsg tells that the system prepares to sleep. The model stops the +// playback, and it calls Release when the stop has sent its requests, so +// that logind can continue. +type SystemSleepMsg struct { + Release func() +} + // SessionSyncedMsg carries the result of a sync of the playback session. // NewSessionID is the session that pine opened because the server did not // have the session SessionID. diff --git a/internal/app/model.go b/internal/app/model.go index 3a5d12b..43fd450 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -87,6 +87,11 @@ type Model struct { // of the last session at the start then does nothing. playRequested bool + // sleepEpoch counts the system sleeps. A command that asks for a play + // session stamps the session with it, and pine closes a session from an + // earlier epoch and does not play it (see PlaySessionMsg.SleepEpoch). + sleepEpoch uint64 + // The library and the series of the item that plays: for the cache // eviction after the playback, and for the series auto-continue. playbackLibraryID string @@ -469,6 +474,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case home.PersonalizedMsg: + // The home screen keeps its shelves on a failed load, so a 401 must + // open the login screen here. + if msg.Err != nil { + if m2, cmd, ok := m.checkUnauthorized(msg.Err); ok { + return m2, cmd + } + } var cmd tea.Cmd m.home, cmd = m.home.Update(msg) cmds := []tea.Cmd{} @@ -713,6 +725,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.handleCaptionLoaded(msg) case PlaySessionMsg: + if msg.SleepEpoch != m.sleepEpoch { + return m, m.closeSessionFromBeforeSleep(msg.Session) + } logger.Info("play session started", "session", abs.SessionTag(msg.Session.SessionID), "itemID", msg.Session.ItemID, "episodeID", msg.Session.EpisodeID, "currentTime", msg.Session.CurrentTime, "duration", msg.Session.Duration) return m.handlePlaySessionMsg(msg) @@ -735,6 +750,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, m.startRestorePlaybackCmd(msg) case RestorePlaySessionMsg: + if msg.PlaySessionMsg.SleepEpoch != m.sleepEpoch { + return m, m.closeSessionFromBeforeSleep(msg.PlaySessionMsg.Session) + } if m.isPlaying() || m.playRequested { session := msg.PlaySessionMsg.Session logger.Info("closing restored session: the user started a playback", "session", abs.SessionTag(session.SessionID), "itemID", session.ItemID) @@ -757,6 +775,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, cmd + case SystemSleepMsg: + return m.handleSystemSleep(msg) + case SessionSyncedMsg: return m.handleSessionSynced(msg), nil diff --git a/internal/app/model_test.go b/internal/app/model_test.go index c42813c..6b931f9 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -2817,3 +2817,19 @@ func TestMetadataSavedKeepsDetailProgress(t *testing.T) { t.Errorf("detail progress = %+v, want the finished progress", got.UserMediaProgress) } } + +// TestHomeLoadUnauthorizedOpensLogin verifies that a 401 from the load of the +// home shelves opens the login screen, also when the home screen shows +// cached shelves and keeps them on other errors. +func TestHomeLoadUnauthorizedOpensLogin(t *testing.T) { + m := newTestModelAuthenticated() + if m.screen != ScreenHome { + t.Fatalf("screen = %v, want home", m.screen) + } + err := fmt.Errorf("fetch personalized: %w", &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}) + + result, _ := m.Update(home.PersonalizedMsg{Err: err}) + m = result.(Model) + + assertScreen(t, m, ScreenLogin) +} diff --git a/internal/app/playback.go b/internal/app/playback.go index f797744..17d1252 100644 --- a/internal/app/playback.go +++ b/internal/app/playback.go @@ -171,6 +171,7 @@ func (m Model) handlePlayCmd(msg detail.PlayCmd) (Model, tea.Cmd) { item := msg.Item client := m.client + sleepEpoch := m.sleepEpoch startCmd := func() tea.Msg { device := m.playbackDevice() session, err := client.StartPlaySession(context.Background(), item.ID, device) @@ -189,6 +190,7 @@ func (m Model) handlePlayCmd(msg detail.PlayCmd) (Model, tea.Cmd) { if err != nil { return PlaybackErrorMsg{Err: err} } + playMsg.SleepEpoch = sleepEpoch return playMsg } @@ -230,6 +232,7 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd) item := msg.Item episode := msg.Episode client := m.client + sleepEpoch := m.sleepEpoch startCmd := func() tea.Msg { device := m.playbackDevice() session, err := client.StartEpisodePlaySession(context.Background(), item.ID, episode.ID, device) @@ -240,6 +243,7 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd) if err != nil { return PlaybackErrorMsg{Err: err} } + playMsg.SleepEpoch = sleepEpoch return playMsg } @@ -518,6 +522,7 @@ func (m Model) restartPlaybackAt(bookPos float64) (Model, tea.Cmd) { m.sessionID = "" m.timeListened = 0 m.captionCues = nil + sleepEpoch := m.sleepEpoch return m, func() tea.Msg { if client != nil && sessionID != "" { @@ -537,12 +542,14 @@ func (m Model) restartPlaybackAt(bookPos float64) (Model, tea.Cmd) { if err != nil { return PlaybackErrorMsg{Err: err} } + playMsg.SleepEpoch = sleepEpoch return playMsg } } func (m Model) startPlaybackAtBookPositionCmd(item abs.LibraryItem, bookPos float64) tea.Cmd { client := m.client + sleepEpoch := m.sleepEpoch return func() tea.Msg { device := m.playbackDevice() session, err := client.StartPlaySession(context.Background(), item.ID, device) @@ -561,6 +568,7 @@ func (m Model) startPlaybackAtBookPositionCmd(item abs.LibraryItem, bookPos floa if err != nil { return PlaybackErrorMsg{Err: err} } + playMsg.SleepEpoch = sleepEpoch return playMsg } } @@ -594,6 +602,7 @@ func (m Model) playItemAt(item abs.LibraryItem, episode *abs.PodcastEpisode, pos func (m Model) startEpisodePlaybackAtPositionCmd(item abs.LibraryItem, episode abs.PodcastEpisode, pos float64) tea.Cmd { client := m.client + sleepEpoch := m.sleepEpoch return func() tea.Msg { device := m.playbackDevice() session, err := client.StartEpisodePlaySession(context.Background(), item.ID, episode.ID, device) @@ -604,6 +613,7 @@ func (m Model) startEpisodePlaybackAtPositionCmd(item abs.LibraryItem, episode a if err != nil { return PlaybackErrorMsg{Err: err} } + playMsg.SleepEpoch = sleepEpoch return playMsg } } @@ -626,15 +636,16 @@ func (m Model) startRestorePlaybackCmd(msg RestoreSessionMsg) tea.Cmd { return m.startRestoredBookPlaybackCmd(*msg.Item) } -// closeRestoredSessionCmd closes a session that the restore opened and that -// pine does not play. The session has no position to send. +// closeRestoredSessionCmd closes a session that pine opened and does not play: +// a restore that the user superseded, or a session that a command asked for +// before the system slept. The session has no position to send. func closeRestoredSessionCmd(client *cache.Client, sessionID string) tea.Cmd { if client == nil || sessionID == "" { return nil } return func() tea.Msg { if err := client.CloseSessionNoSync(context.Background(), sessionID); err != nil { - logger.Warn("failed to close restored session", "session", abs.SessionTag(sessionID), "err", err) + logger.Warn("failed to close an unused session", "session", abs.SessionTag(sessionID), "err", err) } return nil } @@ -643,6 +654,7 @@ func closeRestoredSessionCmd(client *cache.Client, sessionID string) tea.Cmd { func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd { client := m.client store := m.db + sleepEpoch := m.sleepEpoch return func() tea.Msg { device := m.playbackDevice() session, err := client.StartPlaySession(context.Background(), item.ID, device) @@ -681,6 +693,7 @@ func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd { logSkippedRestore("book playback session invalid", "itemID", item.ID, "session", abs.SessionTag(session.ID), "err", err) return nil } + playMsg.SleepEpoch = sleepEpoch return RestorePlaySessionMsg{PlaySessionMsg: playMsg} } } @@ -688,6 +701,7 @@ func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd { func (m Model) startRestoredEpisodePlaybackCmd(item abs.LibraryItem, episode abs.PodcastEpisode) tea.Cmd { client := m.client store := m.db + sleepEpoch := m.sleepEpoch return func() tea.Msg { device := m.playbackDevice() session, err := client.StartEpisodePlaySession(context.Background(), item.ID, episode.ID, device) @@ -720,6 +734,7 @@ func (m Model) startRestoredEpisodePlaybackCmd(item abs.LibraryItem, episode abs logSkippedRestore("podcast episode playback session invalid", "itemID", item.ID, "episodeID", episode.ID, "session", abs.SessionTag(session.ID), "err", err) return nil } + playMsg.SleepEpoch = sleepEpoch return RestorePlaySessionMsg{PlaySessionMsg: playMsg} } } @@ -969,14 +984,16 @@ func (m Model) handleSessionSynced(msg SessionSyncedMsg) Model { } // evictProgressCaches drops cached data that embeds user progress for an item: -// the library item, the home shelves, and the series view. +// the library item, the home shelves, and the series view. The home shelves +// only expire, so that the next start can show them from the cache before +// the server answers. func evictProgressCaches(store *cache.Store, itemID, libraryID, seriesID string) { if store == nil || itemID == "" { return } _ = store.Delete(cache.ItemKey(itemID)) if libraryID != "" { - _ = store.Delete(cache.PersonalizedKey(libraryID)) + _ = store.Expire(cache.PersonalizedKey(libraryID)) } if seriesID != "" { _ = store.Delete(cache.SeriesContentsKey(seriesID)) @@ -1067,6 +1084,40 @@ func (m Model) stopPlayback() (Model, tea.Cmd) { return m, tea.Batch(closeCmd, stopCmd) } +// handleSystemSleep stops the playback before the system sleeps, so that it +// does not play on after the wake, and so that a later sync cannot replace +// newer progress of another device. The next play takes the position of the +// server. Release runs after each stop command has ended. A network that is +// already down makes the requests fail, and the position since the last sync +// is then lost. +// +// A start or a change of the track can be in progress with no session yet. +// The new sleep epoch makes pine close the session that such a command gets, +// and a change of the track that keeps the item (restartPlaybackAt) stops +// here, so that mpv does not play on. +func (m Model) handleSystemSleep(msg SystemSleepMsg) (Model, tea.Cmd) { + release := func() tea.Msg { + if msg.Release != nil { + msg.Release() + } + return nil + } + m.sleepEpoch++ + if !m.isPlaying() && m.itemID == "" { + return m, release + } + logger.Info("system sleep: stopping playback", "session", abs.SessionTag(m.sessionID), "itemID", m.itemID) + m, stopCmd := m.stopPlayback() + return m, tea.Sequence(stopCmd, release) +} + +// closeSessionFromBeforeSleep closes a play session that a command asked for +// before the system slept, and does not play it. +func (m Model) closeSessionFromBeforeSleep(session PlaySessionData) tea.Cmd { + logger.Info("system sleep: closing a play session from before the sleep", "session", abs.SessionTag(session.SessionID), "itemID", session.ItemID, "episodeID", session.EpisodeID) + return closeRestoredSessionCmd(m.client, session.SessionID) +} + // stopPlaybackCmds stops the playback as stopPlayback does. It returns the // close of the session apart from the other cleanup commands, so that a // caller can run a play request after the close with closeThen. diff --git a/internal/app/playback_test.go b/internal/app/playback_test.go index e40eb6c..197ea01 100644 --- a/internal/app/playback_test.go +++ b/internal/app/playback_test.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "reflect" "strings" "sync" "testing" @@ -2296,3 +2297,219 @@ func TestRestoredSessionClosedWhilePlaying(t *testing.T) { t.Error("pine closed the session of the playback") } } + +// runCmdToEnd runs cmd and the commands that it returns until each one has +// ended, as the Bubble Tea program does: the commands of a batch run at the +// same time, and the commands of a sequence run in order. Bubble Tea does not +// export the type of a sequence, so the helper finds it as a slice of +// tea.Cmd. +func runCmdToEnd(cmd tea.Cmd) { + if cmd == nil { + return + } + msg := cmd() + if batch, ok := msg.(tea.BatchMsg); ok { + var wg sync.WaitGroup + for _, c := range batch { + wg.Add(1) + go func() { + defer wg.Done() + runCmdToEnd(c) + }() + } + wg.Wait() + return + } + v := reflect.ValueOf(msg) + if v.Kind() == reflect.Slice && v.Type().Elem() == reflect.TypeFor[tea.Cmd]() { + for i := range v.Len() { + runCmdToEnd(v.Index(i).Interface().(tea.Cmd)) + } + } +} + +// TestSystemSleepStopsPlaybackBeforeRelease verifies that pine stops the +// playback before the system sleeps, and that it releases logind only after +// the server got the close of the session. +func TestSystemSleepStopsPlaybackBeforeRelease(t *testing.T) { + book := testLibraryItem("book-001", "A Book") + log, client := newFakeABS(t, map[string]abs.PlaySession{ + "/api/items/book-001/play": { + ID: "sess-sleep", + AudioTracks: []abs.AudioTrack{{ContentURL: "/s/audio.mp3", Duration: 1800}}, + }, + }, nil) + m := NewWithPlayer(config.Default(), nil, client, nil, &mockPlayer{}) + m, cmd := m.handlePlayCmd(detail.PlayCmd{Item: book}) + m, _ = feedCmdWithin(m, cmd, slowCmdWait) + if !m.isPlaying() { + t.Fatal("the playback did not start") + } + m.player.Position = 120 + + released := false + closesAtRelease := 0 + result, cmd := m.Update(SystemSleepMsg{Release: func() { + released = true + closesAtRelease = log.count(http.MethodPost, "/api/session/sess-sleep/close") + }}) + m = result.(Model) + if m.isPlaying() { + t.Error("the playback continues after the sleep signal") + } + runCmdToEnd(cmd) + if !released { + t.Fatal("pine did not release logind") + } + if closesAtRelease != 1 { + t.Errorf("closes of the session before the release = %d, want 1", closesAtRelease) + } +} + +// TestSystemSleepWithoutPlaybackReleases verifies that pine releases logind +// at once when nothing plays. +func TestSystemSleepWithoutPlaybackReleases(t *testing.T) { + m := newPlaybackTestModel() + released := false + _, cmd := m.Update(SystemSleepMsg{Release: func() { released = true }}) + runCmdToEnd(cmd) + if !released { + t.Error("pine did not release logind") + } +} + +// TestSystemSleepDropsPlaySessionAskedBeforeSleep verifies that a play +// session that a command asked for before the system slept does not play: +// pine closes it. Before the sleep, a start or a change of the track has no +// session yet. +func TestSystemSleepDropsPlaySessionAskedBeforeSleep(t *testing.T) { + book := testLibraryItem("book-001", "A Book") + sessions := map[string]abs.PlaySession{ + "/api/items/book-001/play": { + ID: "sess-sleep", + AudioTracks: []abs.AudioTrack{{ContentURL: "/s/audio.mp3", Duration: 1800}}, + }, + } + sleep := func(t *testing.T, m Model) Model { + t.Helper() + released := false + result, cmd := m.Update(SystemSleepMsg{Release: func() { released = true }}) + runCmdToEnd(cmd) + if !released { + t.Fatal("pine did not release logind") + } + return result.(Model) + } + assertNotPlayed := func(t *testing.T, m Model, mp *mockPlayer, msg tea.Msg) { + t.Helper() + if _, ok := msg.(PlaySessionMsg); !ok { + t.Fatalf("the command gave %T, want PlaySessionMsg", msg) + } + result, cmd := m.Update(msg) + m = result.(Model) + runCmdToEnd(cmd) + if m.isPlaying() { + t.Error("the session from before the sleep plays") + } + mp.mu.Lock() + launched := mp.launched + mp.mu.Unlock() + if launched { + t.Error("mpv started for the session from before the sleep") + } + } + + t.Run("start", func(t *testing.T) { + log, client := newFakeABS(t, sessions, nil) + mp := &mockPlayer{} + m := NewWithPlayer(config.Default(), nil, client, nil, mp) + m, startCmd := m.handlePlayCmd(detail.PlayCmd{Item: book}) + + m = sleep(t, m) + assertNotPlayed(t, m, mp, startCmd()) + if n := log.count(http.MethodPost, "/api/session/sess-sleep/close"); n != 1 { + t.Errorf("closes of the new session = %d, want 1", n) + } + }) + + t.Run("change of the track", func(t *testing.T) { + log, client := newFakeABS(t, sessions, nil) + mp := &mockPlayer{} + m := NewWithPlayer(config.Default(), nil, client, nil, mp) + m, cmd := m.handlePlayCmd(detail.PlayCmd{Item: book}) + m, _ = feedCmdWithin(m, cmd, slowCmdWait) + if !m.isPlaying() { + t.Fatal("the playback did not start") + } + mp.mu.Lock() + mp.launched = false + mp.mu.Unlock() + m, restartCmd := m.restartPlaybackAt(900) + + m = sleep(t, m) + mp.mu.Lock() + quit := mp.quit + mp.mu.Unlock() + if !quit { + t.Error("mpv was not quit before the sleep") + } + assertNotPlayed(t, m, mp, restartCmd()) + // The restart closes the old session, and pine closes the new one. + if n := log.count(http.MethodPost, "/api/session/sess-sleep/close"); n != 2 { + t.Errorf("closes of the sessions = %d, want 2", n) + } + }) + + t.Run("restore", func(t *testing.T) { + log, client := newFakeABS(t, sessions, nil) + mp := &mockPlayer{} + m := NewWithPlayer(config.Default(), nil, client, nil, mp) + restoreCmd := m.startRestoredBookPlaybackCmd(book) + + m = sleep(t, m) + msg, ok := restoreCmd().(RestorePlaySessionMsg) + if !ok { + t.Fatal("the restore gave no RestorePlaySessionMsg") + } + result, cmd := m.Update(msg) + m = result.(Model) + runCmdToEnd(cmd) + if m.isPlaying() || m.restorePaused { + t.Errorf("playing = %v, restorePaused = %v after a restore from before the sleep, want false", m.isPlaying(), m.restorePaused) + } + if n := log.count(http.MethodPost, "/api/session/sess-sleep/close"); n != 1 { + t.Errorf("closes of the restored session = %d, want 1", n) + } + }) +} + +// TestStopKeepsHomeShelvesForTheNextStart verifies that a stop expires the +// shelves of the library, so that the next load asks the server, and that +// the next start can still show them from the cache. +func TestStopKeepsHomeShelvesForTheNextStart(t *testing.T) { + book := testLibraryItem("book-001", "A Book") + book.LibraryID = "lib-books" + _, client := newFakeABS(t, map[string]abs.PlaySession{ + "/api/items/book-001/play": { + ID: "sess-new", + AudioTracks: []abs.AudioTrack{{ContentURL: "/s/audio.mp3", Duration: 1800}}, + }, + }, nil) + cacheStore := newTestCacheStore(t) + m := NewWithPlayer(config.Default(), nil, client, cacheStore, &mockPlayer{}) + m, cmd := m.handlePlayCmd(detail.PlayCmd{Item: book}) + m, _ = feedCmdWithin(m, cmd, slowCmdWait) + if !m.isPlaying() { + t.Fatal("the playback did not start") + } + seedCache(t, cacheStore, cache.PersonalizedKey("lib-books"), []abs.PersonalizedResponse{{ID: "continue-listening"}}) + + m, cmd = m.stopPlayback() + feedCmdWithin(m, cmd, slowCmdWait) + + assertEvicted[[]abs.PersonalizedResponse](t, cacheStore, cache.PersonalizedKey("lib-books")) + var shelves []abs.PersonalizedResponse + if hit, err := cacheStore.GetStale(cache.PersonalizedKey("lib-books"), &shelves); err != nil || !hit { + t.Fatalf("GetStale = (%v, %v) after the stop, want the expired shelves", hit, err) + } +} diff --git a/internal/cache/client.go b/internal/cache/client.go index f1a6876..ec2e819 100644 --- a/internal/cache/client.go +++ b/internal/cache/client.go @@ -2,6 +2,7 @@ package cache import ( "context" + "errors" "sync" "time" @@ -46,11 +47,27 @@ func NewClient(inner *abs.Client, store *Store) *Client { } } +// ErrNotCached is the error of a read with a CachedOnly context that finds no +// entry. +var ErrNotCached = errors.New("not in the cache") + +type cachedOnlyKey struct{} + +// CachedOnly returns a context for reads that answer only from the local +// cache, also from an expired entry, and send no request. A read that finds +// no entry returns ErrNotCached. +func CachedOnly(ctx context.Context) context.Context { + return context.WithValue(ctx, cachedOnlyKey{}, true) +} + // cached returns the cached value of key, or calls fetch and caches its // result for ttl. The cache only makes a request faster: a read or a write // error of the cache goes to the log, and the caller gets the value of the -// server. -func cached[T any](c *Client, key string, ttl time.Duration, fetch func() (T, error)) (T, error) { +// server. With a CachedOnly context, cached never calls fetch. +func cached[T any](ctx context.Context, c *Client, key string, ttl time.Duration, fetch func() (T, error)) (T, error) { + if ctx.Value(cachedOnlyKey{}) != nil { + return cachedOnly[T](c, key) + } if c.store == nil { return fetch() } @@ -79,23 +96,41 @@ func cached[T any](c *Client, key string, ttl time.Duration, fetch func() (T, er return v, nil } +// cachedOnly returns the cached value of key, also an expired one. +func cachedOnly[T any](c *Client, key string) (T, error) { + var zero T + if c.store == nil { + return zero, ErrNotCached + } + var v T + hit, err := c.store.GetStale(key, &v) + if err != nil { + logger.Warn("cache read failed", "key", key, "err", err) + return zero, ErrNotCached + } + if !hit { + return zero, ErrNotCached + } + return v, nil +} + // GetLibraries returns libraries from cache or fetches from the API. func (c *Client) GetLibraries(ctx context.Context) ([]abs.Library, error) { - return cached(c, librariesKey, ttlLibraries, func() ([]abs.Library, error) { + return cached(ctx, c, librariesKey, ttlLibraries, func() ([]abs.Library, error) { return c.Client.GetLibraries(ctx) }) } // GetPersonalized returns personalized shelves from cache or fetches from the API. func (c *Client) GetPersonalized(ctx context.Context, libraryID string) ([]abs.PersonalizedResponse, error) { - return cached(c, PersonalizedKey(libraryID), ttlPersonalized, func() ([]abs.PersonalizedResponse, error) { + return cached(ctx, c, PersonalizedKey(libraryID), ttlPersonalized, func() ([]abs.PersonalizedResponse, error) { return c.Client.GetPersonalized(ctx, libraryID) }) } // GetRecentEpisodes returns recent podcast episodes from cache or fetches from the API. func (c *Client) GetRecentEpisodes(ctx context.Context, libraryID string, limit int) ([]abs.LibraryItem, error) { - return cached(c, recentEpisodesKey(libraryID, limit), ttlRecentEpisodes, func() ([]abs.LibraryItem, error) { + return cached(ctx, c, recentEpisodesKey(libraryID, limit), ttlRecentEpisodes, func() ([]abs.LibraryItem, error) { return c.Client.GetRecentEpisodes(ctx, libraryID, limit) }) } @@ -103,7 +138,7 @@ func (c *Client) GetRecentEpisodes(ctx context.Context, libraryID string, limit // GetLibraryItems returns a paginated list of library items from cache or // fetches from the API. The response has the requested page and limit. func (c *Client) GetLibraryItems(ctx context.Context, libraryID string, page, limit int) (*abs.LibraryItemsResponse, error) { - return cached(c, libraryItemsKey(libraryID, page, limit), ttlLibraryItems, func() (*abs.LibraryItemsResponse, error) { + return cached(ctx, c, libraryItemsKey(libraryID, page, limit), ttlLibraryItems, func() (*abs.LibraryItemsResponse, error) { resp, err := c.Client.GetLibraryItems(ctx, libraryID, page, limit) if err != nil { return nil, err @@ -116,7 +151,7 @@ func (c *Client) GetLibraryItems(ctx context.Context, libraryID string, page, li // GetLibrarySeries returns a paginated list of series from cache or fetches // from the API. The response has the requested page and limit. func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, limit int) (*abs.LibrarySeriesResponse, error) { - return cached(c, librarySeriesKey(libraryID, page, limit), ttlLibrarySeries, func() (*abs.LibrarySeriesResponse, error) { + return cached(ctx, c, librarySeriesKey(libraryID, page, limit), ttlLibrarySeries, func() (*abs.LibrarySeriesResponse, error) { resp, err := c.Client.GetLibrarySeries(ctx, libraryID, page, limit) if err != nil { return nil, err @@ -128,21 +163,21 @@ func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, l // GetLibraryItem returns a single library item from cache or fetches from the API. func (c *Client) GetLibraryItem(ctx context.Context, itemID string) (*abs.LibraryItem, error) { - return cached(c, ItemKey(itemID), ttlLibraryItem, func() (*abs.LibraryItem, error) { + return cached(ctx, c, ItemKey(itemID), ttlLibraryItem, func() (*abs.LibraryItem, error) { return c.Client.GetLibraryItem(ctx, itemID) }) } // GetSeriesContents returns series contents from cache or fetches from the API. func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID string) (*abs.SeriesContents, error) { - return cached(c, SeriesContentsKey(seriesID), ttlSeriesContents, func() (*abs.SeriesContents, error) { + return cached(ctx, c, SeriesContentsKey(seriesID), ttlSeriesContents, func() (*abs.SeriesContents, error) { return c.Client.GetSeriesContents(ctx, libraryID, seriesID) }) } // FilterAudioLibraries filters audio libraries using cache or fetches from the API. func (c *Client) FilterAudioLibraries(ctx context.Context, libs []abs.Library) []abs.Library { - v, _ := cached(c, filteredLibrariesKey, ttlLibraries, func() ([]abs.Library, error) { + v, _ := cached(ctx, c, filteredLibrariesKey, ttlLibraries, func() ([]abs.Library, error) { return c.Client.FilterAudioLibraries(ctx, libs), nil }) return v @@ -150,7 +185,7 @@ func (c *Client) FilterAudioLibraries(ctx context.Context, libs []abs.Library) [ // GetBookmarks returns bookmarks from cache or fetches from the API. func (c *Client) GetBookmarks(ctx context.Context, itemID string) ([]abs.Bookmark, error) { - return cached(c, BookmarksKey(itemID), ttlBookmarks, func() ([]abs.Bookmark, error) { + return cached(ctx, c, BookmarksKey(itemID), ttlBookmarks, func() ([]abs.Bookmark, error) { return c.Client.GetBookmarks(ctx, itemID) }) } diff --git a/internal/cache/client_test.go b/internal/cache/client_test.go index 2915736..f407235 100644 --- a/internal/cache/client_test.go +++ b/internal/cache/client_test.go @@ -2,6 +2,7 @@ package cache import ( "context" + "errors" "fmt" "net/http" "net/http/httptest" @@ -549,3 +550,42 @@ func TestClient_ScanLibraryClearsCacheAfterTheScan(t *testing.T) { }) } } + +// TestClient_CachedOnly verifies that a read with a CachedOnly context +// answers from an expired entry, and that it sends no request. +func TestClient_CachedOnly(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"libraries":[{"id":"lib1","name":"Books","mediaType":"book"}]}`)) + })) + defer srv.Close() + + store := NewStore(openTestDB(t)) + client := NewClient(abs.NewClient(srv.URL, "tok"), store) + ctx := CachedOnly(context.Background()) + + if _, err := client.GetLibraries(ctx); !errors.Is(err, ErrNotCached) { + t.Fatalf("GetLibraries with no entry: error %v, want ErrNotCached", err) + } + if got := client.FilterAudioLibraries(ctx, []abs.Library{{ID: "lib1"}}); got != nil { + t.Fatalf("FilterAudioLibraries with no entry = %v, want nil", got) + } + + if err := store.Put(librariesKey, []abs.Library{{ID: "old"}}, 1*time.Millisecond); err != nil { + t.Fatalf("put error: %v", err) + } + time.Sleep(50 * time.Millisecond) + + libs, err := client.GetLibraries(ctx) + if err != nil { + t.Fatalf("GetLibraries with an expired entry: %v", err) + } + if len(libs) != 1 || libs[0].ID != "old" { + t.Fatalf("GetLibraries = %v, want the expired entry", libs) + } + if n := requests.Load(); n != 0 { + t.Fatalf("requests = %d, want 0", n) + } +} diff --git a/internal/cache/store.go b/internal/cache/store.go index 72e4bdb..a49c173 100644 --- a/internal/cache/store.go +++ b/internal/cache/store.go @@ -13,9 +13,14 @@ import ( // keyVersion is the prefix of each key in the database. Raise it when the // type of a cached value changes: the store then does not read the old rows, -// and EvictExpired deletes them when they expire. +// and EvictExpired deletes them keepExpired after they expire. const keyVersion = "v2-" +// keepExpired is how long an expired entry stays for GetStale. It is longer +// than a usual break between two starts of pine, so that a start can show the +// last answer at once. +const keepExpired = 30 * 24 * time.Hour + // Store provides generic get/put/delete/evict operations over a SQLite table. type Store struct { db *db.Store @@ -26,15 +31,26 @@ func NewStore(db *db.Store) *Store { return &Store{db: db} } -// Get attempts to retrieve and decode the value for key into dest. -// Returns (true, nil) on hit, (false, nil) on miss, and (false, err) if the -// database or the decode fails. +// Get attempts to retrieve and decode the value for key into dest. An expired +// entry is a miss. Returns (true, nil) on hit, (false, nil) on miss, and +// (false, err) if the database or the decode fails. func (s *Store) Get(key string, dest any) (bool, error) { - var data []byte - err := s.db.DB.QueryRow( + return s.get(dest, key, `SELECT data FROM api_cache WHERE cache_key = ? AND expires_at > datetime('now')`, - keyVersion+key, - ).Scan(&data) + keyVersion+key) +} + +// GetStale is Get that also reads an entry that expired less than +// keepExpired ago. +func (s *Store) GetStale(key string, dest any) (bool, error) { + return s.get(dest, key, + `SELECT data FROM api_cache WHERE cache_key = ? AND expires_at > datetime('now', '-' || ? || ' seconds')`, + keyVersion+key, int64(keepExpired.Seconds())) +} + +func (s *Store) get(dest any, key, query string, args ...any) (bool, error) { + var data []byte + err := s.db.DB.QueryRow(query, args...).Scan(&data) if errors.Is(err, sql.ErrNoRows) { return false, nil // miss } @@ -77,9 +93,25 @@ func (s *Store) Delete(key string) error { return nil } -// EvictExpired removes all expired entries. +// Expire makes a fresh entry for key expired now, so that Get misses it and +// GetStale still reads it. +func (s *Store) Expire(key string) error { + _, err := s.db.DB.Exec( + `UPDATE api_cache SET expires_at = datetime('now') WHERE cache_key = ? AND expires_at > datetime('now')`, + keyVersion+key, + ) + if err != nil { + return fmt.Errorf("expire cache key %q: %w", key, err) + } + return nil +} + +// EvictExpired removes the entries that expired more than keepExpired ago. func (s *Store) EvictExpired() error { - _, err := s.db.DB.Exec(`DELETE FROM api_cache WHERE expires_at <= datetime('now')`) + _, err := s.db.DB.Exec( + `DELETE FROM api_cache WHERE expires_at <= datetime('now', '-' || ? || ' seconds')`, + int64(keepExpired.Seconds()), + ) if err != nil { return fmt.Errorf("evict expired cache entries: %w", err) } diff --git a/internal/cache/store_test.go b/internal/cache/store_test.go index c5ae926..7975ac6 100644 --- a/internal/cache/store_test.go +++ b/internal/cache/store_test.go @@ -155,19 +155,94 @@ func TestStore_Delete(t *testing.T) { } } +func TestStore_GetStaleReadsExpiredRow(t *testing.T) { + dbStore := openTestDB(t) + s := NewStore(dbStore) + + if err := s.Put("old", "value", 1*time.Millisecond); err != nil { + t.Fatalf("Put error: %v", err) + } + time.Sleep(50 * time.Millisecond) + + var v string + if hit, _ := s.Get("old", &v); hit { + t.Fatal("Get read an expired entry") + } + hit, err := s.GetStale("old", &v) + if err != nil { + t.Fatalf("GetStale error: %v", err) + } + if !hit || v != "value" { + t.Fatalf("GetStale = (%v, %q), want (true, %q)", hit, v, "value") + } + if hit, _ := s.GetStale("missing", &v); hit { + t.Fatal("GetStale found an entry that does not exist") + } +} + +// TestStore_GetStaleSkipsAnEntryPastKeepExpired verifies that GetStale does +// not read an entry that expired more than keepExpired ago, also before +// EvictExpired deletes it. +func TestStore_GetStaleSkipsAnEntryPastKeepExpired(t *testing.T) { + dbStore := openTestDB(t) + s := NewStore(dbStore) + + if err := s.Put("old", "value", time.Minute); err != nil { + t.Fatalf("Put error: %v", err) + } + if _, err := dbStore.DB.Exec( + `UPDATE api_cache SET expires_at = datetime('now', '-31 days') WHERE cache_key = ?`, + keyVersion+"old", + ); err != nil { + t.Fatalf("expire old: %v", err) + } + + var v string + if hit, _ := s.GetStale("old", &v); hit { + t.Fatal("GetStale read an entry that expired more than keepExpired ago") + } +} + +// TestStore_ExpireKeepsTheEntryForGetStale verifies that Expire makes Get +// miss the entry, and that GetStale still reads it. +func TestStore_ExpireKeepsTheEntryForGetStale(t *testing.T) { + s := NewStore(openTestDB(t)) + if err := s.Put("shelves", "value", time.Hour); err != nil { + t.Fatalf("Put error: %v", err) + } + if err := s.Expire("shelves"); err != nil { + t.Fatalf("Expire error: %v", err) + } + var v string + if hit, _ := s.Get("shelves", &v); hit { + t.Fatal("Get read an entry after Expire") + } + if hit, _ := s.GetStale("shelves", &v); !hit || v != "value" { + t.Fatalf("GetStale = (%v, %q) after Expire, want (true, %q)", hit, v, "value") + } +} + +// TestStore_EvictExpired verifies that an expired entry stays for GetStale, +// and that EvictExpired deletes it keepExpired after it expired. func TestStore_EvictExpired(t *testing.T) { dbStore := openTestDB(t) s := NewStore(dbStore) - if err := s.Put("exp1", "a", 1*time.Millisecond); err != nil { + if err := s.Put("recent", "a", 1*time.Millisecond); err != nil { t.Fatalf("Put error: %v", err) } - if err := s.Put("exp2", "b", 1*time.Millisecond); err != nil { + if err := s.Put("old", "b", 1*time.Millisecond); err != nil { t.Fatalf("Put error: %v", err) } if err := s.Put("live", "c", 5*time.Minute); err != nil { t.Fatalf("Put error: %v", err) } + if _, err := dbStore.DB.Exec( + `UPDATE api_cache SET expires_at = datetime('now', '-31 days') WHERE cache_key = ?`, + keyVersion+"old", + ); err != nil { + t.Fatalf("expire old: %v", err) + } time.Sleep(50 * time.Millisecond) @@ -176,11 +251,11 @@ func TestStore_EvictExpired(t *testing.T) { } var v string - if hit, _ := s.Get("exp1", &v); hit { - t.Fatal("expected exp1 to be evicted") + if hit, _ := s.GetStale("recent", &v); !hit { + t.Fatal("EvictExpired deleted an entry that expired less than keepExpired ago") } - if hit, _ := s.Get("exp2", &v); hit { - t.Fatal("expected exp2 to be evicted") + if hit, _ := s.GetStale("old", &v); hit { + t.Fatal("EvictExpired kept an entry that expired more than keepExpired ago") } hit, err := s.Get("live", &v) if err != nil { diff --git a/internal/screens/home/model.go b/internal/screens/home/model.go index e491527..a483a8a 100644 --- a/internal/screens/home/model.go +++ b/internal/screens/home/model.go @@ -35,6 +35,10 @@ type PersonalizedMsg struct { // refreshed is true when the load read the library list again. Libraries // is then the new list, and LibraryID is the library to select in it. refreshed bool + // cached is true when the answer came from the local cache, expired + // entries included. The answer of the server for the same load replaces + // it, and it never replaces the answer of the server. + cached bool } type rowKind int @@ -167,6 +171,10 @@ type Model struct { client *cache.Client libraries []abs.Library selectedLibrary int + + // serverAnswered is true after the server answered the current load with + // no error. A cached answer of the load then does not apply. + serverAnswered bool } // New creates a new home screen model. @@ -205,7 +213,7 @@ func (m *Model) SetSize(width, height int) { // Init returns the initial command that fetches personalized data. func (m Model) Init() tea.Cmd { - return tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) + return tea.Batch(m.fetchPersonalizedCmd(false, true), m.fetchPersonalizedCmd(false, false), m.loadingRevealCmd()) } // Update handles messages for the home screen. @@ -216,6 +224,10 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { logger.Debug("STALE: discarding personalized msg of an earlier load", "msgLib", msg.LibraryID) return m, nil } + if msg.cached && m.serverAnswered { + logger.Debug("personalized: the server answered before the cache", "msgLib", msg.LibraryID) + return m, nil + } currentLib := m.SelectedLibraryID() // The answer of a refresh selects its library in the new library list. if !msg.refreshed && msg.LibraryID != "" && currentLib != "" && msg.LibraryID != currentLib { @@ -225,6 +237,15 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.loading = false m.loadingVisible = false m.updateListTitle() + if msg.cached { + logger.Debug("personalized: showing the cached shelves", "msgLib", msg.LibraryID) + } + // The shelves of the selected library stay when a later load fails, + // for example a start with no network after the cached answer. + if msg.Err != nil && m.contentLibrary != "" && m.contentLibrary == m.SelectedLibraryID() { + logger.Warn("personalized load failed, keeping the shelves", "library", m.contentLibrary, "err", msg.Err) + return m, nil + } if msg.Err != nil { logger.Debug("personalized error", "err", msg.Err) m.err = msg.Err @@ -232,6 +253,9 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { return m, nil } m.err = nil + if !msg.cached { + m.serverAnswered = true + } if msg.refreshed { m.libraries = msg.Libraries m.selectedLibrary = max(0, slices.IndexFunc(m.libraries, func(lib abs.Library) bool { return lib.ID == msg.LibraryID })) @@ -308,12 +332,13 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.loading = true m.loadingVisible = false m.loadingGen++ + m.serverAnswered = false m.err = nil m.updateListTitle() // Keep current content visible briefly; show skeletons only if // the fetch outlives the reveal delay. m.refreshListRows() - return m, tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) + return m, tea.Batch(m.fetchPersonalizedCmd(false, true), m.fetchPersonalizedCmd(false, false), m.loadingRevealCmd()) } return m, nil case key.Matches(msg, m.keys.PageDown): @@ -342,33 +367,52 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { // fetchPersonalizedCmd creates a command that fetches personalized shelves. // With refreshLibraries, the command also reads the library list again, and // it loads the shelves of the selected library by its ID. -func (m *Model) fetchPersonalizedCmd(refreshLibraries bool) tea.Cmd { - msg := PersonalizedMsg{generation: m.loadingGen, refreshed: refreshLibraries} +// +// With cachedOnly, the command reads only the local cache, expired entries +// included, and sends no request. It sends no message if the cache does not +// have the full answer. +func (m *Model) fetchPersonalizedCmd(refreshLibraries, cachedOnly bool) tea.Cmd { + existingLibs := m.libraries + if refreshLibraries { + existingLibs = nil + } + // A load that reads the library list is a refresh of the list: at the + // start, the list of the server can differ from the cached list. + msg := PersonalizedMsg{generation: m.loadingGen, refreshed: len(existingLibs) == 0, cached: cachedOnly} if m.client == nil { + if cachedOnly { + return nil + } msg.Err = fmt.Errorf("not authenticated") return func() tea.Msg { return msg } } client := m.client selectedIdx := m.selectedLibrary - existingLibs := m.libraries - if refreshLibraries { - existingLibs = nil - } currentLibID := m.SelectedLibraryID() + ctx := context.Background() + if cachedOnly { + ctx = cache.CachedOnly(ctx) + } return func() tea.Msg { libs := existingLibs // Fetch libraries if we don't have them yet if len(libs) == 0 { var err error - libs, err = client.GetLibraries(context.Background()) + libs, err = client.GetLibraries(ctx) if err != nil { + if cachedOnly { + return nil + } msg.Err = fmt.Errorf("fetch libraries: %w", err) return msg } - libs = client.FilterAudioLibraries(context.Background(), libs) + libs = client.FilterAudioLibraries(ctx, libs) } msg.Libraries = libs if len(libs) == 0 { + if cachedOnly { + return nil + } msg.LibraryID = currentLibID return msg } @@ -382,8 +426,11 @@ func (m *Model) fetchPersonalizedCmd(refreshLibraries bool) tea.Cmd { } msg.LibraryID = libs[idx].ID - sections, err := client.GetPersonalized(context.Background(), libs[idx].ID) + sections, err := client.GetPersonalized(ctx, libs[idx].ID) if err != nil { + if cachedOnly { + return nil + } msg.Err = fmt.Errorf("fetch personalized: %w", err) return msg } @@ -398,7 +445,7 @@ func (m *Model) fetchPersonalizedCmd(refreshLibraries bool) tea.Cmd { } if libs[idx].MediaType == "podcast" { - if eps, err := client.GetRecentEpisodes(context.Background(), libs[idx].ID, recentlyAddedLimit); err == nil { + if eps, err := client.GetRecentEpisodes(ctx, libs[idx].ID, recentlyAddedLimit); err == nil { msg.RecentlyAdded = eps } } @@ -572,8 +619,9 @@ func (m *Model) reloadCmd(refreshLibraries bool) tea.Cmd { m.loading = true m.loadingVisible = false m.loadingGen++ + m.serverAnswered = false m.refreshListRows() - return tea.Batch(m.fetchPersonalizedCmd(refreshLibraries), m.loadingRevealCmd()) + return tea.Batch(m.fetchPersonalizedCmd(refreshLibraries, false), m.loadingRevealCmd()) } // Libraries returns the available libraries. diff --git a/internal/screens/home/model_test.go b/internal/screens/home/model_test.go index edd5f5d..05ee0df 100644 --- a/internal/screens/home/model_test.go +++ b/internal/screens/home/model_test.go @@ -5,11 +5,15 @@ import ( "fmt" "net/http" "net/http/httptest" + "path/filepath" "strings" + "sync" + "sync/atomic" "testing" "github.com/Thelost77/pine/internal/abs" "github.com/Thelost77/pine/internal/cache" + "github.com/Thelost77/pine/internal/db" "github.com/Thelost77/pine/internal/ui" tea "github.com/charmbracelet/bubbletea" ) @@ -837,7 +841,7 @@ func TestFetchPersonalizedPodcastLibraryUsesRecentEpisodes(t *testing.T) { m.libraries = []abs.Library{{ID: "lib-pod", Name: "Podcasts", MediaType: "podcast"}} m.selectedLibrary = 0 - cmd := m.fetchPersonalizedCmd(false) + cmd := m.fetchPersonalizedCmd(false, false) msg := cmd() pMsg, ok := msg.(PersonalizedMsg) if !ok { @@ -960,7 +964,7 @@ func TestRefreshLoadsShelvesOfSelectedLibraryByID(t *testing.T) { m.libraries = refreshTestLibraries() m.selectedLibrary = 1 - msg, ok := m.fetchPersonalizedCmd(true)().(PersonalizedMsg) + msg, ok := m.fetchPersonalizedCmd(true, false)().(PersonalizedMsg) if !ok { t.Fatal("the command gives no PersonalizedMsg") } @@ -971,3 +975,178 @@ func TestRefreshLoadsShelvesOfSelectedLibraryByID(t *testing.T) { t.Errorf("shelves requests = %v, want only lib-2", shelves) } } + +// TestCachedOnlyLoadReadsExpiredRowsWithoutRequest verifies that the +// cached-only load answers from expired cache entries and sends no request. +func TestCachedOnlyLoadReadsExpiredRowsWithoutRequest(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/libraries": + _ = json.NewEncoder(w).Encode(map[string]any{ + "libraries": []abs.Library{{ID: "lib-1", Name: "Books", MediaType: "book"}}, + }) + case "/api/libraries/lib-1/personalized": + _ = json.NewEncoder(w).Encode([]abs.PersonalizedResponse{ + {ID: "continue-listening", Entities: sampleItems()}, + }) + default: + // The audio check of the library fails, and the library stays. + http.NotFound(w, r) + } + })) + defer srv.Close() + + dbStore, err := db.Open(filepath.Join(t.TempDir(), "pine.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { _ = dbStore.Close() }) + client := cache.NewClient(abs.NewClient(srv.URL, "tok"), cache.NewStore(dbStore)) + + // A load from the server fills the cache. Then each entry expires. + server := New(ui.DefaultStyles(), client) + if msg, ok := server.fetchPersonalizedCmd(false, false)().(PersonalizedMsg); !ok || msg.Err != nil { + t.Fatalf("the load from the server failed: %#v", msg) + } + if _, err := dbStore.DB.Exec(`UPDATE api_cache SET expires_at = datetime('now', '-1 minute')`); err != nil { + t.Fatalf("expire the cache: %v", err) + } + requests.Store(0) + + m := New(ui.DefaultStyles(), client) + msg, ok := m.fetchPersonalizedCmd(false, true)().(PersonalizedMsg) + if !ok { + t.Fatal("the cached-only load gives no PersonalizedMsg") + } + if !msg.cached || msg.LibraryID != "lib-1" || len(msg.Items) != len(sampleItems()) { + t.Errorf("cached = %v, library = %q, items = %d, want true, lib-1, %d", msg.cached, msg.LibraryID, len(msg.Items), len(sampleItems())) + } + if n := requests.Load(); n != 0 { + t.Errorf("requests = %d, want 0", n) + } +} + +// TestServerAnswerBeforeCachedAnswerWins verifies that a cached answer does +// not replace the answer of the server for the same load. +func TestServerAnswerBeforeCachedAnswerWins(t *testing.T) { + m := newTestModel() + m.SetSize(80, 24) + gen := m.loadingGen + + m, _ = m.Update(PersonalizedMsg{Items: sampleItems()[:1], generation: gen}) + m, _ = m.Update(PersonalizedMsg{Items: sampleItems(), generation: gen, cached: true}) + + if got := len(m.Items()); got != 1 { + t.Errorf("items = %d, want the 1 item of the server answer", got) + } +} + +// TestFailedLoadKeepsCachedShelves verifies that a failed load from the +// server keeps the cached shelves of the selected library. +func TestFailedLoadKeepsCachedShelves(t *testing.T) { + m := newTestModel() + m.SetSize(80, 24) + gen := m.loadingGen + libs := []abs.Library{{ID: "lib-1", Name: "Books", MediaType: "book"}} + + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: sampleItems(), generation: gen, cached: true}) + m, _ = m.Update(PersonalizedMsg{Err: fmt.Errorf("fetch libraries: network error"), generation: gen}) + + if m.Error() != nil { + t.Errorf("Error() = %v, want nil", m.Error()) + } + v := m.View() + if strings.Contains(v, "Error:") || !strings.Contains(v, "The Great Adventure") { + t.Errorf("the view does not keep the cached shelves:\n%s", v) + } +} + +// TestServerErrorBeforeCachedAnswerShowsCachedShelves verifies that a cached +// answer still applies after a fast error of the server for the same load, +// for example a start with no network. +func TestServerErrorBeforeCachedAnswerShowsCachedShelves(t *testing.T) { + m := newTestModel() + m.SetSize(80, 24) + gen := m.loadingGen + libs := []abs.Library{{ID: "lib-1", Name: "Books", MediaType: "book"}} + + m, _ = m.Update(PersonalizedMsg{Err: fmt.Errorf("fetch libraries: network error"), generation: gen}) + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: sampleItems(), generation: gen, cached: true}) + + if m.Error() != nil { + t.Errorf("Error() = %v, want nil", m.Error()) + } + v := m.View() + if strings.Contains(v, "Error:") || !strings.Contains(v, "The Great Adventure") { + t.Errorf("the view does not show the cached shelves:\n%s", v) + } +} + +// TestServerAnswerReplacesAnOldCachedLibraryList verifies that the server +// answer at the start applies when the cached library list is old and the +// first library of the server is a different one. +func TestServerAnswerReplacesAnOldCachedLibraryList(t *testing.T) { + var mu sync.Mutex + libraries := []abs.Library{{ID: "lib-old", Name: "Old", MediaType: "podcast"}} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/libraries": + mu.Lock() + libs := libraries + mu.Unlock() + _ = json.NewEncoder(w).Encode(map[string]any{"libraries": libs}) + case "/api/libraries/lib-old/personalized": + _ = json.NewEncoder(w).Encode([]abs.PersonalizedResponse{{ID: "continue-listening", Entities: sampleItems()}}) + case "/api/libraries/lib-new/personalized": + _ = json.NewEncoder(w).Encode([]abs.PersonalizedResponse{{ID: "continue-listening", Entities: sampleItems()[:1]}}) + default: + _ = json.NewEncoder(w).Encode(map[string]any{"episodes": []any{}}) + } + })) + defer srv.Close() + + dbStore, err := db.Open(filepath.Join(t.TempDir(), "pine.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { _ = dbStore.Close() }) + client := cache.NewClient(abs.NewClient(srv.URL, "tok"), cache.NewStore(dbStore)) + + // The cache gets the old list. Then it expires, and the server gets a + // new first library. + first := New(ui.DefaultStyles(), client) + if msg, ok := first.fetchPersonalizedCmd(false, false)().(PersonalizedMsg); !ok || msg.Err != nil { + t.Fatalf("the load from the server failed: %#v", msg) + } + if _, err := dbStore.DB.Exec(`UPDATE api_cache SET expires_at = datetime('now', '-1 minute')`); err != nil { + t.Fatalf("expire the cache: %v", err) + } + mu.Lock() + libraries = []abs.Library{ + {ID: "lib-new", Name: "New", MediaType: "podcast"}, + {ID: "lib-old", Name: "Old", MediaType: "podcast"}, + } + mu.Unlock() + + // As Init does: both loads start before an answer comes. + m := New(ui.DefaultStyles(), client) + m.SetSize(80, 24) + cachedMsg := m.fetchPersonalizedCmd(false, true)() + serverMsg := m.fetchPersonalizedCmd(false, false)() + m, _ = m.Update(cachedMsg) + m, _ = m.Update(serverMsg) + + if got := m.SelectedLibraryID(); got != "lib-new" { + t.Errorf("selected library = %q, want lib-new", got) + } + if got := len(m.Libraries()); got != 2 { + t.Errorf("libraries = %d, want the 2 of the server", got) + } + if got := len(m.Items()); got != 1 { + t.Errorf("items = %d, want the 1 item of lib-new", got) + } +} diff --git a/internal/systemsleep/systemsleep.go b/internal/systemsleep/systemsleep.go new file mode 100644 index 0000000..1b404d0 --- /dev/null +++ b/internal/systemsleep/systemsleep.go @@ -0,0 +1,178 @@ +// Package systemsleep lets an app finish work before the system sleeps. It +// holds a logind sleep delay inhibitor, so that logind waits before a suspend +// or a hibernation until the app has done its work. +// +// The name keeps the package apart from the sleep timer of pine. +package systemsleep + +import ( + "context" + "fmt" + "os" + "sync" + "time" + + "github.com/godbus/dbus/v5" + + "github.com/Thelost77/pine/internal/logger" +) + +const ( + logindName = "org.freedesktop.login1" + logindPath = dbus.ObjectPath("/org/freedesktop/login1") + managerIface = "org.freedesktop.login1.Manager" + prepareSignal = managerIface + ".PrepareForSleep" + inhibitReason = "Stop playback before sleep" + + // releaseAfter is the longest time that the monitor holds logind back + // before a sleep. It is the timeout of an abs.Client request. logind + // itself waits at most InhibitDelayMaxSec, which can be shorter. + releaseAfter = 10 * time.Second + + // inhibitTimeout is the longest wait for an answer to Inhibit. + inhibitTimeout = 3 * time.Second +) + +// Monitor holds a logind sleep delay inhibitor. Before each sleep, it calls +// prepare, and it releases the inhibitor when prepare calls release or when +// the wait time ends. After the wake, it takes a new inhibitor. +type Monitor struct { + conn *dbus.Conn + who string + wait time.Duration + prepare func(release func()) + + mu sync.Mutex + inhibitor *os.File + closed bool +} + +// Start connects to the system bus and starts a monitor. who is the name that +// logind shows for the inhibitor. prepare runs in its own goroutine before +// each sleep, and it must call release when its work has ended. +// +// Without a system bus, for example on macOS and Windows, Start logs the +// cause and returns nil. A nil monitor is valid. +func Start(who string, prepare func(release func())) *Monitor { + conn, err := dbus.ConnectSystemBus() + if err != nil { + logger.Info("system sleep monitor is off: no system bus", "err", err) + return nil + } + m, err := start(conn, who, releaseAfter, prepare) + if err != nil { + logger.Warn("system sleep monitor is off", "err", err) + _ = conn.Close() + return nil + } + return m +} + +func start(conn *dbus.Conn, who string, wait time.Duration, prepare func(release func())) (*Monitor, error) { + if err := conn.AddMatchSignal( + dbus.WithMatchSender(logindName), + dbus.WithMatchObjectPath(logindPath), + dbus.WithMatchInterface(managerIface), + dbus.WithMatchMember("PrepareForSleep"), + ); err != nil { + return nil, fmt.Errorf("subscribe to PrepareForSleep: %w", err) + } + signals := make(chan *dbus.Signal, 8) + conn.Signal(signals) + + m := &Monitor{conn: conn, who: who, wait: wait, prepare: prepare} + m.inhibit() + go m.loop(signals) + return m, nil +} + +// inhibit takes a sleep delay inhibitor. If logind refuses it or does not +// answer in inhibitTimeout, the monitor still calls prepare before a sleep, +// but logind does not wait. +func (m *Monitor) inhibit() { + ctx, cancel := context.WithTimeout(context.Background(), inhibitTimeout) + defer cancel() + var fd dbus.UnixFD + err := m.conn.Object(logindName, logindPath). + CallWithContext(ctx, managerIface+".Inhibit", 0, "sleep", m.who, inhibitReason, "delay"). + Store(&fd) + if err != nil { + logger.Warn("system sleep: logind gave no inhibitor", "err", err) + return + } + f := os.NewFile(uintptr(fd), "logind-inhibitor") + + m.mu.Lock() + if m.closed || m.inhibitor != nil { + m.mu.Unlock() + _ = f.Close() + return + } + m.inhibitor = f + m.mu.Unlock() + logger.Debug("system sleep: inhibitor taken") +} + +func (m *Monitor) loop(signals <-chan *dbus.Signal) { + for sig := range signals { + if sig.Name != prepareSignal || sig.Path != logindPath || len(sig.Body) != 1 { + continue + } + sleeping, ok := sig.Body[0].(bool) + if !ok { + continue + } + if sleeping { + m.beforeSleep() + } else { + m.afterWake() + } + } +} + +func (m *Monitor) beforeSleep() { + m.mu.Lock() + f := m.inhibitor + m.inhibitor = nil + m.mu.Unlock() + logger.Info("system sleep: the system prepares to sleep") + + var once sync.Once + release := func() { + once.Do(func() { + if f != nil { + _ = f.Close() + } + logger.Debug("system sleep: inhibitor released") + }) + } + time.AfterFunc(m.wait, release) + go m.prepare(release) +} + +func (m *Monitor) afterWake() { + logger.Info("system sleep: the system woke up") + m.mu.Lock() + skip := m.closed || m.inhibitor != nil + m.mu.Unlock() + if !skip { + m.inhibit() + } +} + +// Close releases the inhibitor and closes the connection. It does nothing on +// a nil monitor. +func (m *Monitor) Close() { + if m == nil { + return + } + m.mu.Lock() + f := m.inhibitor + m.inhibitor = nil + m.closed = true + m.mu.Unlock() + if f != nil { + _ = f.Close() + } + _ = m.conn.Close() +} diff --git a/internal/systemsleep/systemsleep_linux_test.go b/internal/systemsleep/systemsleep_linux_test.go new file mode 100644 index 0000000..1222a39 --- /dev/null +++ b/internal/systemsleep/systemsleep_linux_test.go @@ -0,0 +1,270 @@ +//go:build linux + +package systemsleep + +import ( + "bufio" + "errors" + "io" + "os" + "os/exec" + "strings" + "sync" + "testing" + "time" + + "github.com/godbus/dbus/v5" +) + +// startSessionBus starts a private D-Bus session bus and returns its address. +// Without dbus-daemon the test skips. With PINE_REQUIRE_DBUS=1 it fails, so +// that a release cannot skip this test. +func startSessionBus(t *testing.T) string { + t.Helper() + path, err := exec.LookPath("dbus-daemon") + if err != nil { + if os.Getenv("PINE_REQUIRE_DBUS") == "1" { + t.Fatalf("dbus-daemon is required: %v", err) + } + t.Skipf("dbus-daemon is not available: %v", err) + } + cmd := exec.Command(path, "--session", "--nofork", "--print-address") + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatalf("StdoutPipe() error: %v", err) + } + if err := cmd.Start(); err != nil { + t.Fatalf("start dbus-daemon: %v", err) + } + t.Cleanup(func() { + _ = cmd.Process.Kill() + _ = cmd.Wait() + }) + address, err := bufio.NewReader(stdout).ReadString('\n') + if err != nil { + t.Fatalf("read the address of dbus-daemon: %v", err) + } + return strings.TrimSpace(address) +} + +// fakeLogind owns the name of logind on a private bus. Each Inhibit call +// returns the write end of a new pipe. The read end gets EOF when the +// monitor closes its copy of the write end. +type fakeLogind struct { + conn *dbus.Conn + + mu sync.Mutex + // block, if it is not nil, makes Inhibit wait until it closes. + block chan struct{} + reads []*os.File + writes []*os.File +} + +// Inhibit is the logind method. The write end stays open until +// closeWriteEnds, so that it is valid while D-Bus sends it. +func (f *fakeLogind) Inhibit(what, who, why, mode string) (dbus.UnixFD, *dbus.Error) { + f.mu.Lock() + block := f.block + f.mu.Unlock() + if block != nil { + <-block + } + if what != "sleep" || mode != "delay" { + return 0, dbus.MakeFailedError(errors.New("unexpected inhibitor " + what + " " + mode)) + } + r, w, err := os.Pipe() + if err != nil { + return 0, dbus.MakeFailedError(err) + } + // The fake reads the descriptor under mu, because closeWriteEnds closes + // the file under mu. + f.mu.Lock() + defer f.mu.Unlock() + f.reads = append(f.reads, r) + f.writes = append(f.writes, w) + return dbus.UnixFD(w.Fd()), nil +} + +func (f *fakeLogind) calls() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.reads) +} + +// closeWriteEnds closes the copies of the fake, so that the monitor holds +// the only write end of each pipe. +func (f *fakeLogind) closeWriteEnds() { + f.mu.Lock() + defer f.mu.Unlock() + for _, w := range f.writes { + _ = w.Close() + } + f.writes = nil +} + +func (f *fakeLogind) read(i int) *os.File { + f.mu.Lock() + defer f.mu.Unlock() + return f.reads[i] +} + +func (f *fakeLogind) prepareForSleep(t *testing.T, sleeping bool) { + t.Helper() + if err := f.conn.Emit(logindPath, prepareSignal, sleeping); err != nil { + t.Fatalf("emit PrepareForSleep(%v): %v", sleeping, err) + } +} + +func startFakeLogind(t *testing.T, address string) *fakeLogind { + t.Helper() + conn, err := dbus.Connect(address) + if err != nil { + t.Fatalf("connect the fake logind: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + fake := &fakeLogind{conn: conn} + t.Cleanup(func() { + fake.closeWriteEnds() + fake.mu.Lock() + defer fake.mu.Unlock() + for _, r := range fake.reads { + _ = r.Close() + } + }) + if err := conn.Export(fake, logindPath, managerIface); err != nil { + t.Fatalf("export the fake logind: %v", err) + } + reply, err := conn.RequestName(logindName, dbus.NameFlagDoNotQueue) + if err != nil || reply != dbus.RequestNameReplyPrimaryOwner { + t.Fatalf("own %s: reply %v, error %v", logindName, reply, err) + } + return fake +} + +func startMonitor(t *testing.T, address string, wait time.Duration, prepare func(release func())) *Monitor { + t.Helper() + conn, err := dbus.Connect(address) + if err != nil { + t.Fatalf("connect the monitor: %v", err) + } + m, err := start(conn, "pinetest", wait, prepare) + if err != nil { + _ = conn.Close() + t.Fatalf("start() error: %v", err) + } + t.Cleanup(m.Close) + return m +} + +// assertOpen fails if the inhibitor of the pipe is released. +func assertOpen(t *testing.T, r *os.File) { + t.Helper() + if err := r.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { + t.Fatalf("SetReadDeadline() error: %v", err) + } + if _, err := r.Read(make([]byte, 1)); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("the inhibitor is released too early: read error %v", err) + } +} + +// assertReleased fails if the inhibitor of the pipe is not released in 2 s. +func assertReleased(t *testing.T, r *os.File) { + t.Helper() + if err := r.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatalf("SetReadDeadline() error: %v", err) + } + if _, err := r.Read(make([]byte, 1)); !errors.Is(err, io.EOF) { + t.Fatalf("the inhibitor is not released: read error %v", err) + } +} + +func waitForCalls(t *testing.T, fake *fakeLogind, want int) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for fake.calls() < want { + if time.Now().After(deadline) { + t.Fatalf("Inhibit calls = %d, want %d", fake.calls(), want) + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestReleaseAfterPrepare checks that the monitor holds logind back until +// prepare calls release, and that it takes a new inhibitor after the wake. +func TestReleaseAfterPrepare(t *testing.T) { + address := startSessionBus(t) + fake := startFakeLogind(t, address) + releases := make(chan func(), 1) + startMonitor(t, address, time.Minute, func(release func()) { releases <- release }) + waitForCalls(t, fake, 1) + fake.closeWriteEnds() + + fake.prepareForSleep(t, true) + var release func() + select { + case release = <-releases: + case <-time.After(2 * time.Second): + t.Fatal("prepare was not called before the sleep") + } + assertOpen(t, fake.read(0)) + release() + assertReleased(t, fake.read(0)) + + fake.prepareForSleep(t, false) + waitForCalls(t, fake, 2) +} + +// TestReleaseAfterTimeout checks that the monitor releases the inhibitor +// when prepare does not call release in time. +func TestReleaseAfterTimeout(t *testing.T) { + address := startSessionBus(t) + fake := startFakeLogind(t, address) + called := make(chan struct{}, 1) + startMonitor(t, address, 50*time.Millisecond, func(func()) { called <- struct{}{} }) + waitForCalls(t, fake, 1) + fake.closeWriteEnds() + + fake.prepareForSleep(t, true) + select { + case <-called: + case <-time.After(2 * time.Second): + t.Fatal("prepare was not called before the sleep") + } + assertReleased(t, fake.read(0)) +} + +// TestStartDoesNotWaitForAnInhibitWithNoAnswer verifies that the start of the +// monitor does not wait longer than inhibitTimeout for logind. +func TestStartDoesNotWaitForAnInhibitWithNoAnswer(t *testing.T) { + address := startSessionBus(t) + fake := startFakeLogind(t, address) + block := make(chan struct{}) + fake.mu.Lock() + fake.block = block + fake.mu.Unlock() + t.Cleanup(func() { close(block) }) + + conn, err := dbus.Connect(address) + if err != nil { + t.Fatalf("connect the monitor: %v", err) + } + type result struct { + m *Monitor + err error + } + done := make(chan result, 1) + go func() { + m, err := start(conn, "pinetest", time.Minute, func(func()) {}) + done <- result{m, err} + }() + select { + case r := <-done: + if r.err != nil { + t.Fatalf("start() error: %v", r.err) + } + r.m.Close() + case <-time.After(inhibitTimeout + 2*time.Second): + _ = conn.Close() + t.Fatal("start waits for an Inhibit call that gets no answer") + } +} diff --git a/main.go b/main.go index e2f684d..d9575de 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "github.com/Thelost77/pine/internal/db" "github.com/Thelost77/pine/internal/logger" "github.com/Thelost77/pine/internal/player" + "github.com/Thelost77/pine/internal/systemsleep" "github.com/Thelost77/pine/internal/ui" tea "github.com/charmbracelet/bubbletea" ) @@ -82,6 +83,12 @@ func main() { model := app.New(cfg, store, cachedClient, cacheStore) p := tea.NewProgram(model, tea.WithAltScreen()) model.SetProgram(p) + // After the program ends, p.Send returns at once, and the monitor + // releases logind after its wait time. + sleepMonitor := systemsleep.Start("pine", func(release func()) { + p.Send(app.SystemSleepMsg{Release: release}) + }) + defer sleepMonitor.Close() logger.Info("starting TUI") finalModel, err := ui.RunProgram(p) if err != nil { diff --git a/scripts/release.sh b/scripts/release.sh index 5491bd3..b5d418b 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -71,7 +71,7 @@ go vet ./... go build ./... # Each binary must link only the shared packages and its own app packages. -if go list -deps ./cmd/spruce | grep -E 'Thelost77/pine/internal/(abs|app|cache|captions|config|db|screens)(/|$)'; then +if go list -deps ./cmd/spruce | grep -E 'Thelost77/pine/internal/(abs|app|cache|captions|config|db|screens|systemsleep)(/|$)'; then echo "spruce links pine-only packages" >&2 exit 1 fi