slack-rs 0.1.70

A Slack CLI tool with OAuth authentication, profile management, and API access
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
//! HTTP client for Slack API calls
//!
//! This module provides a configurable HTTP client with:
//! - Configurable base URL (for testing with mock servers)
//! - Retry logic with exponential backoff
//! - Rate limit handling (429 + Retry-After)
//! - Support for both wrapper commands and generic API calls

use reqwest::{Client, Method, Response, StatusCode};
use serde_json::Value;
use std::collections::HashMap;
use std::time::Duration;
use thiserror::Error;

use super::guidance::format_error_guidance;
use super::types::{ApiMethod, ApiResponse};

/// API client errors (for wrapper commands)
#[derive(Error, Debug)]
pub enum ApiError {
    #[error("HTTP request failed: {0}")]
    RequestFailed(#[from] reqwest::Error),

    #[error("JSON serialization failed: {0}")]
    JsonError(#[from] serde_json::Error),

    #[error("Slack API error: {0}")]
    SlackError(String),

    #[allow(dead_code)]
    #[error("Missing required parameter: {0}")]
    MissingParameter(String),

    #[error("Write operation denied. Set SLACKCLI_ALLOW_WRITE=true to enable write operations")]
    WriteNotAllowed,

    #[error("Destructive operation cancelled")]
    OperationCancelled,

    #[error("Non-interactive mode error: {0}")]
    NonInteractiveError(String),
}

/// API client errors (for generic API calls)
#[derive(Debug, Error)]
pub enum ApiClientError {
    #[error("HTTP request failed: {0}")]
    RequestFailed(#[from] reqwest::Error),

    #[error("Rate limit exceeded, retry after {0} seconds")]
    RateLimitExceeded(u64),

    #[error("API error: {0}")]
    ApiError(String),

    #[error("Invalid response: {0}")]
    InvalidResponse(String),
}

pub type Result<T> = std::result::Result<T, ApiClientError>;

/// Configuration for the API client
#[derive(Debug, Clone)]
pub struct ApiClientConfig {
    /// Base URL for API calls (default: https://slack.com/api)
    pub base_url: String,

    /// Maximum number of retry attempts
    pub max_retries: u32,

    /// Initial backoff duration in milliseconds
    pub initial_backoff_ms: u64,

    /// Maximum backoff duration in milliseconds
    pub max_backoff_ms: u64,
}

impl Default for ApiClientConfig {
    fn default() -> Self {
        Self {
            base_url: "https://slack.com/api".to_string(),
            max_retries: 3,
            initial_backoff_ms: 1000,
            max_backoff_ms: 32000,
        }
    }
}

/// Slack API client
///
/// Supports both:
/// - Wrapper commands via `call_method()` with `ApiMethod` enum
/// - Generic API calls via `call()` with arbitrary endpoints
pub struct ApiClient {
    client: Client,
    pub(crate) token: Option<String>,
    config: ApiClientConfig,
}

impl ApiClient {
    /// Create a new API client with default configuration (for generic API calls)
    pub fn new() -> Self {
        Self::with_config(ApiClientConfig::default())
    }

    /// Create a new API client with a token (for wrapper commands)
    pub fn with_token(token: String) -> Self {
        Self {
            client: Client::builder()
                .timeout(Duration::from_secs(30))
                .build()
                .expect("Failed to create HTTP client"),
            token: Some(token),
            config: ApiClientConfig::default(),
        }
    }

    /// Create a new API client with custom configuration
    pub fn with_config(config: ApiClientConfig) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("Failed to create HTTP client");

        Self {
            client,
            token: None,
            config,
        }
    }

    /// Create a new API client with custom base URL (for testing)
    #[doc(hidden)]
    #[allow(dead_code)]
    pub fn new_with_base_url(token: String, base_url: String) -> Self {
        Self {
            client: Client::new(),
            token: Some(token),
            config: ApiClientConfig {
                base_url,
                ..Default::default()
            },
        }
    }

    /// Get the base URL
    pub fn base_url(&self) -> &str {
        &self.config.base_url
    }

    /// Call a Slack API method using the ApiMethod enum (for wrapper commands)
    pub async fn call_method(
        &self,
        method: ApiMethod,
        params: HashMap<String, Value>,
    ) -> std::result::Result<ApiResponse, ApiError> {
        let token = self
            .token
            .as_ref()
            .ok_or_else(|| ApiError::SlackError("No token configured".to_string()))?;

        let url = format!("{}/{}", self.config.base_url, method.as_str());

        let response = if method.uses_get_method() {
            // Use GET request with query parameters
            let mut query_params = vec![];
            for (key, value) in params {
                let value_str = match value {
                    Value::String(s) => s,
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    _ => serde_json::to_string(&value).unwrap_or_default(),
                };
                query_params.push((key, value_str));
            }

            self.client
                .get(&url)
                .bearer_auth(token)
                .query(&query_params)
                .send()
                .await?
        } else {
            // Use POST request with JSON body
            self.client
                .post(&url)
                .bearer_auth(token)
                .json(&params)
                .send()
                .await?
        };

        let response_json: ApiResponse = response.json().await?;

        if !response_json.ok {
            let error_code = response_json.error.as_deref().unwrap_or("Unknown error");

            // Display error guidance if available
            if let Some(guidance) = format_error_guidance(error_code) {
                eprintln!("{}", guidance);
            }

            return Err(ApiError::SlackError(error_code.to_string()));
        }

        Ok(response_json)
    }

    /// Make an API call with automatic retry logic (for generic API calls)
    pub async fn call(
        &self,
        method: Method,
        endpoint: &str,
        token: &str,
        body: RequestBody,
        query_params: Vec<(String, String)>,
    ) -> Result<Response> {
        let url = format!("{}/{}", self.config.base_url, endpoint);
        let mut attempt = 0;

        loop {
            let response = self
                .execute_request(&url, &method, token, &body, &query_params)
                .await?;

            // Check for rate limiting
            if response.status() == StatusCode::TOO_MANY_REQUESTS {
                // Extract Retry-After header
                let retry_after = self.extract_retry_after(&response);

                if attempt >= self.config.max_retries {
                    return Err(ApiClientError::RateLimitExceeded(retry_after));
                }

                // Wait for the specified duration
                tokio::time::sleep(Duration::from_secs(retry_after)).await;
                attempt += 1;
                continue;
            }

            // For other errors, apply exponential backoff
            if !response.status().is_success() && attempt < self.config.max_retries {
                let backoff = self.calculate_backoff(attempt);
                tokio::time::sleep(backoff).await;
                attempt += 1;
                continue;
            }

            return Ok(response);
        }
    }

    /// Execute a single HTTP request
    async fn execute_request(
        &self,
        url: &str,
        method: &Method,
        token: &str,
        body: &RequestBody,
        query_params: &[(String, String)],
    ) -> Result<Response> {
        let mut request = self.client.request(method.clone(), url);

        // Add authorization header
        request = request.header("Authorization", format!("Bearer {}", token));

        // Add query parameters
        if !query_params.is_empty() {
            request = request.query(query_params);
        }

        // Add body based on type
        match body {
            RequestBody::Form(params) => {
                request = request
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .form(params);
            }
            RequestBody::Json(json) => {
                request = request
                    .header("Content-Type", "application/json")
                    .json(json);
            }
            RequestBody::None => {}
        }

        let response = request.send().await?;
        Ok(response)
    }

    /// Extract Retry-After header value
    fn extract_retry_after(&self, response: &Response) -> u64 {
        response
            .headers()
            .get("Retry-After")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(60) // Default to 60 seconds if not specified
    }

    /// Calculate exponential backoff with jitter
    fn calculate_backoff(&self, attempt: u32) -> Duration {
        let base = self.config.initial_backoff_ms;
        let max = self.config.max_backoff_ms;

        // Exponential backoff: base * 2^attempt
        let backoff = base * 2_u64.pow(attempt);
        let backoff = backoff.min(max);

        // Add jitter (±25%)
        let jitter = (backoff as f64 * 0.25) as u64;
        let jitter = rand::random::<u64>() % (jitter * 2 + 1);
        let backoff = backoff
            .saturating_sub(jitter / 2)
            .saturating_add(jitter / 2);

        Duration::from_millis(backoff)
    }
}

impl Default for ApiClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Request body type
#[derive(Debug, Clone)]
pub enum RequestBody {
    Form(Vec<(String, String)>),
    Json(Value),
    None,
}

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

    #[test]
    fn test_api_method_as_str() {
        assert_eq!(ApiMethod::SearchMessages.as_str(), "search.messages");
        assert_eq!(ApiMethod::ConversationsList.as_str(), "conversations.list");
        assert_eq!(
            ApiMethod::ConversationsHistory.as_str(),
            "conversations.history"
        );
        assert_eq!(
            ApiMethod::ConversationsReplies.as_str(),
            "conversations.replies"
        );
        assert_eq!(ApiMethod::UsersInfo.as_str(), "users.info");
        assert_eq!(ApiMethod::ChatPostMessage.as_str(), "chat.postMessage");
        assert_eq!(ApiMethod::ChatUpdate.as_str(), "chat.update");
        assert_eq!(ApiMethod::ChatDelete.as_str(), "chat.delete");
        assert_eq!(ApiMethod::ReactionsAdd.as_str(), "reactions.add");
        assert_eq!(ApiMethod::ReactionsRemove.as_str(), "reactions.remove");
    }

    #[test]
    fn test_api_method_is_write() {
        assert!(!ApiMethod::SearchMessages.is_write());
        assert!(!ApiMethod::ConversationsList.is_write());
        assert!(!ApiMethod::ConversationsHistory.is_write());
        assert!(!ApiMethod::UsersInfo.is_write());
        assert!(ApiMethod::ChatPostMessage.is_write());
        assert!(ApiMethod::ChatUpdate.is_write());
        assert!(ApiMethod::ChatDelete.is_write());
        assert!(ApiMethod::ReactionsAdd.is_write());
        assert!(ApiMethod::ReactionsRemove.is_write());
    }

    #[test]
    fn test_api_method_is_destructive() {
        assert!(!ApiMethod::SearchMessages.is_destructive());
        assert!(!ApiMethod::ConversationsList.is_destructive());
        assert!(!ApiMethod::ConversationsHistory.is_destructive());
        assert!(!ApiMethod::UsersInfo.is_destructive());
        assert!(!ApiMethod::ChatPostMessage.is_destructive());
        assert!(ApiMethod::ChatUpdate.is_destructive());
        assert!(ApiMethod::ChatDelete.is_destructive());
        assert!(!ApiMethod::ReactionsAdd.is_destructive());
        assert!(ApiMethod::ReactionsRemove.is_destructive());
    }

    #[test]
    fn test_api_method_uses_get() {
        // GET methods
        assert!(ApiMethod::SearchMessages.uses_get_method());
        assert!(ApiMethod::ConversationsList.uses_get_method());
        assert!(ApiMethod::ConversationsHistory.uses_get_method());
        assert!(ApiMethod::ConversationsReplies.uses_get_method());
        assert!(ApiMethod::UsersInfo.uses_get_method());
        assert!(ApiMethod::UsersList.uses_get_method());

        // POST methods
        assert!(!ApiMethod::ChatPostMessage.uses_get_method());
        assert!(!ApiMethod::ChatUpdate.uses_get_method());
        assert!(!ApiMethod::ChatDelete.uses_get_method());
        assert!(!ApiMethod::ReactionsAdd.uses_get_method());
        assert!(!ApiMethod::ReactionsRemove.uses_get_method());
    }

    #[test]
    fn test_api_client_config_default() {
        let config = ApiClientConfig::default();
        assert_eq!(config.base_url, "https://slack.com/api");
        assert_eq!(config.max_retries, 3);
        assert_eq!(config.initial_backoff_ms, 1000);
        assert_eq!(config.max_backoff_ms, 32000);
    }

    #[test]
    fn test_api_client_creation() {
        let client = ApiClient::new();
        assert_eq!(client.base_url(), "https://slack.com/api");
    }

    #[test]
    fn test_api_client_custom_config() {
        let config = ApiClientConfig {
            base_url: "https://test.example.com".to_string(),
            max_retries: 5,
            initial_backoff_ms: 500,
            max_backoff_ms: 10000,
        };

        let client = ApiClient::with_config(config.clone());
        assert_eq!(client.base_url(), "https://test.example.com");
        assert_eq!(client.config.max_retries, 5);
    }
}