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);
    });

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

注册了一系列事件,本次从创建账号开始
可以看到最终调用

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_);
    }
}

调用登录服务器中的 reqCreateAccount 方法。
登录服务器:最终将数据发送至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 服务器 注册账号信息经过一系列的验证将消息压如队列。

最终 DBTaskCreateAccount 这个类里面,最重要的函数是 db_thread_process,是子类真正做的事情。
这个类里,presentMainThread这个函数,是持久化执行完的回调调用,在这里持久化结束以后调用的函数就是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是否有此账号, 如果有则创建失败
    // 如果没有则向account表新建一个entity数据同时在accountlog表写入一个log关联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;
}

可以看到最终调用 loginapp 中LoginappInterface::onReqCreateAccountResult 将数据发送至客户端

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,176评论 5 469
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,190评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,232评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,953评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,879评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,177评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,626评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,295评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,436评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,365评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,414评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,096评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,685评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,771评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,987评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,438评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,032评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,076评论 1 32
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,279评论 8 265
  • 我怕死,怕的不是生命终结,怕的不是意外发生。我怕的死,是灵魂的安息,是另一个我的死去。 怕的事很多,怕蟑螂,怕人潮...
    周周周的个人秀阅读 305评论 1 1
  • spring 容器就是一个工厂,而bean 是工厂里的每一个产品,而这个工厂生产什么样的产品,是依赖于配置文件的声...
    David_jim阅读 433评论 0 3