pq_impl.cpp 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977
  1. #include "pq_impl.h"
  2. #include "event_helpers.h"
  3. #include "partition_log.h"
  4. #include "partition.h"
  5. #include "read.h"
  6. #include <ydb/core/base/tx_processing.h>
  7. #include <ydb/core/base/feature_flags.h>
  8. #include <ydb/core/persqueue/config/config.h>
  9. #include <ydb/core/persqueue/partition_key_range/partition_key_range.h>
  10. #include <ydb/core/persqueue/writer/source_id_encoding.h>
  11. #include <ydb/core/protos/pqconfig.pb.h>
  12. #include <ydb/core/protos/counters_keyvalue.pb.h>
  13. #include <ydb/core/metering/metering.h>
  14. #include <ydb/core/scheme/scheme_types_proto.h>
  15. #include <ydb/core/sys_view/service/sysview_service.h>
  16. #include <ydb/core/tablet/tablet_counters.h>
  17. #include <library/cpp/json/json_writer.h>
  18. #include <util/generic/strbuf.h>
  19. //TODO: move this code to vieiwer
  20. #include <ydb/core/tablet/tablet_counters_aggregator.h>
  21. #include <library/cpp/monlib/service/pages/templates.h>
  22. #include <util/string/escape.h>
  23. namespace NKikimr::NPQ {
  24. static constexpr TDuration TOTAL_TIMEOUT = TDuration::Seconds(120);
  25. static constexpr char TMP_REQUEST_MARKER[] = "__TMP__REQUEST__MARKER__";
  26. static constexpr ui32 CACHE_SIZE = 100_MB;
  27. static constexpr ui32 MAX_BYTES = 25_MB;
  28. static constexpr ui32 MAX_SOURCE_ID_LENGTH = 2048;
  29. static constexpr ui32 MAX_HEARTBEAT_SIZE = 2_KB;
  30. struct TPartitionInfo {
  31. TPartitionInfo(const TActorId& actor, TMaybe<TPartitionKeyRange>&& keyRange,
  32. const TTabletCountersBase& baseline)
  33. : Actor(actor)
  34. , KeyRange(std::move(keyRange))
  35. , InitDone(false)
  36. {
  37. Baseline.Populate(baseline);
  38. }
  39. TPartitionInfo(const TPartitionInfo& info)
  40. : Actor(info.Actor)
  41. , KeyRange(info.KeyRange)
  42. , InitDone(info.InitDone)
  43. {
  44. Baseline.Populate(info.Baseline);
  45. }
  46. TActorId Actor;
  47. TMaybe<TPartitionKeyRange> KeyRange;
  48. bool InitDone;
  49. TTabletCountersBase Baseline;
  50. THashMap<TString, TTabletLabeledCountersBase> LabeledCounters;
  51. };
  52. struct TChangeNotification {
  53. TChangeNotification(const TActorId& actor, const ui64 txId)
  54. : Actor(actor)
  55. , TxId(txId)
  56. {}
  57. operator size_t() const {
  58. return THash<TActorId>()(Actor) + TxId;
  59. }
  60. bool operator==(const TChangeNotification& b) {
  61. return b.Actor == Actor && b.TxId == TxId;
  62. }
  63. bool operator < (const TChangeNotification& req) const {
  64. return (Actor < req.Actor) || (Actor == req.Actor && TxId < req.TxId);
  65. }
  66. TActorId Actor;
  67. ui64 TxId;
  68. };
  69. static TMaybe<TPartitionKeyRange> GetPartitionKeyRange(const NKikimrPQ::TPQTabletConfig& config,
  70. const NKikimrPQ::TPQTabletConfig::TPartition& proto) {
  71. if (!proto.HasKeyRange() || config.GetPartitionKeySchema().empty()) {
  72. return Nothing();
  73. }
  74. return TPartitionKeyRange::Parse(proto.GetKeyRange());
  75. }
  76. static bool IsDirectReadCmd(const auto& cmd) {
  77. return cmd.GetDirectReadId() != 0;
  78. }
  79. /******************************************************* ReadProxy *********************************************************/
  80. //megaqc - remove it when LB will be ready
  81. class TReadProxy : public TActorBootstrapped<TReadProxy> {
  82. public:
  83. static constexpr NKikimrServices::TActivity::EType ActorActivityType() {
  84. return NKikimrServices::TActivity::PERSQUEUE_ANS_ACTOR;
  85. }
  86. TReadProxy(const TActorId& sender, const TActorId& tablet, ui64 tabletGeneration,
  87. const TDirectReadKey& directReadKey, const NKikimrClient::TPersQueueRequest& request)
  88. : Sender(sender)
  89. , Tablet(tablet)
  90. , TabletGeneration(tabletGeneration)
  91. , Request(request)
  92. , Response(new TEvPersQueue::TEvResponse)
  93. , DirectReadKey(directReadKey)
  94. {
  95. Y_ABORT_UNLESS(Request.HasPartitionRequest() && Request.GetPartitionRequest().HasCmdRead());
  96. Y_ABORT_UNLESS(Request.GetPartitionRequest().GetCmdRead().GetPartNo() == 0); //partial request are not allowed, otherwise remove ReadProxy
  97. Y_ABORT_UNLESS(!Response->Record.HasPartitionResponse());
  98. if (!directReadKey.SessionId.Empty()) {
  99. DirectReadKey.ReadId = Request.GetPartitionRequest().GetCmdRead().GetDirectReadId();
  100. }
  101. }
  102. void Bootstrap(const TActorContext& ctx)
  103. {
  104. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Read proxy: bootstrap for direct read id: " << DirectReadKey.ReadId);
  105. Become(&TThis::StateFunc);
  106. }
  107. private:
  108. void Handle(TEvPersQueue::TEvResponse::TPtr& ev, const TActorContext& ctx)
  109. {
  110. Y_ABORT_UNLESS(Response);
  111. const auto& record = ev->Get()->Record;
  112. if (!record.HasPartitionResponse() || !record.GetPartitionResponse().HasCmdReadResult() ||
  113. record.GetStatus() != NMsgBusProxy::MSTATUS_OK || record.GetErrorCode() != NPersQueue::NErrorCode::OK ||
  114. record.GetPartitionResponse().GetCmdReadResult().ResultSize() == 0) {
  115. Response->Record.CopyFrom(record);
  116. ctx.Send(Sender, Response.Release());
  117. Die(ctx);
  118. return;
  119. }
  120. Y_ABORT_UNLESS(record.HasPartitionResponse() && record.GetPartitionResponse().HasCmdReadResult());
  121. const auto& readResult = record.GetPartitionResponse().GetCmdReadResult();
  122. auto isDirectRead = IsDirectReadCmd(Request.GetPartitionRequest().GetCmdRead());
  123. if (isDirectRead) {
  124. if (!PreparedResponse) {
  125. PreparedResponse = std::make_shared<NKikimrClient::TResponse>();
  126. }
  127. }
  128. auto& responseRecord = isDirectRead ? *PreparedResponse : Response->Record;
  129. responseRecord.SetStatus(NMsgBusProxy::MSTATUS_OK);
  130. responseRecord.SetErrorCode(NPersQueue::NErrorCode::OK);
  131. Y_ABORT_UNLESS(readResult.ResultSize() > 0);
  132. bool isStart = false;
  133. if (!responseRecord.HasPartitionResponse()) {
  134. Y_ABORT_UNLESS(!readResult.GetResult(0).HasPartNo() || readResult.GetResult(0).GetPartNo() == 0); //starts from begin of record
  135. auto partResp = responseRecord.MutablePartitionResponse();
  136. auto readRes = partResp->MutableCmdReadResult();
  137. readRes->SetBlobsFromDisk(readRes->GetBlobsFromDisk() + readResult.GetBlobsFromDisk());
  138. readRes->SetBlobsFromCache(readRes->GetBlobsFromCache() + readResult.GetBlobsFromCache());
  139. isStart = true;
  140. }
  141. ui64 readFromTimestampMs = AppData(ctx)->PQConfig.GetTopicsAreFirstClassCitizen()
  142. ? (isStart ? readResult.GetReadFromTimestampMs()
  143. : responseRecord.GetPartitionResponse().GetCmdReadResult().GetReadFromTimestampMs())
  144. : 0;
  145. if (record.GetPartitionResponse().HasCookie())
  146. responseRecord.MutablePartitionResponse()->SetCookie(record.GetPartitionResponse().GetCookie());
  147. auto partResp = responseRecord.MutablePartitionResponse()->MutableCmdReadResult();
  148. partResp->SetMaxOffset(readResult.GetMaxOffset());
  149. partResp->SetSizeLag(readResult.GetSizeLag());
  150. partResp->SetWaitQuotaTimeMs(partResp->GetWaitQuotaTimeMs() + readResult.GetWaitQuotaTimeMs());
  151. partResp->SetRealReadOffset(Max(partResp->GetRealReadOffset(), readResult.GetRealReadOffset()));
  152. for (ui32 i = 0; i < readResult.ResultSize(); ++i) {
  153. bool isNewMsg = !readResult.GetResult(i).HasPartNo() || readResult.GetResult(i).GetPartNo() == 0;
  154. if (!isStart) {
  155. Y_ABORT_UNLESS(partResp->ResultSize() > 0);
  156. auto& back = partResp->GetResult(partResp->ResultSize() - 1);
  157. bool lastMsgIsNotFull = back.GetPartNo() + 1 < back.GetTotalParts();
  158. bool trancate = lastMsgIsNotFull && isNewMsg;
  159. if (trancate) {
  160. partResp->MutableResult()->RemoveLast();
  161. if (partResp->GetResult().empty()) isStart = false;
  162. }
  163. }
  164. if (isNewMsg) {
  165. if (!isStart && readResult.GetResult(i).HasTotalParts()
  166. && readResult.GetResult(i).GetTotalParts() + i > readResult.ResultSize()) //last blob is not full
  167. break;
  168. partResp->AddResult()->CopyFrom(readResult.GetResult(i));
  169. isStart = false;
  170. } else { //glue to last res
  171. auto rr = partResp->MutableResult(partResp->ResultSize() - 1);
  172. if (rr->GetSeqNo() != readResult.GetResult(i).GetSeqNo() || rr->GetPartNo() + 1 != readResult.GetResult(i).GetPartNo()) {
  173. LOG_CRIT_S(ctx, NKikimrServices::PERSQUEUE, "Handle TEvRead tablet: " << Tablet
  174. << " last read pos (seqno/parno): " << rr->GetSeqNo() << "," << rr->GetPartNo() << " readed now "
  175. << readResult.GetResult(i).GetSeqNo() << ", " << readResult.GetResult(i).GetPartNo()
  176. << " full request(now): " << Request);
  177. }
  178. Y_ABORT_UNLESS(rr->GetSeqNo() == readResult.GetResult(i).GetSeqNo());
  179. (*rr->MutableData()) += readResult.GetResult(i).GetData();
  180. rr->SetPartitionKey(readResult.GetResult(i).GetPartitionKey());
  181. rr->SetExplicitHash(readResult.GetResult(i).GetExplicitHash());
  182. rr->SetPartNo(readResult.GetResult(i).GetPartNo());
  183. rr->SetUncompressedSize(rr->GetUncompressedSize() + readResult.GetResult(i).GetUncompressedSize());
  184. if (readResult.GetResult(i).GetPartNo() + 1 == readResult.GetResult(i).GetTotalParts()) {
  185. Y_ABORT_UNLESS((ui32)rr->GetTotalSize() == (ui32)rr->GetData().size());
  186. }
  187. }
  188. }
  189. if (!partResp->GetResult().empty()) {
  190. const auto& lastRes = partResp->GetResult(partResp->GetResult().size() - 1);
  191. if (lastRes.HasPartNo() && lastRes.GetPartNo() + 1 < lastRes.GetTotalParts()) { //last res is not full
  192. Request.SetRequestId(TMP_REQUEST_MARKER);
  193. auto read = Request.MutablePartitionRequest()->MutableCmdRead();
  194. read->SetOffset(lastRes.GetOffset());
  195. read->SetPartNo(lastRes.GetPartNo() + 1);
  196. read->SetCount(1);
  197. read->ClearBytes();
  198. read->ClearTimeoutMs();
  199. read->ClearMaxTimeLagMs();
  200. read->SetReadTimestampMs(readFromTimestampMs);
  201. THolder<TEvPersQueue::TEvRequest> req(new TEvPersQueue::TEvRequest);
  202. req->Record = Request;
  203. ctx.Send(Tablet, req.Release());
  204. return;
  205. }
  206. }
  207. //filter old messages
  208. ::google::protobuf::RepeatedPtrField<NKikimrClient::TCmdReadResult::TResult> records;
  209. records.Swap(partResp->MutableResult());
  210. partResp->ClearResult();
  211. for (auto & rec : records) {
  212. partResp->SetRealReadOffset(Max(partResp->GetRealReadOffset(), rec.GetOffset()));
  213. if (rec.GetWriteTimestampMS() >= readFromTimestampMs) {
  214. auto result = partResp->AddResult();
  215. result->CopyFrom(rec);
  216. }
  217. }
  218. if (isDirectRead) {
  219. auto* prepareResponse = Response->Record.MutablePartitionResponse()->MutableCmdPrepareReadResult();
  220. prepareResponse->SetBytesSizeEstimate(readResult.GetSizeEstimate());
  221. prepareResponse->SetDirectReadId(DirectReadKey.ReadId);
  222. prepareResponse->SetReadOffset(readResult.GetRealReadOffset());
  223. prepareResponse->SetLastOffset(readResult.GetLastOffset());
  224. prepareResponse->SetEndOffset(readResult.GetEndOffset());
  225. prepareResponse->SetSizeLag(readResult.GetSizeLag());
  226. Response->Record.MutablePartitionResponse()->SetCookie(record.GetPartitionResponse().GetCookie());
  227. if (readResult.ResultSize()) {
  228. prepareResponse->SetWriteTimestampMS(readResult.GetResult(readResult.ResultSize() - 1).GetWriteTimestampMS());
  229. }
  230. Response->Record.SetStatus(NMsgBusProxy::MSTATUS_OK);
  231. Response->Record.SetErrorCode(NPersQueue::NErrorCode::OK);
  232. ctx.Send(Sender, Response.Release());
  233. ctx.Send(
  234. MakePQDReadCacheServiceActorId(),
  235. new TEvPQ::TEvStageDirectReadData(DirectReadKey, TabletGeneration, PreparedResponse)
  236. );
  237. } else {
  238. ctx.Send(Sender, Response.Release());
  239. }
  240. Die(ctx);
  241. }
  242. STFUNC(StateFunc) {
  243. switch (ev->GetTypeRewrite()) {
  244. HFunc(TEvPersQueue::TEvResponse, Handle);
  245. default:
  246. break;
  247. };
  248. }
  249. const TActorId Sender;
  250. const TActorId Tablet;
  251. ui32 TabletGeneration;
  252. NKikimrClient::TPersQueueRequest Request;
  253. THolder<TEvPersQueue::TEvResponse> Response;
  254. std::shared_ptr<NKikimrClient::TResponse> PreparedResponse;
  255. TDirectReadKey DirectReadKey;
  256. };
  257. TActorId CreateReadProxy(const TActorId& sender, const TActorId& tablet, ui32 tabletGeneration,
  258. const TDirectReadKey& directReadKey, const NKikimrClient::TPersQueueRequest& request,
  259. const TActorContext& ctx)
  260. {
  261. return ctx.Register(new TReadProxy(sender, tablet, tabletGeneration, directReadKey, request));
  262. }
  263. /******************************************************* AnswerBuilderProxy *********************************************************/
  264. class TResponseBuilder {
  265. public:
  266. TResponseBuilder(const TActorId& sender, const TActorId& tablet, const TString& topicName, const ui32 partition, const ui64 messageNo,
  267. const TString& reqId, const TMaybe<ui64> cookie, NMetrics::TResourceMetrics* resourceMetrics,
  268. const TActorContext& ctx)
  269. : Sender(sender)
  270. , Tablet(tablet)
  271. , TopicName(topicName)
  272. , Partition(partition)
  273. , MessageNo(messageNo)
  274. , CounterId(0)
  275. , Waiting(0)
  276. , ReqId(reqId)
  277. , Response(new TEvPersQueue::TEvResponse)
  278. , Timestamp(TAppData::TimeProvider->Now())
  279. , WasSplit(false)
  280. , Cookie(cookie)
  281. , ResourceMetrics(resourceMetrics)
  282. {
  283. if (cookie)
  284. Response->Record.MutablePartitionResponse()->SetCookie(*cookie);
  285. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Handle TEvRequest topic: '" << TopicName << "' requestId: " << ReqId);
  286. }
  287. void SetWasSplit()
  288. {
  289. WasSplit = true;
  290. }
  291. void AddPartialReplyCount(const ui32 partialReplyCount)
  292. {
  293. Waiting += partialReplyCount;
  294. }
  295. void SetCounterId(const ui32 counterId)
  296. {
  297. CounterId = counterId;
  298. }
  299. bool HandleProxyResponse(TEvPQ::TEvProxyResponse::TPtr& ev, const TActorContext& ctx)
  300. {
  301. Y_ABORT_UNLESS(Waiting);
  302. Y_ABORT_UNLESS(Response);
  303. --Waiting;
  304. bool skip = false;
  305. if (WasSplit && ev->Get()->Response->GetPartitionResponse().CmdWriteResultSize() == 1) { //megaqc - remove this
  306. const auto& x = ev->Get()->Response->GetPartitionResponse().GetCmdWriteResult(0);
  307. if (x.HasPartNo() && x.GetPartNo() > 0)
  308. skip = true;
  309. }
  310. if (!skip) //megaqc - remove this
  311. Response->Record.MergeFrom(*ev->Get()->Response);
  312. if (!Waiting) {
  313. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Answer ok topic: '" << TopicName << "' partition: " << Partition
  314. << " messageNo: " << MessageNo << " requestId: " << ReqId << " cookie: " << (Cookie ? *Cookie : 0));
  315. if (ResourceMetrics) {
  316. ResourceMetrics->Network.Increment(Response->Record.ByteSizeLong());
  317. ResourceMetrics->TryUpdate(ctx);
  318. }
  319. ctx.Send(Sender, Response.Release());
  320. return true;
  321. }
  322. return false;
  323. }
  324. bool HandleError(TEvPQ::TEvError *ev, const TActorContext& ctx)
  325. {
  326. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  327. "Answer error topic: '" << TopicName << "'" <<
  328. " partition: " << Partition <<
  329. " messageNo: " << MessageNo <<
  330. " requestId: " << ReqId <<
  331. " error: " << ev->Error);
  332. Response->Record.SetStatus(NMsgBusProxy::MSTATUS_ERROR);
  333. Response->Record.SetErrorCode(ev->ErrorCode);
  334. Response->Record.SetErrorReason(ev->Error);
  335. ctx.Send(Sender, Response.Release());
  336. return true;
  337. }
  338. const TActorId Sender;
  339. const TActorId Tablet;
  340. const TString TopicName;
  341. const ui32 Partition;
  342. const ui64 MessageNo;
  343. ui32 CounterId;
  344. ui32 Waiting;
  345. const TString ReqId;
  346. THolder<TEvPersQueue::TEvResponse> Response;
  347. TInstant Timestamp;
  348. bool WasSplit;
  349. TMaybe<ui64> Cookie;
  350. NMetrics::TResourceMetrics* ResourceMetrics;
  351. };
  352. TAutoPtr<TResponseBuilder> CreateResponseProxy(const TActorId& sender, const TActorId& tablet, const TString& topicName,
  353. const ui32 partition, const ui64 messageNo, const TString& reqId, const TMaybe<ui64> cookie,
  354. NMetrics::TResourceMetrics *resourceMetrics, const TActorContext& ctx)
  355. {
  356. return new TResponseBuilder(sender, tablet, topicName, partition, messageNo, reqId, cookie, resourceMetrics, ctx);
  357. }
  358. /******************************************************* OffsetsBuilderProxy *********************************************************/
  359. template <typename T, typename T2, typename T3>
  360. class TBuilderProxy : public TActorBootstrapped<TBuilderProxy<T,T2,T3>> {
  361. typedef TBuilderProxy<T,T2,T3> TThis;
  362. friend class TActorBootstrapped<TThis>;
  363. typedef T TEvent;
  364. typedef typename TEvent::TPtr TTPtr;
  365. public:
  366. static constexpr NKikimrServices::TActivity::EType ActorActivityType() {
  367. return NKikimrServices::TActivity::PERSQUEUE_ANS_ACTOR;
  368. }
  369. TBuilderProxy(const ui64 tabletId, const TActorId& sender, const ui32 count, const ui64 cookie)
  370. : TabletId(tabletId)
  371. , Sender(sender)
  372. , Waiting(count)
  373. , Result()
  374. , Cookie(cookie)
  375. {}
  376. void Bootstrap(const TActorContext& ctx)
  377. {
  378. TThis::Become(&TThis::StateFunc);
  379. if (!Waiting) {
  380. AnswerAndDie(ctx);
  381. return;
  382. }
  383. ctx.Schedule(TOTAL_TIMEOUT, new TEvents::TEvWakeup());
  384. }
  385. private:
  386. void AnswerAndDie(const TActorContext& ctx)
  387. {
  388. std::sort(Result.begin(), Result.end(), [](const typename T2::TPartResult& a, const typename T2::TPartResult& b){
  389. return a.GetPartition() < b.GetPartition();
  390. });
  391. THolder<T3> res = MakeHolder<T3>();
  392. auto& resp = res->Record;
  393. resp.SetTabletId(TabletId);
  394. for (const auto& p : Result) {
  395. resp.AddPartResult()->CopyFrom(p);
  396. }
  397. ctx.Send(Sender, res.Release(), 0, Cookie);
  398. TThis::Die(ctx);
  399. }
  400. void Handle(TTPtr& ev, const TActorContext& ctx)
  401. {
  402. Result.push_back(ev->Get()->PartResult);
  403. if (--Waiting == 0) {
  404. AnswerAndDie(ctx);
  405. }
  406. }
  407. void Wakeup(const TActorContext& ctx) {
  408. AnswerAndDie(ctx);
  409. }
  410. STFUNC(StateFunc) {
  411. switch (ev->GetTypeRewrite()) {
  412. HFunc(TEvent, Handle);
  413. CFunc(TEvents::TSystem::Wakeup, Wakeup);
  414. default:
  415. break;
  416. };
  417. }
  418. ui64 TabletId;
  419. TActorId Sender;
  420. ui32 Waiting;
  421. TVector<typename T2::TPartResult> Result;
  422. ui64 Cookie;
  423. };
  424. TActorId CreateOffsetsProxyActor(const ui64 tabletId, const TActorId& sender, const ui32 count, const TActorContext& ctx)
  425. {
  426. return ctx.Register(new TBuilderProxy<TEvPQ::TEvPartitionOffsetsResponse,
  427. NKikimrPQ::TOffsetsResponse,
  428. TEvPersQueue::TEvOffsetsResponse>(tabletId, sender, count, 0));
  429. }
  430. /******************************************************* StatusProxy *********************************************************/
  431. TActorId CreateStatusProxyActor(const ui64 tabletId, const TActorId& sender, const ui32 count, const ui64 cookie, const TActorContext& ctx)
  432. {
  433. return ctx.Register(new TBuilderProxy<TEvPQ::TEvPartitionStatusResponse,
  434. NKikimrPQ::TStatusResponse,
  435. TEvPersQueue::TEvStatusResponse>(tabletId, sender, count, cookie));
  436. }
  437. /******************************************************* MonitoringProxy *********************************************************/
  438. class TMonitoringProxy : public TActorBootstrapped<TMonitoringProxy> {
  439. public:
  440. static constexpr NKikimrServices::TActivity::EType ActorActivityType() {
  441. return NKikimrServices::TActivity::PERSQUEUE_MON_ACTOR;
  442. }
  443. TMonitoringProxy(const TActorId& sender, const TString& query, const TMap<ui32, TActorId>& partitions, const TActorId& cache,
  444. const TString& topicName, ui64 tabletId, ui32 inflight)
  445. : Sender(sender)
  446. , Query(query)
  447. , Partitions(partitions)
  448. , Cache(cache)
  449. , TotalRequests(partitions.size() + 1)
  450. , TotalResponses(0)
  451. , TopicName(topicName)
  452. , TabletID(tabletId)
  453. , Inflight(inflight)
  454. {
  455. for (auto& p: Partitions) {
  456. Results[p.first].push_back(Sprintf("Partition %u: NO DATA", p.first));
  457. }
  458. }
  459. void Bootstrap(const TActorContext& ctx)
  460. {
  461. Become(&TThis::StateFunc);
  462. ctx.Send(Cache, new TEvPQ::TEvMonRequest(Sender, Query));
  463. for (auto& p : Partitions) {
  464. ctx.Send(p.second, new TEvPQ::TEvMonRequest(Sender, Query));
  465. }
  466. ctx.Schedule(TDuration::Seconds(10), new TEvents::TEvWakeup());
  467. }
  468. private:
  469. void Reply(const TActorContext& ctx) {
  470. TStringStream str;
  471. ui32 mx = 0;
  472. for (auto& r: Results) mx = Max<ui32>(mx, r.second.size());
  473. HTML(str) {
  474. TAG(TH2) {str << "PersQueue Tablet";}
  475. TAG(TH3) {str << "Topic: " << TopicName;}
  476. TAG(TH4) {str << "inflight: " << Inflight;}
  477. UL_CLASS("nav nav-tabs") {
  478. LI_CLASS("active") {
  479. str << "<a href=\"#main\" data-toggle=\"tab\">main</a>";
  480. }
  481. LI() {
  482. str << "<a href=\"#cache\" data-toggle=\"tab\">cache</a>";
  483. }
  484. for (auto& r: Results) {
  485. LI() {
  486. str << "<a href=\"#partition_" << r.first << "\" data-toggle=\"tab\">" << r.first << "</a>";
  487. }
  488. }
  489. }
  490. DIV_CLASS("tab-content") {
  491. DIV_CLASS_ID("tab-pane fade in active", "main") {
  492. TABLE() {
  493. for (ui32 i = 0; i < mx; ++i) {
  494. TABLER() {
  495. for (auto& r : Results) {
  496. TABLED() {
  497. if (r.second.size() > i)
  498. str << r.second[i];
  499. }
  500. }
  501. }
  502. }
  503. }
  504. }
  505. for (auto& s: Str) {
  506. str << s;
  507. }
  508. }
  509. TAG(TH3) {str << "<a href=\"app?TabletID=" << TabletID << "&kv=1\">KV-tablet internals</a>";}
  510. }
  511. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Answer TEvRemoteHttpInfoRes: to " << Sender << " self " << ctx.SelfID);
  512. ctx.Send(Sender, new NMon::TEvRemoteHttpInfoRes(str.Str()));
  513. Die(ctx);
  514. }
  515. void Wakeup(const TActorContext& ctx) {
  516. Reply(ctx);
  517. }
  518. void Handle(TEvPQ::TEvMonResponse::TPtr& ev, const TActorContext& ctx)
  519. {
  520. if (ev->Get()->Partition != Max<ui32>()) {
  521. Results[ev->Get()->Partition] = ev->Get()->Res;
  522. } else {
  523. Y_ABORT_UNLESS(ev->Get()->Partition == Max<ui32>());
  524. }
  525. Str.push_back(ev->Get()->Str);
  526. if(++TotalResponses == TotalRequests) {
  527. Reply(ctx);
  528. }
  529. }
  530. STFUNC(StateFunc) {
  531. switch (ev->GetTypeRewrite()) {
  532. CFunc(TEvents::TSystem::Wakeup, Wakeup);
  533. HFunc(TEvPQ::TEvMonResponse, Handle);
  534. default:
  535. break;
  536. };
  537. }
  538. TActorId Sender;
  539. TString Query;
  540. TMap<ui32, TVector<TString>> Results;
  541. TVector<TString> Str;
  542. TMap<ui32, TActorId> Partitions;
  543. TActorId Cache;
  544. ui32 TotalRequests;
  545. ui32 TotalResponses;
  546. TString TopicName;
  547. ui64 TabletID;
  548. ui32 Inflight;
  549. };
  550. /******************************************************* TPersQueue *********************************************************/
  551. struct TPersQueue::TReplyToActor {
  552. using TEventBasePtr = std::unique_ptr<IEventBase>;
  553. TReplyToActor(const TActorId& actorId, TEventBasePtr event) :
  554. ActorId(actorId),
  555. Event(std::move(event))
  556. {
  557. }
  558. TActorId ActorId;
  559. TEventBasePtr Event;
  560. };
  561. void TPersQueue::ReplyError(const TActorContext& ctx, const ui64 responseCookie, NPersQueue::NErrorCode::EErrorCode errorCode, const TString& error)
  562. {
  563. ReplyPersQueueError(
  564. ctx.SelfID, ctx, TabletID(), TopicName, Nothing(), *Counters, NKikimrServices::PERSQUEUE,
  565. responseCookie, errorCode, error
  566. );
  567. }
  568. void TPersQueue::ApplyNewConfigAndReply(const TActorContext& ctx)
  569. {
  570. THashSet<ui32> was;
  571. if (NewConfig.PartitionsSize()) {
  572. for (const auto& partition : NewConfig.GetPartitions()) {
  573. was.insert(partition.GetPartitionId());
  574. }
  575. } else {
  576. for (const auto partitionId : NewConfig.GetPartitionIds()) {
  577. was.insert(partitionId);
  578. }
  579. }
  580. for (const auto& partition : Config.GetPartitions()) {
  581. Y_VERIFY_S(was.contains(partition.GetPartitionId()), "New config is bad, missing partition " << partition.GetPartitionId());
  582. }
  583. // in order to answer only after all parts are ready to work
  584. Y_ABORT_UNLESS(ConfigInited && PartitionsInited == Partitions.size());
  585. ApplyNewConfig(NewConfig, ctx);
  586. ClearNewConfig();
  587. for (auto& p : Partitions) { //change config for already created partitions
  588. ctx.Send(p.second.Actor, new TEvPQ::TEvChangePartitionConfig(TopicConverter, Config));
  589. }
  590. ChangePartitionConfigInflight += Partitions.size();
  591. for (const auto& partition : Config.GetPartitions()) {
  592. const auto partitionId = partition.GetPartitionId();
  593. if (Partitions.find(partitionId) == Partitions.end()) {
  594. Partitions.emplace(partitionId,
  595. TPartitionInfo(ctx.Register(CreatePartitionActor(partitionId, TopicConverter, Config, true, ctx)),
  596. GetPartitionKeyRange(Config, partition),
  597. *Counters
  598. ));
  599. }
  600. }
  601. TrySendUpdateConfigResponses(ctx);
  602. }
  603. void TPersQueue::ApplyNewConfig(const NKikimrPQ::TPQTabletConfig& newConfig,
  604. const TActorContext& ctx)
  605. {
  606. Config = newConfig;
  607. if (!Config.PartitionsSize()) {
  608. for (const auto partitionId : Config.GetPartitionIds()) {
  609. Config.AddPartitions()->SetPartitionId(partitionId);
  610. }
  611. }
  612. ui32 cacheSize = CACHE_SIZE;
  613. if (Config.HasCacheSize()) {
  614. cacheSize = Config.GetCacheSize();
  615. }
  616. if (!TopicConverter) { // it's the first time
  617. TopicName = Config.GetTopicName();
  618. TopicPath = Config.GetTopicPath();
  619. IsLocalDC = Config.GetLocalDC();
  620. CreateTopicConverter(Config,
  621. TopicConverterFactory,
  622. TopicConverter,
  623. ctx);
  624. KeySchema.clear();
  625. KeySchema.reserve(Config.PartitionKeySchemaSize());
  626. for (const auto& component : Config.GetPartitionKeySchema()) {
  627. auto typeInfoMod = NScheme::TypeInfoModFromProtoColumnType(component.GetTypeId(),
  628. component.HasTypeInfo() ? &component.GetTypeInfo() : nullptr);
  629. KeySchema.push_back(typeInfoMod.TypeInfo);
  630. }
  631. Y_ABORT_UNLESS(TopicName.size(), "Need topic name here");
  632. ctx.Send(CacheActor, new TEvPQ::TEvChangeCacheConfig(TopicName, cacheSize));
  633. } else {
  634. //Y_ABORT_UNLESS(TopicName == Config.GetTopicName(), "Changing topic name is not supported");
  635. TopicPath = Config.GetTopicPath();
  636. ctx.Send(CacheActor, new TEvPQ::TEvChangeCacheConfig(cacheSize));
  637. }
  638. InitializeMeteringSink(ctx);
  639. }
  640. void TPersQueue::EndWriteConfig(const NKikimrClient::TResponse& resp, const TActorContext& ctx)
  641. {
  642. if (resp.GetStatus() != NMsgBusProxy::MSTATUS_OK ||
  643. resp.WriteResultSize() < 1) {
  644. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  645. << " Config write error: " << resp.DebugString() << " " << ctx.SelfID);
  646. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  647. return;
  648. }
  649. for (const auto& res : resp.GetWriteResult()) {
  650. if (res.GetStatus() != NKikimrProto::OK) {
  651. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  652. << " Config write error: " << resp.DebugString() << " " << ctx.SelfID);
  653. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  654. return;
  655. }
  656. }
  657. if (resp.WriteResultSize() > 1) {
  658. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  659. << " restarting - have some registering of message groups");
  660. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  661. return;
  662. }
  663. Y_ABORT_UNLESS(resp.WriteResultSize() >= 1);
  664. Y_ABORT_UNLESS(resp.GetWriteResult(0).GetStatus() == NKikimrProto::OK);
  665. if (ConfigInited && PartitionsInited == Partitions.size()) //all partitions are working well - can apply new config
  666. ApplyNewConfigAndReply(ctx);
  667. else
  668. NewConfigShouldBeApplied = true; //when config will be inited with old value new config will be applied
  669. }
  670. void TPersQueue::HandleConfigReadResponse(const NKikimrClient::TResponse& resp, const TActorContext& ctx)
  671. {
  672. bool ok =
  673. (resp.GetStatus() == NMsgBusProxy::MSTATUS_OK) &&
  674. (resp.ReadResultSize() == 3) &&
  675. (resp.HasSetExecutorFastLogPolicyResult()) &&
  676. (resp.GetSetExecutorFastLogPolicyResult().GetStatus() == NKikimrProto::OK);
  677. if (!ok) {
  678. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  679. "Tablet " << TabletID() << " Config read error: " << resp.DebugString() << " " << ctx.SelfID);
  680. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  681. return;
  682. }
  683. ReadTxInfo(resp.GetReadResult(2), ctx);
  684. ReadConfig(resp.GetReadResult(0), resp.GetReadRangeResult(0), ctx);
  685. ReadState(resp.GetReadResult(1), ctx);
  686. }
  687. void TPersQueue::ReadTxInfo(const NKikimrClient::TKeyValueResponse::TReadResult& read,
  688. const TActorContext& ctx)
  689. {
  690. Y_ABORT_UNLESS(read.HasStatus());
  691. if (read.GetStatus() != NKikimrProto::OK && read.GetStatus() != NKikimrProto::NODATA) {
  692. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  693. "Tablet " << TabletID() << " tx info read error " << ctx.SelfID);
  694. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  695. return;
  696. }
  697. switch (read.GetStatus()) {
  698. case NKikimrProto::OK: {
  699. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " has a tx info");
  700. NKikimrPQ::TTabletTxInfo info;
  701. Y_ABORT_UNLESS(info.ParseFromString(read.GetValue()));
  702. LastStep = info.GetLastStep();
  703. LastTxId = info.GetLastTxId();
  704. break;
  705. }
  706. case NKikimrProto::NODATA: {
  707. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " doesn't have tx info");
  708. LastStep = 0;
  709. LastTxId = 0;
  710. break;
  711. }
  712. default:
  713. Y_ABORT("Unexpected tx info read status: %d", read.GetStatus());
  714. }
  715. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " LastStep " << LastStep << " LastTxId " << LastTxId);
  716. }
  717. void TPersQueue::ReadConfig(const NKikimrClient::TKeyValueResponse::TReadResult& read,
  718. const NKikimrClient::TKeyValueResponse::TReadRangeResult& readRange,
  719. const TActorContext& ctx)
  720. {
  721. Y_ABORT_UNLESS(read.HasStatus());
  722. if (read.GetStatus() != NKikimrProto::OK && read.GetStatus() != NKikimrProto::NODATA) {
  723. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  724. "Tablet " << TabletID() << " Config read error " << ctx.SelfID <<
  725. " Error status code " << read.GetStatus());
  726. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  727. return;
  728. }
  729. Y_ABORT_UNLESS(readRange.HasStatus());
  730. if (readRange.GetStatus() != NKikimrProto::OK && readRange.GetStatus() != NKikimrProto::NODATA) {
  731. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  732. "Tablet " << TabletID() << " Transactions read error " << ctx.SelfID <<
  733. " Error status code " << readRange.GetStatus());
  734. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  735. return;
  736. }
  737. Y_ABORT_UNLESS(!ConfigInited);
  738. if (read.GetStatus() == NKikimrProto::OK) {
  739. bool res = Config.ParseFromString(read.GetValue());
  740. Y_ABORT_UNLESS(res);
  741. if (!Config.PartitionsSize()) {
  742. for (const auto partitionId : Config.GetPartitionIds()) {
  743. Config.AddPartitions()->SetPartitionId(partitionId);
  744. }
  745. }
  746. TopicName = Config.GetTopicName();
  747. TopicPath = Config.GetTopicPath();
  748. IsLocalDC = Config.GetLocalDC();
  749. CreateTopicConverter(Config,
  750. TopicConverterFactory,
  751. TopicConverter,
  752. ctx);
  753. KeySchema.clear();
  754. KeySchema.reserve(Config.PartitionKeySchemaSize());
  755. for (const auto& component : Config.GetPartitionKeySchema()) {
  756. auto typeInfoMod = NScheme::TypeInfoModFromProtoColumnType(component.GetTypeId(),
  757. component.HasTypeInfo() ? &component.GetTypeInfo() : nullptr);
  758. KeySchema.push_back(typeInfoMod.TypeInfo);
  759. }
  760. ui32 cacheSize = CACHE_SIZE;
  761. if (Config.HasCacheSize())
  762. cacheSize = Config.GetCacheSize();
  763. Y_ABORT_UNLESS(TopicName.size(), "Need topic name here");
  764. ctx.Send(CacheActor, new TEvPQ::TEvChangeCacheConfig(TopicName, cacheSize));
  765. } else if (read.GetStatus() == NKikimrProto::NODATA) {
  766. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " no config, start with empty partitions and default config");
  767. } else {
  768. Y_ABORT("Unexpected config read status: %d", read.GetStatus());
  769. }
  770. THashMap<ui32, TVector<TTransaction>> partitionTxs;
  771. InitTransactions(readRange, partitionTxs);
  772. for (const auto& partition : Config.GetPartitions()) { // no partitions will be created with empty config
  773. const auto partitionId = partition.GetPartitionId();
  774. Partitions.emplace(partitionId, TPartitionInfo(
  775. ctx.Register(CreatePartitionActor(partitionId, TopicConverter, Config, false, ctx)),
  776. GetPartitionKeyRange(Config, partition),
  777. *Counters
  778. ));
  779. }
  780. ConfigInited = true;
  781. InitializeMeteringSink(ctx);
  782. Y_ABORT_UNLESS(!NewConfigShouldBeApplied);
  783. for (auto& req : UpdateConfigRequests) {
  784. ProcessUpdateConfigRequest(req.first, req.second, ctx);
  785. }
  786. UpdateConfigRequests.clear();
  787. for (auto& req : HasDataRequests) {
  788. auto it = Partitions.find(req->Record.GetPartition());
  789. if (it != Partitions.end()) {
  790. if (ctx.Now().MilliSeconds() < req->Record.GetDeadline()) { //otherwise there is no need to send event - proxy will generate event itself
  791. ctx.Send(it->second.Actor, req.Release());
  792. }
  793. }
  794. }
  795. HasDataRequests.clear();
  796. if (Partitions.empty()) {
  797. OnInitComplete(ctx);
  798. }
  799. }
  800. void TPersQueue::ReadState(const NKikimrClient::TKeyValueResponse::TReadResult& read, const TActorContext& ctx)
  801. {
  802. Y_UNUSED(ctx);
  803. if (read.GetStatus() == NKikimrProto::OK) {
  804. NKikimrPQ::TTabletState stateProto;
  805. bool ok = stateProto.ParseFromString(read.GetValue());
  806. Y_ABORT_UNLESS(ok);
  807. Y_ABORT_UNLESS(stateProto.HasState());
  808. TabletState = stateProto.GetState();
  809. } else if (read.GetStatus() == NKikimrProto::NODATA) {
  810. TabletState = NKikimrPQ::ENormal;
  811. } else {
  812. Y_ABORT("Unexpected state read status: %d", read.GetStatus());
  813. }
  814. }
  815. void TPersQueue::InitializeMeteringSink(const TActorContext& ctx) {
  816. TStringBuf stream;
  817. const auto streamName =
  818. TStringBuf(Config.GetTopicPath()).AfterPrefix(Config.GetYdbDatabasePath() + "/", stream)
  819. ? stream.data() : Config.GetTopicPath();
  820. const auto streamPath = Config.GetTopicPath();
  821. auto& pqConfig = AppData(ctx)->PQConfig;
  822. if (!pqConfig.GetBillingMeteringConfig().GetEnabled()) {
  823. LOG_NOTICE_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " disable metering"
  824. << ": reason# " << "billing is not enabled in BillingMeteringConfig");
  825. return;
  826. }
  827. TSet<EMeteringJson> whichToFlush{EMeteringJson::PutEventsV1,
  828. EMeteringJson::ResourcesReservedV1,
  829. EMeteringJson::UsedStorageV1};
  830. ui64 storageLimitBytes{Config.GetPartitionConfig().GetWriteSpeedInBytesPerSecond() *
  831. Config.GetPartitionConfig().GetLifetimeSeconds()};
  832. if (Config.GetPartitionConfig().HasStorageLimitBytes()) {
  833. storageLimitBytes = Config.GetPartitionConfig().GetStorageLimitBytes();
  834. whichToFlush = TSet<EMeteringJson>{EMeteringJson::PutEventsV1,
  835. EMeteringJson::ThroughputV1,
  836. EMeteringJson::StorageV1,
  837. EMeteringJson::UsedStorageV1};
  838. }
  839. switch (Config.GetMeteringMode()) {
  840. case NKikimrPQ::TPQTabletConfig::METERING_MODE_REQUEST_UNITS:
  841. LOG_NOTICE_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " metering mode METERING_MODE_REQUEST_UNITS");
  842. whichToFlush = TSet<EMeteringJson>{EMeteringJson::UsedStorageV1};
  843. break;
  844. default:
  845. break;
  846. }
  847. auto countReadRulesWithPricing = [&](const TActorContext& ctx, const auto& config) {
  848. ui32 result = 0;
  849. for (ui32 i = 0; i < config.ReadRulesSize(); ++i) {
  850. TString rrServiceType = config.ReadRuleServiceTypesSize() <= i ? "" : config.GetReadRuleServiceTypes(i);
  851. if (rrServiceType.empty() || rrServiceType == AppData(ctx)->PQConfig.GetDefaultClientServiceType().GetName())
  852. ++result;
  853. }
  854. return result;
  855. };
  856. MeteringSink.Create(ctx.Now(), {
  857. .FlushInterval = TDuration::Seconds(pqConfig.GetBillingMeteringConfig().GetFlushIntervalSec()),
  858. .TabletId = ToString(TabletID()),
  859. .YcCloudId = Config.GetYcCloudId(),
  860. .YcFolderId = Config.GetYcFolderId(),
  861. .YdbDatabaseId = Config.GetYdbDatabaseId(),
  862. .StreamName = streamName,
  863. .ResourceId = streamPath,
  864. .PartitionsSize = Config.PartitionsSize(),
  865. .WriteQuota = Config.GetPartitionConfig().GetWriteSpeedInBytesPerSecond(),
  866. .ReservedSpace = storageLimitBytes,
  867. .ConsumersCount = countReadRulesWithPricing(ctx, Config),
  868. }, whichToFlush, std::bind(NMetering::SendMeteringJson, ctx, std::placeholders::_1));
  869. }
  870. void TPersQueue::ReturnTabletState(const TActorContext& ctx, const TChangeNotification& req, NKikimrProto::EReplyStatus status)
  871. {
  872. THolder<TEvPersQueue::TEvDropTabletReply> event = MakeHolder<TEvPersQueue::TEvDropTabletReply>();
  873. event->Record.SetStatus(status);
  874. event->Record.SetTabletId(TabletID());
  875. event->Record.SetTxId(req.TxId);
  876. event->Record.SetActualState(TabletState);
  877. ctx.Send(req.Actor, event.Release());
  878. }
  879. void TPersQueue::TryReturnTabletStateAll(const TActorContext& ctx, NKikimrProto::EReplyStatus status)
  880. {
  881. if (AllTransactionsHaveBeenProcessed() && (TabletState == NKikimrPQ::EDropped)) {
  882. for (auto req : TabletStateRequests) {
  883. ReturnTabletState(ctx, req, status);
  884. }
  885. TabletStateRequests.clear();
  886. }
  887. }
  888. void TPersQueue::BeginWriteTabletState(const TActorContext& ctx, NKikimrPQ::ETabletState state)
  889. {
  890. NKikimrPQ::TTabletState stateProto;
  891. stateProto.SetState(state);
  892. TString strState;
  893. bool ok = stateProto.SerializeToString(&strState);
  894. Y_ABORT_UNLESS(ok);
  895. TAutoPtr<TEvKeyValue::TEvRequest> kvRequest(new TEvKeyValue::TEvRequest);
  896. kvRequest->Record.SetCookie(WRITE_STATE_COOKIE);
  897. auto kvCmd = kvRequest->Record.AddCmdWrite();
  898. kvCmd->SetKey(KeyState());
  899. kvCmd->SetValue(strState);
  900. kvCmd->SetTactic(AppData(ctx)->PQConfig.GetTactic());
  901. ctx.Send(ctx.SelfID, kvRequest.Release());
  902. }
  903. void TPersQueue::EndWriteTabletState(const NKikimrClient::TResponse& resp, const TActorContext& ctx)
  904. {
  905. bool ok = (resp.GetStatus() == NMsgBusProxy::MSTATUS_OK) &&
  906. (resp.WriteResultSize() == 1) &&
  907. (resp.GetWriteResult(0).GetStatus() == NKikimrProto::OK);
  908. if (!ok) {
  909. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  910. "Tablet " << TabletID() << " SelfId " << ctx.SelfID << " State write error: " << resp.DebugString());
  911. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  912. return;
  913. }
  914. TabletState = NKikimrPQ::EDropped;
  915. TryReturnTabletStateAll(ctx);
  916. }
  917. void TPersQueue::Handle(TEvKeyValue::TEvResponse::TPtr& ev, const TActorContext& ctx)
  918. {
  919. auto& resp = ev->Get()->Record;
  920. switch (resp.GetCookie()) {
  921. case WRITE_CONFIG_COOKIE:
  922. EndWriteConfig(resp, ctx);
  923. break;
  924. case READ_CONFIG_COOKIE:
  925. // read is only for config - is signal to create interal actors
  926. HandleConfigReadResponse(resp, ctx);
  927. break;
  928. case WRITE_STATE_COOKIE:
  929. EndWriteTabletState(resp, ctx);
  930. break;
  931. case WRITE_TX_COOKIE:
  932. EndWriteTxs(resp, ctx);
  933. break;
  934. default:
  935. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  936. << " Unexpected KV response: " << ev->Get()->ToString() << " " << ctx.SelfID);
  937. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  938. }
  939. }
  940. void TPersQueue::SetCacheCounters(TEvPQ::TEvTabletCacheCounters::TCacheCounters& cacheCounters)
  941. {
  942. Counters->Simple()[COUNTER_PQ_TABLET_CACHE_SIZE] = cacheCounters.CacheSizeBytes;
  943. Counters->Simple()[COUNTER_PQ_TABLET_CACHE_COUNT] = cacheCounters.CacheSizeBlobs;
  944. Counters->Simple()[COUNTER_PQ_TABLET_CACHED_ON_READ] = cacheCounters.CachedOnRead;
  945. Counters->Simple()[COUNTER_PQ_TABLET_CACHED_ON_WRATE] = cacheCounters.CachedOnWrite;
  946. Counters->Simple()[COUNTER_PQ_TABLET_OPENED_PIPES] = PipesInfo.size();
  947. }
  948. void TPersQueue::Handle(TEvPQ::TEvMetering::TPtr& ev, const TActorContext&)
  949. {
  950. MeteringSink.IncreaseQuantity(ev->Get()->Type, ev->Get()->Quantity);
  951. }
  952. void TPersQueue::Handle(TEvPQ::TEvPartitionCounters::TPtr& ev, const TActorContext& ctx)
  953. {
  954. auto it = Partitions.find(ev->Get()->Partition);
  955. Y_ABORT_UNLESS(it != Partitions.end());
  956. auto diff = ev->Get()->Counters.MakeDiffForAggr(it->second.Baseline);
  957. ui64 cpuUsage = diff->Cumulative()[COUNTER_PQ_TABLET_CPU_USAGE].Get();
  958. ui64 networkBytesUsage = diff->Cumulative()[COUNTER_PQ_TABLET_NETWORK_BYTES_USAGE].Get();
  959. if (ResourceMetrics) {
  960. if (cpuUsage > 0) {
  961. ResourceMetrics->CPU.Increment(cpuUsage);
  962. }
  963. if (networkBytesUsage > 0) {
  964. ResourceMetrics->Network.Increment(networkBytesUsage);
  965. }
  966. if (cpuUsage > 0 || networkBytesUsage > 0) {
  967. ResourceMetrics->TryUpdate(ctx);
  968. }
  969. }
  970. Counters->Populate(*diff.Get());
  971. ev->Get()->Counters.RememberCurrentStateAsBaseline(it->second.Baseline);
  972. // restore cache's simple counters cleaned by partition's counters
  973. SetCacheCounters(CacheCounters);
  974. ui64 reservedSize = 0;
  975. for (auto& p : Partitions) {
  976. if (p.second.Baseline.Simple().Size() > 0) //there could be no counters from this partition yet
  977. reservedSize += p.second.Baseline.Simple()[COUNTER_PQ_TABLET_RESERVED_BYTES_SIZE].Get();
  978. }
  979. Counters->Simple()[COUNTER_PQ_TABLET_RESERVED_BYTES_SIZE].Set(reservedSize);
  980. }
  981. void TPersQueue::AggregateAndSendLabeledCountersFor(const TString& group, const TActorContext& ctx)
  982. {
  983. if (CounterEventsInflight[group].RefCount() <= 1) {
  984. if (CounterEventsInflight[group].RefCount() == 0) {
  985. CounterEventsInflight[group] = new TEvTabletCounters::TInFlightCookie;
  986. }
  987. const TMaybe<TString> dbPath = AppData(ctx)->PQConfig.GetTopicsAreFirstClassCitizen()
  988. ? TMaybe<TString>(Config.GetYdbDatabasePath())
  989. : Nothing();
  990. TAutoPtr<TTabletLabeledCountersBase> aggr(new TTabletLabeledCountersBase);
  991. aggr->SetDatabasePath(dbPath);
  992. for (auto& p : Partitions) {
  993. auto it = p.second.LabeledCounters.find(group);
  994. if (it != p.second.LabeledCounters.end()) {
  995. aggr->AggregateWith(it->second);
  996. if (it->second.GetDrop()) {
  997. p.second.LabeledCounters.erase(it);
  998. }
  999. }
  1000. }
  1001. Y_ABORT_UNLESS(aggr->HasCounters());
  1002. TActorId countersAggregator = MakeTabletCountersAggregatorID(ctx.SelfID.NodeId());
  1003. ctx.Send(countersAggregator,
  1004. new TEvTabletCounters::TEvTabletAddLabeledCounters(
  1005. CounterEventsInflight[group], TabletID(), TTabletTypes::PersQueue, aggr));
  1006. }
  1007. }
  1008. void TPersQueue::Handle(TEvPQ::TEvPartitionLabeledCounters::TPtr& ev, const TActorContext& ctx)
  1009. {
  1010. auto it = Partitions.find(ev->Get()->Partition);
  1011. Y_ABORT_UNLESS(it != Partitions.end());
  1012. const TString& group = ev->Get()->LabeledCounters.GetGroup();
  1013. it->second.LabeledCounters[group] = ev->Get()->LabeledCounters;
  1014. Y_UNUSED(ctx);
  1015. // if uncommented, all changes will be reported immediatly
  1016. // AggregateAndSendLabeledCountersFor(group, ctx);
  1017. }
  1018. void TPersQueue::Handle(TEvPQ::TEvPartitionLabeledCountersDrop::TPtr& ev, const TActorContext& ctx)
  1019. {
  1020. auto it = Partitions.find(ev->Get()->Partition);
  1021. Y_ABORT_UNLESS(it != Partitions.end());
  1022. const TString& group = ev->Get()->Group;
  1023. auto jt = it->second.LabeledCounters.find(group);
  1024. if (jt != it->second.LabeledCounters.end())
  1025. jt->second.SetDrop();
  1026. Y_UNUSED(ctx);
  1027. // if uncommented, all changes will be reported immediatly
  1028. // AggregateAndSendLabeledCountersFor(group, ctx);
  1029. }
  1030. void TPersQueue::Handle(TEvPQ::TEvTabletCacheCounters::TPtr& ev, const TActorContext& ctx)
  1031. {
  1032. CacheCounters = ev->Get()->Counters;
  1033. SetCacheCounters(CacheCounters);
  1034. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " topic '" << (TopicConverter ? TopicConverter->GetClientsideName() : "Undefined")
  1035. << "Counters. CacheSize " << CacheCounters.CacheSizeBytes << " CachedBlobs " << CacheCounters.CacheSizeBlobs);
  1036. }
  1037. void TPersQueue::Handle(TEvPQ::TEvInitComplete::TPtr& ev, const TActorContext& ctx)
  1038. {
  1039. const auto partitionId = ev->Get()->Partition;
  1040. auto it = Partitions.find(partitionId);
  1041. Y_ABORT_UNLESS(it != Partitions.end());
  1042. Y_ABORT_UNLESS(!it->second.InitDone);
  1043. it->second.InitDone = true;
  1044. ++PartitionsInited;
  1045. Y_ABORT_UNLESS(ConfigInited);//partitions are inited only after config
  1046. auto allInitialized = PartitionsInited == Partitions.size();
  1047. if (!InitCompleted && allInitialized) {
  1048. OnInitComplete(ctx);
  1049. }
  1050. if (NewConfigShouldBeApplied && allInitialized) {
  1051. ApplyNewConfigAndReply(ctx);
  1052. }
  1053. ProcessSourceIdRequests(partitionId);
  1054. if (allInitialized) {
  1055. SourceIdRequests.clear();
  1056. }
  1057. }
  1058. void TPersQueue::Handle(TEvPQ::TEvError::TPtr& ev, const TActorContext& ctx)
  1059. {
  1060. auto it = ResponseProxy.find(ev->Get()->Cookie);
  1061. if (it == ResponseProxy.end())
  1062. return;
  1063. bool res = it->second->HandleError(ev->Get(), ctx);
  1064. if (res) {
  1065. FinishResponse(it);
  1066. }
  1067. }
  1068. void TPersQueue::Handle(TEvPQ::TEvProxyResponse::TPtr& ev, const TActorContext& ctx)
  1069. {
  1070. auto it = ResponseProxy.find(ev->Get()->Cookie);
  1071. if (it == ResponseProxy.end()) { //response for already closed proxy
  1072. return;
  1073. }
  1074. bool res = it->second->HandleProxyResponse(ev, ctx);
  1075. if (res) {
  1076. FinishResponse(it);
  1077. }
  1078. }
  1079. void TPersQueue::FinishResponse(THashMap<ui64, TAutoPtr<TResponseBuilder>>::iterator it)
  1080. {
  1081. // ctx.Send(Tablet, new TEvPQ::TEvCompleteResponse(Sender, CounterId, , Response.Release()));
  1082. Counters->Percentile()[it->second->CounterId].IncrementFor((TAppData::TimeProvider->Now() - it->second->Timestamp).MilliSeconds());
  1083. ResponseProxy.erase(it);
  1084. Counters->Simple()[COUNTER_PQ_TABLET_INFLIGHT].Set(ResponseProxy.size());
  1085. }
  1086. void TPersQueue::Handle(TEvPersQueue::TEvUpdateConfig::TPtr& ev, const TActorContext& ctx)
  1087. {
  1088. if (!ConfigInited) {
  1089. UpdateConfigRequests.emplace_back(ev->Release(), ev->Sender);
  1090. return;
  1091. }
  1092. ProcessUpdateConfigRequest(ev->Release(), ev->Sender, ctx);
  1093. }
  1094. void TPersQueue::Handle(TEvPQ::TEvPartitionConfigChanged::TPtr&, const TActorContext& ctx)
  1095. {
  1096. Y_ABORT_UNLESS(ChangePartitionConfigInflight > 0);
  1097. --ChangePartitionConfigInflight;
  1098. TrySendUpdateConfigResponses(ctx);
  1099. }
  1100. void TPersQueue::TrySendUpdateConfigResponses(const TActorContext& ctx)
  1101. {
  1102. if (ChangePartitionConfigInflight) {
  1103. return;
  1104. }
  1105. for (auto& p : ChangeConfigNotification) {
  1106. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1107. << " Config applied version " << Config.GetVersion() << " actor " << p.Actor
  1108. << " txId " << p.TxId << " config:\n" << Config.DebugString());
  1109. THolder<TEvPersQueue::TEvUpdateConfigResponse> res{new TEvPersQueue::TEvUpdateConfigResponse};
  1110. res->Record.SetStatus(NKikimrPQ::OK);
  1111. res->Record.SetTxId(p.TxId);
  1112. res->Record.SetOrigin(TabletID());
  1113. ctx.Send(p.Actor, res.Release());
  1114. }
  1115. ChangeConfigNotification.clear();
  1116. }
  1117. void TPersQueue::CreateTopicConverter(const NKikimrPQ::TPQTabletConfig& config,
  1118. NPersQueue::TConverterFactoryPtr& converterFactory,
  1119. NPersQueue::TTopicConverterPtr& topicConverter,
  1120. const TActorContext& ctx)
  1121. {
  1122. auto& pqConfig = AppData(ctx)->PQConfig;
  1123. converterFactory =
  1124. std::make_shared<NPersQueue::TTopicNamesConverterFactory>(pqConfig,
  1125. "",
  1126. config.GetLocalDC());
  1127. topicConverter = converterFactory->MakeTopicConverter(config);
  1128. Y_ABORT_UNLESS(topicConverter);
  1129. Y_ABORT_UNLESS(topicConverter->IsValid(), "%s", topicConverter->GetReason().c_str());
  1130. }
  1131. void TPersQueue::ProcessUpdateConfigRequest(TAutoPtr<TEvPersQueue::TEvUpdateConfig> ev, const TActorId& sender, const TActorContext& ctx)
  1132. {
  1133. auto& record = ev->Record;
  1134. int oldConfigVersion = Config.HasVersion() ? Config.GetVersion() : -1;
  1135. int newConfigVersion = NewConfig.HasVersion() ? NewConfig.GetVersion() : oldConfigVersion;
  1136. Y_ABORT_UNLESS(newConfigVersion >= oldConfigVersion);
  1137. NKikimrPQ::TPQTabletConfig cfg = record.GetTabletConfig();
  1138. Y_ABORT_UNLESS(cfg.HasVersion());
  1139. int curConfigVersion = cfg.GetVersion();
  1140. if (curConfigVersion == oldConfigVersion) { //already applied
  1141. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1142. << " Config already applied version " << Config.GetVersion() << " actor " << sender
  1143. << " txId " << record.GetTxId() << " config:\n" << cfg.DebugString());
  1144. THolder<TEvPersQueue::TEvUpdateConfigResponse> res{new TEvPersQueue::TEvUpdateConfigResponse};
  1145. res->Record.SetStatus(NKikimrPQ::OK);
  1146. res->Record.SetTxId(record.GetTxId());
  1147. res->Record.SetOrigin(TabletID());
  1148. ctx.Send(sender, res.Release());
  1149. return;
  1150. }
  1151. if (curConfigVersion < newConfigVersion) { //Version must increase
  1152. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1153. << " Config has too small version " << curConfigVersion << " actual " << newConfigVersion << " actor " << sender
  1154. << " txId " << record.GetTxId() << " config:\n" << cfg.DebugString());
  1155. THolder<TEvPersQueue::TEvUpdateConfigResponse> res{new TEvPersQueue::TEvUpdateConfigResponse};
  1156. res->Record.SetStatus(NKikimrPQ::ERROR_BAD_VERSION);
  1157. res->Record.SetTxId(record.GetTxId());
  1158. res->Record.SetOrigin(TabletID());
  1159. ctx.Send(sender, res.Release());
  1160. return;
  1161. }
  1162. if (curConfigVersion == newConfigVersion) { //nothing to change, will be answered on cfg write from prev step
  1163. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1164. << " Config update version " << newConfigVersion << " is already in progress actor " << sender
  1165. << " txId " << record.GetTxId() << " config:\n" << cfg.DebugString());
  1166. ChangeConfigNotification.insert(TChangeNotification(sender, record.GetTxId()));
  1167. return;
  1168. }
  1169. if (curConfigVersion > newConfigVersion && NewConfig.HasVersion()) { //already in progress with older version
  1170. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1171. << " Config version " << curConfigVersion << " is too big, applying right now version " << newConfigVersion
  1172. << " actor " << sender
  1173. << " txId " << record.GetTxId() << " config:\n" << cfg.DebugString());
  1174. THolder<TEvPersQueue::TEvUpdateConfigResponse> res{new TEvPersQueue::TEvUpdateConfigResponse};
  1175. res->Record.SetStatus(NKikimrPQ::ERROR_UPDATE_IN_PROGRESS);
  1176. res->Record.SetTxId(record.GetTxId());
  1177. res->Record.SetOrigin(TabletID());
  1178. ctx.Send(sender, res.Release());
  1179. return;
  1180. }
  1181. const auto& bootstrapCfg = record.GetBootstrapConfig();
  1182. if (bootstrapCfg.ExplicitMessageGroupsSize() && !AppData(ctx)->PQConfig.GetEnableProtoSourceIdInfo()) {
  1183. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1184. << ": cannot apply explicit message groups unless proto source id enabled"
  1185. << ", actor " << sender
  1186. << ", txId " << record.GetTxId());
  1187. THolder<TEvPersQueue::TEvUpdateConfigResponse> res{new TEvPersQueue::TEvUpdateConfigResponse};
  1188. res->Record.SetStatus(NKikimrPQ::ERROR);
  1189. res->Record.SetTxId(record.GetTxId());
  1190. res->Record.SetOrigin(TabletID());
  1191. ctx.Send(sender, res.Release());
  1192. return;
  1193. }
  1194. for (const auto& mg : bootstrapCfg.GetExplicitMessageGroups()) {
  1195. TString error;
  1196. if (!mg.HasId() || mg.GetId().empty()) {
  1197. error = "Empty Id";
  1198. } else if (mg.GetId().size() > MAX_SOURCE_ID_LENGTH) {
  1199. error = "Too long Id";
  1200. } else if (mg.HasKeyRange() && !cfg.PartitionKeySchemaSize()) {
  1201. error = "Missing KeySchema";
  1202. }
  1203. if (error) {
  1204. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1205. << "Cannot apply explicit message group: " << error
  1206. << " actor " << sender
  1207. << " txId " << record.GetTxId());
  1208. THolder<TEvPersQueue::TEvUpdateConfigResponse> res{new TEvPersQueue::TEvUpdateConfigResponse};
  1209. res->Record.SetStatus(NKikimrPQ::ERROR);
  1210. res->Record.SetTxId(record.GetTxId());
  1211. res->Record.SetOrigin(TabletID());
  1212. ctx.Send(sender, res.Release());
  1213. return;
  1214. }
  1215. }
  1216. ChangeConfigNotification.insert(TChangeNotification(sender, record.GetTxId()));
  1217. if (!cfg.HasPartitionConfig())
  1218. cfg.MutablePartitionConfig()->CopyFrom(Config.GetPartitionConfig());
  1219. if (!cfg.HasCacheSize() && Config.HasCacheSize()) //if not set and it is alter - preserve old cache size
  1220. cfg.SetCacheSize(Config.GetCacheSize());
  1221. // set rr generation for provided read rules
  1222. {
  1223. THashMap<TString, std::pair<ui64, ui64>> existed; // map name -> rrVersion, rrGeneration
  1224. for (ui32 i = 0; i < Config.ReadRulesSize(); ++i) {
  1225. auto version = i < Config.ReadRuleVersionsSize() ? Config.GetReadRuleVersions(i) : 0;
  1226. auto generation = i < Config.ReadRuleGenerationsSize() ? Config.GetReadRuleGenerations(i) : 0;
  1227. existed[Config.GetReadRules(i)] = std::make_pair(version, generation);
  1228. }
  1229. for (ui32 i = 0; i < cfg.ReadRulesSize(); ++i) {
  1230. auto version = i < cfg.ReadRuleVersionsSize() ? cfg.GetReadRuleVersions(i) : 0;
  1231. auto it = existed.find(cfg.GetReadRules(i));
  1232. ui64 generation = 0;
  1233. if (it != existed.end() && it->second.first == version) {
  1234. generation = it->second.second;
  1235. } else {
  1236. generation = curConfigVersion;
  1237. }
  1238. cfg.AddReadRuleGenerations(generation);
  1239. }
  1240. }
  1241. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID()
  1242. << " Config update version " << cfg.GetVersion() << "(current " << Config.GetVersion() << ") received from actor " << sender
  1243. << " txId " << record.GetTxId() << " config:\n" << cfg.DebugString());
  1244. TString str;
  1245. Y_ABORT_UNLESS(CheckPersQueueConfig(cfg, true, &str), "%s", str.c_str());
  1246. BeginWriteConfig(cfg, bootstrapCfg, ctx);
  1247. NewConfig = cfg;
  1248. }
  1249. void TPersQueue::BeginWriteConfig(const NKikimrPQ::TPQTabletConfig& cfg,
  1250. const NKikimrPQ::TBootstrapConfig& bootstrapCfg,
  1251. const TActorContext& ctx)
  1252. {
  1253. TAutoPtr<TEvKeyValue::TEvRequest> request(new TEvKeyValue::TEvRequest);
  1254. request->Record.SetCookie(WRITE_CONFIG_COOKIE);
  1255. AddCmdWriteConfig(request.Get(),
  1256. cfg,
  1257. bootstrapCfg,
  1258. ctx);
  1259. Y_ABORT_UNLESS((ui64)request->Record.GetCmdWrite().size() == (ui64)bootstrapCfg.GetExplicitMessageGroups().size() * cfg.PartitionsSize() + 1);
  1260. ctx.Send(ctx.SelfID, request.Release());
  1261. }
  1262. void TPersQueue::AddCmdWriteConfig(TEvKeyValue::TEvRequest* request,
  1263. const NKikimrPQ::TPQTabletConfig& cfg,
  1264. const NKikimrPQ::TBootstrapConfig& bootstrapCfg,
  1265. const TActorContext& ctx)
  1266. {
  1267. Y_ABORT_UNLESS(request);
  1268. TString str;
  1269. Y_ABORT_UNLESS(cfg.SerializeToString(&str));
  1270. auto write = request->Record.AddCmdWrite();
  1271. write->SetKey(KeyConfig());
  1272. write->SetValue(str);
  1273. write->SetTactic(AppData(ctx)->PQConfig.GetTactic());
  1274. TSourceIdWriter sourceIdWriter(ESourceIdFormat::Proto);
  1275. for (const auto& mg : bootstrapCfg.GetExplicitMessageGroups()) {
  1276. TMaybe<TPartitionKeyRange> keyRange;
  1277. if (mg.HasKeyRange()) {
  1278. keyRange = TPartitionKeyRange::Parse(mg.GetKeyRange());
  1279. }
  1280. sourceIdWriter.RegisterSourceId(mg.GetId(), 0, 0, ctx.Now(), std::move(keyRange));
  1281. }
  1282. for (const auto& partition : cfg.GetPartitions()) {
  1283. sourceIdWriter.FillRequest(request, partition.GetPartitionId());
  1284. }
  1285. }
  1286. void TPersQueue::ClearNewConfig()
  1287. {
  1288. NewConfigShouldBeApplied = false;
  1289. NewConfig.Clear();
  1290. }
  1291. void TPersQueue::Handle(TEvPersQueue::TEvDropTablet::TPtr& ev, const TActorContext& ctx)
  1292. {
  1293. auto& record = ev->Get()->Record;
  1294. ui64 txId = record.GetTxId();
  1295. TChangeNotification stateRequest(ev->Sender, txId);
  1296. NKikimrPQ::ETabletState reqState = record.GetRequestedState();
  1297. if (reqState == NKikimrPQ::ENormal) {
  1298. ReturnTabletState(ctx, stateRequest, NKikimrProto::ERROR);
  1299. return;
  1300. }
  1301. Y_ABORT_UNLESS(reqState == NKikimrPQ::EDropped);
  1302. TabletStateRequests.insert(stateRequest);
  1303. if (TabletStateRequests.size() > 1) {
  1304. return; // already writing, just enqueue
  1305. }
  1306. BeginWriteTabletState(ctx, reqState);
  1307. }
  1308. void TPersQueue::Handle(TEvPersQueue::TEvOffsets::TPtr& ev, const TActorContext& ctx)
  1309. {
  1310. if (!ConfigInited) {
  1311. THolder<TEvPersQueue::TEvOffsetsResponse> res = MakeHolder<TEvPersQueue::TEvOffsetsResponse>();
  1312. auto& resp = res->Record;
  1313. resp.SetTabletId(TabletID());
  1314. ctx.Send(ev->Sender, res.Release());
  1315. return;
  1316. }
  1317. ui32 cnt = 0;
  1318. for (auto& p : Partitions) {
  1319. cnt += p.second.InitDone;
  1320. }
  1321. TActorId ans = CreateOffsetsProxyActor(TabletID(), ev->Sender, cnt, ctx);
  1322. for (auto& p : Partitions) {
  1323. if (!p.second.InitDone)
  1324. continue;
  1325. THolder<TEvPQ::TEvPartitionOffsets> event = MakeHolder<TEvPQ::TEvPartitionOffsets>(ans, ev->Get()->Record.HasClientId() ?
  1326. ev->Get()->Record.GetClientId() : "");
  1327. ctx.Send(p.second.Actor, event.Release());
  1328. }
  1329. }
  1330. void TPersQueue::Handle(TEvPersQueue::TEvHasDataInfo::TPtr& ev, const TActorContext& ctx)
  1331. {
  1332. auto& record = ev->Get()->Record;
  1333. ActorIdToProto(ev->Sender, record.MutableSender());
  1334. if (!ConfigInited) {
  1335. HasDataRequests.push_back(ev->Release());
  1336. } else {
  1337. auto it = Partitions.find(record.GetPartition());
  1338. if (it != Partitions.end()) {
  1339. ctx.Send(it->second.Actor, ev->Release().Release());
  1340. }
  1341. }
  1342. }
  1343. void TPersQueue::Handle(TEvPersQueue::TEvPartitionClientInfo::TPtr& ev, const TActorContext& ctx) {
  1344. for (auto partition : ev->Get()->Record.GetPartitions()) {
  1345. auto it = Partitions.find(partition);
  1346. if (it != Partitions.end()) {
  1347. ctx.Send(it->second.Actor, new TEvPQ::TEvGetPartitionClientInfo(ev->Sender), 0, ev->Cookie);
  1348. } else {
  1349. THolder<TEvPersQueue::TEvPartitionClientInfoResponse> clientInfo = MakeHolder<TEvPersQueue::TEvPartitionClientInfoResponse>();
  1350. clientInfo->Record.SetPartition(partition);
  1351. ctx.Send(ev->Sender, clientInfo.Release(), 0, ev->Cookie);
  1352. }
  1353. }
  1354. }
  1355. void TPersQueue::Handle(TEvPersQueue::TEvStatus::TPtr& ev, const TActorContext& ctx)
  1356. {
  1357. if (!ConfigInited) {
  1358. THolder<TEvPersQueue::TEvStatusResponse> res = MakeHolder<TEvPersQueue::TEvStatusResponse>();
  1359. auto& resp = res->Record;
  1360. resp.SetTabletId(TabletID());
  1361. ctx.Send(ev->Sender, res.Release());
  1362. return;
  1363. }
  1364. ui32 cnt = 0;
  1365. for (auto& p : Partitions) {
  1366. cnt += p.second.InitDone;
  1367. }
  1368. TActorId ans = CreateStatusProxyActor(TabletID(), ev->Sender, cnt, ev->Cookie, ctx);
  1369. for (auto& p : Partitions) {
  1370. if (!p.second.InitDone)
  1371. continue;
  1372. THolder<TEvPQ::TEvPartitionStatus> event;
  1373. if (ev->Get()->Record.GetConsumers().empty()) {
  1374. event = MakeHolder<TEvPQ::TEvPartitionStatus>(ans, ev->Get()->Record.HasClientId() ? ev->Get()->Record.GetClientId() : "",
  1375. ev->Get()->Record.HasGetStatForAllConsumers() ? ev->Get()->Record.GetGetStatForAllConsumers() : false);
  1376. } else {
  1377. TVector<TString> consumers;
  1378. for (auto consumer : ev->Get()->Record.GetConsumers()) {
  1379. consumers.emplace_back(consumer);
  1380. }
  1381. event = MakeHolder<TEvPQ::TEvPartitionStatus>(ans, consumers);
  1382. }
  1383. ctx.Send(p.second.Actor, event.Release());
  1384. }
  1385. }
  1386. void TPersQueue::InitResponseBuilder(const ui64 responseCookie, const ui32 count, const ui32 counterId)
  1387. {
  1388. auto it = ResponseProxy.find(responseCookie);
  1389. Y_ABORT_UNLESS(it != ResponseProxy.end());
  1390. it->second->AddPartialReplyCount(count);
  1391. it->second->SetCounterId(counterId);
  1392. }
  1393. void TPersQueue::HandleGetMaxSeqNoRequest(const ui64 responseCookie, const TActorId& partActor,
  1394. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1395. {
  1396. Y_ABORT_UNLESS(req.HasCmdGetMaxSeqNo());
  1397. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_GET_MAX_SEQ_NO);
  1398. const auto& cmd = req.GetCmdGetMaxSeqNo();
  1399. TVector<TString> ids;
  1400. ids.reserve(cmd.SourceIdSize());
  1401. for (ui32 i = 0; i < cmd.SourceIdSize(); ++i)
  1402. ids.push_back(cmd.GetSourceId(i));
  1403. THolder<TEvPQ::TEvGetMaxSeqNoRequest> event = MakeHolder<TEvPQ::TEvGetMaxSeqNoRequest>(responseCookie, ids);
  1404. ctx.Send(partActor, event.Release());
  1405. }
  1406. void TPersQueue::HandleDeleteSessionRequest(
  1407. const ui64 responseCookie, const TActorId& partActor,
  1408. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1409. const TActorId& pipeClient, const TActorId&
  1410. )
  1411. {
  1412. Y_ABORT_UNLESS(req.HasCmdDeleteSession());
  1413. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_DELETE_SESSION);
  1414. const auto& cmd = req.GetCmdDeleteSession();
  1415. //To do : priority
  1416. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Got cmd delete session: " << cmd.DebugString());
  1417. if (!cmd.HasClientId()){
  1418. return ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1419. TStringBuilder() << "no clientId in DeleteSession request: " << ToString(req).data());
  1420. } else if (!cmd.HasSessionId()) {
  1421. return ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1422. TStringBuilder() << "not sessionId in DeleteSession request: " << ToString(req).data());
  1423. } else {
  1424. THolder<TEvPQ::TEvSetClientInfo> event = MakeHolder<TEvPQ::TEvSetClientInfo>(
  1425. responseCookie, cmd.GetClientId(), 0, cmd.GetSessionId(), 0, 0, 0, pipeClient,
  1426. TEvPQ::TEvSetClientInfo::ESCI_DROP_SESSION
  1427. );
  1428. ctx.Send(partActor, event.Release());
  1429. }
  1430. auto pipe = PipesInfo.find(pipeClient);
  1431. if (!pipe.IsEnd()) {
  1432. DestroySession(pipe->second);
  1433. }
  1434. }
  1435. void TPersQueue::HandleCreateSessionRequest(const ui64 responseCookie, const TActorId& partActor,
  1436. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1437. const TActorId& pipeClient, const TActorId&
  1438. ) {
  1439. Y_ABORT_UNLESS(req.HasCmdCreateSession());
  1440. const auto& cmd = req.GetCmdCreateSession();
  1441. if (!cmd.HasClientId()){
  1442. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1443. TStringBuilder() << "no clientId in CreateSession request: " << ToString(req).data());
  1444. } else if (!cmd.HasSessionId()) {
  1445. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1446. TStringBuilder() << "not sessionId in CreateSession request: " << ToString(req).data());
  1447. } else if (!cmd.HasGeneration()) {
  1448. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1449. TStringBuilder() << "not geneartion in CreateSession request: " << ToString(req).data());
  1450. } else if (!cmd.HasStep()) {
  1451. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1452. TStringBuilder() << "not step in CreateSession request: " << ToString(req).data());
  1453. } else {
  1454. bool isDirectRead = cmd.GetPartitionSessionId() > 0;
  1455. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_CREATE_SESSION);
  1456. THolder<TEvPQ::TEvSetClientInfo> event = MakeHolder<TEvPQ::TEvSetClientInfo>(
  1457. responseCookie, cmd.GetClientId(), 0, cmd.GetSessionId(), cmd.GetPartitionSessionId(), cmd.GetGeneration(), cmd.GetStep(),
  1458. pipeClient, TEvPQ::TEvSetClientInfo::ESCI_CREATE_SESSION, 0, false
  1459. );
  1460. if (isDirectRead) {
  1461. auto pipeIter = PipesInfo.find(pipeClient);
  1462. if (pipeIter.IsEnd()) {
  1463. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::ERROR,
  1464. TStringBuilder() << "Internal error - server pipe " << pipeClient.ToString() << " not found");
  1465. return;
  1466. }
  1467. pipeIter->second.ClientId = cmd.GetClientId();
  1468. pipeIter->second.SessionId = cmd.GetSessionId();
  1469. pipeIter->second.PartitionSessionId = cmd.GetPartitionSessionId();
  1470. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Created session " << cmd.GetSessionId() << " on pipe: " << pipeIter->first.ToString());
  1471. ctx.Send(MakePQDReadCacheServiceActorId(),
  1472. new TEvPQ::TEvRegisterDirectReadSession(
  1473. TReadSessionKey{cmd.GetSessionId(), cmd.GetPartitionSessionId()},
  1474. GetGeneration()
  1475. )
  1476. );
  1477. }
  1478. ctx.Send(partActor, event.Release());
  1479. }
  1480. }
  1481. void TPersQueue::HandleSetClientOffsetRequest(const ui64 responseCookie, const TActorId& partActor,
  1482. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1483. {
  1484. Y_ABORT_UNLESS(req.HasCmdSetClientOffset());
  1485. const auto& cmd = req.GetCmdSetClientOffset();
  1486. if (!cmd.HasClientId()) {
  1487. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1488. TStringBuilder() << "no clientId in SetClientOffset request: " << ToString(req).data());
  1489. } else if (!cmd.HasOffset()) {
  1490. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1491. TStringBuilder() << "no offset in SetClientOffset request: " << ToString(req).data());
  1492. } else if (cmd.GetOffset() < 0) {
  1493. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1494. TStringBuilder() << "negative offset in SetClientOffset request: " << ToString(req).data());
  1495. } else {
  1496. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_SET_OFFSET);
  1497. THolder<TEvPQ::TEvSetClientInfo> event = MakeHolder<TEvPQ::TEvSetClientInfo>(
  1498. responseCookie, cmd.GetClientId(), cmd.GetOffset(), cmd.HasSessionId() ? cmd.GetSessionId() : "", 0, 0, 0,
  1499. TActorId{}, TEvPQ::TEvSetClientInfo::ESCI_OFFSET, 0, cmd.GetStrict()
  1500. );
  1501. ctx.Send(partActor, event.Release());
  1502. }
  1503. }
  1504. void TPersQueue::HandleGetClientOffsetRequest(const ui64 responseCookie, const TActorId& partActor,
  1505. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1506. {
  1507. Y_ABORT_UNLESS(req.HasCmdGetClientOffset());
  1508. const auto& cmd = req.GetCmdGetClientOffset();
  1509. if (!cmd.HasClientId() || cmd.GetClientId().empty()) {
  1510. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1511. TStringBuilder() << "no clientId in GetClientOffset request: " << ToString(req).data());
  1512. } else {
  1513. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_GET_OFFSET);
  1514. THolder<TEvPQ::TEvGetClientOffset> event = MakeHolder<TEvPQ::TEvGetClientOffset>(responseCookie, cmd.GetClientId());
  1515. ctx.Send(partActor, event.Release());
  1516. }
  1517. }
  1518. void TPersQueue::HandleUpdateWriteTimestampRequest(const ui64 responseCookie, const TActorId& partActor,
  1519. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1520. {
  1521. Y_ABORT_UNLESS(req.HasCmdUpdateWriteTimestamp());
  1522. const auto& cmd = req.GetCmdUpdateWriteTimestamp();
  1523. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_GET_OFFSET);
  1524. THolder<TEvPQ::TEvUpdateWriteTimestamp> event = MakeHolder<TEvPQ::TEvUpdateWriteTimestamp>(responseCookie, cmd.GetWriteTimeMS());
  1525. ctx.Send(partActor, event.Release());
  1526. }
  1527. void TPersQueue::HandleWriteRequest(const ui64 responseCookie, const TActorId& partActor,
  1528. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1529. {
  1530. Y_ABORT_UNLESS(req.CmdWriteSize());
  1531. MeteringSink.MayFlush(ctx.Now()); // To ensure hours' border;
  1532. if (Config.GetMeteringMode() != NKikimrPQ::TPQTabletConfig::METERING_MODE_REQUEST_UNITS) {
  1533. MeteringSink.IncreaseQuantity(EMeteringJson::PutEventsV1, req.HasPutUnitsSize() ? req.GetPutUnitsSize() : 0);
  1534. }
  1535. TVector <TEvPQ::TEvWrite::TMsg> msgs;
  1536. bool mirroredPartition = Config.GetPartitionConfig().HasMirrorFrom();
  1537. if (!req.GetIsDirectWrite()) {
  1538. if (!req.HasMessageNo()) {
  1539. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1540. "MessageNo must be set for writes");
  1541. return;
  1542. }
  1543. if (!mirroredPartition && !req.HasOwnerCookie()) {
  1544. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1545. "OwnerCookie must be set for writes");
  1546. return;
  1547. }
  1548. }
  1549. if (req.HasCmdWriteOffset() && req.GetCmdWriteOffset() < 0) {
  1550. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1551. "CmdWriteOffset can't be negative");
  1552. return;
  1553. }
  1554. if (req.HasWriteId()) {
  1555. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  1556. "Tablet " << TabletID() <<
  1557. " Write in transaction." <<
  1558. " Partition: " << req.GetPartition() <<
  1559. ", WriteId: " << req.GetWriteId());
  1560. }
  1561. for (ui32 i = 0; i < req.CmdWriteSize(); ++i) {
  1562. const auto& cmd = req.GetCmdWrite(i);
  1563. if (AppData(ctx)->Counters && !AppData(ctx)->PQConfig.GetTopicsAreFirstClassCitizen()) {
  1564. auto counters = AppData(ctx)->Counters;
  1565. TString clientDC = to_lower(cmd.HasClientDC() ? cmd.GetClientDC() : "unknown");
  1566. clientDC.to_title();
  1567. auto it = BytesWrittenFromDC.find(clientDC);
  1568. if (it == BytesWrittenFromDC.end()) {
  1569. auto labels = NPersQueue::GetLabelsForCustomCluster(TopicConverter, clientDC);
  1570. if (!labels.empty()) {
  1571. labels.pop_back();
  1572. }
  1573. it = BytesWrittenFromDC.emplace(clientDC, NKikimr::NPQ::TMultiCounter(GetServiceCounters(counters, "pqproxy|writeSession"),
  1574. labels, {{"ClientDC", clientDC}}, {"BytesWrittenFromDC"}, true)).first;
  1575. }
  1576. if (it != BytesWrittenFromDC.end())
  1577. it->second.Inc(cmd.ByteSize());
  1578. }
  1579. TString errorStr = "";
  1580. if (!cmd.HasSeqNo() && !req.GetIsDirectWrite()) {
  1581. errorStr = "no SeqNo";
  1582. } else if (cmd.HasData() && cmd.HasHeartbeat()) {
  1583. errorStr = "Data and Heartbeat are mutually exclusive";
  1584. } else if (cmd.GetData().empty() && cmd.GetHeartbeat().GetData().empty()) {
  1585. errorStr = "empty Data";
  1586. } else if ((!cmd.HasSourceId() || cmd.GetSourceId().empty()) && !req.GetIsDirectWrite() && !cmd.GetDisableDeduplication()) {
  1587. errorStr = "empty SourceId";
  1588. } else if (cmd.GetPartitionKey().size() > 256) {
  1589. errorStr = "too long partition key";
  1590. } else if (cmd.GetSeqNo() < 0) {
  1591. errorStr = "SeqNo must be >= 0";
  1592. } else if (cmd.HasPartNo() && (cmd.GetPartNo() < 0 || cmd.GetPartNo() >= Max<ui16>())) {
  1593. errorStr = "PartNo must be >= 0 and < 65535";
  1594. } else if (cmd.HasPartNo() != cmd.HasTotalParts()) {
  1595. errorStr = "PartNo and TotalParts must be filled together";
  1596. } else if (cmd.HasTotalParts() && (cmd.GetTotalParts() <= cmd.GetPartNo() || cmd.GetTotalParts() <= 1 || cmd.GetTotalParts() > Max<ui16>())) {
  1597. errorStr = "TotalParts must be > PartNo and > 1 and < 65536";
  1598. } else if (cmd.HasPartNo() && cmd.GetPartNo() == 0 && !cmd.HasTotalSize()) {
  1599. errorStr = "TotalSize must be filled for first part";
  1600. } else if (cmd.HasTotalSize() && static_cast<size_t>(cmd.GetTotalSize()) <= cmd.GetData().size()) { // TotalSize must be > size of each part
  1601. errorStr = "TotalSize is incorrect";
  1602. } else if (cmd.HasSourceId() && !cmd.GetSourceId().empty() && NPQ::NSourceIdEncoding::Decode(cmd.GetSourceId()).length() > MAX_SOURCE_ID_LENGTH) {
  1603. errorStr = "Too big SourceId";
  1604. } else if (mirroredPartition && !cmd.GetDisableDeduplication()) {
  1605. errorStr = "Write to mirrored topic is forbiden";
  1606. } else if (cmd.HasHeartbeat() && cmd.GetHeartbeat().GetData().size() > MAX_HEARTBEAT_SIZE) {
  1607. errorStr = "Too big Heartbeat";
  1608. } else if (cmd.HasHeartbeat() && cmd.HasTotalParts() && cmd.GetTotalParts() != 1) {
  1609. errorStr = "Heartbeat must be a single-part message";
  1610. }
  1611. ui64 createTimestampMs = 0, writeTimestampMs = 0;
  1612. if (cmd.HasCreateTimeMS() && cmd.GetCreateTimeMS() >= 0)
  1613. createTimestampMs = cmd.GetCreateTimeMS();
  1614. if (cmd.HasWriteTimeMS() && cmd.GetWriteTimeMS() > 0) {
  1615. writeTimestampMs = cmd.GetWriteTimeMS();
  1616. if (!cmd.GetDisableDeduplication()) {
  1617. errorStr = "WriteTimestamp avail only without deduplication";
  1618. }
  1619. }
  1620. if (!errorStr.empty()) {
  1621. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, errorStr);
  1622. return;
  1623. }
  1624. ui32 mSize = MAX_BLOB_PART_SIZE - cmd.GetSourceId().size() - sizeof(ui32) - TClientBlob::OVERHEAD; //megaqc - remove this
  1625. Y_ABORT_UNLESS(mSize > 204800);
  1626. ui64 receiveTimestampMs = TAppData::TimeProvider->Now().MilliSeconds();
  1627. bool disableDeduplication = cmd.GetDisableDeduplication();
  1628. std::optional<TRowVersion> heartbeatVersion;
  1629. if (cmd.HasHeartbeat()) {
  1630. heartbeatVersion.emplace(cmd.GetHeartbeat().GetStep(), cmd.GetHeartbeat().GetTxId());
  1631. }
  1632. if (cmd.GetData().size() > mSize) {
  1633. if (cmd.HasPartNo()) {
  1634. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1635. TStringBuilder() << "Too big message while using PartNo; must be at most " << mSize << ", but got " << cmd.GetData().size());
  1636. return;
  1637. }
  1638. auto it = ResponseProxy.find(responseCookie);
  1639. Y_ABORT_UNLESS(it != ResponseProxy.end());
  1640. it->second->SetWasSplit();
  1641. ui32 pos = 0;
  1642. ui16 partNo = 0;
  1643. ui32 totalSize = cmd.GetData().size();
  1644. ui16 totalParts = (totalSize - 1) / mSize + 1;
  1645. ui32 diff = 0;
  1646. ui32 lastPartSize = (totalSize - 1) % mSize + 1; // mSize for x*mSize , x for x (x < mSize)
  1647. ui32 uncompressedSize = cmd.HasUncompressedSize() ? cmd.GetUncompressedSize() : 0;
  1648. if (lastPartSize < 100) { //size of first part will be reduced by diff, => size of last part will be increased by diff => = 100 bytes
  1649. diff = 100 - lastPartSize;
  1650. }
  1651. Y_ABORT_UNLESS(!cmd.HasTotalParts(), "too big part"); //change this verify for errorStr, when LB will be ready
  1652. while (pos < totalSize) {
  1653. TString data = cmd.GetData().substr(pos, mSize - diff);
  1654. pos += mSize - diff;
  1655. diff = 0;
  1656. msgs.push_back({cmd.GetSourceId(), static_cast<ui64>(cmd.GetSeqNo()), partNo,
  1657. totalParts, totalSize, createTimestampMs, receiveTimestampMs,
  1658. disableDeduplication, writeTimestampMs, data, uncompressedSize,
  1659. cmd.GetPartitionKey(), cmd.GetExplicitHash(), cmd.GetExternalOperation(),
  1660. cmd.GetIgnoreQuotaDeadline(), heartbeatVersion
  1661. });
  1662. partNo++;
  1663. uncompressedSize = 0;
  1664. LOG_DEBUG_S(
  1665. ctx, NKikimrServices::PERSQUEUE,
  1666. "Tablet " << TabletID() <<
  1667. " got client PART message topic: " << (TopicConverter ? TopicConverter->GetClientsideName() : "Undefined") << " partition: " << req.GetPartition()
  1668. << " SourceId: \'" << EscapeC(msgs.back().SourceId) << "\' SeqNo: "
  1669. << msgs.back().SeqNo << " partNo : " << msgs.back().PartNo
  1670. << " messageNo: " << req.GetMessageNo() << " size: " << data.size()
  1671. );
  1672. }
  1673. Y_ABORT_UNLESS(partNo == totalParts);
  1674. } else if (cmd.GetHeartbeat().GetData().size() > mSize) {
  1675. Y_DEBUG_ABORT_UNLESS(false, "This should never happen");
  1676. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, TStringBuilder()
  1677. << "Too big heartbeat message, must be at most " << mSize << ", but got " << cmd.GetHeartbeat().GetData().size());
  1678. return;
  1679. } else {
  1680. ui32 totalSize = cmd.GetData().Size();
  1681. if (cmd.HasHeartbeat()) {
  1682. totalSize = cmd.GetHeartbeat().GetData().Size();
  1683. }
  1684. if (cmd.HasTotalSize()) {
  1685. totalSize = cmd.GetTotalSize();
  1686. }
  1687. const auto& data = cmd.HasHeartbeat()
  1688. ? cmd.GetHeartbeat().GetData()
  1689. : cmd.GetData();
  1690. msgs.push_back({cmd.GetSourceId(), static_cast<ui64>(cmd.GetSeqNo()), static_cast<ui16>(cmd.HasPartNo() ? cmd.GetPartNo() : 0),
  1691. static_cast<ui16>(cmd.HasPartNo() ? cmd.GetTotalParts() : 1), totalSize,
  1692. createTimestampMs, receiveTimestampMs, disableDeduplication, writeTimestampMs, data,
  1693. cmd.HasUncompressedSize() ? cmd.GetUncompressedSize() : 0u, cmd.GetPartitionKey(), cmd.GetExplicitHash(),
  1694. cmd.GetExternalOperation(), cmd.GetIgnoreQuotaDeadline(), heartbeatVersion
  1695. });
  1696. }
  1697. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  1698. "Tablet " << TabletID() <<
  1699. " got client message topic: " << (TopicConverter ? TopicConverter->GetClientsideName() : "Undefined") <<
  1700. " partition: " << req.GetPartition() <<
  1701. " SourceId: \'" << EscapeC(msgs.back().SourceId) <<
  1702. "\' SeqNo: " << msgs.back().SeqNo << " partNo : " << msgs.back().PartNo <<
  1703. " messageNo: " << req.GetMessageNo() << " size " << msgs.back().Data.size() <<
  1704. " offset: " << (req.HasCmdWriteOffset() ? (req.GetCmdWriteOffset() + i) : -1));
  1705. }
  1706. InitResponseBuilder(responseCookie, msgs.size(), COUNTER_LATENCY_PQ_WRITE);
  1707. THolder<TEvPQ::TEvWrite> event =
  1708. MakeHolder<TEvPQ::TEvWrite>(responseCookie, req.GetMessageNo(),
  1709. req.HasOwnerCookie() ? req.GetOwnerCookie() : "",
  1710. req.HasCmdWriteOffset() ? req.GetCmdWriteOffset() : TMaybe<ui64>(),
  1711. std::move(msgs), req.GetIsDirectWrite());
  1712. ctx.Send(partActor, event.Release());
  1713. }
  1714. void TPersQueue::HandleReserveBytesRequest(const ui64 responseCookie, const TActorId& partActor,
  1715. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1716. const TActorId& pipeClient, const TActorId&)
  1717. {
  1718. Y_ABORT_UNLESS(req.HasCmdReserveBytes());
  1719. auto it = PipesInfo.find(pipeClient);
  1720. if (it == PipesInfo.end()) {
  1721. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::ERROR,
  1722. TStringBuilder() << "pipe already dead: " << pipeClient);
  1723. return;
  1724. }
  1725. if (!req.HasMessageNo()) {
  1726. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, "MessageNo must be set for ReserveBytes request");
  1727. return;
  1728. }
  1729. if (!req.HasOwnerCookie()) {
  1730. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, "OwnerCookie must be set for ReserveBytes request");
  1731. return;
  1732. }
  1733. if (req.HasWriteId()) {
  1734. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  1735. "Tablet " << TabletID() <<
  1736. " Reserve bytes in transaction." <<
  1737. " Partition: " << req.GetPartition() <<
  1738. ", WriteId: " << req.GetWriteId());
  1739. }
  1740. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_RESERVE_BYTES);
  1741. THolder<TEvPQ::TEvReserveBytes> event = MakeHolder<TEvPQ::TEvReserveBytes>(responseCookie, req.GetCmdReserveBytes().GetSize(),
  1742. req.GetOwnerCookie(), req.GetMessageNo(), req.GetCmdReserveBytes().GetLastRequest());
  1743. ctx.Send(partActor, event.Release());
  1744. }
  1745. void TPersQueue::HandleGetOwnershipRequest(const ui64 responseCookie, const TActorId& partActor,
  1746. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1747. const TActorId& pipeClient, const TActorId& sender)
  1748. {
  1749. Y_ABORT_UNLESS(req.HasCmdGetOwnership());
  1750. const TString& owner = req.GetCmdGetOwnership().GetOwner();
  1751. if (owner.empty()) {
  1752. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1753. TStringBuilder() << "empty owner in CmdGetOwnership request");
  1754. return;
  1755. }
  1756. Y_ABORT_UNLESS(pipeClient != TActorId());
  1757. auto it = PipesInfo.find(pipeClient);
  1758. if (it == PipesInfo.end()) { //do nothing. this could not be happen, just in tests
  1759. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1760. TStringBuilder() << "request via dead pipe");
  1761. return;
  1762. }
  1763. it->second = TPipeInfo::ForOwner(partActor, owner, it->second.ServerActors);
  1764. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_GET_OWNERSHIP);
  1765. THolder<TEvPQ::TEvChangeOwner> event = MakeHolder<TEvPQ::TEvChangeOwner>(responseCookie, owner, pipeClient, sender, req.GetCmdGetOwnership().GetForce());
  1766. ctx.Send(partActor, event.Release());
  1767. }
  1768. void TPersQueue::HandleReadRequest(
  1769. const ui64 responseCookie, const TActorId& partActor,
  1770. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1771. const TActorId& pipeClient, const TActorId&
  1772. ) {
  1773. Y_ABORT_UNLESS(req.HasCmdRead());
  1774. auto cmd = req.GetCmdRead();
  1775. if (!cmd.HasOffset()) {
  1776. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1777. TStringBuilder() << "no offset in read request: " << ToString(req).data());
  1778. } else if (!cmd.HasClientId()) {
  1779. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1780. TStringBuilder() << "no clientId in read request: " << ToString(req).data());
  1781. } else if (cmd.HasCount() && cmd.GetCount() <= 0) {
  1782. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1783. TStringBuilder() << "invalid count in read request: " << ToString(req).data());
  1784. } else if (!cmd.HasOffset() || cmd.GetOffset() < 0) {
  1785. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1786. TStringBuilder() << "invalid offset in read request: " << ToString(req).data());
  1787. } else if (cmd.HasBytes() && cmd.GetBytes() <= 0) {
  1788. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1789. TStringBuilder() << "invalid bytes in read request: " << ToString(req).data());
  1790. } else if (cmd.HasTimeoutMs() && cmd.GetTimeoutMs() < 0) {
  1791. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1792. TStringBuilder() << "invalid timeout in read request: " << ToString(req).data());
  1793. } else if (cmd.HasTimeoutMs() && cmd.GetTimeoutMs() > 120000) {
  1794. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1795. TStringBuilder() << "invalid timeout in read request, must be less than 120 secs: " << ToString(req).data());
  1796. } else if (cmd.HasPartNo() && cmd.GetPartNo() < 0) {
  1797. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1798. TStringBuilder() << "invalid partNo in read request: " << ToString(req).data());
  1799. } else if (cmd.HasMaxTimeLagMs() && cmd.GetMaxTimeLagMs() < 0) {
  1800. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  1801. TStringBuilder() << "invalid maxTimeLagMs in read request: " << ToString(req).data());
  1802. } else {
  1803. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_READ);
  1804. ui32 count = cmd.HasCount() ? cmd.GetCount() : Max<ui32>();
  1805. ui32 bytes = Min<ui32>(MAX_BYTES, cmd.HasBytes() ? cmd.GetBytes() : MAX_BYTES);
  1806. auto clientDC = cmd.HasClientDC() ? to_lower(cmd.GetClientDC()) : "unknown";
  1807. clientDC.to_title();
  1808. if (IsDirectReadCmd(cmd)) {
  1809. auto pipeIter = PipesInfo.find(pipeClient);
  1810. if (pipeIter.IsEnd()) {
  1811. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::READ_ERROR_NO_SESSION,
  1812. TStringBuilder() << "Read prepare request from unknown(old?) pipe");
  1813. return;
  1814. } else if (cmd.GetSessionId().empty()) {
  1815. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::READ_ERROR_NO_SESSION,
  1816. TStringBuilder() << "Read prepare request with empty session id");
  1817. return;
  1818. } else if (pipeIter->second.SessionId != cmd.GetSessionId()) {
  1819. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::READ_ERROR_NO_SESSION,
  1820. TStringBuilder() << "Read prepare request with unknown(old?) session id " << cmd.GetSessionId());
  1821. return;
  1822. }
  1823. }
  1824. THolder<TEvPQ::TEvRead> event =
  1825. MakeHolder<TEvPQ::TEvRead>(responseCookie, cmd.GetOffset(), cmd.GetLastOffset(),
  1826. cmd.HasPartNo() ? cmd.GetPartNo() : 0,
  1827. count,
  1828. cmd.HasSessionId() ? cmd.GetSessionId() : "",
  1829. cmd.GetClientId(),
  1830. cmd.HasTimeoutMs() ? cmd.GetTimeoutMs() : 0, bytes,
  1831. cmd.HasMaxTimeLagMs() ? cmd.GetMaxTimeLagMs() : 0,
  1832. cmd.HasReadTimestampMs() ? cmd.GetReadTimestampMs() : 0, clientDC,
  1833. cmd.GetExternalOperation(),
  1834. pipeClient);
  1835. ctx.Send(partActor, event.Release());
  1836. }
  1837. }
  1838. template<class TRequest>
  1839. bool ValidateDirectReadRequestBase(
  1840. const TRequest& cmd, const THashMap<TActorId, TPersQueue::TPipeInfo>::iterator& pipeIter,
  1841. TStringBuilder& error, TDirectReadKey& key
  1842. ) {
  1843. key = TDirectReadKey{cmd.GetSessionKey().GetSessionId(), cmd.GetSessionKey().GetPartitionSessionId(), cmd.GetDirectReadId()};
  1844. if (key.SessionId.Empty()) {
  1845. error << "no session id in publish read request: ";
  1846. return false;
  1847. } else if (key.PartitionSessionId == 0) {
  1848. error << "No or zero partition session id in publish read request: ";
  1849. return false;
  1850. } else if (key.ReadId == 0) {
  1851. error << "No or zero ReadId in publish read request: ";
  1852. return false;
  1853. }
  1854. if (pipeIter.IsEnd()) {
  1855. error << "Read prepare request from unknown(old?) pipe";
  1856. return false;
  1857. } else if (pipeIter->second.SessionId != key.SessionId) {
  1858. error << "Read prepare request with unknown(old?) session id " << key.SessionId;
  1859. return false;
  1860. }
  1861. return true;
  1862. }
  1863. void TPersQueue::HandlePublishReadRequest(
  1864. const ui64 responseCookie, const TActorId&,
  1865. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1866. const TActorId& pipeClient, const TActorId&
  1867. ) {
  1868. auto cmd = req.GetCmdPublishRead();
  1869. TDirectReadKey key;
  1870. TStringBuilder error;
  1871. if (!ValidateDirectReadRequestBase(cmd, PipesInfo.find(pipeClient), error, key)) {
  1872. error << req.DebugString();
  1873. return ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, error);
  1874. }
  1875. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_PUBLISH_READ);
  1876. THolder<TEvPQ::TEvProxyResponse> publishDoneEvent = MakeHolder<TEvPQ::TEvProxyResponse>(responseCookie);
  1877. publishDoneEvent->Response->SetStatus(NMsgBusProxy::MSTATUS_OK);
  1878. publishDoneEvent->Response->SetErrorCode(NPersQueue::NErrorCode::OK);
  1879. publishDoneEvent->Response->MutablePartitionResponse()->MutableCmdPublishReadResult();
  1880. ctx.Send(SelfId(), publishDoneEvent.Release());
  1881. LOG_DEBUG_S(
  1882. ctx, NKikimrServices::PERSQUEUE, "Publish direct read id " << key.ReadId << " for session " << key.SessionId
  1883. );
  1884. ctx.Send(
  1885. MakePQDReadCacheServiceActorId(),
  1886. new TEvPQ::TEvPublishDirectRead(key, GetGeneration())
  1887. );
  1888. }
  1889. void TPersQueue::HandleForgetReadRequest(
  1890. const ui64 responseCookie, const TActorId& ,
  1891. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx,
  1892. const TActorId& pipeClient, const TActorId&
  1893. ) {
  1894. auto cmd = req.GetCmdForgetRead();
  1895. TDirectReadKey key;
  1896. TStringBuilder error;
  1897. if (!ValidateDirectReadRequestBase(cmd, PipesInfo.find(pipeClient), error, key)) {
  1898. error << req.DebugString();
  1899. return ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, error);
  1900. }
  1901. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_FORGET_READ);
  1902. THolder<TEvPQ::TEvProxyResponse> forgetDoneEvent = MakeHolder<TEvPQ::TEvProxyResponse>(responseCookie);
  1903. forgetDoneEvent->Response->SetStatus(NMsgBusProxy::MSTATUS_OK);
  1904. forgetDoneEvent->Response->SetErrorCode(NPersQueue::NErrorCode::OK);
  1905. forgetDoneEvent->Response->MutablePartitionResponse()->MutableCmdForgetReadResult();
  1906. ctx.Send(SelfId(), forgetDoneEvent.Release());
  1907. LOG_DEBUG_S(
  1908. ctx, NKikimrServices::PERSQUEUE, "Forget direct read id " << key.ReadId << " for session " << key.SessionId
  1909. );
  1910. ctx.Send(
  1911. MakePQDReadCacheServiceActorId(),
  1912. new TEvPQ::TEvForgetDirectRead(key, GetGeneration())
  1913. );
  1914. }
  1915. void TPersQueue::DestroySession(TPipeInfo& pipeInfo) {
  1916. const auto& ctx = ActorContext();
  1917. LOG_DEBUG_S(
  1918. ctx, NKikimrServices::PERSQUEUE, "PQ: Destroy direct read session " << pipeInfo.SessionId
  1919. );
  1920. if (pipeInfo.SessionId.Empty())
  1921. return;
  1922. ActorContext().Send(
  1923. MakePQDReadCacheServiceActorId(),
  1924. new TEvPQ::TEvDeregisterDirectReadSession(
  1925. TReadSessionKey{pipeInfo.SessionId, pipeInfo.PartitionSessionId},
  1926. GetGeneration()
  1927. )
  1928. );
  1929. pipeInfo.SessionId = TString{};
  1930. }
  1931. TMaybe<TEvPQ::TEvRegisterMessageGroup::TBody> TPersQueue::MakeRegisterMessageGroup(
  1932. const NKikimrClient::TPersQueuePartitionRequest::TCmdRegisterMessageGroup& cmd,
  1933. NPersQueue::NErrorCode::EErrorCode& code, TString& error) const
  1934. {
  1935. if (!cmd.HasId() || cmd.GetId().empty()) {
  1936. code = NPersQueue::NErrorCode::BAD_REQUEST;
  1937. error = "Empty Id";
  1938. return Nothing();
  1939. } else if (cmd.GetId().size() > MAX_SOURCE_ID_LENGTH) {
  1940. code = NPersQueue::NErrorCode::BAD_REQUEST;
  1941. error = "Too long Id";
  1942. return Nothing();
  1943. } else if (cmd.HasPartitionKeyRange() && !Config.PartitionKeySchemaSize()) {
  1944. code = NPersQueue::NErrorCode::BAD_REQUEST;
  1945. error = "Missing KeySchema";
  1946. return Nothing();
  1947. }
  1948. TMaybe<NKikimrPQ::TPartitionKeyRange> keyRange;
  1949. if (cmd.HasPartitionKeyRange()) {
  1950. keyRange = cmd.GetPartitionKeyRange();
  1951. }
  1952. return TEvPQ::TEvRegisterMessageGroup::TBody(cmd.GetId(), std::move(keyRange), cmd.GetStartingSeqNo(), cmd.GetAfterSplit());
  1953. }
  1954. TMaybe<TEvPQ::TEvDeregisterMessageGroup::TBody> TPersQueue::MakeDeregisterMessageGroup(
  1955. const NKikimrClient::TPersQueuePartitionRequest::TCmdDeregisterMessageGroup& cmd,
  1956. NPersQueue::NErrorCode::EErrorCode& code, TString& error) const
  1957. {
  1958. if (!cmd.HasId() || cmd.GetId().empty()) {
  1959. code = NPersQueue::NErrorCode::BAD_REQUEST;
  1960. error = "Empty Id";
  1961. return Nothing();
  1962. } else if (cmd.GetId().size() > MAX_SOURCE_ID_LENGTH) {
  1963. code = NPersQueue::NErrorCode::BAD_REQUEST;
  1964. error = "Too long Id";
  1965. return Nothing();
  1966. }
  1967. return TEvPQ::TEvDeregisterMessageGroup::TBody(cmd.GetId());
  1968. }
  1969. void TPersQueue::HandleRegisterMessageGroupRequest(ui64 responseCookie, const TActorId& partActor,
  1970. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1971. {
  1972. Y_ABORT_UNLESS(req.HasCmdRegisterMessageGroup());
  1973. NPersQueue::NErrorCode::EErrorCode code;
  1974. TString error;
  1975. auto body = MakeRegisterMessageGroup(req.GetCmdRegisterMessageGroup(), code, error);
  1976. if (!body) {
  1977. return ReplyError(ctx, responseCookie, code, error);
  1978. }
  1979. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_REGISTER_MESSAGE_GROUP);
  1980. ctx.Send(partActor, new TEvPQ::TEvRegisterMessageGroup(responseCookie, std::move(body.GetRef())));
  1981. }
  1982. void TPersQueue::HandleDeregisterMessageGroupRequest(ui64 responseCookie, const TActorId& partActor,
  1983. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1984. {
  1985. Y_ABORT_UNLESS(req.HasCmdDeregisterMessageGroup());
  1986. NPersQueue::NErrorCode::EErrorCode code;
  1987. TString error;
  1988. auto body = MakeDeregisterMessageGroup(req.GetCmdDeregisterMessageGroup(), code, error);
  1989. if (!body) {
  1990. return ReplyError(ctx, responseCookie, code, error);
  1991. }
  1992. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_DEREGISTER_MESSAGE_GROUP);
  1993. ctx.Send(partActor, new TEvPQ::TEvDeregisterMessageGroup(responseCookie, std::move(body.GetRef())));
  1994. }
  1995. void TPersQueue::HandleSplitMessageGroupRequest(ui64 responseCookie, const TActorId& partActor,
  1996. const NKikimrClient::TPersQueuePartitionRequest& req, const TActorContext& ctx)
  1997. {
  1998. Y_ABORT_UNLESS(req.HasCmdSplitMessageGroup());
  1999. const auto& cmd = req.GetCmdSplitMessageGroup();
  2000. NPersQueue::NErrorCode::EErrorCode code;
  2001. TString error;
  2002. TVector<TEvPQ::TEvDeregisterMessageGroup::TBody> deregistrations;
  2003. for (const auto& group : cmd.GetDeregisterGroups()) {
  2004. auto body = MakeDeregisterMessageGroup(group, code, error);
  2005. if (!body) {
  2006. return ReplyError(ctx, responseCookie, code, error);
  2007. }
  2008. deregistrations.push_back(std::move(body.GetRef()));
  2009. }
  2010. TVector<TEvPQ::TEvRegisterMessageGroup::TBody> registrations;
  2011. for (const auto& group : cmd.GetRegisterGroups()) {
  2012. if (group.GetAfterSplit()) {
  2013. return ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, "AfterSplit cannot be set");
  2014. }
  2015. auto body = MakeRegisterMessageGroup(group, code, error);
  2016. if (!body) {
  2017. return ReplyError(ctx, responseCookie, code, error);
  2018. }
  2019. registrations.push_back(std::move(body.GetRef()));
  2020. }
  2021. InitResponseBuilder(responseCookie, 1, COUNTER_LATENCY_PQ_SPLIT_MESSAGE_GROUP);
  2022. ctx.Send(partActor, new TEvPQ::TEvSplitMessageGroup(responseCookie, std::move(deregistrations), std::move(registrations)));
  2023. }
  2024. void TPersQueue::Handle(TEvPersQueue::TEvRequest::TPtr& ev, const TActorContext& ctx)
  2025. {
  2026. NKikimrClient::TPersQueueRequest& request = ev->Get()->Record;
  2027. TString s = request.HasRequestId() ? request.GetRequestId() : "<none>";
  2028. ui32 p = request.HasPartitionRequest() && request.GetPartitionRequest().HasPartition() ? request.GetPartitionRequest().GetPartition() : 0;
  2029. ui64 m = request.HasPartitionRequest() && request.GetPartitionRequest().HasMessageNo() ? request.GetPartitionRequest().GetMessageNo() : 0;
  2030. TMaybe<ui64> c;
  2031. if (request.HasPartitionRequest() && request.GetPartitionRequest().HasCookie())
  2032. c = request.GetPartitionRequest().GetCookie();
  2033. TAutoPtr<TResponseBuilder> ans;
  2034. ui64 responseCookie = ++NextResponseCookie;
  2035. auto& req = request.GetPartitionRequest();
  2036. TActorId pipeClient = ActorIdFromProto(req.GetPipeClient());
  2037. if (request.GetPartitionRequest().HasCmdRead() && s != TMP_REQUEST_MARKER) {
  2038. auto pipeIter = PipesInfo.find(pipeClient);
  2039. TDirectReadKey directKey{};
  2040. if (!pipeIter.IsEnd()) {
  2041. directKey.SessionId = pipeIter->second.SessionId;
  2042. directKey.PartitionSessionId = pipeIter->second.PartitionSessionId;
  2043. }
  2044. TActorId rr = CreateReadProxy(ev->Sender, ctx.SelfID, GetGeneration(), directKey, request, ctx);
  2045. ans = CreateResponseProxy(rr, ctx.SelfID, TopicName, p, m, s, c, ResourceMetrics, ctx);
  2046. } else {
  2047. ans = CreateResponseProxy(ev->Sender, ctx.SelfID, TopicName, p, m, s, c, ResourceMetrics, ctx);
  2048. }
  2049. ResponseProxy[responseCookie] = ans;
  2050. Counters->Simple()[COUNTER_PQ_TABLET_INFLIGHT].Set(ResponseProxy.size());
  2051. if (!ConfigInited) {
  2052. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::INITIALIZING, "tablet is not ready");
  2053. return;
  2054. }
  2055. if (TabletState == NKikimrPQ::EDropped) {
  2056. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::TABLET_IS_DROPPED, "tablet is dropped");
  2057. return;
  2058. }
  2059. if (!request.HasPartitionRequest()) {
  2060. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, "no partition request");
  2061. return;
  2062. }
  2063. if (!req.HasPartition()) {
  2064. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST, "no partition number");
  2065. return;
  2066. }
  2067. ui32 partition = req.GetPartition();
  2068. auto it = Partitions.find(partition);
  2069. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " got client message batch for topic '"
  2070. << (TopicConverter ? TopicConverter->GetClientsideName() : "Undefined") << "' partition " << partition);
  2071. if (it == Partitions.end()) {
  2072. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::WRONG_PARTITION_NUMBER,
  2073. TStringBuilder() << "wrong partition number " << partition);
  2074. return;
  2075. }
  2076. if (!it->second.InitDone) {
  2077. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::INITIALIZING,
  2078. TStringBuilder() << "partition " << partition << " is not ready");
  2079. return;
  2080. }
  2081. ui32 count = req.HasCmdGetMaxSeqNo()
  2082. + req.HasCmdDeleteSession()
  2083. + req.HasCmdCreateSession()
  2084. + req.HasCmdSetClientOffset()
  2085. + req.HasCmdGetClientOffset()
  2086. + req.HasCmdRead()
  2087. + req.HasCmdGetOwnership()
  2088. + (req.CmdWriteSize() > 0 ? 1 : 0)
  2089. + req.HasCmdReserveBytes()
  2090. + req.HasCmdUpdateWriteTimestamp()
  2091. + req.HasCmdRegisterMessageGroup()
  2092. + req.HasCmdDeregisterMessageGroup()
  2093. + req.HasCmdSplitMessageGroup()
  2094. + req.HasCmdPublishRead()
  2095. + req.HasCmdForgetRead();
  2096. if (count != 1) {
  2097. ReplyError(ctx, responseCookie, NPersQueue::NErrorCode::BAD_REQUEST,
  2098. TStringBuilder() << "multiple commands in request: " << count);
  2099. return;
  2100. }
  2101. const TActorId& partActor = it->second.Actor;
  2102. if (req.HasCmdGetMaxSeqNo()) {
  2103. HandleGetMaxSeqNoRequest(responseCookie, partActor, req, ctx);
  2104. } else if (req.HasCmdDeleteSession()) {
  2105. HandleDeleteSessionRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2106. } else if (req.HasCmdCreateSession()) {
  2107. HandleCreateSessionRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2108. } else if (req.HasCmdSetClientOffset()) {
  2109. HandleSetClientOffsetRequest(responseCookie, partActor, req, ctx);
  2110. } else if (req.HasCmdGetClientOffset()) {
  2111. HandleGetClientOffsetRequest(responseCookie, partActor, req, ctx);
  2112. } else if (req.CmdWriteSize()) {
  2113. HandleWriteRequest(responseCookie, partActor, req, ctx);
  2114. } else if (req.HasCmdUpdateWriteTimestamp()) {
  2115. HandleUpdateWriteTimestampRequest(responseCookie, partActor, req, ctx);
  2116. } else if (req.HasCmdRead()) {
  2117. HandleReadRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2118. } else if (req.HasCmdPublishRead()) {
  2119. HandlePublishReadRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2120. } else if (req.HasCmdForgetRead()) {
  2121. HandleForgetReadRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2122. } else if (req.HasCmdGetOwnership()) {
  2123. HandleGetOwnershipRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2124. } else if (req.HasCmdReserveBytes()) {
  2125. HandleReserveBytesRequest(responseCookie, partActor, req, ctx, pipeClient, ev->Sender);
  2126. } else if (req.HasCmdRegisterMessageGroup()) {
  2127. HandleRegisterMessageGroupRequest(responseCookie, partActor, req, ctx);
  2128. } else if (req.HasCmdDeregisterMessageGroup()) {
  2129. HandleDeregisterMessageGroupRequest(responseCookie, partActor, req, ctx);
  2130. } else if (req.HasCmdSplitMessageGroup()) {
  2131. HandleSplitMessageGroupRequest(responseCookie, partActor, req, ctx);
  2132. } else Y_ABORT("unknown or empty command");
  2133. }
  2134. void TPersQueue::Handle(TEvTabletPipe::TEvServerConnected::TPtr& ev, const TActorContext&)
  2135. {
  2136. auto it = PipesInfo.insert({ev->Get()->ClientId, {}}).first;
  2137. it->second.ServerActors++;
  2138. Counters->Simple()[COUNTER_PQ_TABLET_OPENED_PIPES] = PipesInfo.size();
  2139. }
  2140. void TPersQueue::Handle(TEvTabletPipe::TEvServerDisconnected::TPtr& ev, const TActorContext& ctx)
  2141. {
  2142. //inform partition if needed;
  2143. auto it = PipesInfo.find(ev->Get()->ClientId);
  2144. if (it != PipesInfo.end()) {
  2145. if(--(it->second.ServerActors) > 0) {
  2146. return;
  2147. }
  2148. if (it->second.PartActor != TActorId()) {
  2149. ctx.Send(it->second.PartActor, new TEvPQ::TEvPipeDisconnected(
  2150. it->second.Owner, it->first
  2151. ));
  2152. }
  2153. if (!it->second.SessionId.Empty()) {
  2154. DestroySession(it->second);
  2155. }
  2156. PipesInfo.erase(it);
  2157. Counters->Simple()[COUNTER_PQ_TABLET_OPENED_PIPES] = PipesInfo.size();
  2158. }
  2159. }
  2160. void TPersQueue::Handle(TEvTabletPipe::TEvClientConnected::TPtr& ev, const TActorContext& ctx)
  2161. {
  2162. Y_ABORT_UNLESS(ev->Get()->Leader, "Unexpectedly connected to follower of tablet %" PRIu64, ev->Get()->TabletId);
  2163. if (PipeClientCache->OnConnect(ev)) {
  2164. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  2165. "Tablet " << TabletID() <<
  2166. " Connected to tablet " << ev->Get()->TabletId);
  2167. return;
  2168. }
  2169. RestartPipe(ev->Get()->TabletId, ctx);
  2170. }
  2171. void TPersQueue::Handle(TEvTabletPipe::TEvClientDestroyed::TPtr& ev, const TActorContext& ctx)
  2172. {
  2173. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  2174. "Tablet " << TabletID() <<
  2175. " Client pipe to tablet " << ev->Get()->TabletId << " is reset");
  2176. PipeClientCache->OnDisconnect(ev);
  2177. RestartPipe(ev->Get()->TabletId, ctx);
  2178. }
  2179. void TPersQueue::RestartPipe(ui64 tabletId, const TActorContext& ctx)
  2180. {
  2181. for (auto& txId: GetBindedTxs(tabletId)) {
  2182. auto* tx = GetTransaction(ctx, txId);
  2183. if (!tx) {
  2184. continue;
  2185. }
  2186. for (auto& message : tx->GetBindedMsgs(tabletId)) {
  2187. PipeClientCache->Send(ctx, tabletId, message.Type, message.Data);
  2188. }
  2189. }
  2190. }
  2191. bool TPersQueue::OnRenderAppHtmlPage(NMon::TEvRemoteHttpInfo::TPtr ev, const TActorContext& ctx)
  2192. {
  2193. if (!ev)
  2194. return true;
  2195. if (ev->Get()->Cgi().Has("kv")) {
  2196. return TKeyValueFlat::OnRenderAppHtmlPage(ev, ctx);
  2197. }
  2198. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvRemoteHttpInfo: " << ev->Get()->Query);
  2199. TMap<ui32, TActorId> res;
  2200. for (auto& p : Partitions) {
  2201. res.insert({p.first, p.second.Actor});
  2202. }
  2203. ctx.Register(new TMonitoringProxy(ev->Sender, ev->Get()->Query, res, CacheActor, TopicName, TabletID(), ResponseProxy.size()));
  2204. return true;
  2205. }
  2206. void TPersQueue::HandleDie(const TActorContext& ctx)
  2207. {
  2208. MeteringSink.MayFlushForcibly(ctx.Now());
  2209. for (const auto& p : Partitions) {
  2210. ctx.Send(p.second.Actor, new TEvents::TEvPoisonPill());
  2211. }
  2212. ctx.Send(CacheActor, new TEvents::TEvPoisonPill());
  2213. for (auto& pipe : PipesInfo) {
  2214. if (!pipe.second.SessionId.empty()) {
  2215. DestroySession(pipe.second);
  2216. }
  2217. }
  2218. for (const auto& p : ResponseProxy) {
  2219. THolder<TEvPQ::TEvError> ev = MakeHolder<TEvPQ::TEvError>(NPersQueue::NErrorCode::INITIALIZING, "tablet will be restarted right now", p.first);
  2220. bool res = p.second->HandleError(ev.Get(), ctx);
  2221. Y_ABORT_UNLESS(res);
  2222. }
  2223. ResponseProxy.clear();
  2224. StopWatchingTenantPathId(ctx);
  2225. MediatorTimeCastUnregisterTablet(ctx);
  2226. NKeyValue::TKeyValueFlat::HandleDie(ctx);
  2227. }
  2228. TPersQueue::TPersQueue(const TActorId& tablet, TTabletStorageInfo *info)
  2229. : TKeyValueFlat(tablet, info)
  2230. , ConfigInited(false)
  2231. , PartitionsInited(0)
  2232. , NewConfigShouldBeApplied(false)
  2233. , TabletState(NKikimrPQ::ENormal)
  2234. , Counters(nullptr)
  2235. , NextResponseCookie(0)
  2236. , ResourceMetrics(nullptr)
  2237. , PipeClientCacheConfig(new NTabletPipe::TBoundedClientCacheConfig())
  2238. , PipeClientCache(NTabletPipe::CreateBoundedClientCache(PipeClientCacheConfig, GetPipeClientConfig()))
  2239. {
  2240. typedef TProtobufTabletCounters<
  2241. NKeyValue::ESimpleCounters_descriptor,
  2242. NKeyValue::ECumulativeCounters_descriptor,
  2243. NKeyValue::EPercentileCounters_descriptor,
  2244. NKeyValue::ETxTypes_descriptor> TKeyValueCounters;
  2245. typedef TAppProtobufTabletCounters<
  2246. ESimpleCounters_descriptor,
  2247. ECumulativeCounters_descriptor,
  2248. EPercentileCounters_descriptor> TPersQueueCounters;
  2249. typedef TProtobufTabletCountersPair<TKeyValueCounters, TPersQueueCounters> TCounters;
  2250. TAutoPtr<TCounters> counters(new TCounters());
  2251. Counters = (counters->GetSecondTabletCounters()).Release();
  2252. State.SetupTabletCounters(counters->GetFirstTabletCounters().Release()); //FirstTabletCounters is of good type and contains all counters
  2253. State.Clear();
  2254. }
  2255. void TPersQueue::CreatedHook(const TActorContext& ctx)
  2256. {
  2257. IsServerless = AppData(ctx)->FeatureFlags.GetEnableDbCounters(); //TODO: find out it via describe
  2258. CacheActor = ctx.Register(new TPQCacheProxy(ctx.SelfID, TabletID()));
  2259. ctx.Send(GetNameserviceActorId(), new TEvInterconnect::TEvGetNode(ctx.SelfID.NodeId()));
  2260. InitProcessingParams(ctx);
  2261. }
  2262. void TPersQueue::StartWatchingTenantPathId(const TActorContext& ctx)
  2263. {
  2264. ctx.Send(MakeSchemeCacheID(), new TEvTxProxySchemeCache::TEvWatchPathId(Info()->TenantPathId));
  2265. }
  2266. void TPersQueue::StopWatchingTenantPathId(const TActorContext& ctx)
  2267. {
  2268. ctx.Send(MakeSchemeCacheID(), new TEvTxProxySchemeCache::TEvWatchRemove());
  2269. }
  2270. void TPersQueue::Handle(TEvTxProxySchemeCache::TEvWatchNotifyUpdated::TPtr& ev, const TActorContext& ctx)
  2271. {
  2272. const auto& result = ev->Get()->Result;
  2273. ProcessingParams = result->GetPathDescription().GetDomainDescription().GetProcessingParams();
  2274. InitMediatorTimeCast(ctx);
  2275. }
  2276. void TPersQueue::MediatorTimeCastRegisterTablet(const TActorContext& ctx)
  2277. {
  2278. Y_ABORT_UNLESS(ProcessingParams);
  2279. ctx.Send(MakeMediatorTimecastProxyID(),
  2280. new TEvMediatorTimecast::TEvRegisterTablet(TabletID(), *ProcessingParams));
  2281. }
  2282. void TPersQueue::MediatorTimeCastUnregisterTablet(const TActorContext& ctx)
  2283. {
  2284. ctx.Send(MakeMediatorTimecastProxyID(),
  2285. new TEvMediatorTimecast::TEvUnregisterTablet(TabletID()));
  2286. }
  2287. void TPersQueue::Handle(TEvMediatorTimecast::TEvRegisterTabletResult::TPtr& ev, const TActorContext& ctx)
  2288. {
  2289. const auto* message = ev->Get();
  2290. Y_ABORT_UNLESS(message->TabletId == TabletID());
  2291. MediatorTimeCastEntry = message->Entry;
  2292. Y_ABORT_UNLESS(MediatorTimeCastEntry);
  2293. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() <<
  2294. "Registered with mediator time cast");
  2295. TryWriteTxs(ctx);
  2296. }
  2297. void TPersQueue::Handle(TEvInterconnect::TEvNodeInfo::TPtr& ev, const TActorContext& ctx)
  2298. {
  2299. Y_ABORT_UNLESS(ev->Get()->Node);
  2300. DCId = ev->Get()->Node->Location.GetDataCenterId();
  2301. ResourceMetrics = Executor()->GetResourceMetrics();
  2302. THolder<TEvKeyValue::TEvRequest> request(new TEvKeyValue::TEvRequest);
  2303. request->Record.SetCookie(READ_CONFIG_COOKIE);
  2304. request->Record.AddCmdRead()->SetKey(KeyConfig());
  2305. request->Record.AddCmdRead()->SetKey(KeyState());
  2306. request->Record.AddCmdRead()->SetKey(KeyTxInfo());
  2307. auto cmd = request->Record.AddCmdReadRange();
  2308. cmd->MutableRange()->SetFrom(GetTxKey(Min<ui64>()));
  2309. cmd->MutableRange()->SetIncludeFrom(true);
  2310. cmd->MutableRange()->SetTo(GetTxKey(Max<ui64>()));
  2311. cmd->MutableRange()->SetIncludeTo(true);
  2312. cmd->SetIncludeData(true);
  2313. request->Record.MutableCmdSetExecutorFastLogPolicy()
  2314. ->SetIsAllowed(AppData(ctx)->PQConfig.GetTactic() == NKikimrClient::TKeyValueRequest::MIN_LATENCY);
  2315. ctx.Send(ctx.SelfID, request.Release());
  2316. ctx.Schedule(TDuration::Seconds(5), new TEvents::TEvWakeup());
  2317. }
  2318. void TPersQueue::HandleWakeup(const TActorContext& ctx) {
  2319. THashSet<TString> groups;
  2320. for (auto& p : Partitions) {
  2321. for (auto& m : p.second.LabeledCounters) {
  2322. groups.insert(m.first);
  2323. }
  2324. }
  2325. for (auto& g : groups) {
  2326. AggregateAndSendLabeledCountersFor(g, ctx);
  2327. }
  2328. MeteringSink.MayFlush(ctx.Now());
  2329. DeleteExpiredTransactions(ctx);
  2330. ctx.Schedule(TDuration::Seconds(5), new TEvents::TEvWakeup());
  2331. }
  2332. void TPersQueue::DeleteExpiredTransactions(const TActorContext& ctx)
  2333. {
  2334. if (!MediatorTimeCastEntry) {
  2335. return;
  2336. }
  2337. ui64 step = MediatorTimeCastEntry->Get(TabletID());
  2338. for (auto& [txId, tx] : Txs) {
  2339. if ((tx.MaxStep < step) && (tx.State <= NKikimrPQ::TTransaction::PREPARED)) {
  2340. DeleteTx(tx);
  2341. }
  2342. }
  2343. TryWriteTxs(ctx);
  2344. }
  2345. void TPersQueue::Handle(TEvPersQueue::TEvCancelTransactionProposal::TPtr& ev, const TActorContext& ctx)
  2346. {
  2347. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvPersQueue::TEvCancelTransactionProposal");
  2348. NKikimrPQ::TEvCancelTransactionProposal& event = ev->Get()->Record;
  2349. Y_ABORT_UNLESS(event.HasTxId());
  2350. if (auto tx = GetTransaction(ctx, event.GetTxId()); tx) {
  2351. Y_ABORT_UNLESS(tx->State <= NKikimrPQ::TTransaction::PREPARED);
  2352. DeleteTx(*tx);
  2353. TryWriteTxs(ctx);
  2354. }
  2355. }
  2356. void TPersQueue::Handle(TEvPersQueue::TEvProposeTransaction::TPtr& ev, const TActorContext& ctx)
  2357. {
  2358. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvPersQueue::TEvProposeTransaction");
  2359. NKikimrPQ::TEvProposeTransaction& event = ev->Get()->Record;
  2360. switch (event.GetTxBodyCase()) {
  2361. case NKikimrPQ::TEvProposeTransaction::kData:
  2362. HandleDataTransaction(ev->Release(), ctx);
  2363. break;
  2364. case NKikimrPQ::TEvProposeTransaction::kConfig:
  2365. HandleConfigTransaction(ev->Release(), ctx);
  2366. break;
  2367. case NKikimrPQ::TEvProposeTransaction::TXBODY_NOT_SET:
  2368. SendProposeTransactionAbort(ActorIdFromProto(event.GetSourceActor()),
  2369. event.GetTxId(),
  2370. ctx);
  2371. break;
  2372. }
  2373. }
  2374. void TPersQueue::HandleDataTransaction(TAutoPtr<TEvPersQueue::TEvProposeTransaction> ev,
  2375. const TActorContext& ctx)
  2376. {
  2377. NKikimrPQ::TEvProposeTransaction& event = ev->Record;
  2378. Y_ABORT_UNLESS(event.GetTxBodyCase() == NKikimrPQ::TEvProposeTransaction::kData);
  2379. Y_ABORT_UNLESS(event.HasData());
  2380. const NKikimrPQ::TDataTransaction& txBody = event.GetData();
  2381. for (auto& operation : txBody.GetOperations()) {
  2382. Y_ABORT_UNLESS(!operation.HasPath() || (operation.GetPath() == TopicPath));
  2383. bool isWriteOperation = !operation.HasBegin();
  2384. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  2385. "Tablet " << TabletID() <<
  2386. " tx=" << event.GetTxId() <<
  2387. ", write_id=" << txBody.GetWriteId() <<
  2388. ", path=" << operation.GetPath() <<
  2389. ", partition=" << operation.GetPartitionId() <<
  2390. ", consumer=" << operation.GetConsumer() <<
  2391. ", begin=" << operation.GetBegin() <<
  2392. ", end=" << operation.GetEnd() <<
  2393. ", is_write=" << isWriteOperation);
  2394. }
  2395. if ((TabletState != NKikimrPQ::ENormal) || txBody.HasWriteId()) {
  2396. SendProposeTransactionAbort(ActorIdFromProto(event.GetSourceActor()),
  2397. event.GetTxId(),
  2398. ctx);
  2399. return;
  2400. }
  2401. //
  2402. // TODO(abcdef): сохранить пока инициализируемся. TEvPersQueue::TEvHasDataInfo::TPtr как образец. не только конфиг. Inited==true
  2403. //
  2404. if (txBody.GetImmediate()) {
  2405. //
  2406. // FIXME(abcdef): вместо Y_ABORT_UNLESS отправлять TEvProposeTransactionResult с кодом ошибки
  2407. //
  2408. Y_ABORT_UNLESS(txBody.OperationsSize() > 0);
  2409. auto i = Partitions.find(txBody.GetOperations(0).GetPartitionId());
  2410. Y_ABORT_UNLESS(i != Partitions.end());
  2411. ctx.Send(i->second.Actor, ev.Release());
  2412. } else {
  2413. EvProposeTransactionQueue.emplace_back(ev.Release());
  2414. TryWriteTxs(ctx);
  2415. }
  2416. }
  2417. void TPersQueue::HandleConfigTransaction(TAutoPtr<TEvPersQueue::TEvProposeTransaction> ev,
  2418. const TActorContext& ctx)
  2419. {
  2420. NKikimrPQ::TEvProposeTransaction& event = ev->Record;
  2421. Y_ABORT_UNLESS(event.GetTxBodyCase() == NKikimrPQ::TEvProposeTransaction::kConfig);
  2422. Y_ABORT_UNLESS(event.HasConfig());
  2423. EvProposeTransactionQueue.emplace_back(ev.Release());
  2424. TryWriteTxs(ctx);
  2425. }
  2426. void TPersQueue::Handle(TEvTxProcessing::TEvPlanStep::TPtr& ev, const TActorContext& ctx)
  2427. {
  2428. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvTxProcessing::TEvPlanStep");
  2429. NKikimrTx::TEvMediatorPlanStep& event = ev->Get()->Record;
  2430. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  2431. "Tablet: " << TabletID() <<
  2432. ", PlanStep: " << event.GetStep() <<
  2433. ", Mediator: " << event.GetMediatorID());
  2434. EvPlanStepQueue.emplace_back(ev->Sender, ev->Release().Release());
  2435. TryWriteTxs(ctx);
  2436. }
  2437. void TPersQueue::Handle(TEvTxProcessing::TEvReadSet::TPtr& ev, const TActorContext& ctx)
  2438. {
  2439. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvTxProcessing::TEvReadSet");
  2440. NKikimrTx::TEvReadSet& event = ev->Get()->Record;
  2441. Y_ABORT_UNLESS(event.HasTxId());
  2442. std::unique_ptr<TEvTxProcessing::TEvReadSetAck> ack;
  2443. if (!(event.GetFlags() & NKikimrTx::TEvReadSet::FLAG_NO_ACK)) {
  2444. ack = std::make_unique<TEvTxProcessing::TEvReadSetAck>(*ev->Get(), TabletID());
  2445. }
  2446. if (auto tx = GetTransaction(ctx, event.GetTxId()); tx && tx->Senders.contains(event.GetTabletProducer())) {
  2447. tx->OnReadSet(event, ev->Sender, std::move(ack));
  2448. if (tx->State == NKikimrPQ::TTransaction::WAIT_RS) {
  2449. CheckTxState(ctx, *tx);
  2450. TryWriteTxs(ctx);
  2451. }
  2452. } else if (ack) {
  2453. //
  2454. // для неизвестных транзакций подтверждение отправляется сразу
  2455. //
  2456. ctx.Send(ev->Sender, ack.release());
  2457. }
  2458. }
  2459. void TPersQueue::Handle(TEvTxProcessing::TEvReadSetAck::TPtr& ev, const TActorContext& ctx)
  2460. {
  2461. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvTxProcessing::TEvReadSetAck");
  2462. NKikimrTx::TEvReadSetAck& event = ev->Get()->Record;
  2463. Y_ABORT_UNLESS(event.HasTxId());
  2464. auto tx = GetTransaction(ctx, event.GetTxId());
  2465. if (!tx) {
  2466. return;
  2467. }
  2468. tx->OnReadSetAck(event);
  2469. tx->UnbindMsgsFromPipe(event.GetTabletConsumer());
  2470. if (tx->State == NKikimrPQ::TTransaction::EXECUTED) {
  2471. CheckTxState(ctx, *tx);
  2472. TryWriteTxs(ctx);
  2473. }
  2474. }
  2475. void TPersQueue::Handle(TEvPQ::TEvTxCalcPredicateResult::TPtr& ev, const TActorContext& ctx)
  2476. {
  2477. const TEvPQ::TEvTxCalcPredicateResult& event = *ev->Get();
  2478. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE,
  2479. "Tablet " << TabletID() <<
  2480. " Handle TEvPQ::TEvTxCalcPredicateResult" <<
  2481. " Step " << event.Step <<
  2482. " TxId " << event.TxId <<
  2483. " Partition " << event.Partition <<
  2484. " Predicate " << (event.Predicate ? "true" : "false"));
  2485. auto tx = GetTransaction(ctx, event.TxId);
  2486. if (!tx) {
  2487. return;
  2488. }
  2489. tx->OnTxCalcPredicateResult(event);
  2490. CheckTxState(ctx, *tx);
  2491. TryWriteTxs(ctx);
  2492. }
  2493. void TPersQueue::Handle(TEvPQ::TEvProposePartitionConfigResult::TPtr& ev, const TActorContext& ctx)
  2494. {
  2495. const TEvPQ::TEvProposePartitionConfigResult& event = *ev->Get();
  2496. auto tx = GetTransaction(ctx, event.TxId);
  2497. if (!tx) {
  2498. return;
  2499. }
  2500. Y_ABORT_UNLESS(tx->State == NKikimrPQ::TTransaction::CALCULATING);
  2501. tx->OnProposePartitionConfigResult(event);
  2502. CheckTxState(ctx, *tx);
  2503. TryWriteTxs(ctx);
  2504. }
  2505. void TPersQueue::Handle(TEvPQ::TEvTxCommitDone::TPtr& ev, const TActorContext& ctx)
  2506. {
  2507. LOG_DEBUG_S(ctx, NKikimrServices::PERSQUEUE, "Tablet " << TabletID() << " Handle TEvPQ::TEvTxCommitDone");
  2508. const TEvPQ::TEvTxCommitDone& event = *ev->Get();
  2509. auto tx = GetTransaction(ctx, event.TxId);
  2510. if (!tx) {
  2511. return;
  2512. }
  2513. Y_ABORT_UNLESS(tx->State == NKikimrPQ::TTransaction::EXECUTING);
  2514. tx->OnTxCommitDone(event);
  2515. CheckTxState(ctx, *tx);
  2516. TryWriteTxs(ctx);
  2517. }
  2518. bool TPersQueue::CanProcessProposeTransactionQueue() const
  2519. {
  2520. return
  2521. !EvProposeTransactionQueue.empty()
  2522. && ProcessingParams
  2523. && (!UseMediatorTimeCast || MediatorTimeCastEntry);
  2524. }
  2525. bool TPersQueue::CanProcessPlanStepQueue() const
  2526. {
  2527. return !EvPlanStepQueue.empty();
  2528. }
  2529. bool TPersQueue::CanProcessWriteTxs() const
  2530. {
  2531. return !WriteTxs.empty();
  2532. }
  2533. bool TPersQueue::CanProcessDeleteTxs() const
  2534. {
  2535. return !DeleteTxs.empty();
  2536. }
  2537. void TPersQueue::BeginWriteTxs(const TActorContext& ctx)
  2538. {
  2539. Y_ABORT_UNLESS(!WriteTxsInProgress);
  2540. if (!CanProcessProposeTransactionQueue() && !CanProcessPlanStepQueue() && !CanProcessWriteTxs() && !CanProcessDeleteTxs()) {
  2541. return;
  2542. }
  2543. auto request = MakeHolder<TEvKeyValue::TEvRequest>();
  2544. request->Record.SetCookie(WRITE_TX_COOKIE);
  2545. ProcessProposeTransactionQueue(ctx);
  2546. ProcessPlanStepQueue(ctx);
  2547. ProcessWriteTxs(ctx, request->Record);
  2548. ProcessDeleteTxs(ctx, request->Record);
  2549. AddCmdWriteTabletTxInfo(request->Record);
  2550. ProcessConfigTx(ctx, request.Get());
  2551. WriteTxsInProgress = true;
  2552. ctx.Send(ctx.SelfID, request.Release());
  2553. TryReturnTabletStateAll(ctx);
  2554. }
  2555. void TPersQueue::EndWriteTxs(const NKikimrClient::TResponse& resp,
  2556. const TActorContext& ctx)
  2557. {
  2558. Y_ABORT_UNLESS(WriteTxsInProgress);
  2559. bool ok = (resp.GetStatus() == NMsgBusProxy::MSTATUS_OK);
  2560. if (ok) {
  2561. for (auto& result : resp.GetWriteResult()) {
  2562. if (result.GetStatus() != NKikimrProto::OK) {
  2563. ok = false;
  2564. break;
  2565. }
  2566. }
  2567. }
  2568. if (!ok) {
  2569. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  2570. "Tablet " << TabletID() << " SelfId " << ctx.SelfID << " TxInfo write error: " << resp.DebugString());
  2571. ctx.Send(ctx.SelfID, new TEvents::TEvPoisonPill());
  2572. return;
  2573. }
  2574. SendReplies(ctx);
  2575. CheckChangedTxStates(ctx);
  2576. WriteTxsInProgress = false;
  2577. TryWriteTxs(ctx);
  2578. }
  2579. void TPersQueue::TryWriteTxs(const TActorContext& ctx)
  2580. {
  2581. if (!WriteTxsInProgress) {
  2582. BeginWriteTxs(ctx);
  2583. }
  2584. }
  2585. void TPersQueue::ProcessProposeTransactionQueue(const TActorContext& ctx)
  2586. {
  2587. Y_ABORT_UNLESS(!WriteTxsInProgress);
  2588. while (CanProcessProposeTransactionQueue()) {
  2589. const auto front = std::move(EvProposeTransactionQueue.front());
  2590. EvProposeTransactionQueue.pop_front();
  2591. const NKikimrPQ::TEvProposeTransaction& event = front->Record;
  2592. TDistributedTransaction& tx = Txs[event.GetTxId()];
  2593. switch (tx.State) {
  2594. case NKikimrPQ::TTransaction::UNKNOWN:
  2595. tx.OnProposeTransaction(event, GetAllowedStep(),
  2596. TabletID());
  2597. CheckTxState(ctx, tx);
  2598. break;
  2599. case NKikimrPQ::TTransaction::PREPARING:
  2600. case NKikimrPQ::TTransaction::PREPARED:
  2601. //
  2602. // the sender re-sent the TEvProposeTransaction. the actor ID could have changed. you need to
  2603. // update the ID in the transaction and schedule a response to the new actor
  2604. //
  2605. tx.SourceActor = ActorIdFromProto(event.GetSourceActor());
  2606. ScheduleProposeTransactionResult(tx);
  2607. break;
  2608. default:
  2609. Y_ABORT();
  2610. }
  2611. }
  2612. }
  2613. void TPersQueue::ProcessPlanStepQueue(const TActorContext& ctx)
  2614. {
  2615. Y_ABORT_UNLESS(!WriteTxsInProgress);
  2616. while (CanProcessPlanStepQueue()) {
  2617. const auto front = std::move(EvPlanStepQueue.front());
  2618. EvPlanStepQueue.pop_front();
  2619. const TActorId& sender = front.first;
  2620. const NKikimrTx::TEvMediatorPlanStep& event = front.second->Record;
  2621. ui64 step = event.GetStep();
  2622. TVector<ui64> txIds;
  2623. THashMap<TActorId, TVector<ui64>> txAcks;
  2624. for (auto& tx : event.GetTransactions()) {
  2625. Y_ABORT_UNLESS(tx.HasTxId());
  2626. Y_ABORT_UNLESS(tx.HasAckTo());
  2627. txIds.push_back(tx.GetTxId());
  2628. txAcks[ActorIdFromProto(tx.GetAckTo())].push_back(tx.GetTxId());
  2629. }
  2630. if (step >= LastStep) {
  2631. ui64 lastPlannedTxId = 0;
  2632. for (ui64 txId : txIds) {
  2633. Y_ABORT_UNLESS(lastPlannedTxId < txId);
  2634. if (auto p = Txs.find(txId); p != Txs.end()) {
  2635. TDistributedTransaction& tx = p->second;
  2636. Y_ABORT_UNLESS(tx.MaxStep >= step);
  2637. if (tx.Step == Max<ui64>()) {
  2638. Y_ABORT_UNLESS(TxQueue.empty() || (TxQueue.back() < std::make_pair(step, txId)));
  2639. tx.OnPlanStep(step);
  2640. CheckTxState(ctx, tx);
  2641. TxQueue.emplace(step, txId);
  2642. } else {
  2643. LOG_WARN_S(ctx, NKikimrServices::PERSQUEUE,
  2644. "Tablet " << TabletID() <<
  2645. " Transaction already planned for step " << tx.Step <<
  2646. ", Step: " << step <<
  2647. ", TxId: " << txId);
  2648. }
  2649. } else {
  2650. LOG_WARN_S(ctx, NKikimrServices::PERSQUEUE,
  2651. "Tablet " << TabletID() <<
  2652. " Unknown transaction " << txId <<
  2653. ", Step: " << step);
  2654. }
  2655. lastPlannedTxId = txId;
  2656. }
  2657. LastStep = step;
  2658. LastTxId = lastPlannedTxId;
  2659. } else {
  2660. LOG_ERROR_S(ctx, NKikimrServices::PERSQUEUE,
  2661. "Tablet " << TabletID() <<
  2662. " Old plan step " << step <<
  2663. ", LastStep: " << LastStep);
  2664. }
  2665. SchedulePlanStepAck(step, txAcks);
  2666. SchedulePlanStepAccepted(sender, step);
  2667. }
  2668. }
  2669. void TPersQueue::ProcessWriteTxs(const TActorContext& ctx,
  2670. NKikimrClient::TKeyValueRequest& request)
  2671. {
  2672. Y_ABORT_UNLESS(!WriteTxsInProgress);
  2673. for (auto& [txId, state] : WriteTxs) {
  2674. auto tx = GetTransaction(ctx, txId);
  2675. Y_ABORT_UNLESS(tx);
  2676. tx->AddCmdWrite(request, state);
  2677. ChangedTxs.insert(txId);
  2678. }
  2679. WriteTxs.clear();
  2680. }
  2681. void TPersQueue::ProcessDeleteTxs(const TActorContext& ctx,
  2682. NKikimrClient::TKeyValueRequest& request)
  2683. {
  2684. Y_ABORT_UNLESS(!WriteTxsInProgress);
  2685. for (ui64 txId : DeleteTxs) {
  2686. auto tx = GetTransaction(ctx, txId);
  2687. Y_ABORT_UNLESS(tx);
  2688. tx->AddCmdDelete(request);
  2689. Txs.erase(tx->TxId);
  2690. }
  2691. DeleteTxs.clear();
  2692. }
  2693. void TPersQueue::ProcessConfigTx(const TActorContext& ctx,
  2694. TEvKeyValue::TEvRequest* request)
  2695. {
  2696. Y_ABORT_UNLESS(!WriteTxsInProgress);
  2697. if (!TabletConfigTx.Defined()) {
  2698. return;
  2699. }
  2700. AddCmdWriteConfig(request,
  2701. *TabletConfigTx,
  2702. *BootstrapConfigTx,
  2703. ctx);
  2704. TabletConfigTx = Nothing();
  2705. BootstrapConfigTx = Nothing();
  2706. }
  2707. void TPersQueue::AddCmdWriteTabletTxInfo(NKikimrClient::TKeyValueRequest& request)
  2708. {
  2709. NKikimrPQ::TTabletTxInfo info;
  2710. info.SetLastStep(LastStep);
  2711. info.SetLastTxId(LastTxId);
  2712. TString value;
  2713. Y_ABORT_UNLESS(info.SerializeToString(&value));
  2714. auto command = request.AddCmdWrite();
  2715. command->SetKey(KeyTxInfo());
  2716. command->SetValue(value);
  2717. }
  2718. void TPersQueue::ScheduleProposeTransactionResult(const TDistributedTransaction& tx)
  2719. {
  2720. auto event = std::make_unique<TEvPersQueue::TEvProposeTransactionResult>();
  2721. event->Record.SetOrigin(TabletID());
  2722. event->Record.SetStatus(NKikimrPQ::TEvProposeTransactionResult::PREPARED);
  2723. event->Record.SetTxId(tx.TxId);
  2724. event->Record.SetMinStep(tx.MinStep);
  2725. event->Record.SetMaxStep(tx.MaxStep);
  2726. if (ProcessingParams) {
  2727. event->Record.MutableDomainCoordinators()->CopyFrom(ProcessingParams->GetCoordinators());
  2728. }
  2729. RepliesToActor.emplace_back(tx.SourceActor, std::move(event));
  2730. }
  2731. void TPersQueue::SchedulePlanStepAck(ui64 step,
  2732. const THashMap<TActorId, TVector<ui64>>& txAcks)
  2733. {
  2734. for (auto& [actorId, txIds] : txAcks) {
  2735. auto event = std::make_unique<TEvTxProcessing::TEvPlanStepAck>(TabletID(),
  2736. step,
  2737. txIds.begin(), txIds.end());
  2738. RepliesToActor.emplace_back(actorId, std::move(event));
  2739. }
  2740. }
  2741. void TPersQueue::SchedulePlanStepAccepted(const TActorId& actorId,
  2742. ui64 step)
  2743. {
  2744. auto event = std::make_unique<TEvTxProcessing::TEvPlanStepAccepted>(TabletID(), step);
  2745. RepliesToActor.emplace_back(actorId, std::move(event));
  2746. }
  2747. void TPersQueue::SendEvReadSetToReceivers(const TActorContext& ctx,
  2748. TDistributedTransaction& tx)
  2749. {
  2750. NKikimrTx::TReadSetData data;
  2751. data.SetDecision(tx.SelfDecision);
  2752. TString body;
  2753. Y_ABORT_UNLESS(data.SerializeToString(&body));
  2754. PQ_LOG_D("Send TEvTxProcessing::TEvReadSet to " << tx.Receivers.size() << " receivers. Wait TEvTxProcessing::TEvReadSet from " << tx.Senders.size() << " senders.");
  2755. for (ui64 receiverId : tx.Receivers) {
  2756. if (receiverId != TabletID()) {
  2757. auto event = std::make_unique<TEvTxProcessing::TEvReadSet>(tx.Step,
  2758. tx.TxId,
  2759. TabletID(),
  2760. receiverId,
  2761. TabletID(),
  2762. body,
  2763. 0);
  2764. SendToPipe(receiverId, tx, std::move(event), ctx);
  2765. }
  2766. }
  2767. }
  2768. void TPersQueue::SendEvReadSetAckToSenders(const TActorContext& ctx,
  2769. TDistributedTransaction& tx)
  2770. {
  2771. for (auto& [target, event] : tx.ReadSetAcks) {
  2772. ctx.Send(target, event.release());
  2773. }
  2774. }
  2775. void TPersQueue::SendEvTxCalcPredicateToPartitions(const TActorContext& ctx,
  2776. TDistributedTransaction& tx)
  2777. {
  2778. THashMap<ui32, std::unique_ptr<TEvPQ::TEvTxCalcPredicate>> events;
  2779. for (auto& operation : tx.Operations) {
  2780. auto& event = events[operation.GetPartitionId()];
  2781. if (!event) {
  2782. event = std::make_unique<TEvPQ::TEvTxCalcPredicate>(tx.Step, tx.TxId);
  2783. }
  2784. event->AddOperation(operation.GetConsumer(),
  2785. operation.GetBegin(),
  2786. operation.GetEnd());
  2787. }
  2788. for (auto& [partition, event] : events) {
  2789. auto p = Partitions.find(partition);
  2790. Y_ABORT_UNLESS(p != Partitions.end());
  2791. ctx.Send(p->second.Actor, event.release());
  2792. }
  2793. tx.PartitionRepliesCount = 0;
  2794. tx.PartitionRepliesExpected = events.size();
  2795. }
  2796. void TPersQueue::SendEvTxCommitToPartitions(const TActorContext& ctx,
  2797. TDistributedTransaction& tx)
  2798. {
  2799. PQ_LOG_T("Commit tx " << tx.TxId);
  2800. for (ui32 partitionId : tx.Partitions) {
  2801. auto event = std::make_unique<TEvPQ::TEvTxCommit>(tx.Step, tx.TxId);
  2802. auto p = Partitions.find(partitionId);
  2803. Y_ABORT_UNLESS(p != Partitions.end());
  2804. ctx.Send(p->second.Actor, event.release());
  2805. }
  2806. tx.PartitionRepliesCount = 0;
  2807. tx.PartitionRepliesExpected = tx.Partitions.size();
  2808. }
  2809. void TPersQueue::SendEvTxRollbackToPartitions(const TActorContext& ctx,
  2810. TDistributedTransaction& tx)
  2811. {
  2812. PQ_LOG_T("Rollback tx " << tx.TxId);
  2813. for (ui32 partitionId : tx.Partitions) {
  2814. auto event = std::make_unique<TEvPQ::TEvTxRollback>(tx.Step, tx.TxId);
  2815. auto p = Partitions.find(partitionId);
  2816. Y_ABORT_UNLESS(p != Partitions.end());
  2817. ctx.Send(p->second.Actor, event.release());
  2818. }
  2819. tx.PartitionRepliesCount = 0;
  2820. tx.PartitionRepliesExpected = 0;
  2821. }
  2822. void TPersQueue::SendEvProposeTransactionResult(const TActorContext& ctx,
  2823. TDistributedTransaction& tx)
  2824. {
  2825. auto result = std::make_unique<TEvPersQueue::TEvProposeTransactionResult>();
  2826. auto status =
  2827. (tx.GetDecision() == NKikimrTx::TReadSetData::DECISION_COMMIT) ? NKikimrPQ::TEvProposeTransactionResult::COMPLETE : NKikimrPQ::TEvProposeTransactionResult::ABORTED;
  2828. result->Record.SetOrigin(TabletID());
  2829. result->Record.SetStatus(status);
  2830. result->Record.SetTxId(tx.TxId);
  2831. result->Record.SetStep(tx.Step);
  2832. ctx.Send(tx.SourceActor, std::move(result));
  2833. }
  2834. void TPersQueue::SendToPipe(ui64 tabletId,
  2835. TDistributedTransaction& tx,
  2836. std::unique_ptr<IEventBase> event,
  2837. const TActorContext& ctx)
  2838. {
  2839. Y_ABORT_UNLESS(event);
  2840. BindTxToPipe(tabletId, tx.TxId);
  2841. tx.BindMsgToPipe(tabletId, *event);
  2842. PipeClientCache->Send(ctx, tabletId, event.release());
  2843. }
  2844. void TPersQueue::BindTxToPipe(ui64 tabletId, ui64 txId)
  2845. {
  2846. BindedTxs[tabletId].insert(txId);
  2847. }
  2848. void TPersQueue::UnbindTxFromPipe(ui64 tabletId, ui64 txId)
  2849. {
  2850. if (auto p = BindedTxs.find(tabletId); p != BindedTxs.end()) {
  2851. p->second.erase(txId);
  2852. }
  2853. }
  2854. const THashSet<ui64>& TPersQueue::GetBindedTxs(ui64 tabletId)
  2855. {
  2856. if (auto p = BindedTxs.find(tabletId); p != BindedTxs.end()) {
  2857. return p->second;
  2858. }
  2859. static THashSet<ui64> empty;
  2860. return empty;
  2861. }
  2862. TDistributedTransaction* TPersQueue::GetTransaction(const TActorContext& ctx,
  2863. ui64 txId)
  2864. {
  2865. auto p = Txs.find(txId);
  2866. if (p == Txs.end()) {
  2867. LOG_WARN_S(ctx, NKikimrServices::PERSQUEUE,
  2868. "Tablet " << TabletID() <<
  2869. " Unknown transaction " << txId);
  2870. return nullptr;
  2871. }
  2872. return &p->second;
  2873. }
  2874. void TPersQueue::CheckTxState(const TActorContext& ctx,
  2875. TDistributedTransaction& tx)
  2876. {
  2877. switch (tx.State) {
  2878. case NKikimrPQ::TTransaction::UNKNOWN:
  2879. Y_ABORT_UNLESS(tx.TxId != Max<ui64>());
  2880. PQ_LOG_T("TxId="<< tx.TxId << ", State=UNKNOWN");
  2881. WriteTx(tx, NKikimrPQ::TTransaction::PREPARED);
  2882. ScheduleProposeTransactionResult(tx);
  2883. tx.State = NKikimrPQ::TTransaction::PREPARING;
  2884. break;
  2885. case NKikimrPQ::TTransaction::PREPARING:
  2886. Y_ABORT_UNLESS(tx.WriteInProgress);
  2887. PQ_LOG_T("TxId="<< tx.TxId << ", State=PREPARING");
  2888. tx.WriteInProgress = false;
  2889. //
  2890. // запланированные события будут отправлены в EndWriteTxs
  2891. //
  2892. tx.State = NKikimrPQ::TTransaction::PREPARED;
  2893. break;
  2894. case NKikimrPQ::TTransaction::PREPARED:
  2895. Y_ABORT_UNLESS(tx.Step != Max<ui64>());
  2896. PQ_LOG_T("TxId="<< tx.TxId << ", State=PREPARED");
  2897. WriteTx(tx, NKikimrPQ::TTransaction::PLANNED);
  2898. tx.State = NKikimrPQ::TTransaction::PLANNING;
  2899. break;
  2900. case NKikimrPQ::TTransaction::PLANNING:
  2901. Y_ABORT_UNLESS(tx.WriteInProgress);
  2902. PQ_LOG_T("TxId="<< tx.TxId << ", State=PLANNING");
  2903. tx.WriteInProgress = false;
  2904. //
  2905. // запланированные события будут отправлены в EndWriteTxs
  2906. //
  2907. tx.State = NKikimrPQ::TTransaction::PLANNED;
  2908. [[fallthrough]];
  2909. case NKikimrPQ::TTransaction::PLANNED:
  2910. PQ_LOG_T("TxId="<< tx.TxId << ", State=PLANNED" <<
  2911. ", (!TxQueue.empty())=" << !TxQueue.empty());
  2912. if (!TxQueue.empty() && (TxQueue.front().second == tx.TxId)) {
  2913. switch (tx.Kind) {
  2914. case NKikimrPQ::TTransaction::KIND_DATA:
  2915. SendEvTxCalcPredicateToPartitions(ctx, tx);
  2916. break;
  2917. case NKikimrPQ::TTransaction::KIND_CONFIG: {
  2918. NPersQueue::TConverterFactoryPtr converterFactory;
  2919. CreateTopicConverter(tx.TabletConfig,
  2920. converterFactory,
  2921. tx.TopicConverter,
  2922. ctx);
  2923. CreateNewPartitions(tx.TabletConfig,
  2924. tx.TopicConverter,
  2925. ctx);
  2926. SendEvProposePartitionConfig(ctx, tx);
  2927. break;
  2928. }
  2929. case NKikimrPQ::TTransaction::KIND_UNKNOWN:
  2930. Y_ABORT_UNLESS(false);
  2931. }
  2932. tx.State = NKikimrPQ::TTransaction::CALCULATING;
  2933. }
  2934. break;
  2935. case NKikimrPQ::TTransaction::CALCULATING:
  2936. Y_ABORT_UNLESS(tx.PartitionRepliesCount <= tx.PartitionRepliesExpected);
  2937. PQ_LOG_T("TxId="<< tx.TxId << ", State=CALCULATING" <<
  2938. ", tx.PartitionRepliesCount=" << tx.PartitionRepliesCount <<
  2939. ", tx.PartitionRepliesExpected=" << tx.PartitionRepliesExpected);
  2940. if (tx.PartitionRepliesCount == tx.PartitionRepliesExpected) {
  2941. switch (tx.Kind) {
  2942. case NKikimrPQ::TTransaction::KIND_DATA:
  2943. SendEvReadSetToReceivers(ctx, tx);
  2944. WriteTx(tx, NKikimrPQ::TTransaction::WAIT_RS);
  2945. tx.State = NKikimrPQ::TTransaction::CALCULATED;
  2946. break;
  2947. case NKikimrPQ::TTransaction::KIND_CONFIG:
  2948. SendEvReadSetToReceivers(ctx, tx);
  2949. tx.State = NKikimrPQ::TTransaction::WAIT_RS;
  2950. CheckTxState(ctx, tx);
  2951. break;
  2952. case NKikimrPQ::TTransaction::KIND_UNKNOWN:
  2953. Y_ABORT_UNLESS(false);
  2954. }
  2955. }
  2956. break;
  2957. case NKikimrPQ::TTransaction::CALCULATED:
  2958. Y_ABORT_UNLESS(tx.WriteInProgress);
  2959. PQ_LOG_T("TxId="<< tx.TxId << ", State=CALCULATED");
  2960. tx.WriteInProgress = false;
  2961. tx.State = NKikimrPQ::TTransaction::WAIT_RS;
  2962. [[fallthrough]];
  2963. case NKikimrPQ::TTransaction::WAIT_RS:
  2964. //
  2965. // the number of TEvReadSetAck sent should not be greater than the number of senders
  2966. // from TEvProposeTransaction
  2967. //
  2968. Y_ABORT_UNLESS(tx.ReadSetAcks.size() <= tx.Senders.size());
  2969. PQ_LOG_T("TxId="<< tx.TxId << ", State=WAIT_RS" <<
  2970. ", tx.HaveParticipantsDecision()=" << tx.HaveParticipantsDecision());
  2971. if (tx.HaveParticipantsDecision()) {
  2972. SendEvProposeTransactionResult(ctx, tx);
  2973. if (tx.GetDecision() == NKikimrTx::TReadSetData::DECISION_COMMIT) {
  2974. SendEvTxCommitToPartitions(ctx, tx);
  2975. } else {
  2976. SendEvTxRollbackToPartitions(ctx, tx);
  2977. }
  2978. tx.State = NKikimrPQ::TTransaction::EXECUTING;
  2979. } else {
  2980. break;
  2981. }
  2982. [[fallthrough]];
  2983. case NKikimrPQ::TTransaction::EXECUTING:
  2984. Y_ABORT_UNLESS(tx.PartitionRepliesCount <= tx.PartitionRepliesExpected);
  2985. PQ_LOG_T("TxId="<< tx.TxId << ", State=EXECUTING" <<
  2986. ", tx.PartitionRepliesCount=" << tx.PartitionRepliesCount <<
  2987. ", tx.PartitionRepliesExpected=" << tx.PartitionRepliesExpected);
  2988. if (tx.PartitionRepliesCount == tx.PartitionRepliesExpected) {
  2989. Y_ABORT_UNLESS(!TxQueue.empty());
  2990. Y_ABORT_UNLESS(TxQueue.front().second == tx.TxId);
  2991. switch (tx.Kind) {
  2992. case NKikimrPQ::TTransaction::KIND_DATA:
  2993. SendEvReadSetAckToSenders(ctx, tx);
  2994. break;
  2995. case NKikimrPQ::TTransaction::KIND_CONFIG:
  2996. SendEvReadSetAckToSenders(ctx, tx);
  2997. ApplyNewConfig(tx.TabletConfig, ctx);
  2998. TabletConfigTx = tx.TabletConfig;
  2999. BootstrapConfigTx = tx.BootstrapConfig;
  3000. break;
  3001. case NKikimrPQ::TTransaction::KIND_UNKNOWN:
  3002. Y_ABORT_UNLESS(false);
  3003. }
  3004. tx.State = NKikimrPQ::TTransaction::EXECUTED;
  3005. TxQueue.pop();
  3006. TryStartTransaction(ctx);
  3007. } else {
  3008. break;
  3009. }
  3010. [[fallthrough]];
  3011. case NKikimrPQ::TTransaction::EXECUTED:
  3012. PQ_LOG_T("TxId="<< tx.TxId << ", State=EXECUTED, tx.HaveAllRecipientsReceive()=" << tx.HaveAllRecipientsReceive());
  3013. if (tx.HaveAllRecipientsReceive()) {
  3014. DeleteTx(tx);
  3015. }
  3016. break;
  3017. }
  3018. }
  3019. void TPersQueue::WriteTx(TDistributedTransaction& tx, NKikimrPQ::TTransaction::EState state)
  3020. {
  3021. WriteTxs[tx.TxId] = state;
  3022. tx.WriteInProgress = true;
  3023. }
  3024. void TPersQueue::DeleteTx(TDistributedTransaction& tx)
  3025. {
  3026. DeleteTxs.insert(tx.TxId);
  3027. tx.WriteInProgress = true;
  3028. }
  3029. void TPersQueue::SendReplies(const TActorContext& ctx)
  3030. {
  3031. for (auto& [actorId, event] : RepliesToActor) {
  3032. ctx.Send(actorId, event.release());
  3033. }
  3034. RepliesToActor.clear();
  3035. }
  3036. void TPersQueue::CheckChangedTxStates(const TActorContext& ctx)
  3037. {
  3038. for (ui64 txId : ChangedTxs) {
  3039. auto tx = GetTransaction(ctx, txId);
  3040. Y_ABORT_UNLESS(tx);
  3041. CheckTxState(ctx, *tx);
  3042. }
  3043. ChangedTxs.clear();
  3044. }
  3045. void TPersQueue::InitProcessingParams(const TActorContext& ctx)
  3046. {
  3047. if (Info()->TenantPathId) {
  3048. UseMediatorTimeCast = true;
  3049. StartWatchingTenantPathId(ctx);
  3050. return;
  3051. }
  3052. auto appdata = AppData(ctx);
  3053. const ui32 domainId = appdata->DomainsInfo->GetDomainUidByTabletId(TabletID());
  3054. Y_ABORT_UNLESS(domainId != appdata->DomainsInfo->BadDomainId);
  3055. const auto& domain = appdata->DomainsInfo->GetDomain(domainId);
  3056. ProcessingParams = ExtractProcessingParams(domain);
  3057. InitMediatorTimeCast(ctx);
  3058. }
  3059. void TPersQueue::InitMediatorTimeCast(const TActorContext& ctx)
  3060. {
  3061. Y_ABORT_UNLESS(ProcessingParams);
  3062. if (ProcessingParams->MediatorsSize()) {
  3063. UseMediatorTimeCast = true;
  3064. MediatorTimeCastRegisterTablet(ctx);
  3065. } else {
  3066. UseMediatorTimeCast = false;
  3067. TryWriteTxs(ctx);
  3068. }
  3069. }
  3070. bool TPersQueue::AllTransactionsHaveBeenProcessed() const
  3071. {
  3072. return EvProposeTransactionQueue.empty() && Txs.empty();
  3073. }
  3074. void TPersQueue::SendProposeTransactionAbort(const TActorId& target,
  3075. ui64 txId,
  3076. const TActorContext& ctx)
  3077. {
  3078. auto event = std::make_unique<TEvPersQueue::TEvProposeTransactionResult>();
  3079. event->Record.SetOrigin(TabletID());
  3080. event->Record.SetStatus(NKikimrPQ::TEvProposeTransactionResult::ABORTED);
  3081. event->Record.SetTxId(txId);
  3082. ctx.Send(target, std::move(event));
  3083. }
  3084. void TPersQueue::SendEvProposePartitionConfig(const TActorContext& ctx,
  3085. TDistributedTransaction& tx)
  3086. {
  3087. for (auto& [_, partition] : Partitions) {
  3088. auto event = std::make_unique<TEvPQ::TEvProposePartitionConfig>(tx.Step, tx.TxId);
  3089. event->TopicConverter = tx.TopicConverter;
  3090. event->Config = tx.TabletConfig;
  3091. ctx.Send(partition.Actor, std::move(event));
  3092. }
  3093. tx.PartitionRepliesCount = 0;
  3094. tx.PartitionRepliesExpected = Partitions.size();
  3095. }
  3096. TPartition* TPersQueue::CreatePartitionActor(ui32 partitionId,
  3097. const NPersQueue::TTopicConverterPtr topicConverter,
  3098. const NKikimrPQ::TPQTabletConfig& config,
  3099. bool newPartition,
  3100. const TActorContext& ctx)
  3101. {
  3102. int channels = Info()->Channels.size() - NKeyValue::BLOB_CHANNEL; // channels 0,1 are reserved in tablet
  3103. Y_ABORT_UNLESS(channels > 0);
  3104. return new TPartition(TabletID(),
  3105. partitionId,
  3106. ctx.SelfID,
  3107. GetGeneration(),
  3108. CacheActor,
  3109. topicConverter,
  3110. DCId,
  3111. IsServerless,
  3112. config,
  3113. *Counters,
  3114. SubDomainOutOfSpace,
  3115. (ui32)channels,
  3116. newPartition);
  3117. }
  3118. void TPersQueue::CreateNewPartitions(NKikimrPQ::TPQTabletConfig& config,
  3119. NPersQueue::TTopicConverterPtr topicConverter,
  3120. const TActorContext& ctx)
  3121. {
  3122. EnsurePartitionsAreNotDeleted(config);
  3123. Y_ABORT_UNLESS(ConfigInited && PartitionsInited == Partitions.size());
  3124. if (!config.PartitionsSize()) {
  3125. for (const auto partitionId : config.GetPartitionIds()) {
  3126. config.AddPartitions()->SetPartitionId(partitionId);
  3127. }
  3128. }
  3129. for (const auto& partition : config.GetPartitions()) {
  3130. const auto partitionId = partition.GetPartitionId();
  3131. if (Partitions.contains(partitionId)) {
  3132. continue;
  3133. }
  3134. TActorId actorId = ctx.Register(CreatePartitionActor(partitionId, topicConverter, config, true, ctx));
  3135. Partitions.emplace(std::piecewise_construct,
  3136. std::forward_as_tuple(partitionId),
  3137. std::forward_as_tuple(actorId,
  3138. GetPartitionKeyRange(config, partition),
  3139. *Counters));
  3140. }
  3141. }
  3142. void TPersQueue::EnsurePartitionsAreNotDeleted(const NKikimrPQ::TPQTabletConfig& config) const
  3143. {
  3144. THashSet<ui32> was;
  3145. if (config.PartitionsSize()) {
  3146. for (const auto& partition : config.GetPartitions()) {
  3147. was.insert(partition.GetPartitionId());
  3148. }
  3149. } else {
  3150. for (const auto partitionId : config.GetPartitionIds()) {
  3151. was.insert(partitionId);
  3152. }
  3153. }
  3154. for (const auto& partition : Config.GetPartitions()) {
  3155. Y_VERIFY_S(was.contains(partition.GetPartitionId()), "New config is bad, missing partition " << partition.GetPartitionId());
  3156. }
  3157. }
  3158. void TPersQueue::InitTransactions(const NKikimrClient::TKeyValueResponse::TReadRangeResult& readRange,
  3159. THashMap<ui32, TVector<TTransaction>>& partitionTxs)
  3160. {
  3161. Txs.clear();
  3162. TxQueue.clear();
  3163. std::deque<std::pair<ui64, ui64>> plannedTxs;
  3164. for (size_t i = 0; i < readRange.PairSize(); ++i) {
  3165. auto& pair = readRange.GetPair(i);
  3166. NKikimrPQ::TTransaction tx;
  3167. Y_ABORT_UNLESS(tx.ParseFromString(pair.GetValue()));
  3168. Txs.emplace(tx.GetTxId(), tx);
  3169. if (tx.HasStep()) {
  3170. if (std::make_pair(tx.GetStep(), tx.GetTxId()) >= std::make_pair(LastStep, LastTxId)) {
  3171. plannedTxs.emplace_back(tx.GetStep(), tx.GetTxId());
  3172. }
  3173. }
  3174. }
  3175. std::sort(plannedTxs.begin(), plannedTxs.end());
  3176. for (auto& item : plannedTxs) {
  3177. TxQueue.push(item);
  3178. }
  3179. Y_UNUSED(partitionTxs);
  3180. }
  3181. void TPersQueue::TryStartTransaction(const TActorContext& ctx)
  3182. {
  3183. if (TxQueue.empty()) {
  3184. return;
  3185. }
  3186. auto next = GetTransaction(ctx, TxQueue.front().second);
  3187. Y_ABORT_UNLESS(next);
  3188. CheckTxState(ctx, *next);
  3189. }
  3190. void TPersQueue::OnInitComplete(const TActorContext& ctx)
  3191. {
  3192. SignalTabletActive(ctx);
  3193. TryStartTransaction(ctx);
  3194. InitCompleted = true;
  3195. }
  3196. ui64 TPersQueue::GetAllowedStep() const
  3197. {
  3198. return Max(LastStep + 1,
  3199. MediatorTimeCastEntry ? MediatorTimeCastEntry->Get(TabletID()) : TAppData::TimeProvider->Now().MilliSeconds());
  3200. }
  3201. NTabletPipe::TClientConfig TPersQueue::GetPipeClientConfig()
  3202. {
  3203. NTabletPipe::TClientConfig config;
  3204. config.CheckAliveness = true;
  3205. config.RetryPolicy = {
  3206. .RetryLimitCount = 30,
  3207. .MinRetryTime = TDuration::MilliSeconds(10),
  3208. .MaxRetryTime = TDuration::MilliSeconds(500),
  3209. .BackoffMultiplier = 2,
  3210. };
  3211. return config;
  3212. }
  3213. void TPersQueue::Handle(TEvPQ::TEvSubDomainStatus::TPtr& ev, const TActorContext& ctx)
  3214. {
  3215. const TEvPQ::TEvSubDomainStatus& event = *ev->Get();
  3216. SubDomainOutOfSpace = event.SubDomainOutOfSpace();
  3217. for (auto& p : Partitions) {
  3218. ctx.Send(p.second.Actor, new TEvPQ::TEvSubDomainStatus(event.SubDomainOutOfSpace()));
  3219. }
  3220. }
  3221. void TPersQueue::Handle(TEvPersQueue::TEvProposeTransactionAttach::TPtr &ev, const TActorContext &ctx)
  3222. {
  3223. const ui64 txId = ev->Get()->Record.GetTxId();
  3224. NKikimrProto::EReplyStatus status = NKikimrProto::NODATA;
  3225. auto tx = GetTransaction(ctx, txId);
  3226. if (tx) {
  3227. //
  3228. // the actor's ID could have changed from the moment he sent the TEvProposeTransaction. you need to
  3229. // update the actor ID in the transaction
  3230. //
  3231. // if the transaction has progressed beyond WAIT_RS, then a response has been sent to the sender
  3232. //
  3233. tx->SourceActor = ev->Sender;
  3234. if (tx->State <= NKikimrPQ::TTransaction::WAIT_RS) {
  3235. status = NKikimrProto::OK;
  3236. }
  3237. }
  3238. ctx.Send(ev->Sender, new TEvPersQueue::TEvProposeTransactionAttachResult(TabletID(), txId, status), 0, ev->Cookie);
  3239. }
  3240. void TPersQueue::Handle(TEvPQ::TEvSourceIdRequest::TPtr& ev, const TActorContext& ctx) {
  3241. auto& record = ev->Get()->Record;
  3242. auto it = Partitions.find(record.GetPartition());
  3243. if (it == Partitions.end()) {
  3244. LOG_INFO_S(ctx, NKikimrServices::PERSQUEUE, "Unknown partition " << record.GetPartition());
  3245. auto response = MakeHolder<TEvPQ::TEvSourceIdResponse>();
  3246. response->Record.SetError("Partition was not found");
  3247. Send(ev->Sender, response.Release());
  3248. return;
  3249. }
  3250. if (it->second.InitDone) {
  3251. Forward(ev, it->second.Actor);
  3252. } else {
  3253. SourceIdRequests[record.GetPartition()].push_back(ev);
  3254. }
  3255. }
  3256. void TPersQueue::ProcessSourceIdRequests(ui32 partitionId) {
  3257. auto sit = SourceIdRequests.find(partitionId);
  3258. if (sit != SourceIdRequests.end()) {
  3259. auto it = Partitions.find(partitionId);
  3260. for (auto& r : sit->second) {
  3261. Forward(r, it->second.Actor);
  3262. }
  3263. SourceIdRequests.erase(partitionId);
  3264. }
  3265. }
  3266. TString TPersQueue::LogPrefix() const {
  3267. return TStringBuilder() << SelfId() << " ";
  3268. }
  3269. ui64 TPersQueue::GetGeneration() {
  3270. if (!TabletGeneration.Defined()) {
  3271. TabletGeneration = Executor()->Generation();
  3272. }
  3273. return *TabletGeneration;
  3274. }
  3275. bool TPersQueue::HandleHook(STFUNC_SIG)
  3276. {
  3277. SetActivityType(NKikimrServices::TActivity::PERSQUEUE_ACTOR);
  3278. TRACE_EVENT(NKikimrServices::PERSQUEUE);
  3279. switch(ev->GetTypeRewrite())
  3280. {
  3281. HFuncTraced(TEvInterconnect::TEvNodeInfo, Handle);
  3282. HFuncTraced(TEvPersQueue::TEvRequest, Handle);
  3283. HFuncTraced(TEvPersQueue::TEvUpdateConfig, Handle);
  3284. HFuncTraced(TEvPersQueue::TEvOffsets, Handle);
  3285. HFuncTraced(TEvPersQueue::TEvHasDataInfo, Handle);
  3286. HFuncTraced(TEvPersQueue::TEvStatus, Handle);
  3287. HFuncTraced(TEvPersQueue::TEvPartitionClientInfo, Handle);
  3288. HFuncTraced(TEvKeyValue::TEvResponse, Handle);
  3289. HFuncTraced(TEvPQ::TEvInitComplete, Handle);
  3290. HFuncTraced(TEvPQ::TEvPartitionCounters, Handle);
  3291. HFuncTraced(TEvPQ::TEvMetering, Handle);
  3292. HFuncTraced(TEvPQ::TEvPartitionLabeledCounters, Handle);
  3293. HFuncTraced(TEvPQ::TEvPartitionLabeledCountersDrop, Handle);
  3294. HFuncTraced(TEvPQ::TEvTabletCacheCounters, Handle);
  3295. HFuncTraced(TEvPersQueue::TEvDropTablet, Handle);
  3296. HFuncTraced(TEvTabletPipe::TEvServerConnected, Handle);
  3297. HFuncTraced(TEvTabletPipe::TEvServerDisconnected, Handle);
  3298. HFuncTraced(TEvTabletPipe::TEvClientConnected, Handle);
  3299. HFuncTraced(TEvTabletPipe::TEvClientDestroyed, Handle);
  3300. HFuncTraced(TEvPQ::TEvError, Handle);
  3301. HFuncTraced(TEvPQ::TEvProxyResponse, Handle);
  3302. CFunc(TEvents::TSystem::Wakeup, HandleWakeup);
  3303. HFuncTraced(TEvPersQueue::TEvProposeTransaction, Handle);
  3304. HFuncTraced(TEvPQ::TEvPartitionConfigChanged, Handle);
  3305. HFuncTraced(TEvTxProcessing::TEvPlanStep, Handle);
  3306. HFuncTraced(TEvTxProcessing::TEvReadSet, Handle);
  3307. HFuncTraced(TEvTxProcessing::TEvReadSetAck, Handle);
  3308. HFuncTraced(TEvPQ::TEvTxCalcPredicateResult, Handle);
  3309. HFuncTraced(TEvPQ::TEvProposePartitionConfigResult, Handle);
  3310. HFuncTraced(TEvPQ::TEvTxCommitDone, Handle);
  3311. HFuncTraced(TEvPQ::TEvSubDomainStatus, Handle);
  3312. HFuncTraced(TEvPersQueue::TEvProposeTransactionAttach, Handle);
  3313. HFuncTraced(TEvTxProxySchemeCache::TEvWatchNotifyUpdated, Handle);
  3314. HFuncTraced(TEvPersQueue::TEvCancelTransactionProposal, Handle);
  3315. HFuncTraced(TEvMediatorTimecast::TEvRegisterTabletResult, Handle);
  3316. HFuncTraced(TEvPQ::TEvSourceIdRequest, Handle);
  3317. default:
  3318. return false;
  3319. }
  3320. return true;
  3321. }
  3322. } // namespace NKikimr::NPQ