tuxedo 0.5.0

A parallel masking library for MongoDB
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use super::{
    manager::ReplicationConfig,
    task::{ModelTask, ReplicatorTask, Task},
    types::DatabasePair,
};
use crate::replication::task::TaskConfig;
use crate::{Mask, TuxedoResult};
use async_trait::async_trait;
use bson::{Document, RawDocumentBuf};
use indicatif::ProgressBar;
use serde::{de::DeserializeOwned, Serialize};
use std::marker::PhantomData;
use std::sync::Arc;
use tokio::sync::mpsc;

#[async_trait]
pub(crate) trait Processor: Send + Sync {
    async fn run(
        &self,
        dbs: Arc<DatabasePair>,
        task_sender: mpsc::Sender<Box<dyn Task>>,
        default_config: ReplicationConfig,
        progress_bar: ProgressBar,
    );

    async fn get_total_documents(
        &self,
        dbs: &Arc<DatabasePair>,
        query: Document,
    ) -> TuxedoResult<usize> {
        match dbs
            .read_total_documents::<RawDocumentBuf>(self.collection_name(), query)
            .await
        {
            Ok(total_documents) => Ok(total_documents),
            Err(e) => {
                println!(
                    "Could not get total number of documents for collection: `{}`. Collection will be skipped. Encountered error: {e}",
                    self.collection_name(),
                );
                Err(e)
            }
        }
    }

    fn setup_progress_bar(
        &self,
        progress_bar: ProgressBar,
        total_documents: usize,
        entity_name: &str,
    ) -> Arc<ProgressBar> {
        let progress_bar = Arc::new(progress_bar);

        progress_bar.set_length(total_documents as u64);
        progress_bar.set_message(format!("{} ({})", self.collection_name(), entity_name,));

        progress_bar
    }

    async fn setup_adaptive_batching(&self, dbs: &Arc<DatabasePair>) -> TuxedoResult<u64> {
        let average_document_size = dbs
            .get_average_document_size(self.collection_name())
            .await?;
        let target_bytes = calculate_optimal_target_bytes(average_document_size);
        // Calculate docs to match target_bytes (at least 1 document)
        let optimal_document_count = target_bytes / average_document_size;
        let batch_size = optimal_document_count.max(1);

        Ok(batch_size)
    }

    async fn copy_indexes(&self, dbs: &Arc<DatabasePair>) {
        if let Err(e) = dbs.copy_indexes(self.collection_name()).await {
            println!(
                "Error when copying indexes for collection `{}` from source to target - Error: {:?}",
                self.collection_name(),
                e
            )
        }
    }

    fn collection_name(&self) -> &str;
}

pub(crate) struct ModelProcessor<T: Mask + Serialize + DeserializeOwned + Send + Sync + Unpin> {
    config: ProcessorConfig,
    collection_name: String,
    _phantom_data: PhantomData<T>,
}

impl<T: Mask + Serialize + DeserializeOwned + Send + Sync + Unpin> ModelProcessor<T> {
    pub(crate) fn new(collection_name: impl Into<String>, config: ProcessorConfig) -> Self {
        Self {
            config,
            collection_name: collection_name.into(),
            _phantom_data: PhantomData,
        }
    }
}

pub(crate) struct ReplicatorProcessor<T: Send + Sync> {
    config: ReplicatorConfig,
    collection_name: String,
    _phantom_data: PhantomData<T>,
}

impl<T: Send + Sync> ReplicatorProcessor<T> {
    pub(crate) fn new(config: ReplicatorConfig, collection_name: String) -> Self {
        Self {
            config,
            collection_name,
            _phantom_data: PhantomData,
        }
    }
}

#[async_trait]
impl<T: Mask + Serialize + DeserializeOwned + Send + Sync + Unpin + 'static> Processor
    for ModelProcessor<T>
{
    async fn run(
        &self,
        dbs: Arc<DatabasePair>,
        task_sender: mpsc::Sender<Box<dyn Task>>,
        default_config: ReplicationConfig,
        progress_bar: ProgressBar,
    ) {
        let mut batch_size = self.config.batch_size.unwrap_or(default_config.batch_size);
        let write_batch_size = self
            .config
            .write_batch_size
            .unwrap_or(default_config.write_batch_size);

        let total_documents = match self
            .get_total_documents(&dbs, self.config.query.clone())
            .await
        {
            Ok(total_documents) => total_documents,
            Err(_) => return,
        };

        let progress_bar = self.setup_progress_bar(
            progress_bar,
            total_documents,
            std::any::type_name::<T>()
                .split("::")
                .last()
                .expect("Expected to get model name for progress bar"),
        );

        if total_documents == 0 {
            progress_bar.finish_and_clear();
            return;
        }

        if self.config.adaptive_batching == Some(true) || default_config.adaptive_batching {
            if let Ok(adaptive_batch_size) = self.setup_adaptive_batching(&dbs).await {
                batch_size = adaptive_batch_size;
            }
        }

        let batch_count = total_documents.div_ceil(batch_size as usize);
        let strategy = default_config.strategy;
        let write_options = default_config.write_options;

        for batch_index in 0..batch_count {
            let skip = batch_index * batch_size as usize;
            let remaining_documents = total_documents.saturating_sub(skip);
            let limit = batch_size.min(remaining_documents as u64) as i64;

            // This should never happen in theory
            if limit == 0 {
                // No more documents to process
                break;
            }

            let dbs = Arc::clone(&dbs);
            let query = self.config.query.clone();
            let strategy = strategy.clone();
            let progress_bar = Arc::clone(&progress_bar);

            let mut read_options = default_config.read_options.clone();
            // Ensure stable sort order for skip/limit pagination
            // if read_options.sort.is_none() {
            //     read_options.sort = Some(doc! { "_id": 1 });
            // }
            read_options.skip = (skip as u64).into();
            read_options.limit = limit.into();
            read_options.batch_size = Some(limit as u32);

            let task = Box::new(ModelTask::<T>::new(
                dbs,
                self.collection_name.clone(),
                TaskConfig {
                    query,
                    write_batch_size,
                    read_options,
                    write_options: write_options.clone(),
                },
                strategy,
                progress_bar,
            ));

            if task_sender.send(task).await.is_err() {
                println!(
                    "Failed to send task to worker pool for collection '{}' (batch {}/{}). Channel closed, stopping processor.",
                    &self.collection_name,
                    batch_index + 1,
                    batch_count
                );
                // Channel closed, stop sending tasks
                break;
            }
        }
    }

    fn collection_name(&self) -> &str {
        &self.collection_name
    }
}

fn calculate_optimal_target_bytes(average_document_size: u64) -> u64 {
    // For very small documents (<1KB), use larger batches to reduce i/o overhead
    if average_document_size < 1024 {
        return to_mb(75);
    }

    // For small documents (1KB-10KB), use standard batch size
    if average_document_size < 10 * 1024 {
        return to_mb(50);
    }

    // For medium documents (10KB-100KB), use moderate batch size
    if average_document_size < 100 * 1024 {
        return to_mb(30);
    }

    // For large documents (100KB-500KB), use smaller batches
    if average_document_size < 500 * 1024 {
        return to_mb(15);
    }

    // For very large documents (>500KB), use minimal batches
    // to avoid excessive memory pressure
    to_mb(5)
}

fn to_mb(size: u64) -> u64 {
    size * 1024 * 1024
}

#[async_trait]
impl<T: Send + Sync + 'static> Processor for ReplicatorProcessor<T> {
    async fn run(
        &self,
        dbs: Arc<DatabasePair>,
        task_sender: mpsc::Sender<Box<dyn Task>>,
        default_config: ReplicationConfig,
        progress_bar: ProgressBar,
    ) {
        let mut batch_size = self.config.batch_size.unwrap_or(default_config.batch_size);
        let write_batch_size = self
            .config
            .write_batch_size
            .unwrap_or(default_config.write_batch_size);

        let total_documents = match self
            .get_total_documents(&dbs, self.config.query.clone())
            .await
        {
            Ok(total_documents) => total_documents,
            Err(_) => return,
        };

        let progress_bar = self.setup_progress_bar(progress_bar, total_documents, "Document");

        if total_documents == 0 {
            progress_bar.finish_and_clear();
            return;
        }

        if self.config.adaptive_batching == Some(true) || default_config.adaptive_batching {
            if let Ok(adaptive_batch_size) = self.setup_adaptive_batching(&dbs).await {
                batch_size = adaptive_batch_size;
            }
        }

        let batch_count = total_documents.div_ceil(batch_size as usize);
        let write_options = default_config.write_options;

        for batch_index in 0..batch_count {
            let skip = batch_index * batch_size as usize;
            let remaining_documents = total_documents.saturating_sub(skip);
            let limit = batch_size.min(remaining_documents as u64) as i64;

            // This should never happen in theory
            if limit == 0 {
                // No more documents to process
                break;
            }

            let dbs = Arc::clone(&dbs);
            let query = self.config.query.clone();
            let progress_bar = Arc::clone(&progress_bar);

            let mut read_options = default_config.read_options.clone();
            // Ensure stable sort order for skip/limit pagination
            // if read_options.sort.is_none() {
            //     read_options.sort = Some(doc! { "_id": 1 });
            // }
            read_options.skip = (skip as u64).into();
            read_options.limit = limit.into();
            read_options.batch_size = Some(limit as u32);

            let task = Box::new(ReplicatorTask::<T>::new(
                dbs,
                self.collection_name.clone(),
                TaskConfig {
                    query,
                    write_batch_size,
                    read_options,
                    write_options: write_options.clone(),
                },
                // QueryConfig::new(query, skip, limit, batch_size),
                self.config.lambda.clone(),
                progress_bar,
            ));

            if task_sender.send(task).await.is_err() {
                println!(
                    "Failed to send task to worker pool for collection '{}' (batch {}/{}). Channel closed, stopping processor.",
                    &self.collection_name,
                    batch_index + 1,
                    batch_count
                );
                // Channel closed, stop sending tasks
                break;
            }
        }
    }

    fn collection_name(&self) -> &str {
        &self.collection_name
    }
}

#[derive(Debug, Default)]
pub struct ProcessorConfig {
    adaptive_batching: Option<bool>,
    batch_size: Option<u64>,
    write_batch_size: Option<u64>,
    query: Document,
}

#[derive(Debug, Default)]
pub struct ProcessorConfigBuilder {
    config: ProcessorConfig,
}

impl ProcessorConfig {
    pub fn builder() -> ProcessorConfigBuilder {
        ProcessorConfigBuilder::new()
    }
}

impl ProcessorConfigBuilder {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn batch_size(mut self, size: impl Into<u64>) -> Self {
        self.config.batch_size = Some(size.into());
        self
    }

    pub fn write_batch_size(mut self, size: impl Into<u64>) -> Self {
        self.config.write_batch_size = Some(size.into());
        self
    }

    pub fn query<Q: Into<Document>>(mut self, query: Q) -> Self {
        self.config.query = query.into();
        self
    }

    pub fn adaptive_batching(mut self, enabled: bool) -> Self {
        self.config.adaptive_batching = Some(enabled);
        self
    }

    pub fn build(self) -> ProcessorConfig {
        self.config
    }
}

#[derive(Default)]
pub struct ReplicatorConfig {
    adaptive_batching: Option<bool>,
    batch_size: Option<u64>,
    write_batch_size: Option<u64>,
    query: Document,
    lambda: Option<Arc<dyn Fn(&mut Document) + Send + Sync>>,
}

impl ReplicatorConfig {
    fn new(
        batch_size: Option<u64>,
        write_batch_size: Option<u64>,
        query: Document,
        adaptive_batching: Option<bool>,
        lambda: Option<Arc<dyn Fn(&mut Document) + Send + Sync>>,
    ) -> Self {
        Self {
            batch_size,
            write_batch_size,
            query,
            adaptive_batching,
            lambda,
        }
    }

    pub fn builder() -> ReplicationConfigBuilder {
        ReplicationConfigBuilder::new()
    }
}

#[derive(Default)]
pub struct ReplicationConfigBuilder {
    batch_size: Option<u64>,
    write_batch_size: Option<u64>,
    query: Document,
    adaptive_batching: Option<bool>,
    lambda: Option<Arc<dyn Fn(&mut Document) + Send + Sync>>,
}

impl ReplicationConfigBuilder {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn batch_size(mut self, size: impl Into<Option<u64>>) -> Self {
        self.batch_size = size.into();
        self
    }

    pub fn write_batch_size(mut self, size: impl Into<Option<u64>>) -> Self {
        self.write_batch_size = size.into();
        self
    }

    pub fn query(mut self, query: impl Into<Document>) -> Self {
        self.query = query.into();
        self
    }

    pub fn adaptive_batching(mut self, enabled: impl Into<bool>) -> Self {
        self.adaptive_batching = Some(enabled.into());
        self
    }

    pub fn mask<F>(mut self, lambda: F) -> Self
    where
        F: Fn(&mut Document) + Send + Sync + 'static,
    {
        self.lambda = Some(Arc::new(lambda));
        self
    }

    pub fn build(self) -> ReplicatorConfig {
        ReplicatorConfig::new(
            self.batch_size,
            self.write_batch_size,
            self.query,
            self.adaptive_batching,
            self.lambda,
        )
    }
}