open-lark 0.14.0

Enterprise-grade Lark/Feishu Open API SDK with comprehensive Chinese documentation and advanced error handling
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
/// 核心宏:为Builder类型自动实现ExecutableBuilder trait
///
/// 这个宏消除了手动实现重复execute方法的需要,
/// 通过声明式配置自动生成trait实现。
///
/// # 参数
/// - `$builder`: Builder类型名称
/// - `$service`: 服务类型名称  
/// - `$request`: 请求类型名称
/// - `$response`: 响应类型名称
/// - `$method`: 服务方法名称
///
/// # 生成的代码
/// 为指定的Builder类型实现ExecutableBuilder trait,包括:
/// - `execute()` 方法:调用 `service.$method(self.build(), None)`
/// - `execute_with_options()` 方法:调用 `service.$method(self.build(), Some(option))`
///
/// # Example
/// ```rust,ignore
/// impl_executable_builder!(
///     UploadMediaRequestBuilder,
///     MediaService,
///     UploadMediaRequest,
///     BaseResponse<UploadMediaRespData>,
///     upload_all
/// );
/// ```
#[macro_export]
macro_rules! impl_executable_builder {
    (
        $builder:ty,
        $service:ty,
        $request:ty,
        $response:ty,
        $method:ident
    ) => {
        #[async_trait::async_trait]
        impl $crate::core::trait_system::ExecutableBuilder<$service, $request, $response>
            for $builder
        {
            fn build(self) -> $request {
                self.build()
            }

            async fn execute(self, service: &$service) -> $crate::core::SDKResult<$response> {
                service.$method(&self.build(), None).await
            }

            async fn execute_with_options(
                self,
                service: &$service,
                option: $crate::core::req_option::RequestOption,
            ) -> $crate::core::SDKResult<$response> {
                service.$method(&self.build(), Some(option)).await
            }
        }
    };
}

/// 为使用值类型参数的Builder实现ExecutableBuilder trait
///
/// 与主宏的差异:服务方法接受值类型而不是引用类型的Request
#[macro_export]
macro_rules! impl_executable_builder_owned {
    (
        $builder:ty,
        $service:ty,
        $request:ty,
        $response:ty,
        $method:ident
    ) => {
        #[async_trait::async_trait]
        impl $crate::core::trait_system::ExecutableBuilder<$service, $request, $response>
            for $builder
        {
            fn build(self) -> $request {
                self.build()
            }

            async fn execute(self, service: &$service) -> $crate::core::SDKResult<$response> {
                service.$method(self.build(), None).await
            }

            async fn execute_with_options(
                self,
                service: &$service,
                option: $crate::core::req_option::RequestOption,
            ) -> $crate::core::SDKResult<$response> {
                service.$method(self.build(), Some(option)).await
            }
        }
    };
}

/// 为直接使用Config参数的独立函数实现ExecutableBuilder trait
///
/// 这个宏用于那些不通过服务而是直接调用独立函数的Builder类型
#[macro_export]
macro_rules! impl_executable_builder_config {
    (
        $builder:ty,
        $request:ty,
        $response:ty,
        $function:ident
    ) => {
        impl $builder {
            /// 执行请求
            pub async fn execute(
                self,
                config: &$crate::core::config::Config,
            ) -> $crate::core::SDKResult<$response> {
                $function(self.build(), config, None).await
            }

            /// 执行请求(带选项)
            pub async fn execute_with_options(
                self,
                config: &$crate::core::config::Config,
                option: $crate::core::req_option::RequestOption,
            ) -> $crate::core::SDKResult<$response> {
                $function(self.build(), config, Some(option)).await
            }
        }
    };
}

// Service trait 相关宏

/// 为基础服务生成标准实现的宏
///
/// 这个宏减少了创建简单服务时的样板代码
#[macro_export]
macro_rules! impl_basic_service {
    ($service_type:ty, $name:expr, $version:expr) => {
        impl $crate::core::trait_system::Service for $service_type {
            fn config(&self) -> &$crate::core::config::Config {
                &self.config
            }

            fn service_name() -> &'static str {
                $name
            }

            fn service_version() -> &'static str {
                $version
            }
        }

        impl $crate::core::trait_system::ServiceObservability for $service_type {}

        impl $crate::core::trait_system::ServiceBuilder<$service_type> for $service_type {
            fn build(config: $crate::core::config::Config) -> $service_type {
                Self { config }
            }
        }
    };
}

/// 为服务生成异步操作支持的宏
#[macro_export]
macro_rules! impl_async_service {
    ($service_type:ty, $request_type:ty, $response_type:ty) => {
        impl $crate::core::trait_system::AsyncServiceOperation<$request_type, $response_type>
            for $service_type
        {
        }
    };
}

/// 为服务生成健康检查实现的宏
#[macro_export]
macro_rules! impl_service_health_check {
    ($service_type:ty) => {
        impl $crate::core::trait_system::ServiceHealthCheck for $service_type {
            async fn health_check(
                &self,
            ) -> $crate::core::SDKResult<$crate::core::trait_system::ServiceHealthStatus> {
                use $crate::core::trait_system::ServiceHealthStatus;

                if !self.is_config_valid() {
                    return Ok(ServiceHealthStatus::Unhealthy(
                        "Invalid configuration".to_string(),
                    ));
                }

                // 基础健康检查 - 可以在具体服务中重写
                Ok(ServiceHealthStatus::Healthy)
            }
        }
    };
}

/// 为服务生成可配置实现的宏
#[macro_export]
macro_rules! impl_configurable_service {
    ($service_type:ty) => {
        impl $crate::core::trait_system::ConfigurableService for $service_type {
            fn update_config(
                &mut self,
                new_config: $crate::core::config::Config,
            ) -> $crate::core::SDKResult<()> {
                self.validate_config(&new_config)?;
                self.config = new_config;
                Ok(())
            }
        }
    };
}

/// 一次性实现所有基础服务 traits 的便利宏
#[macro_export]
macro_rules! impl_full_service {
    ($service_type:ty, $name:expr) => {
        impl_full_service!($service_type, $name, "v1");
    };
    ($service_type:ty, $name:expr, $version:expr) => {
        $crate::impl_basic_service!($service_type, $name, $version);
        $crate::impl_service_health_check!($service_type);
        $crate::impl_configurable_service!($service_type);
    };
}

/// 为服务 builder 生成构造函数的宏
#[macro_export]
macro_rules! impl_service_constructor {
    ($service_type:ty) => {
        impl $service_type {
            /// 创建服务实例
            pub fn new(config: $crate::core::config::Config) -> Self {
                <Self as $crate::core::trait_system::ServiceBuilder<Self>>::build(config)
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use crate::core::{
        api_resp::{ApiResponseTrait, BaseResponse, RawResponse, ResponseFormat},
        config::Config,
        req_option::RequestOption,
        trait_system::ExecutableBuilder,
        SDKResult,
    };
    use serde::{Deserialize, Serialize};

    // Test types for macro validation
    #[derive(Debug, Clone)]
    struct MockRequest {
        data: String,
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct MockResponse {
        result: String,
    }

    impl ApiResponseTrait for MockResponse {
        fn data_format() -> ResponseFormat {
            ResponseFormat::Data
        }
    }

    #[derive(Clone)]
    struct MockService;

    impl MockService {
        async fn test_method(
            &self,
            request: &MockRequest,
            _option: Option<RequestOption>,
        ) -> SDKResult<BaseResponse<MockResponse>> {
            Ok(BaseResponse {
                raw_response: RawResponse {
                    code: 0,
                    msg: "success".to_string(),
                    err: None,
                },
                data: Some(MockResponse {
                    result: format!("processed: {}", request.data),
                }),
            })
        }

        async fn test_method_owned(
            &self,
            request: MockRequest,
            _option: Option<RequestOption>,
        ) -> SDKResult<BaseResponse<MockResponse>> {
            Ok(BaseResponse {
                raw_response: RawResponse {
                    code: 0,
                    msg: "success".to_string(),
                    err: None,
                },
                data: Some(MockResponse {
                    result: format!("owned: {}", request.data),
                }),
            })
        }
    }

    #[derive(Default)]
    struct MockRequestBuilder {
        data: String,
    }

    impl MockRequestBuilder {
        pub fn data(mut self, data: impl Into<String>) -> Self {
            self.data = data.into();
            self
        }

        pub fn build(self) -> MockRequest {
            MockRequest { data: self.data }
        }
    }

    #[derive(Default)]
    struct MockRequestBuilderOwned {
        data: String,
    }

    impl MockRequestBuilderOwned {
        pub fn data(mut self, data: impl Into<String>) -> Self {
            self.data = data.into();
            self
        }

        pub fn build(self) -> MockRequest {
            MockRequest { data: self.data }
        }
    }

    // Use the macro to implement the trait
    crate::impl_executable_builder!(
        MockRequestBuilder,
        MockService,
        MockRequest,
        BaseResponse<MockResponse>,
        test_method
    );

    crate::impl_executable_builder_owned!(
        MockRequestBuilderOwned,
        MockService,
        MockRequest,
        BaseResponse<MockResponse>,
        test_method_owned
    );

    async fn mock_config_function(
        request: MockRequest,
        _config: &Config,
        _option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<MockResponse>> {
        Ok(BaseResponse {
            raw_response: RawResponse {
                code: 0,
                msg: "success".to_string(),
                err: None,
            },
            data: Some(MockResponse {
                result: format!("config: {}", request.data),
            }),
        })
    }

    #[derive(Default)]
    struct MockConfigBuilder {
        data: String,
    }

    impl MockConfigBuilder {
        pub fn data(mut self, data: impl Into<String>) -> Self {
            self.data = data.into();
            self
        }

        pub fn build(self) -> MockRequest {
            MockRequest { data: self.data }
        }
    }

    crate::impl_executable_builder_config!(
        MockConfigBuilder,
        MockRequest,
        BaseResponse<MockResponse>,
        mock_config_function
    );

    #[tokio::test]
    async fn test_executable_builder_macro() {
        let service = MockService;
        let builder = MockRequestBuilder::default().data("test data");

        let result = builder.execute(&service).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.code(), 0);
        assert_eq!(
            response.data.as_ref().unwrap().result,
            "processed: test data"
        );
    }

    #[tokio::test]
    async fn test_executable_builder_macro_with_options() {
        let service = MockService;
        let builder = MockRequestBuilder::default().data("test with options");
        let option = RequestOption::default();

        let result = builder.execute_with_options(&service, option).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.code(), 0);
        assert_eq!(
            response.data.as_ref().unwrap().result,
            "processed: test with options"
        );
    }

    #[tokio::test]
    async fn test_executable_builder_owned_macro() {
        let service = MockService;
        let builder = MockRequestBuilderOwned::default().data("owned test");

        let result = builder.execute(&service).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.code(), 0);
        assert_eq!(response.data.as_ref().unwrap().result, "owned: owned test");
    }

    #[tokio::test]
    async fn test_executable_builder_config_macro() {
        let config = Config::default();
        let builder = MockConfigBuilder::default().data("config test");

        let result = builder.execute(&config).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.code(), 0);
        assert_eq!(
            response.data.as_ref().unwrap().result,
            "config: config test"
        );
    }

    #[tokio::test]
    async fn test_executable_builder_config_macro_with_options() {
        let config = Config::default();
        let builder = MockConfigBuilder::default().data("config with options");
        let option = RequestOption::default();

        let result = builder.execute_with_options(&config, option).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.code(), 0);
        assert_eq!(
            response.data.as_ref().unwrap().result,
            "config: config with options"
        );
    }

    #[test]
    fn test_builder_construction() {
        let builder = MockRequestBuilder::default().data("test");
        let request = builder.build();
        assert_eq!(request.data, "test");
    }

    #[test]
    fn test_builder_chaining() {
        let builder = MockRequestBuilder::default().data("first").data("second");
        let request = builder.build();
        assert_eq!(request.data, "second");
    }

    #[test]
    fn test_owned_builder_construction() {
        let builder = MockRequestBuilderOwned::default().data("owned test");
        let request = builder.build();
        assert_eq!(request.data, "owned test");
    }

    #[test]
    fn test_config_builder_construction() {
        let builder = MockConfigBuilder::default().data("config builder test");
        let request = builder.build();
        assert_eq!(request.data, "config builder test");
    }

    #[test]
    fn test_mock_response_api_trait() {
        let format = MockResponse::data_format();
        assert!(matches!(format, ResponseFormat::Data));
    }

    #[test]
    fn test_mock_response_serialization() {
        let response = MockResponse {
            result: "test result".to_string(),
        };

        let serialized = serde_json::to_string(&response).expect("Should serialize");
        let deserialized: MockResponse =
            serde_json::from_str(&serialized).expect("Should deserialize");

        assert_eq!(response.result, deserialized.result);
    }

    #[test]
    fn test_mock_request_debug() {
        let request = MockRequest {
            data: "debug test".to_string(),
        };

        let debug_str = format!("{:?}", request);
        assert!(debug_str.contains("MockRequest"));
        assert!(debug_str.contains("debug test"));
    }

    #[test]
    fn test_mock_request_clone() {
        let request = MockRequest {
            data: "clone test".to_string(),
        };

        let cloned = request.clone();
        assert_eq!(request.data, cloned.data);
    }

    #[test]
    fn test_builder_with_empty_data() {
        let builder = MockRequestBuilder::default().data("");
        let request = builder.build();
        assert_eq!(request.data, "");
    }

    #[test]
    fn test_builder_with_unicode_data() {
        let builder = MockRequestBuilder::default().data("测试数据 🚀");
        let request = builder.build();
        assert_eq!(request.data, "测试数据 🚀");
    }

    #[test]
    fn test_builder_with_long_data() {
        let long_data = "a".repeat(10000);
        let builder = MockRequestBuilder::default().data(&long_data);
        let request = builder.build();
        assert_eq!(request.data, long_data);
    }
}