KBEngine源碼閱讀筆記(注冊)

KBEngine與Unreal
1.客戶端 KbEngine 中

void KBEngineApp::installEvents()
{
    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("login", "login", [this](const UKBEventData* pEventData)
    {
        const UKBEventData_login& data = static_cast<const UKBEventData_login&>(*pEventData);
        login(data.username, data.password, data.datas);
    });

    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("logout", "logout", [this](const UKBEventData* pEventData)
    {
        logout();
    });

    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("createAccount", "createAccount", [this](const UKBEventData* pEventData)
    {
        const UKBEventData_createAccount& data = static_cast<const UKBEventData_createAccount&>(*pEventData);
        createAccount(data.username, data.password, data.datas);
    });

    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("reloginBaseapp", "reloginBaseapp", [this](const UKBEventData* pEventData)
    {
        reloginBaseapp();
    });

    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("resetPassword", "resetPassword", [this](const UKBEventData* pEventData)
    {
        const UKBEventData_resetPassword& data = static_cast<const UKBEventData_resetPassword&>(*pEventData);
        resetPassword(data.username);
    });

    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("bindAccountEmail", "bindAccountEmail", [this](const UKBEventData* pEventData)
    {
        const UKBEventData_bindAccountEmail& data = static_cast<const UKBEventData_bindAccountEmail&>(*pEventData);
        bindAccountEmail(data.email);
    });

    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("newPassword", "newPassword", [this](const UKBEventData* pEventData)
    {
        const UKBEventData_newPassword& data = static_cast<const UKBEventData_newPassword&>(*pEventData);
        newPassword(data.old_password, data.new_password);
    });

    // 內(nèi)部事件
    KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC("_closeNetwork", "_closeNetwork", [this](const UKBEventData* pEventData)
    {
        _closeNetwork();
    });
}

注冊了一系列事件,本次從創(chuàng)建賬號開始
可以看到最終調(diào)用

void KBEngineApp::createAccount_loginapp(bool noconnect)
{
    if (noconnect)
    {
        reset();
        pNetworkInterface_->connectTo(pArgs_->ip, pArgs_->port, this, 1);
    }
    else
    {
        INFO_MSG("KBEngineApp::createAccount_loginapp(): send create! username=%s", *username_);
        Bundle* pBundle = Bundle::createObject();
        pBundle->newMessage(Messages::messages[TEXT("Loginapp_reqCreateAccount"]));
        (*pBundle) << username_;
        (*pBundle) << password_;
        pBundle->appendBlob(clientdatas_);
        pBundle->send(pNetworkInterface_);
    }
}

調(diào)用登錄服務(wù)器中的 reqCreateAccount 方法。
登錄服務(wù)器:最終將數(shù)據(jù)發(fā)送至dbmsr

bool Loginapp::_createAccount(Network::Channel* pChannel, std::string& accountName, 
                                 std::string& password, std::string& datas, ACCOUNT_TYPE type)
{
    AUTO_SCOPED_PROFILE("createAccount");

    ACCOUNT_TYPE oldType = type;

    if(!g_kbeSrvConfig.getDBMgr().account_registration_enable)
    {
        ERROR_MSG(fmt::format("Loginapp::_createAccount({}): not available! modify kbengine[_defs].xml->dbmgr->account_registration.\n",
            accountName));

        std::string retdatas = "";
        Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
        (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
        SERVER_ERROR_CODE retcode = SERVER_ERR_ACCOUNT_REGISTER_NOT_AVAILABLE;
        (*pBundle) << retcode;
        (*pBundle).appendBlob(retdatas);
        pChannel->send(pBundle);
        return false;
    }

    accountName = KBEngine::strutil::kbe_trim(accountName);
    password = KBEngine::strutil::kbe_trim(password);

    if(accountName.size() > ACCOUNT_NAME_MAX_LENGTH)
    {
        ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName too big, size={}, limit={}.\n",
            accountName.size(), ACCOUNT_NAME_MAX_LENGTH));

        return false;
    }

    if(password.size() > ACCOUNT_PASSWD_MAX_LENGTH)
    {
        ERROR_MSG(fmt::format("Loginapp::_createAccount: password too big, size={}, limit={}.\n",
            password.size(), ACCOUNT_PASSWD_MAX_LENGTH));

        return false;
    }

    if(datas.size() > ACCOUNT_DATA_MAX_LENGTH)
    {
        ERROR_MSG(fmt::format("Loginapp::_createAccount: bindatas too big, size={}, limit={}.\n",
            datas.size(), ACCOUNT_DATA_MAX_LENGTH));

        return false;
    }
    
    std::string retdatas = "";
    if(shuttingdown_ != SHUTDOWN_STATE_STOP)
    {
        WARNING_MSG(fmt::format("Loginapp::_createAccount: shutting down, create {} failed!\n", accountName));

        Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
        (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
        SERVER_ERROR_CODE retcode = SERVER_ERR_IN_SHUTTINGDOWN;
        (*pBundle) << retcode;
        (*pBundle).appendBlob(retdatas);
        pChannel->send(pBundle);
        return false;
    }

    PendingLoginMgr::PLInfos* ptinfos = pendingCreateMgr_.find(const_cast<std::string&>(accountName));
    if(ptinfos != NULL)
    {
        WARNING_MSG(fmt::format("Loginapp::_createAccount: pendingCreateMgr has {}, request create failed!\n", 
            accountName));

        Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
        (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
        SERVER_ERROR_CODE retcode = SERVER_ERR_BUSY;
        (*pBundle) << retcode;
        (*pBundle).appendBlob(retdatas);
        pChannel->send(pBundle);
        return false;
    }
    
    {
        // 把請求交由腳本處理
        SERVER_ERROR_CODE retcode = SERVER_SUCCESS;
        SCOPED_PROFILE(SCRIPTCALL_PROFILE);

        PyObject* pyResult = PyObject_CallMethod(getEntryScript().get(), 
                                            const_cast<char*>("onRequestCreateAccount"), 
                                            const_cast<char*>("ssy#"), 
                                            accountName.c_str(),
                                            password.c_str(),
                                            datas.c_str(), datas.length());

        if(pyResult != NULL)
        {
            if(PySequence_Check(pyResult) && PySequence_Size(pyResult) == 4)
            {
                char* sname;
                char* spassword;
                char *extraDatas;
                Py_ssize_t extraDatas_size = 0;
                
                if(PyArg_ParseTuple(pyResult, "H|s|s|y#",  &retcode, &sname, &spassword, &extraDatas, &extraDatas_size) == -1)
                {
                    ERROR_MSG(fmt::format("Loginapp::_createAccount: {}.onRequestLogin, Return value error! accountName={}\n", 
                        g_kbeSrvConfig.getLoginApp().entryScriptFile, accountName));

                    retcode = SERVER_ERR_OP_FAILED;
                }
                else
                {
                    accountName = sname;
                    password = spassword;

                    if (extraDatas && extraDatas_size > 0)
                        datas.assign(extraDatas, extraDatas_size);
                    else
                        SCRIPT_ERROR_CHECK();
                }
            }
            else
            {
                ERROR_MSG(fmt::format("Loginapp::_createAccount: {}.onRequestLogin, Return value error, must be errorcode or tuple! accountName={}\n", 
                    g_kbeSrvConfig.getLoginApp().entryScriptFile, accountName));

                retcode = SERVER_ERR_OP_FAILED;
            }
            
            Py_DECREF(pyResult);
        }
        else
        {
            SCRIPT_ERROR_CHECK();
            retcode = SERVER_ERR_OP_FAILED;
        }
            
        if(retcode != SERVER_SUCCESS)
        {
            Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
            (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
            (*pBundle) << retcode;
            (*pBundle).appendBlob(retdatas);
            pChannel->send(pBundle);
            return false;
        }
        else
        {
            if(accountName.size() == 0)
            {
                ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName is empty!\n"));

                retcode = SERVER_ERR_NAME;
                Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
                (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
                (*pBundle) << retcode;
                (*pBundle).appendBlob(retdatas);
                pChannel->send(pBundle);
                return false;
            }
        }
    }

    if(type == ACCOUNT_TYPE_SMART)
    {
        if (email_isvalid(accountName.c_str()))
        {
            type = ACCOUNT_TYPE_MAIL;
        }
        else
        {
            if(!validName(accountName))
            {
                ERROR_MSG(fmt::format("Loginapp::_createAccount: invalid accountName({})\n",
                    accountName));

                Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
                (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
                SERVER_ERROR_CODE retcode = SERVER_ERR_NAME;
                (*pBundle) << retcode;
                (*pBundle).appendBlob(retdatas);
                pChannel->send(pBundle);
                return false;
            }

            type = ACCOUNT_TYPE_NORMAL;
        }
    }
    else if(type == ACCOUNT_TYPE_NORMAL)
    {
        if(!validName(accountName))
        {
            ERROR_MSG(fmt::format("Loginapp::_createAccount: invalid accountName({})\n",
                accountName));

            Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
            (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
            SERVER_ERROR_CODE retcode = SERVER_ERR_NAME;
            (*pBundle) << retcode;
            (*pBundle).appendBlob(retdatas);
            pChannel->send(pBundle);
            return false;
        }
    }
    else if (!email_isvalid(accountName.c_str()))
    {
        /*
        std::string user_name, domain_name;
        user_name = regex_replace(accountName, _g_mail_pattern, std::string("$1") );
        domain_name = regex_replace(accountName, _g_mail_pattern, std::string("$2") );
        */
        WARNING_MSG(fmt::format("Loginapp::_createAccount: invalid email={}\n", 
            accountName));

        Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
        (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
        SERVER_ERROR_CODE retcode = SERVER_ERR_NAME_MAIL;
        (*pBundle) << retcode;
        (*pBundle).appendBlob(retdatas);
        pChannel->send(pBundle);
        return false;
    }

    DEBUG_MSG(fmt::format("Loginapp::_createAccount: accountName={}, passwordsize={}, type={}, oldType={}.\n",
        accountName.c_str(), password.size(), type, oldType));

    ptinfos = new PendingLoginMgr::PLInfos;
    ptinfos->accountName = accountName;
    ptinfos->password = password;
    ptinfos->datas = datas;
    ptinfos->addr = pChannel->addr();
    pendingCreateMgr_.add(ptinfos);

    Components::COMPONENTS& cts = Components::getSingleton().getComponents(DBMGR_TYPE);
    Components::ComponentInfos* dbmgrinfos = NULL;

    if(cts.size() > 0)
        dbmgrinfos = &(*cts.begin());

    if(dbmgrinfos == NULL || dbmgrinfos->pChannel == NULL || dbmgrinfos->cid == 0)
    {
        ERROR_MSG(fmt::format("Loginapp::_createAccount: create({}), not found dbmgr!\n", 
            accountName));

        Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
        (*pBundle).newMessage(ClientInterface::onCreateAccountResult);
        SERVER_ERROR_CODE retcode = SERVER_ERR_SRV_NO_READY;
        (*pBundle) << retcode;
        (*pBundle).appendBlob(retdatas);
        pChannel->send(pBundle);
        return false;
    }

    pChannel->extra(accountName);

    Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
    (*pBundle).newMessage(DbmgrInterface::reqCreateAccount);
    uint8 uatype = uint8(type);
    (*pBundle) << accountName << password << uatype;
    (*pBundle).appendBlob(datas);
    dbmgrinfos->pChannel->send(pBundle);
    printf("**********_reqCreateAccount step 2 **********");
    return true;
}

dbmgr 服務(wù)器 注冊賬號信息經(jīng)過一系列的驗(yàn)證將消息壓如隊(duì)列。

最終 DBTaskCreateAccount 這個類里面,最重要的函數(shù)是 db_thread_process,是子類真正做的事情。
這個類里,presentMainThread這個函數(shù),是持久化執(zhí)行完的回調(diào)調(diào)用,在這里持久化結(jié)束以后調(diào)用的函數(shù)就是onReqCreateAccountResult

bool DBTaskCreateAccount::db_thread_process()
{
    ACCOUNT_INFOS info;
    success_ = DBTaskCreateAccount::writeAccount(pdbi_, accountName_, password_, postdatas_, info) && info.dbid > 0;
    return false;
}

//-------------------------------------------------------------------------------------
bool DBTaskCreateAccount::writeAccount(DBInterface* pdbi, const std::string& accountName, 
                                       const std::string& passwd, const std::string& datas, ACCOUNT_INFOS& info)
{
    info.dbid = 0;
    if(accountName.size() == 0)
    {
        return false;
    }

    // 尋找dblog是否有此賬號, 如果有則創(chuàng)建失敗
    // 如果沒有則向account表新建一個entity數(shù)據(jù)同時在accountlog表寫入一個log關(guān)聯(lián)dbid
    EntityTables& entityTables = EntityTables::findByInterfaceName(pdbi->name());
    KBEAccountTable* pTable = static_cast<KBEAccountTable*>(entityTables.findKBETable(KBE_TABLE_PERFIX "_accountinfos"));
    KBE_ASSERT(pTable);

    ScriptDefModule* pModule = EntityDef::findScriptModule(DBUtil::accountScriptName());
    if(pModule == NULL)
    {
        ERROR_MSG(fmt::format("DBTaskCreateAccount::writeAccount(): not found account script[{}], create[{}] error!\n", 
            DBUtil::accountScriptName(), accountName));

        return false;
    }

    if(pTable->queryAccount(pdbi, accountName, info) && (info.flags & ACCOUNT_FLAG_NOT_ACTIVATED) <= 0)
    {
        if(pdbi->getlasterror() > 0)
        {
            WARNING_MSG(fmt::format("DBTaskCreateAccount::writeAccount({}): queryAccount error: {}\n", 
                accountName, pdbi->getstrerror()));
        }

        return false;
    }

    bool hasset = (info.dbid != 0);
    if(!hasset)
    {
        info.flags = g_kbeSrvConfig.getDBMgr().accountDefaultFlags;
        info.deadline = g_kbeSrvConfig.getDBMgr().accountDefaultDeadline;
    }

    DBID entityDBID = info.dbid;
    
    if(entityDBID == 0)
    {
        // 防止多線程問題, 這里做一個拷貝。
        MemoryStream copyAccountDefMemoryStream(pTable->accountDefMemoryStream());

        entityDBID = EntityTables::findByInterfaceName(pdbi->name()).writeEntity(pdbi, 0, -1,
                &copyAccountDefMemoryStream, pModule);

        if (entityDBID <= 0)
        {
            WARNING_MSG(fmt::format("DBTaskCreateAccount::writeAccount({}): writeEntity error: {}\n",
                accountName, pdbi->getstrerror()));

            return false;
        }
    }

    info.name = accountName;
    info.email = accountName + "@0.0";
    info.password = passwd;
    info.dbid = entityDBID;
    info.datas = datas;
    
    if(!hasset)
    {
        if(!pTable->logAccount(pdbi, info))
        {
            if(pdbi->getlasterror() > 0)
            {
                WARNING_MSG(fmt::format("DBTaskCreateAccount::writeAccount(): logAccount error:{}\n", 
                    pdbi->getstrerror()));
            }

            return false;
        }
    }
    else
    {
        if(!pTable->setFlagsDeadline(pdbi, accountName, info.flags & ~ACCOUNT_FLAG_NOT_ACTIVATED, info.deadline))
        {
            if(pdbi->getlasterror() > 0)
            {
                WARNING_MSG(fmt::format("DBTaskCreateAccount::writeAccount(): logAccount error:{}\n", 
                    pdbi->getstrerror()));
            }

            return false;
        }
    }

    return true;
}

//-------------------------------------------------------------------------------------
thread::TPTask::TPTaskState DBTaskCreateAccount::presentMainThread()
{
    DEBUG_MSG(fmt::format("Dbmgr::reqCreateAccount: {}, success={}.\n", registerName_.c_str(), success_));

    Network::Bundle* pBundle = Network::Bundle::createPoolObject(OBJECTPOOL_POINT);
    (*pBundle).newMessage(LoginappInterface::onReqCreateAccountResult);
    SERVER_ERROR_CODE failedcode = SERVER_SUCCESS;

    if(!success_)
        failedcode = SERVER_ERR_ACCOUNT_CREATE_FAILED;

    (*pBundle) << failedcode << registerName_ << password_;
    (*pBundle).appendBlob(getdatas_);

    if(!this->send(pBundle))
    {
        ERROR_MSG(fmt::format("DBTaskCreateAccount::presentMainThread: channel({}) not found.\n", addr_.c_str()));
        Network::Bundle::reclaimPoolObject(pBundle);
    }

    return thread::TPTask::TPTASK_STATE_COMPLETED;
}

可以看到最終調(diào)用 loginapp 中LoginappInterface::onReqCreateAccountResult 將數(shù)據(jù)發(fā)送至客戶端

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,661評論 19 139
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,675評論 1 32
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時...
    歐辰_OSR閱讀 30,265評論 8 265
  • 我怕死,怕的不是生命終結(jié),怕的不是意外發(fā)生。我怕的死,是靈魂的安息,是另一個我的死去。 怕的事很多,怕蟑螂,怕人潮...
    周周周的個人秀閱讀 383評論 1 1
  • spring 容器就是一個工廠,而bean 是工廠里的每一個產(chǎn)品,而這個工廠生產(chǎn)什么樣的產(chǎn)品,是依賴于配置文件的聲...
    David_jim閱讀 491評論 0 3

友情鏈接更多精彩內(nèi)容