docbox-http 0.9.1

Docbox HTTP layer, routes, types, and middleware
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
//! Admin related access and routes for managing tenants and document boxes

use crate::{
    error::{DynHttpError, HttpCommonError, HttpErrorResponse, HttpResult, HttpStatusResult},
    middleware::tenant::{TenantDb, TenantParams, TenantSearch, TenantStorage},
    models::admin::{
        HttpAdminError, TenantDocumentBoxesRequest, TenantDocumentBoxesResponse,
        TenantStatsResponse,
    },
};
use axum::{Extension, Json, extract::Path, http::StatusCode};
use axum_valid::Garde;
use docbox_core::{
    database::{
        DatabasePoolCache,
        models::{
            document_box::{DocumentBox, WithScope},
            file::File,
            folder::Folder,
            link::Link,
            user::User,
        },
        utils::DatabaseErrorExt,
    },
    document_box::search_document_box::{ResolvedSearchResult, search_document_boxes_admin},
    processing::ProcessingLayer,
    purge::purge_expired_presigned_tasks::purge_expired_presigned_tasks,
    search::models::{
        AdminSearchRequest, AdminSearchResultResponse, AdminUsersResults, SearchResultItem,
        UsersRequest,
    },
    storage::StorageLayerFactory,
    tenant::tenant_cache::TenantCache,
};
use std::sync::Arc;
use tokio::{join, try_join};

pub const ADMIN_TAG: &str = "Admin";

/// Admin Boxes
///
/// Requests a list of document boxes within the tenant optionally filtered to
/// a specific query with support for wildcards
#[utoipa::path(
    post,
    operation_id = "admin_tenant_boxes",
    tag = ADMIN_TAG,
    path = "/admin/boxes",
    responses(
        (status = 201, description = "Searched successfully", body = TenantDocumentBoxesResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all, fields(?req))]
pub async fn tenant_boxes(
    TenantDb(db): TenantDb,
    Garde(Json(req)): Garde<Json<TenantDocumentBoxesRequest>>,
) -> HttpResult<TenantDocumentBoxesResponse> {
    let offset = req.offset.unwrap_or(0);
    let limit = req.size.unwrap_or(100);

    let (document_boxes, total) = match req.query {
        Some(query) if !query.is_empty() => {
            // Adjust the query to be better suited for searching
            let mut query = query
                // Replace wildcards with the SQL wildcard version
                .replace("*", "%")
                // Escape underscore literal
                .replace("_", "\\_");

            let has_wildcard = query.chars().any(|char| matches!(char, '*' | '%'));

            // Query contains no wildcards, insert a wildcard at the end for prefix matching
            if !has_wildcard {
                query.push('%');
            }

            let document_boxes = DocumentBox::search_query(&db, &query, offset, limit as u64)
                .await
                .map_err(|error| {
                    tracing::error!(?error, "failed to query document boxes");
                    HttpCommonError::ServerError
                })?;

            let total = DocumentBox::search_total(&db, &query)
                .await
                .map_err(|error| {
                    tracing::error!(?error, "failed to query document boxes total");
                    HttpCommonError::ServerError
                })?;

            (document_boxes, total)
        }
        _ => {
            let document_boxes = DocumentBox::query(&db, offset, limit as u64)
                .await
                .map_err(|error| {
                    tracing::error!(?error, "failed to query document boxes");
                    HttpCommonError::ServerError
                })?;

            let total = DocumentBox::total(&db).await.map_err(|error| {
                tracing::error!(?error, "failed to query document boxes total");
                HttpCommonError::ServerError
            })?;

            (document_boxes, total)
        }
    };

    Ok(Json(TenantDocumentBoxesResponse {
        results: document_boxes,
        total,
    }))
}

/// Admin Stats
///
/// Requests stats about a tenant such as the total of each item type as
/// well as the total file size consumed
#[utoipa::path(
    get,
    operation_id = "admin_tenant_stats",
    tag = ADMIN_TAG,
    path = "/admin/tenant-stats",
    responses(
        (status = 201, description = "Got stats successfully", body = TenantStatsResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all)]
pub async fn tenant_stats(TenantDb(db): TenantDb) -> HttpResult<TenantStatsResponse> {
    let total_files_future = File::total_count(&db);
    let total_links_future = Link::total_count(&db);
    let total_folders_future = Folder::total_count(&db);
    let file_size_future = File::total_size(&db);

    let (total_files, total_links, total_folders, file_size) = join!(
        total_files_future,
        total_links_future,
        total_folders_future,
        file_size_future
    );

    let total_files = total_files.map_err(|error| {
        tracing::error!(?error, "failed to query tenant total files");
        HttpCommonError::ServerError
    })?;

    let total_links = total_links.map_err(|error| {
        tracing::error!(?error, "failed to query tenant total links");
        HttpCommonError::ServerError
    })?;

    let total_folders = total_folders.map_err(|error| {
        tracing::error!(?error, "failed to query tenant total folders");
        HttpCommonError::ServerError
    })?;

    let file_size = file_size.map_err(|error| {
        tracing::error!(?error, "failed to query tenant files size");
        HttpCommonError::ServerError
    })?;

    Ok(Json(TenantStatsResponse {
        total_files,
        total_folders,
        total_links,
        file_size,
    }))
}

/// Admin Search
///
/// Performs a search across multiple document box scopes. This
/// is an administrator route as unlike other routes we cannot
/// assert through the URL that the user has access to all the
/// scopes
#[utoipa::path(
    post,
    operation_id = "admin_search_tenant",
    tag = ADMIN_TAG,
    path = "/admin/search",
    responses(
        (status = 201, description = "Searched successfully", body = AdminSearchResultResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all, fields(?req))]
pub async fn search_tenant(
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    Garde(Json(req)): Garde<Json<AdminSearchRequest>>,
) -> HttpResult<AdminSearchResultResponse> {
    // Not searching any scopes
    if req.scopes.is_empty() {
        return Ok(Json(AdminSearchResultResponse {
            total_hits: 0,
            results: vec![],
        }));
    }

    let resolved = search_document_boxes_admin(&db, &search, req)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to perform admin search");
            HttpCommonError::ServerError
        })?;

    let out: Vec<WithScope<SearchResultItem>> = resolved
        .results
        .into_iter()
        .map(|ResolvedSearchResult { result, data, path }| WithScope {
            data: SearchResultItem {
                path,
                score: result.score,
                data,
                page_matches: result.page_matches,
                total_hits: result.total_hits,
                name_match: result.name_match,
                content_match: result.content_match,
            },
            scope: result.document_box,
        })
        .collect();

    Ok(Json(AdminSearchResultResponse {
        total_hits: resolved.total_hits,
        results: out,
    }))
}

/// Reprocess octet-stream files
///
/// Useful if a files were previously accepted into the tenant with some unknown
/// file type (or ingested through a source that was unable to get the correct mime).
///
/// Will reprocess files that have this unknown file type mime to see if a different
/// type can be obtained.
///
/// This endpoint is not supported on serverless
#[utoipa::path(
    post,
    operation_id = "admin_reprocess_octet_stream_files",
    tag = ADMIN_TAG,
    path = "/admin/reprocess-octet-stream-files",
    responses(
        (status = 204, description = "Reprocessed successfully", body = AdminSearchResultResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all)]
pub async fn reprocess_octet_stream_files_tenant(
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    TenantStorage(storage): TenantStorage,
    Extension(processing): Extension<ProcessingLayer>,
) -> HttpStatusResult {
    docbox_core::files::reprocess_octet_stream_files::reprocess_octet_stream_files(
        &db,
        &search,
        &storage,
        &processing,
    )
    .await
    .map_err(|error| {
        tracing::error!(?error, "failed to reprocess octet-stream files");
        HttpCommonError::ServerError
    })?;

    Ok(StatusCode::NO_CONTENT)
}

/// Rebuild search index
///
/// Rebuild the tenant search index from the data stored in the database
/// and in storage
///
/// This endpoint is not supported on serverless
#[utoipa::path(
    post,
    operation_id = "admin_rebuild_search_index",
    tag = ADMIN_TAG,
    path = "/admin/rebuild-search-index",
    responses(
        (status = 204, description = "Rebuilt successfully", body = ()),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all)]
pub async fn rebuild_search_index_tenant(
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    TenantStorage(storage): TenantStorage,
) -> HttpStatusResult {
    docbox_core::tenant::rebuild_tenant_index::rebuild_tenant_index(&db, &search, &storage)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to rebuilt tenant search index");
            HttpCommonError::ServerError
        })?;

    Ok(StatusCode::NO_CONTENT)
}

/// Flush database cache
///
/// Empties all the database pool and credentials caches, you can use this endpoint
/// if you rotate your database credentials to refresh the database pool without
/// needing to restart the server
#[utoipa::path(
    post,
    operation_id = "admin_flush_database_pool_cache",
    tag = ADMIN_TAG,
    path = "/admin/flush-db-cache",
    responses(
        (status = 204, description = "Database cache flushed"),
    )
)]
pub async fn flush_database_pool_cache(
    Extension(db_cache): Extension<Arc<DatabasePoolCache>>,
) -> HttpStatusResult {
    db_cache.flush().await;
    Ok(StatusCode::NO_CONTENT)
}

/// Flush tenant cache
///
/// Clears the tenant cache, you can use this endpoint if you've updated the
/// tenant configuration and want it to be applied immediately without
/// restarting the server
#[utoipa::path(
    post,
    operation_id = "admin_flush_tenant_cache",
    tag = ADMIN_TAG,
    path = "/admin/flush-tenant-cache",
    responses(
        (status = 204, description = "Tenant cache flushed"),
    )
)]
pub async fn flush_tenant_cache(
    Extension(tenant_cache): Extension<Arc<TenantCache>>,
) -> HttpStatusResult {
    tenant_cache.flush().await;
    Ok(StatusCode::NO_CONTENT)
}

/// Purge Presigned Tasks
///
/// Purges all expired presigned tasks, this operation deletes any presigned uploads
/// that have not yet been completed but have passed the expiration date
#[utoipa::path(
    post,
    operation_id = "admin_purge_expired_presigned_tasks",
    tag = ADMIN_TAG,
    path = "/admin/purge-expired-presigned-tasks",
    responses(
        (status = 204, description = "Database cache flushed"),
        (status = 500, description = "Failed to purge presigned cache", body = HttpErrorResponse),
    )
)]
pub async fn http_purge_expired_presigned_tasks(
    Extension(db_cache): Extension<Arc<DatabasePoolCache>>,
    Extension(storage_factory): Extension<StorageLayerFactory>,
) -> HttpStatusResult {
    purge_expired_presigned_tasks(db_cache, storage_factory)
        .await
        .map_err(|_| HttpCommonError::ServerError)?;

    Ok(StatusCode::NO_CONTENT)
}

/// List Users
///
/// Request lists of users stored in the docbox database
#[utoipa::path(
    post,
    operation_id = "admin_list_users",
    tag = ADMIN_TAG,
    path = "/admin/users",
    responses(
        (status = 200, description = "Listed users successfully", body = AdminSearchResultResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all, fields(?req))]
pub async fn list_users(
    TenantDb(db): TenantDb,
    Garde(Json(req)): Garde<Json<UsersRequest>>,
) -> HttpResult<AdminUsersResults> {
    let offset = req.offset.unwrap_or(0);
    let limit = req.size.unwrap_or(100) as u64;

    let total_future = User::total(&db);
    let results_future = User::query(&db, offset, limit);
    let (total, results) = try_join!(total_future, results_future).map_err(|error| {
        tracing::error!(?error, "failed to query users");
        HttpCommonError::ServerError
    })?;

    Ok(Json(AdminUsersResults { total, results }))
}

/// Delete User
///
/// Delete a user by ID, the user must not be associated with any resources
/// (Edit history or creation of resources)
#[utoipa::path(
    delete,
    operation_id = "admin_delete_user",
    tag = ADMIN_TAG,
    path = "/admin/users/{id}",
    responses(
        (status = 204, description = "Listed users successfully", body = AdminSearchResultResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(TenantParams)
)]
#[tracing::instrument(skip_all, fields(id))]
pub async fn delete_user(TenantDb(db): TenantDb, Path(id): Path<String>) -> HttpStatusResult {
    let user = User::find(&db, &id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query user");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpAdminError::UnknownUser)?;

    user.delete(&db).await.map_err(|error| {
        if error.is_restrict() {
            tracing::error!(
                ?error,
                "attempted to delete a user without first deleting attached resources"
            );
            DynHttpError::from(HttpAdminError::UserResourcesAttached)
        } else {
            tracing::error!(?error, "failed to delete user");
            DynHttpError::from(HttpCommonError::ServerError)
        }
    })?;

    Ok(StatusCode::NO_CONTENT)
}