hyperchad_renderer_html_lambda 0.4.0

HyperChad HTML Lambda renderer package
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! AWS Lambda renderer implementation for `HyperChad` HTML applications.
//!
//! This crate provides a Lambda-based runtime for `HyperChad` HTML renderers,
//! enabling serverless deployment of `HyperChad` applications on AWS Lambda.
//! It handles HTTP request/response processing, gzip compression, and
//! integrates with the `HyperChad` renderer framework.
//!
//! # Features
//!
//! * `assets` - Enable static asset route support (enabled by default)
//! * `json` - Enable JSON response content type (enabled by default)
//! * `debug` - Enable debug logging (enabled by default)
//!
//! # Example
//!
//! ```rust,no_run
//! use hyperchad_renderer_html_lambda::{LambdaApp, LambdaResponseProcessor, Content};
//! use hyperchad_renderer::ToRenderRunner;
//! use async_trait::async_trait;
//! use std::sync::Arc;
//! use bytes::Bytes;
//! # use lambda_http::Request;
//!
//! #[derive(Clone)]
//! struct MyProcessor;
//!
//! #[async_trait]
//! impl LambdaResponseProcessor<String> for MyProcessor {
//!     fn prepare_request(
//!         &self,
//!         req: Request,
//!         body: Option<Arc<Bytes>>,
//!     ) -> Result<String, lambda_runtime::Error> {
//!         Ok(req.uri().path().to_string())
//!     }
//!
//!     fn headers(&self, _content: &hyperchad_renderer::Content) -> Option<Vec<(String, String)>> {
//!         None
//!     }
//!
//!     async fn to_response(
//!         &self,
//!         data: String,
//!     ) -> Result<Option<(Content, Option<Vec<(String, String)>>)>, lambda_runtime::Error> {
//!         Ok(Some((Content::Html(format!("<h1>Path: {}</h1>", data)), None)))
//!     }
//!
//!     async fn to_body(
//!         &self,
//!         _content: hyperchad_renderer::Content,
//!         _data: String,
//!     ) -> Result<Content, lambda_runtime::Error> {
//!         Ok(Content::Html("<h1>Hello</h1>".to_string()))
//!     }
//! }
//! ```

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use std::{io::Write, marker::PhantomData, sync::Arc};

use async_trait::async_trait;
use bytes::Bytes;
use flate2::{Compression, write::GzEncoder};
use hyperchad_renderer::{Handle, RenderRunner, ToRenderRunner};
use lambda_http::{
    Request, Response,
    http::header::{CONTENT_ENCODING, CONTENT_TYPE},
    service_fn,
};

/// Re-exported [`lambda_http`] crate for request/response types.
///
/// Provides access to HTTP request/response types, the `Request` and `Response`
/// builders, and other HTTP-related utilities needed when implementing
/// [`LambdaResponseProcessor`].
///
/// [`lambda_http`]: https://docs.rs/lambda_http
pub use lambda_http;

/// Re-exported [`lambda_runtime`] crate for Lambda runtime types.
///
/// Provides access to the `Error` type used throughout this crate's API,
/// as well as other Lambda runtime utilities.
///
/// [`lambda_runtime`]: https://docs.rs/lambda_runtime
pub use lambda_runtime;

/// HTTP response content types for Lambda responses.
///
/// Represents the different types of content that can be returned from a Lambda
/// function, each with appropriate MIME type handling.
pub enum Content {
    /// HTML content with UTF-8 encoding.
    ///
    /// The content will be sent with `Content-Type: text/html; charset=utf-8`.
    Html(String),
    /// Raw binary content with a custom content type.
    ///
    /// Use this variant for serving any binary data (images, PDFs, etc.) or
    /// non-HTML text formats with a specific MIME type.
    Raw {
        /// The binary data to send.
        data: Bytes,
        /// The MIME type for the content.
        content_type: String,
    },
    /// JSON content (requires `json` feature).
    ///
    /// The content will be sent with `Content-Type: application/json`.
    /// Automatically serializes the value to JSON string format.
    #[cfg(feature = "json")]
    Json(serde_json::Value),
}

/// Processes Lambda HTTP requests and generates responses.
///
/// This trait defines the interface for handling Lambda HTTP events, allowing
/// custom request processing, response generation, and content transformation.
/// Implementors control how requests are parsed, what content is generated,
/// and how it's formatted for the HTTP response.
#[async_trait]
pub trait LambdaResponseProcessor<T: Send + Sync + Clone> {
    /// Prepares request data for processing.
    ///
    /// Extracts and transforms the incoming Lambda HTTP request and optional
    /// body into the application's request type `T`.
    ///
    /// # Errors
    ///
    /// Implementations may return errors for:
    /// * Invalid request format or missing required data
    /// * Request parsing or validation failures
    /// * Authentication or authorization failures
    fn prepare_request(
        &self,
        req: Request,
        body: Option<Arc<Bytes>>,
    ) -> Result<T, lambda_runtime::Error>;

    /// Returns additional HTTP headers for the response based on content.
    ///
    /// Allows adding custom headers like `Cache-Control`, `ETag`, or
    /// `Content-Security-Policy` based on the rendered content.
    fn headers(&self, content: &hyperchad_renderer::Content) -> Option<Vec<(String, String)>>;

    /// Generates the response content and headers from processed data.
    ///
    /// Produces the final response content and optional headers from the
    /// prepared request data. Returns `None` to indicate no response should
    /// be sent (for handling by other middleware or routes).
    ///
    /// # Errors
    ///
    /// Implementations may return errors for:
    /// * Data fetching or database query failures
    /// * Business logic validation errors
    /// * Template rendering failures
    async fn to_response(
        &self,
        data: T,
    ) -> Result<Option<(Content, Option<Vec<(String, String)>>)>, lambda_runtime::Error>;

    /// Converts rendered content to the appropriate response body type.
    ///
    /// Transforms `hyperchad_renderer::Content` into the Lambda response
    /// `Content` format, allowing customization of how rendered content
    /// is serialized for HTTP responses.
    ///
    /// # Errors
    ///
    /// Implementations may return errors for:
    /// * Content serialization or encoding failures
    /// * Resource loading failures when building the response
    async fn to_body(
        &self,
        content: hyperchad_renderer::Content,
        data: T,
    ) -> Result<Content, lambda_runtime::Error>;
}

/// Lambda application with configurable response processing.
///
/// The main entry point for creating a Lambda-based `HyperChad` application.
/// Combines a custom `LambdaResponseProcessor` with optional static asset
/// routing to handle HTTP requests in AWS Lambda environment.
#[derive(Clone)]
pub struct LambdaApp<T: Send + Sync + Clone, R: LambdaResponseProcessor<T> + Send + Sync + Clone> {
    /// The response processor for handling requests.
    pub processor: R,
    /// Static asset routes (requires `assets` feature).
    ///
    /// Defines routes that serve embedded static files like CSS, JavaScript,
    /// or images. Only available when the `assets` feature is enabled.
    #[cfg(feature = "assets")]
    pub static_asset_routes: Vec<hyperchad_renderer::assets::StaticAssetRoute>,
    _phantom: PhantomData<T>,
}

impl<T: Send + Sync + Clone, R: LambdaResponseProcessor<T> + Send + Sync + Clone> LambdaApp<T, R> {
    /// Creates a new Lambda application with the given response processor.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperchad_renderer_html_lambda::{LambdaApp, LambdaResponseProcessor};
    /// # use async_trait::async_trait;
    /// # #[derive(Clone)]
    /// # struct MyProcessor;
    /// # #[async_trait]
    /// # impl LambdaResponseProcessor<String> for MyProcessor {
    /// #     fn prepare_request(&self, req: lambda_http::Request, body: Option<std::sync::Arc<bytes::Bytes>>) -> Result<String, lambda_runtime::Error> { Ok(String::new()) }
    /// #     fn headers(&self, content: &hyperchad_renderer::Content) -> Option<Vec<(String, String)>> { None }
    /// #     async fn to_response(&self, data: String) -> Result<Option<(hyperchad_renderer_html_lambda::Content, Option<Vec<(String, String)>>)>, lambda_runtime::Error> { Ok(None) }
    /// #     async fn to_body(&self, content: hyperchad_renderer::Content, data: String) -> Result<hyperchad_renderer_html_lambda::Content, lambda_runtime::Error> { Ok(hyperchad_renderer_html_lambda::Content::Html(String::new())) }
    /// # }
    /// let processor = MyProcessor;
    /// let app = LambdaApp::new(processor);
    /// ```
    #[must_use]
    pub const fn new(to_html: R) -> Self {
        Self {
            processor: to_html,
            #[cfg(feature = "assets")]
            static_asset_routes: vec![],
            _phantom: PhantomData,
        }
    }
}

impl<
    T: Send + Sync + Clone + 'static,
    R: LambdaResponseProcessor<T> + Send + Sync + Clone + 'static,
> ToRenderRunner for LambdaApp<T, R>
{
    /// Converts the Lambda application into a runtime-ready runner.
    ///
    /// Creates a `LambdaAppRunner` that wraps this application with the
    /// provided async runtime handle, preparing it for execution in the
    /// Lambda event loop.
    ///
    /// # Errors
    ///
    /// This implementation always returns `Ok` and does not produce errors.
    fn to_runner(
        self,
        handle: Handle,
    ) -> Result<Box<dyn RenderRunner>, Box<dyn std::error::Error + Send>> {
        Ok(Box::new(LambdaAppRunner { app: self, handle }))
    }
}

/// Runtime handler for executing the Lambda application.
///
/// Wraps a `LambdaApp` with a runtime handle to execute the Lambda event loop.
/// This type is created automatically when converting a `LambdaApp` to a
/// `RenderRunner` via the `ToRenderRunner` trait.
pub struct LambdaAppRunner<
    T: Send + Sync + Clone,
    R: LambdaResponseProcessor<T> + Send + Sync + Clone,
> {
    /// The Lambda application configuration.
    pub app: LambdaApp<T, R>,
    /// Runtime handle for async execution.
    ///
    /// Provides the async runtime context for executing Lambda handlers.
    pub handle: Handle,
}

impl<
    T: Send + Sync + Clone + 'static,
    R: LambdaResponseProcessor<T> + Send + Sync + Clone + 'static,
> RenderRunner for LambdaAppRunner<T, R>
{
    /// Runs the Lambda runtime event loop to handle incoming HTTP requests.
    ///
    /// # Errors
    ///
    /// * If the Lambda runtime fails to start or process events
    /// * If request preparation fails via `prepare_request`
    /// * If response generation fails via `to_response`
    /// * If gzip compression fails during encoding
    /// * If JSON serialization fails (when using `json` feature)
    /// * If response building fails
    #[allow(clippy::too_many_lines)]
    fn run(&mut self) -> Result<(), Box<dyn std::error::Error + Send>> {
        log::debug!("run: starting");

        let app = self.app.clone();
        let func = service_fn(move |event: Request| {
            let app = app.clone();
            async move {
                let body: &[u8] = event.body().as_ref();
                let body = Bytes::copy_from_slice(body);
                let body = if body.is_empty() {
                    None
                } else {
                    Some(Arc::new(body))
                };
                let data = app.processor.prepare_request(event, body)?;
                let content = app.processor.to_response(data).await?;

                let mut response = Response::builder()
                    .status(200)
                    .header(CONTENT_ENCODING, "gzip");

                let mut gz = GzEncoder::new(vec![], Compression::default());

                if let Some((content, headers)) = content {
                    if let Some(headers) = headers {
                        for (key, value) in headers {
                            response = response.header(key, value);
                        }
                    }
                    match content {
                        Content::Html(x) => {
                            log::debug!("run: sending HTML response type");
                            gz.write_all(x.as_bytes())?;
                            response = response.header(CONTENT_TYPE, "text/html; charset=utf-8");
                        }
                        Content::Raw { data, content_type } => {
                            log::debug!("run: sending raw response type '{content_type}'");
                            gz.write_all(&data)?;
                            response = response.header(CONTENT_TYPE, content_type);
                        }
                        #[cfg(feature = "json")]
                        Content::Json(x) => {
                            log::debug!("run: sending JSON response type");
                            gz.write_all(serde_json::to_string(&x)?.as_bytes())?;
                            response = response.header(CONTENT_TYPE, "application/json");
                        }
                    }
                }

                let gzip = gz.finish()?;

                let response = response
                    .body(lambda_http::Body::Binary(gzip))
                    .map_err(Box::new)?;

                Ok::<_, lambda_runtime::Error>(response)
            }
        });

        self.handle
            .block_on(async move { lambda_http::run_with_streaming_response(func).await })
            .map_err(|e| e as Box<dyn std::error::Error + Send>)?;

        log::debug!("run: finished");

        Ok(())
    }
}

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

    #[cfg(feature = "assets")]
    #[derive(Clone)]
    struct TestProcessor;

    #[cfg(feature = "assets")]
    #[async_trait]
    impl LambdaResponseProcessor<String> for TestProcessor {
        fn prepare_request(
            &self,
            _req: Request,
            _body: Option<Arc<Bytes>>,
        ) -> Result<String, lambda_runtime::Error> {
            Ok(String::new())
        }

        fn headers(&self, _content: &hyperchad_renderer::Content) -> Option<Vec<(String, String)>> {
            None
        }

        async fn to_response(
            &self,
            _data: String,
        ) -> Result<Option<(Content, Option<Vec<(String, String)>>)>, lambda_runtime::Error>
        {
            Ok(None)
        }

        async fn to_body(
            &self,
            _content: hyperchad_renderer::Content,
            _data: String,
        ) -> Result<Content, lambda_runtime::Error> {
            Ok(Content::Html(String::new()))
        }
    }

    #[test_log::test]
    fn test_content_html_creation() {
        let html = Content::Html("<h1>Test</h1>".to_string());
        match html {
            Content::Html(s) => assert_eq!(s, "<h1>Test</h1>"),
            Content::Raw { .. } => panic!("Expected Html variant"),
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected Html variant"),
        }
    }

    #[test_log::test]
    fn test_content_html_empty() {
        let html = Content::Html(String::new());
        match html {
            Content::Html(s) => assert!(s.is_empty()),
            Content::Raw { .. } => panic!("Expected Html variant"),
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected Html variant"),
        }
    }

    #[test_log::test]
    fn test_content_raw_creation() {
        let data = Bytes::from_static(b"test data");
        let content_type = "application/octet-stream".to_string();
        let raw = Content::Raw {
            data: data.clone(),
            content_type: content_type.clone(),
        };

        match raw {
            Content::Raw {
                data: d,
                content_type: ct,
            } => {
                assert_eq!(d, data);
                assert_eq!(ct, content_type);
            }
            Content::Html(_) => panic!("Expected Raw variant"),
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected Raw variant"),
        }
    }

    #[test_log::test]
    fn test_content_raw_with_image_mime_type() {
        let data = Bytes::from_static(b"\x89PNG\r\n\x1a\n");
        let raw = Content::Raw {
            data: data.clone(),
            content_type: "image/png".to_string(),
        };

        match raw {
            Content::Raw {
                data: d,
                content_type: ct,
            } => {
                assert_eq!(d, data);
                assert_eq!(ct, "image/png");
            }
            Content::Html(_) => panic!("Expected Raw variant"),
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected Raw variant"),
        }
    }

    #[cfg(feature = "json")]
    #[test_log::test]
    fn test_content_json_creation() {
        let value = serde_json::json!({"key": "value"});
        let json = Content::Json(value.clone());

        match json {
            Content::Json(v) => assert_eq!(v, value),
            _ => panic!("Expected Json variant"),
        }
    }

    #[cfg(feature = "json")]
    #[test_log::test]
    fn test_content_json_array() {
        let value = serde_json::json!([1, 2, 3]);
        let json = Content::Json(value.clone());

        match json {
            Content::Json(v) => {
                assert!(v.is_array());
                assert_eq!(v, value);
            }
            _ => panic!("Expected Json variant"),
        }
    }

    #[cfg(feature = "json")]
    #[test_log::test]
    fn test_content_json_null() {
        let value = serde_json::json!(null);
        let json = Content::Json(value.clone());

        match json {
            Content::Json(v) => {
                assert!(v.is_null());
                assert_eq!(v, value);
            }
            _ => panic!("Expected Json variant"),
        }
    }

    #[cfg(feature = "assets")]
    #[test_log::test]
    fn test_lambda_app_new() {
        let processor = TestProcessor;
        let app = LambdaApp::new(processor);

        // Verify the app was created successfully
        assert!(app.static_asset_routes.is_empty());
    }

    #[cfg(feature = "assets")]
    #[test_log::test]
    fn test_lambda_app_with_static_routes() {
        let processor = TestProcessor;
        let mut app = LambdaApp::new(processor);

        // Add a static route with in-memory content
        app.static_asset_routes
            .push(hyperchad_renderer::assets::StaticAssetRoute {
                route: "/static/style.css".to_string(),
                target: hyperchad_renderer::assets::AssetPathTarget::FileContents(
                    Bytes::from_static(b"body { margin: 0; }"),
                ),
                not_found_behavior: None,
            });

        assert_eq!(app.static_asset_routes.len(), 1);
        assert_eq!(app.static_asset_routes[0].route, "/static/style.css");

        // Verify the target is FileContents
        match &app.static_asset_routes[0].target {
            hyperchad_renderer::assets::AssetPathTarget::FileContents(bytes) => {
                assert_eq!(bytes, &Bytes::from_static(b"body { margin: 0; }"));
            }
            _ => panic!("Expected FileContents target"),
        }
    }
}