@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
@@ -66,6 +66,14 @@ private final class RealSendReadyCapacitorUpdaterPlugin: CapacitorUpdaterPlugin
66
66
  private var _appReadyNotifiedAt: Date?
67
67
  private var _appReadyNotifiedOnMainThread: Bool?
68
68
  private var _appReadyRetainUntilConsumed: Bool?
69
+ private var recordedAppReadyRawEventName: String?
70
+
71
+ /// The bridge event name the appReady notification went out under (v9: `updaterEvent`).
72
+ var appReadyRawEventName: String? {
73
+ eventLock.lock()
74
+ defer { eventLock.unlock() }
75
+ return recordedAppReadyRawEventName
76
+ }
69
77
 
70
78
  var appReadyNotifiedOnMainThread: Bool? {
71
79
  eventLock.lock()
@@ -106,6 +114,7 @@ private final class RealSendReadyCapacitorUpdaterPlugin: CapacitorUpdaterPlugin
106
114
  _appReadyNotifiedAt = Date()
107
115
  _appReadyNotifiedOnMainThread = Thread.isMainThread
108
116
  _appReadyRetainUntilConsumed = retain
117
+ recordedAppReadyRawEventName = eventName
109
118
  }
110
119
  if let payload = event.data {
111
120
  _notifiedEventPayloads[event.name] = payload
@@ -158,21 +167,37 @@ private class FreshDownloadCapgoUpdater: CapgoUpdater {
158
167
  return existingBundleValue
159
168
  }
160
169
 
170
+ /// Bundles listed after `existingBundleValue` when every same-version entry is requested.
171
+ var additionalVersionBundles: [BundleInfo] = []
172
+
173
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
174
+ ([existingBundleValue].compactMap { $0 } + additionalVersionBundles)
175
+ .filter { $0.getVersionName() == version }
176
+ }
177
+
178
+ /// Stored records returned by getBundleInfo(id:) instead of the current bundle, e.g. a bundle marked ERROR.
179
+ var storedBundleInfoOverrides: [String: BundleInfo] = [:]
180
+
161
181
  override func getBundleInfo(id: String?) -> BundleInfo {
162
182
  if id == BundleInfo.ID_BUILTIN {
163
183
  return builtinBundleValue
164
184
  }
185
+ if let id, let override = storedBundleInfoOverrides[id] {
186
+ return override
187
+ }
165
188
  return currentBundleValue
166
189
  }
167
190
 
168
- override func downloadVerified(
191
+ override func downloadVerifiedWithTransferHook(
169
192
  url _: URL,
170
193
  version _: String,
171
194
  sessionKey _: String,
172
195
  expectedChecksum _: String,
173
- link _: String? = nil,
174
- comment _: String? = nil
196
+ link _: String?,
197
+ comment _: String?,
198
+ beforeTransfer: (() throws -> Void)?
175
199
  ) throws -> BundleInfo {
200
+ try beforeTransfer?()
176
201
  downloadCalls += 1
177
202
  onDownloadStart?()
178
203
  if let downloadedBundleValue {
@@ -190,6 +215,26 @@ private class FreshDownloadCapgoUpdater: CapgoUpdater {
190
215
  return true
191
216
  }
192
217
 
218
+ override func canSet(bundle: BundleInfo) -> Bool {
219
+ if let existingBundleValue, existingBundleValue.getId() == bundle.getId() {
220
+ return existingBundleValue.getStatus() == BundleStatus.PENDING.storedValue
221
+ }
222
+ if let downloadedBundleValue, downloadedBundleValue.getId() == bundle.getId() {
223
+ return downloadedBundleValue.getStatus() == BundleStatus.PENDING.storedValue
224
+ }
225
+ return super.canSet(bundle: bundle)
226
+ }
227
+
228
+ override func isBundleOnDisk(id: String) -> Bool {
229
+ if let existingBundleValue, existingBundleValue.getId() == id {
230
+ return self.canSet(bundle: existingBundleValue)
231
+ }
232
+ if let downloadedBundleValue, downloadedBundleValue.getId() == id {
233
+ return self.canSet(bundle: downloadedBundleValue)
234
+ }
235
+ return super.isBundleOnDisk(id: id)
236
+ }
237
+
193
238
  override func setNextBundle(next: String?) -> Bool {
194
239
  setNextBundleCalls += 1
195
240
  lastSetNextBundleId = next
@@ -231,19 +276,61 @@ private final class SplashTimeoutCapgoUpdater: FreshDownloadCapgoUpdater {
231
276
  return true
232
277
  }
233
278
 
234
- override func set(bundle: BundleInfo) -> Bool {
279
+ /// Fixture-only active bundle path. Production persists the active path and the queue (NEXT_VERSION) and
280
+ /// reset-state capture/restore read and write both; this fixture models that in memory so tests never
281
+ /// leave fixture state in the shared UserDefaults.
282
+ private static let fixturePathPrefix = "fixture-bundle/"
283
+ private var fixtureFallbackBundleId = BundleInfo.ID_BUILTIN
284
+ /// Every bundle the fixture has had active, so a restored path can resolve the initial bundle too.
285
+ private var knownActiveBundles: [String: BundleInfo] = [:]
286
+
287
+ private func activate(_ bundle: BundleInfo) {
288
+ knownActiveBundles[currentBundleValue.getId()] = currentBundleValue
289
+ knownActiveBundles[bundle.getId()] = bundle
235
290
  currentBundleValue = bundle
291
+ }
292
+
293
+ override func captureResetState() -> ResetState {
294
+ knownActiveBundles[currentBundleValue.getId()] = currentBundleValue
295
+ return ResetState(
296
+ currentBundlePath: Self.fixturePathPrefix + currentBundleValue.getId(),
297
+ fallbackBundleId: fixtureFallbackBundleId,
298
+ nextBundleId: queuedBundle?.getId()
299
+ )
300
+ }
301
+
302
+ override func restoreResetState(_ state: ResetState) {
303
+ let bundles = [existingBundleValue, downloadedBundleValue, builtinBundleValue, currentBundleValue].compactMap { $0 }
304
+ if state.currentBundlePath.hasPrefix(Self.fixturePathPrefix) {
305
+ let activeId = String(state.currentBundlePath.dropFirst(Self.fixturePathPrefix.count))
306
+ if let active = knownActiveBundles[activeId] ?? bundles.first(where: { $0.getId() == activeId }) {
307
+ currentBundleValue = active
308
+ }
309
+ }
310
+ fixtureFallbackBundleId = state.fallbackBundleId
311
+ queuedBundle = state.nextBundleId.flatMap { id in bundles.first(where: { $0.getId() == id }) }
312
+ }
313
+
314
+ override func prepareResetStateForTransition() {
315
+ // Production clears the active path, fallback and queue and activates the builtin bundle.
316
+ activate(builtinBundleValue)
317
+ fixtureFallbackBundleId = BundleInfo.ID_BUILTIN
318
+ queuedBundle = nil
319
+ }
320
+
321
+ override func set(bundle: BundleInfo) -> Bool {
322
+ activate(bundle)
236
323
  return true
237
324
  }
238
325
 
239
326
  override func stagePendingReload(bundle: BundleInfo) -> Bool {
240
327
  stagePendingReloadCalls += 1
328
+ // Production staging points the current bundle at the new one; finalization only sends stats.
329
+ activate(bundle)
241
330
  return true
242
331
  }
243
332
 
244
- override func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {
245
- currentBundleValue = bundle
246
- }
333
+ override func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {}
247
334
  }
248
335
 
249
336
  private final class SplashTimeoutCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
@@ -253,9 +340,15 @@ private final class SplashTimeoutCapacitorUpdaterPlugin: TestableCapacitorUpdate
253
340
  override func beginDownloadBackgroundTask() {}
254
341
  override func checkAppReady() {}
255
342
 
343
+ var onReload: (() -> Void)?
344
+ /// Result of the n-th `reloadCurrentBundle()` call (1-based); nil means success.
345
+ var reloadResult: ((Int) -> Bool)?
346
+
256
347
  override func reloadCurrentBundle() -> Bool {
257
348
  reloadCalls += 1
258
- return true
349
+ let call = reloadCalls
350
+ onReload?()
351
+ return reloadResult?(call) ?? true
259
352
  }
260
353
 
261
354
  override func _reset(toLastSuccessful: Bool, usePendingBundle: Bool) -> Bool {
@@ -604,9 +697,12 @@ class CapacitorUpdaterTests: XCTestCase {
604
697
  super.setUp()
605
698
  plugin = TestableCapacitorUpdaterPlugin()
606
699
  implementation = CapgoUpdater()
700
+ // Retry budgets persist in UserDefaults until a successful install; start every test from a clean one.
701
+ resetRetryState()
607
702
  }
608
703
 
609
704
  override func tearDown() {
705
+ resetRetryState()
610
706
  plugin = nil
611
707
  implementation = nil
612
708
  super.tearDown()
@@ -623,6 +719,14 @@ class CapacitorUpdaterTests: XCTestCase {
623
719
  }
624
720
  for persistAfterSaving in [false, true] {
625
721
  let testPlugin = CapacitorUpdaterPlugin()
722
+ // The plugin's own updater persists its stats queue on shutdown (deinit): keep it off the real
723
+ // capgo_pending_stats.json. The teardown block removes the directory after every plugin is gone.
724
+ let statsDirectory = FileManager.default.temporaryDirectory
725
+ .appendingPathComponent("CustomIdTests-\(UUID().uuidString)", isDirectory: true)
726
+ testPlugin.implementation.pendingStatsDirectoryOverride = statsDirectory
727
+ addTeardownBlock {
728
+ try? FileManager.default.removeItem(at: statsDirectory)
729
+ }
626
730
  var resolved = 0
627
731
  for customId in ["alice", "bob", ""] {
628
732
  if customId != "alice" {
@@ -648,6 +752,12 @@ class CapacitorUpdaterTests: XCTestCase {
648
752
  }
649
753
  }
650
754
 
755
+ private func resetRetryState() {
756
+ for version in ["1.0.0", "2.0.0", "3.0.0"] {
757
+ implementation?.resetIncompleteDownloadRetryCount(version: version)
758
+ }
759
+ }
760
+
651
761
  private func makeOnlyDownloadBundle(
652
762
  id: String = "downloaded-id",
653
763
  version: String = "2.0.0",
@@ -1019,13 +1129,20 @@ class CapacitorUpdaterTests: XCTestCase {
1019
1129
  }
1020
1130
 
1021
1131
  func testShouldRetryDownloadForIncompleteExistingBundles() {
1022
- let pending = BundleInfo(
1132
+ let pendingOnDisk = BundleInfo(
1023
1133
  id: "pending-id",
1024
1134
  version: "2.0.0",
1025
1135
  status: .PENDING,
1026
1136
  downloaded: Date(),
1027
1137
  checksum: "abc123"
1028
1138
  )
1139
+ let pendingStale = BundleInfo(
1140
+ id: "pending-stale",
1141
+ version: "2.0.0",
1142
+ status: .PENDING,
1143
+ downloaded: Date(),
1144
+ checksum: "abc123"
1145
+ )
1029
1146
  let downloading = BundleInfo(
1030
1147
  id: "downloading-id",
1031
1148
  version: "2.0.0",
@@ -1047,11 +1164,191 @@ class CapacitorUpdaterTests: XCTestCase {
1047
1164
  downloaded: Date(),
1048
1165
  checksum: "abc123"
1049
1166
  )
1167
+ let interruptedError = BundleInfo(
1168
+ id: "error-id",
1169
+ version: "2.0.0",
1170
+ status: .ERROR,
1171
+ downloaded: Date(),
1172
+ checksum: ""
1173
+ )
1174
+
1175
+ XCTAssertFalse(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1176
+ pendingOnDisk,
1177
+ bundleOnDisk: true,
1178
+ incompleteRetryCount: 0,
1179
+ integrityBlocked: false,
1180
+ interruptedDownloadFailure: false,
1181
+ isCurrentBundle: false,
1182
+ isQueuedNext: true
1183
+ ))
1184
+ XCTAssertFalse(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1185
+ pendingStale,
1186
+ bundleOnDisk: true,
1187
+ incompleteRetryCount: 0,
1188
+ integrityBlocked: false,
1189
+ interruptedDownloadFailure: false,
1190
+ isCurrentBundle: false,
1191
+ isQueuedNext: false
1192
+ ))
1193
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1194
+ pendingStale,
1195
+ bundleOnDisk: false,
1196
+ incompleteRetryCount: 0,
1197
+ integrityBlocked: false,
1198
+ interruptedDownloadFailure: false,
1199
+ isCurrentBundle: false,
1200
+ isQueuedNext: false
1201
+ ))
1202
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1203
+ downloading,
1204
+ bundleOnDisk: false,
1205
+ incompleteRetryCount: 0,
1206
+ integrityBlocked: false,
1207
+ interruptedDownloadFailure: false,
1208
+ isCurrentBundle: false,
1209
+ isQueuedNext: false
1210
+ ))
1211
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1212
+ deleting,
1213
+ bundleOnDisk: true,
1214
+ incompleteRetryCount: 0,
1215
+ integrityBlocked: false,
1216
+ interruptedDownloadFailure: false,
1217
+ isCurrentBundle: false,
1218
+ isQueuedNext: false
1219
+ ))
1220
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1221
+ deleted,
1222
+ bundleOnDisk: false,
1223
+ incompleteRetryCount: 0,
1224
+ integrityBlocked: false,
1225
+ interruptedDownloadFailure: false,
1226
+ isCurrentBundle: false,
1227
+ isQueuedNext: false
1228
+ ))
1229
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1230
+ interruptedError,
1231
+ bundleOnDisk: false,
1232
+ incompleteRetryCount: 0,
1233
+ integrityBlocked: false,
1234
+ interruptedDownloadFailure: false,
1235
+ isCurrentBundle: false,
1236
+ isQueuedNext: false
1237
+ ))
1238
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1239
+ interruptedError,
1240
+ bundleOnDisk: false,
1241
+ incompleteRetryCount: 0,
1242
+ integrityBlocked: true,
1243
+ interruptedDownloadFailure: false,
1244
+ isCurrentBundle: false,
1245
+ isQueuedNext: false
1246
+ ))
1247
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1248
+ interruptedError,
1249
+ bundleOnDisk: false,
1250
+ incompleteRetryCount: 0,
1251
+ integrityBlocked: false,
1252
+ interruptedDownloadFailure: true,
1253
+ isCurrentBundle: false,
1254
+ isQueuedNext: false
1255
+ ))
1256
+ XCTAssertFalse(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1257
+ interruptedError,
1258
+ bundleOnDisk: false,
1259
+ incompleteRetryCount: CapgoUpdater.maxIncompleteDownloadRetries,
1260
+ integrityBlocked: false,
1261
+ interruptedDownloadFailure: true,
1262
+ isCurrentBundle: false,
1263
+ isQueuedNext: false
1264
+ ))
1265
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1266
+ interruptedError,
1267
+ bundleOnDisk: false,
1268
+ incompleteRetryCount: 0,
1269
+ integrityBlocked: true,
1270
+ interruptedDownloadFailure: true,
1271
+ isCurrentBundle: false,
1272
+ isQueuedNext: false
1273
+ ))
1274
+ }
1275
+
1276
+ func testInterruptedDownloadingBundleRetriesDespiteVersionInProgress() {
1277
+ let plugin = TestableCapacitorUpdaterPlugin()
1278
+ let updater = CapgoUpdater()
1279
+ updater.setLogger(Logger(withTag: "TestLogger"))
1280
+ plugin.implementation = updater
1281
+ plugin.setVersionDownloadInProgressForTesting(version: "2.0.0")
1282
+
1283
+ let bundleId = "downloading-id"
1284
+ updater.markInterruptedDownloadBundle(bundleId: bundleId)
1285
+ defer {
1286
+ updater.clearInterruptedDownloadBundle(bundleId: bundleId)
1287
+ }
1288
+
1289
+ let downloading = BundleInfo(
1290
+ id: bundleId,
1291
+ version: "2.0.0",
1292
+ status: .DOWNLOADING,
1293
+ downloaded: Date(),
1294
+ checksum: ""
1295
+ )
1296
+ let current = BundleInfo(
1297
+ id: "current-id",
1298
+ version: "1.0.0",
1299
+ status: .SUCCESS,
1300
+ downloaded: Date(),
1301
+ checksum: "abc123"
1302
+ )
1303
+
1304
+ XCTAssertTrue(
1305
+ plugin.shouldRetryDownloadForExistingBundleForTesting(downloading, latestVersionName: "2.0.0", current: current)
1306
+ )
1307
+
1308
+ let otherDownloading = BundleInfo(
1309
+ id: "other-id",
1310
+ version: "2.0.0",
1311
+ status: .DOWNLOADING,
1312
+ downloaded: Date(),
1313
+ checksum: ""
1314
+ )
1315
+ XCTAssertFalse(
1316
+ plugin.shouldRetryDownloadForExistingBundleForTesting(otherDownloading, latestVersionName: "2.0.0", current: current)
1317
+ )
1318
+ }
1319
+
1320
+ func testIncompleteDownloadRetryReservationChargesNextStart() {
1321
+ let updater = CapgoUpdater()
1322
+ let version = "retry-accounting-\(UUID().uuidString)"
1323
+ defer {
1324
+ updater.resetIncompleteDownloadRetryCount(version: version)
1325
+ }
1050
1326
 
1051
- XCTAssertFalse(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(pending))
1052
- XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(downloading))
1053
- XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(deleting))
1054
- XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(deleted))
1327
+ // A first download with no admitted retry and no reservation is free.
1328
+ updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: false)
1329
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 0)
1330
+
1331
+ // A reservation written before the old record is deleted survives process death and charges the restart.
1332
+ updater.reserveIncompleteDownloadRetry(version: version)
1333
+ XCTAssertTrue(updater.hasIncompleteDownloadRetryReservation(version: version))
1334
+ updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: false)
1335
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 1)
1336
+ XCTAssertFalse(updater.hasIncompleteDownloadRetryReservation(version: version))
1337
+
1338
+ // Integrity-blocked versions keep their block and count until a successful install resets them.
1339
+ updater.markIntegrityBlockedVersion(version: version)
1340
+ updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: true)
1341
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 2)
1342
+ XCTAssertTrue(updater.isIntegrityBlockedVersion(version: version))
1343
+
1344
+ // The cap check and charge are atomic: the last slot is charged once, then admitted retries are refused.
1345
+ XCTAssertTrue(updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: true))
1346
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), CapgoUpdater.maxIncompleteDownloadRetries)
1347
+ XCTAssertFalse(updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: true))
1348
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), CapgoUpdater.maxIncompleteDownloadRetries)
1349
+ updater.resetIncompleteDownloadRetryCount(version: version)
1350
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 0)
1351
+ XCTAssertFalse(updater.isIntegrityBlockedVersion(version: version))
1055
1352
  }
1056
1353
 
1057
1354
  func testBuildUserAgentStripsNonIsoCharacters() {
@@ -2124,6 +2421,36 @@ class CapacitorUpdaterTests: XCTestCase {
2124
2421
  XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
2125
2422
  }
2126
2423
 
2424
+ func testResetToLastSuccessfulBelowNativeFloorFallsBackToBuiltin() {
2425
+ let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
2426
+ let resetImplementation = ResetTrackingCapgoUpdater()
2427
+ // A native upgrade to 2.0.0 left a 1.5.0 last successful bundle behind.
2428
+ resetImplementation.versionBuild = "2.0.0"
2429
+ resetImplementation.fallbackBundleValue = BundleInfo(
2430
+ id: "fallback-id",
2431
+ version: "1.5.0",
2432
+ status: .SUCCESS,
2433
+ downloaded: Date(),
2434
+ checksum: "fallback"
2435
+ )
2436
+ // Both the replaced default updater and the test updater write pending stats; keep them out of the real file.
2437
+ let statsDirectory = FileManager.default.temporaryDirectory
2438
+ .appendingPathComponent("ResetFloorTests-\(UUID().uuidString)", isDirectory: true)
2439
+ resetPlugin.implementation.pendingStatsDirectoryOverride = statsDirectory
2440
+ resetImplementation.pendingStatsDirectoryOverride = statsDirectory
2441
+ addTeardownBlock {
2442
+ try? FileManager.default.removeItem(at: statsDirectory)
2443
+ }
2444
+
2445
+ resetPlugin.implementation = resetImplementation
2446
+
2447
+ XCTAssertTrue(resetPlugin._reset(toLastSuccessful: true, usePendingBundle: false))
2448
+ XCTAssertEqual(resetImplementation.setCalls, 0)
2449
+ XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
2450
+ XCTAssertTrue(resetImplementation.finalizeResetTransitionCalled)
2451
+ XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
2452
+ }
2453
+
2127
2454
  func testResetToLastSuccessfulRestoresStateWhenSwitchFails() {
2128
2455
  let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
2129
2456
  let resetImplementation = ResetTrackingCapgoUpdater()
@@ -2529,6 +2856,8 @@ class CapacitorUpdaterTests: XCTestCase {
2529
2856
  testPlugin.backgroundDownload()
2530
2857
 
2531
2858
  XCTAssertTrue(testPlugin.notifiedEventNames.contains("noNeedUpdate"))
2859
+ // Retained like updateAvailable and appReady, so a listener attached after the check still sees it.
2860
+ XCTAssertEqual(testPlugin.notifiedEventRetainValues["noNeedUpdate"], true)
2532
2861
  XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateCheckResult"))
2533
2862
  XCTAssertFalse(testPlugin.notifiedEventNames.contains("downloadFailed"))
2534
2863
  XCTAssertFalse(noUpdateImplementation.sentStatsActions.contains("download_fail"))
@@ -2808,6 +3137,10 @@ class CapacitorUpdaterTests: XCTestCase {
2808
3137
  // Per-event listeners were removed in 9.0.0: one bridge call per event, always as updaterEvent.
2809
3138
  XCTAssertEqual(testPlugin.notifiedEvents.map { $0.name }, ["updaterEvent", "updaterEvent"])
2810
3139
  let events = testPlugin.notifiedEvents
3140
+ guard events.count == 2 else {
3141
+ XCTFail("Expected exactly two bridge events, got \(events.count)")
3142
+ return
3143
+ }
2811
3144
  XCTAssertEqual(events[0].data?["type"] as? String, "download")
2812
3145
  XCTAssertEqual((events[0].data?["data"] as? [String: Any])?["percent"] as? Int, 10)
2813
3146
  XCTAssertFalse(events[0].retain)
@@ -3097,6 +3430,14 @@ class CapacitorUpdaterTests: XCTestCase {
3097
3430
  implementation.latestResponse = makeOnlyDownloadLatest()
3098
3431
  implementation.downloadedBundleValue = makeOnlyDownloadBundle()
3099
3432
  let testPlugin = SplashTimeoutCapacitorUpdaterPlugin()
3433
+ // Both the replaced default updater and the test updater write pending stats; keep them out of the real file.
3434
+ let statsDirectory = FileManager.default.temporaryDirectory
3435
+ .appendingPathComponent("SplashTimeoutTests-\(UUID().uuidString)", isDirectory: true)
3436
+ testPlugin.implementation.pendingStatsDirectoryOverride = statsDirectory
3437
+ implementation.pendingStatsDirectoryOverride = statsDirectory
3438
+ addTeardownBlock {
3439
+ try? FileManager.default.removeItem(at: statsDirectory)
3440
+ }
3100
3441
  testPlugin.implementation = implementation
3101
3442
  testPlugin.configureDirectUpdateModeForTesting(mode)
3102
3443
  testPlugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
@@ -3163,6 +3504,20 @@ class CapacitorUpdaterTests: XCTestCase {
3163
3504
  assertDeferredBundleInstallsOnNextBackground(plugin: testPlugin, implementation: implementation, expectedBundleId: "downloaded-id")
3164
3505
  }
3165
3506
 
3507
+ /// Control for the expired case: without a splash timeout, `always` installs the download immediately.
3508
+ func testUnexpiredAlwaysDownloadInstallsImmediately() throws {
3509
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
3510
+ defer { clearDelayStorage() }
3511
+
3512
+ testPlugin.backgroundDownload()
3513
+
3514
+ XCTAssertEqual(implementation.downloadCalls, 1)
3515
+ XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3516
+ XCTAssertEqual(testPlugin.reloadCalls, 1)
3517
+ XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3518
+ XCTAssertNil(implementation.lastSetNextBundleId)
3519
+ }
3520
+
3166
3521
  func testExpiredLaunchCachedBundleStaysDeferredAfterBackgroundAndForeground() throws {
3167
3522
  let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3168
3523
  implementation.existingBundleValue = makeOnlyDownloadBundle()
@@ -3208,105 +3563,519 @@ class CapacitorUpdaterTests: XCTestCase {
3208
3563
  XCTAssertNil(implementation.lastSetNextBundleId)
3209
3564
  }
3210
3565
 
3211
- func testLaterAlwaysDownloadCanInstallAfterEarlierSplashTimeout() throws {
3212
- let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
3213
- defer { implementation.onDownloadStart = nil; clearDelayStorage() }
3214
- implementation.onDownloadStart = { self.resumeAfterSplashTimeout(testPlugin) }
3215
- testPlugin.backgroundDownload()
3216
- XCTAssertEqual(testPlugin.reloadCalls, 0)
3566
+ private func makeNextCall(id: String, onResolve: @escaping () -> Void) -> CAPPluginCall? {
3567
+ CAPPluginCall(
3568
+ callbackId: "next-during-direct-reload-\(id)",
3569
+ options: ["id": id],
3570
+ success: { _, _ in onResolve() },
3571
+ error: { _ in }
3572
+ )
3573
+ }
3574
+
3575
+ func testDirectUpdateKeepsNextBundleQueuedByJsDuringReload() throws {
3576
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3577
+ defer { testPlugin.onReload = nil; clearDelayStorage() }
3578
+ var jsNextResolved = false
3579
+ testPlugin.onReload = {
3580
+ // JS queues another bundle while the direct update's reload is in flight.
3581
+ guard let call = self.makeNextCall(id: BundleInfo.ID_BUILTIN, onResolve: { jsNextResolved = true }) else {
3582
+ XCTFail("could not build next() call")
3583
+ return
3584
+ }
3585
+ testPlugin.next(call)
3586
+ }
3217
3587
 
3218
- implementation.onDownloadStart = nil
3219
3588
  testPlugin.backgroundDownload()
3220
3589
 
3590
+ XCTAssertTrue(jsNextResolved)
3221
3591
  XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3222
3592
  XCTAssertEqual(testPlugin.reloadCalls, 1)
3593
+ // The direct update still completes the activation of 2.0.0 and publishes it...
3223
3594
  XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3595
+ XCTAssertTrue(testPlugin.notifiedEventNames.contains("set"))
3596
+ // ...but keeps the bundle the app queued instead of clearing it.
3597
+ XCTAssertEqual(implementation.getNextBundle()?.getId(), BundleInfo.ID_BUILTIN)
3224
3598
  }
3225
3599
 
3226
- func testLaunchSplashDoesNotScheduleTimeoutAfterOnLaunchDirectUpdateConsumed() {
3227
- plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
3228
- plugin.configureDirectUpdateModeForTesting("onLaunch", onLaunchDirectUpdateUsed: true)
3600
+ func testDirectUpdateRollsBackBundleMarkedErrorDuringReload() throws {
3601
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3602
+ // The rollback restores persisted reset state, which logs through the updater.
3603
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3604
+ let savedResetState = implementation.captureResetState()
3605
+ defer {
3606
+ testPlugin.onReload = nil
3607
+ implementation.restoreResetState(savedResetState)
3608
+ clearDelayStorage()
3609
+ }
3610
+ let downloadedId = try XCTUnwrap(implementation.downloadedBundleValue?.getId())
3611
+ let downloadedVersion = try XCTUnwrap(implementation.downloadedBundleValue?.getVersionName())
3612
+ testPlugin.onReload = {
3613
+ // setBundleError fails the bundle while its direct-update reload is in flight.
3614
+ implementation.storedBundleInfoOverrides[downloadedId] = BundleInfo(
3615
+ id: downloadedId,
3616
+ version: downloadedVersion,
3617
+ status: .ERROR,
3618
+ downloaded: Date(),
3619
+ checksum: "abc"
3620
+ )
3621
+ }
3229
3622
 
3230
- plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
3623
+ testPlugin.backgroundDownload()
3231
3624
 
3232
- XCTAssertFalse(plugin.hasSplashscreenTimeoutScheduledForTesting())
3625
+ XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3626
+ XCTAssertFalse(testPlugin.notifiedEventNames.contains("set"))
3627
+ XCTAssertNil(implementation.lastSetNextBundleId)
3628
+ XCTAssertNil(implementation.getNextBundle())
3233
3629
  }
3234
3630
 
3235
- func testLaunchSplashTimeoutDoesNotConsumeAtInstallDirectUpdateWindow() {
3236
- plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
3237
- plugin.configureDirectUpdateModeForTesting("atInstall", onLaunchDirectUpdateUsed: false)
3238
- plugin.setWasRecentlyInstalledOrUpdatedForTesting(true)
3631
+ func testDirectUpdateIsSupersededByJsReloadDuringItsReload() throws {
3632
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3633
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3634
+ let savedResetState = implementation.captureResetState()
3635
+ defer {
3636
+ testPlugin.onReload = nil
3637
+ implementation.restoreResetState(savedResetState)
3638
+ clearDelayStorage()
3639
+ }
3640
+ let directVersion = try XCTUnwrap(implementation.downloadedBundleValue?.getVersionName())
3641
+ var jsReloadStarted = false
3642
+ var jsReloadResolved = false
3643
+ testPlugin.onReload = {
3644
+ guard !jsReloadStarted else {
3645
+ return
3646
+ }
3647
+ jsReloadStarted = true
3648
+ // While the direct update reloads, JS queues the builtin bundle and calls reload(), which activates it.
3649
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3650
+ let call = CAPPluginCall(
3651
+ callbackId: "reload-during-direct-update",
3652
+ options: [:],
3653
+ success: { _, _ in jsReloadResolved = true },
3654
+ error: { _ in XCTFail("reload() should apply the queued bundle") }
3655
+ )
3656
+ if let call {
3657
+ testPlugin.reload(call)
3658
+ }
3659
+ }
3239
3660
 
3240
- plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
3661
+ testPlugin.backgroundDownload()
3241
3662
 
3242
- XCTAssertTrue(plugin.hasSplashscreenTimeoutScheduledForTesting())
3243
- XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
3663
+ XCTAssertTrue(jsReloadResolved)
3664
+ let setBundleVersions = testPlugin.notifiedEvents
3665
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3666
+ .filter { $0.name == "set" }
3667
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3668
+ // Only reload() publishes its activation; the superseded direct update must not emit set(2.0.0) after it.
3669
+ XCTAssertFalse(setBundleVersions.contains(directVersion))
3670
+ XCTAssertEqual(setBundleVersions.count, 1)
3244
3671
  }
3245
3672
 
3246
- func testShowSplashscreenOptionsDisableAutoHide() {
3247
- let options = plugin.splashscreenOptionsForTesting(methodName: "show")
3248
-
3249
- XCTAssertEqual(options["autoHide"] as? Bool, false)
3250
- XCTAssertEqual(options["fadeInDuration"] as? Int, 0)
3251
- }
3673
+ func testDirectUpdateIsSupersededByBackgroundInstallDuringItsReload() throws {
3674
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3675
+ defer { testPlugin.onReload = nil; clearDelayStorage() }
3676
+ let builtin = implementation.builtinBundleValue
3677
+ let directVersion = try XCTUnwrap(implementation.downloadedBundleValue?.getVersionName())
3678
+ var backgroundInstalled = false
3679
+ testPlugin.onReload = {
3680
+ guard !backgroundInstalled else {
3681
+ return
3682
+ }
3683
+ backgroundInstalled = true
3684
+ // While the direct update reloads, the app goes to background and installs a queued bundle from
3685
+ // another thread, as the background-task path does.
3686
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3687
+ var installed = false
3688
+ let installDone = DispatchSemaphore(value: 0)
3689
+ // A dedicated thread, not the shared global queue: earlier tests can leave its threads blocked in
3690
+ // app-ready waits, and on a loaded CI runner a queued job then may not start within the wait below.
3691
+ let installThread = Thread {
3692
+ installed = testPlugin.installNextForTesting()
3693
+ installDone.signal()
3694
+ }
3695
+ installThread.start()
3696
+ XCTAssertEqual(installDone.wait(timeout: .now() + 5), .success)
3697
+ XCTAssertTrue(installed)
3698
+ }
3252
3699
 
3253
- func testHideSplashscreenOptionsStayEmpty() {
3254
- let options = plugin.splashscreenOptionsForTesting(methodName: "hide")
3700
+ testPlugin.backgroundDownload()
3255
3701
 
3256
- XCTAssertTrue(options.isEmpty)
3702
+ XCTAssertTrue(backgroundInstalled)
3703
+ XCTAssertEqual(implementation.currentBundleValue.getId(), builtin.getId())
3704
+ let setBundleVersions = testPlugin.notifiedEvents
3705
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3706
+ .filter { $0.name == "set" }
3707
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3708
+ XCTAssertFalse(setBundleVersions.contains(directVersion))
3257
3709
  }
3258
3710
 
3259
- func testSplashscreenInvocationTokenRejectsStaleRequests() {
3260
- XCTAssertTrue(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
3711
+ func testBackgroundInstallIsSupersededByJsReloadDuringItsReload() throws {
3712
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3713
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3714
+ let savedResetState = implementation.captureResetState()
3715
+ defer {
3716
+ testPlugin.onReload = nil
3717
+ implementation.restoreResetState(savedResetState)
3718
+ clearDelayStorage()
3719
+ }
3720
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3721
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3722
+ var jsReloadStarted = false
3723
+ var jsReloadResolved = false
3724
+ testPlugin.onReload = {
3725
+ guard !jsReloadStarted else {
3726
+ return
3727
+ }
3728
+ jsReloadStarted = true
3729
+ // While the background install reloads, JS queues the builtin bundle and calls reload(), which activates it.
3730
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3731
+ let call = CAPPluginCall(
3732
+ callbackId: "reload-during-background-install",
3733
+ options: [:],
3734
+ success: { _, _ in jsReloadResolved = true },
3735
+ error: { _ in XCTFail("reload() should apply the queued bundle") }
3736
+ )
3737
+ if let call {
3738
+ testPlugin.reload(call)
3739
+ }
3740
+ }
3261
3741
 
3262
- plugin.advanceSplashscreenInvocationTokenForTesting()
3742
+ XCTAssertFalse(testPlugin.installNextForTesting())
3263
3743
 
3264
- XCTAssertFalse(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
3744
+ XCTAssertTrue(jsReloadResolved)
3745
+ XCTAssertTrue(implementation.getCurrentBundle().isBuiltin())
3746
+ let setBundleVersions = testPlugin.notifiedEvents
3747
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3748
+ .filter { $0.name == "set" }
3749
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3750
+ // Only reload() publishes its activation; the superseded install must not emit a stale set event after it.
3751
+ XCTAssertFalse(setBundleVersions.contains(downloaded.getVersionName()))
3752
+ XCTAssertEqual(setBundleVersions.count, 1)
3265
3753
  }
3266
3754
 
3267
- func testDelayUpdateUtilsSetMultiDelayStoresMultipleConditions() throws {
3268
- let utils = try makeDelayUpdateUtils()
3269
- clearDelayStorage()
3270
- defer { clearDelayStorage() }
3271
- let json = try makeDelayConditionsJSON()
3755
+ func testJsReloadIsSupersededByBackgroundInstallDuringItsReload() throws {
3756
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3757
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3758
+ let savedResetState = implementation.captureResetState()
3759
+ defer {
3760
+ testPlugin.onReload = nil
3761
+ implementation.restoreResetState(savedResetState)
3762
+ clearDelayStorage()
3763
+ }
3764
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3765
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3766
+ var backgroundInstalled = false
3767
+ testPlugin.onReload = {
3768
+ guard !backgroundInstalled else {
3769
+ return
3770
+ }
3771
+ backgroundInstalled = true
3772
+ // While reload() applies the queued bundle, the app goes to background and installs another queued bundle.
3773
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3774
+ XCTAssertTrue(testPlugin.installNextForTesting())
3775
+ }
3776
+ var jsReloadResolved = false
3777
+ let call = try XCTUnwrap(CAPPluginCall(
3778
+ callbackId: "reload-superseded-by-background-install",
3779
+ options: [:],
3780
+ success: { _, _ in jsReloadResolved = true },
3781
+ error: { _ in XCTFail("reload() should resolve once its reload succeeded") }
3782
+ ))
3272
3783
 
3273
- XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
3274
- XCTAssertEqual(UserDefaults.standard.string(forKey: delayPreferencesKey), json)
3275
- }
3784
+ testPlugin.reload(call)
3276
3785
 
3277
- func testDelayUpdateUtilsCheckCancelDelayKilledKeepsOtherConditions() throws {
3278
- let utils = try makeDelayUpdateUtils()
3279
- clearDelayStorage()
3280
- defer { clearDelayStorage() }
3281
- let json = try makeDelayConditionsJSON()
3282
- XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
3786
+ XCTAssertTrue(backgroundInstalled)
3787
+ XCTAssertTrue(jsReloadResolved)
3788
+ XCTAssertTrue(implementation.currentBundleValue.isBuiltin())
3789
+ let setBundleVersions = testPlugin.notifiedEvents
3790
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3791
+ .filter { $0.name == "set" }
3792
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3793
+ // Only the background install publishes its activation; the superseded reload must not emit set(2.0.0) after it.
3794
+ XCTAssertFalse(setBundleVersions.contains(downloaded.getVersionName()))
3795
+ XCTAssertEqual(setBundleVersions.count, 1)
3796
+ }
3283
3797
 
3284
- utils.checkCancelDelay(source: .killed)
3798
+ func testFailedBackgroundInstallKeepsNextBundleQueuedByJsDuringReload() throws {
3799
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3800
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3801
+ let savedResetState = implementation.captureResetState()
3802
+ defer {
3803
+ testPlugin.onReload = nil
3804
+ testPlugin.reloadResult = nil
3805
+ implementation.restoreResetState(savedResetState)
3806
+ clearDelayStorage()
3807
+ }
3808
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3809
+ let previousActiveId = implementation.currentBundleValue.getId()
3810
+ XCTAssertNotEqual(previousActiveId, downloaded.getId())
3811
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3812
+ var jsNextResolved = false
3813
+ testPlugin.reloadResult = { _ in false }
3814
+ testPlugin.onReload = {
3815
+ // JS queues another bundle while the background install's reload is in flight; then the reload fails.
3816
+ guard let call = self.makeNextCall(id: BundleInfo.ID_BUILTIN, onResolve: { jsNextResolved = true }) else {
3817
+ XCTFail("could not build next() call")
3818
+ return
3819
+ }
3820
+ testPlugin.next(call)
3821
+ }
3285
3822
 
3286
- let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
3287
- let storedData = try XCTUnwrap(stored.data(using: .utf8))
3288
- let parsed = try XCTUnwrap(JSONSerialization.jsonObject(with: storedData) as? [[String: String]])
3823
+ XCTAssertFalse(testPlugin.installNextForTesting())
3289
3824
 
3290
- XCTAssertEqual(parsed.count, 1)
3291
- XCTAssertEqual(parsed.first?["kind"], "background")
3292
- XCTAssertEqual(parsed.first?["value"], "5000")
3825
+ XCTAssertTrue(jsNextResolved)
3826
+ // The rollback must not overwrite the app's newer queue with the pre-install snapshot.
3827
+ XCTAssertEqual(implementation.captureResetState().nextBundleId, BundleInfo.ID_BUILTIN)
3828
+ XCTAssertFalse(testPlugin.notifiedEventNames.contains("set"))
3829
+ // The failed activation is rolled back to the previously active bundle.
3830
+ XCTAssertEqual(implementation.getCurrentBundle().getId(), previousActiveId)
3293
3831
  }
3294
3832
 
3295
- func testDelayUpdateUtilsCheckCancelDelayOrModeKilledCancelsImmediately() throws {
3296
- let utils = try makeDelayUpdateUtils()
3297
- clearDelayStorage()
3298
- defer { clearDelayStorage() }
3299
- let json = try makeDelayConditionsJSON()
3300
- XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
3301
- XCTAssertTrue(utils.setConditionMode(DelayUpdateUtils.DELAY_CONDITION_MODE_OR))
3833
+ func testFailedBackgroundInstallKeepsBuiltinQueuedByUpdateCheckDuringReload() throws {
3834
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3835
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3836
+ let savedResetState = implementation.captureResetState()
3837
+ defer {
3838
+ testPlugin.onReload = nil
3839
+ testPlugin.reloadResult = nil
3840
+ implementation.restoreResetState(savedResetState)
3841
+ clearDelayStorage()
3842
+ }
3843
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3844
+ let previousActiveId = implementation.currentBundleValue.getId()
3845
+ XCTAssertNotEqual(previousActiveId, downloaded.getId())
3846
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3847
+ testPlugin.reloadResult = { _ in false }
3848
+ testPlugin.onReload = {
3849
+ // An update check whose latest version is builtin queues it while the background install reloads.
3850
+ XCTAssertTrue(testPlugin.queueBuiltinBundleAsNextForTesting())
3851
+ }
3302
3852
 
3303
- utils.checkCancelDelay(source: .killed)
3853
+ XCTAssertFalse(testPlugin.installNextForTesting())
3304
3854
 
3305
- XCTAssertNil(UserDefaults.standard.string(forKey: delayPreferencesKey))
3306
- XCTAssertNil(UserDefaults.standard.string(forKey: delayConditionModeKey))
3855
+ XCTAssertEqual(implementation.captureResetState().nextBundleId, BundleInfo.ID_BUILTIN)
3856
+ // The failed activation is rolled back to the previously active bundle.
3857
+ XCTAssertEqual(implementation.getCurrentBundle().getId(), previousActiveId)
3307
3858
  }
3308
3859
 
3309
- func testDelayUpdateUtilsSetConditionModePersistsValue() throws {
3860
+ func testFailedJsReloadKeepsNextBundleQueuedByJsDuringReload() throws {
3861
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3862
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3863
+ let savedResetState = implementation.captureResetState()
3864
+ defer {
3865
+ testPlugin.onReload = nil
3866
+ testPlugin.reloadResult = nil
3867
+ implementation.restoreResetState(savedResetState)
3868
+ clearDelayStorage()
3869
+ }
3870
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3871
+ let previousActiveId = implementation.currentBundleValue.getId()
3872
+ XCTAssertNotEqual(previousActiveId, downloaded.getId())
3873
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3874
+ var jsNextResolved = false
3875
+ testPlugin.reloadResult = { _ in false }
3876
+ testPlugin.onReload = {
3877
+ guard let call = self.makeNextCall(id: BundleInfo.ID_BUILTIN, onResolve: { jsNextResolved = true }) else {
3878
+ XCTFail("could not build next() call")
3879
+ return
3880
+ }
3881
+ testPlugin.next(call)
3882
+ }
3883
+ var reloadRejected = false
3884
+ let call = try XCTUnwrap(CAPPluginCall(
3885
+ callbackId: "failed-reload-with-next",
3886
+ options: [:],
3887
+ success: { _, _ in XCTFail("reload() should reject when its reload fails") },
3888
+ error: { _ in reloadRejected = true }
3889
+ ))
3890
+
3891
+ testPlugin.reload(call)
3892
+
3893
+ XCTAssertTrue(jsNextResolved)
3894
+ XCTAssertTrue(reloadRejected)
3895
+ XCTAssertEqual(implementation.captureResetState().nextBundleId, BundleInfo.ID_BUILTIN)
3896
+ // The failed activation is rolled back to the previously active bundle.
3897
+ XCTAssertEqual(implementation.getCurrentBundle().getId(), previousActiveId)
3898
+ }
3899
+
3900
+ func testFailedBackgroundInstallDoesNotRevertConcurrentJsReload() throws {
3901
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3902
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3903
+ let savedResetState = implementation.captureResetState()
3904
+ defer {
3905
+ testPlugin.onReload = nil
3906
+ testPlugin.reloadResult = nil
3907
+ implementation.restoreResetState(savedResetState)
3908
+ clearDelayStorage()
3909
+ }
3910
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3911
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3912
+ // The background install's own reload (call 1) fails; the nested JS reload (call 2) succeeds.
3913
+ testPlugin.reloadResult = { call in call != 1 }
3914
+ var stateAfterJsReload: CapgoUpdater.ResetState?
3915
+ testPlugin.onReload = {
3916
+ guard stateAfterJsReload == nil, testPlugin.reloadCalls == 1 else {
3917
+ return
3918
+ }
3919
+ // JS queues the builtin bundle and reloads into it while the background install reloads.
3920
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3921
+ if let call = CAPPluginCall(
3922
+ callbackId: "reload-during-failed-background-install",
3923
+ options: [:],
3924
+ success: { _, _ in },
3925
+ error: { _ in XCTFail("reload() should apply the queued bundle") }
3926
+ ) {
3927
+ testPlugin.reload(call)
3928
+ }
3929
+ stateAfterJsReload = implementation.captureResetState()
3930
+ }
3931
+
3932
+ XCTAssertFalse(testPlugin.installNextForTesting())
3933
+
3934
+ let expected = try XCTUnwrap(stateAfterJsReload)
3935
+ let actual = implementation.captureResetState()
3936
+ // The failed install must not roll back over the activation JS completed during its reload.
3937
+ XCTAssertEqual(actual.currentBundlePath, expected.currentBundlePath)
3938
+ XCTAssertEqual(actual.fallbackBundleId, expected.fallbackBundleId)
3939
+ XCTAssertEqual(actual.nextBundleId, expected.nextBundleId)
3940
+ // The bundle JS activated stays active.
3941
+ XCTAssertTrue(implementation.getCurrentBundle().isBuiltin())
3942
+ }
3943
+
3944
+ func testCompletedDownloadFingerprintsArePrunedForBundlesWithoutStoredRecord() {
3945
+ // Ids with no stored record behave like bundles removed by autoDeletePrevious; getBundleInfo(id:)
3946
+ // returns a PENDING placeholder for them, which previously kept their fingerprints forever.
3947
+ plugin.implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3948
+ let staleIds = (0..<40).map { "pruned-fingerprint-\($0)-\(UUID().uuidString)" }
3949
+ for id in staleIds {
3950
+ plugin.recordCompletedZipDownloadForTesting(bundleId: id)
3951
+ }
3952
+
3953
+ // Pruning runs once the map exceeds 16 entries and always keeps the id just recorded.
3954
+ let remaining = plugin.completedDownloadFingerprintIdsForTesting
3955
+ XCTAssertLessThanOrEqual(remaining.count, 17)
3956
+ XCTAssertTrue(remaining.contains(staleIds[staleIds.count - 1]))
3957
+ }
3958
+
3959
+ func testDirectUpdateIgnoresRejectedNextDuringReload() throws {
3960
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3961
+ defer { testPlugin.onReload = nil; clearDelayStorage() }
3962
+ var rejectedNextResolved = false
3963
+ testPlugin.onReload = {
3964
+ // A next() for a bundle that is not installed changes nothing and must not invalidate the update.
3965
+ guard let call = self.makeNextCall(id: "not-installed", onResolve: { rejectedNextResolved = true }) else {
3966
+ XCTFail("could not build next() call")
3967
+ return
3968
+ }
3969
+ testPlugin.next(call)
3970
+ }
3971
+
3972
+ testPlugin.backgroundDownload()
3973
+
3974
+ XCTAssertFalse(rejectedNextResolved)
3975
+ XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3976
+ XCTAssertTrue(testPlugin.notifiedEventNames.contains("set"))
3977
+ XCTAssertNil(implementation.getNextBundle())
3978
+ }
3979
+
3980
+ func testLaterAlwaysDownloadCanInstallAfterEarlierSplashTimeout() throws {
3981
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
3982
+ defer { implementation.onDownloadStart = nil; clearDelayStorage() }
3983
+ implementation.onDownloadStart = { self.resumeAfterSplashTimeout(testPlugin) }
3984
+ testPlugin.backgroundDownload()
3985
+ XCTAssertEqual(testPlugin.reloadCalls, 0)
3986
+
3987
+ implementation.onDownloadStart = nil
3988
+ testPlugin.backgroundDownload()
3989
+
3990
+ XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3991
+ XCTAssertEqual(testPlugin.reloadCalls, 1)
3992
+ XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3993
+ }
3994
+
3995
+ func testLaunchSplashDoesNotScheduleTimeoutAfterOnLaunchDirectUpdateConsumed() {
3996
+ plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
3997
+ plugin.configureDirectUpdateModeForTesting("onLaunch", onLaunchDirectUpdateUsed: true)
3998
+
3999
+ plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
4000
+
4001
+ XCTAssertFalse(plugin.hasSplashscreenTimeoutScheduledForTesting())
4002
+ }
4003
+
4004
+ func testLaunchSplashTimeoutDoesNotConsumeAtInstallDirectUpdateWindow() {
4005
+ plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
4006
+ plugin.configureDirectUpdateModeForTesting("atInstall", onLaunchDirectUpdateUsed: false)
4007
+ plugin.setWasRecentlyInstalledOrUpdatedForTesting(true)
4008
+
4009
+ plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
4010
+
4011
+ XCTAssertTrue(plugin.hasSplashscreenTimeoutScheduledForTesting())
4012
+ XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
4013
+ }
4014
+
4015
+ func testShowSplashscreenOptionsDisableAutoHide() {
4016
+ let options = plugin.splashscreenOptionsForTesting(methodName: "show")
4017
+
4018
+ XCTAssertEqual(options["autoHide"] as? Bool, false)
4019
+ XCTAssertEqual(options["fadeInDuration"] as? Int, 0)
4020
+ }
4021
+
4022
+ func testHideSplashscreenOptionsStayEmpty() {
4023
+ let options = plugin.splashscreenOptionsForTesting(methodName: "hide")
4024
+
4025
+ XCTAssertTrue(options.isEmpty)
4026
+ }
4027
+
4028
+ func testSplashscreenInvocationTokenRejectsStaleRequests() {
4029
+ XCTAssertTrue(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
4030
+
4031
+ plugin.advanceSplashscreenInvocationTokenForTesting()
4032
+
4033
+ XCTAssertFalse(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
4034
+ }
4035
+
4036
+ func testDelayUpdateUtilsSetMultiDelayStoresMultipleConditions() throws {
4037
+ let utils = try makeDelayUpdateUtils()
4038
+ clearDelayStorage()
4039
+ defer { clearDelayStorage() }
4040
+ let json = try makeDelayConditionsJSON()
4041
+
4042
+ XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
4043
+ XCTAssertEqual(UserDefaults.standard.string(forKey: delayPreferencesKey), json)
4044
+ }
4045
+
4046
+ func testDelayUpdateUtilsCheckCancelDelayKilledKeepsOtherConditions() throws {
4047
+ let utils = try makeDelayUpdateUtils()
4048
+ clearDelayStorage()
4049
+ defer { clearDelayStorage() }
4050
+ let json = try makeDelayConditionsJSON()
4051
+ XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
4052
+
4053
+ utils.checkCancelDelay(source: .killed)
4054
+
4055
+ let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
4056
+ let storedData = try XCTUnwrap(stored.data(using: .utf8))
4057
+ let parsed = try XCTUnwrap(JSONSerialization.jsonObject(with: storedData) as? [[String: String]])
4058
+
4059
+ XCTAssertEqual(parsed.count, 1)
4060
+ XCTAssertEqual(parsed.first?["kind"], "background")
4061
+ XCTAssertEqual(parsed.first?["value"], "5000")
4062
+ }
4063
+
4064
+ func testDelayUpdateUtilsCheckCancelDelayOrModeKilledCancelsImmediately() throws {
4065
+ let utils = try makeDelayUpdateUtils()
4066
+ clearDelayStorage()
4067
+ defer { clearDelayStorage() }
4068
+ let json = try makeDelayConditionsJSON()
4069
+ XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
4070
+ XCTAssertTrue(utils.setConditionMode(DelayUpdateUtils.DELAY_CONDITION_MODE_OR))
4071
+
4072
+ utils.checkCancelDelay(source: .killed)
4073
+
4074
+ XCTAssertNil(UserDefaults.standard.string(forKey: delayPreferencesKey))
4075
+ XCTAssertNil(UserDefaults.standard.string(forKey: delayConditionModeKey))
4076
+ }
4077
+
4078
+ func testDelayUpdateUtilsSetConditionModePersistsValue() throws {
3310
4079
  let utils = try makeDelayUpdateUtils()
3311
4080
  clearDelayStorage()
3312
4081
  defer { clearDelayStorage() }
@@ -3779,6 +4548,7 @@ class CapacitorUpdaterTests: XCTestCase {
3779
4548
  wait(for: [expectation], timeout: 2.0)
3780
4549
  XCTAssertEqual(testPlugin.appReadyNotifiedOnMainThread, true)
3781
4550
  XCTAssertEqual(testPlugin.appReadyRetainUntilConsumed, true)
4551
+ XCTAssertEqual(testPlugin.appReadyRawEventName, CapacitorUpdaterPlugin.updaterEvent)
3782
4552
  }
3783
4553
 
3784
4554
  func testSendReadyToJsWaitsOnlyWhenArmed() {
@@ -3902,4 +4672,1875 @@ class CapacitorUpdaterTests: XCTestCase {
3902
4672
  XCTAssertFalse(script.contains("plugin.notifyAppReady="))
3903
4673
  }
3904
4674
 
4675
+ func testRunGetLatestWorkUsesUserInitiatedQoS() {
4676
+ let basePlugin = CapacitorUpdaterPlugin()
4677
+ let executed = expectation(description: "runGetLatestWork executed")
4678
+ var observedQoS: qos_class_t = QOS_CLASS_UNSPECIFIED
4679
+
4680
+ basePlugin.runGetLatestWork {
4681
+ observedQoS = qos_class_self()
4682
+ executed.fulfill()
4683
+ }
4684
+
4685
+ wait(for: [executed], timeout: 5.0)
4686
+ XCTAssertGreaterThanOrEqual(observedQoS.rawValue, QOS_CLASS_USER_INITIATED.rawValue)
4687
+ XCTAssertNotEqual(observedQoS, QOS_CLASS_BACKGROUND)
4688
+ }
4689
+
4690
+ func testConcurrentJsDownloadAndBackgroundDownloadCoalesceWithoutDeletingActiveBundle() throws {
4691
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4692
+ CryptoCipher.setLogger(testLogger)
4693
+ let downloadEntered = OnceSignal()
4694
+ let waiterJoined = OnceSignal()
4695
+ let allowDownloadFinish = OnceSignal()
4696
+ let backgroundFinished = expectation(description: "backgroundDownload finished")
4697
+ let jsDownloadFinished = expectation(description: "JS download resolved")
4698
+
4699
+ let current = BundleInfo(
4700
+ id: "current-id",
4701
+ version: "1.0.0",
4702
+ status: .SUCCESS,
4703
+ downloaded: Date(),
4704
+ checksum: "current-checksum"
4705
+ )
4706
+ let inFlightDownloading = BundleInfo(
4707
+ id: "in-flight-id",
4708
+ version: "2.0.0",
4709
+ status: .DOWNLOADING,
4710
+ downloaded: Date(),
4711
+ checksum: ""
4712
+ )
4713
+ let completedBundle = BundleInfo(
4714
+ id: "fresh-id",
4715
+ version: "2.0.0",
4716
+ status: .PENDING,
4717
+ downloaded: Date(),
4718
+ checksum: "abc123"
4719
+ )
4720
+ let latest = AppVersion()
4721
+ latest.version = "2.0.0"
4722
+ latest.url = "https://example.com/update-2.0.0.zip"
4723
+ latest.checksum = "abc123"
4724
+
4725
+ let updater = CoalescingDownloadCapgoUpdater()
4726
+ updater.setLogger(testLogger)
4727
+ updater.currentBundleValue = current
4728
+ updater.latestResponse = latest
4729
+ updater.downloadedBundleValue = completedBundle
4730
+ updater.onDownloadStart = {
4731
+ updater.existingBundleValue = inFlightDownloading
4732
+ downloadEntered.signal()
4733
+ _ = allowDownloadFinish.wait(timeout: .now() + 5.0)
4734
+ updater.existingBundleValue = completedBundle
4735
+ }
4736
+ updater.onSetNextBundle = {
4737
+ backgroundFinished.fulfill()
4738
+ }
4739
+
4740
+ let concurrentPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
4741
+ concurrentPlugin.implementation = updater
4742
+ concurrentPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
4743
+ concurrentPlugin.setUpdateUrlForTesting("https://example.com/channel")
4744
+ concurrentPlugin.onCoalesceWaiterJoinedForTesting = { version in
4745
+ if version == "2.0.0" {
4746
+ waiterJoined.signal()
4747
+ }
4748
+ }
4749
+
4750
+ var resolvedId: String?
4751
+ let call = try XCTUnwrap(CAPPluginCall(
4752
+ callbackId: "coalesce-js-download",
4753
+ options: [
4754
+ "url": "https://example.com/update-2.0.0.zip",
4755
+ "version": "2.0.0",
4756
+ "checksum": "abc123"
4757
+ ],
4758
+ success: { result, _ in
4759
+ resolvedId = result?.data?["id"] as? String
4760
+ jsDownloadFinished.fulfill()
4761
+ },
4762
+ error: { error in
4763
+ XCTFail("JS download should coalesce and succeed: \(error?.message ?? "unknown")")
4764
+ jsDownloadFinished.fulfill()
4765
+ }
4766
+ ))
4767
+
4768
+ concurrentPlugin.download(call)
4769
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
4770
+
4771
+ concurrentPlugin.backgroundDownload()
4772
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
4773
+ allowDownloadFinish.signal()
4774
+
4775
+ wait(for: [jsDownloadFinished, backgroundFinished], timeout: 5.0)
4776
+ XCTAssertEqual(resolvedId, "fresh-id")
4777
+ XCTAssertEqual(updater.downloadCalls, 1)
4778
+ XCTAssertEqual(updater.deleteCalls, 0)
4779
+ XCTAssertEqual(updater.lastSetNextBundleId, "fresh-id")
4780
+ }
4781
+
4782
+ func testCoalescedDownloadPropagatesErrorAndClearsInFlightSlotForRetry() throws {
4783
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4784
+ CryptoCipher.setLogger(testLogger)
4785
+ let downloadEntered = OnceSignal()
4786
+ let waiterJoined = OnceSignal()
4787
+ let allowFailure = OnceSignal()
4788
+ let updater = CoalescingDownloadCapgoUpdater()
4789
+ updater.setLogger(testLogger)
4790
+ updater.currentBundleValue = BundleInfo(
4791
+ id: "current-id",
4792
+ version: "1.0.0",
4793
+ status: .SUCCESS,
4794
+ downloaded: Date(),
4795
+ checksum: "current-checksum"
4796
+ )
4797
+ updater.downloadedBundleValue = nil
4798
+ updater.onDownloadStart = {
4799
+ downloadEntered.signal()
4800
+ _ = allowFailure.wait(timeout: .now() + 5.0)
4801
+ }
4802
+
4803
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
4804
+ testPlugin.implementation = updater
4805
+ testPlugin.onCoalesceWaiterJoinedForTesting = { version in
4806
+ if version == "3.0.0" {
4807
+ waiterJoined.signal()
4808
+ }
4809
+ }
4810
+
4811
+ let firstDone = expectation(description: "first download failed")
4812
+ let secondDone = expectation(description: "coalesced download failed")
4813
+ var firstFailed = false
4814
+ var secondFailed = false
4815
+
4816
+ DispatchQueue.global(qos: .userInitiated).async {
4817
+ do {
4818
+ _ = try testPlugin.downloadBundleForTesting(
4819
+ urlString: "https://example.com/update-3.0.0.zip",
4820
+ version: "3.0.0",
4821
+ sessionKey: "",
4822
+ checksum: "abc123",
4823
+ manifestEntries: nil
4824
+ )
4825
+ } catch {
4826
+ firstFailed = true
4827
+ }
4828
+ firstDone.fulfill()
4829
+ }
4830
+
4831
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
4832
+
4833
+ DispatchQueue.global(qos: .userInitiated).async {
4834
+ do {
4835
+ _ = try testPlugin.downloadBundleForTesting(
4836
+ urlString: "https://example.com/update-3.0.0.zip",
4837
+ version: "3.0.0",
4838
+ sessionKey: "",
4839
+ checksum: "abc123",
4840
+ manifestEntries: nil
4841
+ )
4842
+ } catch {
4843
+ secondFailed = true
4844
+ }
4845
+ secondDone.fulfill()
4846
+ }
4847
+
4848
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
4849
+ allowFailure.signal()
4850
+ wait(for: [firstDone, secondDone], timeout: 5.0)
4851
+
4852
+ XCTAssertTrue(firstFailed)
4853
+ XCTAssertTrue(secondFailed)
4854
+ XCTAssertEqual(updater.downloadCalls, 1)
4855
+
4856
+ // Slot must be cleared so a subsequent retry executes cleanly.
4857
+ let recovered = BundleInfo(
4858
+ id: "recovered-id",
4859
+ version: "3.0.0",
4860
+ status: .PENDING,
4861
+ downloaded: Date(),
4862
+ checksum: "abc123"
4863
+ )
4864
+ updater.downloadedBundleValue = recovered
4865
+ updater.onDownloadStart = nil
4866
+
4867
+ let retryBundle = try testPlugin.downloadBundleForTesting(
4868
+ urlString: "https://example.com/update-3.0.0.zip",
4869
+ version: "3.0.0",
4870
+ sessionKey: "",
4871
+ checksum: "abc123",
4872
+ manifestEntries: nil
4873
+ )
4874
+ XCTAssertEqual(retryBundle.getId(), "recovered-id")
4875
+ XCTAssertEqual(updater.downloadCalls, 2)
4876
+ }
4877
+
4878
+ func testCoalescedDownloadEnforcesHttpsOnlyForJoiningZipAndManifestCallers() throws {
4879
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4880
+ CryptoCipher.setLogger(testLogger)
4881
+ let downloadEntered = OnceSignal()
4882
+ let allowFinish = OnceSignal()
4883
+
4884
+ let completedBundle = BundleInfo(
4885
+ id: "secure-id",
4886
+ version: "4.0.0",
4887
+ status: .PENDING,
4888
+ downloaded: Date(),
4889
+ checksum: "abc123"
4890
+ )
4891
+ let updater = CoalescingDownloadCapgoUpdater()
4892
+ updater.setLogger(testLogger)
4893
+ updater.httpsOnly = true
4894
+ updater.downloadedBundleValue = completedBundle
4895
+ updater.onDownloadStart = {
4896
+ downloadEntered.signal()
4897
+ _ = allowFinish.wait(timeout: .now() + 5.0)
4898
+ }
4899
+
4900
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
4901
+ testPlugin.implementation = updater
4902
+ var waiterJoinedCount = 0
4903
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in
4904
+ waiterJoinedCount += 1
4905
+ }
4906
+
4907
+ let firstDone = expectation(description: "https download succeeded")
4908
+ DispatchQueue.global(qos: .userInitiated).async {
4909
+ defer { firstDone.fulfill() }
4910
+ do {
4911
+ let bundle = try testPlugin.downloadBundleForTesting(
4912
+ urlString: "https://example.com/update-4.0.0.zip",
4913
+ version: "4.0.0",
4914
+ sessionKey: "",
4915
+ checksum: "abc123",
4916
+ manifestEntries: nil
4917
+ )
4918
+ XCTAssertEqual(bundle.getId(), "secure-id")
4919
+ } catch {
4920
+ XCTFail("HTTPS download should succeed: \(error.localizedDescription)")
4921
+ }
4922
+ }
4923
+
4924
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
4925
+
4926
+ // Plain HTTP zip caller must fail httpsOnly before joining the in-flight HTTPS download.
4927
+ XCTAssertThrowsError(
4928
+ try testPlugin.downloadBundleForTesting(
4929
+ urlString: "http://example.com/update-4.0.0.zip",
4930
+ version: "4.0.0",
4931
+ sessionKey: "",
4932
+ checksum: "abc123",
4933
+ manifestEntries: nil
4934
+ )
4935
+ ) { error in
4936
+ XCTAssertEqual((error as NSError).code, 7)
4937
+ }
4938
+
4939
+ // Manifest caller containing a plain HTTP entry URL must also fail httpsOnly before joining.
4940
+ let insecureManifest = [
4941
+ ManifestEntry(
4942
+ file_name: "index.html",
4943
+ file_hash: "deadbeef",
4944
+ download_url: "http://example.com/index.html"
4945
+ )
4946
+ ]
4947
+ XCTAssertThrowsError(
4948
+ try testPlugin.downloadBundleForTesting(
4949
+ urlString: "https://example.com/manifest-4.0.0",
4950
+ version: "4.0.0",
4951
+ sessionKey: "",
4952
+ checksum: "",
4953
+ manifestEntries: insecureManifest
4954
+ )
4955
+ ) { error in
4956
+ XCTAssertEqual((error as NSError).code, 7)
4957
+ }
4958
+
4959
+ XCTAssertEqual(waiterJoinedCount, 0)
4960
+ allowFinish.signal()
4961
+ wait(for: [firstDone], timeout: 5.0)
4962
+ }
4963
+
4964
+ func testConcurrentManifestAndZipDownloadsSerializeWithoutDeletingCompletedBundle() throws {
4965
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4966
+ CryptoCipher.setLogger(testLogger)
4967
+ let manifestEntered = OnceSignal()
4968
+ let waiterJoined = OnceSignal()
4969
+ let allowManifestFinish = OnceSignal()
4970
+
4971
+ let current = BundleInfo(
4972
+ id: "current-id",
4973
+ version: "1.0.0",
4974
+ status: .SUCCESS,
4975
+ downloaded: Date(),
4976
+ checksum: "current-checksum"
4977
+ )
4978
+ let manifestBundle = BundleInfo(
4979
+ id: "manifest-id",
4980
+ version: "5.0.0",
4981
+ status: .PENDING,
4982
+ downloaded: Date(),
4983
+ checksum: ""
4984
+ )
4985
+ let zipBundle = BundleInfo(
4986
+ id: "zip-id",
4987
+ version: "5.0.0",
4988
+ status: .PENDING,
4989
+ downloaded: Date(),
4990
+ checksum: "zip-checksum"
4991
+ )
4992
+ let latest = AppVersion()
4993
+ latest.version = "5.0.0"
4994
+ latest.url = "https://example.com/update-5.0.0.zip"
4995
+ latest.checksum = "zip-checksum"
4996
+
4997
+ let updater = CoalescingDownloadCapgoUpdater()
4998
+ updater.setLogger(testLogger)
4999
+ updater.currentBundleValue = current
5000
+ updater.latestResponse = latest
5001
+ updater.downloadedManifestBundleValue = manifestBundle
5002
+ updater.downloadedBundleValue = zipBundle
5003
+ updater.onManifestDownloadStart = {
5004
+ updater.existingBundleValue = BundleInfo(
5005
+ id: "manifest-id",
5006
+ version: "5.0.0",
5007
+ status: .DOWNLOADING,
5008
+ downloaded: Date(),
5009
+ checksum: ""
5010
+ )
5011
+ manifestEntered.signal()
5012
+ _ = allowManifestFinish.wait(timeout: .now() + 5.0)
5013
+ updater.existingBundleValue = manifestBundle
5014
+ }
5015
+ let backgroundFinished = expectation(description: "background zip download finished")
5016
+ updater.onSetNextBundle = {
5017
+ backgroundFinished.fulfill()
5018
+ }
5019
+
5020
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5021
+ testPlugin.implementation = updater
5022
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5023
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5024
+ testPlugin.onCoalesceWaiterJoinedForTesting = { version in
5025
+ if version == "5.0.0" {
5026
+ waiterJoined.signal()
5027
+ }
5028
+ }
5029
+
5030
+ let manifestDone = expectation(description: "manifest download finished")
5031
+ var manifestResultId: String?
5032
+ let manifest = [
5033
+ ManifestEntry(
5034
+ file_name: "index.html",
5035
+ file_hash: "file-hash-1",
5036
+ download_url: "https://example.com/index.html"
5037
+ )
5038
+ ]
5039
+
5040
+ DispatchQueue.global(qos: .userInitiated).async {
5041
+ defer { manifestDone.fulfill() }
5042
+ do {
5043
+ let bundle = try testPlugin.downloadBundleForTesting(
5044
+ urlString: "https://example.com/manifest-5.0.0",
5045
+ version: "5.0.0",
5046
+ sessionKey: "",
5047
+ checksum: "",
5048
+ manifestEntries: manifest
5049
+ )
5050
+ manifestResultId = bundle.getId()
5051
+ } catch {
5052
+ XCTFail("Manifest download should succeed: \(error.localizedDescription)")
5053
+ }
5054
+ }
5055
+
5056
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5057
+
5058
+ testPlugin.backgroundDownload()
5059
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5060
+ XCTAssertEqual(updater.downloadCalls, 0)
5061
+
5062
+ allowManifestFinish.signal()
5063
+ wait(for: [manifestDone, backgroundFinished], timeout: 5.0)
5064
+
5065
+ XCTAssertEqual(manifestResultId, "manifest-id")
5066
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5067
+ XCTAssertEqual(updater.downloadCalls, 1)
5068
+ XCTAssertEqual(updater.deleteCalls, 0)
5069
+ XCTAssertEqual(updater.lastSetNextBundleId, "zip-id")
5070
+ }
5071
+
5072
+ func testConcurrentManifestDownloadsCoalesceOnlyWhenManifestMatches() throws {
5073
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5074
+ CryptoCipher.setLogger(testLogger)
5075
+
5076
+ let manifestA = [
5077
+ ManifestEntry(file_name: "index.html.br", file_hash: "hash-index", download_url: "https://cdn-a.example.com/index.html.br"),
5078
+ ManifestEntry(file_name: "app.js", file_hash: "hash-app", download_url: "https://cdn-a.example.com/app.js")
5079
+ ]
5080
+ let manifestAEquivalent = [
5081
+ ManifestEntry(file_name: "app.js", file_hash: "hash-app", download_url: "https://cdn-b.example.com/app.js?sig=2"),
5082
+ ManifestEntry(file_name: "index.html", file_hash: "hash-index", download_url: "https://cdn-b.example.com/index.html?sig=2")
5083
+ ]
5084
+ let manifestB = [
5085
+ ManifestEntry(file_name: "index.html", file_hash: "different-hash", download_url: "https://cdn-a.example.com/index.html")
5086
+ ]
5087
+
5088
+ // 1. Equivalent manifests coalesce into a single download.
5089
+ do {
5090
+ let manifestEntered = OnceSignal()
5091
+ let waiterJoined = OnceSignal()
5092
+ let allowFinish = OnceSignal()
5093
+
5094
+ let updater = CoalescingDownloadCapgoUpdater()
5095
+ updater.setLogger(testLogger)
5096
+ updater.downloadedManifestBundleValue = BundleInfo(
5097
+ id: "manifest-shared",
5098
+ version: "6.0.0",
5099
+ status: .PENDING,
5100
+ downloaded: Date(),
5101
+ checksum: ""
5102
+ )
5103
+ updater.onManifestDownloadStart = {
5104
+ manifestEntered.signal()
5105
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5106
+ }
5107
+
5108
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5109
+ testPlugin.implementation = updater
5110
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5111
+
5112
+ let firstDone = expectation(description: "first matching manifest finished")
5113
+ let secondDone = expectation(description: "second matching manifest finished")
5114
+ var secondId: String?
5115
+
5116
+ DispatchQueue.global(qos: .userInitiated).async {
5117
+ defer { firstDone.fulfill() }
5118
+ _ = try? testPlugin.downloadBundleForTesting(
5119
+ urlString: "https://example.com/m",
5120
+ version: "6.0.0",
5121
+ sessionKey: "",
5122
+ checksum: "",
5123
+ manifestEntries: manifestA
5124
+ )
5125
+ }
5126
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5127
+
5128
+ DispatchQueue.global(qos: .userInitiated).async {
5129
+ defer { secondDone.fulfill() }
5130
+ secondId = try? testPlugin.downloadBundleForTesting(
5131
+ urlString: "https://example.com/m",
5132
+ version: "6.0.0",
5133
+ sessionKey: "",
5134
+ checksum: "",
5135
+ manifestEntries: manifestAEquivalent
5136
+ ).getId()
5137
+ }
5138
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5139
+ allowFinish.signal()
5140
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5141
+
5142
+ XCTAssertEqual(secondId, "manifest-shared")
5143
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5144
+ }
5145
+
5146
+ // 2. Different manifests for the same version serialize and both execute.
5147
+ do {
5148
+ let manifestEntered = OnceSignal()
5149
+ let waiterJoined = OnceSignal()
5150
+ let allowFinish = OnceSignal()
5151
+
5152
+ let updater = CoalescingDownloadCapgoUpdater()
5153
+ updater.setLogger(testLogger)
5154
+ updater.manifestDownloadBundles = [
5155
+ BundleInfo(id: "manifest-a", version: "6.0.1", status: .PENDING, downloaded: Date(), checksum: ""),
5156
+ BundleInfo(id: "manifest-b", version: "6.0.1", status: .PENDING, downloaded: Date(), checksum: "")
5157
+ ]
5158
+ updater.onManifestDownloadStart = {
5159
+ if manifestEntered.signal() {
5160
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5161
+ }
5162
+ }
5163
+
5164
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5165
+ testPlugin.implementation = updater
5166
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5167
+
5168
+ let firstDone = expectation(description: "manifest A finished")
5169
+ let secondDone = expectation(description: "manifest B finished")
5170
+ var firstId: String?
5171
+ var secondId: String?
5172
+
5173
+ DispatchQueue.global(qos: .userInitiated).async {
5174
+ defer { firstDone.fulfill() }
5175
+ firstId = try? testPlugin.downloadBundleForTesting(
5176
+ urlString: "https://example.com/m",
5177
+ version: "6.0.1",
5178
+ sessionKey: "",
5179
+ checksum: "",
5180
+ manifestEntries: manifestA
5181
+ ).getId()
5182
+ }
5183
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5184
+
5185
+ DispatchQueue.global(qos: .userInitiated).async {
5186
+ defer { secondDone.fulfill() }
5187
+ secondId = try? testPlugin.downloadBundleForTesting(
5188
+ urlString: "https://example.com/m",
5189
+ version: "6.0.1",
5190
+ sessionKey: "",
5191
+ checksum: "",
5192
+ manifestEntries: manifestB
5193
+ ).getId()
5194
+ }
5195
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5196
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5197
+
5198
+ allowFinish.signal()
5199
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5200
+
5201
+ XCTAssertEqual(firstId, "manifest-a")
5202
+ XCTAssertEqual(secondId, "manifest-b")
5203
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5204
+ }
5205
+ }
5206
+
5207
+ func testBackgroundDownloadWithMissingChecksumCleansStaleIncompleteBundleOnlyWhenIdle() throws {
5208
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5209
+ CryptoCipher.setLogger(testLogger)
5210
+
5211
+ // 1. Idle: stale DOWNLOADING bundle is cleaned before reporting checksum_required.
5212
+ do {
5213
+ let stale = makeOnlyDownloadBundle(id: "stale-id", status: .DOWNLOADING, checksum: "")
5214
+ let (testPlugin, implementation) = makeAtBackgroundPlugin(existing: stale)
5215
+ implementation.setLogger(testLogger)
5216
+ implementation.latestResponse.checksum = ""
5217
+
5218
+ testPlugin.backgroundDownload()
5219
+
5220
+ XCTAssertEqual(implementation.deleteCalls, 1)
5221
+ XCTAssertEqual(implementation.lastDeletedId, "stale-id")
5222
+ XCTAssertTrue(implementation.sentStatsActions.contains("checksum_required"))
5223
+ }
5224
+
5225
+ // 2. Active in-flight download: checksum-less background response does not delete it.
5226
+ do {
5227
+ let downloadEntered = OnceSignal()
5228
+ let allowFinish = OnceSignal()
5229
+
5230
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
5231
+ let inFlight = BundleInfo(id: "active-id", version: "7.0.0", status: .DOWNLOADING, downloaded: Date(), checksum: "")
5232
+ let completed = BundleInfo(id: "active-id", version: "7.0.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
5233
+ let latest = AppVersion()
5234
+ latest.version = "7.0.0"
5235
+ latest.url = "https://example.com/update-7.0.0.zip"
5236
+ latest.checksum = ""
5237
+
5238
+ let updater = CoalescingDownloadCapgoUpdater()
5239
+ updater.setLogger(testLogger)
5240
+ updater.currentBundleValue = current
5241
+ updater.latestResponse = latest
5242
+ updater.downloadedBundleValue = completed
5243
+ updater.onDownloadStart = {
5244
+ updater.existingBundleValue = inFlight
5245
+ downloadEntered.signal()
5246
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5247
+ updater.existingBundleValue = completed
5248
+ }
5249
+
5250
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5251
+ testPlugin.implementation = updater
5252
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5253
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5254
+
5255
+ let bgDone = expectation(description: "background checksum_required completed")
5256
+ testPlugin.onSendReadyToJs = { msg in
5257
+ if msg == "Checksum required" {
5258
+ bgDone.fulfill()
5259
+ }
5260
+ }
5261
+
5262
+ let jsDone = expectation(description: "active JS download finished")
5263
+ DispatchQueue.global(qos: .userInitiated).async {
5264
+ defer { jsDone.fulfill() }
5265
+ _ = try? testPlugin.downloadBundleForTesting(
5266
+ urlString: "https://example.com/update-7.0.0.zip",
5267
+ version: "7.0.0",
5268
+ sessionKey: "",
5269
+ checksum: "abc123",
5270
+ manifestEntries: nil
5271
+ )
5272
+ }
5273
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5274
+
5275
+ testPlugin.backgroundDownload()
5276
+ wait(for: [bgDone], timeout: 5.0)
5277
+ XCTAssertEqual(updater.deleteCalls, 0)
5278
+ XCTAssertTrue(updater.sentStatsActions.contains("checksum_required"))
5279
+
5280
+ allowFinish.signal()
5281
+ wait(for: [jsDone], timeout: 5.0)
5282
+ }
5283
+ }
5284
+
5285
+ func testBackgroundDownloadDoesNotRegressAlreadyActiveBundleToPending() throws {
5286
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5287
+ CryptoCipher.setLogger(testLogger)
5288
+ let downloadEntered = OnceSignal()
5289
+ let waiterJoined = OnceSignal()
5290
+ let allowFinish = OnceSignal()
5291
+
5292
+ let initialCurrent = BundleInfo(
5293
+ id: "old-id",
5294
+ version: "1.0.0",
5295
+ status: .SUCCESS,
5296
+ downloaded: Date(),
5297
+ checksum: "old-checksum"
5298
+ )
5299
+ let downloaded = BundleInfo(
5300
+ id: "active-2.0.0",
5301
+ version: "2.0.0",
5302
+ status: .PENDING,
5303
+ downloaded: Date(),
5304
+ checksum: "abc123"
5305
+ )
5306
+ let activated = BundleInfo(
5307
+ id: "active-2.0.0",
5308
+ version: "2.0.0",
5309
+ status: .SUCCESS,
5310
+ downloaded: Date(),
5311
+ checksum: "abc123"
5312
+ )
5313
+ let latest = AppVersion()
5314
+ latest.version = "2.0.0"
5315
+ latest.url = "https://example.com/update-2.0.0.zip"
5316
+ latest.checksum = "abc123"
5317
+
5318
+ let updater = CoalescingDownloadCapgoUpdater()
5319
+ updater.setLogger(testLogger)
5320
+ updater.currentBundleValue = initialCurrent
5321
+ updater.latestResponse = latest
5322
+ updater.downloadedBundleValue = downloaded
5323
+ updater.onDownloadStart = {
5324
+ downloadEntered.signal()
5325
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5326
+ // Simulate JS activating and confirming the bundle before backgroundDownload queues next.
5327
+ updater.currentBundleValue = activated
5328
+ }
5329
+
5330
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5331
+ testPlugin.implementation = updater
5332
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5333
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5334
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5335
+
5336
+ let bgDone = expectation(description: "backgroundDownload skipped queueing active bundle")
5337
+ testPlugin.onSendReadyToJs = { msg in
5338
+ if msg == "No need to update" {
5339
+ bgDone.fulfill()
5340
+ }
5341
+ }
5342
+
5343
+ let jsDone = expectation(description: "JS download finished")
5344
+ DispatchQueue.global(qos: .userInitiated).async {
5345
+ defer { jsDone.fulfill() }
5346
+ _ = try? testPlugin.downloadBundleForTesting(
5347
+ urlString: "https://example.com/update-2.0.0.zip",
5348
+ version: "2.0.0",
5349
+ sessionKey: "",
5350
+ checksum: "abc123",
5351
+ manifestEntries: nil
5352
+ )
5353
+ }
5354
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5355
+
5356
+ testPlugin.backgroundDownload()
5357
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5358
+ allowFinish.signal()
5359
+
5360
+ wait(for: [jsDone, bgDone], timeout: 5.0)
5361
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
5362
+ XCTAssertEqual(updater.getCurrentBundle().getStatus(), BundleStatus.SUCCESS.storedValue)
5363
+ }
5364
+
5365
+ func testCoalescedDownloadRequiresExactVersionMatchAndValidSessionKey() throws {
5366
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5367
+ CryptoCipher.setLogger(testLogger)
5368
+
5369
+ // 1. Whitespace-differing version strings serialize instead of sharing a mismatched version.
5370
+ do {
5371
+ let downloadEntered = OnceSignal()
5372
+ let waiterJoined = OnceSignal()
5373
+ let allowFinish = OnceSignal()
5374
+
5375
+ let updater = CoalescingDownloadCapgoUpdater()
5376
+ updater.setLogger(testLogger)
5377
+ updater.zipDownloadBundles = [
5378
+ BundleInfo(id: "padded-id", version: " 8.0.0 ", status: .PENDING, downloaded: Date(), checksum: "abc123"),
5379
+ BundleInfo(id: "trimmed-id", version: "8.0.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
5380
+ ]
5381
+ updater.onDownloadStart = {
5382
+ if downloadEntered.signal() {
5383
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5384
+ }
5385
+ }
5386
+
5387
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5388
+ testPlugin.implementation = updater
5389
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5390
+
5391
+ let firstDone = expectation(description: "padded version finished")
5392
+ let secondDone = expectation(description: "trimmed version finished")
5393
+ var firstVersion: String?
5394
+ var secondVersion: String?
5395
+
5396
+ DispatchQueue.global(qos: .userInitiated).async {
5397
+ defer { firstDone.fulfill() }
5398
+ firstVersion = try? testPlugin.downloadBundleForTesting(
5399
+ urlString: "https://example.com/update-8.0.0.zip",
5400
+ version: " 8.0.0 ",
5401
+ sessionKey: "",
5402
+ checksum: "abc123",
5403
+ manifestEntries: nil
5404
+ ).getVersionName()
5405
+ }
5406
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5407
+
5408
+ DispatchQueue.global(qos: .userInitiated).async {
5409
+ defer { secondDone.fulfill() }
5410
+ secondVersion = try? testPlugin.downloadBundleForTesting(
5411
+ urlString: "https://example.com/update-8.0.0.zip",
5412
+ version: "8.0.0",
5413
+ sessionKey: "",
5414
+ checksum: "abc123",
5415
+ manifestEntries: nil
5416
+ ).getVersionName()
5417
+ }
5418
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5419
+ XCTAssertEqual(updater.downloadCalls, 1)
5420
+
5421
+ allowFinish.signal()
5422
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5423
+
5424
+ XCTAssertEqual(firstVersion, " 8.0.0 ")
5425
+ XCTAssertEqual(secondVersion, "8.0.0")
5426
+ XCTAssertEqual(updater.downloadCalls, 2)
5427
+ }
5428
+
5429
+ // 2. Undecodable sessionKey fails immediately even when a valid encrypted download is in flight.
5430
+ do {
5431
+ let directory = try XCTUnwrap(CliCryptoFixtureTests.fixtureDirectories().first)
5432
+ let json = try Data(contentsOf: directory.appendingPathComponent("cli-crypto.json"))
5433
+ let fixture = try XCTUnwrap(try JSONSerialization.jsonObject(with: json) as? [String: Any])
5434
+ let publicKeyPem = try XCTUnwrap(fixture["publicKey"] as? String)
5435
+ let bundle = try XCTUnwrap((fixture["bundles"] as? [[String: Any]])?.first)
5436
+ let encryptedChecksumHex = try XCTUnwrap(bundle["checksum"] as? String)
5437
+ let expectedDecryptedChecksum = try XCTUnwrap(bundle["sha256"] as? String)
5438
+ let validSessionKey = try XCTUnwrap(bundle["ivSessionKey"] as? String)
5439
+
5440
+ let downloadEntered = OnceSignal()
5441
+ let allowFinish = OnceSignal()
5442
+
5443
+ let updater = CoalescingDownloadCapgoUpdater()
5444
+ updater.setLogger(testLogger)
5445
+ updater.setPublicKey(publicKeyPem)
5446
+ updater.downloadedBundleValue = BundleInfo(
5447
+ id: "encrypted-id",
5448
+ version: "8.1.0",
5449
+ status: .PENDING,
5450
+ downloaded: Date(),
5451
+ checksum: expectedDecryptedChecksum
5452
+ )
5453
+ updater.onDownloadStart = {
5454
+ downloadEntered.signal()
5455
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5456
+ }
5457
+
5458
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5459
+ testPlugin.implementation = updater
5460
+ var waiterJoinedCount = 0
5461
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoinedCount += 1 }
5462
+
5463
+ let ownerDone = expectation(description: "encrypted owner finished")
5464
+ DispatchQueue.global(qos: .userInitiated).async {
5465
+ defer { ownerDone.fulfill() }
5466
+ do {
5467
+ let bundle = try testPlugin.downloadBundleForTesting(
5468
+ urlString: "https://example.com/update-8.1.0.zip",
5469
+ version: "8.1.0",
5470
+ sessionKey: validSessionKey,
5471
+ checksum: encryptedChecksumHex,
5472
+ manifestEntries: nil
5473
+ )
5474
+ XCTAssertEqual(bundle.getId(), "encrypted-id")
5475
+ } catch {
5476
+ XCTFail("Valid encrypted download should succeed: \(error.localizedDescription)")
5477
+ }
5478
+ }
5479
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5480
+
5481
+ XCTAssertThrowsError(
5482
+ try testPlugin.downloadBundleForTesting(
5483
+ urlString: "https://example.com/update-8.1.0.zip",
5484
+ version: "8.1.0",
5485
+ sessionKey: "not-base64:not-a-valid-key",
5486
+ checksum: encryptedChecksumHex,
5487
+ manifestEntries: nil
5488
+ )
5489
+ )
5490
+ XCTAssertEqual(waiterJoinedCount, 0)
5491
+
5492
+ allowFinish.signal()
5493
+ wait(for: [ownerDone], timeout: 5.0)
5494
+ }
5495
+ }
5496
+
5497
+ func testBackgroundDownloadSerializesDifferingManifestEvenAfterInFlightPersistsPending() throws {
5498
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5499
+ CryptoCipher.setLogger(testLogger)
5500
+ let manifestEntered = OnceSignal()
5501
+ let waiterJoined = OnceSignal()
5502
+ let allowFinish = OnceSignal()
5503
+
5504
+ let current = BundleInfo(
5505
+ id: "current-id",
5506
+ version: "1.0.0",
5507
+ status: .SUCCESS,
5508
+ downloaded: Date(),
5509
+ checksum: "cur"
5510
+ )
5511
+ let manifestABundle = BundleInfo(
5512
+ id: "manifest-a-pending",
5513
+ version: "8.2.0",
5514
+ status: .PENDING,
5515
+ downloaded: Date(),
5516
+ checksum: ""
5517
+ )
5518
+ let manifestBBundle = BundleInfo(
5519
+ id: "manifest-b-pending",
5520
+ version: "8.2.0",
5521
+ status: .PENDING,
5522
+ downloaded: Date(),
5523
+ checksum: ""
5524
+ )
5525
+ let manifestA = [
5526
+ ManifestEntry(file_name: "index.html", file_hash: "hash-a", download_url: "https://example.com/a/index.html")
5527
+ ]
5528
+ let manifestB = [
5529
+ ManifestEntry(file_name: "index.html", file_hash: "hash-b", download_url: "https://example.com/b/index.html")
5530
+ ]
5531
+
5532
+ let latest = AppVersion()
5533
+ latest.version = "8.2.0"
5534
+ latest.url = "https://example.com/manifest-8.2.0"
5535
+ latest.manifest = manifestB
5536
+
5537
+ let updater = CoalescingDownloadCapgoUpdater()
5538
+ updater.setLogger(testLogger)
5539
+ updater.currentBundleValue = current
5540
+ updater.latestResponse = latest
5541
+ updater.manifestDownloadBundles = [manifestABundle, manifestBBundle]
5542
+ updater.onManifestDownloadStart = {
5543
+ if manifestEntered.signal() {
5544
+ // Simulate downloadManifest persisting PENDING before the in-flight slot is released.
5545
+ updater.existingBundleValue = manifestABundle
5546
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5547
+ }
5548
+ }
5549
+ let bgFinished = expectation(description: "background downloaded manifest B")
5550
+ updater.onSetNextBundle = {
5551
+ bgFinished.fulfill()
5552
+ }
5553
+
5554
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5555
+ testPlugin.implementation = updater
5556
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5557
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5558
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5559
+
5560
+ let jsDone = expectation(description: "JS manifest A finished")
5561
+ DispatchQueue.global(qos: .userInitiated).async {
5562
+ defer { jsDone.fulfill() }
5563
+ _ = try? testPlugin.downloadBundleForTesting(
5564
+ urlString: "https://example.com/manifest-8.2.0",
5565
+ version: "8.2.0",
5566
+ sessionKey: "",
5567
+ checksum: "",
5568
+ manifestEntries: manifestA
5569
+ )
5570
+ }
5571
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5572
+
5573
+ testPlugin.backgroundDownload()
5574
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5575
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5576
+
5577
+ allowFinish.signal()
5578
+ wait(for: [jsDone, bgFinished], timeout: 5.0)
5579
+
5580
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5581
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-b-pending")
5582
+ }
5583
+
5584
+ func testCoalescedDownloadRetriesDifferentSourceUrlAfterLeaderFailure() throws {
5585
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5586
+ CryptoCipher.setLogger(testLogger)
5587
+ let downloadEntered = OnceSignal()
5588
+ let waiterJoined = OnceSignal()
5589
+ let allowFailure = OnceSignal()
5590
+
5591
+ let recovered = BundleInfo(
5592
+ id: "fallback-url-id",
5593
+ version: "9.0.0",
5594
+ status: .PENDING,
5595
+ downloaded: Date(),
5596
+ checksum: "abc123"
5597
+ )
5598
+ let updater = CoalescingDownloadCapgoUpdater()
5599
+ updater.setLogger(testLogger)
5600
+ updater.zipDownloadBundles = [nil, recovered]
5601
+ updater.onDownloadStart = {
5602
+ if downloadEntered.signal() {
5603
+ _ = allowFailure.wait(timeout: .now() + 5.0)
5604
+ }
5605
+ }
5606
+
5607
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5608
+ testPlugin.implementation = updater
5609
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5610
+
5611
+ let firstDone = expectation(description: "first URL failed")
5612
+ let secondDone = expectation(description: "different URL retried and succeeded")
5613
+ var firstFailed = false
5614
+ var secondId: String?
5615
+
5616
+ DispatchQueue.global(qos: .userInitiated).async {
5617
+ defer { firstDone.fulfill() }
5618
+ do {
5619
+ _ = try testPlugin.downloadBundleForTesting(
5620
+ urlString: "https://cdn-a.example.com/update-9.0.0.zip",
5621
+ version: "9.0.0",
5622
+ sessionKey: "",
5623
+ checksum: "abc123",
5624
+ manifestEntries: nil
5625
+ )
5626
+ } catch {
5627
+ firstFailed = true
5628
+ }
5629
+ }
5630
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5631
+
5632
+ DispatchQueue.global(qos: .userInitiated).async {
5633
+ defer { secondDone.fulfill() }
5634
+ secondId = try? testPlugin.downloadBundleForTesting(
5635
+ urlString: "https://cdn-b.example.com/update-9.0.0.zip",
5636
+ version: "9.0.0",
5637
+ sessionKey: "",
5638
+ checksum: "abc123",
5639
+ manifestEntries: nil
5640
+ ).getId()
5641
+ }
5642
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5643
+ allowFailure.signal()
5644
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5645
+
5646
+ XCTAssertTrue(firstFailed)
5647
+ XCTAssertEqual(secondId, "fallback-url-id")
5648
+ XCTAssertEqual(updater.downloadCalls, 2)
5649
+ }
5650
+
5651
+ func testBackgroundDownloadRejectsRetainedErrorBundleEvenWhileJsDownloadsSameVersion() throws {
5652
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5653
+ CryptoCipher.setLogger(testLogger)
5654
+ let downloadEntered = OnceSignal()
5655
+ let allowFinish = OnceSignal()
5656
+
5657
+ let current = BundleInfo(
5658
+ id: "current-id",
5659
+ version: "1.0.0",
5660
+ status: .SUCCESS,
5661
+ downloaded: Date(),
5662
+ checksum: "cur"
5663
+ )
5664
+ let retainedError = BundleInfo(
5665
+ id: "failed-9.1.0",
5666
+ version: "9.1.0",
5667
+ status: .ERROR,
5668
+ downloaded: Date(),
5669
+ checksum: "abc123"
5670
+ )
5671
+ let jsBundle = BundleInfo(
5672
+ id: "js-9.1.0",
5673
+ version: "9.1.0",
5674
+ status: .PENDING,
5675
+ downloaded: Date(),
5676
+ checksum: "abc123"
5677
+ )
5678
+ let latest = AppVersion()
5679
+ latest.version = "9.1.0"
5680
+ latest.url = "https://example.com/update-9.1.0.zip"
5681
+ latest.checksum = "abc123"
5682
+
5683
+ let updater = CoalescingDownloadCapgoUpdater()
5684
+ updater.setLogger(testLogger)
5685
+ updater.currentBundleValue = current
5686
+ updater.existingBundleValue = retainedError
5687
+ updater.latestResponse = latest
5688
+ updater.downloadedBundleValue = jsBundle
5689
+ updater.onDownloadStart = {
5690
+ downloadEntered.signal()
5691
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5692
+ }
5693
+
5694
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5695
+ testPlugin.implementation = updater
5696
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5697
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5698
+
5699
+ let bgRejected = expectation(description: "backgroundDownload rejected retained ERROR bundle")
5700
+ testPlugin.onSendReadyToJs = { msg in
5701
+ if msg == "Latest version is in error state. Aborting update." {
5702
+ bgRejected.fulfill()
5703
+ }
5704
+ }
5705
+
5706
+ let jsDone = expectation(description: "JS download succeeded")
5707
+ DispatchQueue.global(qos: .userInitiated).async {
5708
+ defer { jsDone.fulfill() }
5709
+ _ = try? testPlugin.downloadBundleForTesting(
5710
+ urlString: "https://example.com/update-9.1.0.zip",
5711
+ version: "9.1.0",
5712
+ sessionKey: "",
5713
+ checksum: "abc123",
5714
+ manifestEntries: nil
5715
+ )
5716
+ }
5717
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5718
+
5719
+ testPlugin.backgroundDownload()
5720
+ wait(for: [bgRejected], timeout: 5.0)
5721
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
5722
+
5723
+ allowFinish.signal()
5724
+ wait(for: [jsDone], timeout: 5.0)
5725
+ }
5726
+
5727
+ func testBackgroundDownloadDoesNotReuseMismatchedCompletedManifestBundle() throws {
5728
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5729
+ CryptoCipher.setLogger(testLogger)
5730
+
5731
+ let current = BundleInfo(
5732
+ id: "current-id",
5733
+ version: "1.0.0",
5734
+ status: .SUCCESS,
5735
+ downloaded: Date(),
5736
+ checksum: "cur"
5737
+ )
5738
+ let manifestABundle = BundleInfo(
5739
+ id: "manifest-a-id",
5740
+ version: "9.2.0",
5741
+ status: .PENDING,
5742
+ downloaded: Date(),
5743
+ checksum: ""
5744
+ )
5745
+ let manifestBBundle = BundleInfo(
5746
+ id: "manifest-b-id",
5747
+ version: "9.2.0",
5748
+ status: .PENDING,
5749
+ downloaded: Date(),
5750
+ checksum: ""
5751
+ )
5752
+ let manifestA = [
5753
+ ManifestEntry(
5754
+ file_name: "index.html",
5755
+ file_hash: "hash-manifest-a",
5756
+ download_url: "https://example.com/a/index.html"
5757
+ )
5758
+ ]
5759
+ let manifestB = [
5760
+ ManifestEntry(
5761
+ file_name: "index.html",
5762
+ file_hash: "hash-manifest-b",
5763
+ download_url: "https://example.com/b/index.html"
5764
+ )
5765
+ ]
5766
+
5767
+ let latest = AppVersion()
5768
+ latest.version = "9.2.0"
5769
+ latest.url = "https://example.com/manifest-9.2.0"
5770
+ latest.manifest = manifestB
5771
+
5772
+ let updater = CoalescingDownloadCapgoUpdater()
5773
+ updater.setLogger(testLogger)
5774
+ updater.currentBundleValue = current
5775
+ updater.latestResponse = latest
5776
+ updater.manifestDownloadBundles = [manifestABundle, manifestBBundle]
5777
+
5778
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5779
+ testPlugin.implementation = updater
5780
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5781
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5782
+
5783
+ let jsBundle = try testPlugin.downloadBundleForTesting(
5784
+ urlString: "https://example.com/manifest-9.2.0",
5785
+ version: "9.2.0",
5786
+ sessionKey: "",
5787
+ checksum: "",
5788
+ manifestEntries: manifestA
5789
+ )
5790
+ XCTAssertEqual(jsBundle.getId(), "manifest-a-id")
5791
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5792
+ updater.existingBundleValue = manifestABundle
5793
+
5794
+ let mismatchHandled = expectation(description: "backgroundDownload downloaded manifest B instead of reusing manifest A")
5795
+ testPlugin.onSendReadyToJs = { _ in
5796
+ mismatchHandled.fulfill()
5797
+ }
5798
+ testPlugin.backgroundDownload()
5799
+ wait(for: [mismatchHandled], timeout: 5.0)
5800
+
5801
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5802
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-b-id")
5803
+
5804
+ // A subsequent backgroundDownload requesting the same manifest B should reuse it.
5805
+ updater.existingBundleValue = manifestBBundle
5806
+ let matchReused = expectation(description: "backgroundDownload reused matching manifest B")
5807
+ testPlugin.onSendReadyToJs = { _ in
5808
+ matchReused.fulfill()
5809
+ }
5810
+ testPlugin.backgroundDownload()
5811
+ wait(for: [matchReused], timeout: 5.0)
5812
+
5813
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5814
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-b-id")
5815
+ }
5816
+
5817
+ func testBackgroundDownloadRejectsRetainedErrorBundleListedAfterNewerSameVersionBundle() throws {
5818
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5819
+ CryptoCipher.setLogger(testLogger)
5820
+ let downloadEntered = OnceSignal()
5821
+ let allowFinish = OnceSignal()
5822
+
5823
+ let current = BundleInfo(
5824
+ id: "current-id",
5825
+ version: "1.0.0",
5826
+ status: .SUCCESS,
5827
+ downloaded: Date(),
5828
+ checksum: "cur"
5829
+ )
5830
+ let retainedError = BundleInfo(
5831
+ id: "failed-9.3.0",
5832
+ version: "9.3.0",
5833
+ status: .ERROR,
5834
+ downloaded: Date(),
5835
+ checksum: "abc123"
5836
+ )
5837
+ let jsBundle = BundleInfo(
5838
+ id: "js-9.3.0",
5839
+ version: "9.3.0",
5840
+ status: .PENDING,
5841
+ downloaded: Date(),
5842
+ checksum: "abc123"
5843
+ )
5844
+ let latest = AppVersion()
5845
+ latest.version = "9.3.0"
5846
+ latest.url = "https://example.com/update-9.3.0.zip"
5847
+ latest.checksum = "abc123"
5848
+
5849
+ let updater = CoalescingDownloadCapgoUpdater()
5850
+ updater.setLogger(testLogger)
5851
+ updater.currentBundleValue = current
5852
+ updater.latestResponse = latest
5853
+ updater.downloadedBundleValue = jsBundle
5854
+ // The retained ERROR copy is listed after the new JS copy, so a first-match lookup would miss it.
5855
+ updater.additionalVersionBundles = [retainedError]
5856
+ updater.onDownloadStart = {
5857
+ updater.existingBundleValue = jsBundle
5858
+ downloadEntered.signal()
5859
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5860
+ }
5861
+
5862
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5863
+ testPlugin.implementation = updater
5864
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5865
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5866
+
5867
+ let bgRejected = expectation(description: "backgroundDownload rejected retained ERROR bundle listed second")
5868
+ testPlugin.onSendReadyToJs = { msg in
5869
+ if msg == "Latest version is in error state. Aborting update." {
5870
+ bgRejected.fulfill()
5871
+ }
5872
+ }
5873
+
5874
+ let jsDone = expectation(description: "JS download succeeded")
5875
+ DispatchQueue.global(qos: .userInitiated).async {
5876
+ defer { jsDone.fulfill() }
5877
+ _ = try? testPlugin.downloadBundleForTesting(
5878
+ urlString: "https://example.com/update-9.3.0.zip",
5879
+ version: "9.3.0",
5880
+ sessionKey: "",
5881
+ checksum: "abc123",
5882
+ manifestEntries: nil
5883
+ )
5884
+ }
5885
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5886
+ XCTAssertEqual(updater.getBundleInfoByVersionName(version: "9.3.0")?.getId(), "js-9.3.0")
5887
+
5888
+ testPlugin.backgroundDownload()
5889
+ wait(for: [bgRejected], timeout: 5.0)
5890
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
5891
+ XCTAssertEqual(updater.downloadCalls, 1)
5892
+
5893
+ allowFinish.signal()
5894
+ wait(for: [jsDone], timeout: 5.0)
5895
+ }
5896
+
5897
+ func testBackgroundDownloadDoesNotReuseManifestBundlePublishedBetweenInFlightCheckAndLookup() throws {
5898
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5899
+ CryptoCipher.setLogger(testLogger)
5900
+ let jsManifestPersisted = OnceSignal()
5901
+ let allowJsFinish = OnceSignal()
5902
+ let backgroundLookupStarted = OnceSignal()
5903
+ let waiterJoined = OnceSignal()
5904
+ let jsReachedSlotAcquire = OnceSignal()
5905
+
5906
+ let current = BundleInfo(
5907
+ id: "current-id",
5908
+ version: "1.0.0",
5909
+ status: .SUCCESS,
5910
+ downloaded: Date(),
5911
+ checksum: "cur"
5912
+ )
5913
+ let manifestABundle = BundleInfo(
5914
+ id: "race-manifest-a",
5915
+ version: "9.4.0",
5916
+ status: .PENDING,
5917
+ downloaded: Date(),
5918
+ checksum: ""
5919
+ )
5920
+ let manifestBBundle = BundleInfo(
5921
+ id: "race-manifest-b",
5922
+ version: "9.4.0",
5923
+ status: .PENDING,
5924
+ downloaded: Date(),
5925
+ checksum: ""
5926
+ )
5927
+ let manifestA = [
5928
+ ManifestEntry(file_name: "index.html", file_hash: "race-hash-a", download_url: "https://example.com/a/index.html")
5929
+ ]
5930
+ let manifestB = [
5931
+ ManifestEntry(file_name: "index.html", file_hash: "race-hash-b", download_url: "https://example.com/b/index.html")
5932
+ ]
5933
+
5934
+ let latest = AppVersion()
5935
+ latest.version = "9.4.0"
5936
+ latest.url = "https://example.com/manifest-9.4.0"
5937
+ latest.manifest = manifestB
5938
+
5939
+ let updater = CoalescingDownloadCapgoUpdater()
5940
+ updater.setLogger(testLogger)
5941
+ updater.currentBundleValue = current
5942
+ updater.latestResponse = latest
5943
+ updater.manifestBundlesByFirstHash = [
5944
+ "race-hash-a": manifestABundle,
5945
+ "race-hash-b": manifestBBundle
5946
+ ]
5947
+ updater.onManifestDownload = { manifest in
5948
+ guard manifest.first?.file_hash == "race-hash-a" else {
5949
+ return
5950
+ }
5951
+ // Simulate downloadManifest persisting PENDING A before its fingerprint is recorded.
5952
+ updater.existingBundleValue = manifestABundle
5953
+ jsManifestPersisted.signal()
5954
+ _ = allowJsFinish.wait(timeout: .now() + 5.0)
5955
+ }
5956
+
5957
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5958
+ testPlugin.implementation = updater
5959
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5960
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5961
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5962
+ // The background check is inside its lookup when this first fires, so the first caller is the JS worker.
5963
+ testPlugin.onDownloadSlotAcquireAttemptForTesting = { _ in jsReachedSlotAcquire.signal() }
5964
+
5965
+ let jsDone = expectation(description: "JS manifest A finished")
5966
+ var jsAtSlotDuringLookup: DispatchTimeoutResult?
5967
+ var persistDuringLookup: DispatchTimeoutResult?
5968
+ // Start the JS download for manifest A exactly when the background check looks up the stored bundle,
5969
+ // i.e. after it decided whether a download is in flight, and give it time to persist A before the lookup
5970
+ // returns. With an atomic snapshot the JS download cannot claim its slot (and so cannot persist A) until the
5971
+ // lookup is done; without it, A is persisted here and was previously reused without a fingerprint check.
5972
+ updater.onVersionLookup = {
5973
+ guard backgroundLookupStarted.signal() else {
5974
+ return
5975
+ }
5976
+ DispatchQueue.global(qos: .userInitiated).async {
5977
+ defer { jsDone.fulfill() }
5978
+ _ = try? testPlugin.downloadBundleForTesting(
5979
+ urlString: "https://example.com/manifest-9.4.0",
5980
+ version: "9.4.0",
5981
+ sessionKey: "",
5982
+ checksum: "",
5983
+ manifestEntries: manifestA
5984
+ )
5985
+ }
5986
+ // The JS worker must actually reach slot acquisition before the lookup returns.
5987
+ jsAtSlotDuringLookup = jsReachedSlotAcquire.wait(timeout: .now() + 5.0)
5988
+ persistDuringLookup = jsManifestPersisted.wait(timeout: .now() + 0.5)
5989
+ }
5990
+
5991
+ let bgFinished = expectation(description: "background queued a bundle")
5992
+ updater.onSetNextBundle = {
5993
+ bgFinished.fulfill()
5994
+ }
5995
+
5996
+ testPlugin.backgroundDownload()
5997
+ XCTAssertEqual(backgroundLookupStarted.wait(timeout: .now() + 5.0), .success)
5998
+ // Usually one download waits behind the other, but they may also serialize without overlapping
5999
+ // (the background check finishes B before JS takes the slot), so a waiter is not required.
6000
+ _ = waiterJoined.wait(timeout: .now() + 2.0)
6001
+ allowJsFinish.signal()
6002
+ wait(for: [bgFinished, jsDone], timeout: 5.0)
6003
+
6004
+ // The JS worker was at the slot boundary, yet the lookup snapshot holds downloadLock, so JS manifest A
6005
+ // could not be published mid-lookup.
6006
+ XCTAssertEqual(jsAtSlotDuringLookup, .success)
6007
+ XCTAssertEqual(persistDuringLookup, .timedOut)
6008
+ XCTAssertEqual(jsManifestPersisted.wait(timeout: .now()), .success)
6009
+
6010
+ XCTAssertEqual(updater.lastSetNextBundleId, "race-manifest-b")
6011
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
6012
+ }
6013
+
6014
+ func testBackgroundDownloadDoesNotReuseCompletedZipForManifestRequest() throws {
6015
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6016
+ CryptoCipher.setLogger(testLogger)
6017
+
6018
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6019
+ let zipBundle = BundleInfo(id: "zip-9.5.0", version: "9.5.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6020
+ let manifestBundle = BundleInfo(id: "manifest-9.5.0", version: "9.5.0", status: .PENDING, downloaded: Date(), checksum: "")
6021
+ let manifestB = [
6022
+ ManifestEntry(file_name: "index.html", file_hash: "zip-vs-manifest-b", download_url: "https://example.com/b/index.html")
6023
+ ]
6024
+ let latest = AppVersion()
6025
+ latest.version = "9.5.0"
6026
+ latest.url = "https://example.com/manifest-9.5.0"
6027
+ latest.manifest = manifestB
6028
+
6029
+ let updater = CoalescingDownloadCapgoUpdater()
6030
+ updater.setLogger(testLogger)
6031
+ updater.currentBundleValue = current
6032
+ updater.latestResponse = latest
6033
+ updater.downloadedBundleValue = zipBundle
6034
+ updater.manifestBundlesByFirstHash = ["zip-vs-manifest-b": manifestBundle]
6035
+
6036
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6037
+ testPlugin.implementation = updater
6038
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6039
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6040
+
6041
+ // JS completes a ZIP download of the same version before the automatic check runs.
6042
+ let jsBundle = try testPlugin.downloadBundleForTesting(
6043
+ urlString: "https://example.com/update-9.5.0.zip",
6044
+ version: "9.5.0",
6045
+ sessionKey: "",
6046
+ checksum: "abc123",
6047
+ manifestEntries: nil
6048
+ )
6049
+ XCTAssertEqual(jsBundle.getId(), "zip-9.5.0")
6050
+ updater.existingBundleValue = zipBundle
6051
+
6052
+ let bgFinished = expectation(description: "background downloaded the requested manifest")
6053
+ updater.onSetNextBundle = { bgFinished.fulfill() }
6054
+ testPlugin.backgroundDownload()
6055
+ wait(for: [bgFinished], timeout: 5.0)
6056
+
6057
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
6058
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-9.5.0")
6059
+ }
6060
+
6061
+ func testBackgroundDownloadReusesMatchingManifestCopyListedAfterAnotherCompleteCopy() throws {
6062
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6063
+ CryptoCipher.setLogger(testLogger)
6064
+
6065
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6066
+ let manifestABundle = BundleInfo(id: "copies-manifest-a", version: "9.6.0", status: .PENDING, downloaded: Date(), checksum: "")
6067
+ let manifestBBundle = BundleInfo(id: "copies-manifest-b", version: "9.6.0", status: .PENDING, downloaded: Date(), checksum: "")
6068
+ let manifestA = [
6069
+ ManifestEntry(file_name: "index.html", file_hash: "copies-hash-a", download_url: "https://example.com/a/index.html")
6070
+ ]
6071
+ let manifestB = [
6072
+ ManifestEntry(file_name: "index.html", file_hash: "copies-hash-b", download_url: "https://example.com/b/index.html")
6073
+ ]
6074
+ let latest = AppVersion()
6075
+ latest.version = "9.6.0"
6076
+ latest.url = "https://example.com/manifest-9.6.0"
6077
+ latest.manifest = manifestB
6078
+
6079
+ let updater = CoalescingDownloadCapgoUpdater()
6080
+ updater.setLogger(testLogger)
6081
+ updater.currentBundleValue = current
6082
+ updater.latestResponse = latest
6083
+ updater.manifestBundlesByFirstHash = [
6084
+ "copies-hash-a": manifestABundle,
6085
+ "copies-hash-b": manifestBBundle
6086
+ ]
6087
+
6088
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6089
+ testPlugin.implementation = updater
6090
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6091
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6092
+
6093
+ for manifest in [manifestA, manifestB] {
6094
+ _ = try testPlugin.downloadBundleForTesting(
6095
+ urlString: "https://example.com/manifest-9.6.0",
6096
+ version: "9.6.0",
6097
+ sessionKey: "",
6098
+ checksum: "",
6099
+ manifestEntries: manifest
6100
+ )
6101
+ }
6102
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
6103
+ // Manifest A is listed first; the requested manifest B is a later complete copy.
6104
+ updater.existingBundleValue = manifestABundle
6105
+ updater.additionalVersionBundles = [manifestBBundle]
6106
+
6107
+ let slotAttemptLock = NSLock()
6108
+ var backgroundSlotAttempts = 0
6109
+ testPlugin.onDownloadSlotAcquireAttemptForTesting = { _ in
6110
+ slotAttemptLock.lock()
6111
+ backgroundSlotAttempts += 1
6112
+ slotAttemptLock.unlock()
6113
+ }
6114
+ let bgFinished = expectation(description: "background reused manifest B")
6115
+ updater.onSetNextBundle = { bgFinished.fulfill() }
6116
+ testPlugin.backgroundDownload()
6117
+ wait(for: [bgFinished], timeout: 5.0)
6118
+
6119
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
6120
+ XCTAssertEqual(updater.lastSetNextBundleId, "copies-manifest-b")
6121
+ // The snapshot itself picked the matching copy, so the check never needed a download slot.
6122
+ slotAttemptLock.lock()
6123
+ XCTAssertEqual(backgroundSlotAttempts, 0)
6124
+ slotAttemptLock.unlock()
6125
+ }
6126
+
6127
+ func testBackgroundDownloadRejectsVersionMarkedErrorWhileWaitingOnSharedDownload() throws {
6128
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6129
+ CryptoCipher.setLogger(testLogger)
6130
+ let downloadEntered = OnceSignal()
6131
+ let waiterJoined = OnceSignal()
6132
+ let allowFinish = OnceSignal()
6133
+
6134
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6135
+ let jsBundle = BundleInfo(id: "wait-js-9.7.0", version: "9.7.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6136
+ let markedError = BundleInfo(id: "wait-error-9.7.0", version: "9.7.0", status: .ERROR, downloaded: Date(), checksum: "abc123")
6137
+ let latest = AppVersion()
6138
+ latest.version = "9.7.0"
6139
+ latest.url = "https://example.com/update-9.7.0.zip"
6140
+ latest.checksum = "abc123"
6141
+
6142
+ let updater = CoalescingDownloadCapgoUpdater()
6143
+ updater.setLogger(testLogger)
6144
+ updater.currentBundleValue = current
6145
+ updater.latestResponse = latest
6146
+ updater.downloadedBundleValue = jsBundle
6147
+ updater.onDownloadStart = {
6148
+ downloadEntered.signal()
6149
+ _ = allowFinish.wait(timeout: .now() + 5.0)
6150
+ }
6151
+
6152
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6153
+ testPlugin.implementation = updater
6154
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6155
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6156
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
6157
+
6158
+ let bgRejected = expectation(description: "backgroundDownload rejected the version marked ERROR during the wait")
6159
+ testPlugin.onSendReadyToJs = { msg in
6160
+ if msg == "Latest version is in error state. Aborting update." {
6161
+ bgRejected.fulfill()
6162
+ }
6163
+ }
6164
+
6165
+ let jsDone = expectation(description: "JS download finished")
6166
+ DispatchQueue.global(qos: .userInitiated).async {
6167
+ defer { jsDone.fulfill() }
6168
+ _ = try? testPlugin.downloadBundleForTesting(
6169
+ urlString: "https://example.com/update-9.7.0.zip",
6170
+ version: "9.7.0",
6171
+ sessionKey: "",
6172
+ checksum: "abc123",
6173
+ manifestEntries: nil
6174
+ )
6175
+ }
6176
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
6177
+
6178
+ testPlugin.backgroundDownload()
6179
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
6180
+ // Another copy of the version is marked ERROR (e.g. via setBundleError) while the check waits.
6181
+ updater.additionalVersionBundles = [markedError]
6182
+ updater.existingBundleValue = jsBundle
6183
+ allowFinish.signal()
6184
+
6185
+ wait(for: [bgRejected, jsDone], timeout: 5.0)
6186
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
6187
+ XCTAssertEqual(updater.downloadCalls, 1)
6188
+ }
6189
+
6190
+ func testBackgroundDownloadFillsServerMetadataWhenSlotOwnerReusesStoredBundle() throws {
6191
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6192
+ CryptoCipher.setLogger(testLogger)
6193
+
6194
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6195
+ let jsBundle = BundleInfo(id: "reuse-js-9.8.0", version: "9.8.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6196
+ let latest = AppVersion()
6197
+ latest.version = "9.8.0"
6198
+ latest.url = "https://example.com/update-9.8.0.zip"
6199
+ latest.checksum = "abc123"
6200
+ latest.link = "https://example.com/release-notes"
6201
+ latest.comment = "server comment"
6202
+
6203
+ let updater = CoalescingDownloadCapgoUpdater()
6204
+ updater.setLogger(testLogger)
6205
+ updater.currentBundleValue = current
6206
+ updater.latestResponse = latest
6207
+ updater.downloadedBundleValue = jsBundle
6208
+ updater.onDownloadStart = {
6209
+ updater.existingBundleValue = jsBundle
6210
+ }
6211
+
6212
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6213
+ testPlugin.implementation = updater
6214
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6215
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6216
+
6217
+ // JS completes its download after the background snapshot but before the background check takes the slot.
6218
+ let jsRan = OnceSignal()
6219
+ testPlugin.onDownloadSlotAcquireAttemptForTesting = { _ in
6220
+ guard jsRan.signal() else {
6221
+ return
6222
+ }
6223
+ _ = try? testPlugin.downloadBundleForTesting(
6224
+ urlString: "https://example.com/update-9.8.0.zip",
6225
+ version: "9.8.0",
6226
+ sessionKey: "",
6227
+ checksum: "abc123",
6228
+ manifestEntries: nil
6229
+ )
6230
+ }
6231
+
6232
+ let metadataNotified = expectation(description: "updateAvailable emitted for the reused bundle")
6233
+ var notifiedBundle: [String: Any]?
6234
+ testPlugin.onUpdateAvailable = { bundle in
6235
+ guard bundle["id"] as? String == "reuse-js-9.8.0" else {
6236
+ return
6237
+ }
6238
+ notifiedBundle = bundle
6239
+ metadataNotified.fulfill()
6240
+ }
6241
+ testPlugin.backgroundDownload()
6242
+ wait(for: [metadataNotified], timeout: 5.0)
6243
+
6244
+ // Only the JS download hit the network; the slot owner reused its bundle by checksum.
6245
+ XCTAssertEqual(updater.downloadCalls, 1)
6246
+ XCTAssertEqual(updater.lastSetNextBundleId, "reuse-js-9.8.0")
6247
+ XCTAssertEqual(notifiedBundle?["link"] as? String, "https://example.com/release-notes")
6248
+ XCTAssertEqual(notifiedBundle?["comment"] as? String, "server comment")
6249
+ }
6250
+
6251
+ func testBackgroundDownloadDoesNotQueueBundleMarkedErrorBeforeCommit() throws {
6252
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6253
+ CryptoCipher.setLogger(testLogger)
6254
+
6255
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6256
+ let downloaded = BundleInfo(id: "commit-9.9.0", version: "9.9.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6257
+ let latest = AppVersion()
6258
+ latest.version = "9.9.0"
6259
+ latest.url = "https://example.com/update-9.9.0.zip"
6260
+ latest.checksum = "abc123"
6261
+
6262
+ let updater = CoalescingDownloadCapgoUpdater()
6263
+ updater.setLogger(testLogger)
6264
+ updater.currentBundleValue = current
6265
+ updater.latestResponse = latest
6266
+ updater.downloadedBundleValue = downloaded
6267
+ updater.onDownloadStart = {
6268
+ // setBundleError marks the bundle after the automatic check scanned the version for ERROR copies.
6269
+ updater.storedBundleInfoOverrides["commit-9.9.0"] = BundleInfo(
6270
+ id: "commit-9.9.0",
6271
+ version: "9.9.0",
6272
+ status: .ERROR,
6273
+ downloaded: Date(),
6274
+ checksum: "abc123"
6275
+ )
6276
+ }
6277
+
6278
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6279
+ testPlugin.implementation = updater
6280
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6281
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6282
+
6283
+ let bgRejected = expectation(description: "commit rejected the bundle marked ERROR")
6284
+ testPlugin.onSendReadyToJs = { msg in
6285
+ if msg == "Latest version is in error state. Aborting update." {
6286
+ bgRejected.fulfill()
6287
+ }
6288
+ }
6289
+ testPlugin.backgroundDownload()
6290
+ wait(for: [bgRejected], timeout: 5.0)
6291
+
6292
+ XCTAssertEqual(updater.downloadCalls, 1)
6293
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
6294
+ }
6295
+
6296
+ func testFillStoredBundleMetadataDoesNotRecreateDeletedRecord() {
6297
+ let updater = CapgoUpdater()
6298
+ updater.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
6299
+ let id = "deletedMeta"
6300
+ UserDefaults.standard.removeObject(forKey: "\(id)_info")
6301
+
6302
+ let filled = updater.fillStoredBundleMetadataIfPresent(id: id, link: "https://example.com", comment: "c")
6303
+
6304
+ XCTAssertNil(filled)
6305
+ XCTAssertNil(UserDefaults.standard.object(forKey: "\(id)_info"))
6306
+ }
6307
+
6308
+ func testApplyCurrentBundleToBridgeReloadsAtomicallyOnMainThread() throws {
6309
+ let serverURL = try XCTUnwrap(URL(string: "capacitor://localhost"))
6310
+ let targetPath = "/var/mobile/Containers/Data/Application/bundle-2.0.0"
6311
+ var activeBasePath = "/var/mobile/Containers/Data/Application/public"
6312
+ var events: [String] = []
6313
+ var loadedURL: URL?
6314
+ var basePathAtLoadTime: String?
6315
+
6316
+ CapacitorUpdaterPlugin.reloadServerBasePathAtomically(
6317
+ path: targetPath,
6318
+ serverURL: serverURL,
6319
+ setServerBasePath: { nextPath in
6320
+ activeBasePath = nextPath
6321
+ events.append("setServerBasePath")
6322
+ },
6323
+ loadRequest: { request in
6324
+ loadedURL = request.url
6325
+ basePathAtLoadTime = activeBasePath
6326
+ events.append("load")
6327
+ }
6328
+ )
6329
+
6330
+ XCTAssertEqual(events, ["setServerBasePath", "load"])
6331
+ XCTAssertEqual(loadedURL, serverURL)
6332
+ XCTAssertEqual(basePathAtLoadTime, targetPath)
6333
+ }
6334
+
6335
+ }
6336
+
6337
+ /// A one-shot latch the test thread opens for download threads (or the reverse).
6338
+ /// Waiters poll a flag instead of blocking on a DispatchGroup, semaphore or condition. A blocking wait from a
6339
+ /// userInitiated download thread on a primitive created or entered by the Default-QoS test thread is a priority
6340
+ /// inversion for Xcode's Thread Performance Checker, which SwiftPM test runs inject. On CI, capturing and
6341
+ /// symbolicating each report stalled the process for 10-20s, so the coalescing tests' 5s waits timed out.
6342
+ private final class OnceSignal {
6343
+ private static let pollInterval: TimeInterval = 0.001
6344
+ private let lock = NSLock()
6345
+ private var signaled = false
6346
+
6347
+ private var isSignaled: Bool {
6348
+ lock.lock()
6349
+ defer { lock.unlock() }
6350
+ return signaled
6351
+ }
6352
+
6353
+ @discardableResult
6354
+ func signal() -> Bool {
6355
+ lock.lock()
6356
+ defer { lock.unlock() }
6357
+ let changed = !signaled
6358
+ signaled = true
6359
+ return changed
6360
+ }
6361
+
6362
+ func wait(timeout: DispatchTime) -> DispatchTimeoutResult {
6363
+ while !isSignaled {
6364
+ if DispatchTime.now() >= timeout {
6365
+ return isSignaled ? .success : .timedOut
6366
+ }
6367
+ Thread.sleep(forTimeInterval: Self.pollInterval)
6368
+ }
6369
+ return .success
6370
+ }
6371
+ }
6372
+
6373
+ private final class CoalescingDownloadCapgoUpdater: FreshDownloadCapgoUpdater {
6374
+ private let stateLock = NSLock()
6375
+ var onSetNextBundle: (() -> Void)?
6376
+ var onManifestDownloadStart: (() -> Void)?
6377
+ var downloadedManifestBundleValue: BundleInfo?
6378
+ var manifestDownloadBundles: [BundleInfo] = []
6379
+ /// When set, manifest downloads return the bundle keyed by the first entry's file hash instead of call order.
6380
+ var manifestBundlesByFirstHash: [String: BundleInfo] = [:]
6381
+ var onManifestDownload: (([ManifestEntry]) -> Void)?
6382
+ var onVersionLookup: (() -> Void)?
6383
+ var zipDownloadBundles: [BundleInfo?] = []
6384
+ private var manifestCallCount = 0
6385
+
6386
+ var manifestDownloadCalls: Int {
6387
+ stateLock.lock()
6388
+ defer { stateLock.unlock() }
6389
+ return manifestCallCount
6390
+ }
6391
+
6392
+ override var currentBundleValue: BundleInfo! {
6393
+ get {
6394
+ stateLock.lock()
6395
+ defer { stateLock.unlock() }
6396
+ return super.currentBundleValue
6397
+ }
6398
+ set {
6399
+ stateLock.lock()
6400
+ super.currentBundleValue = newValue
6401
+ stateLock.unlock()
6402
+ }
6403
+ }
6404
+
6405
+ override var existingBundleValue: BundleInfo? {
6406
+ get {
6407
+ stateLock.lock()
6408
+ defer { stateLock.unlock() }
6409
+ return super.existingBundleValue
6410
+ }
6411
+ set {
6412
+ stateLock.lock()
6413
+ super.existingBundleValue = newValue
6414
+ stateLock.unlock()
6415
+ }
6416
+ }
6417
+
6418
+ override func downloadVerifiedWithTransferHook(
6419
+ url: URL,
6420
+ version: String,
6421
+ sessionKey: String,
6422
+ expectedChecksum: String,
6423
+ link: String?,
6424
+ comment: String?,
6425
+ beforeTransfer: (() throws -> Void)?
6426
+ ) throws -> BundleInfo {
6427
+ try beforeTransfer?()
6428
+ return try self.downloadVerified(
6429
+ url: url,
6430
+ version: version,
6431
+ sessionKey: sessionKey,
6432
+ expectedChecksum: expectedChecksum,
6433
+ link: link,
6434
+ comment: comment
6435
+ )
6436
+ }
6437
+
6438
+ override func downloadManifestWithTransferHook(
6439
+ manifest: [ManifestEntry],
6440
+ version: String,
6441
+ sessionKey: String,
6442
+ link: String?,
6443
+ comment: String?,
6444
+ beforeTransfer: (() throws -> Void)?
6445
+ ) throws -> BundleInfo {
6446
+ try beforeTransfer?()
6447
+ return try self.downloadManifest(
6448
+ manifest: manifest,
6449
+ version: version,
6450
+ sessionKey: sessionKey,
6451
+ link: link,
6452
+ comment: comment
6453
+ )
6454
+ }
6455
+
6456
+ override func downloadVerified(
6457
+ url _: URL,
6458
+ version _: String,
6459
+ sessionKey _: String,
6460
+ expectedChecksum _: String,
6461
+ link _: String? = nil,
6462
+ comment _: String? = nil
6463
+ ) throws -> BundleInfo {
6464
+ stateLock.lock()
6465
+ let index = downloadCalls
6466
+ downloadCalls += 1
6467
+ let bundle: BundleInfo? = index < zipDownloadBundles.count
6468
+ ? zipDownloadBundles[index]
6469
+ : downloadedBundleValue
6470
+ stateLock.unlock()
6471
+
6472
+ onDownloadStart?()
6473
+ if let bundle {
6474
+ return bundle
6475
+ }
6476
+ throw NSError(domain: "CapacitorUpdaterPluginTests", code: 1)
6477
+ }
6478
+
6479
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
6480
+ onVersionLookup?()
6481
+ return super.getBundleInfosByVersionName(version: version)
6482
+ }
6483
+
6484
+ override func downloadManifest(
6485
+ manifest: [ManifestEntry],
6486
+ version _: String,
6487
+ sessionKey _: String,
6488
+ link _: String? = nil,
6489
+ comment _: String? = nil
6490
+ ) throws -> BundleInfo {
6491
+ stateLock.lock()
6492
+ manifestCallCount += 1
6493
+ let index = manifestCallCount - 1
6494
+ let bundle: BundleInfo?
6495
+ if let hash = manifest.first?.file_hash, let mapped = manifestBundlesByFirstHash[hash] {
6496
+ bundle = mapped
6497
+ } else {
6498
+ bundle = index < manifestDownloadBundles.count
6499
+ ? manifestDownloadBundles[index]
6500
+ : downloadedManifestBundleValue
6501
+ }
6502
+ stateLock.unlock()
6503
+
6504
+ onManifestDownloadStart?()
6505
+ onManifestDownload?(manifest)
6506
+ if let bundle {
6507
+ return bundle
6508
+ }
6509
+ throw NSError(domain: "CapacitorUpdaterPluginTests", code: 2)
6510
+ }
6511
+
6512
+ override func setNextBundle(next: String?) -> Bool {
6513
+ let result = super.setNextBundle(next: next)
6514
+ onSetNextBundle?()
6515
+ return result
6516
+ }
6517
+ }
6518
+
6519
+ private final class ConcurrentDownloadCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
6520
+ var onSendReadyToJs: ((String) -> Void)?
6521
+ var onUpdateAvailable: (([String: Any]) -> Void)?
6522
+ private let eventsLock = NSLock()
6523
+ private var updateAvailableBundles: [[String: Any]] = []
6524
+
6525
+ var notifiedUpdateAvailableBundles: [[String: Any]] {
6526
+ eventsLock.lock()
6527
+ defer { eventsLock.unlock() }
6528
+ return updateAvailableBundles
6529
+ }
6530
+
6531
+ override func beginDownloadBackgroundTask() {}
6532
+ override func endBackGroundTask() {}
6533
+ override func notifyListeners(_ eventName: String, data: [String: Any]?, retainUntilConsumed retain: Bool) {
6534
+ let event = decodeUpdaterEvent(eventName, data: data)
6535
+ guard event.name == "updateAvailable", let bundle = event.data?["bundle"] as? [String: Any] else {
6536
+ return
6537
+ }
6538
+ eventsLock.lock()
6539
+ updateAvailableBundles.append(bundle)
6540
+ eventsLock.unlock()
6541
+ onUpdateAvailable?(bundle)
6542
+ }
6543
+ override func sendReadyToJs(current: BundleInfo, msg: String) {
6544
+ onSendReadyToJs?(msg)
6545
+ }
3905
6546
  }