tq.c 38.6 KB
Newer Older
H
refact  
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
S
Shengliang Guan 已提交
14 15
 */

H
Hongze Cheng 已提交
16
#include "tq.h"
L
Liu Jicong 已提交
17
#include "tqueue.h"
S
Shengliang Guan 已提交
18

L
Liu Jicong 已提交
19 20 21 22
int32_t tqInit() {
  //
  return 0;
}
L
Liu Jicong 已提交
23

L
Liu Jicong 已提交
24
void tqCleanUp() {}
L
Liu Jicong 已提交
25

L
Liu Jicong 已提交
26
STQ* tqOpen(const char* path, SVnode* pVnode, SWal* pWal) {
wafwerar's avatar
wafwerar 已提交
27
  STQ* pTq = taosMemoryMalloc(sizeof(STQ));
L
Liu Jicong 已提交
28
  if (pTq == NULL) {
L
Liu Jicong 已提交
29
    terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
L
Liu Jicong 已提交
30 31
    return NULL;
  }
H
Hongze Cheng 已提交
32
  pTq->path = strdup(path);
L
Liu Jicong 已提交
33
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
34
  pTq->pWal = pWal;
35 36 37
  /*if (tdbOpen(path, 4096, 1, &pTq->pTdb) < 0) {*/
  /*ASSERT(0);*/
  /*}*/
38

L
Liu Jicong 已提交
39
#if 0
L
Liu Jicong 已提交
40 41
  pTq->tqMeta = tqStoreOpen(pTq, path, (FTqSerialize)tqSerializeConsumer, (FTqDeserialize)tqDeserializeConsumer,
                            (FTqDelete)taosMemoryFree, 0);
L
Liu Jicong 已提交
42
  if (pTq->tqMeta == NULL) {
wafwerar's avatar
wafwerar 已提交
43
    taosMemoryFree(pTq);
L
Liu Jicong 已提交
44 45
    return NULL;
  }
L
Liu Jicong 已提交
46
#endif
L
Liu Jicong 已提交
47

L
Liu Jicong 已提交
48
  pTq->execs = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
49

L
Liu Jicong 已提交
50 51
  pTq->pStreamTasks = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);

L
Liu Jicong 已提交
52 53
  pTq->pushMgr = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);

L
Liu Jicong 已提交
54 55
  return pTq;
}
L
Liu Jicong 已提交
56

L
Liu Jicong 已提交
57
void tqClose(STQ* pTq) {
H
Hongze Cheng 已提交
58
  if (pTq) {
wafwerar's avatar
wafwerar 已提交
59 60
    taosMemoryFreeClear(pTq->path);
    taosMemoryFree(pTq);
H
Hongze Cheng 已提交
61
  }
L
Liu Jicong 已提交
62 63
  // TODO
}
L
Liu Jicong 已提交
64

L
Liu Jicong 已提交
65 66 67 68 69 70 71 72
static void tdSRowDemo() {
#define DEMO_N_COLS 3

  int16_t     schemaVersion = 0;
  int32_t     numOfCols = DEMO_N_COLS;  // ts + int
  SRowBuilder rb = {0};

  SSchema schema[DEMO_N_COLS] = {
H
Hongze Cheng 已提交
73 74 75
      {.type = TSDB_DATA_TYPE_TIMESTAMP, .colId = 1, .name = "ts", .bytes = 8, .flags = COL_SMA_ON},
      {.type = TSDB_DATA_TYPE_INT, .colId = 2, .name = "c1", .bytes = 4, .flags = COL_SMA_ON},
      {.type = TSDB_DATA_TYPE_INT, .colId = 3, .name = "c2", .bytes = 4, .flags = COL_SMA_ON}};
L
Liu Jicong 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

  SSchema*  pSchema = schema;
  STSchema* pTSChema = tdGetSTSChemaFromSSChema(&pSchema, numOfCols);

  tdSRowInit(&rb, schemaVersion);
  tdSRowSetTpInfo(&rb, numOfCols, pTSChema->flen);
  int32_t maxLen = TD_ROW_MAX_BYTES_FROM_SCHEMA(pTSChema);
  void*   row = taosMemoryCalloc(1, maxLen);  // make sure the buffer is enough

  // set row buf
  tdSRowResetBuf(&rb, row);

  for (int32_t idx = 0; idx < pTSChema->numOfCols; ++idx) {
    STColumn* pColumn = pTSChema->columns + idx;
    if (idx == 0) {
      int64_t tsKey = 1651234567;
      tdAppendColValToRow(&rb, pColumn->colId, pColumn->type, TD_VTYPE_NORM, &tsKey, true, pColumn->offset, idx);
    } else if (idx == 1) {
      int32_t val1 = 10;
      tdAppendColValToRow(&rb, pColumn->colId, pColumn->type, TD_VTYPE_NORM, &val1, true, pColumn->offset, idx);
    } else {
      tdAppendColValToRow(&rb, pColumn->colId, pColumn->type, TD_VTYPE_NONE, NULL, true, pColumn->offset, idx);
    }
  }

  // print
  tdSRowPrint(row, pTSChema, __func__);

  taosMemoryFree(pTSChema);
}

107
int32_t tqUpdateTbUidList(STQ* pTq, const SArray* tbUidList, bool isAdd) {
108 109 110 111 112 113
  void*    pIter = NULL;
  STqExec* pExec = NULL;
  while (1) {
    pIter = taosHashIterate(pTq->execs, pIter);
    if (pIter == NULL) break;
    pExec = (STqExec*)pIter;
114
    if (pExec->subType == TOPIC_SUB_TYPE__DB) {
L
Liu Jicong 已提交
115
      if (!isAdd) {
116 117 118 119 120 121
        int32_t sz = taosArrayGetSize(tbUidList);
        for (int32_t i = 0; i < sz; i++) {
          int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
          taosHashPut(pExec->pDropTbUid, &tbUid, sizeof(int64_t), NULL, 0);
        }
      }
L
Liu Jicong 已提交
122 123 124 125 126
    } else {
      for (int32_t i = 0; i < 5; i++) {
        int32_t code = qUpdateQualifiedTableId(pExec->task[i], tbUidList, isAdd);
        ASSERT(code == 0);
      }
127 128 129 130 131
    }
  }
  return 0;
}

L
Liu Jicong 已提交
132 133 134 135 136 137 138 139 140 141 142
int32_t tqPushMsgNew(STQ* pTq, void* msg, int32_t msgLen, tmsg_t msgType, int64_t ver) {
  if (msgType != TDMT_VND_SUBMIT) return 0;
  void*       pIter = NULL;
  STqExec*    pExec = NULL;
  SSubmitReq* pReq = (SSubmitReq*)msg;
  int32_t     workerId = 4;
  int64_t     fetchOffset = ver;

  while (1) {
    pIter = taosHashIterate(pTq->pushMgr, pIter);
    if (pIter == NULL) break;
L
Liu Jicong 已提交
143
    pExec = *(STqExec**)pIter;
L
Liu Jicong 已提交
144 145 146 147 148 149 150 151

    taosWLockLatch(&pExec->pushHandle.lock);

    SRpcMsg* pMsg = atomic_load_ptr(&pExec->pushHandle.handle);
    ASSERT(pMsg);

    SMqDataBlkRsp rsp = {0};
    rsp.reqOffset = pExec->pushHandle.reqOffset;
152
    rsp.blockData = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    rsp.blockDataLen = taosArrayInit(0, sizeof(int32_t));

    if (pExec->subType == TOPIC_SUB_TYPE__TABLE) {
      qTaskInfo_t task = pExec->task[workerId];
      ASSERT(task);
      qSetStreamInput(task, pReq, STREAM_DATA_TYPE_SUBMIT_BLOCK);
      while (1) {
        SSDataBlock* pDataBlock = NULL;
        uint64_t     ts = 0;
        if (qExecTask(task, &pDataBlock, &ts) < 0) {
          ASSERT(0);
        }
        if (pDataBlock == NULL) break;

        ASSERT(pDataBlock->info.rows != 0);
        ASSERT(pDataBlock->info.numOfCols != 0);

        int32_t            dataStrLen = sizeof(SRetrieveTableRsp) + blockGetEncodeSize(pDataBlock);
        void*              buf = taosMemoryCalloc(1, dataStrLen);
        SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)buf;
        pRetrieve->useconds = ts;
        pRetrieve->precision = TSDB_DEFAULT_PRECISION;
        pRetrieve->compressed = 0;
        pRetrieve->completed = 1;
        pRetrieve->numOfRows = htonl(pDataBlock->info.rows);

        // TODO enable compress
        int32_t actualLen = 0;
        blockCompressEncode(pDataBlock, pRetrieve->data, &actualLen, pDataBlock->info.numOfCols, false);
        actualLen += sizeof(SRetrieveTableRsp);
        ASSERT(actualLen <= dataStrLen);
        taosArrayPush(rsp.blockDataLen, &actualLen);
        taosArrayPush(rsp.blockData, &buf);
        rsp.blockNum++;
      }
    } else if (pExec->subType == TOPIC_SUB_TYPE__DB) {
      STqReadHandle* pReader = pExec->pExecReader[workerId];
      tqReadHandleSetMsg(pReader, pReq, 0);
      while (tqNextDataBlock(pReader)) {
        SSDataBlock block = {0};
193
        if (tqRetrieveDataBlock(&block.pDataBlock, pReader, &block.info.groupId, &block.info.uid, &block.info.rows,
L
Liu Jicong 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
                                &block.info.numOfCols) < 0) {
          ASSERT(0);
        }
        int32_t            dataStrLen = sizeof(SRetrieveTableRsp) + blockGetEncodeSize(&block);
        void*              buf = taosMemoryCalloc(1, dataStrLen);
        SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)buf;
        /*pRetrieve->useconds = 0;*/
        pRetrieve->precision = TSDB_DEFAULT_PRECISION;
        pRetrieve->compressed = 0;
        pRetrieve->completed = 1;
        pRetrieve->numOfRows = htonl(block.info.rows);

        // TODO enable compress
        int32_t actualLen = 0;
        blockCompressEncode(&block, pRetrieve->data, &actualLen, block.info.numOfCols, false);
        actualLen += sizeof(SRetrieveTableRsp);
        ASSERT(actualLen <= dataStrLen);
        taosArrayPush(rsp.blockDataLen, &actualLen);
        taosArrayPush(rsp.blockData, &buf);
        rsp.blockNum++;
      }
    } else {
      ASSERT(0);
    }

    if (rsp.blockNum == 0) {
      taosWUnLockLatch(&pExec->pushHandle.lock);
      continue;
    }

    ASSERT(taosArrayGetSize(rsp.blockData) == rsp.blockNum);
    ASSERT(taosArrayGetSize(rsp.blockDataLen) == rsp.blockNum);

    rsp.rspOffset = fetchOffset;

    int32_t tlen = sizeof(SMqRspHead) + tEncodeSMqDataBlkRsp(NULL, &rsp);
    void*   buf = rpcMallocCont(tlen);
    if (buf == NULL) {
      pMsg->code = -1;
      return -1;
    }

    ((SMqRspHead*)buf)->mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
    ((SMqRspHead*)buf)->epoch = pExec->pushHandle.epoch;
    ((SMqRspHead*)buf)->consumerId = pExec->pushHandle.consumerId;

    void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
    tEncodeSMqDataBlkRsp(&abuf, &rsp);
    pMsg->pCont = buf;
    pMsg->contLen = tlen;
    pMsg->code = 0;
    tmsgSendRsp(pMsg);

    atomic_store_ptr(&pExec->pushHandle.handle, NULL);
    taosWUnLockLatch(&pExec->pushHandle.lock);

H
Hongze Cheng 已提交
250 251 252
    tqDebug("vg %d offset %ld from consumer %ld (epoch %d) send rsp, block num: %d, reqOffset: %ld, rspOffset: %ld",
            TD_VID(pTq->pVnode), fetchOffset, pExec->pushHandle.consumerId, pExec->pushHandle.epoch, rsp.blockNum,
            rsp.reqOffset, rsp.rspOffset);
L
Liu Jicong 已提交
253 254 255 256 257 258 259 260 261

    // TODO destroy
    taosArrayDestroy(rsp.blockData);
    taosArrayDestroy(rsp.blockDataLen);
  }

  return 0;
}

L
Liu Jicong 已提交
262
int tqPushMsg(STQ* pTq, void* msg, int32_t msgLen, tmsg_t msgType, int64_t ver) {
L
Liu Jicong 已提交
263
  if (msgType != TDMT_VND_SUBMIT) return 0;
L
Liu Jicong 已提交
264

L
Liu Jicong 已提交
265
  // make sure msgType == TDMT_VND_SUBMIT
266
  if (tdUpdateExpireWindow(pTq->pVnode->pSma, msg, ver) != 0) {
L
Liu Jicong 已提交
267
    return -1;
L
Liu Jicong 已提交
268
  }
C
Cary Xu 已提交
269

L
Liu Jicong 已提交
270 271 272 273
  if (taosHashGetSize(pTq->pStreamTasks) == 0) return 0;

  void* data = taosMemoryMalloc(msgLen);
  if (data == NULL) {
C
Cary Xu 已提交
274
    return -1;
C
Cary Xu 已提交
275
  }
L
Liu Jicong 已提交
276
  memcpy(data, msg, msgLen);
C
Cary Xu 已提交
277

L
Liu Jicong 已提交
278 279 280 281 282
  SRpcMsg req = {
      .msgType = TDMT_VND_STREAM_TRIGGER,
      .pCont = data,
      .contLen = msgLen,
  };
L
Liu Jicong 已提交
283

L
Liu Jicong 已提交
284
  tmsgPutToQueue(&pTq->pVnode->msgCb, FETCH_QUEUE, &req);
L
Liu Jicong 已提交
285

L
Liu Jicong 已提交
286 287 288
  return 0;
}

L
Liu Jicong 已提交
289 290 291 292 293
int tqCommit(STQ* pTq) {
  // do nothing
  /*return tqStorePersist(pTq->tqMeta);*/
  return 0;
}
L
Liu Jicong 已提交
294 295

int32_t tqGetTopicHandleSize(const STqTopic* pTopic) {
L
Liu Jicong 已提交
296 297
  return strlen(pTopic->topicName) + strlen(pTopic->sql) + strlen(pTopic->physicalPlan) + strlen(pTopic->qmsg) +
         sizeof(int64_t) * 3;
L
Liu Jicong 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
}

int32_t tqGetConsumerHandleSize(const STqConsumer* pConsumer) {
  int     num = taosArrayGetSize(pConsumer->topics);
  int32_t sz = 0;
  for (int i = 0; i < num; i++) {
    STqTopic* pTopic = taosArrayGet(pConsumer->topics, i);
    sz += tqGetTopicHandleSize(pTopic);
  }
  return sz;
}

static FORCE_INLINE int32_t tEncodeSTqTopic(void** buf, const STqTopic* pTopic) {
  int32_t tlen = 0;
  tlen += taosEncodeString(buf, pTopic->topicName);
  /*tlen += taosEncodeString(buf, pTopic->sql);*/
  /*tlen += taosEncodeString(buf, pTopic->physicalPlan);*/
  tlen += taosEncodeString(buf, pTopic->qmsg);
L
Liu Jicong 已提交
316 317 318
  /*tlen += taosEncodeFixedI64(buf, pTopic->persistedOffset);*/
  /*tlen += taosEncodeFixedI64(buf, pTopic->committedOffset);*/
  /*tlen += taosEncodeFixedI64(buf, pTopic->currentOffset);*/
L
Liu Jicong 已提交
319 320 321 322 323 324 325 326
  return tlen;
}

static FORCE_INLINE const void* tDecodeSTqTopic(const void* buf, STqTopic* pTopic) {
  buf = taosDecodeStringTo(buf, pTopic->topicName);
  /*buf = taosDecodeString(buf, &pTopic->sql);*/
  /*buf = taosDecodeString(buf, &pTopic->physicalPlan);*/
  buf = taosDecodeString(buf, &pTopic->qmsg);
L
Liu Jicong 已提交
327 328 329
  /*buf = taosDecodeFixedI64(buf, &pTopic->persistedOffset);*/
  /*buf = taosDecodeFixedI64(buf, &pTopic->committedOffset);*/
  /*buf = taosDecodeFixedI64(buf, &pTopic->currentOffset);*/
L
Liu Jicong 已提交
330 331 332 333 334 335 336 337
  return buf;
}

static FORCE_INLINE int32_t tEncodeSTqConsumer(void** buf, const STqConsumer* pConsumer) {
  int32_t sz;

  int32_t tlen = 0;
  tlen += taosEncodeFixedI64(buf, pConsumer->consumerId);
L
Liu Jicong 已提交
338
  tlen += taosEncodeFixedI32(buf, pConsumer->epoch);
L
Liu Jicong 已提交
339 340 341 342 343 344 345 346
  tlen += taosEncodeString(buf, pConsumer->cgroup);
  sz = taosArrayGetSize(pConsumer->topics);
  tlen += taosEncodeFixedI32(buf, sz);
  for (int32_t i = 0; i < sz; i++) {
    STqTopic* pTopic = taosArrayGet(pConsumer->topics, i);
    tlen += tEncodeSTqTopic(buf, pTopic);
  }
  return tlen;
L
Liu Jicong 已提交
347 348
}

L
Liu Jicong 已提交
349 350 351 352
static FORCE_INLINE const void* tDecodeSTqConsumer(const void* buf, STqConsumer* pConsumer) {
  int32_t sz;

  buf = taosDecodeFixedI64(buf, &pConsumer->consumerId);
L
Liu Jicong 已提交
353
  buf = taosDecodeFixedI32(buf, &pConsumer->epoch);
L
Liu Jicong 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  buf = taosDecodeStringTo(buf, pConsumer->cgroup);
  buf = taosDecodeFixedI32(buf, &sz);
  pConsumer->topics = taosArrayInit(sz, sizeof(STqTopic));
  if (pConsumer->topics == NULL) return NULL;
  for (int32_t i = 0; i < sz; i++) {
    STqTopic pTopic;
    buf = tDecodeSTqTopic(buf, &pTopic);
    taosArrayPush(pConsumer->topics, &pTopic);
  }
  return buf;
}

int tqSerializeConsumer(const STqConsumer* pConsumer, STqSerializedHead** ppHead) {
  int32_t sz = tEncodeSTqConsumer(NULL, pConsumer);

L
Liu Jicong 已提交
369
  if (sz > (*ppHead)->ssize) {
wafwerar's avatar
wafwerar 已提交
370
    void* tmpPtr = taosMemoryRealloc(*ppHead, sizeof(STqSerializedHead) + sz);
L
Liu Jicong 已提交
371
    if (tmpPtr == NULL) {
wafwerar's avatar
wafwerar 已提交
372
      taosMemoryFree(*ppHead);
L
Liu Jicong 已提交
373
      terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
L
Liu Jicong 已提交
374 375 376 377 378 379 380
      return -1;
    }
    *ppHead = tmpPtr;
    (*ppHead)->ssize = sz;
  }

  void* ptr = (*ppHead)->content;
L
Liu Jicong 已提交
381 382
  void* abuf = ptr;
  tEncodeSTqConsumer(&abuf, pConsumer);
L
Liu Jicong 已提交
383

L
Liu Jicong 已提交
384 385 386
  return 0;
}

L
Liu Jicong 已提交
387 388
int32_t tqDeserializeConsumer(STQ* pTq, const STqSerializedHead* pHead, STqConsumer** ppConsumer) {
  const void* str = pHead->content;
wafwerar's avatar
wafwerar 已提交
389
  *ppConsumer = taosMemoryCalloc(1, sizeof(STqConsumer));
L
Liu Jicong 已提交
390 391 392 393 394 395 396 397 398 399
  if (*ppConsumer == NULL) {
    terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
    return -1;
  }
  if (tDecodeSTqConsumer(str, *ppConsumer) == NULL) {
    terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
    return -1;
  }
  STqConsumer* pConsumer = *ppConsumer;
  int32_t      sz = taosArrayGetSize(pConsumer->topics);
L
Liu Jicong 已提交
400
  for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
401 402 403 404 405
    STqTopic* pTopic = taosArrayGet(pConsumer->topics, i);
    pTopic->pReadhandle = walOpenReadHandle(pTq->pWal);
    if (pTopic->pReadhandle == NULL) {
      ASSERT(false);
    }
L
Liu Jicong 已提交
406 407
    for (int j = 0; j < TQ_BUFFER_SIZE; j++) {
      pTopic->buffer.output[j].status = 0;
L
Liu Jicong 已提交
408
      STqReadHandle* pReadHandle = tqInitSubmitMsgScanner(pTq->pVnode->pMeta);
L
Liu Jicong 已提交
409 410
      SReadHandle    handle = {
             .reader = pReadHandle,
L
Liu Jicong 已提交
411
             .meta = pTq->pVnode->pMeta,
412
             .pMsgCb = &pTq->pVnode->msgCb,
L
Liu Jicong 已提交
413
      };
L
Liu Jicong 已提交
414 415
      pTopic->buffer.output[j].pReadHandle = pReadHandle;
      pTopic->buffer.output[j].task = qCreateStreamExecTaskInfo(pTopic->qmsg, &handle);
L
Liu Jicong 已提交
416
    }
L
Liu Jicong 已提交
417
  }
L
Liu Jicong 已提交
418 419

  return 0;
L
Liu Jicong 已提交
420
}
L
Liu Jicong 已提交
421

L
fix  
Liu Jicong 已提交
422
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg, int32_t workerId) {
L
Liu Jicong 已提交
423 424 425 426 427
  SMqPollReq* pReq = pMsg->pCont;
  int64_t     consumerId = pReq->consumerId;
  int64_t     waitTime = pReq->waitTime;
  int32_t     reqEpoch = pReq->epoch;
  int64_t     fetchOffset;
428

L
Liu Jicong 已提交
429
  // get offset to fetch message
L
Liu Jicong 已提交
430
  if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__EARLIEAST) {
L
Liu Jicong 已提交
431
    fetchOffset = walGetFirstVer(pTq->pWal);
L
Liu Jicong 已提交
432
  } else if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__LATEST) {
L
Liu Jicong 已提交
433
    fetchOffset = walGetCommittedVer(pTq->pWal);
L
Liu Jicong 已提交
434 435 436 437
  } else {
    fetchOffset = pReq->currentOffset + 1;
  }

H
Hongze Cheng 已提交
438 439
  tqDebug("tmq poll: consumer %ld (epoch %d) recv poll req in vg %d, req %ld %ld", consumerId, pReq->epoch,
          TD_VID(pTq->pVnode), pReq->currentOffset, fetchOffset);
L
fix  
Liu Jicong 已提交
440

L
Liu Jicong 已提交
441
  STqExec* pExec = taosHashGet(pTq->execs, pReq->subKey, strlen(pReq->subKey));
L
Liu Jicong 已提交
442
  ASSERT(pExec);
L
Liu Jicong 已提交
443

L
Liu Jicong 已提交
444
  int32_t consumerEpoch = atomic_load_32(&pExec->epoch);
L
Liu Jicong 已提交
445
  while (consumerEpoch < reqEpoch) {
L
Liu Jicong 已提交
446
    consumerEpoch = atomic_val_compare_exchange_32(&pExec->epoch, consumerEpoch, reqEpoch);
L
Liu Jicong 已提交
447 448
  }

449 450 451 452 453 454 455
  SWalHead* pHeadWithCkSum = taosMemoryMalloc(sizeof(SWalHead) + 2048);
  if (pHeadWithCkSum == NULL) {
    return -1;
  }

  walSetReaderCapacity(pExec->pWalReader, 2048);

L
Liu Jicong 已提交
456
  SMqDataBlkRsp rsp = {0};
L
Liu Jicong 已提交
457
  rsp.reqOffset = pReq->currentOffset;
L
Liu Jicong 已提交
458
  rsp.withSchema = pExec->withSchema;
L
Liu Jicong 已提交
459

L
Liu Jicong 已提交
460
  rsp.blockData = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
461
  rsp.blockDataLen = taosArrayInit(0, sizeof(int32_t));
L
Liu Jicong 已提交
462
  rsp.blockSchema = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
463
  rsp.blockTbName = taosArrayInit(0, sizeof(void*));
464

465 466 467 468 469 470
  int8_t withTbName = pExec->withTbName;
  if (pReq->withTbName != -1) {
    withTbName = pReq->withTbName;
  }
  rsp.withTbName = withTbName;

471
  while (1) {
L
Liu Jicong 已提交
472
    consumerEpoch = atomic_load_32(&pExec->epoch);
L
Liu Jicong 已提交
473
    if (consumerEpoch > reqEpoch) {
H
Hongze Cheng 已提交
474 475
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, found new consumer epoch %d discard req epoch %d",
              consumerId, pReq->epoch, TD_VID(pTq->pVnode), fetchOffset, consumerEpoch, reqEpoch);
L
Liu Jicong 已提交
476 477
      break;
    }
L
Liu Jicong 已提交
478

479 480 481
    taosThreadMutexLock(&pExec->pWalReader->mutex);

    if (walFetchHead(pExec->pWalReader, fetchOffset, pHeadWithCkSum) < 0) {
H
Hongze Cheng 已提交
482 483
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, no more log to return", consumerId, pReq->epoch,
              TD_VID(pTq->pVnode), fetchOffset);
484 485 486 487 488
      taosThreadMutexUnlock(&pExec->pWalReader->mutex);
      break;
    }

    if (pHeadWithCkSum->head.msgType != TDMT_VND_SUBMIT) {
L
Liu Jicong 已提交
489
      ASSERT(walSkipFetchBody(pExec->pWalReader, pHeadWithCkSum) == 0);
490
    } else {
L
Liu Jicong 已提交
491
      ASSERT(walFetchBody(pExec->pWalReader, &pHeadWithCkSum) == 0);
492 493 494 495 496 497 498
    }

    SWalReadHead* pHead = &pHeadWithCkSum->head;

    taosThreadMutexUnlock(&pExec->pWalReader->mutex);

#if 0
L
fix  
Liu Jicong 已提交
499
    SWalReadHead* pHead;
L
Liu Jicong 已提交
500
    if (walReadWithHandle_s(pExec->pWalReader, fetchOffset, &pHead) < 0) {
L
Liu Jicong 已提交
501 502
      // TODO: no more log, set timer to wait blocking time
      // if data inserted during waiting, launch query and
L
Liu Jicong 已提交
503
      // response to user
H
Hongze Cheng 已提交
504
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, no more log to return", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
505
             TD_VID(pTq->pVnode), fetchOffset);
L
Liu Jicong 已提交
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

#if 0
      // add to pushMgr
      taosWLockLatch(&pExec->pushHandle.lock);

      pExec->pushHandle.consumerId = consumerId;
      pExec->pushHandle.epoch = reqEpoch;
      pExec->pushHandle.reqOffset = rsp.reqOffset;
      pExec->pushHandle.skipLogNum = rsp.skipLogNum;
      pExec->pushHandle.handle = pMsg;

      taosWUnLockLatch(&pExec->pushHandle.lock);

      // TODO add timer

      // TODO: the pointer will always be valid?
      taosHashPut(pTq->pushMgr, &consumerId, sizeof(int64_t), &pExec, sizeof(void*));
      taosArrayDestroy(rsp.blockData);
      taosArrayDestroy(rsp.blockDataLen);
      return 0;
#endif

528 529 530
    break;
  }
#endif
L
Liu Jicong 已提交
531

H
Hongze Cheng 已提交
532 533
    tqDebug("tmq poll: consumer %ld (epoch %d) iter log, vg %d offset %ld msgType %d", consumerId, pReq->epoch,
            TD_VID(pTq->pVnode), fetchOffset, pHead->msgType);
L
Liu Jicong 已提交
534

L
fix  
Liu Jicong 已提交
535 536
    if (pHead->msgType == TDMT_VND_SUBMIT) {
      SSubmitReq* pCont = (SSubmitReq*)&pHead->body;
537
      // table subscribe
L
Liu Jicong 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
      if (pExec->subType == TOPIC_SUB_TYPE__TABLE) {
        qTaskInfo_t task = pExec->task[workerId];
        ASSERT(task);
        qSetStreamInput(task, pCont, STREAM_DATA_TYPE_SUBMIT_BLOCK);
        while (1) {
          SSDataBlock* pDataBlock = NULL;
          uint64_t     ts = 0;
          if (qExecTask(task, &pDataBlock, &ts) < 0) {
            ASSERT(0);
          }
          if (pDataBlock == NULL) break;

          ASSERT(pDataBlock->info.rows != 0);
          ASSERT(pDataBlock->info.numOfCols != 0);

          int32_t            dataStrLen = sizeof(SRetrieveTableRsp) + blockGetEncodeSize(pDataBlock);
          void*              buf = taosMemoryCalloc(1, dataStrLen);
          SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)buf;
          pRetrieve->useconds = ts;
          pRetrieve->precision = TSDB_DEFAULT_PRECISION;
          pRetrieve->compressed = 0;
          pRetrieve->completed = 1;
          pRetrieve->numOfRows = htonl(pDataBlock->info.rows);

          // TODO enable compress
          int32_t actualLen = 0;
          blockCompressEncode(pDataBlock, pRetrieve->data, &actualLen, pDataBlock->info.numOfCols, false);
          actualLen += sizeof(SRetrieveTableRsp);
          ASSERT(actualLen <= dataStrLen);
          taosArrayPush(rsp.blockDataLen, &actualLen);
          taosArrayPush(rsp.blockData, &buf);
L
Liu Jicong 已提交
569 570 571 572 573 574

          if (pExec->withSchema) {
            SSchemaWrapper* pSW = tCloneSSchemaWrapper(pExec->pExecReader[workerId]->pSchemaWrapper);
            taosArrayPush(rsp.blockSchema, &pSW);
          }

575
          if (withTbName) {
L
Liu Jicong 已提交
576 577 578 579 580 581 582 583 584 585 586
            SMetaReader mr = {0};
            metaReaderInit(&mr, pTq->pVnode->pMeta, 0);
            int64_t uid = pExec->pExecReader[workerId]->msgIter.uid;
            if (metaGetTableEntryByUid(&mr, uid) < 0) {
              ASSERT(0);
            }
            char* tbName = strdup(mr.me.name);
            taosArrayPush(rsp.blockTbName, &tbName);
            metaReaderClear(&mr);
          }

L
Liu Jicong 已提交
587
          rsp.blockNum++;
588
        }
589
        // db subscribe
L
Liu Jicong 已提交
590
      } else if (pExec->subType == TOPIC_SUB_TYPE__DB) {
L
Liu Jicong 已提交
591
        rsp.withSchema = 1;
L
Liu Jicong 已提交
592
        STqReadHandle* pReader = pExec->pExecReader[workerId];
L
Liu Jicong 已提交
593
        tqReadHandleSetMsg(pReader, pCont, 0);
594
        while (tqNextDataBlockFilterOut(pReader, pExec->pDropTbUid)) {
L
Liu Jicong 已提交
595
          SSDataBlock block = {0};
596
          if (tqRetrieveDataBlock(&block.pDataBlock, pReader, &block.info.groupId, &block.info.uid, &block.info.rows,
L
Liu Jicong 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
                                  &block.info.numOfCols) < 0) {
            ASSERT(0);
          }
          int32_t            dataStrLen = sizeof(SRetrieveTableRsp) + blockGetEncodeSize(&block);
          void*              buf = taosMemoryCalloc(1, dataStrLen);
          SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)buf;
          /*pRetrieve->useconds = 0;*/
          pRetrieve->precision = TSDB_DEFAULT_PRECISION;
          pRetrieve->compressed = 0;
          pRetrieve->completed = 1;
          pRetrieve->numOfRows = htonl(block.info.rows);

          // TODO enable compress
          int32_t actualLen = 0;
          blockCompressEncode(&block, pRetrieve->data, &actualLen, block.info.numOfCols, false);
          actualLen += sizeof(SRetrieveTableRsp);
          ASSERT(actualLen <= dataStrLen);
          taosArrayPush(rsp.blockDataLen, &actualLen);
          taosArrayPush(rsp.blockData, &buf);
616
          if (withTbName) {
L
Liu Jicong 已提交
617 618 619 620 621 622 623 624 625
            SMetaReader mr = {0};
            metaReaderInit(&mr, pTq->pVnode->pMeta, 0);
            if (metaGetTableEntryByUid(&mr, block.info.uid) < 0) {
              ASSERT(0);
            }
            char* tbName = strdup(mr.me.name);
            taosArrayPush(rsp.blockTbName, &tbName);
            metaReaderClear(&mr);
          }
L
Liu Jicong 已提交
626 627 628 629

          SSchemaWrapper* pSW = tCloneSSchemaWrapper(pExec->pExecReader[workerId]->pSchemaWrapper);
          taosArrayPush(rsp.blockSchema, &pSW);

L
Liu Jicong 已提交
630 631 632 633
          rsp.blockNum++;
        }
      } else {
        ASSERT(0);
L
fix  
Liu Jicong 已提交
634
      }
L
Liu Jicong 已提交
635
    }
636

L
Liu Jicong 已提交
637 638
    // TODO batch optimization:
    // TODO continue scan until meeting batch requirement
L
Liu Jicong 已提交
639 640 641 642
    if (rsp.blockNum != 0) break;
    rsp.skipLogNum++;
    fetchOffset++;
  }
643

L
Liu Jicong 已提交
644
  taosMemoryFree(pHeadWithCkSum);
L
Liu Jicong 已提交
645 646
  ASSERT(taosArrayGetSize(rsp.blockData) == rsp.blockNum);
  ASSERT(taosArrayGetSize(rsp.blockDataLen) == rsp.blockNum);
L
fix  
Liu Jicong 已提交
647

L
Liu Jicong 已提交
648 649 650 651
  if (rsp.blockNum != 0)
    rsp.rspOffset = fetchOffset;
  else
    rsp.rspOffset = fetchOffset - 1;
652

L
Liu Jicong 已提交
653
  int32_t tlen = sizeof(SMqRspHead) + tEncodeSMqDataBlkRsp(NULL, &rsp);
654 655 656 657 658
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    pMsg->code = -1;
    return -1;
  }
L
Liu Jicong 已提交
659

L
Liu Jicong 已提交
660 661
  ((SMqRspHead*)buf)->mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
  ((SMqRspHead*)buf)->epoch = pReq->epoch;
L
Liu Jicong 已提交
662
  ((SMqRspHead*)buf)->consumerId = consumerId;
663

L
Liu Jicong 已提交
664
  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
L
Liu Jicong 已提交
665
  tEncodeSMqDataBlkRsp(&abuf, &rsp);
666 667 668
  pMsg->pCont = buf;
  pMsg->contLen = tlen;
  pMsg->code = 0;
S
shm  
Shengliang Guan 已提交
669
  tmsgSendRsp(pMsg);
L
Liu Jicong 已提交
670

H
Hongze Cheng 已提交
671 672
  tqDebug("vg %d offset %ld from consumer %ld (epoch %d) send rsp, block num: %d, reqOffset: %ld, rspOffset: %ld",
          TD_VID(pTq->pVnode), fetchOffset, consumerId, pReq->epoch, rsp.blockNum, rsp.reqOffset, rsp.rspOffset);
L
Liu Jicong 已提交
673 674

  // TODO destroy
L
Liu Jicong 已提交
675 676
  taosArrayDestroy(rsp.blockData);
  taosArrayDestroy(rsp.blockDataLen);
L
Liu Jicong 已提交
677
  taosArrayDestroyP(rsp.blockSchema, (FDelete)tDeleteSSchemaWrapper);
L
Liu Jicong 已提交
678
  taosArrayDestroyP(rsp.blockTbName, (FDelete)taosMemoryFree);
L
Liu Jicong 已提交
679

680 681
  return 0;
}
L
Liu Jicong 已提交
682

L
Liu Jicong 已提交
683
#if 0
L
Liu Jicong 已提交
684 685 686 687 688 689 690 691
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg, int32_t workerId) {
  SMqPollReq* pReq = pMsg->pCont;
  int64_t     consumerId = pReq->consumerId;
  int64_t     fetchOffset;
  int64_t     blockingTime = pReq->blockingTime;
  int32_t     reqEpoch = pReq->epoch;

  if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__EARLIEAST) {
L
Liu Jicong 已提交
692
    fetchOffset = walGetFirstVer(pTq->pWal);
L
Liu Jicong 已提交
693 694 695 696 697 698
  } else if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__LATEST) {
    fetchOffset = walGetLastVer(pTq->pWal);
  } else {
    fetchOffset = pReq->currentOffset + 1;
  }

H
Hongze Cheng 已提交
699
  tqDebug("tmq poll: consumer %ld (epoch %d) recv poll req in vg %d, req %ld %ld", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
700
         TD_VID(pTq->pVnode), pReq->currentOffset, fetchOffset);
L
Liu Jicong 已提交
701 702 703 704 705 706

  SMqPollRspV2 rspV2 = {0};
  rspV2.dataLen = 0;

  STqConsumer* pConsumer = tqHandleGet(pTq->tqMeta, consumerId);
  if (pConsumer == NULL) {
H
refact  
Hongze Cheng 已提交
707
    vWarn("tmq poll: consumer %ld (epoch %d) not found in vg %d", consumerId, pReq->epoch, TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    pMsg->pCont = NULL;
    pMsg->contLen = 0;
    pMsg->code = -1;
    tmsgSendRsp(pMsg);
    return 0;
  }

  int32_t consumerEpoch = atomic_load_32(&pConsumer->epoch);
  while (consumerEpoch < reqEpoch) {
    consumerEpoch = atomic_val_compare_exchange_32(&pConsumer->epoch, consumerEpoch, reqEpoch);
  }

  STqTopic* pTopic = NULL;
  int32_t   topicSz = taosArrayGetSize(pConsumer->topics);
  for (int32_t i = 0; i < topicSz; i++) {
    STqTopic* topic = taosArrayGet(pConsumer->topics, i);
    // TODO race condition
    ASSERT(pConsumer->consumerId == consumerId);
    if (strcmp(topic->topicName, pReq->topic) == 0) {
      pTopic = topic;
      break;
    }
  }
  if (pTopic == NULL) {
    vWarn("tmq poll: consumer %ld (epoch %d) topic %s not found in vg %d", consumerId, pReq->epoch, pReq->topic,
H
refact  
Hongze Cheng 已提交
733
          TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
734 735 736 737 738 739 740
    pMsg->pCont = NULL;
    pMsg->contLen = 0;
    pMsg->code = -1;
    tmsgSendRsp(pMsg);
    return 0;
  }

H
Hongze Cheng 已提交
741
  tqDebug("poll topic %s from consumer %ld (epoch %d) vg %d", pTopic->topicName, consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
742
         TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
743 744 745 746 747 748 749 750 751

  rspV2.reqOffset = pReq->currentOffset;
  rspV2.skipLogNum = 0;

  while (1) {
    /*if (fetchOffset > walGetLastVer(pTq->pWal) || walReadWithHandle(pTopic->pReadhandle, fetchOffset) < 0) {*/
    // TODO
    consumerEpoch = atomic_load_32(&pConsumer->epoch);
    if (consumerEpoch > reqEpoch) {
H
Hongze Cheng 已提交
752
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, found new consumer epoch %d discard req epoch %d",
H
refact  
Hongze Cheng 已提交
753
             consumerId, pReq->epoch, TD_VID(pTq->pVnode), fetchOffset, consumerEpoch, reqEpoch);
L
Liu Jicong 已提交
754 755 756 757 758 759 760
      break;
    }
    SWalReadHead* pHead;
    if (walReadWithHandle_s(pTopic->pReadhandle, fetchOffset, &pHead) < 0) {
      // TODO: no more log, set timer to wait blocking time
      // if data inserted during waiting, launch query and
      // response to user
H
Hongze Cheng 已提交
761
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, no more log to return", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
762
             TD_VID(pTq->pVnode), fetchOffset);
L
Liu Jicong 已提交
763 764
      break;
    }
H
Hongze Cheng 已提交
765
    tqDebug("tmq poll: consumer %ld (epoch %d) iter log, vg %d offset %ld msgType %d", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
766
           TD_VID(pTq->pVnode), fetchOffset, pHead->msgType);
L
Liu Jicong 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    /*int8_t pos = fetchOffset % TQ_BUFFER_SIZE;*/
    /*pHead = pTopic->pReadhandle->pHead;*/
    if (pHead->msgType == TDMT_VND_SUBMIT) {
      SSubmitReq* pCont = (SSubmitReq*)&pHead->body;
      qTaskInfo_t task = pTopic->buffer.output[workerId].task;
      ASSERT(task);
      qSetStreamInput(task, pCont, STREAM_DATA_TYPE_SUBMIT_BLOCK);
      SArray* pRes = taosArrayInit(0, sizeof(SSDataBlock));
      while (1) {
        SSDataBlock* pDataBlock = NULL;
        uint64_t     ts;
        if (qExecTask(task, &pDataBlock, &ts) < 0) {
          ASSERT(false);
        }
        if (pDataBlock == NULL) {
          /*pos = fetchOffset % TQ_BUFFER_SIZE;*/
          break;
        }

        taosArrayPush(pRes, pDataBlock);
      }

      if (taosArrayGetSize(pRes) == 0) {
H
Hongze Cheng 已提交
790
        tqDebug("tmq poll: consumer %ld (epoch %d) iter log, vg %d skip log %ld since not wanted", consumerId,
H
refact  
Hongze Cheng 已提交
791
               pReq->epoch, TD_VID(pTq->pVnode), fetchOffset);
L
Liu Jicong 已提交
792 793 794 795 796 797 798 799
        fetchOffset++;
        rspV2.skipLogNum++;
        taosArrayDestroy(pRes);
        continue;
      }
      rspV2.rspOffset = fetchOffset;

      int32_t blockSz = taosArrayGetSize(pRes);
L
Liu Jicong 已提交
800
      int32_t dataBlockStrLen = 0;
L
Liu Jicong 已提交
801 802
      for (int32_t i = 0; i < blockSz; i++) {
        SSDataBlock* pBlock = taosArrayGet(pRes, i);
L
Liu Jicong 已提交
803
        dataBlockStrLen += sizeof(SRetrieveTableRsp) + blockGetEncodeSize(pBlock);
L
Liu Jicong 已提交
804 805
      }

L
Liu Jicong 已提交
806 807
      void* dataBlockBuf = taosMemoryMalloc(dataBlockStrLen);
      if (dataBlockBuf == NULL) {
L
Liu Jicong 已提交
808 809 810 811
        pMsg->code = -1;
        taosMemoryFree(pHead);
      }

L
Liu Jicong 已提交
812
      rspV2.blockData = dataBlockBuf;
L
Liu Jicong 已提交
813 814

      int32_t pos;
L
Liu Jicong 已提交
815
      rspV2.blockPos = taosArrayInit(blockSz, sizeof(int32_t));
L
Liu Jicong 已提交
816 817
      for (int32_t i = 0; i < blockSz; i++) {
        pos = 0;
L
Liu Jicong 已提交
818 819 820 821 822 823 824 825
        SSDataBlock*       pBlock = taosArrayGet(pRes, i);
        SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)dataBlockBuf;
        pRetrieve->useconds = 0;
        pRetrieve->precision = 0;
        pRetrieve->compressed = 0;
        pRetrieve->completed = 1;
        pRetrieve->numOfRows = htonl(pBlock->info.rows);
        blockCompressEncode(pBlock, pRetrieve->data, &pos, pBlock->info.numOfCols, false);
L
Liu Jicong 已提交
826
        taosArrayPush(rspV2.blockPos, &rspV2.dataLen);
L
Liu Jicong 已提交
827 828 829 830 831

        int32_t totLen = sizeof(SRetrieveTableRsp) + pos;
        pRetrieve->compLen = htonl(totLen);
        rspV2.dataLen += totLen;
        dataBlockBuf = POINTER_SHIFT(dataBlockBuf, totLen);
L
Liu Jicong 已提交
832
      }
L
Liu Jicong 已提交
833
      ASSERT(POINTER_DISTANCE(dataBlockBuf, rspV2.blockData) <= dataBlockStrLen);
L
Liu Jicong 已提交
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848

      int32_t msgLen = sizeof(SMqRspHead) + tEncodeSMqPollRspV2(NULL, &rspV2);
      void*   buf = rpcMallocCont(msgLen);

      ((SMqRspHead*)buf)->mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
      ((SMqRspHead*)buf)->epoch = pReq->epoch;
      ((SMqRspHead*)buf)->consumerId = consumerId;

      void* msgBodyBuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
      tEncodeSMqPollRspV2(&msgBodyBuf, &rspV2);

      /*rsp.pBlockData = pRes;*/

      /*taosArrayDestroyEx(rsp.pBlockData, (void (*)(void*))tDeleteSSDataBlock);*/
      pMsg->pCont = buf;
L
Liu Jicong 已提交
849
      pMsg->contLen = msgLen;
L
Liu Jicong 已提交
850
      pMsg->code = 0;
H
Hongze Cheng 已提交
851
      tqDebug("vg %d offset %ld msgType %d from consumer %ld (epoch %d) actual rsp", TD_VID(pTq->pVnode), fetchOffset,
L
Liu Jicong 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
             pHead->msgType, consumerId, pReq->epoch);
      tmsgSendRsp(pMsg);
      taosMemoryFree(pHead);
      return 0;
    } else {
      taosMemoryFree(pHead);
      fetchOffset++;
      rspV2.skipLogNum++;
    }
  }

  /*if (blockingTime != 0) {*/
  /*tqAddClientPusher(pTq->tqPushMgr, pMsg, consumerId, blockingTime);*/
  /*} else {*/

  rspV2.rspOffset = fetchOffset - 1;

  int32_t tlen = sizeof(SMqRspHead) + tEncodeSMqPollRspV2(NULL, &rspV2);
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    pMsg->code = -1;
    return -1;
  }
  ((SMqRspHead*)buf)->mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
  ((SMqRspHead*)buf)->epoch = pReq->epoch;
  ((SMqRspHead*)buf)->consumerId = consumerId;

  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
  tEncodeSMqPollRspV2(&abuf, &rspV2);
  pMsg->pCont = buf;
  pMsg->contLen = tlen;
  pMsg->code = 0;
  tmsgSendRsp(pMsg);
H
Hongze Cheng 已提交
885
  tqDebug("vg %d offset %ld from consumer %ld (epoch %d) not rsp", TD_VID(pTq->pVnode), fetchOffset, consumerId,
L
Liu Jicong 已提交
886 887 888 889 890
         pReq->epoch);
  /*}*/

  return 0;
}
L
Liu Jicong 已提交
891 892
#endif

L
Liu Jicong 已提交
893 894
int32_t tqProcessVgDeleteReq(STQ* pTq, char* msg, int32_t msgLen) {
  SMqVDeleteReq* pReq = (SMqVDeleteReq*)msg;
L
Liu Jicong 已提交
895 896 897 898

  int32_t code = taosHashRemove(pTq->execs, pReq->subKey, strlen(pReq->subKey));
  ASSERT(code == 0);
  return 0;
L
Liu Jicong 已提交
899 900
}

L
Liu Jicong 已提交
901 902
// TODO: persist meta into tdb
int32_t tqProcessVgChangeReq(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
903
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
904 905
  tDecodeSMqRebVgReq(msg, &req);
  // todo lock
L
Liu Jicong 已提交
906
  STqExec* pExec = taosHashGet(pTq->execs, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
907 908 909 910 911 912 913 914 915 916
  if (pExec == NULL) {
    ASSERT(req.oldConsumerId == -1);
    ASSERT(req.newConsumerId != -1);
    STqExec exec = {0};
    pExec = &exec;
    /*taosInitRWLatch(&pExec->lock);*/

    memcpy(pExec->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pExec->consumerId = req.newConsumerId;
    pExec->epoch = -1;
L
Liu Jicong 已提交
917 918 919 920 921 922

    pExec->subType = req.subType;
    pExec->withTbName = req.withTbName;
    pExec->withSchema = req.withSchema;
    pExec->withTag = req.withTag;

L
Liu Jicong 已提交
923 924
    pExec->qmsg = req.qmsg;
    req.qmsg = NULL;
L
Liu Jicong 已提交
925 926

    pExec->pWalReader = walOpenReadHandle(pTq->pVnode->pWal);
927 928 929 930
    if (pExec->subType == TOPIC_SUB_TYPE__TABLE) {
      for (int32_t i = 0; i < 5; i++) {
        pExec->pExecReader[i] = tqInitSubmitMsgScanner(pTq->pVnode->pMeta);

L
Liu Jicong 已提交
931 932 933
        SReadHandle handle = {
            .reader = pExec->pExecReader[i],
            .meta = pTq->pVnode->pMeta,
934
            .pMsgCb = &pTq->pVnode->msgCb,
L
Liu Jicong 已提交
935 936 937 938
        };
        pExec->task[i] = qCreateStreamExecTaskInfo(pExec->qmsg, &handle);
        ASSERT(pExec->task[i]);
      }
939 940 941 942 943
    } else {
      for (int32_t i = 0; i < 5; i++) {
        pExec->pExecReader[i] = tqInitSubmitMsgScanner(pTq->pVnode->pMeta);
      }
      pExec->pDropTbUid = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
L
Liu Jicong 已提交
944
    }
L
Liu Jicong 已提交
945
    taosHashPut(pTq->execs, req.subKey, strlen(req.subKey), pExec, sizeof(STqExec));
L
Liu Jicong 已提交
946 947
    return 0;
  } else {
L
Liu Jicong 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961
    /*if (req.newConsumerId != -1) {*/
    /*taosWLockLatch(&pExec->lock);*/
    ASSERT(pExec->consumerId == req.oldConsumerId);
    // TODO handle qmsg and exec modification
    atomic_store_32(&pExec->epoch, -1);
    atomic_store_64(&pExec->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pExec->epoch, 1);
    /*taosWUnLockLatch(&pExec->lock);*/
    return 0;
    /*} else {*/
    // TODO
    /*taosHashRemove(pTq->tqMetaNew, req.subKey, strlen(req.subKey));*/
    /*return 0;*/
    /*}*/
L
Liu Jicong 已提交
962 963
  }
}
964

L
Liu Jicong 已提交
965 966 967 968 969 970
void tqTableSink(SStreamTask* pTask, void* vnode, int64_t ver, void* data) {
  const SArray* pRes = (const SArray*)data;
  SVnode*       pVnode = (SVnode*)vnode;

  ASSERT(pTask->tbSink.pTSchema);
  SSubmitReq* pReq = tdBlockToSubmit(pRes, pTask->tbSink.pTSchema, true, pTask->tbSink.stbUid, pVnode->config.vgId);
L
Liu Jicong 已提交
971
  /*tPrintFixedSchemaSubmitReq(pReq, pTask->tbSink.pTSchema);*/
L
Liu Jicong 已提交
972
  // build write msg
L
Liu Jicong 已提交
973 974 975 976 977
  SRpcMsg msg = {
      .msgType = TDMT_VND_SUBMIT,
      .pCont = pReq,
      .contLen = ntohl(pReq->length),
  };
L
Liu Jicong 已提交
978

L
Liu Jicong 已提交
979
  ASSERT(tmsgPutToQueue(&pVnode->msgCb, WRITE_QUEUE, &msg) == 0);
L
Liu Jicong 已提交
980
}
L
Liu Jicong 已提交
981

L
Liu Jicong 已提交
982 983 984 985 986 987 988 989 990 991 992 993 994
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int32_t parallel) {
  if (pTask->execType != TASK_EXEC__NONE) {
    // expand runners
    pTask->exec.numOfRunners = parallel;
    pTask->exec.runners = taosMemoryCalloc(parallel, sizeof(SStreamRunner));
    if (pTask->exec.runners == NULL) {
      return -1;
    }
    for (int32_t i = 0; i < parallel; i++) {
      STqReadHandle* pStreamReader = tqInitSubmitMsgScanner(pTq->pVnode->pMeta);
      SReadHandle    handle = {
             .reader = pStreamReader,
             .meta = pTq->pVnode->pMeta,
995
             .pMsgCb = &pTq->pVnode->msgCb,
5
54liuyao 已提交
996
             .vnode = pTq->pVnode,
L
Liu Jicong 已提交
997 998 999 1000 1001
      };
      pTask->exec.runners[i].inputHandle = pStreamReader;
      pTask->exec.runners[i].executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
      ASSERT(pTask->exec.runners[i].executor);
    }
L
Liu Jicong 已提交
1002
  }
L
Liu Jicong 已提交
1003 1004 1005 1006

  if (pTask->sinkType == TASK_SINK__TABLE) {
    pTask->tbSink.vnode = pTq->pVnode;
    pTask->tbSink.tbSinkFunc = tqTableSink;
L
Liu Jicong 已提交
1007
  }
L
Liu Jicong 已提交
1008

L
Liu Jicong 已提交
1009 1010 1011
  return 0;
}

L
Liu Jicong 已提交
1012
int32_t tqProcessTaskDeploy(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1013
  SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask));
L
Liu Jicong 已提交
1014 1015 1016
  if (pTask == NULL) {
    return -1;
  }
H
Hongze Cheng 已提交
1017 1018
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
L
Liu Jicong 已提交
1019 1020 1021
  if (tDecodeSStreamTask(&decoder, pTask) < 0) {
    ASSERT(0);
  }
H
Hongze Cheng 已提交
1022
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1023

L
Liu Jicong 已提交
1024
  // exec
L
Liu Jicong 已提交
1025 1026 1027
  if (tqExpandTask(pTq, pTask, 4) < 0) {
    ASSERT(0);
  }
L
Liu Jicong 已提交
1028 1029

  // sink
L
Liu Jicong 已提交
1030
  pTask->ahandle = pTq->pVnode;
L
Liu Jicong 已提交
1031
  if (pTask->sinkType == TASK_SINK__SMA) {
L
Liu Jicong 已提交
1032
    pTask->smaSink.smaSink = smaHandleRes;
L
Liu Jicong 已提交
1033 1034 1035 1036 1037 1038
  } else if (pTask->sinkType == TASK_SINK__TABLE) {
    ASSERT(pTask->tbSink.pSchemaWrapper);
    ASSERT(pTask->tbSink.pSchemaWrapper->pSchema);
    pTask->tbSink.pTSchema =
        tdGetSTSChemaFromSSChema(&pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols);
    ASSERT(pTask->tbSink.pTSchema);
L
Liu Jicong 已提交
1039
  }
L
Liu Jicong 已提交
1040

L
Liu Jicong 已提交
1041 1042 1043 1044
  taosHashPut(pTq->pStreamTasks, &pTask->taskId, sizeof(int32_t), pTask, sizeof(SStreamTask));

  return 0;
}
L
Liu Jicong 已提交
1045

L
Liu Jicong 已提交
1046
int32_t tqProcessStreamTrigger(STQ* pTq, void* data, int32_t dataLen, int32_t workerId) {
L
Liu Jicong 已提交
1047 1048 1049 1050 1051 1052 1053
  void* pIter = NULL;

  while (1) {
    pIter = taosHashIterate(pTq->pStreamTasks, pIter);
    if (pIter == NULL) break;
    SStreamTask* pTask = (SStreamTask*)pIter;

L
Liu Jicong 已提交
1054
    if (streamExecTask(pTask, &pTq->pVnode->msgCb, data, STREAM_DATA_TYPE_SUBMIT_BLOCK, workerId) < 0) {
L
Liu Jicong 已提交
1055
      // TODO
L
Liu Jicong 已提交
1056 1057 1058 1059 1060
    }
  }
  return 0;
}

L
Liu Jicong 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
int32_t tqProcessStreamTriggerNew(STQ* pTq, SSubmitReq* data) {
  SStreamDataSubmit* pSubmit = NULL;

  // build data
  pSubmit = taosAllocateQitem(sizeof(SStreamDataSubmit), DEF_QITEM);
  if (pSubmit == NULL) return -1;
  pSubmit->dataRef = taosMemoryMalloc(sizeof(int32_t));
  if (pSubmit->dataRef == NULL) goto FAIL;
  *pSubmit->dataRef = 1;
  pSubmit->data = data;
  pSubmit->type = STREAM_INPUT__DATA_BLOCK;

  void* pIter = NULL;
  while (1) {
    pIter = taosHashIterate(pTq->pStreamTasks, pIter);
    if (pIter == NULL) break;
    SStreamTask* pTask = (SStreamTask*)pIter;
    if (pTask->inputType == TASK_INPUT_TYPE__SUMBIT_BLOCK) {
      streamEnqueueDataSubmit(pTask, pSubmit);
      // TODO cal back pressure
    }
    // check run
    int8_t execStatus = atomic_load_8(&pTask->status);
    if (execStatus == TASK_STATUS__IDLE || execStatus == TASK_STATUS__CLOSING) {
      SStreamTaskRunReq* pReq = taosMemoryMalloc(sizeof(SStreamTaskRunReq));
      if (pReq == NULL) continue;
      // TODO: do we need htonl?
      pReq->head.vgId = pTq->pVnode->config.vgId;
      pReq->streamId = pTask->streamId;
      pReq->taskId = pTask->taskId;
      SRpcMsg msg = {
          .msgType = 0,
          .pCont = pReq,
          .contLen = sizeof(SStreamTaskRunReq),
      };
      tmsgPutToQueue(&pTq->pVnode->msgCb, FETCH_QUEUE, &msg);
    }
  }
  streamDataSubmitRefDec(pSubmit);

  return 0;
FAIL:
  if (pSubmit) {
    if (pSubmit->dataRef) {
      taosMemoryFree(pSubmit->dataRef);
    }
    taosFreeQitem(pSubmit);
  }
  return -1;
}

L
Liu Jicong 已提交
1112
int32_t tqProcessTaskExec(STQ* pTq, char* msg, int32_t msgLen, int32_t workerId) {
L
Liu Jicong 已提交
1113
  SStreamTaskExecReq req;
L
Liu Jicong 已提交
1114
  tDecodeSStreamTaskExecReq(msg, &req);
L
Liu Jicong 已提交
1115

L
Liu Jicong 已提交
1116 1117 1118
  int32_t taskId = req.taskId;
  ASSERT(taskId);

L
Liu Jicong 已提交
1119
  SStreamTask* pTask = taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
L
Liu Jicong 已提交
1120
  ASSERT(pTask);
L
Liu Jicong 已提交
1121

L
Liu Jicong 已提交
1122
  if (streamExecTask(pTask, &pTq->pVnode->msgCb, req.data, STREAM_DATA_TYPE_SSDATA_BLOCK, workerId) < 0) {
L
Liu Jicong 已提交
1123
    // TODO
L
Liu Jicong 已提交
1124
  }
L
Liu Jicong 已提交
1125 1126
  return 0;
}
L
Liu Jicong 已提交
1127

L
Liu Jicong 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
int32_t tqProcessStreamTrigger2(STQ* pTq, SSubmitReq* pReq, int64_t ver) {
  void* pIter = NULL;
  bool  failed = false;

  SStreamDataSubmit* pSubmit = taosAllocateQitem(sizeof(SStreamDataSubmit), DEF_QITEM);
  if (pSubmit == NULL) {
    failed = true;
  }
  pSubmit->dataRef = taosMemoryMalloc(sizeof(int32_t));
  if (pSubmit->dataRef == NULL) {
    failed = true;
  }

  pSubmit->type = STREAM_DATA_TYPE_SUBMIT_BLOCK;
  pSubmit->sourceVer = ver;
  pSubmit->sourceVg = pTq->pVnode->config.vgId;
  pSubmit->data = pReq;
  *pSubmit->dataRef = 1;

  while (1) {
    pIter = taosHashIterate(pTq->pStreamTasks, pIter);
    if (pIter == NULL) break;
    SStreamTask* pTask = (SStreamTask*)pIter;
    if (pTask->inputType != STREAM_INPUT__DATA_SUBMIT) continue;

    int8_t inputStatus = atomic_load_8(&pTask->inputStatus);
    if (inputStatus == TASK_INPUT_STATUS__NORMAL) {
      if (failed) {
        atomic_store_8(&pTask->inputStatus, TASK_INPUT_STATUS__FAILED);
        continue;
      }

      streamDataSubmitRefInc(pSubmit);
      taosWriteQitem(pTask->inputQ, pSubmit);

      int8_t execStatus = atomic_load_8(&pTask->status);
      if (execStatus == TASK_STATUS__IDLE || execStatus == TASK_STATUS__CLOSING) {
        // TODO dispatch task launch msg to fetch queue
      }

    } else {
      // blocked or stopped, do nothing
    }
  }

  if (!failed) {
    streamDataSubmitRefDec(pSubmit);
    return 0;
  } else {
    return -1;
  }
}

L
Liu Jicong 已提交
1181
int32_t tqProcessTaskExec2(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1182
  //
L
Liu Jicong 已提交
1183 1184
  return 0;
}