turbomcp-wasm 3.0.2

WebAssembly bindings for TurboMCP - MCP client for browsers and WASI environments
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
//! Durable Object-backed rate limiter for per-client rate limiting.
//!
//! Provides sliding window rate limiting using Cloudflare Durable Objects
//! for consistent enforcement across Worker instances.

use serde::{Deserialize, Serialize};
use worker::Env;

/// Rate limiter backed by Cloudflare Durable Objects.
///
/// Uses a sliding window algorithm for smooth rate limiting that doesn't
/// have the burst issues of fixed windows.
///
/// # Setup
///
/// Configure the Durable Object binding in `wrangler.toml`:
///
/// ```toml
/// [[durable_objects.bindings]]
/// name = "MCP_RATE_LIMIT"
/// class_name = "McpRateLimitObject"
///
/// [[durable_objects.classes]]
/// name = "McpRateLimitObject"
/// class_name = "McpRateLimitObject"
/// ```
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp_wasm::wasm_server::durable_objects::DurableObjectRateLimiter;
///
/// // Create a rate limiter: 100 requests per minute
/// let limiter = DurableObjectRateLimiter::from_env(&env, "MCP_RATE_LIMIT")?
///     .with_config(RateLimitConfig {
///         limit: 100,
///         window_ms: 60_000, // 1 minute
///     });
///
/// // Check before processing a request
/// let result = limiter.check("client-123").await?;
/// if !result.allowed {
///     return Err(ToolError::new(format!(
///         "Rate limit exceeded. Retry after {}ms",
///         result.retry_after_ms.unwrap_or(0)
///     )));
/// }
///
/// // Process the request...
/// ```
#[derive(Clone)]
pub struct DurableObjectRateLimiter {
    namespace: String,
    env: Option<Env>,
    config: RateLimitConfig,
}

/// Configuration for rate limiting.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Maximum number of requests allowed in the window
    pub limit: u64,
    /// Time window in milliseconds
    pub window_ms: u64,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            limit: 100,        // 100 requests
            window_ms: 60_000, // per minute
        }
    }
}

impl RateLimitConfig {
    /// Create a new rate limit configuration.
    pub fn new(limit: u64, window_ms: u64) -> Self {
        Self { limit, window_ms }
    }

    /// Create a per-second rate limit.
    pub fn per_second(limit: u64) -> Self {
        Self::new(limit, 1_000)
    }

    /// Create a per-minute rate limit.
    pub fn per_minute(limit: u64) -> Self {
        Self::new(limit, 60_000)
    }

    /// Create a per-hour rate limit.
    pub fn per_hour(limit: u64) -> Self {
        Self::new(limit, 3_600_000)
    }
}

/// Result of a rate limit check.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RateLimitResult {
    /// Whether the request is allowed
    pub allowed: bool,
    /// Number of requests remaining in the current window
    pub remaining: u64,
    /// Total limit
    pub limit: u64,
    /// Milliseconds until the rate limit resets
    pub reset_ms: u64,
    /// Milliseconds to wait before retrying (only if not allowed)
    pub retry_after_ms: Option<u64>,
}

impl DurableObjectRateLimiter {
    /// Create a new rate limiter with the given DO namespace binding name.
    pub fn new(namespace: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            env: None,
            config: RateLimitConfig::default(),
        }
    }

    /// Create a rate limiter from an environment binding.
    pub fn from_env(env: &Env, binding: &str) -> worker::Result<Self> {
        // Validate the binding exists
        let _ = env.durable_object(binding)?;
        Ok(Self {
            namespace: binding.to_string(),
            env: Some(env.clone()),
            config: RateLimitConfig::default(),
        })
    }

    /// Set the environment for the limiter.
    pub fn with_env(mut self, env: Env) -> Self {
        self.env = Some(env);
        self
    }

    /// Set the rate limit configuration.
    pub fn with_config(mut self, config: RateLimitConfig) -> Self {
        self.config = config;
        self
    }

    /// Set the rate limit (requests per window).
    pub fn with_limit(mut self, limit: u64) -> Self {
        self.config.limit = limit;
        self
    }

    /// Set the time window in milliseconds.
    pub fn with_window_ms(mut self, window_ms: u64) -> Self {
        self.config.window_ms = window_ms;
        self
    }

    /// Check if a request is allowed for the given client ID.
    ///
    /// If allowed, this also records the request in the rate limiter.
    ///
    /// # Arguments
    ///
    /// * `client_id` - Unique identifier for the client (e.g., IP, API key, session ID)
    ///
    /// # Returns
    ///
    /// A `RateLimitResult` indicating whether the request is allowed.
    pub async fn check(&self, client_id: &str) -> Result<RateLimitResult, RateLimitError> {
        #[derive(Serialize)]
        struct CheckRequest<'a> {
            limit: u64,
            window_ms: u64,
            record: bool,
            client_id: &'a str,
        }

        let request = CheckRequest {
            limit: self.config.limit,
            window_ms: self.config.window_ms,
            record: true,
            client_id,
        };

        self.do_request(client_id, "/rate-limit/check", Some(&request))
            .await
    }

    /// Check the rate limit without recording a request.
    ///
    /// Useful for pre-flight checks or displaying remaining quota.
    pub async fn peek(&self, client_id: &str) -> Result<RateLimitResult, RateLimitError> {
        #[derive(Serialize)]
        struct CheckRequest<'a> {
            limit: u64,
            window_ms: u64,
            record: bool,
            client_id: &'a str,
        }

        let request = CheckRequest {
            limit: self.config.limit,
            window_ms: self.config.window_ms,
            record: false,
            client_id,
        };

        self.do_request(client_id, "/rate-limit/check", Some(&request))
            .await
    }

    /// Reset the rate limit for a client.
    ///
    /// Useful for administrative purposes.
    pub async fn reset(&self, client_id: &str) -> Result<(), RateLimitError> {
        self.do_request::<()>(client_id, "/rate-limit/reset", None::<&()>)
            .await
    }

    /// Send a request to the Durable Object.
    async fn do_request<T: for<'de> Deserialize<'de>>(
        &self,
        client_id: &str,
        path: &str,
        body: Option<&impl Serialize>,
    ) -> Result<T, RateLimitError> {
        let env = self.env.as_ref().ok_or(RateLimitError::NoEnvironment)?;

        let ns = env
            .durable_object(&self.namespace)
            .map_err(RateLimitError::Worker)?;
        let id = ns.id_from_name(client_id).map_err(RateLimitError::Worker)?;
        let stub = id.get_stub().map_err(RateLimitError::Worker)?;

        let mut init = worker::RequestInit::new();
        init.with_method(worker::Method::Post);

        if let Some(body) = body {
            let json = serde_json::to_string(body).map_err(RateLimitError::Serialization)?;
            init.with_body(Some(json.into()));
        }

        let url = format!("https://do-internal{path}");
        let request =
            worker::Request::new_with_init(&url, &init).map_err(RateLimitError::Worker)?;
        let mut response = stub
            .fetch_with_request(request)
            .await
            .map_err(RateLimitError::Worker)?;

        let text = response.text().await.map_err(RateLimitError::Worker)?;
        serde_json::from_str(&text).map_err(RateLimitError::Deserialization)
    }
}

/// Error type for rate limiter operations.
#[derive(Debug)]
pub enum RateLimitError {
    /// No environment has been set
    NoEnvironment,
    /// Worker/DO communication error
    Worker(worker::Error),
    /// Serialization error
    Serialization(serde_json::Error),
    /// Deserialization error
    Deserialization(serde_json::Error),
}

impl std::fmt::Display for RateLimitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoEnvironment => write!(f, "No environment set"),
            Self::Worker(e) => write!(f, "Worker error: {e:?}"),
            Self::Serialization(e) => write!(f, "Serialization error: {e}"),
            Self::Deserialization(e) => write!(f, "Deserialization error: {e}"),
        }
    }
}

impl std::error::Error for RateLimitError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Worker(e) => Some(e),
            Self::Serialization(e) => Some(e),
            Self::Deserialization(e) => Some(e),
            Self::NoEnvironment => None,
        }
    }
}

impl From<worker::Error> for RateLimitError {
    fn from(e: worker::Error) -> Self {
        Self::Worker(e)
    }
}

// ============================================================================
// Protocol Types
// ============================================================================

/// Request/response types for the rate limit Durable Object.
///
/// Implement a Durable Object class that handles these routes:
///
/// - `POST /rate-limit/check` - Check and optionally record a request
/// - `POST /rate-limit/reset` - Reset the rate limit
///
/// # Example Durable Object Implementation
///
/// ```rust,ignore
/// use std::collections::VecDeque;
///
/// #[durable_object]
/// pub struct McpRateLimitObject {
///     state: State,
///     timestamps: VecDeque<u64>,
/// }
///
/// #[durable_object]
/// impl DurableObject for McpRateLimitObject {
///     fn new(state: State, _env: Env) -> Self {
///         Self {
///             state,
///             timestamps: VecDeque::new(),
///         }
///     }
///
///     async fn fetch(&mut self, req: Request) -> Result<Response> {
///         match req.path().as_str() {
///             "/rate-limit/check" => {
///                 #[derive(Deserialize)]
///                 struct Req {
///                     limit: u64,
///                     window_ms: u64,
///                     record: bool,
///                 }
///                 let req: Req = req.json().await?;
///                 let now = js_sys::Date::now() as u64;
///                 let cutoff = now.saturating_sub(req.window_ms);
///
///                 // Remove expired timestamps
///                 while self.timestamps.front().map(|&t| t < cutoff).unwrap_or(false) {
///                     self.timestamps.pop_front();
///                 }
///
///                 let count = self.timestamps.len() as u64;
///                 let allowed = count < req.limit;
///                 let remaining = req.limit.saturating_sub(count + if allowed && req.record { 1 } else { 0 });
///
///                 if allowed && req.record {
///                     self.timestamps.push_back(now);
///                 }
///
///                 let reset_ms = self.timestamps.front()
///                     .map(|&t| req.window_ms.saturating_sub(now.saturating_sub(t)))
///                     .unwrap_or(0);
///
///                 Response::from_json(&json!({
///                     "allowed": allowed,
///                     "remaining": remaining,
///                     "limit": req.limit,
///                     "reset_ms": reset_ms,
///                     "retry_after_ms": if allowed { null } else { Some(reset_ms) }
///                 }))
///             }
///             "/rate-limit/reset" => {
///                 self.timestamps.clear();
///                 Response::ok("{}")
///             }
///             _ => Response::error("Not found", 404),
///         }
///     }
/// }
/// ```
/// Protocol types for implementing the Durable Object handler.
///
/// These types are used for documentation and should be implemented
/// by the user in their Durable Object class.
#[allow(dead_code)]
pub mod protocol {
    use super::*;

    /// Request to check rate limit.
    #[derive(Debug, Serialize, Deserialize)]
    pub struct CheckRequest {
        /// Maximum allowed requests
        pub limit: u64,
        /// Time window in milliseconds
        pub window_ms: u64,
        /// Whether to record this request
        pub record: bool,
        /// Client identifier
        pub client_id: String,
    }

    /// Response from rate limit check.
    pub type CheckResponse = RateLimitResult;
}

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

    #[test]
    fn test_rate_limiter_creation() {
        let limiter = DurableObjectRateLimiter::new("MCP_RATE_LIMIT")
            .with_limit(50)
            .with_window_ms(30_000);

        assert_eq!(limiter.namespace, "MCP_RATE_LIMIT");
        assert_eq!(limiter.config.limit, 50);
        assert_eq!(limiter.config.window_ms, 30_000);
    }

    #[test]
    fn test_rate_limit_config_presets() {
        let per_second = RateLimitConfig::per_second(10);
        assert_eq!(per_second.limit, 10);
        assert_eq!(per_second.window_ms, 1_000);

        let per_minute = RateLimitConfig::per_minute(100);
        assert_eq!(per_minute.limit, 100);
        assert_eq!(per_minute.window_ms, 60_000);

        let per_hour = RateLimitConfig::per_hour(1000);
        assert_eq!(per_hour.limit, 1000);
        assert_eq!(per_hour.window_ms, 3_600_000);
    }

    #[test]
    fn test_rate_limit_error_display() {
        let err = RateLimitError::NoEnvironment;
        assert_eq!(err.to_string(), "No environment set");
    }
}