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
//! WSLC 安全错误类型与 Win32 HRESULT 解析器
//!
//! 错误模型分为两层:官方头文件中 19 个具名 HRESULT 收敛为 [`WslcDomainError`],
//! 由 [`WslcError::Domain`] 变体包裹;文本编码、IO、JSON、任务调度等基础设施类
//! 错误保留在 [`WslcError`] 外层。调用方据此可快速区分「业务终态」与
//! 「可重试的系统抖动」,无需解析错误文本。

use crate::com_memory::ComWideString;
use thiserror::Error;
use windows_sys::Win32::Foundation::{
    CO_E_NOTINITIALIZED, E_ABORT, E_ACCESSDENIED, E_FAIL, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL,
    E_OUTOFMEMORY, E_POINTER, E_UNEXPECTED, RPC_E_CHANGED_MODE, RPC_E_DISCONNECTED,
    RPC_E_WRONG_THREAD,
};
use windows_sys::core::HRESULT;
use wslcsdk_sys::errors::*;

/// WSLC 官方业务领域错误
///
/// 与官方头文件中的具名错误码一一对应。变体载荷为调用点上下文与官方返回的
/// 动态错误描述;需要进行程序化判断时请匹配变体本身,切勿解析该文本。
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum WslcDomainError {
    /// 按名称、ID 或摘要引用的镜像在当前会话中不存在
    #[error("镜像未找到: {0}")]
    ImageNotFound(String),

    /// 容器 ID 前缀匹配到多个候选,无法确定目标容器
    #[error("容器 ID 前缀存在歧义,匹配到多个容器: {0}")]
    ContainerPrefixAmbiguous(String),

    /// 按名称或 ID 指定的容器在当前会话中不存在
    #[error("容器未找到: {0}")]
    ContainerNotFound(String),

    /// 按名称指定的存储卷在当前会话中不存在
    #[error("存储卷未找到: {0}")]
    VolumeNotFound(String),

    /// 要求容器处于运行状态的操作(如向其派生进程)失败
    #[error("容器未处于运行状态: {0}")]
    ContainerNotRunning(String),

    /// 要求容器处于停止状态的操作(如启动)因其已在运行而失败
    #[error("容器已处于运行状态: {0}")]
    ContainerAlreadyRunning(String),

    /// 会话名与系统内置名称冲突,改用其他名称即可
    #[error("会话名称属于系统保留名称: {0}")]
    SessionReserved(String),

    /// 会话名含非法字符,或不符合命名规则
    #[error("会话名称非法: {0}")]
    InvalidSessionName(String),

    /// 指定的网络不存在,可能已被删除或名称拼写有误
    #[error("网络未找到: {0}")]
    NetworkNotFound(String),

    /// 通过 Windows Update 补齐缺失组件时,组件搜索未能完成
    #[error("Windows Update 组件搜索失败: {0}")]
    WindowsUpdateSearchFailed(String),

    /// 已安装的 WSLC 版本低于本库要求,需先升级系统组件
    #[error("WSLC SDK 版本落后,需要更新系统组件: {0}")]
    SdkUpdateNeeded(String),

    /// 容器相关功能被系统或安全策略(如企业策略)禁用
    #[error("容器功能被系统或安全策略禁用: {0}")]
    ContainerDisabled(String),

    /// 镜像仓库访问被本机安全策略拦截,非凭据问题
    #[error("镜像仓库访问被安全策略拦截: {0}")]
    RegistryBlockedByPolicy(String),

    /// 存储卷存在但当前不可用,常见于被其他进程独占挂载
    #[error("存储卷当前不可用或被独占锁定: {0}")]
    VolumeNotAvailable(String),

    /// 指定的会话不存在或已被终止
    #[error("会话未找到: {0}")]
    SessionNotFound(String),

    /// WSL 虚拟机未启动,多数操作需先触发其启动
    #[error("WSL 虚拟机未处于运行状态: {0}")]
    VmNotRunning(String),

    /// 事件队列溢出,部分事件被丢弃;可增大缓冲区后重试
    #[error("事件队列溢出,部分事件已丢失: {0}")]
    EventsLost(String),

    /// 事件流已正常结束,通常意味着相关会话或容器已终止
    #[error("事件流已终止: {0}")]
    EventStreamFinished(String),

    /// 操作目标容器已被删除,无法再对其执行任何操作
    #[error("容器已被删除: {0}")]
    ContainerDeleted(String),
}

impl WslcDomainError {
    /// 依据官方 HRESULT 解析业务领域错误;非官方业务码返回 `None`
    pub fn from_hresult(hr: HRESULT, context: impl Into<String>) -> Option<Self> {
        let message = context.into();
        Some(match hr {
            WSLC_E_IMAGE_NOT_FOUND => Self::ImageNotFound(message),
            WSLC_E_CONTAINER_PREFIX_AMBIGUOUS => Self::ContainerPrefixAmbiguous(message),
            WSLC_E_CONTAINER_NOT_FOUND => Self::ContainerNotFound(message),
            WSLC_E_VOLUME_NOT_FOUND => Self::VolumeNotFound(message),
            WSLC_E_CONTAINER_NOT_RUNNING => Self::ContainerNotRunning(message),
            WSLC_E_CONTAINER_IS_RUNNING => Self::ContainerAlreadyRunning(message),
            WSLC_E_SESSION_RESERVED => Self::SessionReserved(message),
            WSLC_E_INVALID_SESSION_NAME => Self::InvalidSessionName(message),
            WSLC_E_NETWORK_NOT_FOUND => Self::NetworkNotFound(message),
            WSLC_E_WU_SEARCH_FAILED => Self::WindowsUpdateSearchFailed(message),
            WSLC_E_SDK_UPDATE_NEEDED => Self::SdkUpdateNeeded(message),
            WSLC_E_CONTAINER_DISABLED => Self::ContainerDisabled(message),
            WSLC_E_REGISTRY_BLOCKED_BY_POLICY => Self::RegistryBlockedByPolicy(message),
            WSLC_E_VOLUME_NOT_AVAILABLE => Self::VolumeNotAvailable(message),
            WSLC_E_SESSION_NOT_FOUND => Self::SessionNotFound(message),
            WSLC_E_VM_NOT_RUNNING => Self::VmNotRunning(message),
            WSLC_E_EVENTS_LOST => Self::EventsLost(message),
            WSLC_E_EVENT_STREAM_FINISHED => Self::EventStreamFinished(message),
            WSLC_E_CONTAINER_DELETED => Self::ContainerDeleted(message),
            _ => return None,
        })
    }
}

/// WSLC SDK 统一错误类型
///
/// 分两层组织:官方业务领域错误由 [`WslcError::Domain`] 包裹,其余均为基础设施类
/// 错误。本枚举标记为 `#[non_exhaustive]`,后续新增变体不构成破坏性变更。
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum WslcError {
    /// WSLC 官方业务领域错误
    #[error(transparent)]
    Domain(#[from] WslcDomainError),

    /// 未能识别的 Windows HRESULT
    ///
    /// 载荷为原始错误码,以及「标准错误名 + 调用点上下文」的描述。常见标准码会被
    /// 还原为可读名称,避免笼统的「系统调用失败」误导排查方向。
    #[error("Windows 调用失败,HRESULT: 0x{0:08X},详情: {1}")]
    Hresult(u32, String),

    /// Win32 系统调用失败(错误码来自 `GetLastError`)
    ///
    /// 与 [`Self::Hresult`] 分列:Win32 错误码与 HRESULT 是两套编码体系,
    /// 前者为小整数(`6` = ERROR_INVALID_HANDLE),后者最高位表示严重性。
    /// 若把 Win32 码塞进 `Hresult`,会按 `0x00000006` 呈现——最高位为 0,
    /// 与本库「hr >= 0 即成功」的判定方向相反,极易被误读为一次成功的调用。
    #[error("Win32 调用失败,错误码: {0},详情: {1}")]
    Win32(u32, String),

    /// SDK 返回了违背其公开契约的非预期结果
    ///
    /// 例如接口声明返回成功状态,却未按要求给出输出指针。此类情形无法归入任何
    /// 官方错误码,也不属于调用方的入参问题,故单列一类以便上层识别。
    #[error("SDK 返回非预期结果: {0}")]
    UnexpectedSdkResult(String),

    /// 空指针或无效句柄
    #[error("空指针或无效句柄")]
    InvalidHandle,

    /// 文本编码转换失败
    #[error("文本编码转换失败: {0}")]
    Utf8Error(String),

    /// 字符串中包含非法空字符 (Nul Byte)
    #[error("字符串中包含非法空字符 (Nul Byte): {0}")]
    NulError(String),

    /// JSON 序列化或反序列化失败
    #[error("JSON 序列化或反序列化失败: {0}")]
    JsonError(String),

    /// 异步任务调度或执行失败
    #[error("异步任务执行失败: {0}")]
    TaskJoin(String),

    /// 一次性资源已被消费,无可重复领取的剩余
    ///
    /// 单列一类而非复用 [`Self::TaskJoin`]:该变体描述的是**调用方重复调用**
    /// 所触发的业务终态(同一退出码只通知一次),而非异步任务本身失败。
    /// 两者若混同,调用方按「任务可重试」处理就会陷入无效重试。
    #[error("{0}已被消费,不可重复获取")]
    AlreadyConsumed(String),

    /// 内部异步通知通道异常终止
    ///
    /// 与 [`Self::TaskJoin`] 区分:此处并非任务执行出错,而是承载通知的
    /// 通道两端失联,调用方重试无意义。
    #[error("内部通知通道异常终止: {0}")]
    ChannelTerminated(String),

    /// I/O 操作失败
    #[error("I/O 操作失败: {0}")]
    Io(String),

    /// 客户端侧配置、环境变量或入参校验失败
    #[error("配置或环境变量非法: {0}")]
    InvalidConfiguration(String),
}

impl WslcError {
    /// 根据 HRESULT 与上下文描述解析为强类型错误
    ///
    /// 优先匹配官方具名业务错误码;未识别时归入 [`WslcError::Hresult`],并在描述中
    /// 尽可能还原标准错误名称。
    pub fn from_hresult(hr: HRESULT, context_desc: impl Into<String>) -> Self {
        let message = context_desc.into();

        // 以借用传入:from_hresult 仅在命中官方业务码时才调用 Into::into,
        // 非业务码(占绝大多数)因此不必为一次必定落空的分支克隆上下文字符串
        if let Some(domain) = WslcDomainError::from_hresult(hr, message.as_str()) {
            return Self::Domain(domain);
        }

        let code = hr as u32;
        match hresult_name(code) {
            Some(name) => Self::Hresult(code, format!("{name},{message}")),
            None => Self::Hresult(code, message),
        }
    }

    /// 官方返回非失败码,却未给出其声明的输出指针
    ///
    /// 此类情形若沿用 [`Self::from_hresult`],`hr` 会是一个成功码(0 或正值),
    /// 错误文本遂呈现为「Windows 调用失败,HRESULT: 0x00000000」——把一个
    /// **成功码当作失败原因**报出,既自相矛盾,又把排查方向从「SDK 违背契约」
    /// 带偏到「某次 Windows 调用失败」。故在此单列一支,与真正的 HRESULT
    /// 失败区分开:调用方只需匹配 [`Self::UnexpectedSdkResult`] 即可识别。
    pub(crate) fn missing_output(api_name: &str, hr: HRESULT) -> Self {
        Self::UnexpectedSdkResult(format!(
            "{api_name} 返回 HRESULT 0x{hr:08X}(非失败码)却未给出其声明的输出指针"
        ))
    }

    /// 检查 HRESULT,若小于 0 则解析为带上下文描述的领域错误
    pub(crate) fn check_hr(hr: HRESULT, context_desc: impl Into<String>) -> Result<(), Self> {
        if hr >= 0 {
            Ok(())
        } else {
            Err(Self::from_hresult(hr, context_desc))
        }
    }

    /// 解析 HRESULT 及官方返回的动态宽字符串错误信息
    ///
    /// `msg_ptr` 交由 [`ComWideString`] 托管:无论本方法走哪个分支,COM 堆内存
    /// 都会被自动释放,调用方无需也不应再手工调用 `CoTaskMemFree`。
    ///
    /// # 为何必须另行传入调用点上下文
    ///
    /// 官方并非每次失败都给出错误描述——静默失败时 `msg_ptr` 为空串或空指针。
    /// 若把官方描述直接当作错误上下文,此类失败会退化成「容器未找到: 」这类
    /// 没有现场信息的空壳消息:调用方明知出了业务终态,却无从判断是哪一步操作、
    /// 针对哪个对象失败。故上下文一律由调用点提供,官方描述降级为附加详情。
    pub(crate) unsafe fn from_hresult_and_raw_msg(
        hr: HRESULT,
        msg_ptr: *mut u16,
        context_desc: impl Into<String>,
    ) -> Self {
        // SAFETY: 调用方均为官方 API 的 _Outptr_opt_result_z_ 输出参数,
        // 所有权在交接给本方法的那一刻即转由 Rust 侧接管
        let official = unsafe { ComWideString::from_raw(msg_ptr) }
            .map(|msg| msg.to_string_lossy())
            .unwrap_or_default();

        let context = context_desc.into();
        let detail = if official.is_empty() {
            context
        } else {
            format!("{context},SDK 描述: {official}")
        };

        Self::from_hresult(hr, detail)
    }

    /// 读取 `GetLastError` 并包装为带上下文描述的 [`WslcError::Win32`]
    ///
    /// # Safety
    ///
    /// 必须**紧随**失败的 Win32 调用之后执行:任何其他 Win32 调用都可能
    /// 覆盖线程内的最后一个错误码,使读到的值不属于本次失败。
    pub(crate) unsafe fn last_win32_error(context_desc: impl Into<String>) -> Self {
        // SAFETY: 由调用方保证本方法紧随失败的 Win32 调用,
        // 且该 API 无参数、无副作用。
        let code = unsafe { windows_sys::Win32::Foundation::GetLastError() };
        Self::Win32(code, context_desc.into())
    }

    /// 检查 HRESULT,若失败则解析错误,成功则返回 `Ok(())`
    ///
    /// 无论成功与否,`msg_ptr` 都会被 [`ComWideString`] 自动释放。
    ///
    /// `context_desc` 为调用点上下文(建议带上操作对象标识),是错误描述的主干;
    /// 官方给出的错误描述若非空,则拼在其后作为详情。二者不可互换——官方常
    /// 静默失败,此时唯一可用的现场信息只剩调用点上下文。
    pub(crate) unsafe fn check(
        hr: HRESULT,
        msg_ptr: *mut u16,
        context_desc: impl Into<String>,
    ) -> Result<(), Self> {
        if hr >= 0 {
            // SAFETY: msg_ptr 为官方输出的宽字符串指针,
            // 本函数负责接管其所有权并在读取后释放。
            drop(unsafe { ComWideString::from_raw(msg_ptr) });
            Ok(())
        } else {
            // SAFETY: msg_ptr 为官方输出的宽字符串指针,
            // 本函数负责接管其所有权并在读取后释放。
            Err(unsafe { Self::from_hresult_and_raw_msg(hr, msg_ptr, context_desc) })
        }
    }
}

/// 将常见标准 HRESULT 还原为可读名称,未知错误码返回 `None`
///
/// 覆盖 WSLC 调用链路上最可能遇到的标准错误码,用于替代原先笼统的
/// 「Win32 系统调用失败」描述。
fn hresult_name(code: u32) -> Option<&'static str> {
    // 还原为 HRESULT 后即可直接使用 windows-sys 导出的标准常量做模式匹配
    Some(match code as HRESULT {
        E_ACCESSDENIED => "E_ACCESSDENIED (拒绝访问)",
        E_INVALIDARG => "E_INVALIDARG (参数或标志位不合法)",
        E_OUTOFMEMORY => "E_OUTOFMEMORY (内存不足)",
        E_FAIL => "E_FAIL (未指定的失败)",
        E_NOTIMPL => "E_NOTIMPL (未实现该功能)",
        E_NOINTERFACE => "E_NOINTERFACE (不支持所请求的接口)",
        E_POINTER => "E_POINTER (无效指针)",
        E_UNEXPECTED => "E_UNEXPECTED (非预期状态)",
        E_ABORT => "E_ABORT (操作已中止)",
        CO_E_NOTINITIALIZED => "CO_E_NOTINITIALIZED (COM 尚未初始化)",
        RPC_E_CHANGED_MODE => "RPC_E_CHANGED_MODE (COM 套间模型冲突,当前线程已被初始化为 STA)",
        RPC_E_WRONG_THREAD => "RPC_E_WRONG_THREAD (在错误的线程上调用)",
        RPC_E_DISCONNECTED => "RPC_E_DISCONNECTED (对象已与调用方断开连接)",
        _ => return None,
    })
}

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

    /// 官方 19 个具名错误码,用于批量验证映射行为
    const ALL_DOMAIN_CODES: [HRESULT; 19] = [
        WSLC_E_IMAGE_NOT_FOUND,
        WSLC_E_CONTAINER_PREFIX_AMBIGUOUS,
        WSLC_E_CONTAINER_NOT_FOUND,
        WSLC_E_VOLUME_NOT_FOUND,
        WSLC_E_CONTAINER_NOT_RUNNING,
        WSLC_E_CONTAINER_IS_RUNNING,
        WSLC_E_SESSION_RESERVED,
        WSLC_E_INVALID_SESSION_NAME,
        WSLC_E_NETWORK_NOT_FOUND,
        WSLC_E_WU_SEARCH_FAILED,
        WSLC_E_SDK_UPDATE_NEEDED,
        WSLC_E_CONTAINER_DISABLED,
        WSLC_E_REGISTRY_BLOCKED_BY_POLICY,
        WSLC_E_VOLUME_NOT_AVAILABLE,
        WSLC_E_SESSION_NOT_FOUND,
        WSLC_E_VM_NOT_RUNNING,
        WSLC_E_EVENTS_LOST,
        WSLC_E_EVENT_STREAM_FINISHED,
        WSLC_E_CONTAINER_DELETED,
    ];

    #[test]
    fn test_domain_error_mapping_with_raw_message() {
        // SAFETY: msg_ptr 为官方输出的宽字符串指针,
        // 本函数负责接管其所有权并在读取后释放。
        unsafe {
            let err = WslcError::from_hresult_and_raw_msg(
                WSLC_E_CONTAINER_NOT_FOUND,
                std::ptr::null_mut(),
                "打开容器失败",
            );
            assert_eq!(
                err,
                WslcError::Domain(WslcDomainError::ContainerNotFound(
                    "打开容器失败".to_string()
                ))
            );

            let err2 = WslcError::from_hresult_and_raw_msg(
                WSLC_E_IMAGE_NOT_FOUND,
                std::ptr::null_mut(),
                "拉取镜像失败",
            );
            assert_eq!(
                err2,
                WslcError::Domain(WslcDomainError::ImageNotFound("拉取镜像失败".to_string()))
            );

            let err3 = WslcError::from_hresult_and_raw_msg(
                WSLC_E_VM_NOT_RUNNING,
                std::ptr::null_mut(),
                "创建会话失败",
            );
            assert_eq!(
                err3,
                WslcError::Domain(WslcDomainError::VmNotRunning("创建会话失败".to_string()))
            );
        }

        let err_direct = WslcError::from_hresult(WSLC_E_CONTAINER_NOT_FOUND, "测试上下文");
        assert_eq!(
            err_direct,
            WslcError::Domain(WslcDomainError::ContainerNotFound("测试上下文".to_string()))
        );
    }

    #[test]
    fn test_every_official_code_lands_in_domain_layer() {
        // 全部官方具名错误码都必须归入 Domain 层,不得退化为通用 Hresult,
        // 否则调用方无法区分业务终态与基础设施故障
        for code in ALL_DOMAIN_CODES {
            let err = WslcError::from_hresult(code, "上下文");
            assert!(
                matches!(err, WslcError::Domain(_)),
                "错误码 0x{:08X} 未映射为领域错误: {err:?}",
                code as u32
            );
        }

        // 反向校验:非官方码不得被误判为领域错误
        assert!(WslcDomainError::from_hresult(0x8004_9999_u32 as HRESULT, "x").is_none());
    }

    #[test]
    fn test_standard_hresult_reported_by_name() {
        let err = WslcError::from_hresult(E_INVALIDARG, "设置容器标志位失败");
        match err {
            WslcError::Hresult(code, detail) => {
                assert_eq!(code, E_INVALIDARG as u32);
                assert!(detail.contains("E_INVALIDARG"), "实际描述: {detail}");
                assert!(detail.contains("设置容器标志位失败"), "实际描述: {detail}");
            }
            other => panic!("预期返回 Hresult 变体,实际为: {other:?}"),
        }
    }

    #[test]
    fn test_unknown_hresult_keeps_raw_code_and_context() {
        let err = WslcError::from_hresult(0x8004_9999_u32 as HRESULT, "未知调用失败");
        match err {
            WslcError::Hresult(code, detail) => {
                assert_eq!(code, 0x8004_9999);
                assert_eq!(detail, "未知调用失败");
            }
            other => panic!("预期返回 Hresult 变体,实际为: {other:?}"),
        }
    }

    #[test]
    fn test_check_hr_boundary() {
        assert!(WslcError::check_hr(0, "S_OK").is_ok());
        assert!(WslcError::check_hr(1, "S_FALSE 亦视为成功").is_ok());
        assert!(WslcError::check_hr(WSLC_E_CONTAINER_NOT_FOUND, "失败").is_err());
    }

    /// 官方静默失败时,错误描述仍须带调用点上下文
    ///
    /// `check` 曾把官方错误消息直接当作上下文。官方大量接口在失败时并不填写
    /// `err_msg`,此时领域错误的描述退化为「容器未找到: 」这类空壳:调用方
    /// 明知命中了业务终态,却无从判断是哪一步操作、针对哪个对象失败。
    /// 故上下文一律由调用点提供,官方描述降级为附加详情。
    #[test]
    fn test_silent_failure_still_carries_call_site_context() {
        // 官方静默(空消息指针)
        // SAFETY: 空指针由 ComWideString::from_raw 判空处理,不涉及解引用
        let err = unsafe {
            WslcError::from_hresult_and_raw_msg(
                WSLC_E_CONTAINER_NOT_FOUND,
                std::ptr::null_mut(),
                "启动容器失败",
            )
        };
        assert_eq!(
            err.to_string(),
            "容器未找到: 启动容器失败",
            "官方未给出描述时,上下文必须独占描述位"
        );

        // 官方给出描述时,二者并存且上下文在前
        // SAFETY: com_wide_ptr 返回的指针由 ComWideString 接管并释放一次,
        // 未在本测试中重复使用,亦不跨越其作用域
        let err = unsafe {
            WslcError::from_hresult_and_raw_msg(
                WSLC_E_IMAGE_NOT_FOUND,
                com_wide_ptr("镜像不存在"),
                "删除镜像失败",
            )
        };
        assert_eq!(
            err.to_string(),
            "镜像未找到: 删除镜像失败,SDK 描述: 镜像不存在",
            "官方有描述时,上下文在前、官方描述在后"
        );
    }

    /// 在 COM 堆上构造一块以 NUL 结尾的宽字符串,所有权交由接收方释放
    ///
    /// # Safety
    ///
    /// 返回的指针必须由 [`ComWideString::from_raw`] 或等价路径接管并释放一次。
    unsafe fn com_wide_ptr(text: &str) -> *mut u16 {
        let units: Vec<u16> = text.encode_utf16().chain(std::iter::once(0)).collect();
        // SAFETY: 申请长度按元素数与元素宽度计算,返回值判空后写入同样长度,
        // 不越界;该内存随后由接收方经 ComWideString 释放。
        unsafe {
            let ptr =
                windows_sys::Win32::System::Com::CoTaskMemAlloc(units.len() * size_of::<u16>())
                    as *mut u16;
            if ptr.is_null() {
                return ptr;
            }
            std::ptr::copy_nonoverlapping(units.as_ptr(), ptr, units.len());
            ptr
        }
    }

    /// 官方「声明成功却未给出输出指针」不得报成 HRESULT 0x00000000
    ///
    /// 三处调用点(容器检查、取 init 进程句柄、取进程 IO 句柄)曾把
    /// `hr < 0 || ptr.is_null()` 合并为一个分支并统一交给 `from_hresult`,
    /// 于是成功码 0 被当成失败原因报出。此用例锁定分支拆分后的归属。
    #[test]
    fn test_missing_output_is_not_reported_as_success_hresult() {
        let err = WslcError::missing_output("WslcInspectContainer", 0);
        assert!(
            matches!(err, WslcError::UnexpectedSdkResult(_)),
            "契约违背须归入 UnexpectedSdkResult,实际为: {err:?}"
        );
        assert!(!matches!(err, WslcError::Hresult(..)));

        let text = err.to_string();
        assert!(
            text.contains("WslcInspectContainer"),
            "错误须点名接口: {text}"
        );
        assert!(text.contains("0x00000000"), "错误须保留官方返回值: {text}");
        // 不得呈现为「调用失败」——那会把成功码说成失败
        assert!(!text.contains("调用失败"), "实际描述: {text}");
    }

    #[test]
    fn test_hresult_name_coverage() {
        for code in [
            E_ACCESSDENIED,
            E_FAIL,
            CO_E_NOTINITIALIZED,
            RPC_E_CHANGED_MODE,
        ] {
            assert!(
                hresult_name(code as u32).is_some(),
                "0x{:08X} 应有可读名称",
                code as u32
            );
        }
        assert!(hresult_name(0x8004_9999).is_none());
    }

    /// 业务终态与基础设施抖动必须可编程区分
    ///
    /// 这三个变体都曾在实现中被`TaskJoin` 混同。若调用方按「任务失败」
    /// 处理「通知已被消费」,会陷入无效重试——退出码通知本就只投递一次,
    /// 重试永远不会成功。
    #[test]
    fn test_business_terminal_states_are_distinguishable_from_task_failure() {
        // 重复消费:业务终态,调用方重试无意义
        let consumed = WslcError::AlreadyConsumed("进程退出通知".to_string());
        assert!(matches!(consumed, WslcError::AlreadyConsumed(_)));
        assert!(!matches!(consumed, WslcError::TaskJoin(_)));
        assert_eq!(
            consumed.to_string(),
            "进程退出通知已被消费,不可重复获取",
            "错误描述须指出被消费的资源"
        );

        // 通道失联:与任务执行失败区分开
        let channel = WslcError::ChannelTerminated("进程退出通知通道".to_string());
        assert!(matches!(channel, WslcError::ChannelTerminated(_)));
        assert!(!matches!(channel, WslcError::TaskJoin(_)));

        // 三者互不相等,模式匹配可无歧义地区分
        assert_ne!(consumed, channel);
        assert_ne!(consumed, WslcError::TaskJoin("x".to_string()));
    }
}