euv-core 0.48.10

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
use super::*;

/// Encodes raw proxy credentials (`"user:pass"`) into an HTTP `Basic <base64>` header value, or preserves pre-prefixed auth schemes.
///
/// # Arguments
///
/// - `&str` - Raw proxy credential string (e.g. `"dev:secret"`, `"Basic ..."`, or `"Bearer ..."`).
///
/// # Returns
///
/// - `String` - Normalized `Proxy-Authorization` header value.
#[must_use]
pub fn encode_proxy_basic_auth(raw: &str) -> String {
    let trimmed: &str = raw.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    let lower: String = trimmed.to_ascii_lowercase();
    if lower.starts_with("basic ") || lower.starts_with("bearer ") {
        return trimmed.to_string();
    }
    let bytes: &[u8] = trimmed.as_bytes();
    let mut out: String = String::with_capacity(6 + bytes.len().div_ceil(3) * 4);
    out.push_str("Basic ");
    let mut idx: usize = 0;
    while idx < bytes.len() {
        let b0: u8 = bytes[idx];
        let b1: u8 = if idx + 1 < bytes.len() {
            bytes[idx + 1]
        } else {
            0
        };
        let b2: u8 = if idx + 2 < bytes.len() {
            bytes[idx + 2]
        } else {
            0
        };
        let triple: u32 = ((b0 as u32) << 16) | ((b1 as u32) << 8) | (b2 as u32);
        out.push(BASE64_STD_TABLE[((triple >> 18) & 0x3F) as usize] as char);
        out.push(BASE64_STD_TABLE[((triple >> 12) & 0x3F) as usize] as char);
        if idx + 1 < bytes.len() {
            out.push(BASE64_STD_TABLE[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            out.push('=');
        }
        if idx + 2 < bytes.len() {
            out.push(BASE64_STD_TABLE[(triple & 0x3F) as usize] as char);
        } else {
            out.push('=');
        }
        idx += 3;
    }
    out
}

/// Resolves a `HotUpdateProxyConfig` using a caller-provided environment lookup closure (enabling deterministic tests).
///
/// # Arguments
///
/// - `F` - Environment lookup function mapping variable name to optional value.
///
/// # Returns
///
/// - `HotUpdateProxyConfig` - Resolved hot-update server and proxy settings.
#[must_use]
pub fn resolve_proxy_env_from<F>(get_var: F) -> HotUpdateProxyConfig
where
    F: Fn(&str) -> Option<String>,
{
    /// Body of the `lookup_non_empty` free function.
    ///
    /// # Arguments
    ///
    /// - `&F` - Shared reference to a `F`.
    /// - `&str` - Shared reference to a `str`.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - `Some(...)` on success, `None` otherwise.
    fn lookup_non_empty<F>(get_var: &F, name: &str) -> Option<String>
    where
        F: Fn(&str) -> Option<String>,
    {
        get_var(name)
            .map(|v: String| v.trim().to_string())
            .filter(|v: &String| !v.is_empty())
    }
    let server_url: String = lookup_non_empty(&get_var, ENV_EUV_UPDATE_URL)
        .unwrap_or_else(|| DEFAULT_HOT_UPDATE_SERVER_URL.to_string());
    let channel: String = lookup_non_empty(&get_var, ENV_EUV_UPDATE_CHANNEL)
        .unwrap_or_else(|| DEFAULT_HOT_UPDATE_CHANNEL.to_string());
    let cache_dir: Option<PathBuf> =
        lookup_non_empty(&get_var, ENV_EUV_UPDATE_CACHE_DIR).map(PathBuf::from);
    let proxy_url: Option<String> = lookup_non_empty(&get_var, ENV_EUV_PROXY_URL)
        .or_else(|| lookup_non_empty(&get_var, ENV_HTTPS_PROXY))
        .or_else(|| lookup_non_empty(&get_var, ENV_HTTP_PROXY))
        .or_else(|| lookup_non_empty(&get_var, ENV_HTTPS_PROXY_LOWER))
        .or_else(|| lookup_non_empty(&get_var, ENV_HTTP_PROXY_LOWER));
    HotUpdateProxyConfig::new(
        server_url,
        proxy_url,
        None,
        channel,
        true,
        DEFAULT_POLL_FALLBACK_SECS,
    )
    .with_cache_dir(cache_dir)
}

/// Resolves a `HotUpdateProxyConfig` from standard process environment variables (`EUV_UPDATE_URL`, `EUV_PROXY_URL`, `HTTPS_PROXY`, `HTTP_PROXY`).
///
/// # Returns
///
/// - `HotUpdateProxyConfig` - Resolved on-device hot-update configuration.
#[must_use]
pub fn resolve_proxy_env() -> HotUpdateProxyConfig {
    #[cfg(not(target_arch = "wasm32"))]
    {
        resolve_proxy_env_from(|name: &str| env::var(name).ok())
    }
    #[cfg(target_arch = "wasm32")]
    {
        resolve_proxy_env_from(|_: &str| None)
    }
}

/// Starts the dedicated background `UpdateWorker` thread with live Hyperlane SSE subscription and manifest reconciliation (Sec 11.2 / 11.8).
///
/// # Arguments
///
/// - `UpdateClientConfig` - Client connection, negotiation, verification key, and budget configuration.
/// - `Arc<dyn StateMigrator>` - Pure background state migrator.
/// - `Option<ReleaseManifest>` - Optional currently active built-in or cached manifest baseline.
///
/// # Returns
///
/// - `Result<UpdateWorkerHandle, DynamicReleaseError>` - Running handle with non-blocking candidate mailbox.
pub fn start_updates(
    config: UpdateClientConfig,
    migrator: Arc<dyn StateMigrator>,
    initial_manifest: Option<ReleaseManifest>,
) -> Result<UpdateWorkerHandle, DynamicReleaseError> {
    start_updates_with_attention(
        config,
        migrator,
        initial_manifest,
        Arc::new(AtomicBool::new(false)),
    )
}

/// Starts the dedicated background `UpdateWorker` thread bound to a shared lock-free `ui_attention_flag`.
///
/// # Arguments
///
/// - `UpdateClientConfig` - Client connection, negotiation, verification key, and budget configuration.
/// - `Arc<dyn StateMigrator>` - Pure background state migrator.
/// - `Option<ReleaseManifest>` - Optional currently active built-in or cached manifest baseline.
/// - `Arc<AtomicBool>` - Lock-free attention flag set ONLY when a new candidate arrives or error state transitions.
///
/// # Returns
///
/// - `Result<UpdateWorkerHandle, DynamicReleaseError>` - Running handle with non-blocking candidate mailbox.
pub(crate) fn start_updates_with_attention(
    config: UpdateClientConfig,
    migrator: Arc<dyn StateMigrator>,
    initial_manifest: Option<ReleaseManifest>,
    ui_attention_flag: Arc<AtomicBool>,
) -> Result<UpdateWorkerHandle, DynamicReleaseError> {
    #[cfg(not(target_arch = "wasm32"))]
    let restored_pair: Option<PersistedReleaseRestore> = if initial_manifest.is_none() {
        load_persisted_release_with_blobs(&config)
    } else {
        None
    };
    #[cfg(target_arch = "wasm32")]
    let restored_pair: Option<PersistedReleaseRestore> = None;
    let seed_manifest: Option<ReleaseManifest>;
    let seed_blobs: HashMap<String, Arc<Vec<u8>>>;
    let restored_candidate: Option<PreparedReleaseCandidate>;
    match restored_pair {
        Some(restored) => {
            seed_manifest = Some(restored.candidate.get_manifest().clone());
            seed_blobs = restored.blobs;
            restored_candidate = Some(restored.candidate);
        }
        None => {
            seed_manifest = initial_manifest;
            seed_blobs = HashMap::new();
            restored_candidate = None;
        }
    }
    let initial_seq: u64 = seed_manifest
        .as_ref()
        .map(ReleaseManifest::get_release_seq)
        .unwrap_or(0);
    let mailbox_baseline_seq: u64 = if restored_candidate.is_some() {
        0
    } else {
        initial_seq
    };
    let mailbox: CandidateMailbox =
        CandidateMailbox::new(config.get_mailbox_capacity(), mailbox_baseline_seq);
    if let Some(cand) = restored_candidate {
        mailbox.push_candidate(cand);
        ui_attention_flag.store(true, Ordering::Release);
        notify_frame_needed();
    }
    let shared: Arc<UpdateWorkerShared> = Arc::new(UpdateWorkerShared {
        config,
        mailbox,
        blob_cache: Mutex::new(seed_blobs),
        fetched_hashes_log: Mutex::new(Vec::new()),
        last_event_id: Mutex::new(if initial_seq > 0 {
            Some(initial_seq.to_string())
        } else {
            None
        }),
        last_prepared_manifest: Mutex::new(seed_manifest),
        last_error: Mutex::new(None),
        pending_snapshot: Mutex::new(None),
        migrator,
        running: AtomicBool::new(true),
        reconcile_requested: AtomicBool::new(true),
        sse_connect_count: AtomicU64::new(0),
        sse_live: AtomicBool::new(false),
        ui_attention_flag,
    });
    #[cfg(not(target_arch = "wasm32"))]
    {
        let worker_shared: Arc<UpdateWorkerShared> = Arc::clone(&shared);
        let worker_thread: JoinHandle<()> = Builder::new()
            .name(UPDATE_WORKER_THREAD_NAME.to_string())
            .spawn(move || {
                run_update_worker_loop(worker_shared);
            })
            .map_err(|err: io::Error| {
                DynamicReleaseError::StorageError(format!("{ERR_WORKER_SPAWN}: {err}"))
            })?;
        Ok(UpdateWorkerHandle {
            shared,
            worker_thread: Some(worker_thread),
        })
    }
    #[cfg(target_arch = "wasm32")]
    {
        Ok(UpdateWorkerHandle { shared })
    }
}

/// Formats the query parameter token for `DeliveryChannelMode`.
///
/// # Arguments
///
/// - `DeliveryChannelMode` - Client channel delivery mode.
///
/// # Returns
///
/// - `&'static str` - Query string token.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub(crate) fn delivery_mode_query_token(mode: DeliveryChannelMode) -> &'static str {
    match mode {
        DeliveryChannelMode::WasmComponent => QUERY_MODE_WASM,
        DeliveryChannelMode::DeclarativeData => QUERY_MODE_DATA,
    }
}

/// Parses an `http://host:port` base URL into `(host_port, base_path)`.
///
/// # Arguments
///
/// - `&str` - Base URL string.
///
/// # Returns
///
/// - `Result<(&str, &str), DynamicReleaseError>` - Host-and-port authority and normalized prefix path.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn parse_http_base_url(base_url: &str) -> Result<(&str, &str), DynamicReleaseError> {
    let trimmed: &str = base_url.trim().trim_end_matches('/');
    let Some(rest) = trimmed.strip_prefix(UPDATE_HTTP_SCHEME) else {
        return Err(DynamicReleaseError::NetworkError(
            ERR_INVALID_HTTP_BASE_URL.to_string(),
        ));
    };
    if rest.is_empty() {
        return Err(DynamicReleaseError::NetworkError(
            ERR_INVALID_HTTP_BASE_URL.to_string(),
        ));
    }
    if let Some((authority, path)) = rest.split_once('/') {
        Ok((authority, path))
    } else {
        Ok((rest, ""))
    }
}

/// Resolves an HTTP authority (`host`, `host:port`, or `[ipv6]:port`) into a `SocketAddr`, defaulting to port `80`.
///
/// # Arguments
///
/// - `&str` - Authority slice extracted from `parse_http_base_url`.
///
/// # Returns
///
/// - `Result<SocketAddr, DynamicReleaseError>` - First resolved TCP socket address or network error.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn resolve_http_socket_addr(authority: &str) -> Result<SocketAddr, DynamicReleaseError> {
    let trimmed: &str = authority.trim();
    let has_port: bool = if trimmed.starts_with('[') {
        trimmed.contains("]:")
    } else {
        trimmed.matches(':').count() == 1
    };
    let host_port: Cow<'_, str> = if has_port {
        Cow::Borrowed(trimmed)
    } else if trimmed.contains(':') && !trimmed.starts_with('[') {
        Cow::Owned(format!("[{trimmed}]:{DEFAULT_UPDATE_HTTP_PORT}"))
    } else {
        Cow::Owned(format!("{trimmed}:{DEFAULT_UPDATE_HTTP_PORT}"))
    };
    host_port
        .as_ref()
        .to_socket_addrs()
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?
        .next()
        .ok_or_else(|| DynamicReleaseError::NetworkError(ERR_INVALID_HTTP_BASE_URL.to_string()))
}

/// Computes the on-disk content-addressed blob cache path for `sha256` under `cache_dir`.
///
/// # Arguments
///
/// - `&Path` - Root hot-update cache directory.
/// - `&str` - Lowercase 64-character SHA-256 hex digest.
///
/// # Returns
///
/// - `PathBuf` - Destination blob file path.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
fn cache_blob_path(cache_dir: &Path, sha256: &str) -> PathBuf {
    cache_dir.join(HOT_UPDATE_CACHE_BLOBS_DIR).join(sha256)
}

/// Atomically persists a verified SHA-256 blob into `cache_dir/blobs/<sha256>`.
///
/// # Arguments
///
/// - `&Path` - Root hot-update cache directory.
/// - `&str` - Verified lowercase 64-character SHA-256 hex digest.
/// - `&[u8]` - Raw blob payload bytes.
#[cfg(not(target_arch = "wasm32"))]
fn persist_verified_blob(cache_dir: &Path, sha256: &str, bytes: &[u8]) {
    if !is_valid_sha256_hex(sha256) {
        return;
    }
    let blobs_dir: PathBuf = cache_dir.join(HOT_UPDATE_CACHE_BLOBS_DIR);
    if fs::create_dir_all(&blobs_dir).is_err() {
        return;
    }
    let target: PathBuf = cache_blob_path(cache_dir, sha256);
    if let Ok(meta) = fs::metadata(&target)
        && meta.len() == bytes.len() as u64
    {
        return;
    }
    let tmp: PathBuf = blobs_dir.join(format!("{sha256}{HOT_UPDATE_CACHE_TMP_SUFFIX}"));
    if fs::write(&tmp, bytes).is_ok() {
        let _: io::Result<()> = fs::rename(&tmp, &target);
    }
}

/// Loads and re-verifies a content-addressed blob from `cache_dir/blobs/<sha256>`.
///
/// # Arguments
///
/// - `&Path` - Root hot-update cache directory.
/// - `&str` - Expected lowercase 64-character SHA-256 hex digest.
///
/// # Returns
///
/// - `Option<Vec<u8>>` - Verified bytes when present and digest-matching, `None` otherwise.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
fn load_verified_blob(cache_dir: &Path, sha256: &str) -> Option<Vec<u8>> {
    if !is_valid_sha256_hex(sha256) {
        return None;
    }
    let bytes: Vec<u8> = fs::read(cache_blob_path(cache_dir, sha256)).ok()?;
    let actual_sha: String = sha256_hex(&bytes);
    if constant_time_eq(actual_sha.as_bytes(), sha256.as_bytes()) {
        Some(bytes)
    } else {
        None
    }
}

/// Atomically persists the active `ReleaseManifest` to `active_manifest.json`, preserving any prior manifest in `previous_manifest.json`.
///
/// # Arguments
///
/// - `&Path` - Root hot-update cache directory.
/// - `&ReleaseManifest` - Verified applied release manifest.
///
/// # Returns
///
/// - `Result<(), DynamicReleaseError>` - Persistence outcome.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn persist_active_manifest(
    cache_dir: &Path,
    manifest: &ReleaseManifest,
) -> Result<(), DynamicReleaseError> {
    fs::create_dir_all(cache_dir)
        .map_err(|err: io::Error| DynamicReleaseError::StorageError(err.to_string()))?;
    let serialized: String = to_string_pretty(manifest).map_err(|err: serde_json::Error| {
        DynamicReleaseError::StorageError(format!("{ERR_MANIFEST_SERIALIZE}: {err}"))
    })?;
    let active_path: PathBuf = cache_dir.join(HOT_UPDATE_CACHE_ACTIVE_MANIFEST);
    let prev_path: PathBuf = cache_dir.join(HOT_UPDATE_CACHE_PREV_MANIFEST);
    if let Ok(existing) = fs::read_to_string(&active_path)
        && existing != serialized
    {
        let prev_tmp: PathBuf = cache_dir.join(format!(
            "{HOT_UPDATE_CACHE_PREV_MANIFEST}{HOT_UPDATE_CACHE_TMP_SUFFIX}"
        ));
        if fs::write(&prev_tmp, existing.as_bytes()).is_ok() {
            let _: io::Result<()> = fs::rename(&prev_tmp, &prev_path);
        }
    }
    let active_tmp: PathBuf = cache_dir.join(format!(
        "{HOT_UPDATE_CACHE_ACTIVE_MANIFEST}{HOT_UPDATE_CACHE_TMP_SUFFIX}"
    ));
    fs::write(&active_tmp, serialized.as_bytes())
        .map_err(|err: io::Error| DynamicReleaseError::StorageError(err.to_string()))?;
    fs::rename(&active_tmp, &active_path)
        .map_err(|err: io::Error| DynamicReleaseError::StorageError(err.to_string()))
}

/// Attempts to load, verify, and warm a single persisted manifest file and all of its cached SHA-256 blobs.
///
/// # Arguments
///
/// - `&Path` - Root hot-update cache directory.
/// - `&Path` - Path to `active_manifest.json` or `previous_manifest.json`.
/// - `&UpdateClientConfig` - Client verification key, ABI, delivery mode, and sandbox ceilings.
///
/// # Returns
///
/// - `Option<PersistedReleaseRestore>` - Warmed candidate and loaded blobs when valid.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
fn load_manifest_candidate_from_file(
    cache_dir: &Path,
    manifest_path: &Path,
    config: &UpdateClientConfig,
) -> Option<PersistedReleaseRestore> {
    let raw: String = fs::read_to_string(manifest_path).ok()?;
    let manifest: ReleaseManifest = from_str::<ReleaseManifest>(&raw).ok()?;
    if manifest.get_project() != config.get_project()
        || manifest.get_channel() != config.get_channel()
    {
        return None;
    }
    manifest.verify_signature(config.get_verify_key()).ok()?;
    manifest
        .validate_for_host(
            config.get_host_abi(),
            config.get_capabilities(),
            config.get_delivery_mode(),
            config.get_max_artifact_bytes(),
        )
        .ok()?;
    let mut blobs: HashMap<String, Arc<Vec<u8>>> = HashMap::new();
    let mut reused_hashes: Vec<String> = Vec::new();
    for sha in manifest.all_blob_hashes().into_iter() {
        let bytes: Vec<u8> = load_verified_blob(cache_dir, &sha)?;
        let _: Option<Arc<Vec<u8>>> = blobs.insert(sha.clone(), Arc::new(bytes));
        reused_hashes.push(sha);
    }
    let mut warmed_artifacts: BTreeMap<String, WarmedArtifact> = BTreeMap::new();
    for (art_key, artifact) in manifest.get_artifacts().iter() {
        let blob: &Arc<Vec<u8>> = blobs.get(artifact.get_sha256())?;
        let warmed: WarmedArtifact = warm_verified_artifact(
            artifact,
            blob.as_slice(),
            config.get_host_abi(),
            &config.get_sandbox_config(),
        )
        .ok()?;
        let _: Option<WarmedArtifact> = warmed_artifacts.insert(art_key.clone(), warmed);
    }
    let manifest_sha256: String = manifest.manifest_sha256().ok()?;
    let affected_routes: Vec<String> = manifest.affected_routes_since(None);
    let candidate: PreparedReleaseCandidate = PreparedReleaseCandidate {
        manifest,
        manifest_sha256,
        warmed_artifacts,
        affected_routes,
        newly_fetched_hashes: Vec::new(),
        reused_cached_hashes: reused_hashes,
        migrated_ui_states: BTreeMap::new(),
        snapshot_business_revision: 0,
        snapshot_entity_revisions: BTreeMap::new(),
        prepared_on_thread: UPDATE_CACHE_RESTORE_SOURCE.to_string(),
    };
    Some(PersistedReleaseRestore { candidate, blobs })
}

/// Restores the active verified hot-update release from `config.cache_dir`, falling back to `previous_manifest.json` on corruption.
///
/// # Arguments
///
/// - `&UpdateClientConfig` - Client configuration carrying `cache_dir`, `verify_key`, and host constraints.
///
/// # Returns
///
/// - `Option<PersistedReleaseRestore>` - Verified restored candidate and cached blobs, if present.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub(crate) fn load_persisted_release_with_blobs(
    config: &UpdateClientConfig,
) -> Option<PersistedReleaseRestore> {
    let cache_dir: &Path = config.cache_dir_path()?;
    let active_path: PathBuf = cache_dir.join(HOT_UPDATE_CACHE_ACTIVE_MANIFEST);
    if let Some(restored) = load_manifest_candidate_from_file(cache_dir, &active_path, config) {
        return Some(restored);
    }
    let prev_path: PathBuf = cache_dir.join(HOT_UPDATE_CACHE_PREV_MANIFEST);
    load_manifest_candidate_from_file(cache_dir, &prev_path, config)
}

/// Decodes an HTTP/1.1 `Transfer-Encoding: chunked` body into contiguous bytes.
///
/// # Arguments
///
/// - `&[u8]` - Raw chunked response body bytes.
///
/// # Returns
///
/// - `Result<Vec<u8>, DynamicReleaseError>` - Decoded payload bytes.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn decode_chunked_body(raw: &[u8]) -> Result<Vec<u8>, DynamicReleaseError> {
    let mut out: Vec<u8> = Vec::new();
    let mut cursor: usize = 0;
    while cursor < raw.len() {
        let Some(rel_end) = raw[cursor..].windows(2).position(|w: &[u8]| w == b"\r\n") else {
            return Err(DynamicReleaseError::NetworkError(
                ERR_MALFORMED_HTTP_RESP.to_string(),
            ));
        };
        let size_line: &str = from_utf8(&raw[cursor..cursor + rel_end])
            .map_err(|_| DynamicReleaseError::NetworkError(ERR_MALFORMED_HTTP_RESP.to_string()))?;
        let hex_part: &str = size_line.split(';').next().unwrap_or("").trim();
        let chunk_len: usize = usize::from_str_radix(hex_part, 16)
            .map_err(|_| DynamicReleaseError::NetworkError(ERR_MALFORMED_HTTP_RESP.to_string()))?;
        cursor += rel_end + 2;
        if chunk_len == 0 {
            break;
        }
        let end: usize = cursor.saturating_add(chunk_len);
        if end + 2 > raw.len() {
            return Err(DynamicReleaseError::NetworkError(
                ERR_MALFORMED_HTTP_RESP.to_string(),
            ));
        }
        out.extend_from_slice(&raw[cursor..end]);
        cursor = end + 2;
    }
    Ok(out)
}

/// Executes a single synchronous HTTP/1.1 GET request against `authority` (directly or via an explicit HTTP forward proxy) and returns `(status_code, body)`.
///
/// # Arguments
///
/// - `&str` - Target `host:port` authority.
/// - `&str` - Request path and query string.
/// - `&[(&str, &str)]` - Additional HTTP headers to include.
/// - `u64` - Connect/read timeout in milliseconds.
/// - `Option<&str>` - Optional explicit HTTP forward proxy URL (`http://proxy:port`).
/// - `Option<&str>` - Optional `Proxy-Authorization` credential string.
///
/// # Returns
///
/// - `Result<(u16, Vec<u8>), DynamicReleaseError>` - HTTP status code and decoded response body.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn http_get_once_with_proxy(
    authority: &str,
    path_and_query: &str,
    extra_headers: &[(&str, &str)],
    timeout_ms: u64,
    proxy_url: Option<&str>,
    proxy_auth: Option<&str>,
) -> Result<(u16, Vec<u8>), DynamicReleaseError> {
    let (dial_authority, request_target): (&str, String) =
        if let Some(raw_proxy) = proxy_url.map(str::trim).filter(|p: &&str| !p.is_empty()) {
            let (proxy_auth_host, _): (&str, &str) = parse_http_base_url(raw_proxy)?;
            (
                proxy_auth_host,
                format!("{UPDATE_HTTP_SCHEME}{authority}{path_and_query}"),
            )
        } else {
            (authority, path_and_query.to_string())
        };
    let addr: SocketAddr = resolve_http_socket_addr(dial_authority)?;
    let timeout: Duration = Duration::from_millis(timeout_ms.max(100));
    let mut stream: TcpStream = TcpStream::connect_timeout(&addr, timeout)
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
    let _: Result<(), io::Error> = stream.set_read_timeout(Some(timeout));
    let _: Result<(), io::Error> = stream.set_write_timeout(Some(timeout));
    let mut req: String =
        format!("GET {request_target} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n");
    if let Some(auth) = proxy_auth.map(str::trim).filter(|a: &&str| !a.is_empty()) {
        let encoded: String = encode_proxy_basic_auth(auth);
        if !encoded.is_empty() {
            req.push_str(HDR_PROXY_AUTHORIZATION);
            req.push_str(": ");
            req.push_str(&encoded);
            req.push_str("\r\n");
        }
    }
    for (k, v) in extra_headers.iter() {
        req.push_str(k);
        req.push_str(": ");
        req.push_str(v);
        req.push_str("\r\n");
    }
    req.push_str("\r\n");
    stream
        .write_all(req.as_bytes())
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
    let _: Result<(), io::Error> = stream.flush();
    let mut raw: Vec<u8> = Vec::with_capacity(4096);
    let _: usize = stream
        .read_to_end(&mut raw)
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
    let Some(head_end) = raw
        .windows(HTTP_HEADER_END_MARKER.len())
        .position(|w: &[u8]| w == HTTP_HEADER_END_MARKER)
    else {
        return Err(DynamicReleaseError::NetworkError(
            ERR_MALFORMED_HTTP_RESP.to_string(),
        ));
    };
    let head_str: &str = from_utf8(&raw[..head_end])
        .map_err(|_| DynamicReleaseError::NetworkError(ERR_MALFORMED_HTTP_RESP.to_string()))?;
    let mut lines: Lines<'_> = head_str.lines();
    let status_line: &str = lines.next().unwrap_or("");
    let status: u16 = status_line
        .split_whitespace()
        .nth(1)
        .and_then(|s: &str| s.parse::<u16>().ok())
        .ok_or_else(|| DynamicReleaseError::NetworkError(ERR_MALFORMED_HTTP_RESP.to_string()))?;
    let mut is_chunked: bool = false;
    let mut content_length: Option<usize> = None;
    for line in lines {
        if let Some((k, v)) = line.split_once(':') {
            let key_lower: String = k.trim().to_ascii_lowercase();
            let val_trimmed: &str = v.trim();
            if key_lower == HDR_TRANSFER_ENCODING_KEY
                && val_trimmed
                    .to_ascii_lowercase()
                    .contains(HDR_TRANSFER_ENCODING_CHUNKED)
            {
                is_chunked = true;
            } else if key_lower == HDR_CONTENT_LENGTH_KEY {
                content_length = val_trimmed.parse::<usize>().ok();
            }
        }
    }
    let body_slice: &[u8] = &raw[head_end + HTTP_HEADER_END_MARKER.len()..];
    let body: Vec<u8> = if is_chunked {
        decode_chunked_body(body_slice)?
    } else if let Some(cl) = content_length {
        body_slice[..cl.min(body_slice.len())].to_vec()
    } else {
        body_slice.to_vec()
    };
    Ok((status, body))
}

/// Parses a JSON-encoded `ReleaseManifest` payload (used by both native transports and `wasm32` browser `fetch` clients).
///
/// # Arguments
///
/// - `&str` - Raw manifest JSON string.
///
/// # Returns
///
/// - `Result<ReleaseManifest, DynamicReleaseError>` - Parsed `ReleaseManifest` or typed storage error.
pub fn parse_release_manifest_json(json: &str) -> Result<ReleaseManifest, DynamicReleaseError> {
    from_str::<ReleaseManifest>(json).map_err(|err: serde_json::Error| {
        DynamicReleaseError::StorageError(format!("{ERR_MANIFEST_SERIALIZE}: {err}"))
    })
}

/// Verifies a signed JSON manifest and pre-fetched SHA-256 blobs, warming both declarative and WASM artifacts for immediate atomic apply.
///
/// # Arguments
///
/// - `&UpdateClientConfig` - Client verification key, ABI, capabilities, delivery mode, and sandbox limits.
/// - `&str` - Signed `ReleaseManifest` JSON payload.
/// - `&BTreeMap<String, Vec<u8>>` - Raw downloaded blob bytes keyed by lowercase 64-character SHA-256 digest.
///
/// # Returns
///
/// - `Result<PreparedReleaseCandidate, DynamicReleaseError>` - Verified, warmed candidate ready for `DynamicUpdateHub::apply_prepared_release`.
pub fn prepare_verified_release_from_blobs(
    config: &UpdateClientConfig,
    manifest_json: &str,
    blobs: &BTreeMap<String, Vec<u8>>,
) -> Result<PreparedReleaseCandidate, DynamicReleaseError> {
    let manifest: ReleaseManifest = parse_release_manifest_json(manifest_json)?;
    manifest.verify_signature(config.get_verify_key())?;
    manifest.validate_for_host(
        config.get_host_abi(),
        config.get_capabilities(),
        config.get_delivery_mode(),
        config.get_max_artifact_bytes(),
    )?;
    let mut warmed_artifacts: BTreeMap<String, WarmedArtifact> = BTreeMap::new();
    let mut newly_fetched_hashes: Vec<String> = Vec::new();
    for sha in manifest.all_blob_hashes().into_iter() {
        let Some(bytes) = blobs.get(&sha) else {
            return Err(DynamicReleaseError::BlobMissing(sha));
        };
        let actual_sha: String = sha256_hex(bytes);
        if !constant_time_eq(actual_sha.as_bytes(), sha.as_bytes()) {
            return Err(DynamicReleaseError::HashMismatch {
                expected: sha,
                actual: actual_sha,
            });
        }
        newly_fetched_hashes.push(sha);
    }
    for (art_key, artifact) in manifest.get_artifacts().iter() {
        let Some(bytes) = blobs.get(artifact.get_sha256()) else {
            return Err(DynamicReleaseError::BlobMissing(
                artifact.get_sha256().clone(),
            ));
        };
        let warmed: WarmedArtifact = warm_verified_artifact(
            artifact,
            bytes.as_slice(),
            config.get_host_abi(),
            &config.get_sandbox_config(),
        )?;
        let _: Option<WarmedArtifact> = warmed_artifacts.insert(art_key.clone(), warmed);
    }
    let manifest_sha256: String = manifest.manifest_sha256()?;
    let affected_routes: Vec<String> = manifest.affected_routes_since(None);
    Ok(PreparedReleaseCandidate {
        manifest,
        manifest_sha256,
        warmed_artifacts,
        affected_routes,
        newly_fetched_hashes,
        reused_cached_hashes: Vec::new(),
        migrated_ui_states: BTreeMap::new(),
        snapshot_business_revision: 0,
        snapshot_entity_revisions: BTreeMap::new(),
        prepared_on_thread: UPDATE_WORKER_THREAD_NAME.to_string(),
    })
}

/// Validates, warms up, and compiles a verified blob into a `WarmedArtifact` off the UI thread.
///
/// # Arguments
///
/// - `&BlobArtifact` - Artifact metadata from the verified signed manifest.
/// - `&[u8]` - Raw blob bytes verified against `artifact.sha256`.
/// - `u32` - Running host ABI version.
/// - `&WasmSandboxConfig` - Wasm sandbox ceilings.
///
/// # Returns
///
/// - `Result<WarmedArtifact, DynamicReleaseError>` - Warmed executable or declarative artifact.
pub(crate) fn warm_verified_artifact(
    artifact: &BlobArtifact,
    bytes: &[u8],
    host_abi: u32,
    sandbox_config: &WasmSandboxConfig,
) -> Result<WarmedArtifact, DynamicReleaseError> {
    let actual_sha: String = sha256_hex(bytes);
    if !constant_time_eq(actual_sha.as_bytes(), artifact.get_sha256().as_bytes()) {
        return Err(DynamicReleaseError::HashMismatch {
            expected: artifact.get_sha256().clone(),
            actual: actual_sha,
        });
    }
    match artifact.get_kind() {
        ArtifactKind::WasmComponent => {
            let parsed: WasmParsedModule =
                parse_wasm_binary(bytes, sandbox_config).map_err(|err: WasmDynamicError| {
                    DynamicReleaseError::BrokenDependencyClosure(format!(
                        "{ERR_WASM_ARTIFACT_ABI}: {err}"
                    ))
                })?;
            let abi_out: WasmExecutionOutput =
                execute_wasm_export(&parsed, WASM_EXPORT_ABI, &[], sandbox_config).map_err(
                    |err: WasmDynamicError| {
                        DynamicReleaseError::BrokenDependencyClosure(format!(
                            "{ERR_WASM_ARTIFACT_ABI}: {err}"
                        ))
                    },
                )?;
            let mod_abi: u32 = abi_out.get_return_value().max(0) as u32;
            if mod_abi != host_abi {
                return Err(DynamicReleaseError::AbiIncompatible {
                    host_abi,
                    min_abi: mod_abi,
                    max_abi: mod_abi,
                });
            }
            let entry: &str = if artifact.get_entrypoint().is_empty() {
                WASM_EXPORT_RENDER
            } else {
                artifact.get_entrypoint().as_str()
            };
            if !parsed.get_exports().contains_key(entry) {
                return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
                    "{ERR_WASM_ARTIFACT_ABI}: missing export `{entry}`"
                )));
            }
            Ok(WarmedArtifact::Wasm(Arc::new(parsed)))
        }
        ArtifactKind::DeclarativeSpec => {
            let text: &str = from_utf8(bytes)
                .map_err(|_| DynamicReleaseError::StorageError(ERR_DECLARATIVE_JSON.to_string()))?;
            let spec: DynamicNodeSpec = match from_str::<DynamicNodeSpec>(text) {
                Ok(parsed) => parsed,
                Err(err) => {
                    return Err(DynamicReleaseError::StorageError(format!(
                        "{ERR_DECLARATIVE_JSON}: {err}"
                    )));
                }
            };
            Ok(WarmedArtifact::Declarative(spec))
        }
        ArtifactKind::AssetBundle => Ok(WarmedArtifact::Asset(Arc::new(bytes.to_vec()))),
    }
}

/// Prepares a signed manifest off the UI thread: verifies signature/ABI/closure, fetches missing SHA-256 blobs incrementally, warms modules, and runs pure state migration.
///
/// # Arguments
///
/// - `&UpdateWorkerShared` - Shared worker configuration, verified cache, and migrator.
/// - `&dyn ReleaseTransport` - Release manifest and blob transport.
/// - `ReleaseManifest` - Signed target release manifest.
/// - `Option<NestedStateSnapshot>` - Optional captured route UI state snapshot at revision `R`.
///
/// # Returns
///
/// - `Result<PreparedReleaseCandidate, DynamicReleaseError>` - Ready candidate or typed error.
pub(crate) fn prepare_release_with_shared(
    shared: &UpdateWorkerShared,
    transport: &dyn ReleaseTransport,
    manifest: ReleaseManifest,
    snapshot: Option<NestedStateSnapshot>,
) -> Result<PreparedReleaseCandidate, DynamicReleaseError> {
    let cfg: &UpdateClientConfig = &shared.config;
    manifest.verify_signature(cfg.get_verify_key())?;
    manifest.validate_for_host(
        cfg.get_host_abi(),
        cfg.get_capabilities(),
        cfg.get_delivery_mode(),
        cfg.get_max_artifact_bytes(),
    )?;
    let prev_manifest: Option<ReleaseManifest> = shared
        .last_prepared_manifest
        .lock()
        .ok()
        .and_then(|g: MutexGuard<'_, Option<ReleaseManifest>>| g.clone());
    if let Some(prev) = prev_manifest.as_ref()
        && manifest.get_release_seq() <= prev.get_release_seq()
    {
        return Err(DynamicReleaseError::NonMonotonicRelease {
            current: prev.get_release_seq(),
            incoming: manifest.get_release_seq(),
        });
    }
    let cached_keys: HashSet<String> = shared
        .blob_cache
        .lock()
        .map(|g: MutexGuard<'_, HashMap<String, Arc<Vec<u8>>>>| g.keys().cloned().collect())
        .unwrap_or_default();
    let missing_hashes: Vec<String> = manifest.missing_blob_hashes(&cached_keys);
    let mut newly_fetched_hashes: Vec<String> = Vec::with_capacity(missing_hashes.len());
    for sha in missing_hashes.iter() {
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(cache_dir) = cfg.cache_dir_path()
            && let Some(disk_bytes) = load_verified_blob(cache_dir, sha)
        {
            if let Ok(mut cache) = shared.blob_cache.lock() {
                let _: Option<Arc<Vec<u8>>> = cache.insert(sha.clone(), Arc::new(disk_bytes));
            }
            continue;
        }
        let downloaded: Vec<u8> = transport.fetch_blob(sha, 0)?;
        let actual_sha: String = sha256_hex(&downloaded);
        if !constant_time_eq(actual_sha.as_bytes(), sha.as_bytes()) {
            return Err(DynamicReleaseError::HashMismatch {
                expected: sha.clone(),
                actual: actual_sha,
            });
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(cache_dir) = cfg.cache_dir_path() {
            persist_verified_blob(cache_dir, sha, &downloaded);
        }
        if let Ok(mut cache) = shared.blob_cache.lock() {
            let _: Option<Arc<Vec<u8>>> = cache.insert(sha.clone(), Arc::new(downloaded));
        }
        if let Ok(mut log) = shared.fetched_hashes_log.lock() {
            log.push(sha.clone());
        }
        newly_fetched_hashes.push(sha.clone());
    }
    let all_hashes: BTreeSet<String> = manifest.all_blob_hashes();
    let reused_cached_hashes: Vec<String> = all_hashes
        .iter()
        .filter(|sha: &&String| !newly_fetched_hashes.contains(*sha))
        .cloned()
        .collect();
    let mut warmed_artifacts: BTreeMap<String, WarmedArtifact> = BTreeMap::new();
    for (art_key, artifact) in manifest.get_artifacts().iter() {
        let blob: Arc<Vec<u8>> = shared
            .blob_cache
            .lock()
            .ok()
            .and_then(|g: MutexGuard<'_, HashMap<String, Arc<Vec<u8>>>>| {
                g.get(artifact.get_sha256()).cloned()
            })
            .ok_or_else(|| DynamicReleaseError::BlobMissing(artifact.get_sha256().clone()))?;
        let warmed: WarmedArtifact = warm_verified_artifact(
            artifact,
            blob.as_slice(),
            cfg.get_host_abi(),
            &cfg.get_sandbox_config(),
        )?;
        let _: Option<WarmedArtifact> = warmed_artifacts.insert(art_key.clone(), warmed);
    }
    let affected_routes: Vec<String> = manifest.affected_routes_since(prev_manifest.as_ref());
    let mut migrated_ui_states: BTreeMap<String, ComponentUiStateSnapshot> = BTreeMap::new();
    let mut snap_rev: u64 = 0;
    let mut snap_entity_revs: BTreeMap<String, u64> = BTreeMap::new();
    if let Some(snap) = snapshot {
        snap_rev = snap.get_business_revision();
        for (eid, (erev, _)) in snap.get_entity_snapshots().iter() {
            let _: Option<u64> = snap_entity_revs.insert(eid.clone(), *erev);
        }
        let target_route_opt: Option<&RouteManifest> = manifest.get_routes().get(snap.get_route());
        for (addr_key, ui_snap) in snap.get_ui_states().iter() {
            let slot_name: &str = ui_snap.get_address().get_slot_key().as_str();
            let target_schema: u32 = target_route_opt
                .and_then(|rm: &RouteManifest| rm.get_slot_bindings().get(slot_name))
                .and_then(|ak: &String| manifest.get_artifacts().get(ak))
                .map(BlobArtifact::get_state_schema_version)
                .unwrap_or_else(|| ui_snap.get_schema_version());
            let migrated: ComponentUiStateSnapshot =
                shared
                    .migrator
                    .migrate(ui_snap.get_schema_version(), target_schema, ui_snap)?;
            let _: Option<ComponentUiStateSnapshot> =
                migrated_ui_states.insert(addr_key.clone(), migrated);
        }
    }
    let manifest_sha256: String = manifest.manifest_sha256()?;
    let thread_name: String = {
        #[cfg(not(target_arch = "wasm32"))]
        {
            current()
                .name()
                .unwrap_or(UPDATE_WORKER_THREAD_NAME)
                .to_string()
        }
        #[cfg(target_arch = "wasm32")]
        {
            UPDATE_WORKER_THREAD_NAME.to_string()
        }
    };
    if let Ok(mut guard) = shared.last_prepared_manifest.lock() {
        *guard = Some(manifest.clone());
    }
    Ok(PreparedReleaseCandidate {
        manifest,
        manifest_sha256,
        warmed_artifacts,
        affected_routes,
        newly_fetched_hashes,
        reused_cached_hashes,
        migrated_ui_states,
        snapshot_business_revision: snap_rev,
        snapshot_entity_revisions: snap_entity_revs,
        prepared_on_thread: thread_name,
    })
}

/// Updates `shared.sse_live` and signals `ui_attention_flag` ONLY when live connectivity actually transitions.
///
/// # Arguments
///
/// - `&UpdateWorkerShared` - Shared background worker state.
/// - `bool` - Whether the SSE stream currently holds a live HTTP 200 connection.
#[cfg(not(target_arch = "wasm32"))]
fn set_worker_sse_live(shared: &UpdateWorkerShared, live: bool) {
    if shared.sse_live.swap(live, Ordering::AcqRel) != live {
        shared.ui_attention_flag.store(true, Ordering::Release);
        notify_frame_needed();
    }
}

/// Runs the dedicated background `UpdateWorker` SSE + manifest reconciliation loop until stopped.
///
/// # Arguments
///
/// - `Arc<UpdateWorkerShared>` - Shared worker coordination state.
#[cfg(not(target_arch = "wasm32"))]
fn run_update_worker_loop(shared: Arc<UpdateWorkerShared>) {
    let mut transport: HttpReleaseTransport = HttpReleaseTransport::new(
        shared.config.get_base_url().clone(),
        shared.config.get_http_timeout_ms(),
    );
    if let Some(proxy) = shared.config.proxy_url_str() {
        let _: &mut HttpReleaseTransport = transport.set_proxy_url(Some(proxy.to_string()));
    }
    if let Some(auth) = shared.config.proxy_auth_str() {
        let _: &mut HttpReleaseTransport = transport.set_proxy_auth(Some(auth.to_string()));
    }
    let backoff: Duration = Duration::from_millis(shared.config.get_reconnect_backoff_ms().max(25));
    while shared.running.load(Ordering::Acquire) {
        if shared.reconcile_requested.swap(false, Ordering::AcqRel) {
            reconcile_manifest_once(&shared, &transport);
        }
        let _: Result<(), DynamicReleaseError> = stream_sse_session(&shared, &transport);
        set_worker_sse_live(&shared, false);
        if !shared.running.load(Ordering::Acquire) {
            break;
        }
        shared.reconcile_requested.store(true, Ordering::Release);
        sleep(backoff);
    }
}

/// Updates `shared.last_error` and signals `ui_attention_flag` ONLY when the error state actually changed.
///
/// # Arguments
///
/// - `&UpdateWorkerShared` - Shared background worker state.
/// - `Option<DynamicReleaseError>` - New error value or `None` when healthy.
#[cfg(not(target_arch = "wasm32"))]
fn record_worker_error(shared: &UpdateWorkerShared, next_err: Option<DynamicReleaseError>) {
    if let Ok(mut err_slot) = shared.last_error.lock()
        && *err_slot != next_err
    {
        *err_slot = next_err;
        shared.ui_attention_flag.store(true, Ordering::Release);
        notify_frame_needed();
    }
}

/// Reconciles the current channel manifest on startup, reconnect, or after an SSE gap.
///
/// # Arguments
///
/// - `&UpdateWorkerShared` - Shared worker state.
/// - `&HttpReleaseTransport` - Active HTTP transport.
#[cfg(not(target_arch = "wasm32"))]
fn reconcile_manifest_once(shared: &UpdateWorkerShared, transport: &HttpReleaseTransport) {
    let negotiation: ClientNegotiation = shared.config.negotiation();
    match transport.fetch_manifest(
        shared.config.get_project(),
        shared.config.get_channel(),
        &negotiation,
    ) {
        Ok(manifest) => {
            let seq: u64 = manifest.get_release_seq();
            let snapshot: Option<NestedStateSnapshot> = shared
                .pending_snapshot
                .lock()
                .ok()
                .and_then(|mut g: MutexGuard<'_, Option<NestedStateSnapshot>>| g.take());
            match prepare_release_with_shared(shared, transport, manifest, snapshot) {
                Ok(candidate) => {
                    if let Ok(mut cur) = shared.last_event_id.lock() {
                        *cur = Some(seq.to_string());
                    }
                    if let Ok(mut err_slot) = shared.last_error.lock() {
                        *err_slot = None;
                    }
                    shared.mailbox.push_candidate(candidate);
                    shared.ui_attention_flag.store(true, Ordering::Release);
                    notify_frame_needed();
                }
                Err(DynamicReleaseError::NonMonotonicRelease { .. }) => {
                    record_worker_error(shared, None);
                }
                Err(err) => {
                    record_worker_error(shared, Some(err));
                }
            }
        }
        Err(DynamicReleaseError::RouteNotFound(_)) => {
            record_worker_error(shared, None);
        }
        Err(err) => {
            record_worker_error(shared, Some(err));
        }
    }
}

/// Opens a persistent HTTP/1.1 SSE connection with `Last-Event-ID` and triggers background preparation on `release.activated`.
///
/// # Arguments
///
/// - `&UpdateWorkerShared` - Shared worker state.
/// - `&HttpReleaseTransport` - Active HTTP transport for manifest/blob fetches.
///
/// # Returns
///
/// - `Result<(), DynamicReleaseError>` - Returns when disconnected or stopped.
#[cfg(not(target_arch = "wasm32"))]
fn stream_sse_session(
    shared: &UpdateWorkerShared,
    transport: &HttpReleaseTransport,
) -> Result<(), DynamicReleaseError> {
    let (authority, prefix): (&str, &str) = parse_http_base_url(shared.config.get_base_url())?;
    let proxy_opt: Option<&str> = shared
        .config
        .proxy_url_str()
        .map(str::trim)
        .filter(|p: &&str| !p.is_empty());
    let dial_authority: &str = if let Some(raw_proxy) = proxy_opt {
        let (proxy_host, _): (&str, &str) = parse_http_base_url(raw_proxy)?;
        proxy_host
    } else {
        authority
    };
    let addr: SocketAddr = resolve_http_socket_addr(dial_authority)?;
    let timeout: Duration = Duration::from_millis(shared.config.get_http_timeout_ms().max(100));
    let mut stream: TcpStream = TcpStream::connect_timeout(&addr, timeout)
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
    let _: Result<(), io::Error> = stream.set_read_timeout(Some(Duration::from_millis(200)));
    let _: Result<(), io::Error> = stream.set_write_timeout(Some(timeout));
    let mode_tok: &str = delivery_mode_query_token(shared.config.get_delivery_mode());
    let base_prefix: String = if prefix.is_empty() {
        String::new()
    } else {
        format!("/{prefix}")
    };
    let path: String = format!(
        "{base_prefix}/v1/projects/{}/channels/{}/events?protocol={DYNAMIC_PROTOCOL_VERSION_V1}&abi={}&mode={mode_tok}",
        shared.config.get_project(),
        shared.config.get_channel(),
        shared.config.get_host_abi()
    );
    let request_target: String = if proxy_opt.is_some() {
        format!("{UPDATE_HTTP_SCHEME}{authority}{path}")
    } else {
        path
    };
    let last_id: Option<String> = shared
        .last_event_id
        .lock()
        .ok()
        .and_then(|g: MutexGuard<'_, Option<String>>| g.clone());
    let mut req: String = format!(
        "GET {request_target} HTTP/1.1\r\nHost: {authority}\r\nAccept: text/event-stream\r\nCache-Control: no-cache\r\n"
    );
    if proxy_opt.is_some() {
        req.push_str(&format!("{HDR_PROXY_CONNECTION}: keep-alive\r\n"));
        if let Some(auth) = shared
            .config
            .proxy_auth_str()
            .map(str::trim)
            .filter(|a: &&str| !a.is_empty())
        {
            let encoded: String = encode_proxy_basic_auth(auth);
            if !encoded.is_empty() {
                req.push_str(&format!("{HDR_PROXY_AUTHORIZATION}: {encoded}\r\n"));
            }
        }
    }
    if let Some(cursor) = last_id.as_deref() {
        req.push_str(&format!("{HDR_LAST_EVENT_ID}: {cursor}\r\n"));
    }
    req.push_str("\r\n");
    stream
        .write_all(req.as_bytes())
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
    let _: Result<(), io::Error> = stream.flush();
    let mut reader: BufReader<TcpStream> = BufReader::new(stream);
    let mut status_line: String = String::new();
    let n_status: usize = reader
        .read_line(&mut status_line)
        .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
    if n_status == 0 || !status_line.contains("200") {
        return Err(DynamicReleaseError::NetworkError(format!(
            "{ERR_HTTP_NON_OK}: {status_line}"
        )));
    }
    let mut is_chunked: bool = false;
    loop {
        let mut hdr_line: String = String::new();
        let n_hdr: usize = reader
            .read_line(&mut hdr_line)
            .map_err(|err: io::Error| DynamicReleaseError::NetworkError(err.to_string()))?;
        if n_hdr == 0 || hdr_line == "\r\n" || hdr_line == "\n" {
            break;
        }
        if let Some((k, v)) = hdr_line.split_once(':')
            && k.trim().eq_ignore_ascii_case(HDR_TRANSFER_ENCODING_KEY)
            && v.trim()
                .to_ascii_lowercase()
                .contains(HDR_TRANSFER_ENCODING_CHUNKED)
        {
            is_chunked = true;
        }
    }
    let _: u64 = shared.sse_connect_count.fetch_add(1, Ordering::AcqRel);
    set_worker_sse_live(shared, true);
    reconcile_manifest_once(shared, transport);
    let mut cur_id: Option<String> = None;
    let mut cur_event: Option<String> = None;
    let mut cur_data: String = String::new();
    let mut chunk_remaining: usize = 0;
    let mut expect_chunk_crlf: bool = false;
    let mut pending_sse_bytes: Vec<u8> = Vec::with_capacity(256);
    while shared.running.load(Ordering::Acquire) {
        if shared.reconcile_requested.swap(false, Ordering::AcqRel) {
            reconcile_manifest_once(shared, transport);
        }
        match read_next_sse_line(
            &mut reader,
            is_chunked,
            &mut chunk_remaining,
            &mut expect_chunk_crlf,
            &mut pending_sse_bytes,
        ) {
            Ok(None) => break,
            Ok(Some(line)) => {
                let trimmed: &str = line.trim_end_matches(['\r', '\n']);
                if trimmed.is_empty() {
                    if !cur_data.is_empty() {
                        let ev_name: &str = cur_event.as_deref().unwrap_or("");
                        if ev_name == SSE_EVENT_RELEASE_ACTIVATED
                            && let Ok(evt) = from_str::<ReleaseActivatedEvent>(&cur_data)
                        {
                            let cursor_str: String = cur_id
                                .clone()
                                .unwrap_or_else(|| evt.get_to_release().to_string());
                            if let Ok(mut cur) = shared.last_event_id.lock() {
                                *cur = Some(cursor_str);
                            }
                            reconcile_manifest_once(shared, transport);
                        }
                    }
                    cur_id = None;
                    cur_event = None;
                    cur_data.clear();
                } else if trimmed.starts_with(':') {
                    continue;
                } else if let Some(val) = trimmed.strip_prefix(SSE_WIRE_ID_PREFIX) {
                    cur_id = Some(val.trim().to_string());
                } else if let Some(val) = trimmed.strip_prefix(SSE_WIRE_EVENT_PREFIX) {
                    cur_event = Some(val.trim().to_string());
                } else if let Some(val) = trimmed.strip_prefix(SSE_WIRE_DATA_PREFIX) {
                    if !cur_data.is_empty() {
                        cur_data.push('\n');
                    }
                    cur_data.push_str(val.trim_start());
                }
            }
            Err(err)
                if err.kind() == io::ErrorKind::WouldBlock
                    || err.kind() == io::ErrorKind::TimedOut =>
            {
                continue;
            }
            Err(err) => {
                return Err(DynamicReleaseError::NetworkError(err.to_string()));
            }
        }
    }
    Ok(())
}

/// Reads the next `\n`-terminated SSE line from `reader`, transparently decoding HTTP/1.1 chunked framing when active.
///
/// # Arguments
///
/// - `&mut BufReader<TcpStream>` - Active SSE socket reader.
/// - `bool` - Whether `Transfer-Encoding: chunked` was negotiated in the HTTP response head.
/// - `&mut usize` - Remaining unread byte count inside the active chunk.
/// - `&mut bool` - Whether the trailing `\r\n` terminator of a finished chunk must be consumed next.
/// - `&mut Vec<u8>` - Incremental decoded byte buffer preserving partial lines across read timeouts.
///
/// # Returns
///
/// - `io::Result<Option<String>>` - Next decoded line (`Some`), clean EOF (`None`), or I/O error (`WouldBlock`/`TimedOut`).
#[cfg(not(target_arch = "wasm32"))]
fn read_next_sse_line(
    reader: &mut BufReader<TcpStream>,
    is_chunked: bool,
    chunk_remaining: &mut usize,
    expect_chunk_crlf: &mut bool,
    pending_bytes: &mut Vec<u8>,
) -> io::Result<Option<String>> {
    loop {
        if let Some(nl_pos) = pending_bytes.iter().position(|b: &u8| *b == b'\n') {
            let line_bytes: Vec<u8> = pending_bytes.drain(..=nl_pos).collect();
            let text: String = String::from_utf8_lossy(&line_bytes).into_owned();
            return Ok(Some(text));
        }
        if !is_chunked {
            let mut raw_line: String = String::new();
            let n: usize = reader.read_line(&mut raw_line)?;
            if n == 0 {
                if pending_bytes.is_empty() {
                    return Ok(None);
                }
                let tail: Vec<u8> = take(pending_bytes);
                return Ok(Some(String::from_utf8_lossy(&tail).into_owned()));
            }
            pending_bytes.extend_from_slice(raw_line.as_bytes());
            continue;
        }
        if *expect_chunk_crlf {
            let mut crlf: String = String::new();
            let n: usize = reader.read_line(&mut crlf)?;
            if n == 0 {
                return Ok(None);
            }
            *expect_chunk_crlf = false;
        }
        if *chunk_remaining == 0 {
            let mut size_line: String = String::new();
            let n: usize = reader.read_line(&mut size_line)?;
            if n == 0 {
                return Ok(None);
            }
            let hex_part: &str = size_line
                .trim_end_matches(['\r', '\n'])
                .split(';')
                .next()
                .unwrap_or("")
                .trim();
            let chunk_len: usize = usize::from_str_radix(hex_part, 16)
                .map_err(|_| io::Error::new(ErrorKind::InvalidData, ERR_MALFORMED_HTTP_RESP))?;
            if chunk_len == 0 {
                return Ok(None);
            }
            *chunk_remaining = chunk_len;
        }
        let mut scratch: [u8; 2048] = [0; 2048];
        let to_read: usize = (*chunk_remaining).min(scratch.len());
        let n: usize = reader.read(&mut scratch[..to_read])?;
        if n == 0 {
            return Ok(None);
        }
        pending_bytes.extend_from_slice(&scratch[..n]);
        *chunk_remaining = chunk_remaining.saturating_sub(n);
        if *chunk_remaining == 0 {
            *expect_chunk_crlf = true;
        }
    }
}