clientTmq.c 77.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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/>.
 */

L
Liu Jicong 已提交
16
#include "cJSON.h"
17 18 19
#include "clientInt.h"
#include "clientLog.h"
#include "parser.h"
H
Haojun Liao 已提交
20
#include "tdatablock.h"
21 22
#include "tdef.h"
#include "tglobal.h"
X
Xiaoyu Wang 已提交
23
#include "tqueue.h"
24
#include "tref.h"
L
Liu Jicong 已提交
25 26
#include "ttimer.h"

X
Xiaoyu Wang 已提交
27 28
#define EMPTY_BLOCK_POLL_IDLE_DURATION 10
#define DEFAULT_AUTO_COMMIT_INTERVAL   5000
29

30 31
typedef void (*__tmq_askep_fn_t)(tmq_t* pTmq, int32_t code, SDataBuf* pBuf, void* pParam);

X
Xiaoyu Wang 已提交
32
struct SMqMgmt {
33 34 35
  int8_t  inited;
  tmr_h   timer;
  int32_t rsetId;
36
};
L
Liu Jicong 已提交
37

X
Xiaoyu Wang 已提交
38 39
static TdThreadOnce   tmqInit = PTHREAD_ONCE_INIT;  // initialize only once
volatile int32_t      tmqInitRes = 0;               // initialize rsp code
40
static struct SMqMgmt tmqMgmt = {0};
41

L
Liu Jicong 已提交
42 43 44 45 46 47
typedef struct {
  int8_t  tmqRspType;
  int32_t epoch;
} SMqRspWrapper;

typedef struct {
L
Liu Jicong 已提交
48 49 50
  int8_t      tmqRspType;
  int32_t     epoch;
  SMqAskEpRsp msg;
L
Liu Jicong 已提交
51 52
} SMqAskEpRspWrapper;

L
Liu Jicong 已提交
53
struct tmq_list_t {
L
Liu Jicong 已提交
54
  SArray container;
L
Liu Jicong 已提交
55
};
L
Liu Jicong 已提交
56

L
Liu Jicong 已提交
57
struct tmq_conf_t {
58 59 60 61 62 63 64 65
  char           clientId[256];
  char           groupId[TSDB_CGROUP_LEN];
  int8_t         autoCommit;
  int8_t         resetOffset;
  int8_t         withTbName;
  int8_t         snapEnable;
  int32_t        snapBatchSize;
  bool           hbBgEnable;
66 67 68 69 70
  uint16_t       port;
  int32_t        autoCommitInterval;
  char*          ip;
  char*          user;
  char*          pass;
71
  tmq_commit_cb* commitCb;
L
Liu Jicong 已提交
72
  void*          commitCbUserParam;
L
Liu Jicong 已提交
73 74 75
};

struct tmq_t {
76 77 78 79 80 81 82 83 84 85
  int64_t        refId;
  char           groupId[TSDB_CGROUP_LEN];
  char           clientId[256];
  int8_t         withTbName;
  int8_t         useSnapshot;
  int8_t         autoCommit;
  int32_t        autoCommitInterval;
  int32_t        resetOffsetCfg;
  uint64_t       consumerId;
  bool           hbBgEnable;
L
Liu Jicong 已提交
86 87
  tmq_commit_cb* commitCb;
  void*          commitCbUserParam;
L
Liu Jicong 已提交
88 89 90 91

  // status
  int8_t  status;
  int32_t epoch;
L
Liu Jicong 已提交
92 93
#if 0
  int8_t  epStatus;
L
Liu Jicong 已提交
94
  int32_t epSkipCnt;
L
Liu Jicong 已提交
95
#endif
96
  // poll info
X
Xiaoyu Wang 已提交
97 98
  int64_t pollCnt;
  int64_t totalRows;
L
Liu Jicong 已提交
99

L
Liu Jicong 已提交
100
  // timer
X
Xiaoyu Wang 已提交
101 102 103 104 105 106 107 108 109 110
  tmr_h       hbLiveTimer;
  tmr_h       epTimer;
  tmr_h       reportTimer;
  tmr_h       commitTimer;
  STscObj*    pTscObj;       // connection
  SArray*     clientTopics;  // SArray<SMqClientTopic>
  STaosQueue* mqueue;        // queue of rsp
  STaosQall*  qall;
  STaosQueue* delayedTask;  // delayed task queue for heartbeat and auto commit
  tsem_t      rspSem;
L
Liu Jicong 已提交
111 112
};

113 114
typedef struct SAskEpInfo {
  int32_t code;
H
Haojun Liao 已提交
115
  tsem_t  sem;
116 117
} SAskEpInfo;

X
Xiaoyu Wang 已提交
118 119 120 121 122 123 124 125
enum {
  TMQ_VG_STATUS__IDLE = 0,
  TMQ_VG_STATUS__WAIT,
};

enum {
  TMQ_CONSUMER_STATUS__INIT = 0,
  TMQ_CONSUMER_STATUS__READY,
126
  TMQ_CONSUMER_STATUS__NO_TOPIC,
L
Liu Jicong 已提交
127
  TMQ_CONSUMER_STATUS__RECOVER,
L
Liu Jicong 已提交
128 129
};

L
Liu Jicong 已提交
130
enum {
131
  TMQ_DELAYED_TASK__ASK_EP = 1,
L
Liu Jicong 已提交
132 133 134 135
  TMQ_DELAYED_TASK__REPORT,
  TMQ_DELAYED_TASK__COMMIT,
};

H
Haojun Liao 已提交
136
typedef struct SVgOffsetInfo {
L
Liu Jicong 已提交
137 138
  STqOffsetVal committedOffset;
  STqOffsetVal currentOffset;
H
Haojun Liao 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151
  int64_t      walVerBegin;
  int64_t      walVerEnd;
} SVgOffsetInfo;

typedef struct {
  int64_t       pollCnt;
  int64_t       numOfRows;
  SVgOffsetInfo offsetInfo;
  int32_t       vgId;
  int32_t       vgStatus;
  int32_t       vgSkipCnt;            // here used to mark the slow vgroups
  int64_t       emptyBlockReceiveTs;  // once empty block is received, idle for ignoreCnt then start to poll data
  SEpSet        epSet;
152 153
} SMqClientVg;

L
Liu Jicong 已提交
154
typedef struct {
155 156 157
  char           topicName[TSDB_TOPIC_FNAME_LEN];
  char           db[TSDB_DB_FNAME_LEN];
  SArray*        vgs;  // SArray<SMqClientVg>
L
Liu Jicong 已提交
158
  SSchemaWrapper schema;
159 160
} SMqClientTopic;

L
Liu Jicong 已提交
161 162
typedef struct {
  int8_t          tmqRspType;
163
  int32_t         epoch;  // epoch can be used to guard the vgHandle
164
  int32_t         vgId;
L
Liu Jicong 已提交
165 166
  SMqClientVg*    vgHandle;
  SMqClientTopic* topicHandle;
H
Haojun Liao 已提交
167
  uint64_t        reqId;
168
  SEpSet*         pEpset;
L
Liu Jicong 已提交
169
  union {
L
Liu Jicong 已提交
170 171
    SMqDataRsp dataRsp;
    SMqMetaRsp metaRsp;
L
Liu Jicong 已提交
172
    STaosxRsp  taosxRsp;
L
Liu Jicong 已提交
173
  };
L
Liu Jicong 已提交
174 175
} SMqPollRspWrapper;

L
Liu Jicong 已提交
176
typedef struct {
177 178
  int64_t refId;
  int32_t epoch;
L
Liu Jicong 已提交
179 180
  tsem_t  rspSem;
  int32_t rspErr;
L
Liu Jicong 已提交
181
} SMqSubscribeCbParam;
L
Liu Jicong 已提交
182

L
Liu Jicong 已提交
183
typedef struct {
184 185 186 187
  int64_t          refId;
  int32_t          epoch;
  void*            pParam;
  __tmq_askep_fn_t pUserFn;
188 189
} SMqAskEpCbParam;

L
Liu Jicong 已提交
190
typedef struct {
191 192
  int64_t         refId;
  int32_t         epoch;
L
Liu Jicong 已提交
193
  SMqClientVg*    pVg;
L
Liu Jicong 已提交
194
  SMqClientTopic* pTopic;
L
Liu Jicong 已提交
195
  int32_t         vgId;
X
Xiaoyu Wang 已提交
196
  uint64_t        requestId;  // request id for debug purpose
X
Xiaoyu Wang 已提交
197
} SMqPollCbParam;
198

199
typedef struct {
200 201
  int64_t        refId;
  int32_t        epoch;
L
Liu Jicong 已提交
202 203
  int32_t        waitingRspNum;
  int32_t        totalRspNum;
204
  int32_t        code;
205
  tmq_commit_cb* callbackFn;
L
Liu Jicong 已提交
206 207
  /*SArray*        successfulOffsets;*/
  /*SArray*        failedOffsets;*/
X
Xiaoyu Wang 已提交
208
  void* userParam;
209 210 211 212 213
} SMqCommitCbParamSet;

typedef struct {
  SMqCommitCbParamSet* params;
  STqOffset*           pOffset;
H
Haojun Liao 已提交
214 215 216
  char                 topicName[TSDB_TOPIC_FNAME_LEN];
  int32_t              vgId;
  tmq_t*               pTmq;
217
} SMqCommitCbParam;
218

219 220 221 222 223
typedef struct SSyncCommitInfo {
  tsem_t  sem;
  int32_t code;
} SSyncCommitInfo;

224
static int32_t doAskEp(tmq_t* tmq);
225 226
static int32_t makeTopicVgroupKey(char* dst, const char* topicName, int32_t vg);
static int32_t tmqCommitDone(SMqCommitCbParamSet* pParamSet);
227 228
static int32_t doSendCommitMsg(tmq_t* tmq, SMqClientVg* pVg, const char* pTopicName, SMqCommitCbParamSet* pParamSet,
                               int32_t index, int32_t totalVgroups);
X
Xiaoyu Wang 已提交
229 230 231
static void    commitRspCountDown(SMqCommitCbParamSet* pParamSet, int64_t consumerId, const char* pTopic, int32_t vgId);
static void    asyncAskEp(tmq_t* pTmq, __tmq_askep_fn_t askEpFn, void* param);
static void    addToQueueCallbackFn(tmq_t* pTmq, int32_t code, SDataBuf* pDataBuf, void* param);
232

233
tmq_conf_t* tmq_conf_new() {
wafwerar's avatar
wafwerar 已提交
234
  tmq_conf_t* conf = taosMemoryCalloc(1, sizeof(tmq_conf_t));
235 236 237 238 239
  if (conf == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return conf;
  }

240
  conf->withTbName = false;
L
Liu Jicong 已提交
241
  conf->autoCommit = true;
242
  conf->autoCommitInterval = DEFAULT_AUTO_COMMIT_INTERVAL;
243
  conf->resetOffset = TMQ_OFFSET__RESET_EARLIEAST;
244
  conf->hbBgEnable = true;
245

246 247 248
  return conf;
}

L
Liu Jicong 已提交
249
void tmq_conf_destroy(tmq_conf_t* conf) {
L
Liu Jicong 已提交
250
  if (conf) {
251 252 253 254 255 256 257 258 259
    if (conf->ip) {
      taosMemoryFree(conf->ip);
    }
    if (conf->user) {
      taosMemoryFree(conf->user);
    }
    if (conf->pass) {
      taosMemoryFree(conf->pass);
    }
L
Liu Jicong 已提交
260 261
    taosMemoryFree(conf);
  }
L
Liu Jicong 已提交
262 263 264
}

tmq_conf_res_t tmq_conf_set(tmq_conf_t* conf, const char* key, const char* value) {
265
  if (strcasecmp(key, "group.id") == 0) {
L
Liu Jicong 已提交
266
    tstrncpy(conf->groupId, value, TSDB_CGROUP_LEN);
L
Liu Jicong 已提交
267
    return TMQ_CONF_OK;
268
  }
L
Liu Jicong 已提交
269

270
  if (strcasecmp(key, "client.id") == 0) {
L
Liu Jicong 已提交
271
    tstrncpy(conf->clientId, value, 256);
L
Liu Jicong 已提交
272 273
    return TMQ_CONF_OK;
  }
L
Liu Jicong 已提交
274

275 276
  if (strcasecmp(key, "enable.auto.commit") == 0) {
    if (strcasecmp(value, "true") == 0) {
L
Liu Jicong 已提交
277
      conf->autoCommit = true;
L
Liu Jicong 已提交
278
      return TMQ_CONF_OK;
279
    } else if (strcasecmp(value, "false") == 0) {
L
Liu Jicong 已提交
280
      conf->autoCommit = false;
L
Liu Jicong 已提交
281 282 283 284
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
285
  }
L
Liu Jicong 已提交
286

287
  if (strcasecmp(key, "auto.commit.interval.ms") == 0) {
288
    conf->autoCommitInterval = taosStr2int64(value);
L
Liu Jicong 已提交
289 290 291
    return TMQ_CONF_OK;
  }

292 293 294
  if (strcasecmp(key, "auto.offset.reset") == 0) {
    if (strcasecmp(value, "none") == 0) {
      conf->resetOffset = TMQ_OFFSET__RESET_NONE;
L
Liu Jicong 已提交
295
      return TMQ_CONF_OK;
296 297
    } else if (strcasecmp(value, "earliest") == 0) {
      conf->resetOffset = TMQ_OFFSET__RESET_EARLIEAST;
L
Liu Jicong 已提交
298
      return TMQ_CONF_OK;
299 300
    } else if (strcasecmp(value, "latest") == 0) {
      conf->resetOffset = TMQ_OFFSET__RESET_LATEST;
L
Liu Jicong 已提交
301 302 303 304 305
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
  }
L
Liu Jicong 已提交
306

307 308
  if (strcasecmp(key, "msg.with.table.name") == 0) {
    if (strcasecmp(value, "true") == 0) {
309
      conf->withTbName = true;
L
Liu Jicong 已提交
310
      return TMQ_CONF_OK;
311
    } else if (strcasecmp(value, "false") == 0) {
312
      conf->withTbName = false;
L
Liu Jicong 已提交
313
      return TMQ_CONF_OK;
314 315 316 317 318
    } else {
      return TMQ_CONF_INVALID;
    }
  }

319 320
  if (strcasecmp(key, "experimental.snapshot.enable") == 0) {
    if (strcasecmp(value, "true") == 0) {
L
Liu Jicong 已提交
321
      conf->snapEnable = true;
322
      return TMQ_CONF_OK;
323
    } else if (strcasecmp(value, "false") == 0) {
L
Liu Jicong 已提交
324
      conf->snapEnable = false;
325 326 327 328 329 330
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
  }

331
  if (strcasecmp(key, "experimental.snapshot.batch.size") == 0) {
332
    conf->snapBatchSize = taosStr2int64(value);
L
Liu Jicong 已提交
333 334 335
    return TMQ_CONF_OK;
  }

336
  if (strcasecmp(key, "enable.heartbeat.background") == 0) {
X
Xiaoyu Wang 已提交
337 338 339 340 341 342 343 344 345 346
    //    if (strcasecmp(value, "true") == 0) {
    //      conf->hbBgEnable = true;
    //      return TMQ_CONF_OK;
    //    } else if (strcasecmp(value, "false") == 0) {
    //      conf->hbBgEnable = false;
    //      return TMQ_CONF_OK;
    //    } else {
    tscError("the default value of enable.heartbeat.background is true, can not be seted");
    return TMQ_CONF_INVALID;
    //    }
L
Liu Jicong 已提交
347 348
  }

349
  if (strcasecmp(key, "td.connect.ip") == 0) {
350
    conf->ip = taosStrdup(value);
L
Liu Jicong 已提交
351 352
    return TMQ_CONF_OK;
  }
353

354
  if (strcasecmp(key, "td.connect.user") == 0) {
355
    conf->user = taosStrdup(value);
L
Liu Jicong 已提交
356 357
    return TMQ_CONF_OK;
  }
358

359
  if (strcasecmp(key, "td.connect.pass") == 0) {
360
    conf->pass = taosStrdup(value);
L
Liu Jicong 已提交
361 362
    return TMQ_CONF_OK;
  }
363

364
  if (strcasecmp(key, "td.connect.port") == 0) {
365
    conf->port = taosStr2int64(value);
L
Liu Jicong 已提交
366 367
    return TMQ_CONF_OK;
  }
368

369
  if (strcasecmp(key, "td.connect.db") == 0) {
L
Liu Jicong 已提交
370 371 372
    return TMQ_CONF_OK;
  }

L
Liu Jicong 已提交
373
  return TMQ_CONF_UNKNOWN;
374 375
}

X
Xiaoyu Wang 已提交
376
tmq_list_t* tmq_list_new() { return (tmq_list_t*)taosArrayInit(0, sizeof(void*)); }
377

L
Liu Jicong 已提交
378 379
int32_t tmq_list_append(tmq_list_t* list, const char* src) {
  SArray* container = &list->container;
380
  if (src == NULL || src[0] == 0) return -1;
381
  char* topic = taosStrdup(src);
382 383 384
  if (topic[0] != '`') {
    strtolower(topic, src);
  }
L
fix  
Liu Jicong 已提交
385
  if (taosArrayPush(container, &topic) == NULL) return -1;
386 387 388
  return 0;
}

L
Liu Jicong 已提交
389
void tmq_list_destroy(tmq_list_t* list) {
L
Liu Jicong 已提交
390
  SArray* container = &list->container;
L
Liu Jicong 已提交
391
  taosArrayDestroyP(container, taosMemoryFree);
L
Liu Jicong 已提交
392 393
}

L
Liu Jicong 已提交
394 395 396 397 398 399 400 401 402 403
int32_t tmq_list_get_size(const tmq_list_t* list) {
  const SArray* container = &list->container;
  return taosArrayGetSize(container);
}

char** tmq_list_to_c_array(const tmq_list_t* list) {
  const SArray* container = &list->container;
  return container->pData;
}

X
Xiaoyu Wang 已提交
404 405
static SMqClientVg* foundClientVg(SArray* pTopicList, const char* pName, int32_t vgId, int32_t* index,
                                  int32_t* numOfVgroups) {
406 407 408 409
  int32_t numOfTopics = taosArrayGetSize(pTopicList);
  *index = -1;
  *numOfVgroups = 0;

X
Xiaoyu Wang 已提交
410
  for (int32_t i = 0; i < numOfTopics; ++i) {
411 412
    SMqClientTopic* pTopic = taosArrayGet(pTopicList, i);
    if (strcmp(pTopic->topicName, pName) != 0) {
413 414 415
      continue;
    }

416 417
    *numOfVgroups = taosArrayGetSize(pTopic->vgs);
    for (int32_t j = 0; j < (*numOfVgroups); ++j) {
418
      SMqClientVg* pClientVg = taosArrayGet(pTopic->vgs, j);
419 420 421
      if (pClientVg->vgId == vgId) {
        *index = j;
        return pClientVg;
422 423
      }
    }
L
Liu Jicong 已提交
424
  }
425 426

  return NULL;
L
Liu Jicong 已提交
427
}
428

429 430 431
// Two problems do not need to be addressed here
// 1. update to of epset. the response of poll request will automatically handle this problem
// 2. commit failure. This one needs to be resolved.
H
Haojun Liao 已提交
432
static int32_t tmqCommitCb(void* param, SDataBuf* pBuf, int32_t code) {
433
  SMqCommitCbParam*    pParam = (SMqCommitCbParam*)param;
434
  SMqCommitCbParamSet* pParamSet = (SMqCommitCbParamSet*)pParam->params;
H
Haojun Liao 已提交
435

X
Xiaoyu Wang 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449
  //  if (code != TSDB_CODE_SUCCESS) { // if commit offset failed, let's try again
  //    taosThreadMutexLock(&pParam->pTmq->lock);
  //    int32_t numOfVgroups, index;
  //    SMqClientVg* pVg = foundClientVg(pParam->pTmq->clientTopics, pParam->topicName, pParam->vgId, &index,
  //    &numOfVgroups); if (pVg == NULL) {
  //      tscDebug("consumer:0x%" PRIx64
  //               " subKey:%s vgId:%d commit failed, code:%s has been transferred to other consumer, no need retry
  //               ordinal:%d/%d", pParam->pTmq->consumerId, pParam->pOffset->subKey, pParam->vgId, tstrerror(code),
  //               index + 1, numOfVgroups);
  //    } else { // let's retry the commit
  //      int32_t code1 = doSendCommitMsg(pParam->pTmq, pVg, pParam->topicName, pParamSet, index, numOfVgroups);
  //      if (code1 != TSDB_CODE_SUCCESS) {  // retry failed.
  //        tscError("consumer:0x%" PRIx64 " topic:%s vgId:%d offset:%" PRId64
  //                 " retry failed, ignore this commit. code:%s ordinal:%d/%d",
H
Haojun Liao 已提交
450
  //                 pParam->pTmq->consumerId, pParam->topicName, pVg->vgId, pVg->offsetInfo.committedOffset.version,
X
Xiaoyu Wang 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  //                 tstrerror(terrno), index + 1, numOfVgroups);
  //      }
  //    }
  //
  //    taosThreadMutexUnlock(&pParam->pTmq->lock);
  //
  //    taosMemoryFree(pParam->pOffset);
  //    taosMemoryFree(pBuf->pData);
  //    taosMemoryFree(pBuf->pEpSet);
  //
  //    commitRspCountDown(pParamSet, pParam->pTmq->consumerId, pParam->topicName, pParam->vgId);
  //    return 0;
  //  }
  //
  //  // todo replace the pTmq with refId
466

L
Liu Jicong 已提交
467
  taosMemoryFree(pParam->pOffset);
L
Liu Jicong 已提交
468
  taosMemoryFree(pBuf->pData);
dengyihao's avatar
dengyihao 已提交
469
  taosMemoryFree(pBuf->pEpSet);
L
Liu Jicong 已提交
470

471
  commitRspCountDown(pParamSet, pParam->pTmq->consumerId, pParam->topicName, pParam->vgId);
472 473 474
  return 0;
}

475 476
static int32_t doSendCommitMsg(tmq_t* tmq, SMqClientVg* pVg, const char* pTopicName, SMqCommitCbParamSet* pParamSet,
                               int32_t index, int32_t totalVgroups) {
L
Liu Jicong 已提交
477 478
  STqOffset* pOffset = taosMemoryCalloc(1, sizeof(STqOffset));
  if (pOffset == NULL) {
479
    return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
480
  }
481

H
Haojun Liao 已提交
482
  pOffset->val = pVg->offsetInfo.currentOffset;
483

L
Liu Jicong 已提交
484 485 486
  int32_t groupLen = strlen(tmq->groupId);
  memcpy(pOffset->subKey, tmq->groupId, groupLen);
  pOffset->subKey[groupLen] = TMQ_SEPARATOR;
H
Haojun Liao 已提交
487
  strcpy(pOffset->subKey + groupLen + 1, pTopicName);
L
Liu Jicong 已提交
488

489 490
  int32_t len = 0;
  int32_t code = 0;
L
Liu Jicong 已提交
491 492
  tEncodeSize(tEncodeSTqOffset, pOffset, len, code);
  if (code < 0) {
493
    return TSDB_CODE_INVALID_PARA;
L
Liu Jicong 已提交
494
  }
495

L
Liu Jicong 已提交
496
  void* buf = taosMemoryCalloc(1, sizeof(SMsgHead) + len);
L
Liu Jicong 已提交
497 498
  if (buf == NULL) {
    taosMemoryFree(pOffset);
499
    return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
500
  }
501

L
Liu Jicong 已提交
502
  ((SMsgHead*)buf)->vgId = htonl(pVg->vgId);
L
Liu Jicong 已提交
503

L
Liu Jicong 已提交
504 505 506 507 508
  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));

  SEncoder encoder;
  tEncoderInit(&encoder, abuf, len);
  tEncodeSTqOffset(&encoder, pOffset);
L
Liu Jicong 已提交
509
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
510 511

  // build param
512
  SMqCommitCbParam* pParam = taosMemoryCalloc(1, sizeof(SMqCommitCbParam));
L
Liu Jicong 已提交
513
  if (pParam == NULL) {
L
Liu Jicong 已提交
514
    taosMemoryFree(pOffset);
L
Liu Jicong 已提交
515
    taosMemoryFree(buf);
516
    return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
517
  }
518

L
Liu Jicong 已提交
519 520
  pParam->params = pParamSet;
  pParam->pOffset = pOffset;
H
Haojun Liao 已提交
521 522 523
  pParam->vgId = pVg->vgId;
  pParam->pTmq = tmq;

H
Haojun Liao 已提交
524
  tstrncpy(pParam->topicName, pTopicName, tListLen(pParam->topicName));
L
Liu Jicong 已提交
525 526 527 528

  // build send info
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
  if (pMsgSendInfo == NULL) {
L
Liu Jicong 已提交
529
    taosMemoryFree(pOffset);
L
Liu Jicong 已提交
530 531
    taosMemoryFree(buf);
    taosMemoryFree(pParam);
532
    return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
533
  }
534

535
  pMsgSendInfo->msgInfo = (SDataBuf) { .pData = buf, .len = sizeof(SMsgHead) + len, .handle = NULL };
L
Liu Jicong 已提交
536 537 538 539

  pMsgSendInfo->requestId = generateRequestId();
  pMsgSendInfo->requestObjRefId = 0;
  pMsgSendInfo->param = pParam;
L
Liu Jicong 已提交
540
  pMsgSendInfo->paramFreeFp = taosMemoryFree;
541
  pMsgSendInfo->fp = tmqCommitCb;
L
Liu Jicong 已提交
542
  pMsgSendInfo->msgType = TDMT_VND_TMQ_COMMIT_OFFSET;
L
Liu Jicong 已提交
543

L
Liu Jicong 已提交
544 545 546
  atomic_add_fetch_32(&pParamSet->waitingRspNum, 1);
  atomic_add_fetch_32(&pParamSet->totalRspNum, 1);

H
Haojun Liao 已提交
547
  SEp* pEp = GET_ACTIVE_EP(&pVg->epSet);
548 549 550 551
  char offsetBuf[80] = {0};
  tFormatOffset(offsetBuf, tListLen(offsetBuf), &pOffset->val);

  char commitBuf[80] = {0};
H
Haojun Liao 已提交
552
  tFormatOffset(commitBuf, tListLen(commitBuf), &pVg->offsetInfo.committedOffset);
553 554 555
  tscDebug("consumer:0x%" PRIx64 " topic:%s on vgId:%d send offset:%s prev:%s, ep:%s:%d, ordinal:%d/%d, req:0x%" PRIx64,
           tmq->consumerId, pOffset->subKey, pVg->vgId, offsetBuf, commitBuf, pEp->fqdn, pEp->port, index + 1,
           totalVgroups, pMsgSendInfo->requestId);
H
Haojun Liao 已提交
556

L
Liu Jicong 已提交
557 558
  int64_t transporterId = 0;
  asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &pVg->epSet, &transporterId, pMsgSendInfo);
559 560

  return TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
561 562
}

H
Haojun Liao 已提交
563 564 565 566 567 568 569 570 571 572 573
static SMqClientTopic* getTopicByName(tmq_t* tmq, const char* pTopicName) {
  int32_t numOfTopics = taosArrayGetSize(tmq->clientTopics);
  for (int32_t i = 0; i < numOfTopics; ++i) {
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
    if (strcmp(pTopic->topicName, pTopicName) != 0) {
      continue;
    }

    return pTopic;
  }

H
Haojun Liao 已提交
574
  tscError("consumer:0x%" PRIx64 ", total:%d, failed to find topic:%s", tmq->consumerId, numOfTopics, pTopicName);
H
Haojun Liao 已提交
575 576 577
  return NULL;
}

578 579 580 581 582 583 584 585 586 587 588 589 590
static void asyncCommitOffset(tmq_t* tmq, const TAOS_RES* pRes, tmq_commit_cb* pCommitFp, void* userParam) {
  char*   pTopicName = NULL;
  int32_t vgId = 0;
  int32_t code = 0;

  if (pRes == NULL || tmq == NULL) {
    pCommitFp(tmq, TSDB_CODE_INVALID_PARA, userParam);
    return;
  }

  if (TD_RES_TMQ(pRes)) {
    SMqRspObj* pRspObj = (SMqRspObj*)pRes;
    pTopicName = pRspObj->topic;
L
Liu Jicong 已提交
591
    vgId = pRspObj->vgId;
592 593 594
  } else if (TD_RES_TMQ_META(pRes)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)pRes;
    pTopicName = pMetaRspObj->topic;
L
Liu Jicong 已提交
595
    vgId = pMetaRspObj->vgId;
596 597 598
  } else if (TD_RES_TMQ_METADATA(pRes)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)pRes;
    pTopicName = pRspObj->topic;
599
    vgId = pRspObj->vgId;
L
Liu Jicong 已提交
600
  } else {
601 602
    pCommitFp(tmq, TSDB_CODE_TMQ_INVALID_MSG, userParam);
    return;
L
Liu Jicong 已提交
603 604 605 606
  }

  SMqCommitCbParamSet* pParamSet = taosMemoryCalloc(1, sizeof(SMqCommitCbParamSet));
  if (pParamSet == NULL) {
607 608
    pCommitFp(tmq, TSDB_CODE_OUT_OF_MEMORY, userParam);
    return;
L
Liu Jicong 已提交
609
  }
H
Haojun Liao 已提交
610

611 612
  pParamSet->refId = tmq->refId;
  pParamSet->epoch = tmq->epoch;
613
  pParamSet->callbackFn = pCommitFp;
L
Liu Jicong 已提交
614
  pParamSet->userParam = userParam;
L
Liu Jicong 已提交
615

H
Haojun Liao 已提交
616 617
  int32_t numOfTopics = taosArrayGetSize(tmq->clientTopics);

618 619
  tscDebug("consumer:0x%" PRIx64 " do manual commit offset for %s, vgId:%d", tmq->consumerId, pTopicName, vgId);

H
Haojun Liao 已提交
620 621
  SMqClientTopic* pTopic = getTopicByName(tmq, pTopicName);
  if (pTopic == NULL) {
X
Xiaoyu Wang 已提交
622 623
    tscWarn("consumer:0x%" PRIx64 " failed to find the specified topic:%s, total topics:%d", tmq->consumerId,
            pTopicName, numOfTopics);
624 625 626 627
    taosMemoryFree(pParamSet);
    pCommitFp(tmq, TSDB_CODE_SUCCESS, userParam);
    return;
  }
L
Liu Jicong 已提交
628

629 630 631 632 633 634
  int32_t j = 0;
  int32_t numOfVgroups = taosArrayGetSize(pTopic->vgs);
  for (j = 0; j < numOfVgroups; j++) {
    SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);
    if (pVg->vgId == vgId) {
      break;
L
Liu Jicong 已提交
635
    }
L
Liu Jicong 已提交
636
  }
L
Liu Jicong 已提交
637

638
  if (j == numOfVgroups) {
X
Xiaoyu Wang 已提交
639 640
    tscWarn("consumer:0x%" PRIx64 " failed to find the specified vgId:%d, total Vgs:%d, topic:%s", tmq->consumerId,
            vgId, numOfVgroups, pTopicName);
L
Liu Jicong 已提交
641
    taosMemoryFree(pParamSet);
642 643
    pCommitFp(tmq, TSDB_CODE_SUCCESS, userParam);
    return;
L
Liu Jicong 已提交
644 645
  }

646
  SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);
H
Haojun Liao 已提交
647
  if (pVg->offsetInfo.currentOffset.type > 0 && !tOffsetEqual(&pVg->offsetInfo.currentOffset, &pVg->offsetInfo.committedOffset)) {
648
    code = doSendCommitMsg(tmq, pVg, pTopic->topicName, pParamSet, j, numOfVgroups);
L
Liu Jicong 已提交
649

650 651 652 653 654
    // failed to commit, callback user function directly.
    if (code != TSDB_CODE_SUCCESS) {
      taosMemoryFree(pParamSet);
      pCommitFp(tmq, code, userParam);
    }
X
Xiaoyu Wang 已提交
655
  } else {  // do not perform commit, callback user function directly.
656 657
    taosMemoryFree(pParamSet);
    pCommitFp(tmq, code, userParam);
L
Liu Jicong 已提交
658 659 660
  }
}

661
static void asyncCommitAllOffsets(tmq_t* tmq, tmq_commit_cb* pCommitFp, void* userParam) {
662 663
  SMqCommitCbParamSet* pParamSet = taosMemoryCalloc(1, sizeof(SMqCommitCbParamSet));
  if (pParamSet == NULL) {
664 665
    pCommitFp(tmq, TSDB_CODE_OUT_OF_MEMORY, userParam);
    return;
666
  }
667 668 669

  pParamSet->refId = tmq->refId;
  pParamSet->epoch = tmq->epoch;
670
  pParamSet->callbackFn = pCommitFp;
671 672
  pParamSet->userParam = userParam;

673 674 675
  // init as 1 to prevent concurrency issue
  pParamSet->waitingRspNum = 1;

676
  int32_t numOfTopics = taosArrayGetSize(tmq->clientTopics);
X
Xiaoyu Wang 已提交
677
  tscDebug("consumer:0x%" PRIx64 " start to commit offset for %d topics", tmq->consumerId, numOfTopics);
678 679

  for (int32_t i = 0; i < numOfTopics; i++) {
680
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
681
    int32_t         numOfVgroups = taosArrayGetSize(pTopic->vgs);
L
Liu Jicong 已提交
682

683 684
    tscDebug("consumer:0x%" PRIx64 " commit offset for topics:%s, numOfVgs:%d", tmq->consumerId, pTopic->topicName,
             numOfVgroups);
685
    for (int32_t j = 0; j < numOfVgroups; j++) {
686 687
      SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);

H
Haojun Liao 已提交
688
      if (pVg->offsetInfo.currentOffset.type > 0 && !tOffsetEqual(&pVg->offsetInfo.currentOffset, &pVg->offsetInfo.committedOffset)) {
689
        int32_t code = doSendCommitMsg(tmq, pVg, pTopic->topicName, pParamSet, j, numOfVgroups);
690 691
        if (code != TSDB_CODE_SUCCESS) {
          tscError("consumer:0x%" PRIx64 " topic:%s vgId:%d offset:%" PRId64 " failed, code:%s ordinal:%d/%d",
H
Haojun Liao 已提交
692
                   tmq->consumerId, pTopic->topicName, pVg->vgId, pVg->offsetInfo.committedOffset.version, tstrerror(terrno),
693
                   j + 1, numOfVgroups);
L
Liu Jicong 已提交
694 695
          continue;
        }
H
Haojun Liao 已提交
696 697

        // update the offset value.
H
Haojun Liao 已提交
698
        pVg->offsetInfo.committedOffset = pVg->offsetInfo.currentOffset;
699
      } else {
D
dapan1121 已提交
700
        tscDebug("consumer:0x%" PRIx64 " topic:%s vgId:%d, no commit, current:%" PRId64 ", ordinal:%d/%d",
H
Haojun Liao 已提交
701
                 tmq->consumerId, pTopic->topicName, pVg->vgId, pVg->offsetInfo.currentOffset.version, j + 1, numOfVgroups);
702 703 704 705
      }
    }
  }

H
Haojun Liao 已提交
706
  tscDebug("consumer:0x%" PRIx64 " total commit:%d for %d topics", tmq->consumerId, pParamSet->waitingRspNum - 1,
707
           numOfTopics);
H
Haojun Liao 已提交
708

L
Liu Jicong 已提交
709
  // no request is sent
L
Liu Jicong 已提交
710 711
  if (pParamSet->totalRspNum == 0) {
    taosMemoryFree(pParamSet);
712 713
    pCommitFp(tmq, TSDB_CODE_SUCCESS, userParam);
    return;
L
Liu Jicong 已提交
714 715
  }

L
Liu Jicong 已提交
716
  // count down since waiting rsp num init as 1
717
  commitRspCountDown(pParamSet, tmq->consumerId, "", 0);
718 719
}

720 721
static void generateTimedTask(int64_t refId, int32_t type) {
  tmq_t* tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
722
  if (tmq != NULL) {
S
Shengliang Guan 已提交
723
    int8_t* pTaskType = taosAllocateQitem(sizeof(int8_t), DEF_QITEM, 0);
724
    *pTaskType = type;
725 726 727
    taosWriteQitem(tmq->delayedTask, pTaskType);
    tsem_post(&tmq->rspSem);
  }
728
  taosReleaseRef(tmqMgmt.rsetId, refId);
729 730 731 732 733
}

void tmqAssignAskEpTask(void* param, void* tmrId) {
  int64_t refId = *(int64_t*)param;
  generateTimedTask(refId, TMQ_DELAYED_TASK__ASK_EP);
734
  taosMemoryFree(param);
L
Liu Jicong 已提交
735 736 737
}

void tmqAssignDelayedCommitTask(void* param, void* tmrId) {
738
  int64_t refId = *(int64_t*)param;
739
  generateTimedTask(refId, TMQ_DELAYED_TASK__COMMIT);
740
  taosMemoryFree(param);
L
Liu Jicong 已提交
741 742 743
}

void tmqAssignDelayedReportTask(void* param, void* tmrId) {
744 745 746
  int64_t refId = *(int64_t*)param;
  tmq_t*  tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
  if (tmq != NULL) {
S
Shengliang Guan 已提交
747
    int8_t* pTaskType = taosAllocateQitem(sizeof(int8_t), DEF_QITEM, 0);
748 749 750 751
    *pTaskType = TMQ_DELAYED_TASK__REPORT;
    taosWriteQitem(tmq->delayedTask, pTaskType);
    tsem_post(&tmq->rspSem);
  }
752 753

  taosReleaseRef(tmqMgmt.rsetId, refId);
754
  taosMemoryFree(param);
L
Liu Jicong 已提交
755 756
}

757
int32_t tmqHbCb(void* param, SDataBuf* pMsg, int32_t code) {
dengyihao's avatar
dengyihao 已提交
758 759 760 761
  if (pMsg) {
    taosMemoryFree(pMsg->pData);
    taosMemoryFree(pMsg->pEpSet);
  }
762 763 764 765
  return 0;
}

void tmqSendHbReq(void* param, void* tmrId) {
766
  int64_t refId = *(int64_t*)param;
767

X
Xiaoyu Wang 已提交
768
  tmq_t* tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
769
  if (tmq == NULL) {
L
Liu Jicong 已提交
770
    taosMemoryFree(param);
771 772
    return;
  }
D
dapan1121 已提交
773 774 775 776 777

  SMqHbReq req = {0};
  req.consumerId = tmq->consumerId;
  req.epoch = tmq->epoch;

L
Liu Jicong 已提交
778
  int32_t tlen = tSerializeSMqHbReq(NULL, 0, &req);
D
dapan1121 已提交
779 780
  if (tlen < 0) {
    tscError("tSerializeSMqHbReq failed");
781
    goto OVER;
D
dapan1121 已提交
782
  }
783

L
Liu Jicong 已提交
784
  void* pReq = taosMemoryCalloc(1, tlen);
D
dapan1121 已提交
785 786
  if (tlen < 0) {
    tscError("failed to malloc MqHbReq msg, size:%d", tlen);
787
    goto OVER;
D
dapan1121 已提交
788
  }
789

D
dapan1121 已提交
790 791 792
  if (tSerializeSMqHbReq(pReq, tlen, &req) < 0) {
    tscError("tSerializeSMqHbReq %d failed", tlen);
    taosMemoryFree(pReq);
793
    goto OVER;
D
dapan1121 已提交
794
  }
795 796 797 798

  SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
  if (sendInfo == NULL) {
    taosMemoryFree(pReq);
L
Liu Jicong 已提交
799
    goto OVER;
800
  }
801

802
  sendInfo->msgInfo = (SDataBuf){ .pData = pReq, .len = tlen, .handle = NULL };
803 804 805 806 807

  sendInfo->requestId = generateRequestId();
  sendInfo->requestObjRefId = 0;
  sendInfo->param = NULL;
  sendInfo->fp = tmqHbCb;
L
Liu Jicong 已提交
808
  sendInfo->msgType = TDMT_MND_TMQ_HB;
809 810 811 812 813 814 815

  SEpSet epSet = getEpSet_s(&tmq->pTscObj->pAppInfo->mgmtEp);

  int64_t transporterId = 0;
  asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, sendInfo);

OVER:
816
  taosTmrReset(tmqSendHbReq, 1000, param, tmqMgmt.timer, &tmq->hbLiveTimer);
817
  taosReleaseRef(tmqMgmt.rsetId, refId);
818 819
}

820 821
static void defaultCommitCbFn(tmq_t* pTmq, int32_t code, void* param) {
  if (code != 0) {
X
Xiaoyu Wang 已提交
822
    tscDebug("consumer:0x%" PRIx64 ", failed to commit offset, code:%s", pTmq->consumerId, tstrerror(code));
823 824 825
  }
}

826
int32_t tmqHandleAllDelayedTask(tmq_t* pTmq) {
L
Liu Jicong 已提交
827
  STaosQall* qall = taosAllocateQall();
828
  taosReadAllQitems(pTmq->delayedTask, qall);
L
Liu Jicong 已提交
829

830 831 832 833
  if (qall->numOfItems == 0) {
    taosFreeQall(qall);
    return TSDB_CODE_SUCCESS;
  }
834

X
Xiaoyu Wang 已提交
835
  tscDebug("consumer:0x%" PRIx64 " handle delayed %d tasks before poll data", pTmq->consumerId, qall->numOfItems);
836 837
  int8_t* pTaskType = NULL;
  taosGetQitem(qall, (void**)&pTaskType);
L
Liu Jicong 已提交
838

839
  while (pTaskType != NULL) {
840
    if (*pTaskType == TMQ_DELAYED_TASK__ASK_EP) {
841
      asyncAskEp(pTmq, addToQueueCallbackFn, NULL);
842 843

      int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t));
844
      *pRefId = pTmq->refId;
845

X
Xiaoyu Wang 已提交
846
      tscDebug("consumer:0x%" PRIx64 " retrieve ep from mnode in 1s", pTmq->consumerId);
847
      taosTmrReset(tmqAssignAskEpTask, 1000, pRefId, tmqMgmt.timer, &pTmq->epTimer);
L
Liu Jicong 已提交
848
    } else if (*pTaskType == TMQ_DELAYED_TASK__COMMIT) {
X
Xiaoyu Wang 已提交
849
      tmq_commit_cb* pCallbackFn = pTmq->commitCb ? pTmq->commitCb : defaultCommitCbFn;
850 851

      asyncCommitAllOffsets(pTmq, pCallbackFn, pTmq->commitCbUserParam);
852
      int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t));
853
      *pRefId = pTmq->refId;
854

855
      tscDebug("consumer:0x%" PRIx64 " next commit to vnode(s) in %.2fs", pTmq->consumerId,
X
Xiaoyu Wang 已提交
856
               pTmq->autoCommitInterval / 1000.0);
857
      taosTmrReset(tmqAssignDelayedCommitTask, pTmq->autoCommitInterval, pRefId, tmqMgmt.timer, &pTmq->commitTimer);
L
Liu Jicong 已提交
858 859
    } else if (*pTaskType == TMQ_DELAYED_TASK__REPORT) {
    }
860

L
Liu Jicong 已提交
861
    taosFreeQitem(pTaskType);
862
    taosGetQitem(qall, (void**)&pTaskType);
L
Liu Jicong 已提交
863
  }
864

L
Liu Jicong 已提交
865 866 867 868
  taosFreeQall(qall);
  return 0;
}

869
static void* tmqFreeRspWrapper(SMqRspWrapper* rspWrapper) {
L
Liu Jicong 已提交
870 871 872 873 874 875 876
  if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__END_RSP) {
    // do nothing
  } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__EP_RSP) {
    SMqAskEpRspWrapper* pEpRspWrapper = (SMqAskEpRspWrapper*)rspWrapper;
    tDeleteSMqAskEpRsp(&pEpRspWrapper->msg);
  } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_RSP) {
    SMqPollRspWrapper* pRsp = (SMqPollRspWrapper*)rspWrapper;
877 878
    taosMemoryFreeClear(pRsp->pEpset);

L
Liu Jicong 已提交
879 880 881 882 883 884
    taosArrayDestroyP(pRsp->dataRsp.blockData, taosMemoryFree);
    taosArrayDestroy(pRsp->dataRsp.blockDataLen);
    taosArrayDestroyP(pRsp->dataRsp.blockTbName, taosMemoryFree);
    taosArrayDestroyP(pRsp->dataRsp.blockSchema, (FDelete)tDeleteSSchemaWrapper);
  } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_META_RSP) {
    SMqPollRspWrapper* pRsp = (SMqPollRspWrapper*)rspWrapper;
885 886
    taosMemoryFreeClear(pRsp->pEpset);

L
Liu Jicong 已提交
887 888 889
    taosMemoryFree(pRsp->metaRsp.metaRsp);
  } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__TAOSX_RSP) {
    SMqPollRspWrapper* pRsp = (SMqPollRspWrapper*)rspWrapper;
890 891
    taosMemoryFreeClear(pRsp->pEpset);

L
Liu Jicong 已提交
892 893 894 895 896 897 898 899
    taosArrayDestroyP(pRsp->taosxRsp.blockData, taosMemoryFree);
    taosArrayDestroy(pRsp->taosxRsp.blockDataLen);
    taosArrayDestroyP(pRsp->taosxRsp.blockTbName, taosMemoryFree);
    taosArrayDestroyP(pRsp->taosxRsp.blockSchema, (FDelete)tDeleteSSchemaWrapper);
    // taosx
    taosArrayDestroy(pRsp->taosxRsp.createTableLen);
    taosArrayDestroyP(pRsp->taosxRsp.createTableReq, taosMemoryFree);
  }
900 901

  return NULL;
L
Liu Jicong 已提交
902 903
}

L
Liu Jicong 已提交
904
void tmqClearUnhandleMsg(tmq_t* tmq) {
L
Liu Jicong 已提交
905
  SMqRspWrapper* rspWrapper = NULL;
L
Liu Jicong 已提交
906
  while (1) {
L
Liu Jicong 已提交
907 908 909 910 911
    taosGetQitem(tmq->qall, (void**)&rspWrapper);
    if (rspWrapper) {
      tmqFreeRspWrapper(rspWrapper);
      taosFreeQitem(rspWrapper);
    } else {
L
Liu Jicong 已提交
912
      break;
L
Liu Jicong 已提交
913
    }
L
Liu Jicong 已提交
914 915
  }

L
Liu Jicong 已提交
916
  rspWrapper = NULL;
L
Liu Jicong 已提交
917 918
  taosReadAllQitems(tmq->mqueue, tmq->qall);
  while (1) {
L
Liu Jicong 已提交
919 920 921 922 923
    taosGetQitem(tmq->qall, (void**)&rspWrapper);
    if (rspWrapper) {
      tmqFreeRspWrapper(rspWrapper);
      taosFreeQitem(rspWrapper);
    } else {
L
Liu Jicong 已提交
924
      break;
L
Liu Jicong 已提交
925
    }
L
Liu Jicong 已提交
926 927 928
  }
}

D
dapan1121 已提交
929
int32_t tmqSubscribeCb(void* param, SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
930 931
  SMqSubscribeCbParam* pParam = (SMqSubscribeCbParam*)param;
  pParam->rspErr = code;
dengyihao's avatar
dengyihao 已提交
932 933

  taosMemoryFree(pMsg->pEpSet);
L
Liu Jicong 已提交
934 935 936
  tsem_post(&pParam->rspSem);
  return 0;
}
937

L
Liu Jicong 已提交
938
int32_t tmq_subscription(tmq_t* tmq, tmq_list_t** topics) {
X
Xiaoyu Wang 已提交
939 940 941 942
  if (*topics == NULL) {
    *topics = tmq_list_new();
  }
  for (int i = 0; i < taosArrayGetSize(tmq->clientTopics); i++) {
L
Liu Jicong 已提交
943
    SMqClientTopic* topic = taosArrayGet(tmq->clientTopics, i);
L
Liu Jicong 已提交
944
    tmq_list_append(*topics, strchr(topic->topicName, '.') + 1);
X
Xiaoyu Wang 已提交
945
  }
L
Liu Jicong 已提交
946
  return 0;
X
Xiaoyu Wang 已提交
947 948
}

L
Liu Jicong 已提交
949
int32_t tmq_unsubscribe(tmq_t* tmq) {
L
Liu Jicong 已提交
950 951
  int32_t     rsp;
  int32_t     retryCnt = 0;
L
Liu Jicong 已提交
952
  tmq_list_t* lst = tmq_list_new();
L
Liu Jicong 已提交
953 954 955 956 957 958 959 960 961 962
  while (1) {
    rsp = tmq_subscribe(tmq, lst);
    if (rsp != TSDB_CODE_MND_CONSUMER_NOT_READY || retryCnt > 5) {
      break;
    } else {
      retryCnt++;
      taosMsleep(500);
    }
  }

L
Liu Jicong 已提交
963 964
  tmq_list_destroy(lst);
  return rsp;
X
Xiaoyu Wang 已提交
965 966
}

967 968 969 970 971 972
static void freeClientVgImpl(void* param) {
  SMqClientTopic* pTopic = param;
  taosMemoryFreeClear(pTopic->schema.pSchema);
  taosArrayDestroy(pTopic->vgs);
}

973
void tmqFreeImpl(void* handle) {
974 975
  tmq_t*  tmq = (tmq_t*)handle;
  int64_t id = tmq->consumerId;
L
Liu Jicong 已提交
976

977
  // TODO stop timer
L
Liu Jicong 已提交
978 979 980 981
  if (tmq->mqueue) {
    tmqClearUnhandleMsg(tmq);
    taosCloseQueue(tmq->mqueue);
  }
L
Liu Jicong 已提交
982

H
Haojun Liao 已提交
983 984 985 986 987
  if (tmq->delayedTask) {
    taosCloseQueue(tmq->delayedTask);
  }

  taosFreeQall(tmq->qall);
988
  tsem_destroy(&tmq->rspSem);
L
Liu Jicong 已提交
989

990
  taosArrayDestroyEx(tmq->clientTopics, freeClientVgImpl);
991 992
  taos_close_internal(tmq->pTscObj);
  taosMemoryFree(tmq);
993 994

  tscDebug("consumer:0x%" PRIx64 " closed", id);
L
Liu Jicong 已提交
995 996
}

997 998 999 1000 1001 1002 1003 1004 1005
static void tmqMgmtInit(void) {
  tmqInitRes = 0;
  tmqMgmt.timer = taosTmrInit(1000, 100, 360000, "TMQ");

  if (tmqMgmt.timer == NULL) {
    tmqInitRes = TSDB_CODE_OUT_OF_MEMORY;
  }

  tmqMgmt.rsetId = taosOpenRef(10000, tmqFreeImpl);
1006
  if (tmqMgmt.rsetId < 0) {
1007 1008 1009 1010
    tmqInitRes = terrno;
  }
}

L
Liu Jicong 已提交
1011
tmq_t* tmq_consumer_new(tmq_conf_t* conf, char* errstr, int32_t errstrLen) {
1012 1013 1014 1015
  taosThreadOnce(&tmqInit, tmqMgmtInit);
  if (tmqInitRes != 0) {
    terrno = tmqInitRes;
    return NULL;
L
Liu Jicong 已提交
1016 1017
  }

L
Liu Jicong 已提交
1018 1019
  tmq_t* pTmq = taosMemoryCalloc(1, sizeof(tmq_t));
  if (pTmq == NULL) {
L
Liu Jicong 已提交
1020
    terrno = TSDB_CODE_OUT_OF_MEMORY;
1021
    tscError("failed to create consumer, groupId:%s, code:%s", conf->groupId, terrstr());
L
Liu Jicong 已提交
1022 1023
    return NULL;
  }
L
Liu Jicong 已提交
1024

L
Liu Jicong 已提交
1025 1026 1027
  const char* user = conf->user == NULL ? TSDB_DEFAULT_USER : conf->user;
  const char* pass = conf->pass == NULL ? TSDB_DEFAULT_PASS : conf->pass;

L
Liu Jicong 已提交
1028 1029 1030
  pTmq->clientTopics = taosArrayInit(0, sizeof(SMqClientTopic));
  pTmq->mqueue = taosOpenQueue();
  pTmq->delayedTask = taosOpenQueue();
H
Haojun Liao 已提交
1031
  pTmq->qall = taosAllocateQall();
L
Liu Jicong 已提交
1032

X
Xiaoyu Wang 已提交
1033 1034
  if (pTmq->clientTopics == NULL || pTmq->mqueue == NULL || pTmq->qall == NULL || pTmq->delayedTask == NULL ||
      conf->groupId[0] == 0) {
L
Liu Jicong 已提交
1035
    terrno = TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1036
    tscError("consumer:0x%" PRIx64 " setup failed since %s, groupId:%s", pTmq->consumerId, terrstr(), pTmq->groupId);
1037
    goto _failed;
L
Liu Jicong 已提交
1038
  }
L
Liu Jicong 已提交
1039

L
Liu Jicong 已提交
1040 1041
  // init status
  pTmq->status = TMQ_CONSUMER_STATUS__INIT;
L
Liu Jicong 已提交
1042 1043
  pTmq->pollCnt = 0;
  pTmq->epoch = 0;
L
Liu Jicong 已提交
1044

L
Liu Jicong 已提交
1045 1046 1047
  // set conf
  strcpy(pTmq->clientId, conf->clientId);
  strcpy(pTmq->groupId, conf->groupId);
1048
  pTmq->withTbName = conf->withTbName;
L
Liu Jicong 已提交
1049
  pTmq->useSnapshot = conf->snapEnable;
L
Liu Jicong 已提交
1050
  pTmq->autoCommit = conf->autoCommit;
L
Liu Jicong 已提交
1051
  pTmq->autoCommitInterval = conf->autoCommitInterval;
L
Liu Jicong 已提交
1052 1053
  pTmq->commitCb = conf->commitCb;
  pTmq->commitCbUserParam = conf->commitCbUserParam;
L
Liu Jicong 已提交
1054 1055
  pTmq->resetOffsetCfg = conf->resetOffset;

1056 1057
  pTmq->hbBgEnable = conf->hbBgEnable;

L
Liu Jicong 已提交
1058
  // assign consumerId
L
Liu Jicong 已提交
1059
  pTmq->consumerId = tGenIdPI64();
X
Xiaoyu Wang 已提交
1060

L
Liu Jicong 已提交
1061 1062
  // init semaphore
  if (tsem_init(&pTmq->rspSem, 0, 0) != 0) {
1063
    tscError("consumer:0x %" PRIx64 " setup failed since %s, consumer group %s", pTmq->consumerId, terrstr(),
S
Shengliang Guan 已提交
1064
             pTmq->groupId);
1065
    goto _failed;
L
Liu Jicong 已提交
1066
  }
L
Liu Jicong 已提交
1067

L
Liu Jicong 已提交
1068 1069 1070
  // init connection
  pTmq->pTscObj = taos_connect_internal(conf->ip, user, pass, NULL, NULL, conf->port, CONN_TYPE__TMQ);
  if (pTmq->pTscObj == NULL) {
1071
    tscError("consumer:0x%" PRIx64 " setup failed since %s, groupId:%s", pTmq->consumerId, terrstr(), pTmq->groupId);
L
Liu Jicong 已提交
1072
    tsem_destroy(&pTmq->rspSem);
1073
    goto _failed;
L
Liu Jicong 已提交
1074
  }
L
Liu Jicong 已提交
1075

1076 1077
  pTmq->refId = taosAddRef(tmqMgmt.rsetId, pTmq);
  if (pTmq->refId < 0) {
1078
    goto _failed;
1079 1080
  }

1081
  if (pTmq->hbBgEnable) {
L
Liu Jicong 已提交
1082 1083
    int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t));
    *pRefId = pTmq->refId;
1084
    pTmq->hbLiveTimer = taosTmrStart(tmqSendHbReq, 1000, pRefId, tmqMgmt.timer);
1085 1086
  }

1087 1088 1089
  char         buf[80] = {0};
  STqOffsetVal offset = {.type = pTmq->resetOffsetCfg};
  tFormatOffset(buf, tListLen(buf), &offset);
X
Xiaoyu Wang 已提交
1090 1091 1092 1093
  tscInfo("consumer:0x%" PRIx64 " is setup, refId:%" PRId64
          ", groupId:%s, snapshot:%d, autoCommit:%d, commitInterval:%dms, offset:%s, backgroudHB:%d",
          pTmq->consumerId, pTmq->refId, pTmq->groupId, pTmq->useSnapshot, pTmq->autoCommit, pTmq->autoCommitInterval,
          buf, pTmq->hbBgEnable);
L
Liu Jicong 已提交
1094

1095
  return pTmq;
1096

1097 1098
_failed:
  tmqFreeImpl(pTmq);
L
Liu Jicong 已提交
1099
  return NULL;
1100 1101
}

L
Liu Jicong 已提交
1102
int32_t tmq_subscribe(tmq_t* tmq, const tmq_list_t* topic_list) {
1103
  const int32_t   MAX_RETRY_COUNT = 120 * 2;  // let's wait for 2 mins at most
L
Liu Jicong 已提交
1104 1105 1106
  const SArray*   container = &topic_list->container;
  int32_t         sz = taosArrayGetSize(container);
  void*           buf = NULL;
L
Liu Jicong 已提交
1107
  SMsgSendInfo*   sendInfo = NULL;
L
Liu Jicong 已提交
1108
  SCMSubscribeReq req = {0};
1109
  int32_t         code = 0;
1110

1111
  tscDebug("consumer:0x%" PRIx64 " cgroup:%s, subscribe %d topics", tmq->consumerId, tmq->groupId, sz);
L
Liu Jicong 已提交
1112

1113
  req.consumerId = tmq->consumerId;
L
Liu Jicong 已提交
1114
  tstrncpy(req.clientId, tmq->clientId, 256);
L
Liu Jicong 已提交
1115
  tstrncpy(req.cgroup, tmq->groupId, TSDB_CGROUP_LEN);
1116 1117
  req.topicNames = taosArrayInit(sz, sizeof(void*));

1118 1119 1120 1121
  if (req.topicNames == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto FAIL;
  }
1122

L
Liu Jicong 已提交
1123 1124
  for (int32_t i = 0; i < sz; i++) {
    char* topic = taosArrayGetP(container, i);
1125 1126

    SName name = {0};
L
Liu Jicong 已提交
1127 1128 1129 1130
    tNameSetDbName(&name, tmq->pTscObj->acctId, topic, strlen(topic));
    char* topicFName = taosMemoryCalloc(1, TSDB_TOPIC_FNAME_LEN);
    if (topicFName == NULL) {
      goto FAIL;
1131 1132
    }

1133
    tNameExtractFullName(&name, topicFName);
X
Xiaoyu Wang 已提交
1134
    tscDebug("consumer:0x%" PRIx64 " subscribe topic:%s", tmq->consumerId, topicFName);
L
Liu Jicong 已提交
1135 1136

    taosArrayPush(req.topicNames, &topicFName);
1137 1138
  }

L
Liu Jicong 已提交
1139
  int32_t tlen = tSerializeSCMSubscribeReq(NULL, &req);
1140

L
Liu Jicong 已提交
1141
  buf = taosMemoryMalloc(tlen);
1142 1143 1144 1145
  if (buf == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto FAIL;
  }
L
Liu Jicong 已提交
1146

1147 1148 1149
  void* abuf = buf;
  tSerializeSCMSubscribeReq(&abuf, &req);

L
Liu Jicong 已提交
1150
  sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
1151 1152 1153 1154
  if (sendInfo == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto FAIL;
  }
1155

X
Xiaoyu Wang 已提交
1156
  SMqSubscribeCbParam param = {
L
Liu Jicong 已提交
1157
      .rspErr = 0,
1158 1159
      .refId = tmq->refId,
      .epoch = tmq->epoch,
X
Xiaoyu Wang 已提交
1160
  };
L
Liu Jicong 已提交
1161

1162
  if (tsem_init(&param.rspSem, 0, 0) != 0) {
wmmhello's avatar
wmmhello 已提交
1163
    code = TSDB_CODE_TSC_INTERNAL_ERROR;
1164 1165
    goto FAIL;
  }
L
Liu Jicong 已提交
1166 1167

  sendInfo->msgInfo = (SDataBuf){
X
Xiaoyu Wang 已提交
1168 1169 1170 1171
      .pData = buf,
      .len = tlen,
      .handle = NULL,
  };
1172

L
Liu Jicong 已提交
1173 1174
  sendInfo->requestId = generateRequestId();
  sendInfo->requestObjRefId = 0;
L
Liu Jicong 已提交
1175 1176
  sendInfo->param = &param;
  sendInfo->fp = tmqSubscribeCb;
L
Liu Jicong 已提交
1177
  sendInfo->msgType = TDMT_MND_TMQ_SUBSCRIBE;
L
Liu Jicong 已提交
1178

1179 1180 1181 1182 1183
  SEpSet epSet = getEpSet_s(&tmq->pTscObj->pAppInfo->mgmtEp);

  int64_t transporterId = 0;
  asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, sendInfo);

L
Liu Jicong 已提交
1184 1185
  // avoid double free if msg is sent
  buf = NULL;
L
Liu Jicong 已提交
1186
  sendInfo = NULL;
L
Liu Jicong 已提交
1187

L
Liu Jicong 已提交
1188 1189
  tsem_wait(&param.rspSem);
  tsem_destroy(&param.rspSem);
1190

1191 1192 1193 1194
  if (param.rspErr != 0) {
    code = param.rspErr;
    goto FAIL;
  }
L
Liu Jicong 已提交
1195

L
Liu Jicong 已提交
1196
  int32_t retryCnt = 0;
1197
  while (TSDB_CODE_MND_CONSUMER_NOT_READY == doAskEp(tmq)) {
1198
    if (retryCnt++ > MAX_RETRY_COUNT) {
wmmhello's avatar
wmmhello 已提交
1199 1200
      tscError("consumer:0x%" PRIx64 ", mnd not ready for subscribe, retry:%d in 500ms", tmq->consumerId, retryCnt);
      code = TSDB_CODE_TSC_INTERNAL_ERROR;
L
Liu Jicong 已提交
1201 1202
      goto FAIL;
    }
1203

X
Xiaoyu Wang 已提交
1204
    tscDebug("consumer:0x%" PRIx64 ", mnd not ready for subscribe, retry:%d in 500ms", tmq->consumerId, retryCnt);
L
Liu Jicong 已提交
1205 1206
    taosMsleep(500);
  }
1207

1208 1209
  // init ep timer
  if (tmq->epTimer == NULL) {
1210 1211 1212
    int64_t* pRefId1 = taosMemoryMalloc(sizeof(int64_t));
    *pRefId1 = tmq->refId;
    tmq->epTimer = taosTmrStart(tmqAssignAskEpTask, 1000, pRefId1, tmqMgmt.timer);
1213
  }
L
Liu Jicong 已提交
1214 1215

  // init auto commit timer
1216
  if (tmq->autoCommit && tmq->commitTimer == NULL) {
1217 1218 1219
    int64_t* pRefId2 = taosMemoryMalloc(sizeof(int64_t));
    *pRefId2 = tmq->refId;
    tmq->commitTimer = taosTmrStart(tmqAssignDelayedCommitTask, tmq->autoCommitInterval, pRefId2, tmqMgmt.timer);
L
Liu Jicong 已提交
1220 1221
  }

L
Liu Jicong 已提交
1222
FAIL:
L
Liu Jicong 已提交
1223
  taosArrayDestroyP(req.topicNames, taosMemoryFree);
L
Liu Jicong 已提交
1224
  taosMemoryFree(buf);
L
Liu Jicong 已提交
1225
  taosMemoryFree(sendInfo);
L
Liu Jicong 已提交
1226

L
Liu Jicong 已提交
1227
  return code;
1228 1229
}

L
Liu Jicong 已提交
1230
void tmq_conf_set_auto_commit_cb(tmq_conf_t* conf, tmq_commit_cb* cb, void* param) {
1231
  conf->commitCb = cb;
L
Liu Jicong 已提交
1232
  conf->commitCbUserParam = param;
L
Liu Jicong 已提交
1233
}
1234

D
dapan1121 已提交
1235
int32_t tmqPollCb(void* param, SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
1236
  SMqPollCbParam* pParam = (SMqPollCbParam*)param;
1237 1238

  int64_t         refId = pParam->refId;
X
Xiaoyu Wang 已提交
1239
  SMqClientVg*    pVg = pParam->pVg;
L
Liu Jicong 已提交
1240
  SMqClientTopic* pTopic = pParam->pTopic;
1241

1242
  tmq_t* tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
1243 1244 1245
  if (tmq == NULL) {
    taosMemoryFree(pParam);
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1246
    taosMemoryFree(pMsg->pEpSet);
1247 1248 1249 1250
    terrno = TSDB_CODE_TMQ_CONSUMER_CLOSED;
    return -1;
  }

H
Haojun Liao 已提交
1251 1252 1253 1254
  int32_t  epoch = pParam->epoch;
  int32_t  vgId = pParam->vgId;
  uint64_t requestId = pParam->requestId;

L
Liu Jicong 已提交
1255
  taosMemoryFree(pParam);
H
Haojun Liao 已提交
1256

L
Liu Jicong 已提交
1257
  if (code != 0) {
H
Haojun Liao 已提交
1258 1259
    tscWarn("consumer:0x%" PRIx64 " msg from vgId:%d discarded, epoch %d, since %s, reqId:0x%" PRIx64, tmq->consumerId,
            vgId, epoch, tstrerror(code), requestId);
H
Haojun Liao 已提交
1260

L
Liu Jicong 已提交
1261
    if (pMsg->pData) taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1262 1263
    if (pMsg->pEpSet) taosMemoryFree(pMsg->pEpSet);

H
Haojun Liao 已提交
1264
    // in case of consumer mismatch, wait for 500ms and retry
L
Liu Jicong 已提交
1265
    if (code == TSDB_CODE_TMQ_CONSUMER_MISMATCH) {
1266
      taosMsleep(500);
L
Liu Jicong 已提交
1267
      atomic_store_8(&tmq->status, TMQ_CONSUMER_STATUS__RECOVER);
X
Xiaoyu Wang 已提交
1268 1269
      tscDebug("consumer:0x%" PRIx64 " wait for the re-balance, wait for 500ms and set status to be RECOVER",
               tmq->consumerId);
H
Haojun Liao 已提交
1270
    } else if (code == TSDB_CODE_TQ_NO_COMMITTED_OFFSET) {
S
Shengliang Guan 已提交
1271
      SMqPollRspWrapper* pRspWrapper = taosAllocateQitem(sizeof(SMqPollRspWrapper), DEF_QITEM, 0);
L
Liu Jicong 已提交
1272
      if (pRspWrapper == NULL) {
H
Haojun Liao 已提交
1273 1274
        tscWarn("consumer:0x%" PRIx64 " msg from vgId:%d discarded, epoch %d since out of memory, reqId:0x%" PRIx64,
                tmq->consumerId, vgId, epoch, requestId);
L
Liu Jicong 已提交
1275 1276
        goto CREATE_MSG_FAIL;
      }
H
Haojun Liao 已提交
1277

L
Liu Jicong 已提交
1278 1279
      pRspWrapper->tmqRspType = TMQ_MSG_TYPE__END_RSP;
      taosWriteQitem(tmq->mqueue, pRspWrapper);
X
Xiaoyu Wang 已提交
1280
    } else if (code == TSDB_CODE_WAL_LOG_NOT_EXIST) {  // poll data while insert
1281
      taosMsleep(500);
L
Liu Jicong 已提交
1282
    }
H
Haojun Liao 已提交
1283

L
fix txn  
Liu Jicong 已提交
1284
    goto CREATE_MSG_FAIL;
L
Liu Jicong 已提交
1285 1286
  }

X
Xiaoyu Wang 已提交
1287 1288 1289
  int32_t msgEpoch = ((SMqRspHead*)pMsg->pData)->epoch;
  int32_t tmqEpoch = atomic_load_32(&tmq->epoch);
  if (msgEpoch < tmqEpoch) {
L
Liu Jicong 已提交
1290
    // do not write into queue since updating epoch reset
X
Xiaoyu Wang 已提交
1291 1292
    tscWarn("consumer:0x%" PRIx64
            " msg discard from vgId:%d since from earlier epoch, rsp epoch %d, current epoch %d, reqId:0x%" PRIx64,
H
Haojun Liao 已提交
1293 1294
            tmq->consumerId, vgId, msgEpoch, tmqEpoch, requestId);

1295
    tsem_post(&tmq->rspSem);
1296 1297
    taosReleaseRef(tmqMgmt.rsetId, refId);

L
Liu Jicong 已提交
1298
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1299
    taosMemoryFree(pMsg->pEpSet);
X
Xiaoyu Wang 已提交
1300 1301 1302 1303
    return 0;
  }

  if (msgEpoch != tmqEpoch) {
H
Haojun Liao 已提交
1304 1305
    tscWarn("consumer:0x%" PRIx64 " mismatch rsp from vgId:%d, epoch %d, current epoch %d, reqId:0x%" PRIx64,
            tmq->consumerId, vgId, msgEpoch, tmqEpoch, requestId);
X
Xiaoyu Wang 已提交
1306 1307
  }

L
Liu Jicong 已提交
1308 1309 1310
  // handle meta rsp
  int8_t rspType = ((SMqRspHead*)pMsg->pData)->mqMsgType;

S
Shengliang Guan 已提交
1311
  SMqPollRspWrapper* pRspWrapper = taosAllocateQitem(sizeof(SMqPollRspWrapper), DEF_QITEM, 0);
L
Liu Jicong 已提交
1312
  if (pRspWrapper == NULL) {
L
Liu Jicong 已提交
1313
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1314
    taosMemoryFree(pMsg->pEpSet);
X
Xiaoyu Wang 已提交
1315 1316
    tscWarn("consumer:0x%" PRIx64 " msg discard from vgId:%d, epoch %d since out of memory", tmq->consumerId, vgId,
            epoch);
L
fix txn  
Liu Jicong 已提交
1317
    goto CREATE_MSG_FAIL;
L
Liu Jicong 已提交
1318
  }
L
Liu Jicong 已提交
1319

L
Liu Jicong 已提交
1320
  pRspWrapper->tmqRspType = rspType;
L
Liu Jicong 已提交
1321 1322
  pRspWrapper->vgHandle = pVg;
  pRspWrapper->topicHandle = pTopic;
H
Haojun Liao 已提交
1323
  pRspWrapper->reqId = requestId;
1324
  pRspWrapper->pEpset = pMsg->pEpSet;
1325
  pRspWrapper->vgId = pVg->vgId;
L
Liu Jicong 已提交
1326

1327
  pMsg->pEpSet = NULL;
L
Liu Jicong 已提交
1328
  if (rspType == TMQ_MSG_TYPE__POLL_RSP) {
L
Liu Jicong 已提交
1329 1330 1331
    SDecoder decoder;
    tDecoderInit(&decoder, POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), pMsg->len - sizeof(SMqRspHead));
    tDecodeSMqDataRsp(&decoder, &pRspWrapper->dataRsp);
wmmhello's avatar
wmmhello 已提交
1332
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1333
    memcpy(&pRspWrapper->dataRsp, pMsg->pData, sizeof(SMqRspHead));
L
Liu Jicong 已提交
1334

H
Haojun Liao 已提交
1335 1336
    char buf[80];
    tFormatOffset(buf, 80, &pRspWrapper->dataRsp.rspOffset);
H
Haojun Liao 已提交
1337
    tscDebug("consumer:0x%" PRIx64 " recv poll rsp, vgId:%d, req ver:%" PRId64 ", rsp:%s type %d, reqId:0x%" PRIx64,
H
Haojun Liao 已提交
1338
             tmq->consumerId, vgId, pRspWrapper->dataRsp.reqOffset.version, buf, rspType, requestId);
L
Liu Jicong 已提交
1339
  } else if (rspType == TMQ_MSG_TYPE__POLL_META_RSP) {
1340 1341 1342 1343
    SDecoder decoder;
    tDecoderInit(&decoder, POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), pMsg->len - sizeof(SMqRspHead));
    tDecodeSMqMetaRsp(&decoder, &pRspWrapper->metaRsp);
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1344
    memcpy(&pRspWrapper->metaRsp, pMsg->pData, sizeof(SMqRspHead));
L
Liu Jicong 已提交
1345 1346 1347 1348 1349 1350
  } else if (rspType == TMQ_MSG_TYPE__TAOSX_RSP) {
    SDecoder decoder;
    tDecoderInit(&decoder, POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), pMsg->len - sizeof(SMqRspHead));
    tDecodeSTaosxRsp(&decoder, &pRspWrapper->taosxRsp);
    tDecoderClear(&decoder);
    memcpy(&pRspWrapper->taosxRsp, pMsg->pData, sizeof(SMqRspHead));
X
Xiaoyu Wang 已提交
1351 1352
  } else {  // invalid rspType
    tscError("consumer:0x%" PRIx64 " invalid rsp msg received, type:%d ignored", tmq->consumerId, rspType);
L
Liu Jicong 已提交
1353
  }
L
Liu Jicong 已提交
1354

L
Liu Jicong 已提交
1355
  taosMemoryFree(pMsg->pData);
H
Haojun Liao 已提交
1356
  taosWriteQitem(tmq->mqueue, pRspWrapper);
L
Liu Jicong 已提交
1357

1358
  int32_t total = taosQueueItemSize(tmq->mqueue);
H
Haojun Liao 已提交
1359
  tscDebug("consumer:0x%" PRIx64 " put poll res into mqueue, type:%d, vgId:%d, total in queue:%d, reqId:0x%" PRIx64,
1360
           tmq->consumerId, rspType, vgId, total, requestId);
H
Haojun Liao 已提交
1361

1362
  tsem_post(&tmq->rspSem);
1363 1364
  taosReleaseRef(tmqMgmt.rsetId, refId);

L
Liu Jicong 已提交
1365
  return 0;
H
Haojun Liao 已提交
1366

L
fix txn  
Liu Jicong 已提交
1367
CREATE_MSG_FAIL:
L
Liu Jicong 已提交
1368
  if (epoch == tmq->epoch) {
L
Liu Jicong 已提交
1369 1370
    atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
  }
H
Haojun Liao 已提交
1371

1372
  tsem_post(&tmq->rspSem);
1373 1374
  taosReleaseRef(tmqMgmt.rsetId, refId);

L
Liu Jicong 已提交
1375
  return -1;
1376 1377
}

H
Haojun Liao 已提交
1378 1379 1380 1381 1382
typedef struct SVgroupSaveInfo {
  STqOffsetVal offset;
  int64_t      numOfRows;
} SVgroupSaveInfo;

H
Haojun Liao 已提交
1383 1384 1385 1386 1387 1388
static void initClientTopicFromRsp(SMqClientTopic* pTopic, SMqSubTopicEp* pTopicEp, SHashObj* pVgOffsetHashMap,
                                   tmq_t* tmq) {
  pTopic->schema = pTopicEp->schema;
  pTopicEp->schema.nCols = 0;
  pTopicEp->schema.pSchema = NULL;

X
Xiaoyu Wang 已提交
1389
  char    vgKey[TSDB_TOPIC_FNAME_LEN + 22];
H
Haojun Liao 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  int32_t vgNumGet = taosArrayGetSize(pTopicEp->vgs);

  tstrncpy(pTopic->topicName, pTopicEp->topic, TSDB_TOPIC_FNAME_LEN);
  tstrncpy(pTopic->db, pTopicEp->db, TSDB_DB_FNAME_LEN);

  tscDebug("consumer:0x%" PRIx64 ", update topic:%s, numOfVgs:%d", tmq->consumerId, pTopic->topicName, vgNumGet);
  pTopic->vgs = taosArrayInit(vgNumGet, sizeof(SMqClientVg));

  for (int32_t j = 0; j < vgNumGet; j++) {
    SMqSubVgEp* pVgEp = taosArrayGet(pTopicEp->vgs, j);
H
Haojun Liao 已提交
1400 1401

    makeTopicVgroupKey(vgKey, pTopic->topicName, pVgEp->vgId);
H
Haojun Liao 已提交
1402
    SVgroupSaveInfo* pInfo = taosHashGet(pVgOffsetHashMap, vgKey, strlen(vgKey));
H
Haojun Liao 已提交
1403

X
Xiaoyu Wang 已提交
1404 1405
    int64_t      numOfRows = 0;
    STqOffsetVal offsetNew = {.type = tmq->resetOffsetCfg};
H
Haojun Liao 已提交
1406 1407 1408
    if (pInfo != NULL) {
      offsetNew = pInfo->offset;
      numOfRows = pInfo->numOfRows;
H
Haojun Liao 已提交
1409 1410 1411 1412 1413 1414 1415 1416
    }

    SMqClientVg clientVg = {
        .pollCnt = 0,
        .vgId = pVgEp->vgId,
        .epSet = pVgEp->epSet,
        .vgStatus = TMQ_VG_STATUS__IDLE,
        .vgSkipCnt = 0,
H
Haojun Liao 已提交
1417
        .emptyBlockReceiveTs = 0,
H
Haojun Liao 已提交
1418
        .numOfRows = numOfRows,
H
Haojun Liao 已提交
1419 1420
    };

H
Haojun Liao 已提交
1421 1422 1423 1424
    clientVg.offsetInfo.currentOffset = offsetNew;
    clientVg.offsetInfo.committedOffset = offsetNew;
    clientVg.offsetInfo.walVerBegin = -1;
    clientVg.offsetInfo.walVerEnd = -1;
H
Haojun Liao 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    taosArrayPush(pTopic->vgs, &clientVg);
  }
}

static void freeClientVgInfo(void* param) {
  SMqClientTopic* pTopic = param;
  if (pTopic->schema.nCols) {
    taosMemoryFreeClear(pTopic->schema.pSchema);
  }

  taosArrayDestroy(pTopic->vgs);
}

1438
static bool doUpdateLocalEp(tmq_t* tmq, int32_t epoch, const SMqAskEpRsp* pRsp) {
1439 1440
  bool set = false;

1441
  int32_t topicNumCur = taosArrayGetSize(tmq->clientTopics);
1442
  int32_t topicNumGet = taosArrayGetSize(pRsp->topics);
1443

X
Xiaoyu Wang 已提交
1444 1445
  char vgKey[TSDB_TOPIC_FNAME_LEN + 22];
  tscDebug("consumer:0x%" PRIx64 " update ep epoch from %d to epoch %d, incoming topics:%d, existed topics:%d",
1446
           tmq->consumerId, tmq->epoch, epoch, topicNumGet, topicNumCur);
wmmhello's avatar
wmmhello 已提交
1447 1448 1449
  if (epoch <= tmq->epoch) {
    return false;
  }
1450 1451 1452 1453 1454 1455

  SArray* newTopics = taosArrayInit(topicNumGet, sizeof(SMqClientTopic));
  if (newTopics == NULL) {
    return false;
  }

H
Haojun Liao 已提交
1456 1457
  SHashObj* pVgOffsetHashMap = taosHashInit(64, MurmurHash3_32, false, HASH_NO_LOCK);
  if (pVgOffsetHashMap == NULL) {
1458 1459 1460
    taosArrayDestroy(newTopics);
    return false;
  }
1461

H
Haojun Liao 已提交
1462
  // todo extract method
1463 1464 1465 1466 1467
  for (int32_t i = 0; i < topicNumCur; i++) {
    // find old topic
    SMqClientTopic* pTopicCur = taosArrayGet(tmq->clientTopics, i);
    if (pTopicCur->vgs) {
      int32_t vgNumCur = taosArrayGetSize(pTopicCur->vgs);
1468
      tscDebug("consumer:0x%" PRIx64 ", new vg num: %d", tmq->consumerId, vgNumCur);
1469 1470
      for (int32_t j = 0; j < vgNumCur; j++) {
        SMqClientVg* pVgCur = taosArrayGet(pTopicCur->vgs, j);
H
Haojun Liao 已提交
1471 1472
        makeTopicVgroupKey(vgKey, pTopicCur->topicName, pVgCur->vgId);

L
Liu Jicong 已提交
1473
        char buf[80];
H
Haojun Liao 已提交
1474
        tFormatOffset(buf, 80, &pVgCur->offsetInfo.currentOffset);
X
Xiaoyu Wang 已提交
1475 1476
        tscDebug("consumer:0x%" PRIx64 ", epoch:%d vgId:%d vgKey:%s, offset:%s", tmq->consumerId, epoch, pVgCur->vgId,
                 vgKey, buf);
H
Haojun Liao 已提交
1477

H
Haojun Liao 已提交
1478
        SVgroupSaveInfo info = {.offset = pVgCur->offsetInfo.currentOffset, .numOfRows = pVgCur->numOfRows};
H
Haojun Liao 已提交
1479
        taosHashPut(pVgOffsetHashMap, vgKey, strlen(vgKey), &info, sizeof(SVgroupSaveInfo));
1480 1481 1482 1483 1484 1485 1486
      }
    }
  }

  for (int32_t i = 0; i < topicNumGet; i++) {
    SMqClientTopic topic = {0};
    SMqSubTopicEp* pTopicEp = taosArrayGet(pRsp->topics, i);
H
Haojun Liao 已提交
1487
    initClientTopicFromRsp(&topic, pTopicEp, pVgOffsetHashMap, tmq);
1488 1489
    taosArrayPush(newTopics, &topic);
  }
1490

H
Haojun Liao 已提交
1491 1492
  taosHashCleanup(pVgOffsetHashMap);

1493
  // destroy current buffered existed topics info
1494
  if (tmq->clientTopics) {
H
Haojun Liao 已提交
1495
    taosArrayDestroyEx(tmq->clientTopics, freeClientVgInfo);
X
Xiaoyu Wang 已提交
1496
  }
H
Haojun Liao 已提交
1497
  tmq->clientTopics = newTopics;
1498

X
Xiaoyu Wang 已提交
1499
  int8_t flag = (topicNumGet == 0) ? TMQ_CONSUMER_STATUS__NO_TOPIC : TMQ_CONSUMER_STATUS__READY;
H
Haojun Liao 已提交
1500
  atomic_store_8(&tmq->status, flag);
X
Xiaoyu Wang 已提交
1501
  atomic_store_32(&tmq->epoch, epoch);
H
Haojun Liao 已提交
1502

1503
  tscDebug("consumer:0x%" PRIx64 " update topic info completed", tmq->consumerId);
X
Xiaoyu Wang 已提交
1504 1505 1506
  return set;
}

1507
int32_t askEpCallbackFn(void* param, SDataBuf* pMsg, int32_t code) {
1508
  SMqAskEpCbParam* pParam = (SMqAskEpCbParam*)param;
1509 1510 1511
  tmq_t*           tmq = taosAcquireRef(tmqMgmt.rsetId, pParam->refId);

  if (tmq == NULL) {
1512 1513 1514
    terrno = TSDB_CODE_TMQ_CONSUMER_CLOSED;
    pParam->pUserFn(tmq, terrno, NULL, pParam->pParam);

1515
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1516
    taosMemoryFree(pMsg->pEpSet);
1517 1518
    taosMemoryFree(pParam);
    return terrno;
1519 1520
  }

H
Haojun Liao 已提交
1521
  if (code != TSDB_CODE_SUCCESS) {
1522 1523 1524 1525 1526 1527 1528 1529 1530
    tscError("consumer:0x%" PRIx64 ", get topic endpoint error, code:%s", tmq->consumerId, tstrerror(code));
    pParam->pUserFn(tmq, code, NULL, pParam->pParam);

    taosReleaseRef(tmqMgmt.rsetId, pParam->refId);

    taosMemoryFree(pMsg->pData);
    taosMemoryFree(pMsg->pEpSet);
    taosMemoryFree(pParam);
    return code;
1531
  }
L
Liu Jicong 已提交
1532

L
Liu Jicong 已提交
1533
  // tmq's epoch is monotonically increase,
L
Liu Jicong 已提交
1534
  // so it's safe to discard any old epoch msg.
L
Liu Jicong 已提交
1535
  // Epoch will only increase when received newer epoch ep msg
L
Liu Jicong 已提交
1536 1537 1538
  SMqRspHead* head = pMsg->pData;
  int32_t     epoch = atomic_load_32(&tmq->epoch);
  if (head->epoch <= epoch) {
1539 1540
    tscDebug("consumer:0x%" PRIx64 ", recv ep, msg epoch %d, current epoch %d, no need to update local ep",
             tmq->consumerId, head->epoch, epoch);
1541

1542 1543 1544 1545 1546 1547 1548 1549
    if (tmq->status == TMQ_CONSUMER_STATUS__RECOVER) {
      SMqAskEpRsp rsp;
      tDecodeSMqAskEpRsp(POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), &rsp);
      int8_t flag = (taosArrayGetSize(rsp.topics) == 0) ? TMQ_CONSUMER_STATUS__NO_TOPIC : TMQ_CONSUMER_STATUS__READY;
      atomic_store_8(&tmq->status, flag);
      tDeleteSMqAskEpRsp(&rsp);
    }

X
Xiaoyu Wang 已提交
1550
  } else {
1551 1552
    tscDebug("consumer:0x%" PRIx64 ", recv ep, msg epoch %d, current epoch %d, update local ep", tmq->consumerId,
             head->epoch, epoch);
1553
  }
wmmhello's avatar
wmmhello 已提交
1554
  pParam->pUserFn(tmq, code, pMsg, pParam->pParam);
L
Liu Jicong 已提交
1555

1556 1557
  taosReleaseRef(tmqMgmt.rsetId, pParam->refId);

dengyihao's avatar
dengyihao 已提交
1558
  taosMemoryFree(pMsg->pEpSet);
L
Liu Jicong 已提交
1559
  taosMemoryFree(pMsg->pData);
1560
  taosMemoryFree(pParam);
L
Liu Jicong 已提交
1561
  return code;
1562 1563
}

L
Liu Jicong 已提交
1564
void tmqBuildConsumeReqImpl(SMqPollReq* pReq, tmq_t* tmq, int64_t timeout, SMqClientTopic* pTopic, SMqClientVg* pVg) {
L
Liu Jicong 已提交
1565 1566 1567 1568
  int32_t groupLen = strlen(tmq->groupId);
  memcpy(pReq->subKey, tmq->groupId, groupLen);
  pReq->subKey[groupLen] = TMQ_SEPARATOR;
  strcpy(pReq->subKey + groupLen + 1, pTopic->topicName);
1569

1570
  pReq->withTbName = tmq->withTbName;
L
Liu Jicong 已提交
1571
  pReq->consumerId = tmq->consumerId;
1572
  pReq->timeout = timeout;
X
Xiaoyu Wang 已提交
1573
  pReq->epoch = tmq->epoch;
H
Haojun Liao 已提交
1574
  pReq->reqOffset = pVg->offsetInfo.currentOffset;
D
dapan1121 已提交
1575
  pReq->head.vgId = pVg->vgId;
1576 1577
  pReq->useSnapshot = tmq->useSnapshot;
  pReq->reqId = generateRequestId();
1578 1579
}

L
Liu Jicong 已提交
1580 1581
SMqMetaRspObj* tmqBuildMetaRspFromWrapper(SMqPollRspWrapper* pWrapper) {
  SMqMetaRspObj* pRspObj = taosMemoryCalloc(1, sizeof(SMqMetaRspObj));
L
Liu Jicong 已提交
1582
  pRspObj->resType = RES_TYPE__TMQ_META;
L
Liu Jicong 已提交
1583 1584 1585 1586 1587 1588 1589 1590
  tstrncpy(pRspObj->topic, pWrapper->topicHandle->topicName, TSDB_TOPIC_FNAME_LEN);
  tstrncpy(pRspObj->db, pWrapper->topicHandle->db, TSDB_DB_FNAME_LEN);
  pRspObj->vgId = pWrapper->vgHandle->vgId;

  memcpy(&pRspObj->metaRsp, &pWrapper->metaRsp, sizeof(SMqMetaRsp));
  return pRspObj;
}

1591
SMqRspObj* tmqBuildRspFromWrapper(SMqPollRspWrapper* pWrapper, SMqClientVg* pVg, int64_t* numOfRows) {
L
Liu Jicong 已提交
1592 1593
  SMqRspObj* pRspObj = taosMemoryCalloc(1, sizeof(SMqRspObj));
  pRspObj->resType = RES_TYPE__TMQ;
1594

1595
  (*numOfRows) = 0;
L
Liu Jicong 已提交
1596 1597
  tstrncpy(pRspObj->topic, pWrapper->topicHandle->topicName, TSDB_TOPIC_FNAME_LEN);
  tstrncpy(pRspObj->db, pWrapper->topicHandle->db, TSDB_DB_FNAME_LEN);
1598

L
Liu Jicong 已提交
1599
  pRspObj->vgId = pWrapper->vgHandle->vgId;
L
Liu Jicong 已提交
1600
  pRspObj->resIter = -1;
L
Liu Jicong 已提交
1601
  memcpy(&pRspObj->rsp, &pWrapper->dataRsp, sizeof(SMqDataRsp));
L
Liu Jicong 已提交
1602

L
Liu Jicong 已提交
1603 1604
  pRspObj->resInfo.totalRows = 0;
  pRspObj->resInfo.precision = TSDB_TIME_PRECISION_MILLI;
1605

L
Liu Jicong 已提交
1606
  if (!pWrapper->dataRsp.withSchema) {
L
Liu Jicong 已提交
1607 1608
    setResSchemaInfo(&pRspObj->resInfo, pWrapper->topicHandle->schema.pSchema, pWrapper->topicHandle->schema.nCols);
  }
L
Liu Jicong 已提交
1609

1610
  // extract the rows in this data packet
X
Xiaoyu Wang 已提交
1611
  for (int32_t i = 0; i < pRspObj->rsp.blockNum; ++i) {
1612
    SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)taosArrayGetP(pRspObj->rsp.blockData, i);
X
Xiaoyu Wang 已提交
1613
    int64_t            rows = htobe64(pRetrieve->numOfRows);
1614
    pVg->numOfRows += rows;
1615
    (*numOfRows) += rows;
1616 1617
  }

L
Liu Jicong 已提交
1618
  return pRspObj;
X
Xiaoyu Wang 已提交
1619 1620
}

L
Liu Jicong 已提交
1621 1622
SMqTaosxRspObj* tmqBuildTaosxRspFromWrapper(SMqPollRspWrapper* pWrapper) {
  SMqTaosxRspObj* pRspObj = taosMemoryCalloc(1, sizeof(SMqTaosxRspObj));
1623
  pRspObj->resType = RES_TYPE__TMQ_METADATA;
L
Liu Jicong 已提交
1624 1625 1626 1627
  tstrncpy(pRspObj->topic, pWrapper->topicHandle->topicName, TSDB_TOPIC_FNAME_LEN);
  tstrncpy(pRspObj->db, pWrapper->topicHandle->db, TSDB_DB_FNAME_LEN);
  pRspObj->vgId = pWrapper->vgHandle->vgId;
  pRspObj->resIter = -1;
1628
  memcpy(&pRspObj->rsp, &pWrapper->taosxRsp, sizeof(STaosxRsp));
L
Liu Jicong 已提交
1629 1630 1631

  pRspObj->resInfo.totalRows = 0;
  pRspObj->resInfo.precision = TSDB_TIME_PRECISION_MILLI;
1632
  if (!pWrapper->taosxRsp.withSchema) {
L
Liu Jicong 已提交
1633 1634 1635 1636 1637 1638
    setResSchemaInfo(&pRspObj->resInfo, pWrapper->topicHandle->schema.pSchema, pWrapper->topicHandle->schema.nCols);
  }

  return pRspObj;
}

1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
static int32_t handleErrorBeforePoll(SMqClientVg* pVg, tmq_t* pTmq) {
  atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
  tsem_post(&pTmq->rspSem);
  return -1;
}

static int32_t doTmqPollImpl(tmq_t* pTmq, SMqClientTopic* pTopic, SMqClientVg* pVg, int64_t timeout) {
  SMqPollReq req = {0};
  tmqBuildConsumeReqImpl(&req, pTmq, timeout, pTopic, pVg);

  int32_t msgSize = tSerializeSMqPollReq(NULL, 0, &req);
  if (msgSize < 0) {
    return handleErrorBeforePoll(pVg, pTmq);
  }

  char* msg = taosMemoryCalloc(1, msgSize);
  if (NULL == msg) {
    return handleErrorBeforePoll(pVg, pTmq);
  }

  if (tSerializeSMqPollReq(msg, msgSize, &req) < 0) {
    taosMemoryFree(msg);
    return handleErrorBeforePoll(pVg, pTmq);
  }

  SMqPollCbParam* pParam = taosMemoryMalloc(sizeof(SMqPollCbParam));
  if (pParam == NULL) {
    taosMemoryFree(msg);
    return handleErrorBeforePoll(pVg, pTmq);
  }

  pParam->refId = pTmq->refId;
  pParam->epoch = pTmq->epoch;
H
Haojun Liao 已提交
1672
  pParam->pVg = pVg;
1673 1674
  pParam->pTopic = pTopic;
  pParam->vgId = pVg->vgId;
H
Haojun Liao 已提交
1675
  pParam->requestId = req.reqId;
1676 1677 1678 1679 1680 1681 1682 1683

  SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
  if (sendInfo == NULL) {
    taosMemoryFree(pParam);
    taosMemoryFree(msg);
    return handleErrorBeforePoll(pVg, pTmq);
  }

H
Haojun Liao 已提交
1684
  sendInfo->msgInfo = (SDataBuf){.pData = msg, .len = msgSize, .handle = NULL};
1685 1686 1687 1688 1689 1690 1691 1692
  sendInfo->requestId = req.reqId;
  sendInfo->requestObjRefId = 0;
  sendInfo->param = pParam;
  sendInfo->fp = tmqPollCb;
  sendInfo->msgType = TDMT_VND_TMQ_CONSUME;

  int64_t transporterId = 0;
  char    offsetFormatBuf[80];
H
Haojun Liao 已提交
1693
  tFormatOffset(offsetFormatBuf, tListLen(offsetFormatBuf), &pVg->offsetInfo.currentOffset);
1694

X
Xiaoyu Wang 已提交
1695 1696
  tscDebug("consumer:0x%" PRIx64 " send poll to %s vgId:%d, epoch %d, req:%s, reqId:0x%" PRIx64, pTmq->consumerId,
           pTopic->topicName, pVg->vgId, pTmq->epoch, offsetFormatBuf, req.reqId);
1697 1698 1699 1700 1701 1702 1703 1704
  asyncSendMsgToServer(pTmq->pTscObj->pAppInfo->pTransporter, &pVg->epSet, &transporterId, sendInfo);

  pVg->pollCnt++;
  pTmq->pollCnt++;

  return TSDB_CODE_SUCCESS;
}

1705
// broadcast the poll request to all related vnodes
H
Haojun Liao 已提交
1706
static int32_t tmqPollImpl(tmq_t* tmq, int64_t timeout) {
1707
  int32_t numOfTopics = taosArrayGetSize(tmq->clientTopics);
X
Xiaoyu Wang 已提交
1708
  tscDebug("consumer:0x%" PRIx64 " start to poll data, numOfTopics:%d", tmq->consumerId, numOfTopics);
1709 1710

  for (int i = 0; i < numOfTopics; i++) {
X
Xiaoyu Wang 已提交
1711
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
X
Xiaoyu Wang 已提交
1712
    int32_t         numOfVg = taosArrayGetSize(pTopic->vgs);
1713 1714

    for (int j = 0; j < numOfVg; j++) {
X
Xiaoyu Wang 已提交
1715
      SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);
X
Xiaoyu Wang 已提交
1716 1717 1718
      if (taosGetTimestampMs() - pVg->emptyBlockReceiveTs < EMPTY_BLOCK_POLL_IDLE_DURATION) {  // less than 100ms
        tscTrace("consumer:0x%" PRIx64 " epoch %d, vgId:%d idle for 10ms before start next poll", tmq->consumerId,
                 tmq->epoch, pVg->vgId);
H
Haojun Liao 已提交
1719 1720 1721
        continue;
      }

1722
      int32_t vgStatus = atomic_val_compare_exchange_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE, TMQ_VG_STATUS__WAIT);
1723
      if (vgStatus == TMQ_VG_STATUS__WAIT) {
L
Liu Jicong 已提交
1724
        int32_t vgSkipCnt = atomic_add_fetch_32(&pVg->vgSkipCnt, 1);
H
Haojun Liao 已提交
1725
        tscTrace("consumer:0x%" PRIx64 " epoch %d wait poll-rsp, skip vgId:%d skip cnt %d", tmq->consumerId, tmq->epoch,
X
Xiaoyu Wang 已提交
1726
                 pVg->vgId, vgSkipCnt);
X
Xiaoyu Wang 已提交
1727
        continue;
L
temp  
Liu Jicong 已提交
1728 1729 1730 1731
#if 0
        if (skipCnt < 30000) {
          continue;
        } else {
1732
        tscDebug("consumer:0x%" PRIx64 ",skip vgId:%d skip too much reset", tmq->consumerId, pVg->vgId);
L
temp  
Liu Jicong 已提交
1733 1734
        }
#endif
X
Xiaoyu Wang 已提交
1735
      }
1736

L
Liu Jicong 已提交
1737
      atomic_store_32(&pVg->vgSkipCnt, 0);
1738 1739 1740
      int32_t code = doTmqPollImpl(tmq, pTopic, pVg, timeout);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
D
dapan1121 已提交
1741
      }
X
Xiaoyu Wang 已提交
1742 1743
    }
  }
1744

1745
  tscDebug("consumer:0x%" PRIx64 " end to poll data", tmq->consumerId);
X
Xiaoyu Wang 已提交
1746 1747 1748
  return 0;
}

H
Haojun Liao 已提交
1749
static int32_t tmqHandleNoPollRsp(tmq_t* tmq, SMqRspWrapper* rspWrapper, bool* pReset) {
L
Liu Jicong 已提交
1750
  if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__EP_RSP) {
L
fix  
Liu Jicong 已提交
1751
    /*printf("ep %d %d\n", rspMsg->head.epoch, tmq->epoch);*/
L
Liu Jicong 已提交
1752 1753
    if (rspWrapper->epoch > atomic_load_32(&tmq->epoch)) {
      SMqAskEpRspWrapper* pEpRspWrapper = (SMqAskEpRspWrapper*)rspWrapper;
L
Liu Jicong 已提交
1754
      SMqAskEpRsp*        rspMsg = &pEpRspWrapper->msg;
1755
      doUpdateLocalEp(tmq, rspWrapper->epoch, rspMsg);
L
temp  
Liu Jicong 已提交
1756
      /*tmqClearUnhandleMsg(tmq);*/
L
Liu Jicong 已提交
1757
      tDeleteSMqAskEpRsp(rspMsg);
X
Xiaoyu Wang 已提交
1758 1759
      *pReset = true;
    } else {
L
Liu Jicong 已提交
1760
      tmqFreeRspWrapper(rspWrapper);
X
Xiaoyu Wang 已提交
1761 1762 1763 1764 1765 1766 1767 1768
      *pReset = false;
    }
  } else {
    return -1;
  }
  return 0;
}

H
Haojun Liao 已提交
1769
static void* tmqHandleAllRsp(tmq_t* tmq, int64_t timeout, bool pollIfReset) {
H
Haojun Liao 已提交
1770
  tscDebug("consumer:0x%" PRIx64 " start to handle the rsp, total:%d", tmq->consumerId, tmq->qall->numOfItems);
1771

X
Xiaoyu Wang 已提交
1772
  while (1) {
1773 1774
    SMqRspWrapper* pRspWrapper = NULL;
    taosGetQitem(tmq->qall, (void**)&pRspWrapper);
1775

1776
    if (pRspWrapper == NULL) {
L
Liu Jicong 已提交
1777
      taosReadAllQitems(tmq->mqueue, tmq->qall);
1778 1779
      taosGetQitem(tmq->qall, (void**)&pRspWrapper);
      if (pRspWrapper == NULL) {
L
Liu Jicong 已提交
1780 1781
        return NULL;
      }
X
Xiaoyu Wang 已提交
1782 1783
    }

X
Xiaoyu Wang 已提交
1784
    tscDebug("consumer:0x%" PRIx64 " handle rsp, type:%d", tmq->consumerId, pRspWrapper->tmqRspType);
H
Haojun Liao 已提交
1785

1786 1787
    if (pRspWrapper->tmqRspType == TMQ_MSG_TYPE__END_RSP) {
      taosFreeQitem(pRspWrapper);
L
Liu Jicong 已提交
1788
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
H
Haojun Liao 已提交
1789
      tscError("consumer:0x%" PRIx64 " unexpected rsp from poll, code:%s", tmq->consumerId, tstrerror(terrno));
L
Liu Jicong 已提交
1790
      return NULL;
1791 1792
    } else if (pRspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_RSP) {
      SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)pRspWrapper;
H
Haojun Liao 已提交
1793

X
Xiaoyu Wang 已提交
1794
      int32_t     consumerEpoch = atomic_load_32(&tmq->epoch);
1795 1796 1797
      SMqDataRsp* pDataRsp = &pollRspWrapper->dataRsp;

      if (pDataRsp->head.epoch == consumerEpoch) {
L
Liu Jicong 已提交
1798
        SMqClientVg* pVg = pollRspWrapper->vgHandle;
1799 1800 1801 1802 1803

        // update the epset
        if (pollRspWrapper->pEpset != NULL) {
          SEp* pEp = GET_ACTIVE_EP(pollRspWrapper->pEpset);
          SEp* pOld = GET_ACTIVE_EP(&(pVg->epSet));
X
Xiaoyu Wang 已提交
1804 1805
          tscDebug("consumer:0x%" PRIx64 " update epset vgId:%d, ep:%s:%d, old ep:%s:%d", tmq->consumerId, pVg->vgId,
                   pEp->fqdn, pEp->port, pOld->fqdn, pOld->port);
1806 1807 1808
          pVg->epSet = *pollRspWrapper->pEpset;
        }

1809
        // update the local offset value only for the returned values.
H
Haojun Liao 已提交
1810
        pVg->offsetInfo.currentOffset = pDataRsp->rspOffset;
X
Xiaoyu Wang 已提交
1811
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
H
Haojun Liao 已提交
1812

1813 1814 1815
        char buf[80];
        tFormatOffset(buf, 80, &pDataRsp->rspOffset);
        if (pDataRsp->blockNum == 0) {
X
Xiaoyu Wang 已提交
1816 1817 1818
          tscDebug("consumer:0x%" PRIx64 " empty block received, vgId:%d, offset:%s, vg total:%" PRId64
                   " total:%" PRId64 " reqId:0x%" PRIx64,
                   tmq->consumerId, pVg->vgId, buf, pVg->numOfRows, tmq->totalRows, pollRspWrapper->reqId);
1819
          pRspWrapper = tmqFreeRspWrapper(pRspWrapper);
L
Liu Jicong 已提交
1820
          taosFreeQitem(pollRspWrapper);
1821
        } else {  // build rsp
X
Xiaoyu Wang 已提交
1822
          int64_t    numOfRows = 0;
1823
          SMqRspObj* pRsp = tmqBuildRspFromWrapper(pollRspWrapper, pVg, &numOfRows);
H
Haojun Liao 已提交
1824 1825
          tmq->totalRows += numOfRows;

H
Haojun Liao 已提交
1826
          tscDebug("consumer:0x%" PRIx64 " process poll rsp, vgId:%d, offset:%s, blocks:%d, rows:%" PRId64
H
Haojun Liao 已提交
1827
                   " vg total:%" PRId64 " total:%" PRId64 ", reqId:0x%" PRIx64,
H
Haojun Liao 已提交
1828
                   tmq->consumerId, pVg->vgId, buf, pDataRsp->blockNum, numOfRows, pVg->numOfRows, tmq->totalRows,
H
Haojun Liao 已提交
1829
                   pollRspWrapper->reqId);
1830 1831 1832
          taosFreeQitem(pollRspWrapper);
          return pRsp;
        }
X
Xiaoyu Wang 已提交
1833
      } else {
H
Haojun Liao 已提交
1834
        tscDebug("consumer:0x%" PRIx64 " vgId:%d msg discard since epoch mismatch: msg epoch %d, consumer epoch %d",
1835
                 tmq->consumerId, pollRspWrapper->vgId, pDataRsp->head.epoch, consumerEpoch);
1836
        pRspWrapper = tmqFreeRspWrapper(pRspWrapper);
L
Liu Jicong 已提交
1837 1838
        taosFreeQitem(pollRspWrapper);
      }
1839 1840
    } else if (pRspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_META_RSP) {
      SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)pRspWrapper;
L
Liu Jicong 已提交
1841
      int32_t            consumerEpoch = atomic_load_32(&tmq->epoch);
1842 1843 1844

      tscDebug("consumer:0x%" PRIx64 " process meta rsp", tmq->consumerId);

L
Liu Jicong 已提交
1845
      if (pollRspWrapper->metaRsp.head.epoch == consumerEpoch) {
L
Liu Jicong 已提交
1846
        SMqClientVg* pVg = pollRspWrapper->vgHandle;
H
Haojun Liao 已提交
1847
        pVg->offsetInfo.currentOffset = pollRspWrapper->metaRsp.rspOffset;
L
Liu Jicong 已提交
1848 1849
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
        // build rsp
L
Liu Jicong 已提交
1850
        SMqMetaRspObj* pRsp = tmqBuildMetaRspFromWrapper(pollRspWrapper);
L
Liu Jicong 已提交
1851 1852 1853
        taosFreeQitem(pollRspWrapper);
        return pRsp;
      } else {
H
Haojun Liao 已提交
1854
        tscDebug("consumer:0x%" PRIx64 " vgId:%d msg discard since epoch mismatch: msg epoch %d, consumer epoch %d",
1855
                 tmq->consumerId, pollRspWrapper->vgId, pollRspWrapper->metaRsp.head.epoch, consumerEpoch);
1856
        pRspWrapper = tmqFreeRspWrapper(pRspWrapper);
L
Liu Jicong 已提交
1857
        taosFreeQitem(pollRspWrapper);
X
Xiaoyu Wang 已提交
1858
      }
1859 1860
    } else if (pRspWrapper->tmqRspType == TMQ_MSG_TYPE__TAOSX_RSP) {
      SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)pRspWrapper;
X
Xiaoyu Wang 已提交
1861
      int32_t            consumerEpoch = atomic_load_32(&tmq->epoch);
H
Haojun Liao 已提交
1862

L
Liu Jicong 已提交
1863 1864
      if (pollRspWrapper->taosxRsp.head.epoch == consumerEpoch) {
        SMqClientVg* pVg = pollRspWrapper->vgHandle;
H
Haojun Liao 已提交
1865
        pVg->offsetInfo.currentOffset = pollRspWrapper->taosxRsp.rspOffset;
L
Liu Jicong 已提交
1866
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
H
Haojun Liao 已提交
1867

L
Liu Jicong 已提交
1868
        if (pollRspWrapper->taosxRsp.blockNum == 0) {
H
Haojun Liao 已提交
1869 1870
          tscDebug("consumer:0x%" PRIx64 " taosx empty block received, vgId:%d, vg total:%" PRId64 " reqId:0x%" PRIx64,
                   tmq->consumerId, pVg->vgId, pVg->numOfRows, pollRspWrapper->reqId);
H
Haojun Liao 已提交
1871
          pVg->emptyBlockReceiveTs = taosGetTimestampMs();
1872
          pRspWrapper = tmqFreeRspWrapper(pRspWrapper);
H
Haojun Liao 已提交
1873
          taosFreeQitem(pollRspWrapper);
L
Liu Jicong 已提交
1874
          continue;
H
Haojun Liao 已提交
1875
        } else {
X
Xiaoyu Wang 已提交
1876
          pVg->emptyBlockReceiveTs = 0;  // reset the ts
L
Liu Jicong 已提交
1877
        }
wmmhello's avatar
wmmhello 已提交
1878

L
Liu Jicong 已提交
1879
        // build rsp
X
Xiaoyu Wang 已提交
1880
        void*   pRsp = NULL;
1881
        int64_t numOfRows = 0;
L
Liu Jicong 已提交
1882
        if (pollRspWrapper->taosxRsp.createTableNum == 0) {
1883
          pRsp = tmqBuildRspFromWrapper(pollRspWrapper, pVg, &numOfRows);
L
Liu Jicong 已提交
1884
        } else {
wmmhello's avatar
wmmhello 已提交
1885 1886
          pRsp = tmqBuildTaosxRspFromWrapper(pollRspWrapper);
        }
H
Haojun Liao 已提交
1887

1888 1889
        tmq->totalRows += numOfRows;

H
Haojun Liao 已提交
1890
        char buf[80];
H
Haojun Liao 已提交
1891
        tFormatOffset(buf, 80, &pVg->offsetInfo.currentOffset);
H
Haojun Liao 已提交
1892
        tscDebug("consumer:0x%" PRIx64 " process taosx poll rsp, vgId:%d, offset:%s, blocks:%d, rows:%" PRId64
X
Xiaoyu Wang 已提交
1893
                 ", vg total:%" PRId64 " total:%" PRId64 " reqId:0x%" PRIx64,
H
Haojun Liao 已提交
1894
                 tmq->consumerId, pVg->vgId, buf, pollRspWrapper->dataRsp.blockNum, numOfRows, pVg->numOfRows,
H
Haojun Liao 已提交
1895
                 tmq->totalRows, pollRspWrapper->reqId);
H
Haojun Liao 已提交
1896 1897

        taosFreeQitem(pollRspWrapper);
L
Liu Jicong 已提交
1898
        return pRsp;
H
Haojun Liao 已提交
1899

L
Liu Jicong 已提交
1900
      } else {
H
Haojun Liao 已提交
1901
        tscDebug("consumer:0x%" PRIx64 " vgId:%d msg discard since epoch mismatch: msg epoch %d, consumer epoch %d",
1902
                 tmq->consumerId, pollRspWrapper->vgId, pollRspWrapper->taosxRsp.head.epoch, consumerEpoch);
1903
        pRspWrapper = tmqFreeRspWrapper(pRspWrapper);
L
Liu Jicong 已提交
1904 1905
        taosFreeQitem(pollRspWrapper);
      }
X
Xiaoyu Wang 已提交
1906
    } else {
H
Haojun Liao 已提交
1907 1908
      tscDebug("consumer:0x%" PRIx64 " not data msg received", tmq->consumerId);

X
Xiaoyu Wang 已提交
1909
      bool reset = false;
1910 1911
      tmqHandleNoPollRsp(tmq, pRspWrapper, &reset);
      taosFreeQitem(pRspWrapper);
X
Xiaoyu Wang 已提交
1912
      if (pollIfReset && reset) {
1913
        tscDebug("consumer:0x%" PRIx64 ", reset and repoll", tmq->consumerId);
1914
        tmqPollImpl(tmq, timeout);
X
Xiaoyu Wang 已提交
1915 1916 1917 1918 1919
      }
    }
  }
}

1920
TAOS_RES* tmq_consumer_poll(tmq_t* tmq, int64_t timeout) {
L
Liu Jicong 已提交
1921 1922
  void*   rspObj;
  int64_t startTime = taosGetTimestampMs();
L
Liu Jicong 已提交
1923

X
Xiaoyu Wang 已提交
1924 1925
  tscDebug("consumer:0x%" PRIx64 " start to poll at %" PRId64 ", timeout:%" PRId64, tmq->consumerId, startTime,
           timeout);
L
Liu Jicong 已提交
1926

1927 1928 1929
#if 0
  tmqHandleAllDelayedTask(tmq);
  tmqPollImpl(tmq, timeout);
1930
  rspObj = tmqHandleAllRsp(tmq, timeout, false);
L
Liu Jicong 已提交
1931 1932
  if (rspObj) {
    return (TAOS_RES*)rspObj;
L
fix  
Liu Jicong 已提交
1933
  }
1934
#endif
X
Xiaoyu Wang 已提交
1935

1936
  // in no topic status, delayed task also need to be processed
L
Liu Jicong 已提交
1937
  if (atomic_load_8(&tmq->status) == TMQ_CONSUMER_STATUS__INIT) {
1938
    tscDebug("consumer:0x%" PRIx64 " poll return since consumer is init", tmq->consumerId);
1939
    taosMsleep(500);  //     sleep for a while
1940 1941 1942
    return NULL;
  }

wmmhello's avatar
wmmhello 已提交
1943
  while (atomic_load_8(&tmq->status) == TMQ_CONSUMER_STATUS__RECOVER) {
L
Liu Jicong 已提交
1944
    int32_t retryCnt = 0;
1945
    while (TSDB_CODE_MND_CONSUMER_NOT_READY == doAskEp(tmq)) {
H
Haojun Liao 已提交
1946
      if (retryCnt++ > 40) {
L
Liu Jicong 已提交
1947 1948
        return NULL;
      }
1949

H
Haojun Liao 已提交
1950
      tscDebug("consumer:0x%" PRIx64 " not ready, retry:%d/40 in 500ms", tmq->consumerId, retryCnt);
L
Liu Jicong 已提交
1951 1952 1953 1954
      taosMsleep(500);
    }
  }

X
Xiaoyu Wang 已提交
1955
  while (1) {
L
Liu Jicong 已提交
1956
    tmqHandleAllDelayedTask(tmq);
1957

L
Liu Jicong 已提交
1958
    if (tmqPollImpl(tmq, timeout) < 0) {
1959
      tscDebug("consumer:0x%" PRIx64 " return due to poll error", tmq->consumerId);
L
Liu Jicong 已提交
1960
    }
L
Liu Jicong 已提交
1961

1962
    rspObj = tmqHandleAllRsp(tmq, timeout, false);
L
Liu Jicong 已提交
1963
    if (rspObj) {
1964
      tscDebug("consumer:0x%" PRIx64 " return rsp %p", tmq->consumerId, rspObj);
L
Liu Jicong 已提交
1965
      return (TAOS_RES*)rspObj;
L
Liu Jicong 已提交
1966
    } else if (terrno == TSDB_CODE_TQ_NO_COMMITTED_OFFSET) {
1967
      tscDebug("consumer:0x%" PRIx64 " return null since no committed offset", tmq->consumerId);
L
Liu Jicong 已提交
1968
      return NULL;
X
Xiaoyu Wang 已提交
1969
    }
1970

1971
    if (timeout >= 0) {
L
Liu Jicong 已提交
1972
      int64_t currentTime = taosGetTimestampMs();
1973 1974 1975
      int64_t elapsedTime = currentTime - startTime;
      if (elapsedTime > timeout) {
        tscDebug("consumer:0x%" PRIx64 " (epoch %d) timeout, no rsp, start time %" PRId64 ", current time %" PRId64,
L
Liu Jicong 已提交
1976
                 tmq->consumerId, tmq->epoch, startTime, currentTime);
X
Xiaoyu Wang 已提交
1977 1978
        return NULL;
      }
1979
      tsem_timewait(&tmq->rspSem, (timeout - elapsedTime));
L
Liu Jicong 已提交
1980 1981
    } else {
      // use tsem_timewait instead of tsem_wait to avoid unexpected stuck
L
Liu Jicong 已提交
1982
      tsem_timewait(&tmq->rspSem, 1000);
X
Xiaoyu Wang 已提交
1983 1984 1985 1986
    }
  }
}

1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
static void displayConsumeStatistics(const tmq_t* pTmq) {
  int32_t numOfTopics = taosArrayGetSize(pTmq->clientTopics);
  tscDebug("consumer:0x%" PRIx64 " closing poll:%" PRId64 " rows:%" PRId64 " topics:%d, final epoch:%d",
           pTmq->consumerId, pTmq->pollCnt, pTmq->totalRows, numOfTopics, pTmq->epoch);

  tscDebug("consumer:0x%" PRIx64 " rows dist begin: ", pTmq->consumerId);
  for (int32_t i = 0; i < numOfTopics; ++i) {
    SMqClientTopic* pTopics = taosArrayGet(pTmq->clientTopics, i);

    tscDebug("consumer:0x%" PRIx64 " topic:%d", pTmq->consumerId, i);
    int32_t numOfVgs = taosArrayGetSize(pTopics->vgs);
    for (int32_t j = 0; j < numOfVgs; ++j) {
      SMqClientVg* pVg = taosArrayGet(pTopics->vgs, j);
      tscDebug("topic:%s, %d. vgId:%d rows:%" PRId64, pTopics->topicName, j, pVg->vgId, pVg->numOfRows);
2001
    }
2002
  }
2003

2004 2005
  tscDebug("consumer:0x%" PRIx64 " rows dist end", pTmq->consumerId);
}
2006

2007
int32_t tmq_consumer_close(tmq_t* tmq) {
X
Xiaoyu Wang 已提交
2008
  tscDebug("consumer:0x%" PRIx64 " start to close consumer, status:%d", tmq->consumerId, tmq->status);
2009
  displayConsumeStatistics(tmq);
2010

2011 2012 2013 2014 2015 2016
  if (tmq->status == TMQ_CONSUMER_STATUS__READY) {
    // if auto commit is set, commit before close consumer. Otherwise, do nothing.
    if (tmq->autoCommit) {
      int32_t rsp = tmq_commit_sync(tmq, NULL);
      if (rsp != 0) {
        return rsp;
2017 2018 2019
      }
    }

L
Liu Jicong 已提交
2020
    int32_t     retryCnt = 0;
2021
    tmq_list_t* lst = tmq_list_new();
L
Liu Jicong 已提交
2022
    while (1) {
2023
      int32_t rsp = tmq_subscribe(tmq, lst);
L
Liu Jicong 已提交
2024 2025 2026 2027 2028 2029 2030 2031
      if (rsp != TSDB_CODE_MND_CONSUMER_NOT_READY || retryCnt > 5) {
        break;
      } else {
        retryCnt++;
        taosMsleep(500);
      }
    }

2032
    tmq_list_destroy(lst);
2033
  } else {
X
Xiaoyu Wang 已提交
2034
    tscWarn("consumer:0x%" PRIx64 " not in ready state, close it directly", tmq->consumerId);
L
Liu Jicong 已提交
2035
  }
H
Haojun Liao 已提交
2036

2037
  taosRemoveRef(tmqMgmt.rsetId, tmq->refId);
L
Liu Jicong 已提交
2038
  return 0;
2039
}
L
Liu Jicong 已提交
2040

L
Liu Jicong 已提交
2041 2042
const char* tmq_err2str(int32_t err) {
  if (err == 0) {
L
Liu Jicong 已提交
2043
    return "success";
L
Liu Jicong 已提交
2044
  } else if (err == -1) {
L
Liu Jicong 已提交
2045 2046 2047
    return "fail";
  } else {
    return tstrerror(err);
L
Liu Jicong 已提交
2048 2049
  }
}
L
Liu Jicong 已提交
2050

L
Liu Jicong 已提交
2051 2052 2053 2054 2055
tmq_res_t tmq_get_res_type(TAOS_RES* res) {
  if (TD_RES_TMQ(res)) {
    return TMQ_RES_DATA;
  } else if (TD_RES_TMQ_META(res)) {
    return TMQ_RES_TABLE_META;
2056 2057
  } else if (TD_RES_TMQ_METADATA(res)) {
    return TMQ_RES_METADATA;
L
Liu Jicong 已提交
2058 2059 2060 2061 2062
  } else {
    return TMQ_RES_INVALID;
  }
}

L
Liu Jicong 已提交
2063
const char* tmq_get_topic_name(TAOS_RES* res) {
L
Liu Jicong 已提交
2064 2065
  if (TD_RES_TMQ(res)) {
    SMqRspObj* pRspObj = (SMqRspObj*)res;
L
Liu Jicong 已提交
2066
    return strchr(pRspObj->topic, '.') + 1;
L
Liu Jicong 已提交
2067 2068 2069
  } else if (TD_RES_TMQ_META(res)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    return strchr(pMetaRspObj->topic, '.') + 1;
2070 2071 2072
  } else if (TD_RES_TMQ_METADATA(res)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
    return strchr(pRspObj->topic, '.') + 1;
L
Liu Jicong 已提交
2073 2074 2075 2076 2077
  } else {
    return NULL;
  }
}

L
Liu Jicong 已提交
2078 2079 2080 2081
const char* tmq_get_db_name(TAOS_RES* res) {
  if (TD_RES_TMQ(res)) {
    SMqRspObj* pRspObj = (SMqRspObj*)res;
    return strchr(pRspObj->db, '.') + 1;
L
Liu Jicong 已提交
2082 2083 2084
  } else if (TD_RES_TMQ_META(res)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    return strchr(pMetaRspObj->db, '.') + 1;
2085 2086 2087
  } else if (TD_RES_TMQ_METADATA(res)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
    return strchr(pRspObj->db, '.') + 1;
L
Liu Jicong 已提交
2088 2089 2090 2091 2092
  } else {
    return NULL;
  }
}

L
Liu Jicong 已提交
2093 2094 2095 2096
int32_t tmq_get_vgroup_id(TAOS_RES* res) {
  if (TD_RES_TMQ(res)) {
    SMqRspObj* pRspObj = (SMqRspObj*)res;
    return pRspObj->vgId;
L
Liu Jicong 已提交
2097 2098 2099
  } else if (TD_RES_TMQ_META(res)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    return pMetaRspObj->vgId;
2100
  } else if (TD_RES_TMQ_METADATA(res)) {
2101 2102
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
    return pRspObj->vgId;
L
Liu Jicong 已提交
2103 2104 2105 2106
  } else {
    return -1;
  }
}
L
Liu Jicong 已提交
2107 2108 2109 2110 2111 2112 2113 2114

const char* tmq_get_table_name(TAOS_RES* res) {
  if (TD_RES_TMQ(res)) {
    SMqRspObj* pRspObj = (SMqRspObj*)res;
    if (!pRspObj->rsp.withTbName || pRspObj->rsp.blockTbName == NULL || pRspObj->resIter < 0 ||
        pRspObj->resIter >= pRspObj->rsp.blockNum) {
      return NULL;
    }
2115
    return (const char*)taosArrayGetP(pRspObj->rsp.blockTbName, pRspObj->resIter);
2116 2117
  } else if (TD_RES_TMQ_METADATA(res)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
L
Liu Jicong 已提交
2118 2119 2120
    if (!pRspObj->rsp.withTbName || pRspObj->rsp.blockTbName == NULL || pRspObj->resIter < 0 ||
        pRspObj->resIter >= pRspObj->rsp.blockNum) {
      return NULL;
2121
    }
L
Liu Jicong 已提交
2122 2123
    return (const char*)taosArrayGetP(pRspObj->rsp.blockTbName, pRspObj->resIter);
  }
L
Liu Jicong 已提交
2124 2125
  return NULL;
}
2126

2127 2128 2129 2130 2131 2132
void tmq_commit_async(tmq_t* tmq, const TAOS_RES* pRes, tmq_commit_cb* cb, void* param) {
  if (pRes == NULL) {  // here needs to commit all offsets.
    asyncCommitAllOffsets(tmq, cb, param);
  } else {  // only commit one offset
    asyncCommitOffset(tmq, pRes, cb, param);
  }
L
Liu Jicong 已提交
2133 2134
}

2135 2136 2137 2138
static void commitCallBackFn(tmq_t *pTmq, int32_t code, void* param) {
  SSyncCommitInfo* pInfo = (SSyncCommitInfo*) param;
  pInfo->code = code;
  tsem_post(&pInfo->sem);
2139
}
2140

2141 2142 2143 2144 2145 2146 2147 2148 2149
int32_t tmq_commit_sync(tmq_t* tmq, const TAOS_RES* pRes) {
  int32_t code = 0;

  SSyncCommitInfo* pInfo = taosMemoryMalloc(sizeof(SSyncCommitInfo));
  tsem_init(&pInfo->sem, 0, 0);
  pInfo->code = 0;

  if (pRes == NULL) {
    asyncCommitAllOffsets(tmq, commitCallBackFn, pInfo);
H
Haojun Liao 已提交
2150 2151
  } else {
    asyncCommitOffset(tmq, pRes, commitCallBackFn, pInfo);
2152 2153
  }

2154 2155
  tsem_wait(&pInfo->sem);
  code = pInfo->code;
H
Haojun Liao 已提交
2156 2157

  tsem_destroy(&pInfo->sem);
2158 2159
  taosMemoryFree(pInfo);

X
Xiaoyu Wang 已提交
2160
  tscDebug("consumer:0x%" PRIx64 " sync commit done, code:%s", tmq->consumerId, tstrerror(code));
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
  return code;
}

void updateEpCallbackFn(tmq_t* pTmq, int32_t code, SDataBuf* pDataBuf, void* param) {
  SAskEpInfo* pInfo = param;
  pInfo->code = code;

  if (code == TSDB_CODE_SUCCESS) {
    SMqRspHead* head = pDataBuf->pData;

    SMqAskEpRsp rsp;
    tDecodeSMqAskEpRsp(POINTER_SHIFT(pDataBuf->pData, sizeof(SMqRspHead)), &rsp);
2173
    doUpdateLocalEp(pTmq, head->epoch, &rsp);
2174 2175 2176
    tDeleteSMqAskEpRsp(&rsp);
  }

H
Haojun Liao 已提交
2177
  tsem_post(&pInfo->sem);
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
}

void addToQueueCallbackFn(tmq_t* pTmq, int32_t code, SDataBuf* pDataBuf, void* param) {
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return;
  }

  SMqAskEpRspWrapper* pWrapper = taosAllocateQitem(sizeof(SMqAskEpRspWrapper), DEF_QITEM, 0);
  if (pWrapper == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return;
  }

  SMqRspHead* head = pDataBuf->pData;

  pWrapper->tmqRspType = TMQ_MSG_TYPE__EP_RSP;
  pWrapper->epoch = head->epoch;
  memcpy(&pWrapper->msg, pDataBuf->pData, sizeof(SMqRspHead));
  tDecodeSMqAskEpRsp(POINTER_SHIFT(pDataBuf->pData, sizeof(SMqRspHead)), &pWrapper->msg);

  taosWriteQitem(pTmq->mqueue, pWrapper);
}

int32_t doAskEp(tmq_t* pTmq) {
  SAskEpInfo* pInfo = taosMemoryMalloc(sizeof(SAskEpInfo));
H
Haojun Liao 已提交
2204
  tsem_init(&pInfo->sem, 0, 0);
2205 2206

  asyncAskEp(pTmq, updateEpCallbackFn, pInfo);
H
Haojun Liao 已提交
2207
  tsem_wait(&pInfo->sem);
2208 2209

  int32_t code = pInfo->code;
H
Haojun Liao 已提交
2210
  tsem_destroy(&pInfo->sem);
2211 2212 2213 2214 2215
  taosMemoryFree(pInfo);
  return code;
}

void asyncAskEp(tmq_t* pTmq, __tmq_askep_fn_t askEpFn, void* param) {
2216
  SMqAskEpReq req = {0};
2217 2218 2219
  req.consumerId = pTmq->consumerId;
  req.epoch = pTmq->epoch;
  strcpy(req.cgroup, pTmq->groupId);
2220 2221 2222

  int32_t tlen = tSerializeSMqAskEpReq(NULL, 0, &req);
  if (tlen < 0) {
2223 2224 2225
    tscError("consumer:0x%" PRIx64 ", tSerializeSMqAskEpReq failed", pTmq->consumerId);
    askEpFn(pTmq, TSDB_CODE_INVALID_PARA, NULL, param);
    return;
2226 2227 2228 2229
  }

  void* pReq = taosMemoryCalloc(1, tlen);
  if (pReq == NULL) {
2230 2231 2232
    tscError("consumer:0x%" PRIx64 ", failed to malloc askEpReq msg, size:%d", pTmq->consumerId, tlen);
    askEpFn(pTmq, TSDB_CODE_OUT_OF_MEMORY, NULL, param);
    return;
2233 2234 2235
  }

  if (tSerializeSMqAskEpReq(pReq, tlen, &req) < 0) {
2236
    tscError("consumer:0x%" PRIx64 ", tSerializeSMqAskEpReq %d failed", pTmq->consumerId, tlen);
2237
    taosMemoryFree(pReq);
2238 2239 2240

    askEpFn(pTmq, TSDB_CODE_INVALID_PARA, NULL, param);
    return;
2241 2242 2243 2244
  }

  SMqAskEpCbParam* pParam = taosMemoryCalloc(1, sizeof(SMqAskEpCbParam));
  if (pParam == NULL) {
2245
    tscError("consumer:0x%" PRIx64 ", failed to malloc subscribe param", pTmq->consumerId);
2246
    taosMemoryFree(pReq);
2247 2248 2249

    askEpFn(pTmq, TSDB_CODE_OUT_OF_MEMORY, NULL, param);
    return;
2250 2251
  }

2252 2253 2254 2255
  pParam->refId = pTmq->refId;
  pParam->epoch = pTmq->epoch;
  pParam->pUserFn = askEpFn;
  pParam->pParam = param;
2256 2257 2258 2259 2260

  SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
  if (sendInfo == NULL) {
    taosMemoryFree(pParam);
    taosMemoryFree(pReq);
2261 2262
    askEpFn(pTmq, TSDB_CODE_OUT_OF_MEMORY, NULL, param);
    return;
2263 2264
  }

X
Xiaoyu Wang 已提交
2265
  sendInfo->msgInfo = (SDataBuf){.pData = pReq, .len = tlen, .handle = NULL};
2266 2267 2268 2269

  sendInfo->requestId = generateRequestId();
  sendInfo->requestObjRefId = 0;
  sendInfo->param = pParam;
2270
  sendInfo->fp = askEpCallbackFn;
2271 2272
  sendInfo->msgType = TDMT_MND_TMQ_ASK_EP;

2273 2274
  SEpSet epSet = getEpSet_s(&pTmq->pTscObj->pAppInfo->mgmtEp);
  tscDebug("consumer:0x%" PRIx64 " ask ep from mnode, reqId:0x%" PRIx64, pTmq->consumerId, sendInfo->requestId);
2275 2276

  int64_t transporterId = 0;
2277
  asyncSendMsgToServer(pTmq->pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, sendInfo);
2278 2279 2280 2281 2282 2283 2284
}

int32_t makeTopicVgroupKey(char* dst, const char* topicName, int32_t vg) {
  return sprintf(dst, "%s:%d", topicName, vg);
}

int32_t tmqCommitDone(SMqCommitCbParamSet* pParamSet) {
2285 2286 2287
  int64_t refId = pParamSet->refId;

  tmq_t* tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
2288 2289 2290 2291 2292 2293 2294
  if (tmq == NULL) {
    taosMemoryFree(pParamSet);
    terrno = TSDB_CODE_TMQ_CONSUMER_CLOSED;
    return -1;
  }

  // if no more waiting rsp
2295
  pParamSet->callbackFn(tmq, pParamSet->code, pParamSet->userParam);
2296
  taosMemoryFree(pParamSet);
2297 2298

  taosReleaseRef(tmqMgmt.rsetId, refId);
2299
  return 0;
2300 2301
}

2302
void commitRspCountDown(SMqCommitCbParamSet* pParamSet, int64_t consumerId, const char* pTopic, int32_t vgId) {
2303 2304
  int32_t waitingRspNum = atomic_sub_fetch_32(&pParamSet->waitingRspNum, 1);
  if (waitingRspNum == 0) {
H
Haojun Liao 已提交
2305 2306
    tscDebug("consumer:0x%" PRIx64 " topic:%s vgId:%d all commit-rsp received, commit completed", consumerId, pTopic,
             vgId);
2307
    tmqCommitDone(pParamSet);
H
Haojun Liao 已提交
2308 2309 2310
  } else {
    tscDebug("consumer:0x%" PRIx64 " topic:%s vgId:%d commit-rsp received, remain:%d", consumerId, pTopic, vgId,
             waitingRspNum);
2311 2312
  }
}
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334

SReqResultInfo* tmqGetNextResInfo(TAOS_RES* res, bool convertUcs4) {
  SMqRspObj* pRspObj = (SMqRspObj*)res;
  pRspObj->resIter++;

  if (pRspObj->resIter < pRspObj->rsp.blockNum) {
    SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)taosArrayGetP(pRspObj->rsp.blockData, pRspObj->resIter);
    if (pRspObj->rsp.withSchema) {
      SSchemaWrapper* pSW = (SSchemaWrapper*)taosArrayGetP(pRspObj->rsp.blockSchema, pRspObj->resIter);
      setResSchemaInfo(&pRspObj->resInfo, pSW->pSchema, pSW->nCols);
      taosMemoryFreeClear(pRspObj->resInfo.row);
      taosMemoryFreeClear(pRspObj->resInfo.pCol);
      taosMemoryFreeClear(pRspObj->resInfo.length);
      taosMemoryFreeClear(pRspObj->resInfo.convertBuf);
      taosMemoryFreeClear(pRspObj->resInfo.convertJson);
    }

    setQueryResultFromRsp(&pRspObj->resInfo, pRetrieve, convertUcs4, false);
    return &pRspObj->resInfo;
  }

  return NULL;
H
Haojun Liao 已提交
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
}



int32_t tmq_get_topic_assignment(tmq_t* tmq, const char* pTopicName, tmq_topic_assignment** assignment,
                              int32_t* numOfAssignment) {
  *numOfAssignment = 0;
  *assignment = NULL;

  SMqClientTopic* pTopic = getTopicByName(tmq, pTopicName);
  if (pTopic == NULL) {
    return TSDB_CODE_INVALID_PARA;
  }

  // in case of snapshot is opened, no valid offset will return
  *numOfAssignment = taosArrayGetSize(pTopic->vgs);
  for (int32_t j = 0; j < (*numOfAssignment); ++j) {
    SMqClientVg* pClientVg = taosArrayGet(pTopic->vgs, j);

    tmq_topic_assignment* pAssignment = &(*assignment)[j];
    if (pClientVg->offsetInfo.currentOffset.type == TMQ_OFFSET__LOG) {
      pAssignment->currentOffset = pClientVg->offsetInfo.currentOffset.version;
    } else {
      pAssignment->currentOffset = 0;
    }

    pAssignment->begin = pClientVg->offsetInfo.walVerBegin;
    pAssignment->end = pClientVg->offsetInfo.walVerEnd;
    pAssignment->vgroupHandle = pClientVg->vgId;
  }

  return TSDB_CODE_SUCCESS;
}

int32_t tmq_offset_seek(tmq_t* tmq, const char* pTopicName, int32_t vgroupHandle, int64_t offset) {
  if (tmq == NULL) {
H
Haojun Liao 已提交
2371
    tscError("invalid tmq handle, null");
H
Haojun Liao 已提交
2372 2373 2374 2375 2376
    return TSDB_CODE_INVALID_PARA;
  }

  SMqClientTopic* pTopic = getTopicByName(tmq, pTopicName);
  if (pTopic == NULL) {
H
Haojun Liao 已提交
2377
    tscError("consumer:0x:" PRIx64 " invalid topic name:%s", tmq->consumerId, pTopicName);
H
Haojun Liao 已提交
2378 2379 2380 2381
    return TSDB_CODE_INVALID_PARA;
  }

  SMqClientVg* pVg = NULL;
H
Haojun Liao 已提交
2382 2383
  int32_t      numOfVgs = taosArrayGetSize(pTopic->vgs);
  for (int32_t i = 0; i < numOfVgs; ++i) {
H
Haojun Liao 已提交
2384 2385 2386 2387 2388 2389 2390 2391
    SMqClientVg* pClientVg = taosArrayGet(pTopic->vgs, i);
    if (pClientVg->vgId == vgroupHandle) {
      pVg = pClientVg;
      break;
    }
  }

  if (pVg == NULL) {
H
Haojun Liao 已提交
2392 2393 2394 2395 2396 2397 2398 2399 2400
    tscError("consumer:0x:" PRIx64 " invalid vgroup id:%d", tmq->consumerId, vgroupHandle);
    return TSDB_CODE_INVALID_PARA;
  }

  SVgOffsetInfo* pOffsetInfo = &pVg->offsetInfo;

  int32_t type = pOffsetInfo->currentOffset.type;
  if (type != TMQ_OFFSET__LOG) {
    tscError("consumer:0x:" PRIx64 " offset type:%d not wal version, seek not allowed", tmq->consumerId, type);
H
Haojun Liao 已提交
2401 2402 2403
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2404 2405
  if (offset < pOffsetInfo->walVerBegin || offset > pOffsetInfo->walVerEnd) {
    tscError("consumer:0x:" PRIx64 " invalid seek params, offset:%" PRId64, tmq->consumerId, offset);
H
Haojun Liao 已提交
2406 2407 2408
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2409 2410 2411 2412 2413 2414
  // update the offset, and then commit to vnode
  if (pOffsetInfo->currentOffset.type == TMQ_OFFSET__LOG) {
    pOffsetInfo->currentOffset.version = offset;
    pOffsetInfo->committedOffset.version = offset;
  }

H
Haojun Liao 已提交
2415 2416
  SMqRspObj rspObj = {.resType = RES_TYPE__TMQ, .vgId = pVg->vgId};
  tstrncpy(rspObj.topic, pTopicName, tListLen(rspObj.topic));
H
Haojun Liao 已提交
2417

H
Haojun Liao 已提交
2418 2419 2420 2421 2422 2423 2424 2425
  tscDebug("consumer:0x%" PRIx64 " seek to %" PRId64 " on vgId:%d", tmq->consumerId, offset, pVg->vgId);
  int32_t code = tmq_commit_sync(tmq, &rspObj);
  if (code != TSDB_CODE_SUCCESS) {
    tscError("consumer:0x%" PRIx64 " failed to send seek to vgId:%d, code:%s", tmq->consumerId, pVg->vgId,
             tstrerror(code));
  }

  return code;
2426
}