shiguredo_container 2026.1.0-canary.8

Runtime-agnostic container library for Rust on macOS and Linux
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
//! エラー型。
//!
//! macOS (XPC) の内部エラーは `Error::Other` でラップする。

use std::error::Error as StdError;
use std::fmt;
use std::time::Duration;

use crate::core::ports::ContainerPort;

/// このクレートで使用する結果型。
pub type Result<T> = std::result::Result<T, Error>;

/// `EndOfStream` の表示に含めるログ末尾プレビューの上限バイト数。
const MAX_END_OF_STREAM_PREVIEW_BYTES: usize = 1024;

/// shiguredo_container で発生しうるエラー。
#[derive(Debug)]
pub enum Error {
    /// クライアントエラー。macOS では XPC のエラーもここに入る。
    Client(ClientError),
    /// コンテナが準備完了でない。
    WaitContainer(WaitContainerError),
    /// コンテナが指定ポートを公開していない。
    PortNotExposed {
        /// コンテナ ID。
        id: String,
        /// 公開されていないポート。
        port: ContainerPort,
    },
    /// コンテナの情報が足りない。
    MissingInfo(ContainerMissingInfo),
    /// exec 操作の失敗。
    Exec(ExecError),
    /// I/O エラー。
    Io(std::io::Error),
    /// その他のエラー。
    Other(Box<dyn StdError + Sync + Send>),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Client(e) => write!(f, "client error: {e}"),
            Error::WaitContainer(e) => write!(f, "container is not ready: {e}"),
            Error::PortNotExposed { id, port } => {
                write!(f, "container '{id}' does not expose port {port}")
            }
            Error::MissingInfo(e) => write!(f, "{e}"),
            Error::Exec(e) => write!(f, "exec operation failed: {e}"),
            Error::Io(e) => write!(f, "I/O error: {e}"),
            Error::Other(e) => write!(f, "other error: {e}"),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Client(e) => Some(e),
            Error::WaitContainer(e) => Some(e),
            Error::MissingInfo(e) => Some(e),
            Error::Exec(e) => Some(e),
            Error::Io(e) => Some(e),
            Error::Other(e) => Some(e.as_ref()),
            Error::PortNotExposed { .. } => None,
        }
    }
}

impl From<ClientError> for Error {
    fn from(e: ClientError) -> Self {
        Self::Client(e)
    }
}

impl From<WaitContainerError> for Error {
    fn from(e: WaitContainerError) -> Self {
        Self::WaitContainer(e)
    }
}

impl From<WaitLogError> for Error {
    fn from(e: WaitLogError) -> Self {
        Self::WaitContainer(WaitContainerError::WaitLog(e))
    }
}

impl From<ContainerMissingInfo> for Error {
    fn from(e: ContainerMissingInfo) -> Self {
        Self::MissingInfo(e)
    }
}

impl From<ExecError> for Error {
    fn from(e: ExecError) -> Self {
        Self::Exec(e)
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<tokio::task::JoinError> for Error {
    fn from(e: tokio::task::JoinError) -> Self {
        Self::Other(Box::new(e))
    }
}

/// クライアントエラー。macOS (XPC) では XPC の通信エラー・プロトコルエラーをここに入れる。
#[derive(Debug)]
pub enum ClientError {
    /// XPC の接続失敗。
    XpcConnect,
    /// XPC からエラー応答が返った。
    Xpc(String),
    /// XPC から null 応答が返った。
    XpcNullReply,
    /// XPC 呼び出しがタイムアウトした。
    XpcTimeout,
    /// イメージが見つからない。
    ImageNotFound(String),
    /// コンテナが見つからない。
    ContainerNotFound(String),
    /// コンテナ内のパスが見つからない (コンテナ自体は存在する)。
    ContainerPathNotFound(String),
    /// 設定エラー。
    Configuration(String),
    /// JSON パースエラー。
    Json(String),
    /// その他のクライアントエラー。
    Other(String),
}

impl fmt::Display for ClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ClientError::XpcConnect => write!(f, "XPC connect failed"),
            ClientError::Xpc(s) => write!(f, "XPC error: {s}"),
            ClientError::XpcNullReply => write!(f, "XPC returned null reply"),
            ClientError::XpcTimeout => write!(f, "XPC request timed out"),
            ClientError::ImageNotFound(s) => write!(f, "image not found: {s}"),
            ClientError::ContainerNotFound(s) => write!(f, "container not found: {s}"),
            ClientError::ContainerPathNotFound(s) => write!(f, "container path not found: {s}"),
            ClientError::Configuration(s) => write!(f, "configuration error: {s}"),
            ClientError::Json(s) => write!(f, "JSON parse error: {s}"),
            ClientError::Other(s) => write!(f, "{s}"),
        }
    }
}

impl StdError for ClientError {}

/// コンテナに必要な情報が存在しないことを示すエラー。
#[derive(Debug)]
pub struct ContainerMissingInfo {
    pub(crate) id: String,
    pub(crate) path: String,
}

impl fmt::Display for ContainerMissingInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "container '{}' does not have: {}", self.id, self.path)
    }
}

impl StdError for ContainerMissingInfo {}

/// exec 操作のエラー。
#[derive(Debug)]
pub enum ExecError {
    /// exec プロセスの終了コードが期待値と異なる。
    ExitCodeMismatch {
        /// 期待していた終了コード。
        expected: i64,
        /// 実際の終了コード。
        actual: i64,
    },
    /// exec のログ待機に失敗した。
    WaitLog(WaitLogError),
}

impl fmt::Display for ExecError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExecError::ExitCodeMismatch { expected, actual } => {
                write!(
                    f,
                    "exec process exited with code {actual}, expected {expected}"
                )
            }
            ExecError::WaitLog(e) => write!(f, "failed to wait for exec log: {e}"),
        }
    }
}

impl StdError for ExecError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            ExecError::WaitLog(e) => Some(e),
            ExecError::ExitCodeMismatch { .. } => None,
        }
    }
}

impl From<WaitLogError> for ExecError {
    fn from(e: WaitLogError) -> Self {
        Self::WaitLog(e)
    }
}

/// コンテナ準備完了待機のエラー。
#[derive(Debug)]
pub enum WaitContainerError {
    /// ログ待機に失敗した。
    WaitLog(WaitLogError),
    /// コンテナの状態を取得できない。
    StateUnavailable,
    /// HTTP 待機に失敗した。
    #[cfg(feature = "http_wait_plain")]
    HttpWait(crate::core::wait::http_strategy::HttpWaitError),
    /// ヘルスチェックが設定されていない。
    HealthCheckNotConfigured(String),
    /// コンテナが unhealthy 状態である。
    Unhealthy(String),
    /// コンテナの起動がタイムアウトした。
    StartupTimeout {
        /// コンテナ ID。
        id: String,
        /// タイムアウト時間。
        timeout: Duration,
    },
    /// コンテナが予期しない終了コードで終了した。
    UnexpectedExitCode {
        /// 期待していた終了コード。
        expected: i64,
        /// 実際の終了コード。取得できない場合は `None`。
        actual: Option<i64>,
    },
}

impl fmt::Display for WaitContainerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WaitContainerError::WaitLog(e) => write!(f, "failed to wait for container log: {e}"),
            WaitContainerError::StateUnavailable => write!(f, "container state is unavailable"),
            #[cfg(feature = "http_wait_plain")]
            WaitContainerError::HttpWait(e) => write!(f, "{e}"),
            WaitContainerError::HealthCheckNotConfigured(s) => {
                write!(f, "healthcheck is not configured for container: {s}")
            }
            WaitContainerError::Unhealthy(s) => write!(f, "container is unhealthy: {s}"),
            WaitContainerError::StartupTimeout { id, timeout } => write!(
                f,
                "container startup timeout: container {id} did not become ready within {timeout:?}"
            ),
            WaitContainerError::UnexpectedExitCode { expected, actual } => write!(
                f,
                "container exited with unexpected code: expected {expected}, actual {actual:?}"
            ),
        }
    }
}

impl StdError for WaitContainerError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            WaitContainerError::WaitLog(e) => Some(e),
            WaitContainerError::StateUnavailable => None,
            #[cfg(feature = "http_wait_plain")]
            WaitContainerError::HttpWait(e) => Some(e),
            WaitContainerError::HealthCheckNotConfigured(_) => None,
            WaitContainerError::Unhealthy(_) => None,
            WaitContainerError::StartupTimeout { .. } => None,
            WaitContainerError::UnexpectedExitCode { .. } => None,
        }
    }
}

impl From<WaitLogError> for WaitContainerError {
    fn from(e: WaitLogError) -> Self {
        Self::WaitLog(e)
    }
}

/// ログ待機のエラー。
#[derive(Debug)]
pub enum WaitLogError {
    /// ストリームがメッセージを見つける前に終端に達した。
    /// 診断のため、上限内で保持した直近ログを含める (連結済み、要素は 0 または 1)。
    EndOfStream(Vec<Vec<u8>>),
    /// I/O エラー。
    Io(std::io::Error),
}

impl fmt::Display for WaitLogError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WaitLogError::EndOfStream(chunks) => {
                let total = chunks.iter().map(|c| c.len()).sum::<usize>();
                let mut preview = Vec::new();
                for chunk in chunks.iter().rev() {
                    let remaining = MAX_END_OF_STREAM_PREVIEW_BYTES - preview.len();
                    preview.extend(chunk.iter().rev().take(remaining).copied());
                    if preview.len() == MAX_END_OF_STREAM_PREVIEW_BYTES {
                        break;
                    }
                }
                preview.reverse();
                let preview = String::from_utf8_lossy(&preview);
                write!(
                    f,
                    "end of stream reached before finding message (collected {total} bytes across {} chunks); log preview: {preview}",
                    chunks.len(),
                )
            }
            WaitLogError::Io(e) => write!(f, "I/O error: {e}"),
        }
    }
}

impl StdError for WaitLogError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            WaitLogError::Io(e) => Some(e),
            WaitLogError::EndOfStream(_) => None,
        }
    }
}

impl From<std::io::Error> for WaitLogError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl Error {
    /// 任意のエラーを `Other` で包む。
    pub fn other<E>(error: E) -> Self
    where
        E: Into<Box<dyn StdError + Send + Sync>>,
    {
        Self::Other(error.into())
    }
}

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

    #[test]
    fn error_display_contains_variant_description() {
        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
        let err = Error::Io(io);
        assert!(
            err.to_string().contains("I/O error"),
            "Display がバリアントを表現すること"
        );
    }

    #[test]
    fn error_from_io_is_io_variant() {
        let io = std::io::Error::other("test");
        let err: Error = io.into();
        assert!(
            matches!(err, Error::Io(_)),
            "std::io::Error から Error::Io への変換が正しいこと"
        );
    }

    #[test]
    fn client_error_display_roundtrip() {
        let err = ClientError::ImageNotFound("nginx:latest".into());
        let text = err.to_string();
        assert!(
            text.contains("nginx:latest") && text.contains("image not found"),
            "ClientError::ImageNotFound の Display が画像参照を含むこと"
        );
    }

    #[test]
    fn wait_log_error_end_of_stream_display_contains_counts_and_preview() {
        let chunks = vec![b"hello".to_vec(), b" world".to_vec()];
        let err = WaitLogError::EndOfStream(chunks);
        let text = err.to_string();
        assert!(
            text.contains("11 bytes")
                && text.contains("2 chunks")
                && text.contains("log preview: hello world"),
            "EndOfStream の Display がチャンク数、合計バイト数、ログプレビューを含むこと: {text}"
        );
    }

    #[test]
    fn wait_log_error_end_of_stream_display_limits_preview_to_tail() {
        let chunks = vec![
            vec![b'a'; MAX_END_OF_STREAM_PREVIEW_BYTES],
            b"tail".to_vec(),
        ];
        let err = WaitLogError::EndOfStream(chunks);
        let text = err.to_string();
        assert!(
            text.contains("log preview: ") && text.ends_with("tail"),
            "EndOfStream の Display がログ末尾を含むこと: {text}"
        );
        assert!(
            !text.contains(&"a".repeat(MAX_END_OF_STREAM_PREVIEW_BYTES)),
            "EndOfStream の Display がプレビュー上限を超える先頭ログを含まないこと: {text}"
        );
    }

    #[test]
    fn wait_log_error_source_is_io_error() {
        let io = std::io::Error::other("io failed");
        let err = WaitLogError::Io(io);
        assert!(
            err.source().is_some(),
            "WaitLogError::Io は source を持つこと"
        );
    }

    #[test]
    fn exec_error_wait_log_roundtrip() {
        let wait = WaitLogError::EndOfStream(vec![b"x".to_vec()]);
        let exec: ExecError = wait.into();
        assert!(
            matches!(exec, ExecError::WaitLog(_)),
            "WaitLogError から ExecError::WaitLog への変換が正しいこと"
        );
        assert!(
            exec.source().is_some(),
            "ExecError::WaitLog は source を持つこと"
        );
    }

    #[test]
    fn container_missing_info_display_contains_id_and_path() {
        let info = ContainerMissingInfo {
            id: "abc".to_owned(),
            path: "bridge ip".to_owned(),
        };
        let text = info.to_string();
        assert!(
            text.contains("abc") && text.contains("bridge ip"),
            "ContainerMissingInfo の Display が id と path を含むこと"
        );
    }

    #[test]
    fn wait_container_error_from_wait_log() {
        let wait = WaitLogError::EndOfStream(Vec::new());
        let err: WaitContainerError = wait.into();
        assert!(
            matches!(err, WaitContainerError::WaitLog(_)),
            "WaitLogError から WaitContainerError::WaitLog への変換が正しいこと"
        );
    }

    #[cfg(feature = "http_wait_plain")]
    #[test]
    fn http_wait_error_has_source_and_single_outer_prefix() {
        let err = Error::WaitContainer(WaitContainerError::HttpWait(
            crate::core::wait::HttpWaitError::NoResponseMatcher,
        ));
        let text = err.to_string();
        assert!(
            err.source().is_some(),
            "WaitContainerError::HttpWait は source を持つこと"
        );
        assert_eq!(
            text.matches("container is not ready:").count(),
            1,
            "HttpWait の Display は外側のプレフィックスだけを含むこと: {text}"
        );
    }

    #[test]
    fn startup_timeout_display_contains_id_and_timeout() {
        let err = WaitContainerError::StartupTimeout {
            id: "test-container".into(),
            timeout: Duration::from_secs(2),
        };
        let text = err.to_string();
        assert!(
            text.contains("test-container") && text.contains("2s"),
            "StartupTimeout の Display がコンテナ ID と timeout を含むこと: {text}"
        );
    }
}