linger-openai-sdk 0.1.1

Rust-native async SDK for OpenAI APIs with typed requests, streaming, uploads, retries, and pluggable transports.
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
use crate::transport::{BodyStream, HttpRequest};
use crate::LingerError;
use crate::RequestId;
use bytes::Bytes;
use serde::{Deserialize, Serialize};

/// EN: Video job metadata returned by the Videos API.
/// 中文:Videos API 返回的视频任务元数据。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct Video {
    /// EN: Unique video job identifier.
    /// 中文:唯一的视频任务标识符。
    pub id: String,
    /// EN: API object type, normally `video`.
    /// 中文:API 对象类型,通常为 `video`。
    pub object: String,
    /// EN: Video generation model that produced the job.
    /// 中文:生成该任务的视频模型。
    pub model: String,
    /// EN: Current lifecycle status for the video job.
    /// 中文:视频任务当前生命周期状态。
    pub status: String,
    /// EN: Approximate completion percentage.
    /// 中文:近似完成百分比。
    pub progress: u32,
    /// EN: Unix timestamp for when the job was created.
    /// 中文:任务创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Unix timestamp for completion, when finished.
    /// 中文:任务完成时间的 Unix 时间戳,如已完成。
    pub completed_at: Option<u64>,
    /// EN: Unix timestamp for downloadable asset expiration, when set.
    /// 中文:可下载资产过期时间的 Unix 时间戳,如已设置。
    pub expires_at: Option<u64>,
    /// EN: Prompt used to generate the video, when available.
    /// 中文:用于生成视频的提示词,如可用。
    pub prompt: Option<String>,
    /// EN: Resolution of the generated video.
    /// 中文:生成视频的分辨率。
    pub size: String,
    /// EN: Duration of the generated clip in seconds.
    /// 中文:生成片段的秒数。
    pub seconds: String,
    /// EN: Source video id when this video is a remix.
    /// 中文:当该视频为 remix 时的源视频 ID。
    pub remixed_from_video_id: Option<String>,
    /// EN: Error payload when video generation failed.
    /// 中文:视频生成失败时的错误载荷。
    pub error: Option<VideoError>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl Video {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Page of videos returned by `GET /v1/videos`.
/// 中文:`GET /v1/videos` 返回的视频分页。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VideoPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Videos on this page.
    /// 中文:本页视频。
    #[serde(default)]
    pub data: Vec<Video>,
    /// EN: First video id on this page.
    /// 中文:本页第一个视频 ID。
    pub first_id: Option<String>,
    /// EN: Last video id on this page.
    /// 中文:本页最后一个视频 ID。
    pub last_id: Option<String>,
    /// EN: Whether more videos are available.
    /// 中文:是否还有更多视频。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VideoPage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: JSON request body for `POST /v1/videos`.
/// 中文:`POST /v1/videos` 的 JSON 请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateVideoRequest {
    /// EN: Text prompt that describes the video to generate.
    /// 中文:描述要生成视频的文本提示词。
    pub prompt: String,
    /// EN: Optional video generation model.
    /// 中文:可选的视频生成模型。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// EN: Optional reference object that guides generation.
    /// 中文:可选的参考对象,用于引导生成。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_reference: Option<serde_json::Value>,
    /// EN: Optional clip duration in seconds as a documented string value.
    /// 中文:可选的视频秒数,使用文档中的字符串值。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seconds: Option<String>,
    /// EN: Optional output resolution.
    /// 中文:可选的输出分辨率。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<String>,
}

impl CreateVideoRequest {
    /// EN: Returns a builder for video creation requests.
    /// 中文:返回 video 创建请求的构建器。
    pub fn builder() -> CreateVideoRequestBuilder {
        CreateVideoRequestBuilder::default()
    }
}

/// EN: Builder for `CreateVideoRequest`.
/// 中文:`CreateVideoRequest` 的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVideoRequestBuilder {
    prompt: Option<String>,
    model: Option<String>,
    input_reference: Option<serde_json::Value>,
    seconds: Option<String>,
    size: Option<String>,
}

impl CreateVideoRequestBuilder {
    /// EN: Sets the prompt for video generation.
    /// 中文:设置视频生成提示词。
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// EN: Sets the optional video generation model.
    /// 中文:设置可选的视频生成模型。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets an optional reference object that guides generation.
    /// 中文:设置可选的参考对象,用于引导生成。
    pub fn input_reference(mut self, input_reference: serde_json::Value) -> Self {
        self.input_reference = Some(input_reference);
        self
    }

    /// EN: Sets the optional clip duration in seconds.
    /// 中文:设置可选的视频秒数。
    pub fn seconds(mut self, seconds: impl Into<String>) -> Self {
        self.seconds = Some(seconds.into());
        self
    }

    /// EN: Sets the optional output resolution.
    /// 中文:设置可选的输出分辨率。
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// EN: Builds a validated video creation request.
    /// 中文:构建经过校验的视频创建请求。
    pub fn build(self) -> Result<CreateVideoRequest, LingerError> {
        let prompt = self
            .prompt
            .ok_or_else(|| LingerError::invalid_config("prompt is required"))?;
        if prompt.trim().is_empty() {
            return Err(LingerError::invalid_config("prompt must not be empty"));
        }
        Ok(CreateVideoRequest {
            prompt,
            model: self.model,
            input_reference: self.input_reference,
            seconds: self.seconds,
            size: self.size,
        })
    }
}

/// EN: Reference to a completed video used by JSON video APIs.
/// 中文:JSON video API 使用的已完成视频引用。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VideoReferenceInput {
    /// EN: Completed video identifier.
    /// 中文:已完成视频的标识符。
    pub id: String,
}

impl VideoReferenceInput {
    /// EN: Creates a validated video reference from an id.
    /// 中文:根据 ID 创建经过校验的视频引用。
    pub fn new(id: impl Into<String>) -> Result<Self, LingerError> {
        let id = id.into();
        let id = id.trim();
        if id.is_empty() {
            return Err(LingerError::invalid_config("video id is required"));
        }
        Ok(Self { id: id.to_owned() })
    }
}

/// EN: JSON request body for `POST /v1/videos/edits`.
/// 中文:`POST /v1/videos/edits` 的 JSON 请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateVideoEditRequest {
    /// EN: Completed video to edit.
    /// 中文:要编辑的已完成视频。
    pub video: VideoReferenceInput,
    /// EN: Text prompt describing how to edit the source video.
    /// 中文:描述如何编辑源视频的文本提示词。
    pub prompt: String,
}

impl CreateVideoEditRequest {
    /// EN: Returns a builder for video edit requests.
    /// 中文:返回 video edit 请求的构建器。
    pub fn builder() -> CreateVideoEditRequestBuilder {
        CreateVideoEditRequestBuilder::default()
    }
}

/// EN: Builder for `CreateVideoEditRequest`.
/// 中文:`CreateVideoEditRequest` 的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVideoEditRequestBuilder {
    video: Option<VideoReferenceInput>,
    prompt: Option<String>,
}

impl CreateVideoEditRequestBuilder {
    /// EN: Sets the completed video id to edit.
    /// 中文:设置要编辑的已完成视频 ID。
    pub fn video_id(mut self, video_id: impl Into<String>) -> Self {
        self.video = VideoReferenceInput::new(video_id).ok();
        self
    }

    /// EN: Sets the prompt describing how to edit the source video.
    /// 中文:设置描述如何编辑源视频的提示词。
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// EN: Builds a validated video edit request.
    /// 中文:构建经过校验的视频编辑请求。
    pub fn build(self) -> Result<CreateVideoEditRequest, LingerError> {
        let video = self
            .video
            .ok_or_else(|| LingerError::invalid_config("video id is required"))?;
        let prompt = self
            .prompt
            .ok_or_else(|| LingerError::invalid_config("prompt is required"))?;
        if prompt.trim().is_empty() {
            return Err(LingerError::invalid_config("prompt must not be empty"));
        }
        Ok(CreateVideoEditRequest { video, prompt })
    }
}

/// EN: JSON request body for `POST /v1/videos/extensions`.
/// 中文:`POST /v1/videos/extensions` 的 JSON 请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateVideoExtensionRequest {
    /// EN: Completed video to extend.
    /// 中文:要扩展的已完成视频。
    pub video: VideoReferenceInput,
    /// EN: Updated prompt that directs the extension generation.
    /// 中文:用于指导扩展生成的更新提示词。
    pub prompt: String,
    /// EN: Length of the newly generated extension segment in seconds.
    /// 中文:新生成扩展片段的秒数。
    pub seconds: String,
}

impl CreateVideoExtensionRequest {
    /// EN: Returns a builder for video extension requests.
    /// 中文:返回 video extension 请求的构建器。
    pub fn builder() -> CreateVideoExtensionRequestBuilder {
        CreateVideoExtensionRequestBuilder::default()
    }
}

/// EN: Builder for `CreateVideoExtensionRequest`.
/// 中文:`CreateVideoExtensionRequest` 的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVideoExtensionRequestBuilder {
    video: Option<VideoReferenceInput>,
    prompt: Option<String>,
    seconds: Option<String>,
}

impl CreateVideoExtensionRequestBuilder {
    /// EN: Sets the completed video id to extend.
    /// 中文:设置要扩展的已完成视频 ID。
    pub fn video_id(mut self, video_id: impl Into<String>) -> Self {
        self.video = VideoReferenceInput::new(video_id).ok();
        self
    }

    /// EN: Sets the prompt that directs the extension generation.
    /// 中文:设置指导扩展生成的提示词。
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// EN: Sets the extension duration in seconds.
    /// 中文:设置扩展片段的秒数。
    pub fn seconds(mut self, seconds: impl Into<String>) -> Self {
        self.seconds = Some(seconds.into());
        self
    }

    /// EN: Builds a validated video extension request.
    /// 中文:构建经过校验的视频扩展请求。
    pub fn build(self) -> Result<CreateVideoExtensionRequest, LingerError> {
        let video = self
            .video
            .ok_or_else(|| LingerError::invalid_config("video id is required"))?;
        let prompt = self
            .prompt
            .ok_or_else(|| LingerError::invalid_config("prompt is required"))?;
        if prompt.trim().is_empty() {
            return Err(LingerError::invalid_config("prompt must not be empty"));
        }
        let seconds = self
            .seconds
            .ok_or_else(|| LingerError::invalid_config("seconds is required"))?;
        if seconds.trim().is_empty() {
            return Err(LingerError::invalid_config("seconds must not be empty"));
        }
        Ok(CreateVideoExtensionRequest {
            video,
            prompt,
            seconds,
        })
    }
}

/// EN: Request body for `POST /v1/videos/{video_id}/remix`.
/// 中文:`POST /v1/videos/{video_id}/remix` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateVideoRemixRequest {
    /// EN: Updated prompt that directs the remix generation.
    /// 中文:用于指导 remix 生成的更新提示词。
    pub prompt: String,
}

impl CreateVideoRemixRequest {
    /// EN: Returns a builder for video remix requests.
    /// 中文:返回 video remix 请求构建器。
    pub fn builder() -> CreateVideoRemixRequestBuilder {
        CreateVideoRemixRequestBuilder::default()
    }
}

/// EN: Builder for `CreateVideoRemixRequest`.
/// 中文:`CreateVideoRemixRequest` 的构建器。
#[derive(Clone, Debug, Default)]
pub struct CreateVideoRemixRequestBuilder {
    prompt: Option<String>,
}

impl CreateVideoRemixRequestBuilder {
    /// EN: Sets the updated prompt for the remix.
    /// 中文:设置 remix 的更新提示词。
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// EN: Builds a validated video remix request.
    /// 中文:构建经过校验的 video remix 请求。
    pub fn build(self) -> Result<CreateVideoRemixRequest, LingerError> {
        let prompt = self
            .prompt
            .ok_or_else(|| LingerError::invalid_config("prompt is required"))?;
        if prompt.trim().is_empty() {
            return Err(LingerError::invalid_config("prompt must not be empty"));
        }
        Ok(CreateVideoRemixRequest { prompt })
    }
}

/// EN: Uploadable video file bytes and multipart metadata.
/// 中文:可上传视频文件字节及 multipart 元数据。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct VideoUpload {
    /// EN: Filename sent in the multipart part.
    /// 中文:multipart 分段中发送的文件名。
    pub filename: String,
    /// EN: Content type sent for the video part.
    /// 中文:视频分段发送的内容类型。
    pub content_type: String,
    content: Bytes,
}

impl VideoUpload {
    /// EN: Creates an upload from already available bytes without copying them.
    /// 中文:通过已可用字节创建上传对象,不复制这些字节。
    pub fn from_bytes(
        filename: impl Into<String>,
        content: impl Into<Bytes>,
    ) -> Result<Self, LingerError> {
        let filename = filename.into();
        validate_header_param("filename", &filename)?;
        Ok(Self {
            filename,
            content_type: "application/octet-stream".to_string(),
            content: content.into(),
        })
    }

    /// EN: Sets the video part content type.
    /// 中文:设置视频分段的内容类型。
    pub fn content_type(mut self, content_type: impl Into<String>) -> Result<Self, LingerError> {
        let content_type = content_type.into();
        validate_header_value("content_type", &content_type)?;
        self.content_type = content_type;
        Ok(self)
    }

    /// EN: Returns the video bytes as a cheap `Bytes` clone.
    /// 中文:以廉价 `Bytes` 克隆返回视频字节。
    pub fn bytes(&self) -> Bytes {
        self.content.clone()
    }
}

/// EN: Request body for `POST /v1/videos/characters`.
/// 中文:`POST /v1/videos/characters` 的请求体。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateVideoCharacterRequest {
    /// EN: Display name for the created character.
    /// 中文:创建后角色的显示名称。
    pub name: String,
    /// EN: Uploaded video used to create the character.
    /// 中文:用于创建角色的上传视频。
    pub video: VideoUpload,
}

impl CreateVideoCharacterRequest {
    /// EN: Starts building a video character creation request.
    /// 中文:开始构建 video character 创建请求。
    pub fn builder() -> CreateVideoCharacterRequestBuilder {
        CreateVideoCharacterRequestBuilder::default()
    }

    pub(crate) fn apply_multipart_body(&self, request: &mut HttpRequest) {
        let boundary = video_multipart_boundary(&self.name, &self.video.content);
        request.insert_header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        );
        request.set_body_stream(self.multipart_stream(boundary));
    }

    fn multipart_stream(
        &self,
        boundary: String,
    ) -> impl futures_core::Stream<Item = Result<Bytes, LingerError>> {
        let mut chunks = Vec::new();
        chunks.push(Ok(Bytes::from(format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\n{}\r\n",
            self.name
        ))));
        chunks.push(Ok(Bytes::from(format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"video\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
            escape_multipart_param(&self.video.filename),
            self.video.content_type
        ))));
        chunks.push(Ok(self.video.content.clone()));
        chunks.push(Ok(Bytes::from(format!("\r\n--{boundary}--\r\n"))));
        futures_util::stream::iter(chunks)
    }
}

/// EN: Builder for video character creation requests.
/// 中文:video character 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVideoCharacterRequestBuilder {
    name: Option<String>,
    video: Option<VideoUpload>,
}

impl CreateVideoCharacterRequestBuilder {
    /// EN: Sets the display name for the character.
    /// 中文:设置角色显示名称。
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// EN: Sets the uploaded video used to create the character.
    /// 中文:设置用于创建角色的上传视频。
    pub fn video(mut self, video: VideoUpload) -> Self {
        self.video = Some(video);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateVideoCharacterRequest, LingerError> {
        let name = self
            .name
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| LingerError::invalid_config("name is required"))?;
        let video = self
            .video
            .ok_or_else(|| LingerError::invalid_config("video is required"))?;
        Ok(CreateVideoCharacterRequest { name, video })
    }
}

/// EN: Video character metadata returned by the Videos API.
/// 中文:Videos API 返回的视频角色元数据。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VideoCharacter {
    /// EN: Character identifier, when available.
    /// 中文:角色标识符,如可用。
    pub id: Option<String>,
    /// EN: Character display name, when available.
    /// 中文:角色显示名称,如可用。
    pub name: Option<String>,
    /// EN: Unix timestamp for when the character was created.
    /// 中文:角色创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VideoCharacter {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Error payload embedded in failed video jobs.
/// 中文:失败视频任务中嵌入的错误载荷。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VideoError {
    /// EN: Machine-readable error code.
    /// 中文:机器可读的错误代码。
    pub code: String,
    /// EN: Human-readable error message.
    /// 中文:人类可读的错误消息。
    pub message: String,
}

/// EN: Deletion result returned by `DELETE /v1/videos/{video_id}`.
/// 中文:`DELETE /v1/videos/{video_id}` 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VideoDeletion {
    /// EN: API object type, normally `video.deleted`.
    /// 中文:API 对象类型,通常为 `video.deleted`。
    pub object: String,
    /// EN: Whether the video was deleted.
    /// 中文:视频是否已删除。
    pub deleted: bool,
    /// EN: Deleted video id.
    /// 中文:已删除的视频 ID。
    pub id: String,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VideoDeletion {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Incremental video content response.
/// 中文:增量视频内容响应。
pub struct VideoContent {
    request_id: Option<RequestId>,
    body: BodyStream,
}

impl VideoContent {
    pub(crate) fn new(request_id: Option<RequestId>, body: BodyStream) -> Self {
        Self { request_id, body }
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }

    /// EN: Consumes this response and returns the incremental content stream.
    /// 中文:消耗此响应并返回增量内容流。
    pub fn into_stream(self) -> BodyStream {
        self.body
    }
}

/// EN: Downloadable video content variant.
/// 中文:可下载的视频内容变体。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum VideoContentVariant {
    /// EN: Rendered MP4 video.
    /// 中文:渲染后的 MP4 视频。
    Video,
    /// EN: Thumbnail preview image.
    /// 中文:缩略图预览图片。
    Thumbnail,
    /// EN: Spritesheet preview image.
    /// 中文:精灵图预览图片。
    Spritesheet,
}

impl VideoContentVariant {
    pub(crate) fn as_query_value(self) -> &'static str {
        match self {
            Self::Video => "video",
            Self::Thumbnail => "thumbnail",
            Self::Spritesheet => "spritesheet",
        }
    }
}

fn video_multipart_boundary(name: &str, content: &Bytes) -> String {
    for counter in 0.. {
        let boundary = format!("linger-openai-sdk-video-boundary-{counter}");
        let boundary_bytes = boundary.as_bytes();
        if !contains_bytes(name.as_bytes(), boundary_bytes)
            && !contains_bytes(content, boundary_bytes)
        {
            return boundary;
        }
    }
    unreachable!("unbounded boundary counter")
}

fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() {
        return true;
    }
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

fn validate_header_param(name: &str, value: &str) -> Result<(), LingerError> {
    if value.trim().is_empty() {
        return Err(LingerError::invalid_config(format!("{name} is required")));
    }
    validate_header_value(name, value)
}

fn validate_header_value(name: &str, value: &str) -> Result<(), LingerError> {
    if value.contains('\r') || value.contains('\n') {
        return Err(LingerError::invalid_config(format!(
            "{name} must not contain CR or LF"
        )));
    }
    Ok(())
}

fn escape_multipart_param(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}