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
/*!
# 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 for including Tera files into your executable binary file. You need to specify each file's name and its path. For instance, the above example uses **index** to represent the file **included-tera/index.tera** and **index-2** to represent the file **included-tera/index2.tera**. A name cannot be repeating. 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 be minified.
* `tera_response_static!` is used for in-memory staticizing a `TeraResponse` instance by a given key. It is effective only when you are using the **release** profile.

See `examples`.
*/

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

pub extern crate tera;

extern crate crc_any;
extern crate html_minifier;

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 crc_any::CRC;
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, hyper::header::ETag};
use rocket::fairing::Fairing;

pub use rocket_etag_if_none_match::{EntityTag, EtagIfNoneMatch};

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

#[inline]
fn compute_html_etag(html: &str) -> EntityTag {
    let mut crc64ecma = CRC::crc64ecma();
    crc64ecma.digest(html.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 {
        etag: Option<EntityTag>,
        minify: bool,
        name: String,
        context: Value,
    },
    Cache(Option<String>),
}

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

impl TeraResponse {
    #[inline]
    /// Build a `TeraResponse` instance from a specific template.
    pub fn build_from_template<S: Into<String>, V: Serialize>(client_etag: EtagIfNoneMatch, etag: Option<EntityTag>, minify: bool, name: S, context: V) -> Result<TeraResponse, SerdeJsonError> {
        let context = serde_json::to_value(context)?;

        let name = name.into();

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

        Ok(TeraResponse {
            client_etag,
            source,
        })
    }

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

        TeraResponse {
            client_etag,
            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 {
        TeraResponseFairing {
            custom_callback: Box::new(f)
        }
    }

    #[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 {
        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<(String, 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, etag))
            }
            TeraResponseSource::Cache(name) => {
                let cache_table = cm.cache_table.lock().unwrap();

                match cache_table.get(name.as_ref().unwrap()) {
                    Some((html, etag)) => Ok((html.clone(), etag.clone())),
                    None => Err(TeraError::msg("This Response hasn't triggered yet."))
                }
            }
        }
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    /// Get this response's HTML and Etag.
    pub fn get_html_and_etag(&self, cm: &TeraContextManager) -> Result<(String, 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, etag))
            }
            TeraResponseSource::Cache(name) => {
                let cache_table = cm.cache_table.lock().unwrap();

                match cache_table.get(name.as_ref().unwrap()) {
                    Some((html, etag)) => Ok((html.clone(), etag.clone())),
                    None => Err(TeraError::msg("This Response hasn't triggered yet."))
                }
            }
        }
    }
}

impl<'a> Responder<'a> for TeraResponse {
    fn respond_to(mut self, request: &Request) -> response::Result<'a> {
        let mut response = Response::build();

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

        let (is_template, etag, minify) = {
            match &mut self.source {
                TeraResponseSource::Template {
                    etag,
                    minify,
                    ..
                } => {
                    (true, etag.take(), *minify)
                }
                _ => (false, None, false)
            }
        };

        if is_template {
            let (html, etag) = match etag {
                Some(etag) => {
                    let is_etag_match = self.client_etag.weak_eq(&etag);

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

                        return response.ok();
                    } else {
                        match self.render(&cm) {
                            Ok(html) => (html, etag),
                            Err(_) => {
                                response.status(Status::InternalServerError);

                                return response.ok();
                            }
                        }
                    }
                }
                None => {
                    match self.render(&cm) {
                        Ok(html) => {
                            let etag = compute_html_etag(&html);

                            let is_etag_match = self.client_etag.weak_eq(&etag);

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

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

                            return response.ok();
                        }
                    }
                }
            };

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

            response.header(ETag(etag));

            response.raw_header("Content-Type", "text/html; charset=utf-8")
                .sized_body(Cursor::new(html));
        } else {
            let name = if let TeraResponseSource::Cache(name) = &mut self.source {
                name.take().unwrap()
            } else {
                unreachable!()
            };

            let cache = {
                let cache_table = cm.cache_table.lock().unwrap();

                match cache_table.get(&name) {
                    Some((html, etag)) => {
                        let is_etag_match = self.client_etag.weak_eq(etag);

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

                            None
                        } else {
                            Some((html.clone(), etag.clone()))
                        }
                    }
                    None => {
                        response.status(Status::InternalServerError);

                        return response.ok();
                    }
                }
            };

            if let Some((html, etag)) = cache {
                response.header(ETag(etag));

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

        response.ok()
    }
}