1
use std::{
2
    borrow::Cow,
3
    collections::{hash_map::RandomState, BTreeMap, BTreeSet, HashSet},
4
    sync::Arc,
5
};
6

            
7
use bonsaidb_core::{
8
    arc_bytes::{serde::Bytes, ArcBytes, OwnedBytes},
9
    connection::Connection,
10
    schema::{
11
        view::{self, map, Serialized},
12
        CollectionName, ViewName,
13
    },
14
};
15
use easy_parallel::Parallel;
16
use nebari::{
17
    io::any::AnyFile,
18
    tree::{AnyTreeRoot, CompareSwap, KeyOperation, Operation, Unversioned, Versioned},
19
    LockedTransactionTree, Tree, UnlockedTransactionTree,
20
};
21

            
22
use crate::{
23
    database::{deserialize_document, document_tree_name, Database},
24
    tasks::{Job, Keyed, Task},
25
    views::{
26
        view_document_map_tree_name, view_entries_tree_name, view_invalidated_docs_tree_name,
27
        EntryMapping, ViewEntry,
28
    },
29
    Error,
30
};
31

            
32
#[derive(Debug)]
33
pub struct Mapper {
34
    pub database: Database,
35
    pub map: Map,
36
}
37

            
38
504969
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
39
pub struct Map {
40
    pub database: Arc<Cow<'static, str>>,
41
    pub collection: CollectionName,
42
    pub view_name: ViewName,
43
}
44

            
45
impl Job for Mapper {
46
    type Output = u64;
47
    type Error = Error;
48

            
49
331288
    #[cfg_attr(feature = "tracing", tracing::instrument)]
50
165644
    #[allow(clippy::too_many_lines)]
51
    fn execute(&mut self) -> Result<Self::Output, Error> {
52
        let documents =
53
            self.database
54
                .roots()
55
                .tree(self.database.collection_tree::<Versioned, _>(
56
                    &self.map.collection,
57
                    document_tree_name(&self.map.collection),
58
                )?)?;
59

            
60
        let view_entries =
61
            self.database
62
                .roots()
63
                .tree(self.database.collection_tree::<Unversioned, _>(
64
                    &self.map.collection,
65
                    view_entries_tree_name(&self.map.view_name),
66
                )?)?;
67

            
68
        let document_map =
69
            self.database
70
                .roots()
71
                .tree(self.database.collection_tree::<Unversioned, _>(
72
                    &self.map.collection,
73
                    view_document_map_tree_name(&self.map.view_name),
74
                )?)?;
75

            
76
        let invalidated_entries =
77
            self.database
78
                .roots()
79
                .tree(self.database.collection_tree::<Unversioned, _>(
80
                    &self.map.collection,
81
                    view_invalidated_docs_tree_name(&self.map.view_name),
82
                )?)?;
83

            
84
        let transaction_id = self
85
            .database
86
            .last_transaction_id()?
87
            .expect("no way to have documents without a transaction");
88

            
89
        let storage = self.database.clone();
90
        let map_request = self.map.clone();
91

            
92
        map_view(
93
            &invalidated_entries,
94
            &document_map,
95
            &documents,
96
            &view_entries,
97
            &storage,
98
            &map_request,
99
        )?;
100

            
101
        self.database.storage.instance.tasks().mark_view_updated(
102
            self.map.database.clone(),
103
            self.map.collection.clone(),
104
            self.map.view_name.clone(),
105
            transaction_id,
106
        );
107

            
108
        Ok(transaction_id)
109
    }
110
}
111

            
112
165644
fn map_view(
113
165644
    invalidated_entries: &Tree<Unversioned, AnyFile>,
114
165644
    document_map: &Tree<Unversioned, AnyFile>,
115
165644
    documents: &Tree<Versioned, AnyFile>,
116
165644
    view_entries: &Tree<Unversioned, AnyFile>,
117
165644
    database: &Database,
118
165644
    map_request: &Map,
119
165644
) -> Result<(), Error> {
120
    const CHUNK_SIZE: usize = 100_000;
121
    // Only do any work if there are invalidated documents to process
122
165644
    let mut invalidated_ids = invalidated_entries
123
165644
        .get_range(&(..))?
124
165644
        .into_iter()
125
165644
        .map(|(key, _)| key)
126
165644
        .collect::<Vec<_>>();
127
179991
    while !invalidated_ids.is_empty() {
128
14347
        let transaction = database
129
14347
            .roots()
130
14347
            .transaction::<_, dyn AnyTreeRoot<AnyFile>>(&[
131
14347
                Box::new(invalidated_entries.clone()) as Box<dyn AnyTreeRoot<AnyFile>>,
132
14347
                Box::new(document_map.clone()),
133
14347
                Box::new(documents.clone()),
134
14347
                Box::new(view_entries.clone()),
135
14347
            ])?;
136
        {
137
14347
            let view = database
138
14347
                .data
139
14347
                .schema
140
14347
                .view_by_name(&map_request.view_name)
141
14347
                .unwrap();
142
14347

            
143
14347
            let document_ids = invalidated_ids
144
14347
                .drain(invalidated_ids.len().saturating_sub(CHUNK_SIZE)..)
145
14347
                .collect::<Vec<_>>();
146
14347
            let document_map = transaction.unlocked_tree(1).unwrap();
147
14347
            let documents = transaction.unlocked_tree(2).unwrap();
148
14347
            let view_entries = transaction.unlocked_tree(3).unwrap();
149
14347
            DocumentRequest {
150
14347
                document_ids: document_ids.clone(),
151
14347
                map_request,
152
14347
                database,
153
14347
                document_map,
154
14347
                documents,
155
14347
                view_entries,
156
14347
                view,
157
14347
            }
158
14347
            .map()?;
159

            
160
14347
            let mut invalidated_entries = transaction.tree::<Unversioned>(0).unwrap();
161
14347
            invalidated_entries.modify(document_ids, nebari::tree::Operation::Remove)?;
162
        }
163
14347
        transaction.commit()?;
164
    }
165

            
166
165644
    Ok(())
167
165644
}
168

            
169
pub struct DocumentRequest<'a> {
170
    pub document_ids: Vec<ArcBytes<'static>>,
171
    pub map_request: &'a Map,
172
    pub database: &'a Database,
173

            
174
    pub document_map: &'a UnlockedTransactionTree<AnyFile>,
175
    pub documents: &'a UnlockedTransactionTree<AnyFile>,
176
    pub view_entries: &'a UnlockedTransactionTree<AnyFile>,
177
    pub view: &'a dyn Serialized,
178
}
179

            
180
type DocumentIdPayload = (ArcBytes<'static>, Option<ArcBytes<'static>>);
181
type BatchPayload = (Vec<ArcBytes<'static>>, flume::Receiver<DocumentIdPayload>);
182

            
183
impl<'a> DocumentRequest<'a> {
184
99352
    fn generate_batches(
185
99352
        batch_sender: flume::Sender<BatchPayload>,
186
99352
        document_ids: &[ArcBytes<'static>],
187
99352
        documents: &UnlockedTransactionTree<AnyFile>,
188
99352
    ) -> Result<(), Error> {
189
99352
        // Generate batches
190
99352
        let mut documents = documents.lock::<Versioned>();
191
99352
        for chunk in document_ids.chunks(1024) {
192
99352
            let (document_id_sender, document_id_receiver) = flume::bounded(chunk.len());
193
99352
            batch_sender
194
99352
                .send((chunk.to_vec(), document_id_receiver))
195
99352
                .unwrap();
196
99352
            let mut documents = documents.get_multiple(chunk.iter().map(ArcBytes::as_slice))?;
197
99352
            documents.sort_by(|a, b| a.0.cmp(&b.0));
198

            
199
160866
            for document_id in chunk.iter().rev() {
200
160866
                let document = documents
201
160866
                    .last()
202
160866
                    .map_or(false, |(key, _)| (key == document_id))
203
160866
                    .then(|| documents.pop().unwrap().1);
204
160866

            
205
160866
                document_id_sender
206
160866
                    .send((document_id.clone(), document))
207
160866
                    .unwrap();
208
160866
            }
209

            
210
99352
            drop(document_id_sender);
211
        }
212
99352
        drop(batch_sender);
213
99352
        Ok(())
214
99352
    }
215

            
216
99352
    fn map_batches(
217
99352
        batch_receiver: &flume::Receiver<BatchPayload>,
218
99352
        mapped_sender: flume::Sender<Batch>,
219
99352
        view: &dyn Serialized,
220
99352
        parallelization: usize,
221
99352
    ) -> Result<(), Error> {
222
        // Process batches
223
198704
        while let Ok((document_ids, document_id_receiver)) = batch_receiver.recv() {
224
99352
            let mut batch = Batch {
225
99352
                document_ids,
226
99352
                ..Batch::default()
227
99352
            };
228
198674
            for result in Parallel::new()
229
198704
                .each(1..=parallelization, |_| -> Result<_, Error> {
230
198704
                    let mut results = Vec::new();
231
359539
                    while let Ok((document_id, document)) = document_id_receiver.recv() {
232
160866
                        let map_result = if let Some(document) = document {
233
145215
                            let document = deserialize_document(&document)?;
234

            
235
                            // Call the schema map function
236
145215
                            view.map(&document).map_err(bonsaidb_core::Error::from)?
237
                        } else {
238
                            // Get multiple didn't return this document ID.
239
15620
                            Vec::new()
240
                        };
241
160866
                        let keys: HashSet<OwnedBytes> = map_result
242
160866
                            .iter()
243
160866
                            .map(|map| OwnedBytes::from(map.key.as_slice()))
244
160866
                            .collect();
245
160866
                        let new_keys = ArcBytes::from(bincode::serialize(&keys)?);
246

            
247
160835
                        results.push((document_id, new_keys, keys, map_result));
248
                    }
249

            
250
198704
                    Ok(results)
251
198704
                })
252
99352
                .run()
253
            {
254
198674
                for (document_id, new_keys, keys, map_result) in result? {
255
306380
                    for key in &keys {
256
145544
                        batch.all_keys.insert(key.0.clone());
257
145544
                    }
258
160836
                    batch.document_maps.insert(document_id.clone(), new_keys);
259
160836
                    batch.document_keys.insert(document_id.clone(), keys);
260
306380
                    for mapping in map_result {
261
145544
                        let key_mappings = batch
262
145544
                            .new_mappings
263
145544
                            .entry(ArcBytes::from(mapping.key.to_vec()))
264
145544
                            .or_insert_with(Vec::default);
265
145544
                        key_mappings.push(mapping);
266
145544
                    }
267
                }
268
            }
269
99352
            mapped_sender.send(batch).unwrap();
270
        }
271
99352
        drop(mapped_sender);
272
99352
        Ok(())
273
99352
    }
274

            
275
99352
    fn update_document_map(
276
99352
        document_ids: Vec<ArcBytes<'static>>,
277
99352
        document_map: &mut LockedTransactionTree<'_, Unversioned, AnyFile>,
278
99352
        document_maps: &BTreeMap<ArcBytes<'static>, ArcBytes<'static>>,
279
99352
        mut document_keys: BTreeMap<ArcBytes<'static>, HashSet<OwnedBytes>>,
280
99352
        all_keys: &mut BTreeSet<ArcBytes<'static>>,
281
99352
    ) -> Result<BTreeMap<ArcBytes<'static>, HashSet<ArcBytes<'static>>>, Error> {
282
99352
        // We need to store a record of all the mappings this document produced.
283
99352
        let mut maps_to_clear = Vec::new();
284
99352
        document_map.modify(
285
99352
            document_ids,
286
99352
            nebari::tree::Operation::CompareSwap(CompareSwap::new(&mut |key, value| {
287
160866
                if let Some(existing_map) = value {
288
17129
                    maps_to_clear.push((key.to_owned(), existing_map));
289
143737
                }
290
160866
                let new_map = document_maps.get(key).unwrap();
291
160866
                KeyOperation::Set(new_map.clone())
292
160866
            })),
293
99352
        )?;
294
99352
        let mut view_entries_to_clean = BTreeMap::new();
295
116481
        for (document_id, existing_map) in maps_to_clear {
296
17129
            let existing_keys = bincode::deserialize::<HashSet<OwnedBytes>>(&existing_map)?;
297
17129
            let new_keys = document_keys.remove(&document_id).unwrap();
298
17129
            for key in existing_keys.difference(&new_keys) {
299
16489
                all_keys.insert(key.clone().0);
300
16489
                let key_documents = view_entries_to_clean
301
16489
                    .entry(key.clone().0)
302
16489
                    .or_insert_with(HashSet::<_, RandomState>::default);
303
16489
                key_documents.insert(document_id.clone());
304
16489
            }
305
        }
306
99352
        Ok(view_entries_to_clean)
307
99352
    }
308

            
309
99352
    fn update_view_entries(
310
99352
        view: &dyn Serialized,
311
99352
        map_request: &Map,
312
99352
        view_entries: &mut LockedTransactionTree<'_, Unversioned, AnyFile>,
313
99352
        all_keys: BTreeSet<ArcBytes<'static>>,
314
99352
        view_entries_to_clean: BTreeMap<ArcBytes<'static>, HashSet<ArcBytes<'static>>>,
315
99352
        new_mappings: BTreeMap<ArcBytes<'static>, Vec<map::Serialized>>,
316
99352
    ) -> Result<(), Error> {
317
99352
        let mut updater = ViewEntryUpdater {
318
99352
            view,
319
99352
            map_request,
320
99352
            view_entries_to_clean,
321
99352
            new_mappings,
322
99352
            result: Ok(()),
323
99352
            has_reduce: true,
324
99352
        };
325
99352
        view_entries
326
99352
            .modify(
327
99352
                all_keys.into_iter().collect(),
328
123679
                Operation::CompareSwap(CompareSwap::new(&mut |key, view_entries| {
329
123679
                    updater.compare_swap_view_entry(key, view_entries)
330
123679
                })),
331
99352
            )
332
99352
            .map_err(Error::from)
333
99352
            .and(updater.result)
334
99352
    }
335

            
336
99352
    fn save_mappings(
337
99352
        mapped_receiver: &flume::Receiver<Batch>,
338
99352
        view: &dyn Serialized,
339
99352
        map_request: &Map,
340
99352
        document_map: &mut LockedTransactionTree<'_, Unversioned, AnyFile>,
341
99352
        view_entries: &mut LockedTransactionTree<'_, Unversioned, AnyFile>,
342
99352
    ) -> Result<(), Error> {
343
        while let Ok(Batch {
344
99322
            document_ids,
345
99322
            document_maps,
346
99322
            document_keys,
347
99322
            new_mappings,
348
99322
            mut all_keys,
349
198146
        }) = mapped_receiver.recv()
350
        {
351
99322
            let view_entries_to_clean = Self::update_document_map(
352
99322
                document_ids,
353
99322
                document_map,
354
99322
                &document_maps,
355
99322
                document_keys,
356
99322
                &mut all_keys,
357
99322
            )?;
358

            
359
99322
            Self::update_view_entries(
360
99322
                view,
361
99322
                map_request,
362
99322
                view_entries,
363
99322
                all_keys,
364
99322
                view_entries_to_clean,
365
99322
                new_mappings,
366
99322
            )?;
367
        }
368
98824
        Ok(())
369
99352
    }
370

            
371
99352
    pub fn map(&mut self) -> Result<(), Error> {
372
99352
        let (batch_sender, batch_receiver) = flume::bounded(1);
373
99352
        let (mapped_sender, mapped_receiver) = flume::bounded(1);
374

            
375
297966
        for result in Parallel::new()
376
99352
            .add(|| Self::generate_batches(batch_sender, &self.document_ids, self.documents))
377
99352
            .add(|| {
378
99352
                Self::map_batches(
379
99352
                    &batch_receiver,
380
99352
                    mapped_sender,
381
99352
                    self.view,
382
99352
                    self.database.storage().parallelization(),
383
99352
                )
384
99352
            })
385
99352
            .add(|| {
386
99352
                let mut document_map = self.document_map.lock();
387
99352
                let mut view_entries = self.view_entries.lock();
388
99352
                Self::save_mappings(
389
99352
                    &mapped_receiver,
390
99352
                    self.view,
391
99352
                    self.map_request,
392
99352
                    &mut document_map,
393
99352
                    &mut view_entries,
394
99352
                )
395
99352
            })
396
99352
            .run()
397
        {
398
297966
            result?;
399
        }
400

            
401
98794
        Ok(())
402
99322
    }
403
}
404

            
405
99352
#[derive(Default)]
406
struct Batch {
407
    document_ids: Vec<ArcBytes<'static>>,
408
    document_maps: BTreeMap<ArcBytes<'static>, ArcBytes<'static>>,
409
    document_keys: BTreeMap<ArcBytes<'static>, HashSet<OwnedBytes>>,
410
    new_mappings: BTreeMap<ArcBytes<'static>, Vec<map::Serialized>>,
411
    all_keys: BTreeSet<ArcBytes<'static>>,
412
}
413

            
414
impl Keyed<Task> for Mapper {
415
173681
    fn key(&self) -> Task {
416
173681
        Task::ViewMap(self.map.clone())
417
173681
    }
418
}
419

            
420
struct ViewEntryUpdater<'a> {
421
    view: &'a dyn Serialized,
422
    map_request: &'a Map,
423
    view_entries_to_clean: BTreeMap<ArcBytes<'static>, HashSet<ArcBytes<'static>>>,
424
    new_mappings: BTreeMap<ArcBytes<'static>, Vec<map::Serialized>>,
425
    result: Result<(), Error>,
426
    has_reduce: bool,
427
}
428

            
429
impl<'a> ViewEntryUpdater<'a> {
430
123679
    fn compare_swap_view_entry(
431
123679
        &mut self,
432
123679
        key: &ArcBytes<'_>,
433
123679
        view_entries: Option<ArcBytes<'static>>,
434
123679
    ) -> KeyOperation<ArcBytes<'static>> {
435
123679
        let mut view_entry = view_entries
436
123679
            .and_then(|view_entries| bincode::deserialize::<ViewEntry>(&view_entries).ok())
437
123679
            .unwrap_or_else(|| ViewEntry {
438
96828
                key: Bytes::from(key.to_vec()),
439
96828
                view_version: self.view.version(),
440
96828
                mappings: vec![],
441
96828
                reduced_value: Bytes::default(),
442
123679
            });
443
123679
        let key = key.to_owned();
444
123679
        if let Some(document_ids) = self.view_entries_to_clean.remove(&key) {
445
16395
            view_entry
446
16395
                .mappings
447
16861
                .retain(|m| !document_ids.contains(m.source.id.as_ref()));
448
16395

            
449
16395
            if view_entry.mappings.is_empty() {
450
15993
                return KeyOperation::Remove;
451
402
            } else if self.has_reduce {
452
402
                let mappings = view_entry
453
402
                    .mappings
454
402
                    .iter()
455
402
                    .map(|m| (&key[..], m.value.as_slice()))
456
402
                    .collect::<Vec<_>>();
457
402

            
458
402
                match self.view.reduce(&mappings, false) {
459
372
                    Ok(reduced) => {
460
372
                        view_entry.reduced_value = Bytes::from(reduced);
461
372
                    }
462
                    Err(view::Error::Core(bonsaidb_core::Error::ReduceUnimplemented)) => {
463
                        self.has_reduce = false;
464
                    }
465
                    Err(other) => {
466
                        self.result = Err(Error::from(other));
467
                        return KeyOperation::Skip;
468
                    }
469
                }
470
            }
471
107284
        }
472

            
473
107656
        if let Some(new_mappings) = self.new_mappings.remove(&key[..]) {
474
252300
            for map::Serialized { source, value, .. } in new_mappings {
475
                // Before altering any data, verify that the key is unique if this is a unique view.
476
145514
                if self.view.unique()
477
69715
                    && !view_entry.mappings.is_empty()
478
1204
                    && view_entry.mappings[0].source.id != source.id
479
                {
480
528
                    self.result = Err(Error::Core(bonsaidb_core::Error::UniqueKeyViolation {
481
528
                        view: self.map_request.view_name.clone(),
482
528
                        conflicting_document: Box::new(source),
483
528
                        existing_document: Box::new(view_entry.mappings[0].source.clone()),
484
528
                    }));
485
528
                    return KeyOperation::Skip;
486
144956
                }
487
144956
                let entry_mapping = EntryMapping { source, value };
488
144956

            
489
144956
                // attempt to update an existing
490
144956
                // entry for this document, if
491
144956
                // present
492
144956
                let mut found = false;
493
456704
                for mapping in &mut view_entry.mappings {
494
312518
                    if mapping.source.id == entry_mapping.source.id {
495
770
                        found = true;
496
770
                        mapping.value = entry_mapping.value.clone();
497
770
                        break;
498
311748
                    }
499
                }
500

            
501
                // If an existing mapping wasn't
502
                // found, add it
503
144956
                if !found {
504
144186
                    view_entry.mappings.push(entry_mapping);
505
144186
                }
506
            }
507

            
508
            // There was a choice to be made here of whether to call
509
            // reduce()  with all of the existing values, or call it with
510
            // rereduce=true passing only the new value and the old stored
511
            // value. In this implementation, it's technically less
512
            // efficient, but we can guarantee that every value has only
513
            // been reduced once, and potentially re-reduced a single-time.
514
            // If we constantly try to update the value to optimize the size
515
            // of `mappings`, the fear is that the value computed may lose
516
            // precision in some contexts over time. Thus, the decision was
517
            // made to always call reduce() with all the mappings within a
518
            // single ViewEntry.
519
106786
            if self.has_reduce {
520
106534
                let mappings = view_entry
521
106534
                    .mappings
522
106534
                    .iter()
523
229552
                    .map(|m| (key.as_slice(), m.value.as_slice()))
524
106534
                    .collect::<Vec<_>>();
525
106534

            
526
106534
                match self.view.reduce(&mappings, false) {
527
34988
                    Ok(reduced) => {
528
34988
                        view_entry.reduced_value = Bytes::from(reduced);
529
34988
                    }
530
71516
                    Err(view::Error::Core(bonsaidb_core::Error::ReduceUnimplemented)) => {
531
71516
                        self.has_reduce = false;
532
71516
                    }
533
                    Err(other) => {
534
                        self.result = Err(Error::from(other));
535
                        return KeyOperation::Skip;
536
                    }
537
                }
538
252
            }
539
372
        }
540

            
541
107128
        let value = bincode::serialize(&view_entry).unwrap();
542
107128
        KeyOperation::Set(ArcBytes::from(value))
543
123649
    }
544
}