stelae 0.6.3

A collection of tools in Rust and Python for preserving, authenticating, and accessing laws in perpetuity.
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
//! A central place to register App routes.
#![expect(
    clippy::exit,
    reason = "We exit with 1 error code on any application errors"
)]
use std::sync::Arc;
use std::{process, sync::OnceLock};

use crate::server::api::state;
use crate::stelae::{stele::Stele, types::repositories::Repositories};
use actix_service::ServiceFactory;
use actix_web::{
    body::MessageBody,
    dev::{ServiceRequest, ServiceResponse},
    guard, web, App, Error, Scope,
};

use super::archive::get_blob;
use super::{serve::serve, state::Global, versions::versions};

/// Name of the header to guard current documents
static HEADER_NAME: OnceLock<String> = OnceLock::new();
/// Values of the header to guard current documents
static HEADER_VALUES: OnceLock<Vec<String>> = OnceLock::new();
/// Name of the root stelae
static ROOT_NAME_VALUE: OnceLock<String> = OnceLock::new();

#[expect(
    clippy::literal_string_with_formatting_args,
    reason = "Actix Web resource path uses `{param}` syntax which is not formatting but route pattern matching"
)]
/// Central place to register all the App routing.
///
/// Registers all routes for the given Archive
/// Static routes should be registered first, followed by dynamic routes.
///
/// # Errors
/// Errors if unable to register dynamic routes (e.g. if git repository cannot be opened)
#[tracing::instrument(skip(app, state))]
pub fn register_app<
    T: Global + Clone + 'static,
    U: MessageBody,
    V: ServiceFactory<
        ServiceRequest,
        Response = ServiceResponse<U>,
        Config = (),
        InitError = (),
        Error = Error,
    >,
>(
    mut app: App<V>,
    state: &T,
) -> anyhow::Result<App<V>> {
    app = app
        .service(
            web::scope("/_api").service(
                web::scope("/versions")
                    .service(
                        web::resource("/_publication/{publication}/_compare/{date}/{compare_date}")
                            .to(versions),
                    )
                    .service(
                        web::resource(
                            "/_publication/{publication}/_compare/{date}/{compare_date}/{path:.*}",
                        )
                        .to(versions),
                    )
                    .service(web::resource("/_publication/{publication}/_date/{date}").to(versions))
                    .service(
                        web::resource("/_publication/{publication}/_date/{date}/{path:.*}")
                            .to(versions),
                    )
                    .service(web::resource("/_publication/{publication}").to(versions))
                    .service(web::resource("/_publication/{publication}/{path:.*}").to(versions))
                    .service(web::resource("/_compare/{date}/{compare_date}").to(versions))
                    .service(
                        web::resource("/_compare/{date}/{compare_date}/{path:.*}").to(versions),
                    )
                    .service(web::resource("/_date/{date}").to(versions))
                    .service(web::resource("/_date/{date}/{path:.*}").to(versions))
                    .service(web::resource("/{path:.*}").to(versions))
                    .service(web::resource("").to(versions)),
            ),
        )
        .app_data(web::Data::new(state.clone()));

    app = register_guarded_and_unguarded_routes(app, state)?;
    Ok(app)
}

/// Initialize all dynamic routes for the given Archive.
///
/// Dynamic routes are determined at runtime by looking at the stele's `dependencies.json` and `repositories.json` files
/// in the authentication (e.g. law) repository.
///
/// # Errors
/// Errors if unable to register dynamic routes (e.g. if git repository cannot be opened)
fn register_guarded_and_unguarded_routes<
    T: MessageBody,
    U: ServiceFactory<
        ServiceRequest,
        Response = ServiceResponse<T>,
        Config = (),
        InitError = (),
        Error = Error,
    >,
    V: Global + Clone + 'static,
>(
    mut app: App<U>,
    state: &V,
) -> anyhow::Result<App<U>> {
    let config = state.archive().get_config()?;
    let stelae_guard = config
        .headers
        .and_then(|headers| headers.current_documents_guard);

    if let Some(guard) = stelae_guard {
        app = initialize_guarded_archive_route(guard.clone(), app, state)?;
        app = initialize_guarded_dynamic_routes(guard, app, state)?;
    } else {
        app = initialize_archive_route(app, state);
        app = initialize_dynamic_routes(app, state)?;
    }
    Ok(app)
}

#[expect(
    clippy::expect_used,
    reason = "If there is no root stelae, we should panic"
)]
/// Initialize all guarded archive routes for the given Archive.
/// Routes are guarded by a header value specified in the config.toml file.
///
/// # Errors
/// Errors if unable to register dynamic routes (e.g. if git repository cannot be opened)
fn initialize_guarded_archive_route<
    T: MessageBody,
    U: ServiceFactory<
        ServiceRequest,
        Response = ServiceResponse<T>,
        Config = (),
        InitError = (),
        Error = Error,
    >,
    V: Global + Clone + 'static,
>(
    guard: String,
    mut app: App<U>,
    state: &V,
) -> anyhow::Result<App<U>> {
    tracing::info!("Initializing guarded stelae routes with header: {}", guard);
    HEADER_NAME.get_or_init(|| guard);
    let archive = state.archive();
    let guard_value = archive.get_root()?.get_qualified_name();
    ROOT_NAME_VALUE.get_or_init(|| guard_value);
    let data_state: Arc<dyn Global> = Arc::new(state.clone());
    if let Some(guard_name) = HEADER_NAME.get() {
        let stele = state
            .archive()
            .stelae
            .get(&archive.get_root()?.get_qualified_name());
        if let Some(_guarded_stele) = stele {
            let mut archive_scope = web::scope("_archive");
            archive_scope = archive_scope.guard(guard::Header(
                guard_name,
                ROOT_NAME_VALUE
                    .get()
                    .expect("ROOT_NAME_VALUE not initialized")
                    .as_str(),
            ));
            app = app
                .app_data(web::Data::new(state.archive().path.clone()))
                .app_data(web::Data::new(Arc::clone(&data_state)))
                .service(
                    archive_scope.service(
                        web::resource("/{namespace}/{name}")
                            .route(web::get().to(get_blob))
                            .route(web::head().to(get_blob)),
                    ),
                );
        }
    } else {
        let err_msg =
            "Failed to initialize guarded archive routes. Header name or value not found.";
        tracing::error!(err_msg);
        anyhow::bail!(err_msg);
    }
    Ok(app)
}

/// Initialize _archive routes for the given Archive.
///
/// # Errors
/// Errors if unable to register stelae routes (e.g. if git repository cannot be opened)
fn initialize_archive_route<
    T: MessageBody,
    U: ServiceFactory<
        ServiceRequest,
        Response = ServiceResponse<T>,
        Config = (),
        InitError = (),
        Error = Error,
    >,
    V: Global + Clone + 'static,
>(
    mut app: App<U>,
    state: &V,
) -> actix_web::App<U> {
    let data_state: Arc<dyn Global> = Arc::new(state.clone());
    app = app
        .app_data(web::Data::new(state.archive().path.clone()))
        .app_data(web::Data::new(data_state))
        .service(
            web::scope("_archive").service(
                web::resource("/{namespace}/{name}")
                    .route(web::get().to(get_blob))
                    .route(web::head().to(get_blob)),
            ),
        );
    app
}

/// Initialize all guarded dynamic routes for the given Archive.
/// Routes are guarded by a header value specified in the config.toml file.
///
/// # Errors
/// Errors if unable to register dynamic routes (e.g. if git repository cannot be opened)
fn initialize_guarded_dynamic_routes<
    T: MessageBody,
    U: ServiceFactory<
        ServiceRequest,
        Response = ServiceResponse<T>,
        Config = (),
        InitError = (),
        Error = Error,
    >,
>(
    guard: String,
    mut app: App<U>,
    state: &impl Global,
) -> anyhow::Result<App<U>> {
    tracing::info!(
        "Initializing guarded current documents with header: {}",
        guard
    );
    HEADER_NAME.get_or_init(|| guard);
    HEADER_VALUES.get_or_init(|| {
        state
            .archive()
            .stelae
            .keys()
            .map(ToString::to_string)
            .collect()
    });

    if let (Some(guard_name), Some(guard_values)) = (HEADER_NAME.get(), HEADER_VALUES.get()) {
        for guard_value in guard_values {
            let stele = state.archive().stelae.get(guard_value);
            if let Some(guarded_stele) = stele {
                let shared_state = state::init_shared(guarded_stele)?;
                let mut stelae_scope = web::scope("");
                stelae_scope = stelae_scope.guard(guard::Header(guard_name, guard_value));
                app = app.service(
                    stelae_scope
                        .app_data(web::Data::new(shared_state))
                        .configure(|cfg| {
                            register_root_routes(cfg, guarded_stele).unwrap_or_else(|_| {
                                tracing::error!(
                                    "Failed to initialize routes for Stele: {}",
                                    guarded_stele.get_qualified_name()
                                );
                                process::exit(1);
                            });
                        }),
                );
            }
        }
    } else {
        let err_msg = "Failed to initialize guarded routes. Header name or values not found.";
        tracing::error!(err_msg);
        anyhow::bail!(err_msg);
    }
    Ok(app)
}

/// Initialize all dynamic routes for the given Archive.
///
/// # Errors
/// Errors if unable to register dynamic routes (e.g. if git repository cannot be opened)
fn initialize_dynamic_routes<
    T: MessageBody,
    U: ServiceFactory<
        ServiceRequest,
        Response = ServiceResponse<T>,
        Config = (),
        InitError = (),
        Error = Error,
    >,
>(
    mut app: App<U>,
    state: &impl Global,
) -> anyhow::Result<App<U>> {
    tracing::info!("Initializing app");
    let root = state.archive().get_root()?;
    let shared_state = state::init_shared(root)?;
    app = app.service(
        web::scope("")
            .app_data(web::Data::new(shared_state))
            .configure(|cfg| {
                register_routes(cfg, state).unwrap_or_else(|_| {
                    tracing::error!(
                        // TODO: error handling
                        "Failed to initialize routes for root Stele: {}",
                        root.get_qualified_name()
                    );
                    process::exit(1);
                });
            }),
    );
    Ok(app)
}

/// Registers all dynamic routes for the given Archive
/// Each current document routes consists of two dynamic segments: `{prefix}/{tail}`.
/// prefix: the first part of the request uri, used to determine which dependent Stele to serve.
/// tail: the remaining glob pattern path of the request uri.
/// # Arguments
/// * `cfg` - The Actix `ServiceConfig`
/// * `state` - The application state
/// # Errors
/// Will error if unable to register routes (e.g. if git repository cannot be opened)
#[expect(
    clippy::iter_over_hash_type,
    reason = "List of repositories that are registered as routes are always sorted, even with iterating over hash type"
)]
fn register_routes<T: Global>(cfg: &mut web::ServiceConfig, state: &T) -> anyhow::Result<()> {
    for stele in state.archive().stelae.values() {
        if let Some(repositories) = stele.repositories.as_ref() {
            if stele.is_root() {
                continue;
            }
            register_dependent_routes(cfg, stele, repositories)?;
        }
    }
    let root = state.archive().get_root()?;
    register_root_routes(cfg, root)?;
    Ok(())
}

/// Register routes for the root Stele
/// Root Stele is the Stele specified in config.toml
/// # Arguments
/// * `cfg` - The Actix `ServiceConfig`
/// * `stele` - The root Stele
/// # Errors
/// Will error if unable to register routes (e.g. if git repository cannot be opened)
fn register_root_routes(cfg: &mut web::ServiceConfig, stele: &Stele) -> anyhow::Result<()> {
    let mut root_scope: Scope = web::scope("");
    if let Some(repositories) = stele.repositories.as_ref() {
        let sorted_repositories = repositories.get_sorted();
        for repository in sorted_repositories {
            let custom = &repository.custom;
            let repo_state = state::init_repo(repository, stele)?;
            for route in custom.routes.iter().flat_map(|routes| routes.iter()) {
                let actix_route = format!("/{{tail:{}}}", &route);
                root_scope = root_scope.service(
                    web::resource(actix_route.as_str())
                        .route(web::get().to(serve))
                        .route(web::head().to(serve))
                        .app_data(web::Data::new(repo_state.clone())),
                );
            }
            if let Some(underscore_scope) = custom.scope.as_ref() {
                let actix_underscore_scope = web::scope(underscore_scope.as_str()).service(
                    web::scope("").service(
                        web::resource("/{tail:.*}")
                            .route(web::get().to(serve))
                            .route(web::head().to(serve))
                            .app_data(web::Data::new(repo_state.clone())),
                    ),
                );
                cfg.service(actix_underscore_scope);
            }
        }
        cfg.service(root_scope);
    }
    Ok(())
}

/// Register routes for dependent Stele
/// Dependent Stele are all Steles' specified in the root Stele's `dependencies.json` config file.
/// # Arguments
/// * `cfg` - The Actix `ServiceConfig`
/// * `stele` - The root Stele
/// * `repositories` - Data repositories of the dependent Stele
/// # Errors
/// Will error if unable to register routes (e.g. if git repository cannot be opened)
fn register_dependent_routes(
    cfg: &mut web::ServiceConfig,
    stele: &Stele,
    repositories: &Repositories,
) -> anyhow::Result<()> {
    let sorted_repositories = repositories.get_sorted();
    for scope in repositories.scopes.iter().flat_map(|scopes| scopes.iter()) {
        let scope_str = format!("/{{prefix:{}}}", &scope.as_str());
        let mut actix_scope = web::scope(scope_str.as_str());
        for repository in &sorted_repositories {
            let custom = &repository.custom;
            let repo_state = state::init_repo(repository, stele)?;
            for route in custom.routes.iter().flat_map(|routes| routes.iter()) {
                if route.starts_with('_') {
                    // Ignore routes in dependent Stele that start with underscore
                    // These routes are handled by the root Stele.
                    continue;
                }
                let actix_route = format!("/{{tail:{}}}", &route);
                actix_scope = actix_scope.service(
                    web::resource(actix_route.as_str())
                        .route(web::get().to(serve))
                        .route(web::head().to(serve))
                        .app_data(web::Data::new(repo_state.clone())),
                );
            }
        }
        cfg.service(actix_scope);
    }
    Ok(())
}