@capgo/capacitor-updater 9.0.1 → 9.0.4

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 (28) hide show
  1. package/README.md +106 -81
  2. package/android/build.gradle +1 -3
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +521 -21
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +675 -34
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +10 -2
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  9. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  11. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +5 -2
  12. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  13. package/dist/docs.json +13 -13
  14. package/dist/esm/definitions.d.ts +57 -23
  15. package/dist/esm/definitions.js.map +1 -1
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  17. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  19. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  20. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2718 -77
  22. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  23. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  24. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  25. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +259 -119
  26. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  27. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  28. package/package.json +2 -2
@@ -60,7 +60,6 @@ import java.util.concurrent.ScheduledFuture;
60
60
  import java.util.concurrent.ThreadPoolExecutor;
61
61
  import java.util.concurrent.TimeUnit;
62
62
  import java.util.concurrent.atomic.AtomicBoolean;
63
- import java.util.concurrent.atomic.AtomicReference;
64
63
  import java.util.zip.ZipEntry;
65
64
  import java.util.zip.ZipInputStream;
66
65
  import okhttp3.*;
@@ -89,6 +88,8 @@ public class CapgoUpdater {
89
88
  private static final String TEMP_UNZIP_PREFIX = "capgo_unzip_";
90
89
  static final String MANIFEST_STAGING_PREFIX = "capgo_manifest_";
91
90
  static final String MANIFEST_DEST_SUFFIX = "_manifest_dest";
91
+ /** ZIP archive name (under documentsDir) a background download renames its temp file to before unzip. */
92
+ static final String ZIP_DEST_SUFFIX = "_zip_dest";
92
93
  private static final String LEGACY_MANIFEST_STAGING_FOLDER_PATTERN = "^[0-9A-Za-z]{10}$";
93
94
  private static final long DELETE_PACE_MS = 75L;
94
95
  private static final Object deleteLock = new Object();
@@ -151,7 +152,7 @@ public class CapgoUpdater {
151
152
  public int timeout = 20000;
152
153
  /** Refuse bundles whose version is below the native app version (versionBuild). Config builtinMinimum, default true. */
153
154
  public volatile boolean builtinMinimum = true;
154
- private final AtomicReference<String> lastVersionFloorRejection = new AtomicReference<>();
155
+ private String lastVersionFloorRejection;
155
156
  /**
156
157
  * Require https for every URL the updater downloads from. Config httpsOnly, default true. Mirrors
157
158
  * DownloadService.httpsOnly (the OkHttp interceptor); this field gates URLs before any network IO.
@@ -466,6 +467,451 @@ public class CapgoUpdater {
466
467
  return !observedByThisProcess;
467
468
  }
468
469
 
470
+ /** Retries for interrupted downloads only. Checksum/signature blocks use {@link #markIntegrityBlockedVersion}. */
471
+ public static final int MAX_INCOMPLETE_DOWNLOAD_RETRIES = 3;
472
+ private static final String INCOMPLETE_RETRY_COUNT_PREFIX = "capgo_incomplete_retry_count_";
473
+ private static final String INCOMPLETE_FAIL_REPORTED_PREFIX = "capgo_incomplete_fail_reported_";
474
+ private static final String INTEGRITY_BLOCKED_VERSION_PREFIX = "capgo_integrity_blocked_version_";
475
+ private static final String INTERRUPTED_DOWNLOAD_BUNDLE_PREFIX = "capgo_interrupted_download_bundle_";
476
+ private static final String INCOMPLETE_RETRY_RESERVATION_PREFIX = "capgo_incomplete_retry_reserved_";
477
+
478
+ /** Preview sessions keep their own retry budget, reservation and integrity block (same scope as the block). */
479
+ private String retryScopedVersion(final String version) {
480
+ return (Boolean.TRUE.equals(this.previewSession) ? "preview:" : "") + version;
481
+ }
482
+
483
+ int incompleteDownloadRetryCount(final String version) {
484
+ if (this.prefs == null || version == null || version.isEmpty()) {
485
+ return 0;
486
+ }
487
+ return Math.max(0, this.prefs.getInt(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version), 0));
488
+ }
489
+
490
+ void incrementIncompleteDownloadRetryCount(final String version) {
491
+ if (this.editor == null || version == null || version.isEmpty()) {
492
+ return;
493
+ }
494
+ final int next = this.incompleteDownloadRetryCount(version) + 1;
495
+ this.editor.putInt(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version), next);
496
+ this.editor.commit();
497
+ }
498
+
499
+ void resetIncompleteDownloadRetryCount(final String version) {
500
+ if (this.editor == null || version == null || version.isEmpty()) {
501
+ return;
502
+ }
503
+ this.editor.remove(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version));
504
+ this.editor.remove(INCOMPLETE_RETRY_RESERVATION_PREFIX + this.retryScopedVersion(version));
505
+ this.editor.remove(RETRY_CHARGE_PENDING_PREFIX + this.retryScopedVersion(version));
506
+ this.editor.remove(this.integrityBlockedVersionKey(version));
507
+ this.editor.commit();
508
+ }
509
+
510
+ /**
511
+ * Persist that the next download of {@code version} replaces a failed or interrupted attempt, before the
512
+ * old record is deleted. The reservation survives process death, so the replacement is still charged.
513
+ */
514
+ void reserveIncompleteDownloadRetry(final String version) {
515
+ if (this.editor == null || version == null || version.isEmpty()) {
516
+ return;
517
+ }
518
+ this.editor.putBoolean(INCOMPLETE_RETRY_RESERVATION_PREFIX + this.retryScopedVersion(version), true);
519
+ this.editor.commit();
520
+ }
521
+
522
+ boolean hasIncompleteDownloadRetryReservation(final String version) {
523
+ return (
524
+ this.prefs != null &&
525
+ version != null &&
526
+ !version.isEmpty() &&
527
+ this.prefs.getBoolean(INCOMPLETE_RETRY_RESERVATION_PREFIX + this.retryScopedVersion(version), false)
528
+ );
529
+ }
530
+
531
+ /**
532
+ * Charge one retry slot before a replacement download starts. Returns whether a slot was charged so the
533
+ * caller can settle it with {@link #settleIncompleteDownloadRetry} once it knows whether work started.
534
+ */
535
+ static final int RETRY_NOT_CHARGED = 0;
536
+ static final int RETRY_CHARGED = 1;
537
+ /** The retry cap was reached (for example by a concurrent charge): the replacement must not start. */
538
+ static final int RETRY_REFUSED = 2;
539
+ private static final Object RETRY_ACCOUNTING_LOCK = new Object();
540
+ /**
541
+ * Pending charge of a version: "" until the charging thread enqueues its attempt, then that attempt's bundle id.
542
+ * Only the worker of that attempt can retire (or refund) it, never another same-version attempt.
543
+ */
544
+ private static final String RETRY_CHARGE_PENDING_PREFIX = "capgo_incomplete_retry_charge_attempt_";
545
+ /** Scoped version charged on this thread and not yet bound to the attempt this thread enqueues. */
546
+ private static final ThreadLocal<String> CHARGE_AWAITING_ATTEMPT = new ThreadLocal<>();
547
+
548
+ /**
549
+ * Same minimum free-space admission {@link DownloadService} applies before a ZIP request (twice the 50MB estimate),
550
+ * so a retry is not charged for a worker that would refuse to start.
551
+ */
552
+ boolean hasDiskSpaceForZipDownload() {
553
+ // getUsableSpace() is 0 for a missing path: unknown space is admitted and the worker still checks it.
554
+ if (this.documentsDir == null || !this.documentsDir.exists()) {
555
+ return true;
556
+ }
557
+ return this.documentsDir.getUsableSpace() >= DownloadService.MIN_ZIP_FREE_BYTES;
558
+ }
559
+
560
+ int chargeIncompleteDownloadRetry(final String version, final boolean admittedRetry) {
561
+ if (version == null || version.isEmpty()) {
562
+ return RETRY_NOT_CHARGED;
563
+ }
564
+ synchronized (RETRY_ACCOUNTING_LOCK) {
565
+ if (!admittedRetry && !this.hasIncompleteDownloadRetryReservation(version)) {
566
+ return RETRY_NOT_CHARGED;
567
+ }
568
+ // Check and charge in one step so concurrent plugin/headless checks cannot exceed the cap.
569
+ if (this.incompleteDownloadRetryCount(version) >= MAX_INCOMPLETE_DOWNLOAD_RETRIES) {
570
+ return RETRY_REFUSED;
571
+ }
572
+ this.incrementIncompleteDownloadRetryCount(version);
573
+ // The charge consumes the reservation; settling a not-started attempt restores it.
574
+ if (this.editor != null) {
575
+ this.editor.remove(INCOMPLETE_RETRY_RESERVATION_PREFIX + this.retryScopedVersion(version));
576
+ this.editor.commit();
577
+ }
578
+ // Remember the charge until the attempt's worker reports: a confirmed pre-request refusal refunds it once.
579
+ // It is bound to the attempt this thread enqueues next (bindChargedRetryAttempt).
580
+ if (this.editor != null) {
581
+ this.editor.putString(RETRY_CHARGE_PENDING_PREFIX + this.retryScopedVersion(version), "");
582
+ this.editor.commit();
583
+ }
584
+ CHARGE_AWAITING_ATTEMPT.set(this.retryScopedVersion(version));
585
+ return RETRY_CHARGED;
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Ends the pending charge of the version's attempt once its worker reported. {@code refund} is true only for a
591
+ * confirmed pre-request refusal (no byte requested): the slot is returned and the reservation restored, once.
592
+ * Any other outcome keeps the charge.
593
+ */
594
+ void retireChargedRetryAttempt(final String version, final String attemptId, final boolean refund) {
595
+ if (this.editor == null || this.prefs == null || version == null || version.isEmpty() || attemptId == null) {
596
+ return;
597
+ }
598
+ synchronized (RETRY_ACCOUNTING_LOCK) {
599
+ final String pendingKey = RETRY_CHARGE_PENDING_PREFIX + this.retryScopedVersion(version);
600
+ if (attemptId.isEmpty() || !attemptId.equals(this.pendingRetryChargeAttempt(version))) {
601
+ // Not the charged attempt (another same-version download): its outcome does not settle the charge.
602
+ return;
603
+ }
604
+ this.editor.remove(pendingKey);
605
+ if (refund) {
606
+ final int refunded = Math.max(0, this.incompleteDownloadRetryCount(version) - 1);
607
+ if (refunded == 0) {
608
+ this.editor.remove(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version));
609
+ } else {
610
+ this.editor.putInt(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version), refunded);
611
+ }
612
+ this.editor.putBoolean(INCOMPLETE_RETRY_RESERVATION_PREFIX + this.retryScopedVersion(version), true);
613
+ }
614
+ this.editor.commit();
615
+ }
616
+ }
617
+
618
+ boolean hasPendingRetryCharge(final String version) {
619
+ return this.pendingRetryChargeAttempt(version) != null;
620
+ }
621
+
622
+ /** The attempt id bound to the version's pending charge ("" while unbound), or null when none is pending. */
623
+ String pendingRetryChargeAttempt(final String version) {
624
+ if (this.prefs == null || version == null || version.isEmpty()) {
625
+ return null;
626
+ }
627
+ try {
628
+ return this.prefs.getString(RETRY_CHARGE_PENDING_PREFIX + this.retryScopedVersion(version), null);
629
+ } catch (final ClassCastException e) {
630
+ return null;
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Binds the charge taken on this thread to the attempt it is enqueuing, before the attempt's observer exists.
636
+ * Attempts enqueued from other threads (for example a manual download of the same version) stay unbound.
637
+ */
638
+ void bindChargedRetryAttempt(final String version, final String attemptId) {
639
+ final String awaiting = CHARGE_AWAITING_ATTEMPT.get();
640
+ if (awaiting == null || this.editor == null || version == null || !awaiting.equals(this.retryScopedVersion(version))) {
641
+ return;
642
+ }
643
+ CHARGE_AWAITING_ATTEMPT.remove();
644
+ synchronized (RETRY_ACCOUNTING_LOCK) {
645
+ if (this.pendingRetryChargeAttempt(version) != null) {
646
+ this.editor.putString(RETRY_CHARGE_PENDING_PREFIX + this.retryScopedVersion(version), attemptId);
647
+ this.editor.commit();
648
+ }
649
+ }
650
+ }
651
+
652
+ /**
653
+ * A started replacement keeps its charge and consumes the reservation. A download that did not start
654
+ * (refused, or an existing bundle was reused) is refunded; only a reuse clears the reservation.
655
+ */
656
+ void settleIncompleteDownloadRetry(final String version, final boolean charged, final boolean started, final boolean reused) {
657
+ if (charged) {
658
+ // Whatever happened, this thread's charge no longer waits for an attempt to bind to.
659
+ CHARGE_AWAITING_ATTEMPT.remove();
660
+ }
661
+ if (this.editor == null || version == null || version.isEmpty() || !charged) {
662
+ return;
663
+ }
664
+ synchronized (RETRY_ACCOUNTING_LOCK) {
665
+ this.settleChargedRetry(version, started, reused);
666
+ }
667
+ }
668
+
669
+ private void settleChargedRetry(final String version, final boolean started, final boolean reused) {
670
+ if (!started || reused) {
671
+ // Nothing was enqueued: no worker will report for this charge.
672
+ this.editor.remove(RETRY_CHARGE_PENDING_PREFIX + this.retryScopedVersion(version));
673
+ }
674
+ if (!started) {
675
+ final int refunded = Math.max(0, this.incompleteDownloadRetryCount(version) - 1);
676
+ if (refunded == 0) {
677
+ this.editor.remove(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version));
678
+ } else {
679
+ this.editor.putInt(INCOMPLETE_RETRY_COUNT_PREFIX + this.retryScopedVersion(version), refunded);
680
+ }
681
+ if (!reused) {
682
+ // Refused before starting: the replacement is still owed, so the next start is charged again.
683
+ this.editor.putBoolean(INCOMPLETE_RETRY_RESERVATION_PREFIX + this.retryScopedVersion(version), true);
684
+ }
685
+ }
686
+ this.editor.commit();
687
+ }
688
+
689
+ private String integrityBlockedVersionKey(final String version) {
690
+ if (version == null || version.isEmpty()) {
691
+ return INTEGRITY_BLOCKED_VERSION_PREFIX;
692
+ }
693
+ return INTEGRITY_BLOCKED_VERSION_PREFIX + (Boolean.TRUE.equals(this.previewSession) ? "preview:" : "") + version;
694
+ }
695
+
696
+ void markIntegrityBlockedVersion(final String version) {
697
+ if (this.editor == null || version == null || version.isEmpty()) {
698
+ return;
699
+ }
700
+ this.editor.putBoolean(this.integrityBlockedVersionKey(version), true);
701
+ this.editor.commit();
702
+ }
703
+
704
+ boolean isIntegrityBlockedVersion(final String version) {
705
+ return (
706
+ this.prefs != null &&
707
+ version != null &&
708
+ !version.isEmpty() &&
709
+ this.prefs.getBoolean(this.integrityBlockedVersionKey(version), false)
710
+ );
711
+ }
712
+
713
+ void markInterruptedDownloadBundle(final String bundleId) {
714
+ if (this.editor == null || bundleId == null || bundleId.isEmpty()) {
715
+ return;
716
+ }
717
+ this.editor.putBoolean(INTERRUPTED_DOWNLOAD_BUNDLE_PREFIX + bundleId, true);
718
+ this.editor.commit();
719
+ }
720
+
721
+ boolean isInterruptedDownloadBundle(final String bundleId) {
722
+ return (
723
+ this.prefs != null &&
724
+ bundleId != null &&
725
+ !bundleId.isEmpty() &&
726
+ this.prefs.getBoolean(INTERRUPTED_DOWNLOAD_BUNDLE_PREFIX + bundleId, false)
727
+ );
728
+ }
729
+
730
+ void clearInterruptedDownloadBundle(final String bundleId) {
731
+ if (this.editor == null || bundleId == null || bundleId.isEmpty()) {
732
+ return;
733
+ }
734
+ this.editor.remove(INTERRUPTED_DOWNLOAD_BUNDLE_PREFIX + bundleId);
735
+ this.editor.commit();
736
+ }
737
+
738
+ boolean isVersionDownloadObservedInThisProcess(final String version) {
739
+ return version != null && !version.isEmpty() && this.observedDownloadVersions.contains(version);
740
+ }
741
+
742
+ boolean isVersionDownloadActive(final String version) {
743
+ return (
744
+ this.isVersionDownloadObservedInThisProcess(version) ||
745
+ (this.context() != null && DownloadWorkerManager.isVersionDownloading(this.context(), version))
746
+ );
747
+ }
748
+
749
+ boolean hasPendingDownloadFinalizationForBundleId(final String id) {
750
+ if (id == null || id.isEmpty()) {
751
+ return false;
752
+ }
753
+ synchronized (this.deleteLock) {
754
+ try {
755
+ final File bundleDir = this.getBundleDirectory(id);
756
+ final Set<DownloadFinalization> pending = downloadFinalizations.get(bundleDir);
757
+ return pending != null && !pending.isEmpty();
758
+ } catch (final IOException e) {
759
+ return false;
760
+ }
761
+ }
762
+ }
763
+
764
+ /**
765
+ * True when a stored bundle for the offered version must be removed and downloaded again.
766
+ * Integrity blocks retries only while a failed bundle is still on disk.
767
+ */
768
+ public static boolean shouldRetryDownloadForExistingBundle(
769
+ final BundleInfo bundle,
770
+ final boolean bundleOnDisk,
771
+ final int incompleteRetryCount,
772
+ final boolean integrityBlocked,
773
+ final boolean interruptedDownloadFailure,
774
+ final boolean isCurrentBundle,
775
+ final boolean isQueuedNext
776
+ ) {
777
+ if (incompleteRetryCount >= MAX_INCOMPLETE_DOWNLOAD_RETRIES) {
778
+ return false;
779
+ }
780
+ if (bundle == null) {
781
+ return true;
782
+ }
783
+ // An integrity block (left by an earlier attempt) stops on-disk rows from being reused, but a later attempt
784
+ // that was interrupted is still a retry candidate: its files are deleted and the replacement is verified again.
785
+ if (integrityBlocked && !(bundle.isErrorStatus() && (!bundleOnDisk || interruptedDownloadFailure))) {
786
+ return false;
787
+ }
788
+ if (bundle.isDeleted() || bundle.isDeleting() || BundleStatus.DOWNLOADING == bundle.getStatus()) {
789
+ return incompleteRetryCount < MAX_INCOMPLETE_DOWNLOAD_RETRIES;
790
+ }
791
+ if (bundle.isErrorStatus()) {
792
+ if (!bundleOnDisk) {
793
+ return incompleteRetryCount < MAX_INCOMPLETE_DOWNLOAD_RETRIES;
794
+ }
795
+ return interruptedDownloadFailure;
796
+ }
797
+ if (BundleStatus.SUCCESS == bundle.getStatus()) {
798
+ if (isCurrentBundle || bundleOnDisk) {
799
+ return false;
800
+ }
801
+ return incompleteRetryCount < MAX_INCOMPLETE_DOWNLOAD_RETRIES;
802
+ }
803
+ if (BundleStatus.PENDING == bundle.getStatus()) {
804
+ if (bundleOnDisk) {
805
+ return false;
806
+ }
807
+ return true;
808
+ }
809
+ return false;
810
+ }
811
+
812
+ boolean isBundleOnDisk(final String id) {
813
+ return id != null && !id.isEmpty() && this.bundleExists(id);
814
+ }
815
+
816
+ /**
817
+ * Interrupted {@link BundleStatus#DOWNLOADING} records (e.g. process kill) emit {@code download_fail}
818
+ * once on the next launch, then move to ERROR so a later update check can retry.
819
+ */
820
+ public void reconcileInterruptedDownloadsOnLaunch() {
821
+ for (final BundleInfo info : this.list(true)) {
822
+ if (info == null || info.isBuiltin() || info.getId() == null || info.getId().isEmpty()) {
823
+ continue;
824
+ }
825
+ if (info.getId().equals(this.getCurrentBundleId())) {
826
+ continue;
827
+ }
828
+ final String version = info.getVersionName();
829
+ if (this.isVersionDownloadObservedInThisProcess(version)) {
830
+ continue;
831
+ }
832
+ if (info.getStatus() == BundleStatus.ERROR) {
833
+ // Recoverable capped cleanup: a previous launch may have died after the ERROR write, or failed to
834
+ // remove the directory. Retry on every launch until the files are gone.
835
+ this.removeCappedInterruptedBundleFiles(info.getId(), version);
836
+ continue;
837
+ }
838
+ if (info.getStatus() != BundleStatus.DOWNLOADING) {
839
+ continue;
840
+ }
841
+ final String reportedKey = INCOMPLETE_FAIL_REPORTED_PREFIX + info.getId();
842
+ boolean reportFailure = false;
843
+ // A headless download registers its finalization under deleteLock, possibly after a lock-free check.
844
+ // Claim the stale row (and its one download_fail report) under that lock before touching its staging,
845
+ // worker or row; the report is sent outside the lock.
846
+ synchronized (this.deleteLock) {
847
+ final BundleInfo currentInfo = this.getBundleInfo(info.getId());
848
+ if (
849
+ this.hasPendingDownloadFinalizationForBundleId(info.getId()) ||
850
+ this.isVersionDownloadObservedInThisProcess(version) ||
851
+ currentInfo == null ||
852
+ currentInfo.isDeleted() ||
853
+ currentInfo.isDeleting() ||
854
+ BundleStatus.DOWNLOADING != currentInfo.getStatus()
855
+ ) {
856
+ continue;
857
+ }
858
+ this.cleanupManifestStagingAfterDownloadCancelled(info.getId());
859
+ if (this.context() != null) {
860
+ // Cancel only the stale bundle's unique work, never a newer same-version download.
861
+ DownloadWorkerManager.cancelBundleDownload(this.context(), info.getId(), version);
862
+ }
863
+ this.markInterruptedDownloadBundle(info.getId());
864
+ this.saveBundleInfo(info.getId(), info.setStatus(BundleStatus.ERROR));
865
+ this.removeCappedInterruptedBundleFilesLocked(info.getId(), version);
866
+ if (this.prefs != null && !this.prefs.getBoolean(reportedKey, false)) {
867
+ reportFailure = true;
868
+ if (this.editor != null) {
869
+ this.editor.putBoolean(reportedKey, true);
870
+ this.editor.commit();
871
+ }
872
+ }
873
+ }
874
+ if (reportFailure) {
875
+ this.sendStats("download_fail", version);
876
+ }
877
+ }
878
+ this.sweepAbandonedZips();
879
+ }
880
+
881
+ private void removeCappedInterruptedBundleFiles(final String id, final String version) {
882
+ synchronized (this.deleteLock) {
883
+ final BundleInfo currentInfo = this.getBundleInfo(id);
884
+ if (
885
+ this.hasPendingDownloadFinalizationForBundleId(id) || currentInfo == null || currentInfo.getStatus() != BundleStatus.ERROR
886
+ ) {
887
+ return;
888
+ }
889
+ this.removeCappedInterruptedBundleFilesLocked(id, version);
890
+ }
891
+ }
892
+
893
+ /**
894
+ * No retry will replace a capped interrupted bundle and cleanup protects every non-deleted row: drop its
895
+ * abandoned files (sandboxed bundle dir). The row and marker stay for retry accounting. Caller holds deleteLock.
896
+ */
897
+ private void removeCappedInterruptedBundleFilesLocked(final String id, final String version) {
898
+ if (!this.isInterruptedDownloadBundle(id) || this.incompleteDownloadRetryCount(version) < MAX_INCOMPLETE_DOWNLOAD_RETRIES) {
899
+ return;
900
+ }
901
+ try {
902
+ final File bundleDir = this.getBundleDirectory(id);
903
+ if (!bundleDir.exists()) {
904
+ return;
905
+ }
906
+ this.safeDelete(bundleDir);
907
+ if (bundleDir.exists()) {
908
+ logger.error("Failed to remove abandoned bundle directory, will retry next launch: " + id);
909
+ }
910
+ } catch (final IOException e) {
911
+ logger.error("Failed to remove abandoned bundle directory: " + id);
912
+ }
913
+ }
914
+
469
915
  static boolean shouldReleaseLaunchWhileRetrying(
470
916
  final boolean awaitedByCaller,
471
917
  final boolean setNext,
@@ -552,9 +998,50 @@ public class CapgoUpdater {
552
998
  return;
553
999
  }
554
1000
  this.editor.remove(bundleId + MANIFEST_DEST_SUFFIX);
1001
+ // The renamed ZIP is only temporary: retire its record once the archive is confirmed gone and the attempt's
1002
+ // worker has finished (a cancelled worker may still rename it), otherwise keep it for the launch sweep.
1003
+ if (this.removeAbandonedZip(bundleId) && !this.isBundleWorkUnfinished(bundleId)) {
1004
+ this.editor.remove(bundleId + ZIP_DEST_SUFFIX);
1005
+ }
1006
+ this.editor.commit();
1007
+ }
1008
+
1009
+ void saveZipDest(final String bundleId, final String dest) {
1010
+ if (this.editor == null || bundleId == null || dest == null || dest.isEmpty()) {
1011
+ return;
1012
+ }
1013
+ this.editor.putString(bundleId + ZIP_DEST_SUFFIX, dest);
555
1014
  this.editor.commit();
556
1015
  }
557
1016
 
1017
+ /**
1018
+ * Removes the renamed ZIP an abandoned attempt may have left at {@code documentsDir/<dest>} (sandboxed).
1019
+ * Returns false while the archive still exists, so the caller keeps the cleanup record.
1020
+ */
1021
+ private boolean removeAbandonedZip(final String bundleId) {
1022
+ String zipDest = null;
1023
+ try {
1024
+ zipDest = this.prefs != null ? this.prefs.getString(bundleId + ZIP_DEST_SUFFIX, null) : null;
1025
+ } catch (final ClassCastException e) {
1026
+ // Not an archive record: leave the preference alone.
1027
+ logger.warn("Ignoring non-string abandoned download record");
1028
+ return false;
1029
+ }
1030
+ if (zipDest == null || zipDest.isEmpty() || this.documentsDir == null) {
1031
+ return true;
1032
+ }
1033
+ try {
1034
+ final File archive = resolvePathInsideDirectory(this.documentsDir, zipDest);
1035
+ if (archive.isFile()) {
1036
+ this.safeDelete(archive);
1037
+ }
1038
+ return !archive.exists();
1039
+ } catch (final IOException e) {
1040
+ logger.warn("Ignoring invalid abandoned download destination");
1041
+ return true;
1042
+ }
1043
+ }
1044
+
558
1045
  void cleanupManifestStagingAfterDownloadFailed(final String bundleId, final String failedDest, final boolean failedManifest) {
559
1046
  if (failedManifest) {
560
1047
  this.deleteManifestStagingFolder(failedDest);
@@ -568,6 +1055,44 @@ public class CapgoUpdater {
568
1055
  this.clearManifestStagingDest(bundleId);
569
1056
  }
570
1057
 
1058
+ private boolean isBundleWorkUnfinished(final String bundleId) {
1059
+ final Context context = this.context();
1060
+ return context != null && DownloadWorkerManager.isBundleWorkUnfinished(context, bundleId);
1061
+ }
1062
+
1063
+ static boolean isZipDestKey(final String key) {
1064
+ return key != null && key.matches("[A-Za-z0-9]{10}" + ZIP_DEST_SUFFIX);
1065
+ }
1066
+
1067
+ /** Launch sweep: retries removal of every recorded ZIP whose attempt is no longer downloading. */
1068
+ private void sweepAbandonedZips() {
1069
+ if (this.prefs == null || this.editor == null) {
1070
+ return;
1071
+ }
1072
+ for (final String key : new ArrayList<>(this.prefs.getAll().keySet())) {
1073
+ if (!isZipDestKey(key)) {
1074
+ // Only keys written by saveZipDest (ten-character bundle id + suffix): other preferences such as
1075
+ // retry counters of a version named "x_zip_dest" share the suffix but are not archive records.
1076
+ continue;
1077
+ }
1078
+ final String id = key.substring(0, key.length() - ZIP_DEST_SUFFIX.length());
1079
+ synchronized (this.deleteLock) {
1080
+ final BundleInfo info = this.getBundleInfo(id);
1081
+ if (
1082
+ this.hasPendingDownloadFinalizationForBundleId(id) ||
1083
+ (info != null && BundleStatus.DOWNLOADING == info.getStatus()) ||
1084
+ (info != null && this.isVersionDownloadObservedInThisProcess(info.getVersionName()))
1085
+ ) {
1086
+ continue;
1087
+ }
1088
+ if (this.removeAbandonedZip(id) && !this.isBundleWorkUnfinished(id)) {
1089
+ this.editor.remove(key);
1090
+ this.editor.commit();
1091
+ }
1092
+ }
1093
+ }
1094
+ }
1095
+
571
1096
  Set<String> activeManifestStagingDests() {
572
1097
  final Set<String> activeDests = new HashSet<>();
573
1098
  if (this.prefs == null) {
@@ -827,18 +1352,29 @@ public class CapgoUpdater {
827
1352
  }
828
1353
 
829
1354
  /** Parses major, minor, patch as arbitrary-precision integers; returns null when the core is not numeric. */
1355
+ private static boolean isAsciiDigit(final char c) {
1356
+ return c >= '0' && c <= '9';
1357
+ }
1358
+
830
1359
  static BigInteger[] parseCoreVersionComponents(final String version) {
831
- final String core = stripBuildMetadata(version);
832
- if (core == null || core.isEmpty() || !Character.isDigit(core.charAt(0))) {
1360
+ final String withoutBuild = stripBuildMetadata(version);
1361
+ if (withoutBuild == null) {
1362
+ return null;
1363
+ }
1364
+ // Same order as iOS: drop whitespace first, so " 2.0.0" is read as 2.0.0 on both platforms.
1365
+ final String core = withoutBuild.replaceAll("\\s", "");
1366
+ if (core.isEmpty() || !isAsciiDigit(core.charAt(0))) {
833
1367
  return null;
834
1368
  }
835
- final String[] tokens = core.replaceAll("\\s", "").split("\\.");
1369
+ // Cut the prerelease before splitting, so "1.2-rc.7" reads as 1.2.0, not 1.2.7.
1370
+ final String numeric = core.split("-", 2)[0];
1371
+ final String[] tokens = numeric.split("\\.");
836
1372
  final BigInteger[] components = new BigInteger[3];
837
1373
  for (int i = 0; i < 3; i++) {
838
1374
  if (i < tokens.length) {
839
1375
  final String token = tokens[i];
840
1376
  int end = 0;
841
- while (end < token.length() && Character.isDigit(token.charAt(end))) {
1377
+ while (end < token.length() && isAsciiDigit(token.charAt(end))) {
842
1378
  end++;
843
1379
  }
844
1380
  if (end == 0) {
@@ -885,14 +1421,14 @@ public class CapgoUpdater {
885
1421
  * either version string does not parse, so unversioned bundles keep working. Consecutive identical
886
1422
  * rejections report one stat per updater instance; every attempt still validates and throws.
887
1423
  */
888
- void requireVersionNotBelowBuiltin(final String version) throws IOException {
1424
+ synchronized void requireVersionNotBelowBuiltin(final String version) throws IOException {
889
1425
  if (!this.builtinMinimum) {
890
- this.lastVersionFloorRejection.set(null);
1426
+ this.lastVersionFloorRejection = null;
891
1427
  return;
892
1428
  }
893
1429
  final int cmp = compareCoreVersionStrings(version, this.versionBuild);
894
1430
  if (cmp == Integer.MIN_VALUE) {
895
- this.lastVersionFloorRejection.set(null);
1431
+ this.lastVersionFloorRejection = null;
896
1432
  logBuiltinMinimumParseSkipped(version);
897
1433
  return;
898
1434
  }
@@ -900,12 +1436,14 @@ public class CapgoUpdater {
900
1436
  if (cmp < 0) {
901
1437
  final String message = "Bundle version " + version + " is below native version " + this.versionBuild + " (builtinMinimum)";
902
1438
  logger.error(message);
903
- if (!message.equals(this.lastVersionFloorRejection.getAndSet(message))) {
904
- this.sendStats("version_below_native", version);
1439
+ // Latch only a stat that will be queued, so a rejection dropped by preview or a missing stats URL
1440
+ // is still reported once stats become available.
1441
+ if (!message.equals(this.lastVersionFloorRejection) && this.enqueueStats("version_below_native", version, "", null, null)) {
1442
+ this.lastVersionFloorRejection = message;
905
1443
  }
906
1444
  throw new IOException(message);
907
1445
  }
908
- this.lastVersionFloorRejection.set(null);
1446
+ this.lastVersionFloorRejection = null;
909
1447
  }
910
1448
 
911
1449
  /** Pre-network download gates shared by every entry point: httpsOnly and builtinMinimum. */
@@ -1607,6 +2145,7 @@ public class CapgoUpdater {
1607
2145
  }
1608
2146
 
1609
2147
  CapgoUpdater.this.clearManifestStagingDest(id);
2148
+ CapgoUpdater.this.retireChargedRetryAttempt(version, id, false);
1610
2149
 
1611
2150
  // Complete the future if it exists. download() waits on it.
1612
2151
  // downloadBackground does not, so the launch check must emit appReady here.
@@ -1632,6 +2171,7 @@ public class CapgoUpdater {
1632
2171
  },
1633
2172
  () -> {
1634
2173
  cleanupIncompleteDownload(id, dest, isManifest);
2174
+ CapgoUpdater.this.retireChargedRetryAttempt(observedVersion, id, false);
1635
2175
  cancelled.run();
1636
2176
  }
1637
2177
  );
@@ -1647,6 +2187,12 @@ public class CapgoUpdater {
1647
2187
  String failedVersion = failedData.getString(DownloadService.VERSION);
1648
2188
  final String failedDest = failedData.getString(DownloadService.FILEDEST);
1649
2189
  final boolean failedManifest = failedData.getBoolean(DownloadService.IS_MANIFEST, false);
2190
+ // A confirmed pre-request refusal never transferred: refund that attempt's retry charge once.
2191
+ CapgoUpdater.this.retireChargedRetryAttempt(
2192
+ observedVersion,
2193
+ id,
2194
+ failedData.getBoolean(DownloadService.PRE_REQUEST_REFUSAL, false)
2195
+ );
1650
2196
 
1651
2197
  dispatchDownloadFinalization(
1652
2198
  finalization,
@@ -1659,7 +2205,10 @@ public class CapgoUpdater {
1659
2205
  new Date(System.currentTimeMillis()),
1660
2206
  ""
1661
2207
  );
1662
- saveBundleInfo(id, failedBundle);
2208
+ synchronized (CapgoUpdater.this.deleteLock) {
2209
+ CapgoUpdater.this.markInterruptedDownloadBundle(id);
2210
+ saveBundleInfo(id, failedBundle);
2211
+ }
1663
2212
  // Cleanup download tracking for failed downloads
1664
2213
  DownloadWorkerManager.cancelBundleDownload(context, id, failedVersion);
1665
2214
  Map<String, Object> ret = new HashMap<>();
@@ -1699,6 +2248,7 @@ public class CapgoUpdater {
1699
2248
  DataManager.getInstance().clearManifest(id);
1700
2249
  retireDownloadFinalization(finalization);
1701
2250
  io.execute(() -> this.cleanupManifestStagingAfterDownloadCancelled(id));
2251
+ this.retireChargedRetryAttempt(observedVersion, id, false);
1702
2252
  cancelled.run();
1703
2253
  break;
1704
2254
  }
@@ -1757,6 +2307,8 @@ public class CapgoUpdater {
1757
2307
  if (manifest != null) {
1758
2308
  DataManager.getInstance().setManifest(id, manifest);
1759
2309
  this.saveManifestStagingDest(id, dest);
2310
+ } else {
2311
+ this.saveZipDest(id, dest);
1760
2312
  }
1761
2313
 
1762
2314
  DownloadWorkerManager.enqueueDownload(
@@ -1838,17 +2390,18 @@ public class CapgoUpdater {
1838
2390
  this.requireBundleChecksum(expectedChecksum);
1839
2391
 
1840
2392
  if (CryptoCipher.isValidSessionKey(sessionKey)) {
1841
- final CryptoCipher.BundleChecksum signed = CryptoCipher.decryptBundleChecksum(checksumRes, publicKey);
1842
2393
  try {
1843
- // The encrypted zip is hashed and checked against the signed digest before decrypting.
2394
+ final CryptoCipher.BundleChecksum signed = CryptoCipher.decryptBundleChecksum(checksumRes, publicKey);
1844
2395
  CryptoCipher.decryptFile(downloaded, publicKey, sessionKey, signed.ciphertext);
1845
- } catch (IOException e) {
1846
- if (CryptoCipher.CIPHERTEXT_CHECKSUM_MISMATCH.equals(e.getMessage())) {
2396
+ expectedChecksum = signed.plain;
2397
+ } catch (final Exception decryptError) {
2398
+ // Record the integrity failure before cleanup drops the row, so the next check charges a retry.
2399
+ if (CryptoCipher.CIPHERTEXT_CHECKSUM_MISMATCH.equals(decryptError.getMessage())) {
1847
2400
  this.sendStats("checksum_fail");
1848
2401
  }
1849
- throw e;
2402
+ this.markIntegrityBlockedVersion(version);
2403
+ throw decryptError;
1850
2404
  }
1851
- expectedChecksum = signed.plain;
1852
2405
  }
1853
2406
  checksum = CryptoCipher.calcChecksum(downloaded);
1854
2407
  CryptoCipher.logChecksumInfo("Calculated checksum", checksum);
@@ -1857,6 +2410,7 @@ public class CapgoUpdater {
1857
2410
  logger.error("Checksum mismatch");
1858
2411
  logger.debug("Expected: " + expectedChecksum + ", Got: " + checksum);
1859
2412
  this.sendStats("checksum_fail");
2413
+ this.markIntegrityBlockedVersion(version);
1860
2414
  throw new IOException("Checksum failed: " + id);
1861
2415
  }
1862
2416
  }
@@ -2370,6 +2924,10 @@ public class CapgoUpdater {
2370
2924
  }
2371
2925
  }
2372
2926
 
2927
+ boolean hasStoredBundleInfoForRetry(final String id) {
2928
+ return this.hasStoredBundleInfo(id);
2929
+ }
2930
+
2373
2931
  private boolean hasStoredBundleInfo(final String id) {
2374
2932
  return (
2375
2933
  id != null &&
@@ -2492,6 +3050,7 @@ public class CapgoUpdater {
2492
3050
  }
2493
3051
  if (orphanedBundle != null) {
2494
3052
  this.cleanupManifestStagingAfterDownloadCancelled(orphanedBundle.getId());
3053
+ this.markInterruptedDownloadBundle(orphanedBundle.getId());
2495
3054
  this.saveBundleInfo(orphanedBundle.getId(), orphanedBundle.setStatus(BundleStatus.ERROR));
2496
3055
  }
2497
3056
  logger.info("Restarting download orphaned by a previous process for version: " + version);
@@ -2506,6 +3065,7 @@ public class CapgoUpdater {
2506
3065
  this.notifyDownload(id, 5);
2507
3066
 
2508
3067
  final String dest = manifest != null ? this.manifestStagingDest() : this.randomString();
3068
+ this.bindChargedRetryAttempt(version, id);
2509
3069
  if (downloadContext == null) {
2510
3070
  this.download(id, url, dest, version, sessionKey, checksum, manifest, setNext, null);
2511
3071
  } else {
@@ -2627,6 +3187,7 @@ public class CapgoUpdater {
2627
3187
  synchronized (deleteLock) {
2628
3188
  final BundleInfo info = this.getBundleInfo(id);
2629
3189
  if (this.hasStoredBundleInfo(id) && !this.isBundleBeingDeleted(id) && !info.isDeleting() && !info.isDeleted()) {
3190
+ this.markInterruptedDownloadBundle(id);
2630
3191
  this.saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), ""));
2631
3192
  }
2632
3193
  }
@@ -3194,15 +3755,23 @@ public class CapgoUpdater {
3194
3755
 
3195
3756
  /** Enforces the floor on the final restored startup bundle without deleting retained bundle files or metadata. */
3196
3757
  void enforceStartupVersionFloor() {
3197
- final BundleInfo currentBundle = this.getCurrentBundle();
3198
- if (currentBundle.isBuiltin()) {
3199
- return;
3200
- }
3201
- try {
3202
- this.requireVersionNotBelowBuiltin(currentBundle.getVersionName());
3203
- } catch (IOException e) {
3204
- logger.info("Stored startup bundle is below the native version. Falling back to builtin.");
3205
- this.reset();
3758
+ // Same lock as set(): a headless worker that installs a compatible bundle waits for this check and fallback,
3759
+ // so the fallback can never overwrite a bundle that became current after the read below.
3760
+ synchronized (deleteLock) {
3761
+ final BundleInfo currentBundle = this.getCurrentBundle();
3762
+ if (currentBundle.isBuiltin()) {
3763
+ return;
3764
+ }
3765
+ try {
3766
+ this.requireVersionNotBelowBuiltin(currentBundle.getVersionName());
3767
+ } catch (IOException e) {
3768
+ logger.info("Stored startup bundle is below the native version. Falling back to builtin.");
3769
+ // Like reset(), but a distinct queued update stays pending (its activation runs its own floor check) and
3770
+ // downloads keep running: only an explicit reset cancels unrelated work. The reset stat is still sent.
3771
+ this.clearNextBundleIfMatches(currentBundle.getId());
3772
+ this.prepareBuiltinTransition();
3773
+ this.finalizeBuiltinUpdate(currentBundle.getVersionName());
3774
+ }
3206
3775
  }
3207
3776
  }
3208
3777
 
@@ -3255,6 +3824,11 @@ public class CapgoUpdater {
3255
3824
 
3256
3825
  public void setSuccess(final BundleInfo bundle, Boolean autoDeletePrevious) {
3257
3826
  this.setBundleStatus(bundle.getId(), BundleStatus.SUCCESS);
3827
+ final String versionName = bundle.getVersionName();
3828
+ if (versionName != null && !versionName.isEmpty()) {
3829
+ this.resetIncompleteDownloadRetryCount(versionName);
3830
+ }
3831
+ this.clearInterruptedDownloadBundle(bundle.getId());
3258
3832
  final BundleInfo fallback = this.getFallbackBundle();
3259
3833
  final BundleInfo previewFallback = this.getPreviewFallbackBundle();
3260
3834
  final boolean fallbackIsPreviewFallback = previewFallback != null && previewFallback.getId().equals(fallback.getId());
@@ -3498,6 +4072,11 @@ public class CapgoUpdater {
3498
4072
  }
3499
4073
  }
3500
4074
 
4075
+ /** Whether sendStats would queue an event right now (not stopped, not previewing, stats URL set). */
4076
+ boolean canQueueStats() {
4077
+ return !this.statsStopped.get() && !this.previewSession && this.hasStatsUrl();
4078
+ }
4079
+
3501
4080
  private boolean hasStatsUrl() {
3502
4081
  final String url = this.statsUrl;
3503
4082
  return url != null && !url.isEmpty();
@@ -4233,21 +4812,31 @@ public class CapgoUpdater {
4233
4812
  final String oldVersionName,
4234
4813
  final Map<String, String> metadata,
4235
4814
  final Runnable onSent
4815
+ ) {
4816
+ this.enqueueStats(action, versionName, oldVersionName, metadata, onSent);
4817
+ }
4818
+
4819
+ boolean enqueueStats(
4820
+ final String action,
4821
+ final String versionName,
4822
+ final String oldVersionName,
4823
+ final Map<String, String> metadata,
4824
+ final Runnable onSent
4236
4825
  ) {
4237
4826
  if (statsStopped.get()) {
4238
- return;
4827
+ return false;
4239
4828
  }
4240
4829
 
4241
4830
  if (this.previewSession) {
4242
4831
  if (logger != null) {
4243
4832
  logger.debug("Skipping sendStats during preview session.");
4244
4833
  }
4245
- return;
4834
+ return false;
4246
4835
  }
4247
4836
 
4248
4837
  String statsUrl = this.statsUrl;
4249
4838
  if (statsUrl == null || statsUrl.isEmpty()) {
4250
- return;
4839
+ return false;
4251
4840
  }
4252
4841
 
4253
4842
  JSONObject json;
@@ -4265,12 +4854,12 @@ public class CapgoUpdater {
4265
4854
  logger.error("Error preparing stats");
4266
4855
  logger.debug("JSONException: " + e.getMessage());
4267
4856
  }
4268
- return;
4857
+ return false;
4269
4858
  }
4270
4859
 
4271
4860
  synchronized (statsQueue) {
4272
- if (statsStopped.get()) {
4273
- return;
4861
+ if (!canQueueStats()) {
4862
+ return false;
4274
4863
  }
4275
4864
  while (statsQueue.size() >= MAX_PENDING_STATS) {
4276
4865
  statsQueue.remove(0);
@@ -4278,6 +4867,7 @@ public class CapgoUpdater {
4278
4867
  statsQueue.add(new QueuedStatsEvent(json, onSent));
4279
4868
  }
4280
4869
  ensureStatsTimerStarted();
4870
+ return true;
4281
4871
  }
4282
4872
 
4283
4873
  public void restorePendingStats() {
@@ -4940,6 +5530,57 @@ public class CapgoUpdater {
4940
5530
  return null;
4941
5531
  }
4942
5532
 
5533
+ /** A same-version bundle that is fully stored and installable, regardless of directory listing order. */
5534
+ BundleInfo findReusableBundleByVersionName(final String versionName) {
5535
+ return this.findReusableBundleByVersionName(versionName, null);
5536
+ }
5537
+
5538
+ /** First installable same-version bundle that {@code accept} also admits (all of them are examined). */
5539
+ BundleInfo findReusableBundleByVersionName(final String versionName, final java.util.function.Predicate<BundleInfo> accept) {
5540
+ if (versionName == null || versionName.isEmpty() || this.documentsDir == null) {
5541
+ return null;
5542
+ }
5543
+ for (final BundleInfo i : this.list(false)) {
5544
+ if (
5545
+ i != null &&
5546
+ versionName.equals(i.getVersionName()) &&
5547
+ i.isDownloaded() &&
5548
+ !i.isErrorStatus() &&
5549
+ !i.isDeleted() &&
5550
+ !i.isDeleting() &&
5551
+ BundleStatus.DOWNLOADING != i.getStatus() &&
5552
+ this.isBundleOnDisk(i.getId()) &&
5553
+ (accept == null || accept.test(i))
5554
+ ) {
5555
+ return i;
5556
+ }
5557
+ }
5558
+ return null;
5559
+ }
5560
+
5561
+ /**
5562
+ * Finds a same-version registry record only when {@link #getBundleInfoByName(String)} returned null,
5563
+ * typically a deleted tombstone or other incomplete state kept in prefs.
5564
+ */
5565
+ public BundleInfo findRegistryBundleByVersionName(final String versionName) {
5566
+ if (versionName == null || versionName.isEmpty() || this.prefs == null) {
5567
+ return null;
5568
+ }
5569
+ BundleInfo tombstoneMatch = null;
5570
+ for (final BundleInfo i : this.list(true)) {
5571
+ if (i == null || i.isBuiltin() || i.isUnknown() || !versionName.equals(i.getVersionName())) {
5572
+ continue;
5573
+ }
5574
+ if (!i.isDeleted() && !i.isDeleting()) {
5575
+ return i;
5576
+ }
5577
+ if (tombstoneMatch == null) {
5578
+ tombstoneMatch = i;
5579
+ }
5580
+ }
5581
+ return tombstoneMatch;
5582
+ }
5583
+
4943
5584
  private void removeBundleInfo(final String id) {
4944
5585
  this.saveBundleInfo(id, null);
4945
5586
  }