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
/*!
# Include Handlebars Templates for Rocket Framework

This is a crate which provides macros `handlebars_resources_initialize!` and `handlebars_response!` to statically include HBS (Handlebars) files from your Rust project and make them be the HTTP response sources quickly.

* `handlebars_resources_initialize!` is used in the fairing of `HandlebarsResponse` to include Handlebars files into your executable binary file. You need to specify each file's name and its path. In order to reduce the compilation time and allow to hot-reload templates, files are compiled into your executable binary file together, only when you are using the **release** profile.
* `handlebars_response!` is used for retrieving and rendering the file you input through the macro `handlebars_resources_initialize!` as a `HandlebarsResponse` instance with rendered HTML. When its `respond_to` method is called, three HTTP headers, **Content-Type**, **Content-Length** and **Etag**, will be automatically added, and the rendered HTML can optionally not be minified.
* `handlebars_response_cache!` is used for wrapping a `HandlebarsResponse` and its constructor, and use a **key** to cache its HTML and ETag in memory. The cache is generated only when you are using the **release** profile.

See `examples`.
*/

#[macro_use]
mod helpers;
mod fairing;
mod macros;
mod manager;
mod reloadable;

#[cfg(feature = "helper")]
#[macro_use]
pub extern crate handlebars;

#[cfg(not(feature = "helper"))]
pub extern crate handlebars;

#[macro_use]
extern crate educe;
extern crate crc_any;
extern crate html_minifier;
extern crate lru_time_cache;
extern crate rc_u8_reader;

extern crate serde;

extern crate serde_json;

extern crate rocket;

extern crate rocket_etag_if_none_match;

use std::io::Cursor;
use std::sync::Arc;
#[cfg(debug_assertions)]
use std::sync::MutexGuard;

use crc_any::CRCu64;
use handlebars::{Handlebars, RenderError};
use rc_u8_reader::ArcU8Reader;
use serde::Serialize;
use serde_json::{Error as SerdeJsonError, Value};

use rocket::fairing::Fairing;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rocket::State;

use rocket_etag_if_none_match::{EntityTag, EtagIfNoneMatch};

use fairing::HandlebarsResponseFairing;
pub use manager::HandlebarsContextManager;
pub use reloadable::ReloadableHandlebars;

const DEFAULT_CACHE_CAPACITY: usize = 64;

#[inline]
fn compute_html_etag<S: AsRef<str>>(html: S) -> EntityTag {
    let mut crc64ecma = CRCu64::crc64();
    crc64ecma.digest(html.as_ref().as_bytes());
    let crc64 = crc64ecma.get_crc();
    EntityTag::new(true, format!("{:X}", crc64))
}

#[derive(Debug)]
enum HandlebarsResponseSource {
    Template {
        minify: bool,
        name: &'static str,
        context: Value,
    },
    Cache(Arc<str>),
}

#[derive(Debug)]
/// To respond HTML from Handlebars templates.
pub struct HandlebarsResponse {
    source: HandlebarsResponseSource,
}

impl HandlebarsResponse {
    #[inline]
    /// Build a `HandlebarsResponse` instance from a specific template.
    pub fn build_from_template<V: Serialize>(
        minify: bool,
        name: &'static str,
        context: V,
    ) -> Result<HandlebarsResponse, SerdeJsonError> {
        let context = serde_json::to_value(context)?;

        let source = HandlebarsResponseSource::Template {
            minify,
            name,
            context,
        };

        Ok(HandlebarsResponse {
            source,
        })
    }

    #[inline]
    /// Build a `HandlebarsResponse` instance from cache.
    pub fn build_from_cache<S: Into<Arc<str>>>(name: S) -> HandlebarsResponse {
        let source = HandlebarsResponseSource::Cache(name.into());

        HandlebarsResponse {
            source,
        }
    }
}

impl HandlebarsResponse {
    #[cfg(debug_assertions)]
    #[inline]
    /// Create the fairing of `HandlebarsResponse`.
    pub fn fairing<F>(f: F) -> impl Fairing
    where
        F: Fn(&mut MutexGuard<ReloadableHandlebars>) + Send + Sync + 'static, {
        let f = Box::new(f);

        HandlebarsResponseFairing {
            custom_callback: Box::new(move |handlebars| {
                f(handlebars);

                DEFAULT_CACHE_CAPACITY
            }),
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    /// Create the fairing of `HandlebarsResponse`.
    pub fn fairing<F>(f: F) -> impl Fairing
    where
        F: Fn(&mut Handlebars) + Send + Sync + 'static, {
        let f = Box::new(f);

        HandlebarsResponseFairing {
            custom_callback: Box::new(move |handlebars| {
                f(handlebars);

                DEFAULT_CACHE_CAPACITY
            }),
        }
    }

    #[cfg(debug_assertions)]
    #[inline]
    /// Create the fairing of `HandlebarsResponse` and set the cache capacity.
    pub fn fairing_cache<F>(f: F) -> impl Fairing
    where
        F: Fn(&mut MutexGuard<ReloadableHandlebars>) -> usize + Send + Sync + 'static, {
        HandlebarsResponseFairing {
            custom_callback: Box::new(f),
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    /// Create the fairing of `HandlebarsResponse` and set the cache capacity.
    pub fn fairing_cache<F>(f: F) -> impl Fairing
    where
        F: Fn(&mut Handlebars) -> usize + Send + Sync + 'static, {
        HandlebarsResponseFairing {
            custom_callback: Box::new(f),
        }
    }
}

impl HandlebarsResponse {
    #[cfg(debug_assertions)]
    #[inline]
    fn render(&self, cm: &HandlebarsContextManager) -> Result<String, RenderError> {
        match &self.source {
            HandlebarsResponseSource::Template {
                name,
                context,
                ..
            } => cm.handlebars.lock().unwrap().render(name, context),
            _ => unreachable!(),
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    fn render(&self, cm: &HandlebarsContextManager) -> Result<String, RenderError> {
        match &self.source {
            HandlebarsResponseSource::Template {
                name,
                context,
                ..
            } => cm.handlebars.render(name, context),
            _ => unreachable!(),
        }
    }

    #[cfg(debug_assertions)]
    #[inline]
    /// Get this response's HTML and Etag.
    pub fn get_html_and_etag(
        &self,
        cm: &HandlebarsContextManager,
    ) -> Result<(Arc<str>, Arc<EntityTag>), RenderError> {
        match &self.source {
            HandlebarsResponseSource::Template {
                minify,
                name,
                context,
            } => {
                let html = cm.handlebars.lock().unwrap().render(name, context)?;

                let html = if *minify {
                    html_minifier::minify(&html).unwrap()
                } else {
                    html
                };

                let etag = compute_html_etag(&html);

                Ok((html.into(), Arc::new(etag)))
            }
            HandlebarsResponseSource::Cache(key) => {
                cm.get(key)
                    .ok_or_else(|| RenderError::new("This response hasn't been triggered yet."))
            }
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    /// Get this response's HTML and Etag.
    pub fn get_html_and_etag(
        &self,
        cm: &HandlebarsContextManager,
    ) -> Result<(Arc<str>, Arc<EntityTag>), RenderError> {
        match &self.source {
            HandlebarsResponseSource::Template {
                minify,
                name,
                context,
            } => {
                let html = cm.handlebars.render(name, context)?;

                let html = if *minify {
                    html_minifier::minify(&html).unwrap()
                } else {
                    html
                };

                let etag = compute_html_etag(&html);

                Ok((html.into(), Arc::new(etag)))
            }
            HandlebarsResponseSource::Cache(key) => {
                cm.get(key).ok_or(RenderError::new("This response hasn't been triggered yet."))
            }
        }
    }

    #[cfg(debug_assertions)]
    #[inline]
    /// Get this response's HTML without minifying.
    pub fn get_html(&self, cm: &HandlebarsContextManager) -> Result<String, RenderError> {
        match &self.source {
            HandlebarsResponseSource::Template {
                name,
                context,
                ..
            } => {
                let html = cm.handlebars.lock().unwrap().render(name, context)?;

                Ok(html)
            }
            HandlebarsResponseSource::Cache(key) => {
                cm.get(key)
                    .map(|(html, _)| html.to_string())
                    .ok_or_else(|| RenderError::new("This response hasn't been triggered yet."))
            }
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    /// Get this response's HTML without minifying.
    pub fn get_html(&self, cm: &HandlebarsContextManager) -> Result<String, RenderError> {
        match &self.source {
            HandlebarsResponseSource::Template {
                name,
                context,
                ..
            } => {
                let html = cm.handlebars.render(name, context)?;

                Ok(html)
            }
            HandlebarsResponseSource::Cache(key) => {
                cm.get(key)
                    .map(|(html, _)| html.to_string())
                    .ok_or(RenderError::new("This response hasn't been triggered yet."))
            }
        }
    }
}

impl<'a> Responder<'a> for HandlebarsResponse {
    fn respond_to(self, request: &Request) -> response::Result<'a> {
        let client_etag = request.guard::<EtagIfNoneMatch>().unwrap();

        let mut response = Response::build();

        let cm = request
            .guard::<State<HandlebarsContextManager>>()
            .expect("HandlebarsContextManager registered in on_attach");

        match &self.source {
            HandlebarsResponseSource::Template {
                minify,
                ..
            } => {
                let (html, etag) = match self.render(&cm) {
                    Ok(html) => {
                        let etag = compute_html_etag(&html);

                        let is_etag_match = client_etag.weak_eq(&etag);

                        if is_etag_match {
                            response.status(Status::NotModified);

                            return response.ok();
                        } else {
                            (html, etag.to_string())
                        }
                    }
                    Err(_) => {
                        return Err(Status::InternalServerError);
                    }
                };

                let html = if *minify {
                    html_minifier::minify(&html).unwrap()
                } else {
                    html
                };

                response
                    .raw_header("ETag", etag)
                    .raw_header("Content-Type", "text/html; charset=utf-8")
                    .sized_body(Cursor::new(html));
            }
            HandlebarsResponseSource::Cache(key) => {
                let (html, etag) = {
                    match cm.get(key) {
                        Some((html, etag)) => {
                            let is_etag_match = client_etag.weak_eq(&etag);

                            if is_etag_match {
                                response.status(Status::NotModified);

                                return response.ok();
                            } else {
                                (html, etag.to_string())
                            }
                        }
                        None => {
                            return Err(Status::InternalServerError);
                        }
                    }
                };

                response
                    .raw_header("ETag", etag)
                    .raw_header("Content-Type", "text/html; charset=utf-8")
                    .sized_body(ArcU8Reader::new(html));
            }
        }

        response.ok()
    }
}