@capgo/capacitor-updater 6.50.2 → 6.51.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CapgoCapacitorUpdater.podspec +1 -3
  2. package/Package.swift +5 -6
  3. package/README.md +53 -48
  4. package/android/build.gradle +9 -9
  5. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +29 -2
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +7 -3
  7. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +1 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +452 -139
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1354 -414
  10. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -31
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +23 -7
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +2 -2
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +11 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +540 -224
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +103 -3
  16. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +1 -1
  17. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +131 -145
  18. package/dist/docs.json +32 -8
  19. package/dist/esm/definitions.d.ts +41 -17
  20. package/dist/esm/definitions.js.map +1 -1
  21. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +124 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +9 -1
  23. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +3 -0
  24. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +804 -92
  25. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +1020 -270
  27. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +76 -56
  28. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +73 -251
  29. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +44 -20
  30. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +28 -0
  31. package/package.json +12 -7
  32. package/ios/Sources/CapacitorUpdaterPlugin/BigInt.swift +0 -39
@@ -13,11 +13,16 @@ import android.content.pm.PackageManager;
13
13
  import android.os.Build;
14
14
  import androidx.annotation.NonNull;
15
15
  import androidx.lifecycle.LifecycleOwner;
16
+ import androidx.work.Constraints;
16
17
  import androidx.work.Data;
18
+ import androidx.work.ExistingPeriodicWorkPolicy;
19
+ import androidx.work.ExistingWorkPolicy;
20
+ import androidx.work.ListenableWorker;
21
+ import androidx.work.NetworkType;
22
+ import androidx.work.OneTimeWorkRequest;
23
+ import androidx.work.PeriodicWorkRequest;
17
24
  import androidx.work.WorkInfo;
18
25
  import androidx.work.WorkManager;
19
- import com.google.common.util.concurrent.Futures;
20
- import com.google.common.util.concurrent.ListenableFuture;
21
26
  import java.io.BufferedInputStream;
22
27
  import java.io.BufferedReader;
23
28
  import java.io.File;
@@ -32,7 +37,9 @@ import java.security.SecureRandom;
32
37
  import java.util.ArrayList;
33
38
  import java.util.Date;
34
39
  import java.util.HashMap;
40
+ import java.util.HashSet;
35
41
  import java.util.Iterator;
42
+ import java.util.LinkedHashSet;
36
43
  import java.util.List;
37
44
  import java.util.Map;
38
45
  import java.util.Objects;
@@ -45,6 +52,7 @@ import java.util.concurrent.Executors;
45
52
  import java.util.concurrent.ScheduledExecutorService;
46
53
  import java.util.concurrent.ScheduledFuture;
47
54
  import java.util.concurrent.TimeUnit;
55
+ import java.util.concurrent.atomic.AtomicBoolean;
48
56
  import java.util.zip.ZipEntry;
49
57
  import java.util.zip.ZipInputStream;
50
58
  import okhttp3.*;
@@ -65,16 +73,24 @@ public class CapgoUpdater {
65
73
  private static final String FALLBACK_VERSION = "pastVersion";
66
74
  private static final String NEXT_VERSION = "nextVersion";
67
75
  private static final String PREVIEW_FALLBACK_VERSION = "previewFallbackVersion";
76
+ private static final String PENDING_DELETE_IDS = "pendingDeleteIds";
68
77
  private static final String bundleDirectory = "versions";
69
78
  private static final String TEMP_UNZIP_PREFIX = "capgo_unzip_";
79
+ private static final long DELETE_PACE_MS = 75L;
80
+ private final Object deleteLock = new Object();
70
81
  private static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
71
82
  private static final String BACKGROUND_RUNNER_CONFIG_KEY = "BackgroundRunner";
83
+ private static final String BACKGROUND_RUNNER_WORKER_CLASS = "io.ionic.backgroundrunner.plugin.RunnerWorker";
72
84
 
73
85
  public static final String TAG = "Capacitor-updater";
74
86
  public SharedPreferences.Editor editor;
87
+
88
+ /** Optional gate run before any download touches disk (e.g. wait for launch cleanup). */
89
+ public Runnable downloadGate = null;
75
90
  public SharedPreferences prefs;
76
91
 
77
92
  public File documentsDir;
93
+ public File noBackupDir;
78
94
  public Boolean directUpdate = false;
79
95
  public Activity activity;
80
96
  public String pluginVersion = "";
@@ -96,17 +112,31 @@ public class CapgoUpdater {
96
112
  // Cached key ID calculated once from publicKey
97
113
  private String cachedKeyId = "";
98
114
 
99
- // Flag to track if we received a 429 response - stops requests until app restart
100
- private static volatile boolean rateLimitExceeded = false;
115
+ // Temporary 429 block until this epoch ms (Retry-After / rateLimitResetAt). No sticky latch.
116
+ // Guarded by rateLimitStateLock so concurrent 429s cannot shorten the window or mix metadata.
117
+ private static final Object rateLimitStateLock = new Object();
118
+ private static long rateLimitBlockedUntilMs = 0L;
119
+ private static String rateLimitBlockedError = "too_many_requests";
120
+ private static String rateLimitBlockedMessage = "Too many requests";
121
+
122
+ // Flag to track if we've already sent the rate limit statistic - prevents infinite loop.
123
+ // Released again when the send fails, so a later 429 can retry it.
124
+ private static boolean rateLimitStatisticSent = false;
101
125
 
102
- // Flag to track if we've already sent the rate limit statistic - prevents infinite loop
103
- private static volatile boolean rateLimitStatisticSent = false;
126
+ // Upper bound for a client-side 429 block, so a bogus Retry-After cannot block the app for days.
127
+ private static final long MAX_RATE_LIMIT_WINDOW_MS = 24 * 60 * 60 * 1000L;
104
128
 
105
129
  // Stats batching - queue events and send max once per second
106
130
  private final List<QueuedStatsEvent> statsQueue = new CopyOnWriteArrayList<>();
131
+ private final List<QueuedStatsEvent> statsInFlight = new ArrayList<>();
132
+ private final Object pendingStatsPersistLock = new Object();
107
133
  private final ScheduledExecutorService statsScheduler = Executors.newSingleThreadScheduledExecutor();
108
134
  private ScheduledFuture<?> statsFlushTask = null;
135
+ private final AtomicBoolean statsFlushInFlight = new AtomicBoolean(false);
136
+ private final AtomicBoolean statsStopped = new AtomicBoolean(false);
109
137
  private static final long STATS_FLUSH_INTERVAL_MS = 1000;
138
+ private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
139
+ private static final int MAX_PENDING_STATS = 200;
110
140
 
111
141
  private static final class QueuedStatsEvent {
112
142
 
@@ -128,7 +158,7 @@ public class CapgoUpdater {
128
158
 
129
159
  private final FilenameFilter filter = (f, name) -> {
130
160
  // ignore directories generated by mac os x
131
- return (!name.startsWith("__MACOSX") && !name.startsWith(".") && !name.startsWith(".DS_Store"));
161
+ return !name.startsWith("__MACOSX") && !name.startsWith(".") && !name.startsWith(".DS_Store");
132
162
  };
133
163
 
134
164
  private boolean isProd() {
@@ -283,14 +313,17 @@ public class CapgoUpdater {
283
313
  return this.cachedKeyId;
284
314
  }
285
315
 
286
- private File unzip(final String id, final File zipFile, final String dest) throws IOException {
316
+ File unzip(final String id, final File zipFile, final String dest) throws IOException {
317
+ return unzip(id, zipFile, dest, CryptoCipher.ioBufferBytes());
318
+ }
319
+
320
+ File unzip(final String id, final File zipFile, final String dest, final int bufferSize) throws IOException {
287
321
  final File targetDirectory = new File(this.documentsDir, dest);
288
322
  try (
289
323
  final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFile));
290
324
  final ZipInputStream zis = new ZipInputStream(bis)
291
325
  ) {
292
326
  int count;
293
- final int bufferSize = 8192;
294
327
  final byte[] buffer = new byte[bufferSize];
295
328
  final long lengthTotal = zipFile.length();
296
329
  long lengthRead = bufferSize;
@@ -370,7 +403,7 @@ public class CapgoUpdater {
370
403
  io.execute(() -> cacheBundleFiles(id));
371
404
  }
372
405
 
373
- private void cacheBundleFiles(final String id) {
406
+ void cacheBundleFiles(final String id) {
374
407
  if (this.activity == null) {
375
408
  logger.debug("Skip delta cache population: activity is null");
376
409
  return;
@@ -392,20 +425,32 @@ public class CapgoUpdater {
392
425
  return;
393
426
  }
394
427
 
428
+ final File builtinFolder = new File(this.activity.getFilesDir(), "public");
429
+
395
430
  final List<File> files = new ArrayList<>();
396
431
  collectFiles(bundleDir, files);
432
+ final int bundlePrefixLength = bundleDir.getAbsolutePath().length() + 1;
397
433
  for (File file : files) {
398
434
  final String checksum = CryptoCipher.calcChecksum(file);
399
435
  if (checksum.isEmpty()) {
400
436
  continue;
401
437
  }
438
+
439
+ // Builtin is already a permanent reuse source (see isManifestEntryAvailableLocally),
440
+ // so there's no need to also duplicate a byte-identical file into the delta cache.
441
+ final String relativePath = file.getAbsolutePath().substring(bundlePrefixLength);
442
+ final File builtinFile = new File(builtinFolder, relativePath);
443
+ if (verifyChecksum(builtinFile, checksum)) {
444
+ continue;
445
+ }
446
+
402
447
  final String cacheName = checksum + "_" + file.getName();
403
448
  final File cacheFile = new File(cacheDir, cacheName);
404
449
  if (cacheFile.exists()) {
405
450
  continue;
406
451
  }
407
452
  try {
408
- copyFile(file, cacheFile);
453
+ copyFileAtomically(file, cacheFile);
409
454
  } catch (IOException e) {
410
455
  logger.debug("Delta cache copy failed: " + file.getPath());
411
456
  }
@@ -431,7 +476,7 @@ public class CapgoUpdater {
431
476
 
432
477
  private void copyFile(final File source, final File dest) throws IOException {
433
478
  try (final FileInputStream input = new FileInputStream(source); final FileOutputStream output = new FileOutputStream(dest)) {
434
- final byte[] buffer = new byte[1024 * 1024];
479
+ final byte[] buffer = new byte[CryptoCipher.copyBufferBytes()];
435
480
  int length;
436
481
  while ((length = input.read(buffer)) != -1) {
437
482
  output.write(buffer, 0, length);
@@ -471,28 +516,74 @@ public class CapgoUpdater {
471
516
  return false;
472
517
  }
473
518
 
474
- final File builtinFile = new File(this.activity.getFilesDir(), "public/" + fileName);
475
- if (verifyChecksum(builtinFile, fileHash)) {
519
+ if (DownloadService.builtinAssetMatches(this.activity.getAssets(), fileName, fileHash)) {
476
520
  return true;
477
521
  }
478
522
 
523
+ try {
524
+ final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.activity.getFilesDir(), "public"), fileName);
525
+ if (verifyChecksum(builtinFile, fileHash)) {
526
+ return true;
527
+ }
528
+ } catch (IOException ignored) {
529
+ // Invalid path; fall through to cache lookup.
530
+ }
531
+
479
532
  final boolean isBrotli = fileName.endsWith(".br");
480
533
  final String fileNameWithoutPath = new File(fileName).getName();
481
534
  final String cacheBaseName = isBrotli ? fileNameWithoutPath.substring(0, fileNameWithoutPath.length() - 3) : fileNameWithoutPath;
482
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
483
- final File cacheFile = new File(cacheFolder, fileHash + "_" + cacheBaseName);
484
- if (verifyChecksum(cacheFile, fileHash)) {
485
- return true;
486
- }
535
+ if (isSafeCacheHash(fileHash)) {
536
+ final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
537
+ final File cacheFile = new File(cacheFolder, fileHash + "_" + cacheBaseName);
538
+ // Cache files are named `{hash}_{filename}` and were checksum-verified
539
+ // when written. Re-hashing every hit re-reads the whole bundle and
540
+ // OOMs/janks low-RAM devices during getMissing / delta apply.
541
+ if (isReusableCacheFile(cacheFile, fileHash)) {
542
+ return true;
543
+ }
487
544
 
488
- if (isBrotli) {
489
- final File legacyCacheFile = new File(cacheFolder, fileHash + "_" + fileNameWithoutPath);
490
- return verifyChecksum(legacyCacheFile, fileHash);
545
+ if (isBrotli) {
546
+ final File legacyCacheFile = new File(cacheFolder, fileHash + "_" + fileNameWithoutPath);
547
+ return isReusableCacheFile(legacyCacheFile, fileHash);
548
+ }
491
549
  }
492
550
 
493
551
  return false;
494
552
  }
495
553
 
554
+ static final String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
555
+
556
+ static boolean isSafeCacheHash(final String hash) {
557
+ if (hash == null) {
558
+ return false;
559
+ }
560
+ final int len = hash.length();
561
+ if (len != 64 && len != 8) {
562
+ return false;
563
+ }
564
+ for (int i = 0; i < len; i++) {
565
+ final char c = hash.charAt(i);
566
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
567
+ return false;
568
+ }
569
+ }
570
+ return true;
571
+ }
572
+
573
+ // SHA-256 hash-named cache files were verified when written. Existence is
574
+ // enough for non-empty files; empty files are reused only for the empty SHA-256.
575
+ // CRC32 (8 hex) is too collision-prone to trust without a re-read.
576
+ static boolean isReusableCacheFile(final File file, final String expectedHash) {
577
+ if (file == null || !file.isFile() || !isSafeCacheHash(expectedHash) || expectedHash.length() != 64) {
578
+ return false;
579
+ }
580
+ final long length = file.length();
581
+ if (length > 0) {
582
+ return true;
583
+ }
584
+ return length == 0 && EMPTY_SHA256.equalsIgnoreCase(expectedHash);
585
+ }
586
+
496
587
  public JSONArray getMissingBundleFiles(final JSONArray manifest, final String sessionKey) throws JSONException {
497
588
  final JSONArray missing = new JSONArray();
498
589
  for (int i = 0; i < manifest.length(); i++) {
@@ -656,6 +747,9 @@ public class CapgoUpdater {
656
747
  if ("low_mem_fail".equals(error)) {
657
748
  sendStats("low_mem_fail", failedVersion);
658
749
  }
750
+ if ("insufficient_disk_space".equals(error)) {
751
+ sendStats("insufficient_disk_space", failedVersion);
752
+ }
659
753
  ret.put("error", error != null ? error : "download_fail");
660
754
  sendStats("download_fail", failedVersion);
661
755
  notifyListeners("downloadFailed", ret);
@@ -667,6 +761,13 @@ public class CapgoUpdater {
667
761
  }
668
762
  });
669
763
  break;
764
+ case CANCELLED:
765
+ DataManager.getInstance().clearManifest(id);
766
+ CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
767
+ if (cancelledFuture != null) {
768
+ cancelledFuture.cancel(true);
769
+ }
770
+ break;
670
771
  }
671
772
  });
672
773
  });
@@ -688,6 +789,10 @@ public class CapgoUpdater {
688
789
  }
689
790
  observeWorkProgress(this.activity, id, setNext);
690
791
 
792
+ if (manifest != null) {
793
+ DataManager.getInstance().setManifest(id, manifest);
794
+ }
795
+
691
796
  DownloadWorkerManager.enqueueDownload(
692
797
  this.activity,
693
798
  url,
@@ -712,10 +817,6 @@ public class CapgoUpdater {
712
817
  this.customId,
713
818
  this.defaultChannel
714
819
  );
715
-
716
- if (manifest != null) {
717
- DataManager.getInstance().setManifest(manifest);
718
- }
719
820
  }
720
821
 
721
822
  public Boolean finishDownload(
@@ -916,6 +1017,11 @@ public class CapgoUpdater {
916
1017
 
917
1018
  try {
918
1019
  this.deleteDirectory(entry, threadToCheck);
1020
+ if (entry.exists()) {
1021
+ logger.error("Orphan bundle directory still present after delete");
1022
+ logger.debug("Bundle ID: " + id);
1023
+ continue;
1024
+ }
919
1025
  this.removeBundleInfo(id);
920
1026
  logger.info("Deleted orphan bundle directory");
921
1027
  logger.debug("Bundle ID: " + id);
@@ -927,6 +1033,43 @@ public class CapgoUpdater {
927
1033
  }
928
1034
  }
929
1035
 
1036
+ public Set<String> allowedBundleIdsForCleanup() {
1037
+ final Set<String> allowedIds = new HashSet<>();
1038
+ for (final BundleInfo info : this.list(true)) {
1039
+ if (info == null || info.getId() == null || info.getId().isEmpty()) {
1040
+ continue;
1041
+ }
1042
+ // DELETED tombstones must not protect leftover folders.
1043
+ // DELETING stays protected so drainPendingDeletes owns the removal.
1044
+ if (info.isDeleted()) {
1045
+ continue;
1046
+ }
1047
+ allowedIds.add(info.getId());
1048
+ }
1049
+ final String currentId = this.getCurrentBundleId();
1050
+ if (currentId != null && !currentId.isEmpty()) {
1051
+ allowedIds.add(currentId);
1052
+ }
1053
+ final BundleInfo fallback = this.getFallbackBundle();
1054
+ if (fallback != null && fallback.getId() != null && !fallback.getId().isEmpty() && !fallback.isDeleting()) {
1055
+ allowedIds.add(fallback.getId());
1056
+ }
1057
+ final BundleInfo next = this.getNextBundle();
1058
+ if (next != null && next.getId() != null && !next.getId().isEmpty() && !next.isDeleting()) {
1059
+ allowedIds.add(next.getId());
1060
+ }
1061
+ final BundleInfo previewFallback = this.getPreviewFallbackBundle();
1062
+ if (
1063
+ previewFallback != null &&
1064
+ previewFallback.getId() != null &&
1065
+ !previewFallback.getId().isEmpty() &&
1066
+ !previewFallback.isDeleting()
1067
+ ) {
1068
+ allowedIds.add(previewFallback.getId());
1069
+ }
1070
+ return allowedIds;
1071
+ }
1072
+
930
1073
  public void cleanupOrphanedTempFolders(final Thread threadToCheck) {
931
1074
  if (this.documentsDir == null) {
932
1075
  logger.warn("Documents directory is null, skipping temp folder cleanup");
@@ -983,7 +1126,7 @@ public class CapgoUpdater {
983
1126
  }
984
1127
 
985
1128
  private void setCurrentBundle(final File bundle) {
986
- this.cancelBackgroundRunnerWorkBeforeBundleSwitch();
1129
+ this.resetBackgroundRunnerWorkForBundleSwitch(bundle);
987
1130
  this.editor.putString(this.CAP_SERVER_PATH, bundle.getPath());
988
1131
  logger.info("Current bundle set to: " + bundle);
989
1132
  this.editor.commit();
@@ -993,7 +1136,33 @@ public class CapgoUpdater {
993
1136
  return bundlePath != null && !bundlePath.trim().isEmpty() && !isBuiltin && !hasStoredBundleInfo;
994
1137
  }
995
1138
 
996
- static String getBackgroundRunnerLabelFromConfig(final String configJson) {
1139
+ static final class BackgroundRunnerWorkConfig {
1140
+
1141
+ final String label;
1142
+ final String src;
1143
+ final String event;
1144
+ final boolean autoStart;
1145
+ final boolean repeat;
1146
+ final int interval;
1147
+
1148
+ BackgroundRunnerWorkConfig(
1149
+ final String label,
1150
+ final String src,
1151
+ final String event,
1152
+ final boolean autoStart,
1153
+ final boolean repeat,
1154
+ final int interval
1155
+ ) {
1156
+ this.label = label;
1157
+ this.src = src;
1158
+ this.event = event;
1159
+ this.autoStart = autoStart;
1160
+ this.repeat = repeat;
1161
+ this.interval = interval;
1162
+ }
1163
+ }
1164
+
1165
+ static BackgroundRunnerWorkConfig getBackgroundRunnerWorkConfigFromConfig(final String configJson) {
997
1166
  if (configJson == null || configJson.trim().isEmpty()) {
998
1167
  return null;
999
1168
  }
@@ -1011,12 +1180,30 @@ public class CapgoUpdater {
1011
1180
  }
1012
1181
 
1013
1182
  final String label = backgroundRunner.optString("label", "").trim();
1014
- return label.isEmpty() ? null : label;
1183
+ if (label.isEmpty()) {
1184
+ return null;
1185
+ }
1186
+
1187
+ final String src = backgroundRunner.optString("src", "").trim();
1188
+ final String event = backgroundRunner.optString("event", "").trim();
1189
+ return new BackgroundRunnerWorkConfig(
1190
+ label,
1191
+ src,
1192
+ event,
1193
+ backgroundRunner.optBoolean("autoStart", false),
1194
+ backgroundRunner.optBoolean("repeat", false),
1195
+ backgroundRunner.optInt("interval", 0)
1196
+ );
1015
1197
  } catch (JSONException ignored) {
1016
1198
  return null;
1017
1199
  }
1018
1200
  }
1019
1201
 
1202
+ static String getBackgroundRunnerLabelFromConfig(final String configJson) {
1203
+ final BackgroundRunnerWorkConfig config = getBackgroundRunnerWorkConfigFromConfig(configJson);
1204
+ return config == null ? null : config.label;
1205
+ }
1206
+
1020
1207
  private String readAssetAsString(final String assetPath) throws IOException {
1021
1208
  final StringBuilder buffer = new StringBuilder();
1022
1209
  try (
@@ -1032,32 +1219,131 @@ public class CapgoUpdater {
1032
1219
  return buffer.toString();
1033
1220
  }
1034
1221
 
1035
- private void cancelBackgroundRunnerWorkBeforeBundleSwitch() {
1222
+ private void copyFileAtomically(final File source, final File dest) throws IOException {
1223
+ final File parent = dest.getParentFile();
1224
+ if (parent != null && !parent.exists() && !parent.mkdirs()) {
1225
+ throw new IOException("Failed to create parent directory: " + parent.getAbsolutePath());
1226
+ }
1227
+
1228
+ final File tempFile = File.createTempFile("capgo-", ".tmp", parent);
1229
+ try {
1230
+ try (
1231
+ final FileInputStream input = new FileInputStream(source);
1232
+ final FileOutputStream output = new FileOutputStream(tempFile)
1233
+ ) {
1234
+ final byte[] buffer = new byte[CryptoCipher.copyBufferBytes()];
1235
+ int length;
1236
+ while ((length = input.read(buffer)) != -1) {
1237
+ output.write(buffer, 0, length);
1238
+ }
1239
+ }
1240
+ CryptoCipher.replaceFile(tempFile, dest);
1241
+ } finally {
1242
+ if (tempFile.exists()) {
1243
+ tempFile.delete();
1244
+ }
1245
+ }
1246
+ }
1247
+
1248
+ private void syncBackgroundRunnerScriptFromBundle(final File bundle, final BackgroundRunnerWorkConfig config) {
1249
+ if (this.activity == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1250
+ return;
1251
+ }
1252
+
1253
+ if (bundle.getPath().endsWith("/public") || "public".equals(bundle.getName())) {
1254
+ return;
1255
+ }
1256
+
1257
+ try {
1258
+ final File source = resolvePathInsideDirectory(bundle, config.src);
1259
+ if (!source.isFile()) {
1260
+ return;
1261
+ }
1262
+
1263
+ final File publicDir = new File(this.activity.getFilesDir(), "public");
1264
+ final File dest = resolvePathInsideDirectory(publicDir, config.src);
1265
+ this.copyFileAtomically(source, dest);
1266
+ logger.info("Synced Background Runner script into native public storage before bundle switch.");
1267
+ logger.debug("Background Runner script path: " + dest.getAbsolutePath());
1268
+ } catch (Exception e) {
1269
+ logger.debug("Background Runner script sync skipped: " + e.getMessage());
1270
+ }
1271
+ }
1272
+
1273
+ private void resetBackgroundRunnerWorkForBundleSwitch(final File bundle) {
1036
1274
  if (this.activity == null) {
1037
1275
  return;
1038
1276
  }
1039
1277
 
1040
- final String label;
1278
+ final BackgroundRunnerWorkConfig config;
1041
1279
  try {
1042
- label = getBackgroundRunnerLabelFromConfig(this.readAssetAsString(CAPACITOR_CONFIG_ASSET));
1280
+ config = getBackgroundRunnerWorkConfigFromConfig(this.readAssetAsString(CAPACITOR_CONFIG_ASSET));
1043
1281
  } catch (IOException ignored) {
1044
1282
  return;
1045
1283
  }
1046
1284
 
1047
- if (label == null) {
1285
+ if (config == null) {
1048
1286
  return;
1049
1287
  }
1050
1288
 
1051
1289
  try {
1052
1290
  final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1053
- workManager.cancelUniqueWork(label);
1054
- workManager.cancelAllWorkByTag(label);
1291
+ workManager.cancelUniqueWork(config.label);
1292
+ workManager.cancelAllWorkByTag(config.label);
1055
1293
  logger.info("Cancelled Background Runner work before bundle switch.");
1056
- logger.debug("Background Runner label: " + label);
1294
+ logger.debug("Background Runner label: " + config.label);
1057
1295
  } catch (Exception e) {
1058
1296
  logger.warn("Failed to cancel Background Runner work before bundle switch.");
1059
1297
  logger.debug("Background Runner cancellation error: " + e.getMessage());
1060
1298
  }
1299
+
1300
+ this.syncBackgroundRunnerScriptFromBundle(bundle, config);
1301
+ this.rescheduleBackgroundRunnerWork(config);
1302
+ }
1303
+
1304
+ private void rescheduleBackgroundRunnerWork(final BackgroundRunnerWorkConfig config) {
1305
+ if (!config.autoStart || config.interval <= 0 || config.src.isEmpty()) {
1306
+ return;
1307
+ }
1308
+
1309
+ try {
1310
+ @SuppressWarnings("unchecked")
1311
+ final Class<? extends ListenableWorker> workerClass = (Class<? extends ListenableWorker>) Class.forName(
1312
+ BACKGROUND_RUNNER_WORKER_CLASS
1313
+ );
1314
+ final Data data = new Data.Builder()
1315
+ .putString("label", config.label)
1316
+ .putString("src", config.src)
1317
+ .putString("event", config.event)
1318
+ .build();
1319
+ final Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
1320
+ final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1321
+
1322
+ if (!config.repeat) {
1323
+ final OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(workerClass)
1324
+ .setInitialDelay(config.interval, TimeUnit.MINUTES)
1325
+ .setInputData(data)
1326
+ .addTag(config.label)
1327
+ .setConstraints(constraints)
1328
+ .build();
1329
+ workManager.enqueueUniqueWork(config.label, ExistingWorkPolicy.REPLACE, work);
1330
+ } else {
1331
+ final PeriodicWorkRequest work = new PeriodicWorkRequest.Builder(workerClass, config.interval, TimeUnit.MINUTES)
1332
+ .setInitialDelay(config.interval, TimeUnit.MINUTES)
1333
+ .setInputData(data)
1334
+ .addTag(config.label)
1335
+ .setConstraints(constraints)
1336
+ .build();
1337
+ workManager.enqueueUniquePeriodicWork(config.label, ExistingPeriodicWorkPolicy.UPDATE, work);
1338
+ }
1339
+
1340
+ logger.info("Rescheduled Background Runner work after bundle switch.");
1341
+ } catch (ClassNotFoundException ignored) {
1342
+ logger.debug("Background Runner plugin not installed, skipping reschedule.");
1343
+ } catch (Exception e) {
1344
+ logger.warn("Failed to reschedule Background Runner work after bundle switch.");
1345
+ logger.debug("Background Runner reschedule error: " + e.getMessage());
1346
+ }
1061
1347
  }
1062
1348
 
1063
1349
  private boolean hasStoredBundleInfo(final String id) {
@@ -1070,6 +1356,27 @@ public class CapgoUpdater {
1070
1356
  );
1071
1357
  }
1072
1358
 
1359
+ private void runDownloadGate() throws IOException {
1360
+ if (this.downloadGate == null) {
1361
+ return;
1362
+ }
1363
+ try {
1364
+ this.downloadGate.run();
1365
+ } catch (final RuntimeException e) {
1366
+ throw new IOException(e.getMessage() == null ? "Download gate failed" : e.getMessage(), e);
1367
+ }
1368
+ }
1369
+
1370
+ private boolean runDownloadGateQuiet() {
1371
+ try {
1372
+ this.runDownloadGate();
1373
+ return true;
1374
+ } catch (final IOException e) {
1375
+ logger.error("Download blocked by cleanup gate: " + e.getMessage());
1376
+ return false;
1377
+ }
1378
+ }
1379
+
1073
1380
  public void downloadBackground(
1074
1381
  final String url,
1075
1382
  final String version,
@@ -1088,6 +1395,9 @@ public class CapgoUpdater {
1088
1395
  final JSONArray manifest,
1089
1396
  final boolean setNext
1090
1397
  ) {
1398
+ if (!this.runDownloadGateQuiet()) {
1399
+ return;
1400
+ }
1091
1401
  final String id = this.randomString();
1092
1402
 
1093
1403
  // Check if version is already downloading, but allow retry if previous download failed
@@ -1096,7 +1406,10 @@ public class CapgoUpdater {
1096
1406
  BundleInfo existingBundle = this.getBundleInfoByName(version);
1097
1407
  if (existingBundle != null && existingBundle.isErrorStatus()) {
1098
1408
  // Cancel the failed download and allow retry
1099
- DownloadWorkerManager.cancelVersionDownload(this.activity, version);
1409
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, version)) {
1410
+ logger.error("Failed to cancel previous download before retry");
1411
+ return;
1412
+ }
1100
1413
  logger.info("Retrying failed download for version: " + version);
1101
1414
  } else {
1102
1415
  logger.info("Version already downloading: " + version);
@@ -1112,11 +1425,14 @@ public class CapgoUpdater {
1112
1425
  }
1113
1426
 
1114
1427
  public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
1428
+ this.runDownloadGate();
1115
1429
  // Check for existing bundle with same version and clean up if in error state
1116
1430
  BundleInfo existingBundle = this.getBundleInfoByName(version);
1117
- if (existingBundle != null && (existingBundle.isErrorStatus() || existingBundle.isDeleted())) {
1431
+ if (existingBundle != null && (existingBundle.isErrorStatus() || existingBundle.isDeleted() || existingBundle.isDeleting())) {
1118
1432
  logger.info("Found existing failed bundle for version " + version + ", deleting before retry");
1119
- this.delete(existingBundle.getId(), true);
1433
+ if (!Boolean.TRUE.equals(this.delete(existingBundle.getId(), true))) {
1434
+ throw new IOException("Failed to delete existing bundle before retry");
1435
+ }
1120
1436
  }
1121
1437
 
1122
1438
  final String id = this.randomString();
@@ -1160,15 +1476,18 @@ public class CapgoUpdater {
1160
1476
  final String checksum,
1161
1477
  final JSONArray manifest
1162
1478
  ) throws IOException {
1479
+ this.runDownloadGate();
1163
1480
  if (manifest == null) {
1164
1481
  return download(url, version, sessionKey, checksum);
1165
1482
  }
1166
1483
 
1167
1484
  // Check for existing bundle with same version and clean up if in error state
1168
1485
  BundleInfo existingBundle = this.getBundleInfoByName(version);
1169
- if (existingBundle != null && (existingBundle.isErrorStatus() || existingBundle.isDeleted())) {
1486
+ if (existingBundle != null && (existingBundle.isErrorStatus() || existingBundle.isDeleted() || existingBundle.isDeleting())) {
1170
1487
  logger.info("Found existing failed bundle for version " + version + ", deleting before retry");
1171
- this.delete(existingBundle.getId(), true);
1488
+ if (!Boolean.TRUE.equals(this.delete(existingBundle.getId(), true))) {
1489
+ throw new IOException("Failed to delete existing bundle before retry");
1490
+ }
1172
1491
  }
1173
1492
 
1174
1493
  final String id = this.randomString();
@@ -1233,51 +1552,96 @@ public class CapgoUpdater {
1233
1552
  }
1234
1553
 
1235
1554
  public Boolean delete(final String id, final Boolean removeInfo) throws IOException {
1236
- final BundleInfo deleted = this.getBundleInfo(id);
1237
- if (deleted.isBuiltin() || this.getCurrentBundleId().equals(id)) {
1238
- logger.error("Cannot delete current or builtin bundle");
1239
- logger.debug("Bundle ID: " + id);
1240
- return false;
1241
- }
1242
- final BundleInfo previewFallback = this.getPreviewFallbackBundle();
1243
- if (
1244
- previewFallback != null &&
1245
- !previewFallback.isDeleted() &&
1246
- !previewFallback.isErrorStatus() &&
1247
- previewFallback.getId().equals(id)
1248
- ) {
1249
- logger.error("Cannot delete the preview fallback bundle");
1250
- logger.debug("Bundle ID: " + id);
1251
- return false;
1252
- }
1253
- final BundleInfo next = this.getNextBundle();
1254
- if (next != null && !next.isDeleted() && !next.isErrorStatus() && next.getId().equals(id)) {
1255
- logger.error("Cannot delete the next bundle");
1256
- logger.debug("Bundle ID: " + id);
1257
- return false;
1258
- }
1259
- // Cancel download for this version if active
1260
- if (this.activity != null) {
1261
- DownloadWorkerManager.cancelVersionDownload(this.activity, deleted.getVersionName());
1262
- }
1263
- final File bundle = new File(this.documentsDir, bundleDirectory + "/" + id);
1264
- if (bundle.exists()) {
1265
- this.deleteDirectory(bundle);
1266
- if (!removeInfo) {
1267
- this.saveBundleInfo(id, deleted.setStatus(BundleStatus.DELETED));
1555
+ return this.delete(id, removeInfo, true);
1556
+ }
1557
+
1558
+ public Boolean delete(final String id, final Boolean removeInfo, final boolean cancelActiveDownload) throws IOException {
1559
+ synchronized (this.deleteLock) {
1560
+ final BundleInfo deleted = this.getBundleInfo(id);
1561
+ if (deleted.isBuiltin() || this.getCurrentBundleId().equals(id)) {
1562
+ logger.error("Cannot delete current or builtin bundle");
1563
+ logger.debug("Bundle ID: " + id);
1564
+ return false;
1565
+ }
1566
+ final BundleInfo previewFallback = this.getPreviewFallbackBundle();
1567
+ if (
1568
+ previewFallback != null &&
1569
+ !previewFallback.isDeleted() &&
1570
+ !previewFallback.isErrorStatus() &&
1571
+ !previewFallback.isDeleting() &&
1572
+ previewFallback.getId().equals(id)
1573
+ ) {
1574
+ logger.error("Cannot delete the preview fallback bundle");
1575
+ logger.debug("Bundle ID: " + id);
1576
+ return false;
1577
+ }
1578
+ final BundleInfo next = this.getNextBundle();
1579
+ if (next != null && !next.isDeleted() && !next.isErrorStatus() && !next.isDeleting() && next.getId().equals(id)) {
1580
+ logger.error("Cannot delete the next bundle");
1581
+ logger.debug("Bundle ID: " + id);
1582
+ return false;
1583
+ }
1584
+
1585
+ final File bundle = this.getBundleDirectory(id);
1586
+ final boolean hadRegistry = this.hasStoredBundleInfo(id);
1587
+ final boolean hadFolder = bundle.exists();
1588
+ if (!hadRegistry && !hadFolder) {
1589
+ logger.error("Cannot delete unknown bundle");
1590
+ logger.debug("Bundle ID: " + id);
1591
+ return false;
1592
+ }
1593
+
1594
+ // Persist DELETING before touching disk so kill/OOM can resume on next launch.
1595
+ if (!deleted.isDeleting()) {
1596
+ if (!this.saveBundleInfo(id, deleted.setStatus(BundleStatus.DELETING))) {
1597
+ logger.error("Failed to persist DELETING marker, aborting disk delete");
1598
+ logger.debug("Bundle ID: " + id);
1599
+ return false;
1600
+ }
1601
+ }
1602
+
1603
+ // Cancel download for this version if active
1604
+ if (cancelActiveDownload && this.activity != null) {
1605
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, deleted.getVersionName())) {
1606
+ logger.error("Failed to cancel active download before delete");
1607
+ return false;
1608
+ }
1609
+ }
1610
+
1611
+ if (bundle.exists()) {
1612
+ try {
1613
+ this.deleteDirectory(bundle);
1614
+ } catch (final IOException e) {
1615
+ logger.error("Failed to delete bundle folder, will retry later");
1616
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
1617
+ return false;
1618
+ }
1619
+ }
1620
+
1621
+ // Only drop registry after the folder is confirmed gone.
1622
+ if (bundle.exists()) {
1623
+ logger.error("Bundle folder still present after delete, will retry later");
1624
+ logger.debug("Bundle ID: " + id);
1625
+ return false;
1626
+ }
1627
+
1628
+ final boolean finalized;
1629
+ if (Boolean.FALSE.equals(removeInfo)) {
1630
+ finalized = this.saveBundleInfo(id, deleted.setStatus(BundleStatus.DELETED));
1268
1631
  } else {
1269
- this.removeBundleInfo(id);
1632
+ finalized = this.saveBundleInfo(id, null);
1633
+ }
1634
+ if (!finalized) {
1635
+ logger.error("Failed to finalize delete registry update, will retry later");
1636
+ logger.debug("Bundle ID: " + id);
1637
+ return false;
1270
1638
  }
1639
+ this.sendStats("delete", deleted.getVersionName());
1640
+ this.dequeuePendingDelete(id);
1641
+ logger.info("Bundle deleted and confirmed gone");
1642
+ logger.debug("Bundle ID: " + id);
1271
1643
  return true;
1272
1644
  }
1273
- logger.info("Bundle not found on disk");
1274
- logger.debug("Version: " + deleted.getVersionName());
1275
- // perhaps we did not find the bundle in the files, but if the user requested a delete, we delete
1276
- if (removeInfo) {
1277
- this.removeBundleInfo(id);
1278
- }
1279
- this.sendStats("delete", deleted.getVersionName());
1280
- return false;
1281
1645
  }
1282
1646
 
1283
1647
  public Boolean delete(final String id) {
@@ -1290,6 +1654,82 @@ public class CapgoUpdater {
1290
1654
  }
1291
1655
  }
1292
1656
 
1657
+ /**
1658
+ * Resume incomplete deletes one-by-one. Safe across app kill / OOM because
1659
+ * delete() marks DELETING before disk work and only clears registry after confirm.
1660
+ */
1661
+ public void drainPendingDeletes() {
1662
+ final LinkedHashSet<String> pendingIds = new LinkedHashSet<>();
1663
+ for (final BundleInfo info : this.list(true)) {
1664
+ if (info != null && info.isDeleting() && info.getId() != null && !info.getId().isEmpty()) {
1665
+ pendingIds.add(info.getId());
1666
+ }
1667
+ }
1668
+ pendingIds.addAll(this.getPendingDeleteIds());
1669
+ for (final String id : pendingIds) {
1670
+ try {
1671
+ logger.info("Resuming pending delete for bundle: " + id);
1672
+ if (Boolean.TRUE.equals(this.delete(id, true))) {
1673
+ this.dequeuePendingDelete(id);
1674
+ }
1675
+ } catch (final Exception e) {
1676
+ logger.error("Pending delete failed, will retry next launch");
1677
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
1678
+ }
1679
+ try {
1680
+ Thread.sleep(DELETE_PACE_MS);
1681
+ } catch (final InterruptedException ie) {
1682
+ Thread.currentThread().interrupt();
1683
+ return;
1684
+ }
1685
+ }
1686
+ }
1687
+
1688
+ private Set<String> getPendingDeleteIds() {
1689
+ final Set<String> ids = new LinkedHashSet<>();
1690
+ if (this.prefs == null) {
1691
+ return ids;
1692
+ }
1693
+ final String raw = this.prefs.getString(PENDING_DELETE_IDS, "");
1694
+ if (raw == null || raw.isEmpty()) {
1695
+ return ids;
1696
+ }
1697
+ for (final String part : raw.split(",")) {
1698
+ if (part != null && !part.isEmpty()) {
1699
+ ids.add(part);
1700
+ }
1701
+ }
1702
+ return ids;
1703
+ }
1704
+
1705
+ private void enqueuePendingDelete(final String id) {
1706
+ if (id == null || id.isEmpty() || this.editor == null || this.prefs == null) {
1707
+ return;
1708
+ }
1709
+ final Set<String> ids = this.getPendingDeleteIds();
1710
+ if (!ids.add(id)) {
1711
+ return;
1712
+ }
1713
+ this.editor.putString(PENDING_DELETE_IDS, String.join(",", ids));
1714
+ this.editor.commit();
1715
+ }
1716
+
1717
+ private void dequeuePendingDelete(final String id) {
1718
+ if (id == null || id.isEmpty() || this.editor == null || this.prefs == null) {
1719
+ return;
1720
+ }
1721
+ final Set<String> ids = this.getPendingDeleteIds();
1722
+ if (!ids.remove(id)) {
1723
+ return;
1724
+ }
1725
+ if (ids.isEmpty()) {
1726
+ this.editor.remove(PENDING_DELETE_IDS);
1727
+ } else {
1728
+ this.editor.putString(PENDING_DELETE_IDS, String.join(",", ids));
1729
+ }
1730
+ this.editor.commit();
1731
+ }
1732
+
1293
1733
  private File getBundleDirectory(final String id) {
1294
1734
  return new File(this.documentsDir, bundleDirectory + "/" + id);
1295
1735
  }
@@ -1297,7 +1737,13 @@ public class CapgoUpdater {
1297
1737
  private boolean bundleExists(final String id) {
1298
1738
  final File bundle = this.getBundleDirectory(id);
1299
1739
  final BundleInfo bundleInfo = this.getBundleInfo(id);
1300
- return (bundle.isDirectory() && bundle.exists() && new File(bundle.getPath(), "/index.html").exists() && !bundleInfo.isDeleted());
1740
+ return (
1741
+ bundle.isDirectory() &&
1742
+ bundle.exists() &&
1743
+ new File(bundle.getPath(), "/index.html").exists() &&
1744
+ !bundleInfo.isDeleted() &&
1745
+ !bundleInfo.isDeleting()
1746
+ );
1301
1747
  }
1302
1748
 
1303
1749
  static final class ResetState {
@@ -1322,10 +1768,12 @@ public class CapgoUpdater {
1322
1768
  }
1323
1769
 
1324
1770
  void restoreResetState(final ResetState state) {
1325
- final String currentBundlePath =
1326
- state.currentBundlePath == null || state.currentBundlePath.trim().isEmpty() ? "public" : state.currentBundlePath;
1327
- final String fallbackBundleId =
1328
- state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
1771
+ final String currentBundlePath = state.currentBundlePath == null || state.currentBundlePath.trim().isEmpty()
1772
+ ? "public"
1773
+ : state.currentBundlePath;
1774
+ final String fallbackBundleId = state.fallbackBundleId == null || state.fallbackBundleId.isEmpty()
1775
+ ? BundleInfo.ID_BUILTIN
1776
+ : state.fallbackBundleId;
1329
1777
 
1330
1778
  this.editor.putString(this.CAP_SERVER_PATH, currentBundlePath);
1331
1779
  this.editor.putString(FALLBACK_VERSION, fallbackBundleId);
@@ -1476,21 +1924,54 @@ public class CapgoUpdater {
1476
1924
  // Only attempt to delete when the fallback is a different bundle than the
1477
1925
  // currently loaded one. Otherwise we spam logs with "Cannot delete <id>"
1478
1926
  // because delete() protects the current bundle from removal.
1479
- if (
1480
- autoDeletePrevious &&
1927
+ final String previousFallbackId = fallback.getId();
1928
+ final String previousFallbackVersion = fallback.getVersionName();
1929
+ final BundleInfo nextBundle = this.getNextBundle();
1930
+ final boolean previousIsNext =
1931
+ nextBundle != null &&
1932
+ previousFallbackId != null &&
1933
+ previousFallbackId.equals(nextBundle.getId()) &&
1934
+ !nextBundle.isDeleted() &&
1935
+ !nextBundle.isErrorStatus() &&
1936
+ !nextBundle.isDeleting();
1937
+ final boolean shouldDeletePrevious =
1938
+ Boolean.TRUE.equals(autoDeletePrevious) &&
1481
1939
  !fallback.isBuiltin() &&
1482
- fallback.getId() != null &&
1483
- !fallback.getId().equals(bundle.getId()) &&
1484
- !fallbackIsPreviewFallback
1485
- ) {
1486
- final Boolean res = this.delete(fallback.getId());
1487
- if (res) {
1488
- logger.info("Deleted previous bundle: " + fallback.getVersionName());
1489
- } else {
1490
- logger.debug("Skip deleting previous bundle (same as current or protected): " + fallback.getId());
1940
+ previousFallbackId != null &&
1941
+ !previousFallbackId.equals(bundle.getId()) &&
1942
+ !fallbackIsPreviewFallback &&
1943
+ !previousIsNext;
1944
+ if (shouldDeletePrevious) {
1945
+ if (!this.saveBundleInfo(previousFallbackId, fallback.setStatus(BundleStatus.DELETING))) {
1946
+ logger.error("Failed to persist DELETING for previous bundle; queueing durable retry");
1947
+ logger.debug("Bundle ID: " + previousFallbackId);
1948
+ this.enqueuePendingDelete(previousFallbackId);
1491
1949
  }
1492
1950
  }
1951
+ boolean deletePreviousAsync = shouldDeletePrevious;
1493
1952
  this.setFallbackBundle(bundle);
1953
+ if (deletePreviousAsync) {
1954
+ final String asyncPreviousFallbackId = previousFallbackId;
1955
+ final String asyncPreviousFallbackVersion = previousFallbackVersion;
1956
+ io.execute(() -> {
1957
+ if (this.activity != null) {
1958
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, asyncPreviousFallbackVersion)) {
1959
+ logger.error("Failed to cancel previous version download before delete");
1960
+ return;
1961
+ }
1962
+ }
1963
+ try {
1964
+ final Boolean res = this.delete(asyncPreviousFallbackId, true, false);
1965
+ if (Boolean.TRUE.equals(res)) {
1966
+ logger.info("Deleted previous bundle: " + asyncPreviousFallbackVersion);
1967
+ } else {
1968
+ logger.debug("Previous bundle delete incomplete, will retry: " + asyncPreviousFallbackId);
1969
+ }
1970
+ } catch (final IOException e) {
1971
+ logger.error("Failed to delete previous bundle: " + asyncPreviousFallbackId + " " + e.getMessage());
1972
+ }
1973
+ });
1974
+ }
1494
1975
  }
1495
1976
 
1496
1977
  public void setError(final BundleInfo bundle) {
@@ -1532,56 +2013,229 @@ public class CapgoUpdater {
1532
2013
  return json;
1533
2014
  }
1534
2015
 
1535
- /**
1536
- * Check if a 429 (Too Many Requests) response was received and set the flag
1537
- */
1538
- private boolean checkAndHandleRateLimitResponse(Response response) {
1539
- if (response.code() == 429) {
1540
- // Send a statistic about the rate limit BEFORE setting the flag
1541
- // Only send once to prevent infinite loop if the stat request itself gets rate limited
1542
- if (!this.previewSession && !rateLimitExceeded && !rateLimitStatisticSent) {
1543
- rateLimitStatisticSent = true;
1544
- sendRateLimitStatistic();
1545
- }
1546
- rateLimitExceeded = true;
1547
- logger.warn("Rate limit exceeded (429). Stopping all stats and channel requests until app restart.");
1548
- return true;
2016
+ private static final class RemoteBlockResult {
2017
+
2018
+ final boolean blocked;
2019
+ final String error;
2020
+ final String message;
2021
+
2022
+ RemoteBlockResult(final boolean blocked, final String error, final String message) {
2023
+ this.blocked = blocked;
2024
+ this.error = error;
2025
+ this.message = message;
1549
2026
  }
1550
- return false;
1551
2027
  }
1552
2028
 
1553
2029
  /**
1554
- * Send a synchronous statistic about rate limiting
2030
+ * Handle HTTP 429 responses by honouring Retry-After / rateLimitResetAt.
2031
+ * All 429s use the same temporary client block — no sticky latch until restart.
1555
2032
  */
1556
- private void sendRateLimitStatistic() {
1557
- String statsUrl = this.statsUrl;
1558
- if (statsUrl == null || statsUrl.isEmpty()) {
1559
- return;
2033
+ private RemoteBlockResult checkAndHandleRateLimitResponse(Response response, String responseData) {
2034
+ if (response == null || response.code() != 429) {
2035
+ return new RemoteBlockResult(false, "", "");
2036
+ }
2037
+
2038
+ final String parsedError = parseRemoteError(responseData);
2039
+ final String parsedMessage = parseRemoteMessage(responseData);
2040
+ final String errorCode = parsedError.isEmpty() ? "too_many_requests" : parsedError;
2041
+ final String message = parsedMessage.isEmpty() ? "Too many requests" : parsedMessage;
2042
+
2043
+ final long retryUntilMs = resolveRateLimitBlockedUntilMs(response, responseData);
2044
+ synchronized (rateLimitStateLock) {
2045
+ if (retryUntilMs > rateLimitBlockedUntilMs) {
2046
+ rateLimitBlockedUntilMs = retryUntilMs;
2047
+ rateLimitBlockedError = errorCode;
2048
+ rateLimitBlockedMessage = message;
2049
+ } else if (rateLimitBlockedUntilMs <= 0L) {
2050
+ rateLimitBlockedError = errorCode;
2051
+ rateLimitBlockedMessage = message;
2052
+ }
1560
2053
  }
1561
2054
 
1562
- try {
1563
- BundleInfo current = this.getCurrentBundle();
1564
- JSONObject json = this.createInfoObject();
1565
- json.put("version_name", current.getVersionName());
1566
- json.put("old_version_name", "");
1567
- json.put("action", "rate_limit_reached");
2055
+ // Claim last, and only when there is somewhere to send it, so a 429 burst with no
2056
+ // stats URL does not claim and release the latch once per response.
2057
+ if ("too_many_requests".equals(errorCode) && !this.previewSession && this.hasStatsUrl() && claimRateLimitStatistic()) {
2058
+ sendRateLimitStatistic();
2059
+ }
1568
2060
 
1569
- Request request = new Request.Builder()
1570
- .url(statsUrl)
1571
- .post(RequestBody.create(json.toString(), MediaType.get("application/json")))
1572
- .build();
2061
+ final long nowMs = System.currentTimeMillis();
2062
+ final long retryAfter = Math.max(0L, (Math.max(retryUntilMs, nowMs) - nowMs + 999L) / 1000L);
2063
+ logger.warn("Received 429 (" + errorCode + "). Honouring Retry-After: " + retryAfter + "s.");
2064
+ return new RemoteBlockResult(true, errorCode, message);
2065
+ }
1573
2066
 
1574
- // Send synchronously to ensure it goes out before the flag is set
1575
- // User-Agent header is automatically added by DownloadService.sharedClient interceptor
1576
- try (Response response = DownloadService.sharedClient.newCall(request).execute()) {
1577
- if (response.isSuccessful()) {
1578
- logger.info("Rate limit statistic sent");
1579
- } else {
1580
- logger.error("Error sending rate limit statistic");
1581
- logger.debug("Response code: " + response.code());
2067
+ private String parseRemoteError(final String responseData) {
2068
+ if (responseData == null || responseData.isEmpty()) {
2069
+ return "";
2070
+ }
2071
+ try {
2072
+ final JSONObject json = new JSONObject(responseData);
2073
+ return json.optString("error", "");
2074
+ } catch (JSONException ignored) {
2075
+ return "";
2076
+ }
2077
+ }
2078
+
2079
+ private String parseRemoteMessage(final String responseData) {
2080
+ if (responseData == null || responseData.isEmpty()) {
2081
+ return "";
2082
+ }
2083
+ try {
2084
+ final JSONObject json = new JSONObject(responseData);
2085
+ return json.optString("message", "");
2086
+ } catch (JSONException ignored) {
2087
+ return "";
2088
+ }
2089
+ }
2090
+
2091
+ private long resolveRateLimitBlockedUntilMs(final Response response, final String responseData) {
2092
+ final long nowMs = System.currentTimeMillis();
2093
+ final double candidate = rawRateLimitDeadlineMs(response, responseData, nowMs);
2094
+ // NaN and past deadlines mean "no client-side block"; anything further out is capped.
2095
+ if (!(candidate > nowMs)) {
2096
+ return 0L;
2097
+ }
2098
+ return (long) Math.min(candidate, (double) nowMs + MAX_RATE_LIMIT_WINDOW_MS);
2099
+ }
2100
+
2101
+ private double rawRateLimitDeadlineMs(final Response response, final String responseData, final long nowMs) {
2102
+ final String header = response.header("Retry-After");
2103
+ if (header != null) {
2104
+ try {
2105
+ final double seconds = Double.parseDouble(header.trim());
2106
+ if (seconds >= 0) {
2107
+ return nowMs + seconds * 1000d;
2108
+ }
2109
+ } catch (NumberFormatException ignored) {
2110
+ // Fall through to body fields
2111
+ }
2112
+ }
2113
+
2114
+ if (responseData != null && !responseData.isEmpty()) {
2115
+ try {
2116
+ final JSONObject json = new JSONObject(responseData);
2117
+ final JSONObject moreInfo = json.optJSONObject("moreInfo");
2118
+ if (moreInfo != null && moreInfo.has("retryAfterSeconds")) {
2119
+ final double retryAfter = moreInfo.getDouble("retryAfterSeconds");
2120
+ if (retryAfter >= 0) {
2121
+ return nowMs + retryAfter * 1000d;
2122
+ }
2123
+ } else if (json.has("retryAfterSeconds")) {
2124
+ final double retryAfter = json.getDouble("retryAfterSeconds");
2125
+ if (retryAfter >= 0) {
2126
+ return nowMs + retryAfter * 1000d;
2127
+ }
2128
+ }
2129
+ if (moreInfo != null && moreInfo.has("rateLimitResetAt")) {
2130
+ return moreInfo.getDouble("rateLimitResetAt");
2131
+ } else if (json.has("rateLimitResetAt")) {
2132
+ return json.getDouble("rateLimitResetAt");
1582
2133
  }
2134
+ } catch (JSONException ignored) {
2135
+ // No retry hint
2136
+ }
2137
+ }
2138
+
2139
+ // No retry hint — do not hold a client-side block; allow immediate retry to the worker
2140
+ return 0d;
2141
+ }
2142
+
2143
+ private static boolean claimRateLimitStatistic() {
2144
+ synchronized (rateLimitStateLock) {
2145
+ if (rateLimitStatisticSent) {
2146
+ return false;
2147
+ }
2148
+ rateLimitStatisticSent = true;
2149
+ return true;
2150
+ }
2151
+ }
2152
+
2153
+ /**
2154
+ * Give the claim back when the statistic never made it out, so a later 429 can retry it.
2155
+ */
2156
+ private static void releaseRateLimitStatisticClaim() {
2157
+ synchronized (rateLimitStateLock) {
2158
+ rateLimitStatisticSent = false;
2159
+ }
2160
+ }
2161
+
2162
+ private boolean hasStatsUrl() {
2163
+ final String url = this.statsUrl;
2164
+ return url != null && !url.isEmpty();
2165
+ }
2166
+
2167
+ private boolean isRemoteBlocked() {
2168
+ synchronized (rateLimitStateLock) {
2169
+ if (rateLimitBlockedUntilMs <= 0L) {
2170
+ return false;
2171
+ }
2172
+ if (System.currentTimeMillis() >= rateLimitBlockedUntilMs) {
2173
+ rateLimitBlockedUntilMs = 0L;
2174
+ return false;
1583
2175
  }
2176
+ return true;
2177
+ }
2178
+ }
2179
+
2180
+ private RemoteBlockResult remoteBlockedClientError() {
2181
+ synchronized (rateLimitStateLock) {
2182
+ return new RemoteBlockResult(true, rateLimitBlockedError, rateLimitBlockedMessage);
2183
+ }
2184
+ }
2185
+
2186
+ /**
2187
+ * Send a statistic about rate limiting.
2188
+ * Dispatched through OkHttp so no caller thread waits on the request.
2189
+ */
2190
+ private void sendRateLimitStatistic() {
2191
+ String statsUrl = this.statsUrl;
2192
+ if (statsUrl == null || statsUrl.isEmpty()) {
2193
+ // The URL was cleared after the claim was taken; nothing went out, so hand it back.
2194
+ releaseRateLimitStatisticClaim();
2195
+ return;
2196
+ }
2197
+
2198
+ try {
2199
+ BundleInfo current = this.getCurrentBundle();
2200
+ JSONObject json = this.createInfoObject();
2201
+ json.put("version_name", current.getVersionName());
2202
+ json.put("old_version_name", "");
2203
+ json.put("action", "rate_limit_reached");
2204
+
2205
+ Request request = new Request.Builder()
2206
+ .url(statsUrl)
2207
+ .post(RequestBody.create(json.toString(), MediaType.get("application/json")))
2208
+ .build();
2209
+
2210
+ // User-Agent header is automatically added by DownloadService.sharedClient interceptor
2211
+ DownloadService.sharedClient
2212
+ .newCall(request)
2213
+ .enqueue(
2214
+ new okhttp3.Callback() {
2215
+ @Override
2216
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
2217
+ releaseRateLimitStatisticClaim();
2218
+ logger.error("Failed to send rate limit statistic");
2219
+ logger.debug("Error: " + e.getMessage());
2220
+ }
2221
+
2222
+ @Override
2223
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
2224
+ // The body is unused here; closing the Response closes it.
2225
+ try (response) {
2226
+ if (response.isSuccessful()) {
2227
+ logger.info("Rate limit statistic sent");
2228
+ } else {
2229
+ releaseRateLimitStatisticClaim();
2230
+ logger.error("Error sending rate limit statistic");
2231
+ logger.debug("Response code: " + response.code());
2232
+ }
2233
+ }
2234
+ }
2235
+ }
2236
+ );
1584
2237
  } catch (final Exception e) {
2238
+ releaseRateLimitStatisticClaim();
1585
2239
  logger.error("Failed to send rate limit statistic");
1586
2240
  logger.debug("Error: " + e.getMessage());
1587
2241
  }
@@ -1593,105 +2247,130 @@ public class CapgoUpdater {
1593
2247
 
1594
2248
  Request request = new Request.Builder().url(url).post(body).build();
1595
2249
 
1596
- DownloadService.sharedClient.newCall(request).enqueue(
1597
- new okhttp3.Callback() {
1598
- @Override
1599
- public void onFailure(@NonNull Call call, @NonNull IOException e) {
1600
- Map<String, Object> retError = new HashMap<>();
1601
- retError.put("message", "Request failed: " + e.getMessage());
1602
- retError.put("error", "network_error");
1603
- retError.put("kind", "failed");
1604
- callback.callback(retError);
1605
- }
2250
+ DownloadService.sharedClient
2251
+ .newCall(request)
2252
+ .enqueue(
2253
+ new okhttp3.Callback() {
2254
+ @Override
2255
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
2256
+ Map<String, Object> retError = new HashMap<>();
2257
+ retError.put("message", "Request failed: " + e.getMessage());
2258
+ retError.put("error", "network_error");
2259
+ retError.put("kind", "failed");
2260
+ callback.callback(retError);
2261
+ }
1606
2262
 
1607
- @Override
1608
- public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
1609
- try (ResponseBody responseBody = response.body()) {
1610
- final int statusCode = response.code();
1611
- final String responseData = responseBody != null ? responseBody.string() : "";
1612
- JSONObject jsonResponse = null;
1613
- if (!responseData.isEmpty()) {
1614
- try {
1615
- jsonResponse = new JSONObject(responseData);
1616
- } catch (JSONException ignored) {
1617
- // Non-JSON responses are handled as response or parse errors below.
2263
+ @Override
2264
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
2265
+ try (ResponseBody responseBody = response.body()) {
2266
+ final int statusCode = response.code();
2267
+ final String responseData = responseBody != null ? responseBody.string() : "";
2268
+ JSONObject jsonResponse = null;
2269
+ if (!responseData.isEmpty()) {
2270
+ try {
2271
+ jsonResponse = new JSONObject(responseData);
2272
+ } catch (JSONException ignored) {
2273
+ // Non-JSON responses are handled as response or parse errors below.
2274
+ }
1618
2275
  }
1619
- }
1620
2276
 
1621
- if (jsonResponse != null && (jsonResponse.has("error") || jsonResponse.has("kind"))) {
1622
- if (statusCode == 429) {
1623
- checkAndHandleRateLimitResponse(response);
1624
- }
1625
- Map<String, Object> retError = new HashMap<>();
1626
- if (jsonResponse.has("error") && !jsonResponse.isNull("error")) {
1627
- retError.put("error", jsonResponse.getString("error"));
2277
+ if (jsonResponse != null && (jsonResponse.has("error") || jsonResponse.has("kind"))) {
2278
+ if (statusCode == 429) {
2279
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, responseData);
2280
+ Map<String, Object> retError = new HashMap<>();
2281
+ retError.put(
2282
+ "error",
2283
+ rateLimit.error.isEmpty() ? jsonResponse.optString("error", "too_many_requests") : rateLimit.error
2284
+ );
2285
+ retError.put(
2286
+ "message",
2287
+ rateLimit.message.isEmpty()
2288
+ ? jsonResponse.optString("message", "Too many requests")
2289
+ : rateLimit.message
2290
+ );
2291
+ if (jsonResponse.has("kind") && !jsonResponse.isNull("kind")) {
2292
+ retError.put("kind", jsonResponse.getString("kind"));
2293
+ } else {
2294
+ retError.put("kind", "failed");
2295
+ }
2296
+ if (jsonResponse.has("version") && !jsonResponse.isNull("version")) {
2297
+ retError.put("version", jsonResponse.getString("version"));
2298
+ }
2299
+ retError.put("statusCode", statusCode);
2300
+ callback.callback(retError);
2301
+ return;
2302
+ }
2303
+ Map<String, Object> retError = new HashMap<>();
2304
+ if (jsonResponse.has("error") && !jsonResponse.isNull("error")) {
2305
+ retError.put("error", jsonResponse.getString("error"));
2306
+ }
2307
+ if (jsonResponse.has("kind") && !jsonResponse.isNull("kind")) {
2308
+ retError.put("kind", jsonResponse.getString("kind"));
2309
+ }
2310
+ if (jsonResponse.has("message") && !jsonResponse.isNull("message")) {
2311
+ retError.put("message", jsonResponse.getString("message"));
2312
+ } else {
2313
+ retError.put("message", "server did not provide a message");
2314
+ }
2315
+ if (jsonResponse.has("version") && !jsonResponse.isNull("version")) {
2316
+ retError.put("version", jsonResponse.getString("version"));
2317
+ }
2318
+ retError.put("statusCode", statusCode);
2319
+ callback.callback(retError);
2320
+ return;
1628
2321
  }
1629
- if (jsonResponse.has("kind") && !jsonResponse.isNull("kind")) {
1630
- retError.put("kind", jsonResponse.getString("kind"));
2322
+
2323
+ // Check for 429 rate limit without JSON body
2324
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, responseData);
2325
+ if (rateLimit.blocked) {
2326
+ Map<String, Object> retError = new HashMap<>();
2327
+ retError.put("message", rateLimit.message);
2328
+ retError.put("error", rateLimit.error);
2329
+ retError.put("kind", "failed");
2330
+ retError.put("statusCode", statusCode);
2331
+ callback.callback(retError);
2332
+ return;
1631
2333
  }
1632
- if (jsonResponse.has("message") && !jsonResponse.isNull("message")) {
1633
- retError.put("message", jsonResponse.getString("message"));
1634
- } else {
1635
- retError.put("message", "server did not provide a message");
2334
+
2335
+ if (!response.isSuccessful()) {
2336
+ Map<String, Object> retError = new HashMap<>();
2337
+ retError.put("message", "Server error: " + response.code());
2338
+ retError.put("error", "response_error");
2339
+ retError.put("kind", "failed");
2340
+ retError.put("statusCode", statusCode);
2341
+ callback.callback(retError);
2342
+ return;
1636
2343
  }
1637
- if (jsonResponse.has("version") && !jsonResponse.isNull("version")) {
1638
- retError.put("version", jsonResponse.getString("version"));
2344
+
2345
+ if (jsonResponse == null) {
2346
+ throw new JSONException("Response is not a JSON object");
1639
2347
  }
1640
- retError.put("statusCode", statusCode);
1641
- callback.callback(retError);
1642
- return;
1643
- }
1644
2348
 
1645
- // Check for 429 rate limit
1646
- if (checkAndHandleRateLimitResponse(response)) {
1647
- Map<String, Object> retError = new HashMap<>();
1648
- retError.put("message", "Rate limit exceeded");
1649
- retError.put("error", "rate_limit_exceeded");
1650
- retError.put("kind", "failed");
1651
- retError.put("statusCode", statusCode);
1652
- callback.callback(retError);
1653
- return;
1654
- }
2349
+ Map<String, Object> ret = new HashMap<>();
2350
+ ret.put("statusCode", statusCode);
1655
2351
 
1656
- if (!response.isSuccessful()) {
2352
+ Iterator<String> keys = jsonResponse.keys();
2353
+ while (keys.hasNext()) {
2354
+ String key = keys.next();
2355
+ if (jsonResponse.has(key)) {
2356
+ if ("session_key".equals(key)) {
2357
+ ret.put("sessionKey", jsonResponse.get(key));
2358
+ } else {
2359
+ ret.put(key, jsonResponse.get(key));
2360
+ }
2361
+ }
2362
+ }
2363
+ callback.callback(ret);
2364
+ } catch (JSONException e) {
1657
2365
  Map<String, Object> retError = new HashMap<>();
1658
- retError.put("message", "Server error: " + response.code());
1659
- retError.put("error", "response_error");
2366
+ retError.put("message", "JSON parse error: " + e.getMessage());
2367
+ retError.put("error", "parse_error");
1660
2368
  retError.put("kind", "failed");
1661
- retError.put("statusCode", statusCode);
1662
2369
  callback.callback(retError);
1663
- return;
1664
2370
  }
1665
-
1666
- if (jsonResponse == null) {
1667
- throw new JSONException("Response is not a JSON object");
1668
- }
1669
-
1670
- Map<String, Object> ret = new HashMap<>();
1671
- ret.put("statusCode", statusCode);
1672
-
1673
- Iterator<String> keys = jsonResponse.keys();
1674
- while (keys.hasNext()) {
1675
- String key = keys.next();
1676
- if (jsonResponse.has(key)) {
1677
- if ("session_key".equals(key)) {
1678
- ret.put("sessionKey", jsonResponse.get(key));
1679
- } else {
1680
- ret.put(key, jsonResponse.get(key));
1681
- }
1682
- }
1683
- }
1684
- callback.callback(ret);
1685
- } catch (JSONException e) {
1686
- Map<String, Object> retError = new HashMap<>();
1687
- retError.put("message", "JSON parse error: " + e.getMessage());
1688
- retError.put("error", "parse_error");
1689
- retError.put("kind", "failed");
1690
- callback.callback(retError);
1691
2371
  }
1692
2372
  }
1693
- }
1694
- );
2373
+ );
1695
2374
  }
1696
2375
 
1697
2376
  public void getLatest(final String updateUrl, final String channel, final Callback callback) {
@@ -1699,6 +2378,16 @@ public class CapgoUpdater {
1699
2378
  }
1700
2379
 
1701
2380
  public void getLatest(final String updateUrl, final String channel, final String appIdOverride, final Callback callback) {
2381
+ if (isRemoteBlocked()) {
2382
+ final RemoteBlockResult blocked = remoteBlockedClientError();
2383
+ logger.debug("Skipping getLatest due to remote block (" + blocked.error + ").");
2384
+ final Map<String, Object> retError = new HashMap<>();
2385
+ retError.put("message", blocked.message);
2386
+ retError.put("error", blocked.error);
2387
+ retError.put("kind", "failed");
2388
+ callback.callback(retError);
2389
+ return;
2390
+ }
1702
2391
  JSONObject json;
1703
2392
  try {
1704
2393
  json = this.createInfoObject(appIdOverride);
@@ -1768,12 +2457,12 @@ public class CapgoUpdater {
1768
2457
  return;
1769
2458
  }
1770
2459
 
1771
- // Check if rate limit was exceeded
1772
- if (rateLimitExceeded) {
1773
- logger.debug("Skipping setChannel due to rate limit (429). Requests will resume after app restart.");
2460
+ if (isRemoteBlocked()) {
2461
+ final RemoteBlockResult blocked = remoteBlockedClientError();
2462
+ logger.debug("Skipping setChannel due to remote block (" + blocked.error + ").");
1774
2463
  final Map<String, Object> retError = new HashMap<>();
1775
- retError.put("message", "Rate limit exceeded");
1776
- retError.put("error", "rate_limit_exceeded");
2464
+ retError.put("message", blocked.message);
2465
+ retError.put("error", blocked.error);
1777
2466
  callback.callback(retError);
1778
2467
  return;
1779
2468
  }
@@ -1813,7 +2502,6 @@ public class CapgoUpdater {
1813
2502
  logger.info("Public channel requested, channel override removed");
1814
2503
  callback.callback(res);
1815
2504
  } else {
1816
- // Success - persist defaultChannel
1817
2505
  this.defaultChannel = channel;
1818
2506
  editor.putString(defaultChannelKey, channel);
1819
2507
  editor.apply();
@@ -1828,12 +2516,12 @@ public class CapgoUpdater {
1828
2516
  }
1829
2517
 
1830
2518
  public void getChannel(final Callback callback, final SharedPreferences.Editor editor, final String defaultChannelKey) {
1831
- // Check if rate limit was exceeded
1832
- if (rateLimitExceeded) {
1833
- logger.debug("Skipping getChannel due to rate limit (429). Requests will resume after app restart.");
2519
+ if (isRemoteBlocked()) {
2520
+ final RemoteBlockResult blocked = remoteBlockedClientError();
2521
+ logger.debug("Skipping getChannel due to remote block (" + blocked.error + ").");
1834
2522
  final Map<String, Object> retError = new HashMap<>();
1835
- retError.put("message", "Rate limit exceeded");
1836
- retError.put("error", "rate_limit_exceeded");
2523
+ retError.put("message", blocked.message);
2524
+ retError.put("error", blocked.error);
1837
2525
  callback.callback(retError);
1838
2526
  return;
1839
2527
  }
@@ -1865,99 +2553,93 @@ public class CapgoUpdater {
1865
2553
  .put(RequestBody.create(json.toString(), MediaType.get("application/json")))
1866
2554
  .build();
1867
2555
 
1868
- DownloadService.sharedClient.newCall(request).enqueue(
1869
- new okhttp3.Callback() {
1870
- @Override
1871
- public void onFailure(@NonNull Call call, @NonNull IOException e) {
1872
- Map<String, Object> retError = new HashMap<>();
1873
- retError.put("message", "Request failed: " + e.getMessage());
1874
- retError.put("error", "network_error");
1875
- callback.callback(retError);
1876
- }
2556
+ DownloadService.sharedClient
2557
+ .newCall(request)
2558
+ .enqueue(
2559
+ new okhttp3.Callback() {
2560
+ @Override
2561
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
2562
+ Map<String, Object> retError = new HashMap<>();
2563
+ retError.put("message", "Request failed: " + e.getMessage());
2564
+ retError.put("error", "network_error");
2565
+ callback.callback(retError);
2566
+ }
1877
2567
 
1878
- @Override
1879
- public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
1880
- try (ResponseBody responseBody = response.body()) {
1881
- // Check for 429 rate limit
1882
- if (checkAndHandleRateLimitResponse(response)) {
1883
- Map<String, Object> retError = new HashMap<>();
1884
- retError.put("message", "Rate limit exceeded");
1885
- retError.put("error", "rate_limit_exceeded");
1886
- callback.callback(retError);
1887
- return;
1888
- }
2568
+ @Override
2569
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
2570
+ try (ResponseBody responseBody = response.body()) {
2571
+ final String responseData = responseBody != null ? responseBody.string() : "";
2572
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, responseData);
2573
+ if (rateLimit.blocked) {
2574
+ Map<String, Object> retError = new HashMap<>();
2575
+ retError.put("message", rateLimit.message);
2576
+ retError.put("error", rateLimit.error);
2577
+ callback.callback(retError);
2578
+ return;
2579
+ }
2580
+
2581
+ if (response.code() == 400) {
2582
+ if (responseData.contains("channel_not_found") && !defaultChannel.isEmpty()) {
2583
+ Map<String, Object> ret = new HashMap<>();
2584
+ ret.put("channel", defaultChannel);
2585
+ ret.put("status", "default");
2586
+ logger.info("Channel get to \"" + ret);
2587
+ callback.callback(ret);
2588
+ return;
2589
+ }
2590
+ }
1889
2591
 
1890
- if (response.code() == 400) {
1891
- if (responseBody == null) {
2592
+ if (!response.isSuccessful()) {
2593
+ Map<String, Object> retError = new HashMap<>();
2594
+ retError.put("message", "Server error: " + response.code());
2595
+ retError.put("error", "response_error");
2596
+ callback.callback(retError);
2597
+ return;
2598
+ }
2599
+
2600
+ if (responseData.isEmpty()) {
1892
2601
  Map<String, Object> retError = new HashMap<>();
1893
2602
  retError.put("message", "Empty response body");
1894
2603
  retError.put("error", "no_response_body");
1895
2604
  callback.callback(retError);
1896
2605
  return;
1897
2606
  }
1898
- String data = responseBody.string();
1899
- if (data.contains("channel_not_found") && !defaultChannel.isEmpty()) {
1900
- Map<String, Object> ret = new HashMap<>();
1901
- ret.put("channel", defaultChannel);
1902
- ret.put("status", "default");
1903
- logger.info("Channel get to \"" + ret);
1904
- callback.callback(ret);
2607
+ JSONObject jsonResponse = new JSONObject(responseData);
2608
+
2609
+ // Check for server-side errors first
2610
+ if (jsonResponse.has("error")) {
2611
+ Map<String, Object> retError = new HashMap<>();
2612
+ retError.put("error", jsonResponse.getString("error"));
2613
+ if (jsonResponse.has("message")) {
2614
+ retError.put("message", jsonResponse.getString("message"));
2615
+ } else {
2616
+ retError.put("message", "server did not provide a message");
2617
+ }
2618
+ callback.callback(retError);
1905
2619
  return;
1906
2620
  }
1907
- }
1908
2621
 
1909
- if (!response.isSuccessful()) {
1910
- Map<String, Object> retError = new HashMap<>();
1911
- retError.put("message", "Server error: " + response.code());
1912
- retError.put("error", "response_error");
1913
- callback.callback(retError);
1914
- return;
1915
- }
1916
-
1917
- if (responseBody == null) {
1918
- Map<String, Object> retError = new HashMap<>();
1919
- retError.put("message", "Empty response body");
1920
- retError.put("error", "no_response_body");
1921
- callback.callback(retError);
1922
- return;
1923
- }
1924
- String responseData = responseBody.string();
1925
- JSONObject jsonResponse = new JSONObject(responseData);
2622
+ Map<String, Object> ret = new HashMap<>();
1926
2623
 
1927
- // Check for server-side errors first
1928
- if (jsonResponse.has("error")) {
1929
- Map<String, Object> retError = new HashMap<>();
1930
- retError.put("error", jsonResponse.getString("error"));
1931
- if (jsonResponse.has("message")) {
1932
- retError.put("message", jsonResponse.getString("message"));
1933
- } else {
1934
- retError.put("message", "server did not provide a message");
2624
+ Iterator<String> keys = jsonResponse.keys();
2625
+ while (keys.hasNext()) {
2626
+ String key = keys.next();
2627
+ if (jsonResponse.has(key)) {
2628
+ ret.put(key, jsonResponse.get(key));
2629
+ }
1935
2630
  }
2631
+ persistDefaultChannelFromResponse(ret.get("channel"), editor, defaultChannelKey);
2632
+ logger.info("Channel get to \"" + ret);
2633
+ callback.callback(ret);
2634
+ } catch (JSONException e) {
2635
+ Map<String, Object> retError = new HashMap<>();
2636
+ retError.put("message", "JSON parse error: " + e.getMessage());
2637
+ retError.put("error", "parse_error");
1936
2638
  callback.callback(retError);
1937
- return;
1938
2639
  }
1939
-
1940
- Map<String, Object> ret = new HashMap<>();
1941
-
1942
- Iterator<String> keys = jsonResponse.keys();
1943
- while (keys.hasNext()) {
1944
- String key = keys.next();
1945
- if (jsonResponse.has(key)) {
1946
- ret.put(key, jsonResponse.get(key));
1947
- }
1948
- }
1949
- persistDefaultChannelFromResponse(ret.get("channel"), editor, defaultChannelKey);
1950
- logger.info("Channel get to \"" + ret);
1951
- callback.callback(ret);
1952
- } catch (JSONException e) {
1953
- Map<String, Object> retError = new HashMap<>();
1954
- retError.put("message", "JSON parse error: " + e.getMessage());
1955
- retError.put("error", "parse_error");
1956
- callback.callback(retError);
1957
2640
  }
1958
2641
  }
1959
- }
1960
- );
2642
+ );
1961
2643
  }
1962
2644
 
1963
2645
  void persistDefaultChannelFromResponse(final Object channel, final SharedPreferences.Editor editor, final String defaultChannelKey) {
@@ -1979,12 +2661,12 @@ public class CapgoUpdater {
1979
2661
  }
1980
2662
 
1981
2663
  public void listChannels(final Callback callback) {
1982
- // Check if rate limit was exceeded
1983
- if (rateLimitExceeded) {
1984
- logger.debug("Skipping listChannels due to rate limit (429). Requests will resume after app restart.");
2664
+ if (isRemoteBlocked()) {
2665
+ final RemoteBlockResult blocked = remoteBlockedClientError();
2666
+ logger.debug("Skipping listChannels due to remote block (" + blocked.error + ").");
1985
2667
  final Map<String, Object> retError = new HashMap<>();
1986
- retError.put("message", "Rate limit exceeded");
1987
- retError.put("error", "rate_limit_exceeded");
2668
+ retError.put("message", blocked.message);
2669
+ retError.put("error", blocked.error);
1988
2670
  callback.callback(retError);
1989
2671
  return;
1990
2672
  }
@@ -2030,83 +2712,85 @@ public class CapgoUpdater {
2030
2712
 
2031
2713
  Request request = new Request.Builder().url(urlBuilder.build()).get().build();
2032
2714
 
2033
- DownloadService.sharedClient.newCall(request).enqueue(
2034
- new okhttp3.Callback() {
2035
- @Override
2036
- public void onFailure(@NonNull Call call, @NonNull IOException e) {
2037
- Map<String, Object> retError = new HashMap<>();
2038
- retError.put("message", "Request failed: " + e.getMessage());
2039
- retError.put("error", "network_error");
2040
- callback.callback(retError);
2041
- }
2042
-
2043
- @Override
2044
- public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
2045
- try (ResponseBody responseBody = response.body()) {
2046
- // Check for 429 rate limit
2047
- if (checkAndHandleRateLimitResponse(response)) {
2048
- Map<String, Object> retError = new HashMap<>();
2049
- retError.put("message", "Rate limit exceeded");
2050
- retError.put("error", "rate_limit_exceeded");
2051
- callback.callback(retError);
2052
- return;
2053
- }
2715
+ DownloadService.sharedClient
2716
+ .newCall(request)
2717
+ .enqueue(
2718
+ new okhttp3.Callback() {
2719
+ @Override
2720
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
2721
+ Map<String, Object> retError = new HashMap<>();
2722
+ retError.put("message", "Request failed: " + e.getMessage());
2723
+ retError.put("error", "network_error");
2724
+ callback.callback(retError);
2725
+ }
2054
2726
 
2055
- if (!response.isSuccessful()) {
2056
- Map<String, Object> retError = new HashMap<>();
2057
- retError.put("message", "Server error: " + response.code());
2058
- retError.put("error", "response_error");
2059
- callback.callback(retError);
2060
- return;
2061
- }
2727
+ @Override
2728
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
2729
+ try (ResponseBody responseBody = response.body()) {
2730
+ final String data = responseBody != null ? responseBody.string() : "";
2731
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, data);
2732
+ if (rateLimit.blocked) {
2733
+ Map<String, Object> retError = new HashMap<>();
2734
+ retError.put("message", rateLimit.message);
2735
+ retError.put("error", rateLimit.error);
2736
+ callback.callback(retError);
2737
+ return;
2738
+ }
2062
2739
 
2063
- if (responseBody == null) {
2064
- Map<String, Object> retError = new HashMap<>();
2065
- retError.put("message", "Empty response body");
2066
- retError.put("error", "no_response_body");
2067
- callback.callback(retError);
2068
- return;
2069
- }
2070
- String data = responseBody.string();
2740
+ if (!response.isSuccessful()) {
2741
+ Map<String, Object> retError = new HashMap<>();
2742
+ retError.put("message", "Server error: " + response.code());
2743
+ retError.put("error", "response_error");
2744
+ callback.callback(retError);
2745
+ return;
2746
+ }
2071
2747
 
2072
- try {
2073
- Map<String, Object> ret = parseListChannelsResponse(data);
2748
+ if (data.isEmpty()) {
2749
+ Map<String, Object> retError = new HashMap<>();
2750
+ retError.put("message", "Empty response body");
2751
+ retError.put("error", "no_response_body");
2752
+ callback.callback(retError);
2753
+ return;
2754
+ }
2074
2755
 
2075
- logger.info("Channels listed successfully");
2076
- callback.callback(ret);
2077
- } catch (JSONException arrayException) {
2078
- // If not an array, try to parse as error object
2079
2756
  try {
2080
- JSONObject json = new JSONObject(data);
2081
- if (json.has("error")) {
2082
- Map<String, Object> retError = new HashMap<>();
2083
- retError.put("error", json.getString("error"));
2084
- if (json.has("message")) {
2085
- retError.put("message", json.getString("message"));
2086
- } else {
2087
- retError.put("message", "server did not provide a message");
2757
+ Map<String, Object> ret = parseListChannelsResponse(data);
2758
+
2759
+ logger.info("Channels listed successfully");
2760
+ callback.callback(ret);
2761
+ } catch (JSONException arrayException) {
2762
+ // If not an array, try to parse as error object
2763
+ try {
2764
+ JSONObject json = new JSONObject(data);
2765
+ if (json.has("error")) {
2766
+ Map<String, Object> retError = new HashMap<>();
2767
+ retError.put("error", json.getString("error"));
2768
+ if (json.has("message")) {
2769
+ retError.put("message", json.getString("message"));
2770
+ } else {
2771
+ retError.put("message", "server did not provide a message");
2772
+ }
2773
+ callback.callback(retError);
2774
+ return;
2088
2775
  }
2776
+ Map<String, Object> retError = new HashMap<>();
2777
+ retError.put("message", "Unexpected channels response format");
2778
+ retError.put("error", "parse_error");
2089
2779
  callback.callback(retError);
2090
2780
  return;
2781
+ } catch (JSONException objException) {
2782
+ // If neither array nor object, throw parse error
2783
+ arrayException.addSuppressed(objException);
2784
+ Map<String, Object> retError = new HashMap<>();
2785
+ retError.put("message", "JSON parse error: " + arrayException.getMessage());
2786
+ retError.put("error", "parse_error");
2787
+ callback.callback(retError);
2091
2788
  }
2092
- Map<String, Object> retError = new HashMap<>();
2093
- retError.put("message", "Unexpected channels response format");
2094
- retError.put("error", "parse_error");
2095
- callback.callback(retError);
2096
- return;
2097
- } catch (JSONException objException) {
2098
- // If neither array nor object, throw parse error
2099
- arrayException.addSuppressed(objException);
2100
- Map<String, Object> retError = new HashMap<>();
2101
- retError.put("message", "JSON parse error: " + arrayException.getMessage());
2102
- retError.put("error", "parse_error");
2103
- callback.callback(retError);
2104
2789
  }
2105
2790
  }
2106
2791
  }
2107
2792
  }
2108
- }
2109
- );
2793
+ );
2110
2794
  }
2111
2795
 
2112
2796
  static Map<String, Object> parseListChannelsResponse(final String data) throws JSONException {
@@ -2155,6 +2839,10 @@ public class CapgoUpdater {
2155
2839
  final Map<String, String> metadata,
2156
2840
  final Runnable onSent
2157
2841
  ) {
2842
+ if (statsStopped.get()) {
2843
+ return;
2844
+ }
2845
+
2158
2846
  if (this.previewSession) {
2159
2847
  if (logger != null) {
2160
2848
  logger.debug("Skipping sendStats during preview session.");
@@ -2162,12 +2850,6 @@ public class CapgoUpdater {
2162
2850
  return;
2163
2851
  }
2164
2852
 
2165
- // Check if rate limit was exceeded
2166
- if (rateLimitExceeded) {
2167
- logger.debug("Skipping sendStats due to rate limit (429). Stats will resume after app restart.");
2168
- return;
2169
- }
2170
-
2171
2853
  String statsUrl = this.statsUrl;
2172
2854
  if (statsUrl == null || statsUrl.isEmpty()) {
2173
2855
  return;
@@ -2184,16 +2866,190 @@ public class CapgoUpdater {
2184
2866
  json.put("metadata", new JSONObject(metadata));
2185
2867
  }
2186
2868
  } catch (JSONException e) {
2187
- logger.error("Error preparing stats");
2188
- logger.debug("JSONException: " + e.getMessage());
2869
+ if (logger != null) {
2870
+ logger.error("Error preparing stats");
2871
+ logger.debug("JSONException: " + e.getMessage());
2872
+ }
2189
2873
  return;
2190
2874
  }
2191
2875
 
2192
- statsQueue.add(new QueuedStatsEvent(json, onSent));
2876
+ synchronized (statsQueue) {
2877
+ if (statsStopped.get()) {
2878
+ return;
2879
+ }
2880
+ while (statsQueue.size() >= MAX_PENDING_STATS) {
2881
+ statsQueue.remove(0);
2882
+ }
2883
+ statsQueue.add(new QueuedStatsEvent(json, onSent));
2884
+ }
2193
2885
  ensureStatsTimerStarted();
2194
2886
  }
2195
2887
 
2888
+ public void restorePendingStats() {
2889
+ File file = pendingStatsFile();
2890
+ if (file == null) {
2891
+ return;
2892
+ }
2893
+ File backup = new File(file.getAbsolutePath() + ".bak");
2894
+ if (!file.exists() && backup.exists() && !backup.renameTo(file)) {
2895
+ if (logger != null) {
2896
+ logger.error("Failed to restore stats backup");
2897
+ }
2898
+ return;
2899
+ }
2900
+ if (!file.exists()) {
2901
+ return;
2902
+ }
2903
+ try {
2904
+ String raw = readFileUtf8(file);
2905
+ JSONArray arr = new JSONArray(raw);
2906
+ synchronized (statsQueue) {
2907
+ for (int i = 0; i < arr.length(); i++) {
2908
+ if (statsQueue.size() >= MAX_PENDING_STATS) {
2909
+ break;
2910
+ }
2911
+ statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null));
2912
+ }
2913
+ }
2914
+ if (backup.exists() && !backup.delete()) {
2915
+ if (logger != null) {
2916
+ logger.error("Failed to delete stats backup");
2917
+ }
2918
+ }
2919
+ if (!statsQueue.isEmpty()) {
2920
+ if (logger != null) {
2921
+ logger.info("Restored " + statsQueue.size() + " pending stats events");
2922
+ }
2923
+ ensureStatsTimerStarted();
2924
+ }
2925
+ } catch (Exception e) {
2926
+ if (logger != null) {
2927
+ logger.error("Failed to restore pending stats");
2928
+ logger.debug("Error: " + e.getMessage());
2929
+ }
2930
+ }
2931
+ }
2932
+
2933
+ int pendingStatsCount() {
2934
+ return statsQueue.size();
2935
+ }
2936
+
2937
+ public void persistPendingStats() {
2938
+ persistStatsQueue();
2939
+ }
2940
+
2941
+ private File pendingStatsFile() {
2942
+ final File dir = this.noBackupDir != null ? this.noBackupDir : this.documentsDir;
2943
+ if (dir == null) {
2944
+ return null;
2945
+ }
2946
+ return new File(dir, PENDING_STATS_FILE);
2947
+ }
2948
+
2949
+ private void persistStatsQueue() {
2950
+ persistStatsQueue(false);
2951
+ }
2952
+
2953
+ private void persistStatsQueue(final boolean force) {
2954
+ File file = pendingStatsFile();
2955
+ if (file == null) {
2956
+ return;
2957
+ }
2958
+ synchronized (pendingStatsPersistLock) {
2959
+ if (statsStopped.get() && !force) {
2960
+ return;
2961
+ }
2962
+ JSONArray arr = new JSONArray();
2963
+ synchronized (statsQueue) {
2964
+ final List<QueuedStatsEvent> combined = new ArrayList<>(statsInFlight.size() + statsQueue.size());
2965
+ combined.addAll(statsInFlight);
2966
+ combined.addAll(statsQueue);
2967
+ final int start = Math.max(0, combined.size() - MAX_PENDING_STATS);
2968
+ for (int i = start; i < combined.size(); i++) {
2969
+ arr.put(combined.get(i).event);
2970
+ }
2971
+ }
2972
+ try {
2973
+ if (arr.length() == 0) {
2974
+ writeFileAtomically(file, "[]".getBytes(StandardCharsets.UTF_8));
2975
+ File backup = new File(file.getAbsolutePath() + ".bak");
2976
+ if (backup.exists() && !backup.delete()) {
2977
+ if (logger != null) {
2978
+ logger.error("Failed to delete empty stats backup");
2979
+ }
2980
+ }
2981
+ return;
2982
+ }
2983
+ writeFileAtomically(file, arr.toString().getBytes(StandardCharsets.UTF_8));
2984
+ } catch (Exception e) {
2985
+ if (logger != null) {
2986
+ logger.error("Failed to persist stats queue");
2987
+ logger.debug("Error: " + e.getMessage());
2988
+ }
2989
+ }
2990
+ }
2991
+ }
2992
+
2993
+ private static String readFileUtf8(final File file) throws IOException {
2994
+ final long length = file.length();
2995
+ final byte[] buf = new byte[length > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) length];
2996
+ try (FileInputStream in = new FileInputStream(file)) {
2997
+ int offset = 0;
2998
+ while (offset < buf.length) {
2999
+ final int read = in.read(buf, offset, buf.length - offset);
3000
+ if (read < 0) {
3001
+ break;
3002
+ }
3003
+ offset += read;
3004
+ }
3005
+ return new String(buf, 0, offset, StandardCharsets.UTF_8);
3006
+ }
3007
+ }
3008
+
3009
+ private void writeFileAtomically(final File file, final byte[] bytes) throws IOException {
3010
+ final File tmp = new File(file.getAbsolutePath() + ".tmp");
3011
+ File backup = null;
3012
+ try {
3013
+ try (FileOutputStream out = new FileOutputStream(tmp)) {
3014
+ out.write(bytes);
3015
+ out.flush();
3016
+ }
3017
+ if (tmp.renameTo(file)) {
3018
+ return;
3019
+ }
3020
+ if (file.exists()) {
3021
+ backup = new File(file.getAbsolutePath() + ".bak");
3022
+ if (backup.exists() && !backup.delete()) {
3023
+ throw new IOException("Failed to replace " + file.getAbsolutePath());
3024
+ }
3025
+ if (!file.renameTo(backup)) {
3026
+ throw new IOException("Failed to replace " + file.getAbsolutePath());
3027
+ }
3028
+ }
3029
+ if (tmp.renameTo(file)) {
3030
+ if (backup != null && backup.exists() && !backup.delete()) {
3031
+ if (logger != null) {
3032
+ logger.error("Failed to delete stats backup");
3033
+ }
3034
+ }
3035
+ backup = null;
3036
+ return;
3037
+ }
3038
+ throw new IOException("Failed to persist " + file.getAbsolutePath());
3039
+ } finally {
3040
+ if (backup != null && !file.exists()) {
3041
+ backup.renameTo(file);
3042
+ }
3043
+ if (tmp.exists() && !tmp.delete()) {
3044
+ tmp.deleteOnExit();
3045
+ }
3046
+ }
3047
+ }
3048
+
2196
3049
  private synchronized void ensureStatsTimerStarted() {
3050
+ if (statsStopped.get()) {
3051
+ return;
3052
+ }
2197
3053
  if (statsFlushTask == null || statsFlushTask.isCancelled() || statsFlushTask.isDone()) {
2198
3054
  statsFlushTask = statsScheduler.scheduleAtFixedRate(
2199
3055
  this::flushStatsQueue,
@@ -2205,25 +3061,45 @@ public class CapgoUpdater {
2205
3061
  }
2206
3062
 
2207
3063
  private void flushStatsQueue() {
3064
+ if (statsStopped.get()) {
3065
+ return;
3066
+ }
2208
3067
  if (statsQueue.isEmpty()) {
2209
3068
  return;
2210
3069
  }
2211
3070
 
3071
+ // While Retry-After is active, keep stats queued and skip the network call.
3072
+ if (isRemoteBlocked()) {
3073
+ logger.debug("Deferring stats flush until Retry-After expires.");
3074
+ return;
3075
+ }
3076
+
2212
3077
  String statsUrl = this.statsUrl;
2213
3078
  if (statsUrl == null || statsUrl.isEmpty()) {
2214
- statsQueue.clear();
3079
+ synchronized (statsQueue) {
3080
+ statsQueue.clear();
3081
+ statsInFlight.clear();
3082
+ }
3083
+ persistStatsQueue();
3084
+ return;
3085
+ }
3086
+
3087
+ if (!statsFlushInFlight.compareAndSet(false, true)) {
2215
3088
  return;
2216
3089
  }
2217
3090
 
2218
- // Copy and clear the queue atomically using synchronized block
2219
- List<QueuedStatsEvent> eventsToSend;
3091
+ final List<QueuedStatsEvent> eventsToSend;
2220
3092
  synchronized (statsQueue) {
2221
3093
  if (statsQueue.isEmpty()) {
3094
+ statsFlushInFlight.set(false);
2222
3095
  return;
2223
3096
  }
2224
3097
  eventsToSend = new ArrayList<>(statsQueue);
2225
3098
  statsQueue.clear();
3099
+ statsInFlight.clear();
3100
+ statsInFlight.addAll(eventsToSend);
2226
3101
  }
3102
+ persistStatsQueue();
2227
3103
 
2228
3104
  JSONArray jsonArray = new JSONArray();
2229
3105
  for (QueuedStatsEvent queuedEvent : eventsToSend) {
@@ -2236,34 +3112,97 @@ public class CapgoUpdater {
2236
3112
  .build();
2237
3113
 
2238
3114
  final int eventCount = eventsToSend.size();
2239
- DownloadService.sharedClient.newCall(request).enqueue(
2240
- new okhttp3.Callback() {
2241
- @Override
2242
- public void onFailure(@NonNull Call call, @NonNull IOException e) {
2243
- logger.error("Failed to send stats batch");
2244
- logger.debug("Error: " + e.getMessage());
2245
- }
2246
-
2247
- @Override
2248
- public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
2249
- try (ResponseBody responseBody = response.body()) {
2250
- // Check for 429 rate limit
2251
- if (checkAndHandleRateLimitResponse(response)) {
3115
+ DownloadService.sharedClient
3116
+ .newCall(request)
3117
+ .enqueue(
3118
+ new okhttp3.Callback() {
3119
+ @Override
3120
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
3121
+ if (abandonStoppedStatsFlush()) {
2252
3122
  return;
2253
3123
  }
3124
+ requeueStatsEvents(eventsToSend);
3125
+ if (logger != null) {
3126
+ logger.error("Failed to send stats batch");
3127
+ logger.debug("Error: " + e.getMessage());
3128
+ }
3129
+ statsFlushInFlight.set(false);
3130
+ }
3131
+
3132
+ @Override
3133
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
3134
+ try (ResponseBody responseBody = response.body()) {
3135
+ if (abandonStoppedStatsFlush()) {
3136
+ return;
3137
+ }
3138
+ final String responseData = responseBody != null ? responseBody.string() : "";
3139
+ if (checkAndHandleRateLimitResponse(response, responseData).blocked) {
3140
+ requeueStatsEvents(eventsToSend);
3141
+ return;
3142
+ }
2254
3143
 
2255
- if (response.isSuccessful()) {
2256
- logger.info("Stats batch sent successfully");
2257
- logger.debug("Sent " + eventCount + " events");
2258
- runStatsCallbacks(eventsToSend);
2259
- } else {
2260
- logger.error("Error sending stats batch");
2261
- logger.debug("Response code: " + response.code());
3144
+ if (response.isSuccessful()) {
3145
+ synchronized (statsQueue) {
3146
+ statsInFlight.clear();
3147
+ }
3148
+ persistStatsQueue();
3149
+ if (logger != null) {
3150
+ logger.info("Stats batch sent successfully");
3151
+ logger.debug("Sent " + eventCount + " events");
3152
+ }
3153
+ runStatsCallbacks(eventsToSend);
3154
+ } else if (isTransientStatsFailure(response.code())) {
3155
+ requeueStatsEvents(eventsToSend);
3156
+ if (logger != null) {
3157
+ logger.error("Error sending stats batch");
3158
+ logger.debug("Retrying later, response code: " + response.code());
3159
+ }
3160
+ } else {
3161
+ synchronized (statsQueue) {
3162
+ statsInFlight.clear();
3163
+ }
3164
+ persistStatsQueue();
3165
+ if (logger != null) {
3166
+ logger.error("Dropping stats batch after permanent error");
3167
+ logger.debug("Response code: " + response.code());
3168
+ }
3169
+ }
3170
+ } finally {
3171
+ statsFlushInFlight.set(false);
2262
3172
  }
2263
3173
  }
2264
3174
  }
3175
+ );
3176
+ }
3177
+
3178
+ private boolean abandonStoppedStatsFlush() {
3179
+ if (!statsStopped.get()) {
3180
+ return false;
3181
+ }
3182
+ statsFlushInFlight.set(false);
3183
+ return true;
3184
+ }
3185
+
3186
+ /**
3187
+ * Only 429, request timeout and 5xx are worth retrying; other 4xx are permanent rejections.
3188
+ */
3189
+ private static boolean isTransientStatsFailure(final int statusCode) {
3190
+ return statusCode == 429 || statusCode == 408 || statusCode >= 500;
3191
+ }
3192
+
3193
+ private void requeueStatsEvents(final List<QueuedStatsEvent> events) {
3194
+ if (statsStopped.get() || events == null || events.isEmpty()) {
3195
+ return;
3196
+ }
3197
+ synchronized (statsQueue) {
3198
+ statsInFlight.clear();
3199
+ statsQueue.addAll(0, events);
3200
+ while (statsQueue.size() > MAX_PENDING_STATS) {
3201
+ statsQueue.remove(0);
2265
3202
  }
2266
- );
3203
+ }
3204
+ persistStatsQueue();
3205
+ ensureStatsTimerStarted();
2267
3206
  }
2268
3207
 
2269
3208
  private void runStatsCallbacks(final List<QueuedStatsEvent> sentEvents) {
@@ -2333,10 +3272,10 @@ public class CapgoUpdater {
2333
3272
  this.saveBundleInfo(id, null);
2334
3273
  }
2335
3274
 
2336
- public void saveBundleInfo(final String id, final BundleInfo info) {
3275
+ public boolean saveBundleInfo(final String id, final BundleInfo info) {
2337
3276
  if (id == null || (info != null && (info.isBuiltin() || info.isUnknown()))) {
2338
3277
  logger.debug("Not saving info for bundle: [" + id + "] " + info);
2339
- return;
3278
+ return false;
2340
3279
  }
2341
3280
 
2342
3281
  if (info == null) {
@@ -2348,7 +3287,7 @@ public class CapgoUpdater {
2348
3287
  logger.debug("Storing info for bundle [" + id + "] " + update.getClass().getName() + " -> " + jsonString);
2349
3288
  this.editor.putString(id + INFO_SUFFIX, jsonString);
2350
3289
  }
2351
- this.editor.commit();
3290
+ return this.editor.commit();
2352
3291
  }
2353
3292
 
2354
3293
  private void setBundleStatus(final String id, final BundleStatus status) {
@@ -2453,14 +3392,15 @@ public class CapgoUpdater {
2453
3392
  * Should be called when the plugin is destroyed to prevent resource leaks.
2454
3393
  */
2455
3394
  public void shutdown() {
3395
+ statsStopped.set(true);
2456
3396
  // Cancel the scheduled task
2457
3397
  if (statsFlushTask != null) {
2458
3398
  statsFlushTask.cancel(false);
2459
3399
  statsFlushTask = null;
2460
3400
  }
2461
3401
 
2462
- // Flush any remaining stats before shutdown
2463
- flushStatsQueue();
3402
+ // Write once, then ignore later callbacks so they cannot delete a newer instance's file.
3403
+ persistStatsQueue(true);
2464
3404
 
2465
3405
  // Shutdown the scheduler
2466
3406
  statsScheduler.shutdown();