fraiseql-functions 2.3.0

Serverless functions runtime for FraiseQL — WASM and Deno backends
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
//! HTTP triggers: Custom HTTP endpoints backed by functions.
//!
//! HTTP triggers mount custom endpoints on the FraiseQL server that invoke
//! functions to handle requests and generate responses.
//!
//! ## Routing
//!
//! Routes are mounted under `/functions/v1/` prefix:
//! - `GET /functions/v1/users/:id` → `http:GET:/users/:id`
//! - `POST /functions/v1/process` → `http:POST:/process`
//!
//! Path parameters are extracted and passed to the function in the event payload.
//!
//! ## Request Handling
//!
//! The function receives an `HttpTriggerPayload` containing:
//! - HTTP method and path
//! - Query parameters
//! - Path parameters (from `:id` patterns)
//! - Request headers and body
//! - Authentication context (if required)
//!
//! ## Response Format
//!
//! Functions return `HttpTriggerResponse` with:
//! - Optional status code (default 200)
//! - Optional custom headers
//! - Response body (serialized as JSON)
//! # Trigger Format
//!
//! ```text
//! http:<METHOD>:<path>
//! http:GET:/hello
//! http:POST:/users/:id/avatar
//! http:DELETE:/cache/:key
//! ```
//!
//! # Request Mapping
//!
//! HTTP requests are mapped to `EventPayload` with:
//! - `trigger_type`: `"http:GET:/hello"`
//! - `entity`: `"HttpRequest"`
//! - `event_kind`: `"request"`
//! - `data`: Contains method, path, headers, query params, path params, body
//!
//! # Response Mapping
//!
//! Functions return `HttpTriggerResponse` JSON with:
//! ```json
//! {
//!   "status": 201,
//!   "headers": {"x-custom": "value"},
//!   "body": {...}
//! }
//! ```

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// HTTP method for trigger routes.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct HttpMethod(pub String);

impl HttpMethod {
    /// Create a new HTTP method.
    #[must_use]
    pub fn new(method: &str) -> Self {
        Self(method.to_uppercase())
    }

    /// Check if this method matches another.
    #[must_use]
    pub fn matches(&self, other: &str) -> bool {
        self.0.eq_ignore_ascii_case(other)
    }

    /// Get the method as a string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Route for an HTTP trigger.
///
/// Defines a function that handles requests for a specific HTTP method and path.
///
/// # Execution
///
/// When a request matches this route, the function is invoked with an `EventPayload`
/// containing the request data (method, path, headers, body, params, query).
/// The function returns an HTTP response (status, headers, body).
#[derive(Debug, Clone)]
pub struct HttpTriggerRoute {
    /// Name of the function to invoke.
    pub function_name: String,
    /// HTTP method (GET, POST, etc.).
    pub method:        String,
    /// Path pattern (e.g., "/users/:id").
    pub path:          String,
    /// Whether authentication is required.
    pub requires_auth: bool,
}

impl HttpTriggerRoute {
    /// Create a new HTTP trigger route.
    #[must_use]
    pub fn new(function_name: &str, method: &str, path: &str) -> Self {
        Self {
            function_name: function_name.to_string(),
            method:        method.to_string(),
            path:          path.to_string(),
            requires_auth: false,
        }
    }

    /// Builder method to require authentication.
    #[must_use = "builder method returns modified builder"]
    pub const fn with_auth(mut self) -> Self {
        self.requires_auth = true;
        self
    }

    /// Builder method to not require authentication.
    #[must_use = "builder method returns modified builder"]
    pub const fn without_auth(mut self) -> Self {
        self.requires_auth = false;
        self
    }

    /// Check if this route matches the given method and path.
    #[must_use]
    pub fn matches(&self, method: &str, path: &str) -> bool {
        self.method.eq_ignore_ascii_case(method) && self.path == path
    }

    /// Check if this route's path pattern matches a request path.
    ///
    /// Simple pattern matching: exact match or `*` for variable segments.
    #[must_use]
    pub fn pattern_matches(&self, request_path: &str) -> bool {
        let route_parts: Vec<&str> = self.path.split('/').collect();
        let request_parts: Vec<&str> = request_path.split('/').collect();

        if route_parts.len() != request_parts.len() {
            return false;
        }

        route_parts.iter().zip(request_parts.iter()).all(|(route_part, request_part)| {
            // Exact match or parameter (e.g., ":id")
            route_part == request_part || route_part.starts_with(':')
        })
    }

    /// Extract path parameters from a request path.
    ///
    /// Returns a map of parameter names to values.
    #[must_use]
    pub fn extract_params(&self, request_path: &str) -> HashMap<String, String> {
        let mut params = HashMap::new();

        let route_parts: Vec<&str> = self.path.split('/').collect();
        let request_parts: Vec<&str> = request_path.split('/').collect();

        for (route_part, request_part) in route_parts.iter().zip(request_parts.iter()) {
            if let Some(param_name) = route_part.strip_prefix(':') {
                params.insert(param_name.to_string(), request_part.to_string());
            }
        }

        params
    }
}

/// Request payload for HTTP trigger functions.
///
/// Passed to function as `EventPayload.data`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpTriggerPayload {
    /// HTTP method (GET, POST, etc.).
    pub method:  String,
    /// Request path.
    pub path:    String,
    /// Request headers.
    pub headers: serde_json::Value,
    /// Query parameters.
    pub query:   serde_json::Value,
    /// Path parameters (extracted from route pattern).
    pub params:  serde_json::Value,
    /// Request body (if any).
    pub body:    Option<serde_json::Value>,
}

impl HttpTriggerPayload {
    /// Create a new HTTP trigger payload.
    #[must_use]
    pub fn new(
        method: &str,
        path: &str,
        headers: serde_json::Value,
        query: serde_json::Value,
        body: Option<serde_json::Value>,
    ) -> Self {
        Self {
            method: method.to_string(),
            path: path.to_string(),
            headers,
            query,
            params: serde_json::json!({}),
            body,
        }
    }

    /// Get a header value by name (case-insensitive).
    #[must_use]
    pub fn header(&self, name: &str) -> Option<String> {
        let name_lower = name.to_lowercase();
        if let serde_json::Value::Object(ref obj) = self.headers {
            for (key, value) in obj {
                if key.to_lowercase() == name_lower {
                    return value.as_str().map(|s| s.to_string());
                }
            }
        }
        None
    }

    /// Get a query parameter value.
    #[must_use]
    pub fn query_param(&self, name: &str) -> Option<String> {
        self.query.get(name).and_then(|v| v.as_str().map(|s| s.to_string()))
    }

    /// Get a path parameter value.
    #[must_use]
    pub fn path_param(&self, name: &str) -> Option<String> {
        self.params.get(name).and_then(|v| v.as_str().map(|s| s.to_string()))
    }

    /// Get the request body as JSON.
    #[must_use]
    pub const fn json_body(&self) -> Option<&serde_json::Value> {
        self.body.as_ref()
    }

    /// Check if this is a GET request.
    #[must_use]
    pub fn is_get(&self) -> bool {
        self.method.eq_ignore_ascii_case("GET")
    }

    /// Check if this is a POST request.
    #[must_use]
    pub fn is_post(&self) -> bool {
        self.method.eq_ignore_ascii_case("POST")
    }

    /// Check if this is a PUT request.
    #[must_use]
    pub fn is_put(&self) -> bool {
        self.method.eq_ignore_ascii_case("PUT")
    }

    /// Check if this is a DELETE request.
    #[must_use]
    pub fn is_delete(&self) -> bool {
        self.method.eq_ignore_ascii_case("DELETE")
    }

    /// Check if this is a PATCH request.
    #[must_use]
    pub fn is_patch(&self) -> bool {
        self.method.eq_ignore_ascii_case("PATCH")
    }
}

/// Response from an HTTP trigger function.
///
/// Functions should return this format as JSON.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpTriggerResponse {
    /// HTTP status code (default 200).
    pub status:  u16,
    /// Response headers.
    pub headers: serde_json::Value,
    /// Response body.
    pub body:    serde_json::Value,
}

impl HttpTriggerResponse {
    /// Create a successful response with the given body.
    #[must_use]
    pub fn ok(body: serde_json::Value) -> Self {
        Self {
            status: 200,
            headers: serde_json::json!({}),
            body,
        }
    }

    /// Create a response with custom status and body.
    #[must_use]
    pub fn with_status(status: u16, body: serde_json::Value) -> Self {
        Self {
            status,
            headers: serde_json::json!({}),
            body,
        }
    }

    /// Create a 201 Created response.
    #[must_use]
    pub fn created(body: serde_json::Value) -> Self {
        Self::with_status(201, body)
    }

    /// Create a 204 No Content response.
    #[must_use]
    pub fn no_content() -> Self {
        Self {
            status:  204,
            headers: serde_json::json!({}),
            body:    serde_json::json!({}),
        }
    }

    /// Create a 400 Bad Request response.
    #[must_use]
    pub fn bad_request(message: &str) -> Self {
        Self::with_status(400, serde_json::json!({"error": message}))
    }

    /// Create a 401 Unauthorized response.
    #[must_use]
    pub fn unauthorized() -> Self {
        Self::with_status(401, serde_json::json!({"error": "Unauthorized"}))
    }

    /// Create a 403 Forbidden response.
    #[must_use]
    pub fn forbidden() -> Self {
        Self::with_status(403, serde_json::json!({"error": "Forbidden"}))
    }

    /// Create a 404 Not Found response.
    #[must_use]
    pub fn not_found() -> Self {
        Self::with_status(404, serde_json::json!({"error": "Not found"}))
    }

    /// Create a 500 Internal Server Error response.
    #[must_use]
    pub fn internal_error(message: &str) -> Self {
        Self::with_status(500, serde_json::json!({"error": message}))
    }

    /// Add a header to the response.
    #[must_use = "builder method returns modified builder"]
    pub fn with_header(mut self, key: String, value: String) -> Self {
        if let serde_json::Value::Object(ref mut map) = self.headers {
            map.insert(key, serde_json::Value::String(value));
        }
        self
    }
}

/// Matcher for efficiently finding HTTP trigger routes.
///
/// Supports path parameter extraction and pattern matching.
#[derive(Debug, Clone, Default)]
pub struct HttpTriggerMatcher {
    /// Routes indexed by (method, path).
    routes: Vec<HttpTriggerRoute>,
}

impl HttpTriggerMatcher {
    /// Create a new empty HTTP trigger matcher.
    #[must_use]
    pub const fn new() -> Self {
        Self { routes: Vec::new() }
    }

    /// Add a route to the matcher.
    pub fn add(&mut self, route: HttpTriggerRoute) {
        self.routes.push(route);
    }

    /// Find a matching route for the given method and path.
    #[must_use]
    pub fn find(&self, method: &str, path: &str) -> Option<HttpTriggerRoute> {
        self.routes
            .iter()
            .find(|route| route.method.eq_ignore_ascii_case(method) && route.pattern_matches(path))
            .cloned()
    }

    /// Get all routes.
    #[must_use]
    pub fn routes(&self) -> &[HttpTriggerRoute] {
        &self.routes
    }
}

#[cfg(test)]
mod tests;