tq.c 34.1 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"
S
Shengliang Guan 已提交
17

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

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

L
Liu Jicong 已提交
25
STQ* tqOpen(const char* path, SVnode* pVnode, SWal* pWal) {
wafwerar's avatar
wafwerar 已提交
26
  STQ* pTq = taosMemoryMalloc(sizeof(STQ));
L
Liu Jicong 已提交
27
  if (pTq == NULL) {
L
Liu Jicong 已提交
28
    terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
L
Liu Jicong 已提交
29 30
    return NULL;
  }
H
Hongze Cheng 已提交
31
  pTq->path = strdup(path);
L
Liu Jicong 已提交
32
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
33
  pTq->pWal = pWal;
34

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

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

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

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

L
Liu Jicong 已提交
50 51
  return pTq;
}
L
Liu Jicong 已提交
52

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

L
Liu Jicong 已提交
61 62 63 64 65 66 67 68
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 已提交
69 70 71
      {.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 已提交
72 73 74 75 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

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

L
Liu Jicong 已提交
103 104 105 106 107 108 109 110 111 112 113
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 已提交
114
    pExec = *(STqExec**)pIter;
L
Liu Jicong 已提交
115 116 117 118 119 120 121 122

    taosWLockLatch(&pExec->pushHandle.lock);

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

    SMqDataBlkRsp rsp = {0};
    rsp.reqOffset = pExec->pushHandle.reqOffset;
123
    rsp.blockData = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    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};
164
        if (tqRetrieveDataBlock(&block.pDataBlock, pReader, &block.info.groupId, &block.info.uid, &block.info.rows,
L
Liu Jicong 已提交
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 193 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
                                &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 已提交
221 222 223
    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 已提交
224 225 226 227 228 229 230 231 232

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

  return 0;
}

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

L
Liu Jicong 已提交
236 237
  // make sure msgType == TDMT_VND_SUBMIT
  if (tsdbUpdateSmaWindow(pTq->pVnode->pTsdb, msg, ver) != 0) {
L
Liu Jicong 已提交
238
    return -1;
L
Liu Jicong 已提交
239
  }
C
Cary Xu 已提交
240

L
Liu Jicong 已提交
241 242 243 244
  if (taosHashGetSize(pTq->pStreamTasks) == 0) return 0;

  void* data = taosMemoryMalloc(msgLen);
  if (data == NULL) {
C
Cary Xu 已提交
245
    return -1;
C
Cary Xu 已提交
246
  }
L
Liu Jicong 已提交
247
  memcpy(data, msg, msgLen);
C
Cary Xu 已提交
248

L
Liu Jicong 已提交
249 250 251 252 253
  SRpcMsg req = {
      .msgType = TDMT_VND_STREAM_TRIGGER,
      .pCont = data,
      .contLen = msgLen,
  };
L
Liu Jicong 已提交
254

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

L
Liu Jicong 已提交
257 258 259
  return 0;
}

L
Liu Jicong 已提交
260 261 262 263 264
int tqCommit(STQ* pTq) {
  // do nothing
  /*return tqStorePersist(pTq->tqMeta);*/
  return 0;
}
L
Liu Jicong 已提交
265 266

int32_t tqGetTopicHandleSize(const STqTopic* pTopic) {
L
Liu Jicong 已提交
267 268
  return strlen(pTopic->topicName) + strlen(pTopic->sql) + strlen(pTopic->physicalPlan) + strlen(pTopic->qmsg) +
         sizeof(int64_t) * 3;
L
Liu Jicong 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
}

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 已提交
287 288 289
  /*tlen += taosEncodeFixedI64(buf, pTopic->persistedOffset);*/
  /*tlen += taosEncodeFixedI64(buf, pTopic->committedOffset);*/
  /*tlen += taosEncodeFixedI64(buf, pTopic->currentOffset);*/
L
Liu Jicong 已提交
290 291 292 293 294 295 296 297
  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 已提交
298 299 300
  /*buf = taosDecodeFixedI64(buf, &pTopic->persistedOffset);*/
  /*buf = taosDecodeFixedI64(buf, &pTopic->committedOffset);*/
  /*buf = taosDecodeFixedI64(buf, &pTopic->currentOffset);*/
L
Liu Jicong 已提交
301 302 303 304 305 306 307 308
  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 已提交
309
  tlen += taosEncodeFixedI32(buf, pConsumer->epoch);
L
Liu Jicong 已提交
310 311 312 313 314 315 316 317
  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 已提交
318 319
}

L
Liu Jicong 已提交
320 321 322 323
static FORCE_INLINE const void* tDecodeSTqConsumer(const void* buf, STqConsumer* pConsumer) {
  int32_t sz;

  buf = taosDecodeFixedI64(buf, &pConsumer->consumerId);
L
Liu Jicong 已提交
324
  buf = taosDecodeFixedI32(buf, &pConsumer->epoch);
L
Liu Jicong 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  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 已提交
340
  if (sz > (*ppHead)->ssize) {
wafwerar's avatar
wafwerar 已提交
341
    void* tmpPtr = taosMemoryRealloc(*ppHead, sizeof(STqSerializedHead) + sz);
L
Liu Jicong 已提交
342
    if (tmpPtr == NULL) {
wafwerar's avatar
wafwerar 已提交
343
      taosMemoryFree(*ppHead);
L
Liu Jicong 已提交
344
      terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
L
Liu Jicong 已提交
345 346 347 348 349 350 351
      return -1;
    }
    *ppHead = tmpPtr;
    (*ppHead)->ssize = sz;
  }

  void* ptr = (*ppHead)->content;
L
Liu Jicong 已提交
352 353
  void* abuf = ptr;
  tEncodeSTqConsumer(&abuf, pConsumer);
L
Liu Jicong 已提交
354

L
Liu Jicong 已提交
355 356 357
  return 0;
}

L
Liu Jicong 已提交
358 359
int32_t tqDeserializeConsumer(STQ* pTq, const STqSerializedHead* pHead, STqConsumer** ppConsumer) {
  const void* str = pHead->content;
wafwerar's avatar
wafwerar 已提交
360
  *ppConsumer = taosMemoryCalloc(1, sizeof(STqConsumer));
L
Liu Jicong 已提交
361 362 363 364 365 366 367 368 369 370
  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 已提交
371
  for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
372 373 374 375 376
    STqTopic* pTopic = taosArrayGet(pConsumer->topics, i);
    pTopic->pReadhandle = walOpenReadHandle(pTq->pWal);
    if (pTopic->pReadhandle == NULL) {
      ASSERT(false);
    }
L
Liu Jicong 已提交
377 378
    for (int j = 0; j < TQ_BUFFER_SIZE; j++) {
      pTopic->buffer.output[j].status = 0;
L
Liu Jicong 已提交
379
      STqReadHandle* pReadHandle = tqInitSubmitMsgScanner(pTq->pVnode->pMeta);
L
Liu Jicong 已提交
380 381
      SReadHandle    handle = {
             .reader = pReadHandle,
L
Liu Jicong 已提交
382
             .meta = pTq->pVnode->pMeta,
383
             .pMsgCb = &pTq->pVnode->msgCb,
L
Liu Jicong 已提交
384
      };
L
Liu Jicong 已提交
385 386
      pTopic->buffer.output[j].pReadHandle = pReadHandle;
      pTopic->buffer.output[j].task = qCreateStreamExecTaskInfo(pTopic->qmsg, &handle);
L
Liu Jicong 已提交
387
    }
L
Liu Jicong 已提交
388
  }
L
Liu Jicong 已提交
389 390

  return 0;
L
Liu Jicong 已提交
391
}
L
Liu Jicong 已提交
392

L
fix  
Liu Jicong 已提交
393
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg, int32_t workerId) {
L
Liu Jicong 已提交
394 395 396 397 398
  SMqPollReq* pReq = pMsg->pCont;
  int64_t     consumerId = pReq->consumerId;
  int64_t     waitTime = pReq->waitTime;
  int32_t     reqEpoch = pReq->epoch;
  int64_t     fetchOffset;
399

L
Liu Jicong 已提交
400
  // get offset to fetch message
L
Liu Jicong 已提交
401
  if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__EARLIEAST) {
L
Liu Jicong 已提交
402
    fetchOffset = walGetFirstVer(pTq->pWal);
L
Liu Jicong 已提交
403
  } else if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__LATEST) {
L
Liu Jicong 已提交
404
    fetchOffset = walGetCommittedVer(pTq->pWal);
L
Liu Jicong 已提交
405 406 407 408
  } else {
    fetchOffset = pReq->currentOffset + 1;
  }

H
Hongze Cheng 已提交
409 410
  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 已提交
411

L
Liu Jicong 已提交
412
  STqExec* pExec = taosHashGet(pTq->execs, pReq->subKey, strlen(pReq->subKey));
L
Liu Jicong 已提交
413
  ASSERT(pExec);
L
Liu Jicong 已提交
414

L
Liu Jicong 已提交
415
  int32_t consumerEpoch = atomic_load_32(&pExec->epoch);
L
Liu Jicong 已提交
416
  while (consumerEpoch < reqEpoch) {
L
Liu Jicong 已提交
417
    consumerEpoch = atomic_val_compare_exchange_32(&pExec->epoch, consumerEpoch, reqEpoch);
L
Liu Jicong 已提交
418 419
  }

420 421 422 423 424 425 426
  SWalHead* pHeadWithCkSum = taosMemoryMalloc(sizeof(SWalHead) + 2048);
  if (pHeadWithCkSum == NULL) {
    return -1;
  }

  walSetReaderCapacity(pExec->pWalReader, 2048);

L
Liu Jicong 已提交
427
  SMqDataBlkRsp rsp = {0};
L
Liu Jicong 已提交
428
  rsp.reqOffset = pReq->currentOffset;
L
Liu Jicong 已提交
429
  rsp.withSchema = pExec->withSchema;
L
Liu Jicong 已提交
430 431
  rsp.withTbName = pExec->withTbName;

L
Liu Jicong 已提交
432
  rsp.blockData = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
433
  rsp.blockDataLen = taosArrayInit(0, sizeof(int32_t));
L
Liu Jicong 已提交
434
  rsp.blockSchema = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
435
  rsp.blockTbName = taosArrayInit(0, sizeof(void*));
436 437

  while (1) {
L
Liu Jicong 已提交
438
    consumerEpoch = atomic_load_32(&pExec->epoch);
L
Liu Jicong 已提交
439
    if (consumerEpoch > reqEpoch) {
H
Hongze Cheng 已提交
440 441
      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 已提交
442 443
      break;
    }
L
Liu Jicong 已提交
444

445 446 447
    taosThreadMutexLock(&pExec->pWalReader->mutex);

    if (walFetchHead(pExec->pWalReader, fetchOffset, pHeadWithCkSum) < 0) {
H
Hongze Cheng 已提交
448 449
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, no more log to return", consumerId, pReq->epoch,
              TD_VID(pTq->pVnode), fetchOffset);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
      taosThreadMutexUnlock(&pExec->pWalReader->mutex);
      break;
    }

    if (pHeadWithCkSum->head.msgType != TDMT_VND_SUBMIT) {
      walSkipFetchBody(pExec->pWalReader, pHeadWithCkSum);
    } else {
      walFetchBody(pExec->pWalReader, &pHeadWithCkSum);
    }

    SWalReadHead* pHead = &pHeadWithCkSum->head;

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

#if 0
L
fix  
Liu Jicong 已提交
465
    SWalReadHead* pHead;
L
Liu Jicong 已提交
466
    if (walReadWithHandle_s(pExec->pWalReader, fetchOffset, &pHead) < 0) {
L
Liu Jicong 已提交
467 468
      // TODO: no more log, set timer to wait blocking time
      // if data inserted during waiting, launch query and
L
Liu Jicong 已提交
469
      // response to user
H
Hongze Cheng 已提交
470
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, no more log to return", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
471
             TD_VID(pTq->pVnode), fetchOffset);
L
Liu Jicong 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

#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

494 495 496
    break;
  }
#endif
L
Liu Jicong 已提交
497

H
Hongze Cheng 已提交
498 499
    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 已提交
500

L
fix  
Liu Jicong 已提交
501 502
    if (pHead->msgType == TDMT_VND_SUBMIT) {
      SSubmitReq* pCont = (SSubmitReq*)&pHead->body;
503
      // table subscribe
L
Liu Jicong 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
      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 已提交
535 536 537 538 539 540

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

L
Liu Jicong 已提交
541 542 543 544 545 546 547 548 549 550 551 552
          if (pExec->withTbName) {
            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 已提交
553
          rsp.blockNum++;
554
        }
555
        // db subscribe
L
Liu Jicong 已提交
556
      } else if (pExec->subType == TOPIC_SUB_TYPE__DB) {
L
Liu Jicong 已提交
557
        STqReadHandle* pReader = pExec->pExecReader[workerId];
L
Liu Jicong 已提交
558 559 560
        tqReadHandleSetMsg(pReader, pCont, 0);
        while (tqNextDataBlock(pReader)) {
          SSDataBlock block = {0};
561
          if (tqRetrieveDataBlock(&block.pDataBlock, pReader, &block.info.groupId, &block.info.uid, &block.info.rows,
L
Liu Jicong 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
                                  &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);
L
Liu Jicong 已提交
581 582 583 584 585 586 587 588 589 590
          if (pExec->withTbName) {
            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 已提交
591 592 593 594

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

L
Liu Jicong 已提交
595 596 597 598
          rsp.blockNum++;
        }
      } else {
        ASSERT(0);
L
fix  
Liu Jicong 已提交
599
      }
L
Liu Jicong 已提交
600
    }
601

L
Liu Jicong 已提交
602 603
    // TODO batch optimization:
    // TODO continue scan until meeting batch requirement
L
Liu Jicong 已提交
604 605 606 607
    if (rsp.blockNum != 0) break;
    rsp.skipLogNum++;
    fetchOffset++;
  }
608

L
Liu Jicong 已提交
609 610
  ASSERT(taosArrayGetSize(rsp.blockData) == rsp.blockNum);
  ASSERT(taosArrayGetSize(rsp.blockDataLen) == rsp.blockNum);
L
fix  
Liu Jicong 已提交
611

L
Liu Jicong 已提交
612 613 614 615
  if (rsp.blockNum != 0)
    rsp.rspOffset = fetchOffset;
  else
    rsp.rspOffset = fetchOffset - 1;
616

L
Liu Jicong 已提交
617
  int32_t tlen = sizeof(SMqRspHead) + tEncodeSMqDataBlkRsp(NULL, &rsp);
618 619 620 621 622
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    pMsg->code = -1;
    return -1;
  }
L
Liu Jicong 已提交
623

L
Liu Jicong 已提交
624 625
  ((SMqRspHead*)buf)->mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
  ((SMqRspHead*)buf)->epoch = pReq->epoch;
L
Liu Jicong 已提交
626
  ((SMqRspHead*)buf)->consumerId = consumerId;
627

L
Liu Jicong 已提交
628
  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
L
Liu Jicong 已提交
629
  tEncodeSMqDataBlkRsp(&abuf, &rsp);
630 631 632
  pMsg->pCont = buf;
  pMsg->contLen = tlen;
  pMsg->code = 0;
S
shm  
Shengliang Guan 已提交
633
  tmsgSendRsp(pMsg);
L
Liu Jicong 已提交
634

H
Hongze Cheng 已提交
635 636
  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 已提交
637 638

  // TODO destroy
L
Liu Jicong 已提交
639 640
  taosArrayDestroy(rsp.blockData);
  taosArrayDestroy(rsp.blockDataLen);
L
Liu Jicong 已提交
641
  taosArrayDestroyP(rsp.blockSchema, (FDelete)tDeleteSSchemaWrapper);
L
Liu Jicong 已提交
642
  taosArrayDestroyP(rsp.blockTbName, (FDelete)taosMemoryFree);
L
Liu Jicong 已提交
643

644 645
  return 0;
}
L
Liu Jicong 已提交
646

L
Liu Jicong 已提交
647
#if 0
L
Liu Jicong 已提交
648 649 650 651 652 653 654 655
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 已提交
656
    fetchOffset = walGetFirstVer(pTq->pWal);
L
Liu Jicong 已提交
657 658 659 660 661 662
  } else if (pReq->currentOffset == TMQ_CONF__RESET_OFFSET__LATEST) {
    fetchOffset = walGetLastVer(pTq->pWal);
  } else {
    fetchOffset = pReq->currentOffset + 1;
  }

H
Hongze Cheng 已提交
663
  tqDebug("tmq poll: consumer %ld (epoch %d) recv poll req in vg %d, req %ld %ld", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
664
         TD_VID(pTq->pVnode), pReq->currentOffset, fetchOffset);
L
Liu Jicong 已提交
665 666 667 668 669 670

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

  STqConsumer* pConsumer = tqHandleGet(pTq->tqMeta, consumerId);
  if (pConsumer == NULL) {
H
refact  
Hongze Cheng 已提交
671
    vWarn("tmq poll: consumer %ld (epoch %d) not found in vg %d", consumerId, pReq->epoch, TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    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 已提交
697
          TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
698 699 700 701 702 703 704
    pMsg->pCont = NULL;
    pMsg->contLen = 0;
    pMsg->code = -1;
    tmsgSendRsp(pMsg);
    return 0;
  }

H
Hongze Cheng 已提交
705
  tqDebug("poll topic %s from consumer %ld (epoch %d) vg %d", pTopic->topicName, consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
706
         TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
707 708 709 710 711 712 713 714 715

  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 已提交
716
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, found new consumer epoch %d discard req epoch %d",
H
refact  
Hongze Cheng 已提交
717
             consumerId, pReq->epoch, TD_VID(pTq->pVnode), fetchOffset, consumerEpoch, reqEpoch);
L
Liu Jicong 已提交
718 719 720 721 722 723 724
      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 已提交
725
      tqDebug("tmq poll: consumer %ld (epoch %d) vg %d offset %ld, no more log to return", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
726
             TD_VID(pTq->pVnode), fetchOffset);
L
Liu Jicong 已提交
727 728
      break;
    }
H
Hongze Cheng 已提交
729
    tqDebug("tmq poll: consumer %ld (epoch %d) iter log, vg %d offset %ld msgType %d", consumerId, pReq->epoch,
H
refact  
Hongze Cheng 已提交
730
           TD_VID(pTq->pVnode), fetchOffset, pHead->msgType);
L
Liu Jicong 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    /*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 已提交
754
        tqDebug("tmq poll: consumer %ld (epoch %d) iter log, vg %d skip log %ld since not wanted", consumerId,
H
refact  
Hongze Cheng 已提交
755
               pReq->epoch, TD_VID(pTq->pVnode), fetchOffset);
L
Liu Jicong 已提交
756 757 758 759 760 761 762 763
        fetchOffset++;
        rspV2.skipLogNum++;
        taosArrayDestroy(pRes);
        continue;
      }
      rspV2.rspOffset = fetchOffset;

      int32_t blockSz = taosArrayGetSize(pRes);
L
Liu Jicong 已提交
764
      int32_t dataBlockStrLen = 0;
L
Liu Jicong 已提交
765 766
      for (int32_t i = 0; i < blockSz; i++) {
        SSDataBlock* pBlock = taosArrayGet(pRes, i);
L
Liu Jicong 已提交
767
        dataBlockStrLen += sizeof(SRetrieveTableRsp) + blockGetEncodeSize(pBlock);
L
Liu Jicong 已提交
768 769
      }

L
Liu Jicong 已提交
770 771
      void* dataBlockBuf = taosMemoryMalloc(dataBlockStrLen);
      if (dataBlockBuf == NULL) {
L
Liu Jicong 已提交
772 773 774 775
        pMsg->code = -1;
        taosMemoryFree(pHead);
      }

L
Liu Jicong 已提交
776
      rspV2.blockData = dataBlockBuf;
L
Liu Jicong 已提交
777 778

      int32_t pos;
L
Liu Jicong 已提交
779
      rspV2.blockPos = taosArrayInit(blockSz, sizeof(int32_t));
L
Liu Jicong 已提交
780 781
      for (int32_t i = 0; i < blockSz; i++) {
        pos = 0;
L
Liu Jicong 已提交
782 783 784 785 786 787 788 789
        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 已提交
790
        taosArrayPush(rspV2.blockPos, &rspV2.dataLen);
L
Liu Jicong 已提交
791 792 793 794 795

        int32_t totLen = sizeof(SRetrieveTableRsp) + pos;
        pRetrieve->compLen = htonl(totLen);
        rspV2.dataLen += totLen;
        dataBlockBuf = POINTER_SHIFT(dataBlockBuf, totLen);
L
Liu Jicong 已提交
796
      }
L
Liu Jicong 已提交
797
      ASSERT(POINTER_DISTANCE(dataBlockBuf, rspV2.blockData) <= dataBlockStrLen);
L
Liu Jicong 已提交
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

      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 已提交
813
      pMsg->contLen = msgLen;
L
Liu Jicong 已提交
814
      pMsg->code = 0;
H
Hongze Cheng 已提交
815
      tqDebug("vg %d offset %ld msgType %d from consumer %ld (epoch %d) actual rsp", TD_VID(pTq->pVnode), fetchOffset,
L
Liu Jicong 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
             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 已提交
849
  tqDebug("vg %d offset %ld from consumer %ld (epoch %d) not rsp", TD_VID(pTq->pVnode), fetchOffset, consumerId,
L
Liu Jicong 已提交
850 851 852 853 854
         pReq->epoch);
  /*}*/

  return 0;
}
L
Liu Jicong 已提交
855 856 857 858
#endif

// TODO: persist meta into tdb
int32_t tqProcessVgChangeReq(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
859
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
860 861
  tDecodeSMqRebVgReq(msg, &req);
  // todo lock
L
Liu Jicong 已提交
862
  STqExec* pExec = taosHashGet(pTq->execs, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
863 864 865 866 867 868 869 870 871 872
  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 已提交
873 874 875 876 877 878

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

L
Liu Jicong 已提交
879 880
    pExec->qmsg = req.qmsg;
    req.qmsg = NULL;
L
Liu Jicong 已提交
881 882

    pExec->pWalReader = walOpenReadHandle(pTq->pVnode->pWal);
L
Liu Jicong 已提交
883 884
    for (int32_t i = 0; i < 5; i++) {
      pExec->pExecReader[i] = tqInitSubmitMsgScanner(pTq->pVnode->pMeta);
L
Liu Jicong 已提交
885 886 887 888
      if (pExec->subType == TOPIC_SUB_TYPE__TABLE) {
        SReadHandle handle = {
            .reader = pExec->pExecReader[i],
            .meta = pTq->pVnode->pMeta,
889
            .pMsgCb = &pTq->pVnode->msgCb,
L
Liu Jicong 已提交
890 891 892 893 894 895
        };
        pExec->task[i] = qCreateStreamExecTaskInfo(pExec->qmsg, &handle);
        ASSERT(pExec->task[i]);
      } else {
        pExec->task[i] = NULL;
      }
L
Liu Jicong 已提交
896
    }
L
Liu Jicong 已提交
897
    taosHashPut(pTq->execs, req.subKey, strlen(req.subKey), pExec, sizeof(STqExec));
L
Liu Jicong 已提交
898 899
    return 0;
  } else {
L
Liu Jicong 已提交
900 901 902 903 904 905 906 907 908 909 910 911 912 913
    /*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 已提交
914 915
  }
}
916

L
Liu Jicong 已提交
917 918 919 920 921 922
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 已提交
923
  /*tPrintFixedSchemaSubmitReq(pReq, pTask->tbSink.pTSchema);*/
L
Liu Jicong 已提交
924
  // build write msg
L
Liu Jicong 已提交
925 926 927 928 929
  SRpcMsg msg = {
      .msgType = TDMT_VND_SUBMIT,
      .pCont = pReq,
      .contLen = ntohl(pReq->length),
  };
L
Liu Jicong 已提交
930

L
Liu Jicong 已提交
931
  ASSERT(tmsgPutToQueue(&pVnode->msgCb, WRITE_QUEUE, &msg) == 0);
L
Liu Jicong 已提交
932
}
L
Liu Jicong 已提交
933

L
Liu Jicong 已提交
934 935 936 937 938 939 940 941 942 943 944 945 946
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,
947
             .pMsgCb = &pTq->pVnode->msgCb,
L
Liu Jicong 已提交
948 949 950 951 952
      };
      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 已提交
953
  }
L
Liu Jicong 已提交
954 955 956 957

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

L
Liu Jicong 已提交
960 961 962
  return 0;
}

L
Liu Jicong 已提交
963
int32_t tqProcessTaskDeploy(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
964
  SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask));
L
Liu Jicong 已提交
965 966 967
  if (pTask == NULL) {
    return -1;
  }
H
Hongze Cheng 已提交
968 969
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
L
Liu Jicong 已提交
970 971 972
  if (tDecodeSStreamTask(&decoder, pTask) < 0) {
    ASSERT(0);
  }
H
Hongze Cheng 已提交
973
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
974

L
Liu Jicong 已提交
975
  // exec
L
Liu Jicong 已提交
976 977 978
  if (tqExpandTask(pTq, pTask, 4) < 0) {
    ASSERT(0);
  }
L
Liu Jicong 已提交
979 980

  // sink
L
Liu Jicong 已提交
981
  pTask->ahandle = pTq->pVnode;
L
Liu Jicong 已提交
982
  if (pTask->sinkType == TASK_SINK__SMA) {
L
Liu Jicong 已提交
983
    pTask->smaSink.smaSink = smaHandleRes;
L
Liu Jicong 已提交
984 985 986 987 988 989
  } 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 已提交
990
  }
L
Liu Jicong 已提交
991

L
Liu Jicong 已提交
992 993 994 995
  taosHashPut(pTq->pStreamTasks, &pTask->taskId, sizeof(int32_t), pTask, sizeof(SStreamTask));

  return 0;
}
L
Liu Jicong 已提交
996

L
Liu Jicong 已提交
997
int32_t tqProcessStreamTrigger(STQ* pTq, void* data, int32_t dataLen, int32_t workerId) {
L
Liu Jicong 已提交
998 999 1000 1001 1002 1003 1004
  void* pIter = NULL;

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

L
Liu Jicong 已提交
1005
    if (streamExecTask(pTask, &pTq->pVnode->msgCb, data, STREAM_DATA_TYPE_SUBMIT_BLOCK, workerId) < 0) {
L
Liu Jicong 已提交
1006
      // TODO
L
Liu Jicong 已提交
1007 1008 1009 1010 1011
    }
  }
  return 0;
}

L
Liu Jicong 已提交
1012
int32_t tqProcessTaskExec(STQ* pTq, char* msg, int32_t msgLen, int32_t workerId) {
L
Liu Jicong 已提交
1013
  SStreamTaskExecReq req;
L
Liu Jicong 已提交
1014
  tDecodeSStreamTaskExecReq(msg, &req);
L
Liu Jicong 已提交
1015

L
Liu Jicong 已提交
1016 1017 1018
  int32_t taskId = req.taskId;
  ASSERT(taskId);

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

L
Liu Jicong 已提交
1022
  if (streamExecTask(pTask, &pTq->pVnode->msgCb, req.data, STREAM_DATA_TYPE_SSDATA_BLOCK, workerId) < 0) {
L
Liu Jicong 已提交
1023
    // TODO
L
Liu Jicong 已提交
1024
  }
L
Liu Jicong 已提交
1025 1026
  return 0;
}