SimpMusic icon indicating copy to clipboard operation
SimpMusic copied to clipboard

Scraper HttpClient is closed and recreated on every settings write, in-flight requests fail

Open Me-xico opened this issue 2 months ago • 0 comments

Describe the bug

Every write to the settings DataStore (switching account, toggling any preference) closes the YouTube Music scraper's Ktor HttpClient and creates a new one, even when the proxy settings did not change. Requests that are in flight at that moment fail. The Spotify client has the same setter and the same behaviour.

To Reproduce

  1. Desktop build from dev with the proxy disabled (default).
  2. Start playing a song or open a page that is still loading.
  3. Switch account in Settings, or toggle any unrelated setting.
  4. The loading request fails; the logs show the client being rebuilt.

Seen on Desktop (Linux) while testing core#37; the code path is common, so Android should behave the same.

Cause

DataStore.data emits the whole Preferences snapshot on every write, whatever key was touched. The proxy flows in DataStoreManagerImpl (usingProxy, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword, lines 1036-1129) are plain .map on that flow with no distinctUntilChanged(), so each of them re-emits the same value on every write.

CommonRepositoryImpl combines those six flows and collects them (CommonRepositoryImpl.kt:102-145). The combined tuple is identical but it is a new emission, so the collectLatest block runs again. With the proxy disabled it calls youTube.removeProxy() and spotify.removeProxy().

removeProxy() sets ytMusic.proxy = null unconditionally (YouTube.kt:221-223), and the setter rebuilds the client on every assignment, null to null included (Ytmusic.kt:162-167):

var proxy: ProxyConfig? = null
    set(value) {
        field = value
        httpClient.close()
        httpClient = createClient()
    }

SpotifyClient.kt:46-51 is the same setter for spotifyClient.

The other jobs in the same init block (sessionJob, tidalCredentialJob) already use distinctUntilChanged(). The proxy block is the only one that both lacks it and has an expensive side effect.

Proposed fix

Two small changes. Either one stops the symptom; together they also cover future callers:

  1. CommonRepositoryImpl.kt:117: .distinctUntilChanged() on the combined flow before .collectLatest. This removes the spurious re-runs at the source.
  2. Ytmusic.kt:162 and SpotifyClient.kt:46: if (field == value) return at the top of the setter, so the client is only rebuilt when the proxy actually changes. On JVM ProxyConfig is java.net.Proxy, which compares by value; if that is not true on every target, compare the source parameters instead.

I can open a PR on core for this if you want it.

Me-xico avatar Sep 16 '26 22:09 Me-xico