mixi2 0.1.1

Async Rust SDK for the mixi2 Application API.
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Async Rust SDK for the mixi2 Application API.
//!
//! This crate combines the complete SDK surface into a single package:
//! - `OAuth2` client-credentials authentication via [`ClientCredentialsAuthenticator`]
//! - Authenticated unary gRPC access via [`ApiClient`] and [`ApiClientBuilder`]
//! - Webhook and streaming event helpers via [`WebhookService`], [`WebhookServer`], and
//!   [`StreamClientBuilder`]
//! - Raw generated `prost` and `tonic` types under [`social`] plus [`FILE_DESCRIPTOR_SET`]
//!
//! The public API is async-only and designed for Tokio runtimes. Generated protobuf types remain
//! visible so callers can keep full protocol fidelity, while the builders in this crate add
//! validation only where the mixi2 API requires it.
//!
//! # Quick Start
//!
//! ```no_run
//! # #[cfg(all(feature = "api", feature = "client-credentials-auth"))]
//! use std::sync::Arc;
//! # #[cfg(all(feature = "api", feature = "client-credentials-auth"))]
//! use mixi2::{ApiClientBuilder, ClientCredentialsAuthenticator, GetStampsRequestBuilder};
//! # #[cfg(all(feature = "api", feature = "client-credentials-auth"))]
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let authenticator =
//!         Arc::new(ClientCredentialsAuthenticator::new("client-id", "client-secret").await?);
//!
//!     let mut client = ApiClientBuilder::new(authenticator).build().await?;
//!
//!     let _stamps = client
//!         .get_stamps(GetStampsRequestBuilder::new().build())
//!         .await?;
//!
//!     Ok(())
//! }
//! # #[cfg(not(all(feature = "api", feature = "client-credentials-auth")))]
//! # fn main() {}
//! ```
//!
//! # Raw Protocol Types
//!
//! The generated protobuf and gRPC types are re-exported under [`social`]. Reach for them when you
//! need direct access to the mixi2 schema or an RPC/request shape that does not need a convenience
//! builder.
//!
//! # Event Delivery
//!
//! Use [`WebhookService`] and [`WebhookServer`] for signed webhook delivery, or
//! [`StreamClientBuilder`] together with [`EventHandler`] for long-lived gRPC event streams.

#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "stream")]
use std::future::ready;
#[cfg(any(feature = "api", feature = "stream"))]
use std::sync::Arc;

mod auth;
mod events;
mod proto;

use crate::proto::social::mixi::application::{
    r#const::v1::{LanguageCode, PostPublishingType},
    model::v1::PostMask,
    service::application_api::v1::{
        self as application_api_v1, AddStampToPostRequest, CreatePostRequest, DeletePostRequest,
        GetStampsRequest, InitiatePostMediaUploadRequest, SendChatMessageRequest,
    },
};
#[cfg(feature = "api")]
use crate::proto::social::mixi::application::service::application_api::v1::{
    AddStampToPostResponse, CreatePostResponse, DeletePostResponse, GetPostMediaStatusRequest,
    GetPostMediaStatusResponse, GetPostsRequest, GetPostsResponse, GetStampsResponse,
    GetUsersRequest, GetUsersResponse, InitiatePostMediaUploadResponse,
    SendChatMessageResponse,
    application_service_client::ApplicationServiceClient as RawApiClient,
};
#[cfg(feature = "stream")]
use crate::proto::social::mixi::application::service::application_stream::v1::application_service_client::ApplicationServiceClient as RawStreamClient;
#[cfg(feature = "api")]
use crate::auth::AuthError as AuthLayerError;
#[cfg(any(feature = "api", feature = "stream"))]
use crate::auth::Authenticator as AuthenticatorTrait;
#[cfg(feature = "stream")]
use crate::events::StreamWatcher as EventStreamWatcher;
use thiserror::Error;
#[cfg(feature = "api")]
use tonic::{
    IntoRequest, Request, Response, Status,
    body::Body as TransportBody,
    client::GrpcService,
    codegen::{Body, Bytes as TonicBytes, StdError},
};
#[cfg(any(feature = "api", feature = "stream"))]
use tonic::transport::{Channel, Endpoint, Error as TransportError};

#[cfg(feature = "api")]
/// Official mixi2 Application API endpoint for unary SDK clients.
///
/// This endpoint is used automatically when builders are created without an
/// explicit `with_endpoint` or `with_channel` transport override.
pub const DEFAULT_API_ENDPOINT: &str = "https://application-api.mixi.social";

#[cfg(feature = "stream")]
/// Official mixi2 Application stream endpoint for event streaming clients.
///
/// This endpoint is used automatically when stream builders are created without
/// an explicit `with_endpoint` or `with_channel` transport override.
pub const DEFAULT_STREAM_ENDPOINT: &str = "https://application-stream.mixi.social";

pub use crate::auth::{AuthError, Authenticator};
#[cfg(feature = "client-credentials-auth")]
pub use crate::auth::{AuthenticatorBuilder, ClientCredentialsAuthenticator, DEFAULT_TOKEN_URL};
#[cfg(any(feature = "stream", feature = "webhook-core", feature = "testutil"))]
pub use crate::events::BoxError;
#[cfg(any(feature = "stream", feature = "webhook-core", feature = "testutil"))]
pub use crate::events::EventHandler;
#[cfg(feature = "webhook-axum")]
pub use crate::events::WebhookServer;
#[cfg(feature = "testutil")]
pub use crate::events::testutil;
#[cfg(feature = "webhook-core")]
pub use crate::events::{DispatchMode, WebhookError, WebhookService};
#[cfg(feature = "stream")]
pub use crate::events::{StreamWatcher, StreamWatcherError};
pub use crate::proto::{FILE_DESCRIPTOR_SET, social};

/// Validation errors returned by the high-level request builders.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum RequestValidationError {
    #[error("in_reply_to_post_id and quoted_post_id cannot both be set")]
    ConflictingPostTargets,
    #[error("media_id_list can contain at most 4 entries")]
    TooManyMediaIds,
    #[error("room_id must not be empty")]
    EmptyRoomId,
    #[error("post_id must not be empty")]
    EmptyPostId,
    #[error("stamp_id must not be empty")]
    EmptyStampId,
    #[error("send chat message requires text or media_id")]
    MissingChatPayload,
    #[error("content_type must not be empty")]
    EmptyContentType,
    #[error("data_size must be greater than zero")]
    EmptyUploadSize,
    #[error("media_type must not be unspecified")]
    UnspecifiedUploadType,
}

#[cfg(any(feature = "api", feature = "stream"))]
/// Transport setup errors returned by the top-level builders.
#[derive(Debug, Error)]
pub enum ClientBuildError {
    #[error("channel and endpoint are mutually exclusive")]
    ConflictingTransport,
    #[error("failed to configure transport endpoint")]
    Transport(#[source] TransportError),
}

#[cfg(feature = "api")]
/// Authenticated façade over the raw unary gRPC client.
pub struct ApiClient<T> {
    authenticator: Arc<dyn AuthenticatorTrait>,
    inner: RawApiClient<T>,
}

#[cfg(feature = "api")]
impl<T> ApiClient<T>
where
    T: GrpcService<TransportBody> + Send + Sync,
    T::Error: Into<StdError>,
    T::Future: Send,
    T::ResponseBody: Body<Data = TonicBytes> + Send + 'static,
    <T::ResponseBody as Body>::Error: Into<StdError> + Send,
{
    /// Creates a new authenticated API client wrapper.
    #[must_use]
    pub fn new(inner: RawApiClient<T>, authenticator: Arc<dyn AuthenticatorTrait>) -> Self {
        Self {
            authenticator,
            inner,
        }
    }

    /// Returns a shared reference to the raw client.
    #[must_use]
    pub const fn inner(&self) -> &RawApiClient<T> {
        &self.inner
    }

    /// Returns a mutable reference to the raw client.
    #[must_use]
    pub const fn inner_mut(&mut self) -> &mut RawApiClient<T> {
        &mut self.inner
    }

    /// Consumes the wrapper and returns the raw client.
    #[must_use]
    pub fn into_inner(self) -> RawApiClient<T> {
        self.inner
    }

    /// Calls `GetUsers`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn get_users(
        &mut self,
        request: impl IntoRequest<GetUsersRequest> + Send,
    ) -> Result<Response<GetUsersResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.get_users(request).await
    }

    /// Calls `GetPosts`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn get_posts(
        &mut self,
        request: impl IntoRequest<GetPostsRequest> + Send,
    ) -> Result<Response<GetPostsResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.get_posts(request).await
    }

    /// Calls `CreatePost`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn create_post(
        &mut self,
        request: impl IntoRequest<CreatePostRequest> + Send,
    ) -> Result<Response<CreatePostResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.create_post(request).await
    }

    /// Calls `DeletePost`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn delete_post(
        &mut self,
        request: impl IntoRequest<DeletePostRequest> + Send,
    ) -> Result<Response<DeletePostResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.delete_post(request).await
    }

    /// Calls `InitiatePostMediaUpload`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn initiate_post_media_upload(
        &mut self,
        request: impl IntoRequest<InitiatePostMediaUploadRequest> + Send,
    ) -> Result<Response<InitiatePostMediaUploadResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.initiate_post_media_upload(request).await
    }

    /// Calls `GetPostMediaStatus`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn get_post_media_status(
        &mut self,
        request: impl IntoRequest<GetPostMediaStatusRequest> + Send,
    ) -> Result<Response<GetPostMediaStatusResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.get_post_media_status(request).await
    }

    /// Calls `SendChatMessage`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn send_chat_message(
        &mut self,
        request: impl IntoRequest<SendChatMessageRequest> + Send,
    ) -> Result<Response<SendChatMessageResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.send_chat_message(request).await
    }

    /// Calls `GetStamps`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn get_stamps(
        &mut self,
        request: impl IntoRequest<GetStampsRequest> + Send,
    ) -> Result<Response<GetStampsResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.get_stamps(request).await
    }

    /// Calls `AddStampToPost`.
    ///
    /// # Errors
    ///
    /// Returns `Status::unauthenticated` when token acquisition fails, or the RPC status
    /// returned by the upstream server.
    pub async fn add_stamp_to_post(
        &mut self,
        request: impl IntoRequest<AddStampToPostRequest> + Send,
    ) -> Result<Response<AddStampToPostResponse>, Status> {
        let request = self.authorize_request(request).await?;
        self.inner.add_stamp_to_post(request).await
    }

    async fn authorize_request<R: Send>(
        &self,
        request: impl IntoRequest<R> + Send,
    ) -> Result<Request<R>, Status> {
        let mut request = request.into_request();
        self.authenticator
            .authorize(request.metadata_mut())
            .await
            .map_err(|error| auth_error_to_status(&error))?;
        Ok(request)
    }
}

#[cfg(feature = "api")]
/// Builder for an authenticated unary client.
pub struct ApiClientBuilder {
    authenticator: Arc<dyn AuthenticatorTrait>,
    channel: Option<Channel>,
    endpoint: Option<String>,
}

#[cfg(feature = "api")]
impl ApiClientBuilder {
    /// Creates a new builder for the given authenticator.
    #[must_use]
    pub fn new(authenticator: Arc<dyn AuthenticatorTrait>) -> Self {
        Self {
            authenticator,
            channel: None,
            endpoint: None,
        }
    }

    /// Injects an already-connected channel.
    #[must_use]
    pub fn with_channel(mut self, channel: Channel) -> Self {
        self.channel = Some(channel);
        self
    }

    /// Connects to the given endpoint when `build` is called.
    #[must_use]
    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = Some(endpoint.into());
        self
    }

    /// Builds the authenticated unary client wrapper.
    ///
    /// # Errors
    ///
    /// Returns an error when both channel and endpoint were configured, or when
    /// endpoint connection setup fails.
    pub async fn build(self) -> Result<ApiClient<Channel>, ClientBuildError> {
        let channel = resolve_channel(self.channel, self.endpoint, DEFAULT_API_ENDPOINT).await?;
        let raw_client = RawApiClient::new(channel);
        Ok(ApiClient::new(raw_client, self.authenticator))
    }
}

#[cfg(feature = "stream")]
/// Builder for an authenticated stream watcher.
pub struct StreamClientBuilder {
    authenticator: Arc<dyn AuthenticatorTrait>,
    channel: Option<Channel>,
    endpoint: Option<String>,
}

#[cfg(feature = "stream")]
impl StreamClientBuilder {
    /// Creates a new builder for the given authenticator.
    #[must_use]
    pub fn new(authenticator: Arc<dyn AuthenticatorTrait>) -> Self {
        Self {
            authenticator,
            channel: None,
            endpoint: None,
        }
    }

    /// Injects an already-connected channel.
    #[must_use]
    pub fn with_channel(mut self, channel: Channel) -> Self {
        self.channel = Some(channel);
        self
    }

    /// Connects to the given endpoint when `build` is called.
    #[must_use]
    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = Some(endpoint.into());
        self
    }

    /// Builds the stream watcher.
    ///
    /// # Errors
    ///
    /// Returns an error when both channel and endpoint were configured, or when
    /// endpoint connection setup fails.
    pub async fn build(self) -> Result<EventStreamWatcher, ClientBuildError> {
        let watcher = match (self.channel, self.endpoint) {
            (Some(_), Some(_)) => Err(ClientBuildError::ConflictingTransport),
            (Some(channel), None) => {
                let raw_client = RawStreamClient::new(channel);
                Ok(EventStreamWatcher::new(raw_client, self.authenticator))
            }
            (None, endpoint) => {
                let endpoint = Endpoint::new(resolve_endpoint(endpoint, DEFAULT_STREAM_ENDPOINT))
                    .map_err(ClientBuildError::Transport)?;
                let raw_client = events::http_stream_client(endpoint.uri().clone());
                Ok(EventStreamWatcher::new(raw_client, self.authenticator))
            }
        };

        ready(watcher).await
    }
}

/// Builder for `CreatePostRequest`.
#[derive(Clone, Debug)]
pub struct CreatePostRequestBuilder {
    request: CreatePostRequest,
}

impl CreatePostRequestBuilder {
    /// Creates a new builder with the required post text field.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            request: CreatePostRequest {
                text: text.into(),
                in_reply_to_post_id: None,
                quoted_post_id: None,
                media_id_list: Vec::new(),
                post_mask: None,
                publishing_type: None,
            },
        }
    }

    /// Sets the reply target.
    #[must_use]
    pub fn in_reply_to_post_id(mut self, post_id: impl Into<String>) -> Self {
        self.request.in_reply_to_post_id = Some(post_id.into());
        self
    }

    /// Sets the quoted post target.
    #[must_use]
    pub fn quoted_post_id(mut self, post_id: impl Into<String>) -> Self {
        self.request.quoted_post_id = Some(post_id.into());
        self
    }

    /// Appends one media identifier.
    #[must_use]
    pub fn push_media_id(mut self, media_id: impl Into<String>) -> Self {
        self.request.media_id_list.push(media_id.into());
        self
    }

    /// Replaces the media identifier list.
    #[must_use]
    pub fn media_ids<I, S>(mut self, media_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.request.media_id_list = media_ids.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the optional post mask.
    #[must_use]
    pub fn post_mask(mut self, post_mask: PostMask) -> Self {
        self.request.post_mask = Some(post_mask);
        self
    }

    /// Sets the optional publishing type.
    #[must_use]
    pub const fn publishing_type(mut self, publishing_type: PostPublishingType) -> Self {
        self.request.publishing_type = Some(publishing_type as i32);
        self
    }

    /// Finalizes the validated request.
    ///
    /// # Errors
    ///
    /// Returns an error when both reply and quote targets are set, or when more than
    /// four media identifiers are attached.
    pub fn build(self) -> Result<CreatePostRequest, RequestValidationError> {
        if self.request.in_reply_to_post_id.is_some() && self.request.quoted_post_id.is_some() {
            return Err(RequestValidationError::ConflictingPostTargets);
        }
        if self.request.media_id_list.len() > 4 {
            return Err(RequestValidationError::TooManyMediaIds);
        }
        Ok(self.request)
    }
}

/// Builder for `DeletePostRequest`.
#[derive(Clone, Debug)]
pub struct DeletePostRequestBuilder {
    request: DeletePostRequest,
}

impl DeletePostRequestBuilder {
    /// Creates a new builder with the required post identifier.
    #[must_use]
    pub fn new(post_id: impl Into<String>) -> Self {
        Self {
            request: DeletePostRequest {
                post_id: post_id.into(),
            },
        }
    }

    /// Overrides the target post identifier.
    #[must_use]
    pub fn post_id(mut self, post_id: impl Into<String>) -> Self {
        self.request.post_id = post_id.into();
        self
    }

    /// Finalizes the validated request.
    ///
    /// # Errors
    ///
    /// Returns an error when `post_id` is empty.
    pub fn build(self) -> Result<DeletePostRequest, RequestValidationError> {
        if self.request.post_id.is_empty() {
            return Err(RequestValidationError::EmptyPostId);
        }
        Ok(self.request)
    }
}

/// Builder for `SendChatMessageRequest`.
#[derive(Clone, Debug)]
pub struct SendChatMessageRequestBuilder {
    request: SendChatMessageRequest,
}

impl SendChatMessageRequestBuilder {
    /// Creates a new builder with the required room identifier.
    #[must_use]
    pub fn new(room_id: impl Into<String>) -> Self {
        Self {
            request: SendChatMessageRequest {
                room_id: room_id.into(),
                text: None,
                media_id: None,
            },
        }
    }

    /// Sets the message text.
    #[must_use]
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.request.text = Some(text.into());
        self
    }

    /// Sets the optional media attachment.
    #[must_use]
    pub fn media_id(mut self, media_id: impl Into<String>) -> Self {
        self.request.media_id = Some(media_id.into());
        self
    }

    /// Finalizes the validated request.
    ///
    /// # Errors
    ///
    /// Returns an error when `room_id` is empty or both `text` and `media_id` are missing.
    pub fn build(self) -> Result<SendChatMessageRequest, RequestValidationError> {
        if self.request.room_id.is_empty() {
            return Err(RequestValidationError::EmptyRoomId);
        }
        if self.request.text.is_none() && self.request.media_id.is_none() {
            return Err(RequestValidationError::MissingChatPayload);
        }
        Ok(self.request)
    }
}

/// Builder for `InitiatePostMediaUploadRequest`.
#[derive(Clone, Debug)]
pub struct InitiatePostMediaUploadRequestBuilder {
    request: InitiatePostMediaUploadRequest,
}

impl InitiatePostMediaUploadRequestBuilder {
    /// Creates a new builder with the required upload metadata.
    #[must_use]
    pub fn new(
        content_type: impl Into<String>,
        data_size: u64,
        media_type: application_api_v1::initiate_post_media_upload_request::Type,
    ) -> Self {
        Self {
            request: InitiatePostMediaUploadRequest {
                content_type: content_type.into(),
                data_size,
                media_type: media_type as i32,
                description: None,
            },
        }
    }

    /// Sets the optional description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.request.description = Some(description.into());
        self
    }

    /// Finalizes the validated request.
    ///
    /// # Errors
    ///
    /// Returns an error when `content_type` is empty, `data_size` is zero, or the
    /// media type is unspecified.
    pub fn build(self) -> Result<InitiatePostMediaUploadRequest, RequestValidationError> {
        if self.request.content_type.is_empty() {
            return Err(RequestValidationError::EmptyContentType);
        }
        if self.request.data_size == 0 {
            return Err(RequestValidationError::EmptyUploadSize);
        }
        if self.request.media_type
            == application_api_v1::initiate_post_media_upload_request::Type::Unspecified as i32
        {
            return Err(RequestValidationError::UnspecifiedUploadType);
        }
        Ok(self.request)
    }
}

/// Builder for `GetStampsRequest`.
#[derive(Clone, Copy, Debug, Default)]
pub struct GetStampsRequestBuilder {
    request: GetStampsRequest,
}

impl GetStampsRequestBuilder {
    /// Creates a new builder.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            request: GetStampsRequest {
                official_stamp_language: None,
            },
        }
    }

    /// Sets the optional official stamp language.
    #[must_use]
    pub const fn official_stamp_language(mut self, language: LanguageCode) -> Self {
        self.request.official_stamp_language = Some(language as i32);
        self
    }

    /// Finalizes the request.
    #[must_use]
    pub const fn build(self) -> GetStampsRequest {
        self.request
    }
}

/// Builder for `AddStampToPostRequest`.
#[derive(Clone, Debug)]
pub struct AddStampToPostRequestBuilder {
    request: AddStampToPostRequest,
}

impl AddStampToPostRequestBuilder {
    /// Creates a new builder with the required identifiers.
    #[must_use]
    pub fn new(post_id: impl Into<String>, stamp_id: impl Into<String>) -> Self {
        Self {
            request: AddStampToPostRequest {
                post_id: post_id.into(),
                stamp_id: stamp_id.into(),
            },
        }
    }

    /// Overrides the target post identifier.
    #[must_use]
    pub fn post_id(mut self, post_id: impl Into<String>) -> Self {
        self.request.post_id = post_id.into();
        self
    }

    /// Overrides the stamp identifier.
    #[must_use]
    pub fn stamp_id(mut self, stamp_id: impl Into<String>) -> Self {
        self.request.stamp_id = stamp_id.into();
        self
    }

    /// Finalizes the validated request.
    ///
    /// # Errors
    ///
    /// Returns an error when either `post_id` or `stamp_id` is empty.
    pub fn build(self) -> Result<AddStampToPostRequest, RequestValidationError> {
        if self.request.post_id.is_empty() {
            return Err(RequestValidationError::EmptyPostId);
        }
        if self.request.stamp_id.is_empty() {
            return Err(RequestValidationError::EmptyStampId);
        }
        Ok(self.request)
    }
}

#[cfg(feature = "api")]
fn auth_error_to_status(error: &AuthLayerError) -> Status {
    Status::unauthenticated(error.to_string())
}

#[cfg(feature = "api")]
async fn resolve_channel(
    channel: Option<Channel>,
    endpoint: Option<String>,
    default_endpoint: &str,
) -> Result<Channel, ClientBuildError> {
    match (channel, endpoint) {
        (Some(_), Some(_)) => Err(ClientBuildError::ConflictingTransport),
        (Some(channel), None) => Ok(channel),
        (None, endpoint) => {
            let endpoint = Endpoint::new(resolve_endpoint(endpoint, default_endpoint))
                .map_err(ClientBuildError::Transport)?;
            endpoint
                .connect()
                .await
                .map_err(ClientBuildError::Transport)
        }
    }
}

#[cfg(any(feature = "api", feature = "stream"))]
fn resolve_endpoint(endpoint: Option<String>, default_endpoint: &str) -> String {
    endpoint.unwrap_or_else(|| default_endpoint.to_owned())
}

#[cfg(test)]
mod tests {
    use crate::social::mixi::application::{
        r#const::v1::{LanguageCode, PostMaskType, PostPublishingType},
        model::v1::PostMask,
        service::application_api::v1::initiate_post_media_upload_request::Type as UploadType,
    };

    #[cfg(feature = "api")]
    use super::DEFAULT_API_ENDPOINT;
    #[cfg(feature = "stream")]
    use super::DEFAULT_STREAM_ENDPOINT;
    #[cfg(any(feature = "api", feature = "stream"))]
    use super::resolve_endpoint;
    use super::{
        AddStampToPostRequestBuilder, CreatePostRequestBuilder, DeletePostRequestBuilder,
        GetStampsRequestBuilder, InitiatePostMediaUploadRequestBuilder, RequestValidationError,
        SendChatMessageRequestBuilder,
    };

    #[cfg(feature = "api")]
    #[test]
    fn resolve_endpoint_defaults_to_official_api_endpoint() {
        assert_eq!(
            resolve_endpoint(None, DEFAULT_API_ENDPOINT),
            DEFAULT_API_ENDPOINT
        );
    }

    #[cfg(feature = "stream")]
    #[test]
    fn resolve_endpoint_defaults_to_official_stream_endpoint() {
        assert_eq!(
            resolve_endpoint(None, DEFAULT_STREAM_ENDPOINT),
            DEFAULT_STREAM_ENDPOINT
        );
    }

    #[cfg(feature = "api")]
    #[test]
    fn resolve_endpoint_prefers_explicit_override() {
        let override_endpoint = String::from("https://override.example.test");

        assert_eq!(
            resolve_endpoint(Some(override_endpoint.clone()), DEFAULT_API_ENDPOINT),
            override_endpoint
        );
    }

    #[test]
    fn create_post_builder_rejects_conflicting_targets() {
        let result = CreatePostRequestBuilder::new("hello")
            .in_reply_to_post_id("reply")
            .quoted_post_id("quote")
            .build();

        assert_eq!(result, Err(RequestValidationError::ConflictingPostTargets));
    }

    #[test]
    fn create_post_builder_rejects_too_many_media_ids() {
        let result = CreatePostRequestBuilder::new("hello")
            .media_ids(["1", "2", "3", "4", "5"])
            .build();

        assert_eq!(result, Err(RequestValidationError::TooManyMediaIds));
    }

    #[test]
    fn create_post_builder_accepts_optional_fields() {
        let result = CreatePostRequestBuilder::new("hello")
            .push_media_id("media-id")
            .post_mask(PostMask {
                mask_type: PostMaskType::Sensitive as i32,
                caption: String::from("spoilers"),
            })
            .publishing_type(PostPublishingType::NotPublishing)
            .build();

        assert!(result.is_ok());
    }

    #[test]
    fn delete_post_builder_requires_post_id() {
        let result = DeletePostRequestBuilder::new("").build();

        assert_eq!(result, Err(RequestValidationError::EmptyPostId));
    }

    #[test]
    fn delete_post_builder_accepts_post_id() {
        let result = DeletePostRequestBuilder::new("post-id").build();

        assert!(result.is_ok());
    }

    #[test]
    fn send_chat_message_builder_requires_payload() {
        let result = SendChatMessageRequestBuilder::new("room-id").build();

        assert_eq!(result, Err(RequestValidationError::MissingChatPayload));
    }

    #[test]
    fn send_chat_message_builder_requires_room_id() {
        let result = SendChatMessageRequestBuilder::new("").text("hello").build();

        assert_eq!(result, Err(RequestValidationError::EmptyRoomId));
    }

    #[test]
    fn initiate_upload_builder_requires_non_empty_content_type() {
        let result = InitiatePostMediaUploadRequestBuilder::new("", 128, UploadType::Image).build();

        assert_eq!(result, Err(RequestValidationError::EmptyContentType));
    }

    #[test]
    fn initiate_upload_builder_requires_non_zero_size() {
        let result =
            InitiatePostMediaUploadRequestBuilder::new("image/png", 0, UploadType::Image).build();

        assert_eq!(result, Err(RequestValidationError::EmptyUploadSize));
    }

    #[test]
    fn initiate_upload_builder_rejects_unspecified_type() {
        let result =
            InitiatePostMediaUploadRequestBuilder::new("image/png", 128, UploadType::Unspecified)
                .build();

        assert_eq!(result, Err(RequestValidationError::UnspecifiedUploadType));
    }

    #[test]
    fn get_stamps_builder_sets_optional_language() {
        let request = GetStampsRequestBuilder::new()
            .official_stamp_language(LanguageCode::En)
            .build();

        assert_eq!(
            request.official_stamp_language,
            Some(LanguageCode::En as i32)
        );
    }

    #[test]
    fn add_stamp_to_post_builder_requires_post_id() {
        let result = AddStampToPostRequestBuilder::new("", "stamp-id").build();

        assert_eq!(result, Err(RequestValidationError::EmptyPostId));
    }

    #[test]
    fn add_stamp_to_post_builder_requires_stamp_id() {
        let result = AddStampToPostRequestBuilder::new("post-id", "").build();

        assert_eq!(result, Err(RequestValidationError::EmptyStampId));
    }

    #[test]
    fn add_stamp_to_post_builder_accepts_identifiers() {
        let result = AddStampToPostRequestBuilder::new("post-id", "stamp-id").build();

        assert!(result.is_ok());
    }
}