@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
@@ -43,7 +43,14 @@ public class CryptoCipher {
43
43
  }
44
44
 
45
45
  public static byte[] decryptRSA(byte[] source, PublicKey publicKey)
46
- throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
46
+ throws
47
+ NoSuchPaddingException,
48
+ NoSuchAlgorithmException,
49
+ InvalidAlgorithmParameterException,
50
+ InvalidKeyException,
51
+ IllegalBlockSizeException,
52
+ BadPaddingException
53
+ {
47
54
  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
48
55
  cipher.init(Cipher.DECRYPT_MODE, publicKey);
49
56
  byte[] decryptedBytes = cipher.doFinal(source);
@@ -111,7 +118,8 @@ public class CryptoCipher {
111
118
  };
112
119
 
113
120
  private static PublicKey readPkcs1PublicKey(byte[] pkcs1Bytes)
114
- throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException {
121
+ throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException
122
+ {
115
123
  // convert the pkcs1 public key to an x509 favorable format
116
124
  byte[] keyBitString = createDEREncoding(BIT_STRING_TAG, joinPublic(NO_UNUSED_BITS, pkcs1Bytes));
117
125
  byte[] keyInfoValue = joinPublic(RSA_ALGORITHM_IDENTIFIER_SEQUENCE, keyBitString);
@@ -131,6 +131,19 @@ public class DownloadService extends Worker {
131
131
  public static final String PERCENT = "percent";
132
132
  public static final String FILEDEST = "filendest";
133
133
  public static final String DOCDIR = "docdir";
134
+ /** Output flag: the worker refused before requesting any byte (the attempt never transferred). */
135
+ public static final String PRE_REQUEST_REFUSAL = "pre_request_refusal";
136
+
137
+ /** A refusal raised before the HTTP request is made. */
138
+ static final class PreRequestRefusalException extends RuntimeException {
139
+
140
+ PreRequestRefusalException(final String message) {
141
+ super(message);
142
+ }
143
+ }
144
+
145
+ /** Minimum free space before a ZIP request: twice the 50MB default size estimate. */
146
+ static final long MIN_ZIP_FREE_BYTES = 2L * 50 * 1024 * 1024;
134
147
  public static final String ERROR = "error";
135
148
  public static final String VERSION = "version";
136
149
  public static final String SESSIONKEY = "sessionkey";
@@ -343,7 +356,14 @@ public class DownloadService extends Worker {
343
356
  }
344
357
 
345
358
  private Result createFailureResult(String error, String version, String dest, boolean isManifest) {
359
+ return createFailureResult(error, version, dest, isManifest, false);
360
+ }
361
+
362
+ private Result createFailureResult(String error, String version, String dest, boolean isManifest, boolean preRequestRefusal) {
346
363
  Data.Builder builder = new Data.Builder().putString(ERROR, error);
364
+ if (preRequestRefusal) {
365
+ builder.putBoolean(PRE_REQUEST_REFUSAL, true);
366
+ }
347
367
  if (version != null) {
348
368
  builder.putString(VERSION, version);
349
369
  }
@@ -779,7 +799,10 @@ public class DownloadService extends Worker {
779
799
  if (isManifest) {
780
800
  CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
781
801
  }
782
- return createFailureResult(e.getMessage(), version, dest, isManifest);
802
+ // Only the first run of this work request is a confirmed pre-request refusal: a WorkManager retry run
803
+ // follows a run that already passed this check and sent the ZIP request, so its charge is kept.
804
+ final boolean preRequestRefusal = e instanceof PreRequestRefusalException && getRunAttemptCount() == 0;
805
+ return createFailureResult(e.getMessage(), version, dest, isManifest, preRequestRefusal);
783
806
  }
784
807
  }
785
808
 
@@ -1149,9 +1172,8 @@ public class DownloadService extends Worker {
1149
1172
 
1150
1173
  // Check available disk space before starting
1151
1174
  long availableSpace = target.getParentFile().getUsableSpace();
1152
- long estimatedSize = 50 * 1024 * 1024; // 50MB default estimate
1153
- if (availableSpace < estimatedSize * 2) {
1154
- throw new RuntimeException("insufficient_disk_space");
1175
+ if (availableSpace < MIN_ZIP_FREE_BYTES) {
1176
+ throw new PreRequestRefusalException("insufficient_disk_space");
1155
1177
  }
1156
1178
 
1157
1179
  Response response = null;
@@ -1167,6 +1189,7 @@ public class DownloadService extends Worker {
1167
1189
 
1168
1190
  // Reading progress file (if exist)
1169
1191
  long downloadedBytes = 0;
1192
+ boolean allowEngine = true;
1170
1193
 
1171
1194
  if (infoFile.exists() && tempFile.exists()) {
1172
1195
  try {
@@ -1176,6 +1199,9 @@ public class DownloadService extends Worker {
1176
1199
  clearDownloadData(documentsDir, id);
1177
1200
  } else {
1178
1201
  downloadedBytes = tempFile.length();
1202
+ // An earlier attempt's engine body failed: resume this download on OkHttp, even after the
1203
+ // process-wide cooldown expired, so the retry cannot hit the same engine failure again.
1204
+ allowEngine = !ZIP_OKHTTP_FALLBACK.equals(reader.readLine());
1179
1205
  }
1180
1206
  } finally {
1181
1207
  if (reader != null) {
@@ -1192,7 +1218,7 @@ public class DownloadService extends Worker {
1192
1218
  throw new DownloadRetryException("download_stopped");
1193
1219
  }
1194
1220
 
1195
- response = executeZipRequest(zipUrl, downloadedBytes);
1221
+ response = executeZipRequest(zipUrl, downloadedBytes, allowEngine);
1196
1222
  int responseCode = response.code();
1197
1223
 
1198
1224
  if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
@@ -1216,7 +1242,7 @@ public class DownloadService extends Worker {
1216
1242
  try {
1217
1243
  inputStream = responseBody.byteStream();
1218
1244
 
1219
- if (writePlan.writeOffset == 0 && downloadedBytes == 0) {
1245
+ if (allowEngine && writePlan.writeOffset == 0 && downloadedBytes == 0) {
1220
1246
  writer = new BufferedWriter(new FileWriter(infoFile));
1221
1247
  writer.write(String.valueOf(version));
1222
1248
  writer.close();
@@ -1245,14 +1271,29 @@ public class DownloadService extends Worker {
1245
1271
  responseBodyLength
1246
1272
  );
1247
1273
 
1248
- // Rename the temp file with the final name (dest)
1249
- if (!tempFile.renameTo(new File(documentsDir, dest))) {
1274
+ // Rename the temp file with the final name (dest), never after a stop request: cleanup of a
1275
+ // cancelled attempt may already have checked that no archive exists.
1276
+ if (isStopped()) {
1277
+ throw new IOException("download_stopped");
1278
+ }
1279
+ final File finalArchive = new File(documentsDir, dest);
1280
+ if (!tempFile.renameTo(finalArchive)) {
1250
1281
  throw new RuntimeException("Failed to rename temp file to final destination");
1251
1282
  }
1283
+ if (isStopped()) {
1284
+ // Stopped during the rename: remove the archive this cancelled attempt just produced.
1285
+ finalArchive.delete();
1286
+ throw new IOException("download_stopped");
1287
+ }
1252
1288
  infoFile.delete();
1253
1289
 
1254
1290
  // Send stats for zip download complete
1255
1291
  sendStatsAsync("download_zip_complete", version, java.util.Collections.singletonMap("attempt_id", id));
1292
+ } catch (DownloadRetryException e) {
1293
+ if (Http3.servedByEngine(response)) {
1294
+ markZipOkHttpFallback(infoFile, version);
1295
+ }
1296
+ throw e;
1256
1297
  } catch (OutOfMemoryError e) {
1257
1298
  logger.error("Out of memory during download: " + e.getMessage());
1258
1299
  // Try to free some memory
@@ -1262,6 +1303,9 @@ public class DownloadService extends Worker {
1262
1303
  if ("download_stopped".equals(e.getMessage())) {
1263
1304
  throw new DownloadRetryException("download_stopped", e);
1264
1305
  }
1306
+ if (Http3.servedByEngine(response)) {
1307
+ markZipOkHttpFallback(infoFile, version);
1308
+ }
1265
1309
  throw new DownloadRetryException(e.getMessage(), e);
1266
1310
  } finally {
1267
1311
  if (inputStream != null) {
@@ -1317,6 +1361,11 @@ public class DownloadService extends Worker {
1317
1361
  * {@code downloadedBytes} with a Range header. The caller closes the response.
1318
1362
  */
1319
1363
  static Response executeZipRequest(HttpUrl url, long downloadedBytes) throws IOException {
1364
+ return executeZipRequest(url, downloadedBytes, true);
1365
+ }
1366
+
1367
+ /** Same request; {@code allowEngine} false keeps it on OkHttp (a retry after an engine body failed). */
1368
+ static Response executeZipRequest(HttpUrl url, long downloadedBytes, boolean allowEngine) throws IOException {
1320
1369
  // Zip can stall longer than a JSON API call; keep a floor so
1321
1370
  // responseTimeout cannot shrink large-bundle downloads.
1322
1371
  int zipTimeoutMs = Math.max(httpTimeoutMs, 60_000);
@@ -1326,11 +1375,34 @@ public class DownloadService extends Worker {
1326
1375
  .readTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
1327
1376
  .writeTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
1328
1377
  .build();
1329
- Request.Builder builder = Http3.markDownload(new Request.Builder().url(url));
1378
+ return zipClient.newCall(zipRequest(url, downloadedBytes, allowEngine)).execute();
1379
+ }
1380
+
1381
+ static Request zipRequest(HttpUrl url, long downloadedBytes, boolean allowEngine) {
1382
+ Request.Builder builder = new Request.Builder().url(url);
1383
+ if (allowEngine) {
1384
+ Http3.markDownload(builder);
1385
+ }
1330
1386
  if (downloadedBytes > 0) {
1331
1387
  builder.header("Range", "bytes=" + downloadedBytes + "-");
1332
1388
  }
1333
- return zipClient.newCall(builder.build()).execute();
1389
+ return builder.build();
1390
+ }
1391
+
1392
+ /** Progress-file line that sends this download's later attempts to OkHttp. */
1393
+ static final String ZIP_OKHTTP_FALLBACK = "okhttp";
1394
+
1395
+ /** Records, next to the partial ZIP, that its retries must skip the engine. Best effort: a failed write keeps the engine. */
1396
+ static void markZipOkHttpFallback(File infoFile, String version) {
1397
+ try (BufferedWriter out = new BufferedWriter(new FileWriter(infoFile))) {
1398
+ out.write(String.valueOf(version));
1399
+ out.newLine();
1400
+ out.write(ZIP_OKHTTP_FALLBACK);
1401
+ } catch (IOException e) {
1402
+ if (logger != null) {
1403
+ logger.debug("Cannot record the OkHttp fallback for the zip retry: " + e.getMessage());
1404
+ }
1405
+ }
1334
1406
  }
1335
1407
 
1336
1408
  static boolean isRetryableHttpStatus(int responseCode) {
@@ -261,6 +261,29 @@ public class DownloadWorkerManager {
261
261
  throw new IllegalStateException("Timed out waiting for version download cancel: " + version);
262
262
  }
263
263
 
264
+ /**
265
+ * Whether any work of this bundle attempt (tagged with its id) has not finished yet, for example a cancelled worker
266
+ * still returning from doWork. Unknown state counts as unfinished so callers keep their cleanup records.
267
+ */
268
+ public static boolean isBundleWorkUnfinished(Context context, String id) {
269
+ if (context == null || id == null || id.isEmpty()) {
270
+ return false;
271
+ }
272
+ initializeIfNeeded(context.getApplicationContext());
273
+ try {
274
+ return WorkManager.getInstance(context)
275
+ .getWorkInfosByTag(id)
276
+ .get()
277
+ .stream()
278
+ .anyMatch((workInfo) -> !workInfo.getState().isFinished());
279
+ } catch (Exception e) {
280
+ if (logger != null) {
281
+ logger.error("Error checking bundle work status: " + e.getMessage());
282
+ }
283
+ return true;
284
+ }
285
+ }
286
+
264
287
  public static void cancelBundleDownload(Context context, String id, String version) {
265
288
  String uniqueWorkName = "bundle_" + id + "_" + version;
266
289
  initializeIfNeeded(context.getApplicationContext());
@@ -179,18 +179,183 @@ public class HeadlessUpdateWorker extends Worker {
179
179
  final String sessionKey = latest.get("sessionKey") instanceof String ? (String) latest.get("sessionKey") : "";
180
180
  final String checksum = latest.get("checksum") instanceof String ? (String) latest.get("checksum") : "";
181
181
 
182
- final BundleInfo existing = updater.getBundleInfoByName(version);
183
- if (existing != null && existing.isErrorStatus()) {
184
- return "failed";
182
+ BundleInfo existing = updater.getBundleInfoByName(version);
183
+ if (existing == null) {
184
+ existing = updater.findRegistryBundleByVersionName(version);
185
+ }
186
+ boolean retryDownloadSlot = false;
187
+ final BundleInfo next = updater.getNextBundle();
188
+ final boolean isQueuedNext = existing != null && next != null && existing.getId().equals(next.getId());
189
+ final boolean isCurrent =
190
+ existing != null &&
191
+ existing.getId().equals(current.getId()) &&
192
+ BundleStatus.SUCCESS == current.getStatus() &&
193
+ version.equals(current.getVersionName());
194
+ if (existing != null) {
195
+ final boolean interrupted = updater.isInterruptedDownloadBundle(existing.getId());
196
+ final int retryCount = updater.incompleteDownloadRetryCount(version);
197
+ final boolean integrityBlocked = updater.isIntegrityBlockedVersion(version);
198
+ final boolean bundleOnDisk = updater.isBundleOnDisk(existing.getId());
199
+ if (
200
+ existing.isErrorStatus() &&
201
+ !CapgoUpdater.shouldRetryDownloadForExistingBundle(
202
+ existing,
203
+ bundleOnDisk,
204
+ retryCount,
205
+ integrityBlocked,
206
+ interrupted,
207
+ isCurrent,
208
+ isQueuedNext
209
+ )
210
+ ) {
211
+ return "failed";
212
+ }
213
+ final boolean replaceExisting = CapgoUpdater.shouldRetryDownloadForExistingBundle(
214
+ existing,
215
+ bundleOnDisk,
216
+ retryCount,
217
+ integrityBlocked,
218
+ interrupted,
219
+ isCurrent,
220
+ isQueuedNext
221
+ );
222
+ // A finished worker whose bundle is still being finalized owns this row too: deleting it now would
223
+ // cancel the finalization and discard a completed transfer.
224
+ final boolean versionDownloadActive = hasLiveDownloadOwner(updater, version, existing.getId());
225
+ if (replaceExisting && BundleStatus.DOWNLOADING != existing.getStatus() && versionDownloadActive) {
226
+ // Another live attempt (e.g. a manual download()) owns this version: deleting the older row
227
+ // would cancel its work by version. Defer to it.
228
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
229
+ updater.handOverPendingStats();
230
+ return "handed_over";
231
+ }
232
+ return "skipped";
233
+ }
234
+ if (replaceExisting && !(BundleStatus.DOWNLOADING == existing.getStatus() && versionDownloadActive)) {
235
+ // An ordinary deletion tombstone (a retired bundle) carries no retry history: removing it is
236
+ // cleanup, and the next transfer is a first download. Anything else is a charged retry.
237
+ final boolean retryHistory =
238
+ !(existing.isDeleted() || existing.isDeleting()) ||
239
+ interrupted ||
240
+ retryCount > 0 ||
241
+ integrityBlocked ||
242
+ updater.hasIncompleteDownloadRetryReservation(version);
243
+ retryDownloadSlot = retryHistory;
244
+ if (isQueuedNext) {
245
+ updater.clearNextBundleIfMatches(existing.getId());
246
+ }
247
+ if (retryHistory) {
248
+ // Persist the retry before deleting the record that proves it (survives process death).
249
+ updater.reserveIncompleteDownloadRetry(version);
250
+ }
251
+ boolean deleted = false;
252
+ try {
253
+ deleted = Boolean.TRUE.equals(updater.delete(existing.getId(), true));
254
+ } catch (final IOException e) {
255
+ logger.error("Failed to delete incomplete bundle: " + version + " " + e.getMessage());
256
+ }
257
+ if (!deleted) {
258
+ // A pending deletion of the old record can cancel same-version work when it resumes;
259
+ // do not start a replacement until it is gone (the reservation keeps the retry charged).
260
+ logger.error("Incomplete bundle still pending deletion, skipping replacement: " + version);
261
+ return "skipped";
262
+ }
263
+ final String deletedId = existing.getId();
264
+ existing = updater.getBundleInfoByName(version);
265
+ if (existing == null) {
266
+ existing = updater.findRegistryBundleByVersionName(version);
267
+ }
268
+ if (existing != null && !deletedId.equals(existing.getId()) && existing.isErrorStatus()) {
269
+ // Another failed row of this version surfaced: run the eligibility decision again for it.
270
+ final boolean refreshedEligible = CapgoUpdater.shouldRetryDownloadForExistingBundle(
271
+ existing,
272
+ updater.isBundleOnDisk(existing.getId()),
273
+ updater.incompleteDownloadRetryCount(version),
274
+ updater.isIntegrityBlockedVersion(version),
275
+ updater.isInterruptedDownloadBundle(existing.getId()),
276
+ false,
277
+ next != null && existing.getId().equals(next.getId())
278
+ );
279
+ // Eligible rows are replaced by the next check (the reservation keeps that retry charged).
280
+ return refreshedEligible ? "skipped" : "failed";
281
+ }
282
+ }
283
+ }
284
+ if (existing != null && BundleStatus.DOWNLOADING == existing.getStatus()) {
285
+ final int retryCount = updater.incompleteDownloadRetryCount(version);
286
+ final boolean interrupted = updater.isInterruptedDownloadBundle(existing.getId());
287
+ final boolean integrityBlocked = updater.isIntegrityBlockedVersion(version);
288
+ final boolean bundleOnDisk = updater.isBundleOnDisk(existing.getId());
289
+ if (
290
+ !CapgoUpdater.shouldRetryDownloadForExistingBundle(
291
+ existing,
292
+ bundleOnDisk,
293
+ retryCount,
294
+ integrityBlocked,
295
+ interrupted,
296
+ isCurrent,
297
+ isQueuedNext
298
+ )
299
+ ) {
300
+ return "failed";
301
+ }
302
+ if (hasLiveDownloadOwner(updater, version, existing.getId())) {
303
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
304
+ updater.handOverPendingStats();
305
+ return "handed_over";
306
+ }
307
+ return "skipped";
308
+ }
309
+ // The owner may have finished between the checks: reread so a finalized PENDING bundle is reused.
310
+ final BundleInfo reread = updater.getBundleInfo(existing.getId());
311
+ if (reread != null && BundleStatus.DOWNLOADING != reread.getStatus()) {
312
+ existing = reread;
313
+ }
314
+ // The stale DOWNLOADING row's owner has ended: what follows replaces that attempt, so charge it.
315
+ retryDownloadSlot = true;
185
316
  }
186
317
  final String reused = reuseDownloadedBundle(updater, existing, version, setNext, logger);
187
318
  if (reused != null) {
188
319
  return reused;
189
320
  }
190
321
 
322
+ if (existing != null && existing.isDeleting()) {
323
+ // The old row's deletion has not finished: when it resumes it cancels same-version work, so do
324
+ // not start (or charge) a replacement yet. Any reservation keeps the retry charged.
325
+ logger.info("Bundle still pending deletion, skipping replacement: " + version);
326
+ return "skipped";
327
+ }
191
328
  // downloadBackground returns null when it refuses the download (blocked encryption, gate,
192
329
  // version already downloading): only wait for a download it started.
193
- final String startedId = updater.downloadBackground((String) url, version, sessionKey, checksum, manifestOf(latest), setNext);
330
+ if (updater.incompleteDownloadRetryCount(version) >= CapgoUpdater.MAX_INCOMPLETE_DOWNLOAD_RETRIES) {
331
+ return "failed";
332
+ }
333
+ if (updater.incompleteDownloadRetryCount(version) > 0 || updater.isIntegrityBlockedVersion(version)) {
334
+ retryDownloadSlot = true;
335
+ }
336
+ final JSONArray manifest = manifestOf(latest);
337
+ if (
338
+ manifest == null &&
339
+ (retryDownloadSlot || updater.hasIncompleteDownloadRetryReservation(version)) &&
340
+ !updater.hasDiskSpaceForZipDownload()
341
+ ) {
342
+ // The ZIP worker would refuse before any request: do not spend a retry slot on it.
343
+ updater.sendStats("insufficient_disk_space", version);
344
+ return "failed";
345
+ }
346
+ final int retryCharge = updater.chargeIncompleteDownloadRetry(version, retryDownloadSlot);
347
+ if (retryCharge == CapgoUpdater.RETRY_REFUSED) {
348
+ return "failed";
349
+ }
350
+ final boolean retryCharged = retryCharge == CapgoUpdater.RETRY_CHARGED;
351
+ final String startedId;
352
+ try {
353
+ startedId = updater.downloadBackground((String) url, version, sessionKey, checksum, manifest, setNext);
354
+ } catch (final RuntimeException e) {
355
+ updater.settleIncompleteDownloadRetry(version, retryCharged, false, false);
356
+ throw e;
357
+ }
358
+ updater.settleIncompleteDownloadRetry(version, retryCharged, startedId != null, false);
194
359
  if (startedId == null) {
195
360
  return "skipped";
196
361
  }
@@ -226,6 +391,22 @@ public class HeadlessUpdateWorker extends Worker {
226
391
  }
227
392
  }
228
393
 
394
+ /**
395
+ * Whether a live owner will finish the version's download: a pending finalization, work observed by this
396
+ * process, or (with a plugin instance loaded) persisted work the plugin owns or restarts itself. Persisted
397
+ * WorkManager work that nothing in this process observes was left by a killed process: nobody would verify,
398
+ * extract or queue its result, so the headless check recovers it (downloadBackground restarts orphaned work).
399
+ */
400
+ static boolean hasLiveDownloadOwner(final CapgoUpdater updater, final String version, final String bundleId) {
401
+ if (updater.hasPendingDownloadFinalizationForBundleId(bundleId)) {
402
+ return true;
403
+ }
404
+ if (!updater.isVersionDownloadActive(version)) {
405
+ return false;
406
+ }
407
+ return CapacitorUpdaterPlugin.isInstanceLoaded() || updater.isVersionDownloadObservedInThisProcess(version);
408
+ }
409
+
229
410
  /**
230
411
  * With no plugin instance (no bridge, no WebView) nothing shows the current bundle, so switching
231
412
  * it is the same as installing on a background transition. Delay conditions keep it as next.
@@ -312,6 +493,9 @@ public class HeadlessUpdateWorker extends Worker {
312
493
  }
313
494
  return "skipped";
314
495
  }
496
+ if (!updater.canSet(existing)) {
497
+ return null;
498
+ }
315
499
  if (setNext && updater.setNextBundle(existing.getId())) {
316
500
  return applyIfNoUi(updater, existing, logger) ? "installed" : "queued";
317
501
  }
@@ -47,6 +47,18 @@ final class Http3 {
47
47
  private Download() {}
48
48
  }
49
49
 
50
+ /** Request tag on responses HttpEngine served, so a caller can tell an engine body from an OkHttp one. */
51
+ static final class ServedByEngine {
52
+
53
+ static final ServedByEngine TAG = new ServedByEngine();
54
+
55
+ private ServedByEngine() {}
56
+ }
57
+
58
+ static boolean servedByEngine(@Nullable Response response) {
59
+ return response != null && response.request().tag(ServedByEngine.class) != null;
60
+ }
61
+
50
62
  /** Runs one tagged download outside OkHttp's network stack. */
51
63
  interface Transport {
52
64
  @NonNull
@@ -70,6 +82,18 @@ final class Http3 {
70
82
  }
71
83
  }
72
84
 
85
+ /**
86
+ * No response headers within the full header-wait budget, without an engine stall (a cold host still setting up
87
+ * its connection). Nothing reached the caller, so the download retries once on OkHttp, but HTTP/3 stays on for
88
+ * other downloads: a slow handshake to one host is not an engine failure.
89
+ */
90
+ static final class EngineHeaderTimeoutException extends SocketTimeoutException {
91
+
92
+ EngineHeaderTimeoutException(String message) {
93
+ super(message);
94
+ }
95
+ }
96
+
73
97
  /**
74
98
  * How long the whole engine may stay silent, while downloads wait on it, before they move to OkHttp. A live
75
99
  * connection with requests in flight answers in a few round trips, far below this.
@@ -83,6 +107,12 @@ final class Http3 {
83
107
  // System.nanoTime() until which downloads skip the engine after a stall; only read while stalledOnce is true.
84
108
  private static volatile long suspendedUntilNanos;
85
109
  private static volatile boolean stalledOnce;
110
+ // Same cooldown, but set only by a confirmed engine stall (no progress while requests waited on it). Only this
111
+ // arms early cancellation of bodies already streaming; an ordinary body read timeout just reroutes new requests.
112
+ private static volatile long stallConfirmedUntilNanos;
113
+ private static volatile boolean stallConfirmedOnce;
114
+ // Serializes cooldown writes so a delayed writer never replaces a later deadline with an earlier one.
115
+ private static final Object COOLDOWN_LOCK = new Object();
86
116
  // True once the plugin or the headless worker applied the http3 config in this process.
87
117
  private static volatile boolean configured;
88
118
  // Guards the configured check plus the enabled write, kept apart from init() so it never waits on engine setup.
@@ -176,19 +206,51 @@ final class Http3 {
176
206
 
177
207
  /** Called when the engine stalled: downloads use OkHttp for {@link #STALL_COOLDOWN_MS}. */
178
208
  static void suspendAfterStall(long nowNanos) {
179
- suspendedUntilNanos = nowNanos + TimeUnit.MILLISECONDS.toNanos(STALL_COOLDOWN_MS);
209
+ long until = nowNanos + TimeUnit.MILLISECONDS.toNanos(STALL_COOLDOWN_MS);
210
+ synchronized (COOLDOWN_LOCK) {
211
+ extendSuspension(until);
212
+ if (!stallConfirmedOnce || until - stallConfirmedUntilNanos > 0) {
213
+ stallConfirmedUntilNanos = until;
214
+ }
215
+ stallConfirmedOnce = true;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Called when a body read timed out: new downloads use OkHttp for {@link #STALL_COOLDOWN_MS}, but bodies already
221
+ * streaming on the engine keep their normal read timeout, because one slow response does not prove the engine stalled.
222
+ */
223
+ static void suspendAfterBodyTimeout(long nowNanos) {
224
+ long until = nowNanos + TimeUnit.MILLISECONDS.toNanos(STALL_COOLDOWN_MS);
225
+ synchronized (COOLDOWN_LOCK) {
226
+ extendSuspension(until);
227
+ }
228
+ }
229
+
230
+ /** Keeps the later reroute deadline; callers hold {@link #COOLDOWN_LOCK}. */
231
+ private static void extendSuspension(long untilNanos) {
232
+ if (!stalledOnce || untilNanos - suspendedUntilNanos > 0) {
233
+ suspendedUntilNanos = untilNanos;
234
+ }
180
235
  stalledOnce = true;
181
236
  }
182
237
 
238
+ /** Whether new downloads skip the engine (after a confirmed stall or a body read timeout). */
183
239
  static boolean isSuspended(long nowNanos) {
184
240
  return stalledOnce && nowNanos - suspendedUntilNanos < 0;
185
241
  }
186
242
 
243
+ /** Whether a confirmed engine stall is recent enough to cancel silent bodies early. */
244
+ static boolean isStallConfirmed(long nowNanos) {
245
+ return stallConfirmedOnce && nowNanos - stallConfirmedUntilNanos < 0;
246
+ }
247
+
187
248
  /** Test hook: forget the engine so the next init() starts over. */
188
249
  static synchronized void resetForTest() {
189
250
  transport = null;
190
251
  initialized = false;
191
252
  stalledOnce = false;
253
+ stallConfirmedOnce = false;
192
254
  synchronized (OPTION_LOCK) {
193
255
  enabled = true;
194
256
  configured = false;
@@ -242,6 +304,15 @@ final class Http3 {
242
304
  Response response = chain.proceed(request);
243
305
  logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
244
306
  return response;
307
+ } catch (SocketTimeoutException timeout) {
308
+ // Same recovery for a cold host that never answered, without suspending HTTP/3 for other downloads.
309
+ Logger logger = DownloadService.logger();
310
+ if (logger != null) {
311
+ logger.warn("HttpEngine header timeout, download moved to OkHttp: " + timeout.getMessage());
312
+ }
313
+ Response response = chain.proceed(request);
314
+ logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
315
+ return response;
245
316
  }
246
317
  }
247
318
  }
@@ -309,6 +380,15 @@ final class Http3 {
309
380
  return parsed != null ? parsed.host() : "unknown host";
310
381
  }
311
382
 
383
+ /**
384
+ * Connection identity for warmth tracking: scheme, host and effective port, so a redirect to another port of the
385
+ * same host is judged as a new connection. Logs keep {@link #safeHost(String)}.
386
+ */
387
+ static String connectionKey(@Nullable String url) {
388
+ HttpUrl parsed = url == null ? null : HttpUrl.parse(url);
389
+ return parsed != null ? parsed.scheme() + "://" + parsed.host() + ":" + parsed.port() : "unknown";
390
+ }
391
+
312
392
  /** Same policy as the shared client's network interceptor, for redirects the engine follows itself. */
313
393
  @Nullable
314
394
  static IOException redirectError(@Nullable String from, @Nullable String to) {