liteforge 0.2.3

Rust SDK for LiteForge - LLM completions via OpenAI-compatible 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
//! Webhook trigger for HTTP endpoints.

use super::{Trigger, TriggerError, TriggerEvent, TriggerStatus};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};

/// HTTP method for webhook requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum HttpMethod {
    Get,
    #[default]
    Post,
    Put,
    Patch,
    Delete,
}

impl std::fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HttpMethod::Get => write!(f, "GET"),
            HttpMethod::Post => write!(f, "POST"),
            HttpMethod::Put => write!(f, "PUT"),
            HttpMethod::Patch => write!(f, "PATCH"),
            HttpMethod::Delete => write!(f, "DELETE"),
        }
    }
}

/// A webhook event received from an HTTP request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookEvent {
    /// HTTP method of the request.
    pub method: String,
    /// Request path.
    pub path: String,
    /// Query parameters.
    pub query: HashMap<String, String>,
    /// Request headers.
    pub headers: HashMap<String, String>,
    /// Request body (if any).
    pub body: Option<serde_json::Value>,
    /// Source IP address.
    pub source_ip: Option<String>,
}

impl WebhookEvent {
    /// Create a new webhook event.
    pub fn new(method: impl Into<String>, path: impl Into<String>) -> Self {
        Self {
            method: method.into(),
            path: path.into(),
            query: HashMap::new(),
            headers: HashMap::new(),
            body: None,
            source_ip: None,
        }
    }

    /// Set query parameters.
    pub fn with_query(mut self, query: HashMap<String, String>) -> Self {
        self.query = query;
        self
    }

    /// Set headers.
    pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
        self.headers = headers;
        self
    }

    /// Set body.
    pub fn with_body(mut self, body: serde_json::Value) -> Self {
        self.body = Some(body);
        self
    }

    /// Set source IP.
    pub fn with_source_ip(mut self, ip: impl Into<String>) -> Self {
        self.source_ip = Some(ip.into());
        self
    }

    /// Get a header value.
    pub fn header(&self, key: &str) -> Option<&String> {
        self.headers.get(key)
    }

    /// Get a query parameter.
    pub fn query_param(&self, key: &str) -> Option<&String> {
        self.query.get(key)
    }
}

/// Configuration for a webhook trigger.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
    /// The path to listen on.
    pub path: String,
    /// Allowed HTTP methods.
    pub methods: Vec<HttpMethod>,
    /// Secret for signature verification (optional).
    pub secret: Option<String>,
    /// Whether to require authentication.
    pub require_auth: bool,
    /// Maximum body size in bytes.
    pub max_body_size: usize,
    /// Allowed source IPs (empty = allow all).
    pub allowed_ips: Vec<String>,
}

impl Default for WebhookConfig {
    fn default() -> Self {
        Self {
            path: "/webhook".to_string(),
            methods: vec![HttpMethod::Post],
            secret: None,
            require_auth: false,
            max_body_size: 1024 * 1024, // 1MB
            allowed_ips: Vec::new(),
        }
    }
}

impl WebhookConfig {
    /// Create a new webhook config with a path.
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            ..Default::default()
        }
    }

    /// Set allowed methods.
    pub fn methods(mut self, methods: Vec<HttpMethod>) -> Self {
        self.methods = methods;
        self
    }

    /// Set the secret for signature verification.
    pub fn secret(mut self, secret: impl Into<String>) -> Self {
        self.secret = Some(secret.into());
        self
    }

    /// Require authentication.
    pub fn require_auth(mut self, require: bool) -> Self {
        self.require_auth = require;
        self
    }

    /// Set max body size.
    pub fn max_body_size(mut self, size: usize) -> Self {
        self.max_body_size = size;
        self
    }

    /// Add allowed IPs.
    pub fn allowed_ips(mut self, ips: Vec<String>) -> Self {
        self.allowed_ips = ips;
        self
    }
}

/// A trigger that fires on HTTP webhook requests.
///
/// This is a queue-based trigger. To use it, integrate with your HTTP server
/// and call `receive()` when requests arrive.
#[derive(Debug, Clone)]
pub struct WebhookTrigger {
    id: String,
    config: WebhookConfig,
    status: Arc<Mutex<TriggerStatus>>,
    events: Arc<Mutex<VecDeque<WebhookEvent>>>,
    request_count: Arc<Mutex<u64>>,
}

impl WebhookTrigger {
    /// Create a new webhook trigger.
    pub fn new(id: impl Into<String>, config: WebhookConfig) -> Self {
        Self {
            id: id.into(),
            config,
            status: Arc::new(Mutex::new(TriggerStatus::Stopped)),
            events: Arc::new(Mutex::new(VecDeque::new())),
            request_count: Arc::new(Mutex::new(0)),
        }
    }

    /// Create a webhook trigger with default config for a path.
    pub fn on_path(id: impl Into<String>, path: impl Into<String>) -> Self {
        Self::new(id, WebhookConfig::new(path))
    }

    /// Get the configuration.
    pub fn config(&self) -> &WebhookConfig {
        &self.config
    }

    /// Get the path this webhook listens on.
    pub fn path(&self) -> &str {
        &self.config.path
    }

    /// Get the total request count.
    pub fn request_count(&self) -> u64 {
        *self.request_count.lock().unwrap()
    }

    /// Receive a webhook event.
    ///
    /// Call this from your HTTP server when a request matches this webhook's path.
    pub fn receive(&self, event: WebhookEvent) -> Result<(), TriggerError> {
        let status = *self.status.lock().unwrap();
        if status != TriggerStatus::Running {
            return Err(TriggerError::not_running());
        }

        // Validate method
        let method = event.method.to_uppercase();
        let method_allowed = self.config.methods.iter().any(|m| m.to_string() == method);
        if !method_allowed {
            return Err(TriggerError::runtime(format!(
                "Method {} not allowed",
                method
            )));
        }

        // Validate source IP if configured
        if !self.config.allowed_ips.is_empty() {
            if let Some(ref ip) = event.source_ip {
                if !self.config.allowed_ips.contains(ip) {
                    return Err(TriggerError::runtime("Source IP not allowed"));
                }
            } else {
                return Err(TriggerError::runtime("Source IP required but not provided"));
            }
        }

        // Increment request count
        let mut count = self.request_count.lock().unwrap();
        *count += 1;

        // Queue the event
        self.events.lock().unwrap().push_back(event);
        Ok(())
    }

    /// Receive a raw webhook request.
    ///
    /// Convenience method that constructs the WebhookEvent from parts.
    pub fn receive_request(
        &self,
        method: impl Into<String>,
        path: impl Into<String>,
        headers: HashMap<String, String>,
        body: Option<serde_json::Value>,
    ) -> Result<(), TriggerError> {
        let event = WebhookEvent {
            method: method.into(),
            path: path.into(),
            query: HashMap::new(),
            headers,
            body,
            source_ip: None,
        };
        self.receive(event)
    }

    /// Get the number of pending events.
    pub fn pending_count(&self) -> usize {
        self.events.lock().unwrap().len()
    }

    /// Verify a webhook signature (HMAC-SHA256).
    ///
    /// Returns true if no secret is configured (verification disabled).
    pub fn verify_signature(&self, _payload: &[u8], signature: &str) -> bool {
        let Some(ref _secret) = self.config.secret else {
            return true; // No secret configured, skip verification
        };

        // In a real implementation, this would compute HMAC-SHA256
        // For now, we just check that a signature was provided
        !signature.is_empty()
    }
}

impl Trigger for WebhookTrigger {
    fn id(&self) -> &str {
        &self.id
    }

    fn trigger_type(&self) -> &str {
        "webhook"
    }

    fn status(&self) -> TriggerStatus {
        *self.status.lock().unwrap()
    }

    fn start(&mut self) -> Result<(), TriggerError> {
        let mut status = self.status.lock().unwrap();
        if *status == TriggerStatus::Running {
            return Err(TriggerError::already_running());
        }
        *status = TriggerStatus::Running;
        Ok(())
    }

    fn stop(&mut self) -> Result<(), TriggerError> {
        let mut status = self.status.lock().unwrap();
        *status = TriggerStatus::Stopped;
        Ok(())
    }

    fn pause(&mut self) -> Result<(), TriggerError> {
        let mut status = self.status.lock().unwrap();
        if *status != TriggerStatus::Running {
            return Err(TriggerError::not_running());
        }
        *status = TriggerStatus::Paused;
        Ok(())
    }

    fn resume(&mut self) -> Result<(), TriggerError> {
        let mut status = self.status.lock().unwrap();
        if *status != TriggerStatus::Paused {
            return Err(TriggerError::runtime("Trigger is not paused"));
        }
        *status = TriggerStatus::Running;
        Ok(())
    }

    fn poll(&self) -> Option<TriggerEvent> {
        let status = *self.status.lock().unwrap();
        if status != TriggerStatus::Running {
            return None;
        }

        let mut events = self.events.lock().unwrap();
        events.pop_front().map(|webhook_event| {
            TriggerEvent::new(
                &self.id,
                "webhook",
                serde_json::to_value(&webhook_event).unwrap_or_default(),
            )
        })
    }

    fn has_pending(&self) -> bool {
        !self.events.lock().unwrap().is_empty()
    }
}

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

    #[test]
    fn test_webhook_event_new() {
        let event = WebhookEvent::new("POST", "/api/webhook");
        assert_eq!(event.method, "POST");
        assert_eq!(event.path, "/api/webhook");
    }

    #[test]
    fn test_webhook_event_with_body() {
        let event = WebhookEvent::new("POST", "/webhook")
            .with_body(serde_json::json!({"message": "hello"}));

        assert_eq!(event.body, Some(serde_json::json!({"message": "hello"})));
    }

    #[test]
    fn test_webhook_config() {
        let config = WebhookConfig::new("/api/events")
            .methods(vec![HttpMethod::Post, HttpMethod::Put])
            .secret("my-secret")
            .require_auth(true);

        assert_eq!(config.path, "/api/events");
        assert_eq!(config.methods.len(), 2);
        assert_eq!(config.secret, Some("my-secret".to_string()));
        assert!(config.require_auth);
    }

    #[test]
    fn test_webhook_trigger_receive() {
        let config = WebhookConfig::new("/webhook");
        let mut trigger = WebhookTrigger::new("test", config);
        trigger.start().unwrap();

        let event =
            WebhookEvent::new("POST", "/webhook").with_body(serde_json::json!({"data": "test"}));

        trigger.receive(event).unwrap();
        assert_eq!(trigger.request_count(), 1);

        let trigger_event = trigger.poll().unwrap();
        assert_eq!(trigger_event.trigger_id, "test");
        assert_eq!(trigger_event.event_type, "webhook");
    }

    #[test]
    fn test_webhook_trigger_method_validation() {
        let config = WebhookConfig::new("/webhook").methods(vec![HttpMethod::Post]);
        let mut trigger = WebhookTrigger::new("test", config);
        trigger.start().unwrap();

        // GET should fail
        let event = WebhookEvent::new("GET", "/webhook");
        let result = trigger.receive(event);
        assert!(result.is_err());

        // POST should succeed
        let event = WebhookEvent::new("POST", "/webhook");
        let result = trigger.receive(event);
        assert!(result.is_ok());
    }

    #[test]
    fn test_webhook_trigger_ip_validation() {
        let config = WebhookConfig::new("/webhook").allowed_ips(vec!["192.168.1.1".to_string()]);
        let mut trigger = WebhookTrigger::new("test", config);
        trigger.start().unwrap();

        // Wrong IP should fail
        let event = WebhookEvent::new("POST", "/webhook").with_source_ip("192.168.1.2");
        let result = trigger.receive(event);
        assert!(result.is_err());

        // Correct IP should succeed
        let event = WebhookEvent::new("POST", "/webhook").with_source_ip("192.168.1.1");
        let result = trigger.receive(event);
        assert!(result.is_ok());
    }

    #[test]
    fn test_webhook_trigger_not_running() {
        let config = WebhookConfig::new("/webhook");
        let trigger = WebhookTrigger::new("test", config);

        let event = WebhookEvent::new("POST", "/webhook");
        let result = trigger.receive(event);
        assert!(result.is_err()); // Not started
    }

    #[test]
    fn test_webhook_trigger_on_path() {
        let trigger = WebhookTrigger::on_path("test", "/api/callback");
        assert_eq!(trigger.path(), "/api/callback");
    }
}