@capgo/capacitor-updater 9.0.1 → 9.0.2

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 (26) 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 +513 -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/DownloadService.java +82 -10
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  9. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  11. package/dist/docs.json +13 -13
  12. package/dist/esm/definitions.d.ts +57 -23
  13. package/dist/esm/definitions.js.map +1 -1
  14. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  15. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  17. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  19. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2705 -77
  20. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  22. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  23. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +22 -8
  24. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  26. package/package.json +2 -2
@@ -95,7 +95,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
95
95
  deinit {
96
96
  implementation.shutdown()
97
97
  }
98
- private let pluginVersion: String = "9.0.1"
98
+ private let pluginVersion: String = "9.0.2"
99
99
  private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
100
100
  static let updateUrlDefault = "https://plugin.capgo.app/updates"
101
101
  static let statsUrlDefault = "https://plugin.capgo.app/stats"
@@ -210,9 +210,70 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
210
210
  private var backgroundWork: DispatchWorkItem?
211
211
  private var taskRunning = false
212
212
  private var periodCheckDelay = 0
213
+ private struct ManifestFingerprintEntry: Equatable {
214
+ let targetPath: String
215
+ let fileHash: String
216
+ }
217
+
218
+ private enum VersionDownloadDescriptor: Equatable {
219
+ case zip(expectedChecksum: String, sessionKey: String)
220
+ case manifest(entries: [ManifestFingerprintEntry], sessionKey: String)
221
+ }
222
+
223
+ /// How a bundle completed by an in-process download was delivered, so reuse can require the same delivery.
224
+ private enum CompletedDownloadFingerprint: Equatable {
225
+ case zip
226
+ case manifest([ManifestFingerprintEntry])
227
+ }
228
+
229
+ private enum DirectUpdateResult {
230
+ case applied
231
+ case alreadyActive
232
+ /// A concurrent set() activated another bundle during the reload; it owns the active state.
233
+ case superseded
234
+ /// The bundle was marked ERROR before it could be committed.
235
+ case rejectedError
236
+ case failed
237
+ /// The reload failed after the app queued its own next bundle; that queue is kept as-is.
238
+ case failedKeepingAppQueue
239
+ }
240
+
241
+ private enum QueueNextBundleResult {
242
+ case queued
243
+ case alreadyActive
244
+ /// The bundle was marked ERROR before it could be committed.
245
+ case rejectedError
246
+ case failed
247
+ }
248
+
249
+ private final class InFlightVersionDownload {
250
+ let version: String
251
+ let descriptor: VersionDownloadDescriptor
252
+ let sourceIdentity: String
253
+ let group = DispatchGroup()
254
+ var result: Result<BundleInfo, Error>?
255
+
256
+ init(version: String, descriptor: VersionDownloadDescriptor, sourceIdentity: String) {
257
+ self.version = version
258
+ self.descriptor = descriptor
259
+ self.sourceIdentity = sourceIdentity
260
+ }
261
+ }
262
+
213
263
  private let downloadLock = NSLock()
264
+ private let nextBundleLock = NSLock()
265
+ /// Bumped under `nextBundleLock` whenever the active bundle actually changes (set() or a staged direct update),
266
+ /// so a direct update that releases the lock to reload can tell whether another activation happened meanwhile.
267
+ private var activeBundleGeneration: UInt64 = 0
268
+ /// Bumped under `nextBundleLock` whenever the queued next bundle is actually changed by next() or the queue path.
269
+ private var queuedBundleGeneration: UInt64 = 0
270
+ private var inFlightDownloadsByVersion: [String: InFlightVersionDownload] = [:]
271
+ private var completedDownloadFingerprintsByBundleId: [String: CompletedDownloadFingerprint] = [:]
272
+ internal var onCoalesceWaiterJoinedForTesting: ((String) -> Void)?
273
+ internal var onDownloadSlotAcquireAttemptForTesting: ((String) -> Void)?
214
274
  private let onLaunchDirectUpdateStateLock = NSLock()
215
275
  private var downloadInProgress = false
276
+ private var downloadActiveVersionName: String?
216
277
  private var downloadStartTime: Date?
217
278
  private let downloadTimeout: TimeInterval = 600 // 10 minute timeout
218
279
 
@@ -1111,7 +1172,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1111
1172
  try self.implementation.requireVersionNotBelowBuiltin(currentBundle.getVersionName())
1112
1173
  } catch {
1113
1174
  self.logger.warn("Stored bundle is below the native version. Resetting startup bundle to builtin.")
1114
- self.implementation.reset(isInternal: true)
1175
+ self.implementation.resetRejectedStartupBundle()
1115
1176
  didResetCurrentBundle = true
1116
1177
  }
1117
1178
  }
@@ -1219,6 +1280,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1219
1280
  }
1220
1281
  self.implementation.cleanupOrphanedTempFolders(threadToCheck: Thread.current)
1221
1282
 
1283
+ self.implementation.reconcileInterruptedDownloadsOnLaunch()
1284
+
1222
1285
  if self.defaultChannelCleanupMustRetry {
1223
1286
  self.logger.warn("Keeping the previous native build version so default channel cleanup retries")
1224
1287
  } else {
@@ -1731,6 +1794,359 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1731
1794
  NSError(domain: "CapacitorUpdaterPreview", code: 0, userInfo: [NSLocalizedDescriptionKey: message])
1732
1795
  }
1733
1796
 
1797
+ private func validateAndBuildDownloadDescriptor(
1798
+ url: URL,
1799
+ version: String,
1800
+ sessionKey: String,
1801
+ expectedZipChecksum: String,
1802
+ manifestEntries: [ManifestEntry]?
1803
+ ) throws -> VersionDownloadDescriptor {
1804
+ try self.implementation.requireVersionNotBelowBuiltin(version)
1805
+ let normalizedSessionKey: String
1806
+ if !self.implementation.publicKey.isEmpty {
1807
+ try CryptoCipher.validateDecryptionKey(
1808
+ publicKey: self.implementation.publicKey,
1809
+ sessionKey: sessionKey
1810
+ )
1811
+ normalizedSessionKey = sessionKey
1812
+ } else {
1813
+ normalizedSessionKey = ""
1814
+ }
1815
+
1816
+ if let manifestEntries = manifestEntries {
1817
+ for entry in manifestEntries {
1818
+ if let downloadUrl = entry.download_url, let entryUrl = URL(string: downloadUrl) {
1819
+ try self.implementation.assertAllowedScheme(entryUrl)
1820
+ }
1821
+ }
1822
+
1823
+ let syntheticRoot = URL(fileURLWithPath: "/capgo-manifest-root")
1824
+ var seenTargets = Set<String>()
1825
+ var entries: [ManifestFingerprintEntry] = []
1826
+ entries.reserveCapacity(manifestEntries.count)
1827
+
1828
+ for entry in manifestEntries {
1829
+ guard let fileName = entry.file_name,
1830
+ let downloadUrl = entry.download_url else {
1831
+ throw NSError(
1832
+ domain: "ManifestEntryError",
1833
+ code: 1,
1834
+ userInfo: [
1835
+ NSLocalizedDescriptionKey: "Manifest entry is missing file_name or download_url"
1836
+ ]
1837
+ )
1838
+ }
1839
+ guard URL(string: downloadUrl) != nil else {
1840
+ throw NSError(
1841
+ domain: "ManifestDownloadError",
1842
+ code: 1,
1843
+ userInfo: [
1844
+ NSLocalizedDescriptionKey: "Invalid manifest download URL for file \(fileName): \(downloadUrl)"
1845
+ ]
1846
+ )
1847
+ }
1848
+ guard let entryFileHash = entry.file_hash, !entryFileHash.isEmpty else {
1849
+ throw NSError(
1850
+ domain: "ManifestEntryError",
1851
+ code: 2,
1852
+ userInfo: [
1853
+ NSLocalizedDescriptionKey: "Manifest entry is missing file_hash for \(fileName)"
1854
+ ]
1855
+ )
1856
+ }
1857
+ let finalFileHash: String
1858
+ if !self.implementation.publicKey.isEmpty {
1859
+ finalFileHash = try CryptoCipher.decryptChecksum(
1860
+ checksum: entryFileHash,
1861
+ publicKey: self.implementation.publicKey
1862
+ )
1863
+ } else {
1864
+ finalFileHash = entryFileHash
1865
+ }
1866
+ let targetFile = try CapgoUpdater.resolveManifestTargetPath(
1867
+ baseDirectory: syntheticRoot,
1868
+ fileName: fileName
1869
+ )
1870
+ guard CapgoUpdater.rememberManifestTarget(&seenTargets, targetFile: targetFile) else {
1871
+ throw NSError(
1872
+ domain: "ManifestEntryError",
1873
+ code: 3,
1874
+ userInfo: [
1875
+ NSLocalizedDescriptionKey: "Duplicate manifest target path for \(fileName)"
1876
+ ]
1877
+ )
1878
+ }
1879
+ entries.append(
1880
+ ManifestFingerprintEntry(
1881
+ targetPath: targetFile.standardizedFileURL.path,
1882
+ fileHash: finalFileHash
1883
+ )
1884
+ )
1885
+ }
1886
+
1887
+ entries.sort {
1888
+ if $0.targetPath != $1.targetPath {
1889
+ return $0.targetPath < $1.targetPath
1890
+ }
1891
+ return $0.fileHash < $1.fileHash
1892
+ }
1893
+ return .manifest(entries: entries, sessionKey: normalizedSessionKey)
1894
+ }
1895
+
1896
+ try self.implementation.assertAllowedScheme(url)
1897
+ return .zip(expectedChecksum: expectedZipChecksum, sessionKey: normalizedSessionKey)
1898
+ }
1899
+
1900
+ private static func downloadSourceIdentity(url: URL, manifestEntries: [ManifestEntry]?) -> String {
1901
+ if let manifestEntries = manifestEntries {
1902
+ let urls = manifestEntries
1903
+ .map { "\($0.file_name ?? "")=\($0.download_url ?? "")" }
1904
+ .sorted()
1905
+ return "manifest:\(urls.joined(separator: "\n"))"
1906
+ }
1907
+ return "zip:\(url.absoluteString)"
1908
+ }
1909
+
1910
+ private func recordCompletedDownloadFingerprint(bundleId: String, fingerprint: CompletedDownloadFingerprint) {
1911
+ self.downloadLock.lock()
1912
+ self.completedDownloadFingerprintsByBundleId[bundleId] = fingerprint
1913
+ let candidateIds = self.completedDownloadFingerprintsByBundleId.count > 16
1914
+ ? Array(self.completedDownloadFingerprintsByBundleId.keys)
1915
+ : []
1916
+ self.downloadLock.unlock()
1917
+
1918
+ guard !candidateIds.isEmpty else {
1919
+ return
1920
+ }
1921
+ let staleIds = candidateIds.filter { id in
1922
+ guard id != bundleId else {
1923
+ return false
1924
+ }
1925
+ // getBundleInfo(id:) returns a PENDING placeholder for a missing record, so check storage directly:
1926
+ // bundles removed by autoDeletePrevious/delete(id:) have no record or no folder any more.
1927
+ return !self.implementation.hasStoredDownloadedBundle(id: id)
1928
+ }
1929
+ guard !staleIds.isEmpty else {
1930
+ return
1931
+ }
1932
+ self.downloadLock.lock()
1933
+ for id in staleIds {
1934
+ self.completedDownloadFingerprintsByBundleId.removeValue(forKey: id)
1935
+ }
1936
+ self.downloadLock.unlock()
1937
+ }
1938
+
1939
+ private func applyServerMetadataIfMissing(bundle: BundleInfo, link: String?, comment: String?) -> BundleInfo {
1940
+ let needsLink = link != nil && bundle.getLink() == nil
1941
+ let needsComment = comment != nil && bundle.getComment() == nil
1942
+ guard needsLink || needsComment else {
1943
+ return bundle
1944
+ }
1945
+ // Persist only into a record that still exists (ordered with delete() by deleteLock), and hold
1946
+ // nextBundleLock so the read-modify-write cannot overwrite a concurrent setBundleError/notifyAppReady status.
1947
+ self.nextBundleLock.lock()
1948
+ let stored = self.implementation.fillStoredBundleMetadataIfPresent(id: bundle.getId(), link: link, comment: comment)
1949
+ self.nextBundleLock.unlock()
1950
+ if let stored {
1951
+ return stored
1952
+ }
1953
+ var updated = bundle
1954
+ if let link, updated.getLink() == nil {
1955
+ updated = updated.setLink(link: link)
1956
+ }
1957
+ if let comment, updated.getComment() == nil {
1958
+ updated = updated.setComment(comment: comment)
1959
+ }
1960
+ return updated
1961
+ }
1962
+
1963
+ private func deleteIncompleteBundle(_ existing: BundleInfo) {
1964
+ self.logger.info("Latest bundle already exists in incomplete state (\(existing.getStatus())) and will be deleted, download will overwrite it.")
1965
+ self.nextBundleLock.lock()
1966
+ if self.implementation.getNextBundle()?.getId() == existing.getId() {
1967
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
1968
+ }
1969
+ self.nextBundleLock.unlock()
1970
+ let deleted = self.implementation.delete(id: existing.getId(), removeInfo: true)
1971
+ if deleted {
1972
+ self.downloadLock.lock()
1973
+ self.completedDownloadFingerprintsByBundleId.removeValue(forKey: existing.getId())
1974
+ self.downloadLock.unlock()
1975
+ self.logger.info("Incomplete bundle deleted: \(existing.toString())")
1976
+ } else {
1977
+ self.logger.error("Failed to delete incomplete bundle: \(existing.toString())")
1978
+ }
1979
+ }
1980
+
1981
+ private struct VersionDownloadSnapshot {
1982
+ let inFlight: Bool
1983
+ let existing: BundleInfo?
1984
+ let retainedErrorBundle: BundleInfo?
1985
+ let recordedFingerprint: CompletedDownloadFingerprint?
1986
+ }
1987
+
1988
+ /// Reads the in-flight slot, the stored bundles for `version` and the recorded manifest fingerprint
1989
+ /// under `downloadLock`. A leader records its fingerprint before releasing its slot under the same lock,
1990
+ /// so a bundle seen here without an in-flight slot can never be a half-published in-process download.
1991
+ private func snapshotVersionDownloadState(
1992
+ version: String,
1993
+ requestedManifest: [ManifestFingerprintEntry]?
1994
+ ) -> VersionDownloadSnapshot {
1995
+ let key = version.trimmingCharacters(in: .whitespacesAndNewlines)
1996
+ self.downloadLock.lock()
1997
+ defer { self.downloadLock.unlock() }
1998
+ let inFlight = !key.isEmpty && self.inFlightDownloadsByVersion[key] != nil
1999
+ let matchingBundles = self.implementation.getBundleInfosByVersionName(version: version)
2000
+ // A retained ERROR copy of the version must block automatic updates wherever it is listed.
2001
+ let retainedErrorBundle = matchingBundles.first { $0.isErrorStatus() }
2002
+ // For a manifest request, prefer a complete copy delivered with that exact manifest over the first match.
2003
+ let matchingManifestCopy = requestedManifest.flatMap { requested in
2004
+ matchingBundles.first { bundle in
2005
+ !bundle.isErrorStatus()
2006
+ && !Self.shouldRetryDownloadForExistingBundle(bundle)
2007
+ && self.completedDownloadFingerprintsByBundleId[bundle.getId()] == .manifest(requested)
2008
+ }
2009
+ }
2010
+ let existing = matchingManifestCopy ?? matchingBundles.first
2011
+ let recordedFingerprint = existing.flatMap { self.completedDownloadFingerprintsByBundleId[$0.getId()] }
2012
+ return VersionDownloadSnapshot(
2013
+ inFlight: inFlight,
2014
+ existing: existing,
2015
+ retainedErrorBundle: retainedErrorBundle,
2016
+ recordedFingerprint: recordedFingerprint
2017
+ )
2018
+ }
2019
+
2020
+ /// Called by the slot owner: returns a stored copy of `version` that already satisfies `descriptor`,
2021
+ /// deleting incomplete leftovers on the way. Copies are only reused on an exact in-process fingerprint
2022
+ /// (manifest) or checksum (ZIP) match.
2023
+ private func findReusableStoredBundle(
2024
+ version: String,
2025
+ descriptor: VersionDownloadDescriptor,
2026
+ expectedZipChecksum: String?
2027
+ ) -> BundleInfo? {
2028
+ for candidate in self.implementation.getBundleInfosByVersionName(version: version) {
2029
+ if Self.shouldRetryDownloadForExistingBundle(candidate) {
2030
+ self.deleteIncompleteBundle(candidate)
2031
+ continue
2032
+ }
2033
+ if candidate.isErrorStatus() {
2034
+ continue
2035
+ }
2036
+ if let expectedZipChecksum {
2037
+ if !candidate.getChecksum().isEmpty && candidate.getChecksum() == expectedZipChecksum {
2038
+ return candidate
2039
+ }
2040
+ } else if case let .manifest(requestedEntries, _) = descriptor {
2041
+ self.downloadLock.lock()
2042
+ let recorded = self.completedDownloadFingerprintsByBundleId[candidate.getId()]
2043
+ self.downloadLock.unlock()
2044
+ if recorded == .manifest(requestedEntries) {
2045
+ return candidate
2046
+ }
2047
+ }
2048
+ }
2049
+ return nil
2050
+ }
2051
+
2052
+ private func deleteStaleIncompleteBundleIfIdle(version: String) {
2053
+ let key = version.trimmingCharacters(in: .whitespacesAndNewlines)
2054
+ self.downloadLock.lock()
2055
+ let inFlight = !key.isEmpty && self.inFlightDownloadsByVersion[key] != nil
2056
+ let existing = inFlight ? nil : self.implementation.getBundleInfoByVersionName(version: version)
2057
+ self.downloadLock.unlock()
2058
+ guard let existing, Self.shouldRetryDownloadForExistingBundle(existing) else {
2059
+ return
2060
+ }
2061
+ self.deleteIncompleteBundle(existing)
2062
+ }
2063
+
2064
+ private func coalesceVersionDownload(
2065
+ version: String,
2066
+ descriptor: VersionDownloadDescriptor,
2067
+ sourceIdentity: String,
2068
+ work: () throws -> BundleInfo
2069
+ ) throws -> (bundle: BundleInfo, coalesced: Bool) {
2070
+ let key = version.trimmingCharacters(in: .whitespacesAndNewlines)
2071
+ guard !key.isEmpty else {
2072
+ return (try work(), false)
2073
+ }
2074
+
2075
+ var retriedAfterDifferentSourceFailure = false
2076
+ while true {
2077
+ self.onDownloadSlotAcquireAttemptForTesting?(key)
2078
+ self.downloadLock.lock()
2079
+ if let existing = self.inFlightDownloadsByVersion[key] {
2080
+ let matchesFlight = existing.version == version && existing.descriptor == descriptor
2081
+ let matchesSource = existing.sourceIdentity == sourceIdentity
2082
+ self.downloadLock.unlock()
2083
+ if matchesFlight {
2084
+ self.logger.info("Coalescing concurrent download for version \(key)")
2085
+ } else {
2086
+ self.logger.info("Waiting for incompatible in-flight download for version \(key) before downloading")
2087
+ }
2088
+ self.onCoalesceWaiterJoinedForTesting?(key)
2089
+ existing.group.wait()
2090
+ if matchesFlight {
2091
+ if let result = existing.result {
2092
+ switch result {
2093
+ case let .success(bundle):
2094
+ return (bundle, true)
2095
+ case let .failure(error):
2096
+ if !matchesSource && !retriedAfterDifferentSourceFailure {
2097
+ retriedAfterDifferentSourceFailure = true
2098
+ continue
2099
+ }
2100
+ throw error
2101
+ }
2102
+ }
2103
+ throw NSError(
2104
+ domain: "CapacitorUpdater",
2105
+ code: -1,
2106
+ userInfo: [NSLocalizedDescriptionKey: "Concurrent download for \(key) completed without a result"]
2107
+ )
2108
+ }
2109
+ continue
2110
+ }
2111
+
2112
+ let entry = InFlightVersionDownload(
2113
+ version: version,
2114
+ descriptor: descriptor,
2115
+ sourceIdentity: sourceIdentity
2116
+ )
2117
+ entry.group.enter()
2118
+ self.inFlightDownloadsByVersion[key] = entry
2119
+ self.downloadLock.unlock()
2120
+
2121
+ let result: Result<BundleInfo, Error>
2122
+ do {
2123
+ let bundle = try work()
2124
+ result = .success(bundle)
2125
+ } catch {
2126
+ result = .failure(error)
2127
+ }
2128
+
2129
+ if case let .success(bundle) = result {
2130
+ let fingerprint: CompletedDownloadFingerprint
2131
+ switch descriptor {
2132
+ case .zip:
2133
+ fingerprint = .zip
2134
+ case let .manifest(entries, _):
2135
+ fingerprint = .manifest(entries)
2136
+ }
2137
+ self.recordCompletedDownloadFingerprint(bundleId: bundle.getId(), fingerprint: fingerprint)
2138
+ }
2139
+
2140
+ self.downloadLock.lock()
2141
+ entry.result = result
2142
+ self.inFlightDownloadsByVersion.removeValue(forKey: key)
2143
+ self.downloadLock.unlock()
2144
+ entry.group.leave()
2145
+
2146
+ return (try result.get(), false)
2147
+ }
2148
+ }
2149
+
1734
2150
  private func downloadBundle(urlString: String, version: String, sessionKey: String, checksum rawChecksum: String, manifestEntries: [ManifestEntry]?) throws -> BundleInfo {
1735
2151
  guard let url = URL(string: urlString) else {
1736
2152
  throw makePreviewError("Invalid download URL")
@@ -1742,37 +2158,57 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1742
2158
  throw makePreviewError("Session key required when public key is present")
1743
2159
  }
1744
2160
 
1745
- var checksum = rawChecksum
1746
- if manifestEntries == nil && checksum.isEmpty {
2161
+ if manifestEntries == nil && rawChecksum.isEmpty {
1747
2162
  self.logger.error("No checksum provided")
1748
2163
  self.implementation.sendStats(action: "checksum_required", versionName: version)
1749
2164
  throw makePreviewError("Checksum required")
1750
2165
  }
1751
2166
 
1752
- let next: BundleInfo
1753
- if let manifestEntries = manifestEntries {
1754
- next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
2167
+ let expectedChecksum: String
2168
+ if manifestEntries == nil {
2169
+ expectedChecksum = try CryptoCipher.decryptChecksum(checksum: rawChecksum, publicKey: self.implementation.publicKey)
1755
2170
  } else {
1756
- next = try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
2171
+ expectedChecksum = ""
2172
+ }
2173
+
2174
+ let descriptor = try self.validateAndBuildDownloadDescriptor(
2175
+ url: url,
2176
+ version: version,
2177
+ sessionKey: sessionKey,
2178
+ expectedZipChecksum: expectedChecksum,
2179
+ manifestEntries: manifestEntries
2180
+ )
2181
+ let sourceIdentity = Self.downloadSourceIdentity(url: url, manifestEntries: manifestEntries)
2182
+
2183
+ let (next, coalesced) = try self.coalesceVersionDownload(
2184
+ version: version,
2185
+ descriptor: descriptor,
2186
+ sourceIdentity: sourceIdentity
2187
+ ) {
2188
+ if let manifestEntries = manifestEntries {
2189
+ return try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
2190
+ }
2191
+ return try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
1757
2192
  }
1758
2193
 
1759
2194
  if manifestEntries == nil {
1760
- checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
1761
2195
  CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
1762
- CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: checksum)
1763
- if next.getChecksum() != checksum {
1764
- self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
2196
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: expectedChecksum)
2197
+ if next.getChecksum() != expectedChecksum {
2198
+ self.logger.error("Error checksum \(next.getChecksum()) \(expectedChecksum)")
1765
2199
  self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
1766
- let id = next.getId()
1767
- let resDel = self.implementation.delete(id: id)
1768
- if !resDel {
1769
- self.logger.error("Delete failed, id \(id) doesn't exist")
2200
+ if !coalesced {
2201
+ let id = next.getId()
2202
+ let resDel = self.implementation.delete(id: id)
2203
+ if !resDel {
2204
+ self.logger.error("Delete failed, id \(id) doesn't exist")
2205
+ }
1770
2206
  }
1771
2207
  throw ObjectSavableError.checksum
1772
2208
  }
1773
2209
  }
1774
2210
 
1775
- self.logger.info("Good checksum \(next.getChecksum()) \(checksum)")
2211
+ self.logger.info("Good checksum \(next.getChecksum()) \(expectedChecksum)")
1776
2212
  return next
1777
2213
  }
1778
2214
 
@@ -1828,6 +2264,25 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1828
2264
  }
1829
2265
  }
1830
2266
 
2267
+ static func reloadServerBasePathAtomically(
2268
+ path: String,
2269
+ serverURL: URL,
2270
+ setServerBasePath: (String) -> Void,
2271
+ loadRequest: (URLRequest) -> Void
2272
+ ) {
2273
+ setServerBasePath(path)
2274
+ loadRequest(URLRequest(url: serverURL))
2275
+ }
2276
+
2277
+ private func reloadServerBasePathAtomically(path: String, capBridge: CAPBridgeProtocol, webView: WKWebView?) {
2278
+ Self.reloadServerBasePathAtomically(
2279
+ path: path,
2280
+ serverURL: capBridge.config.serverURL,
2281
+ setServerBasePath: { capBridge.setServerBasePath($0) },
2282
+ loadRequest: { _ = webView?.load($0) }
2283
+ )
2284
+ }
2285
+
1831
2286
  private func applyCurrentBundleToBridge(_ bridge: CAPBridgeProtocol) -> Bool {
1832
2287
  let id = self.implementation.getCurrentBundleId()
1833
2288
  let dest = self.currentReloadDestination()
@@ -1853,14 +2308,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1853
2308
  _ = vc.webView?.load(URLRequest(url: finalUrl))
1854
2309
  } else {
1855
2310
  self.logger.error("Unable to build final URL when keeping path after reload; falling back to base path")
1856
- vc.setServerBasePath(path: dest.path)
2311
+ self.reloadServerBasePathAtomically(path: dest.path, capBridge: capBridge, webView: vc.webView)
1857
2312
  }
1858
2313
  } else {
1859
2314
  self.logger.error("vc.webView?.url is null? Falling back to base path reload.")
1860
- vc.setServerBasePath(path: dest.path)
2315
+ self.reloadServerBasePathAtomically(path: dest.path, capBridge: capBridge, webView: vc.webView)
1861
2316
  }
1862
2317
  } else {
1863
- vc.setServerBasePath(path: dest.path)
2318
+ self.reloadServerBasePathAtomically(path: dest.path, capBridge: capBridge, webView: vc.webView)
1864
2319
  }
1865
2320
  return true
1866
2321
  }
@@ -1934,6 +2389,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1934
2389
 
1935
2390
  /// Reloads the app, rejecting an incompatible pending bundle with VERSION_BELOW_NATIVE before changing state.
1936
2391
  @objc func reload(_ call: CAPPluginCall) {
2392
+ // Decide and stage under nextBundleLock, like set() and the direct update, so a concurrent direct update
2393
+ // sees this activation through activeBundleGeneration.
2394
+ self.nextBundleLock.lock()
1937
2395
  let current: BundleInfo = self.implementation.getCurrentBundle()
1938
2396
  let next: BundleInfo? = self.implementation.getNextBundle()
1939
2397
 
@@ -1945,12 +2403,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1945
2403
  do {
1946
2404
  try self.implementation.requireVersionNotBelowBuiltin(next.getVersionName())
1947
2405
  } catch {
2406
+ self.nextBundleLock.unlock()
1948
2407
  call.reject(error.localizedDescription, "VERSION_BELOW_NATIVE", error)
1949
2408
  return
1950
2409
  }
1951
2410
  }
1952
2411
  let previousState = self.implementation.captureResetState()
1953
- let previousBundleName = self.implementation.getCurrentBundle().getVersionName()
2412
+ let previousBundleName = current.getVersionName()
1954
2413
  logger.info("Applying pending bundle before reload: \(next.toString())")
1955
2414
  let didApplyPendingBundle: Bool
1956
2415
  if next.isBuiltin() {
@@ -1959,24 +2418,50 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1959
2418
  } else {
1960
2419
  didApplyPendingBundle = self.implementation.stagePendingReload(bundle: next)
1961
2420
  }
2421
+ if didApplyPendingBundle {
2422
+ self.activeBundleGeneration &+= 1
2423
+ }
2424
+ let stagedActiveGeneration = self.activeBundleGeneration
2425
+ let stagedQueueGeneration = self.queuedBundleGeneration
2426
+ self.nextBundleLock.unlock()
1962
2427
  if didApplyPendingBundle && self.reloadCurrentBundle() {
2428
+ self.nextBundleLock.lock()
2429
+ guard self.activeBundleGeneration == stagedActiveGeneration else {
2430
+ // A concurrent set()/installNext()/direct update activated another bundle during this reload;
2431
+ // it owns the set event and the queue, so do not publish or clear anything for this one.
2432
+ self.nextBundleLock.unlock()
2433
+ logger.info("Reload of pending bundle \(next.getId()) was superseded by a concurrent activation.")
2434
+ call.resolve()
2435
+ return
2436
+ }
2437
+ self.notifyBundleSet(next)
2438
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
2439
+ self.nextBundleLock.unlock()
1963
2440
  if next.isBuiltin() {
1964
2441
  self.implementation.finalizeResetTransition(previousBundleName: previousBundleName, isInternal: false)
1965
2442
  } else {
1966
2443
  self.implementation.finalizePendingReload(bundle: next, previousBundleName: previousBundleName)
1967
2444
  }
1968
- self.notifyBundleSet(next)
1969
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
1970
2445
  self.showPreviewSessionNoticeIfNeeded()
1971
2446
  call.resolve()
1972
2447
  return
1973
2448
  }
1974
- self.implementation.restoreResetState(previousState)
2449
+ self.nextBundleLock.lock()
2450
+ guard !didApplyPendingBundle || self.activeBundleGeneration == stagedActiveGeneration else {
2451
+ // A concurrent activation replaced this one during the reload; keep its newer state.
2452
+ self.nextBundleLock.unlock()
2453
+ logger.error("Reload failed after applying pending bundle: \(next.toString()); a concurrent activation replaced it")
2454
+ call.reject("Reload failed after applying pending bundle")
2455
+ return
2456
+ }
2457
+ self.restoreResetStateKeepingAppQueue(previousState, appChangedQueue: self.queuedBundleGeneration != stagedQueueGeneration)
2458
+ self.nextBundleLock.unlock()
1975
2459
  self.restoreLiveBundleStateAfterFailedReload()
1976
2460
  logger.error("Reload failed after applying pending bundle: \(next.toString())")
1977
2461
  call.reject("Reload failed after applying pending bundle")
1978
2462
  return
1979
2463
  }
2464
+ self.nextBundleLock.unlock()
1980
2465
 
1981
2466
  if self.reloadCurrentBundle() {
1982
2467
  self.showPreviewSessionNoticeIfNeeded()
@@ -1987,34 +2472,121 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1987
2472
  }
1988
2473
  }
1989
2474
 
1990
- private func queueBundleForNextBackgroundInstall(_ next: BundleInfo) -> Bool {
1991
- guard self.implementation.setNextBundle(next: next.getId()) else {
2475
+ private func queueBundleForNextBackgroundInstall(_ next: BundleInfo) -> QueueNextBundleResult {
2476
+ self.nextBundleLock.lock()
2477
+ let currentBundle = self.implementation.getCurrentBundle()
2478
+ if currentBundle.getId() == next.getId() {
2479
+ self.nextBundleLock.unlock()
2480
+ self.logger.info("Downloaded bundle \(next.getId()) is already active; skipping next queue.")
2481
+ return .alreadyActive
2482
+ }
2483
+ // setBundleError takes nextBundleLock, so this status check is ordered with manual error marks.
2484
+ if self.implementation.getBundleInfo(id: next.getId()).isErrorStatus() {
2485
+ self.nextBundleLock.unlock()
2486
+ self.logger.error("Downloaded bundle \(next.getId()) was marked as error; not queuing it.")
2487
+ return .rejectedError
2488
+ }
2489
+ let didSetNext = self.implementation.setNextBundle(next: next.getId())
2490
+ if didSetNext {
2491
+ self.queuedBundleGeneration &+= 1
2492
+ }
2493
+ self.nextBundleLock.unlock()
2494
+ guard didSetNext else {
1992
2495
  self.logger.error("Failed to queue downloaded bundle as next: \(next.toString())")
1993
- return false
2496
+ return .failed
1994
2497
  }
1995
- return true
2498
+ return .queued
1996
2499
  }
1997
2500
 
1998
- private func applyDownloadedBundleForDirectUpdate(_ next: BundleInfo) -> Bool {
1999
- let previousState = self.implementation.captureResetState()
2000
- let previousBundleName = self.implementation.getCurrentBundle().getVersionName()
2501
+ /// Queues the builtin bundle under nextBundleLock and records it in queuedBundleGeneration, so a failed
2502
+ /// reload that rolls back concurrently keeps this queue instead of restoring its older snapshot.
2503
+ private func queueBuiltinBundleAsNext() -> Bool {
2504
+ self.nextBundleLock.lock()
2505
+ defer { self.nextBundleLock.unlock() }
2506
+ let didSetNext = self.implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
2507
+ if didSetNext {
2508
+ self.queuedBundleGeneration &+= 1
2509
+ }
2510
+ return didSetNext
2511
+ }
2001
2512
 
2513
+ /// Rolls back a failed activation. When the app queued a bundle with next() during the reload, keeps that
2514
+ /// queue instead of restoring the snapshot's. Call with nextBundleLock held.
2515
+ private func restoreResetStateKeepingAppQueue(_ previousState: CapgoUpdater.ResetState, appChangedQueue: Bool) {
2516
+ guard appChangedQueue else {
2517
+ self.implementation.restoreResetState(previousState)
2518
+ return
2519
+ }
2520
+ let appQueue = self.implementation.captureResetState().nextBundleId
2521
+ self.implementation.restoreResetState(CapgoUpdater.ResetState(
2522
+ currentBundlePath: previousState.currentBundlePath,
2523
+ fallbackBundleId: previousState.fallbackBundleId,
2524
+ nextBundleId: appQueue
2525
+ ))
2526
+ }
2527
+
2528
+ private func applyDownloadedBundleForDirectUpdate(_ next: BundleInfo) -> DirectUpdateResult {
2529
+ // Recheck the active bundle and stage under nextBundleLock (like queueBundleForNextBackgroundInstall),
2530
+ // so a concurrent JS set() of the same bundle is not staged and reloaded a second time.
2531
+ self.nextBundleLock.lock()
2532
+ let activeBundle = self.implementation.getCurrentBundle()
2533
+ if activeBundle.getId() == next.getId() {
2534
+ self.nextBundleLock.unlock()
2535
+ logger.info("Downloaded bundle \(next.getId()) is already active; skipping direct update.")
2536
+ return .alreadyActive
2537
+ }
2538
+ // setBundleError takes nextBundleLock, so this status check is ordered with manual error marks.
2539
+ if self.implementation.getBundleInfo(id: next.getId()).isErrorStatus() {
2540
+ self.nextBundleLock.unlock()
2541
+ logger.error("Downloaded bundle \(next.getId()) was marked as error; skipping direct update.")
2542
+ return .rejectedError
2543
+ }
2544
+ let previousState = self.implementation.captureResetState()
2545
+ let previousBundleName = activeBundle.getVersionName()
2002
2546
  guard self.implementation.stagePendingReload(bundle: next) else {
2003
2547
  self.implementation.restoreResetState(previousState)
2548
+ self.nextBundleLock.unlock()
2004
2549
  logger.error("Direct update failed to stage downloaded bundle: \(next.toString())")
2005
- return false
2006
- }
2007
-
2008
- if self.reloadCurrentBundle() {
2550
+ return .failed
2551
+ }
2552
+ self.activeBundleGeneration &+= 1
2553
+ let stagedActiveGeneration = self.activeBundleGeneration
2554
+ let stagedQueueGeneration = self.queuedBundleGeneration
2555
+ self.nextBundleLock.unlock()
2556
+
2557
+ // The reload hops to the main thread, so it must not run under nextBundleLock.
2558
+ let reloaded = self.reloadCurrentBundle()
2559
+
2560
+ self.nextBundleLock.lock()
2561
+ // A concurrent set() activated another bundle (and reloads it itself): it owns the active state.
2562
+ guard self.activeBundleGeneration == stagedActiveGeneration else {
2563
+ self.nextBundleLock.unlock()
2564
+ logger.info("Direct update of \(next.getId()) was superseded by a concurrent set() during reload.")
2565
+ return .superseded
2566
+ }
2567
+ // A concurrent next() only changed the queue: keep the app's choice, but still finish (or undo) activation.
2568
+ let appChangedQueue = self.queuedBundleGeneration != stagedQueueGeneration
2569
+ // setBundleError (ordered by nextBundleLock) may have failed this bundle during the reload: roll it back.
2570
+ let markedErrorDuringReload = self.implementation.getBundleInfo(id: next.getId()).isErrorStatus()
2571
+ if reloaded && !markedErrorDuringReload {
2572
+ if !appChangedQueue {
2573
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
2574
+ }
2575
+ // Publish while holding the lock so a later set() cannot emit its event before this one.
2576
+ self.notifyBundleSet(next)
2577
+ self.nextBundleLock.unlock()
2009
2578
  self.implementation.finalizePendingReload(bundle: next, previousBundleName: previousBundleName)
2010
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
2011
- return true
2579
+ return .applied
2012
2580
  }
2013
-
2014
- self.implementation.restoreResetState(previousState)
2581
+ self.restoreResetStateKeepingAppQueue(previousState, appChangedQueue: appChangedQueue)
2582
+ self.nextBundleLock.unlock()
2015
2583
  self.restoreLiveBundleStateAfterFailedReload()
2584
+ if markedErrorDuringReload {
2585
+ logger.error("Bundle \(next.getId()) was marked as error during the direct update reload; restored the previous bundle.")
2586
+ return .rejectedError
2587
+ }
2016
2588
  logger.error("Direct update reload failed after staging bundle: \(next.toString())")
2017
- return false
2589
+ return appChangedQueue ? .failedKeepingAppQueue : .failed
2018
2590
  }
2019
2591
 
2020
2592
  @objc func next(_ call: CAPPluginCall) {
@@ -2024,7 +2596,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2024
2596
  return
2025
2597
  }
2026
2598
  logger.info("Setting next active id \(id)")
2027
- if !self.implementation.setNextBundle(next: id) {
2599
+ self.nextBundleLock.lock()
2600
+ let didSetNext = self.implementation.setNextBundle(next: id)
2601
+ if didSetNext {
2602
+ self.queuedBundleGeneration &+= 1
2603
+ }
2604
+ self.nextBundleLock.unlock()
2605
+ if !didSetNext {
2028
2606
  logger.error("Set next version failed. id \(id) does not exist.")
2029
2607
  call.reject("Set next version failed. id \(id) does not exist.")
2030
2608
  } else {
@@ -2038,7 +2616,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2038
2616
  call.reject("Set called without id")
2039
2617
  return
2040
2618
  }
2619
+ self.nextBundleLock.lock()
2041
2620
  let res = implementation.set(id: id)
2621
+ if res {
2622
+ self.activeBundleGeneration &+= 1
2623
+ // The bundle is now active: it must not stay reported as the pending next bundle.
2624
+ self.implementation.clearNextBundleIfCurrent()
2625
+ }
2626
+ self.nextBundleLock.unlock()
2042
2627
  logger.info("Set active bundle: \(id)")
2043
2628
  if !res {
2044
2629
  let bundle = self.implementation.getBundleInfo(id: id)
@@ -2054,8 +2639,6 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2054
2639
  call.reject("Update failed, id \(id) doesn't exist")
2055
2640
  return
2056
2641
  }
2057
- // The bundle is now active: it must not stay reported as the pending next bundle.
2058
- self.implementation.clearNextBundleIfCurrent()
2059
2642
  if self.previewSessionEnabled {
2060
2643
  let bundle = self.implementation.getBundleInfo(id: id)
2061
2644
  _ = self.recordPreviewBundle(bundle)
@@ -2468,7 +3051,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2468
3051
  }
2469
3052
 
2470
3053
  private func leavePreviewSessionWithoutReload(keepPreviewGuard: Bool = false) -> Bool {
2471
- guard let previewFallbackBundle = self.resolvePreviewFallbackBundle(reason: "preview deeplink launch") else {
3054
+ // Launch-time routing: the startup version floor runs afterwards and reports a below-native fallback.
3055
+ guard let previewFallbackBundle = self.resolvePreviewFallbackBundle(
3056
+ reason: "preview deeplink launch",
3057
+ enforceVersionFloor: false
3058
+ ) else {
2472
3059
  return false
2473
3060
  }
2474
3061
  guard self.implementation.stagePreviewFallbackReload(bundle: previewFallbackBundle) else {
@@ -2547,15 +3134,19 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2547
3134
  return false
2548
3135
  }
2549
3136
 
2550
- private func resolvePreviewFallbackBundle(reason: String) -> BundleInfo? {
3137
+ private func resolvePreviewFallbackBundle(reason: String, enforceVersionFloor: Bool = true) -> BundleInfo? {
2551
3138
  let fallback = self.implementation.getPreviewFallbackBundle()
2552
- if let fallback, !fallback.isErrorStatus(), self.implementation.canSet(bundle: fallback) {
3139
+ let usable = fallback.map { !$0.isErrorStatus() && self.implementation.canSet(bundle: $0) } ?? false
3140
+ // A native upgrade during preview can leave the fallback below the version floor; never reactivate it.
3141
+ if let fallback, usable, !enforceVersionFloor || self.fallbackMeetsVersionFloor(fallback) {
2553
3142
  return fallback
2554
3143
  }
2555
3144
 
2556
3145
  if let fallback {
2557
3146
  if fallback.isErrorStatus() {
2558
3147
  logger.warn("Preview fallback bundle is in error state for \(reason). Falling back to builtin bundle.")
3148
+ } else if usable {
3149
+ logger.warn("Preview fallback bundle is below the native version for \(reason). Falling back to builtin bundle.")
2559
3150
  } else {
2560
3151
  logger.warn("Preview fallback bundle is not installable for \(reason). Falling back to builtin bundle.")
2561
3152
  }
@@ -2572,6 +3163,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2572
3163
  return nil
2573
3164
  }
2574
3165
 
3166
+ func fallbackMeetsVersionFloor(_ fallback: BundleInfo) -> Bool {
3167
+ if fallback.isBuiltin() {
3168
+ return true
3169
+ }
3170
+ return (try? self.implementation.requireVersionNotBelowBuiltin(fallback.getVersionName())) != nil
3171
+ }
3172
+
2575
3173
  private func endPreviewSession(keepPreviewGuard: Bool = false) {
2576
3174
  let previousShakeMenuEnabled = UserDefaults.standard.object(forKey: self.previewPreviousShakeMenuDefaultsKey) as? Bool
2577
3175
  ?? self.getBooleanConfig("shakeMenu", defaultValue: false)
@@ -3001,6 +3599,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3001
3599
  }
3002
3600
  let res = implementation.delete(id: id)
3003
3601
  if res {
3602
+ self.downloadLock.lock()
3603
+ self.completedDownloadFingerprintsByBundleId.removeValue(forKey: id)
3604
+ self.downloadLock.unlock()
3004
3605
  call.resolve()
3005
3606
  } else {
3006
3607
  logger.error("Delete failed, id \(id) doesn't exist or it cannot be deleted (perhaps it is the 'next' bundle)")
@@ -3033,7 +3634,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3033
3634
  if self._isAutoUpdateEnabled() {
3034
3635
  logger.warn("setBundleError used while autoUpdate is enabled; this method is intended for manual mode")
3035
3636
  }
3637
+ // Ordered with automatic-update commits, which recheck ERROR status under nextBundleLock.
3638
+ self.nextBundleLock.lock()
3036
3639
  implementation.setError(bundle: bundle)
3640
+ self.nextBundleLock.unlock()
3037
3641
  let updated = implementation.getBundleInfo(id: id)
3038
3642
  call.resolve(["bundle": updated.toJSON()])
3039
3643
  }
@@ -3163,8 +3767,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3163
3767
  logger.info("Download already in progress, skipping duplicate download request")
3164
3768
  return "already_running"
3165
3769
  }
3166
- self.backgroundDownload()
3167
- return "queued"
3770
+ switch self.backgroundDownload() {
3771
+ case .queued:
3772
+ return "queued"
3773
+ case .alreadyRunning:
3774
+ return "already_running"
3775
+ case .unavailable:
3776
+ return "unavailable"
3777
+ }
3168
3778
  }
3169
3779
 
3170
3780
  @objc func triggerUpdateCheck(_ call: CAPPluginCall) {
@@ -3374,7 +3984,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3374
3984
  // If developer wants to reset to the last successful bundle, and that bundle is not
3375
3985
  // the built-in bundle, set it as the bundle to use and reload.
3376
3986
  if toLastSuccessful && !fallback.isBuiltin() {
3377
- if self.implementation.canSet(bundle: fallback) {
3987
+ // A last successful bundle below the native version floor cannot be activated: use builtin instead.
3988
+ if self.implementation.canSet(bundle: fallback) && self.fallbackMeetsVersionFloor(fallback) {
3378
3989
  self.implementation.prepareResetStateForTransition()
3379
3990
  logger.info("Resetting to: \(fallback.toString())")
3380
3991
  if self.implementation.set(bundle: fallback) && self.reloadCurrentBundle() {
@@ -3560,8 +4171,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3560
4171
  return
3561
4172
  }
3562
4173
  self.semaphoreDown()
4174
+ self.nextBundleLock.lock()
3563
4175
  let bundle = self.implementation.getCurrentBundle()
3564
4176
  self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
4177
+ self.nextBundleLock.unlock()
3565
4178
  self.reportAppLaunchReady(bundle)
3566
4179
  logger.info("Current bundle loaded successfully. [notifyAppReady was called] \(bundle.toString())")
3567
4180
  self.clearIncomingPreviewTransition()
@@ -4429,13 +5042,91 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4429
5042
  isAutoUpdateModeEnabled(autoUpdateMode) && autoUpdateMode != autoUpdateModeOnlyDownload
4430
5043
  }
4431
5044
 
4432
- /// Incomplete leftovers must be downloaded again. Android already skips
4433
- /// `DOWNLOADING` here; iOS used to treat them as ready, then `setNextBundle`
4434
- /// failed quietly and the update never applied.
5045
+ /// Incomplete leftovers that coalescing may delete when no in-process download owns the version.
4435
5046
  static func shouldRetryDownloadForExistingBundle(_ bundle: BundleInfo) -> Bool {
4436
5047
  bundle.isDeleted() || bundle.isDeleting() || bundle.isDownloading()
4437
5048
  }
4438
5049
 
5050
+ private func shouldRetryDownloadForExistingBundle(
5051
+ _ bundle: BundleInfo,
5052
+ latestVersionName: String,
5053
+ current: BundleInfo
5054
+ ) -> Bool {
5055
+ if bundle.isDownloaded() && !bundle.isDownloading() && !bundle.isErrorStatus()
5056
+ && self.implementation.isBundleOnDisk(id: bundle.getId()) {
5057
+ return false
5058
+ }
5059
+ if bundle.isDownloading() && self.isVersionDownloadInProgress(version: latestVersionName) {
5060
+ if !self.implementation.isInterruptedDownloadBundle(bundleId: bundle.getId()) {
5061
+ return false
5062
+ }
5063
+ }
5064
+ // A usable queued bundle of this version takes precedence over a tombstone; an unusable one must not veto it.
5065
+ if bundle.isDeleted() || bundle.isDeleting(),
5066
+ self.usableQueuedBundle(latestVersionName: latestVersionName, excluding: bundle.getId()) != nil {
5067
+ return false
5068
+ }
5069
+ let bundleOnDisk = self.implementation.isBundleOnDisk(id: bundle.getId())
5070
+ let retryCount = self.implementation.incompleteDownloadRetryCount(version: latestVersionName)
5071
+ let integrityBlocked = self.implementation.isIntegrityBlockedVersion(version: latestVersionName)
5072
+ let isCurrent = current.getId() == bundle.getId()
5073
+ && current.getVersionName() == latestVersionName
5074
+ && current.getStatus() == BundleStatus.SUCCESS.storedValue
5075
+ let isQueuedNext = self.implementation.getNextBundle()?.getId() == bundle.getId()
5076
+ let interrupted = self.implementation.isInterruptedDownloadBundle(bundleId: bundle.getId())
5077
+ return CapgoUpdater.shouldRetryDownloadForExistingBundle(
5078
+ bundle,
5079
+ bundleOnDisk: bundleOnDisk,
5080
+ incompleteRetryCount: retryCount,
5081
+ integrityBlocked: integrityBlocked,
5082
+ interruptedDownloadFailure: interrupted,
5083
+ isCurrentBundle: isCurrent,
5084
+ isQueuedNext: isQueuedNext
5085
+ )
5086
+ }
5087
+
5088
+ private func shouldRetryDownloadForMissingBundle(latestVersionName: String) -> Bool {
5089
+ return self.implementation.incompleteDownloadRetryCount(version: latestVersionName) < CapgoUpdater.maxIncompleteDownloadRetries
5090
+ }
5091
+
5092
+ /// The queued next bundle of this version when it is installable (stored, on disk, not failed or deleted).
5093
+ private func usableQueuedBundle(latestVersionName: String, excluding bundleId: String) -> BundleInfo? {
5094
+ guard let queued = self.implementation.getNextBundle(),
5095
+ latestVersionName == queued.getVersionName(),
5096
+ bundleId != queued.getId(),
5097
+ !queued.isDeleted(),
5098
+ !queued.isDeleting(),
5099
+ !queued.isErrorStatus(),
5100
+ !queued.isDownloading(),
5101
+ self.implementation.isBundleOnDisk(id: queued.getId()) else {
5102
+ return nil
5103
+ }
5104
+ return queued
5105
+ }
5106
+
5107
+ private func preferredAutoUpdateBundle(existing: BundleInfo?, latestVersionName: String, offeredZipChecksum: String? = nil) -> BundleInfo? {
5108
+ guard let existing else {
5109
+ return nil
5110
+ }
5111
+ // A usable lookup result whose ZIP checksum matches the offer is the right bundle: a queued same-version
5112
+ // bundle with other content would only fail the checksum gate (which still runs before activation).
5113
+ if let offeredZipChecksum, !offeredZipChecksum.isEmpty,
5114
+ existing.getChecksum() == offeredZipChecksum,
5115
+ !existing.isErrorStatus(), !existing.isDeleted(), !existing.isDeleting(), !existing.isDownloading(),
5116
+ self.implementation.isBundleOnDisk(id: existing.getId()) {
5117
+ return existing
5118
+ }
5119
+ // Prefer the queued bundle only when it is usable; an errored or missing queued bundle must not
5120
+ // displace a usable lookup result.
5121
+ if let queued = self.usableQueuedBundle(latestVersionName: latestVersionName, excluding: existing.getId()) {
5122
+ return queued
5123
+ }
5124
+ if existing.isDeleted() || existing.isDeleting() {
5125
+ return nil
5126
+ }
5127
+ return existing
5128
+ }
5129
+
4439
5130
  static func isDirectUpdateMode(_ directUpdateMode: String) -> Bool {
4440
5131
  directUpdateMode == autoUpdateModeInstall || directUpdateMode == autoUpdateModeLaunch || directUpdateMode == autoUpdateModeAlways
4441
5132
  }
@@ -4518,6 +5209,24 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4518
5209
  )
4519
5210
  }
4520
5211
 
5212
+ func recordCompletedZipDownloadForTesting(bundleId: String) {
5213
+ self.recordCompletedDownloadFingerprint(bundleId: bundleId, fingerprint: .zip)
5214
+ }
5215
+
5216
+ var completedDownloadFingerprintIdsForTesting: Set<String> {
5217
+ self.downloadLock.lock()
5218
+ defer { self.downloadLock.unlock() }
5219
+ return Set(self.completedDownloadFingerprintsByBundleId.keys)
5220
+ }
5221
+
5222
+ func queueBuiltinBundleAsNextForTesting() -> Bool {
5223
+ self.queueBuiltinBundleAsNext()
5224
+ }
5225
+
5226
+ func installNextForTesting() -> Bool {
5227
+ self.installNext()
5228
+ }
5229
+
4521
5230
  func setAutoUpdateModeForTesting(_ autoUpdateMode: String) {
4522
5231
  self.autoUpdateMode = Self.normalizedAutoUpdateMode(autoUpdateMode)
4523
5232
  self.autoUpdate = Self.isAutoUpdateModeEnabled(self.autoUpdateMode)
@@ -4583,6 +5292,22 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4583
5292
  self.getOnLaunchDirectUpdateUsed()
4584
5293
  }
4585
5294
 
5295
+ func setVersionDownloadInProgressForTesting(version: String) {
5296
+ downloadLock.lock()
5297
+ defer { downloadLock.unlock() }
5298
+ downloadInProgress = true
5299
+ downloadActiveVersionName = version
5300
+ downloadStartTime = Date()
5301
+ }
5302
+
5303
+ func shouldRetryDownloadForExistingBundleForTesting(
5304
+ _ bundle: BundleInfo,
5305
+ latestVersionName: String,
5306
+ current: BundleInfo
5307
+ ) -> Bool {
5308
+ self.shouldRetryDownloadForExistingBundle(bundle, latestVersionName: latestVersionName, current: current)
5309
+ }
5310
+
4586
5311
  /// Emits the `breakingAvailable` updater event for `version`. Empty versions are skipped.
4587
5312
  private func notifyBreakingEvents(version: String) {
4588
5313
  guard !version.isEmpty else {
@@ -4737,6 +5462,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4737
5462
  downloadLock.lock()
4738
5463
  defer { downloadLock.unlock() }
4739
5464
  downloadInProgress = false
5465
+ downloadActiveVersionName = nil
4740
5466
  downloadStartTime = nil
4741
5467
 
4742
5468
  self.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate: plannedDirectUpdate)
@@ -4748,7 +5474,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4748
5474
  self.notifyListenersOnMain(failureEvent, data: ["version": latestVersionName])
4749
5475
  }
4750
5476
  if notifyNoNeedUpdate {
4751
- self.notifyListenersOnMain("noNeedUpdate", data: ["bundle": current.toJSON()])
5477
+ // Retained like updateAvailable/appReady: the check can finish before the JS listener attaches.
5478
+ self.notifyListenersOnMain("noNeedUpdate", data: ["bundle": current.toJSON()], retainUntilConsumed: true)
4752
5479
  }
4753
5480
  self.sendReadyToJs(current: current, msg: msg)
4754
5481
  logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
@@ -4777,10 +5504,35 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4777
5504
  return true
4778
5505
  }
4779
5506
 
5507
+ private func isVersionDownloadInProgress(version: String) -> Bool {
5508
+ downloadLock.lock()
5509
+ defer { downloadLock.unlock() }
5510
+
5511
+ guard downloadInProgress, downloadActiveVersionName == version else {
5512
+ return false
5513
+ }
5514
+
5515
+ if let startTime = downloadStartTime {
5516
+ let elapsed = Date().timeIntervalSince(startTime)
5517
+ if elapsed > downloadTimeout {
5518
+ self.logger.warn(
5519
+ "Download for \(version) exceeded timeout of \(downloadTimeout) seconds. Clearing stuck state."
5520
+ )
5521
+ downloadInProgress = false
5522
+ downloadActiveVersionName = nil
5523
+ downloadStartTime = nil
5524
+ return false
5525
+ }
5526
+ }
5527
+
5528
+ return true
5529
+ }
5530
+
4780
5531
  private func clearDownloadInProgressState() {
4781
5532
  downloadLock.lock()
4782
5533
  defer { downloadLock.unlock() }
4783
5534
  downloadInProgress = false
5535
+ downloadActiveVersionName = nil
4784
5536
  downloadStartTime = nil
4785
5537
  }
4786
5538
 
@@ -4805,15 +5557,35 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4805
5557
  }
4806
5558
 
4807
5559
  func runGetLatestWork(_ work: @escaping () -> Void) {
4808
- DispatchQueue.global(qos: .background).async(execute: work)
5560
+ // Explicit getLatest() checks are user-visible cold-start / foreground work.
5561
+ // Using `.background` allows iOS QoS scheduling to starve them behind lower-priority tasks.
5562
+ DispatchQueue.global(qos: .userInitiated).async(execute: work)
5563
+ }
5564
+
5565
+ enum BackgroundDownloadAdmission {
5566
+ case queued
5567
+ /// Another auto-update download already owns the in-progress flag.
5568
+ case alreadyRunning
5569
+ /// Nothing was scheduled (preview session, invalid update URL).
5570
+ case unavailable
4809
5571
  }
4810
5572
 
4811
- func backgroundDownload() {
5573
+ @discardableResult
5574
+ func backgroundDownload() -> BackgroundDownloadAdmission {
4812
5575
  if self.shouldBlockAutoUpdateForPreviewSession() {
4813
- return
5576
+ return .unavailable
4814
5577
  }
4815
- // Set download in progress flag (thread-safe)
5578
+ // Test and set the in-progress flag in one lock section so two checks cannot both start
5579
+ // (and both charge a retry for) the same version.
4816
5580
  downloadLock.lock()
5581
+ if downloadInProgress {
5582
+ let timedOut = downloadStartTime.map { Date().timeIntervalSince($0) > downloadTimeout } ?? false
5583
+ if !timedOut {
5584
+ downloadLock.unlock()
5585
+ logger.info("Auto-update download already in progress, skipping this check")
5586
+ return .alreadyRunning
5587
+ }
5588
+ }
4817
5589
  downloadInProgress = true
4818
5590
  downloadStartTime = Date()
4819
5591
  downloadLock.unlock()
@@ -4835,7 +5607,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4835
5607
  defer { downloadLock.unlock() }
4836
5608
  downloadInProgress = false
4837
5609
  downloadStartTime = nil
4838
- return
5610
+ return .unavailable
4839
5611
  }
4840
5612
 
4841
5613
  self.runBackgroundDownloadWork {
@@ -4893,7 +5665,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4893
5665
  self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will apply later.")
4894
5666
  }
4895
5667
  self.logger.info("Setting next bundle to builtin")
4896
- _ = self.implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
5668
+ _ = self.queueBuiltinBundleAsNext()
4897
5669
  self.endBackGroundTaskWithNotif(
4898
5670
  msg: "Next update will be to builtin version",
4899
5671
  latestVersionName: res.version,
@@ -4958,43 +5730,313 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4958
5730
  )
4959
5731
  return
4960
5732
  }
4961
- var nextImpl = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
4962
- let needsDownload = nextImpl.map(Self.shouldRetryDownloadForExistingBundle) ?? true
5733
+ var prebuiltManifestDescriptor: VersionDownloadDescriptor?
5734
+ var requestedManifestEntries: [ManifestFingerprintEntry]?
5735
+ if let manifest = res.manifest {
5736
+ let descriptor = try self.validateAndBuildDownloadDescriptor(
5737
+ url: downloadUrl,
5738
+ version: latestVersionName,
5739
+ sessionKey: sessionKey,
5740
+ expectedZipChecksum: "",
5741
+ manifestEntries: manifest
5742
+ )
5743
+ prebuiltManifestDescriptor = descriptor
5744
+ if case let .manifest(entries, _) = descriptor {
5745
+ requestedManifestEntries = entries
5746
+ }
5747
+ }
5748
+ let versionSnapshot = self.snapshotVersionDownloadState(
5749
+ version: latestVersionName,
5750
+ requestedManifest: requestedManifestEntries
5751
+ )
5752
+ let inFlightDownload = versionSnapshot.inFlight
5753
+ var didCoalesceDownload = false
5754
+ var downloadedByThisCheck = false
5755
+ var expectedZipChecksum: String?
5756
+
5757
+ let diskMatch = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
5758
+ var nextImpl = diskMatch ?? self.implementation.findRegistryBundleByVersionName(version: latestVersionName)
5759
+ // A registry-only DOWNLOADING row (no bundle directory yet) may be a live manual download(), which
5760
+ // the auto check does not track: only launch reconciliation's interruption marker proves it is
5761
+ // abandoned, so leave it alone otherwise. An in-process slot is joined through coalescing instead.
5762
+ if !inFlightDownload, diskMatch == nil, let registryRow = nextImpl, registryRow.isDownloading(),
5763
+ !self.implementation.isInterruptedDownloadBundle(bundleId: registryRow.getId()) {
5764
+ self.logger.info("Latest version has a download in progress, skipping this check.")
5765
+ self.endBackGroundTaskWithNotif(
5766
+ msg: "Latest version is already downloading.",
5767
+ latestVersionName: latestVersionName,
5768
+ current: current,
5769
+ error: false,
5770
+ plannedDirectUpdate: plannedDirectUpdate,
5771
+ sendStats: false,
5772
+ notifyNoNeedUpdate: false
5773
+ )
5774
+ return
5775
+ }
5776
+ // The lookup returns the first same-version row: a usable queued bundle beats a failed or
5777
+ // interrupted row, so no retry is charged when an installable bundle already exists.
5778
+ if let found = nextImpl,
5779
+ found.isErrorStatus() || found.isDeleted() || found.isDeleting() || found.isDownloading()
5780
+ || !self.implementation.isBundleOnDisk(id: found.getId()),
5781
+ let queued = self.usableQueuedBundle(latestVersionName: latestVersionName, excluding: found.getId()) {
5782
+ nextImpl = queued
5783
+ }
5784
+ // A retained ERROR copy blocks automatic updates unless it is an interrupted-download retry
5785
+ // that is still under the retry cap. Main's coalescing tests rely on that block, including when
5786
+ // the ERROR copy is listed after a newer same-version bundle.
5787
+ let retainedError = versionSnapshot.retainedErrorBundle
5788
+ let retainedErrorBlocksAutoUpdate: Bool
5789
+ if let retainedError {
5790
+ let interrupted = self.implementation.isInterruptedDownloadBundle(bundleId: retainedError.getId())
5791
+ let retryable = self.shouldRetryDownloadForExistingBundle(
5792
+ retainedError,
5793
+ latestVersionName: latestVersionName,
5794
+ current: current
5795
+ )
5796
+ retainedErrorBlocksAutoUpdate = !(interrupted && retryable)
5797
+ } else {
5798
+ retainedErrorBlocksAutoUpdate = false
5799
+ }
5800
+ if retainedErrorBlocksAutoUpdate, let retainedError {
5801
+ nextImpl = retainedError
5802
+ } else if let requestedManifestEntries,
5803
+ let snapshotExisting = versionSnapshot.existing,
5804
+ versionSnapshot.recordedFingerprint == .manifest(requestedManifestEntries) {
5805
+ // The snapshot prefers a complete copy whose recorded manifest matches this request,
5806
+ // even when an earlier same-version row is a different complete manifest.
5807
+ nextImpl = snapshotExisting
5808
+ } else if nextImpl == nil {
5809
+ nextImpl = versionSnapshot.existing
5810
+ }
5811
+ var prNeedsDownload = nextImpl.map {
5812
+ self.shouldRetryDownloadForExistingBundle($0, latestVersionName: latestVersionName, current: current)
5813
+ } ?? self.shouldRetryDownloadForMissingBundle(latestVersionName: latestVersionName)
5814
+ // A copy whose recorded in-process manifest matches this request is complete, even when a
5815
+ // disk lookup does not see that later same-version row. Do not take a download slot for it.
5816
+ if let nextImpl,
5817
+ let requestedManifestEntries,
5818
+ !nextImpl.isErrorStatus(),
5819
+ !Self.shouldRetryDownloadForExistingBundle(nextImpl) {
5820
+ self.downloadLock.lock()
5821
+ let nextImplRecordedFingerprint = self.completedDownloadFingerprintsByBundleId[nextImpl.getId()]
5822
+ self.downloadLock.unlock()
5823
+ if nextImplRecordedFingerprint == .manifest(requestedManifestEntries) {
5824
+ prNeedsDownload = false
5825
+ }
5826
+ }
5827
+ // A copy completed in this process for a manifest request must carry the same manifest; a ZIP
5828
+ // or a different manifest is a mismatch. A copy with no record predates this process and keeps
5829
+ // the legacy version-name reuse.
5830
+ let hasMismatchedManifestFingerprint: Bool
5831
+ if let existing = nextImpl,
5832
+ !existing.isErrorStatus(),
5833
+ !Self.shouldRetryDownloadForExistingBundle(existing),
5834
+ let requestedManifestEntries,
5835
+ let recorded = versionSnapshot.recordedFingerprint {
5836
+ hasMismatchedManifestFingerprint = recorded != .manifest(requestedManifestEntries)
5837
+ } else {
5838
+ hasMismatchedManifestFingerprint = false
5839
+ }
5840
+ let needsDownload = !retainedErrorBlocksAutoUpdate
5841
+ && (prNeedsDownload || inFlightDownload || hasMismatchedManifestFingerprint)
5842
+ if !needsDownload, !retainedErrorBlocksAutoUpdate, let existing = nextImpl {
5843
+ let offeredZipChecksum = res.manifest == nil
5844
+ ? try? CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
5845
+ : nil
5846
+ nextImpl = self.preferredAutoUpdateBundle(
5847
+ existing: existing,
5848
+ latestVersionName: latestVersionName,
5849
+ offeredZipChecksum: offeredZipChecksum
5850
+ )
5851
+ }
5852
+ if !needsDownload, !inFlightDownload, let active = nextImpl, active.isDownloading() {
5853
+ // Another download still owns this row: it is neither verified nor reusable yet.
5854
+ self.logger.info("Latest bundle is still downloading elsewhere, skipping reuse.")
5855
+ self.endBackGroundTaskWithNotif(
5856
+ msg: "Latest version is already downloading.",
5857
+ latestVersionName: latestVersionName,
5858
+ current: current,
5859
+ error: false,
5860
+ plannedDirectUpdate: plannedDirectUpdate,
5861
+ sendStats: false,
5862
+ notifyNoNeedUpdate: false
5863
+ )
5864
+ return
5865
+ }
5866
+ var retryDownloadSlot = false
4963
5867
  if needsDownload {
4964
- if let existing = nextImpl {
4965
- self.logger.info("Latest bundle already exists in incomplete state (\(existing.getStatus())) and will be deleted, download will overwrite it.")
4966
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
4967
- let deleted = self.implementation.delete(id: existing.getId(), removeInfo: true)
4968
- if deleted {
4969
- self.logger.info("Incomplete bundle deleted: \(existing.toString())")
4970
- } else {
4971
- self.logger.error("Failed to delete incomplete bundle: \(existing.toString())")
4972
- }
5868
+ if prNeedsDownload,
5869
+ !inFlightDownload,
5870
+ self.implementation.incompleteDownloadRetryCount(version: latestVersionName) >= CapgoUpdater.maxIncompleteDownloadRetries {
5871
+ self.logger.error("Latest bundle exceeded incomplete download retries. Aborting update.")
5872
+ self.endBackGroundTaskWithNotif(
5873
+ msg: "Latest version is in error state. Aborting update.",
5874
+ latestVersionName: latestVersionName,
5875
+ current: current,
5876
+ plannedDirectUpdate: plannedDirectUpdate,
5877
+ sendStats: false
5878
+ )
5879
+ return
4973
5880
  }
4974
- self.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate: plannedDirectUpdate)
4975
- if res.manifest != nil {
4976
- nextImpl = try self.implementation.downloadManifest(manifest: res.manifest!, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4977
- } else {
4978
- if res.checksum.isEmpty {
4979
- self.logger.error("No checksum provided")
4980
- self.implementation.sendStats(action: "checksum_required", versionName: latestVersionName)
4981
- self.endBackGroundTaskWithNotif(
4982
- msg: "Checksum required",
5881
+ if res.manifest == nil && res.checksum.isEmpty {
5882
+ self.deleteStaleIncompleteBundleIfIdle(version: latestVersionName)
5883
+ self.logger.error("No checksum provided")
5884
+ self.implementation.sendStats(action: "checksum_required", versionName: latestVersionName)
5885
+ self.endBackGroundTaskWithNotif(
5886
+ msg: "Checksum required",
5887
+ latestVersionName: latestVersionName,
5888
+ current: current,
5889
+ plannedDirectUpdate: plannedDirectUpdate
5890
+ )
5891
+ return
5892
+ }
5893
+ if res.manifest == nil {
5894
+ expectedZipChecksum = try CryptoCipher.decryptChecksum(
5895
+ checksum: res.checksum,
5896
+ publicKey: self.implementation.publicKey
5897
+ )
5898
+ }
5899
+ let descriptor = try prebuiltManifestDescriptor ?? self.validateAndBuildDownloadDescriptor(
5900
+ url: downloadUrl,
5901
+ version: latestVersionName,
5902
+ sessionKey: sessionKey,
5903
+ expectedZipChecksum: expectedZipChecksum ?? "",
5904
+ manifestEntries: res.manifest
5905
+ )
5906
+ let sourceIdentity = Self.downloadSourceIdentity(url: downloadUrl, manifestEntries: res.manifest)
5907
+ let (resolvedBundle, coalesced) = try self.coalesceVersionDownload(
5908
+ version: latestVersionName,
5909
+ descriptor: descriptor,
5910
+ sourceIdentity: sourceIdentity
5911
+ ) {
5912
+ let storedForVersion = self.implementation.getBundleInfosByVersionName(version: latestVersionName)
5913
+ let hasReusableStoredBundle = storedForVersion.contains { candidate in
5914
+ if Self.shouldRetryDownloadForExistingBundle(candidate) {
5915
+ return false
5916
+ }
5917
+ if candidate.isErrorStatus() {
5918
+ return false
5919
+ }
5920
+ if let expectedZipChecksum {
5921
+ return !candidate.getChecksum().isEmpty && candidate.getChecksum() == expectedZipChecksum
5922
+ }
5923
+ if case let .manifest(requestedEntries, _) = descriptor {
5924
+ self.downloadLock.lock()
5925
+ let recorded = self.completedDownloadFingerprintsByBundleId[candidate.getId()]
5926
+ self.downloadLock.unlock()
5927
+ return recorded == .manifest(requestedEntries)
5928
+ }
5929
+ return false
5930
+ }
5931
+ // Reserve before deleting the record that proves the retry, and only when this slot owner
5932
+ // will replace an incomplete record rather than reuse a complete stored bundle.
5933
+ if !hasReusableStoredBundle {
5934
+ let replacesIncompleteRecord = storedForVersion.contains { candidate in
5935
+ self.shouldRetryDownloadForExistingBundle(
5936
+ candidate,
5937
+ latestVersionName: latestVersionName,
5938
+ current: current
5939
+ )
5940
+ }
5941
+ if replacesIncompleteRecord {
5942
+ retryDownloadSlot = true
5943
+ self.implementation.reserveIncompleteDownloadRetry(version: latestVersionName)
5944
+ } else if storedForVersion.isEmpty
5945
+ && (self.implementation.incompleteDownloadRetryCount(version: latestVersionName) > 0
5946
+ || self.implementation.isIntegrityBlockedVersion(version: latestVersionName)) {
5947
+ retryDownloadSlot = true
5948
+ }
5949
+ }
5950
+ if let reusable = self.findReusableStoredBundle(
5951
+ version: latestVersionName,
5952
+ descriptor: descriptor,
5953
+ expectedZipChecksum: expectedZipChecksum
5954
+ ) {
5955
+ return reusable
5956
+ }
5957
+ // Slot owner only: remove retryable incomplete leftovers, including interrupted ERROR rows,
5958
+ // before the replacement transfer. Do this after the reusable check so an in-process
5959
+ // download is not deleted by a coalesced waiter.
5960
+ for candidate in self.implementation.getBundleInfosByVersionName(version: latestVersionName) {
5961
+ guard self.shouldRetryDownloadForExistingBundle(
5962
+ candidate,
4983
5963
  latestVersionName: latestVersionName,
4984
- current: current,
4985
- plannedDirectUpdate: plannedDirectUpdate
5964
+ current: current
5965
+ ) else {
5966
+ continue
5967
+ }
5968
+ self.logger.info("Latest bundle already exists in incomplete state (\(candidate.getStatus())) and will be deleted, download will overwrite it.")
5969
+ self.implementation.clearNextBundleIfMatches(bundleId: candidate.getId())
5970
+ let deleted = self.implementation.delete(id: candidate.getId(), removeInfo: true)
5971
+ if deleted {
5972
+ self.logger.info("Incomplete bundle deleted: \(candidate.toString())")
5973
+ } else {
5974
+ self.logger.error("Failed to delete incomplete bundle: \(candidate.toString())")
5975
+ throw CapgoUpdater.IncompleteBundleDeletionPendingError()
5976
+ }
5977
+ }
5978
+ self.downloadLock.lock()
5979
+ self.downloadActiveVersionName = latestVersionName
5980
+ self.downloadLock.unlock()
5981
+ downloadedByThisCheck = true
5982
+ self.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate: plannedDirectUpdate)
5983
+ // Charge the retry slot once every admission check (scheme, session key, checksum metadata,
5984
+ // disk space) has passed and right before the synchronous transfer starts, so a refused offer
5985
+ // costs nothing and a started attempt that throws still counts. The charge refuses at the cap.
5986
+ let consumeRetrySlotOnStart = retryDownloadSlot
5987
+ let chargeOnTransferStart: () throws -> Void = {
5988
+ if !self.implementation.chargeIncompleteDownloadRetry(version: latestVersionName, admittedRetry: consumeRetrySlotOnStart) {
5989
+ throw CapgoUpdater.IncompleteRetryRefusedError()
5990
+ }
5991
+ }
5992
+ if let manifest = res.manifest {
5993
+ return try self.implementation.downloadManifestWithTransferHook(
5994
+ manifest: manifest,
5995
+ version: latestVersionName,
5996
+ sessionKey: sessionKey,
5997
+ link: res.link,
5998
+ comment: res.comment,
5999
+ beforeTransfer: chargeOnTransferStart
4986
6000
  )
4987
- return
4988
6001
  }
4989
- nextImpl = try self.implementation.downloadVerified(
6002
+ return try self.implementation.downloadVerifiedWithTransferHook(
4990
6003
  url: downloadUrl,
4991
6004
  version: latestVersionName,
4992
6005
  sessionKey: sessionKey,
4993
6006
  expectedChecksum: res.checksum,
4994
6007
  link: res.link,
4995
- comment: res.comment
6008
+ comment: res.comment,
6009
+ beforeTransfer: chargeOnTransferStart
4996
6010
  )
4997
6011
  }
6012
+ nextImpl = resolvedBundle
6013
+ didCoalesceDownload = coalesced
6014
+ // A copy of this version may have been marked ERROR while this check waited on the slot.
6015
+ // An interrupted-download ERROR that is still a retry candidate must not override a
6016
+ // replacement this check just produced.
6017
+ if let retainedError = self.implementation.getBundleInfosByVersionName(version: latestVersionName)
6018
+ .first(where: { $0.isErrorStatus() }) {
6019
+ let interrupted = self.implementation.isInterruptedDownloadBundle(bundleId: retainedError.getId())
6020
+ let retryable = self.shouldRetryDownloadForExistingBundle(
6021
+ retainedError,
6022
+ latestVersionName: latestVersionName,
6023
+ current: current
6024
+ )
6025
+ if !(interrupted && retryable) {
6026
+ nextImpl = retainedError
6027
+ }
6028
+ }
6029
+ }
6030
+ if nextImpl == nil && !needsDownload {
6031
+ self.logger.error("Latest bundle exceeded incomplete download retries. Aborting update.")
6032
+ self.endBackGroundTaskWithNotif(
6033
+ msg: "Latest version is in error state. Aborting update.",
6034
+ latestVersionName: latestVersionName,
6035
+ current: current,
6036
+ plannedDirectUpdate: plannedDirectUpdate,
6037
+ sendStats: false
6038
+ )
6039
+ return
4998
6040
  }
4999
6041
  guard let next = nextImpl else {
5000
6042
  self.logger.error("Error downloading file")
@@ -5007,12 +6049,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5007
6049
  return
5008
6050
  }
5009
6051
  if next.isErrorStatus() {
5010
- self.logger.error("Latest bundle already exists and is in error state. Aborting update.")
6052
+ self.logger.error("Latest bundle is in error state after download and exceeded incomplete retries. Aborting update.")
5011
6053
  self.endBackGroundTaskWithNotif(
5012
6054
  msg: "Latest version is in error state. Aborting update.",
5013
6055
  latestVersionName: latestVersionName,
5014
6056
  current: current,
5015
- plannedDirectUpdate: plannedDirectUpdate
6057
+ plannedDirectUpdate: plannedDirectUpdate,
6058
+ sendStats: false
5016
6059
  )
5017
6060
  return
5018
6061
  }
@@ -5022,16 +6065,22 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5022
6065
  return
5023
6066
  }
5024
6067
  if res.manifest == nil {
5025
- res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
6068
+ res.checksum = try expectedZipChecksum ?? CryptoCipher.decryptChecksum(
6069
+ checksum: res.checksum,
6070
+ publicKey: self.implementation.publicKey
6071
+ )
5026
6072
  CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
5027
6073
  CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: res.checksum)
5028
6074
  if next.getChecksum() != res.checksum {
5029
6075
  self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
5030
6076
  self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
5031
- let id = next.getId()
5032
- let resDel = self.implementation.delete(id: id)
5033
- if !resDel {
5034
- self.logger.error("Delete failed, id \(id) doesn't exist")
6077
+ self.implementation.markIntegrityBlockedVersion(version: latestVersionName)
6078
+ if !didCoalesceDownload {
6079
+ let id = next.getId()
6080
+ let resDel = self.implementation.delete(id: id)
6081
+ if !resDel {
6082
+ self.logger.error("Delete failed, id \(id) doesn't exist")
6083
+ }
5035
6084
  }
5036
6085
  self.endBackGroundTaskWithNotif(
5037
6086
  msg: "Error checksum",
@@ -5047,6 +6096,22 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5047
6096
  self.endBackGroundTask()
5048
6097
  return
5049
6098
  }
6099
+ // Only a bundle downloaded by this check already carries this response's link/comment.
6100
+ let resolvedNext = downloadedByThisCheck
6101
+ ? next
6102
+ : self.applyServerMetadataIfMissing(bundle: next, link: res.link, comment: res.comment)
6103
+ let activeBundle = self.implementation.getCurrentBundle()
6104
+ if activeBundle.getId() == resolvedNext.getId() {
6105
+ self.logger.info("Downloaded bundle \(resolvedNext.getId()) is already active; skipping install/queue.")
6106
+ self.endBackGroundTaskWithNotif(
6107
+ msg: "No need to update",
6108
+ latestVersionName: latestVersionName,
6109
+ current: activeBundle,
6110
+ error: false,
6111
+ plannedDirectUpdate: plannedDirectUpdate
6112
+ )
6113
+ return
6114
+ }
5050
6115
  let directUpdateAllowed = plannedDirectUpdate && self.isDirectUpdateAllowedAfterDownload(timeoutGeneration: timeoutGeneration)
5051
6116
  if directUpdateAllowed {
5052
6117
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
@@ -5056,44 +6121,85 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5056
6121
  self.endBackGroundTaskWithNotif(
5057
6122
  msg: "Update delayed until delay conditions met",
5058
6123
  latestVersionName: latestVersionName,
5059
- current: next,
6124
+ current: resolvedNext,
5060
6125
  error: false,
5061
6126
  plannedDirectUpdate: plannedDirectUpdate
5062
6127
  )
5063
6128
  return
5064
6129
  }
5065
- if self.applyDownloadedBundleForDirectUpdate(next) {
5066
- self.notifyBundleSet(next)
6130
+ let directUpdateResult = self.applyDownloadedBundleForDirectUpdate(resolvedNext)
6131
+ if directUpdateResult == .applied {
5067
6132
  self.endBackGroundTaskWithNotif(
5068
6133
  msg: "update installed",
5069
6134
  latestVersionName: latestVersionName,
5070
- current: next,
6135
+ current: resolvedNext,
5071
6136
  error: false,
5072
6137
  plannedDirectUpdate: plannedDirectUpdate
5073
6138
  )
5074
- } else if self.queueBundleForNextBackgroundInstall(next) {
5075
- self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
6139
+ } else if directUpdateResult == .alreadyActive || directUpdateResult == .superseded {
5076
6140
  self.endBackGroundTaskWithNotif(
5077
- msg: "Direct update reload failed, update will install next background",
6141
+ msg: "No need to update",
5078
6142
  latestVersionName: latestVersionName,
5079
6143
  current: self.implementation.getCurrentBundle(),
5080
6144
  error: false,
5081
6145
  plannedDirectUpdate: plannedDirectUpdate
5082
6146
  )
5083
- } else {
6147
+ } else if directUpdateResult == .rejectedError {
5084
6148
  self.endBackGroundTaskWithNotif(
5085
- msg: "Direct update reload failed, and next bundle could not be queued",
6149
+ msg: "Latest version is in error state. Aborting update.",
5086
6150
  latestVersionName: latestVersionName,
5087
- current: current,
6151
+ current: self.implementation.getCurrentBundle(),
5088
6152
  plannedDirectUpdate: plannedDirectUpdate
5089
6153
  )
6154
+ } else if directUpdateResult == .failedKeepingAppQueue {
6155
+ self.endBackGroundTaskWithNotif(
6156
+ msg: "Direct update reload failed; keeping the next bundle queued by the app",
6157
+ latestVersionName: latestVersionName,
6158
+ current: self.implementation.getCurrentBundle(),
6159
+ plannedDirectUpdate: plannedDirectUpdate
6160
+ )
6161
+ } else {
6162
+ switch self.queueBundleForNextBackgroundInstall(resolvedNext) {
6163
+ case .queued:
6164
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": resolvedNext.toJSON()])
6165
+ self.endBackGroundTaskWithNotif(
6166
+ msg: "Direct update reload failed, update will install next background",
6167
+ latestVersionName: latestVersionName,
6168
+ current: self.implementation.getCurrentBundle(),
6169
+ error: false,
6170
+ plannedDirectUpdate: plannedDirectUpdate
6171
+ )
6172
+ case .alreadyActive:
6173
+ self.endBackGroundTaskWithNotif(
6174
+ msg: "No need to update",
6175
+ latestVersionName: latestVersionName,
6176
+ current: self.implementation.getCurrentBundle(),
6177
+ error: false,
6178
+ plannedDirectUpdate: plannedDirectUpdate
6179
+ )
6180
+ case .rejectedError:
6181
+ self.endBackGroundTaskWithNotif(
6182
+ msg: "Latest version is in error state. Aborting update.",
6183
+ latestVersionName: latestVersionName,
6184
+ current: self.implementation.getCurrentBundle(),
6185
+ plannedDirectUpdate: plannedDirectUpdate
6186
+ )
6187
+ case .failed:
6188
+ self.endBackGroundTaskWithNotif(
6189
+ msg: "Direct update reload failed, and next bundle could not be queued",
6190
+ latestVersionName: latestVersionName,
6191
+ current: current,
6192
+ plannedDirectUpdate: plannedDirectUpdate
6193
+ )
6194
+ }
5090
6195
  }
5091
6196
  } else if self.shouldAutoSetNextBundle() {
5092
6197
  if plannedDirectUpdate && !directUpdateAllowed {
5093
6198
  self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will install on next app background.")
5094
6199
  }
5095
- if self.queueBundleForNextBackgroundInstall(next) {
5096
- self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()])
6200
+ switch self.queueBundleForNextBackgroundInstall(resolvedNext) {
6201
+ case .queued:
6202
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": resolvedNext.toJSON()])
5097
6203
  let installed = self.installNextIfInBackground()
5098
6204
  self.endBackGroundTaskWithNotif(
5099
6205
  msg: installed ? "update downloaded and installed in background" : "update downloaded, will install next background",
@@ -5102,7 +6208,22 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5102
6208
  error: false,
5103
6209
  plannedDirectUpdate: plannedDirectUpdate
5104
6210
  )
5105
- } else {
6211
+ case .alreadyActive:
6212
+ self.endBackGroundTaskWithNotif(
6213
+ msg: "No need to update",
6214
+ latestVersionName: latestVersionName,
6215
+ current: self.implementation.getCurrentBundle(),
6216
+ error: false,
6217
+ plannedDirectUpdate: plannedDirectUpdate
6218
+ )
6219
+ case .rejectedError:
6220
+ self.endBackGroundTaskWithNotif(
6221
+ msg: "Latest version is in error state. Aborting update.",
6222
+ latestVersionName: latestVersionName,
6223
+ current: self.implementation.getCurrentBundle(),
6224
+ plannedDirectUpdate: plannedDirectUpdate
6225
+ )
6226
+ case .failed:
5106
6227
  self.endBackGroundTaskWithNotif(
5107
6228
  msg: "Update downloaded, but next bundle could not be queued",
5108
6229
  latestVersionName: latestVersionName,
@@ -5112,7 +6233,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5112
6233
  }
5113
6234
  } else {
5114
6235
  self.logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle")
5115
- self.notifyListenersOnMain("updateAvailable", data: ["bundle": next.toJSON()], retainUntilConsumed: true)
6236
+ self.notifyListenersOnMain("updateAvailable", data: ["bundle": resolvedNext.toJSON()], retainUntilConsumed: true)
5116
6237
  self.endBackGroundTaskWithNotif(
5117
6238
  msg: "update downloaded, autoUpdate onlyDownload",
5118
6239
  latestVersionName: latestVersionName,
@@ -5123,6 +6244,27 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5123
6244
  )
5124
6245
  }
5125
6246
  return
6247
+ } catch is CapgoUpdater.IncompleteBundleDeletionPendingError {
6248
+ self.logger.error("Incomplete bundle deletion is still pending. Retrying later.")
6249
+ self.endBackGroundTaskWithNotif(
6250
+ msg: "Incomplete bundle deletion is still pending. Retrying later.",
6251
+ latestVersionName: latestVersionName,
6252
+ current: current,
6253
+ plannedDirectUpdate: plannedDirectUpdate,
6254
+ sendStats: false
6255
+ )
6256
+ return
6257
+ } catch is CapgoUpdater.IncompleteRetryRefusedError {
6258
+ // A concurrent check used the last slot: no transfer started, so no download_fail.
6259
+ self.logger.error("Latest bundle exceeded incomplete download retries. Aborting update.")
6260
+ self.endBackGroundTaskWithNotif(
6261
+ msg: "Latest version is in error state. Aborting update.",
6262
+ latestVersionName: latestVersionName,
6263
+ current: self.implementation.getCurrentBundle(),
6264
+ plannedDirectUpdate: plannedDirectUpdate,
6265
+ sendStats: false
6266
+ )
6267
+ return
5126
6268
  } catch {
5127
6269
  self.logger.error("Error downloading file \(error.localizedDescription)")
5128
6270
  let current: BundleInfo = self.implementation.getCurrentBundle()
@@ -5146,6 +6288,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5146
6288
  return
5147
6289
  }
5148
6290
  }
6291
+ return .queued
5149
6292
  }
5150
6293
 
5151
6294
  /// A download that finishes while the app is in the background (silent push,
@@ -5205,6 +6348,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5205
6348
  logger.info("Update delayed until delay conditions met")
5206
6349
  return false
5207
6350
  }
6351
+ // Decide and activate under nextBundleLock, like set(), so a concurrent direct update sees this
6352
+ // activation through activeBundleGeneration. The reload runs after releasing the lock.
6353
+ self.nextBundleLock.lock()
5208
6354
  let current: BundleInfo = self.implementation.getCurrentBundle()
5209
6355
  let next: BundleInfo? = self.implementation.getNextBundle()
5210
6356
 
@@ -5212,20 +6358,45 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5212
6358
  logger.info("Next bundle is: \(next!.toString())")
5213
6359
  let resetState = self.implementation.captureResetState()
5214
6360
  guard self.implementation.set(bundle: next!) else {
6361
+ self.nextBundleLock.unlock()
5215
6362
  logger.error("Update to bundle: \(next!.toString()) Failed!")
5216
6363
  return false
5217
6364
  }
6365
+ // The generation stays bumped on failure: generations only need to change on every transition attempt.
6366
+ self.activeBundleGeneration &+= 1
6367
+ let stagedActiveGeneration = self.activeBundleGeneration
6368
+ let stagedQueueGeneration = self.queuedBundleGeneration
6369
+ self.nextBundleLock.unlock()
5218
6370
  guard self.reloadCurrentBundle() else {
5219
- // Built-in `set` may reset fallback/next; restore the full pre-install state for retry.
5220
- self.implementation.restoreResetState(resetState)
6371
+ self.nextBundleLock.lock()
6372
+ guard self.activeBundleGeneration == stagedActiveGeneration else {
6373
+ // A concurrent activation replaced this one during the reload; keep its newer state.
6374
+ self.nextBundleLock.unlock()
6375
+ logger.error("Update to bundle: \(next!.toString()) Failed! Reload failed after a concurrent activation; keeping it")
6376
+ return false
6377
+ }
6378
+ // Built-in `set` may reset fallback/next; restore the pre-install state for retry, but keep a
6379
+ // bundle the app queued with next() during the reload.
6380
+ self.restoreResetStateKeepingAppQueue(resetState, appChangedQueue: self.queuedBundleGeneration != stagedQueueGeneration)
6381
+ self.nextBundleLock.unlock()
5221
6382
  logger.error("Update to bundle: \(next!.toString()) Failed! Reload failed, keeping it as next")
5222
6383
  return false
5223
6384
  }
6385
+ self.nextBundleLock.lock()
6386
+ guard self.activeBundleGeneration == stagedActiveGeneration else {
6387
+ // A concurrent set()/reload()/direct update activated another bundle during this reload; it owns
6388
+ // the set event and the queue, so do not publish a stale set event or clear its next bundle.
6389
+ self.nextBundleLock.unlock()
6390
+ logger.info("Background install of \(next!.getId()) was superseded by a concurrent activation.")
6391
+ return false
6392
+ }
5224
6393
  logger.info("Updated to bundle: \(next!.toString())")
5225
6394
  self.notifyBundleSet(next!)
5226
6395
  _ = self.implementation.setNextBundle(next: Optional<String>.none)
6396
+ self.nextBundleLock.unlock()
5227
6397
  return true
5228
6398
  }
6399
+ self.nextBundleLock.unlock()
5229
6400
  return false
5230
6401
  }
5231
6402