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
use async_trait::async_trait;
use bson::{doc, Document};
use convert_case::{Case, Casing};
use futures::StreamExt;
use mongodb::{
    options::{FindOneAndUpdateOptions, FindOptions, ReturnDocument},
    results::{DeleteResult, InsertManyResult, UpdateResult},
    Client, Collection, Database,
};
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use serde::{de::DeserializeOwned, Serialize};
use std::fmt::Debug;

use crate::{
    connection::POOL,
    types::{ListOptions, MongooseError, PipelineStage},
};

#[async_trait]
pub trait Model:
    Serialize + DeserializeOwned + Unpin + Sync + Sized + Send + Default + Clone + Debug
{
    async fn client() -> &'static Client {
        &POOL.get().await.client
    }
    async fn database() -> &'static Database {
        &POOL.get().await.database
    }
    async fn collection() -> Collection<Self> {
        POOL.get().await.database.collection::<Self>(&Self::name())
    }
    fn name() -> String {
        let name = std::any::type_name::<Self>();
        name.split("::").last().map_or_else(
            || name.to_string(),
            |name| {
                let mut normalized = name.to_case(Case::Snake);
                if !normalized.ends_with('s') {
                    normalized.push('s');
                }
                normalized
            },
        )
    }
    fn generate_id() -> String {
        use nanoid::nanoid;
        // ~2 million years needed, in order to have a 1% probability of at least one collision.
        // https://zelark.github.io/nano-id-cc/
        nanoid!(
            20,
            &[
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            ]
        )
    }
    fn create_pipeline(pipeline: &[PipelineStage]) -> Vec<Document> {
        pipeline
            .par_iter()
            .map(|stage| match stage {
                PipelineStage::Match(doc) => doc! { "$match": doc },
                PipelineStage::Lookup(doc) => doc! {
                    "$lookup": doc! {
                        "from": doc.from.to_string(),
                        "localField": doc.local_field.to_string(),
                        "foreignField": doc.foreign_field.to_string(),
                        "as": doc.as_field.to_string()
                    }
                },
                PipelineStage::Project(doc) => doc! { "$project": doc },
                PipelineStage::Unwind(path) => doc! {
                    "$unwind": doc! {
                        "path": path
                    }
                },
                PipelineStage::AddFields(doc) => doc! { "$addFields": doc },
                PipelineStage::Limit(limit) => doc! { "$limit": limit },
                PipelineStage::Sort(doc) => doc! { "$sort": doc },
            })
            .collect::<Vec<_>>()
    }
    fn normalize_updates(updates: &Document) -> Document {
        let (mut set_updates, mut document_updates) =
            updates
                .keys()
                .fold((Document::new(), Document::new()), |mut acc, key| {
                    let val = updates.get(key);
                    if val.is_none() || key == "$set" {
                        // $set is built internally, so skip it
                        return acc;
                    }
                    if key.starts_with('$') {
                        // indicates something like $inc / $push / $pull
                        acc.1.insert(key, val);
                    } else {
                        // all other document field updates contained in $set
                        acc.0.insert(key, val);
                    }
                    acc
                });
        // update timestamp
        set_updates.insert("updated_at", chrono::Utc::now());
        document_updates.insert("$set", set_updates);
        // overall document now looks something like:
        // { $set: { "updated_at": Date, ... }, "$inc": { ... }, "$push": { ... } }
        document_updates
    }

    // client api methods
    async fn save(&self) -> Result<Self, MongooseError> {
        match Self::collection().await.insert_one(self, None).await {
            Ok(_) => Ok(self.clone()),
            Err(err) => {
                tracing::error!(
                    "error inserting {:?} document: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::Insert(Self::name()))
            }
        }
    }

    async fn bulk_insert(docs: &[Self]) -> Result<InsertManyResult, MongooseError> {
        match Self::collection().await.insert_many(docs, None).await {
            Ok(inserted) => Ok(inserted),
            Err(err) => {
                tracing::error!(
                    "error bulk inserting {:?} documents: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::BulkInsert(Self::name()))
            }
        }
    }

    async fn read(filter: Document) -> Result<Self, MongooseError> {
        match Self::collection().await.find_one(filter, None).await {
            Ok(result) => result.map_or_else(
                || Err(MongooseError::NotFound(Self::name())),
                |result| Ok(result),
            ),
            Err(err) => {
                tracing::error!(
                    "error reading {:?} document: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::NotFound(Self::name()))
            }
        }
    }

    async fn read_by_id(id: &str) -> Result<Self, MongooseError> {
        Self::read(doc! { "_id": id }).await
    }

    async fn list(
        filter: Option<Document>,
        options: Option<ListOptions>,
    ) -> Result<Vec<Self>, MongooseError> {
        let opts = match options {
            Some(opts) => {
                let limit = if opts.limit.is_some() {
                    opts.limit
                } else {
                    Some(1_000)
                };
                Some(
                    FindOptions::builder()
                        .skip(opts.skip)
                        .limit(limit)
                        .sort(opts.sort)
                        .projection(None)
                        .build(),
                )
            }
            None => None,
        };
        let mut result_cursor = match Self::collection().await.find(filter, opts).await {
            Ok(cursor) => cursor,
            Err(err) => {
                tracing::error!(
                    "error listing {:?} documents: {:?}",
                    Self::name(),
                    err.to_string()
                );
                return Err(MongooseError::List(Self::name()));
            }
        };
        let mut list_result = vec![];
        while let Some(cursor) = result_cursor.next().await {
            match cursor {
                Ok(document) => list_result.push(document),
                Err(err) => {
                    tracing::error!(
                        "error iterating {:?} cursor: {:?}",
                        Self::name(),
                        err.to_string()
                    );
                    continue;
                }
            }
        }
        Ok(list_result)
    }

    async fn update(filter: Document, updates: Document) -> Result<Self, MongooseError> {
        match Self::collection()
            .await
            .find_one_and_update(
                filter,
                Self::normalize_updates(&updates),
                FindOneAndUpdateOptions::builder()
                    .return_document(ReturnDocument::After)
                    .build(),
            )
            .await
        {
            Ok(updated) => updated.map_or_else(
                || Err(MongooseError::NotFound(Self::name())),
                |result| Ok(result),
            ),
            Err(err) => {
                tracing::error!(
                    "error updating {:?} document: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::Update(Self::name()))
            }
        }
    }

    async fn bulk_update(
        filter: Document,
        updates: Document,
    ) -> Result<UpdateResult, MongooseError> {
        match Self::collection()
            .await
            .update_many(filter, Self::normalize_updates(&updates), None)
            .await
        {
            Ok(updates) => Ok(updates),
            Err(err) => {
                tracing::error!(
                    "error updating {:?} documents: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::BulkUpdate(Self::name()))
            }
        }
    }

    async fn delete(filter: Document) -> Result<DeleteResult, MongooseError> {
        match Self::collection().await.delete_one(filter, None).await {
            Ok(found) => Ok(found),
            Err(err) => {
                tracing::error!(
                    "error deleting {:?} document: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::Delete(Self::name()))
            }
        }
    }

    async fn bulk_delete(filter: Document) -> Result<DeleteResult, MongooseError> {
        match Self::collection().await.delete_many(filter, None).await {
            Ok(found) => Ok(found),
            Err(err) => {
                tracing::error!(
                    "error bulk deleting {:?} documents: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::BulkDelete(Self::name()))
            }
        }
    }

    async fn count(filter: Option<Document>) -> Result<u64, MongooseError> {
        match Self::collection().await.count_documents(filter, None).await {
            Ok(count) => Ok(count),
            Err(err) => {
                tracing::error!(
                    "error counting {:?} documents: {:?}",
                    Self::name(),
                    err.to_string()
                );
                Err(MongooseError::Count(Self::name()))
            }
        }
    }

    async fn aggregate<T: DeserializeOwned + Send>(
        pipeline: &[PipelineStage],
    ) -> Result<Vec<T>, MongooseError> {
        let pipeline = Self::create_pipeline(pipeline);
        let mut result_cursor = match Self::collection().await.aggregate(pipeline, None).await {
            Ok(cursor) => cursor,
            Err(err) => {
                tracing::error!(
                    "error creating {:?} aggregate cursor: {:?}",
                    Self::name(),
                    err.to_string()
                );
                return Err(MongooseError::Aggregate(Self::name()));
            }
        };
        let mut aggregate_docs = vec![];
        while let Some(cursor) = result_cursor.next().await {
            match cursor {
                Ok(document) => match bson::from_document::<T>(document) {
                    Ok(data) => aggregate_docs.push(data),
                    Err(err) => {
                        tracing::error!(
                            "error converting {:?} bson in aggregation: {:?}",
                            Self::name(),
                            err.to_string()
                        );
                        return Err(MongooseError::Aggregate(Self::name()));
                    }
                },
                Err(err) => {
                    tracing::error!(
                        "error iterating {:?} aggregate cursor: {:?}",
                        Self::name(),
                        err.to_string()
                    );
                    return Err(MongooseError::Aggregate(Self::name()));
                }
            }
        }
        Ok(aggregate_docs)
    }
}