wslcsdk 0.3.0

Idiomatic, safe, and asynchronous Rust SDK for Microsoft WSL Containers (WSLC)
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
//! WSLC 镜像枚举、远程拉取、推送与归档载入

use crate::callback::invoke_callback;
use crate::com_memory::ComArray;
use crate::error::WslcError;
use crate::session::{WslcSessionHandle, path_to_wide_null};
use core::ffi::c_void;
use serde::{Deserialize, Serialize};
use std::ffi::{CStr, CString};
use std::fmt::Write as _;
use std::os::windows::raw::HANDLE;
use std::path::Path;
use windows_sys::core::HRESULT;
use wslcsdk_sys::types::{
    WslcImageInfo, WslcImageProgressMessage, WslcImportImageOptions, WslcLoadImageOptions,
    WslcPullImageOptions, WslcPushImageOptions, WslcTagImageOptions,
};
use wslcsdk_sys::*;

/// 容器镜像元数据
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ImageInfo {
    /// 镜像的完整引用名(如 `docker.io/library/alpine:latest`)
    pub name: String,
    /// 内容寻址摘要,可用于精确比对两镜像是否一致
    pub sha256: String,
    /// 展开后的镜像大小,单位字节
    pub size_bytes: i64,
    /// 创建时间,Unix纪元秒
    pub created_unix_time: u64,
}

/// 镜像拉取与推送进度结构 (借用切片)
#[derive(Debug, Clone)]
pub struct ImageProgress<'a> {
    /// 本次进度的阶段标识(如某一 layer 的摘要)
    pub id: &'a str,
    /// 当前所处的传输阶段
    pub status: WslcImageProgressStatus,
    /// 已传输字节数
    pub current_bytes: u64,
    /// 总字节数;未知大小时为 0
    pub total_bytes: u64,
}

impl ImageProgress<'_> {
    /// 转换为拥有独立所有权的进度对象,便于跨线程或异步通道传递
    pub fn to_owned(&self) -> OwnedImageProgress {
        OwnedImageProgress {
            id: self.id.to_string(),
            status: self.status,
            current_bytes: self.current_bytes,
            total_bytes: self.total_bytes,
        }
    }
}

/// 拥有独立所有权的镜像进度结构体
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedImageProgress {
    /// 本次进度的阶段标识(如某一 layer 的摘要)
    pub id: String,
    /// 当前所处的传输阶段
    pub status: WslcImageProgressStatus,
    /// 已传输字节数
    pub current_bytes: u64,
    /// 总字节数;未知大小时为 0
    pub total_bytes: u64,
}

/// 将二进制摘要编码为小写十六进制字符串
///
/// 输出长度恒为输入的两倍,字符集限定为 `0-9a-f`,因此结果必为合法 UTF-8。
/// 该不变量由`write!` 格式化保证,无需调用方再做编码校验。
fn to_hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        // 写入 String 永不失败,故忽略返回值是安全的
        let _ = write!(out, "{b:02x}");
    }
    out
}

/// 镜像管理门面
///
/// 镜像进度回调的 FFI跳板
///
/// 将官方以裸指针传入的进度消息转回 [`ImageProgress`] 后再交给调用方的闭包。
/// 供 [`WslcImageManager::pull_image`] 与
/// [`WslcImageManager::push_image_with_progress`] 共用。
///
/// 跨 FFI 边界必须捕获 panic:unwind 穿过 C 栈帧属未定义行为。
///
/// # 上下文生命周期的隐含契约(调用方必须自行确认)
///
/// `ctx` 指向的 `Box<Mutex<F>>` 由 [`WslcImageManager::pull_image`] 与
/// [`WslcImageManager::push_image_with_progress`] 在**官方调用返回后立刻**回收。
/// 这隐含一项未见于官方文档的假设:官方只在该次调用期间同步派发进度回调,
/// 不会把回调上下文留存到调用返回之后。
///
/// 该假设对拉取这类长耗时操作尤为关键——若官方改为在后台线程异步派发,
/// 提前回收即构成 use-after-free。届时须改为「先向官方注销回调、再释放
/// 上下文」的二段式生命周期,与
/// [`CrashDumpSubscription`](crate::CrashDumpSubscription) 的析构顺序一致:
/// 它在 `Drop` 中先 `WslcReleaseCrashDumpSubscription` 注销订阅,确认官方
/// 不会再触发回调,之后才释放闭包内存。
///
/// # Safety
///
/// `ctx` 必须是由调用方以 `Box::into_raw` 移交的 `Mutex<F>` 指针,且在官方停止回调前
/// 保持有效;`msg` 由官方保证在回调期间指向有效结构体。
unsafe extern "system" fn progress_trampoline<F>(
    msg: *const WslcImageProgressMessage,
    ctx: *mut c_void,
) -> HRESULT
where
    F: FnMut(&ImageProgress<'_>) -> bool,
{
    if msg.is_null() {
        return windows_sys::Win32::Foundation::S_OK;
    }
    // SAFETY: ctx 由 pull_image / push_image_with_progress 以
    // Box<Mutex<F>> 拆出并原样回传,类型与拆出时严格一致。
    let should_continue = unsafe {
        invoke_callback::<F, _>(ctx, |callback| {
            // SAFETY: 官方保证回调期间 msg 指向有效的进度结构体,
            // 其内部指针的有效性由官方契约保证。
            let raw = &*msg;
            let id_str = if !raw.id.is_null() {
                // SAFETY: id 非空且为官方保证以 NUL 结尾的字符串。
                CStr::from_ptr(raw.id).to_str().unwrap_or_default()
            } else {
                ""
            };
            let progress = ImageProgress {
                id: id_str,
                status: raw.status,
                current_bytes: raw.detail.current_bytes,
                total_bytes: raw.detail.total_bytes,
            };
            callback(&progress)
        })
    };

    match should_continue {
        Some(true) => windows_sys::Win32::Foundation::S_OK,
        // 上下文为空、锁中毒或闭包 panic:一律按中止处理,
        // 避免让官方继续向一个已不可用的回调推送数据
        _ => windows_sys::Win32::Foundation::E_ABORT,
    }
}

/// 全部方法均为关联函数,不持有状态;使用 `WslcSessionHandle` 显式指定操作会话。
#[derive(Debug, Clone, Copy, Default)]
pub struct WslcImageManager;

impl WslcImageManager {
    /// 获取当前会话内的镜像列表
    pub fn list_images(session: &WslcSessionHandle) -> Result<Vec<ImageInfo>, WslcError> {
        let mut raw_images: *mut WslcImageInfo = std::ptr::null_mut();
        let mut count: u32 = 0;

        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe { WslcListSessionImages(session.as_raw(), &mut raw_images, &mut count) };
        if hr < 0 {
            return Err(WslcError::from_hresult(hr, "获取镜像列表失败"));
        }

        // SDK 声明成功并声称有 count 个镜像,却未给出数组指针:属契约违背。
        // 若静默放行,下方 as_slice() 会返回空切片,调用方得到「会话内没有镜像」
        // 这一看似合理却完全错误的结果,且与真实的空会话无从区分。
        if count > 0 && raw_images.is_null() {
            return Err(WslcError::UnexpectedSdkResult(format!(
                "WslcListSessionImages 返回成功状态并声称有 {count} 个镜像,却未给出数组指针"
            )));
        }

        // 数组所有权移交 ComArray:空指针与 count 为 0 两种情形均被自动收敛,
        // 无论后续如何提前返回,COM 堆内存都会被恰好释放一次
        // SAFETY: raw_images 为官方 _Outptr_result_buffer_ 输出数组,所有权移交本侧
        let images =
            unsafe { ComArray::from_raw(raw_images, count as usize) }.ok_or_else(|| {
                WslcError::UnexpectedSdkResult("WslcListSessionImages 未返回镜像数组".to_string())
            })?;

        let slice = images.as_slice();
        if slice.is_empty() {
            return Ok(Vec::new());
        }

        let mut list = Vec::with_capacity(slice.len());

        for item in slice {
            let name_end = item
                .name
                .iter()
                .position(|&b| b == 0)
                .unwrap_or(item.name.len());
            let name = String::from_utf8_lossy(&item.name[..name_end]).to_string();

            // 摘要以标准小写十六进制呈现。长度由摘要数组自身推导而非硬编码,
            // 官方若变更摘要长度不会越界panic;格式化宏保证输出必为合法 UTF-8,
            // 无需 unsafe 转换。
            let sha_hex = to_hex(&item.sha256);

            list.push(ImageInfo {
                name,
                sha256: sha_hex,
                size_bytes: item.size_bytes,
                created_unix_time: item.created_unix_time,
            });
        }

        Ok(list)
    }

    /// 拉取远程镜像
    ///
    /// `uri` 会先经 [`resolve_image_reference`](crate::registry::resolve_image_reference)
    /// 应用环境变量配置的镜像加速器,再交给官方拉取。
    /// [`push_image`](Self::push_image) 则**不**做此重写,
    /// 理由见 [`push_image_with_progress`](Self::push_image_with_progress)。
    pub fn pull_image<F>(
        session: &WslcSessionHandle,
        uri: &str,
        registry_auth: Option<&str>,
        on_progress: Option<F>,
    ) -> Result<(), WslcError>
    where
        F: FnMut(&ImageProgress<'_>) -> bool + Send,
    {
        let resolved_uri = crate::registry::resolve_image_reference(uri)?;
        let c_uri = CString::new(resolved_uri.as_str())
            .map_err(|e| WslcError::NulError(format!("URI 包含非法空字节: {e}")))?;
        let c_auth = match registry_auth {
            Some(a) => Some(
                CString::new(a)
                    .map_err(|e| WslcError::NulError(format!("鉴权信息包含非法空字节: {e}")))?,
            ),
            None => None,
        };

        let (cb, ctx) = match on_progress {
            Some(f) => {
                let boxed = Box::into_raw(Box::new(std::sync::Mutex::new(f)));
                (Some(progress_trampoline::<F> as _), boxed as *mut c_void)
            }
            None => (None, std::ptr::null_mut()),
        };

        let options = WslcPullImageOptions {
            uri: c_uri.as_ptr(),
            progress_callback: cb,
            progress_callback_context: ctx,
            registry_auth: c_auth.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
        };

        let mut err_msg: *mut u16 = std::ptr::null_mut();
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe { WslcPullSessionImage(session.as_raw(), &options, &mut err_msg) };
        if !ctx.is_null() {
            // 此处立即回收,依赖「官方只在本次调用期间同步派发进度回调」这一
            // 未在官方文档中载明的假设。该假设及其失效时的改法见
            // progress_trampoline 的文档。
            //
            // SAFETY: ctx 在本函数开头由 Box::into_raw 分配,调用结束立即安全回收
            let _ = unsafe { Box::from_raw(ctx as *mut std::sync::Mutex<F>) };
        }
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(
                hr,
                err_msg,
                format!("拉取镜像失败,实际拉取地址: '{resolved_uri}'"),
            )?;
        }
        // 同时记录请求 URI 与实际拉取地址:二者在配置了镜像加速器时并不相同,
        // 只打前者会让审计无法回答「镜像究竟从哪个主机拉取」——那恰是加速器
        // 引入的供应链投毒路径上最关键的追问(见 registry 模块的安全提示)
        log::info!(
            "镜像拉取完成,请求 URI: '{}',实际拉取地址: '{}',所属会话: '{}'",
            uri,
            resolved_uri,
            session.name()
        );
        Ok(())
    }

    /// 从文件导入 tar 镜像
    pub fn import_image_from_file(
        session: &WslcSessionHandle,
        image_name: &str,
        path: impl AsRef<Path>,
    ) -> Result<(), WslcError> {
        let c_name = CString::new(image_name)
            .map_err(|e| WslcError::NulError(format!("镜像名称非法: {e}")))?;
        let wide_path = path_to_wide_null(path)?;

        let options = WslcImportImageOptions::default();
        let mut err_msg: *mut u16 = std::ptr::null_mut();

        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe {
            WslcImportSessionImageFromFile(
                session.as_raw(),
                c_name.as_ptr(),
                wide_path.as_ptr(),
                &options,
                &mut err_msg,
            )
        };
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(hr, err_msg, format!("导入镜像失败,名称: '{image_name}'"))?;
        }
        log::info!(
            "镜像导入完成,名称: '{}',所属会话: '{}'",
            image_name,
            session.name()
        );
        Ok(())
    }

    /// 从文件载入 docker save 镜像
    pub fn load_image_from_file(
        session: &WslcSessionHandle,
        path: impl AsRef<Path>,
    ) -> Result<(), WslcError> {
        let wide_path = path_to_wide_null(path)?;

        let options = WslcLoadImageOptions::default();
        let mut err_msg: *mut u16 = std::ptr::null_mut();

        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe {
            WslcLoadSessionImageFromFile(
                session.as_raw(),
                wide_path.as_ptr(),
                &options,
                &mut err_msg,
            )
        };
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(
                hr,
                err_msg,
                format!("载入镜像失败,所属会话: '{}'", session.name()),
            )?;
        }
        log::info!("镜像载入完成,所属会话: '{}'", session.name());
        Ok(())
    }

    /// 从内存流载入镜像
    ///
    /// # Safety
    ///
    /// 调用方必须确保 `content_handle` 是具有可读权限的有效 Win32 文件或管道句柄,且其生命周期覆盖当前调用。
    pub unsafe fn load_image_from_handle(
        session: &WslcSessionHandle,
        content_handle: HANDLE,
        bytes: u64,
    ) -> Result<(), WslcError> {
        let options = WslcLoadImageOptions::default();
        let mut err_msg: *mut u16 = std::ptr::null_mut();

        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe {
            WslcLoadSessionImage(
                session.as_raw(),
                content_handle,
                bytes,
                &options,
                &mut err_msg,
            )
        };
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(
                hr,
                err_msg,
                format!("从句柄载入镜像失败,所属会话: '{}'", session.name()),
            )
        }
    }

    /// 从内存流导入镜像
    ///
    /// # Safety
    ///
    /// 调用方必须确保 `content_handle` 是具有可读权限的有效 Win32 文件或管道句柄,且其生命周期覆盖当前调用。
    pub unsafe fn import_image_from_handle(
        session: &WslcSessionHandle,
        image_name: &str,
        content_handle: HANDLE,
        bytes: u64,
    ) -> Result<(), WslcError> {
        let c_name = CString::new(image_name)
            .map_err(|e| WslcError::NulError(format!("镜像名称非法: {e}")))?;
        let options = WslcImportImageOptions::default();
        let mut err_msg: *mut u16 = std::ptr::null_mut();

        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe {
            WslcImportSessionImage(
                session.as_raw(),
                c_name.as_ptr(),
                content_handle,
                bytes,
                &options,
                &mut err_msg,
            )
        };
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(
                hr,
                err_msg,
                format!("从句柄导入镜像失败,名称: '{image_name}'"),
            )
        }
    }

    /// 为已有镜像打标签
    pub fn tag_image(
        session: &WslcSessionHandle,
        image: &str,
        repo: &str,
        tag: &str,
    ) -> Result<(), WslcError> {
        let c_img =
            CString::new(image).map_err(|e| WslcError::NulError(format!("镜像名称非法: {e}")))?;
        let c_repo =
            CString::new(repo).map_err(|e| WslcError::NulError(format!("仓库名称非法: {e}")))?;
        let c_tag =
            CString::new(tag).map_err(|e| WslcError::NulError(format!("标签名称非法: {e}")))?;

        let options = WslcTagImageOptions {
            image: c_img.as_ptr(),
            repo: c_repo.as_ptr(),
            tag: c_tag.as_ptr(),
        };

        let mut err_msg: *mut u16 = std::ptr::null_mut();
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe { WslcTagSessionImage(session.as_raw(), &options, &mut err_msg) };
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(hr, err_msg, format!("镜像打标签失败,目标: '{repo}:{tag}'"))
        }
    }

    /// 推送镜像至远程仓库 (支持进度监控)
    ///
    /// # 与镜像加速器的差异(有意为之)
    ///
    /// 本方法**不**应用 [`resolve_image_reference`](crate::registry::resolve_image_reference)
    /// 的镜像加速器重写,而 [`pull_image`](Self::pull_image) 会应用。
    /// 这一不对称是刻意的设计,理由有二:
    ///
    /// 1. **镜像加速器本质是拉取侧的优化**。其用途是在网络受限环境中
    ///    从就近副本拉取,用以加速*读取*;推送是写操作,目标仓库应由
    ///    调用方显式指定,不应被一个为读取设计的配置悄悄改写。
    /// 2. **避免推错仓库**。若推送也走重写,从加速器地址拉来的镜像会被
    ///    推回加速器地址而非原始仓库,而调用方以为自己在推
    ///    `docker.io/library/alpine`。这类错误不会报错,只会成功推送到
    ///    一个错误的地点。
    ///
    /// 故推送目标恒为调用方给出的 `image` 原值。
    pub fn push_image_with_progress<F>(
        session: &WslcSessionHandle,
        image: &str,
        registry_auth: Option<&str>,
        on_progress: Option<F>,
    ) -> Result<(), WslcError>
    where
        F: FnMut(&ImageProgress<'_>) -> bool + Send,
    {
        let c_img =
            CString::new(image).map_err(|e| WslcError::NulError(format!("镜像名称非法: {e}")))?;
        let c_auth = match registry_auth {
            Some(a) => Some(
                CString::new(a).map_err(|e| WslcError::NulError(format!("鉴权信息非法: {e}")))?,
            ),
            None => None,
        };

        let (cb, ctx) = match on_progress {
            Some(f) => {
                let boxed = Box::into_raw(Box::new(std::sync::Mutex::new(f)));
                (Some(progress_trampoline::<F> as _), boxed as *mut c_void)
            }
            None => (None, std::ptr::null_mut()),
        };

        let options = WslcPushImageOptions {
            image: c_img.as_ptr(),
            registry_auth: c_auth.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
            progress_callback: cb,
            progress_callback_context: ctx,
        };

        let mut err_msg: *mut u16 = std::ptr::null_mut();
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe { WslcPushSessionImage(session.as_raw(), &options, &mut err_msg) };
        if !ctx.is_null() {
            // SAFETY: ctx 在本函数开头由 Box::into_raw 分配,调用结束立即安全回收
            let _ = unsafe { Box::from_raw(ctx as *mut std::sync::Mutex<F>) };
        }
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(hr, err_msg, format!("推送镜像失败,目标: '{image}'"))?;
        }
        log::info!(
            "镜像推送完成,镜像: '{}',所属会话: '{}'",
            image,
            session.name()
        );
        Ok(())
    }

    /// 推送镜像至远程仓库
    ///
    /// 推送目标为 `image` 原值,**不**应用镜像加速器重写——
    /// 理由见 [`push_image_with_progress`](Self::push_image_with_progress)
    /// 的说明。
    pub fn push_image(
        session: &WslcSessionHandle,
        image: &str,
        registry_auth: Option<&str>,
    ) -> Result<(), WslcError> {
        Self::push_image_with_progress(
            session,
            image,
            registry_auth,
            None::<fn(&ImageProgress<'_>) -> bool>,
        )
    }

    /// 删除镜像
    pub fn delete_image(session: &WslcSessionHandle, name_or_id: &str) -> Result<(), WslcError> {
        let c_str = CString::new(name_or_id)
            .map_err(|e| WslcError::NulError(format!("镜像名称或 ID 非法: {e}")))?;
        let mut err_msg: *mut u16 = std::ptr::null_mut();
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        let hr = unsafe { WslcDeleteSessionImage(session.as_raw(), c_str.as_ptr(), &mut err_msg) };
        // SAFETY: 入参均为已初始化且存活期覆盖本次调用的本地缓冲区或官方句柄,
        // 出参为合法的可写指针,不涉及未定义行为。
        unsafe {
            WslcError::check(
                hr,
                err_msg,
                format!("删除镜像失败,名称或 ID: '{name_or_id}'"),
            )?;
        }
        log::info!(
            "镜像删除成功,目标: '{}',所属会话: '{}'",
            name_or_id,
            session.name()
        );
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_image_progress_to_owned_roundtrip() {
        let borrowed = ImageProgress {
            id: "sha256:1234",
            status: WslcImageProgressStatus::Downloading,
            current_bytes: 1024,
            total_bytes: 2048,
        };
        let owned = borrowed.to_owned();
        assert_eq!(owned.id, "sha256:1234");
        assert_eq!(owned.status, WslcImageProgressStatus::Downloading);
        assert_eq!(owned.current_bytes, 1024);
        assert_eq!(owned.total_bytes, 2048);
    }

    #[test]
    fn test_image_progress_to_owned_is_independent() {
        let mut owned = {
            let borrowed = ImageProgress {
                id: "layer-a",
                status: WslcImageProgressStatus::Pulling,
                current_bytes: 0,
                total_bytes: 0,
            };
            borrowed.to_owned()
        };
        // 借用对象已随作用域释放,拥有所有权的副本仍可独立使用
        owned.id.push_str("-mutated");
        assert_eq!(owned.id, "layer-a-mutated");
    }

    #[test]
    fn test_image_info_serde_roundtrip() {
        let info = ImageInfo {
            name: "alpine:latest".to_string(),
            sha256: "a".repeat(64),
            size_bytes: 3_500_000,
            created_unix_time: 1_700_000_000,
        };
        let json = serde_json::to_string(&info).expect("序列化失败");
        let back: ImageInfo = serde_json::from_str(&json).expect("反序列化失败");
        assert_eq!(info, back);
    }

    /// 十六进制编码须为定长两倍输出,且字符集限定为小写十六进制
    #[test]
    fn test_to_hex_produces_lowercase_fixed_width() {
        assert_eq!(to_hex(&[]), "");
        assert_eq!(to_hex(&[0x00]), "00");
        assert_eq!(to_hex(&[0xff]), "ff");
        // 高低半字节均需补零,锁定宽度语义
        assert_eq!(to_hex(&[0x0f, 0xf0]), "0ff0");
        // 摘要全字节全覆盖,锁定不会漏位或错位
        let all: Vec<u8> = (0..=255u8).collect();
        let hex = to_hex(&all);
        assert_eq!(hex.len(), 512);
        assert!(
            hex.chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase())
        );
        assert!(hex.starts_with("000102"));
        assert!(hex.ends_with("fdfeff"));
    }
}