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

This is a crate which provides macros `tera_resources_initialize!` and `tera_response!` to statically include Tera files from your Rust project and make them be the HTTP response sources quickly.

* `tera_resources_initialize!` is used in the fairing of `TeraResponseFairing` to include Tera 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.
* `tera_response!` is used for retrieving and rendering the file you input through the macro `tera_resources_initialize!` as a `TeraResponse` 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.
* `tera_response_cache!` is used for wrapping a `TeraResponse` 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`.
*/

mod reloadable;
mod manager;
mod fairing;
mod macros;

pub extern crate tera;

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

extern crate serde;

extern crate serde_json;

extern crate rocket;

extern crate rocket_etag_if_none_match;

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

use crc_any::CRCu64;
use rc_u8_reader::ArcU8Reader;
use tera::{Tera, Context, Error as TeraError};
use serde::Serialize;
use serde_json::{Value, Error as SerdeJsonError};

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

use rocket_etag_if_none_match::{EntityTag, EtagIfNoneMatch};

pub use reloadable::ReloadableTera;
pub use manager::TeraContextManager;
use fairing::TeraResponseFairing;

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))
}

#[inline]
fn build_context(value: &Value) -> Context {
    let mut context = Context::new();

    if let Value::Object(map) = value {
        for (k, v) in map {
            context.insert(k, v);
        }
    }

    context
}

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

#[derive(Debug)]
/// To respond HTML from Tera templates.
pub struct TeraResponse {
    source: TeraResponseSource,
}

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

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

        Ok(TeraResponse {
            source,
        })
    }

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

        TeraResponse {
            source,
        }
    }
}

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

        TeraResponseFairing {
            custom_callback: Box::new(move |tera| {
                f(tera);

                DEFAULT_CACHE_CAPACITY
            }),
        }
    }

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

        TeraResponseFairing {
            custom_callback: Box::new(move |tera| {
                f(tera);

                DEFAULT_CACHE_CAPACITY
            }),
        }
    }

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

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

impl TeraResponse {
    #[cfg(debug_assertions)]
    #[inline]
    fn render(&self, cm: &TeraContextManager) -> Result<String, TeraError> {
        match &self.source {
            TeraResponseSource::Template {
                name,
                context,
                ..
            } => {
                let context = build_context(context);

                cm.tera.lock().unwrap().render(name, context)
            }
            _ => unreachable!()
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    fn render(&self, cm: &TeraContextManager) -> Result<String, TeraError> {
        match &self.source {
            TeraResponseSource::Template {
                name,
                context,
                ..
            } => {
                let context = build_context(context);

                cm.tera.render(name, context)
            }
            _ => unreachable!()
        }
    }

    #[cfg(debug_assertions)]
    #[inline]
    /// Get this response's HTML and Etag.
    pub fn get_html_and_etag(&self, cm: &TeraContextManager) -> Result<(Arc<str>, Arc<EntityTag>), TeraError> {
        match &self.source {
            TeraResponseSource::Template {
                name,
                context,
                ..
            } => {
                let context = build_context(context);

                let html = cm.tera.lock().unwrap().render(name, context)?;

                let etag = compute_html_etag(&html);

                Ok((html.into(), Arc::new(etag)))
            }
            TeraResponseSource::Cache(key) => {
                cm.get(key).ok_or(TeraError::msg("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: &TeraContextManager) -> Result<(Arc<str>, Arc<EntityTag>), TeraError> {
        match &self.source {
            TeraResponseSource::Template {
                name,
                context,
                ..
            } => {
                let context = build_context(context);

                let html = cm.tera.render(name, context)?;

                let etag = compute_html_etag(&html);

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

    #[cfg(debug_assertions)]
    #[inline]
    /// Get this response's HTML.
    pub fn get_html(&self, cm: &TeraContextManager) -> Result<String, TeraError> {
        match &self.source {
            TeraResponseSource::Template {
                name,
                context,
                ..
            } => {
                let context = build_context(context);

                let html = cm.tera.lock().unwrap().render(name, context)?;

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

    #[cfg(not(debug_assertions))]
    #[inline]
    /// Get this response's HTML.
    pub fn get_html(&self, cm: &TeraContextManager) -> Result<String, TeraError> {
        match &self.source {
            TeraResponseSource::Template {
                name,
                context,
                ..
            } => {
                let context = build_context(context);

                let html = cm.tera.render(name, context)?;

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

impl<'a> Responder<'a> for TeraResponse {
    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<TeraContextManager>>().expect("TeraContextManager registered in on_attach");

        match &self.source {
            TeraResponseSource::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));
            }
            TeraResponseSource::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()
    }
}