clientTmq.c 57.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 23
#include "tdef.h"
#include "tglobal.h"
#include "tmsgtype.h"
X
Xiaoyu Wang 已提交
24
#include "tqueue.h"
25
#include "tref.h"
L
Liu Jicong 已提交
26 27
#include "ttimer.h"

L
Liu Jicong 已提交
28 29 30 31 32 33 34
#if 0
#undef tsem_post
#define tsem_post(x)                                         \
  tscInfo("call sem post at %s %d", __FUNCTION__, __LINE__); \
  sem_post(x)
#endif

L
Liu Jicong 已提交
35 36 37
int32_t tmqAskEp(tmq_t* tmq, bool async);

typedef struct {
38 39 40
  int8_t  inited;
  tmr_h   timer;
  int32_t rsetId;
L
Liu Jicong 已提交
41 42 43
} SMqMgmt;

static SMqMgmt tmqMgmt = {0};
44

L
Liu Jicong 已提交
45 46 47 48 49 50
typedef struct {
  int8_t  tmqRspType;
  int32_t epoch;
} SMqRspWrapper;

typedef struct {
L
Liu Jicong 已提交
51 52 53
  int8_t      tmqRspType;
  int32_t     epoch;
  SMqAskEpRsp msg;
L
Liu Jicong 已提交
54 55
} SMqAskEpRspWrapper;

L
Liu Jicong 已提交
56
struct tmq_list_t {
L
Liu Jicong 已提交
57
  SArray container;
L
Liu Jicong 已提交
58
};
L
Liu Jicong 已提交
59

L
Liu Jicong 已提交
60
struct tmq_conf_t {
61 62 63 64 65
  char    clientId[256];
  char    groupId[TSDB_CGROUP_LEN];
  int8_t  autoCommit;
  int8_t  resetOffset;
  int8_t  withTbName;
L
Liu Jicong 已提交
66 67
  int8_t  snapEnable;
  int32_t snapBatchSize;
68 69 70

  bool hbBgEnable;

71 72 73 74 75
  uint16_t       port;
  int32_t        autoCommitInterval;
  char*          ip;
  char*          user;
  char*          pass;
76
  tmq_commit_cb* commitCb;
L
Liu Jicong 已提交
77
  void*          commitCbUserParam;
L
Liu Jicong 已提交
78 79 80
};

struct tmq_t {
81
  int64_t refId;
L
Liu Jicong 已提交
82
  // conf
83 84 85 86 87 88 89 90 91 92 93
  char    groupId[TSDB_CGROUP_LEN];
  char    clientId[256];
  int8_t  withTbName;
  int8_t  useSnapshot;
  int8_t  autoCommit;
  int32_t autoCommitInterval;
  int32_t resetOffsetCfg;
  int64_t consumerId;

  bool hbBgEnable;

L
Liu Jicong 已提交
94 95
  tmq_commit_cb* commitCb;
  void*          commitCbUserParam;
L
Liu Jicong 已提交
96 97 98 99

  // status
  int8_t  status;
  int32_t epoch;
L
Liu Jicong 已提交
100 101
#if 0
  int8_t  epStatus;
L
Liu Jicong 已提交
102
  int32_t epSkipCnt;
L
Liu Jicong 已提交
103
#endif
L
Liu Jicong 已提交
104 105
  int64_t pollCnt;

L
Liu Jicong 已提交
106
  // timer
107 108
  tmr_h hbLiveTimer;
  tmr_h epTimer;
L
Liu Jicong 已提交
109 110 111
  tmr_h reportTimer;
  tmr_h commitTimer;

L
Liu Jicong 已提交
112 113 114 115
  // connection
  STscObj* pTscObj;

  // container
L
Liu Jicong 已提交
116
  SArray*     clientTopics;  // SArray<SMqClientTopic>
L
Liu Jicong 已提交
117
  STaosQueue* mqueue;        // queue of rsp
L
Liu Jicong 已提交
118
  STaosQall*  qall;
L
Liu Jicong 已提交
119 120 121 122
  STaosQueue* delayedTask;  // delayed task queue for heartbeat and auto commit

  // ctl
  tsem_t rspSem;
L
Liu Jicong 已提交
123 124
};

X
Xiaoyu Wang 已提交
125 126 127 128 129 130 131 132
enum {
  TMQ_VG_STATUS__IDLE = 0,
  TMQ_VG_STATUS__WAIT,
};

enum {
  TMQ_CONSUMER_STATUS__INIT = 0,
  TMQ_CONSUMER_STATUS__READY,
133
  TMQ_CONSUMER_STATUS__NO_TOPIC,
L
Liu Jicong 已提交
134
  TMQ_CONSUMER_STATUS__RECOVER,
L
Liu Jicong 已提交
135 136
};

L
Liu Jicong 已提交
137
enum {
138
  TMQ_DELAYED_TASK__ASK_EP = 1,
L
Liu Jicong 已提交
139 140 141 142
  TMQ_DELAYED_TASK__REPORT,
  TMQ_DELAYED_TASK__COMMIT,
};

L
Liu Jicong 已提交
143
typedef struct {
144 145 146
  // statistics
  int64_t pollCnt;
  // offset
L
Liu Jicong 已提交
147 148
  STqOffsetVal committedOffset;
  STqOffsetVal currentOffset;
L
Liu Jicong 已提交
149
  // connection info
150
  int32_t vgId;
X
Xiaoyu Wang 已提交
151
  int32_t vgStatus;
L
Liu Jicong 已提交
152
  int32_t vgSkipCnt;
153 154 155
  SEpSet  epSet;
} SMqClientVg;

L
Liu Jicong 已提交
156
typedef struct {
157
  // subscribe info
158 159
  char topicName[TSDB_TOPIC_FNAME_LEN];
  char db[TSDB_DB_FNAME_LEN];
L
Liu Jicong 已提交
160 161 162

  SArray* vgs;  // SArray<SMqClientVg>

L
Liu Jicong 已提交
163
  SSchemaWrapper schema;
164 165
} SMqClientTopic;

L
Liu Jicong 已提交
166 167 168 169 170
typedef struct {
  int8_t          tmqRspType;
  int32_t         epoch;
  SMqClientVg*    vgHandle;
  SMqClientTopic* topicHandle;
L
Liu Jicong 已提交
171
  union {
L
Liu Jicong 已提交
172 173
    SMqDataRsp dataRsp;
    SMqMetaRsp metaRsp;
L
Liu Jicong 已提交
174
    STaosxRsp  taosxRsp;
L
Liu Jicong 已提交
175
  };
L
Liu Jicong 已提交
176 177
} SMqPollRspWrapper;

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

L
Liu Jicong 已提交
185
typedef struct {
186 187
  int64_t refId;
  int32_t epoch;
L
Liu Jicong 已提交
188
  int32_t code;
L
Liu Jicong 已提交
189
  int32_t async;
X
Xiaoyu Wang 已提交
190
  tsem_t  rspSem;
191 192
} SMqAskEpCbParam;

L
Liu Jicong 已提交
193
typedef struct {
194 195
  int64_t         refId;
  int32_t         epoch;
L
Liu Jicong 已提交
196
  SMqClientVg*    pVg;
L
Liu Jicong 已提交
197
  SMqClientTopic* pTopic;
L
Liu Jicong 已提交
198
  int32_t         vgId;
L
Liu Jicong 已提交
199
  tsem_t          rspSem;
X
Xiaoyu Wang 已提交
200
} SMqPollCbParam;
201

202
typedef struct {
203 204
  int64_t        refId;
  int32_t        epoch;
L
Liu Jicong 已提交
205 206
  int8_t         automatic;
  int8_t         async;
L
Liu Jicong 已提交
207 208
  int32_t        waitingRspNum;
  int32_t        totalRspNum;
L
Liu Jicong 已提交
209
  int32_t        rspErr;
210
  tmq_commit_cb* userCb;
L
Liu Jicong 已提交
211 212 213 214
  /*SArray*        successfulOffsets;*/
  /*SArray*        failedOffsets;*/
  void*  userParam;
  tsem_t rspSem;
215 216 217 218 219
} SMqCommitCbParamSet;

typedef struct {
  SMqCommitCbParamSet* params;
  STqOffset*           pOffset;
L
Liu Jicong 已提交
220 221
  /*char                 topicName[TSDB_TOPIC_FNAME_LEN];*/
  /*int32_t              vgId;*/
222
} SMqCommitCbParam;
223

224
tmq_conf_t* tmq_conf_new() {
wafwerar's avatar
wafwerar 已提交
225
  tmq_conf_t* conf = taosMemoryCalloc(1, sizeof(tmq_conf_t));
226
  conf->withTbName = false;
L
Liu Jicong 已提交
227
  conf->autoCommit = true;
L
Liu Jicong 已提交
228
  conf->autoCommitInterval = 5000;
X
Xiaoyu Wang 已提交
229
  conf->resetOffset = TMQ_CONF__RESET_OFFSET__EARLIEAST;
230
  conf->hbBgEnable = true;
231 232 233
  return conf;
}

L
Liu Jicong 已提交
234
void tmq_conf_destroy(tmq_conf_t* conf) {
L
Liu Jicong 已提交
235 236 237 238 239 240
  if (conf) {
    if (conf->ip) taosMemoryFree(conf->ip);
    if (conf->user) taosMemoryFree(conf->user);
    if (conf->pass) taosMemoryFree(conf->pass);
    taosMemoryFree(conf);
  }
L
Liu Jicong 已提交
241 242 243
}

tmq_conf_res_t tmq_conf_set(tmq_conf_t* conf, const char* key, const char* value) {
244
  if (strcmp(key, "group.id") == 0) {
L
Liu Jicong 已提交
245
    tstrncpy(conf->groupId, value, TSDB_CGROUP_LEN);
L
Liu Jicong 已提交
246
    return TMQ_CONF_OK;
247
  }
L
Liu Jicong 已提交
248

249
  if (strcmp(key, "client.id") == 0) {
L
Liu Jicong 已提交
250
    tstrncpy(conf->clientId, value, 256);
L
Liu Jicong 已提交
251 252
    return TMQ_CONF_OK;
  }
L
Liu Jicong 已提交
253

L
Liu Jicong 已提交
254 255
  if (strcmp(key, "enable.auto.commit") == 0) {
    if (strcmp(value, "true") == 0) {
L
Liu Jicong 已提交
256
      conf->autoCommit = true;
L
Liu Jicong 已提交
257 258
      return TMQ_CONF_OK;
    } else if (strcmp(value, "false") == 0) {
L
Liu Jicong 已提交
259
      conf->autoCommit = false;
L
Liu Jicong 已提交
260 261 262 263
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
264
  }
L
Liu Jicong 已提交
265

L
Liu Jicong 已提交
266 267 268 269 270
  if (strcmp(key, "auto.commit.interval.ms") == 0) {
    conf->autoCommitInterval = atoi(value);
    return TMQ_CONF_OK;
  }

L
Liu Jicong 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284
  if (strcmp(key, "auto.offset.reset") == 0) {
    if (strcmp(value, "none") == 0) {
      conf->resetOffset = TMQ_CONF__RESET_OFFSET__NONE;
      return TMQ_CONF_OK;
    } else if (strcmp(value, "earliest") == 0) {
      conf->resetOffset = TMQ_CONF__RESET_OFFSET__EARLIEAST;
      return TMQ_CONF_OK;
    } else if (strcmp(value, "latest") == 0) {
      conf->resetOffset = TMQ_CONF__RESET_OFFSET__LATEST;
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
  }
L
Liu Jicong 已提交
285

286 287
  if (strcmp(key, "msg.with.table.name") == 0) {
    if (strcmp(value, "true") == 0) {
288
      conf->withTbName = true;
L
Liu Jicong 已提交
289
      return TMQ_CONF_OK;
290
    } else if (strcmp(value, "false") == 0) {
291
      conf->withTbName = false;
L
Liu Jicong 已提交
292
      return TMQ_CONF_OK;
293 294 295 296 297
    } else {
      return TMQ_CONF_INVALID;
    }
  }

L
Liu Jicong 已提交
298
  if (strcmp(key, "experimental.snapshot.enable") == 0) {
L
Liu Jicong 已提交
299
    if (strcmp(value, "true") == 0) {
L
Liu Jicong 已提交
300
      conf->snapEnable = true;
301 302
      return TMQ_CONF_OK;
    } else if (strcmp(value, "false") == 0) {
L
Liu Jicong 已提交
303
      conf->snapEnable = false;
304 305 306 307 308 309
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
  }

L
Liu Jicong 已提交
310 311 312 313 314
  if (strcmp(key, "experimental.snapshot.batch.size") == 0) {
    conf->snapBatchSize = atoi(value);
    return TMQ_CONF_OK;
  }

315 316 317
  if (strcmp(key, "enable.heartbeat.background") == 0) {
    if (strcmp(value, "true") == 0) {
      conf->hbBgEnable = true;
L
Liu Jicong 已提交
318 319
      return TMQ_CONF_OK;
    } else if (strcmp(value, "false") == 0) {
320
      conf->hbBgEnable = false;
L
Liu Jicong 已提交
321 322 323 324
      return TMQ_CONF_OK;
    } else {
      return TMQ_CONF_INVALID;
    }
325
    return TMQ_CONF_OK;
L
Liu Jicong 已提交
326 327
  }

L
Liu Jicong 已提交
328
  if (strcmp(key, "td.connect.ip") == 0) {
L
Liu Jicong 已提交
329 330 331
    conf->ip = strdup(value);
    return TMQ_CONF_OK;
  }
L
Liu Jicong 已提交
332
  if (strcmp(key, "td.connect.user") == 0) {
L
Liu Jicong 已提交
333 334 335
    conf->user = strdup(value);
    return TMQ_CONF_OK;
  }
L
Liu Jicong 已提交
336
  if (strcmp(key, "td.connect.pass") == 0) {
L
Liu Jicong 已提交
337 338 339
    conf->pass = strdup(value);
    return TMQ_CONF_OK;
  }
L
Liu Jicong 已提交
340
  if (strcmp(key, "td.connect.port") == 0) {
L
Liu Jicong 已提交
341 342 343
    conf->port = atoi(value);
    return TMQ_CONF_OK;
  }
L
Liu Jicong 已提交
344
  if (strcmp(key, "td.connect.db") == 0) {
345
    /*conf->db = strdup(value);*/
L
Liu Jicong 已提交
346 347 348
    return TMQ_CONF_OK;
  }

L
Liu Jicong 已提交
349
  return TMQ_CONF_UNKNOWN;
350 351 352
}

tmq_list_t* tmq_list_new() {
L
Liu Jicong 已提交
353 354
  //
  return (tmq_list_t*)taosArrayInit(0, sizeof(void*));
355 356
}

L
Liu Jicong 已提交
357 358
int32_t tmq_list_append(tmq_list_t* list, const char* src) {
  SArray* container = &list->container;
359 360 361 362 363
  if (src == NULL || src[0] == 0) return -1;
  char* topic = strdup(src);
  if (topic[0] != '`') {
    strtolower(topic, src);
  }
L
fix  
Liu Jicong 已提交
364
  if (taosArrayPush(container, &topic) == NULL) return -1;
365 366 367
  return 0;
}

L
Liu Jicong 已提交
368
void tmq_list_destroy(tmq_list_t* list) {
L
Liu Jicong 已提交
369
  SArray* container = &list->container;
L
Liu Jicong 已提交
370
  taosArrayDestroyP(container, taosMemoryFree);
L
Liu Jicong 已提交
371 372
}

L
Liu Jicong 已提交
373 374 375 376 377 378 379 380 381 382
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;
}

L
Liu Jicong 已提交
383 384 385 386
static int32_t tmqMakeTopicVgKey(char* dst, const char* topicName, int32_t vg) {
  return sprintf(dst, "%s:%d", topicName, vg);
}

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
int32_t tmqCommitDone(SMqCommitCbParamSet* pParamSet) {
  tmq_t* tmq = taosAcquireRef(tmqMgmt.rsetId, pParamSet->refId);
  if (tmq == NULL) {
    if (!pParamSet->async) {
      tsem_destroy(&pParamSet->rspSem);
    }
    taosMemoryFree(pParamSet);
    terrno = TSDB_CODE_TMQ_CONSUMER_CLOSED;
    return -1;
  }

  // if no more waiting rsp
  if (pParamSet->async) {
    // call async cb func
    if (pParamSet->automatic && tmq->commitCb) {
      tmq->commitCb(tmq, pParamSet->rspErr, tmq->commitCbUserParam);
    } else if (!pParamSet->automatic && pParamSet->userCb) {
      // sem post
      pParamSet->userCb(tmq, pParamSet->rspErr, pParamSet->userParam);
    }
    taosMemoryFree(pParamSet);
  } else {
    tsem_post(&pParamSet->rspSem);
  }

#if 0
    taosArrayDestroyP(pParamSet->successfulOffsets, taosMemoryFree);
    taosArrayDestroyP(pParamSet->failedOffsets, taosMemoryFree);
#endif
  return 0;
}

L
Liu Jicong 已提交
419 420
static void tmqCommitRspCountDown(SMqCommitCbParamSet* pParamSet) {
  int32_t waitingRspNum = atomic_sub_fetch_32(&pParamSet->waitingRspNum, 1);
421
  ASSERT(waitingRspNum >= 0);
L
Liu Jicong 已提交
422 423 424 425 426
  if (waitingRspNum == 0) {
    tmqCommitDone(pParamSet);
  }
}

427 428
int32_t tmqCommitCb(void* param, SDataBuf* pBuf, int32_t code) {
  SMqCommitCbParam*    pParam = (SMqCommitCbParam*)param;
429 430
  SMqCommitCbParamSet* pParamSet = (SMqCommitCbParamSet*)pParam->params;
  // push into array
L
Liu Jicong 已提交
431
#if 0
432 433 434 435 436
  if (code == 0) {
    taosArrayPush(pParamSet->failedOffsets, &pParam->pOffset);
  } else {
    taosArrayPush(pParamSet->successfulOffsets, &pParam->pOffset);
  }
L
Liu Jicong 已提交
437
#endif
L
Liu Jicong 已提交
438

L
Liu Jicong 已提交
439
  taosMemoryFree(pParam->pOffset);
L
Liu Jicong 已提交
440
  taosMemoryFree(pBuf->pData);
L
Liu Jicong 已提交
441

S
Shengliang Guan 已提交
442
  /*tscDebug("receive offset commit cb of %s on vgId:%d, offset is %" PRId64, pParam->pOffset->subKey, pParam->->vgId,
L
Liu Jicong 已提交
443 444
   * pOffset->version);*/

L
Liu Jicong 已提交
445
  tmqCommitRspCountDown(pParamSet);
446 447 448 449

  return 0;
}

L
Liu Jicong 已提交
450 451 452 453 454 455
static int32_t tmqSendCommitReq(tmq_t* tmq, SMqClientVg* pVg, SMqClientTopic* pTopic, SMqCommitCbParamSet* pParamSet) {
  STqOffset* pOffset = taosMemoryCalloc(1, sizeof(STqOffset));
  if (pOffset == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
L
Liu Jicong 已提交
456
  pOffset->val = pVg->currentOffset;
457

L
Liu Jicong 已提交
458 459 460 461
  int32_t groupLen = strlen(tmq->groupId);
  memcpy(pOffset->subKey, tmq->groupId, groupLen);
  pOffset->subKey[groupLen] = TMQ_SEPARATOR;
  strcpy(pOffset->subKey + groupLen + 1, pTopic->topicName);
L
Liu Jicong 已提交
462

L
Liu Jicong 已提交
463 464 465 466 467 468 469
  int32_t len;
  int32_t code;
  tEncodeSize(tEncodeSTqOffset, pOffset, len, code);
  if (code < 0) {
    return -1;
  }
  void* buf = taosMemoryCalloc(1, sizeof(SMsgHead) + len);
L
Liu Jicong 已提交
470 471 472 473
  if (buf == NULL) {
    taosMemoryFree(pOffset);
    return -1;
  }
L
Liu Jicong 已提交
474
  ((SMsgHead*)buf)->vgId = htonl(pVg->vgId);
L
Liu Jicong 已提交
475

L
Liu Jicong 已提交
476 477 478 479 480
  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));

  SEncoder encoder;
  tEncoderInit(&encoder, abuf, len);
  tEncodeSTqOffset(&encoder, pOffset);
L
Liu Jicong 已提交
481
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
482 483

  // build param
484
  SMqCommitCbParam* pParam = taosMemoryCalloc(1, sizeof(SMqCommitCbParam));
L
Liu Jicong 已提交
485
  if (pParam == NULL) {
L
Liu Jicong 已提交
486
    taosMemoryFree(pOffset);
L
Liu Jicong 已提交
487 488 489
    taosMemoryFree(buf);
    return -1;
  }
L
Liu Jicong 已提交
490 491 492 493 494 495
  pParam->params = pParamSet;
  pParam->pOffset = pOffset;

  // build send info
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
  if (pMsgSendInfo == NULL) {
L
Liu Jicong 已提交
496
    taosMemoryFree(pOffset);
L
Liu Jicong 已提交
497 498
    taosMemoryFree(buf);
    taosMemoryFree(pParam);
L
Liu Jicong 已提交
499 500 501 502 503 504 505 506
    return -1;
  }
  pMsgSendInfo->msgInfo = (SDataBuf){
      .pData = buf,
      .len = sizeof(SMsgHead) + len,
      .handle = NULL,
  };

S
Shengliang Guan 已提交
507 508
  tscDebug("consumer:%" PRId64 ", commit offset of %s on vgId:%d, offset is %" PRId64, tmq->consumerId, pOffset->subKey,
           pVg->vgId, pOffset->val.version);
L
Liu Jicong 已提交
509 510

  // TODO: put into cb
L
Liu Jicong 已提交
511
  pVg->committedOffset = pVg->currentOffset;
L
Liu Jicong 已提交
512 513 514 515

  pMsgSendInfo->requestId = generateRequestId();
  pMsgSendInfo->requestObjRefId = 0;
  pMsgSendInfo->param = pParam;
L
Liu Jicong 已提交
516
  pMsgSendInfo->paramFreeFp = taosMemoryFree;
517
  pMsgSendInfo->fp = tmqCommitCb;
L
Liu Jicong 已提交
518
  pMsgSendInfo->msgType = TDMT_VND_TMQ_COMMIT_OFFSET;
L
Liu Jicong 已提交
519 520
  // send msg

L
Liu Jicong 已提交
521 522 523
  atomic_add_fetch_32(&pParamSet->waitingRspNum, 1);
  atomic_add_fetch_32(&pParamSet->totalRspNum, 1);

L
Liu Jicong 已提交
524 525 526 527 528 529 530 531
  int64_t transporterId = 0;
  asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &pVg->epSet, &transporterId, pMsgSendInfo);
  return 0;
}

int32_t tmqCommitMsgImpl(tmq_t* tmq, const TAOS_RES* msg, int8_t async, tmq_commit_cb* userCb, void* userParam) {
  char*   topic;
  int32_t vgId;
532
  ASSERT(msg != NULL);
L
Liu Jicong 已提交
533 534 535 536 537 538 539 540
  if (TD_RES_TMQ(msg)) {
    SMqRspObj* pRspObj = (SMqRspObj*)msg;
    topic = pRspObj->topic;
    vgId = pRspObj->vgId;
  } else if (TD_RES_TMQ_META(msg)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)msg;
    topic = pMetaRspObj->topic;
    vgId = pMetaRspObj->vgId;
L
Liu Jicong 已提交
541
  } else if (TD_RES_TMQ_METADATA(msg)) {
542 543 544
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)msg;
    topic = pRspObj->topic;
    vgId = pRspObj->vgId;
L
Liu Jicong 已提交
545 546 547 548 549 550 551 552 553
  } else {
    return TSDB_CODE_TMQ_INVALID_MSG;
  }

  SMqCommitCbParamSet* pParamSet = taosMemoryCalloc(1, sizeof(SMqCommitCbParamSet));
  if (pParamSet == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
554 555
  pParamSet->refId = tmq->refId;
  pParamSet->epoch = tmq->epoch;
L
Liu Jicong 已提交
556 557 558 559 560 561
  pParamSet->automatic = 0;
  pParamSet->async = async;
  pParamSet->userCb = userCb;
  pParamSet->userParam = userParam;
  tsem_init(&pParamSet->rspSem, 0, 0);

L
Liu Jicong 已提交
562 563
  int32_t code = -1;

L
Liu Jicong 已提交
564 565 566 567 568 569 570
  for (int32_t i = 0; i < taosArrayGetSize(tmq->clientTopics); i++) {
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
    if (strcmp(pTopic->topicName, topic) != 0) continue;
    for (int32_t j = 0; j < taosArrayGetSize(pTopic->vgs); j++) {
      SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);
      if (pVg->vgId != vgId) continue;

L
Liu Jicong 已提交
571
      if (pVg->currentOffset.type > 0 && !tOffsetEqual(&pVg->currentOffset, &pVg->committedOffset)) {
L
Liu Jicong 已提交
572
        if (tmqSendCommitReq(tmq, pVg, pTopic, pParamSet) < 0) {
L
Liu Jicong 已提交
573 574
          tsem_destroy(&pParamSet->rspSem);
          taosMemoryFree(pParamSet);
L
Liu Jicong 已提交
575
          goto FAIL;
L
Liu Jicong 已提交
576
        }
L
Liu Jicong 已提交
577
        goto HANDLE_RSP;
L
Liu Jicong 已提交
578 579
      }
    }
L
Liu Jicong 已提交
580
  }
L
Liu Jicong 已提交
581

L
Liu Jicong 已提交
582 583 584 585
HANDLE_RSP:
  if (pParamSet->totalRspNum == 0) {
    tsem_destroy(&pParamSet->rspSem);
    taosMemoryFree(pParamSet);
L
Liu Jicong 已提交
586 587 588
    return 0;
  }

L
Liu Jicong 已提交
589 590 591 592
  if (!async) {
    tsem_wait(&pParamSet->rspSem);
    code = pParamSet->rspErr;
    tsem_destroy(&pParamSet->rspSem);
L
Liu Jicong 已提交
593
    taosMemoryFree(pParamSet);
L
Liu Jicong 已提交
594 595 596 597 598 599 600 601 602 603 604 605
    return code;
  } else {
    code = 0;
  }

FAIL:
  if (code != 0 && async) {
    userCb(tmq, code, userParam);
  }
  return 0;
}

L
Liu Jicong 已提交
606 607
static int32_t tmqCommitConsumerImpl(tmq_t* tmq, int8_t automatic, int8_t async, tmq_commit_cb* userCb,
                                     void* userParam) {
L
Liu Jicong 已提交
608 609
  int32_t code = -1;

610 611
  SMqCommitCbParamSet* pParamSet = taosMemoryCalloc(1, sizeof(SMqCommitCbParamSet));
  if (pParamSet == NULL) {
L
Liu Jicong 已提交
612 613 614 615 616 617 618 619
    code = TSDB_CODE_OUT_OF_MEMORY;
    if (async) {
      if (automatic) {
        tmq->commitCb(tmq, code, tmq->commitCbUserParam);
      } else {
        userCb(tmq, code, userParam);
      }
    }
620 621
    return -1;
  }
622 623 624 625

  pParamSet->refId = tmq->refId;
  pParamSet->epoch = tmq->epoch;

626 627 628 629 630 631
  pParamSet->automatic = automatic;
  pParamSet->async = async;
  pParamSet->userCb = userCb;
  pParamSet->userParam = userParam;
  tsem_init(&pParamSet->rspSem, 0, 0);

632 633 634
  // init as 1 to prevent concurrency issue
  pParamSet->waitingRspNum = 1;

635 636
  for (int32_t i = 0; i < taosArrayGetSize(tmq->clientTopics); i++) {
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
L
Liu Jicong 已提交
637

S
Shengliang Guan 已提交
638
    tscDebug("consumer:%" PRId64 ", begin commit for topic %s, vgNum %d", tmq->consumerId, pTopic->topicName,
L
Liu Jicong 已提交
639 640
             (int32_t)taosArrayGetSize(pTopic->vgs));

641
    for (int32_t j = 0; j < taosArrayGetSize(pTopic->vgs); j++) {
L
Liu Jicong 已提交
642 643
      SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);

S
Shengliang Guan 已提交
644 645
      tscDebug("consumer:%" PRId64 ", begin commit for topic %s, vgId:%d", tmq->consumerId, pTopic->topicName,
               pVg->vgId);
L
Liu Jicong 已提交
646

L
Liu Jicong 已提交
647
      if (pVg->currentOffset.type > 0 && !tOffsetEqual(&pVg->currentOffset, &pVg->committedOffset)) {
648
        tscDebug("consumer: %" PRId64 ", vg:%d, current %" PRId64 ", committed %" PRId64 "", tmq->consumerId, pVg->vgId,
L
Liu Jicong 已提交
649
                 pVg->currentOffset.version, pVg->committedOffset.version);
L
Liu Jicong 已提交
650 651 652
        if (tmqSendCommitReq(tmq, pVg, pTopic, pParamSet) < 0) {
          continue;
        }
653 654 655 656
      }
    }
  }

L
Liu Jicong 已提交
657
  // no request is sent
L
Liu Jicong 已提交
658 659 660 661 662 663
  if (pParamSet->totalRspNum == 0) {
    tsem_destroy(&pParamSet->rspSem);
    taosMemoryFree(pParamSet);
    return 0;
  }

L
Liu Jicong 已提交
664 665
  // count down since waiting rsp num init as 1
  tmqCommitRspCountDown(pParamSet);
666

667 668 669 670
  if (!async) {
    tsem_wait(&pParamSet->rspSem);
    code = pParamSet->rspErr;
    tsem_destroy(&pParamSet->rspSem);
671
    taosMemoryFree(pParamSet);
L
Liu Jicong 已提交
672
#if 0
673 674
    taosArrayDestroyP(pParamSet->successfulOffsets, taosMemoryFree);
    taosArrayDestroyP(pParamSet->failedOffsets, taosMemoryFree);
L
Liu Jicong 已提交
675
#endif
L
Liu Jicong 已提交
676
  }
677

L
Liu Jicong 已提交
678 679 680 681 682 683 684 685 686 687
  return code;
}

int32_t tmqCommitInner(tmq_t* tmq, const TAOS_RES* msg, int8_t automatic, int8_t async, tmq_commit_cb* userCb,
                       void* userParam) {
  if (msg) {
    return tmqCommitMsgImpl(tmq, msg, async, userCb, userParam);
  } else {
    return tmqCommitConsumerImpl(tmq, automatic, async, userCb, userParam);
  }
688 689
}

690
void tmqAssignAskEpTask(void* param, void* tmrId) {
691 692 693 694 695 696 697 698 699
  int64_t refId = *(int64_t*)param;
  tmq_t*  tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
  if (tmq != NULL) {
    int8_t* pTaskType = taosAllocateQitem(sizeof(int8_t), DEF_QITEM);
    *pTaskType = TMQ_DELAYED_TASK__ASK_EP;
    taosWriteQitem(tmq->delayedTask, pTaskType);
    tsem_post(&tmq->rspSem);
  }
  taosMemoryFree(param);
L
Liu Jicong 已提交
700 701 702
}

void tmqAssignDelayedCommitTask(void* param, void* tmrId) {
703 704 705 706 707 708 709 710 711
  int64_t refId = *(int64_t*)param;
  tmq_t*  tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
  if (tmq != NULL) {
    int8_t* pTaskType = taosAllocateQitem(sizeof(int8_t), DEF_QITEM);
    *pTaskType = TMQ_DELAYED_TASK__COMMIT;
    taosWriteQitem(tmq->delayedTask, pTaskType);
    tsem_post(&tmq->rspSem);
  }
  taosMemoryFree(param);
L
Liu Jicong 已提交
712 713 714
}

void tmqAssignDelayedReportTask(void* param, void* tmrId) {
715 716 717 718 719 720 721 722 723
  int64_t refId = *(int64_t*)param;
  tmq_t*  tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
  if (tmq != NULL) {
    int8_t* pTaskType = taosAllocateQitem(sizeof(int8_t), DEF_QITEM);
    *pTaskType = TMQ_DELAYED_TASK__REPORT;
    taosWriteQitem(tmq->delayedTask, pTaskType);
    tsem_post(&tmq->rspSem);
  }
  taosMemoryFree(param);
L
Liu Jicong 已提交
724 725
}

726 727 728 729 730 731
int32_t tmqHbCb(void* param, SDataBuf* pMsg, int32_t code) {
  if (pMsg && pMsg->pData) taosMemoryFree(pMsg->pData);
  return 0;
}

void tmqSendHbReq(void* param, void* tmrId) {
732 733 734
  int64_t refId = *(int64_t*)param;
  tmq_t*  tmq = taosAcquireRef(tmqMgmt.rsetId, refId);
  if (tmq == NULL) {
L
Liu Jicong 已提交
735
    taosMemoryFree(param);
736 737
    return;
  }
D
dapan1121 已提交
738 739 740 741 742

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

L
Liu Jicong 已提交
743
  int32_t tlen = tSerializeSMqHbReq(NULL, 0, &req);
D
dapan1121 已提交
744 745 746 747
  if (tlen < 0) {
    tscError("tSerializeSMqHbReq failed");
    return;
  }
L
Liu Jicong 已提交
748
  void* pReq = taosMemoryCalloc(1, tlen);
D
dapan1121 已提交
749 750 751 752 753 754 755 756 757
  if (tlen < 0) {
    tscError("failed to malloc MqHbReq msg, size:%d", tlen);
    return;
  }
  if (tSerializeSMqHbReq(pReq, tlen, &req) < 0) {
    tscError("tSerializeSMqHbReq %d failed", tlen);
    taosMemoryFree(pReq);
    return;
  }
758 759 760 761

  SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
  if (sendInfo == NULL) {
    taosMemoryFree(pReq);
L
Liu Jicong 已提交
762
    goto OVER;
763 764 765
  }
  sendInfo->msgInfo = (SDataBuf){
      .pData = pReq,
D
dapan1121 已提交
766
      .len = tlen,
767 768 769 770 771 772 773
      .handle = NULL,
  };

  sendInfo->requestId = generateRequestId();
  sendInfo->requestObjRefId = 0;
  sendInfo->param = NULL;
  sendInfo->fp = tmqHbCb;
L
Liu Jicong 已提交
774
  sendInfo->msgType = TDMT_MND_TMQ_HB;
775 776 777 778 779 780 781

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

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

OVER:
782
  taosTmrReset(tmqSendHbReq, 1000, param, tmqMgmt.timer, &tmq->hbLiveTimer);
783 784
}

L
Liu Jicong 已提交
785 786 787 788 789 790 791 792
int32_t tmqHandleAllDelayedTask(tmq_t* tmq) {
  STaosQall* qall = taosAllocateQall();
  taosReadAllQitems(tmq->delayedTask, qall);
  while (1) {
    int8_t* pTaskType = NULL;
    taosGetQitem(qall, (void**)&pTaskType);
    if (pTaskType == NULL) break;

793
    if (*pTaskType == TMQ_DELAYED_TASK__ASK_EP) {
L
Liu Jicong 已提交
794
      tmqAskEp(tmq, true);
795 796 797 798 799

      int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t));
      *pRefId = tmq->refId;

      taosTmrReset(tmqAssignAskEpTask, 1000, pRefId, tmqMgmt.timer, &tmq->epTimer);
L
Liu Jicong 已提交
800
    } else if (*pTaskType == TMQ_DELAYED_TASK__COMMIT) {
L
Liu Jicong 已提交
801
      tmqCommitInner(tmq, NULL, 1, 1, tmq->commitCb, tmq->commitCbUserParam);
802 803 804 805 806

      int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t));
      *pRefId = tmq->refId;

      taosTmrReset(tmqAssignDelayedCommitTask, tmq->autoCommitInterval, pRefId, tmqMgmt.timer, &tmq->commitTimer);
L
Liu Jicong 已提交
807 808
    } else if (*pTaskType == TMQ_DELAYED_TASK__REPORT) {
    } else {
809
      ASSERT(0);
L
Liu Jicong 已提交
810
    }
L
Liu Jicong 已提交
811
    taosFreeQitem(pTaskType);
L
Liu Jicong 已提交
812 813 814 815 816
  }
  taosFreeQall(qall);
  return 0;
}

L
Liu Jicong 已提交
817
void tmqClearUnhandleMsg(tmq_t* tmq) {
L
Liu Jicong 已提交
818
  SMqRspWrapper* msg = NULL;
L
Liu Jicong 已提交
819 820 821 822 823 824 825 826
  while (1) {
    taosGetQitem(tmq->qall, (void**)&msg);
    if (msg)
      taosFreeQitem(msg);
    else
      break;
  }

L
fix  
Liu Jicong 已提交
827
  msg = NULL;
L
Liu Jicong 已提交
828 829 830 831 832 833 834 835 836 837
  taosReadAllQitems(tmq->mqueue, tmq->qall);
  while (1) {
    taosGetQitem(tmq->qall, (void**)&msg);
    if (msg)
      taosFreeQitem(msg);
    else
      break;
  }
}

D
dapan1121 已提交
838
int32_t tmqSubscribeCb(void* param, SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
839 840 841 842 843
  SMqSubscribeCbParam* pParam = (SMqSubscribeCbParam*)param;
  pParam->rspErr = code;
  tsem_post(&pParam->rspSem);
  return 0;
}
844

L
Liu Jicong 已提交
845
int32_t tmq_subscription(tmq_t* tmq, tmq_list_t** topics) {
X
Xiaoyu Wang 已提交
846 847 848 849
  if (*topics == NULL) {
    *topics = tmq_list_new();
  }
  for (int i = 0; i < taosArrayGetSize(tmq->clientTopics); i++) {
L
Liu Jicong 已提交
850
    SMqClientTopic* topic = taosArrayGet(tmq->clientTopics, i);
L
Liu Jicong 已提交
851
    tmq_list_append(*topics, strchr(topic->topicName, '.') + 1);
X
Xiaoyu Wang 已提交
852
  }
L
Liu Jicong 已提交
853
  return 0;
X
Xiaoyu Wang 已提交
854 855
}

L
Liu Jicong 已提交
856
int32_t tmq_unsubscribe(tmq_t* tmq) {
L
Liu Jicong 已提交
857 858
  int32_t     rsp;
  int32_t     retryCnt = 0;
L
Liu Jicong 已提交
859
  tmq_list_t* lst = tmq_list_new();
L
Liu Jicong 已提交
860 861 862 863 864 865 866 867 868 869
  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 已提交
870 871
  tmq_list_destroy(lst);
  return rsp;
X
Xiaoyu Wang 已提交
872 873
}

874 875
void tmqFreeImpl(void* handle) {
  tmq_t* tmq = (tmq_t*)handle;
L
Liu Jicong 已提交
876

877
  // TODO stop timer
L
Liu Jicong 已提交
878
  tmqClearUnhandleMsg(tmq);
879 880 881
  if (tmq->mqueue) taosCloseQueue(tmq->mqueue);
  if (tmq->delayedTask) taosCloseQueue(tmq->delayedTask);
  if (tmq->qall) taosFreeQall(tmq->qall);
L
Liu Jicong 已提交
882

883
  tsem_destroy(&tmq->rspSem);
L
Liu Jicong 已提交
884

885 886 887
  int32_t sz = taosArrayGetSize(tmq->clientTopics);
  for (int32_t i = 0; i < sz; i++) {
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
L
Liu Jicong 已提交
888
    taosMemoryFreeClear(pTopic->schema.pSchema);
889 890 891 892 893
    taosArrayDestroy(pTopic->vgs);
  }
  taosArrayDestroy(tmq->clientTopics);
  taos_close_internal(tmq->pTscObj);
  taosMemoryFree(tmq);
L
Liu Jicong 已提交
894 895
}

L
Liu Jicong 已提交
896
tmq_t* tmq_consumer_new(tmq_conf_t* conf, char* errstr, int32_t errstrLen) {
L
Liu Jicong 已提交
897 898 899 900 901 902 903 904 905
  // init timer
  int8_t inited = atomic_val_compare_exchange_8(&tmqMgmt.inited, 0, 1);
  if (inited == 0) {
    tmqMgmt.timer = taosTmrInit(1000, 100, 360000, "TMQ");
    if (tmqMgmt.timer == NULL) {
      atomic_store_8(&tmqMgmt.inited, 0);
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return NULL;
    }
906
    tmqMgmt.rsetId = taosOpenRef(10000, tmqFreeImpl);
L
Liu Jicong 已提交
907 908
  }

L
Liu Jicong 已提交
909 910
  tmq_t* pTmq = taosMemoryCalloc(1, sizeof(tmq_t));
  if (pTmq == NULL) {
L
Liu Jicong 已提交
911
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
912
    tscError("setting up new consumer failed since %s, consumer group %s", terrstr(), conf->groupId);
L
Liu Jicong 已提交
913 914
    return NULL;
  }
L
Liu Jicong 已提交
915

L
Liu Jicong 已提交
916 917 918
  const char* user = conf->user == NULL ? TSDB_DEFAULT_USER : conf->user;
  const char* pass = conf->pass == NULL ? TSDB_DEFAULT_PASS : conf->pass;

919 920 921
  ASSERT(user);
  ASSERT(pass);
  ASSERT(conf->groupId[0]);
L
Liu Jicong 已提交
922

L
Liu Jicong 已提交
923 924 925 926 927 928
  pTmq->clientTopics = taosArrayInit(0, sizeof(SMqClientTopic));
  pTmq->mqueue = taosOpenQueue();
  pTmq->qall = taosAllocateQall();
  pTmq->delayedTask = taosOpenQueue();

  if (pTmq->clientTopics == NULL || pTmq->mqueue == NULL || pTmq->qall == NULL || pTmq->delayedTask == NULL) {
L
Liu Jicong 已提交
929
    terrno = TSDB_CODE_OUT_OF_MEMORY;
S
Shengliang Guan 已提交
930 931
    tscError("consumer %" PRId64 " setup failed since %s, consumer group %s", pTmq->consumerId, terrstr(),
             pTmq->groupId);
L
Liu Jicong 已提交
932 933
    goto FAIL;
  }
L
Liu Jicong 已提交
934

L
Liu Jicong 已提交
935 936
  // init status
  pTmq->status = TMQ_CONSUMER_STATUS__INIT;
L
Liu Jicong 已提交
937 938
  pTmq->pollCnt = 0;
  pTmq->epoch = 0;
L
Liu Jicong 已提交
939 940
  /*pTmq->epStatus = 0;*/
  /*pTmq->epSkipCnt = 0;*/
L
Liu Jicong 已提交
941

L
Liu Jicong 已提交
942 943 944
  // set conf
  strcpy(pTmq->clientId, conf->clientId);
  strcpy(pTmq->groupId, conf->groupId);
945
  pTmq->withTbName = conf->withTbName;
L
Liu Jicong 已提交
946
  pTmq->useSnapshot = conf->snapEnable;
L
Liu Jicong 已提交
947
  pTmq->autoCommit = conf->autoCommit;
L
Liu Jicong 已提交
948
  pTmq->autoCommitInterval = conf->autoCommitInterval;
L
Liu Jicong 已提交
949 950
  pTmq->commitCb = conf->commitCb;
  pTmq->commitCbUserParam = conf->commitCbUserParam;
L
Liu Jicong 已提交
951 952
  pTmq->resetOffsetCfg = conf->resetOffset;

953 954
  pTmq->hbBgEnable = conf->hbBgEnable;

L
Liu Jicong 已提交
955
  // assign consumerId
L
Liu Jicong 已提交
956
  pTmq->consumerId = tGenIdPI64();
X
Xiaoyu Wang 已提交
957

L
Liu Jicong 已提交
958 959
  // init semaphore
  if (tsem_init(&pTmq->rspSem, 0, 0) != 0) {
S
Shengliang Guan 已提交
960 961
    tscError("consumer %" PRId64 " setup failed since %s, consumer group %s", pTmq->consumerId, terrstr(),
             pTmq->groupId);
L
Liu Jicong 已提交
962 963
    goto FAIL;
  }
L
Liu Jicong 已提交
964

L
Liu Jicong 已提交
965 966 967
  // init connection
  pTmq->pTscObj = taos_connect_internal(conf->ip, user, pass, NULL, NULL, conf->port, CONN_TYPE__TMQ);
  if (pTmq->pTscObj == NULL) {
S
Shengliang Guan 已提交
968 969
    tscError("consumer %" PRId64 " setup failed since %s, consumer group %s", pTmq->consumerId, terrstr(),
             pTmq->groupId);
L
Liu Jicong 已提交
970 971 972
    tsem_destroy(&pTmq->rspSem);
    goto FAIL;
  }
L
Liu Jicong 已提交
973

974 975 976 977 978 979
  pTmq->refId = taosAddRef(tmqMgmt.rsetId, pTmq);
  if (pTmq->refId < 0) {
    tmqFreeImpl(pTmq);
    return NULL;
  }

980
  if (pTmq->hbBgEnable) {
L
Liu Jicong 已提交
981 982
    int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t));
    *pRefId = pTmq->refId;
983
    pTmq->hbLiveTimer = taosTmrStart(tmqSendHbReq, 1000, pRefId, tmqMgmt.timer);
984 985
  }

S
Shengliang Guan 已提交
986
  tscInfo("consumer %" PRId64 " is setup, consumer group %s", pTmq->consumerId, pTmq->groupId);
L
Liu Jicong 已提交
987

988
  return pTmq;
L
Liu Jicong 已提交
989 990 991 992 993 994 995 996

FAIL:
  if (pTmq->clientTopics) taosArrayDestroy(pTmq->clientTopics);
  if (pTmq->mqueue) taosCloseQueue(pTmq->mqueue);
  if (pTmq->delayedTask) taosCloseQueue(pTmq->delayedTask);
  if (pTmq->qall) taosFreeQall(pTmq->qall);
  taosMemoryFree(pTmq);
  return NULL;
997 998
}

L
Liu Jicong 已提交
999
int32_t tmq_subscribe(tmq_t* tmq, const tmq_list_t* topic_list) {
L
Liu Jicong 已提交
1000 1001 1002
  const SArray*   container = &topic_list->container;
  int32_t         sz = taosArrayGetSize(container);
  void*           buf = NULL;
L
Liu Jicong 已提交
1003
  SMsgSendInfo*   sendInfo = NULL;
L
Liu Jicong 已提交
1004 1005
  SCMSubscribeReq req = {0};
  int32_t         code = -1;
1006

1007
  tscDebug("call tmq subscribe, consumer: %" PRId64 ", topic num %d", tmq->consumerId, sz);
L
Liu Jicong 已提交
1008

1009
  req.consumerId = tmq->consumerId;
L
Liu Jicong 已提交
1010
  tstrncpy(req.clientId, tmq->clientId, 256);
L
Liu Jicong 已提交
1011
  tstrncpy(req.cgroup, tmq->groupId, TSDB_CGROUP_LEN);
1012
  req.topicNames = taosArrayInit(sz, sizeof(void*));
L
Liu Jicong 已提交
1013
  if (req.topicNames == NULL) goto FAIL;
1014

1015 1016
  tscDebug("call tmq subscribe, consumer: %" PRId64 ", topic num %d", tmq->consumerId, sz);

L
Liu Jicong 已提交
1017 1018
  for (int32_t i = 0; i < sz; i++) {
    char* topic = taosArrayGetP(container, i);
1019 1020

    SName name = {0};
L
Liu Jicong 已提交
1021
    tNameSetDbName(&name, tmq->pTscObj->acctId, topic, strlen(topic));
1022

L
Liu Jicong 已提交
1023 1024 1025
    char* topicFName = taosMemoryCalloc(1, TSDB_TOPIC_FNAME_LEN);
    if (topicFName == NULL) {
      goto FAIL;
1026
    }
L
Liu Jicong 已提交
1027
    tNameExtractFullName(&name, topicFName);
1028

L
Liu Jicong 已提交
1029 1030 1031
    tscDebug("subscribe topic: %s", topicFName);

    taosArrayPush(req.topicNames, &topicFName);
1032 1033
  }

L
Liu Jicong 已提交
1034 1035 1036 1037
  int32_t tlen = tSerializeSCMSubscribeReq(NULL, &req);
  buf = taosMemoryMalloc(tlen);
  if (buf == NULL) goto FAIL;

1038 1039 1040
  void* abuf = buf;
  tSerializeSCMSubscribeReq(&abuf, &req);

L
Liu Jicong 已提交
1041
  sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
L
Liu Jicong 已提交
1042
  if (sendInfo == NULL) goto FAIL;
1043

X
Xiaoyu Wang 已提交
1044
  SMqSubscribeCbParam param = {
L
Liu Jicong 已提交
1045
      .rspErr = 0,
1046 1047
      .refId = tmq->refId,
      .epoch = tmq->epoch,
X
Xiaoyu Wang 已提交
1048
  };
L
Liu Jicong 已提交
1049

L
Liu Jicong 已提交
1050 1051 1052
  if (tsem_init(&param.rspSem, 0, 0) != 0) goto FAIL;

  sendInfo->msgInfo = (SDataBuf){
X
Xiaoyu Wang 已提交
1053 1054 1055 1056
      .pData = buf,
      .len = tlen,
      .handle = NULL,
  };
1057

L
Liu Jicong 已提交
1058 1059
  sendInfo->requestId = generateRequestId();
  sendInfo->requestObjRefId = 0;
L
Liu Jicong 已提交
1060 1061
  sendInfo->param = &param;
  sendInfo->fp = tmqSubscribeCb;
L
Liu Jicong 已提交
1062
  sendInfo->msgType = TDMT_MND_TMQ_SUBSCRIBE;
L
Liu Jicong 已提交
1063

1064 1065 1066 1067 1068
  SEpSet epSet = getEpSet_s(&tmq->pTscObj->pAppInfo->mgmtEp);

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

L
Liu Jicong 已提交
1069 1070
  // avoid double free if msg is sent
  buf = NULL;
L
Liu Jicong 已提交
1071
  sendInfo = NULL;
L
Liu Jicong 已提交
1072

L
Liu Jicong 已提交
1073 1074
  tsem_wait(&param.rspSem);
  tsem_destroy(&param.rspSem);
1075

L
Liu Jicong 已提交
1076 1077 1078
  code = param.rspErr;
  if (code != 0) goto FAIL;

L
Liu Jicong 已提交
1079
  int32_t retryCnt = 0;
L
Liu Jicong 已提交
1080
  while (TSDB_CODE_MND_CONSUMER_NOT_READY == tmqAskEp(tmq, false)) {
L
Liu Jicong 已提交
1081 1082 1083
    if (retryCnt++ > 10) {
      goto FAIL;
    }
L
fix  
Liu Jicong 已提交
1084
    tscDebug("consumer not ready, retry");
L
Liu Jicong 已提交
1085 1086
    taosMsleep(500);
  }
1087

1088 1089
  // init ep timer
  if (tmq->epTimer == NULL) {
1090 1091 1092
    int64_t* pRefId1 = taosMemoryMalloc(sizeof(int64_t));
    *pRefId1 = tmq->refId;
    tmq->epTimer = taosTmrStart(tmqAssignAskEpTask, 1000, pRefId1, tmqMgmt.timer);
1093
  }
L
Liu Jicong 已提交
1094 1095

  // init auto commit timer
1096
  if (tmq->autoCommit && tmq->commitTimer == NULL) {
1097 1098 1099
    int64_t* pRefId2 = taosMemoryMalloc(sizeof(int64_t));
    *pRefId2 = tmq->refId;
    tmq->commitTimer = taosTmrStart(tmqAssignDelayedCommitTask, tmq->autoCommitInterval, pRefId2, tmqMgmt.timer);
L
Liu Jicong 已提交
1100 1101
  }

L
Liu Jicong 已提交
1102 1103
  code = 0;
FAIL:
L
Liu Jicong 已提交
1104
  taosArrayDestroyP(req.topicNames, taosMemoryFree);
L
Liu Jicong 已提交
1105
  taosMemoryFree(buf);
L
Liu Jicong 已提交
1106
  taosMemoryFree(sendInfo);
L
Liu Jicong 已提交
1107

L
Liu Jicong 已提交
1108
  return code;
1109 1110
}

L
Liu Jicong 已提交
1111
void tmq_conf_set_auto_commit_cb(tmq_conf_t* conf, tmq_commit_cb* cb, void* param) {
L
Liu Jicong 已提交
1112
  //
1113
  conf->commitCb = cb;
L
Liu Jicong 已提交
1114
  conf->commitCbUserParam = param;
L
Liu Jicong 已提交
1115
}
1116

D
dapan1121 已提交
1117
int32_t tmqPollCb(void* param, SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
1118 1119
  SMqPollCbParam* pParam = (SMqPollCbParam*)param;
  SMqClientVg*    pVg = pParam->pVg;
L
Liu Jicong 已提交
1120
  SMqClientTopic* pTopic = pParam->pTopic;
1121 1122 1123 1124 1125 1126

  tmq_t* tmq = taosAcquireRef(tmqMgmt.rsetId, pParam->refId);
  if (tmq == NULL) {
    tsem_destroy(&pParam->rspSem);
    taosMemoryFree(pParam);
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1127
    taosMemoryFree(pMsg->pEpSet);
1128 1129 1130 1131 1132 1133
    terrno = TSDB_CODE_TMQ_CONSUMER_CLOSED;
    return -1;
  }

  int32_t epoch = pParam->epoch;
  int32_t vgId = pParam->vgId;
L
Liu Jicong 已提交
1134
  taosMemoryFree(pParam);
L
Liu Jicong 已提交
1135
  if (code != 0) {
L
Liu Jicong 已提交
1136
    tscWarn("msg discard from vgId:%d, epoch %d, since %s", vgId, epoch, terrstr());
L
Liu Jicong 已提交
1137
    if (pMsg->pData) taosMemoryFree(pMsg->pData);
L
Liu Jicong 已提交
1138 1139 1140 1141
    if (code == TSDB_CODE_TMQ_CONSUMER_MISMATCH) {
      atomic_store_8(&tmq->status, TMQ_CONSUMER_STATUS__RECOVER);
      goto CREATE_MSG_FAIL;
    }
L
Liu Jicong 已提交
1142 1143 1144
    if (code == TSDB_CODE_TQ_NO_COMMITTED_OFFSET) {
      SMqPollRspWrapper* pRspWrapper = taosAllocateQitem(sizeof(SMqPollRspWrapper), DEF_QITEM);
      if (pRspWrapper == NULL) {
S
Shengliang Guan 已提交
1145
        tscWarn("msg discard from vgId:%d, epoch %d since out of memory", vgId, epoch);
L
Liu Jicong 已提交
1146 1147 1148 1149 1150 1151 1152 1153
        goto CREATE_MSG_FAIL;
      }
      pRspWrapper->tmqRspType = TMQ_MSG_TYPE__END_RSP;
      /*pRspWrapper->vgHandle = pVg;*/
      /*pRspWrapper->topicHandle = pTopic;*/
      taosWriteQitem(tmq->mqueue, pRspWrapper);
      tsem_post(&tmq->rspSem);
    }
L
fix txn  
Liu Jicong 已提交
1154
    goto CREATE_MSG_FAIL;
L
Liu Jicong 已提交
1155 1156
  }

X
Xiaoyu Wang 已提交
1157 1158 1159
  int32_t msgEpoch = ((SMqRspHead*)pMsg->pData)->epoch;
  int32_t tmqEpoch = atomic_load_32(&tmq->epoch);
  if (msgEpoch < tmqEpoch) {
L
Liu Jicong 已提交
1160
    // do not write into queue since updating epoch reset
S
Shengliang Guan 已提交
1161
    tscWarn("msg discard from vgId:%d since from earlier epoch, rsp epoch %d, current epoch %d", vgId, msgEpoch,
L
Liu Jicong 已提交
1162
            tmqEpoch);
1163
    tsem_post(&tmq->rspSem);
L
Liu Jicong 已提交
1164
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1165
    taosMemoryFree(pMsg->pEpSet);
X
Xiaoyu Wang 已提交
1166 1167 1168 1169
    return 0;
  }

  if (msgEpoch != tmqEpoch) {
S
Shengliang Guan 已提交
1170
    tscWarn("mismatch rsp from vgId:%d, epoch %d, current epoch %d", vgId, msgEpoch, tmqEpoch);
X
Xiaoyu Wang 已提交
1171 1172
  }

L
Liu Jicong 已提交
1173 1174 1175
  // handle meta rsp
  int8_t rspType = ((SMqRspHead*)pMsg->pData)->mqMsgType;

1176
  SMqPollRspWrapper* pRspWrapper = taosAllocateQitem(sizeof(SMqPollRspWrapper), DEF_QITEM);
L
Liu Jicong 已提交
1177
  if (pRspWrapper == NULL) {
L
Liu Jicong 已提交
1178
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1179
    taosMemoryFree(pMsg->pEpSet);
S
Shengliang Guan 已提交
1180
    tscWarn("msg discard from vgId:%d, epoch %d since out of memory", vgId, epoch);
L
fix txn  
Liu Jicong 已提交
1181
    goto CREATE_MSG_FAIL;
L
Liu Jicong 已提交
1182
  }
L
Liu Jicong 已提交
1183

L
Liu Jicong 已提交
1184
  pRspWrapper->tmqRspType = rspType;
L
Liu Jicong 已提交
1185 1186
  pRspWrapper->vgHandle = pVg;
  pRspWrapper->topicHandle = pTopic;
L
Liu Jicong 已提交
1187

L
Liu Jicong 已提交
1188
  if (rspType == TMQ_MSG_TYPE__POLL_RSP) {
L
Liu Jicong 已提交
1189 1190 1191
    SDecoder decoder;
    tDecoderInit(&decoder, POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), pMsg->len - sizeof(SMqRspHead));
    tDecodeSMqDataRsp(&decoder, &pRspWrapper->dataRsp);
wmmhello's avatar
wmmhello 已提交
1192
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1193
    memcpy(&pRspWrapper->dataRsp, pMsg->pData, sizeof(SMqRspHead));
L
Liu Jicong 已提交
1194 1195 1196 1197 1198 1199

    tscDebug("consumer:%" PRId64 ", recv poll: vgId:%d, req offset %" PRId64 ", rsp offset %" PRId64 " type %d",
             tmq->consumerId, pVg->vgId, pRspWrapper->dataRsp.reqOffset.version, pRspWrapper->dataRsp.rspOffset.version,
             rspType);

  } else if (rspType == TMQ_MSG_TYPE__POLL_META_RSP) {
1200 1201 1202 1203
    SDecoder decoder;
    tDecoderInit(&decoder, POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), pMsg->len - sizeof(SMqRspHead));
    tDecodeSMqMetaRsp(&decoder, &pRspWrapper->metaRsp);
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1204
    memcpy(&pRspWrapper->metaRsp, pMsg->pData, sizeof(SMqRspHead));
L
Liu Jicong 已提交
1205 1206 1207 1208 1209 1210 1211
  } 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));
  } else {
1212
    ASSERT(0);
L
Liu Jicong 已提交
1213
  }
L
Liu Jicong 已提交
1214

L
Liu Jicong 已提交
1215
  taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
1216
  taosMemoryFree(pMsg->pEpSet);
L
Liu Jicong 已提交
1217

L
Liu Jicong 已提交
1218 1219
  tscDebug("consumer:%" PRId64 ", put poll res into mqueue %p", tmq->consumerId, pRspWrapper);

L
Liu Jicong 已提交
1220
  taosWriteQitem(tmq->mqueue, pRspWrapper);
1221
  tsem_post(&tmq->rspSem);
L
Liu Jicong 已提交
1222

L
Liu Jicong 已提交
1223
  return 0;
L
fix txn  
Liu Jicong 已提交
1224
CREATE_MSG_FAIL:
L
Liu Jicong 已提交
1225
  if (epoch == tmq->epoch) {
L
Liu Jicong 已提交
1226 1227
    atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
  }
1228
  tsem_post(&tmq->rspSem);
L
Liu Jicong 已提交
1229
  return -1;
1230 1231
}

L
Liu Jicong 已提交
1232
bool tmqUpdateEp(tmq_t* tmq, int32_t epoch, const SMqAskEpRsp* pRsp) {
1233 1234 1235 1236
  bool set = false;

  int32_t topicNumGet = taosArrayGetSize(pRsp->topics);
  char    vgKey[TSDB_TOPIC_FNAME_LEN + 22];
S
Shengliang Guan 已提交
1237
  tscDebug("consumer:%" PRId64 ", update ep epoch %d to epoch %d, topic num:%d", tmq->consumerId, tmq->epoch, epoch,
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
           topicNumGet);

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

  SHashObj* pHash = taosHashInit(64, MurmurHash3_32, false, HASH_NO_LOCK);
  if (pHash == NULL) {
    taosArrayDestroy(newTopics);
    return false;
  }
  int32_t topicNumCur = taosArrayGetSize(tmq->clientTopics);
  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);
S
Shengliang Guan 已提交
1256
      tscDebug("consumer:%" PRId64 ", new vg num: %d", tmq->consumerId, vgNumCur);
1257 1258 1259
      for (int32_t j = 0; j < vgNumCur; j++) {
        SMqClientVg* pVgCur = taosArrayGet(pTopicCur->vgs, j);
        sprintf(vgKey, "%s:%d", pTopicCur->topicName, pVgCur->vgId);
L
Liu Jicong 已提交
1260
        char buf[80];
L
Liu Jicong 已提交
1261
        tFormatOffset(buf, 80, &pVgCur->currentOffset);
L
Liu Jicong 已提交
1262 1263
        tscDebug("consumer:%" PRId64 ", epoch %d vgId:%d vgKey is %s, offset is %s", tmq->consumerId, epoch,
                 pVgCur->vgId, vgKey, buf);
L
Liu Jicong 已提交
1264
        taosHashPut(pHash, vgKey, strlen(vgKey), &pVgCur->currentOffset, sizeof(STqOffsetVal));
1265 1266 1267 1268 1269 1270 1271 1272
      }
    }
  }

  for (int32_t i = 0; i < topicNumGet; i++) {
    SMqClientTopic topic = {0};
    SMqSubTopicEp* pTopicEp = taosArrayGet(pRsp->topics, i);
    topic.schema = pTopicEp->schema;
L
Liu Jicong 已提交
1273 1274
    pTopicEp->schema.nCols = 0;
    pTopicEp->schema.pSchema = NULL;
1275
    tstrncpy(topic.topicName, pTopicEp->topic, TSDB_TOPIC_FNAME_LEN);
1276 1277
    tstrncpy(topic.db, pTopicEp->db, TSDB_DB_FNAME_LEN);

S
Shengliang Guan 已提交
1278
    tscDebug("consumer:%" PRId64 ", update topic: %s", tmq->consumerId, topic.topicName);
1279 1280 1281 1282 1283 1284

    int32_t vgNumGet = taosArrayGetSize(pTopicEp->vgs);
    topic.vgs = taosArrayInit(vgNumGet, sizeof(SMqClientVg));
    for (int32_t j = 0; j < vgNumGet; j++) {
      SMqSubVgEp* pVgEp = taosArrayGet(pTopicEp->vgs, j);
      sprintf(vgKey, "%s:%d", topic.topicName, pVgEp->vgId);
L
Liu Jicong 已提交
1285 1286
      STqOffsetVal* pOffset = taosHashGet(pHash, vgKey, strlen(vgKey));
      STqOffsetVal  offsetNew = {.type = tmq->resetOffsetCfg};
1287
      if (pOffset != NULL) {
L
Liu Jicong 已提交
1288
        offsetNew = *pOffset;
1289 1290 1291 1292
      }

      SMqClientVg clientVg = {
          .pollCnt = 0,
L
Liu Jicong 已提交
1293
          .currentOffset = offsetNew,
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
          .vgId = pVgEp->vgId,
          .epSet = pVgEp->epSet,
          .vgStatus = TMQ_VG_STATUS__IDLE,
          .vgSkipCnt = 0,
      };
      taosArrayPush(topic.vgs, &clientVg);
      set = true;
    }
    taosArrayPush(newTopics, &topic);
  }
1304 1305 1306 1307
  if (tmq->clientTopics) {
    int32_t sz = taosArrayGetSize(tmq->clientTopics);
    for (int32_t i = 0; i < sz; i++) {
      SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
L
Liu Jicong 已提交
1308
      if (pTopic->schema.nCols) taosMemoryFreeClear(pTopic->schema.pSchema);
1309
      taosArrayDestroy(pTopic->vgs);
L
Liu Jicong 已提交
1310
    }
1311
    taosArrayDestroy(tmq->clientTopics);
X
Xiaoyu Wang 已提交
1312
  }
L
Liu Jicong 已提交
1313
  taosHashCleanup(pHash);
L
Liu Jicong 已提交
1314
  tmq->clientTopics = newTopics;
1315

1316 1317 1318 1319
  if (taosArrayGetSize(tmq->clientTopics) == 0)
    atomic_store_8(&tmq->status, TMQ_CONSUMER_STATUS__NO_TOPIC);
  else
    atomic_store_8(&tmq->status, TMQ_CONSUMER_STATUS__READY);
1320

X
Xiaoyu Wang 已提交
1321 1322 1323 1324
  atomic_store_32(&tmq->epoch, epoch);
  return set;
}

D
dapan1121 已提交
1325
int32_t tmqAskEpCb(void* param, SDataBuf* pMsg, int32_t code) {
1326
  SMqAskEpCbParam* pParam = (SMqAskEpCbParam*)param;
L
Liu Jicong 已提交
1327
  int8_t           async = pParam->async;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
  tmq_t*           tmq = taosAcquireRef(tmqMgmt.rsetId, pParam->refId);

  if (tmq == NULL) {
    if (!async) {
      tsem_destroy(&pParam->rspSem);
    } else {
      taosMemoryFree(pParam);
    }
    taosMemoryFree(pMsg->pData);
    terrno = TSDB_CODE_TMQ_CONSUMER_CLOSED;
    return -1;
  }

L
Liu Jicong 已提交
1341
  pParam->code = code;
1342
  if (code != 0) {
L
Liu Jicong 已提交
1343 1344
    tscError("consumer:%" PRId64 ", get topic endpoint error, not ready, wait:%d, code %x", tmq->consumerId,
             pParam->async, code);
L
Liu Jicong 已提交
1345
    goto END;
1346
  }
L
Liu Jicong 已提交
1347

L
Liu Jicong 已提交
1348
  // tmq's epoch is monotonically increase,
L
Liu Jicong 已提交
1349
  // so it's safe to discard any old epoch msg.
L
Liu Jicong 已提交
1350
  // Epoch will only increase when received newer epoch ep msg
L
Liu Jicong 已提交
1351 1352
  SMqRspHead* head = pMsg->pData;
  int32_t     epoch = atomic_load_32(&tmq->epoch);
S
Shengliang Guan 已提交
1353
  tscDebug("consumer:%" PRId64 ", recv ep, msg epoch %d, current epoch %d", tmq->consumerId, head->epoch, epoch);
L
Liu Jicong 已提交
1354 1355
  if (head->epoch <= epoch) {
    goto END;
1356
  }
L
Liu Jicong 已提交
1357

L
Liu Jicong 已提交
1358
  if (!async) {
L
Liu Jicong 已提交
1359 1360
    SMqAskEpRsp rsp;
    tDecodeSMqAskEpRsp(POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), &rsp);
S
Shengliang Guan 已提交
1361 1362
    /*printf("rsp epoch %" PRId64 " sz %" PRId64 "\n", rsp.epoch, rsp.topics->size);*/
    /*printf("tmq epoch %" PRId64 " sz %" PRId64 "\n", tmq->epoch, tmq->clientTopics->size);*/
L
Liu Jicong 已提交
1363
    tmqUpdateEp(tmq, head->epoch, &rsp);
L
Liu Jicong 已提交
1364
    tDeleteSMqAskEpRsp(&rsp);
X
Xiaoyu Wang 已提交
1365
  } else {
1366
    SMqAskEpRspWrapper* pWrapper = taosAllocateQitem(sizeof(SMqAskEpRspWrapper), DEF_QITEM);
L
Liu Jicong 已提交
1367
    if (pWrapper == NULL) {
X
Xiaoyu Wang 已提交
1368
      terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1369 1370
      code = -1;
      goto END;
X
Xiaoyu Wang 已提交
1371
    }
L
Liu Jicong 已提交
1372 1373 1374
    pWrapper->tmqRspType = TMQ_MSG_TYPE__EP_RSP;
    pWrapper->epoch = head->epoch;
    memcpy(&pWrapper->msg, pMsg->pData, sizeof(SMqRspHead));
L
Liu Jicong 已提交
1375
    tDecodeSMqAskEpRsp(POINTER_SHIFT(pMsg->pData, sizeof(SMqRspHead)), &pWrapper->msg);
L
Liu Jicong 已提交
1376

L
Liu Jicong 已提交
1377
    taosWriteQitem(tmq->mqueue, pWrapper);
1378
    tsem_post(&tmq->rspSem);
1379
  }
L
Liu Jicong 已提交
1380 1381

END:
L
Liu Jicong 已提交
1382
  /*atomic_store_8(&tmq->epStatus, 0);*/
L
Liu Jicong 已提交
1383
  if (!async) {
L
Liu Jicong 已提交
1384
    tsem_post(&pParam->rspSem);
L
Liu Jicong 已提交
1385 1386
  } else {
    taosMemoryFree(pParam);
L
Liu Jicong 已提交
1387
  }
L
Liu Jicong 已提交
1388
  taosMemoryFree(pMsg->pData);
L
Liu Jicong 已提交
1389
  return code;
1390 1391
}

L
Liu Jicong 已提交
1392
int32_t tmqAskEp(tmq_t* tmq, bool async) {
L
Liu Jicong 已提交
1393
  int32_t code = 0;
L
Liu Jicong 已提交
1394
#if 0
L
Liu Jicong 已提交
1395
  int8_t  epStatus = atomic_val_compare_exchange_8(&tmq->epStatus, 0, 1);
L
fix txn  
Liu Jicong 已提交
1396
  if (epStatus == 1) {
L
temp  
Liu Jicong 已提交
1397
    int32_t epSkipCnt = atomic_add_fetch_32(&tmq->epSkipCnt, 1);
S
Shengliang Guan 已提交
1398
    tscTrace("consumer:%" PRId64 ", skip ask ep cnt %d", tmq->consumerId, epSkipCnt);
L
Liu Jicong 已提交
1399
    if (epSkipCnt < 5000) return 0;
L
fix txn  
Liu Jicong 已提交
1400
  }
L
temp  
Liu Jicong 已提交
1401
  atomic_store_32(&tmq->epSkipCnt, 0);
L
Liu Jicong 已提交
1402
#endif
D
dapan1121 已提交
1403 1404 1405 1406 1407
  SMqAskEpReq req = {0};
  req.consumerId = tmq->consumerId;
  req.epoch = tmq->epoch;
  strcpy(req.cgroup, tmq->groupId);

L
Liu Jicong 已提交
1408
  int32_t tlen = tSerializeSMqAskEpReq(NULL, 0, &req);
D
dapan1121 已提交
1409 1410 1411 1412
  if (tlen < 0) {
    tscError("tSerializeSMqAskEpReq failed");
    return -1;
  }
L
Liu Jicong 已提交
1413
  void* pReq = taosMemoryCalloc(1, tlen);
L
Liu Jicong 已提交
1414
  if (pReq == NULL) {
D
dapan1121 已提交
1415 1416 1417 1418 1419 1420
    tscError("failed to malloc askEpReq msg, size:%d", tlen);
    return -1;
  }
  if (tSerializeSMqAskEpReq(pReq, tlen, &req) < 0) {
    tscError("tSerializeSMqAskEpReq %d failed", tlen);
    taosMemoryFree(pReq);
L
Liu Jicong 已提交
1421
    return -1;
L
Liu Jicong 已提交
1422
  }
1423

L
Liu Jicong 已提交
1424
  SMqAskEpCbParam* pParam = taosMemoryCalloc(1, sizeof(SMqAskEpCbParam));
L
Liu Jicong 已提交
1425 1426
  if (pParam == NULL) {
    tscError("failed to malloc subscribe param");
D
dapan1121 已提交
1427
    taosMemoryFree(pReq);
L
Liu Jicong 已提交
1428
    /*atomic_store_8(&tmq->epStatus, 0);*/
L
Liu Jicong 已提交
1429
    return -1;
L
Liu Jicong 已提交
1430
  }
1431 1432
  pParam->refId = tmq->refId;
  pParam->epoch = tmq->epoch;
L
Liu Jicong 已提交
1433
  pParam->async = async;
X
Xiaoyu Wang 已提交
1434
  tsem_init(&pParam->rspSem, 0, 0);
1435

1436
  SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
L
Liu Jicong 已提交
1437 1438
  if (sendInfo == NULL) {
    tsem_destroy(&pParam->rspSem);
wafwerar's avatar
wafwerar 已提交
1439
    taosMemoryFree(pParam);
D
dapan1121 已提交
1440
    taosMemoryFree(pReq);
L
Liu Jicong 已提交
1441
    /*atomic_store_8(&tmq->epStatus, 0);*/
L
Liu Jicong 已提交
1442 1443 1444 1445
    return -1;
  }

  sendInfo->msgInfo = (SDataBuf){
D
dapan1121 已提交
1446
      .pData = pReq,
L
Liu Jicong 已提交
1447 1448 1449 1450 1451
      .len = tlen,
      .handle = NULL,
  };

  sendInfo->requestId = generateRequestId();
L
Liu Jicong 已提交
1452 1453 1454
  sendInfo->requestObjRefId = 0;
  sendInfo->param = pParam;
  sendInfo->fp = tmqAskEpCb;
L
Liu Jicong 已提交
1455
  sendInfo->msgType = TDMT_MND_TMQ_ASK_EP;
1456

L
Liu Jicong 已提交
1457 1458
  SEpSet epSet = getEpSet_s(&tmq->pTscObj->pAppInfo->mgmtEp);

S
Shengliang Guan 已提交
1459
  tscDebug("consumer:%" PRId64 ", ask ep", tmq->consumerId);
L
add log  
Liu Jicong 已提交
1460

L
Liu Jicong 已提交
1461 1462
  int64_t transporterId = 0;
  asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, sendInfo);
1463

L
Liu Jicong 已提交
1464
  if (!async) {
L
Liu Jicong 已提交
1465 1466 1467 1468 1469
    tsem_wait(&pParam->rspSem);
    code = pParam->code;
    taosMemoryFree(pParam);
  }
  return code;
1470 1471
}

L
Liu Jicong 已提交
1472
void tmqBuildConsumeReqImpl(SMqPollReq* pReq, tmq_t* tmq, int64_t timeout, SMqClientTopic* pTopic, SMqClientVg* pVg) {
L
Liu Jicong 已提交
1473 1474 1475
  /*strcpy(pReq->topic, pTopic->topicName);*/
  /*strcpy(pReq->cgroup, tmq->groupId);*/

L
Liu Jicong 已提交
1476 1477 1478 1479
  int32_t groupLen = strlen(tmq->groupId);
  memcpy(pReq->subKey, tmq->groupId, groupLen);
  pReq->subKey[groupLen] = TMQ_SEPARATOR;
  strcpy(pReq->subKey + groupLen + 1, pTopic->topicName);
1480

1481
  pReq->withTbName = tmq->withTbName;
1482
  pReq->timeout = timeout;
L
Liu Jicong 已提交
1483
  pReq->consumerId = tmq->consumerId;
X
Xiaoyu Wang 已提交
1484
  pReq->epoch = tmq->epoch;
L
Liu Jicong 已提交
1485
  /*pReq->currentOffset = reqOffset;*/
L
Liu Jicong 已提交
1486
  pReq->reqOffset = pVg->currentOffset;
L
Liu Jicong 已提交
1487
  pReq->reqId = generateRequestId();
1488

L
Liu Jicong 已提交
1489 1490
  pReq->useSnapshot = tmq->useSnapshot;

D
dapan1121 已提交
1491
  pReq->head.vgId = pVg->vgId;
1492 1493
}

L
Liu Jicong 已提交
1494 1495
SMqMetaRspObj* tmqBuildMetaRspFromWrapper(SMqPollRspWrapper* pWrapper) {
  SMqMetaRspObj* pRspObj = taosMemoryCalloc(1, sizeof(SMqMetaRspObj));
L
Liu Jicong 已提交
1496
  pRspObj->resType = RES_TYPE__TMQ_META;
L
Liu Jicong 已提交
1497 1498 1499 1500 1501 1502 1503 1504
  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;
}

L
Liu Jicong 已提交
1505 1506 1507
SMqRspObj* tmqBuildRspFromWrapper(SMqPollRspWrapper* pWrapper) {
  SMqRspObj* pRspObj = taosMemoryCalloc(1, sizeof(SMqRspObj));
  pRspObj->resType = RES_TYPE__TMQ;
L
Liu Jicong 已提交
1508 1509
  tstrncpy(pRspObj->topic, pWrapper->topicHandle->topicName, TSDB_TOPIC_FNAME_LEN);
  tstrncpy(pRspObj->db, pWrapper->topicHandle->db, TSDB_DB_FNAME_LEN);
L
Liu Jicong 已提交
1510
  pRspObj->vgId = pWrapper->vgHandle->vgId;
L
Liu Jicong 已提交
1511
  pRspObj->resIter = -1;
L
Liu Jicong 已提交
1512
  memcpy(&pRspObj->rsp, &pWrapper->dataRsp, sizeof(SMqDataRsp));
L
Liu Jicong 已提交
1513

L
Liu Jicong 已提交
1514 1515
  pRspObj->resInfo.totalRows = 0;
  pRspObj->resInfo.precision = TSDB_TIME_PRECISION_MILLI;
L
Liu Jicong 已提交
1516
  if (!pWrapper->dataRsp.withSchema) {
L
Liu Jicong 已提交
1517 1518
    setResSchemaInfo(&pRspObj->resInfo, pWrapper->topicHandle->schema.pSchema, pWrapper->topicHandle->schema.nCols);
  }
L
Liu Jicong 已提交
1519

L
Liu Jicong 已提交
1520
  return pRspObj;
X
Xiaoyu Wang 已提交
1521 1522
}

L
Liu Jicong 已提交
1523 1524
SMqTaosxRspObj* tmqBuildTaosxRspFromWrapper(SMqPollRspWrapper* pWrapper) {
  SMqTaosxRspObj* pRspObj = taosMemoryCalloc(1, sizeof(SMqTaosxRspObj));
1525
  pRspObj->resType = RES_TYPE__TMQ_METADATA;
L
Liu Jicong 已提交
1526 1527 1528 1529
  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;
1530
  memcpy(&pRspObj->rsp, &pWrapper->taosxRsp, sizeof(STaosxRsp));
L
Liu Jicong 已提交
1531 1532 1533

  pRspObj->resInfo.totalRows = 0;
  pRspObj->resInfo.precision = TSDB_TIME_PRECISION_MILLI;
1534
  if (!pWrapper->taosxRsp.withSchema) {
L
Liu Jicong 已提交
1535 1536 1537 1538 1539 1540
    setResSchemaInfo(&pRspObj->resInfo, pWrapper->topicHandle->schema.pSchema, pWrapper->topicHandle->schema.nCols);
  }

  return pRspObj;
}

1541
int32_t tmqPollImpl(tmq_t* tmq, int64_t timeout) {
L
Liu Jicong 已提交
1542
  /*tscDebug("call poll");*/
X
Xiaoyu Wang 已提交
1543 1544 1545 1546 1547 1548
  for (int i = 0; i < taosArrayGetSize(tmq->clientTopics); i++) {
    SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i);
    for (int j = 0; j < taosArrayGetSize(pTopic->vgs); j++) {
      SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j);
      int32_t      vgStatus = atomic_val_compare_exchange_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE, TMQ_VG_STATUS__WAIT);
      if (vgStatus != TMQ_VG_STATUS__IDLE) {
L
Liu Jicong 已提交
1549
        int32_t vgSkipCnt = atomic_add_fetch_32(&pVg->vgSkipCnt, 1);
L
Liu Jicong 已提交
1550 1551
        tscTrace("consumer:%" PRId64 ", epoch %d skip vgId:%d skip cnt %d", tmq->consumerId, tmq->epoch, pVg->vgId,
                 vgSkipCnt);
X
Xiaoyu Wang 已提交
1552
        continue;
L
Liu Jicong 已提交
1553
        /*if (vgSkipCnt < 10000) continue;*/
L
temp  
Liu Jicong 已提交
1554 1555 1556 1557
#if 0
        if (skipCnt < 30000) {
          continue;
        } else {
S
Shengliang Guan 已提交
1558
        tscDebug("consumer:%" PRId64 ",skip vgId:%d skip too much reset", tmq->consumerId, pVg->vgId);
L
temp  
Liu Jicong 已提交
1559 1560
        }
#endif
X
Xiaoyu Wang 已提交
1561
      }
L
Liu Jicong 已提交
1562
      atomic_store_32(&pVg->vgSkipCnt, 0);
D
dapan1121 已提交
1563 1564 1565 1566 1567 1568 1569 1570 1571

      SMqPollReq req = {0};
      tmqBuildConsumeReqImpl(&req, tmq, timeout, pTopic, pVg);
      int32_t msgSize = tSerializeSMqPollReq(NULL, 0, &req);
      if (msgSize < 0) {
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
        tsem_post(&tmq->rspSem);
        return -1;
      }
L
Liu Jicong 已提交
1572
      char* msg = taosMemoryCalloc(1, msgSize);
D
dapan1121 已提交
1573 1574 1575 1576 1577
      if (NULL == msg) {
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
        tsem_post(&tmq->rspSem);
        return -1;
      }
L
Liu Jicong 已提交
1578

D
dapan1121 已提交
1579 1580
      if (tSerializeSMqPollReq(msg, msgSize, &req) < 0) {
        taosMemoryFree(msg);
X
Xiaoyu Wang 已提交
1581
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
1582
        tsem_post(&tmq->rspSem);
X
Xiaoyu Wang 已提交
1583 1584
        return -1;
      }
L
Liu Jicong 已提交
1585

wafwerar's avatar
wafwerar 已提交
1586
      SMqPollCbParam* pParam = taosMemoryMalloc(sizeof(SMqPollCbParam));
L
Liu Jicong 已提交
1587
      if (pParam == NULL) {
D
dapan1121 已提交
1588
        taosMemoryFree(msg);
X
Xiaoyu Wang 已提交
1589
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
1590
        tsem_post(&tmq->rspSem);
X
Xiaoyu Wang 已提交
1591 1592
        return -1;
      }
1593 1594 1595
      pParam->refId = tmq->refId;
      pParam->epoch = tmq->epoch;

L
Liu Jicong 已提交
1596
      pParam->pVg = pVg;
L
Liu Jicong 已提交
1597
      pParam->pTopic = pTopic;
L
Liu Jicong 已提交
1598
      pParam->vgId = pVg->vgId;
L
Liu Jicong 已提交
1599

1600
      SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
L
Liu Jicong 已提交
1601
      if (sendInfo == NULL) {
D
dapan1121 已提交
1602
        taosMemoryFree(msg);
wafwerar's avatar
wafwerar 已提交
1603
        taosMemoryFree(pParam);
L
Liu Jicong 已提交
1604
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
1605
        tsem_post(&tmq->rspSem);
L
Liu Jicong 已提交
1606 1607 1608 1609
        return -1;
      }

      sendInfo->msgInfo = (SDataBuf){
D
dapan1121 已提交
1610 1611
          .pData = msg,
          .len = msgSize,
X
Xiaoyu Wang 已提交
1612 1613
          .handle = NULL,
      };
D
dapan1121 已提交
1614
      sendInfo->requestId = req.reqId;
X
Xiaoyu Wang 已提交
1615
      sendInfo->requestObjRefId = 0;
L
Liu Jicong 已提交
1616
      sendInfo->param = pParam;
X
Xiaoyu Wang 已提交
1617
      sendInfo->fp = tmqPollCb;
L
Liu Jicong 已提交
1618
      sendInfo->msgType = TDMT_VND_TMQ_CONSUME;
X
Xiaoyu Wang 已提交
1619 1620

      int64_t transporterId = 0;
L
fix  
Liu Jicong 已提交
1621
      /*printf("send poll\n");*/
L
Liu Jicong 已提交
1622

1623
      char offsetFormatBuf[80];
L
Liu Jicong 已提交
1624
      tFormatOffset(offsetFormatBuf, 80, &pVg->currentOffset);
L
Liu Jicong 已提交
1625
      tscDebug("consumer:%" PRId64 ", send poll to %s vgId:%d, epoch %d, req offset:%s, reqId:%" PRIu64,
D
dapan1121 已提交
1626
               tmq->consumerId, pTopic->topicName, pVg->vgId, tmq->epoch, offsetFormatBuf, req.reqId);
S
Shengliang Guan 已提交
1627
      /*printf("send vgId:%d %" PRId64 "\n", pVg->vgId, pVg->currentOffset);*/
X
Xiaoyu Wang 已提交
1628 1629 1630 1631 1632 1633 1634 1635
      asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &pVg->epSet, &transporterId, sendInfo);
      pVg->pollCnt++;
      tmq->pollCnt++;
    }
  }
  return 0;
}

L
Liu Jicong 已提交
1636 1637
int32_t tmqHandleNoPollRsp(tmq_t* tmq, SMqRspWrapper* rspWrapper, bool* pReset) {
  if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__EP_RSP) {
L
fix  
Liu Jicong 已提交
1638
    /*printf("ep %d %d\n", rspMsg->head.epoch, tmq->epoch);*/
L
Liu Jicong 已提交
1639 1640
    if (rspWrapper->epoch > atomic_load_32(&tmq->epoch)) {
      SMqAskEpRspWrapper* pEpRspWrapper = (SMqAskEpRspWrapper*)rspWrapper;
L
Liu Jicong 已提交
1641
      SMqAskEpRsp*        rspMsg = &pEpRspWrapper->msg;
L
Liu Jicong 已提交
1642
      tmqUpdateEp(tmq, rspWrapper->epoch, rspMsg);
L
temp  
Liu Jicong 已提交
1643
      /*tmqClearUnhandleMsg(tmq);*/
L
Liu Jicong 已提交
1644
      tDeleteSMqAskEpRsp(rspMsg);
X
Xiaoyu Wang 已提交
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
      *pReset = true;
    } else {
      *pReset = false;
    }
  } else {
    return -1;
  }
  return 0;
}

L
Liu Jicong 已提交
1655
void* tmqHandleAllRsp(tmq_t* tmq, int64_t timeout, bool pollIfReset) {
X
Xiaoyu Wang 已提交
1656
  while (1) {
L
Liu Jicong 已提交
1657 1658 1659
    SMqRspWrapper* rspWrapper = NULL;
    taosGetQitem(tmq->qall, (void**)&rspWrapper);
    if (rspWrapper == NULL) {
L
Liu Jicong 已提交
1660
      taosReadAllQitems(tmq->mqueue, tmq->qall);
L
Liu Jicong 已提交
1661
      taosGetQitem(tmq->qall, (void**)&rspWrapper);
L
Liu Jicong 已提交
1662 1663

      if (rspWrapper == NULL) {
L
Liu Jicong 已提交
1664
        /*tscDebug("consumer %" PRId64 " mqueue empty", tmq->consumerId);*/
L
Liu Jicong 已提交
1665 1666
        return NULL;
      }
X
Xiaoyu Wang 已提交
1667 1668
    }

L
Liu Jicong 已提交
1669 1670
    tscDebug("consumer:%" PRId64 " handle rsp %p", tmq->consumerId, rspWrapper);

L
Liu Jicong 已提交
1671 1672 1673 1674 1675
    if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__END_RSP) {
      taosFreeQitem(rspWrapper);
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
      return NULL;
    } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_RSP) {
L
Liu Jicong 已提交
1676
      SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)rspWrapper;
1677
      tscDebug("consumer %" PRId64 " actual process poll rsp", tmq->consumerId);
L
Liu Jicong 已提交
1678
      /*atomic_sub_fetch_32(&tmq->readyRequest, 1);*/
1679
      int32_t consumerEpoch = atomic_load_32(&tmq->epoch);
L
Liu Jicong 已提交
1680
      if (pollRspWrapper->dataRsp.head.epoch == consumerEpoch) {
L
Liu Jicong 已提交
1681
        SMqClientVg* pVg = pollRspWrapper->vgHandle;
S
Shengliang Guan 已提交
1682
        /*printf("vgId:%d, offset %" PRId64 " up to %" PRId64 "\n", pVg->vgId, pVg->currentOffset,
L
Liu Jicong 已提交
1683
         * rspMsg->msg.rspOffset);*/
L
Liu Jicong 已提交
1684
        pVg->currentOffset = pollRspWrapper->dataRsp.rspOffset;
X
Xiaoyu Wang 已提交
1685
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
L
Liu Jicong 已提交
1686
        if (pollRspWrapper->dataRsp.blockNum == 0) {
L
Liu Jicong 已提交
1687 1688
          taosFreeQitem(pollRspWrapper);
          rspWrapper = NULL;
L
temp  
Liu Jicong 已提交
1689 1690
          continue;
        }
L
Liu Jicong 已提交
1691
        // build rsp
L
Liu Jicong 已提交
1692
        SMqRspObj* pRsp = tmqBuildRspFromWrapper(pollRspWrapper);
L
Liu Jicong 已提交
1693
        taosFreeQitem(pollRspWrapper);
L
Liu Jicong 已提交
1694
        return pRsp;
X
Xiaoyu Wang 已提交
1695
      } else {
1696
        tscDebug("msg discard since epoch mismatch: msg epoch %d, consumer epoch %d",
L
Liu Jicong 已提交
1697 1698 1699 1700 1701 1702
                 pollRspWrapper->dataRsp.head.epoch, consumerEpoch);
        taosFreeQitem(pollRspWrapper);
      }
    } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_META_RSP) {
      SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)rspWrapper;
      int32_t            consumerEpoch = atomic_load_32(&tmq->epoch);
L
Liu Jicong 已提交
1703
      if (pollRspWrapper->metaRsp.head.epoch == consumerEpoch) {
L
Liu Jicong 已提交
1704
        SMqClientVg* pVg = pollRspWrapper->vgHandle;
S
Shengliang Guan 已提交
1705
        /*printf("vgId:%d, offset %" PRId64 " up to %" PRId64 "\n", pVg->vgId, pVg->currentOffset,
L
Liu Jicong 已提交
1706
         * rspMsg->msg.rspOffset);*/
wmmhello's avatar
wmmhello 已提交
1707
        pVg->currentOffset = pollRspWrapper->metaRsp.rspOffset;
L
Liu Jicong 已提交
1708 1709
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
        // build rsp
L
Liu Jicong 已提交
1710
        SMqMetaRspObj* pRsp = tmqBuildMetaRspFromWrapper(pollRspWrapper);
L
Liu Jicong 已提交
1711 1712 1713
        taosFreeQitem(pollRspWrapper);
        return pRsp;
      } else {
1714
        tscDebug("msg discard since epoch mismatch: msg epoch %d, consumer epoch %d",
L
Liu Jicong 已提交
1715
                 pollRspWrapper->metaRsp.head.epoch, consumerEpoch);
L
Liu Jicong 已提交
1716
        taosFreeQitem(pollRspWrapper);
X
Xiaoyu Wang 已提交
1717
      }
L
Liu Jicong 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__TAOSX_RSP) {
      SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)rspWrapper;
      /*atomic_sub_fetch_32(&tmq->readyRequest, 1);*/
      int32_t consumerEpoch = atomic_load_32(&tmq->epoch);
      if (pollRspWrapper->taosxRsp.head.epoch == consumerEpoch) {
        SMqClientVg* pVg = pollRspWrapper->vgHandle;
        /*printf("vgId:%d, offset %" PRId64 " up to %" PRId64 "\n", pVg->vgId, pVg->currentOffset,
         * rspMsg->msg.rspOffset);*/
        pVg->currentOffset = pollRspWrapper->taosxRsp.rspOffset;
        atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE);
        if (pollRspWrapper->taosxRsp.blockNum == 0) {
          taosFreeQitem(pollRspWrapper);
          rspWrapper = NULL;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
1733

L
Liu Jicong 已提交
1734
        // build rsp
wmmhello's avatar
wmmhello 已提交
1735
        void* pRsp = NULL;
L
Liu Jicong 已提交
1736
        if (pollRspWrapper->taosxRsp.createTableNum == 0) {
wmmhello's avatar
wmmhello 已提交
1737
          pRsp = tmqBuildRspFromWrapper(pollRspWrapper);
L
Liu Jicong 已提交
1738
        } else {
wmmhello's avatar
wmmhello 已提交
1739 1740
          pRsp = tmqBuildTaosxRspFromWrapper(pollRspWrapper);
        }
L
Liu Jicong 已提交
1741 1742 1743
        taosFreeQitem(pollRspWrapper);
        return pRsp;
      } else {
L
Liu Jicong 已提交
1744
        tscDebug("msg discard since epoch mismatch: msg epoch %d, consumer epoch %d",
L
Liu Jicong 已提交
1745 1746 1747
                 pollRspWrapper->taosxRsp.head.epoch, consumerEpoch);
        taosFreeQitem(pollRspWrapper);
      }
X
Xiaoyu Wang 已提交
1748
    } else {
L
fix  
Liu Jicong 已提交
1749
      /*printf("handle ep rsp %d\n", rspMsg->head.mqMsgType);*/
X
Xiaoyu Wang 已提交
1750
      bool reset = false;
L
Liu Jicong 已提交
1751 1752
      tmqHandleNoPollRsp(tmq, rspWrapper, &reset);
      taosFreeQitem(rspWrapper);
X
Xiaoyu Wang 已提交
1753
      if (pollIfReset && reset) {
S
Shengliang Guan 已提交
1754
        tscDebug("consumer:%" PRId64 ", reset and repoll", tmq->consumerId);
1755
        tmqPollImpl(tmq, timeout);
X
Xiaoyu Wang 已提交
1756 1757 1758 1759 1760
      }
    }
  }
}

1761
TAOS_RES* tmq_consumer_poll(tmq_t* tmq, int64_t timeout) {
L
Liu Jicong 已提交
1762
  /*tscDebug("call poll1");*/
L
Liu Jicong 已提交
1763 1764
  void*   rspObj;
  int64_t startTime = taosGetTimestampMs();
L
Liu Jicong 已提交
1765

L
Liu Jicong 已提交
1766 1767
  tscDebug("consumer:%" PRId64 ", start poll at %" PRId64, tmq->consumerId, startTime);

1768 1769 1770
#if 0
  tmqHandleAllDelayedTask(tmq);
  tmqPollImpl(tmq, timeout);
1771
  rspObj = tmqHandleAllRsp(tmq, timeout, false);
L
Liu Jicong 已提交
1772 1773
  if (rspObj) {
    return (TAOS_RES*)rspObj;
L
fix  
Liu Jicong 已提交
1774
  }
1775
#endif
X
Xiaoyu Wang 已提交
1776

1777
  // in no topic status, delayed task also need to be processed
L
Liu Jicong 已提交
1778
  if (atomic_load_8(&tmq->status) == TMQ_CONSUMER_STATUS__INIT) {
1779
    tscDebug("consumer:%" PRId64 ", poll return since consumer status is init", tmq->consumerId);
1780 1781 1782
    return NULL;
  }

L
Liu Jicong 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
  if (atomic_load_8(&tmq->status) == TMQ_CONSUMER_STATUS__RECOVER) {
    int32_t retryCnt = 0;
    while (TSDB_CODE_MND_CONSUMER_NOT_READY == tmqAskEp(tmq, false)) {
      if (retryCnt++ > 10) {
        return NULL;
      }
      tscDebug("consumer not ready, retry");
      taosMsleep(500);
    }
  }

X
Xiaoyu Wang 已提交
1794
  while (1) {
L
Liu Jicong 已提交
1795
    tmqHandleAllDelayedTask(tmq);
L
Liu Jicong 已提交
1796 1797 1798 1799
    if (tmqPollImpl(tmq, timeout) < 0) {
      tscDebug("return since poll err");
      /*return NULL;*/
    }
L
Liu Jicong 已提交
1800

1801
    rspObj = tmqHandleAllRsp(tmq, timeout, false);
L
Liu Jicong 已提交
1802
    if (rspObj) {
1803
      tscDebug("consumer:%" PRId64 ", return rsp %p", tmq->consumerId, rspObj);
L
Liu Jicong 已提交
1804
      return (TAOS_RES*)rspObj;
L
Liu Jicong 已提交
1805
    } else if (terrno == TSDB_CODE_TQ_NO_COMMITTED_OFFSET) {
L
Liu Jicong 已提交
1806
      tscDebug("consumer:%" PRId64 ", return null since no committed offset", tmq->consumerId);
L
Liu Jicong 已提交
1807
      return NULL;
X
Xiaoyu Wang 已提交
1808
    }
1809
    if (timeout != -1) {
L
Liu Jicong 已提交
1810 1811 1812 1813 1814
      int64_t currentTime = taosGetTimestampMs();
      int64_t passedTime = currentTime - startTime;
      if (passedTime > timeout) {
        tscDebug("consumer:%" PRId64 ", (epoch %d) timeout, no rsp, start time %" PRId64 ", current time %" PRId64,
                 tmq->consumerId, tmq->epoch, startTime, currentTime);
X
Xiaoyu Wang 已提交
1815 1816
        return NULL;
      }
L
Liu Jicong 已提交
1817 1818 1819 1820
      /*tscInfo("consumer:%" PRId64 ", (epoch %d) wait, start time %" PRId64 ", current time %" PRId64*/
      /*", left time %" PRId64,*/
      /*tmq->consumerId, tmq->epoch, startTime, currentTime, (timeout - passedTime));*/
      tsem_timewait(&tmq->rspSem, (timeout - passedTime));
L
Liu Jicong 已提交
1821 1822
    } else {
      // use tsem_timewait instead of tsem_wait to avoid unexpected stuck
L
Liu Jicong 已提交
1823
      tsem_timewait(&tmq->rspSem, 1000);
X
Xiaoyu Wang 已提交
1824 1825 1826 1827
    }
  }
}

L
Liu Jicong 已提交
1828
int32_t tmq_consumer_close(tmq_t* tmq) {
1829
  if (tmq->status == TMQ_CONSUMER_STATUS__READY) {
L
Liu Jicong 已提交
1830 1831
    int32_t rsp = tmq_commit_sync(tmq, NULL);
    if (rsp != 0) {
L
Liu Jicong 已提交
1832
      return rsp;
1833 1834
    }

L
Liu Jicong 已提交
1835
    int32_t     retryCnt = 0;
1836
    tmq_list_t* lst = tmq_list_new();
L
Liu Jicong 已提交
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
    while (1) {
      rsp = tmq_subscribe(tmq, lst);
      if (rsp != TSDB_CODE_MND_CONSUMER_NOT_READY || retryCnt > 5) {
        break;
      } else {
        retryCnt++;
        taosMsleep(500);
      }
    }

1847
    tmq_list_destroy(lst);
1848

L
Liu Jicong 已提交
1849 1850
    /*return rsp;*/
    return 0;
L
Liu Jicong 已提交
1851
  }
1852
  taosRemoveRef(tmqMgmt.rsetId, tmq->refId);
L
Liu Jicong 已提交
1853
  return 0;
1854
}
L
Liu Jicong 已提交
1855

L
Liu Jicong 已提交
1856 1857
const char* tmq_err2str(int32_t err) {
  if (err == 0) {
L
Liu Jicong 已提交
1858
    return "success";
L
Liu Jicong 已提交
1859
  } else if (err == -1) {
L
Liu Jicong 已提交
1860 1861 1862
    return "fail";
  } else {
    return tstrerror(err);
L
Liu Jicong 已提交
1863 1864
  }
}
L
Liu Jicong 已提交
1865

L
Liu Jicong 已提交
1866 1867 1868 1869
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)) {
wmmhello's avatar
wmmhello 已提交
1870 1871
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    if (pMetaRspObj->metaRsp.resMsgType == TDMT_VND_DELETE) {
1872
      return TMQ_RES_DATA;
wmmhello's avatar
wmmhello 已提交
1873
    }
L
Liu Jicong 已提交
1874
    return TMQ_RES_TABLE_META;
1875 1876
  } else if (TD_RES_TMQ_METADATA(res)) {
    return TMQ_RES_METADATA;
L
Liu Jicong 已提交
1877 1878 1879 1880 1881
  } else {
    return TMQ_RES_INVALID;
  }
}

L
Liu Jicong 已提交
1882
const char* tmq_get_topic_name(TAOS_RES* res) {
L
Liu Jicong 已提交
1883 1884
  if (TD_RES_TMQ(res)) {
    SMqRspObj* pRspObj = (SMqRspObj*)res;
L
Liu Jicong 已提交
1885
    return strchr(pRspObj->topic, '.') + 1;
L
Liu Jicong 已提交
1886 1887 1888
  } else if (TD_RES_TMQ_META(res)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    return strchr(pMetaRspObj->topic, '.') + 1;
1889 1890 1891
  } else if (TD_RES_TMQ_METADATA(res)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
    return strchr(pRspObj->topic, '.') + 1;
L
Liu Jicong 已提交
1892 1893 1894 1895 1896
  } else {
    return NULL;
  }
}

L
Liu Jicong 已提交
1897 1898 1899 1900
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 已提交
1901 1902 1903
  } else if (TD_RES_TMQ_META(res)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    return strchr(pMetaRspObj->db, '.') + 1;
1904 1905 1906
  } else if (TD_RES_TMQ_METADATA(res)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
    return strchr(pRspObj->db, '.') + 1;
L
Liu Jicong 已提交
1907 1908 1909 1910 1911
  } else {
    return NULL;
  }
}

L
Liu Jicong 已提交
1912 1913 1914 1915
int32_t tmq_get_vgroup_id(TAOS_RES* res) {
  if (TD_RES_TMQ(res)) {
    SMqRspObj* pRspObj = (SMqRspObj*)res;
    return pRspObj->vgId;
L
Liu Jicong 已提交
1916 1917 1918
  } else if (TD_RES_TMQ_META(res)) {
    SMqMetaRspObj* pMetaRspObj = (SMqMetaRspObj*)res;
    return pMetaRspObj->vgId;
1919
  } else if (TD_RES_TMQ_METADATA(res)) {
1920 1921
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
    return pRspObj->vgId;
L
Liu Jicong 已提交
1922 1923 1924 1925
  } else {
    return -1;
  }
}
L
Liu Jicong 已提交
1926 1927 1928 1929 1930 1931 1932 1933

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;
    }
1934
    return (const char*)taosArrayGetP(pRspObj->rsp.blockTbName, pRspObj->resIter);
1935 1936
  } else if (TD_RES_TMQ_METADATA(res)) {
    SMqTaosxRspObj* pRspObj = (SMqTaosxRspObj*)res;
L
Liu Jicong 已提交
1937 1938 1939
    if (!pRspObj->rsp.withTbName || pRspObj->rsp.blockTbName == NULL || pRspObj->resIter < 0 ||
        pRspObj->resIter >= pRspObj->rsp.blockNum) {
      return NULL;
1940
    }
L
Liu Jicong 已提交
1941 1942
    return (const char*)taosArrayGetP(pRspObj->rsp.blockTbName, pRspObj->resIter);
  }
L
Liu Jicong 已提交
1943 1944
  return NULL;
}
1945

L
Liu Jicong 已提交
1946
void tmq_commit_async(tmq_t* tmq, const TAOS_RES* msg, tmq_commit_cb* cb, void* param) {
1947
  //
L
Liu Jicong 已提交
1948
  tmqCommitInner(tmq, msg, 0, 1, cb, param);
L
Liu Jicong 已提交
1949 1950
}

1951 1952
int32_t tmq_commit_sync(tmq_t* tmq, const TAOS_RES* msg) {
  //
L
Liu Jicong 已提交
1953
  return tmqCommitInner(tmq, msg, 0, 0, NULL, NULL);
1954
}