You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: ldap.rs
    path of file: ./repos/kanidm/server/lib/src/idm
    
    the code of the file until where you have to start completion: //! LDAP specific operations handling components. This is where LDAP operations
//! are sent to for processing.

use std::collections::BTreeSet;
use std::iter;

use kanidm_proto::constants::*;
use kanidm_proto::internal::{ApiToken, UserAuthToken};
use ldap3_proto::simple::*;
use regex::Regex;
use std::net::IpAddr;
use tracing::trace;
use uuid::Uuid;

use crate::event::SearchEvent;
use crate::idm::event::{LdapAuthEvent, LdapTokenAuthEvent};
use crate::idm::server::{IdmServer, IdmServerTransaction};
use crate::prelude::*;

// Clippy doesn't like Bind here. But proto needs unboxed ldapmsg,
// and ldapboundtoken is moved. Really, it's not too bad, every message here is pretty sucky.
#[allow(clippy::large_enum_variant)]
pub enum LdapResponseState {
    Unbind,
    Disconnect(LdapMsg),
    Bind(LdapBoundToken, LdapMsg),
    Respond(LdapMsg),
    MultiPartResponse(Vec<LdapMsg>),
    BindMultiPartResponse(LdapBoundToken, Vec<LdapMsg>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LdapSession {
    // Maps through and provides anon read, but allows us to check the validity
    // of the account still.
    UnixBind(Uuid),
    UserAuthToken(UserAuthToken),
    ApiToken(ApiToken),
}

#[derive(Debug, Clone)]
pub struct LdapBoundToken {
    // Used to help ID the user doing the action, makes logging nicer.
    pub spn: String,
    pub session_id: Uuid,
    // This is the effective session permission. This is generated from either:
    // * A valid anonymous bind
    // * A valid unix pw bind
    // * A valid ApiToken
    // In a way, this is a stepping stone to an "ident" but allows us to check
    // the session is still "valid" depending on it's origin.
    pub effective_session: LdapSession,
}

pub struct LdapServer {
    rootdse: LdapSearchResultEntry,
    basedn: String,
    dnre: Regex,
    binddnre: Regex,
}

#[derive(Debug)]
enum LdapBindTarget {
    Account(Uuid),
    ApiToken,
}

impl LdapServer {
    pub async fn new(idms: &IdmServer) -> Result<Self, OperationError> {
        // let ct = duration_from_epoch_now();
        let mut idms_prox_read = idms.proxy_read().await;
        // This is the rootdse path.
        // get the domain_info item
        let domain_entry = idms_prox_read
            .qs_read
            .internal_search_uuid(UUID_DOMAIN_INFO)?;

        let basedn = domain_entry
            .get_ava_single_iutf8(Attribute::DomainLdapBasedn)
            .map(|s| s.to_string())
            .or_else(|| {
                domain_entry
                    .get_ava_single_iname(Attribute::DomainName)
                    .map(ldap_domain_to_dc)
            })
            .ok_or(OperationError::InvalidEntryState)?;

        let dnre = Regex::new(format!("^((?P<attr>[^=]+)=(?P<val>[^=]+),)?{basedn}$").as_str())
            .map_err(|_| OperationError::InvalidEntryState)?;

        let binddnre = Regex::new(format!("^(([^=,]+)=)?(?P<val>[^=,]+)(,{basedn})?$").as_str())
            .map_err(|_| OperationError::InvalidEntryState)?;

        let rootdse = LdapSearchResultEntry {
            dn: "".to_string(),
            attributes: vec![
                Ldap
    
    async fn test_ldap_sssd_compat(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");

        let acct_uuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");

        // Setup a user we want to check.
        {
            let e1 = entry_init!(
                (Attribute::Class, EntryClass::Person.to_value()),
                (Attribute::Class, EntryClass::Account.to_value()),
                (Attribute::Class, EntryClass::PosixAccount.to_value()),
                (Attribute::Name, Value::new_iname("testperson1")),
                (Attribute::Uuid, Value::Uuid(acct_uuid)),
                (Attribute::GidNumber, Value::Uint32(12345)),
                (Attribute::Description, Value::new_utf8s("testperson1")),
                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
            );

            let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await;
            assert!(server_txn
                .qs_write
                .internal_create(vec![e1])
                .and_then(|_| server_txn.commit())
                .is_ok());
        }

        // Setup the anonymous login.
        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
        assert!(anon_t.effective_session == LdapSession::UnixBind(UUID_ANONYMOUS));

        // SSSD tries to just search for silly attrs all the time. We ignore them.
        let sr = SearchRequest {
            msgid: 1,
            base: "dc=example,dc=com".to_string(),
            scope: LdapSearchScope::Subtree,
            filter: LdapFilter::And(vec![
                LdapFilter::Equality(Attribute::Class.to_string(), "sudohost".to_string()),
                LdapFilter::Substring(
                    Attribute::SudoHost.to_string(),
                    LdapSubstringFilter {
                        initial: Some("a".to_string()),
                        any: vec!["x".to_string()],
                        final_: Some("z".to_string()),
                    },
                ),
            ]),
            attrs: vec![
                "*".to_string(),
                // Already being returned
                LDAP_ATTR_NAME.to_string(),
                // This is a virtual attribute
                Attribute::EntryUuid.to_string(),
            ],
        };
        let r1 = ldaps
            .do_search(idms, &sr, &anon_t, Source::Internal)
            .await
            .unwrap();

        // Empty results and ldap proto success msg.
        assert!(r1.len() == 1);

        // Second search

        let sr = SearchRequest {
            msgid: 1,
            base: "dc=example,dc=com".to_string(),
            scope: LdapSearchScope::Subtree,
            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
            attrs: vec![
                "uid".to_string(),
                "uidNumber".to_string(),
                "gidNumber".to_string(),
                "gecos".to_string(),
                "cn".to_string(),
                "entryuuid".to_string(),
            ],
        };
        let r1 = ldaps
            .do_search(idms, &sr, &anon_t, Source::Internal)
            .await
            .unwrap();

        trace!(?r1);

        // The result, and the ldap proto success msg.
        assert!(r1.len() == 2);
        match &r1[0].op {
            LdapOp::SearchResultEntry(lsre) => {
                assert_entry_contains!(
                    lsre,
                    "spn=testperson1@example.com,dc=example,dc=com",
                    (Attribute::Uid, "testperson1"),
                    (Attribute::Cn, "testperson1"),
                    (Attribute::Gecos, "testperson1"),
                    (Attribute::UidNumber, "12345"),
                    (Attribute::GidNumber, "12345"),
                    (
                        Attribute::EntryUuid.as_ref(),
                        "cc8e95b4-c24f-4d68-ba54-8bed76f63930"
                    )
                );
            }
            _ => assert!(false),
        };
    }