From 4a93a5932c443c182f22a92d9e1456a53f4d6e96 Mon Sep 17 00:00:00 2001 From: Maxim Shevarev Date: Mon, 9 Nov 2026 12:42:15 +0300 Subject: [PATCH 1/2] Fix API throttling and resume partial library refreshes --- app/build.gradle.kts | 4 +- .../likefolder/app/LibraryRepositoryTest.java | 211 +++++++++++++ .../likefolder/app/NetRequestQueueTest.java | 281 ++++++++++++++++++ .../com/likefolder/app/ApiRequestQueue.java | 162 ++++++++++ .../com/likefolder/app/LibraryActivity.java | 31 +- .../com/likefolder/app/LibraryRepository.java | 70 ++++- app/src/main/java/com/likefolder/app/Net.java | 31 +- .../likefolder/app/ApiRequestQueueTest.java | 187 ++++++++++++ 8 files changed, 955 insertions(+), 22 deletions(-) create mode 100644 app/src/androidTest/java/com/likefolder/app/LibraryRepositoryTest.java create mode 100644 app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java create mode 100644 app/src/main/java/com/likefolder/app/ApiRequestQueue.java create mode 100644 app/src/test/java/com/likefolder/app/ApiRequestQueueTest.java diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 738d117..17765ca 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "com.likefolder.app" minSdk = 29 targetSdk = 35 - versionCode = 4 - versionName = "0.2.0" + versionCode = 5 + versionName = "0.2.1" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } compileOptions { diff --git a/app/src/androidTest/java/com/likefolder/app/LibraryRepositoryTest.java b/app/src/androidTest/java/com/likefolder/app/LibraryRepositoryTest.java new file mode 100644 index 0000000..1d724ff --- /dev/null +++ b/app/src/androidTest/java/com/likefolder/app/LibraryRepositoryTest.java @@ -0,0 +1,211 @@ +package com.likefolder.app; + +import android.content.Context; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.work.WorkManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +/** Real SQLite checkpoints with a synthetic API; no credentials or network are needed. */ +@RunWith(AndroidJUnit4.class) +public final class LibraryRepositoryTest { + private Context context; + private Store store; + + @Before public void prepareCache() throws Exception { + context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + WorkManager.getInstance(context).cancelAllWork().getResult().get(5, TimeUnit.SECONDS); + store = new Store(context); + store.signOut(); + } + + @After public void clearCache() { + if (store != null) store.signOut(); + } + + @Test public void failedSecondBatchKeepsFirstBatchAndRetryFetchesOnlyMissingTracks() throws Exception { + FakeSource source = new FakeSource(likes(0)); + LibraryRepository repository = new LibraryRepository(context, source); + repository.refresh(null); + assertTrue(repository.lastRefreshAt() > 0); + + source.likes = likes(70); + source.failBatch = 2; + Set seenBefore = Collections.singleton("999"); + store.setIds("seen", seenBefore); + List progress = new ArrayList<>(); + try { + repository.refresh((loaded, total) -> { + assertEquals(70, total); + assertEquals("Progress must describe rows already persisted", loaded, repository.load().size()); + progress.add(loaded); + }); + fail("The second metadata batch should fail"); + } catch (IOException expected) { + assertEquals("synthetic HTTP 429", expected.getMessage()); + } + assertEquals(Arrays.asList(0, 35), progress); + assertEquals(35, repository.load().size()); + assertEquals(0, repository.lastRefreshAt()); + assertEquals(70, store.likedCount()); + assertFalse("Reading the library must not create a download baseline", store.hasBaseline()); + assertEquals(seenBefore, store.ids("seen")); + LibraryTrack saved = repository.load().get(0); + assertEquals(1000L, saved.likedAt); + assertEquals(0, saved.likeOrder); + + source.failBatch = 0; + source.batches.clear(); + progress.clear(); + repository.refresh((loaded, total) -> progress.add(loaded)); + assertEquals(Arrays.asList(35, 70), progress); + assertEquals(1, source.batches.size()); + List remaining = new ArrayList<>(); + for (int id = 36; id <= 70; id++) remaining.add(String.valueOf(id)); + assertEquals(remaining, source.batches.get(0)); + assertEquals(70, repository.load().size()); + assertTrue(repository.lastRefreshAt() > 0); + assertEquals(seenBefore, store.ids("seen")); + assertFalse(store.hasBaseline()); + } + + @Test public void warmRefreshUpdatesDatesAndOrderWithoutRefetchingMetadata() throws Exception { + FakeSource source = new FakeSource(likes(2)); + LibraryRepository repository = new LibraryRepository(context, source); + repository.refresh(null); + source.batches.clear(); + source.likes = Arrays.asList(new YandexApi.Like("2", 9000, 0), new YandexApi.Like("1", 8000, 1)); + repository.refresh((loaded, total) -> { + assertEquals(2, loaded); + List checkpoint = repository.load(); + assertEquals("2", checkpoint.get(0).id); + assertEquals(9000L, checkpoint.get(0).likedAt); + }); + assertTrue("Cached metadata should require no track requests", source.batches.isEmpty()); + List rows = repository.load(); + assertEquals("2", rows.get(0).id); + assertEquals(9000L, rows.get(0).likedAt); + assertEquals(0, rows.get(0).likeOrder); + assertEquals("1", rows.get(1).id); + assertEquals(8000L, rows.get(1).likedAt); + assertEquals(1, rows.get(1).likeOrder); + + // A later refresh failing on a new track must also preserve the previous good snapshot. + source.likes = Arrays.asList(new YandexApi.Like("1", 10000, 0), new YandexApi.Like("3", 9500, 1)); + source.failBatch = 1; + try { + repository.refresh(null); + fail("The new track request should fail"); + } catch (IOException expected) { + assertEquals("synthetic HTTP 429", expected.getMessage()); + } + assertEquals(new HashSet<>(Arrays.asList("1", "2")), ids(repository.load())); + assertEquals(10000L, find(repository.load(), "1").likedAt); + assertEquals(0, repository.lastRefreshAt()); + } + + @Test public void logoutDuringMetadataFetchCannotRestoreOldAccountCache() throws Exception { + FakeSource source = new FakeSource(likes(35)); + LibraryRepository repository = new LibraryRepository(context, source); + repository.refresh(null); + assertEquals(35, repository.load().size()); + source.likes = likes(70); + source.onTracks = store::signOut; + try { + repository.refresh(null); + fail("The old account refresh must be invalidated by logout"); + } catch (InterruptedIOException expected) { + // Models a logout completing while the old HTTP response is still in flight. + } + LibraryRepository afterLogout = new LibraryRepository(context); + assertTrue(afterLogout.load().isEmpty()); + assertEquals(0, afterLogout.lastRefreshAt()); + assertEquals(0, store.likedCount()); + assertFalse(store.isLoggedIn()); + } + + @Test public void completedRefreshRetainsUnlikedDownloadedTracksOnly() throws Exception { + FakeSource source = new FakeSource(likes(3)); + LibraryRepository repository = new LibraryRepository(context, source); + repository.refresh(null); + store.setIds("downloaded", Collections.singleton("2")); + source.likes = Collections.singletonList(new YandexApi.Like("1", 12000, 0)); + source.batches.clear(); + repository.refresh(null); + + assertEquals(new HashSet<>(Arrays.asList("1", "2")), ids(repository.load())); + assertEquals("Title 2", find(repository.load(), "2").title); + assertTrue(source.batches.isEmpty()); + assertEquals(1, store.likedCount()); + assertEquals(Collections.singleton("2"), store.ids("downloaded")); + assertTrue(repository.lastRefreshAt() > 0); + } + + @Test public void placeholderTitleStillNeedsMetadataEvenWithAnAlbumSuffix() throws Exception { + FakeSource source = new FakeSource(Arrays.asList( + new YandexApi.Like("1:99", 1000, 0), new YandexApi.Like("2", 2000, 1))); + LibraryRepository repository = new LibraryRepository(context, source); + repository.remember(Arrays.asList(new YandexApi.Track("1:99", "Track 1", "", ""), + new YandexApi.Track("2", "Title 2", "Artist 2", "Album"))); + repository.refresh(null); + + assertEquals(1, source.batches.size()); + assertEquals(Collections.singletonList("1:99"), source.batches.get(0)); + assertEquals("Title 1:99", find(repository.load(), "1:99").title); + assertEquals(1000L, find(repository.load(), "1:99").likedAt); + } + + private static List likes(int count) { + List result = new ArrayList<>(); + for (int id = 1; id <= count; id++) result.add(new YandexApi.Like(String.valueOf(id), id * 1000L, id - 1)); + return result; + } + + private static Set ids(List rows) { + Set result = new HashSet<>(); + for (LibraryTrack row : rows) result.add(row.id); + return result; + } + + private static LibraryTrack find(List rows, String id) { + for (LibraryTrack row : rows) if (row.id.equals(id)) return row; + throw new AssertionError("Missing cached track " + id); + } + + private static final class FakeSource implements LibraryRepository.Source { + List likes; + final List> batches = new ArrayList<>(); + int failBatch; + Runnable onTracks; + + FakeSource(List likes) { this.likes = likes; } + + @Override public List likedEntries() { return new ArrayList<>(likes); } + + @Override public List tracks(List ids) throws IOException { + batches.add(new ArrayList<>(ids)); + if (batches.size() == failBatch) throw new IOException("synthetic HTTP 429"); + if (onTracks != null) onTracks.run(); + List result = new ArrayList<>(); + for (String id : ids) result.add(new YandexApi.Track(id, "Title " + id, "Artist " + id, "Album")); + return result; + } + } +} diff --git a/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java b/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java new file mode 100644 index 0000000..4dbb082 --- /dev/null +++ b/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java @@ -0,0 +1,281 @@ +package com.likefolder.app; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.Assert.*; + +/** Exercises real Net/JSON/cancellation wiring with fake connections; never opens a socket. */ +@RunWith(AndroidJUnit4.class) +public final class NetRequestQueueTest { + private static final String MUSIC = "https://api.music.yandex.net/tracks"; + private static final String OAUTH = "https://oauth.yandex.ru/token"; + + @Test public void retryClosesResponseBeforeReplayAndStaysOnCallerThread() throws Exception { + AtomicLong now = new AtomicLong(1000); + List sleeps = new ArrayList<>(); + ApiRequestQueue queue = new ApiRequestQueue(now::get, millis -> { + sleeps.add(millis); + now.addAndGet(millis); + }); + Thread caller = Thread.currentThread(); + FakeConnection limited = new FakeConnection(MUSIC, 429, "{\"error\":\"limit\"}", "2"); + FakeConnection success = new FakeConnection(MUSIC, 200, "{\"result\":true}", null); + AtomicInteger opens = new AtomicInteger(); + AtomicInteger callbacks = new AtomicInteger(); + try (ApiRequestQueue.ListenerScope ignored = ApiRequestQueue.withListener((delay, attempt) -> { + assertSame(caller, Thread.currentThread()); + assertTrue(limited.streamClosed.get()); + assertEquals(1, limited.disconnects.get()); + assertEquals(2000L, delay); + assertEquals(1, attempt); + callbacks.incrementAndGet(); + })) { + JSONObject result = Net.json(MUSIC, "POST", "track-ids=1001", "synthetic-token", queue, url -> { + assertSame(caller, Thread.currentThread()); + if (opens.getAndIncrement() == 0) return limited; + assertEquals("The previous connection must be closed before reopening", 1, limited.disconnects.get()); + return success; + }); + assertTrue(result.getBoolean("result")); + } + assertEquals(2, opens.get()); + assertEquals(1, callbacks.get()); + assertEquals(java.util.Collections.singletonList(2000L), sleeps); + for (FakeConnection connection : new FakeConnection[]{limited, success}) { + assertSame(caller, connection.requestThread); + assertEquals("POST", connection.getRequestMethod()); + assertEquals("OAuth synthetic-token", connection.getRequestProperty("Authorization")); + assertEquals("track-ids=1001", new String(connection.requestBody.toByteArray(), StandardCharsets.UTF_8)); + assertTrue(connection.streamClosed.get()); + assertEquals(1, connection.disconnects.get()); + } + } + + @Test public void oauthRequestCompletesWhileMusicQueueIsOccupied() throws Exception { + AtomicLong now = new AtomicLong(1000); + ApiRequestQueue queue = new ApiRequestQueue(now::get, now::addAndGet); + CountDownLatch musicEntered = new CountDownLatch(1), releaseMusic = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future holder = executor.submit(() -> queue.execute(() -> { + musicEntered.countDown(); + awaitLatch(releaseMusic); + return null; + })); + assertTrue(musicEntered.await(5, TimeUnit.SECONDS)); + FakeConnection oauth = new FakeConnection(OAUTH, 200, "{\"access_token\":\"fake\"}", null); + Future request = executor.submit(() -> Net.json(OAUTH, "POST", "grant_type=device_code", + null, queue, url -> oauth)); + assertEquals("fake", request.get(3, TimeUnit.SECONDS).getString("access_token")); + assertFalse("OAuth must finish before the Music queue is released", holder.isDone()); + assertNull(oauth.getRequestProperty("Authorization")); + assertEquals(1, oauth.disconnects.get()); + releaseMusic.countDown(); + holder.get(5, TimeUnit.SECONDS); + } finally { + releaseMusic.countDown(); + shutdown(executor); + } + } + + @Test public void musicCallsSharePermitAndQueuedDownloadCanBeCancelled() throws Exception { + AtomicLong now = new AtomicLong(1000); + ApiRequestQueue queue = new ApiRequestQueue(now::get, now::addAndGet); + AtomicInteger active = new AtomicInteger(), maximum = new AtomicInteger(), opens = new AtomicInteger(); + CountDownLatch firstEntered = new CountDownLatch(1), releaseFirst = new CountDownLatch(1); + CountDownLatch jobStarted = new CountDownLatch(1); + AtomicReference jobThread = new AtomicReference<>(); + DownloadCoordinator.Job job = DownloadCoordinator.tryStart(); + assertNotNull("Tests must not overlap real download jobs", job); + ExecutorService executor = Executors.newFixedThreadPool(3); + try { + FakeConnection first = new FakeConnection(MUSIC, 200, "{\"result\":1}", null); + first.active = active; first.maximum = maximum; + first.entered = firstEntered; first.release = releaseFirst; + Future library = executor.submit(() -> Net.json(MUSIC, "GET", null, null, queue, url -> { + opens.incrementAndGet(); + return first; + })); + assertTrue(firstEntered.await(5, TimeUnit.SECONDS)); + Future cancelled = executor.submit(() -> { + job.bind(); + jobThread.set(Thread.currentThread()); + jobStarted.countDown(); + try { + Net.json(MUSIC, "GET", null, null, queue, url -> { + fail("A cancelled queued download must never create a connection"); + return null; + }); + throw new AssertionError("Queued download should be cancelled"); + } catch (IOException ex) { + assertTrue(Thread.currentThread().isInterrupted()); + return ex; + } finally { job.close(); } + }); + assertTrue(jobStarted.await(5, TimeUnit.SECONDS)); + awaitWaiting(jobThread.get()); + FakeConnection second = new FakeConnection(MUSIC, 200, "{\"result\":2}", null); + second.active = active; second.maximum = maximum; + Future next = executor.submit(() -> Net.json(MUSIC, "GET", null, null, queue, url -> { + opens.incrementAndGet(); + assertEquals("The earlier request must disconnect before the next opens", 1, first.disconnects.get()); + return second; + })); + job.cancel(); + assertTrue(cancelled.get(3, TimeUnit.SECONDS) instanceof InterruptedIOException); + assertFalse(DownloadCoordinator.snapshot().running); + assertEquals(1, opens.get()); + assertEquals("Cancelling a waiter must not release another request's permit", 1, active.get()); + assertFalse(library.isDone()); + releaseFirst.countDown(); + assertEquals(1, library.get(5, TimeUnit.SECONDS).getInt("result")); + assertEquals(2, next.get(5, TimeUnit.SECONDS).getInt("result")); + assertEquals(2, opens.get()); + assertEquals(1, maximum.get()); + assertEquals(0, active.get()); + } finally { + releaseFirst.countDown(); + job.cancel(); + shutdown(executor); + job.close(); + } + } + + @Test public void cancellingDownloadDuringBackoffReleasesPermitAndConnection() throws Exception { + AtomicLong now = new AtomicLong(1000); + CountDownLatch backoffStarted = new CountDownLatch(1); + AtomicBoolean blockFirstSleep = new AtomicBoolean(true); + ApiRequestQueue queue = new ApiRequestQueue(now::get, millis -> { + if (blockFirstSleep.getAndSet(false)) { + backoffStarted.countDown(); + new CountDownLatch(1).await(); // Only cancellation may end this synthetic backoff. + } else now.addAndGet(millis); + }); + FakeConnection limited = new FakeConnection(MUSIC, 429, "{\"error\":\"limit\"}", "5"); + DownloadCoordinator.Job job = DownloadCoordinator.tryStart(); + assertNotNull(job); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future cancelled = executor.submit(() -> { + job.bind(); + try { + Net.json(MUSIC, "GET", null, null, queue, url -> limited); + throw new AssertionError("Backoff should be cancelled"); + } catch (IOException ex) { + assertTrue(Thread.currentThread().isInterrupted()); + return ex; + } finally { job.close(); } + }); + assertTrue(backoffStarted.await(5, TimeUnit.SECONDS)); + assertTrue(limited.streamClosed.get()); + assertEquals(1, limited.disconnects.get()); + job.cancel(); + assertTrue(cancelled.get(3, TimeUnit.SECONDS) instanceof InterruptedIOException); + assertFalse(DownloadCoordinator.snapshot().running); + assertEquals("The finished HTTP connection must no longer be registered with the job", 1, limited.disconnects.get()); + now.set(10_000); // Advance past the shared server cooldown without real-time sleeps. + FakeConnection success = new FakeConnection(MUSIC, 200, "{\"result\":true}", null); + assertTrue(Net.json(MUSIC, "GET", null, null, queue, url -> success).getBoolean("result")); + assertEquals(1, success.disconnects.get()); + } finally { + job.cancel(); + shutdown(executor); + job.close(); + } + } + + private static void awaitWaiting(Thread thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + Thread.State state = thread.getState(); + if (state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING) return; + Thread.sleep(10); + } + fail("Download thread did not start waiting for the occupied API queue"); + } + + private static void awaitLatch(CountDownLatch latch) throws IOException { + try { + if (!latch.await(10, TimeUnit.SECONDS)) throw new IOException("Timed out waiting for test fixture"); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Synthetic connection interrupted"); + } + } + + private static void shutdown(ExecutorService executor) throws InterruptedException { + executor.shutdownNow(); + assertTrue("Synthetic request threads must stop", executor.awaitTermination(5, TimeUnit.SECONDS)); + } + + private static final class FakeConnection extends HttpURLConnection { + private final int responseStatus; + private final String retryAfter; + private final InputStream responseBody; + final ByteArrayOutputStream requestBody = new ByteArrayOutputStream(); + final AtomicBoolean streamClosed = new AtomicBoolean(); + final AtomicInteger disconnects = new AtomicInteger(); + private final AtomicBoolean countedActive = new AtomicBoolean(); + volatile Thread requestThread; + AtomicInteger active, maximum; + CountDownLatch entered, release; + + FakeConnection(String url, int responseStatus, String responseBody, String retryAfter) throws Exception { + super(new URL(url)); + this.responseStatus = responseStatus; + this.retryAfter = retryAfter; + this.responseBody = new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)) { + @Override public void close() throws IOException { + streamClosed.set(true); + super.close(); + } + }; + } + + @Override public int getResponseCode() throws IOException { + requestThread = Thread.currentThread(); + if (active != null && countedActive.compareAndSet(false, true)) + maximum.accumulateAndGet(active.incrementAndGet(), Math::max); + if (entered != null) entered.countDown(); + if (release != null) awaitLatch(release); + return responseStatus; + } + @Override public String getHeaderField(String name) { + return "Retry-After".equalsIgnoreCase(name) ? retryAfter : null; + } + @Override public InputStream getErrorStream() { return responseBody; } + @Override public InputStream getInputStream() { return responseBody; } + @Override public OutputStream getOutputStream() { return requestBody; } + @Override public void disconnect() { + disconnects.incrementAndGet(); + if (active != null && countedActive.compareAndSet(true, false)) active.decrementAndGet(); + } + @Override public boolean usingProxy() { return false; } + @Override public void connect() { } + } +} diff --git a/app/src/main/java/com/likefolder/app/ApiRequestQueue.java b/app/src/main/java/com/likefolder/app/ApiRequestQueue.java new file mode 100644 index 0000000..93c3e4d --- /dev/null +++ b/app/src/main/java/com/likefolder/app/ApiRequestQueue.java @@ -0,0 +1,162 @@ +package com.likefolder.app; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +/** Serializes Music API calls across screens and downloads; OAuth and audio use separate paths. */ +final class ApiRequestQueue { + private static final long REQUEST_GAP_MILLIS = 500; + private static final long MAX_WAIT_MILLIS = 60_000; + private static final int MAX_RETRIES = 4; + private static final ThreadLocal LISTENER = new ThreadLocal<>(); + + interface Request { T run() throws IOException; } + interface Clock { long nowMillis(); } + interface Sleeper { void sleep(long millis) throws InterruptedException; } + /** attempt is zero for a shared cooldown, or 1..4 for this request's retries. */ + interface Listener { void onRetry(long delayMillis, int attempt); } + + static class HttpError extends IOException { + final int status; + final long retryAfterMillis; + HttpError(int status, String message, long retryAfterMillis) { + super(message); + this.status = status; + this.retryAfterMillis = Math.max(0, retryAfterMillis); + } + } + + static final class RateLimitException extends HttpError { + RateLimitException(long delayMillis, Throwable cause) { + super(429, rateLimitMessage(delayMillis), delayMillis); + if (cause != null) initCause(cause); + } + } + + /** Install on the thread performing API calls; close restores any enclosing listener. */ + static ListenerScope withListener(Listener listener) { return new ListenerScope(listener); } + + static final class ListenerScope implements AutoCloseable { + private final Listener previous; + private boolean closed; + private ListenerScope(Listener listener) { + previous = LISTENER.get(); + if (listener == null) LISTENER.remove(); else LISTENER.set(listener); + } + @Override public void close() { + if (closed) return; + closed = true; + if (previous == null) LISTENER.remove(); else LISTENER.set(previous); + } + } + + private final ReentrantLock permit = new ReentrantLock(true); + private final Clock clock; + private final Sleeper sleeper; + private long nextRequestAt, rateLimitedUntil; + + ApiRequestQueue() { this(new MonotonicClock(), Thread::sleep); } + ApiRequestQueue(Clock clock, Sleeper sleeper) { + this.clock = clock; + this.sleeper = sleeper; + nextRequestAt = rateLimitedUntil = clock.nowMillis(); + } + + T execute(Request request) throws IOException { + try { permit.lockInterruptibly(); } + catch (InterruptedException ex) { throw interrupted(ex); } + try { + int retry = 0; + while (true) { + awaitTurn(retry); + try { + T result = request.run(); + checkInterrupted(); + return result; + } catch (HttpError ex) { + if (ex.status != 429) throw ex; + // jsonOnce has closed and disconnected its response before this catch runs. + long backoff = 1_000L << retry; + long delay = Math.max(backoff, ex.retryAfterMillis); + long deadline = addClamped(clock.nowMillis(), delay); + rateLimitedUntil = Math.max(rateLimitedUntil, deadline); + nextRequestAt = Math.max(nextRequestAt, rateLimitedUntil); + if (delay > MAX_WAIT_MILLIS || retry == MAX_RETRIES) + throw new RateLimitException(remaining(nextRequestAt), ex); + ++retry; + } finally { + // Enforce the gap after success, HTTP errors and transport failures alike. + nextRequestAt = Math.max(nextRequestAt, addClamped(clock.nowMillis(), REQUEST_GAP_MILLIS)); + } + } + } finally { permit.unlock(); } + } + + private void awaitTurn(int retry) throws IOException { + checkInterrupted(); + long delay = remaining(nextRequestAt); + long limitedDelay = remaining(rateLimitedUntil); + // Keep the shared deadline, but don't occupy a caller for minutes or hours. + if (limitedDelay > MAX_WAIT_MILLIS) throw new RateLimitException(limitedDelay, null); + Listener listener = LISTENER.get(); + if (limitedDelay > 0 && listener != null) listener.onRetry(delay, retry); + while (delay > 0) { + checkInterrupted(); + try { sleeper.sleep(delay); } + catch (InterruptedException ex) { throw interrupted(ex); } + checkInterrupted(); + delay = remaining(nextRequestAt); + } + checkInterrupted(); + } + + private long remaining(long deadline) { return Math.max(0, deadline - clock.nowMillis()); } + + /** Retry-After accepts either delta-seconds or an HTTP date; bad values use local backoff. */ + static long retryAfterMillis(String value, long nowEpochMillis) { + if (value == null) return 0; + String trimmed = value.trim(); + if (trimmed.matches("[0-9]+")) { + try { + long seconds = Long.parseLong(trimmed); + return seconds > Long.MAX_VALUE / 1_000 ? Long.MAX_VALUE : seconds * 1_000; + } catch (NumberFormatException ex) { return Long.MAX_VALUE; } + } + try { + long target = ZonedDateTime.parse(trimmed, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli(); + return Math.max(0, target - nowEpochMillis); + } catch (DateTimeParseException | ArithmeticException ex) { return 0; } + } + + private static long addClamped(long value, long increment) { + return value > Long.MAX_VALUE - increment ? Long.MAX_VALUE : value + increment; + } + + private static void checkInterrupted() throws InterruptedIOException { + if (Thread.currentThread().isInterrupted()) throw interrupted(null); + } + + private static InterruptedIOException interrupted(InterruptedException cause) { + Thread.currentThread().interrupt(); + InterruptedIOException result = new InterruptedIOException("Ожидание запроса остановлено"); + if (cause != null) result.initCause(cause); + return result; + } + + private static String rateLimitMessage(long delayMillis) { + String intro = "Яндекс Музыка временно ограничила запросы. "; + if (delayMillis > 3_600_000) return intro + "Сервер просит длительную паузу. Попробуй позже."; + long seconds = delayMillis / 1_000 + (delayMillis % 1_000 == 0 ? 0 : 1); + return intro + "Повтори попытку примерно через " + Math.max(1, seconds) + " сек."; + } + + private static final class MonotonicClock implements Clock { + private final long origin = System.nanoTime(); + @Override public long nowMillis() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - origin); } + } +} diff --git a/app/src/main/java/com/likefolder/app/LibraryActivity.java b/app/src/main/java/com/likefolder/app/LibraryActivity.java index 114f4e8..42d6129 100644 --- a/app/src/main/java/com/likefolder/app/LibraryActivity.java +++ b/app/src/main/java/com/likefolder/app/LibraryActivity.java @@ -159,6 +159,7 @@ private void buildUi() { loadStatus.setVisibility(View.GONE); tools.addView(loadStatus); loading = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); loading.setIndeterminate(true); loading.setIndeterminateTintList(ColorStateList.valueOf(AppUi.ACCENT)); + loading.setProgressTintList(ColorStateList.valueOf(AppUi.ACCENT)); loading.setVisibility(View.GONE); tools.addView(loading, new LinearLayout.LayoutParams(-1, dp(3))); LinearLayout selectionTools = new LinearLayout(this); selectionTools.setGravity(Gravity.CENTER_VERTICAL); @@ -225,13 +226,25 @@ private Spinner spinner(String[] labels) { private void loadLibrary(boolean fetchFromYandex) { if (loadingLibrary) return; loadingLibrary = true; final int generation = ++loadGeneration; + loading.setIndeterminate(true); refreshButton.setEnabled(false); refreshButton.setAlpha(.4f); loading.setVisibility(View.VISIBLE); - loadStatus.setText(fetchFromYandex ? "Обновляю названия и даты лайков…" : "Читаю сохранённую медиатеку…"); + loadStatus.setText(fetchFromYandex ? "Обновляю список треков…" : "Читаю сохранённую медиатеку…"); loadStatus.setVisibility(View.VISIBLE); + applyQuery(); loadTask = executor.submit(() -> { - try { - if (fetchFromYandex) repository.refresh((loaded, total) -> postLoad(generation, () -> - loadStatus.setText("Загружаю медиатеку: " + loaded + " / " + total))); + try (ApiRequestQueue.ListenerScope ignored = ApiRequestQueue.withListener((delayMillis, attempt) -> + postLoad(generation, () -> loadStatus.setText("Яндекс просит паузу. Продолжу автоматически через " + + Math.max(1, (delayMillis + 999) / 1000) + " с…")))) { + if (fetchFromYandex) repository.refresh((loaded, total) -> { + // The repository checkpoints each successful batch before reporting progress. + List partial = repository.load(); + postLoad(generation, () -> { + tracks = partial; downloaded = store.ids("downloaded"); selected.removeAll(downloaded); + loading.setIndeterminate(false); loading.setMax(Math.max(1, total)); loading.setProgress(loaded); + loadStatus.setText("Загружаю медиатеку: " + loaded + " / " + total); + applyQuery(); + }); + }); List result = repository.load(); boolean needsRefresh = !fetchFromYandex && System.currentTimeMillis() - repository.lastRefreshAt() > 15 * 60 * 1000L; postLoad(generation, () -> { @@ -241,8 +254,16 @@ private void loadLibrary(boolean fetchFromYandex) { if (needsRefresh) loadLibrary(true); }); } catch (Exception ex) { + // Even an exhausted server limit must not hide the batches that already arrived. + List cached = null; + try { cached = repository.load(); } catch (RuntimeException ignored) { } + final List recovered = cached; postLoad(generation, () -> { - finishLoad(); loadStatus.setText("Не удалось обновить медиатеку. " + ex.getMessage()); + if (recovered != null) { + tracks = recovered; downloaded = store.ids("downloaded"); selected.removeAll(downloaded); + } + finishLoad(); loadStatus.setText((tracks.isEmpty() ? "Не удалось загрузить медиатеку. " + : "Список загружен не полностью. Уже полученные треки сохранены. ") + ex.getMessage()); loadStatus.setVisibility(View.VISIBLE); applyQuery(); }); } diff --git a/app/src/main/java/com/likefolder/app/LibraryRepository.java b/app/src/main/java/com/likefolder/app/LibraryRepository.java index 1e74fa1..36113bb 100644 --- a/app/src/main/java/com/likefolder/app/LibraryRepository.java +++ b/app/src/main/java/com/likefolder/app/LibraryRepository.java @@ -17,13 +17,23 @@ /** Persistent metadata cache. Download status stays in Store for compatibility with existing installs. */ final class LibraryRepository { interface Progress { void onProgress(int loaded, int total); } + interface Source { + List likedEntries() throws IOException; + List tracks(List ids) throws IOException; + } private static final Object LOCK = new Object(); private static long generation; private final Context context; private final long sessionGeneration; + private final Source source; LibraryRepository(Context context) { + this(context, null); + } + + LibraryRepository(Context context, Source source) { this.context = context.getApplicationContext(); + this.source = source; synchronized (LOCK) { sessionGeneration = generation; } } @@ -66,31 +76,48 @@ void refresh(Progress listener) throws IOException { Store store = new Store(context); YandexApi api = new YandexApi(store); checkActive(); - List likes = api.likedEntries(); + List likes = source == null ? api.likedEntries() : source.likedEntries(); checkActive(); Map previous = new HashMap<>(); for (LibraryTrack row : load()) previous.put(row.id, row); LinkedHashMap refreshed = new LinkedHashMap<>(); - if (listener != null) listener.onProgress(0, likes.size()); - for (int offset = 0; offset < likes.size(); offset += 35) { + List missing = new ArrayList<>(); + for (YandexApi.Like like : likes) { + LibraryTrack old = previous.get(like.id); + if (hasMetadata(old)) { + refreshed.put(like.id, new LibraryTrack(like.id, old.title, old.artist, old.album, + like.timestampMillis, like.order)); + } else missing.add(like); + } + // A fresh likes response updates dates immediately. Keep old rows until the whole refresh succeeds. + checkpoint(new ArrayList<>(refreshed.values()), true, store, likes.size()); + int loaded = likes.size() - missing.size(); + if (listener != null) listener.onProgress(loaded, likes.size()); + for (int offset = 0; offset < missing.size(); offset += 35) { checkActive(); - List batch = likes.subList(offset, Math.min(offset + 35, likes.size())); + List batch = missing.subList(offset, Math.min(offset + 35, missing.size())); List ids = new ArrayList<>(); for (YandexApi.Like like : batch) ids.add(like.id); Map metadata = new HashMap<>(); - for (YandexApi.Track track : api.tracks(ids)) metadata.put(track.id, track); + List detailsBatch = source == null ? api.tracks(ids) : source.tracks(ids); + for (YandexApi.Track track : detailsBatch) metadata.put(track.id, track); checkActive(); + List completed = new ArrayList<>(); for (YandexApi.Like like : batch) { YandexApi.Track details = metadata.get(like.id); if (details == null) details = metadata.get(like.id.split(":")[0]); LibraryTrack old = previous.get(like.id); - refreshed.put(like.id, new LibraryTrack(like.id, + LibraryTrack row = new LibraryTrack(like.id, details != null ? details.title : old == null ? null : old.title, details != null ? details.artist : old == null ? null : old.artist, details != null ? details.album : old == null ? null : old.album, - like.timestampMillis, like.order)); + like.timestampMillis, like.order); + refreshed.put(like.id, row); + completed.add(row); } - if (listener != null) listener.onProgress(Math.min(offset + 35, likes.size()), likes.size()); + checkpoint(completed, false, store, likes.size()); + loaded += batch.size(); + if (listener != null) listener.onProgress(loaded, likes.size()); } checkActive(); synchronized (LOCK) { @@ -117,6 +144,33 @@ void refresh(Progress listener) throws IOException { } } + private static boolean hasMetadata(LibraryTrack row) { + if (row == null) return false; + String baseId = row.id.split(":")[0]; + return !row.title.equals("Трек " + row.id) && !row.title.equals("Track " + row.id) + && !row.title.equals("Трек " + baseId) && !row.title.equals("Track " + baseId); + } + + /** Persist useful work before reporting progress, without marking a partial snapshot complete. */ + private void checkpoint(List rows, boolean start, Store store, int likedCount) + throws InterruptedIOException { + synchronized (LOCK) { + checkActive(); + Database helper = new Database(context); + try { + SQLiteDatabase db = helper.getWritableDatabase(); + db.beginTransaction(); + try { + if (start) db.delete("metadata", "key=?", new String[]{"refreshed_at"}); + for (LibraryTrack row : rows) db.replaceOrThrow("tracks", null, values(row)); + checkActive(); + db.setTransactionSuccessful(); + } finally { db.endTransaction(); } + if (start) store.likedCount(likedCount); // Never changes the downloader's baseline or seen IDs. + } finally { helper.close(); } + } + } + /** Cache details already fetched by the downloader without disturbing dates or other rows. */ void remember(List tracks) { if (tracks.isEmpty() || Thread.currentThread().isInterrupted()) return; diff --git a/app/src/main/java/com/likefolder/app/Net.java b/app/src/main/java/com/likefolder/app/Net.java index 0b04dc9..3b6575b 100644 --- a/app/src/main/java/com/likefolder/app/Net.java +++ b/app/src/main/java/com/likefolder/app/Net.java @@ -13,9 +13,11 @@ /** Small networking helper; credentials are ONLY sent to the API host. */ final class Net { - static final class ApiError extends IOException { - final int status; - ApiError(int status, String message) { super(message); this.status = status; } + private static final ApiRequestQueue MUSIC_REQUESTS = new ApiRequestQueue(); + interface ConnectionFactory { HttpURLConnection open(URL url) throws IOException; } + static final class ApiError extends ApiRequestQueue.HttpError { + ApiError(int status, String message) { this(status, message, 0); } + ApiError(int status, String message, long retryAfterMillis) { super(status, message, retryAfterMillis); } } static String form(String... fields) { if (fields.length % 2 != 0) throw new IllegalArgumentException("Expected pairs"); @@ -25,9 +27,23 @@ static String form(String... fields) { return encoded == null ? "" : encoded; } static JSONObject json(String url, String method, String body, String oauth) throws IOException { + return json(url, method, body, oauth, MUSIC_REQUESTS, + parsed -> (HttpURLConnection) parsed.openConnection()); + } + static JSONObject json(String url, String method, String body, String oauth, + ApiRequestQueue queue, ConnectionFactory connections) throws IOException { + DownloadCoordinator.check(); + URL parsed = new URL(url); + if (!parsed.getProtocol().equals("https")) throw new IOException("HTTPS обязателен"); + if (parsed.getHost().equalsIgnoreCase("api.music.yandex.net")) + return queue.execute(() -> jsonOnce(parsed, method, body, oauth, connections)); + // Device-code polling already has its own timing/retry rules. Do not alter OAuth here. + return jsonOnce(parsed, method, body, oauth, connections); + } + private static JSONObject jsonOnce(URL url, String method, String body, String oauth, + ConnectionFactory connections) throws IOException { DownloadCoordinator.check(); - if (!url.startsWith("https://")) throw new IOException("HTTPS обязателен"); - HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + HttpURLConnection conn = connections.open(url); try { DownloadCoordinator.register(conn); conn.setConnectTimeout(15000); @@ -37,7 +53,7 @@ static JSONObject json(String url, String method, String body, String oauth) thr conn.setRequestProperty("Accept-Language", "ru"); conn.setRequestProperty("User-Agent", "LikeFolder/0.1 (Android)"); if (oauth != null && !oauth.trim().isEmpty()) { - if (!new URL(url).getHost().equals("api.music.yandex.net")) + if (!url.getHost().equalsIgnoreCase("api.music.yandex.net")) throw new IOException("Заблокирована передача токена на посторонний сервер"); conn.setRequestProperty("Authorization", "OAuth " + oauth); } @@ -53,7 +69,8 @@ static JSONObject json(String url, String method, String body, String oauth) thr DownloadCoordinator.check(); if (code >= 400) { String detail = result.length() > 250 ? result.substring(0, 250) : result; - throw new ApiError(code, "HTTP " + code + " (" + detail + ")"); + long retryAfter = ApiRequestQueue.retryAfterMillis(conn.getHeaderField("Retry-After"), System.currentTimeMillis()); + throw new ApiError(code, "HTTP " + code + " (" + detail + ")", retryAfter); } try { return new JSONObject(result); } catch (Exception e) { throw new IOException("Некорректный JSON от сервера", e); } diff --git a/app/src/test/java/com/likefolder/app/ApiRequestQueueTest.java b/app/src/test/java/com/likefolder/app/ApiRequestQueueTest.java new file mode 100644 index 0000000..07b7bbc --- /dev/null +++ b/app/src/test/java/com/likefolder/app/ApiRequestQueueTest.java @@ -0,0 +1,187 @@ +package com.likefolder.app; + +import org.junit.Test; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import static org.junit.Assert.*; + +public final class ApiRequestQueueTest { + @Test public void requestGapStartsAfterThePreviousResponseFinishes() throws Exception { + Time time = new Time(); ApiRequestQueue queue = time.queue(); + queue.execute(() -> { time.now.addAndGet(1_750); return null; }); + assertEquals(Long.valueOf(2_250), queue.execute(time.now::get)); + assertEquals(Arrays.asList(500L), time.sleeps); + } + + @Test public void concurrentRequestsRunInArrivalOrderWithoutOverlap() throws Exception { + Time time = new Time(); ApiRequestQueue queue = time.queue(); + List order = Collections.synchronizedList(new ArrayList<>()); + AtomicInteger active = new AtomicInteger(), maximum = new AtomicInteger(); + AtomicReference failure = new AtomicReference<>(); + CountDownLatch firstRunning = new CountDownLatch(1), finishFirst = new CountDownLatch(1); + Thread first = thread(() -> queue.execute(() -> { + maximum.accumulateAndGet(active.incrementAndGet(), Math::max); + order.add(1); firstRunning.countDown(); await(finishFirst); active.decrementAndGet(); return null; + }), failure); + Thread second = thread(() -> queue.execute(() -> { + maximum.accumulateAndGet(active.incrementAndGet(), Math::max); + order.add(2); active.decrementAndGet(); return null; + }), failure); + Thread third = thread(() -> queue.execute(() -> { + maximum.accumulateAndGet(active.incrementAndGet(), Math::max); + order.add(3); active.decrementAndGet(); return null; + }), failure); + first.start(); + try { + assertTrue(firstRunning.await(2, TimeUnit.SECONDS)); + second.start(); waitUntilQueued(second); + third.start(); waitUntilQueued(third); + finishFirst.countDown(); + join(first); join(second); join(third); + assertNull(failure.get()); assertEquals(1, maximum.get()); + assertEquals(Arrays.asList(1, 2, 3), order); + assertEquals(Arrays.asList(500L, 500L), time.sleeps); + } finally { finishFirst.countDown(); stop(first, second, third); } + } + + @Test public void retries429WithExponentialBackoffThenReturnsSuccess() throws Exception { + Time time = new Time(); ApiRequestQueue queue = time.queue(); AtomicInteger calls = new AtomicInteger(); + List retries = new ArrayList<>(); + try (ApiRequestQueue.ListenerScope ignored = ApiRequestQueue.withListener((delay, attempt) -> retries.add(attempt + ":" + delay))) { + assertEquals("ok", queue.execute(() -> { + if (calls.incrementAndGet() < 3) throw limit(0); + return "ok"; + })); + } + assertEquals(3, calls.get()); assertEquals(Arrays.asList(1_000L, 2_000L), time.sleeps); + assertEquals(Arrays.asList("1:1000", "2:2000"), retries); + } + + @Test public void authenticationAndTransportFailuresAreNeverRetried() { + for (IOException failure : new IOException[]{ + new ApiRequestQueue.HttpError(401, "expired", 0), + new ApiRequestQueue.HttpError(403, "denied", 0), new IOException("offline")}) { + Time time = new Time(); AtomicInteger calls = new AtomicInteger(); + IOException actual = assertThrows(IOException.class, () -> time.queue().execute(() -> { + calls.incrementAndGet(); throw failure; + })); + assertSame(failure, actual); assertEquals(1, calls.get()); assertTrue(time.sleeps.isEmpty()); + } + } + + @Test public void retryAfterSupportsSecondsHttpDatesAndMalformedValues() { + assertEquals(12_000, ApiRequestQueue.retryAfterMillis(" 12 ", 0)); + assertEquals(3_000, ApiRequestQueue.retryAfterMillis("Thu, 1 Jan 1970 00:00:05 GMT", 2_000)); + assertEquals(0, ApiRequestQueue.retryAfterMillis("Thu, 1 Jan 1970 00:00:01 GMT", 2_000)); + for (String value : new String[]{null, "", "bad-date", "-1", "1.5"}) + assertEquals(0, ApiRequestQueue.retryAfterMillis(value, 0)); + assertEquals(Long.MAX_VALUE, ApiRequestQueue.retryAfterMillis("9223372036854775807", 0)); + assertEquals(Long.MAX_VALUE, ApiRequestQueue.retryAfterMillis("999999999999999999999999999999", 0)); + } + + @Test public void serverPauseIsNeverShortenedToLocalBackoff() throws Exception { + Time time = new Time(); AtomicInteger calls = new AtomicInteger(); + long completedAt = time.queue().execute(() -> { + if (calls.incrementAndGet() == 1) throw limit(7_000); + return time.now.get(); + }); + assertEquals(7_000, completedAt); assertEquals(Arrays.asList(7_000L), time.sleeps); + } + + @Test public void longServerPauseFailsPromptlyAndBlocksLaterRequestsUntilItsDeadline() throws Exception { + Time time = new Time(); ApiRequestQueue queue = time.queue(); AtomicInteger calls = new AtomicInteger(); + ApiRequestQueue.RateLimitException first = assertThrows(ApiRequestQueue.RateLimitException.class, + () -> queue.execute(() -> { calls.incrementAndGet(); throw limit(120_000); })); + assertEquals(120_000, first.retryAfterMillis); assertEquals(1, calls.get()); assertTrue(time.sleeps.isEmpty()); + assertThrows(ApiRequestQueue.RateLimitException.class, () -> queue.execute(calls::incrementAndGet)); + assertEquals(1, calls.get()); + time.now.set(119_500); + List notices = new ArrayList<>(); + try (ApiRequestQueue.ListenerScope ignored = ApiRequestQueue.withListener((delay, attempt) -> notices.add(attempt + ":" + delay))) { + assertEquals(Integer.valueOf(2), queue.execute(calls::incrementAndGet)); + } + assertEquals(120_000, time.now.get()); assertEquals(Arrays.asList("0:500"), notices); + } + + @Test public void exhaustionKeepsTheFinalBackoffForTheNextCaller() throws Exception { + Time time = new Time(); ApiRequestQueue queue = time.queue(); AtomicInteger calls = new AtomicInteger(); + ApiRequestQueue.RateLimitException error = assertThrows(ApiRequestQueue.RateLimitException.class, + () -> queue.execute(() -> { calls.incrementAndGet(); throw limit(0); })); + assertEquals(5, calls.get()); assertEquals(16_000, error.retryAfterMillis); + assertEquals(Arrays.asList(1_000L, 2_000L, 4_000L, 8_000L), time.sleeps); + assertEquals(Long.valueOf(31_000), queue.execute(time.now::get)); + assertEquals(Long.valueOf(16_000), time.sleeps.get(4)); + } + + @Test public void interruptingQueuedCallerDoesNotRunItsRequestOrBlockSuccessor() throws Exception { + Time time = new Time(); ApiRequestQueue queue = time.queue(); + CountDownLatch started = new CountDownLatch(1), finish = new CountDownLatch(1); + AtomicReference firstFailure = new AtomicReference<>(), queuedFailure = new AtomicReference<>(); + AtomicBoolean ran = new AtomicBoolean(), interrupted = new AtomicBoolean(); + Thread first = thread(() -> queue.execute(() -> { started.countDown(); await(finish); return null; }), firstFailure); + Thread queued = new Thread(() -> { + try { queue.execute(() -> { ran.set(true); return null; }); } + catch (Throwable ex) { queuedFailure.set(ex); interrupted.set(Thread.currentThread().isInterrupted()); } + }); + first.start(); + try { + assertTrue(started.await(2, TimeUnit.SECONDS)); queued.start(); waitUntilQueued(queued); + queued.interrupt(); join(queued); + assertTrue(queuedFailure.get() instanceof InterruptedIOException); assertTrue(interrupted.get()); assertFalse(ran.get()); + finish.countDown(); join(first); assertNull(firstFailure.get()); + assertEquals("next", queue.execute(() -> "next")); + } finally { finish.countDown(); stop(first, queued); } + } + + @Test public void interruptingBackoffStopsRetryButPreservesSharedCooldown() throws Exception { + AtomicLong now = new AtomicLong(); AtomicBoolean firstSleep = new AtomicBoolean(true); + CountDownLatch sleeping = new CountDownLatch(1); + ApiRequestQueue queue = new ApiRequestQueue(now::get, millis -> { + if (firstSleep.getAndSet(false)) { sleeping.countDown(); new CountDownLatch(1).await(); } + now.addAndGet(millis); + }); + AtomicInteger calls = new AtomicInteger(); AtomicReference failure = new AtomicReference<>(); + Thread retrying = thread(() -> queue.execute(() -> { calls.incrementAndGet(); throw limit(0); }), failure); + retrying.start(); + try { + assertTrue(sleeping.await(2, TimeUnit.SECONDS)); retrying.interrupt(); join(retrying); + assertTrue(failure.get() instanceof InterruptedIOException); assertEquals(1, calls.get()); + assertEquals(Long.valueOf(1_000), queue.execute(now::get)); + } finally { stop(retrying); } + } + + private static ApiRequestQueue.HttpError limit(long retryAfter) { return new ApiRequestQueue.HttpError(429, "limit", retryAfter); } + private interface Task { void run() throws Exception; } + private static Thread thread(Task task, AtomicReference failure) { + return new Thread(() -> { try { task.run(); } catch (Throwable ex) { failure.set(ex); } }); + } + private static void await(CountDownLatch latch) throws IOException { + try { if (!latch.await(2, TimeUnit.SECONDS)) throw new IOException("test timeout"); } + catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new InterruptedIOException(); } + } + private static void waitUntilQueued(Thread thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (thread.getState() != Thread.State.WAITING && System.nanoTime() < deadline) Thread.sleep(1); + assertEquals(Thread.State.WAITING, thread.getState()); + } + private static void join(Thread thread) throws InterruptedException { thread.join(2_000); assertFalse(thread.isAlive()); } + private static void stop(Thread... threads) throws InterruptedException { + for (Thread thread : threads) if (thread.isAlive()) thread.interrupt(); + for (Thread thread : threads) thread.join(2_000); + } + private static final class Time { + final AtomicLong now = new AtomicLong(); + final List sleeps = Collections.synchronizedList(new ArrayList<>()); + ApiRequestQueue queue() { return new ApiRequestQueue(now::get, millis -> { sleeps.add(millis); now.addAndGet(millis); }); } + } +} From bcd2d9768e4f930122184c72d8b8eff0e9aafd7d Mon Sep 17 00:00:00 2001 From: Maxim Shevarev Date: Mon, 9 Nov 2026 12:44:53 +0300 Subject: [PATCH 2/2] Make concurrent network cancellation check deterministic --- .../likefolder/app/NetRequestQueueTest.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java b/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java index 4dbb082..d163f78 100644 --- a/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java +++ b/app/src/androidTest/java/com/likefolder/app/NetRequestQueueTest.java @@ -108,8 +108,8 @@ public final class NetRequestQueueTest { ApiRequestQueue queue = new ApiRequestQueue(now::get, now::addAndGet); AtomicInteger active = new AtomicInteger(), maximum = new AtomicInteger(), opens = new AtomicInteger(); CountDownLatch firstEntered = new CountDownLatch(1), releaseFirst = new CountDownLatch(1); - CountDownLatch jobStarted = new CountDownLatch(1); - AtomicReference jobThread = new AtomicReference<>(); + CountDownLatch jobStarted = new CountDownLatch(1), nextStarted = new CountDownLatch(1); + AtomicReference jobThread = new AtomicReference<>(), nextThread = new AtomicReference<>(); DownloadCoordinator.Job job = DownloadCoordinator.tryStart(); assertNotNull("Tests must not overlap real download jobs", job); ExecutorService executor = Executors.newFixedThreadPool(3); @@ -141,11 +141,17 @@ public final class NetRequestQueueTest { awaitWaiting(jobThread.get()); FakeConnection second = new FakeConnection(MUSIC, 200, "{\"result\":2}", null); second.active = active; second.maximum = maximum; - Future next = executor.submit(() -> Net.json(MUSIC, "GET", null, null, queue, url -> { - opens.incrementAndGet(); - assertEquals("The earlier request must disconnect before the next opens", 1, first.disconnects.get()); - return second; - })); + Future next = executor.submit(() -> { + nextThread.set(Thread.currentThread()); + nextStarted.countDown(); + return Net.json(MUSIC, "GET", null, null, queue, url -> { + opens.incrementAndGet(); + assertEquals("The earlier request must disconnect before the next opens", 1, first.disconnects.get()); + return second; + }); + }); + assertTrue(nextStarted.await(5, TimeUnit.SECONDS)); + awaitWaiting(nextThread.get()); job.cancel(); assertTrue(cancelled.get(3, TimeUnit.SECONDS) instanceof InterruptedIOException); assertFalse(DownloadCoordinator.snapshot().running);