### Run Quick Start Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'readme_quick_start' example, requiring 'auth' and 'docs-bitable' features. ```bash cargo run --example readme_quick_start --features "auth,docs-bitable" ``` -------------------------------- ### Run Client Setup Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'client_setup' example, demonstrating client creation with 'auth' and 'communication' features. ```bash cargo run --example client_setup --features "auth,communication" ``` -------------------------------- ### Configure Development Environment Source: https://github.com/foxzool/openlark/blob/main/CONTRIBUTING.md Copy the example environment configuration file and install optional development tools like 'just'. Use 'just --list' to view available commands. ```bash cp .env-example .env cargo install just just --list ``` -------------------------------- ### Run Example with Multiple Features Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Shows how to run an example with multiple features enabled, such as 'card' and 'signature'. ```bash cargo run --example webhook_text_message -p openlark-webhook --features "card,signature" ``` -------------------------------- ### Copy Environment Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Copies the example environment file to be configured for local use. ```bash cp examples/01_getting_started/.env.example .env ``` -------------------------------- ### Run Card Message Example Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Shows how to execute the card message example, which requires the 'card' feature to be enabled. ```bash cargo run --example webhook_card_message -p openlark-webhook --features card ``` -------------------------------- ### Run Docs Helpers Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'docs_helpers' example, demonstrating various docs helper functionalities with 'auth' and 'docs-bitable' features. ```bash cargo run --example docs_helpers --features "auth,docs-bitable" ``` -------------------------------- ### Run Signature Verification Example Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Demonstrates running the example for sending messages with signature verification, requiring the 'signature' feature. ```bash cargo run --example webhook_with_signature -p openlark-webhook --features signature ``` -------------------------------- ### Check Examples Compilation Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Command to check the compilation of all examples for the openlark-webhook crate. ```bash cargo check -p openlark-webhook --examples ``` -------------------------------- ### Basic API Call Example Source: https://github.com/foxzool/openlark/blob/main/RELEASE_NOTES.md Example demonstrating how to initialize a `Client` using `Client::builder` with application credentials and make a basic API call. ```rust use open_lark::prelude::*; use open_lark::communication::endpoints::IM_V1_MESSAGES; let client = Client::builder() .app_id("your_app_id") .app_secret("your_app_secret") .build()?; ``` -------------------------------- ### Run Error Handling Example Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Illustrates how to run the example that showcases proper error handling patterns for webhook operations. ```bash cargo run --example webhook_error_handling -p openlark-webhook ``` -------------------------------- ### Run Docs Workflows Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'docs_workflows' example, demonstrating combined helper usage for Drive, Sheets, Wiki, and Bitable with 'auth' and 'docs-bitable' features. ```bash cargo run --example docs_workflows --features "auth,docs-bitable" ``` -------------------------------- ### Run Communication Workflows Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'communication_workflows' example, showcasing Communication/Workflow helper combinations with 'auth', 'communication', and 'workflow' features. ```bash cargo run --example communication_workflows --features "auth,communication,workflow" ``` -------------------------------- ### Check Examples Compilation with Features Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Command to check the compilation of all examples with specific features enabled for the openlark-webhook crate. ```bash cargo check -p openlark-webhook --examples --features "card,signature" ``` -------------------------------- ### Run WebSocket Echo Bot Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'websocket_echo_bot' example for a long-polling echo bot with 'communication' and 'websocket' features. ```bash cargo run --example websocket_echo_bot --features "communication,websocket" ``` -------------------------------- ### Run Text Message Example Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md Demonstrates how to run the basic text message example for the OpenLark webhook. ```bash cargo run --example webhook_text_message -p openlark-webhook ``` -------------------------------- ### Clone Project and Install Dependencies Source: https://github.com/foxzool/openlark/blob/main/CONTRIBUTING.md Clone the open-lark repository and install all project dependencies. This is the initial step for setting up your development environment. ```bash git clone https://github.com/foxzool/openlark.git cd open-lark cargo build --all-features cargo test --all-features ``` -------------------------------- ### Run Workflow API Example Source: https://github.com/foxzool/openlark/blob/main/examples/README.md Executes the 'workflow_api_example' to demonstrate workflow module calls, requiring the 'workflow' feature. ```bash cargo run --example workflow_api_example --features "workflow" ``` -------------------------------- ### Feature Model Examples Source: https://github.com/foxzool/openlark/blob/main/RELEASE_NOTES.md Examples of how to specify features for the `openlark` crate in `Cargo.toml` to include different sets of capabilities. ```toml [dependencies] openlark = "0.16.0" # 默认: auth openlark = { version = "0.16.0", features = ["essential"] } openlark = { version = "0.16.0", features = ["enterprise"] } openlark = { version = "0.16.0", features = ["full"] } ``` -------------------------------- ### Documentation Test Example Source: https://github.com/foxzool/openlark/blob/main/CONTRIBUTING.md Rust code showing how to include runnable code examples within documentation comments, which can be tested using `cargo test`. ```rust /// 函数说明 /// /// # 示例 /// ```rust /// use open_lark::prelude::*; /// /// let result = function_call(); /// assert_eq!(result, expected); /// ``` pub fn your_function() {} ``` -------------------------------- ### Full Combination Installation Source: https://github.com/foxzool/openlark/blob/main/RELEASE_NOTES.md Configuration for a complete feature set, including all available capabilities via the `full` feature flag. ```toml [dependencies] openlark = { version = "0.16.0", features = ["full"] } ``` -------------------------------- ### Meeting Example: Create Room Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-client/docs/meta-api-style.md Illustrates how to create a meeting room using the meeting module in openlark-client. This example shows how to obtain a builder from the `client.meeting.vc.v1.room` entry point and execute the creation request with specific room details. ```APIDOC ## client.meeting.vc.v1.room.create ### Description Creates a new meeting room. This method is accessed through the `meeting` business entry point, specifically within the `vc` service, version `v1`, and operating on the `room` resource. It utilizes a builder pattern for constructing the request. ### Method POST ### Endpoint (Specific endpoint not detailed, but implied by the builder pattern and context) ### Parameters #### Request Body - **name** (string) - Required - The name of the meeting room. (Other potential fields can be set via the builder) ### Request Example ```json { "name": "demo" } ``` ### Response #### Success Response (200) (Response details not explicitly provided in the source, but the `execute` method suggests a successful operation.) ``` -------------------------------- ### Recommended Business Development Installation Source: https://github.com/foxzool/openlark/blob/main/RELEASE_NOTES.md Configuration for typical business development, including `auth`, `communication`, and `docs` features via the `essential` feature flag. ```toml [dependencies] openlark = { version = "0.16.0", features = ["essential"] } ``` -------------------------------- ### Using the shared TestServer utility Source: https://github.com/foxzool/openlark/blob/main/docs/TESTSERVER_LIMITATIONS.md This example demonstrates how to use the `TestServer` from the `openlark-test-utils` crate in tests of other crates, following the recommended long-term solution. ```rust use openlark_test_utils::TestServer; use serde_json::json; #[tokio::test] async fn test_example() { let server = TestServer::new().await; server.mock_success("/api/v1/test", json!({"code": 0})).await; // ... } ``` -------------------------------- ### Recommended Feature Combinations Source: https://github.com/foxzool/openlark/blob/main/docs/migration-guide.md Examples of how to include common feature sets like 'essential', 'enterprise', or 'full' in your Cargo.toml. ```toml openlark = "0.15" ``` ```toml openlark = { version = "0.15", features = ["essential"] } ``` ```toml openlark = { version = "0.15", features = ["enterprise"] } ``` ```toml openlark = { version = "0.15", features = ["full"] } ``` -------------------------------- ### Send File Message (Builder) Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/README.md Example of using the `.file()` method to send a file message. Requires a file key obtained from Feishu. ```rust .file("file_xxxxxx".to_string()) ``` -------------------------------- ### Accessing Client Capabilities Source: https://github.com/foxzool/openlark/blob/main/docs/migration-guide.md Examples of how to use the initialized client to interact with different OpenLark services like Docs and Communication. Note the use of specific methods for accessing resources. ```rust client.docs.list_folder_children_all("folder_token", None).await?; client.docs.find_sheet_by_title("spreadsheet_token", "汇总表").await?; client.communication; ``` -------------------------------- ### Replace Mock Creation with TestServer Source: https://github.com/foxzool/openlark/blob/main/docs/TEST_MIGRATION.md Demonstrates replacing wiremock's MockServer and Mock setup with TestServer's simplified mock_success method. ```rust // 之前 let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/v1/test")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({...}))) .mount(&server) .await; // 之后 let server = TestServer::new().await; server.mock_success("/api/v1/test", json!({...})).await; ``` -------------------------------- ### Send Image Message (Builder) Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/README.md Example of using the `.image()` method to send an image message. Requires an image key obtained from Feishu. ```rust .image("img_xxxxxx".to_string()) ``` -------------------------------- ### Rust Test Example with Testing Framework Source: https://github.com/foxzool/openlark/blob/main/REFACTORING_PROGRESS.md Demonstrates how to use the custom testing framework for asynchronous operations. It utilizes `test_config` and `test_runtime` for setting up the test environment and `assert_res_ok!` for validating successful API responses. ```rust use openlark_core::testing::prelude::*; #[test] fn test_example() { let config = test_config(); let rt = test_runtime(); let result = rt.block_on(async { some_api().await }); let response = assert_res_ok!(result, "test_example"); assert_eq!(response.id, "123"); } ``` -------------------------------- ### Unit Test Example Source: https://github.com/foxzool/openlark/blob/main/CONTRIBUTING.md Rust code demonstrating how to write unit tests using the `#[cfg(test)]` attribute and `#[tokio::test]` for asynchronous tests. ```rust #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn test_your_function() { // 测试逻辑 } } ``` -------------------------------- ### Send Text and Image Messages using WebhookClient Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/README.md Recommended approach for sending messages. This example shows how to initialize WebhookClient and send both text and image messages. Replace YOUR_WEBHOOK_KEY with your actual webhook key. ```rust use openlark_webhook::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { let client = WebhookClient::new(); let webhook_url = "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_WEBHOOK_KEY"; // 发送文本消息 let response = client .send_text(webhook_url, "Hello from WebhookClient!".to_string()) .await?; println!("Text sent: {}", response.msg); // 发送图片消息 let response = client .send_image(webhook_url, "img_xxxxxx".to_string()) .await?; println!("Image sent: {}", response.msg); Ok(()) } ``` -------------------------------- ### Timeout Test with TestServer Source: https://github.com/foxzool/openlark/blob/main/docs/TEST_MIGRATION.md Advanced usage example demonstrating how to mock a timeout scenario using TestServer and configure a client timeout. ```rust use std::time::Duration; #[tokio::test] async fn test_timeout_handling() { let server = TestServer::new().await; server.mock_timeout("/api/v1/slow", Duration::from_secs(10)).await; let config = test_config(&server.uri()).with_timeout(Duration::from_millis(100)); let result = some_request().await; assert!(matches!(result, Err(CoreError::Timeout { .. }))); } ``` -------------------------------- ### Enterprise-Grade Combination Installation Source: https://github.com/foxzool/openlark/blob/main/RELEASE_NOTES.md Configuration for enterprise-level use, including `essential` features plus `security`, `hr`, and `workflow` via the `enterprise` feature flag. ```toml [dependencies] openlark = { version = "0.16.0", features = ["enterprise"] } ``` -------------------------------- ### Auth Test Before Migration (Wiremock) Source: https://github.com/foxzool/openlark/blob/main/docs/TEST_MIGRATION.md Example of an auth test using wiremock, demonstrating network error handling with a non-existent URL. ```rust use wiremock::{Mock, MockServer, ResponseTemplate}; use wiremock::matchers::{method, path}; #[tokio::test] async fn test_app_access_token_network_error_handling() { let config = create_test_config("http://nonexistent.invalid", 300); let service = AuthServiceV3::new(config); let result = service .app_access_token() .app_id("valid_app_id") .app_secret("valid_app_secret") .execute() .await; assert!(result.is_err()); } ``` -------------------------------- ### Module Export Example Source: https://github.com/foxzool/openlark/blob/main/docs/API_DESIGN_SPECIFICATION.md Demonstrates the standard practice for exporting API modules within a `mod.rs` file. Each API file (e.g., `create.rs`, `get.rs`) should be declared as public within the parent `mod.rs` to make its contents accessible. ```rust // src/xxx/v1/yyy/mod.rs pub mod create; pub mod get; pub mod models; // 如果存在 ``` -------------------------------- ### Project Directory Structure Source: https://github.com/foxzool/openlark/blob/main/CONTRIBUTING.md Overview of the open-lark project's directory structure, highlighting key directories like 'src', 'examples', 'docs', and 'tests'. ```bash open-lark/ ├── src/ │ ├── service/ # 服务模块 │ ├── core/ # 核心功能 │ ├── client/ # 客户端实现 │ ├── event/ # 事件处理 │ └── card/ # 卡片组件 ├── examples/ # 示例代码 ├── docs/ # 文档 ├── reports/ # 技术报告 └── tests/ # 测试文件 ``` -------------------------------- ### Example Usage of Batch Send Text API Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Demonstrates how to prepare a list of messages and use the batch_send_text method to send them. It also shows how to process the results, handling both successful sends and errors. ```rust let messages = vec![ ("user1".to_string(), "Hello User 1".to_string()), ("user2".to_string(), "Hello User 2".to_string()), ("user3".to_string(), "Hello User 3".to_string()), ]; let results = client.communication()?.batch_send_text(messages).await?; for (i, result) in results.into_iter().enumerate() { match result { Ok(response) => println!("消息{}发送成功: {}", i+1, response.message_id), Err(error) => eprintln!("消息{}发送失败: {}", i+1, error.user_friendly_message()), } } ``` -------------------------------- ### Create Meeting Room with Meeting Feature Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-client/docs/meta-api-style.md Example of creating a meeting room using the Meeting API module. Requires enabling the 'meeting' feature. The call chain provides a module-level entry point, and the Room resource offers a builder pattern for creating the request. ```rust use openlark_client::prelude::*; use serde_json::json; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env()?; // 会议:字段链式入口(Room 资源提供 Builder) let req = client.meeting.vc.v1.room.create().build(); let _resp = req.execute(json!({"name": "demo"})).await?; Ok(()) } ``` -------------------------------- ### Secure Token Storage Implementation Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Implements a secure token store using AES-256-GCM encryption for storing and retrieving sensitive tokens. This example demonstrates basic encryption/decryption and file storage, which should be replaced with a more robust solution in production. ```rust // 令牌安全存储 pub struct SecureTokenStore { encryption_key: [u8; 32], } impl SecureTokenStore { pub fn new(key: [u8; 32]) -> Self { Self { encryption_key: key } } pub async fn store_token(&self, token: &str) -> SDKResult<()> { let encrypted = self.encrypt(token)?; // 存储到安全的位置(如系统密钥链) tokio::fs::write("secure_token.enc", encrypted).await?; Ok(()) } pub async fn load_token(&self) -> SDKResult> { if tokio::fs::metadata("secure_token.enc").await.is_err() { return Ok(None); } let encrypted = tokio::fs::read("secure_token.enc").await?; let token = self.decrypt(&encrypted)?; Ok(Some(token)) } fn encrypt(&self, data: &str) -> SDKResult> { // 使用AES-256-GCM加密 // 实际实现需要使用加密库 Ok(data.as_bytes().to_vec()) } fn decrypt(&self, encrypted: &[u8]) -> SDKResult { // 解密实现 Ok(String::from_utf8_lossy(encrypted).to_string()) } } ``` -------------------------------- ### Batch Get User Info with Concurrency Control Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Shows an efficient way to fetch user information in batches using streams and controlling concurrency. This pattern is suitable for processing large datasets. ```rust use futures::stream::{self, StreamExt}; async fn batch_get_users(client: &Client, user_ids: Vec) -> SDKResult> { const BATCH_SIZE: usize = 50; const MAX_CONCURRENT: usize = 5; let mut results = Vec::new(); let batches: Vec<_> = user_ids .chunks(BATCH_SIZE) .map(|chunk| chunk.to_vec()) .collect(); // 使用流处理控制并发 let user_infos = stream::iter(batches) .map(|batch| { let client = client.clone(); async move { let mut batch_results = Vec::new(); for user_id in batch { match client.contact().v4().user().get(&user_id).await { Ok(user_info) => batch_results.push(user_info), Err(e) => { tracing::error!(user_id = %user_id, error = %e, "获取用户信息失败"); } } } batch_results } }) .buffer_unordered(MAX_CONCURRENT) // 限制并发批次 .collect::>() .await; for batch_result in user_infos { results.extend(batch_result); } Ok(results) } ``` -------------------------------- ### CardKit Example: Create Card Entity Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-client/docs/meta-api-style.md Demonstrates how to create a card entity using the CardKit feature in openlark-client. This involves constructing a `CreateCardBody` and executing the `create` method on the client's cardkit v1 card interface. ```APIDOC ## client.cardkit.v1.card.create ### Description Creates a new card entity using the CardKit API. This method is part of the `cardkit` business entry point, version `v1`, operating on the `card` resource. ### Method POST ### Endpoint /open-apis/cardkit/v1/cards ### Parameters #### Request Body - **card_content** (object) - Required - The content of the card, typically a JSON object defining elements. - **card_type** (string) - Optional - The type of the card. - **template_id** (string) - Optional - The ID of the template to use for the card. - **temp** (any) - Optional - Temporary data associated with the card. - **temp_expire_time** (integer) - Optional - The expiration time for temporary data. ### Request Example ```json { "card_content": {"elements": []}, "card_type": null, "template_id": null, "temp": null, "temp_expire_time": null } ``` ### Response #### Success Response (200) - **card_id** (string) - The unique identifier for the created card. ``` -------------------------------- ### Rust Type-Safe Service Access with Features Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Demonstrates type-safe service access using the `openlark_client::Client`. This example shows how to conditionally access different service clients (e.g., communication, docs) based on Cargo features. ```rust // 服务访问模式 use openlark_client::Client; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env()?; // 类型安全的服务访问(编译时检查) #[cfg(feature = "communication")] { let communication = client.communication()?; let result = communication.send_text("user_open_id", "open_id", "Hello!") .await?; println!("消息发送成功: {}", result.message_id); } #[cfg(feature = "docs")] { let docs = client.docs(); let spreadsheet = docs.sheets.v2.spreadsheets.get("sheet_token") .execute() .await?; println!("表格标题: {}", spreadsheet.title); } Ok(()) } ``` -------------------------------- ### Webhook Test Before Migration (Wiremock) Source: https://github.com/foxzool/openlark/blob/main/docs/TEST_MIGRATION.md Example of a webhook test using the original wiremock library. Requires explicit setup of mocks and responses. ```rust use wiremock::matchers::{body_json, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; use serde_json::json; #[tokio::test] async fn test_send_text_message_success_200() { let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/webhook")) .and(body_json(json!({ "msg_type": "text", "content": { "text": "hello webhook" } }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "code": 0, "msg": "ok" }))) .mount(&server) .await; let resp = SendWebhookMessageRequest::new(format!("{}/webhook", server.uri())) .text("hello webhook".to_string()) .execute() .await .expect("text message should be sent successfully"); assert_eq!(resp.code, 0); assert_eq!(resp.msg, "ok"); } ``` -------------------------------- ### Rust API Response Trait and Usage Example Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Illustrates how to define and implement the `ApiResponseTrait` for custom response types like `MessageSendResponse`. This enables type-safe API response handling with clear success and error paths. ```rust // API响应特征 pub trait ApiResponseTrait: Send + Sync + 'static { fn data_format() -> ResponseFormat { ResponseFormat::Data } } // 具体响应类型 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MessageSendResponse { pub message_id: String, pub create_time: String, } impl ApiResponseTrait for MessageSendResponse {} // 使用示例 let response: Response = transport.send(request).await?; match response.into_result() { Ok(data) => { println!("消息发送成功: {}", data.message_id); println!("创建时间: {}", data.create_time); }, Err(error) => { eprintln!("发送失败: {}", error.user_friendly_message()); } } ``` -------------------------------- ### OpenLark Feature Flag Control for Service Availability Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Illustrates the use of compile-time feature flags to control service availability. Includes a macro to check for required features and example implementations for accessing communication, docs, and auth services. ```rust // 功能标志检查宏 macro_rules! require_feature { ($feature:literal, $service:literal) => { if !cfg!(feature = $feature) { compile_error!(concat!( "启用 ", $service, " 服务需要启用 '", $feature, "' feature" )); } }; } // 服务访问器 impl Client { #[cfg(feature = "communication")] pub fn communication(&self) -> Result> { require_feature!("communication", "通讯"); CommunicationService::new(&self.config, &self.registry) } #[cfg(feature = "docs")] pub fn docs(&self) -> DocsService<'_> { require_feature!("docs", "文档"); DocsService::new(&self.config) } #[cfg(feature = "auth")] pub fn auth(&self) -> AuthService { require_feature!("auth", "认证"); AuthService::new(&self.config) } } ``` -------------------------------- ### Rust Service Lifecycle Manager Implementation Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md This Rust code defines the `ServiceLifecycleManager` struct and its associated methods for managing the lifecycle of services. It handles initialization, starting, and stopping services, along with state transitions and error handling. ```rust pub struct ServiceLifecycleManager { services: HashMap, state_transitions: HashMap>, } #[derive(Debug)] struct ServiceInstance { service: Box, state: ServiceState, last_check: Instant, error_count: u32, } #[derive(Debug, Clone, PartialEq)] pub enum ServiceState { Uninitialized, Initializing, Ready, Starting, Running, Stopping, Stopped, Failed(String), } impl ServiceLifecycleManager { pub async fn initialize_service(&mut self, service_name: &str) -> Result<()> { let instance = self.services.get_mut(service_name) .ok_or_else(|| service_error("service_not_found", service_name))?; match instance.state { ServiceState::Uninitialized => { instance.state = ServiceState::Initializing; let ctx = ServiceContext::new(service_name); if let Err(e) = instance.service.init(&ctx).await { instance.state = ServiceState::Failed(e.to_string()); return Err(e); } instance.state = ServiceState::Ready; Ok(()) }, _ => Err(service_error( "invalid_state_transition", &format!("服务 {} 当前状态无法初始化", service_name) )) } } pub async fn start_service(&mut self, service_name: &str) -> Result<()> { let instance = self.services.get_mut(service_name) .ok_or_else(|| service_error("service_not_found", service_name))?; match instance.state { ServiceState::Ready => { instance.state = ServiceState::Starting; let ctx = ServiceContext::new(service_name); if let Err(e) = instance.service.start(&ctx).await { instance.state = ServiceState::Failed(e.to_string()); return Err(e); } instance.state = ServiceState::Running; Ok(()) }, _ => Err(service_error( "invalid_state_transition", &format!("服务 {} 当前状态无法启动", service_name) )) } } pub async fn stop_service(&mut self, service_name: &str) -> Result<()> { let instance = self.services.get_mut(service_name) .ok_or_else(|| service_error("service_not_found", service_name))?; match instance.state { ServiceState::Running => { instance.state = ServiceState::Stopping; let ctx = ServiceContext::new(service_name); if let Err(e) = instance.service.stop(&ctx).await { instance.state = ServiceState::Failed(e.to_string()); return Err(e); } instance.state = ServiceState::Stopped; Ok(()) }, _ => Err(service_error( "invalid_state_transition", &format!("服务 {} 当前状态无法停止", service_name) )) } } } ``` -------------------------------- ### OpenLark Client Creation with Builder Pattern Source: https://github.com/foxzool/openlark/blob/main/ARCHITECTURE.md Demonstrates quick client creation from environment variables and standard builder pattern usage with various configuration options. Also shows asynchronous client building. ```rust use openlark_client::{Client, Config, Result}; use std::time::Duration; // 🔥 快速创建 - 从环境变量 let client = Client::from_env()?; // 🏗️ 标准构建器模式 let client = Client::builder() .app_id("your_app_id") .app_secret("your_app_secret") .base_url("https://open.feishu.cn") .timeout(Duration::from_secs(30)) .retry_count(3) .enable_log(true) .build()?; // 🌙 异步构建器 let client = client::AsyncClient::builder() .app_id("your_app_id") .app_secret("your_app_secret") .build() .await?; ``` -------------------------------- ### Initialize DocsClient and Access Baike API Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-docs/README.md Demonstrates how to initialize the DocsClient with configuration and make a request to the Baike API using a Request object. ```rust use openlark_core::config::Config; use openlark_docs::baike::baike::v1::GetEntityRequest; use openlark_docs::DocsClient; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::builder() .app_id("app_id") .app_secret("app_secret") .build(); let docs = DocsClient::new(config); // 访问知识库(使用 Request 对象方式) let entity = GetEntityRequest::new(docs.baike.config().clone(), "entity_id") .execute() .await?; println!("Entity exists: {}", entity.entity.is_some()); Ok(()) } ``` -------------------------------- ### Cargo Check Command Examples Source: https://github.com/foxzool/openlark/blob/main/RELEASE_NOTES.md Examples of `cargo check` commands used for verifying the crate's integrity and feature combinations during development. ```bash cargo check -p openlark cargo check -p openlark --no-default-features --features docs cargo check -p openlark --example simple_api_call --features "auth,communication" cargo check --workspace --all-features ``` -------------------------------- ### Conventional Commits Message Examples Source: https://github.com/foxzool/openlark/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits format for different types like 'feat', 'fix', and 'docs'. ```bash feat(im): 添加消息撤回功能 fix(auth): 修复token刷新逻辑错误 docs(api): 更新认证接口文档 ``` -------------------------------- ### Basic OpenLark SDK Usage Source: https://github.com/foxzool/openlark/blob/main/README.md Demonstrates basic usage of the OpenLark SDK, including initializing the client, reading folder contents, finding sheets by title, and reading data ranges. ```rust use open_lark::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { let client = Client::builder() .app_id("your_app_id") .app_secret("your_app_secret") .build()?; // 自动分页读取文件夹子项 let children = client .docs .list_folder_children_all("folder_token", Some("sheet")) .await?; println!("文件夹子项数量: {}", children.len()); // 按标题查找工作表并批量读取范围 let sheet = client .docs .find_sheet_by_title("spreadsheet_token", "汇总表") .await?; let ranges = client .docs .read_multiple_ranges( "spreadsheet_token", vec![format!("{}!A1:C10", sheet.sheet_id)], ) .await?; println!("读取范围数量: {}", ranges.value_ranges.len()); // 多维表格全量读取 let records = client .docs .search_bitable_records_all("app_token", "table_id") .await?; println!("记录数量: {}", records.len()); Ok(()) } ``` -------------------------------- ### Development Commands Source: https://github.com/foxzool/openlark/blob/main/AGENTS.md Common commands for formatting, linting, testing, and building the project. ```bash # 开发 just fmt # 格式化代码 just lint # Clippy 检查 just test # 运行测试 just build # 构建项目 ``` -------------------------------- ### Send Text Message (Builder) Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/README.md Example of using the `.text()` method to send a plain text message. ```rust .text("Hello, World!".to_string()) ``` -------------------------------- ### Webhook URL Placeholder Source: https://github.com/foxzool/openlark/blob/main/crates/openlark-webhook/examples/README.md A placeholder for the webhook URL that needs to be replaced with a valid URL before running examples. ```rust let webhook_url = "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_WEBHOOK_KEY".to_string(); ``` -------------------------------- ### Creating RequestOptions in Rust Source: https://github.com/foxzool/openlark/blob/main/docs/api-implementation-template.md Demonstrates various ways to create RequestOption instances, including default, with user access token, with tenant key, and with custom headers. ```rust use openlark_core::req_option::RequestOption; // 方式 1:默认(无特殊选项) let option = RequestOption::default(); // 方式 2:指定 user_access_token let option = RequestOption::builder() .user_access_token("u-xxx".to_string()) .build(); // 方式 3:指定 tenant_key(商店应用) let option = RequestOption::builder() .tenant_key("tenant-xxx".to_string()) .build(); // 方式 4:自定义 header let option = RequestOption::builder() .header("X-Request-Id".to_string(), "req-123".to_string()) .build(); ```