tectonic 0.4.1

A modernized, complete, embeddable TeX/LaTeX engine. Tectonic is forked from the XeTeX extension to the classic “Web2C” implementation of TeX and uses the TeXLive distribution of support files.
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
use flate2::{write::GzEncoder, GzBuilder};
use futures::future;
use headers::HeaderMapExt;
use hyper::header::{self, HeaderValue};
use hyper::rt::Future;
use hyper::service::service_fn;
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::io::{self, Write};
use std::net::SocketAddr;
use std::ops::Bound;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::thread;
use tectonic::config::PersistentConfig;
use tectonic::driver::ProcessingSessionBuilder;
use tectonic::io::OpenResult;
use tectonic::status::termcolor::TermcolorStatusBackend;
use tectonic::status::ChatterLevel;
use tokio::runtime::current_thread;

mod util;

/// Build a fake tarindex by concatenating files.
struct TarIndexBuilder {
    tar: Vec<u8>,
    index: GzEncoder<Vec<u8>>,
    /// Map from (offset, length) to file name.
    map: HashMap<(u64, u64), String>,
}

impl TarIndexBuilder {
    fn new() -> TarIndexBuilder {
        let tar = Vec::new();
        let index = GzBuilder::new()
            .filename("bundle.tar.index.gz")
            .write(Vec::new(), flate2::Compression::default());
        let map = HashMap::new();

        TarIndexBuilder { tar, index, map }
    }

    /// Add a file.
    fn push(&mut self, name: &str, content: &[u8]) -> &mut Self {
        let offset = self.tar.len();
        let len = content.len();
        let _ = writeln!(&mut self.index, "{} {} {}", name, offset, len);
        self.map
            .insert((offset as u64, len as u64), name.to_owned());
        self.tar.extend_from_slice(&content);
        self
    }

    /// Create a tar index.
    fn finish(self) -> TarIndex {
        TarIndex {
            tar: self.tar,
            index: self.index.finish().unwrap(),
            map: self.map,
        }
    }
}

#[derive(Clone, Debug)]
struct TarIndex {
    tar: Vec<u8>,
    index: Vec<u8>,
    map: HashMap<(u64, u64), String>,
}

impl TarIndex {
    fn from_dir<P: AsRef<Path>>(path: P) -> io::Result<TarIndex> {
        let path = path.as_ref();
        let mut builder = TarIndexBuilder::new();
        for de in path.read_dir()? {
            let path = de?.path();
            let content = fs::read(&path)?;
            builder.push(path.file_name().unwrap().to_str().unwrap(), &content);
        }

        builder.push(
            tectonic::digest::DIGEST_NAME,
            b"0000000000000000000000000000000000000000000000000000000000000000",
        );

        Ok(builder.finish())
    }
}

#[derive(Clone, Debug, PartialEq)]
enum TectonicRequest {
    Head(String),
    Index,
    File(String),
}

struct TarIndexService {
    tar_index: Mutex<TarIndex>,
    requests: Mutex<Vec<TectonicRequest>>,
    local_addr: Mutex<Option<SocketAddr>>,
}

type ResponseFuture = Box<dyn Future<Item = Response<Body>, Error = io::Error> + Send>;

impl TarIndexService {
    fn new(tar_index: TarIndex) -> TarIndexService {
        TarIndexService {
            tar_index: Mutex::new(tar_index),
            requests: Mutex::new(Vec::new()),
            local_addr: Mutex::new(None),
        }
    }

    fn set_local_addr(&self, local_addr: SocketAddr) {
        *self.local_addr.lock().unwrap() = Some(local_addr);
    }

    fn set_tar_index(&self, tar_index: TarIndex) {
        *self.tar_index.lock().unwrap() = tar_index;
    }

    fn response(&self, req: Request<Body>) -> ResponseFuture {
        match (
            req.method(),
            req.uri().path(),
            req.headers().typed_get::<headers::Range>(),
        ) {
            (&Method::HEAD, "/tectonic-default", None) => {
                self.log_request(TectonicRequest::Head(req.uri().path().to_owned()));
                let mut resp = Response::builder();
                resp.status(StatusCode::FOUND);
                resp.headers_mut().unwrap().insert(
                    header::LOCATION,
                    HeaderValue::from_str(&format!(
                        "http://{}/bundle.tar",
                        self.local_addr.lock().unwrap().unwrap()
                    ))
                    .unwrap(),
                );
                Box::new(future::ok(resp.body(Body::empty()).unwrap()))
            }
            (&Method::HEAD, "/bundle.tar", None) => {
                self.log_request(TectonicRequest::Head(req.uri().path().to_owned()));
                Box::new(future::ok(Response::new(Body::empty())))
            }
            (&Method::GET, "/bundle.tar", Some(range)) => {
                if let Some((Bound::Included(l), Bound::Included(h))) = range.iter().next() {
                    let tar_index = self.tar_index.lock().unwrap();
                    let name = tar_index
                        .map
                        .get(&(l, h - l + 1))
                        .expect("unknown file data requested");
                    self.log_request(TectonicRequest::File(name.to_owned()));
                    let mut resp = Response::builder();
                    resp.status(StatusCode::PARTIAL_CONTENT);
                    resp.headers_mut()
                        .unwrap()
                        .typed_insert(headers::ContentRange::bytes(l..=h, None).unwrap());
                    Box::new(future::ok(
                        resp.body((&tar_index.tar[l as usize..=h as usize]).to_vec().into())
                            .unwrap(),
                    ))
                } else {
                    panic!("unexpected");
                }
            }
            (&Method::GET, "/bundle.tar.index.gz", None) => {
                self.log_request(TectonicRequest::Index);
                Box::new(future::ok(Response::new(
                    self.tar_index.lock().unwrap().index.to_vec().into(),
                )))
            }
            _ => Box::new(future::ok(
                Response::builder()
                    .status(StatusCode::NOT_FOUND)
                    .body(Body::empty())
                    .unwrap(),
            )),
        }
    }

    fn log_request(&self, request: TectonicRequest) {
        self.requests.lock().unwrap().push(request);
    }

    fn url(&self) -> String {
        format!(
            "http://{}/tectonic-default",
            self.local_addr.lock().unwrap().unwrap()
        )
    }
}

/// Run the provided closure while http service is running. Use the tar index given as
/// the first variable, or a default on if None.
fn run_test<R>(tar_index: Option<TarIndex>, run: R) -> Vec<TectonicRequest>
where
    R: FnOnce(Arc<TarIndexService>, &str),
{
    // Automatically select a port
    let addr = ([127, 0, 0, 1], 0).into();

    let tar_service = Arc::new(TarIndexService::new(tar_index.unwrap_or_else(|| {
        let root = Path::new(&env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("assets");
        TarIndex::from_dir(root).unwrap()
    })));
    let tar_service_clone = Arc::clone(&tar_service);

    let server = Server::bind(&addr).serve(move || {
        let tar_service = Arc::clone(&tar_service_clone);
        service_fn(move |req| tar_service.response(req))
    });

    // server is listening now
    tar_service.set_local_addr(server.local_addr());
    let url = tar_service.url();

    let (server_shutdown_tx, server_shutdown_rx) = futures::sync::oneshot::channel::<()>();

    let graceful = server.with_graceful_shutdown(server_shutdown_rx);

    let server_thread = thread::spawn(|| {
        // Run the server on a single thread (current thread)
        current_thread::run(graceful.map_err(|_| ()));
    });

    // Server running, run the provided test
    run(Arc::clone(&tar_service), &url);

    println!("Shutting down");

    // Shut down server
    let _ = server_shutdown_tx.send(());
    server_thread.join().unwrap();

    // Check tectonic's requests.
    let requests = tar_service.requests.lock().unwrap();

    requests.clone()
}

fn check_req_count(requests: &[TectonicRequest], request: TectonicRequest, expected_number: usize) {
    let number = requests.iter().filter(|r| **r == request).count();
    assert_eq!(
        number, expected_number,
        "Expected {} requests of {:?}, got {}",
        expected_number, request, number
    );
}
#[test]
fn test_full_session() {
    let requests = run_test(None, |_, url| {
        let tempdir = tempfile::tempdir().unwrap();

        let config = PersistentConfig::default();

        let run = |path| {
            let mut status = TermcolorStatusBackend::new(ChatterLevel::Minimal);
            let mut sess_builder = ProcessingSessionBuilder::default();
            sess_builder.bundle(Box::new(
                config
                    .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                    .unwrap(),
            ));
            let input_path = Path::new(path);
            sess_builder.primary_input_path(input_path);
            sess_builder.tex_input_name(&input_path.file_name().unwrap().to_string_lossy());
            sess_builder.output_dir(tempdir.path());
            sess_builder.format_name("plain");
            sess_builder.format_cache_path(tempdir.path());

            let mut sess = sess_builder.create(&mut status).unwrap();
            sess.run(&mut status).unwrap();
        };

        // Run tectonic twice
        run("tests/tex-outputs/the_letter_a.tex");
        // On this run everything should be cached.
        run("tests/tex-outputs/the_letter_a.tex");
        // Run tectonic with a file that needs a new resource
        run("tests/tex-outputs/redbox_png.tex");
    });

    check_req_count(&requests, TectonicRequest::Index, 1);
    check_req_count(
        &requests,
        TectonicRequest::File(tectonic::digest::DIGEST_NAME.into()),
        2,
    );
    // This file should be cached.
    check_req_count(&requests, TectonicRequest::File("plain.tex".into()), 1);
}

#[test]
fn test_cached_url_provider() {
    let tar_index = {
        let mut builder = TarIndexBuilder::new();
        builder
            .push("plain.tex", b"test")
            .push("other.tex", b"other content")
            .push(
                tectonic::digest::DIGEST_NAME,
                b"0000000000000000000000000000000000000000000000000000000000000000",
            );
        builder.finish()
    };

    let requests = run_test(Some(tar_index), |_, url| {
        let tempdir = tempfile::tempdir().unwrap();
        let mut status = TermcolorStatusBackend::new(ChatterLevel::Minimal);

        let config = PersistentConfig::default();

        {
            let mut cache = config
                .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                .unwrap();

            match cache.input_open_name(OsStr::new("plain.tex"), &mut status) {
                OpenResult::Ok(_) => {}
                _ => panic!("Failed to open plain.tex"),
            }
            match cache.input_open_name(OsStr::new("plain.tex"), &mut status) {
                OpenResult::Ok(_) => {}
                _ => panic!("Failed to open plain.tex"),
            }
        }
        {
            let mut cache = config
                .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                .unwrap();

            // should be cached
            match cache.input_open_name(OsStr::new("plain.tex"), &mut status) {
                OpenResult::Ok(_) => {}
                _ => panic!("Failed to open plain.tex"),
            }
        }
        {
            let mut cache = config
                .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                .unwrap();

            // should be cached
            match cache.input_open_name(OsStr::new("plain.tex"), &mut status) {
                OpenResult::Ok(_) => {}
                _ => panic!("Failed to open plain.tex"),
            }
            // in index, should check digest and download the file
            match cache.input_open_name(OsStr::new("other.tex"), &mut status) {
                OpenResult::Ok(_) => {}
                _ => panic!("Failed to open other.tex"),
            }
        }
        {
            let mut cache = config
                .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                .unwrap();

            // not in index
            match cache.input_open_name(OsStr::new("my-favourite-file.tex"), &mut status) {
                OpenResult::NotAvailable => {}
                _ => panic!("'my-favourite-file.tex' file exists?"),
            }
        }
    });

    check_req_count(&requests, TectonicRequest::Index, 1);
    check_req_count(
        &requests,
        TectonicRequest::File(tectonic::digest::DIGEST_NAME.into()),
        2,
    );
    // This files should be cached.
    check_req_count(&requests, TectonicRequest::File("plain.tex".into()), 1);
    check_req_count(&requests, TectonicRequest::File("other.tex".into()), 1);
}

#[test]
fn test_bundle_update() {
    let tempdir = tempfile::tempdir().unwrap();
    let tar_index = {
        let mut builder = TarIndexBuilder::new();
        builder
            .push("only-first.tex", b"test")
            .push("file-in-both.tex", b"in both")
            .push(
                tectonic::digest::DIGEST_NAME,
                b"0000000000000000000000000000000000000000000000000000000000000000",
            );
        builder.finish()
    };

    run_test(Some(tar_index), |service, url| {
        let mut status = TermcolorStatusBackend::new(ChatterLevel::Minimal);

        let config = PersistentConfig::default();

        {
            // Run with first tar index.
            {
                let mut cache = config
                    .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                    .unwrap();

                match cache.input_open_name(OsStr::new("only-first.tex"), &mut status) {
                    OpenResult::Ok(_) => {}
                    _ => panic!("Failed to open only-first.tex"),
                }
            }

            // Set a tar index with a different digest.
            let tar_index = {
                let mut builder = TarIndexBuilder::new();
                builder
                    .push("only-second.tex", b"test")
                    .push("file-in-both.tex", b"in both")
                    .push(
                        tectonic::digest::DIGEST_NAME,
                        b"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
                    );
                builder.finish()
            };
            service.set_tar_index(tar_index);

            // Run with the new tar index.
            {
                let mut status = TermcolorStatusBackend::new(ChatterLevel::Minimal);

                let config = PersistentConfig::default();

                {
                    let mut cache = config
                        .make_cached_url_provider(&url, false, Some(tempdir.path()), &mut status)
                        .unwrap();

                    // This should be cached even thought the bundle does not contain it.
                    match cache.input_open_name(OsStr::new("only-first.tex"), &mut status) {
                        OpenResult::Ok(_) => {}
                        _ => panic!("Failed to open only-first.tex"),
                    }

                    // Not in index of the first bundle and therefore no digest check.
                    match cache.input_open_name(OsStr::new("only-second.tex"), &mut status) {
                        OpenResult::NotAvailable => {}
                        _ => panic!("File should not be in the first bundle"),
                    }
                    // File in the first bundle and the second bundle, but not cached yet. Should
                    // trigger a digest check.
                    match cache.input_open_name(OsStr::new("file-in-both.tex"), &mut status) {
                        OpenResult::Err(_) => {}
                        _ => panic!("Bundle digest changed but no error"),
                    }
                }
            }
        }
    });
}