Skip to main content

kanidmd_lib/repl/
consumer.rs

1use super::proto::*;
2use crate::{
3    plugins::Plugins,
4    prelude::*,
5    server::{ChangeFlag, ServerPhase},
6};
7use std::{
8    collections::{BTreeMap, BTreeSet},
9    sync::Arc,
10};
11
12impl QueryServerWriteTransaction<'_> {
13    // Apply the state changes if they are valid.
14
15    fn consumer_incremental_apply_entries(
16        &mut self,
17        ctx_entries: Vec<ReplIncrementalEntryV1>,
18    ) -> Result<bool, OperationError> {
19        // trace!(?ctx_entries);
20
21        // No action needed for this if the entries are empty.
22        if ctx_entries.is_empty() {
23            debug!("No entries to act upon");
24            return Ok(false);
25        }
26
27        /*
28         *  Incremental is very similar to modify in how we have to treat the entries
29         *  with a pre and post state. However we need an incremental prepare so that
30         *  when new entries are provided to us we can merge to a stub and then commit
31         *  it correctly. This takes an extra backend interface that prepares the
32         *  entry stubs for us.
33         */
34
35        // I think we need to rehydrate all the repl content to a partial
36        // entry. This way all the types are consistent and ready.
37        let ctx_entries: Vec<_> = ctx_entries.into_iter().map(
38            EntryIncrementalNew::rehydrate
39        )
40        .collect::<Result<Vec<_>, _>>()
41        .inspect_err(|err| {
42            error!(?err, "Unable to process replication incremental entries to valid entry states for replication");
43        })?;
44
45        trace!(?ctx_entries);
46
47        let db_entries = self
48            .be_txn
49            .incremental_prepare(&ctx_entries)
50            .inspect_err(|err| {
51                error!(?err, "Failed to access entries from db");
52            })?;
53
54        trace!(?db_entries);
55
56        // Need to probably handle conflicts here in this phase. I think they
57        // need to be pushed to a separate list where they are then "created"
58        // as a conflict.
59
60        // First find if entries are in a conflict state. Remember, these conflicts are purely
61        // UUID creation conflicts at this phase in the process.
62
63        let (conflicts, proceed): (Vec<_>, Vec<_>) = ctx_entries
64            .iter()
65            .zip(db_entries)
66            .partition(|(ctx_ent, db_ent)| ctx_ent.is_add_conflict(db_ent.as_ref()));
67
68        debug!(conflicts = %conflicts.len(), proceed = %proceed.len());
69
70        // Now we have a set of conflicts and a set of entries to proceed.
71        //
72        //    /- entries that need to be created as conflicts.
73        //    |                /- entries that survive and need update to the db in place.
74        //    v                v
75        let (conflict_create, conflict_update): (
76            Vec<Option<EntrySealedNew>>,
77            Vec<(EntryIncrementalCommitted, Arc<EntrySealedCommitted>)>,
78        ) = conflicts
79            .into_iter()
80            .map(
81                |(ctx_ent, db_ent): (&EntryIncrementalNew, Arc<EntrySealedCommitted>)| {
82                    let (opt_create, ent) =
83                        ctx_ent.resolve_add_conflict(self.get_cid(), db_ent.as_ref());
84                    (opt_create, (ent, db_ent))
85                },
86            )
87            .unzip();
88
89        // ⚠️  If we end up with plugins triggering other entries to conflicts, we DON'T need to
90        // add them to this list. This is just for uuid conflicts, not higher level ones!
91        //
92        // ⚠️  We need to collect this from conflict_update since we may NOT be the originator
93        // server for some conflicts, but we still need to know the UUID is IN the conflict
94        // state for plugins. We also need to do this here before the conflict_update
95        // set is consumed by later steps.
96        //
97        // ⚠️  When we upgrade between two nodes, migrations will often create *new* system
98        // entries on both nodes. Until both nodes upgrade they can't replicate. This creates
99        // a situation where both nodes have identical entry content for system entries, but
100        // the entries that were created now are conflicts. Normally this is okay, because the
101        // first node to upgrade will have it's entries persisted, and the other nodes duplicate
102        // entries will be removed. However, just through the nature of being in the conflict
103        // state, these entries are then added to the conflict_uuid set. This conflict_uuid set
104        // is used by referential integrity to remove uuids from references so that group
105        // memberships don't accidentally leak to recipients that were not intended.
106        //
107        // To avoid this, we remove any system entries from this conflict set, so that they are
108        // exempt from this conflict handling which allows upgrades to work.
109        let mut conflict_uuids: BTreeSet<_> = conflict_update
110            .iter()
111            .filter_map(|(_, e)| {
112                let u = e.get_uuid();
113                if u >= DYNAMIC_RANGE_MINIMUM_UUID {
114                    // It is a user created node, process the conflict within plugins
115                    Some(u)
116                } else {
117                    // It is in a system range, do not process this entry
118                    None
119                }
120            })
121            .collect();
122
123        // Filter out None from conflict_create
124        let conflict_create: Vec<EntrySealedNew> = conflict_create.into_iter().flatten().collect();
125
126        let proceed_update: Vec<(EntryIncrementalCommitted, Arc<EntrySealedCommitted>)> = proceed
127            .into_iter()
128            .map(|(ctx_ent, db_ent)| {
129                // This now is the set of entries that are able to be updated. Merge
130                // their attribute sets/states per the change state rules.
131
132                // This must create an EntryInvalidCommitted
133                let merge_ent = ctx_ent.merge_state(db_ent.as_ref(), &self.schema, self.trim_cid());
134                (merge_ent, db_ent)
135            })
136            .collect();
137
138        // We now merge the conflict updates and the updates that can proceed. This is correct
139        // since if an entry was conflicting by uuid then there is nothing for it to merge with
140        // so as a result we can just by pass that step. We now have all_updates which is
141        // the set of live entries to write back.
142        let mut all_updates = conflict_update
143            .into_iter()
144            .chain(proceed_update)
145            .collect::<Vec<_>>();
146
147        // ⚠️  This hook is probably not what you want to use for checking entries are consistent.
148        //
149        // The main issue is that at this point we have a set of entries that need to be
150        // created / marked into conflicts, and until that occurs it's hard to proceed with validations
151        // like attr unique because then we would need to walk the various sets to find cases where
152        // an attribute may not be unique "currently" but *would* be unique once the various entries
153        // have then been conflicted and updated.
154        //
155        // Instead we treat this like refint - we allow the database to "temporarily" become
156        // inconsistent, then we fix it immediately. This hook remains for cases in future
157        // where we may wish to have session cleanup performed for example.
158        Plugins::run_pre_repl_incremental(self, all_updates.as_mut_slice()).map_err(|e| {
159            admin_error!("Operation failed (pre_repl_incremental plugin), {:?}", e);
160            e
161        })?;
162
163        // Now we have to schema check our entries. Remember, here because this is
164        // using into_iter it's possible that entries may be conflicted due to becoming
165        // schema invalid during the merge process.
166        let all_updates_valid = all_updates
167            .into_iter()
168            .map(|(ctx_ent, db_ent)| {
169                // Check the schema
170                //
171                // In these cases when an entry fails schema, we mark it to
172                // a conflict state and then retain it in the update process.
173                //
174                // The marking is done INSIDE this function!
175                let sealed_ent = ctx_ent.validate_repl(&self.schema).seal(&self.schema);
176                (sealed_ent, db_ent)
177            })
178            .collect::<Vec<_>>();
179
180        // We now have two sets!
181        //
182        // * conflict_create - entries to be created that are conflicted via add statements (duplicate uuid)
183        //                     these are only created on the entry origin node!
184        // * all_updates_valid - this has two types of entries
185        //   * entries that have survived a uuid conflict and need inplace write. Unlikely to become invalid.
186        //   * entries that were merged and are schema valid.
187        //   * entries that were merged and their attribute state has now become invalid and are conflicts.
188        //
189        // incremental_apply here handles both the creations and the update processes to ensure that
190        // everything is updated in a single consistent operation.
191        self.be_txn
192            .incremental_apply(&all_updates_valid, conflict_create)
193            .map_err(|e| {
194                admin_error!("betxn create failure {:?}", e);
195                e
196            })?;
197
198        Plugins::run_post_repl_incremental_conflict(
199            self,
200            all_updates_valid.as_slice(),
201            &mut conflict_uuids,
202        )
203        .map_err(|e| {
204            error!(
205                "Operation failed (post_repl_incremental_conflict plugin), {:?}",
206                e
207            );
208            e
209        })?;
210
211        // Plugins need these unzipped
212        //
213        let (cand, pre_cand): (Vec<_>, Vec<_>) = all_updates_valid
214            .into_iter()
215            // We previously excluded this to avoid doing unnecessary work on entries that
216            // were moving to a conflict state, and the survivor was staying "as is" on this
217            // node. However, this gets messy with dyngroups and memberof, where on a conflict
218            // the memberships are deleted across the replication boundary. In these cases
219            // we need dyngroups to see the valid entries, even if they are "identical to before"
220            // to re-assert all their memberships are valid.
221            /*
222            .filter(|(cand, _)| {
223                // Exclude anything that is conflicted as a result of the conflict plugins.
224                !conflict_uuids.contains(&cand.get_uuid())
225            })
226            */
227            .unzip();
228
229        // We don't need to process conflict_creates here, since they are all conflicting
230        // uuids which means that the conflict_uuids are all *here* so they will trigger anything
231        // that requires processing anyway. As well conflict_creates may not be the full
232        // set of conflict entries as we may not be the origin node! Conflict_creates is always
233        // a subset of the conflicts.
234        Plugins::run_post_repl_incremental(
235            self,
236            pre_cand.as_slice(),
237            cand.as_slice(),
238            &conflict_uuids,
239        )
240        .map_err(|e| {
241            error!("Operation failed (post_repl_incremental plugin), {:?}", e);
242            e
243        })?;
244
245        self.changed_uuid.extend(cand.iter().map(|e| e.get_uuid()));
246
247        if !self.changed_flags.contains(ChangeFlag::ACP)
248            && cand
249                .iter()
250                .chain(pre_cand.iter().map(|e| e.as_ref()))
251                .any(|e| {
252                    e.attribute_equality(Attribute::Class, &EntryClass::AccessControlProfile.into())
253                })
254        {
255            self.changed_flags.insert(ChangeFlag::ACP)
256        }
257
258        if !self.changed_flags.contains(ChangeFlag::OAUTH2)
259            && cand
260                .iter()
261                .chain(pre_cand.iter().map(|e| e.as_ref()))
262                .any(|e| {
263                    e.attribute_equality(Attribute::Class, &EntryClass::OAuth2ResourceServer.into())
264                })
265        {
266            self.changed_flags.insert(ChangeFlag::OAUTH2)
267        }
268
269        if !self.changed_flags.contains(ChangeFlag::OAUTH2_CLIENT)
270            && cand
271                .iter()
272                .chain(pre_cand.iter().map(|e| e.as_ref()))
273                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::OAuth2Client.into()))
274        {
275            self.changed_flags.insert(ChangeFlag::OAUTH2_CLIENT)
276        }
277
278        if !self.changed_flags.contains(ChangeFlag::FEATURE)
279            && cand
280                .iter()
281                .chain(pre_cand.iter().map(|e| e.as_ref()))
282                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Feature.into()))
283        {
284            self.changed_flags.insert(ChangeFlag::FEATURE)
285        }
286
287        if !self.changed_flags.contains(ChangeFlag::APPLICATION)
288            && cand
289                .iter()
290                .chain(pre_cand.iter().map(|e| e.as_ref()))
291                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Application.into()))
292        {
293            self.changed_flags.insert(ChangeFlag::APPLICATION)
294        }
295
296        if !self.changed_flags.contains(ChangeFlag::SYNC_AGREEMENT)
297            && cand
298                .iter()
299                .chain(pre_cand.iter().map(|e| e.as_ref()))
300                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::SyncAccount.into()))
301        {
302            self.changed_flags.insert(ChangeFlag::SYNC_AGREEMENT)
303        }
304
305        if !self.changed_flags.contains(ChangeFlag::KEY_MATERIAL)
306            && cand
307                .iter()
308                .chain(pre_cand.iter().map(|e| e.as_ref()))
309                .any(|e| {
310                    e.attribute_equality(Attribute::Class, &EntryClass::KeyProvider.into())
311                        || e.attribute_equality(Attribute::Class, &EntryClass::KeyObject.into())
312                })
313        {
314            self.changed_flags.insert(ChangeFlag::KEY_MATERIAL)
315        }
316
317        trace!(
318            changed = ?self.changed_flags.iter_names().collect::<Vec<_>>(),
319        );
320
321        Ok(true)
322    }
323
324    pub fn consumer_apply_changes(
325        &mut self,
326        ctx: ReplIncrementalContext,
327    ) -> Result<ConsumerState, OperationError> {
328        match ctx {
329            ReplIncrementalContext::DomainMismatch => {
330                error!("Unable to proceed with consumer incremental - the supplier has indicated that our domain_uuid's are not equivalent. This can occur when adding a new consumer to an existing topology.");
331                error!("This server's content must be refreshed to proceed. If you have configured automatic refresh, this will occur shortly.");
332                Ok(ConsumerState::RefreshRequired)
333            }
334            ReplIncrementalContext::NoChangesAvailable => {
335                debug!("no changes are available");
336                Ok(ConsumerState::Ok)
337            }
338            ReplIncrementalContext::RefreshRequired => {
339                error!("Unable to proceed with consumer incremental - the supplier has indicated that our RUV is outdated, and replication would introduce data corruption.");
340                error!("This server's content must be refreshed to proceed. If you have configured automatic refresh, this will occur shortly.");
341                Ok(ConsumerState::RefreshRequired)
342            }
343            ReplIncrementalContext::UnwillingToSupply => {
344                warn!("Unable to proceed with consumer incremental - the supplier has indicated that our RUV is ahead, and replication would introduce data corruption.");
345                error!("This supplier's content must be refreshed to proceed. If you have configured automatic refresh, this will occur shortly.");
346                Ok(ConsumerState::Ok)
347            }
348            ReplIncrementalContext::V1 {
349                domain_version,
350                domain_patch_level,
351                domain_uuid,
352                ranges,
353                schema_entries,
354                meta_entries,
355                entries,
356            } => self.consumer_apply_changes_v1(
357                domain_version,
358                domain_patch_level,
359                domain_uuid,
360                &ranges,
361                schema_entries,
362                meta_entries,
363                entries,
364            ),
365        }
366    }
367
368    #[instrument(level = "debug", skip_all)]
369    fn consumer_apply_changes_v1(
370        &mut self,
371        ctx_domain_version: DomainVersion,
372        ctx_domain_patch_level: u32,
373        ctx_domain_uuid: Uuid,
374        ctx_ranges: &BTreeMap<Uuid, ReplAnchoredCidRange>,
375        ctx_schema_entries: Vec<ReplIncrementalEntryV1>,
376        ctx_meta_entries: Vec<ReplIncrementalEntryV1>,
377        ctx_entries: Vec<ReplIncrementalEntryV1>,
378    ) -> Result<ConsumerState, OperationError> {
379        if ctx_domain_version < DOMAIN_MINIMUM_REPLICATION_LEVEL {
380            error!("Unable to proceed with consumer incremental - incoming domain level is lower than our minimum supported level. {} < {}", ctx_domain_version, DOMAIN_MINIMUM_REPLICATION_LEVEL);
381            return Err(OperationError::ReplDomainLevelUnsatisfiable);
382        } else if ctx_domain_version > DOMAIN_MAXIMUM_REPLICATION_LEVEL {
383            error!("Unable to proceed with consumer incremental - incoming domain level is greater than our maximum supported level. {} > {}", ctx_domain_version, DOMAIN_MAXIMUM_REPLICATION_LEVEL);
384            return Err(OperationError::ReplDomainLevelUnsatisfiable);
385        };
386
387        let domain_patch_level = if self.get_domain_development_taint() {
388            u32::MAX
389        } else {
390            self.get_domain_patch_level()
391        };
392
393        if ctx_domain_patch_level != domain_patch_level {
394            error!("Unable to proceed with consumer incremental - incoming domain patch level is not equal to our patch level. {} != {}", ctx_domain_patch_level, domain_patch_level);
395            return Err(OperationError::ReplDomainLevelUnsatisfiable);
396        };
397
398        // Assert that the d_uuid matches the repl domain uuid.
399        let db_uuid = self.be_txn.get_db_d_uuid()?;
400
401        if db_uuid != ctx_domain_uuid {
402            error!("Unable to proceed with consumer incremental - incoming domain uuid does not match our database uuid. You must investigate this situation. {:?} != {:?}", db_uuid, ctx_domain_uuid);
403            return Err(OperationError::ReplDomainUuidMismatch);
404        }
405
406        // Preflight checks of the incoming RUV to ensure it's in a good state.
407        let txn_cid = self.get_cid().clone();
408        let ruv = self.be_txn.get_ruv_write();
409
410        let change_count = ctx_schema_entries.len() + ctx_meta_entries.len() + ctx_entries.len();
411
412        ruv.incremental_preflight_validate_ruv(ctx_ranges, &txn_cid)
413            .inspect_err(|err| {
414                error!(
415                    ?err,
416                    "Incoming RUV failed preflight checks, unable to proceed."
417                );
418            })?;
419
420        // == ⚠️  Below this point we begin to make changes! ==
421        debug!(
422            "Proceeding to apply incremental with {change_count} changes from domain {ctx_domain_uuid:?} at level {ctx_domain_version}"
423        );
424
425        debug!(?ctx_ranges);
426
427        if ctx_domain_version < DOMAIN_LEVEL_1_11 {
428            // Schema is an in memory property attached to domain level from 1_11, and so the meta entries
429            // will trigger the schema to reload if required.
430            debug!("Applying {} schema entries", ctx_schema_entries.len());
431            // Apply the schema entries first.
432            let schema_changed = self
433                .consumer_incremental_apply_entries(ctx_schema_entries)
434                .inspect_err(|err| {
435                    error!(?err, "Failed to apply incremental schema entries");
436                })?;
437
438            if schema_changed {
439                // We need to reload schema now!
440                self.reload_schema().inspect_err(|err| {
441                    error!(?err, "Failed to reload schema");
442                })?;
443            }
444        } else {
445            self.reload_schema().inspect_err(|err| {
446                error!(?err, "Failed to reload schema");
447            })?;
448        }
449
450        debug!("Applying {} meta entries", ctx_meta_entries.len());
451        // Apply meta entries now.
452        let meta_changed = self
453            .consumer_incremental_apply_entries(ctx_meta_entries)
454            .inspect_err(|err| {
455                error!(?err, "Failed to apply incremental meta entries");
456            })?;
457
458        // This is re-loaded in case the domain name changed on the remote
459        if meta_changed {
460            self.reload_domain_info().inspect_err(|err| {
461                error!(?err, "Failed to reload domain info");
462            })?;
463            self.reload_system_config().inspect_err(|err| {
464                error!(?err, "Failed to reload system configuration");
465            })?;
466        }
467
468        debug!("Applying {} context entries", ctx_entries.len());
469        // Update all other entries now.
470        self.consumer_incremental_apply_entries(ctx_entries)
471            .inspect_err(|err| {
472                error!(?err, "Failed to apply incremental meta entries");
473            })?;
474
475        // Reload the domain version, doing any needed migrations.
476        //
477        // While it seems odd that we do the migrations after we receive the entries,
478        // this is because the supplier will already be sending us everything that
479        // was just migrated. As a result, we only need to apply the migrations to entries
480        // that were not on the supplier, and therefore need updates here.
481        if meta_changed {
482            self.reload_domain_info_version().inspect_err(|err| {
483                error!(?err, "Failed to reload domain info version");
484            })?;
485        }
486
487        // Finally, confirm that the ranges that we have added match the ranges from our
488        // context. Note that we get this in a writeable form!
489        let ruv = self.be_txn.get_ruv_write();
490
491        ruv.refresh_validate_ruv(ctx_ranges).inspect_err(|err| {
492            error!(?err, "RUV ranges were not rebuilt correctly.");
493        })?;
494
495        ruv.refresh_update_ruv(ctx_ranges).inspect_err(|err| {
496            error!(?err, "Unable to update RUV with supplier ranges.");
497        })?;
498
499        Ok(ConsumerState::Ok)
500    }
501
502    pub fn consumer_apply_refresh(
503        &mut self,
504        ctx: ReplRefreshContext,
505    ) -> Result<(), OperationError> {
506        match ctx {
507            ReplRefreshContext::V1 {
508                domain_version,
509                domain_devel,
510                domain_uuid,
511                ranges,
512                schema_entries,
513                meta_entries,
514                entries,
515            } => self.consumer_apply_refresh_v1(
516                domain_version,
517                domain_devel,
518                domain_uuid,
519                &ranges,
520                schema_entries,
521                meta_entries,
522                entries,
523            ),
524        }
525    }
526
527    fn consumer_refresh_create_entries(
528        &mut self,
529        ctx_entries: Vec<ReplEntryV1>,
530    ) -> Result<(), OperationError> {
531        let candidates = ctx_entries
532            .into_iter()
533            .map(EntryRefreshNew::from_repl_entry_v1)
534            .collect::<Result<Vec<EntryRefreshNew>, _>>()
535            .inspect_err(|err| {
536                error!(?err, "Failed to convert entries from supplier");
537            })?;
538
539        Plugins::run_pre_repl_refresh(self, candidates.as_slice()).map_err(|e| {
540            admin_error!(
541                "Refresh operation failed (pre_repl_refresh plugin), {:?}",
542                e
543            );
544            e
545        })?;
546
547        // No need to assign CID's since this is a repl import.
548        let norm_cand = candidates
549            .into_iter()
550            .map(|e| {
551                e.validate(&self.schema)
552                    .map_err(|e| {
553                        admin_error!("Schema Violation in refresh validate {:?}", e);
554                        OperationError::SchemaViolation(e)
555                    })
556                    .map(|e| {
557                        // Then seal the changes?
558                        e.seal(&self.schema)
559                    })
560            })
561            .collect::<Result<Vec<EntrySealedNew>, _>>()?;
562
563        let commit_cand = self.be_txn.refresh(norm_cand).map_err(|e| {
564            admin_error!("betxn create failure {:?}", e);
565            e
566        })?;
567
568        Plugins::run_post_repl_refresh(self, &commit_cand).map_err(|e| {
569            admin_error!(
570                "Refresh operation failed (post_repl_refresh plugin), {:?}",
571                e
572            );
573            e
574        })?;
575
576        self.changed_uuid
577            .extend(commit_cand.iter().map(|e| e.get_uuid()));
578
579        Ok(())
580    }
581
582    #[instrument(level = "info", skip_all)]
583    fn consumer_apply_refresh_v1(
584        &mut self,
585        ctx_domain_version: DomainVersion,
586        ctx_domain_devel: bool,
587        ctx_domain_uuid: Uuid,
588        ctx_ranges: &BTreeMap<Uuid, ReplAnchoredCidRange>,
589        ctx_schema_entries: Vec<ReplEntryV1>,
590        ctx_meta_entries: Vec<ReplEntryV1>,
591        ctx_entries: Vec<ReplEntryV1>,
592    ) -> Result<(), OperationError> {
593        // Can we apply the domain version validly?
594        // if domain_version >= min_support ...
595        let current_devel_flag = option_env!("KANIDM_PRE_RELEASE").is_some();
596
597        if ctx_domain_version < DOMAIN_MINIMUM_REPLICATION_LEVEL {
598            error!("Unable to proceed with consumer refresh - incoming domain level is lower than our minimum supported level. {} < {}", ctx_domain_version, DOMAIN_MINIMUM_REPLICATION_LEVEL);
599            return Err(OperationError::ReplDomainLevelUnsatisfiable);
600        } else if ctx_domain_version > DOMAIN_MAXIMUM_REPLICATION_LEVEL {
601            error!("Unable to proceed with consumer refresh - incoming domain level is greater than our maximum supported level. {} > {}", ctx_domain_version, DOMAIN_MAXIMUM_REPLICATION_LEVEL);
602            return Err(OperationError::ReplDomainLevelUnsatisfiable);
603        } else if ctx_domain_devel && !current_devel_flag {
604            error!("Unable to proceed with consumer refresh - incoming domain is from a development version while this server is a stable release.");
605            return Err(OperationError::ReplDomainLevelUnsatisfiable);
606        } else if !ctx_domain_devel && current_devel_flag {
607            error!("Unable to proceed with consumer refresh - incoming domain is from a stable version while this server is a development release.");
608            return Err(OperationError::ReplDomainLevelUnsatisfiable);
609        } else {
610            debug!(
611                "Proceeding to refresh from domain at level {}",
612                ctx_domain_version
613            );
614        };
615
616        // == ⚠️  Below this point we begin to make changes! ==
617        self.set_phase_bootstrap();
618
619        // Update the d_uuid. This is what defines us as being part of this repl topology!
620        self.be_txn
621            .set_db_d_uuid(ctx_domain_uuid)
622            .inspect_err(|err| {
623                error!(?err, "Failed to reset domain uuid");
624            })?;
625
626        // We need to reset our server uuid now. This is so that any other servers
627        // which had our former server_uuid in their RUV, is able to start to age it
628        // out and trim it.
629        self.reset_server_uuid()?;
630
631        // Delete all entries - *proper delete, not just tombstone!*
632        self.be_txn
633            .danger_delete_all_db_content()
634            .inspect_err(|err| {
635                error!(?err, "Failed to clear existing server database content");
636            })?;
637
638        // Reset this transactions schema to a completely clean slate.
639
640        // Schema is an in memory property attached to domain level from 1_11, and so we don't actually
641        // need to apply these meta entries.
642        if ctx_domain_version < DOMAIN_LEVEL_1_11 {
643            self.schema.generate_in_memory().inspect_err(|err| {
644                error!(?err, "Failed to reset in memory schema to clean state");
645            })?;
646
647            // Reindex now to force some basic indexes to exist
648            self.reindex(false).inspect_err(|err| {
649                error!(?err, "Failed to reload schema");
650            })?;
651
652            // Apply the schema entries first. This is the foundation that everything
653            // else will build upon!
654            self.consumer_refresh_create_entries(ctx_schema_entries)
655                .inspect_err(|err| {
656                    error!(?err, "Failed to refresh schema entries");
657                })?;
658        }
659
660        // We need to reload schema now! From 1.11 and above, this is what actually
661        // generates the in memory schema.
662        self.reload_schema().inspect_err(|err| {
663            error!(?err, "Failed to reload schema");
664        })?;
665
666        // Schema is now ready
667        self.set_phase(ServerPhase::SchemaReady);
668
669        // We have to reindex to force all the existing indexes to be dumped
670        // and recreated before we start to import.
671        self.reindex(false).inspect_err(|err| {
672            error!(?err, "Failed to reload schema");
673        })?;
674
675        // Apply the domain info entry / system info / system config entry?
676        self.consumer_refresh_create_entries(ctx_meta_entries)
677            .inspect_err(|err| {
678                error!(?err, "Failed to refresh meta entries");
679            })?;
680
681        // NOTE: The domain info we receive here will have the domain version populated!
682        // That's okay though, because all the incoming data is already at the right
683        // version!
684        self.reload_domain_info().inspect_err(|err| {
685            error!(?err, "Failed to reload domain info");
686        })?;
687
688        // Mark that everything changed so that post commit hooks function as expected.
689        self.changed_flags.insert(
690            ChangeFlag::SCHEMA
691                | ChangeFlag::ACP
692                | ChangeFlag::OAUTH2
693                | ChangeFlag::OAUTH2_CLIENT
694                | ChangeFlag::FEATURE
695                | ChangeFlag::DOMAIN
696                | ChangeFlag::APPLICATION
697                | ChangeFlag::SYSTEM_CONFIG
698                | ChangeFlag::SYNC_AGREEMENT
699                | ChangeFlag::KEY_MATERIAL,
700        );
701
702        // Domain info is now ready.
703        self.set_phase(ServerPhase::DomainInfoReady);
704
705        // ==== That's it! We are GOOD to go! ====
706
707        // Create all the entries. Note we don't hit plugins here beside post repl plugs.
708        self.consumer_refresh_create_entries(ctx_entries)
709            .inspect_err(|err| {
710                error!(?err, "Failed to refresh main db entries");
711            })?;
712
713        // Finally, confirm that the ranges that we have recreated match the ranges from our
714        // context. Note that we get this in a writeable form!
715        let ruv = self.be_txn.get_ruv_write();
716
717        ruv.refresh_validate_ruv(ctx_ranges).inspect_err(|err| {
718            error!(?err, "RUV ranges were not rebuilt correctly.");
719        })?;
720
721        ruv.refresh_update_ruv(ctx_ranges).inspect_err(|err| {
722            error!(?err, "Unable to update RUV with supplier ranges.");
723        })?;
724
725        // Refresh complete
726        self.set_phase(ServerPhase::Running);
727
728        Ok(())
729    }
730}