Skip to main content

euv_cli/update_server/
fn.rs

1use super::*;
2
3/// Validates that a store path component (`project`, `channel`, `track`, `stage_id`) contains no traversal or slashes.
4///
5/// # Arguments
6///
7/// - `&str` - Candidate identifier segment.
8///
9/// # Returns
10///
11/// - `io::Result<()>` - `Ok(())` when safe, or `InvalidInput`.
12pub fn validate_store_identifier(ident: &str) -> io::Result<()> {
13    let all_allowed: bool = ident.bytes().all(|byte: u8| {
14        byte.is_ascii_alphanumeric()
15            || byte == ASCII_HYPHEN
16            || byte == ASCII_UNDERSCORE
17            || byte == ASCII_DOT
18    });
19    if ident.is_empty()
20        || ident == "."
21        || ident == ".."
22        || ident.contains("..")
23        || ident.contains('/')
24        || ident.contains('\\')
25        || !all_allowed
26    {
27        return Err(Error::new(
28            ErrorKind::InvalidInput,
29            format!("{ERR_INVALID_STORE_IDENT}: `{ident}`"),
30        ));
31    }
32    Ok(())
33}
34
35/// Resolves the external proxy-aware base URL from `--proxy-base` or incoming reverse-proxy headers (`X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Prefix`).
36///
37/// # Arguments
38///
39/// - `&str` - Explicitly configured `--proxy-base` value (may be empty).
40/// - `Option<&str>` - Optional `X-Forwarded-Proto` header value.
41/// - `Option<&str>` - Optional `X-Forwarded-Host` header value.
42/// - `Option<&str>` - Optional `X-Forwarded-Prefix` header value.
43///
44/// # Returns
45///
46/// - `Option<String>` - Normalized proxy base URL or prefix without trailing slash, if any.
47#[must_use]
48pub fn resolve_proxy_base_url(
49    configured_proxy_base: &str,
50    fwd_proto: Option<&str>,
51    fwd_host: Option<&str>,
52    fwd_prefix: Option<&str>,
53) -> Option<String> {
54    let explicit: &str = configured_proxy_base.trim().trim_end_matches('/');
55    if !explicit.is_empty() {
56        return Some(explicit.to_string());
57    }
58    let clean_prefix: String = fwd_prefix
59        .map(|prefix_raw: &str| {
60            let trimmed: &str = prefix_raw.trim().trim_end_matches('/');
61            if trimmed.is_empty() {
62                String::new()
63            } else if trimmed.starts_with('/') {
64                trimmed.to_string()
65            } else {
66                format!("/{trimmed}")
67            }
68        })
69        .unwrap_or_default();
70    if let Some(host_raw) = fwd_host {
71        let host: &str = host_raw
72            .split(',')
73            .next()
74            .unwrap_or("")
75            .trim()
76            .trim_end_matches('/');
77        if !host.is_empty() {
78            let proto: &str = fwd_proto
79                .and_then(|proto_raw: &str| proto_raw.split(',').next())
80                .map(str::trim)
81                .filter(|proto_val: &&str| !proto_val.is_empty())
82                .unwrap_or("http");
83            return Some(format!("{proto}://{host}{clean_prefix}"));
84        }
85    }
86    if !clean_prefix.is_empty() {
87        return Some(clean_prefix);
88    }
89    None
90}
91
92/// Applies permissive CORS response headers for browser and cross-origin proxy clients.
93///
94/// # Arguments
95///
96/// - `&mut Context` - Active Hyperlane request context.
97#[cfg(feature = "update-server")]
98pub(crate) fn apply_update_cors_headers(ctx: &mut Context) {
99    let _: &mut Response = ctx
100        .get_mut_response()
101        .set_header(UPDATE_HDR_CORS_ORIGIN, UPDATE_VAL_CORS_ANY)
102        .set_header(UPDATE_HDR_CORS_METHODS, UPDATE_VAL_CORS_METHODS)
103        .set_header(UPDATE_HDR_CORS_HEADERS, UPDATE_VAL_CORS_HEADERS)
104        .set_header(UPDATE_HDR_CORS_EXPOSE, UPDATE_VAL_CORS_EXPOSE);
105}
106
107/// Formats the Hyperlane SSE topic name isolating events per `(project, channel)`.
108///
109/// # Arguments
110///
111/// - `&str` - Logical project identifier.
112/// - `&str` - Release channel name.
113///
114/// # Returns
115///
116/// - `String` - Canonical SSE topic key.
117#[must_use]
118pub fn sse_topic_for_channel(project: &str, channel: &str) -> String {
119    format!("{project}:{channel}")
120}
121
122/// Parses an HTTP `Range: bytes=start-[end]` header against a blob of `total_len` bytes.
123///
124/// # Arguments
125///
126/// - `Option<&str>` - Raw `Range` header value, if present.
127/// - `usize` - Total immutable blob length in bytes.
128///
129/// # Returns
130///
131/// - `ByteRangeSpec` - Full, inclusive byte slice, or invalid range indicator.
132#[must_use]
133pub fn parse_http_byte_range(header: Option<&str>, total_len: usize) -> ByteRangeSpec {
134    let Some(raw) = header else {
135        return ByteRangeSpec::Full;
136    };
137    let trimmed: &str = raw.trim();
138    let Some(spec) = trimmed.strip_prefix(RANGE_BYTES_PREFIX) else {
139        return ByteRangeSpec::Invalid;
140    };
141    if spec.contains(',') || total_len == 0 {
142        return ByteRangeSpec::Invalid;
143    }
144    let Some((start_str, end_str)) = spec.split_once('-') else {
145        return ByteRangeSpec::Invalid;
146    };
147    let start_trimmed: &str = start_str.trim();
148    let end_trimmed: &str = end_str.trim();
149    if start_trimmed.is_empty() {
150        let Ok(suffix_len) = end_trimmed.parse::<usize>() else {
151            return ByteRangeSpec::Invalid;
152        };
153        if suffix_len == 0 {
154            return ByteRangeSpec::Invalid;
155        }
156        let start: usize = total_len.saturating_sub(suffix_len);
157        return ByteRangeSpec::Slice {
158            start,
159            end: total_len - 1,
160        };
161    }
162    let Ok(start) = start_trimmed.parse::<usize>() else {
163        return ByteRangeSpec::Invalid;
164    };
165    if start >= total_len {
166        return ByteRangeSpec::Invalid;
167    }
168    let end: usize = if end_trimmed.is_empty() {
169        total_len - 1
170    } else {
171        let Ok(parsed_end) = end_trimmed.parse::<usize>() else {
172            return ByteRangeSpec::Invalid;
173        };
174        parsed_end.min(total_len - 1)
175    };
176    if end < start {
177        return ByteRangeSpec::Invalid;
178    }
179    ByteRangeSpec::Slice { start, end }
180}
181
182/// Atomically writes `bytes` to `target` using a sibling temp file, `sync_all()`, atomic rename, and parent directory sync.
183///
184/// # Arguments
185///
186/// - `&Path` - Destination file path.
187/// - `&[u8]` - Complete file bytes to persist crash-safely.
188///
189/// # Returns
190///
191/// - `io::Result<()>` - Crash-safe persistence outcome.
192pub(crate) fn atomic_write_synced(target: &Path, bytes: &[u8]) -> io::Result<()> {
193    if let Some(parent) = target.parent() {
194        fs::create_dir_all(parent)?;
195    }
196    let seq: u64 = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
197    let pid: u32 = process::id();
198    let file_name: String = target
199        .file_name()
200        .map(|file_name_os: &OsStr| file_name_os.to_string_lossy().into_owned())
201        .unwrap_or_else(|| "tmp".to_string());
202    let tmp_path: PathBuf = target.with_file_name(format!(".{file_name}.tmp.{pid}.{seq}"));
203    {
204        let mut file: File = OpenOptions::new()
205            .write(true)
206            .create_new(true)
207            .open(&tmp_path)?;
208        file.write_all(bytes)?;
209        file.sync_all()?;
210    }
211    fs::rename(&tmp_path, target)?;
212    #[cfg(unix)]
213    if let Some(parent) = target.parent()
214        && let Ok(dir) = File::open(parent)
215    {
216        let _: io::Result<()> = dir.sync_all();
217    }
218    Ok(())
219}
220
221/// Returns the current UNIX epoch timestamp in seconds.
222///
223/// # Returns
224///
225/// - `u64` - Whole seconds elapsed since `UNIX_EPOCH`.
226#[must_use]
227pub(crate) fn current_unix_secs() -> u64 {
228    SystemTime::now()
229        .duration_since(UNIX_EPOCH)
230        .map(|elapsed: Duration| elapsed.as_secs())
231        .unwrap_or(0)
232}
233
234/// Parses a delivery mode query token into `DeliveryChannelMode`.
235///
236/// # Arguments
237///
238/// - `Option<&str>` - Optional query string value.
239///
240/// # Returns
241///
242/// - `DeliveryChannelMode` - Resolved channel delivery mode (defaults to `WasmComponent`).
243#[cfg(feature = "update-server")]
244#[must_use]
245pub(crate) fn parse_delivery_mode_token(raw: Option<&str>) -> DeliveryChannelMode {
246    match raw.map(str::trim) {
247        Some(tok) if tok.eq_ignore_ascii_case(MODE_TOKEN_DATA) => {
248            DeliveryChannelMode::DeclarativeData
249        }
250        _ => DeliveryChannelMode::WasmComponent,
251    }
252}
253
254/// Registers the read-only dynamic update and health routes onto an embeddable Hyperlane `Server`.
255///
256/// # Arguments
257///
258/// - `&mut Server` - Hyperlane server instance receiving the routes.
259/// - `Arc<UpdateServerState>` - Shared update store and SSE pub/sub hub state.
260#[cfg(feature = "update-server")]
261pub fn register_update_routes(server: &mut Server, state: Arc<UpdateServerState>) {
262    let slot: &RwLock<Option<Arc<UpdateServerState>>> =
263        DEFAULT_UPDATE_SERVER_STATE.get_or_init(|| RwLock::new(None));
264    if let Ok(mut guard) = slot.write() {
265        *guard = Some(state);
266    }
267    let _: &mut Server = server
268        .route::<ManifestRouteHook>(UPDATE_ROUTE_MANIFEST)
269        .route::<BlobRouteHook>(UPDATE_ROUTE_BLOB)
270        .route::<EventsRouteHook>(UPDATE_ROUTE_EVENTS)
271        .route::<HealthRouteHook>(UPDATE_ROUTE_HEALTHZ);
272}
273
274/// Starts a live read-only Hyperlane HTTP + SSE update server with a background pointer watcher.
275///
276/// # Arguments
277///
278/// - `UpdateServerConfig` - Store root, bind address, SSE heartbeat/replay, and poll settings.
279///
280/// # Returns
281///
282/// - `io::Result<UpdateServerHandle>` - Running server handle or startup I/O error.
283#[cfg(feature = "update-server")]
284pub fn start_update_server(config: UpdateServerConfig) -> io::Result<UpdateServerHandle> {
285    let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
286    store.set_max_artifact_bytes(config.get_max_artifact_bytes());
287    store.init_layout()?;
288    let sse_config: SseConfig = SseConfig::default()
289        .with_heartbeat_ms(config.get_heartbeat_ms())
290        .with_retry_ms(config.get_retry_ms())
291        .with_replay_capacity(config.get_replay_capacity());
292    let state: Arc<UpdateServerState> = Arc::new(
293        UpdateServerState::new(store, sse_config).with_proxy_base(config.get_proxy_base().clone()),
294    );
295    state.sync_store_events_to_sse();
296    let runtime_ref: runtime::Runtime = runtime::Builder::new_multi_thread()
297        .worker_threads(2)
298        .enable_all()
299        .build()?;
300    let max_attempts: usize = if config.get_port() == 0 { 8 } else { 1 };
301    let mut last_err: Option<Error> = None;
302    let mut bound_pair: Option<(SocketAddr, ServerControlHook)> = None;
303    for _ in 0..max_attempts {
304        let candidate_addr: SocketAddr = resolve_bind_addr(config.get_host(), config.get_port())?;
305        register_server_state_for_addr(candidate_addr, Arc::clone(&state));
306        let mut server_cfg: ServerConfig = ServerConfig::default();
307        server_cfg.set_address(candidate_addr.to_string());
308        let mut server: Server = Server::from(server_cfg);
309        register_update_routes(&mut server, Arc::clone(&state));
310        match runtime_ref.block_on(async move { server.run().await }) {
311            Ok(control) => {
312                bound_pair = Some((candidate_addr, control));
313                break;
314            }
315            Err(err) => {
316                unregister_server_state_for_addr(candidate_addr);
317                last_err = Some(Error::other(err.to_string()));
318            }
319        }
320    }
321    let (resolved_addr, control): (SocketAddr, ServerControlHook) = match bound_pair {
322        Some(pair) => pair,
323        None => {
324            return Err(last_err.unwrap_or_else(|| Error::from(ErrorKind::AddrInUse)));
325        }
326    };
327    let watcher_state: Arc<UpdateServerState> = Arc::clone(&state);
328    let poll_ms: u64 = config.get_watch_poll_ms().max(20);
329    let _: task::JoinHandle<()> = runtime_ref.spawn(async move {
330        run_pointer_watcher_task(watcher_state, poll_ms).await;
331    });
332    Ok(UpdateServerHandle {
333        address: resolved_addr,
334        state,
335        control: Some(control),
336        runtime: Some(runtime_ref),
337    })
338}
339
340/// Runs the Hyperlane HTTP + SSE update server in blocking CLI mode (or exits immediately when `--once` is set).
341///
342/// # Arguments
343///
344/// - `UpdateServerConfig` - Server configuration.
345///
346/// # Returns
347///
348/// - `io::Result<UpdateServerReport>` - Machine-readable server startup report.
349#[cfg(feature = "update-server")]
350pub fn run_update_server_blocking(config: UpdateServerConfig) -> io::Result<UpdateServerReport> {
351    let once: bool = config.get_once();
352    let mut handle: UpdateServerHandle = start_update_server(config)?;
353    let report: UpdateServerReport = handle.report(once);
354    if once {
355        handle.shutdown();
356        return Ok(report);
357    }
358    eprintln!(
359        "[euv-update] serving store={} url={} manifest={} blobs={} events={}",
360        report.get_store_root(),
361        report.get_url(),
362        report.get_manifest_route(),
363        report.get_blob_route(),
364        report.get_events_route()
365    );
366    while handle.is_running() {
367        thread::sleep(Duration::from_millis(250));
368    }
369    handle.shutdown();
370    Ok(report)
371}
372
373/// Returns a clear feature error when `euv update serve` is invoked without the `update-server` feature enabled.
374///
375/// # Arguments
376///
377/// - `UpdateServerConfig` - Unused server configuration.
378///
379/// # Returns
380///
381/// - `io::Result<UpdateServerReport>` - Always returns `ErrorKind::Unsupported`.
382#[cfg(not(feature = "update-server"))]
383pub fn run_update_server_blocking(_config: UpdateServerConfig) -> io::Result<UpdateServerReport> {
384    Err(Error::new(
385        ErrorKind::Unsupported,
386        ERR_UPDATE_SERVER_FEATURE_DISABLED,
387    ))
388}
389
390/// Resolves a concrete `SocketAddr`, allocating an ephemeral port when `port == 0`.
391///
392/// # Arguments
393///
394/// - `&str` - Host address string.
395/// - `u16` - Requested port (`0` allocates an ephemeral port).
396///
397/// # Returns
398///
399/// - `io::Result<SocketAddr>` - Resolved concrete socket address.
400#[cfg(feature = "update-server")]
401fn resolve_bind_addr(host: &str, port: u16) -> io::Result<SocketAddr> {
402    if port != 0 {
403        let raw: String = format!("{host}:{port}");
404        return raw
405            .parse::<SocketAddr>()
406            .map_err(|err: AddrParseError| Error::new(ErrorKind::InvalidInput, err.to_string()));
407    }
408    let probe: TcpListener = TcpListener::bind(format!("{host}:0"))?;
409    let addr: SocketAddr = probe.local_addr()?;
410    drop(probe);
411    Ok(addr)
412}
413
414/// Registers `state` for `addr` in the per-listener server registry.
415///
416/// # Arguments
417///
418/// - `SocketAddr` - Bound listener address.
419/// - `Arc<UpdateServerState>` - Shared server state.
420#[cfg(feature = "update-server")]
421pub(crate) fn register_server_state_for_addr(addr: SocketAddr, state: Arc<UpdateServerState>) {
422    let map: &RwLock<HashMap<SocketAddr, Arc<UpdateServerState>>> =
423        UPDATE_SERVER_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()));
424    if let Ok(mut guard) = map.write() {
425        let _: Option<Arc<UpdateServerState>> = guard.insert(addr, state);
426    }
427}
428
429/// Removes `addr` from the per-listener server registry upon server shutdown.
430///
431/// # Arguments
432///
433/// - `SocketAddr` - Listener address being closed.
434#[cfg(feature = "update-server")]
435pub(crate) fn unregister_server_state_for_addr(addr: SocketAddr) {
436    if let Some(map) = UPDATE_SERVER_REGISTRY.get()
437        && let Ok(mut guard) = map.write()
438    {
439        let _: Option<Arc<UpdateServerState>> = guard.remove(&addr);
440    }
441}
442
443/// Resolves the `UpdateServerState` associated with the incoming Hyperlane `Stream`.
444///
445/// # Arguments
446///
447/// - `&Stream` - Active Hyperlane client stream.
448///
449/// # Returns
450///
451/// - `Option<Arc<UpdateServerState>>` - Matching server state if registered.
452#[cfg(feature = "update-server")]
453pub(crate) fn resolve_server_state(stream: &Stream) -> Option<Arc<UpdateServerState>> {
454    if let Ok(local_addr) = stream.get_local_addr()
455        && let Some(map) = UPDATE_SERVER_REGISTRY.get()
456        && let Ok(guard) = map.read()
457        && let Some(found) = guard.get(&local_addr)
458    {
459        return Some(Arc::clone(found));
460    }
461    DEFAULT_UPDATE_SERVER_STATE
462        .get()
463        .and_then(|lock: &RwLock<Option<Arc<UpdateServerState>>>| lock.read().ok())
464        .and_then(|guard: RwLockReadGuard<'_, Option<Arc<UpdateServerState>>>| guard.clone())
465}
466
467/// Background task polling the filesystem store pointers and event log so separate CLI `publish`/`rollback` processes trigger SSE automatically.
468///
469/// # Arguments
470///
471/// - `Arc<UpdateServerState>` - Shared server state.
472/// - `u64` - Polling cadence in milliseconds.
473#[cfg(feature = "update-server")]
474async fn run_pointer_watcher_task(state: Arc<UpdateServerState>, poll_ms: u64) {
475    let mut ticker: Interval = interval(Duration::from_millis(poll_ms));
476    while state.is_running() {
477        let _: Instant = ticker.tick().await.into_std();
478        if !state.is_running() {
479            break;
480        }
481        state.sync_store_events_to_sse();
482    }
483}
484
485/// Streams disk-backed `Last-Event-ID` replay frames followed by live `SseSubscription` fan-out and heartbeats.
486///
487/// # Arguments
488///
489/// - `&mut Stream` - Active Hyperlane client stream.
490/// - `&mut Context` - Active Hyperlane request context.
491/// - `Vec<StoredReleaseEvent>` - Persisted events strictly newer than the client's `Last-Event-ID`.
492/// - `SseSubscription` - Live Hyperlane SSE subscription attached before replay read.
493/// - `&SseConfig` - Heartbeat and reconnect configuration.
494///
495/// # Returns
496///
497/// - `Result<(), SseError>` - Completes cleanly when the stream closes or disconnects.
498#[cfg(feature = "update-server")]
499pub(crate) async fn serve_release_sse_stream(
500    stream: &mut Stream,
501    ctx: &mut Context,
502    replay_events: Vec<StoredReleaseEvent>,
503    mut subscription: SseSubscription,
504    config: &SseConfig,
505) -> Result<(), SseError> {
506    SseStream::prepare(ctx);
507    apply_update_cors_headers(ctx);
508    let _: &mut Response = ctx
509        .get_mut_response()
510        .set_header(CACHE_CONTROL, UPDATE_SSE_CACHE_CONTROL)
511        .set_header(UPDATE_HDR_ACCEL_BUFFERING, UPDATE_VAL_NO_BUFFER);
512    let head: ResponseData = ctx.get_mut_response().build_head();
513    stream
514        .try_send(&head)
515        .await
516        .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
517    let mut scratch: Vec<u8> = Vec::with_capacity(256);
518    if config.get_retry_ms() > 0 {
519        let hint: SseEvent =
520            SseEvent::comment_only(UPDATE_SSE_CONNECTED_COMMENT).with_retry(config.get_retry_ms());
521        SseStream::send_event_buffered(stream, &hint, &mut scratch).await?;
522    }
523    let mut last_sent_seq: u64 = 0;
524    for rec in replay_events.into_iter() {
525        if let Ok(json) = to_string(rec.get_event()) {
526            let ui_event: SseEvent = SseEvent::new(json)
527                .with_id(rec.get_event_id().to_string())
528                .with_event(SSE_EVENT_RELEASE_ACTIVATED);
529            SseStream::send_event_buffered(stream, &ui_event, &mut scratch).await?;
530            if rec.get_event_id() > last_sent_seq {
531                last_sent_seq = rec.get_event_id();
532            }
533        }
534    }
535    let heartbeat_ms: u64 = config.get_heartbeat_ms();
536    if heartbeat_ms == 0 {
537        loop {
538            match subscription.recv().await {
539                Ok(event) => {
540                    let ev_seq: u64 = event
541                        .get_id()
542                        .as_deref()
543                        .and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
544                        .unwrap_or(u64::MAX);
545                    if ev_seq <= last_sent_seq {
546                        continue;
547                    }
548                    SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
549                    if ev_seq != u64::MAX {
550                        last_sent_seq = ev_seq;
551                    }
552                }
553                Err(SseError::Lagged(_)) => continue,
554                Err(SseError::ChannelClosed) => return Ok(()),
555                Err(err) => return Err(err),
556            }
557        }
558    }
559    let heartbeat_frame: Vec<u8> = SseEvent::comment_only(UPDATE_SSE_HEARTBEAT_COMMENT).encode();
560    let mut ticker: Interval = interval(Duration::from_millis(heartbeat_ms));
561    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
562    let _: Instant = ticker.tick().await.into_std();
563    loop {
564        select! {
565            _ = ticker.tick() => {
566                stream
567                    .try_send(&heartbeat_frame)
568                    .await
569                    .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
570            }
571            next = subscription.recv() => {
572                match next {
573                    Ok(event) => {
574                        let ev_seq: u64 = event
575                            .get_id()
576                            .as_deref()
577                            .and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
578                            .unwrap_or(u64::MAX);
579                        if ev_seq <= last_sent_seq {
580                            continue;
581                        }
582                        SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
583                        if ev_seq != u64::MAX {
584                            last_sent_seq = ev_seq;
585                        }
586                    }
587                    Err(SseError::Lagged(_)) => continue,
588                    Err(SseError::ChannelClosed) => return Ok(()),
589                    Err(err) => return Err(err),
590                }
591            }
592        }
593    }
594}
595
596/// Sends a finalized HTTP response over a Hyperlane `Stream` using HEAD-aware `ctx.build_response()`.
597///
598/// # Arguments
599///
600/// - `&mut Stream` - Active client stream.
601/// - `&mut Context` - Active Hyperlane context.
602/// - `usize` - HTTP status code.
603/// - `&str` - Response `Content-Type` header.
604/// - `Vec<u8>` - Response body bytes.
605///
606/// # Returns
607///
608/// - `Status` - `Status::Continue` or `Status::Reject` upon transport error.
609#[cfg(feature = "update-server")]
610pub(crate) async fn send_hyperlane_bytes(
611    stream: &mut Stream,
612    ctx: &mut Context,
613    status_code: usize,
614    content_type: &str,
615    body: Vec<u8>,
616) -> Status {
617    apply_update_cors_headers(ctx);
618    ctx.get_mut_response()
619        .set_status_code(status_code)
620        .set_header(CONTENT_TYPE, content_type)
621        .set_body(body);
622    let data: ResponseData = ctx.build_response();
623    if stream.try_send(&data).await.is_err() {
624        stream.set_closed(true);
625        return Status::Reject;
626    }
627    Status::Continue
628}
629
630/// Checks whether an HTTP `If-None-Match` header matches `current_etag` (supporting `*`, weak `W/`, and comma-separated lists).
631///
632/// # Arguments
633///
634/// - `Option<&str>` - Raw `If-None-Match` request header value, if present.
635/// - `&str` - Canonical unquoted entity tag value (e.g. manifest or blob SHA-256 hex).
636///
637/// # Returns
638///
639/// - `bool` - `true` when the client already holds a matching entity tag (`304 Not Modified`).
640#[must_use]
641pub fn etag_matches_if_none_match(header: Option<&str>, current_etag: &str) -> bool {
642    let Some(raw) = header else {
643        return false;
644    };
645    let clean_current: &str = current_etag.trim().trim_matches('"');
646    if clean_current.is_empty() {
647        return false;
648    }
649    for token in raw.split(',') {
650        let trimmed: &str = token.trim();
651        if trimmed == "*" {
652            return true;
653        }
654        let without_weak: &str = trimmed
655            .strip_prefix(OTA_ETAG_WEAK_PREFIX)
656            .or_else(|| trimmed.strip_prefix(OTA_ETAG_WEAK_PREFIX_LOWER))
657            .unwrap_or(trimmed)
658            .trim();
659        let candidate: &str = without_weak.trim_matches('"');
660        if !candidate.is_empty() && constant_time_eq(candidate.as_bytes(), clean_current.as_bytes())
661        {
662            return true;
663        }
664    }
665    false
666}
667
668/// Generates a cryptographically strong 256-bit HMAC-SHA256 signing secret encoded as 64 lowercase hex characters.
669///
670/// # Returns
671///
672/// - `io::Result<String>` - 64-character lowercase hexadecimal signing secret.
673pub fn generate_signing_key_hex() -> io::Result<String> {
674    let mut seed_buf: Vec<u8> = Vec::with_capacity(128);
675    #[cfg(unix)]
676    {
677        if let Ok(mut urandom) = File::open(OTA_DEV_URANDOM) {
678            let mut os_bytes: [u8; 32] = [0u8; 32];
679            if urandom.read_exact(&mut os_bytes).is_ok() {
680                seed_buf.extend_from_slice(&os_bytes);
681            }
682        }
683    }
684    for round in 0..4u64 {
685        let hasher_builder: RandomState = RandomState::new();
686        let mut hasher: DefaultHasher = hasher_builder.build_hasher();
687        hasher.write_u64(round);
688        hasher.write_u32(process::id());
689        let nanos: u128 = SystemTime::now()
690            .duration_since(UNIX_EPOCH)
691            .map(|elapsed: Duration| elapsed.as_nanos())
692            .unwrap_or(0);
693        hasher.write_u128(nanos);
694        let seq: u64 = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
695        hasher.write_u64(seq);
696        seed_buf.extend_from_slice(&hasher.finish().to_le_bytes());
697    }
698    let digest: [u8; 32] = sha256_bytes(&seed_buf);
699    let hex_key: String = sha256_hex(&digest);
700    Ok(hex_key)
701}
702
703/// Generates a structured `KeygenReport` for `euv update keygen`.
704///
705/// # Returns
706///
707/// - `io::Result<KeygenReport>` - Signing key and environment export snippet.
708pub fn generate_ota_keygen_report() -> io::Result<KeygenReport> {
709    let signing_key: String = generate_signing_key_hex()?;
710    let export_hint: String = format!("export {DEFAULT_OTA_SIGNING_KEY_ENV}={signing_key}");
711    Ok(KeygenReport::new(
712        signing_key,
713        DEFAULT_OTA_SIGNING_KEY_ENV.to_string(),
714        export_hint,
715        OTA_KEYGEN_BIT_LENGTH,
716    ))
717}
718
719/// Initializes an update store directory layout, generates a signing key if absent, and optionally writes `euv-ota.json`.
720///
721/// # Arguments
722///
723/// - `&OtaInitConfig` - Initialization parameters for store path, project, channel, and optional config output.
724///
725/// # Returns
726///
727/// - `io::Result<OtaInitReport>` - Summary of created directories, generated key, and optional config path.
728pub fn init_ota_store(config: &OtaInitConfig) -> io::Result<OtaInitReport> {
729    validate_store_identifier(config.get_project())?;
730    validate_store_identifier(config.get_channel())?;
731    let store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
732    store.init_layout()?;
733    let root: &Path = config.get_store_root();
734    let created_dirs: Vec<String> = vec![
735        root.join(STORE_DIR_STAGING).display().to_string(),
736        root.join(STORE_DIR_BLOBS)
737            .join(STORE_DIR_SHA256)
738            .display()
739            .to_string(),
740        root.join(STORE_DIR_RELEASES).display().to_string(),
741        root.join(STORE_DIR_CHANNELS).display().to_string(),
742        root.join(STORE_DIR_STATE)
743            .join(STORE_DIR_EVENTS)
744            .display()
745            .to_string(),
746    ];
747    let signing_key: String = match config.try_get_signing_key() {
748        Some(existing) if !existing.trim().is_empty() => existing.trim().to_string(),
749        _ => generate_signing_key_hex()?,
750    };
751    let config_file: String = if let Some(cfg_path) = config.try_get_config_path() {
752        let project_cfg: OtaProjectConfig = OtaProjectConfig::new(
753            OTA_CONFIG_SCHEMA_V1,
754            config.get_project().clone(),
755            config.get_channel().clone(),
756            root.display().to_string(),
757            config.get_server_url().clone(),
758            DEFAULT_OTA_SIGNING_KEY_ENV.to_string(),
759        );
760        let encoded: String = to_string_pretty(&project_cfg)
761            .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
762        atomic_write_synced(cfg_path, encoded.as_bytes())?;
763        cfg_path.display().to_string()
764    } else {
765        String::new()
766    };
767    Ok(OtaInitReport::new(
768        root.display().to_string(),
769        config.get_project().clone(),
770        config.get_channel().clone(),
771        config_file,
772        signing_key,
773        DEFAULT_OTA_SIGNING_KEY_ENV.to_string(),
774        created_dirs,
775    ))
776}
777
778/// Validates a dynamic `.wasm` binary against `euv-core` sandbox limits, `euv_abi_version`, and `euv_render` export contracts.
779///
780/// # Arguments
781///
782/// - `&[u8]` - Raw WebAssembly module bytes.
783///
784/// # Returns
785///
786/// - `io::Result<DynamicWasmValidation>` - Verified ABI version, exports, SHA-256 digest, and byte length.
787pub fn validate_dynamic_wasm_bytes(wasm_bytes: &[u8]) -> io::Result<DynamicWasmValidation> {
788    if !wasm_bytes.starts_with(WASM_BINARY_MAGIC) {
789        return Err(Error::new(
790            ErrorKind::InvalidData,
791            ERR_PUSH_INVALID_WASM.to_string(),
792        ));
793    }
794    if (wasm_bytes.len() as u64) > DEFAULT_MAX_ARTIFACT_BYTES {
795        return Err(Error::new(
796            ErrorKind::InvalidData,
797            format!("{ERR_PUSH_INVALID_WASM}: exceeds max artifact byte budget"),
798        ));
799    }
800    let sandbox: WasmSandboxConfig = WasmSandboxConfig::default();
801    let parsed: WasmParsedModule =
802        parse_wasm_binary(wasm_bytes, &sandbox).map_err(|err: WasmDynamicError| {
803            Error::new(
804                ErrorKind::InvalidData,
805                format!("{ERR_PUSH_INVALID_WASM}: {err}"),
806            )
807        })?;
808    let abi_out: WasmExecutionOutput = execute_wasm_export(&parsed, WASM_EXPORT_ABI, &[], &sandbox)
809        .map_err(|err: WasmDynamicError| {
810            Error::new(
811                ErrorKind::InvalidData,
812                format!("{ERR_PUSH_INVALID_WASM}: {err}"),
813            )
814        })?;
815    let mod_abi: u32 = abi_out.get_return_value().max(0) as u32;
816    if mod_abi != DYNAMIC_HOST_ABI_V1 {
817        return Err(Error::new(
818            ErrorKind::InvalidData,
819            format!("{ERR_PUSH_INVALID_WASM}: ABI v{mod_abi} != host v{DYNAMIC_HOST_ABI_V1}"),
820        ));
821    }
822    if !parsed.get_exports().contains_key(WASM_EXPORT_RENDER) {
823        return Err(Error::new(
824            ErrorKind::InvalidData,
825            format!("{ERR_PUSH_INVALID_WASM}: missing `{WASM_EXPORT_RENDER}` export"),
826        ));
827    }
828    let mut exports: Vec<String> = parsed.get_exports().keys().cloned().collect();
829    exports.sort();
830    Ok(DynamicWasmValidation::new(
831        mod_abi,
832        exports,
833        sha256_hex(wasm_bytes),
834        wasm_bytes.len() as u64,
835    ))
836}
837
838/// Compiles a Rust dynamic widget crate targeting `wasm32-unknown-unknown`, validates its host ABI and sandbox constraints, writes the `.wasm` artifact, and optionally publishes it to a local `UpdateStore`.
839///
840/// # Arguments
841///
842/// - `&OtaBuildConfig` - Widget crate directory, optional package/output paths, and optional push target.
843///
844/// # Returns
845///
846/// - `io::Result<OtaBuildReport>` - Build, validation, and optional publish summary.
847pub fn build_dynamic_wasm_widget(config: &OtaBuildConfig) -> io::Result<OtaBuildReport> {
848    let manifest_dir: &Path = config.get_manifest_dir();
849    let mut cargo_args: Vec<String> = vec![
850        ARG_BUILD.to_string(),
851        ARG_TARGET.to_string(),
852        OTA_WASM_TARGET_TRIPLE.to_string(),
853        OTA_CARGO_ARG_LIB.to_string(),
854    ];
855    if let Some(pkg) = config.try_get_package() {
856        cargo_args.push(ARG_PACKAGE.to_string());
857        cargo_args.push(pkg.clone());
858    }
859    if config.get_release() {
860        cargo_args.push(ARG_RELEASE.to_string());
861    }
862    let output: Output = Command::new(BIN_CARGO)
863        .args(&cargo_args)
864        .current_dir(manifest_dir)
865        .output()?;
866    if !output.status.success() {
867        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
868        return Err(Error::other(format!("{OTA_ERR_BUILD_FAILED}: {stderr}")));
869    }
870    let built_wasm: PathBuf = locate_built_wasm_artifact(
871        manifest_dir,
872        config.try_get_package().as_deref(),
873        config.get_release(),
874    )?;
875    let wasm_bytes: Vec<u8> = fs::read(&built_wasm)?;
876    let validated: DynamicWasmValidation = validate_dynamic_wasm_bytes(&wasm_bytes)?;
877    let out_path: PathBuf = match config.try_get_out_path() {
878        Some(explicit) => explicit.clone(),
879        None => {
880            let file_name: String = built_wasm
881                .file_name()
882                .map(|os_name: &OsStr| os_name.to_string_lossy().into_owned())
883                .unwrap_or_else(|| OTA_DEFAULT_WIDGET_FILENAME.to_string());
884            manifest_dir.join(OTA_BUILD_OUT_SUBDIR).join(file_name)
885        }
886    };
887    atomic_write_synced(&out_path, &wasm_bytes)?;
888    let pushed: Option<PublishReport> = if config.get_push() {
889        let signing_key: String = match config.try_get_signing_key() {
890            Some(key) if !key.trim().is_empty() => key.trim().to_string(),
891            _ => match env::var(DEFAULT_OTA_SIGNING_KEY_ENV) {
892                Ok(key) if !key.trim().is_empty() => key,
893                _ => {
894                    return Err(Error::new(
895                        ErrorKind::InvalidInput,
896                        OTA_ERR_PUSH_KEY_MISSING.to_string(),
897                    ));
898                }
899            },
900        };
901        let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
902        let _: &mut UpdateStore = store.set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES);
903        let pub_report: PublishReport = store.publish_artifact_direct(
904            config.get_project(),
905            config.get_channel(),
906            config.try_get_route().as_deref(),
907            config.try_get_slot().as_deref(),
908            &wasm_bytes,
909            signing_key.as_bytes(),
910        )?;
911        Some(pub_report)
912    } else {
913        None
914    };
915    let mut report: OtaBuildReport = OtaBuildReport::new(
916        out_path.display().to_string(),
917        validated.get_sha256().clone(),
918        validated.get_size_bytes(),
919        validated.get_abi_version(),
920        validated.get_exports().clone(),
921    );
922    let _: &mut OtaBuildReport = report.set_pushed(pushed);
923    Ok(report)
924}
925
926/// Locates the compiled `wasm32-unknown-unknown` `.wasm` artifact under Cargo's target directory.
927///
928/// # Arguments
929///
930/// - `&Path` - Crate or workspace root directory.
931/// - `Option<&str>` - Optional Cargo package name.
932/// - `bool` - Whether release profile directory should be searched.
933///
934/// # Returns
935///
936/// - `io::Result<PathBuf>` - Resolved `.wasm` file path or `NotFound`.
937fn locate_built_wasm_artifact(
938    manifest_dir: &Path,
939    package: Option<&str>,
940    release: bool,
941) -> io::Result<PathBuf> {
942    let target_root: PathBuf = match env::var(OTA_ENV_CARGO_TARGET_DIR) {
943        Ok(dir) if !dir.trim().is_empty() => PathBuf::from(dir),
944        _ => manifest_dir.join(OTA_DIR_TARGET),
945    };
946    let profile_dir: &str = if release {
947        OTA_DIR_RELEASE
948    } else {
949        OTA_DIR_DEBUG
950    };
951    let wasm_dir: PathBuf = target_root.join(OTA_WASM_TARGET_TRIPLE).join(profile_dir);
952    if let Some(pkg) = package {
953        let normalized: String = pkg.replace('-', "_");
954        let direct: PathBuf = wasm_dir.join(format!("{normalized}.{OTA_EXT_WASM}"));
955        if direct.is_file() {
956            return Ok(direct);
957        }
958    }
959    if wasm_dir.is_dir() {
960        let mut candidates: Vec<(SystemTime, PathBuf)> = Vec::new();
961        for entry_res in fs::read_dir(&wasm_dir)? {
962            let entry: DirEntry = entry_res?;
963            let path: PathBuf = entry.path();
964            let is_wasm_file: bool = path.is_file()
965                && path
966                    .extension()
967                    .and_then(|ext_os: &OsStr| ext_os.to_str())
968                    .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(OTA_EXT_WASM));
969            if is_wasm_file {
970                let modified: SystemTime = entry
971                    .metadata()
972                    .ok()
973                    .and_then(|meta: Metadata| meta.modified().ok())
974                    .unwrap_or(UNIX_EPOCH);
975                candidates.push((modified, path));
976            }
977        }
978        candidates.sort_by_key(|entry: &(SystemTime, PathBuf)| cmp::Reverse(entry.0));
979        if let Some((_, newest)) = candidates.into_iter().next() {
980            return Ok(newest);
981        }
982    }
983    Err(Error::new(
984        ErrorKind::NotFound,
985        format!("{OTA_ERR_WASM_NOT_FOUND} in {}", wasm_dir.display()),
986    ))
987}
988
989/// Discovers non-loopback local LAN IPv4 addresses so real mobile devices and emulators can connect to local OTA/dev servers.
990///
991/// # Returns
992///
993/// - `Vec<String>` - Deduplicated, sorted local LAN IPv4 address strings.
994#[must_use]
995pub fn detect_lan_ip_addresses() -> Vec<String> {
996    let mut detected: BTreeSet<String> = BTreeSet::new();
997    for probe in [OTA_LAN_PROBE_PRIMARY, OTA_LAN_PROBE_FALLBACK] {
998        if let Ok(socket) = UdpSocket::bind(OTA_LAN_BIND_ANY)
999            && socket.connect(probe).is_ok()
1000            && let Ok(local_addr) = socket.local_addr()
1001            && let IpAddr::V4(ipv4) = local_addr.ip()
1002            && !ipv4.is_loopback()
1003            && !ipv4.is_unspecified()
1004        {
1005            let _: bool = detected.insert(ipv4.to_string());
1006        }
1007    }
1008    detected.into_iter().collect()
1009}
1010
1011/// Runs the unified single-command `euv update dev` Hyperlane OTA server + live file/crate watcher loop.
1012///
1013/// # Arguments
1014///
1015/// - `OtaDevConfig` - Store, bind, project, channel, watch path, and smoke-run settings.
1016///
1017/// # Returns
1018///
1019/// - `io::Result<OtaDevReport>` - Startup summary with localhost and LAN URLs.
1020#[cfg(feature = "update-server")]
1021pub fn run_ota_dev_blocking(config: OtaDevConfig) -> io::Result<OtaDevReport> {
1022    validate_store_identifier(config.get_project())?;
1023    validate_store_identifier(config.get_channel())?;
1024    let signing_key: String = if config.get_signing_key().trim().is_empty() {
1025        generate_signing_key_hex()?
1026    } else {
1027        config.get_signing_key().clone()
1028    };
1029    let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
1030    let _: &mut UpdateStore = store.set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES);
1031    store.init_layout()?;
1032    let initial_release: Option<PublishReport> =
1033        if let Some(watch_path) = config.try_get_watch_path() {
1034            if watch_path.exists() {
1035                Some(push_watched_ota_source(
1036                    &store,
1037                    watch_path,
1038                    (config.get_project(), config.get_channel()),
1039                    (
1040                        config.try_get_route().as_deref(),
1041                        config.try_get_slot().as_deref(),
1042                    ),
1043                    config.try_get_package().as_deref(),
1044                    signing_key.as_bytes(),
1045                )?)
1046            } else {
1047                None
1048            }
1049        } else {
1050            None
1051        };
1052    let mut srv_cfg: UpdateServerConfig = UpdateServerConfig::default();
1053    let _: &mut UpdateServerConfig = srv_cfg
1054        .set_store_root(config.get_store_root().clone())
1055        .set_host(config.get_host().clone())
1056        .set_port(config.get_port())
1057        .set_proxy_base(config.get_proxy_base().clone())
1058        .set_heartbeat_ms(config.get_heartbeat_ms())
1059        .set_watch_poll_ms(config.get_poll_ms().clamp(25, 2000))
1060        .set_once(false);
1061    let mut handle: UpdateServerHandle = start_update_server(srv_cfg)?;
1062    let bound_port: u16 = handle.address().port();
1063    let local_url: String = if config.get_host() == OTA_HOST_ALL_INTERFACES {
1064        format!("http://{OTA_HOST_LOCALHOST}:{bound_port}")
1065    } else {
1066        handle.url()
1067    };
1068    let manifest_path: String = format!(
1069        "{OTA_PATH_V1_PROJECTS_PREFIX}{}/{OTA_PATH_SEG_CHANNELS}/{}/{OTA_PATH_SEG_MANIFEST}",
1070        config.get_project(),
1071        config.get_channel()
1072    );
1073    let events_path: String = format!(
1074        "{OTA_PATH_V1_PROJECTS_PREFIX}{}/{OTA_PATH_SEG_CHANNELS}/{}/{OTA_PATH_SEG_EVENTS}",
1075        config.get_project(),
1076        config.get_channel()
1077    );
1078    let lan_urls: Vec<String> = detect_lan_ip_addresses()
1079        .into_iter()
1080        .map(|lan_ip: String| format!("http://{lan_ip}:{bound_port}{manifest_path}"))
1081        .collect();
1082    let manifest_url: String = format!("{local_url}{manifest_path}");
1083    let events_url: String = format!("{local_url}{events_path}");
1084    let health_url: String = format!("{local_url}{UPDATE_ROUTE_HEALTHZ}");
1085    let mut report: OtaDevReport = OtaDevReport::default();
1086    let _: &mut OtaDevReport = report
1087        .set_store_root(config.get_store_root().display().to_string())
1088        .set_local_url(local_url.clone())
1089        .set_lan_urls(lan_urls.clone())
1090        .set_manifest_url(manifest_url.clone())
1091        .set_events_url(events_url.clone())
1092        .set_health_url(health_url.clone())
1093        .set_project(config.get_project().clone())
1094        .set_channel(config.get_channel().clone())
1095        .set_initial_release(initial_release)
1096        .set_once(config.get_once());
1097    if config.get_once() {
1098        handle.shutdown();
1099        return Ok(report);
1100    }
1101    eprintln!(
1102        "[euv-update-dev] local={local_url} manifest={manifest_url} events={events_url} health={health_url}"
1103    );
1104    for lan_manifest in lan_urls.iter() {
1105        eprintln!("[euv-update-dev] lan={lan_manifest}");
1106    }
1107    let poll_delay: Duration = Duration::from_millis(config.get_poll_ms().clamp(50, 5000));
1108    let mut prev_stamp: String = config
1109        .try_get_watch_path()
1110        .as_deref()
1111        .map(compute_watch_fingerprint)
1112        .unwrap_or_default();
1113    while handle.is_running() {
1114        thread::sleep(poll_delay);
1115        if let Some(watch_path) = config.try_get_watch_path()
1116            && watch_path.exists()
1117        {
1118            let next_stamp: String = compute_watch_fingerprint(watch_path);
1119            if next_stamp != prev_stamp {
1120                prev_stamp = next_stamp;
1121                match push_watched_ota_source(
1122                    &store,
1123                    watch_path,
1124                    (config.get_project(), config.get_channel()),
1125                    (
1126                        config.try_get_route().as_deref(),
1127                        config.try_get_slot().as_deref(),
1128                    ),
1129                    config.try_get_package().as_deref(),
1130                    signing_key.as_bytes(),
1131                ) {
1132                    Ok(pub_rep) => {
1133                        eprintln!(
1134                            "[euv-update-dev] pushed release seq={} sha={}",
1135                            pub_rep.get_to_release(),
1136                            pub_rep.get_manifest_sha256()
1137                        );
1138                    }
1139                    Err(err) => {
1140                        eprintln!("[euv-update-dev] skipped invalid change: {err}");
1141                    }
1142                }
1143            }
1144        }
1145    }
1146    handle.shutdown();
1147    Ok(report)
1148}
1149
1150/// Returns a clear feature error when `euv update dev` is invoked without the `update-server` Cargo feature.
1151///
1152/// # Arguments
1153///
1154/// - `OtaDevConfig` - Unused dev server configuration.
1155///
1156/// # Returns
1157///
1158/// - `io::Result<OtaDevReport>` - Always returns `ErrorKind::Unsupported`.
1159#[cfg(not(feature = "update-server"))]
1160pub fn run_ota_dev_blocking(_config: OtaDevConfig) -> io::Result<OtaDevReport> {
1161    Err(Error::new(
1162        ErrorKind::Unsupported,
1163        ERR_UPDATE_SERVER_FEATURE_DISABLED,
1164    ))
1165}
1166
1167/// Publishes a watched `.json` spec, `.wasm` binary, or Rust widget crate directory directly into `store`.
1168///
1169/// # Arguments
1170///
1171/// - `&UpdateStore` - Target local update store.
1172/// - `&Path` - Path to `.json`, `.wasm`, `Cargo.toml`, or crate root directory.
1173/// - `(&str, &str)` - Target `(project, channel)` pair.
1174/// - `(Option<&str>, Option<&str>)` - Optional `(route, slot)` overrides.
1175/// - `Option<&str>` - Optional Cargo package name when compiling a crate.
1176/// - `&[u8]` - Signing secret key bytes.
1177///
1178/// # Returns
1179///
1180/// - `io::Result<PublishReport>` - Atomic publish summary.
1181pub fn push_watched_ota_source(
1182    store: &UpdateStore,
1183    watch_path: &Path,
1184    project_channel: (&str, &str),
1185    route_slot: (Option<&str>, Option<&str>),
1186    package: Option<&str>,
1187    signing_key: &[u8],
1188) -> io::Result<PublishReport> {
1189    let (project, channel): (&str, &str) = project_channel;
1190    let (route, slot): (Option<&str>, Option<&str>) = route_slot;
1191    let is_cargo_crate: bool = watch_path.is_dir()
1192        || watch_path
1193            .file_name()
1194            .and_then(|file_os: &OsStr| file_os.to_str())
1195            .is_some_and(|name: &str| name == OTA_CARGO_MANIFEST_FILE);
1196    if is_cargo_crate {
1197        let crate_dir: PathBuf = if watch_path.is_dir() {
1198            watch_path.to_path_buf()
1199        } else {
1200            watch_path
1201                .parent()
1202                .map(Path::to_path_buf)
1203                .unwrap_or_else(|| PathBuf::from("."))
1204        };
1205        let mut build_cfg: OtaBuildConfig = OtaBuildConfig::default();
1206        let _: &mut OtaBuildConfig = build_cfg
1207            .set_manifest_dir(crate_dir)
1208            .set_package(package.map(str::to_string))
1209            .set_release(true)
1210            .set_push(false);
1211        let built: OtaBuildReport = build_dynamic_wasm_widget(&build_cfg)?;
1212        let wasm_bytes: Vec<u8> = fs::read(built.get_wasm_path())?;
1213        return store.publish_artifact_direct(
1214            project,
1215            channel,
1216            route,
1217            slot,
1218            &wasm_bytes,
1219            signing_key,
1220        );
1221    }
1222    let raw_bytes: Vec<u8> = fs::read(watch_path)?;
1223    store.publish_artifact_direct(project, channel, route, slot, &raw_bytes, signing_key)
1224}
1225
1226/// Computes a deterministic SHA-256 fingerprint for a watched file or crate directory.
1227///
1228/// # Arguments
1229///
1230/// - `&Path` - Watched file or directory path.
1231///
1232/// # Returns
1233///
1234/// - `String` - Hex digest representing current content or directory stamps.
1235#[cfg(feature = "update-server")]
1236fn compute_watch_fingerprint(watch_path: &Path) -> String {
1237    if watch_path.is_file() {
1238        return fs::read(watch_path)
1239            .map(|bytes: Vec<u8>| sha256_hex(&bytes))
1240            .unwrap_or_default();
1241    }
1242    let snapshot: WatchSnapshot =
1243        WatchSnapshot::scan(watch_path, &WATCH_EXTS_CODE).unwrap_or_default();
1244    let mut acc: String = String::new();
1245    for (entry_path, stamp) in snapshot.get_entries().iter() {
1246        acc.push_str(&format!(
1247            "{}:{}:{}\n",
1248            entry_path.display(),
1249            stamp.get_modified_nanos(),
1250            stamp.get_size_bytes()
1251        ));
1252    }
1253    sha256_hex(acc.as_bytes())
1254}
1255
1256/// Audits an update store offline for signature authenticity, pointer consistency, and SHA-256 blob integrity.
1257///
1258/// # Arguments
1259///
1260/// - `&OtaVerifyConfig` - Verification scope and optional signing secret.
1261///
1262/// # Returns
1263///
1264/// - `io::Result<OtaVerifyReport>` - Structured integrity audit report.
1265pub fn verify_ota_store(config: &OtaVerifyConfig) -> io::Result<OtaVerifyReport> {
1266    let store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
1267    store.verify_store(config)
1268}
1269
1270/// Computes a structured metadata, route, and blob-size diff between two release sequences.
1271///
1272/// # Arguments
1273///
1274/// - `&Path` - Local update store root directory.
1275/// - `&str` - Logical project identifier.
1276/// - `&str` - Release channel name.
1277/// - `u64` - Base release sequence number.
1278/// - `u64` - Target release sequence number.
1279///
1280/// # Returns
1281///
1282/// - `io::Result<OtaReleaseDiff>` - Structured release comparison report.
1283pub fn diff_ota_releases(
1284    store_root: &Path,
1285    project: &str,
1286    channel: &str,
1287    from_seq: u64,
1288    to_seq: u64,
1289) -> io::Result<OtaReleaseDiff> {
1290    let store: UpdateStore = UpdateStore::new(store_root.to_path_buf());
1291    store.diff_releases(project, channel, from_seq, to_seq)
1292}
1293
1294/// Safely garbage-collects unreferenced releases, orphan blobs, and stale staging directories.
1295///
1296/// # Arguments
1297///
1298/// - `&OtaGcConfig` - Garbage collection retention and dry-run configuration.
1299///
1300/// # Returns
1301///
1302/// - `io::Result<OtaGcReport>` - Summary of kept and reclaimed store artifacts.
1303pub fn gc_ota_store(config: &OtaGcConfig) -> io::Result<OtaGcReport> {
1304    let store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
1305    store.gc(config)
1306}
1307
1308/// Builds a JSON-serializable health and store summary response for `GET /healthz`.
1309///
1310/// # Arguments
1311///
1312/// - `&UpdateStore` - Backing update store.
1313/// - `bool` - Whether the hosting server loop is active.
1314///
1315/// # Returns
1316///
1317/// - `io::Result<UpdateHealthResponse>` - Health payload with blob and channel counts.
1318pub fn build_health_response(
1319    store: &UpdateStore,
1320    running: bool,
1321) -> io::Result<UpdateHealthResponse> {
1322    let status: UpdateStoreStatus = store.status(None, None)?;
1323    let channel_count: usize = status.get_channels().len();
1324    let mut response: UpdateHealthResponse = UpdateHealthResponse::default();
1325    let _: &mut UpdateHealthResponse = response
1326        .set_status(OTA_HEALTH_STATUS_OK.to_string())
1327        .set_store_root(status.get_store_root().clone())
1328        .set_blob_count(status.get_blob_count())
1329        .set_blob_total_bytes(status.get_blob_total_bytes())
1330        .set_channel_count(channel_count)
1331        .set_channels(status.get_channels().clone())
1332        .set_running(running)
1333        .set_timestamp_unix(current_unix_secs());
1334    Ok(response)
1335}
1336
1337/// Parses an HTTP request path matching `/v1/projects/{project}/channels/{channel}/events`.
1338///
1339/// # Arguments
1340///
1341/// - `&str` - URL path component without query string.
1342///
1343/// # Returns
1344///
1345/// - `Option<(String, String)>` - Validated `(project, channel)` pair if the path matches the v1 SSE route.
1346#[must_use]
1347pub fn parse_v1_events_path(path: &str) -> Option<(String, String)> {
1348    let rest: &str = path.strip_prefix(OTA_PATH_V1_PROJECTS_PREFIX)?;
1349    let parts: Vec<&str> = rest.split('/').collect();
1350    if parts.len() != 4 || parts[1] != OTA_PATH_SEG_CHANNELS || parts[3] != OTA_PATH_SEG_EVENTS {
1351        return None;
1352    }
1353    let project: &str = parts[0];
1354    let channel: &str = parts[2];
1355    if validate_store_identifier(project).is_err() || validate_store_identifier(channel).is_err() {
1356        return None;
1357    }
1358    Some((project.to_string(), channel.to_string()))
1359}
1360
1361/// Handles read-only v1 OTA HTTP requests (`/healthz`, `/v1/projects/{p}/channels/{c}/manifest`, `/v1/blobs/{sha256}`) directly against `store` for embedding inside `euv dev`.
1362///
1363/// # Arguments
1364///
1365/// - `&UpdateStore` - Backing atomic update store.
1366/// - `&str` - HTTP request method (`GET`, `HEAD`, `OPTIONS`, etc.).
1367/// - `&str` - Raw HTTP request target including optional query string.
1368/// - `Option<&str>` - Optional incoming `If-None-Match` header value.
1369/// - `Option<&str>` - Optional incoming `Range` header value.
1370///
1371/// # Returns
1372///
1373/// - `Option<EmbeddedOtaResponse>` - `Some(response)` if `raw_target` matches a v1 OTA route, or `None` to fall through to static dev serving.
1374#[must_use]
1375pub fn handle_embedded_v1_ota_request(
1376    store: &UpdateStore,
1377    method: &str,
1378    raw_target: &str,
1379    if_none_match: Option<&str>,
1380    range_header: Option<&str>,
1381) -> Option<EmbeddedOtaResponse> {
1382    let (path_only, query_str): (&str, &str) = match raw_target.split_once('?') {
1383        Some((path_part, query_part)) => (path_part, query_part),
1384        None => (raw_target, ""),
1385    };
1386    if path_only == UPDATE_ROUTE_HEALTHZ {
1387        if method.eq_ignore_ascii_case(OTA_METHOD_OPTIONS) {
1388            return Some(EmbeddedOtaResponse::new(
1389                204,
1390                OTA_HTTP_STATUS_NO_CONTENT,
1391                OTA_HTTP_MIME_JSON,
1392                Vec::new(),
1393                Vec::new(),
1394            ));
1395        }
1396        if !method.eq_ignore_ascii_case(OTA_METHOD_GET)
1397            && !method.eq_ignore_ascii_case(OTA_METHOD_HEAD)
1398        {
1399            return Some(EmbeddedOtaResponse::new(
1400                405,
1401                OTA_HTTP_STATUS_METHOD_NOT_ALLOWED,
1402                OTA_HTTP_MIME_JSON,
1403                Vec::new(),
1404                OTA_HTTP_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1405            ));
1406        }
1407        let body: Vec<u8> = build_health_response(store, true)
1408            .ok()
1409            .and_then(|resp: UpdateHealthResponse| to_string(&resp).ok())
1410            .map(String::into_bytes)
1411            .unwrap_or_else(|| OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec());
1412        return Some(EmbeddedOtaResponse::new(
1413            200,
1414            OTA_HTTP_STATUS_OK,
1415            OTA_HTTP_MIME_JSON,
1416            vec![(
1417                OTA_HDR_CACHE_CONTROL_TITLE.to_string(),
1418                OTA_HTTP_CACHE_NO_CACHE.to_string(),
1419            )],
1420            body,
1421        ));
1422    }
1423    if let Some(sha_raw) = path_only.strip_prefix(OTA_PATH_V1_BLOBS_PREFIX) {
1424        if method.eq_ignore_ascii_case(OTA_METHOD_OPTIONS) {
1425            return Some(EmbeddedOtaResponse::new(
1426                204,
1427                OTA_HTTP_STATUS_NO_CONTENT,
1428                OTA_HTTP_MIME_JSON,
1429                Vec::new(),
1430                Vec::new(),
1431            ));
1432        }
1433        if !method.eq_ignore_ascii_case(OTA_METHOD_GET)
1434            && !method.eq_ignore_ascii_case(OTA_METHOD_HEAD)
1435        {
1436            return Some(EmbeddedOtaResponse::new(
1437                405,
1438                OTA_HTTP_STATUS_METHOD_NOT_ALLOWED,
1439                OTA_HTTP_MIME_JSON,
1440                Vec::new(),
1441                OTA_HTTP_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1442            ));
1443        }
1444        if !is_valid_sha256_hex(sha_raw) {
1445            return Some(EmbeddedOtaResponse::new(
1446                400,
1447                OTA_HTTP_STATUS_BAD_REQUEST,
1448                OTA_HTTP_MIME_JSON,
1449                Vec::new(),
1450                OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec(),
1451            ));
1452        }
1453        let blob_bytes: Vec<u8> = match store.read_blob(sha_raw) {
1454            Ok(Some(bytes)) => bytes,
1455            Ok(None) => {
1456                return Some(EmbeddedOtaResponse::new(
1457                    404,
1458                    OTA_HTTP_STATUS_NOT_FOUND,
1459                    OTA_HTTP_MIME_JSON,
1460                    Vec::new(),
1461                    OTA_HTTP_ERR_NOT_FOUND.as_bytes().to_vec(),
1462                ));
1463            }
1464            Err(_) => {
1465                return Some(EmbeddedOtaResponse::new(
1466                    400,
1467                    OTA_HTTP_STATUS_BAD_REQUEST,
1468                    OTA_HTTP_MIME_JSON,
1469                    Vec::new(),
1470                    OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec(),
1471                ));
1472            }
1473        };
1474        let mut headers: Vec<(String, String)> = vec![
1475            (
1476                OTA_HDR_CACHE_CONTROL_TITLE.to_string(),
1477                OTA_HTTP_CACHE_IMMUTABLE.to_string(),
1478            ),
1479            (OTA_HDR_ETAG_TITLE.to_string(), format!("\"{sha_raw}\"")),
1480            (
1481                OTA_HDR_ACCEPT_RANGES_TITLE.to_string(),
1482                OTA_HTTP_RANGE_BYTES.to_string(),
1483            ),
1484        ];
1485        if etag_matches_if_none_match(if_none_match, sha_raw) {
1486            return Some(EmbeddedOtaResponse::new(
1487                304,
1488                OTA_HTTP_STATUS_NOT_MODIFIED,
1489                OTA_HTTP_MIME_OCTET,
1490                headers,
1491                Vec::new(),
1492            ));
1493        }
1494        let total_len: usize = blob_bytes.len();
1495        return match parse_http_byte_range(range_header, total_len) {
1496            ByteRangeSpec::Full => Some(EmbeddedOtaResponse::new(
1497                200,
1498                OTA_HTTP_STATUS_OK,
1499                OTA_HTTP_MIME_OCTET,
1500                headers,
1501                blob_bytes,
1502            )),
1503            ByteRangeSpec::Slice { start, end } => {
1504                headers.push((
1505                    OTA_HDR_CONTENT_RANGE_TITLE.to_string(),
1506                    format!("bytes {start}-{end}/{total_len}"),
1507                ));
1508                Some(EmbeddedOtaResponse::new(
1509                    206,
1510                    OTA_HTTP_STATUS_PARTIAL,
1511                    OTA_HTTP_MIME_OCTET,
1512                    headers,
1513                    blob_bytes[start..=end].to_vec(),
1514                ))
1515            }
1516            ByteRangeSpec::Invalid => {
1517                headers.push((
1518                    OTA_HDR_CONTENT_RANGE_TITLE.to_string(),
1519                    format!("bytes */{total_len}"),
1520                ));
1521                Some(EmbeddedOtaResponse::new(
1522                    416,
1523                    OTA_HTTP_STATUS_RANGE_INVALID,
1524                    OTA_HTTP_MIME_JSON,
1525                    headers,
1526                    OTA_HTTP_ERR_RANGE_INVALID.as_bytes().to_vec(),
1527                ))
1528            }
1529        };
1530    }
1531    if let Some(rest) = path_only.strip_prefix(OTA_PATH_V1_PROJECTS_PREFIX) {
1532        let parts: Vec<&str> = rest.split('/').collect();
1533        if parts.len() == 4
1534            && parts[1] == OTA_PATH_SEG_CHANNELS
1535            && parts[3] == OTA_PATH_SEG_MANIFEST
1536        {
1537            if method.eq_ignore_ascii_case(OTA_METHOD_OPTIONS) {
1538                return Some(EmbeddedOtaResponse::new(
1539                    204,
1540                    OTA_HTTP_STATUS_NO_CONTENT,
1541                    OTA_HTTP_MIME_JSON,
1542                    Vec::new(),
1543                    Vec::new(),
1544                ));
1545            }
1546            if !method.eq_ignore_ascii_case(OTA_METHOD_GET)
1547                && !method.eq_ignore_ascii_case(OTA_METHOD_HEAD)
1548            {
1549                return Some(EmbeddedOtaResponse::new(
1550                    405,
1551                    OTA_HTTP_STATUS_METHOD_NOT_ALLOWED,
1552                    OTA_HTTP_MIME_JSON,
1553                    Vec::new(),
1554                    OTA_HTTP_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1555                ));
1556            }
1557            let project: &str = parts[0];
1558            let channel: &str = parts[2];
1559            let query_map: BTreeMap<String, String> = parse_simple_query(query_str);
1560            let protocol: u32 = query_map
1561                .get(OTA_HTTP_QUERY_PROTOCOL)
1562                .and_then(|val: &String| val.parse::<u32>().ok())
1563                .unwrap_or(DYNAMIC_PROTOCOL_VERSION_V1);
1564            let host_abi: u32 = query_map
1565                .get(OTA_HTTP_QUERY_ABI)
1566                .and_then(|val: &String| val.parse::<u32>().ok())
1567                .unwrap_or(DYNAMIC_HOST_ABI_V1);
1568            let mode: DeliveryChannelMode = match query_map
1569                .get(OTA_HTTP_QUERY_MODE)
1570                .map(|val: &String| val.trim())
1571            {
1572                Some(tok) if tok.eq_ignore_ascii_case(OTA_HTTP_MODE_DATA) => {
1573                    DeliveryChannelMode::DeclarativeData
1574                }
1575                _ => DeliveryChannelMode::WasmComponent,
1576            };
1577            let mut neg: ClientNegotiation = ClientNegotiation::new(protocol, host_abi, mode);
1578            if let Some(track) = query_map.get(OTA_HTTP_QUERY_TRACK)
1579                && !track.is_empty()
1580            {
1581                neg = neg.with_preferred_track(track.clone());
1582            }
1583            return match store.read_compatible_manifest(project, channel, &neg) {
1584                Ok(Ok(manifest)) => {
1585                    let etag: String = manifest.manifest_sha256().unwrap_or_default();
1586                    let headers: Vec<(String, String)> = vec![
1587                        (
1588                            OTA_HDR_CACHE_CONTROL_TITLE.to_string(),
1589                            OTA_HTTP_CACHE_NO_CACHE.to_string(),
1590                        ),
1591                        (OTA_HDR_ETAG_TITLE.to_string(), format!("\"{etag}\"")),
1592                    ];
1593                    if etag_matches_if_none_match(if_none_match, &etag) {
1594                        return Some(EmbeddedOtaResponse::new(
1595                            304,
1596                            OTA_HTTP_STATUS_NOT_MODIFIED,
1597                            OTA_HTTP_MIME_JSON,
1598                            headers,
1599                            Vec::new(),
1600                        ));
1601                    }
1602                    let body: Vec<u8> = to_string(&manifest)
1603                        .map(String::into_bytes)
1604                        .unwrap_or_default();
1605                    Some(EmbeddedOtaResponse::new(
1606                        200,
1607                        OTA_HTTP_STATUS_OK,
1608                        OTA_HTTP_MIME_JSON,
1609                        headers,
1610                        body,
1611                    ))
1612                }
1613                Ok(Err(reason)) => Some(EmbeddedOtaResponse::new(
1614                    409,
1615                    OTA_HTTP_STATUS_CONFLICT,
1616                    OTA_HTTP_MIME_JSON,
1617                    Vec::new(),
1618                    format!("{{\"error\":\"incompatible\",\"detail\":\"{reason}\"}}").into_bytes(),
1619                )),
1620                Err(err) if err.kind() == ErrorKind::NotFound => Some(EmbeddedOtaResponse::new(
1621                    404,
1622                    OTA_HTTP_STATUS_NOT_FOUND,
1623                    OTA_HTTP_MIME_JSON,
1624                    Vec::new(),
1625                    OTA_HTTP_ERR_NOT_FOUND.as_bytes().to_vec(),
1626                )),
1627                Err(_) => Some(EmbeddedOtaResponse::new(
1628                    400,
1629                    OTA_HTTP_STATUS_BAD_REQUEST,
1630                    OTA_HTTP_MIME_JSON,
1631                    Vec::new(),
1632                    OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec(),
1633                )),
1634            };
1635        }
1636    }
1637    None
1638}
1639
1640/// Parses a `key=value&...` HTTP query string into an ordered map.
1641///
1642/// # Arguments
1643///
1644/// - `&str` - Raw query string without leading `?`.
1645///
1646/// # Returns
1647///
1648/// - `BTreeMap<String, String>` - Decoded query parameter key/value pairs.
1649fn parse_simple_query(query: &str) -> BTreeMap<String, String> {
1650    let mut map: BTreeMap<String, String> = BTreeMap::new();
1651    for pair in query.split('&') {
1652        if pair.is_empty() {
1653            continue;
1654        }
1655        if let Some((key, val)) = pair.split_once('=') {
1656            let _: Option<String> = map.insert(key.to_string(), val.to_string());
1657        }
1658    }
1659    map
1660}
1661
1662/// Determines whether an existing `state/writer.lock` file belongs to a dead process or has exceeded `stale_secs`.
1663///
1664/// # Arguments
1665///
1666/// - `&Path` - Lockfile path (`state/writer.lock`).
1667/// - `u64` - Maximum lock age in seconds before reclaiming as expired.
1668///
1669/// # Returns
1670///
1671/// - `bool` - `true` when the lock is stale and safe to remove.
1672pub(crate) fn is_writer_lock_stale(lock_path: &Path, stale_secs: u64) -> bool {
1673    let Ok(raw) = fs::read_to_string(lock_path) else {
1674        return false;
1675    };
1676    let mut parsed_pid: Option<u32> = None;
1677    let mut parsed_created: Option<u64> = None;
1678    for line in raw.lines() {
1679        let trimmed: &str = line.trim();
1680        if let Some(pid_text) = trimmed.strip_prefix(OTA_LOCK_PID_PREFIX) {
1681            parsed_pid = pid_text.trim().parse::<u32>().ok();
1682        } else if let Some(ts_text) = trimmed.strip_prefix(OTA_LOCK_CREATED_PREFIX) {
1683            parsed_created = ts_text.trim().parse::<u64>().ok();
1684        }
1685    }
1686    if let Some(owner_pid) = parsed_pid
1687        && !is_process_alive(owner_pid)
1688    {
1689        return true;
1690    }
1691    let now_secs: u64 = current_unix_secs();
1692    if let Some(created_secs) = parsed_created
1693        && now_secs.saturating_sub(created_secs) >= stale_secs
1694    {
1695        return true;
1696    }
1697    if let Ok(meta) = fs::metadata(lock_path)
1698        && let Ok(modified) = meta.modified()
1699        && let Ok(age) = SystemTime::now().duration_since(modified)
1700        && age.as_secs() >= stale_secs
1701    {
1702        return true;
1703    }
1704    false
1705}
1706
1707/// Probes whether OS process `pid` is still running without delivering any terminating signal.
1708///
1709/// # Arguments
1710///
1711/// - `u32` - Numeric process identifier recorded in `writer.lock`.
1712///
1713/// # Returns
1714///
1715/// - `bool` - `false` only when the process is definitely dead or invalid (`pid == 0`).
1716fn is_process_alive(pid: u32) -> bool {
1717    if pid == 0 {
1718        return false;
1719    }
1720    if pid == process::id() {
1721        return true;
1722    }
1723    #[cfg(unix)]
1724    {
1725        let proc_root: &Path = Path::new(OTA_PROC_DIR);
1726        if proc_root.is_dir() {
1727            return proc_root.join(pid.to_string()).exists();
1728        }
1729        if let Ok(out) = Command::new(OTA_KILL_BIN)
1730            .args([OTA_KILL_SIGNAL_ZERO, &pid.to_string()])
1731            .stdin(Stdio::null())
1732            .output()
1733        {
1734            if out.status.success() {
1735                return true;
1736            }
1737            let stderr_lower: String = String::from_utf8_lossy(&out.stderr).to_ascii_lowercase();
1738            if stderr_lower.contains(OTA_ERR_NO_SUCH_PROCESS) {
1739                return false;
1740            }
1741        }
1742        true
1743    }
1744    #[cfg(not(unix))]
1745    {
1746        true
1747    }
1748}
1749
1750/// Computes the total regular-file byte size recursively under `dir`.
1751///
1752/// # Arguments
1753///
1754/// - `&Path` - Root directory or file path.
1755///
1756/// # Returns
1757///
1758/// - `u64` - Total disk bytes occupied by files beneath `dir`.
1759pub(crate) fn dir_total_bytes(path: &Path) -> u64 {
1760    if path.is_file() {
1761        return fs::metadata(path)
1762            .map(|meta: Metadata| meta.len())
1763            .unwrap_or(0);
1764    }
1765    if !path.is_dir() {
1766        return 0;
1767    }
1768    let mut total: u64 = 0;
1769    if let Ok(entries) = fs::read_dir(path) {
1770        for entry in entries.flatten() {
1771            total = total.saturating_add(dir_total_bytes(&entry.path()));
1772        }
1773    }
1774    total
1775}