euv-cli 0.47.1

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
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
use super::*;

/// Validates that a store path component (`project`, `channel`, `track`, `stage_id`) contains no traversal or slashes.
///
/// # Arguments
///
/// - `&str` - Candidate identifier segment.
///
/// # Returns
///
/// - `io::Result<()>` - `Ok(())` when safe, or `InvalidInput`.
pub fn validate_store_identifier(ident: &str) -> io::Result<()> {
    let all_allowed: bool = ident.bytes().all(|b: u8| {
        b.is_ascii_alphanumeric() || b == ASCII_HYPHEN || b == ASCII_UNDERSCORE || b == ASCII_DOT
    });
    if ident.is_empty()
        || ident == "."
        || ident == ".."
        || ident.contains("..")
        || ident.contains('/')
        || ident.contains('\\')
        || !all_allowed
    {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_INVALID_STORE_IDENT}: `{ident}`"),
        ));
    }
    Ok(())
}

/// Formats the Hyperlane SSE topic name isolating events per `(project, channel)`.
///
/// # Arguments
///
/// - `&str` - Logical project identifier.
/// - `&str` - Release channel name.
///
/// # Returns
///
/// - `String` - Canonical SSE topic key.
#[must_use]
pub fn sse_topic_for_channel(project: &str, channel: &str) -> String {
    format!("{project}:{channel}")
}

/// Parses an HTTP `Range: bytes=start-[end]` header against a blob of `total_len` bytes.
///
/// # Arguments
///
/// - `Option<&str>` - Raw `Range` header value, if present.
/// - `usize` - Total immutable blob length in bytes.
///
/// # Returns
///
/// - `ByteRangeSpec` - Full, inclusive byte slice, or invalid range indicator.
#[must_use]
pub fn parse_http_byte_range(header: Option<&str>, total_len: usize) -> ByteRangeSpec {
    let Some(raw) = header else {
        return ByteRangeSpec::Full;
    };
    let trimmed: &str = raw.trim();
    let Some(spec) = trimmed.strip_prefix(RANGE_BYTES_PREFIX) else {
        return ByteRangeSpec::Invalid;
    };
    if spec.contains(',') || total_len == 0 {
        return ByteRangeSpec::Invalid;
    }
    let Some((start_str, end_str)) = spec.split_once('-') else {
        return ByteRangeSpec::Invalid;
    };
    let start_trimmed: &str = start_str.trim();
    let end_trimmed: &str = end_str.trim();
    if start_trimmed.is_empty() {
        let Ok(suffix_len) = end_trimmed.parse::<usize>() else {
            return ByteRangeSpec::Invalid;
        };
        if suffix_len == 0 {
            return ByteRangeSpec::Invalid;
        }
        let start: usize = total_len.saturating_sub(suffix_len);
        return ByteRangeSpec::Slice {
            start,
            end: total_len - 1,
        };
    }
    let Ok(start) = start_trimmed.parse::<usize>() else {
        return ByteRangeSpec::Invalid;
    };
    if start >= total_len {
        return ByteRangeSpec::Invalid;
    }
    let end: usize = if end_trimmed.is_empty() {
        total_len - 1
    } else {
        let Ok(parsed_end) = end_trimmed.parse::<usize>() else {
            return ByteRangeSpec::Invalid;
        };
        parsed_end.min(total_len - 1)
    };
    if end < start {
        return ByteRangeSpec::Invalid;
    }
    ByteRangeSpec::Slice { start, end }
}

/// Atomically writes `bytes` to `target` using a sibling temp file, `sync_all()`, atomic rename, and parent directory sync.
///
/// # Arguments
///
/// - `&Path` - Destination file path.
/// - `&[u8]` - Complete file bytes to persist crash-safely.
///
/// # Returns
///
/// - `io::Result<()>` - Crash-safe persistence outcome.
pub(crate) fn atomic_write_synced(target: &Path, bytes: &[u8]) -> io::Result<()> {
    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent)?;
    }
    let seq: u64 = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
    let pid: u32 = process::id();
    let file_name: String = target
        .file_name()
        .map(|n: &OsStr| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "tmp".to_string());
    let tmp_path: PathBuf = target.with_file_name(format!(".{file_name}.tmp.{pid}.{seq}"));
    {
        let mut file: File = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp_path)?;
        file.write_all(bytes)?;
        file.sync_all()?;
    }
    fs::rename(&tmp_path, target)?;
    #[cfg(unix)]
    if let Some(parent) = target.parent()
        && let Ok(dir) = File::open(parent)
    {
        let _: io::Result<()> = dir.sync_all();
    }
    Ok(())
}

/// Returns the current UNIX epoch timestamp in seconds.
///
/// # Returns
///
/// - `u64` - Whole seconds elapsed since `UNIX_EPOCH`.
#[must_use]
pub(crate) fn current_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d: Duration| d.as_secs())
        .unwrap_or(0)
}

/// Parses a delivery mode query token into `DeliveryChannelMode`.
///
/// # Arguments
///
/// - `Option<&str>` - Optional query string value.
///
/// # Returns
///
/// - `DeliveryChannelMode` - Resolved channel delivery mode (defaults to `WasmComponent`).
#[cfg(feature = "update-server")]
#[must_use]
pub(crate) fn parse_delivery_mode_token(raw: Option<&str>) -> DeliveryChannelMode {
    match raw.map(str::trim) {
        Some(tok) if tok.eq_ignore_ascii_case(MODE_TOKEN_DATA) => {
            DeliveryChannelMode::DeclarativeData
        }
        _ => DeliveryChannelMode::WasmComponent,
    }
}

/// Registers the three read-only dynamic update routes onto an embeddable Hyperlane `Server`.
///
/// # Arguments
///
/// - `&mut Server` - Hyperlane server instance receiving the routes.
/// - `Arc<UpdateServerState>` - Shared update store and SSE pub/sub hub state.
#[cfg(feature = "update-server")]
pub fn register_update_routes(server: &mut Server, state: Arc<UpdateServerState>) {
    let slot: &RwLock<Option<Arc<UpdateServerState>>> =
        DEFAULT_UPDATE_SERVER_STATE.get_or_init(|| RwLock::new(None));
    if let Ok(mut guard) = slot.write() {
        *guard = Some(state);
    }
    let _: &mut Server = server
        .route::<ManifestRouteHook>(UPDATE_ROUTE_MANIFEST)
        .route::<BlobRouteHook>(UPDATE_ROUTE_BLOB)
        .route::<EventsRouteHook>(UPDATE_ROUTE_EVENTS);
}

/// Starts a live read-only Hyperlane HTTP + SSE update server with a background pointer watcher.
///
/// # Arguments
///
/// - `UpdateServerConfig` - Store root, bind address, SSE heartbeat/replay, and poll settings.
///
/// # Returns
///
/// - `io::Result<UpdateServerHandle>` - Running server handle or startup I/O error.
#[cfg(feature = "update-server")]
pub fn start_update_server(config: UpdateServerConfig) -> io::Result<UpdateServerHandle> {
    let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
    store.set_max_artifact_bytes(config.get_max_artifact_bytes());
    store.init_layout()?;
    let resolved_addr: SocketAddr = resolve_bind_addr(config.get_host(), config.get_port())?;
    let sse_config: SseConfig = SseConfig::default()
        .with_heartbeat_ms(config.get_heartbeat_ms())
        .with_retry_ms(config.get_retry_ms())
        .with_replay_capacity(config.get_replay_capacity());
    let state: Arc<UpdateServerState> = Arc::new(UpdateServerState::new(store, sse_config));
    state.sync_store_events_to_sse();
    register_server_state_for_addr(resolved_addr, Arc::clone(&state));
    let rt: runtime::Runtime = runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()?;
    let mut server_cfg: ServerConfig = ServerConfig::default();
    server_cfg.set_address(resolved_addr.to_string());
    let mut server: Server = Server::from(server_cfg);
    register_update_routes(&mut server, Arc::clone(&state));
    let control: ServerControlHook = rt
        .block_on(async move { server.run().await })
        .map_err(|err: Box<ServerError>| Error::other(err.to_string()))?;
    let watcher_state: Arc<UpdateServerState> = Arc::clone(&state);
    let poll_ms: u64 = config.get_watch_poll_ms().max(20);
    let _: task::JoinHandle<()> = rt.spawn(async move {
        run_pointer_watcher_task(watcher_state, poll_ms).await;
    });
    Ok(UpdateServerHandle {
        address: resolved_addr,
        state,
        control: Some(control),
        runtime: Some(rt),
    })
}

/// Runs the Hyperlane HTTP + SSE update server in blocking CLI mode (or exits immediately when `--once` is set).
///
/// # Arguments
///
/// - `UpdateServerConfig` - Server configuration.
///
/// # Returns
///
/// - `io::Result<UpdateServerReport>` - Machine-readable server startup report.
#[cfg(feature = "update-server")]
pub fn run_update_server_blocking(config: UpdateServerConfig) -> io::Result<UpdateServerReport> {
    let once: bool = config.get_once();
    let mut handle: UpdateServerHandle = start_update_server(config)?;
    let report: UpdateServerReport = handle.report(once);
    if once {
        handle.shutdown();
        return Ok(report);
    }
    eprintln!(
        "[euv-update] serving store={} url={} manifest={} blobs={} events={}",
        report.get_store_root(),
        report.get_url(),
        report.get_manifest_route(),
        report.get_blob_route(),
        report.get_events_route()
    );
    while handle.is_running() {
        thread::sleep(Duration::from_millis(250));
    }
    handle.shutdown();
    Ok(report)
}

/// Returns a clear feature error when `euv update serve` is invoked without the `update-server` feature enabled.
///
/// # Arguments
///
/// - `UpdateServerConfig` - Unused server configuration.
///
/// # Returns
///
/// - `io::Result<UpdateServerReport>` - Always returns `ErrorKind::Unsupported`.
#[cfg(not(feature = "update-server"))]
pub fn run_update_server_blocking(_config: UpdateServerConfig) -> io::Result<UpdateServerReport> {
    Err(Error::new(
        ErrorKind::Unsupported,
        ERR_UPDATE_SERVER_FEATURE_DISABLED,
    ))
}

/// Resolves a concrete `SocketAddr`, allocating an ephemeral port when `port == 0`.
///
/// # Arguments
///
/// - `&str` - Host address string.
/// - `u16` - Requested port (`0` allocates an ephemeral port).
///
/// # Returns
///
/// - `io::Result<SocketAddr>` - Resolved concrete socket address.
#[cfg(feature = "update-server")]
fn resolve_bind_addr(host: &str, port: u16) -> io::Result<SocketAddr> {
    if port != 0 {
        let raw: String = format!("{host}:{port}");
        return raw
            .parse::<SocketAddr>()
            .map_err(|err: AddrParseError| Error::new(ErrorKind::InvalidInput, err.to_string()));
    }
    let probe: TcpListener = TcpListener::bind(format!("{host}:0"))?;
    let addr: SocketAddr = probe.local_addr()?;
    drop(probe);
    Ok(addr)
}

/// Registers `state` for `addr` in the per-listener server registry.
///
/// # Arguments
///
/// - `SocketAddr` - Bound listener address.
/// - `Arc<UpdateServerState>` - Shared server state.
#[cfg(feature = "update-server")]
pub(crate) fn register_server_state_for_addr(addr: SocketAddr, state: Arc<UpdateServerState>) {
    let map: &RwLock<HashMap<SocketAddr, Arc<UpdateServerState>>> =
        UPDATE_SERVER_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()));
    if let Ok(mut guard) = map.write() {
        let _: Option<Arc<UpdateServerState>> = guard.insert(addr, state);
    }
}

/// Removes `addr` from the per-listener server registry upon server shutdown.
///
/// # Arguments
///
/// - `SocketAddr` - Listener address being closed.
#[cfg(feature = "update-server")]
pub(crate) fn unregister_server_state_for_addr(addr: SocketAddr) {
    if let Some(map) = UPDATE_SERVER_REGISTRY.get()
        && let Ok(mut guard) = map.write()
    {
        let _: Option<Arc<UpdateServerState>> = guard.remove(&addr);
    }
}

/// Resolves the `UpdateServerState` associated with the incoming Hyperlane `Stream`.
///
/// # Arguments
///
/// - `&Stream` - Active Hyperlane client stream.
///
/// # Returns
///
/// - `Option<Arc<UpdateServerState>>` - Matching server state if registered.
#[cfg(feature = "update-server")]
pub(crate) fn resolve_server_state(stream: &Stream) -> Option<Arc<UpdateServerState>> {
    if let Ok(local_addr) = stream.get_local_addr()
        && let Some(map) = UPDATE_SERVER_REGISTRY.get()
        && let Ok(guard) = map.read()
        && let Some(found) = guard.get(&local_addr)
    {
        return Some(Arc::clone(found));
    }
    DEFAULT_UPDATE_SERVER_STATE
        .get()
        .and_then(|lock: &RwLock<Option<Arc<UpdateServerState>>>| lock.read().ok())
        .and_then(|guard: RwLockReadGuard<'_, Option<Arc<UpdateServerState>>>| guard.clone())
}

/// Background task polling the filesystem store pointers and event log so separate CLI `publish`/`rollback` processes trigger SSE automatically.
///
/// # Arguments
///
/// - `Arc<UpdateServerState>` - Shared server state.
/// - `u64` - Polling cadence in milliseconds.
#[cfg(feature = "update-server")]
async fn run_pointer_watcher_task(state: Arc<UpdateServerState>, poll_ms: u64) {
    let mut ticker: Interval = interval(Duration::from_millis(poll_ms));
    while state.is_running() {
        let _: Instant = ticker.tick().await;
        if !state.is_running() {
            break;
        }
        state.sync_store_events_to_sse();
    }
}

/// Streams disk-backed `Last-Event-ID` replay frames followed by live `SseSubscription` fan-out and heartbeats.
///
/// # Arguments
///
/// - `&mut Stream` - Active Hyperlane client stream.
/// - `&mut Context` - Active Hyperlane request context.
/// - `Vec<StoredReleaseEvent>` - Persisted events strictly newer than the client's `Last-Event-ID`.
/// - `SseSubscription` - Live Hyperlane SSE subscription attached before replay read.
/// - `&SseConfig` - Heartbeat and reconnect configuration.
///
/// # Returns
///
/// - `Result<(), SseError>` - Completes cleanly when the stream closes or disconnects.
#[cfg(feature = "update-server")]
pub(crate) async fn serve_release_sse_stream(
    stream: &mut Stream,
    ctx: &mut Context,
    replay_events: Vec<StoredReleaseEvent>,
    mut subscription: SseSubscription,
    config: &SseConfig,
) -> Result<(), SseError> {
    SseStream::prepare(ctx);
    let head: ResponseData = ctx.get_mut_response().build_head();
    stream
        .try_send(&head)
        .await
        .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
    let mut scratch: Vec<u8> = Vec::with_capacity(256);
    if config.get_retry_ms() > 0 {
        let hint: SseEvent =
            SseEvent::comment_only(UPDATE_SSE_CONNECTED_COMMENT).with_retry(config.get_retry_ms());
        SseStream::send_event_buffered(stream, &hint, &mut scratch).await?;
    }
    let mut last_sent_seq: u64 = 0;
    for rec in replay_events.into_iter() {
        if let Ok(json) = to_string(rec.get_event()) {
            let ev: SseEvent = SseEvent::new(json)
                .with_id(rec.get_event_id().to_string())
                .with_event(SSE_EVENT_RELEASE_ACTIVATED);
            SseStream::send_event_buffered(stream, &ev, &mut scratch).await?;
            if rec.get_event_id() > last_sent_seq {
                last_sent_seq = rec.get_event_id();
            }
        }
    }
    let heartbeat_ms: u64 = config.get_heartbeat_ms();
    if heartbeat_ms == 0 {
        loop {
            match subscription.recv().await {
                Ok(event) => {
                    let ev_seq: u64 = event
                        .get_id()
                        .as_deref()
                        .and_then(|s: &str| s.parse::<u64>().ok())
                        .unwrap_or(u64::MAX);
                    if ev_seq <= last_sent_seq {
                        continue;
                    }
                    SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
                    if ev_seq != u64::MAX {
                        last_sent_seq = ev_seq;
                    }
                }
                Err(SseError::Lagged(_)) => continue,
                Err(SseError::ChannelClosed) => return Ok(()),
                Err(err) => return Err(err),
            }
        }
    }
    let heartbeat_frame: Vec<u8> = SseEvent::comment_only(UPDATE_SSE_HEARTBEAT_COMMENT).encode();
    let mut ticker: Interval = interval(Duration::from_millis(heartbeat_ms));
    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    let _: Instant = ticker.tick().await;
    loop {
        select! {
            _ = ticker.tick() => {
                stream
                    .try_send(&heartbeat_frame)
                    .await
                    .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
            }
            next = subscription.recv() => {
                match next {
                    Ok(event) => {
                        let ev_seq: u64 = event
                            .get_id()
                            .as_deref()
                            .and_then(|s: &str| s.parse::<u64>().ok())
                            .unwrap_or(u64::MAX);
                        if ev_seq <= last_sent_seq {
                            continue;
                        }
                        SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
                        if ev_seq != u64::MAX {
                            last_sent_seq = ev_seq;
                        }
                    }
                    Err(SseError::Lagged(_)) => continue,
                    Err(SseError::ChannelClosed) => return Ok(()),
                    Err(err) => return Err(err),
                }
            }
        }
    }
}

/// Sends a finalized HTTP response over a Hyperlane `Stream` using HEAD-aware `ctx.build_response()`.
///
/// # Arguments
///
/// - `&mut Stream` - Active client stream.
/// - `&mut Context` - Active Hyperlane context.
/// - `usize` - HTTP status code.
/// - `&str` - Response `Content-Type` header.
/// - `Vec<u8>` - Response body bytes.
///
/// # Returns
///
/// - `Status` - `Status::Continue` or `Status::Reject` upon transport error.
#[cfg(feature = "update-server")]
pub(crate) async fn send_hyperlane_bytes(
    stream: &mut Stream,
    ctx: &mut Context,
    status_code: usize,
    content_type: &str,
    body: Vec<u8>,
) -> Status {
    ctx.get_mut_response()
        .set_status_code(status_code)
        .set_header(CONTENT_TYPE, content_type)
        .set_body(body);
    let data: ResponseData = ctx.build_response();
    if stream.try_send(&data).await.is_err() {
        stream.set_closed(true);
        return Status::Reject;
    }
    Status::Continue
}