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
use std::{collections::HashMap, future::Future};

use bonsaidb::{
    core::{
        api::Api,
        arc_bytes::serde::Bytes,
        async_trait::async_trait,
        connection::{AsyncConnection, AsyncStorageConnection, HasSession},
        schema::NamedCollection,
    },
    files::{FileConfig, Truncate},
    server::{
        api::{Handler, HandlerError, HandlerResult, HandlerSession},
        ServerDatabase,
    },
};
use futures::StreamExt;
use serde::{Deserialize, Serialize};

use crate::{
    permissions::{project_resource_name, DossierAction},
    schema::{Dossier, DossierFiles, Metadata, Project},
    CliBackend,
};

#[derive(Debug)]
pub struct DossierApiHandler;

#[derive(thiserror::Error, Debug, Serialize, Deserialize, Clone)]
pub enum ApiError {
    #[error("project not found")]
    ProjectNotFound,
    /// A name contained an invalid character. Currently, the only disallowed
    /// character is `/`.
    #[error("names must not contain '/'")]
    InvalidName,
    /// An absolute path was expected, but the path provided did not include a
    /// leading `/`.
    #[error("all paths must start with a leading '/'")]
    InvalidPath,
    /// An attempt at creating a file failed because a file already existed.
    #[error("a file already exists at the path provided")]
    AlreadyExists,
    /// The file was deleted during the operation.
    #[error("the file was deleted during the operation")]
    Deleted,
}

trait ResultExt<T> {
    fn map_files_error(self) -> Result<T, HandlerError<ApiError>>;
}

impl<A> ResultExt<A> for Result<A, bonsaidb::files::Error> {
    fn map_files_error(self) -> Result<A, HandlerError<ApiError>> {
        match self {
            Ok(result) => Ok(result),
            Err(bonsaidb::files::Error::Database(db)) => {
                Err(HandlerError::Server(bonsaidb::server::Error::from(db)))
            }
            Err(bonsaidb::files::Error::InvalidName) => {
                Err(HandlerError::Api(ApiError::InvalidName))
            }
            Err(bonsaidb::files::Error::InvalidPath) => {
                Err(HandlerError::Api(ApiError::InvalidPath))
            }
            Err(bonsaidb::files::Error::AlreadyExists) => {
                Err(HandlerError::Api(ApiError::AlreadyExists))
            }
            Err(bonsaidb::files::Error::Deleted) => Err(HandlerError::Api(ApiError::Deleted)),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Api)]
#[api(name = "compute-changes", response = HashMap<String, Bytes>, error = ApiError)]
pub struct ListFiles {
    pub path: String,
}

#[async_trait]
impl Handler<CliBackend, ListFiles> for DossierApiHandler {
    async fn handle(
        session: HandlerSession<'_, CliBackend>,
        request: ListFiles,
    ) -> HandlerResult<ListFiles> {
        handle_sync_op_with_permissions(
            session,
            &request.path,
            &request,
            |database, request| async move { list_files(&request.path, &database).await },
        )
        .await
    }
}

pub async fn list_files<C: AsyncConnection + Clone>(
    base_path: &str,
    database: &C,
) -> HandlerResult<ListFiles> {
    Ok(DossierFiles::list_recursive_async(base_path, database)
        .await?
        .into_iter()
        .filter_map(|file| {
            file.metadata()
                .map(|metadata| (file.path(), Bytes::from(metadata.blake3.to_vec())))
        })
        .collect())
}

#[derive(Serialize, Deserialize, Debug, Api)]
#[api(name = "delete-file", response = bool, error = ApiError)]
pub struct DeleteFile {
    pub path: String,
}

#[async_trait]
impl Handler<CliBackend, DeleteFile> for DossierApiHandler {
    async fn handle(
        session: HandlerSession<'_, CliBackend>,
        request: DeleteFile,
    ) -> HandlerResult<DeleteFile> {
        handle_sync_op_with_permissions(
            session,
            &request.path,
            &request,
            |database, request| async move { delete_file(&request.path, &database).await },
        )
        .await
    }
}

pub async fn delete_file<C: AsyncConnection + Clone>(
    path: &str,
    database: &C,
) -> HandlerResult<DeleteFile> {
    DossierFiles::delete_async(path, database)
        .await
        .map_files_error()
}

#[derive(Serialize, Deserialize, Debug, Api)]
#[api(name = "write-file", response = Option<Bytes>, error = ApiError)]
pub struct WriteFileData {
    pub path: String,
    pub data: Bytes,
    pub start: bool,
    pub finished: bool,
}

#[async_trait]
impl Handler<CliBackend, WriteFileData> for DossierApiHandler {
    async fn handle(
        session: HandlerSession<'_, CliBackend>,
        request: WriteFileData,
    ) -> HandlerResult<WriteFileData> {
        handle_sync_op_with_permissions(
            session,
            &request.path,
            &request,
            |database, request| async move {
                write_file_data(
                    &request.path,
                    &request.data,
                    request.start,
                    request.finished,
                    &database,
                )
                .await
            },
        )
        .await
    }
}

pub async fn write_file_data<C: AsyncConnection + Clone + Unpin + 'static>(
    path: &str,
    data: &[u8],
    start: bool,
    finished: bool,
    database: &C,
) -> HandlerResult<WriteFileData> {
    let mut file = match DossierFiles::load_async(path, database)
        .await
        .map_files_error()?
    {
        Some(file) if start => {
            file.truncate(0, Truncate::RemovingStart).await?;
            file
        }
        Some(file) => file,
        None if start => DossierFiles::build(path)
            .create_async(database)
            .await
            .map_files_error()?,
        None => return Err(HandlerError::Api(ApiError::Deleted)),
    };

    file.append(data).await?;

    if finished {
        // Compute the hash of the file
        let mut contents = file.contents().await?;
        let mut sha = blake3::Hasher::new();
        while let Some(block) = contents.next().await {
            let block = block?;
            sha.update(&block);
        }

        let hash = sha.finalize().try_into().unwrap();
        *file.metadata_mut() = Some(Metadata { blake3: hash });
        file.update_metadata().await?;

        Ok(Some(Bytes::from(hash.to_vec())))
    } else {
        Ok(None)
    }
}

async fn handle_sync_op_with_permissions<
    'future,
    A: Api<Error = ApiError>,
    Handle: FnOnce(ServerDatabase<CliBackend>, &'future A) -> F,
    F: Future<Output = HandlerResult<A>> + 'future,
>(
    session: HandlerSession<'_, CliBackend>,
    path: &str,
    request: &'future A,
    handler: Handle,
) -> HandlerResult<A> {
    let database = session.as_client.database::<Dossier>("dossier").await?;
    let project = path.split('/').nth(1);
    if let Some(project) = project {
        if let Some(project) = Project::load_async(project, &database).await? {
            session.as_client.check_permission(
                project_resource_name(project.header.id),
                &DossierAction::SyncFiles,
            )?;

            return handler(database, request).await;
        }
    }
    Err(HandlerError::Api(ApiError::ProjectNotFound))
}