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
mod reloadable;
mod manager;
mod fairing;
mod macros;
pub extern crate handlebars;
#[macro_use]
extern crate derivative;
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::CRC;
use rc_u8_reader::ArcU8Reader;
use handlebars::{Handlebars, RenderError};
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;
pub use rocket_etag_if_none_match::{EntityTag, EtagIfNoneMatch};
pub use reloadable::ReloadableHandlebars;
pub use manager::HandlebarsContextManager;
use fairing::HandlebarsResponseFairing;
const DEFAULT_CACHE_CAPACITY: usize = 64;
#[inline]
fn compute_html_etag<S: AsRef<str>>(html: S) -> EntityTag {
let mut crc64ecma = CRC::crc64ecma();
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)]
pub struct HandlebarsResponse {
client_etag: EtagIfNoneMatch,
source: HandlebarsResponseSource,
}
impl HandlebarsResponse {
#[inline]
pub fn build_from_template<V: Serialize>(client_etag: EtagIfNoneMatch, 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 {
client_etag,
source,
})
}
#[inline]
pub fn build_from_cache<S: Into<Arc<str>>>(client_etag: EtagIfNoneMatch, name: S) -> HandlebarsResponse {
let source = HandlebarsResponseSource::Cache(name.into());
HandlebarsResponse {
client_etag,
source,
}
}
}
impl HandlebarsResponse {
#[cfg(debug_assertions)]
#[inline]
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]
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]
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]
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]
pub fn get_html_and_etag(&self, cm: &HandlebarsContextManager) -> Result<(Arc<str>, Arc<EntityTag>), RenderError> {
match &self.source {
HandlebarsResponseSource::Template {
name,
context,
..
} => {
let html = cm.handlebars.lock().unwrap().render(name, context)?;
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(not(debug_assertions))]
#[inline]
pub fn get_html_and_etag(&self, cm: &HandlebarsContextManager) -> Result<(Arc<str>, Arc<EntityTag>), RenderError> {
match &self.source {
HandlebarsResponseSource::Template {
name,
context,
..
} => {
let html = cm.handlebars.render(name, context)?;
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]
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(RenderError::new("This response hasn't been triggered yet."))
}
}
}
#[cfg(not(debug_assertions))]
#[inline]
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 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 = self.client_etag.weak_eq(&etag);
if is_etag_match {
response.status(Status::NotModified);
return response.ok();
} else {
(html, etag.to_string())
}
}
Err(_) => {
response.status(Status::InternalServerError);
return response.ok();
}
};
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 = self.client_etag.weak_eq(&etag);
if is_etag_match {
response.status(Status::NotModified);
return response.ok();
} else {
(html, etag.to_string())
}
}
None => {
response.status(Status::InternalServerError);
return response.ok();
}
}
};
response
.raw_header("ETag", etag)
.raw_header("Content-Type", "text/html; charset=utf-8")
.sized_body(ArcU8Reader::new(html));
}
}
response.ok()
}
}