tq.c 60.3 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

dengyihao's avatar
dengyihao 已提交
18 19 20
// 0: not init
// 1: already inited
// 2: wait to be inited or cleaup
21
static int32_t tqInitialize(STQ* pTq);
dengyihao's avatar
dengyihao 已提交
22

wmmhello's avatar
wmmhello 已提交
23
static FORCE_INLINE bool tqIsHandleExec(STqHandle* pHandle) { return TMQ_HANDLE_STATUS_EXEC == pHandle->status; }
dengyihao's avatar
dengyihao 已提交
24 25
static FORCE_INLINE void tqSetHandleExec(STqHandle* pHandle) { pHandle->status = TMQ_HANDLE_STATUS_EXEC; }
static FORCE_INLINE void tqSetHandleIdle(STqHandle* pHandle) { pHandle->status = TMQ_HANDLE_STATUS_IDLE; }
wmmhello's avatar
wmmhello 已提交
26

L
Liu Jicong 已提交
27
int32_t tqInit() {
L
Liu Jicong 已提交
28 29 30 31 32 33
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 0, 2);
    if (old != 2) break;
  }

34 35 36 37 38 39
  if (old == 0) {
    tqMgmt.timer = taosTmrInit(10000, 100, 10000, "TQ");
    if (tqMgmt.timer == NULL) {
      atomic_store_8(&tqMgmt.inited, 0);
      return -1;
    }
40 41 42
    if (streamInit() < 0) {
      return -1;
    }
L
Liu Jicong 已提交
43
    atomic_store_8(&tqMgmt.inited, 1);
44
  }
45

L
Liu Jicong 已提交
46 47
  return 0;
}
L
Liu Jicong 已提交
48

49
void tqCleanUp() {
L
Liu Jicong 已提交
50 51 52 53 54 55 56 57
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 1, 2);
    if (old != 2) break;
  }

  if (old == 1) {
    taosTmrCleanUp(tqMgmt.timer);
L
Liu Jicong 已提交
58
    streamCleanUp();
L
Liu Jicong 已提交
59 60
    atomic_store_8(&tqMgmt.inited, 0);
  }
61
}
L
Liu Jicong 已提交
62

63
void tqDestroyTqHandle(void* data) {
64 65
  STqHandle* pData = (STqHandle*)data;
  qDestroyTask(pData->execHandle.task);
wmmhello's avatar
wmmhello 已提交
66

67
  if (pData->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
68
    taosMemoryFreeClear(pData->execHandle.execCol.qmsg);
69
  } else if (pData->execHandle.subType == TOPIC_SUB_TYPE__DB) {
70
    tqReaderClose(pData->execHandle.pTqReader);
71 72
    walCloseReader(pData->pWalReader);
    taosHashCleanup(pData->execHandle.execDb.pFilterOutTbUid);
L
Liu Jicong 已提交
73
  } else if (pData->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
74
    walCloseReader(pData->pWalReader);
75
    tqReaderClose(pData->execHandle.pTqReader);
76 77
    taosMemoryFreeClear(pData->execHandle.execTb.qmsg);
    nodesDestroyNode(pData->execHandle.execTb.node);
78
  }
dengyihao's avatar
dengyihao 已提交
79
  if (pData->msg != NULL) {
80 81 82
    rpcFreeCont(pData->msg->pCont);
    taosMemoryFree(pData->msg);
    pData->msg = NULL;
D
dapan1121 已提交
83
  }
L
Liu Jicong 已提交
84 85
}

86
static bool tqOffsetEqual(const STqOffset* pLeft, const STqOffset* pRight) {
87
  return pLeft->val.type == TMQ_OFFSET__LOG && pRight->val.type == TMQ_OFFSET__LOG &&
88
         pLeft->val.version == pRight->val.version;
89 90
}

L
Liu Jicong 已提交
91
STQ* tqOpen(const char* path, SVnode* pVnode) {
92
  STQ* pTq = taosMemoryCalloc(1, sizeof(STQ));
L
Liu Jicong 已提交
93
  if (pTq == NULL) {
S
Shengliang Guan 已提交
94
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
95 96
    return NULL;
  }
97

98
  pTq->path = taosStrdup(path);
L
Liu Jicong 已提交
99
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
100
  pTq->walLogLastVer = pVnode->pWal->vers.lastVer;
101

102
  pTq->pHandle = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
103
  taosHashSetFreeFp(pTq->pHandle, tqDestroyTqHandle);
104

105
  taosInitRWLatch(&pTq->lock);
106
  pTq->pPushMgr = taosHashInit(64, MurmurHash3_32, false, HASH_NO_LOCK);
L
Liu Jicong 已提交
107

108
  pTq->pCheckInfo = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
109
  taosHashSetFreeFp(pTq->pCheckInfo, (FDelete)tDeleteSTqCheckInfo);
L
Liu Jicong 已提交
110

111 112 113 114 115 116 117
  int32_t code = tqInitialize(pTq);
  if (code != TSDB_CODE_SUCCESS) {
    tqClose(pTq);
    return NULL;
  } else {
    return pTq;
  }
118 119 120
}

int32_t tqInitialize(STQ* pTq) {
L
Liu Jicong 已提交
121
  if (tqMetaOpen(pTq) < 0) {
122
    return -1;
123 124
  }

L
Liu Jicong 已提交
125 126
  pTq->pOffsetStore = tqOffsetOpen(pTq);
  if (pTq->pOffsetStore == NULL) {
127
    return -1;
128 129
  }

130
  pTq->pStreamMeta = streamMetaOpen(pTq->path, pTq, (FTaskExpand*)tqExpandTask, pTq->pVnode->config.vgId);
L
Liu Jicong 已提交
131
  if (pTq->pStreamMeta == NULL) {
132
    return -1;
L
Liu Jicong 已提交
133 134
  }

135 136
  // the version is kept in task's meta data
  // todo check if this version is required or not
137 138
  if (streamLoadTasks(pTq->pStreamMeta, walGetCommittedVer(pTq->pVnode->pWal)) < 0) {
    return -1;
L
Liu Jicong 已提交
139 140
  }

141
  return 0;
L
Liu Jicong 已提交
142
}
L
Liu Jicong 已提交
143

L
Liu Jicong 已提交
144
void tqClose(STQ* pTq) {
145 146
  if (pTq == NULL) {
    return;
H
Hongze Cheng 已提交
147
  }
148

wmmhello's avatar
wmmhello 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162
  void* pIter = taosHashIterate(pTq->pPushMgr, NULL);
  while (pIter) {
    STqHandle* pHandle = *(STqHandle**)pIter;
    int32_t    vgId = TD_VID(pTq->pVnode);

    if(pHandle->msg != NULL) {
      tqPushEmptyDataRsp(pHandle, vgId);
      rpcFreeCont(pHandle->msg->pCont);
      taosMemoryFree(pHandle->msg);
      pHandle->msg = NULL;
    }
    pIter = taosHashIterate(pTq->pPushMgr, pIter);
  }

163 164 165 166 167 168 169 170
  tqOffsetClose(pTq->pOffsetStore);
  taosHashCleanup(pTq->pHandle);
  taosHashCleanup(pTq->pPushMgr);
  taosHashCleanup(pTq->pCheckInfo);
  taosMemoryFree(pTq->path);
  tqMetaClose(pTq);
  streamMetaClose(pTq->pStreamMeta);
  taosMemoryFree(pTq);
L
Liu Jicong 已提交
171
}
L
Liu Jicong 已提交
172

173 174 175 176 177 178 179 180 181 182 183 184 185
static bool hasStreamTaskInTimer(SStreamMeta* pMeta) {
  bool inTimer = false;

  taosWLockLatch(&pMeta->lock);

  void* pIter = NULL;
  while(1) {
    pIter = taosHashIterate(pMeta->pTasks, pIter);
    if (pIter == NULL) {
      break;
    }

    SStreamTask* pTask = *(SStreamTask**)pIter;
186
    if (pTask->status.timerActive >= 1) {
187 188 189 190 191 192 193 194 195
      inTimer = true;
    }
  }

  taosWUnLockLatch(&pMeta->lock);

  return inTimer;
}

H
Haojun Liao 已提交
196 197 198 199 200 201 202 203 204 205 206 207
void tqNotifyClose(STQ* pTq) {
  if (pTq != NULL) {
    taosWLockLatch(&pTq->pStreamMeta->lock);

    void* pIter = NULL;
    while (1) {
      pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
      if (pIter == NULL) {
        break;
      }

      SStreamTask* pTask = *(SStreamTask**)pIter;
H
Haojun Liao 已提交
208
      tqDebug("vgId:%d s-task:%s set closing flag", pTq->pStreamMeta->vgId, pTask->id.idStr);
209 210 211
      pTask->status.taskStatus = TASK_STATUS__STOP;

      int64_t st = taosGetTimestampMs();
H
Haojun Liao 已提交
212
      qKillTask(pTask->exec.pExecutor, TSDB_CODE_SUCCESS);
H
Haojun Liao 已提交
213

214
      int64_t el = taosGetTimestampMs() - st;
H
Haojun Liao 已提交
215
      tqDebug("vgId:%d s-task:%s is closed in %" PRId64 " ms", pTq->pStreamMeta->vgId, pTask->id.idStr, el);
H
Haojun Liao 已提交
216 217 218
    }

    taosWUnLockLatch(&pTq->pStreamMeta->lock);
H
Haojun Liao 已提交
219 220 221 222 223

    tqDebug("vgId:%d start to check all tasks", pTq->pStreamMeta->vgId);

    int64_t st = taosGetTimestampMs();

224 225 226
    while(hasStreamTaskInTimer(pTq->pStreamMeta)) {
      tqDebug("vgId:%d some tasks in timer, wait for 100ms and recheck", pTq->pStreamMeta->vgId);
      taosMsleep(100);
H
Haojun Liao 已提交
227 228 229 230
    }

    int64_t el = taosGetTimestampMs() - st;
    tqDebug("vgId:%d all stream tasks are not in timer, continue close, elapsed time:%"PRId64" ms", pTq->pStreamMeta->vgId, el);
H
Haojun Liao 已提交
231 232 233
  }
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
//static int32_t doSendDataRsp(const SRpcHandleInfo* pRpcHandleInfo, const SMqDataRsp* pRsp, int32_t epoch,
//                             int64_t consumerId, int32_t type) {
//  int32_t len = 0;
//  int32_t code = 0;
//
//  if (type == TMQ_MSG_TYPE__POLL_DATA_RSP) {
//    tEncodeSize(tEncodeMqDataRsp, pRsp, len, code);
//  } else if (type == TMQ_MSG_TYPE__POLL_DATA_META_RSP) {
//    tEncodeSize(tEncodeSTaosxRsp, (STaosxRsp*)pRsp, len, code);
//  }
//
//  if (code < 0) {
//    return -1;
//  }
//
//  int32_t tlen = sizeof(SMqRspHead) + len;
//  void*   buf = rpcMallocCont(tlen);
//  if (buf == NULL) {
//    return -1;
//  }
//
//  ((SMqRspHead*)buf)->mqMsgType = type;
//  ((SMqRspHead*)buf)->epoch = epoch;
//  ((SMqRspHead*)buf)->consumerId = consumerId;
//
//  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
//
//  SEncoder encoder = {0};
//  tEncoderInit(&encoder, abuf, len);
//
//  if (type == TMQ_MSG_TYPE__POLL_DATA_RSP) {
//    tEncodeMqDataRsp(&encoder, pRsp);
//  } else if (type == TMQ_MSG_TYPE__POLL_DATA_META_RSP) {
//    tEncodeSTaosxRsp(&encoder, (STaosxRsp*)pRsp);
//  }
//
//  tEncoderClear(&encoder);
//
//  SRpcMsg rsp = {
//      .info = *pRpcHandleInfo,
//      .pCont = buf,
//      .contLen = tlen,
//      .code = 0,
//  };
//
//  tmsgSendRsp(&rsp);
//  return 0;
//}
L
Liu Jicong 已提交
282

283 284 285 286 287 288 289
int32_t tqPushEmptyDataRsp(STqHandle* pHandle, int32_t vgId) {
  SMqPollReq req = {0};
  if (tDeserializeSMqPollReq(pHandle->msg->pCont, pHandle->msg->contLen, &req) < 0) {
    tqError("tDeserializeSMqPollReq %d failed", pHandle->msg->contLen);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }
D
dapan1121 已提交
290

291
  SMqDataRsp dataRsp = {0};
292
  tqInitDataRsp(&dataRsp, req.reqOffset);
293
  dataRsp.blockNum = 0;
wmmhello's avatar
wmmhello 已提交
294 295 296 297
  char buf[TSDB_OFFSET_LEN] = {0};
  tFormatOffset(buf, TSDB_OFFSET_LEN, &dataRsp.reqOffset);
  tqInfo("tqPushEmptyDataRsp to consumer:0x%"PRIx64 " vgId:%d, offset:%s, reqId:0x%" PRIx64, req.consumerId, vgId, buf, req.reqId);

H
Haojun Liao 已提交
298
  tqSendDataRsp(pHandle, pHandle->msg, &req, &dataRsp, TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
299
  tDeleteMqDataRsp(&dataRsp);
L
Liu Jicong 已提交
300 301 302
  return 0;
}

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
//int32_t tqPushDataRsp(STqHandle* pHandle, int32_t vgId) {
//  SMqDataRsp dataRsp = {0};
//  dataRsp.head.consumerId = pHandle->consumerId;
//  dataRsp.head.epoch = pHandle->epoch;
//  dataRsp.head.mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
//
//  int64_t sver = 0, ever = 0;
//  walReaderValidVersionRange(pHandle->execHandle.pTqReader->pWalReader, &sver, &ever);
//  tqDoSendDataRsp(&pHandle->msg->info, &dataRsp, pHandle->epoch, pHandle->consumerId, TMQ_MSG_TYPE__POLL_RSP, sver,
//                  ever);
//
//  char buf1[TSDB_OFFSET_LEN] = {0};
//  char buf2[TSDB_OFFSET_LEN] = {0};
//  tFormatOffset(buf1, tListLen(buf1), &dataRsp.reqOffset);
//  tFormatOffset(buf2, tListLen(buf2), &dataRsp.rspOffset);
//  tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) push rsp, block num: %d, req:%s, rsp:%s", vgId,
//          dataRsp.head.consumerId, dataRsp.head.epoch, dataRsp.blockNum, buf1, buf2);
//  return 0;
//}

323 324 325 326 327 328
int32_t tqSendDataRsp(STqHandle* pHandle, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqDataRsp* pRsp,
                      int32_t type, int32_t vgId) {
  int64_t sver = 0, ever = 0;
  walReaderValidVersionRange(pHandle->execHandle.pTqReader->pWalReader, &sver, &ever);

  tqDoSendDataRsp(&pMsg->info, pRsp, pReq->epoch, pReq->consumerId, type, sver, ever);
329

330 331 332 333
  char buf1[TSDB_OFFSET_LEN] = {0};
  char buf2[TSDB_OFFSET_LEN] = {0};
  tFormatOffset(buf1, TSDB_OFFSET_LEN, &pRsp->reqOffset);
  tFormatOffset(buf2, TSDB_OFFSET_LEN, &pRsp->rspOffset);
334

335
  tqDebug("tmq poll vgId:%d consumer:0x%" PRIx64 " (epoch %d) send rsp, block num:%d, req:%s, rsp:%s, reqId:0x%" PRIx64, vgId,
dengyihao's avatar
dengyihao 已提交
336
          pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2, pReq->reqId);
337 338 339 340

  return 0;
}

341
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
342 343
  SMqVgOffset vgOffset = {0};
  int32_t     vgId = TD_VID(pTq->pVnode);
344

X
Xiaoyu Wang 已提交
345 346
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
347
  if (tDecodeMqVgOffset(&decoder, &vgOffset) < 0) {
348 349
    return -1;
  }
350

351 352
  tDecoderClear(&decoder);

353 354 355
  STqOffset* pOffset = &vgOffset.offset;

  if (pOffset->val.type == TMQ_OFFSET__SNAPSHOT_DATA || pOffset->val.type == TMQ_OFFSET__SNAPSHOT_META) {
356
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:snapshot) uid:%" PRId64 ", ts:%" PRId64,
357 358
            pOffset->subKey, vgId, pOffset->val.uid, pOffset->val.ts);
  } else if (pOffset->val.type == TMQ_OFFSET__LOG) {
359
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, pOffset->subKey, vgId,
360
            pOffset->val.version);
361
  } else {
362
    tqError("invalid commit offset type:%d", pOffset->val.type);
363
    return -1;
364
  }
365

366
  STqOffset* pSavedOffset = tqOffsetRead(pTq->pOffsetStore, pOffset->subKey);
367 368
  if (pSavedOffset != NULL && tqOffsetEqual(pOffset, pSavedOffset)) {
    tqInfo("not update the offset, vgId:%d sub:%s since committed:%" PRId64 " less than/equal to existed:%" PRId64,
369
            vgId, pOffset->subKey, pOffset->val.version, pSavedOffset->val.version);
370
    return 0;  // no need to update the offset value
371 372
  }

373
  // save the new offset value
374
  if (tqOffsetWrite(pTq->pOffsetStore, pOffset) < 0) {
375
    return -1;
376
  }
377

378 379 380
  return 0;
}

381 382
int32_t tqProcessSeekReq(STQ* pTq, SRpcMsg* pMsg) {
  SMqSeekReq  req = {0};
383
  int32_t     vgId = TD_VID(pTq->pVnode);
384 385
  SRpcMsg     rsp = {.info = pMsg->info};
  int         code = 0;
386

387 388 389
  if (tDeserializeSMqSeekReq(pMsg->pCont, pMsg->contLen, &req) < 0) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
390 391
  }

392
  tqDebug("tmq seek: consumer:0x%" PRIx64 " vgId:%d, subkey %s", req.consumerId, vgId, req.subKey);
393
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
394
  if (pHandle == NULL) {
395 396 397
    tqWarn("tmq seek: consumer:0x%" PRIx64 " vgId:%d subkey %s not found", req.consumerId, vgId, req.subKey);
    code = 0;
    goto end;
398 399
  }

400 401
  // 2. check consumer-vg assignment status
  taosRLockLatch(&pTq->lock);
402 403 404
  if (pHandle->consumerId != req.consumerId) {
    tqError("ERROR tmq seek: consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
            req.consumerId, vgId, req.subKey, pHandle->consumerId);
405
    taosRUnLockLatch(&pTq->lock);
406 407
    code = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
    goto end;
408 409
  }

410 411 412 413
  //if consumer register to push manager, push empty to consumer to change vg status from TMQ_VG_STATUS__WAIT to TMQ_VG_STATUS__IDLE,
  //otherwise poll data failed after seek.
  tqUnregisterPushHandle(pTq, pHandle);
  taosRUnLockLatch(&pTq->lock);
H
Haojun Liao 已提交
414

415 416 417
end:
  rsp.code = code;
  tmsgSendRsp(&rsp);
418
  return 0;
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

//  SMqVgOffset vgOffset = {0};
//  int32_t     vgId = TD_VID(pTq->pVnode);
//
//  SDecoder decoder;
//  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
//  if (tDecodeMqVgOffset(&decoder, &vgOffset) < 0) {
//    tqError("vgId:%d failed to decode seek msg", vgId);
//    return -1;
//  }
//
//  tDecoderClear(&decoder);
//
//  tqDebug("topic:%s, vgId:%d process offset seek by consumer:0x%" PRIx64 ", req offset:%" PRId64,
//          vgOffset.offset.subKey, vgId, vgOffset.consumerId, vgOffset.offset.val.version);
//
//  STqOffset* pOffset = &vgOffset.offset;
//  if (pOffset->val.type != TMQ_OFFSET__LOG) {
//    tqError("vgId:%d, subKey:%s invalid seek offset type:%d", vgId, pOffset->subKey, pOffset->val.type);
//    return -1;
//  }
//
//  STqHandle* pHandle = taosHashGet(pTq->pHandle, pOffset->subKey, strlen(pOffset->subKey));
//  if (pHandle == NULL) {
//    tqError("tmq seek: consumer:0x%" PRIx64 " vgId:%d subkey %s not found", vgOffset.consumerId, vgId, pOffset->subKey);
//    terrno = TSDB_CODE_INVALID_MSG;
//    return -1;
//  }
//
//  // 2. check consumer-vg assignment status
//  taosRLockLatch(&pTq->lock);
//  if (pHandle->consumerId != vgOffset.consumerId) {
//    tqDebug("ERROR tmq seek: consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
//            vgOffset.consumerId, vgId, pOffset->subKey, pHandle->consumerId);
//    terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
//    taosRUnLockLatch(&pTq->lock);
//    return -1;
//  }
//  taosRUnLockLatch(&pTq->lock);
//
//  // 3. check the offset info
//  STqOffset* pSavedOffset = tqOffsetRead(pTq->pOffsetStore, pOffset->subKey);
//  if (pSavedOffset != NULL) {
//    if (pSavedOffset->val.type != TMQ_OFFSET__LOG) {
//      tqError("invalid saved offset type, vgId:%d sub:%s", vgId, pOffset->subKey);
//      return 0;  // no need to update the offset value
//    }
//
//    if (pSavedOffset->val.version == pOffset->val.version) {
//      tqDebug("vgId:%d subKey:%s no need to seek to %" PRId64 " prev offset:%" PRId64, vgId, pOffset->subKey,
//              pOffset->val.version, pSavedOffset->val.version);
//      return 0;
//    }
//  }
//
//  int64_t sver = 0, ever = 0;
//  walReaderValidVersionRange(pHandle->execHandle.pTqReader->pWalReader, &sver, &ever);
//  if (pOffset->val.version < sver) {
//    pOffset->val.version = sver;
//  } else if (pOffset->val.version > ever) {
//    pOffset->val.version = ever;
//  }
//
//  // save the new offset value
//  if (pSavedOffset != NULL) {
//    tqDebug("vgId:%d sub:%s seek to:%" PRId64 " prev offset:%" PRId64, vgId, pOffset->subKey, pOffset->val.version,
//            pSavedOffset->val.version);
//  } else {
//    tqDebug("vgId:%d sub:%s seek to:%" PRId64 " not saved yet", vgId, pOffset->subKey, pOffset->val.version);
//  }
//
//  if (tqOffsetWrite(pTq->pOffsetStore, pOffset) < 0) {
//    tqError("failed to save offset, vgId:%d sub:%s seek to %" PRId64, vgId, pOffset->subKey, pOffset->val.version);
//    return -1;
//  }
//
//  tqDebug("topic:%s, vgId:%d consumer:0x%" PRIx64 " offset is update to:%" PRId64, vgOffset.offset.subKey, vgId,
//          vgOffset.consumerId, vgOffset.offset.val.version);
//
//  return 0;
499 500
}

L
Liu Jicong 已提交
501
int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) {
L
Liu Jicong 已提交
502
  void* pIter = NULL;
503

L
Liu Jicong 已提交
504
  while (1) {
505
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
506 507 508 509
    if (pIter == NULL) {
      break;
    }

510
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
511

L
Liu Jicong 已提交
512 513
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
514
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
515 516
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
517
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
518 519 520 521 522
          return -1;
        }
      }
    }
  }
523

L
Liu Jicong 已提交
524 525 526
  return 0;
}

527 528 529 530 531 532 533 534
int32_t tqProcessPollPush(STQ* pTq, SRpcMsg* pMsg) {
  int32_t vgId = TD_VID(pTq->pVnode);
  taosWLockLatch(&pTq->lock);
  if (taosHashGetSize(pTq->pPushMgr) > 0) {
    void* pIter = taosHashIterate(pTq->pPushMgr, NULL);

    while (pIter) {
      STqHandle* pHandle = *(STqHandle**)pIter;
wmmhello's avatar
wmmhello 已提交
535
      tqInfo("vgId:%d start set submit for pHandle:%p, consumer:0x%" PRIx64, vgId, pHandle, pHandle->consumerId);
536 537 538

      if (ASSERT(pHandle->msg != NULL)) {
        tqError("pHandle->msg should not be null");
wmmhello's avatar
wmmhello 已提交
539
        taosHashCancelIterate(pTq->pPushMgr, pIter);
540 541 542 543 544 545 546 547 548 549 550 551 552
        break;
      }else{
        SRpcMsg msg = {.msgType = TDMT_VND_TMQ_CONSUME, .pCont = pHandle->msg->pCont, .contLen = pHandle->msg->contLen, .info = pHandle->msg->info};
        tmsgPutToQueue(&pTq->pVnode->msgCb, QUERY_QUEUE, &msg);
        taosMemoryFree(pHandle->msg);
        pHandle->msg = NULL;
      }

      pIter = taosHashIterate(pTq->pPushMgr, pIter);
    }

    taosHashClear(pTq->pPushMgr);
  }
wmmhello's avatar
wmmhello 已提交
553
  taosWUnLockLatch(&pTq->lock);
554 555 556
  return 0;
}

D
dapan1121 已提交
557
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
X
Xiaoyu Wang 已提交
558
  SMqPollReq req = {0};
dengyihao's avatar
dengyihao 已提交
559
  int        code = 0;
D
dapan1121 已提交
560 561 562 563 564 565 566 567 568 569
  if (tDeserializeSMqPollReq(pMsg->pCont, pMsg->contLen, &req) < 0) {
    tqError("tDeserializeSMqPollReq %d failed", pMsg->contLen);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  int64_t      consumerId = req.consumerId;
  int32_t      reqEpoch = req.epoch;
  STqOffsetVal reqOffset = req.reqOffset;
  int32_t      vgId = TD_VID(pTq->pVnode);
wmmhello's avatar
wmmhello 已提交
570
  STqHandle*   pHandle = NULL;
D
dapan1121 已提交
571

wmmhello's avatar
wmmhello 已提交
572 573 574 575 576
  while (1) {
    taosWLockLatch(&pTq->lock);
    // 1. find handle
    pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
    if (pHandle == NULL) {
wmmhello's avatar
wmmhello 已提交
577 578 579 580 581 582 583 584 585 586 587 588
      do{
        if (tqMetaGetHandle(pTq, req.subKey) == 0){
          pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
          if(pHandle != NULL){
            break;
          }
        }
        tqError("tmq poll: consumer:0x%" PRIx64 " vgId:%d subkey %s not found", consumerId, vgId, req.subKey);
        terrno = TSDB_CODE_INVALID_MSG;
        taosWUnLockLatch(&pTq->lock);
        return -1;
      }while(0);
wmmhello's avatar
wmmhello 已提交
589
    }
D
dapan1121 已提交
590

591 592
    // 2. check re-balance status
    if (pHandle->consumerId != consumerId) {
dengyihao's avatar
dengyihao 已提交
593 594
      tqError("ERROR tmq poll: consumer:0x%" PRIx64
              " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
595
              consumerId, TD_VID(pTq->pVnode), req.subKey, pHandle->consumerId);
596
      terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
597 598 599
      taosWUnLockLatch(&pTq->lock);
      return -1;
    }
wmmhello's avatar
wmmhello 已提交
600

wmmhello's avatar
wmmhello 已提交
601
    bool exec = tqIsHandleExec(pHandle);
dengyihao's avatar
dengyihao 已提交
602
    if (!exec) {
wmmhello's avatar
wmmhello 已提交
603
      tqSetHandleExec(pHandle);
dengyihao's avatar
dengyihao 已提交
604
      //      qSetTaskCode(pHandle->execHandle.task, TDB_CODE_SUCCESS);
605
      tqDebug("tmq poll: consumer:0x%" PRIx64 " vgId:%d, topic:%s, set handle exec, pHandle:%p", consumerId, vgId,
dengyihao's avatar
dengyihao 已提交
606
              req.subKey, pHandle);
wmmhello's avatar
wmmhello 已提交
607 608 609
      taosWUnLockLatch(&pTq->lock);
      break;
    }
610
    taosWUnLockLatch(&pTq->lock);
611

dengyihao's avatar
dengyihao 已提交
612 613 614
    tqDebug("tmq poll: consumer:0x%" PRIx64
            "vgId:%d, topic:%s, subscription is executing, wait for 10ms and retry, pHandle:%p",
            consumerId, vgId, req.subKey, pHandle);
wmmhello's avatar
wmmhello 已提交
615
    taosMsleep(10);
D
dapan1121 已提交
616 617 618
  }

  // 3. update the epoch value
619
  if (pHandle->epoch < reqEpoch) {
dengyihao's avatar
dengyihao 已提交
620
    tqDebug("tmq poll: consumer:0x%" PRIx64 " epoch update from %d to %d by poll req", consumerId, pHandle->epoch,
X
Xiaoyu Wang 已提交
621
            reqEpoch);
D
dapan1121 已提交
622 623 624
    pHandle->epoch = reqEpoch;
  }

wmmhello's avatar
wmmhello 已提交
625
  char buf[TSDB_OFFSET_LEN] = {0};
626
  tFormatOffset(buf, TSDB_OFFSET_LEN, &reqOffset);
D
dapan1121 已提交
627 628 629
  tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, recv poll req vgId:%d, req:%s, reqId:0x%" PRIx64,
          consumerId, req.epoch, pHandle->subKey, vgId, buf, req.reqId);

wmmhello's avatar
wmmhello 已提交
630
  code = tqExtractDataForMq(pTq, pHandle, &req, pMsg);
631
  tqSetHandleIdle(pHandle);
632

633
  tqDebug("tmq poll: consumer:0x%" PRIx64 " vgId:%d, topic:%s, set handle idle, pHandle:%p", consumerId, vgId,
dengyihao's avatar
dengyihao 已提交
634
          req.subKey, pHandle);
635
  return code;
D
dapan1121 已提交
636 637
}

638 639 640 641 642 643 644 645 646
int32_t tqProcessVgCommittedInfoReq(STQ* pTq, SRpcMsg* pMsg) {
  void* data = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t len = pMsg->contLen - sizeof(SMsgHead);

  SMqVgOffset vgOffset = {0};

  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)data, len);
  if (tDecodeMqVgOffset(&decoder, &vgOffset) < 0) {
wmmhello's avatar
wmmhello 已提交
647 648
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
649 650 651 652 653 654 655
  }

  tDecoderClear(&decoder);

  STqOffset* pOffset = &vgOffset.offset;
  STqOffset* pSavedOffset = tqOffsetRead(pTq->pOffsetStore, pOffset->subKey);
  if (pSavedOffset == NULL) {
wmmhello's avatar
wmmhello 已提交
656 657
    terrno = TSDB_CODE_TMQ_NO_COMMITTED;
    return terrno;
658 659 660 661 662 663
  }
  vgOffset.offset = *pSavedOffset;

  int32_t code = 0;
  tEncodeSize(tEncodeMqVgOffset, &vgOffset, len, code);
  if (code < 0) {
wmmhello's avatar
wmmhello 已提交
664 665
    terrno = TSDB_CODE_INVALID_PARA;
    return terrno;
666 667
  }

668
  void* buf = rpcMallocCont(len);
669
  if (buf == NULL) {
wmmhello's avatar
wmmhello 已提交
670 671
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
672 673 674 675 676 677 678 679 680 681 682 683 684
  }
  SEncoder encoder;
  tEncoderInit(&encoder, buf, len);
  tEncodeMqVgOffset(&encoder, &vgOffset);
  tEncoderClear(&encoder);

  SRpcMsg rsp = {.info = pMsg->info, .pCont = buf, .contLen = len, .code = 0};

  tmsgSendRsp(&rsp);

  return 0;
}

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
int32_t tqProcessVgWalInfoReq(STQ* pTq, SRpcMsg* pMsg) {
  SMqPollReq req = {0};
  if (tDeserializeSMqPollReq(pMsg->pCont, pMsg->contLen, &req) < 0) {
    tqError("tDeserializeSMqPollReq %d failed", pMsg->contLen);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  int64_t      consumerId = req.consumerId;
  STqOffsetVal reqOffset = req.reqOffset;
  int32_t      vgId = TD_VID(pTq->pVnode);

  // 1. find handle
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
  if (pHandle == NULL) {
    tqError("consumer:0x%" PRIx64 " vgId:%d subkey:%s not found", consumerId, vgId, req.subKey);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  // 2. check re-balance status
  taosRLockLatch(&pTq->lock);
  if (pHandle->consumerId != consumerId) {
    tqDebug("ERROR consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
            consumerId, vgId, req.subKey, pHandle->consumerId);
    terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
    taosRUnLockLatch(&pTq->lock);
    return -1;
  }
  taosRUnLockLatch(&pTq->lock);

  int64_t sver = 0, ever = 0;
  walReaderValidVersionRange(pHandle->execHandle.pTqReader->pWalReader, &sver, &ever);

  SMqDataRsp dataRsp = {0};
720
  tqInitDataRsp(&dataRsp, req.reqOffset);
721

wmmhello's avatar
wmmhello 已提交
722 723 724 725 726 727
  if (req.useSnapshot == true) {
    tqError("consumer:0x%" PRIx64 " vgId:%d subkey:%s snapshot not support wal info", consumerId, vgId, req.subKey);
    terrno = TSDB_CODE_INVALID_PARA;
    tDeleteMqDataRsp(&dataRsp);
    return -1;
  }
728

wmmhello's avatar
wmmhello 已提交
729
  dataRsp.rspOffset.type = TMQ_OFFSET__LOG;
730

wmmhello's avatar
wmmhello 已提交
731 732
  if (reqOffset.type == TMQ_OFFSET__LOG) {
    dataRsp.rspOffset.version = reqOffset.version;
733 734 735 736 737 738 739 740 741
  } else if(reqOffset.type < 0){
    STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, req.subKey);
    if (pOffset != NULL) {
      if (pOffset->val.type != TMQ_OFFSET__LOG) {
        tqError("consumer:0x%" PRIx64 " vgId:%d subkey:%s, no valid wal info", consumerId, vgId, req.subKey);
        terrno = TSDB_CODE_INVALID_PARA;
        tDeleteMqDataRsp(&dataRsp);
        return -1;
      }
742

743 744 745 746 747 748 749
      dataRsp.rspOffset.version = pOffset->val.version;
      tqInfo("consumer:0x%" PRIx64 " vgId:%d subkey:%s get assignment from store:%"PRId64, consumerId, vgId, req.subKey, dataRsp.rspOffset.version);
    }else{
      if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEST) {
        dataRsp.rspOffset.version = sver;  // not consume yet, set the earliest position
      } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
        dataRsp.rspOffset.version = ever;
750
      }
751
      tqInfo("consumer:0x%" PRIx64 " vgId:%d subkey:%s get assignment from init:%"PRId64, consumerId, vgId, req.subKey, dataRsp.rspOffset.version);
752
    }
wmmhello's avatar
wmmhello 已提交
753 754 755 756 757 758
  } else {
    tqError("consumer:0x%" PRIx64 " vgId:%d subkey:%s invalid offset type:%d", consumerId, vgId, req.subKey,
            reqOffset.type);
    terrno = TSDB_CODE_INVALID_PARA;
    tDeleteMqDataRsp(&dataRsp);
    return -1;
759 760 761
  }

  tqDoSendDataRsp(&pMsg->info, &dataRsp, req.epoch, req.consumerId, TMQ_MSG_TYPE__WALINFO_RSP, sver, ever);
wmmhello's avatar
wmmhello 已提交
762
  tDeleteMqDataRsp(&dataRsp);
763 764 765
  return 0;
}

766
int32_t tqProcessDeleteSubReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
767
  SMqVDeleteReq* pReq = (SMqVDeleteReq*)msg;
dengyihao's avatar
dengyihao 已提交
768
  int32_t        vgId = TD_VID(pTq->pVnode);
L
Liu Jicong 已提交
769

770
  tqInfo("vgId:%d, tq process delete sub req %s", vgId, pReq->subKey);
wmmhello's avatar
wmmhello 已提交
771
  int32_t code = 0;
L
Liu Jicong 已提交
772

wmmhello's avatar
wmmhello 已提交
773
  taosWLockLatch(&pTq->lock);
L
Liu Jicong 已提交
774 775
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
wmmhello's avatar
wmmhello 已提交
776
    while (tqIsHandleExec(pHandle)) {
dengyihao's avatar
dengyihao 已提交
777 778
      tqDebug("vgId:%d, topic:%s, subscription is executing, wait for 10ms and retry, pHandle:%p", vgId,
              pHandle->subKey, pHandle);
wmmhello's avatar
wmmhello 已提交
779
      taosMsleep(10);
780
    }
781

L
Liu Jicong 已提交
782 783 784
    if (pHandle->pRef) {
      walCloseRef(pTq->pVnode->pWal, pHandle->pRef->refId);
    }
785

L
Liu Jicong 已提交
786 787 788 789
    code = taosHashRemove(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
    if (code != 0) {
      tqError("cannot process tq delete req %s, since no such handle", pReq->subKey);
    }
L
Liu Jicong 已提交
790
  }
791

L
Liu Jicong 已提交
792 793
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
794
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
795
  }
L
Liu Jicong 已提交
796

L
Liu Jicong 已提交
797
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
798
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
799
  }
wmmhello's avatar
wmmhello 已提交
800 801
  taosWUnLockLatch(&pTq->lock);

L
Liu Jicong 已提交
802
  return 0;
L
Liu Jicong 已提交
803 804
}

805
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
806 807
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
808
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
809
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
810 811 812 813
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
814 815 816 817 818
  if (taosHashPut(pTq->pCheckInfo, info.topic, strlen(info.topic), &info, sizeof(STqCheckInfo)) < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  if (tqMetaSaveCheckInfo(pTq, info.topic, msg, msgLen) < 0) {
L
Liu Jicong 已提交
819 820 821 822 823 824
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

825
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
826 827 828 829 830 831 832 833 834 835 836
  if (taosHashRemove(pTq->pCheckInfo, msg, strlen(msg)) < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  if (tqMetaDeleteCheckInfo(pTq, msg) < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

837
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
dengyihao's avatar
dengyihao 已提交
838
  int         ret = 0;
L
Liu Jicong 已提交
839
  SMqRebVgReq req = {0};
dengyihao's avatar
dengyihao 已提交
840
  SDecoder    dc = {0};
841 842 843 844 845 846 847 848 849

  tDecoderInit(&dc, msg, msgLen);

  // decode req
  if (tDecodeSMqRebVgReq(&dc, &req) < 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    tDecoderClear(&dc);
    return -1;
  }
L
Liu Jicong 已提交
850

851
  tqInfo("vgId:%d, tq process sub req:%s, Id:0x%" PRIx64 " -> Id:0x%" PRIx64, pTq->pVnode->config.vgId, req.subKey,
D
dapan1121 已提交
852
          req.oldConsumerId, req.newConsumerId);
L
Liu Jicong 已提交
853

854 855 856 857 858 859 860 861
  STqHandle* pHandle = NULL;
  while(1){
    pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
    if (pHandle || tqMetaGetHandle(pTq, req.subKey) < 0){
      break;
    }
  }

L
Liu Jicong 已提交
862
  if (pHandle == NULL) {
L
Liu Jicong 已提交
863
    if (req.oldConsumerId != -1) {
864
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId:0x%" PRIx64,
865
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
866
    }
L
Liu Jicong 已提交
867
    if (req.newConsumerId == -1) {
868
      tqError("vgId:%d, tq invalid re-balance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
869
      goto end;
L
Liu Jicong 已提交
870
    }
871 872 873 874
    STqHandle handle = {0};
    ret = tqCreateHandle(pTq, &req, &handle);
    if(ret < 0){
      tqDestroyTqHandle(&handle);
875
      goto end;
876
    }
877
    ret = tqMetaSaveHandle(pTq, req.subKey, &handle);
L
Liu Jicong 已提交
878
  } else {
879
    taosWLockLatch(&pTq->lock);
wmmhello's avatar
wmmhello 已提交
880

D
dapan1121 已提交
881
    if (pHandle->consumerId == req.newConsumerId) {  // do nothing
wmmhello's avatar
wmmhello 已提交
882
      tqInfo("vgId:%d no switch consumer:0x%" PRIx64 " remains, because redo wal log", req.vgId, req.newConsumerId);
883
    } else {
wmmhello's avatar
wmmhello 已提交
884
      tqInfo("vgId:%d switch consumer from Id:0x%" PRIx64 " to Id:0x%" PRIx64, req.vgId, pHandle->consumerId, req.newConsumerId);
885
      atomic_store_64(&pHandle->consumerId, req.newConsumerId);
wmmhello's avatar
wmmhello 已提交
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
      //    atomic_add_fetch_32(&pHandle->epoch, 1);

      // kill executing task
      //    if(tqIsHandleExec(pHandle)) {
      //      qTaskInfo_t pTaskInfo = pHandle->execHandle.task;
      //      if (pTaskInfo != NULL) {
      //        qKillTask(pTaskInfo, TSDB_CODE_SUCCESS);
      //      }

      //      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
      //        qStreamCloseTsdbReader(pTaskInfo);
      //      }
      //    }
      // remove if it has been register in the push manager, and return one empty block to consumer
      tqUnregisterPushHandle(pTq, pHandle);
      ret = tqMetaSaveHandle(pTq, req.subKey, pHandle);
902
    }
903
    taosWUnLockLatch(&pTq->lock);
L
Liu Jicong 已提交
904
  }
L
Liu Jicong 已提交
905

906
end:
907
  tDecoderClear(&dc);
908
  return ret;
L
Liu Jicong 已提交
909
}
910

dengyihao's avatar
dengyihao 已提交
911
void freePtr(void* ptr) { taosMemoryFree(*(void**)ptr); }
L
liuyao 已提交
912

913
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
D
dapan1121 已提交
914
  int32_t vgId = TD_VID(pTq->pVnode);
915

916
  pTask->id.idStr = createStreamTaskIdStr(pTask->id.streamId, pTask->id.taskId);
L
Liu Jicong 已提交
917
  pTask->refCnt = 1;
918
  pTask->status.schedStatus = TASK_SCHED_STATUS__INACTIVE;
dengyihao's avatar
dengyihao 已提交
919
  pTask->inputQueue = streamQueueOpen(512 << 10);
920
  pTask->outputInfo.queue = streamQueueOpen(512 << 10);
L
Liu Jicong 已提交
921

922
  if (pTask->inputQueue == NULL || pTask->outputInfo.queue == NULL) {
H
Haojun Liao 已提交
923
    tqError("s-task:%s failed to prepare the input/output queue, initialize task failed", pTask->id.idStr);
L
Liu Jicong 已提交
924
    return -1;
L
Liu Jicong 已提交
925 926
  }

H
Haojun Liao 已提交
927
  pTask->tsInfo.init = taosGetTimestampMs();
L
Liu Jicong 已提交
928
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
929
  pTask->outputInfo.status = TASK_OUTPUT_STATUS__NORMAL;
930
  pTask->pMsgCb = &pTq->pVnode->msgCb;
931
  pTask->pMeta = pTq->pStreamMeta;
932

933 934
  streamTaskOpenAllUpstreamInput(pTask);

935
  // backup the initial status, and set it to be TASK_STATUS__INIT
936
  pTask->chkInfo.version = ver;
937
  pTask->chkInfo.currentVer = ver;
938

939 940
  pTask->dataRange.range.maxVer = ver;
  pTask->dataRange.range.minVer = ver;
941

942
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
L
liuyao 已提交
943
    SStreamTask* pSateTask = pTask;
L
liuyao 已提交
944
    SStreamTask task = {0};
L
liuyao 已提交
945
    if (pTask->info.fillHistory) {
L
liuyao 已提交
946 947 948
      task.id = pTask->streamTaskId;
      task.pMeta = pTask->pMeta;
      pSateTask = &task;
L
liuyao 已提交
949
    }
950

L
liuyao 已提交
951
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pSateTask, false, -1, -1);
952 953 954 955
    if (pTask->pState == NULL) {
      return -1;
    }

L
liuyao 已提交
956 957 958 959 960
    SReadHandle handle = {.vnode = pTq->pVnode,
                          .initTqReader = 1,
                          .pStateBackend = pTask->pState,
                          .fillHistory = pTask->info.fillHistory,
                          .winRange = pTask->dataRange.window};
961
    initStorageAPI(&handle.api);
962

963
    pTask->exec.pExecutor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle, vgId, pTask->id.taskId);
964
    if (pTask->exec.pExecutor == NULL) {
L
Liu Jicong 已提交
965 966
      return -1;
    }
967

968
    qSetTaskId(pTask->exec.pExecutor, pTask->id.taskId, pTask->id.streamId);
969
  } else if (pTask->info.taskLevel == TASK_LEVEL__AGG) {
L
liuyao 已提交
970
    SStreamTask* pSateTask = pTask;
L
liuyao 已提交
971
    SStreamTask task = {0};
L
liuyao 已提交
972
    if (pTask->info.fillHistory) {
L
liuyao 已提交
973 974 975
      task.id = pTask->streamTaskId;
      task.pMeta = pTask->pMeta;
      pSateTask = &task;
L
liuyao 已提交
976
    }
L
liuyao 已提交
977
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pSateTask, false, -1, -1);
978 979 980
    if (pTask->pState == NULL) {
      return -1;
    }
981

982
    int32_t     numOfVgroups = (int32_t)taosArrayGetSize(pTask->pUpstreamEpInfoList);
L
liuyao 已提交
983 984 985 986 987
    SReadHandle handle = {.vnode = NULL,
                          .numOfVgroups = numOfVgroups,
                          .pStateBackend = pTask->pState,
                          .fillHistory = pTask->info.fillHistory,
                          .winRange = pTask->dataRange.window};
988
    initStorageAPI(&handle.api);
989

990
    pTask->exec.pExecutor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle, vgId, pTask->id.taskId);
991
    if (pTask->exec.pExecutor == NULL) {
L
Liu Jicong 已提交
992 993
      return -1;
    }
994
    qSetTaskId(pTask->exec.pExecutor, pTask->id.taskId, pTask->id.streamId);
L
Liu Jicong 已提交
995
  }
L
Liu Jicong 已提交
996 997

  // sink
998
  if (pTask->outputInfo.type == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
999
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
1000
    pTask->smaSink.smaSink = smaHandleRes;
1001
  } else if (pTask->outputInfo.type == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
1002
    pTask->tbSink.vnode = pTq->pVnode;
H
Haojun Liao 已提交
1003
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline;
L
Liu Jicong 已提交
1004

X
Xiaoyu Wang 已提交
1005
    int32_t   ver1 = 1;
5
54liuyao 已提交
1006
    SMetaInfo info = {0};
dengyihao's avatar
dengyihao 已提交
1007
    int32_t   code = metaGetInfo(pTq->pVnode->pMeta, pTask->tbSink.stbUid, &info, NULL);
5
54liuyao 已提交
1008
    if (code == TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
1009
      ver1 = info.skmVer;
5
54liuyao 已提交
1010
    }
L
Liu Jicong 已提交
1011

1012 1013
    SSchemaWrapper* pschemaWrapper = pTask->tbSink.pSchemaWrapper;
    pTask->tbSink.pTSchema = tBuildTSchema(pschemaWrapper->pSchema, pschemaWrapper->nCols, ver1);
1014
    if (pTask->tbSink.pTSchema == NULL) {
D
dapan1121 已提交
1015 1016
      return -1;
    }
L
liuyao 已提交
1017 1018
    pTask->tbSink.pTblInfo = tSimpleHashInit(10240, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT));
    tSimpleHashSetFreeFp(pTask->tbSink.pTblInfo, freePtr);
L
Liu Jicong 已提交
1019
  }
1020

1021
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
1022
    SWalFilterCond cond = {.deleteMsg = 1};  // delete msg also extract from wal files
1023
    pTask->exec.pWalReader = walOpenReader(pTq->pVnode->pWal, &cond);
1024 1025
  }

1026 1027 1028 1029 1030 1031
  // reset the task status from unfinished transaction
  if (pTask->status.taskStatus == TASK_STATUS__PAUSE) {
    tqWarn("s-task:%s reset task status to be normal, kept in meta status: Paused", pTask->id.idStr);
    pTask->status.taskStatus = TASK_STATUS__NORMAL;
  }

H
Haojun Liao 已提交
1032
  taosThreadMutexInit(&pTask->lock, NULL);
1033
  streamSetupScheduleTrigger(pTask);
1034

1035
  tqInfo("vgId:%d expand stream task, s-task:%s, checkpoint ver:%" PRId64
1036
         " child id:%d, level:%d, fill-history:%d, trigger:%" PRId64 " ms, disable pause",
1037
         vgId, pTask->id.idStr, pTask->chkInfo.version, pTask->info.selfChildId, pTask->info.taskLevel,
1038
         pTask->info.fillHistory, pTask->triggerParam);
1039 1040 1041

  // next valid version will add one
  pTask->chkInfo.version += 1;
L
Liu Jicong 已提交
1042
  return 0;
L
Liu Jicong 已提交
1043
}
L
Liu Jicong 已提交
1044

1045
int32_t tqProcessStreamTaskCheckReq(STQ* pTq, SRpcMsg* pMsg) {
1046 1047 1048 1049
  char*   msgStr = pMsg->pCont;
  char*   msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);

1050 1051
  SStreamTaskCheckReq req;
  SDecoder            decoder;
1052

X
Xiaoyu Wang 已提交
1053
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1054
  tDecodeStreamTaskCheckReq(&decoder, &req);
1055
  tDecoderClear(&decoder);
1056

1057 1058
  int32_t taskId = req.downstreamTaskId;

1059 1060 1061 1062 1063 1064 1065 1066 1067
  SStreamTaskCheckRsp rsp = {
      .reqId = req.reqId,
      .streamId = req.streamId,
      .childId = req.childId,
      .downstreamNodeId = req.downstreamNodeId,
      .downstreamTaskId = req.downstreamTaskId,
      .upstreamNodeId = req.upstreamNodeId,
      .upstreamTaskId = req.upstreamTaskId,
  };
1068

1069
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.streamId, taskId);
1070
  if (pTask != NULL) {
1071
    rsp.status = streamTaskCheckStatus(pTask);
1072 1073
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);

1074 1075 1076
    const char* pStatus = streamGetTaskStatusStr(pTask->status.taskStatus);
    tqDebug("s-task:%s status:%s, recv task check req(reqId:0x%" PRIx64 ") task:0x%x (vgId:%d), ready:%d",
            pTask->id.idStr, pStatus, rsp.reqId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status);
1077 1078
  } else {
    rsp.status = 0;
H
Haojun Liao 已提交
1079 1080 1081
    tqDebug("tq recv task check(taskId:0x%" PRIx64 "-0x%x not built yet) req(reqId:0x%" PRIx64
            ") from task:0x%x (vgId:%d), rsp status %d",
            req.streamId, taskId, rsp.reqId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status);
1082 1083
  }

1084
  return streamSendCheckRsp(pTq->pStreamMeta, &req, &rsp, &pMsg->info, taskId);
1085 1086
}

1087 1088 1089 1090
int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, SRpcMsg* pMsg) {
  char* pReq = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t len = pMsg->contLen - sizeof(SMsgHead);

1091 1092 1093 1094
  int32_t             code;
  SStreamTaskCheckRsp rsp;

  SDecoder decoder;
1095
  tDecoderInit(&decoder, (uint8_t*)pReq, len);
1096
  code = tDecodeStreamTaskCheckRsp(&decoder, &rsp);
1097

1098 1099 1100 1101 1102
  if (code < 0) {
    tDecoderClear(&decoder);
    return -1;
  }

1103
  tDecoderClear(&decoder);
1104 1105
  tqDebug("tq task:0x%x (vgId:%d) recv check rsp(reqId:0x%" PRIx64 ") from 0x%x (vgId:%d) status %d",
          rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.status);
1106

1107
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.streamId, rsp.upstreamTaskId);
1108
  if (pTask == NULL) {
1109
    tqError("tq failed to locate the stream task:0x%x (vgId:%d), it may have been destroyed", rsp.upstreamTaskId,
1110
            pTq->pStreamMeta->vgId);
1111
    terrno = TSDB_CODE_STREAM_TASK_NOT_EXIST;
1112 1113 1114
    return -1;
  }

1115
  code = streamProcessCheckRsp(pTask, &rsp);
L
Liu Jicong 已提交
1116 1117
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1118 1119
}

1120
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1121 1122 1123
  int32_t code = 0;
  int32_t vgId = TD_VID(pTq->pVnode);

5
54liuyao 已提交
1124 1125 1126
  if (tsDisableStream) {
    return 0;
  }
1127 1128 1129 1130

  // 1.deserialize msg and build task
  SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask));
  if (pTask == NULL) {
1131
    terrno = TSDB_CODE_OUT_OF_MEMORY;
dengyihao's avatar
dengyihao 已提交
1132 1133
    tqError("vgId:%d failed to create stream task due to out of memory, alloc size:%d", vgId,
            (int32_t)sizeof(SStreamTask));
1134 1135
    return -1;
  }
1136

1137 1138
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
1139
  code = tDecodeStreamTask(&decoder, pTask);
1140 1141 1142 1143 1144
  if (code < 0) {
    tDecoderClear(&decoder);
    taosMemoryFree(pTask);
    return -1;
  }
1145

1146 1147
  tDecoderClear(&decoder);

1148 1149
  SStreamMeta* pStreamMeta = pTq->pStreamMeta;

1150
  // 2.save task, use the newest commit version as the initial start version of stream task.
1151 1152
  int32_t taskId = pTask->id.taskId;
  bool    added = false;
1153

1154 1155
  taosWLockLatch(&pStreamMeta->lock);
  code = streamMetaRegisterTask(pStreamMeta, sversion, pTask, &added);
1156
  int32_t numOfTasks = streamMetaGetNumOfTasks(pStreamMeta);
1157
  taosWUnLockLatch(&pStreamMeta->lock);
1158

1159
  if (code < 0) {
1160
    tqError("vgId:%d failed to add s-task:0x%x, total:%d", vgId, pTask->id.taskId, numOfTasks);
H
Haojun Liao 已提交
1161
    tFreeStreamTask(pTask);
1162 1163 1164
    return -1;
  }

1165
  // not added into meta store
1166 1167
  if (added) {
    tqDebug("vgId:%d s-task:0x%x is deployed and add into meta, numOfTasks:%d", vgId, taskId, numOfTasks);
1168
    SStreamTask* p = streamMetaAcquireTask(pStreamMeta, pTask->id.streamId, taskId);
1169 1170 1171 1172 1173
    if (p != NULL) {  // reset the downstreamReady flag.
      streamTaskCheckDownstreamTasks(p);
    }
    streamMetaReleaseTask(pStreamMeta, p);
  } else {
1174 1175
    tqWarn("vgId:%d failed to add s-task:0x%x, already exists in meta store", vgId, taskId);
    tFreeStreamTask(pTask);
1176 1177
  }

1178 1179 1180
  return 0;
}

1181
int32_t tqProcessTaskScanHistory(STQ* pTq, SRpcMsg* pMsg) {
1182
  SStreamScanHistoryReq* pReq = (SStreamScanHistoryReq*)pMsg->pCont;
1183
  SStreamMeta*           pMeta = pTq->pStreamMeta;
1184

1185
  int32_t      code = TSDB_CODE_SUCCESS;
1186
  SStreamTask* pTask = streamMetaAcquireTask(pMeta, pReq->streamId, pReq->taskId);
1187
  if (pTask == NULL) {
1188 1189
    tqError("vgId:%d failed to acquire stream task:0x%x during stream recover, task may have been destroyed",
            pMeta->vgId, pReq->taskId);
1190 1191 1192
    return -1;
  }

1193
  // do recovery step1
1194
  const char* id = pTask->id.idStr;
1195
  const char* pStatus = streamGetTaskStatusStr(pTask->status.taskStatus);
1196
  tqDebug("s-task:%s start scan-history stage(step 1), status:%s", id, pStatus);
1197

1198
  if (pTask->tsInfo.step1Start == 0) {
1199
    ASSERT(pTask->status.pauseAllowed == false);
1200
    pTask->tsInfo.step1Start = taosGetTimestampMs();
1201 1202 1203 1204 1205
    if (pTask->info.fillHistory == 1) {
      streamTaskEnablePause(pTask);
    }
  } else {
    tqDebug("s-task:%s resume from paused, start ts:%"PRId64, pTask->id.idStr, pTask->tsInfo.step1Start);
1206
  }
1207

1208
  // we have to continue retrying to successfully execute the scan history task.
1209 1210 1211 1212 1213 1214 1215 1216
  int8_t schedStatus = atomic_val_compare_exchange_8(&pTask->status.schedStatus, TASK_SCHED_STATUS__INACTIVE,
                                                     TASK_SCHED_STATUS__WAITING);
  if (schedStatus != TASK_SCHED_STATUS__INACTIVE) {
    tqError(
        "s-task:%s failed to start scan-history in first stream time window since already started, unexpected "
        "sched-status:%d",
        id, schedStatus);
    return 0;
1217
  }
1218

1219
  if (pTask->info.fillHistory == 1) {
1220
    ASSERT(pTask->status.pauseAllowed == true);
1221 1222
  }

1223 1224
  streamSourceScanHistoryData(pTask);
  if (pTask->status.taskStatus == TASK_STATUS__PAUSE) {
1225
    double el = (taosGetTimestampMs() - pTask->tsInfo.step1Start) / 1000.0;
1226 1227
    tqDebug("s-task:%s is paused in the step1, elapsed time:%.2fs, sched-status:%d", pTask->id.idStr, el,
            TASK_SCHED_STATUS__INACTIVE);
L
liuyao 已提交
1228
    atomic_store_8(&pTask->status.schedStatus, TASK_SCHED_STATUS__INACTIVE);
L
Liu Jicong 已提交
1229 1230 1231
    return 0;
  }

1232 1233
  // the following procedure should be executed, no matter status is stop/pause or not
  double el = (taosGetTimestampMs() - pTask->tsInfo.step1Start) / 1000.0;
H
Haojun Liao 已提交
1234
  tqDebug("s-task:%s scan-history stage(step 1) ended, elapsed time:%.2fs", id, el);
H
Haojun Liao 已提交
1235

H
Haojun Liao 已提交
1236
  if (pTask->info.fillHistory) {
L
liuyao 已提交
1237
    SVersionRange* pRange = NULL;
1238
    SStreamTask*   pStreamTask = NULL;
1239
    bool           done = false;
1240

1241
    // 1. get the related stream task
1242
    pStreamTask = streamMetaAcquireTask(pMeta, pTask->streamTaskId.streamId, pTask->streamTaskId.taskId);
1243 1244 1245 1246
    if (pStreamTask == NULL) {
      // todo delete this task, if the related stream task is dropped
      qError("failed to find s-task:0x%x, it may have been destroyed, drop fill-history task:%s",
             pTask->streamTaskId.taskId, pTask->id.idStr);
1247

1248
      tqDebug("s-task:%s fill-history task set status to be dropping", id);
1249

H
Haojun Liao 已提交
1250
      streamMetaUnregisterTask(pMeta, pTask->id.streamId, pTask->id.taskId);
1251 1252 1253
      streamMetaReleaseTask(pMeta, pTask);
      return -1;
    }
L
Liu Jicong 已提交
1254

1255
    ASSERT(pStreamTask->info.taskLevel == TASK_LEVEL__SOURCE);
L
Liu Jicong 已提交
1256

1257 1258
    // 2. it cannot be paused, when the stream task in TASK_STATUS__SCAN_HISTORY status. Let's wait for the
    // stream task get ready for scan history data
1259 1260 1261 1262 1263 1264
    while (pStreamTask->status.taskStatus == TASK_STATUS__SCAN_HISTORY) {
      tqDebug(
          "s-task:%s level:%d related stream task:%s(status:%s) not ready for halt, wait for it and recheck in 100ms",
          id, pTask->info.taskLevel, pStreamTask->id.idStr, streamGetTaskStatusStr(pStreamTask->status.taskStatus));
      taosMsleep(100);
    }
1265

1266 1267
    // now we can stop the stream task execution
    streamTaskHalt(pStreamTask);
1268

1269 1270
    tqDebug("s-task:%s level:%d sched-status:%d is halt by fill-history task:%s", pStreamTask->id.idStr,
            pStreamTask->info.taskLevel, pStreamTask->status.schedStatus, id);
H
Haojun Liao 已提交
1271

1272 1273 1274 1275
    // if it's an source task, extract the last version in wal.
    pRange = &pTask->dataRange.range;
    int64_t latestVer = walReaderGetCurrentVer(pStreamTask->exec.pWalReader);
    done = streamHistoryTaskSetVerRangeStep2(pTask, latestVer);
1276

1277
    if (done) {
H
Haojun Liao 已提交
1278
      pTask->tsInfo.step2Start = taosGetTimestampMs();
1279 1280
      qDebug("s-task:%s scan-history from WAL stage(step 2) ended, elapsed time:%.2fs", id, 0.0);
      appendTranstateIntoInputQ(pTask);
1281
      streamTryExec(pTask);  // exec directly
1282
    } else {
1283 1284 1285 1286 1287 1288
      STimeWindow* pWindow = &pTask->dataRange.window;
      tqDebug("s-task:%s level:%d verRange:%" PRId64 " - %" PRId64 " window:%" PRId64 "-%" PRId64
              ", do secondary scan-history from WAL after halt the related stream task:%s",
              id, pTask->info.taskLevel, pRange->minVer, pRange->maxVer, pWindow->skey, pWindow->ekey,
              pStreamTask->id.idStr);
      ASSERT(pTask->status.schedStatus == TASK_SCHED_STATUS__WAITING);
1289

1290 1291
      pTask->tsInfo.step2Start = taosGetTimestampMs();
      streamSetParamForStreamScannerStep2(pTask, pRange, pWindow);
H
Haojun Liao 已提交
1292

1293
      int64_t dstVer = pTask->dataRange.range.minVer - 1;
H
Haojun Liao 已提交
1294

1295 1296 1297 1298
      pTask->chkInfo.currentVer = dstVer;
      walReaderSetSkipToVersion(pTask->exec.pWalReader, dstVer);
      tqDebug("s-task:%s wal reader start scan WAL verRange:%" PRId64 "-%" PRId64 ", set sched-status:%d", id, dstVer,
              pTask->dataRange.range.maxVer, TASK_SCHED_STATUS__INACTIVE);
H
Haojun Liao 已提交
1299

1300 1301
      atomic_store_8(&pTask->status.schedStatus, TASK_SCHED_STATUS__INACTIVE);

1302 1303 1304 1305 1306
      // set the fill-history task to be normal
      if (pTask->info.fillHistory == 1) {
        streamSetStatusNormal(pTask);
      }

1307 1308
      tqStartStreamTasks(pTq);
    }
1309 1310 1311

    streamMetaReleaseTask(pMeta, pTask);
    streamMetaReleaseTask(pMeta, pStreamTask);
1312 1313 1314 1315
  } else {
    // todo update the chkInfo version for current task.
    // this task has an associated history stream task, so we need to scan wal from the end version of
    // history scan. The current version of chkInfo.current is not updated during the history scan
1316 1317
    STimeWindow* pWindow = &pTask->dataRange.window;

1318
    if (pTask->historyTaskId.taskId == 0) {
1319
      *pWindow = (STimeWindow){INT64_MIN, INT64_MAX};
1320
      tqDebug(
1321
          "s-task:%s scan-history in stream time window completed, no related fill-history task, reset the time "
1322 1323
          "window:%" PRId64 " - %" PRId64,
          id, pWindow->skey, pWindow->ekey);
1324
      qStreamInfoResetTimewindowFilter(pTask->exec.pExecutor);
1325
    } else {
H
Haojun Liao 已提交
1326 1327
      // when related fill-history task exists, update the fill-history time window only when the
      // state transfer is completed.
1328
      tqDebug(
1329
          "s-task:%s scan-history in stream time window completed, now start to handle data from WAL, start "
1330
          "ver:%" PRId64 ", window:%" PRId64 " - %" PRId64,
1331
          id, pTask->chkInfo.currentVer, pWindow->skey, pWindow->ekey);
1332
    }
1333

1334
    // notify the downstream agg tasks that upstream tasks are ready to processing the WAL data, update the
1335 1336
    code = streamTaskScanHistoryDataComplete(pTask);
    streamMetaReleaseTask(pMeta, pTask);
1337

1338 1339
    // when all source task complete to scan history data in stream time window, they are allowed to handle stream data
    // at the same time.
1340 1341
    return code;
  }
1342 1343 1344 1345

  return 0;
}

1346
int32_t tqProcessTaskScanHistoryFinishReq(STQ* pTq, SRpcMsg* pMsg) {
L
Liu Jicong 已提交
1347 1348
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1349 1350

  // deserialize
1351
  SStreamScanHistoryFinishReq req = {0};
1352 1353

  SDecoder decoder;
X
Xiaoyu Wang 已提交
1354
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
1355
  tDecodeStreamScanHistoryFinishReq(&decoder, &req);
1356 1357
  tDecoderClear(&decoder);

1358
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.streamId, req.downstreamTaskId);
1359
  if (pTask == NULL) {
1360 1361
    tqError("vgId:%d process scan history finish msg, failed to find task:0x%x, it may be destroyed",
            pTq->pStreamMeta->vgId, req.downstreamTaskId);
1362 1363 1364
    return -1;
  }

1365 1366 1367
  tqDebug("s-task:%s receive scan-history finish msg from task:0x%x", pTask->id.idStr, req.upstreamTaskId);

  int32_t code = streamProcessScanHistoryFinishReq(pTask, &req, &pMsg->info);
L
Liu Jicong 已提交
1368
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1369
  return code;
L
Liu Jicong 已提交
1370
}
L
Liu Jicong 已提交
1371

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
int32_t tqProcessTaskScanHistoryFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);

  // deserialize
  SStreamCompleteHistoryMsg req = {0};

  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
  tDecodeCompleteHistoryDataMsg(&decoder, &req);
  tDecoderClear(&decoder);

1384
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.streamId, req.upstreamTaskId);
1385 1386 1387 1388 1389 1390 1391 1392
  if (pTask == NULL) {
    tqError("vgId:%d process scan history finish rsp, failed to find task:0x%x, it may be destroyed",
            pTq->pStreamMeta->vgId, req.upstreamTaskId);
    return -1;
  }

  int32_t remain = atomic_sub_fetch_32(&pTask->notReadyTasks, 1);
  if (remain > 0) {
1393 1394
    tqDebug("s-task:%s scan-history finish rsp received from downstream task:0x%x, remain:%d not send finish rsp",
            pTask->id.idStr, req.downstreamId, remain);
1395
  } else {
1396 1397
    tqDebug(
        "s-task:%s scan-history finish rsp received from downstream task:0x%x, all downstream tasks rsp scan-history "
H
Haojun Liao 已提交
1398
        "completed msg", pTask->id.idStr, req.downstreamId);
1399 1400 1401 1402
    streamProcessScanHistoryFinishRsp(pTask);
  }

  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1403 1404 1405
  return 0;
}

1406 1407 1408 1409
int32_t extractDelDataBlock(const void* pData, int32_t len, int64_t ver, SStreamRefDataBlock** pRefBlock) {
  SDecoder*   pCoder = &(SDecoder){0};
  SDeleteRes* pRes = &(SDeleteRes){0};

H
Haojun Liao 已提交
1410
  (*pRefBlock) = NULL;
H
Haojun Liao 已提交
1411

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
  pRes->uidList = taosArrayInit(0, sizeof(tb_uid_t));
  if (pRes->uidList == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  tDecoderInit(pCoder, (uint8_t*)pData, len);
  tDecodeDeleteRes(pCoder, pRes);
  tDecoderClear(pCoder);

  int32_t numOfTables = taosArrayGetSize(pRes->uidList);
  if (numOfTables == 0 || pRes->affectedRows == 0) {
    taosArrayDestroy(pRes->uidList);
    return TSDB_CODE_SUCCESS;
  }

  SSDataBlock* pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
  blockDataEnsureCapacity(pDelBlock, numOfTables);
  pDelBlock->info.rows = numOfTables;
  pDelBlock->info.version = ver;

  for (int32_t i = 0; i < numOfTables; i++) {
    // start key column
    SColumnInfoData* pStartCol = taosArrayGet(pDelBlock->pDataBlock, START_TS_COLUMN_INDEX);
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
    colDataSetVal(pUidCol, i, (const char*)pUid, false);

    colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, GROUPID_COLUMN_INDEX), i);
    colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), i);
    colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), i);
  }

  taosArrayDestroy(pRes->uidList);
  *pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
H
Haojun Liao 已提交
1450
  if ((*pRefBlock) == NULL) {
1451 1452 1453 1454 1455 1456 1457 1458
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  (*pRefBlock)->type = STREAM_INPUT__REF_DATA_BLOCK;
  (*pRefBlock)->pBlock = pDelBlock;
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1459 1460
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
1461 1462 1463 1464

  int32_t taskId = pReq->taskId;
  int32_t vgId = TD_VID(pTq->pVnode);

1465 1466 1467 1468 1469 1470
  if (taskId == STREAM_TASK_STATUS_CHECK_ID) {
    tqStreamTasksStatusCheck(pTq);
    return 0;
  }

  if (taskId == EXTRACT_DATA_FROM_WAL_ID) {  // all tasks are extracted submit data from the wal
1471
    tqStreamTasksScanWal(pTq);
L
Liu Jicong 已提交
1472
    return 0;
1473
  }
1474

1475
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->streamId, taskId);
1476
  if (pTask != NULL) {
1477
    // even in halt status, the data in inputQ must be processed
H
Haojun Liao 已提交
1478
    int8_t st = pTask->status.taskStatus;
1479
    if (st == TASK_STATUS__NORMAL || st == TASK_STATUS__SCAN_HISTORY) {
1480
      tqDebug("vgId:%d s-task:%s start to process block from inputQ, last chk point:%" PRId64, vgId, pTask->id.idStr,
dengyihao's avatar
dengyihao 已提交
1481
              pTask->chkInfo.version);
1482
      streamProcessRunReq(pTask);
1483
    } else {
1484
      atomic_store_8(&pTask->status.schedStatus, TASK_SCHED_STATUS__INACTIVE);
1485 1486
      tqDebug("vgId:%d s-task:%s ignore run req since not in ready state, status:%s, sched-status:%d", vgId,
              pTask->id.idStr, streamGetTaskStatusStr(pTask->status.taskStatus), pTask->status.schedStatus);
1487
    }
1488

L
Liu Jicong 已提交
1489
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1490
    tqStartStreamTasks(pTq);
L
Liu Jicong 已提交
1491
    return 0;
1492 1493 1494
  } else { // NOTE: pTask->status.schedStatus is not updated since it is not be handled by the run exec.
    // todo add one function to handle this
    tqError("vgId:%d failed to found s-task, taskId:0x%x may have been dropped", vgId, taskId);
1495
    return -1;
L
Liu Jicong 已提交
1496
  }
L
Liu Jicong 已提交
1497 1498
}

L
Liu Jicong 已提交
1499
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
dengyihao's avatar
dengyihao 已提交
1500 1501 1502
  char*   msgStr = pMsg->pCont;
  char*   msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1503 1504 1505 1506

  SStreamDispatchReq req = {0};

  SDecoder decoder;
L
Liu Jicong 已提交
1507
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1508
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1509

1510
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.streamId, req.taskId);
L
Liu Jicong 已提交
1511
  if (pTask) {
1512
    SRpcMsg rsp = {.info = pMsg->info, .code = 0};
1513
    streamProcessDispatchMsg(pTask, &req, &rsp, exec);
L
Liu Jicong 已提交
1514
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1515
    return 0;
1516
  } else {
L
liuyao 已提交
1517
    tDeleteStreamDispatchReq(&req);
1518
    return -1;
L
Liu Jicong 已提交
1519
  }
L
Liu Jicong 已提交
1520 1521
}

L
Liu Jicong 已提交
1522 1523
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1524

1525 1526 1527 1528 1529
  int32_t      vgId = pTq->pStreamMeta->vgId;
  int32_t      taskId = htonl(pRsp->upstreamTaskId);
  int64_t      streamId = htobe64(pRsp->streamId);
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, streamId, taskId);

L
Liu Jicong 已提交
1530
  if (pTask) {
1531
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1532
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1533
    return TSDB_CODE_SUCCESS;
1534
  } else {
1535
    tqDebug("vgId:%d failed to handle the dispatch rsp, since find task:0x%x failed", vgId, taskId);
1536
    return TSDB_CODE_INVALID_MSG;
L
Liu Jicong 已提交
1537
  }
L
Liu Jicong 已提交
1538
}
L
Liu Jicong 已提交
1539

1540
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1541
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1542
  tqDebug("vgId:%d receive msg to drop stream task:0x%x", TD_VID(pTq->pVnode), pReq->taskId);
1543
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->streamId, pReq->taskId);
1544 1545 1546 1547
  if (pTask == NULL) {
    tqError("vgId:%d failed to acquire s-task:0x%x when dropping it", pTq->pStreamMeta->vgId, pReq->taskId);
    return 0;
  }
1548

H
Haojun Liao 已提交
1549
  streamMetaUnregisterTask(pTq->pStreamMeta, pReq->streamId, pReq->taskId);
1550
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1551
  return 0;
L
Liu Jicong 已提交
1552
}
L
Liu Jicong 已提交
1553

5
54liuyao 已提交
1554 1555
int32_t tqProcessTaskPauseReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
  SVPauseStreamTaskReq* pReq = (SVPauseStreamTaskReq*)msg;
1556 1557

  SStreamMeta* pMeta = pTq->pStreamMeta;
1558
  SStreamTask* pTask = streamMetaAcquireTask(pMeta, pReq->streamId, pReq->taskId);
1559
  if (pTask == NULL) {
1560
    tqError("vgId:%d process pause req, failed to acquire task:0x%x, it may have been dropped already", pMeta->vgId,
1561
            pReq->taskId);
1562 1563
    // since task is in [STOP|DROPPING] state, it is safe to assume the pause is active
    return TSDB_CODE_SUCCESS;
1564 1565 1566
  }

  tqDebug("s-task:%s receive pause msg from mnode", pTask->id.idStr);
1567
  streamTaskPause(pTask);
1568 1569 1570

  SStreamTask* pHistoryTask = NULL;
  if (pTask->historyTaskId.taskId != 0) {
1571
    pHistoryTask = streamMetaAcquireTask(pMeta, pTask->historyTaskId.streamId, pTask->historyTaskId.taskId);
1572
    if (pHistoryTask == NULL) {
1573
      tqError("vgId:%d process pause req, failed to acquire fill-history task:0x%x, it may have been dropped already",
1574
              pMeta->vgId, pTask->historyTaskId.taskId);
1575
      streamMetaReleaseTask(pMeta, pTask);
1576 1577 1578

      // since task is in [STOP|DROPPING] state, it is safe to assume the pause is active
      return TSDB_CODE_SUCCESS;
1579 1580
    }

1581
    tqDebug("s-task:%s fill-history task handle paused along with related stream task", pHistoryTask->id.idStr);
1582

1583
    streamTaskPause(pHistoryTask);
1584
    streamMetaReleaseTask(pMeta, pHistoryTask);
L
liuyao 已提交
1585
  }
1586

1587
  streamMetaReleaseTask(pMeta, pTask);
1588
  return TSDB_CODE_SUCCESS;
L
liuyao 已提交
1589 1590 1591 1592
}

int32_t tqProcessTaskResumeImpl(STQ* pTq, SStreamTask* pTask, int64_t sversion, int8_t igUntreated) {
  int32_t vgId = pTq->pStreamMeta->vgId;
1593 1594 1595
  if (pTask == NULL) {
    return -1;
  }
L
liuyao 已提交
1596

1597 1598
  // todo: handle the case: resume from halt to pause/ from halt to normal/ from pause to normal
  streamTaskResume(pTask);
1599

1600 1601 1602
  int32_t level = pTask->info.taskLevel;
  int8_t  status = pTask->status.taskStatus;
  if (status == TASK_STATUS__NORMAL || status == TASK_STATUS__SCAN_HISTORY) {
1603
    // no lock needs to secure the access of the version
1604
    if (igUntreated && level == TASK_LEVEL__SOURCE && !pTask->info.fillHistory) {
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
      // discard all the data  when the stream task is suspended.
      walReaderSetSkipToVersion(pTask->exec.pWalReader, sversion);
      tqDebug("vgId:%d s-task:%s resume to exec, prev paused version:%" PRId64 ", start from vnode ver:%" PRId64
              ", schedStatus:%d",
              vgId, pTask->id.idStr, pTask->chkInfo.currentVer, sversion, pTask->status.schedStatus);
    } else {  // from the previous paused version and go on
      tqDebug("vgId:%d s-task:%s resume to exec, from paused ver:%" PRId64 ", vnode ver:%" PRId64 ", schedStatus:%d",
              vgId, pTask->id.idStr, pTask->chkInfo.currentVer, sversion, pTask->status.schedStatus);
    }

1615
    if (level == TASK_LEVEL__SOURCE && pTask->info.fillHistory && pTask->status.taskStatus == TASK_STATUS__SCAN_HISTORY) {
1616
      streamStartScanHistoryAsync(pTask, igUntreated);
1617
    } else if (level == TASK_LEVEL__SOURCE && (taosQueueItemSize(pTask->inputQueue->queue) == 0)) {
1618 1619 1620
      tqStartStreamTasks(pTq);
    } else {
      streamSchedExec(pTask);
L
liuyao 已提交
1621
    }
L
liuyao 已提交
1622
  }
1623 1624

  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
5
54liuyao 已提交
1625 1626 1627 1628 1629
  return 0;
}

int32_t tqProcessTaskResumeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
  SVResumeStreamTaskReq* pReq = (SVResumeStreamTaskReq*)msg;
1630
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->streamId, pReq->taskId);
L
liuyao 已提交
1631 1632 1633
  int32_t code = tqProcessTaskResumeImpl(pTq, pTask, sversion, pReq->igUntreated);
  if (code != 0) {
    return code;
L
liuyao 已提交
1634
  }
1635

1636
  SStreamTask* pHistoryTask = streamMetaAcquireTask(pTq->pStreamMeta, pTask->historyTaskId.streamId, pTask->historyTaskId.taskId);
L
liuyao 已提交
1637 1638 1639
  if (pHistoryTask) {
    code = tqProcessTaskResumeImpl(pTq, pHistoryTask, sversion, pReq->igUntreated);
  }
1640

L
liuyao 已提交
1641
  return code;
5
54liuyao 已提交
1642 1643
}

L
Liu Jicong 已提交
1644
int32_t tqProcessTaskRetrieveReq(STQ* pTq, SRpcMsg* pMsg) {
1645 1646 1647 1648 1649
  char*    msgStr = pMsg->pCont;
  char*    msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t  msgLen = pMsg->contLen - sizeof(SMsgHead);
  SDecoder decoder;

L
Liu Jicong 已提交
1650
  SStreamRetrieveReq req;
1651
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1652
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1653
  tDecoderClear(&decoder);
1654

1655
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.streamId, req.dstTaskId);
1656

L
Liu Jicong 已提交
1657
  if (pTask) {
1658
    SRpcMsg rsp = {.info = pMsg->info, .code = 0};
L
Liu Jicong 已提交
1659
    streamProcessRetrieveReq(pTask, &req, &rsp);
1660

L
Liu Jicong 已提交
1661
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1662
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1663
    return 0;
L
Liu Jicong 已提交
1664
  } else {
L
liuyao 已提交
1665
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1666
    return -1;
L
Liu Jicong 已提交
1667 1668 1669 1670 1671 1672 1673
  }
}

int32_t tqProcessTaskRetrieveRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}
L
Liu Jicong 已提交
1674

1675 1676
int32_t vnodeEnqueueStreamMsg(SVnode* pVnode, SRpcMsg* pMsg) {
  STQ*      pTq = pVnode->pTq;
1677 1678
  int32_t vgId = pVnode->config.vgId;

1679 1680 1681 1682
  SMsgHead* msgStr = pMsg->pCont;
  char*     msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t   msgLen = pMsg->contLen - sizeof(SMsgHead);
  int32_t   code = 0;
L
Liu Jicong 已提交
1683 1684 1685

  SStreamDispatchReq req;
  SDecoder           decoder;
1686
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1687 1688
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1689
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1690 1691
    goto FAIL;
  }
L
Liu Jicong 已提交
1692
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1693

L
Liu Jicong 已提交
1694
  int32_t taskId = req.taskId;
1695 1696 1697
  tqDebug("vgId:%d receive dispatch msg to s-task:0x%"PRIx64"-0x%x", vgId, req.streamId, taskId);

  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.streamId, taskId);
1698
  if (pTask != NULL) {
1699
    SRpcMsg rsp = {.info = pMsg->info, .code = 0};
1700
    streamProcessDispatchMsg(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1701
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1702 1703
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1704
    return 0;
5
54liuyao 已提交
1705
  } else {
1706

5
54liuyao 已提交
1707
    tDeleteStreamDispatchReq(&req);
L
Liu Jicong 已提交
1708
  }
L
Liu Jicong 已提交
1709

1710 1711
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1712
FAIL:
1713
  if (pMsg->info.handle == NULL) {
1714
    tqError("s-task:0x%x vgId:%d msg handle is null, abort enqueue dispatch msg", vgId, taskId);
1715 1716
    return -1;
  }
1717 1718 1719

  SMsgHead* pRspHead = rpcMallocCont(sizeof(SMsgHead) + sizeof(SStreamDispatchRsp));
  if (pRspHead == NULL) {
1720
    SRpcMsg rsp = {.code = TSDB_CODE_OUT_OF_MEMORY, .info = pMsg->info};
1721
    tqError("s-task:0x%x send dispatch error rsp, code:%s", taskId, tstrerror(code));
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    tmsgSendRsp(&rsp);
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
    return -1;
  }

  pRspHead->vgId = htonl(req.upstreamNodeId);
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pRspHead, sizeof(SMsgHead));
  pRsp->streamId = htobe64(req.streamId);
  pRsp->upstreamTaskId = htonl(req.upstreamTaskId);
  pRsp->upstreamNodeId = htonl(req.upstreamNodeId);
  pRsp->downstreamNodeId = htonl(pVnode->config.vgId);
  pRsp->downstreamTaskId = htonl(req.taskId);
  pRsp->inputStatus = TASK_OUTPUT_STATUS__NORMAL;

1737 1738 1739 1740
  int32_t len = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp);
  SRpcMsg rsp = { .code = code, .info = pMsg->info, .contLen = len, .pCont = pRspHead};
  tqError("s-task:0x%x send dispatch error rsp, code:%s", taskId, tstrerror(code));

L
Liu Jicong 已提交
1741
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1742 1743
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1744
  return -1;
L
Liu Jicong 已提交
1745
}
L
Liu Jicong 已提交
1746

1747
int32_t tqCheckLogInWal(STQ* pTq, int64_t sversion) { return sversion <= pTq->walLogLastVer; }
1748