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
//! Folder related endpoints

use crate::{
    error::{DynHttpError, HttpCommonError, HttpErrorResponse, HttpResult, HttpStatusResult},
    middleware::{
        action_user::{ActionUser, UserParams},
        tenant::{TenantDb, TenantEvents, TenantParams, TenantSearch, TenantStorage},
    },
    models::{
        document_box::DocumentBoxScope,
        file::UploadTaskResponse,
        folder::{
            CreateFolderRequest, FolderResponse, HttpFolderError, UpdateFolderRequest,
            ZipFolderRequest,
        },
    },
};
use axum::{Json, extract::Path, http::StatusCode};
use axum_valid::Garde;
use docbox_core::{
    database::models::{
        edit_history::EditHistory,
        folder::{Folder, FolderId, FolderWithExtra, ResolvedFolderWithExtra},
        shared::WithFullPath,
        tasks::TaskStatus,
    },
    folders::{
        create_folder::{CreateFolderData, safe_create_folder},
        create_folder_zip::{CreateFolderZipOptions, create_folder_zip},
        delete_folder::delete_folder,
        update_folder::{UpdateFolder, UpdateFolderError},
    },
    tasks::background_task::background_task,
};
use tracing::Instrument;

pub const FOLDER_TAG: &str = "Folder";

/// Create folder
///
/// Creates a new folder in the provided document box folder
#[utoipa::path(
    post,
    operation_id = "folder_create",
    tag = FOLDER_TAG,
    path = "/box/{scope}/folder",
    responses(
        (status = 201, description = "Folder created successfully", body = FolderResponse),
        (status = 404, description = "Destination folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope to create the folder within"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, ?req))]
pub async fn create(
    action_user: ActionUser,
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    TenantEvents(events): TenantEvents,
    Path(DocumentBoxScope(scope)): Path<DocumentBoxScope>,
    Garde(Json(req)): Garde<Json<CreateFolderRequest>>,
) -> Result<(StatusCode, Json<FolderResponse>), DynHttpError> {
    let folder_id = req.folder_id;
    let parent_folder = Folder::find_by_id(&db, &scope, folder_id)
        .await
        // Failed to query destination folder
        .map_err(|error| {
            tracing::error!(
                %scope,
                %folder_id,
                ?error,
                "failed to query link destination folder"
            );
            HttpCommonError::ServerError
        })?
        // Folder not found
        .ok_or(HttpFolderError::UnknownFolder)?;

    // Update stored editing user data
    let created_by = action_user.store_user(&db).await?;

    // Make the create query
    let create = CreateFolderData {
        folder: parent_folder,
        name: req.name,
        created_by: created_by.as_ref().map(|value| value.id.to_string()),
    };

    // Perform Folder creation
    let folder = safe_create_folder(&db, search, &events, create)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to create link");
            HttpFolderError::CreateError(error)
        })?;

    Ok((
        StatusCode::CREATED,
        Json(FolderResponse {
            folder: FolderWithExtra {
                folder,
                created_by,
                last_modified_at: None,
                last_modified_by: None,
            },
            children: ResolvedFolderWithExtra::default(),
        }),
    ))
}

/// Get folder by ID
///
/// Requests a specific folder by ID. Will return the folder itself
/// as well as the first resolved set of children for the folder
#[utoipa::path(
    get,
    operation_id = "folder_get",
    tag = FOLDER_TAG,
    path = "/box/{scope}/folder/{folder_id}",
    responses(
        (status = 200, description = "Folder obtained successfully", body = FolderResponse),
        (status = 404, description = "Folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the folder resides within"),
        ("folder_id" = Uuid, Path, description = "ID of the folder to request"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %folder_id))]
pub async fn get(
    TenantDb(db): TenantDb,
    Path((scope, folder_id)): Path<(DocumentBoxScope, FolderId)>,
) -> HttpResult<FolderResponse> {
    let DocumentBoxScope(scope) = scope;

    let WithFullPath {
        data: folder,
        full_path,
    } = Folder::find_by_id_with_extra(&db, &scope, folder_id)
        .await
        // Failed to query folder
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        // Folder not found
        .ok_or(HttpFolderError::UnknownFolder)?;

    let children = ResolvedFolderWithExtra::resolve(&db, folder.folder.id, full_path)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to resolve folder children");
            HttpCommonError::ServerError
        })?;

    Ok(Json(FolderResponse { folder, children }))
}

/// Get folder edit history
///
/// Request the edit history for the provided folder
#[utoipa::path(
    get,
    operation_id = "folder_edit_history",
    tag = FOLDER_TAG,
    path = "/box/{scope}/folder/{folder_id}/edit-history",
    responses(
        (status = 200, description = "Obtained edit history", body = [EditHistory]),
        (status = 404, description = "Folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the folder resides within"),
        ("folder_id" = Uuid, Path, description = "ID of the folder to request"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %folder_id))]
pub async fn get_edit_history(
    TenantDb(db): TenantDb,
    Path((scope, folder_id)): Path<(DocumentBoxScope, FolderId)>,
) -> HttpResult<Vec<EditHistory>> {
    let DocumentBoxScope(scope) = scope;

    _ = Folder::find_by_id(&db, &scope, folder_id)
        .await
        // Failed to query folder
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        // Folder not found
        .ok_or(HttpFolderError::UnknownFolder)?;

    let edit_history = EditHistory::all_by_folder(&db, folder_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder edit history");
            HttpCommonError::ServerError
        })?;

    Ok(Json(edit_history))
}

/// Update folder
///
/// Updates a folder, can be a name change, a folder move, or both
#[utoipa::path(
    put,
    operation_id = "folder_update",
    tag = FOLDER_TAG,
    path = "/box/{scope}/folder/{folder_id}",
    responses(
        (status = 200, description = "Updated folder successfully"),
        (status = 400, description = "Attempted to move a root folder or a folder into itself", body = HttpErrorResponse),
        (status = 404, description = "Folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the folder resides within"),
        ("folder_id" = Uuid, Path, description = "ID of the folder to request"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %folder_id, ?req))]
pub async fn update(
    action_user: ActionUser,
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    Path((scope, folder_id)): Path<(DocumentBoxScope, FolderId)>,
    Garde(Json(req)): Garde<Json<UpdateFolderRequest>>,
) -> HttpStatusResult {
    let DocumentBoxScope(scope) = scope;

    let folder = Folder::find_by_id(&db, &scope, folder_id)
        .await
        // Failed to query folder
        .map_err(|error| {
            tracing::error!(%scope, %folder_id, ?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        // Folder not found
        .ok_or(HttpFolderError::UnknownFolder)?;

    // Update stored editing user data
    let user = action_user.store_user(&db).await?;
    let user_id = user.as_ref().map(|value| value.id.to_string());

    let update = UpdateFolder {
        folder_id: req.folder_id,
        name: req.name,
        pinned: req.pinned,
    };

    docbox_core::folders::update_folder::update_folder(
        &db, &search, &scope, folder, user_id, update,
    )
    .await
    .map_err(|error| match error {
        UpdateFolderError::UnknownTargetFolder => HttpFolderError::UnknownTargetFolder.into(),
        UpdateFolderError::CannotModifyRoot => HttpFolderError::CannotModifyRoot.into(),
        UpdateFolderError::CannotMoveIntoSelf => HttpFolderError::CannotMoveIntoSelf.into(),
        _ => DynHttpError::from(HttpCommonError::ServerError),
    })?;

    Ok(StatusCode::OK)
}

/// Delete a folder by ID
///
/// Deletes a document box folder and all its contents. This will
/// traverse the folder contents as a stack deleting all files and
/// folders within the folder before deleting itself
#[utoipa::path(
    delete,
    operation_id = "folder_delete",
    tag = FOLDER_TAG,
    path = "/box/{scope}/folder/{folder_id}",
    responses(
        (status = 204, description = "Deleted folder successfully"),
        (status = 404, description = "Folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the folder resides within"),
        ("folder_id" = Uuid, Path, description = "ID of the folder to delete"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %folder_id))]
pub async fn delete(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    TenantEvents(events): TenantEvents,
    TenantSearch(search): TenantSearch,
    Path((scope, folder_id)): Path<(DocumentBoxScope, FolderId)>,
) -> HttpStatusResult {
    let DocumentBoxScope(scope) = scope;

    let folder = Folder::find_by_id(&db, &scope, folder_id)
        .await
        // Failed to query folder
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        // Folder not found
        .ok_or(HttpFolderError::UnknownFolder)?;

    // Root folder cannot be deleted through the API
    if folder.folder_id.is_none() {
        return Err(HttpFolderError::CannotDeleteRoot.into());
    }

    delete_folder(&db, &storage, &search, &events, folder)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to delete folder");
            HttpCommonError::ServerError
        })?;

    Ok(StatusCode::NO_CONTENT)
}

/// Create a folder ZIP
///
/// Create a ZIP file from the contents of a folder
#[utoipa::path(
    post,
    operation_id = "folder_create_zip",
    tag = FOLDER_TAG,
    path = "/box/{scope}/folder/{folder_id}/zip",
    responses(
        (status = 204, description = "Deleted folder successfully"),
        (status = 404, description = "Folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the folder resides within"),
        ("folder_id" = Uuid, Path, description = "ID of the folder to delete"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %folder_id, ?req))]
pub async fn create_zip(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    Path((scope, folder_id)): Path<(DocumentBoxScope, FolderId)>,
    Garde(Json(req)): Garde<Json<ZipFolderRequest>>,
) -> HttpResult<UploadTaskResponse> {
    let DocumentBoxScope(scope) = scope;

    let folder = Folder::find_by_id(&db, &scope, folder_id)
        .await
        // Failed to query folder
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        // Folder not found
        .ok_or(HttpFolderError::UnknownFolder)?;

    let options = CreateFolderZipOptions {
        include: req.include,
        exclude: req.exclude,
    };

    let span = tracing::Span::current();

    // Spawn background task
    let (task_id, created_at) = background_task(
        db.clone(),
        scope.clone(),
        async move {
            let result = create_folder_zip(&db, &storage, &folder, options)
                .await
                .map_err(|error| {
                    tracing::error!(?error, "failed to upload file");
                    DynHttpError::from(HttpFolderError::CreateZipFile)
                })
                // Serialize the response for storage
                .and_then(|value| {
                    serde_json::to_value(&value).map_err(|error| {
                        tracing::error!(?error, "failed to serialize upload task outcome");
                        DynHttpError::from(HttpCommonError::ServerError)
                    })
                });

            match result {
                Ok(value) => (TaskStatus::Completed, value),
                Err(error) => (
                    TaskStatus::Failed,
                    serde_json::json!({ "error": error.to_string() }),
                ),
            }
        }
        // Ensure the logging span is passed onto the background task so that
        // logging context continues
        .instrument(span),
    )
    .await
    .map_err(|error| {
        tracing::error!(?error, "failed to create background task");
        HttpCommonError::ServerError
    })?;

    Ok(Json(UploadTaskResponse {
        task_id,
        created_at,
    }))
}