@gfean/react-native-bundle-drop 0.5.1 → 0.7.0

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 (127) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +194 -5
  3. package/android/build.gradle +66 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +206 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  10. package/ios/BundleDropBridge.m +45 -0
  11. package/ios/BundleDropLocator.swift +66 -4
  12. package/ios/BundleDropModule.swift +181 -3
  13. package/ios/BundleDropOtaResolver.swift +137 -29
  14. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  15. package/ios/BundleDropStartupRecovery.swift +1108 -0
  16. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  17. package/lib/CLI/cli.d.ts +1 -0
  18. package/lib/CLI/cli.js +57 -6
  19. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  20. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  21. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  22. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  23. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  24. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  25. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  26. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  27. package/lib/CLI/scripts/aipowered/init-project-config.js +221 -45
  28. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  29. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  30. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  31. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  32. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  33. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  34. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  35. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  36. package/lib/CLI/scripts/doctor.js +162 -22
  37. package/lib/CLI/scripts/expo/configure-expo.js +52 -60
  38. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  39. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  40. package/lib/CLI/scripts/init-config.d.ts +7 -7
  41. package/lib/CLI/scripts/init-config.js +198 -14
  42. package/lib/CLI/scripts/login-cli.js +31 -7
  43. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  44. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  45. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  46. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  47. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  48. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  49. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  50. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  51. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  52. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  53. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  54. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  55. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  56. package/lib/CLI/scripts/upload-cli.js +74 -11
  57. package/lib/CLI/serverUrl.d.ts +3 -0
  58. package/lib/CLI/serverUrl.js +31 -0
  59. package/lib/api/clientApi.d.ts +3 -1
  60. package/lib/api/clientApi.js +14 -0
  61. package/lib/api/types.d.ts +39 -0
  62. package/lib/bundleInfo.d.ts +2 -0
  63. package/lib/bundleInfo.js +16 -1
  64. package/lib/context.d.ts +1 -1
  65. package/lib/context.js +12 -2
  66. package/lib/fs/bundlePointer.d.ts +1 -17
  67. package/lib/fs/bundlePointer.js +5 -93
  68. package/lib/index.d.ts +2 -0
  69. package/lib/index.js +3 -1
  70. package/lib/install/bundleInstallShared.js +4 -4
  71. package/lib/install/installFromZip.d.ts +3 -0
  72. package/lib/install/installFromZip.js +10 -1
  73. package/lib/loadConfig.d.ts +17 -1
  74. package/lib/loadConfig.js +16 -0
  75. package/lib/manager/downloadAndInstall.d.ts +3 -2
  76. package/lib/manager/downloadAndInstall.js +134 -66
  77. package/lib/manager/reporting.d.ts +8 -1
  78. package/lib/manager/reporting.js +17 -22
  79. package/lib/manager/rollbackState.d.ts +18 -52
  80. package/lib/manager/rollbackState.js +115 -216
  81. package/lib/manager/updateCheck.d.ts +1 -0
  82. package/lib/manager/updateCheck.js +224 -78
  83. package/lib/manager/updateState.d.ts +2 -1
  84. package/lib/manager/updateState.js +59 -6
  85. package/lib/metro.d.ts +8 -1
  86. package/lib/metro.js +69 -19
  87. package/lib/native/bundleDropNative.d.ts +62 -0
  88. package/lib/native/bundleDropNative.js +268 -2
  89. package/lib/native/fs.d.ts +6 -0
  90. package/lib/native/fs.js +24 -0
  91. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  92. package/lib/patch-engine/installFromPatchSet.js +16 -5
  93. package/lib/patch-engine/patchTransport.d.ts +2 -0
  94. package/lib/patch-engine/patchTransport.js +9 -0
  95. package/lib/runtime/initState.d.ts +5 -0
  96. package/lib/runtime/initState.js +4 -0
  97. package/lib/runtime/service.js +82 -67
  98. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  99. package/lib/runtime-delivery/artifactCapability.js +32 -0
  100. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  101. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  102. package/lib/runtime-delivery/bootstrapConfig.d.ts +68 -0
  103. package/lib/runtime-delivery/bootstrapConfig.js +278 -0
  104. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  105. package/lib/runtime-delivery/diagnostics.js +58 -0
  106. package/lib/runtime-delivery/encoding.d.ts +5 -0
  107. package/lib/runtime-delivery/encoding.js +132 -0
  108. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  109. package/lib/runtime-delivery/heartbeat.js +88 -0
  110. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  111. package/lib/runtime-delivery/localResolver.js +81 -0
  112. package/lib/runtime-delivery/manifestState.d.ts +11 -0
  113. package/lib/runtime-delivery/manifestState.js +123 -0
  114. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  115. package/lib/runtime-delivery/manifestVerifier.js +335 -0
  116. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  117. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  118. package/lib/runtime-delivery/types.d.ts +87 -0
  119. package/lib/runtime-delivery/types.js +6 -0
  120. package/lib/scripts/bundle.d.ts +9 -2
  121. package/lib/scripts/bundle.js +68 -18
  122. package/lib/scripts/download-bundle.d.ts +1 -0
  123. package/lib/scripts/download-bundle.js +2 -2
  124. package/lib/scripts/resolveModule.d.ts +2 -0
  125. package/lib/scripts/resolveModule.js +5 -0
  126. package/package.json +5 -2
  127. package/plugin/xcodeBuildPhase.js +2 -1
@@ -0,0 +1,1117 @@
1
+ package com.bundledrop
2
+
3
+ import android.content.Context
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.util.AtomicFile
7
+ import android.util.Log
8
+ import com.facebook.react.bridge.ReactMarker
9
+ import com.facebook.react.bridge.ReactMarkerConstants
10
+ import java.io.File
11
+ import java.io.FileOutputStream
12
+ import java.text.SimpleDateFormat
13
+ import java.util.Date
14
+ import java.util.Locale
15
+ import java.util.TimeZone
16
+ import java.util.UUID
17
+ import org.json.JSONArray
18
+ import org.json.JSONObject
19
+
20
+ /**
21
+ * Native source of truth for OTA launch probation.
22
+ *
23
+ * The ledger is persisted before an OTA path is returned to React Native. A later process can
24
+ * therefore recover from Java, JNI, Hermes, or JS failures that happen before the bridge starts.
25
+ */
26
+ internal class BundleDropStartupRecoveryController(
27
+ private val bundleDropRoot: File,
28
+ private val processToken: String,
29
+ private val binaryIdentity: String,
30
+ private val expectedRuntimeVersion: String?,
31
+ private val nowMillis: () -> Long = { System.currentTimeMillis() },
32
+ private val newId: () -> String = { UUID.randomUUID().toString() },
33
+ private val failpoint: (String) -> Unit = {},
34
+ ) {
35
+ data class ActivationResult(val hash: String, val bundlePath: String)
36
+ data class RollbackResult(
37
+ val rolledBack: Boolean,
38
+ val toEmbedded: Boolean,
39
+ val hash: String?,
40
+ )
41
+
42
+ data class StartupSelection(
43
+ val bundlePath: String?,
44
+ val attemptHash: String? = null,
45
+ val attemptId: String? = null,
46
+ )
47
+
48
+ private data class RecoveryPolicy(
49
+ val maxCrashCount: Int,
50
+ val healthCheckMode: String,
51
+ val healthyAfterSec: Double,
52
+ )
53
+
54
+ private data class ActiveAttempt(
55
+ val hash: String,
56
+ val attemptId: String,
57
+ val processToken: String,
58
+ val unacknowledgedLaunchCount: Int,
59
+ )
60
+
61
+ private data class RecoveryEvent(
62
+ val id: String,
63
+ val failedHash: String,
64
+ val recoveryTarget: String,
65
+ val recoveredHash: String?,
66
+ val crashCount: Int,
67
+ val failedAt: Long,
68
+ )
69
+
70
+ private data class Ledger(
71
+ val revision: Long = 0,
72
+ val binaryIdentity: String? = null,
73
+ val phase: String = PHASE_IDLE,
74
+ val candidateHash: String? = null,
75
+ val candidateRuntimeVersion: String? = null,
76
+ val stableHash: String? = null,
77
+ val stableRuntimeVersion: String? = null,
78
+ val previousStableHash: String? = null,
79
+ val previousStableRuntimeVersion: String? = null,
80
+ val policy: RecoveryPolicy? = null,
81
+ val reservedAttemptId: String? = null,
82
+ val activeAttempt: ActiveAttempt? = null,
83
+ val lastHealthyAttemptId: String? = null,
84
+ val quarantinedHashes: Set<String> = emptySet(),
85
+ val revokedHashes: Set<String> = emptySet(),
86
+ val pendingRecoveryEvents: List<RecoveryEvent> = emptyList(),
87
+ val legacyStateImported: Boolean = false,
88
+ val rollbackFailedHash: String? = null,
89
+ val rollbackCrashCount: Int = 0,
90
+ val rollbackReason: String? = null,
91
+ )
92
+
93
+ fun activateCandidate(
94
+ hash: String,
95
+ maxCrashCount: Int,
96
+ healthCheckMode: String,
97
+ healthyAfterSec: Double,
98
+ ): ActivationResult = synchronized(STORAGE_LOCK) {
99
+ requireHash(hash)
100
+ require(maxCrashCount >= 0) { "maxCrashCount must not be negative" }
101
+ require(healthCheckMode == HEALTH_AUTO || healthCheckMode == HEALTH_MANUAL) {
102
+ "healthCheckMode must be auto or manual"
103
+ }
104
+ require(healthyAfterSec.isFinite() && healthyAfterSec >= 0) {
105
+ "healthyAfterSec must be a finite non-negative number"
106
+ }
107
+
108
+ val bundlePath = BundleDropOtaResolver.readBundleForHash(bundleDropRoot, hash)
109
+ ?: throw IllegalArgumentException("Candidate bundle is missing or failed native verification")
110
+ val candidateRuntimeVersion = BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, hash)
111
+ ?: throw IllegalArgumentException("Candidate runtime identity is missing")
112
+ require(!expectedRuntimeVersion.isNullOrBlank()) {
113
+ "Embedded runtime identity is missing; OTA startup activation is disabled"
114
+ }
115
+ require(candidateRuntimeVersion == expectedRuntimeVersion) {
116
+ "Candidate runtime identity does not match the embedded binary"
117
+ }
118
+ var ledger = readLedgerWithLegacyImport()
119
+ require(hash !in ledger.quarantinedHashes && hash !in ledger.revokedHashes) {
120
+ "Candidate bundle is quarantined or revoked"
121
+ }
122
+ failpoint(FAIL_AFTER_VERIFICATION)
123
+
124
+ val currentHash = currentHash()
125
+ val requestedPolicy = RecoveryPolicy(maxCrashCount, healthCheckMode, healthyAfterSec)
126
+ if (
127
+ currentHash == hash &&
128
+ ledger.stableHash == hash &&
129
+ (ledger.phase == PHASE_STABLE || ledger.phase == PHASE_RECOVERED)
130
+ ) {
131
+ return@synchronized ActivationResult(hash, bundlePath)
132
+ }
133
+ if (
134
+ currentHash == hash &&
135
+ ledger.candidateHash == hash &&
136
+ (ledger.phase == PHASE_ARMED || ledger.phase == PHASE_LAUNCHING)
137
+ ) {
138
+ var updated = ledger.copy(policy = requestedPolicy)
139
+ if (maxCrashCount == 0) {
140
+ updated = updated.copy(
141
+ phase = PHASE_ARMED,
142
+ reservedAttemptId = null,
143
+ activeAttempt = null,
144
+ lastHealthyAttemptId = null,
145
+ )
146
+ } else if (updated.phase == PHASE_ARMED && updated.reservedAttemptId == null) {
147
+ updated = updated.copy(reservedAttemptId = newId())
148
+ }
149
+ if (updated != ledger) persist(updated)
150
+ return@synchronized ActivationResult(hash, bundlePath)
151
+ }
152
+
153
+ val previousStableHash = selectKnownGoodHash(ledger, excludedHash = hash)
154
+ val previousStableRuntimeVersion = when (previousStableHash) {
155
+ ledger.stableHash -> ledger.stableRuntimeVersion
156
+ ledger.previousStableHash -> ledger.previousStableRuntimeVersion
157
+ else -> null
158
+ }
159
+ ledger = ledger.copy(
160
+ binaryIdentity = binaryIdentity,
161
+ phase = PHASE_ARMED,
162
+ candidateHash = hash,
163
+ candidateRuntimeVersion = candidateRuntimeVersion,
164
+ previousStableHash = previousStableHash,
165
+ previousStableRuntimeVersion = previousStableRuntimeVersion,
166
+ policy = requestedPolicy,
167
+ reservedAttemptId = if (maxCrashCount == 0) null else newId(),
168
+ activeAttempt = null,
169
+ lastHealthyAttemptId = null,
170
+ rollbackFailedHash = null,
171
+ rollbackCrashCount = 0,
172
+ rollbackReason = null,
173
+ )
174
+ ledger = persist(ledger)
175
+ failpoint(FAIL_AFTER_ARMED)
176
+
177
+ if (previousStableHash != null) {
178
+ writePointer(PREVIOUS_POINTER, previousStableHash)
179
+ failpoint(FAIL_AFTER_PREVIOUS_POINTER)
180
+ } else {
181
+ deletePointer(PREVIOUS_POINTER)
182
+ }
183
+ writePointer(CURRENT_POINTER, hash)
184
+ failpoint(FAIL_AFTER_CURRENT_POINTER)
185
+
186
+ ActivationResult(hash, bundlePath)
187
+ }
188
+
189
+ fun selectForStartup(): StartupSelection = synchronized(STORAGE_LOCK) {
190
+ var ledger = try {
191
+ readLedgerWithLegacyImport()
192
+ } catch (_: IncompatibleLedgerException) {
193
+ return@synchronized resetForBinaryChange()
194
+ } catch (_: CorruptLedgerException) {
195
+ return@synchronized recoverFromCorruptLedger()
196
+ }
197
+
198
+ if (ledger.phase == PHASE_ROLLBACK_REQUIRED) {
199
+ return@synchronized completeRecovery(
200
+ ledger,
201
+ recordCrashLoop = ledger.rollbackReason != ROLLBACK_REVOKED,
202
+ )
203
+ }
204
+
205
+ val path = BundleDropOtaResolver.readCurrentPointer(bundleDropRoot)
206
+ val hash = path?.let(::hashFromBundlePath)
207
+ if (ledger.phase == PHASE_ARMED && hash != ledger.candidateHash) {
208
+ return@synchronized discardUnpublishedArm(ledger, path, hash)
209
+ }
210
+ if (path == null || hash == null) return@synchronized StartupSelection(null)
211
+
212
+ if (
213
+ ledger.binaryIdentity != binaryIdentity ||
214
+ expectedRuntimeVersion.isNullOrBlank() ||
215
+ BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, hash) != expectedRuntimeVersion
216
+ ) {
217
+ return@synchronized resetForBinaryChange()
218
+ }
219
+
220
+ if (hash in ledger.revokedHashes) {
221
+ ledger = persist(ledger.copy(
222
+ phase = PHASE_ROLLBACK_REQUIRED,
223
+ rollbackFailedHash = hash,
224
+ rollbackCrashCount = 0,
225
+ rollbackReason = ROLLBACK_REVOKED,
226
+ ))
227
+ return@synchronized completeRecovery(ledger, recordCrashLoop = false)
228
+ }
229
+
230
+ if (hash in ledger.quarantinedHashes) {
231
+ val crashCount = ledger.activeAttempt?.unacknowledgedLaunchCount ?: 0
232
+ ledger = persist(ledger.copy(
233
+ phase = PHASE_ROLLBACK_REQUIRED,
234
+ rollbackFailedHash = hash,
235
+ rollbackCrashCount = crashCount,
236
+ rollbackReason = ROLLBACK_CRASH_LOOP,
237
+ ))
238
+ return@synchronized completeRecovery(ledger, recordCrashLoop = true)
239
+ }
240
+
241
+ if (
242
+ ledger.stableHash == hash &&
243
+ (ledger.phase == PHASE_STABLE || ledger.phase == PHASE_RECOVERED)
244
+ ) {
245
+ return@synchronized StartupSelection(path)
246
+ }
247
+
248
+ val policy = ledger.policy
249
+ if (
250
+ ledger.candidateHash != hash ||
251
+ ledger.candidateRuntimeVersion != expectedRuntimeVersion ||
252
+ policy == null ||
253
+ (ledger.phase != PHASE_ARMED && ledger.phase != PHASE_LAUNCHING)
254
+ ) {
255
+ deletePointer(CURRENT_POINTER)
256
+ return@synchronized StartupSelection(null)
257
+ }
258
+
259
+ // Zero explicitly disables crash classification while retaining revocation and integrity gates.
260
+ if (policy.maxCrashCount == 0) {
261
+ return@synchronized StartupSelection(path)
262
+ }
263
+
264
+ val activeAttempt = ledger.activeAttempt
265
+ if (activeAttempt?.hash == hash && activeAttempt.processToken == processToken) {
266
+ return@synchronized StartupSelection(path, hash, activeAttempt.attemptId)
267
+ }
268
+
269
+ val failedLaunchCount = if (activeAttempt?.hash == hash) {
270
+ activeAttempt.unacknowledgedLaunchCount + 1
271
+ } else {
272
+ 0
273
+ }
274
+ val threshold = policy.maxCrashCount
275
+ if (threshold > 0 && failedLaunchCount >= threshold) {
276
+ ledger = persist(ledger.copy(
277
+ phase = PHASE_ROLLBACK_REQUIRED,
278
+ rollbackFailedHash = hash,
279
+ rollbackCrashCount = failedLaunchCount,
280
+ rollbackReason = ROLLBACK_CRASH_LOOP,
281
+ quarantinedHashes = ledger.quarantinedHashes + hash,
282
+ ))
283
+ failpoint(FAIL_AFTER_ROLLBACK_REQUIRED)
284
+ return@synchronized completeRecovery(ledger, recordCrashLoop = true)
285
+ }
286
+
287
+ val attempt = ActiveAttempt(
288
+ hash = hash,
289
+ attemptId = ledger.reservedAttemptId ?: newId(),
290
+ processToken = processToken,
291
+ unacknowledgedLaunchCount = failedLaunchCount,
292
+ )
293
+ persist(ledger.copy(
294
+ phase = PHASE_LAUNCHING,
295
+ reservedAttemptId = null,
296
+ activeAttempt = attempt,
297
+ ))
298
+ failpoint(FAIL_AFTER_LAUNCH_PERSISTED)
299
+ StartupSelection(path, hash, attempt.attemptId)
300
+ }
301
+
302
+ fun resolvePassive(): String? = synchronized(STORAGE_LOCK) {
303
+ val path = BundleDropOtaResolver.readCurrentPointer(bundleDropRoot) ?: return@synchronized null
304
+ val hash = hashFromBundlePath(path) ?: return@synchronized null
305
+ val ledger = try {
306
+ readLedgerWithLegacyImport()
307
+ } catch (_: IncompatibleLedgerException) {
308
+ return@synchronized null
309
+ } catch (_: CorruptLedgerException) {
310
+ return@synchronized null
311
+ }
312
+ if (ledger.phase == PHASE_ROLLBACK_REQUIRED) return@synchronized null
313
+ if (hash in ledger.quarantinedHashes || hash in ledger.revokedHashes) return@synchronized null
314
+
315
+ val recordedRuntimeVersion = when {
316
+ ledger.stableHash == hash &&
317
+ (ledger.phase == PHASE_STABLE || ledger.phase == PHASE_RECOVERED) -> ledger.stableRuntimeVersion
318
+ ledger.candidateHash == hash &&
319
+ (ledger.phase == PHASE_ARMED || ledger.phase == PHASE_LAUNCHING) &&
320
+ ledger.policy != null -> ledger.candidateRuntimeVersion
321
+ else -> null
322
+ }
323
+ if (!isCurrentBundleEligible(ledger, hash, recordedRuntimeVersion)) null else path
324
+ }
325
+
326
+ fun markHealthy(hash: String, attemptId: String): Boolean = synchronized(STORAGE_LOCK) {
327
+ requireHash(hash)
328
+ val ledger = try {
329
+ readLedgerWithLegacyImport()
330
+ } catch (_: IncompatibleLedgerException) {
331
+ return@synchronized false
332
+ } catch (_: CorruptLedgerException) {
333
+ return@synchronized false
334
+ }
335
+ val attempt = ledger.activeAttempt
336
+ val recordedRuntimeVersion = when {
337
+ ledger.phase == PHASE_STABLE &&
338
+ ledger.stableHash == hash &&
339
+ ledger.lastHealthyAttemptId == attemptId -> ledger.stableRuntimeVersion
340
+ ledger.phase == PHASE_LAUNCHING &&
341
+ ledger.candidateHash == hash &&
342
+ attempt?.hash == hash &&
343
+ attempt.attemptId == attemptId -> ledger.candidateRuntimeVersion
344
+ else -> null
345
+ }
346
+ if (!isCurrentBundleEligible(ledger, hash, recordedRuntimeVersion)) {
347
+ return@synchronized false
348
+ }
349
+ if (
350
+ ledger.phase == PHASE_STABLE &&
351
+ ledger.stableHash == hash &&
352
+ ledger.lastHealthyAttemptId == attemptId
353
+ ) {
354
+ return@synchronized true
355
+ }
356
+ if (
357
+ ledger.phase != PHASE_LAUNCHING ||
358
+ attempt?.hash != hash ||
359
+ attempt.attemptId != attemptId
360
+ ) {
361
+ return@synchronized false
362
+ }
363
+
364
+ persist(ledger.copy(
365
+ phase = PHASE_STABLE,
366
+ candidateHash = null,
367
+ candidateRuntimeVersion = null,
368
+ stableHash = hash,
369
+ stableRuntimeVersion = recordedRuntimeVersion,
370
+ policy = null,
371
+ reservedAttemptId = null,
372
+ activeAttempt = null,
373
+ lastHealthyAttemptId = attemptId,
374
+ rollbackFailedHash = null,
375
+ rollbackCrashCount = 0,
376
+ rollbackReason = null,
377
+ ))
378
+ failpoint(FAIL_AFTER_HEALTH_COMMITTED)
379
+ true
380
+ }
381
+
382
+ fun setRevokedHashes(hashes: Set<String>): Unit = synchronized(STORAGE_LOCK) {
383
+ hashes.forEach(::requireHash)
384
+ val ledger = readLedgerWithLegacyImport()
385
+ if (ledger.revokedHashes == hashes) return@synchronized
386
+ persist(ledger.copy(revokedHashes = hashes))
387
+ }
388
+
389
+ fun rollbackStartupBundle(forceEmbedded: Boolean): RollbackResult = synchronized(STORAGE_LOCK) {
390
+ val ledger = readLedgerWithLegacyImport()
391
+ val currentHash = currentHash()
392
+ val targetHash = if (forceEmbedded) {
393
+ null
394
+ } else {
395
+ selectKnownGoodHash(ledger, excludedHash = currentHash)
396
+ }
397
+ if (targetHash != null) {
398
+ val targetRuntimeVersion = BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, targetHash)
399
+ writePointer(CURRENT_POINTER, targetHash)
400
+ deletePointer(PREVIOUS_POINTER)
401
+ persist(ledger.copy(
402
+ phase = PHASE_STABLE,
403
+ candidateHash = targetHash,
404
+ candidateRuntimeVersion = targetRuntimeVersion,
405
+ stableHash = targetHash,
406
+ stableRuntimeVersion = targetRuntimeVersion,
407
+ previousStableHash = null,
408
+ previousStableRuntimeVersion = null,
409
+ reservedAttemptId = null,
410
+ activeAttempt = null,
411
+ lastHealthyAttemptId = null,
412
+ policy = null,
413
+ rollbackFailedHash = null,
414
+ rollbackCrashCount = 0,
415
+ rollbackReason = null,
416
+ ))
417
+ } else {
418
+ deletePointer(CURRENT_POINTER)
419
+ deletePointer(PREVIOUS_POINTER)
420
+ persist(ledger.copy(
421
+ phase = PHASE_IDLE,
422
+ candidateHash = null,
423
+ candidateRuntimeVersion = null,
424
+ stableHash = null,
425
+ stableRuntimeVersion = null,
426
+ previousStableHash = null,
427
+ previousStableRuntimeVersion = null,
428
+ reservedAttemptId = null,
429
+ activeAttempt = null,
430
+ lastHealthyAttemptId = null,
431
+ policy = null,
432
+ rollbackFailedHash = null,
433
+ rollbackCrashCount = 0,
434
+ rollbackReason = null,
435
+ ))
436
+ }
437
+ RollbackResult(
438
+ rolledBack = currentHash != null,
439
+ toEmbedded = targetHash == null,
440
+ hash = targetHash,
441
+ )
442
+ }
443
+
444
+ fun acknowledgeRecovery(eventId: String): Boolean = synchronized(STORAGE_LOCK) {
445
+ val ledger = readLedgerWithLegacyImport()
446
+ if (ledger.pendingRecoveryEvents.none { it.id == eventId }) return@synchronized false
447
+ persist(ledger.copy(
448
+ pendingRecoveryEvents = ledger.pendingRecoveryEvents.filterNot { it.id == eventId },
449
+ ))
450
+ true
451
+ }
452
+
453
+ fun snapshot(): JSONObject = synchronized(STORAGE_LOCK) {
454
+ val ledger = readLedgerWithLegacyImport()
455
+ val output = JSONObject()
456
+ .put("protocolVersion", PROTOCOL_VERSION)
457
+ .put("revision", ledger.revision)
458
+ .put("phase", externalPhase(ledger.phase))
459
+ .put("activeAttempt", ledger.activeAttempt?.let(::attemptJson) ?: JSONObject.NULL)
460
+ .put("quarantinedHashes", JSONArray(ledger.quarantinedHashes.sorted()))
461
+ .put("pendingRecoveryEvents", JSONArray(ledger.pendingRecoveryEvents.map(::eventJson)))
462
+ ledger.candidateHash?.let { output.put("candidateHash", it) }
463
+ ledger.stableHash?.let { output.put("stableHash", it) }
464
+ ledger.policy?.let {
465
+ output.put("policy", JSONObject()
466
+ .put("maxCrashCount", it.maxCrashCount)
467
+ .put("healthCheckMode", it.healthCheckMode)
468
+ .put("healthyAfterSec", it.healthyAfterSec))
469
+ }
470
+ output
471
+ }
472
+
473
+ fun activeAttempt(): Pair<String, String>? = synchronized(STORAGE_LOCK) {
474
+ val attempt = try {
475
+ readLedgerWithLegacyImport().activeAttempt
476
+ } catch (_: CorruptLedgerException) {
477
+ null
478
+ } ?: return@synchronized null
479
+ attempt.hash to attempt.attemptId
480
+ }
481
+
482
+ fun scheduleContentAppearedHealth(handler: Handler = Handler(Looper.getMainLooper())) {
483
+ val ledger = synchronized(STORAGE_LOCK) {
484
+ try {
485
+ readLedgerWithLegacyImport()
486
+ } catch (_: CorruptLedgerException) {
487
+ null
488
+ }
489
+ } ?: return
490
+ val attempt = ledger.activeAttempt ?: return
491
+ val policy = ledger.policy ?: return
492
+ if (ledger.phase != PHASE_LAUNCHING || policy.healthCheckMode != HEALTH_AUTO) return
493
+ val delayMillis = (policy.healthyAfterSec * 1000.0).toLong().coerceAtLeast(0)
494
+ handler.postDelayed({ markHealthy(attempt.hash, attempt.attemptId) }, delayMillis)
495
+ }
496
+
497
+ private fun completeRecovery(ledger: Ledger, recordCrashLoop: Boolean): StartupSelection {
498
+ val failedHash = ledger.rollbackFailedHash ?: ledger.candidateHash
499
+ ?: return StartupSelection(null)
500
+ val crashCount = ledger.rollbackCrashCount
501
+ val alreadyPromotedTarget = currentHash()
502
+ ?.takeIf { it != failedHash && isKnownGoodHash(ledger, it) }
503
+ val targetHash = alreadyPromotedTarget ?: selectKnownGoodHash(ledger, failedHash)
504
+ ?.takeIf { readPointerHash(PREVIOUS_POINTER) == it }
505
+ val recoveryTarget: String
506
+
507
+ if (targetHash != null) {
508
+ writePointer(CURRENT_POINTER, targetHash)
509
+ deletePointer(PREVIOUS_POINTER)
510
+ recoveryTarget = RECOVERY_PREVIOUS
511
+ } else {
512
+ deletePointer(CURRENT_POINTER)
513
+ deletePointer(PREVIOUS_POINTER)
514
+ recoveryTarget = RECOVERY_EMBEDDED
515
+ }
516
+ failpoint(FAIL_AFTER_RECOVERY_POINTER)
517
+
518
+ val events = if (recordCrashLoop) {
519
+ val event = RecoveryEvent(
520
+ id = newId(),
521
+ failedHash = failedHash,
522
+ recoveryTarget = recoveryTarget,
523
+ recoveredHash = targetHash,
524
+ crashCount = crashCount,
525
+ failedAt = nowMillis() / 1000,
526
+ )
527
+ (ledger.pendingRecoveryEvents + event).takeLast(MAX_PENDING_EVENTS)
528
+ } else {
529
+ ledger.pendingRecoveryEvents
530
+ }
531
+ persist(ledger.copy(
532
+ phase = PHASE_RECOVERED,
533
+ candidateHash = targetHash,
534
+ candidateRuntimeVersion = targetHash?.let {
535
+ BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, it)
536
+ },
537
+ stableHash = targetHash,
538
+ stableRuntimeVersion = targetHash?.let {
539
+ BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, it)
540
+ },
541
+ previousStableHash = null,
542
+ previousStableRuntimeVersion = null,
543
+ policy = null,
544
+ reservedAttemptId = null,
545
+ activeAttempt = null,
546
+ lastHealthyAttemptId = null,
547
+ quarantinedHashes = if (recordCrashLoop) {
548
+ ledger.quarantinedHashes + failedHash
549
+ } else {
550
+ ledger.quarantinedHashes
551
+ },
552
+ pendingRecoveryEvents = events,
553
+ rollbackFailedHash = null,
554
+ rollbackCrashCount = 0,
555
+ rollbackReason = null,
556
+ ))
557
+ failpoint(FAIL_AFTER_RECOVERED)
558
+ return StartupSelection(
559
+ bundlePath = targetHash?.let { BundleDropOtaResolver.readBundleForHash(bundleDropRoot, it) },
560
+ )
561
+ }
562
+
563
+ private fun discardUnpublishedArm(
564
+ ledger: Ledger,
565
+ currentPath: String?,
566
+ currentHash: String?,
567
+ ): StartupSelection {
568
+ val stableCurrentHash = currentHash?.takeIf { isKnownGoodHash(ledger, it) }
569
+ deletePointer(PREVIOUS_POINTER)
570
+
571
+ if (stableCurrentHash == null) {
572
+ deletePointer(CURRENT_POINTER)
573
+ persist(ledger.copy(
574
+ phase = PHASE_IDLE,
575
+ candidateHash = null,
576
+ candidateRuntimeVersion = null,
577
+ policy = null,
578
+ reservedAttemptId = null,
579
+ activeAttempt = null,
580
+ lastHealthyAttemptId = null,
581
+ rollbackFailedHash = null,
582
+ rollbackCrashCount = 0,
583
+ rollbackReason = null,
584
+ ))
585
+ return StartupSelection(null)
586
+ }
587
+
588
+ val stableRuntimeVersion = BundleDropOtaResolver.readBundleRuntimeVersion(
589
+ bundleDropRoot,
590
+ stableCurrentHash,
591
+ )
592
+ val previousStableHash = selectKnownGoodHash(ledger, excludedHash = stableCurrentHash)
593
+ val previousStableRuntimeVersion = previousStableHash?.let {
594
+ BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, it)
595
+ }
596
+ persist(ledger.copy(
597
+ phase = PHASE_STABLE,
598
+ candidateHash = stableCurrentHash,
599
+ candidateRuntimeVersion = stableRuntimeVersion,
600
+ stableHash = stableCurrentHash,
601
+ stableRuntimeVersion = stableRuntimeVersion,
602
+ previousStableHash = previousStableHash,
603
+ previousStableRuntimeVersion = previousStableRuntimeVersion,
604
+ policy = null,
605
+ reservedAttemptId = null,
606
+ activeAttempt = null,
607
+ lastHealthyAttemptId = null,
608
+ rollbackFailedHash = null,
609
+ rollbackCrashCount = 0,
610
+ rollbackReason = null,
611
+ ))
612
+ return StartupSelection(currentPath)
613
+ }
614
+
615
+ private fun recoverFromCorruptLedger(): StartupSelection {
616
+ val failedHash = currentHash()
617
+ deletePointer(CURRENT_POINTER)
618
+ deletePointer(PREVIOUS_POINTER)
619
+ val quarantined = failedHash?.let(::setOf) ?: emptySet()
620
+ persist(Ledger(
621
+ binaryIdentity = binaryIdentity,
622
+ phase = PHASE_RECOVERED,
623
+ quarantinedHashes = quarantined,
624
+ legacyStateImported = true,
625
+ ), replaceExisting = true)
626
+ return StartupSelection(null)
627
+ }
628
+
629
+ private fun resetForBinaryChange(): StartupSelection {
630
+ deletePointer(CURRENT_POINTER)
631
+ deletePointer(PREVIOUS_POINTER)
632
+ persist(
633
+ Ledger(binaryIdentity = binaryIdentity, legacyStateImported = true),
634
+ replaceExisting = true,
635
+ )
636
+ return StartupSelection(null)
637
+ }
638
+
639
+ private fun selectKnownGoodHash(ledger: Ledger, excludedHash: String?): String? {
640
+ val candidates = listOfNotNull(ledger.stableHash, ledger.previousStableHash).distinct()
641
+ return candidates.firstOrNull { hash -> hash != excludedHash && isKnownGoodHash(ledger, hash) }
642
+ }
643
+
644
+ private fun isKnownGoodHash(ledger: Ledger, hash: String): Boolean {
645
+ val recordedRuntimeVersion = when (hash) {
646
+ ledger.stableHash -> ledger.stableRuntimeVersion
647
+ ledger.previousStableHash -> ledger.previousStableRuntimeVersion
648
+ else -> null
649
+ }
650
+ return ledger.binaryIdentity == binaryIdentity &&
651
+ !recordedRuntimeVersion.isNullOrBlank() &&
652
+ hash !in ledger.quarantinedHashes &&
653
+ hash !in ledger.revokedHashes &&
654
+ recordedRuntimeVersion == expectedRuntimeVersion &&
655
+ BundleDropOtaResolver.readBundleForHash(bundleDropRoot, hash) != null &&
656
+ BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, hash) == expectedRuntimeVersion
657
+ }
658
+
659
+ private fun isCurrentBundleEligible(
660
+ ledger: Ledger,
661
+ hash: String,
662
+ recordedRuntimeVersion: String?,
663
+ ): Boolean {
664
+ return ledger.binaryIdentity == binaryIdentity &&
665
+ !expectedRuntimeVersion.isNullOrBlank() &&
666
+ recordedRuntimeVersion == expectedRuntimeVersion &&
667
+ hash !in ledger.quarantinedHashes &&
668
+ hash !in ledger.revokedHashes &&
669
+ currentHash() == hash &&
670
+ BundleDropOtaResolver.readBundleRuntimeVersion(bundleDropRoot, hash) == expectedRuntimeVersion
671
+ }
672
+
673
+ private fun readLedgerWithLegacyImport(): Ledger {
674
+ val file = ledgerFile()
675
+ val ledger = if (!file.baseFile.exists() && !File(file.baseFile.path + ".new").exists()) {
676
+ Ledger(binaryIdentity = binaryIdentity)
677
+ } else {
678
+ try {
679
+ ledgerFromJson(JSONObject(String(file.readFully(), Charsets.UTF_8)))
680
+ } catch (error: Exception) {
681
+ throw CorruptLedgerException(error)
682
+ }
683
+ }
684
+ if (ledger.binaryIdentity != binaryIdentity) throw IncompatibleLedgerException()
685
+ if (ledger.legacyStateImported) return ledger
686
+
687
+ val legacy = readLegacyState()
688
+ val imported = ledger.copy(
689
+ quarantinedHashes = ledger.quarantinedHashes + legacy,
690
+ legacyStateImported = true,
691
+ )
692
+ return persist(imported)
693
+ }
694
+
695
+ private fun readLegacyState(): Set<String> {
696
+ return try {
697
+ val stateFile = File(bundleDropRoot, LEGACY_STATE)
698
+ if (!stateFile.exists()) return emptySet()
699
+ val json = JSONObject(stateFile.readText())
700
+ val failedBundles = json.optJSONObject("failedBundles")
701
+ val failed = mutableListOf<LegacyFailedHash>()
702
+ failedBundles?.keys()?.forEach { hash ->
703
+ if (isValidHash(hash)) {
704
+ val timestamp = failedBundles.optJSONObject(hash)
705
+ ?.optDouble("failedAt", Double.NaN)
706
+ ?.takeIf { it.isFinite() && it >= 0 }
707
+ failed.add(LegacyFailedHash(hash, timestamp))
708
+ }
709
+ }
710
+ failed.sortedWith(
711
+ compareByDescending<LegacyFailedHash> { it.failedAt != null }
712
+ .thenByDescending { it.failedAt ?: Double.NEGATIVE_INFINITY }
713
+ .thenBy { it.hash },
714
+ ).take(MAX_LEGACY_FAILED_HASHES).mapTo(linkedSetOf()) { it.hash }
715
+ } catch (_: Exception) {
716
+ emptySet()
717
+ }
718
+ }
719
+
720
+ private data class LegacyFailedHash(val hash: String, val failedAt: Double?)
721
+
722
+ private fun persist(ledger: Ledger, replaceExisting: Boolean = false): Ledger {
723
+ failpoint(FAIL_BEFORE_LEDGER_COMMIT)
724
+ if (!replaceExisting) {
725
+ val diskRevision = readPersistedRevision()
726
+ check(diskRevision == ledger.revision) {
727
+ "Startup recovery ledger changed before commit " +
728
+ "(expected revision ${ledger.revision}, found $diskRevision)"
729
+ }
730
+ }
731
+ val next = ledger.copy(revision = ledger.revision + 1)
732
+ writeAtomic(ledgerFile(), ledgerJson(next).toString())
733
+ return next
734
+ }
735
+
736
+ private fun readPersistedRevision(): Long {
737
+ val file = ledgerFile()
738
+ if (!file.baseFile.exists() && !File(file.baseFile.path + ".new").exists()) return 0
739
+ return JSONObject(String(file.readFully(), Charsets.UTF_8)).getLong("revision")
740
+ }
741
+
742
+ private fun ledgerJson(ledger: Ledger): JSONObject {
743
+ val json = JSONObject()
744
+ .put("schemaVersion", PROTOCOL_VERSION)
745
+ .put("revision", ledger.revision)
746
+ .put("binaryIdentity", ledger.binaryIdentity)
747
+ .put("phase", ledger.phase)
748
+ .put("quarantinedHashes", JSONArray(ledger.quarantinedHashes.sorted()))
749
+ .put("revokedHashes", JSONArray(ledger.revokedHashes.sorted()))
750
+ .put("pendingRecoveryEvents", JSONArray(ledger.pendingRecoveryEvents.map(::eventJson)))
751
+ .put("legacyStateImported", ledger.legacyStateImported)
752
+ .put("rollbackCrashCount", ledger.rollbackCrashCount)
753
+ ledger.reservedAttemptId?.let { json.put("reservedAttemptId", it) }
754
+ ledger.candidateHash?.let { json.put("candidateHash", it) }
755
+ ledger.candidateRuntimeVersion?.let { json.put("candidateRuntimeVersion", it) }
756
+ ledger.stableHash?.let { json.put("stableHash", it) }
757
+ ledger.stableRuntimeVersion?.let { json.put("stableRuntimeVersion", it) }
758
+ ledger.previousStableHash?.let { json.put("previousStableHash", it) }
759
+ ledger.previousStableRuntimeVersion?.let { json.put("previousStableRuntimeVersion", it) }
760
+ ledger.rollbackFailedHash?.let { json.put("rollbackFailedHash", it) }
761
+ ledger.rollbackReason?.let { json.put("rollbackReason", it) }
762
+ ledger.lastHealthyAttemptId?.let { json.put("lastHealthyAttemptId", it) }
763
+ ledger.policy?.let {
764
+ json.put("policy", JSONObject()
765
+ .put("maxCrashCount", it.maxCrashCount)
766
+ .put("healthCheckMode", it.healthCheckMode)
767
+ .put("healthyAfterSec", it.healthyAfterSec))
768
+ }
769
+ ledger.activeAttempt?.let {
770
+ json.put("activeAttempt", attemptJson(it).put("processToken", it.processToken))
771
+ }
772
+ return json
773
+ }
774
+
775
+ private fun ledgerFromJson(json: JSONObject): Ledger {
776
+ if (json.getInt("schemaVersion") != PROTOCOL_VERSION) {
777
+ throw IllegalArgumentException("Unsupported startup recovery schema")
778
+ }
779
+ val policyJson = json.optionalObject("policy")
780
+ val policy = policyJson?.let {
781
+ RecoveryPolicy(
782
+ maxCrashCount = it.getInt("maxCrashCount"),
783
+ healthCheckMode = it.getString("healthCheckMode"),
784
+ healthyAfterSec = it.getDouble("healthyAfterSec"),
785
+ )
786
+ }
787
+ val attemptJson = json.optionalObject("activeAttempt")
788
+ val attempt = attemptJson?.let {
789
+ ActiveAttempt(
790
+ hash = it.getString("hash"),
791
+ attemptId = it.getString("attemptId"),
792
+ processToken = it.getString("processToken"),
793
+ unacknowledgedLaunchCount = it.getInt("unacknowledgedLaunchCount"),
794
+ )
795
+ }
796
+ val events = json.requiredObjectList("pendingRecoveryEvents").map {
797
+ require(it.getString("reason") == ROLLBACK_CRASH_LOOP) {
798
+ "Invalid startup recovery event reason"
799
+ }
800
+ RecoveryEvent(
801
+ id = it.getString("id"),
802
+ failedHash = it.getString("failedHash"),
803
+ recoveryTarget = it.getString("recoveryTarget"),
804
+ recoveredHash = it.optionalString("recoveredHash"),
805
+ crashCount = it.getInt("crashCount"),
806
+ failedAt = it.getLong("failedAt"),
807
+ )
808
+ }
809
+ return Ledger(
810
+ revision = json.getLong("revision"),
811
+ binaryIdentity = json.getString("binaryIdentity"),
812
+ phase = json.getString("phase"),
813
+ candidateHash = json.optionalString("candidateHash"),
814
+ candidateRuntimeVersion = json.optionalString("candidateRuntimeVersion"),
815
+ stableHash = json.optionalString("stableHash"),
816
+ stableRuntimeVersion = json.optionalString("stableRuntimeVersion"),
817
+ previousStableHash = json.optionalString("previousStableHash"),
818
+ previousStableRuntimeVersion = json.optionalString("previousStableRuntimeVersion"),
819
+ policy = policy,
820
+ reservedAttemptId = json.optionalString("reservedAttemptId"),
821
+ activeAttempt = attempt,
822
+ lastHealthyAttemptId = json.optionalString("lastHealthyAttemptId"),
823
+ quarantinedHashes = json.requiredHashSet("quarantinedHashes"),
824
+ revokedHashes = json.requiredHashSet("revokedHashes"),
825
+ pendingRecoveryEvents = events,
826
+ legacyStateImported = json.getBoolean("legacyStateImported"),
827
+ rollbackFailedHash = json.optionalString("rollbackFailedHash"),
828
+ rollbackCrashCount = json.getInt("rollbackCrashCount"),
829
+ rollbackReason = json.optionalString("rollbackReason"),
830
+ ).also(::validateLedger)
831
+ }
832
+
833
+ private fun validateLedger(ledger: Ledger) {
834
+ require(ledger.revision >= 0) { "Invalid startup recovery revision" }
835
+ require(!ledger.binaryIdentity.isNullOrBlank()) { "Startup recovery ledger is missing its binary identity" }
836
+ require(ledger.phase in setOf(
837
+ PHASE_IDLE,
838
+ PHASE_ARMED,
839
+ PHASE_LAUNCHING,
840
+ PHASE_STABLE,
841
+ PHASE_ROLLBACK_REQUIRED,
842
+ PHASE_RECOVERED,
843
+ )) { "Invalid startup recovery phase" }
844
+ ledger.candidateHash?.let(::requireHash)
845
+ ledger.stableHash?.let(::requireHash)
846
+ ledger.previousStableHash?.let(::requireHash)
847
+ ledger.rollbackFailedHash?.let(::requireHash)
848
+ ledger.activeAttempt?.let {
849
+ requireHash(it.hash)
850
+ require(it.attemptId.isNotBlank()) { "Active startup attempt is missing its ID" }
851
+ require(it.processToken.isNotBlank()) { "Active startup attempt is missing its process token" }
852
+ require(it.unacknowledgedLaunchCount >= 0) { "Invalid startup launch count" }
853
+ }
854
+ ledger.policy?.let {
855
+ require(it.maxCrashCount >= 0) { "Invalid startup crash limit" }
856
+ require(it.healthCheckMode == HEALTH_AUTO || it.healthCheckMode == HEALTH_MANUAL) {
857
+ "Invalid startup health mode"
858
+ }
859
+ require(it.healthyAfterSec.isFinite() && it.healthyAfterSec >= 0) {
860
+ "Invalid startup health delay"
861
+ }
862
+ }
863
+ if (ledger.phase == PHASE_ARMED && (ledger.policy?.maxCrashCount ?: 0) > 0) {
864
+ require(ledger.candidateHash != null && !ledger.reservedAttemptId.isNullOrBlank()) {
865
+ "Armed startup candidate is missing its reserved attempt ID"
866
+ }
867
+ }
868
+ if (ledger.phase == PHASE_LAUNCHING) {
869
+ require(ledger.activeAttempt != null && ledger.reservedAttemptId == null) {
870
+ "Launching startup candidate has invalid attempt state"
871
+ }
872
+ }
873
+ require(ledger.rollbackReason == null || ledger.rollbackReason in setOf(
874
+ ROLLBACK_CRASH_LOOP,
875
+ ROLLBACK_REVOKED,
876
+ )) { "Invalid startup rollback reason" }
877
+ require(ledger.rollbackCrashCount >= 0) { "Invalid startup rollback crash count" }
878
+ ledger.pendingRecoveryEvents.forEach { event ->
879
+ require(event.id.isNotBlank()) { "Startup recovery event is missing its ID" }
880
+ requireHash(event.failedHash)
881
+ require(event.crashCount >= 0) { "Invalid startup recovery event crash count" }
882
+ require(event.failedAt >= 0) { "Invalid startup recovery event timestamp" }
883
+ require(
884
+ (event.recoveryTarget == RECOVERY_EMBEDDED && event.recoveredHash == null) ||
885
+ (event.recoveryTarget == RECOVERY_PREVIOUS &&
886
+ event.recoveredHash?.let(::isValidHash) == true)
887
+ ) { "Invalid startup recovery event target" }
888
+ }
889
+ }
890
+
891
+ private fun attemptJson(attempt: ActiveAttempt): JSONObject = JSONObject()
892
+ .put("hash", attempt.hash)
893
+ .put("attemptId", attempt.attemptId)
894
+ .put("status", PHASE_LAUNCHING)
895
+ .put("unacknowledgedLaunchCount", attempt.unacknowledgedLaunchCount)
896
+
897
+ private fun eventJson(event: RecoveryEvent): JSONObject {
898
+ val json = JSONObject()
899
+ .put("id", event.id)
900
+ .put("failedHash", event.failedHash)
901
+ .put("recoveryTarget", event.recoveryTarget)
902
+ .put("crashCount", event.crashCount)
903
+ .put("reason", "crash_loop")
904
+ .put("failedAt", event.failedAt)
905
+ event.recoveredHash?.let { json.put("recoveredHash", it) }
906
+ return json
907
+ }
908
+
909
+ private fun externalPhase(phase: String): String = when (phase) {
910
+ PHASE_ROLLBACK_REQUIRED -> PHASE_LAUNCHING
911
+ else -> phase
912
+ }
913
+
914
+ private fun currentHash(): String? = BundleDropOtaResolver.readCurrentPointer(bundleDropRoot)
915
+ ?.let(::hashFromBundlePath)
916
+
917
+ private fun readPointerHash(name: String): String? {
918
+ return try {
919
+ val pointer = File(bundleDropRoot, name)
920
+ if (!pointer.isFile) return null
921
+ JSONObject(pointer.readText()).optString("hash", "").takeIf(::isValidHash)
922
+ } catch (_: Exception) {
923
+ null
924
+ }
925
+ }
926
+
927
+ private fun hashFromBundlePath(path: String): String? = File(path).parentFile?.name?.takeIf(::isValidHash)
928
+
929
+ private fun writePointer(name: String, hash: String) {
930
+ requireHash(hash)
931
+ bundleDropRoot.mkdirs()
932
+ val json = JSONObject()
933
+ .put("hash", hash)
934
+ .put("updatedAt", isoTimestamp(nowMillis()))
935
+ writeAtomic(AtomicFile(File(bundleDropRoot, name)), json.toString())
936
+ }
937
+
938
+ private fun deletePointer(name: String) {
939
+ AtomicFile(File(bundleDropRoot, name)).delete()
940
+ }
941
+
942
+ private fun ledgerFile(): AtomicFile = AtomicFile(File(bundleDropRoot, RECOVERY_LEDGER))
943
+
944
+ private fun isoTimestamp(timestampMillis: Long): String =
945
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
946
+ timeZone = TimeZone.getTimeZone("UTC")
947
+ }.format(Date(timestampMillis))
948
+
949
+ private fun writeAtomic(file: AtomicFile, content: String) {
950
+ file.baseFile.parentFile?.mkdirs()
951
+ var stream: FileOutputStream? = null
952
+ try {
953
+ stream = file.startWrite()
954
+ stream.write(content.toByteArray(Charsets.UTF_8))
955
+ file.finishWrite(stream)
956
+ } catch (error: Exception) {
957
+ if (stream != null) file.failWrite(stream)
958
+ throw error
959
+ }
960
+ }
961
+
962
+ private fun JSONObject.optionalObject(key: String): JSONObject? {
963
+ if (!has(key) || isNull(key)) return null
964
+ return getJSONObject(key)
965
+ }
966
+
967
+ private fun JSONObject.optionalString(key: String): String? {
968
+ if (!has(key) || isNull(key)) return null
969
+ return getString(key)
970
+ }
971
+
972
+ private fun JSONObject.requiredHashSet(key: String): Set<String> {
973
+ val array = getJSONArray(key)
974
+ val values = linkedSetOf<String>()
975
+ for (index in 0 until array.length()) {
976
+ val value = array.getString(index)
977
+ requireHash(value)
978
+ require(values.add(value)) { "Startup recovery ledger contains duplicate $key entries" }
979
+ }
980
+ return values
981
+ }
982
+
983
+ private fun JSONObject.requiredObjectList(key: String): List<JSONObject> {
984
+ val array = getJSONArray(key)
985
+ return (0 until array.length()).map(array::getJSONObject)
986
+ }
987
+
988
+ private fun requireHash(hash: String) {
989
+ require(isValidHash(hash)) { "Bundle hash must be a canonical lowercase SHA-256" }
990
+ }
991
+
992
+ private fun isValidHash(hash: String): Boolean = BUNDLE_HASH.matches(hash)
993
+
994
+ private class CorruptLedgerException(cause: Throwable) : Exception(cause)
995
+ private class IncompatibleLedgerException : Exception()
996
+
997
+ companion object {
998
+ const val PROTOCOL_VERSION = 1
999
+ const val RECOVERY_LEDGER = "startup-recovery.json"
1000
+ const val FAIL_AFTER_ARMED = "after_armed"
1001
+ const val FAIL_AFTER_VERIFICATION = "after_verification"
1002
+ const val FAIL_BEFORE_LEDGER_COMMIT = "before_ledger_commit"
1003
+ const val FAIL_AFTER_PREVIOUS_POINTER = "after_previous_pointer"
1004
+ const val FAIL_AFTER_CURRENT_POINTER = "after_current_pointer"
1005
+ const val FAIL_AFTER_LAUNCH_PERSISTED = "after_launch_persisted"
1006
+ const val FAIL_AFTER_HEALTH_COMMITTED = "after_health_committed"
1007
+ const val FAIL_AFTER_ROLLBACK_REQUIRED = "after_rollback_required"
1008
+ const val FAIL_AFTER_RECOVERY_POINTER = "after_recovery_pointer"
1009
+ const val FAIL_AFTER_RECOVERED = "after_recovered"
1010
+
1011
+ private const val CURRENT_POINTER = "current.json"
1012
+ private const val PREVIOUS_POINTER = "previous.json"
1013
+ private const val LEGACY_STATE = "state.json"
1014
+ private const val MAX_PENDING_EVENTS = 20
1015
+ private const val MAX_LEGACY_FAILED_HASHES = 20
1016
+ private const val HEALTH_AUTO = "auto"
1017
+ private const val HEALTH_MANUAL = "manual"
1018
+ private const val PHASE_IDLE = "idle"
1019
+ private const val PHASE_ARMED = "armed"
1020
+ private const val PHASE_LAUNCHING = "launching"
1021
+ private const val PHASE_STABLE = "stable"
1022
+ private const val PHASE_ROLLBACK_REQUIRED = "rollback_required"
1023
+ private const val PHASE_RECOVERED = "recovered"
1024
+ private const val RECOVERY_PREVIOUS = "previous"
1025
+ private const val RECOVERY_EMBEDDED = "embedded"
1026
+ private const val ROLLBACK_CRASH_LOOP = "crash_loop"
1027
+ private const val ROLLBACK_REVOKED = "revoked"
1028
+ private val BUNDLE_HASH = Regex("^[a-f0-9]{64}$")
1029
+ private val STORAGE_LOCK = Any()
1030
+ }
1031
+ }
1032
+
1033
+ /** Process-scoped facade used by cold-start resolution and the React Native bridge. */
1034
+ internal object BundleDropStartupRecovery {
1035
+ private val processToken = UUID.randomUUID().toString()
1036
+
1037
+ @Volatile private var startupAttemptHash: String? = null
1038
+ @Volatile private var startupAttemptId: String? = null
1039
+ @Volatile private var startupSelectedHash: String? = null
1040
+ @Volatile private var contentListenerInstalled = false
1041
+ @Volatile private var scheduledHealthAttemptKey: String? = null
1042
+
1043
+ fun controller(context: Context): BundleDropStartupRecoveryController =
1044
+ BundleDropStartupRecoveryController(
1045
+ bundleDropRoot = File(context.filesDir, "bundle-drop"),
1046
+ processToken = processToken,
1047
+ binaryIdentity = BundleDropNativePaths.currentBinaryIdentity(context),
1048
+ expectedRuntimeVersion = BundleDropNativePaths.readEmbeddedRuntimeVersion(context),
1049
+ )
1050
+
1051
+ fun selectForStartup(
1052
+ context: Context,
1053
+ select: () -> BundleDropStartupRecoveryController.StartupSelection = {
1054
+ controller(context).selectForStartup()
1055
+ },
1056
+ ): BundleDropStartupRecoveryController.StartupSelection {
1057
+ val selection = try {
1058
+ select()
1059
+ } catch (error: Exception) {
1060
+ Log.e("BundleDrop", "Startup recovery failed closed to the embedded bundle", error)
1061
+ BundleDropStartupRecoveryController.StartupSelection(null)
1062
+ }
1063
+ startupAttemptHash = selection.attemptHash
1064
+ startupAttemptId = selection.attemptId
1065
+ startupSelectedHash = selection.bundlePath
1066
+ ?.let(::File)
1067
+ ?.parentFile
1068
+ ?.name
1069
+ ?.takeIf { it.matches(Regex("^[a-f0-9]{64}$")) }
1070
+ if (selection.attemptId != null) installContentAppearedListener(context)
1071
+ return selection
1072
+ }
1073
+
1074
+ fun startupAttempt(): Pair<String, String>? {
1075
+ val hash = startupAttemptHash ?: return null
1076
+ val id = startupAttemptId ?: return null
1077
+ return hash to id
1078
+ }
1079
+
1080
+ fun startupSelectedHash(): String? = startupSelectedHash
1081
+
1082
+ fun clearStartupSelection() {
1083
+ startupAttemptHash = null
1084
+ startupAttemptId = null
1085
+ startupSelectedHash = null
1086
+ }
1087
+
1088
+ internal fun scheduleContentAppearedHealthOnce(
1089
+ hash: String,
1090
+ attemptId: String,
1091
+ schedule: () -> Unit,
1092
+ ): Boolean = synchronized(this) {
1093
+ val attemptKey = "$hash:$attemptId"
1094
+ if (scheduledHealthAttemptKey == attemptKey) return@synchronized false
1095
+ scheduledHealthAttemptKey = attemptKey
1096
+ schedule()
1097
+ true
1098
+ }
1099
+
1100
+ private fun installContentAppearedListener(context: Context) {
1101
+ if (contentListenerInstalled) return
1102
+ synchronized(this) {
1103
+ if (contentListenerInstalled) return
1104
+ ReactMarker.addListener(object : ReactMarker.MarkerListener {
1105
+ override fun logMarker(name: ReactMarkerConstants, tag: String?, instanceKey: Int) {
1106
+ if (name == ReactMarkerConstants.CONTENT_APPEARED) {
1107
+ val (hash, attemptId) = startupAttempt() ?: return
1108
+ scheduleContentAppearedHealthOnce(hash, attemptId) {
1109
+ controller(context).scheduleContentAppearedHealth()
1110
+ }
1111
+ }
1112
+ }
1113
+ })
1114
+ contentListenerInstalled = true
1115
+ }
1116
+ }
1117
+ }