clientSmlJson.c 34.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * 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/>.
 */

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "clientSml.h"

wmmhello's avatar
wmmhello 已提交
22 23 24
#define OTD_JSON_SUB_FIELDS_NUM 2
#define OTD_JSON_FIELDS_NUM     4

wmmhello's avatar
wmmhello 已提交
25 26
#define JUMP_JSON_SPACE(start) \
while(*(start)){\
wmmhello's avatar
wmmhello 已提交
27
  if(unlikely(*(start) > 32))\
wmmhello's avatar
wmmhello 已提交
28 29
    break;\
  else\
wmmhello's avatar
wmmhello 已提交
30
    (start)++;\
wmmhello's avatar
wmmhello 已提交
31 32
  }

wmmhello's avatar
wmmhello 已提交
33
SArray *smlJsonParseTags(char *start, char *end){
wmmhello's avatar
wmmhello 已提交
34 35 36 37 38 39
  SArray *tags = taosArrayInit(4, sizeof(SSmlKv));
  while(start < end){
    SSmlKv kv = {0};
    kv.type = TSDB_DATA_TYPE_NCHAR;
    bool isInQuote = false;
    while(start < end){
wmmhello's avatar
wmmhello 已提交
40
      if(unlikely(!isInQuote && *start == '"')){
wmmhello's avatar
wmmhello 已提交
41 42 43 44
        start++;
        kv.key = start;
        isInQuote = true;
        continue;
45
      }
wmmhello's avatar
wmmhello 已提交
46
      if(unlikely(isInQuote && *start == '"')){
wmmhello's avatar
wmmhello 已提交
47 48 49
        kv.keyLen = start - kv.key;
        start++;
        break;
50
      }
wmmhello's avatar
wmmhello 已提交
51 52 53 54
      start++;
    }
    bool hasColon = false;
    while(start < end){
wmmhello's avatar
wmmhello 已提交
55
      if(unlikely(!hasColon && *start == ':')){
wmmhello's avatar
wmmhello 已提交
56 57 58
        start++;
        hasColon = true;
        continue;
59
      }
wmmhello's avatar
wmmhello 已提交
60
      if(unlikely(hasColon && kv.value == NULL && (*start > 32 && *start != '"'))){
wmmhello's avatar
wmmhello 已提交
61 62 63
        kv.value = start;
        start++;
        continue;
64 65
      }

wmmhello's avatar
wmmhello 已提交
66
      if(unlikely(hasColon && kv.value != NULL && (*start == '"' || *start == ',' || *start == '}'))){
wmmhello's avatar
wmmhello 已提交
67 68 69 70
        kv.length = start - kv.value;
        taosArrayPush(tags, &kv);
        start++;
        break;
71
      }
wmmhello's avatar
wmmhello 已提交
72
      start++;
73 74
    }
  }
wmmhello's avatar
wmmhello 已提交
75
  return tags;
76 77
}

wmmhello's avatar
wmmhello 已提交
78
static int32_t smlParseTagsFromJSON(SSmlHandle *info, SSmlLineInfo *elements) {
79 80
  int32_t ret = TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
81
  if(is_same_child_table_telnet(elements, &info->preLine) == 0){
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    return TSDB_CODE_SUCCESS;
  }

  bool isSameMeasure = IS_SAME_SUPER_TABLE;

  int     cnt = 0;
  SArray *preLineKV = info->preLineTagKV;
  bool    isSuperKVInit = true;
  SArray *superKV = NULL;
  if(info->dataFormat){
    if(unlikely(!isSameMeasure)){
      SSmlSTableMeta *sMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);

      if(unlikely(sMeta == NULL)){
        sMeta = smlBuildSTableMeta(info->dataFormat);
        STableMeta * pTableMeta = smlGetMeta(info, elements->measure, elements->measureLen);
        sMeta->tableMeta = pTableMeta;
        if(pTableMeta == NULL){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
        nodeListSet(&info->superTables, elements->measure, elements->measureLen, sMeta, NULL);
      }
      info->currSTableMeta = sMeta->tableMeta;
      superKV = sMeta->tags;

      if(unlikely(taosArrayGetSize(superKV) == 0)){
        isSuperKVInit = false;
      }
      taosArraySetSize(preLineKV, 0);
    }
  }else{
    taosArraySetSize(preLineKV, 0);
  }

wmmhello's avatar
wmmhello 已提交
118 119
  SArray *tags = smlJsonParseTags(elements->tags, elements->tags + elements->tagsLen);
  int32_t tagNum = taosArrayGetSize(tags);
120
  for (int32_t i = 0; i < tagNum; ++i) {
wmmhello's avatar
wmmhello 已提交
121
    SSmlKv kv = *(SSmlKv*)taosArrayGet(tags, i);
122 123 124 125 126

    if(info->dataFormat){
      if(unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)){
        info->dataFormat = false;
        info->reRun      = true;
wmmhello's avatar
wmmhello 已提交
127
        taosArrayDestroy(tags);
128 129 130 131 132 133 134
        return TSDB_CODE_SUCCESS;
      }

      if(isSameMeasure){
        if(unlikely(cnt >= taosArrayGetSize(preLineKV))) {
          info->dataFormat = false;
          info->reRun      = true;
wmmhello's avatar
wmmhello 已提交
135
          taosArrayDestroy(tags);
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
          return TSDB_CODE_SUCCESS;
        }
        SSmlKv *preKV = (SSmlKv *)taosArrayGet(preLineKV, cnt);
        if(unlikely(kv.length > preKV->length)){
          preKV->length = kv.length;
          SSmlSTableMeta *tableMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);
          ASSERT(tableMeta != NULL);

          SSmlKv *oldKV = (SSmlKv *)taosArrayGet(tableMeta->tags, cnt);
          oldKV->length = kv.length;
          info->needModifySchema = true;
        }
        if(unlikely(!IS_SAME_KEY)){
          info->dataFormat = false;
          info->reRun      = true;
wmmhello's avatar
wmmhello 已提交
151
          taosArrayDestroy(tags);
152 153 154 155 156 157 158
          return TSDB_CODE_SUCCESS;
        }
      }else{
        if(isSuperKVInit){
          if(unlikely(cnt >= taosArrayGetSize(superKV))) {
            info->dataFormat = false;
            info->reRun      = true;
wmmhello's avatar
wmmhello 已提交
159
            taosArrayDestroy(tags);
160 161 162 163 164 165 166 167 168 169 170 171 172
            return TSDB_CODE_SUCCESS;
          }
          SSmlKv *preKV = (SSmlKv *)taosArrayGet(superKV, cnt);
          if(unlikely(kv.length > preKV->length)) {
            preKV->length = kv.length;
          }else{
            kv.length = preKV->length;
          }
          info->needModifySchema = true;

          if(unlikely(!IS_SAME_KEY)){
            info->dataFormat = false;
            info->reRun      = true;
wmmhello's avatar
wmmhello 已提交
173
            taosArrayDestroy(tags);
174 175 176 177 178 179 180 181 182 183 184 185
            return TSDB_CODE_SUCCESS;
          }
        }else{
          taosArrayPush(superKV, &kv);
        }
        taosArrayPush(preLineKV, &kv);
      }
    }else{
      taosArrayPush(preLineKV, &kv);
    }
    cnt++;
  }
wmmhello's avatar
wmmhello 已提交
186
  taosArrayDestroy(tags);
187

wmmhello's avatar
wmmhello 已提交
188
  SSmlTableInfo *tinfo = (SSmlTableInfo *)nodeListGet(info->childTables, elements, POINTER_BYTES, is_same_child_table_telnet);
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  if (unlikely(tinfo == NULL)) {
    tinfo = smlBuildTableInfo(1, elements->measure, elements->measureLen);
    if (unlikely(!tinfo)) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    tinfo->tags = taosArrayDup(preLineKV, NULL);

    smlSetCTableName(tinfo);
    if (info->dataFormat) {
      info->currSTableMeta->uid = tinfo->uid;
      tinfo->tableDataCtx = smlInitTableDataCtx(info->pQuery, info->currSTableMeta);
      if (tinfo->tableDataCtx == NULL) {
        smlBuildInvalidDataMsg(&info->msgBuf, "smlInitTableDataCtx error", NULL);
        return TSDB_CODE_SML_INVALID_DATA;
      }
    }

wmmhello's avatar
wmmhello 已提交
206 207 208 209
    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
    *key = *elements;
    tinfo->key = key;
    nodeListSet(&info->childTables, key, POINTER_BYTES, tinfo, is_same_child_table_telnet);
210 211 212 213 214 215
  }
  if (info->dataFormat) info->currTableDataCtx = tinfo->tableDataCtx;

  return ret;
}

wmmhello's avatar
wmmhello 已提交
216 217 218
static char* smlJsonGetObj(char *payload){
  int   leftBracketCnt = 0;
  while(*payload) {
wmmhello's avatar
wmmhello 已提交
219
    if (unlikely(*payload == '{')) {
wmmhello's avatar
wmmhello 已提交
220 221 222 223
      leftBracketCnt++;
      payload++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
224
    if (unlikely(*payload == '}')) {
wmmhello's avatar
wmmhello 已提交
225 226 227 228 229 230
      leftBracketCnt--;
      payload++;
      if (leftBracketCnt == 0) {
        return payload;
      } else if (leftBracketCnt < 0) {
        return NULL;
231
      }
wmmhello's avatar
wmmhello 已提交
232
      continue;
233
    }
wmmhello's avatar
wmmhello 已提交
234 235 236 237 238
    payload++;
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
239
void smlJsonParseObjFirst(char **start, SSmlLineInfo *element, int8_t *offset){
wmmhello's avatar
wmmhello 已提交
240
  int index = 0;
wmmhello's avatar
wmmhello 已提交
241
  while(*(*start)){
wmmhello's avatar
wmmhello 已提交
242 243 244 245
    if((*start)[0] != '"'){
      (*start)++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
246 247 248 249 250 251

    if(unlikely(index >= 4)) {
      uError("index >= 4, %s", *start)
      break;
    }
    char *sTmp = *start;
wmmhello's avatar
wmmhello 已提交
252
    if((*start)[1] == 'm' && (*start)[2] == 'e' && (*start)[3] == 't'
wmmhello's avatar
wmmhello 已提交
253
       && (*start)[4] == 'r' &&  (*start)[5] == 'i' && (*start)[6] == 'c' && (*start)[7] == '"'){
wmmhello's avatar
wmmhello 已提交
254

wmmhello's avatar
wmmhello 已提交
255
      (*start) += 8;
wmmhello's avatar
wmmhello 已提交
256
      bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
257 258 259
      while(*(*start)){
        if(unlikely(!isInQuote && *(*start) == '"')){
          (*start)++;
wmmhello's avatar
wmmhello 已提交
260
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
261
          element->measure = (*start);
wmmhello's avatar
wmmhello 已提交
262 263 264
          isInQuote = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
265 266
        if(unlikely(isInQuote && *(*start) == '"')){
          element->measureLen = (*start) - element->measure;
wmmhello's avatar
wmmhello 已提交
267 268
          break;
        }
wmmhello's avatar
wmmhello 已提交
269
        (*start)++;
wmmhello's avatar
wmmhello 已提交
270
      }
wmmhello's avatar
wmmhello 已提交
271
    }else if((*start)[1] == 't' && (*start)[2] == 'i' && (*start)[3] == 'm'
wmmhello's avatar
wmmhello 已提交
272 273
             && (*start)[4] == 'e' &&  (*start)[5] == 's' && (*start)[6] == 't'
             && (*start)[7] == 'a' &&  (*start)[8] == 'm' && (*start)[9] == 'p' && (*start)[10] == '"'){
wmmhello's avatar
wmmhello 已提交
274

wmmhello's avatar
wmmhello 已提交
275
      (*start) += 11;
wmmhello's avatar
wmmhello 已提交
276
      bool hasColon = false;
wmmhello's avatar
wmmhello 已提交
277 278 279 280
      while(*(*start)){
        if(unlikely(!hasColon && *(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
281
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
282
          element->timestamp = (*start);
wmmhello's avatar
wmmhello 已提交
283 284 285
          hasColon = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
286
        if(unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))){
wmmhello's avatar
wmmhello 已提交
287
          element->timestampLen = (*start) - element->timestamp;
wmmhello's avatar
wmmhello 已提交
288 289
          break;
        }
wmmhello's avatar
wmmhello 已提交
290
        (*start)++;
wmmhello's avatar
wmmhello 已提交
291
      }
wmmhello's avatar
wmmhello 已提交
292
    }else if((*start)[1] == 'v' && (*start)[2] == 'a' && (*start)[3] == 'l'
wmmhello's avatar
wmmhello 已提交
293
             && (*start)[4] == 'u' &&  (*start)[5] == 'e' && (*start)[6] == '"'){
wmmhello's avatar
wmmhello 已提交
294

wmmhello's avatar
wmmhello 已提交
295
      (*start) += 7;
wmmhello's avatar
wmmhello 已提交
296 297

      bool hasColon = false;
wmmhello's avatar
wmmhello 已提交
298 299 300 301
      while(*(*start)){
        if(unlikely(!hasColon && *(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
302
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
303
          element->cols = (*start);
wmmhello's avatar
wmmhello 已提交
304 305 306
          hasColon = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
307
        if(unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))){
wmmhello's avatar
wmmhello 已提交
308
          element->colsLen = (*start) - element->cols;
wmmhello's avatar
wmmhello 已提交
309 310
          break;
        }
wmmhello's avatar
wmmhello 已提交
311
        (*start)++;
wmmhello's avatar
wmmhello 已提交
312
      }
wmmhello's avatar
wmmhello 已提交
313
    }else if((*start)[1] == 't' && (*start)[2] == 'a' && (*start)[3] == 'g'
wmmhello's avatar
wmmhello 已提交
314 315 316 317 318 319 320
             && (*start)[4] == 's' && (*start)[5] == '"'){
      (*start) += 6;

      while(*(*start)){
        if(unlikely(*(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
321
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
322 323 324 325 326 327
          element->tags = (*start);
          char* tmp = smlJsonGetObj((*start));
          if(tmp){
            element->tagsLen = tmp - (*start);
            *start = tmp;
          }
wmmhello's avatar
wmmhello 已提交
328 329
          break;
        }
wmmhello's avatar
wmmhello 已提交
330
        (*start)++;
wmmhello's avatar
wmmhello 已提交
331
      }
332
    }
wmmhello's avatar
wmmhello 已提交
333 334 335 336 337
    if(*(*start) == '}'){
      (*start)++;
      break;
    }
    (*start)++;
338 339 340
  }
}

wmmhello's avatar
wmmhello 已提交
341
void smlJsonParseObj(char **start, SSmlLineInfo *element, int8_t *offset){
wmmhello's avatar
wmmhello 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
  int index = 0;
  while(*(*start)){
    if((*start)[0] != '"'){
      (*start)++;
      continue;
    }

    if(unlikely(index >= 4)) {
      uError("index >= 4, %s", *start)
      break;
    }
    if((*start)[1] == 'm'){
      (*start) += offset[index++];
      element->measure = *start;
      while(*(*start)){
        if(unlikely(*(*start) == '"')){
          element->measureLen = (*start) - element->measure;
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 't' && (*start)[2] == 'i'){
      (*start) += offset[index++];
      element->timestamp = *start;
      while(*(*start)){
        if(unlikely(*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)){
          element->timestampLen = (*start) - element->timestamp;
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 'v'){
      (*start) += offset[index++];
      element->cols = *start;
      while(*(*start)){
        if(unlikely( *(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)){
          element->colsLen = (*start) - element->cols;
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 't' && (*start)[2] == 'a'){
      (*start) += offset[index++];
      element->tags = (*start);
      char* tmp = smlJsonGetObj((*start));
      if(tmp){
        element->tagsLen = tmp - (*start);
        *start = tmp;
      }
      break;
    }
    if(*(*start) == '}'){
      (*start)++;
      break;
    }
    (*start)++;
  }
}

wmmhello's avatar
wmmhello 已提交
401
static int32_t smlParseJSONString(SSmlHandle *info, char **start, SSmlLineInfo *elements) {
402 403
  int32_t ret = TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
404 405 406 407 408
  if(info->offset[0] == 0){
    smlJsonParseObjFirst(start, elements, info->offset);
  }else{
    smlJsonParseObj(start, elements, info->offset);
  }
wmmhello's avatar
wmmhello 已提交
409
  if(**start == '\0' && elements->measure == NULL) return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
410

wmmhello's avatar
wmmhello 已提交
411
  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN, .value = elements->cols, .length = (size_t)elements->colsLen};
wmmhello's avatar
wmmhello 已提交
412
  if (smlParseValue(&kv, &info->msgBuf) != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
413
    return TSDB_CODE_TSC_INVALID_VALUE;
414 415 416
  }

  // Parse tags
wmmhello's avatar
wmmhello 已提交
417
  ret = smlParseTagsFromJSON(info, elements);
418 419 420 421 422 423 424 425 426 427 428
  if (unlikely(ret)) {
    uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
    return ret;
  }

  if(unlikely(info->reRun)){
    return TSDB_CODE_SUCCESS;
  }

  // Parse timestamp
  // notice!!! put ts back to tag to ensure get meta->precision
wmmhello's avatar
wmmhello 已提交
429
  int64_t ts = smlParseOpenTsdbTime(info, elements->timestamp, elements->timestampLen);
430 431 432 433
  if (unlikely(ts < 0)) {
    uError("OTD:0x%" PRIx64 " Unable to parse timestamp from JSON payload", info->id);
    return TSDB_CODE_INVALID_TIMESTAMP;
  }
wmmhello's avatar
wmmhello 已提交
434
  SSmlKv kvTs = { .key = TS, .keyLen = TS_LEN, .type = TSDB_DATA_TYPE_TIMESTAMP, .i = ts, .length = (size_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

  if(info->dataFormat){
    ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kvTs, 0);
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 1);
    }
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildRow(info->currTableDataCtx);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
      return ret;
    }
  }else{
    if(elements->colArray == NULL){
      elements->colArray = taosArrayInit(16, sizeof(SSmlKv));
    }
    taosArrayPush(elements->colArray, &kvTs);
    taosArrayPush(elements->colArray, &kv);
  }
  info->preLine = *elements;

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
static inline int32_t smlParseMetricFromJSON(SSmlHandle *info, cJSON *metric, SSmlLineInfo *elements) {
  elements->measureLen = strlen(metric->valuestring);
  if (IS_INVALID_TABLE_LEN(elements->measureLen)) {
    uError("OTD:0x%" PRIx64 " Metric lenght is 0 or large than 192", info->id);
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

  elements->measure = metric->valuestring;
  return TSDB_CODE_SUCCESS;
}

const char *jsonName[OTD_JSON_FIELDS_NUM] = {"metric", "timestamp", "value", "tags"};
static int32_t smlGetJsonElements(cJSON *root, cJSON ***marks){
  cJSON *child = root->child;

  for (int i = 0; i < OTD_JSON_FIELDS_NUM; ++i) {
    while(child != NULL)
    {
      if(strcasecmp(child->string, jsonName[i]) == 0){
        *marks[i] = child;
        break;
      }
      child = child->next;
    }
    if(*marks[i] == NULL){
      uError("smlGetJsonElements error, not find mark:%s", jsonName[i]);
      return -1;
    }
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t smlConvertJSONBool(SSmlKv *pVal, char *typeStr, cJSON *value) {
  if (strcasecmp(typeStr, "bool") != 0) {
    uError("OTD:invalid type(%s) for JSON Bool", typeStr);
    return TSDB_CODE_TSC_INVALID_JSON_TYPE;
  }
  pVal->type = TSDB_DATA_TYPE_BOOL;
  pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
  pVal->i = value->valueint;

  return TSDB_CODE_SUCCESS;
}

static int32_t smlConvertJSONNumber(SSmlKv *pVal, char *typeStr, cJSON *value) {
  // tinyint
  if (strcasecmp(typeStr, "i8") == 0 || strcasecmp(typeStr, "tinyint") == 0) {
    if (!IS_VALID_TINYINT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(tinyint)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_TINYINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->i = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
  // smallint
  if (strcasecmp(typeStr, "i16") == 0 || strcasecmp(typeStr, "smallint") == 0) {
    if (!IS_VALID_SMALLINT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(smallint)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_SMALLINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->i = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
  // int
  if (strcasecmp(typeStr, "i32") == 0 || strcasecmp(typeStr, "int") == 0) {
    if (!IS_VALID_INT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(int)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_INT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->i = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
  // bigint
  if (strcasecmp(typeStr, "i64") == 0 || strcasecmp(typeStr, "bigint") == 0) {
    pVal->type = TSDB_DATA_TYPE_BIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    if (value->valuedouble >= (double)INT64_MAX) {
      pVal->i = INT64_MAX;
    } else if (value->valuedouble <= (double)INT64_MIN) {
      pVal->i = INT64_MIN;
    } else {
      pVal->i = value->valuedouble;
    }
    return TSDB_CODE_SUCCESS;
  }
  // float
  if (strcasecmp(typeStr, "f32") == 0 || strcasecmp(typeStr, "float") == 0) {
    if (!IS_VALID_FLOAT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(float)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_FLOAT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->f = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
  // double
  if (strcasecmp(typeStr, "f64") == 0 || strcasecmp(typeStr, "double") == 0) {
    pVal->type = TSDB_DATA_TYPE_DOUBLE;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->d = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }

  // if reach here means type is unsupported
  uError("OTD:invalid type(%s) for JSON Number", typeStr);
  return TSDB_CODE_TSC_INVALID_JSON_TYPE;
}

static int32_t smlConvertJSONString(SSmlKv *pVal, char *typeStr, cJSON *value) {
  if (strcasecmp(typeStr, "binary") == 0) {
    pVal->type = TSDB_DATA_TYPE_BINARY;
  } else if (strcasecmp(typeStr, "nchar") == 0) {
    pVal->type = TSDB_DATA_TYPE_NCHAR;
  } else {
    uError("OTD:invalid type(%s) for JSON String", typeStr);
    return TSDB_CODE_TSC_INVALID_JSON_TYPE;
  }
  pVal->length = (int16_t)strlen(value->valuestring);

  if (pVal->type == TSDB_DATA_TYPE_BINARY && pVal->length > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) {
    return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
  }
  if (pVal->type == TSDB_DATA_TYPE_NCHAR &&
      pVal->length > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
    return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
  }

  pVal->value = value->valuestring;
  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseValueFromJSONObj(cJSON *root, SSmlKv *kv) {
  int32_t ret = TSDB_CODE_SUCCESS;
  int32_t size = cJSON_GetArraySize(root);

  if (size != OTD_JSON_SUB_FIELDS_NUM) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  cJSON *value = cJSON_GetObjectItem(root, "value");
  if (value == NULL) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  cJSON *type = cJSON_GetObjectItem(root, "type");
  if (!cJSON_IsString(type)) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  switch (value->type) {
    case cJSON_True:
    case cJSON_False: {
      ret = smlConvertJSONBool(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    case cJSON_Number: {
      ret = smlConvertJSONNumber(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    case cJSON_String: {
      ret = smlConvertJSONString(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    default:
      return TSDB_CODE_TSC_INVALID_JSON_TYPE;
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseValueFromJSON(cJSON *root, SSmlKv *kv) {
  switch (root->type) {
    case cJSON_True:
    case cJSON_False: {
      kv->type = TSDB_DATA_TYPE_BOOL;
      kv->length = (int16_t)tDataTypes[kv->type].bytes;
      kv->i = root->valueint;
      break;
    }
    case cJSON_Number: {
      kv->type = TSDB_DATA_TYPE_DOUBLE;
      kv->length = (int16_t)tDataTypes[kv->type].bytes;
      kv->d = root->valuedouble;
      break;
    }
    case cJSON_String: {
      /* set default JSON type to binary/nchar according to
       * user configured parameter tsDefaultJSONStrType
       */

      char *tsDefaultJSONStrType = "nchar";  // todo
      smlConvertJSONString(kv, tsDefaultJSONStrType, root);
      break;
    }
    case cJSON_Object: {
      int32_t ret = smlParseValueFromJSONObj(root, kv);
      if (ret != TSDB_CODE_SUCCESS) {
        uError("OTD:Failed to parse value from JSON Obj");
        return ret;
      }
      break;
    }
    default:
      return TSDB_CODE_TSC_INVALID_JSON;
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseTagsFromJSONExt(SSmlHandle *info, cJSON *tags, SSmlLineInfo *elements) {
  int32_t ret = TSDB_CODE_SUCCESS;

  elements->tags = cJSON_PrintUnformatted(tags);
  elements->tagsLen = strlen(elements->tags);
  if(is_same_child_table_telnet(elements, &info->preLine) == 0){
    return TSDB_CODE_SUCCESS;
  }

  bool isSameMeasure = IS_SAME_SUPER_TABLE;

  int     cnt = 0;
  SArray *preLineKV = info->preLineTagKV;
  bool    isSuperKVInit = true;
  SArray *superKV = NULL;
  if(info->dataFormat){
    if(unlikely(!isSameMeasure)){
      SSmlSTableMeta *sMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);

      if(unlikely(sMeta == NULL)){
        sMeta = smlBuildSTableMeta(info->dataFormat);
        STableMeta * pTableMeta = smlGetMeta(info, elements->measure, elements->measureLen);
        sMeta->tableMeta = pTableMeta;
        if(pTableMeta == NULL){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
        nodeListSet(&info->superTables, elements->measure, elements->measureLen, sMeta, NULL);
      }
      info->currSTableMeta = sMeta->tableMeta;
      superKV = sMeta->tags;

      if(unlikely(taosArrayGetSize(superKV) == 0)){
        isSuperKVInit = false;
      }
      taosArraySetSize(preLineKV, 0);
    }
  }else{
    taosArraySetSize(preLineKV, 0);
  }

  int32_t tagNum = cJSON_GetArraySize(tags);
  for (int32_t i = 0; i < tagNum; ++i) {
    cJSON *tag = cJSON_GetArrayItem(tags, i);
    if (unlikely(tag == NULL)) {
      return TSDB_CODE_TSC_INVALID_JSON;
    }
//    if(unlikely(tag == cMeasure)) continue;
    size_t keyLen = strlen(tag->string);
    if (unlikely(IS_INVALID_COL_LEN(keyLen))) {
      uError("OTD:Tag key length is 0 or too large than 64");
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
    }

    // add kv to SSmlKv
    SSmlKv kv ={.key = tag->string, .keyLen = keyLen};
    // value
    ret = smlParseValueFromJSON(tag, &kv);
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      return ret;
    }

    if(info->dataFormat){
      if(unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)){
        info->dataFormat = false;
        info->reRun      = true;
        return TSDB_CODE_SUCCESS;
      }

      if(isSameMeasure){
        if(unlikely(cnt >= taosArrayGetSize(preLineKV))) {
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
        SSmlKv *preKV = (SSmlKv *)taosArrayGet(preLineKV, cnt);
        if(unlikely(kv.length > preKV->length)){
          preKV->length = kv.length;
          SSmlSTableMeta *tableMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);
          ASSERT(tableMeta != NULL);

          SSmlKv *oldKV = (SSmlKv *)taosArrayGet(tableMeta->tags, cnt);
          oldKV->length = kv.length;
          info->needModifySchema = true;
        }
        if(unlikely(!IS_SAME_KEY)){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
      }else{
        if(isSuperKVInit){
          if(unlikely(cnt >= taosArrayGetSize(superKV))) {
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }
          SSmlKv *preKV = (SSmlKv *)taosArrayGet(superKV, cnt);
          if(unlikely(kv.length > preKV->length)) {
            preKV->length = kv.length;
          }else{
            kv.length = preKV->length;
          }
          info->needModifySchema = true;

          if(unlikely(!IS_SAME_KEY)){
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }
        }else{
          taosArrayPush(superKV, &kv);
        }
        taosArrayPush(preLineKV, &kv);
      }
    }else{
      taosArrayPush(preLineKV, &kv);
    }
    cnt++;
  }

wmmhello's avatar
wmmhello 已提交
807
  SSmlTableInfo *tinfo = (SSmlTableInfo *)nodeListGet(info->childTables, elements, POINTER_BYTES, is_same_child_table_telnet);
wmmhello's avatar
wmmhello 已提交
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
  if (unlikely(tinfo == NULL)) {
    tinfo = smlBuildTableInfo(1, elements->measure, elements->measureLen);
    if (unlikely(!tinfo)) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    tinfo->tags = taosArrayDup(preLineKV, NULL);

    smlSetCTableName(tinfo);
    if (info->dataFormat) {
      info->currSTableMeta->uid = tinfo->uid;
      tinfo->tableDataCtx = smlInitTableDataCtx(info->pQuery, info->currSTableMeta);
      if (tinfo->tableDataCtx == NULL) {
        smlBuildInvalidDataMsg(&info->msgBuf, "smlInitTableDataCtx error", NULL);
        return TSDB_CODE_SML_INVALID_DATA;
      }
    }

wmmhello's avatar
wmmhello 已提交
825 826 827 828
    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
    *key = *elements;
    tinfo->key = key;
    nodeListSet(&info->childTables, key, POINTER_BYTES, tinfo, is_same_child_table_telnet);
wmmhello's avatar
wmmhello 已提交
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  }
  if (info->dataFormat) info->currTableDataCtx = tinfo->tableDataCtx;

  return ret;
}

static int64_t smlParseTSFromJSONObj(SSmlHandle *info, cJSON *root, int32_t toPrecision) {
  int32_t size = cJSON_GetArraySize(root);
  if (unlikely(size != OTD_JSON_SUB_FIELDS_NUM)) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
    return -1;
  }

  cJSON *value = cJSON_GetObjectItem(root, "value");
  if (unlikely(!cJSON_IsNumber(value))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
    return -1;
  }

  cJSON *type = cJSON_GetObjectItem(root, "type");
  if (unlikely(!cJSON_IsString(type))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
    return -1;
  }

  double timeDouble = value->valuedouble;
  if (unlikely(smlDoubleToInt64OverFlow(timeDouble))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
    return -1;
  }

  if (timeDouble == 0) {
    return taosGetTimestampNs()/smlFactorNS[toPrecision];
  }

  if (timeDouble < 0) {
    return timeDouble;
  }

  int64_t tsInt64 = timeDouble;
  size_t typeLen = strlen(type->valuestring);
  if (typeLen == 1 && (type->valuestring[0] == 's' || type->valuestring[0] == 'S')) {
    // seconds
    int8_t fromPrecision = TSDB_TIME_PRECISION_SECONDS;
    if(smlFactorS[toPrecision] < INT64_MAX / tsInt64){
      return tsInt64 * smlFactorS[toPrecision];
    }
    return -1;
  } else if (typeLen == 2 && (type->valuestring[1] == 's' || type->valuestring[1] == 'S')) {
    switch (type->valuestring[0]) {
      case 'm':
      case 'M':
        // milliseconds
        return convertTimePrecision(tsInt64, TSDB_TIME_PRECISION_MILLI, toPrecision);
        break;
      case 'u':
      case 'U':
        // microseconds
        return convertTimePrecision(tsInt64, TSDB_TIME_PRECISION_MICRO, toPrecision);
        break;
      case 'n':
      case 'N':
        return convertTimePrecision(tsInt64, TSDB_TIME_PRECISION_NANO, toPrecision);
        break;
      default:
        return -1;
    }
  } else {
    return -1;
  }
}

uint8_t smlGetTimestampLen(int64_t num) {
  uint8_t len = 0;
  while ((num /= 10) != 0) {
    len++;
  }
  len++;
  return len;
}

static int64_t smlParseTSFromJSON(SSmlHandle *info, cJSON *timestamp) {
  // Timestamp must be the first KV to parse
  int32_t toPrecision = info->currSTableMeta ? info->currSTableMeta->tableInfo.precision : TSDB_TIME_PRECISION_NANO;
  if (cJSON_IsNumber(timestamp)) {
    // timestamp value 0 indicates current system time
    double timeDouble = timestamp->valuedouble;
    if (unlikely(smlDoubleToInt64OverFlow(timeDouble))) {
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
      return -1;
    }

    if (unlikely(timeDouble < 0)) {
      smlBuildInvalidDataMsg(&info->msgBuf,
                             "timestamp is negative", NULL);
      return timeDouble;
    }else if (unlikely(timeDouble == 0)) {
      return taosGetTimestampNs()/smlFactorNS[toPrecision];
    }

    uint8_t tsLen = smlGetTimestampLen((int64_t)timeDouble);

    int8_t fromPrecision = smlGetTsTypeByLen(tsLen);
    if (unlikely(fromPrecision == -1)) {
      smlBuildInvalidDataMsg(&info->msgBuf,
                             "timestamp precision can only be seconds(10 digits) or milli seconds(13 digits)", NULL);
      return -1;
    }
    int64_t tsInt64 = timeDouble;
    if(fromPrecision == TSDB_TIME_PRECISION_SECONDS){
      if(smlFactorS[toPrecision] < INT64_MAX / tsInt64){
        return tsInt64 * smlFactorS[toPrecision];
      }
      return -1;
    }else{
      return convertTimePrecision(timeDouble, fromPrecision, toPrecision);
    }
  } else if (cJSON_IsObject(timestamp)) {
    return smlParseTSFromJSONObj(info, timestamp, toPrecision);
  } else {
    smlBuildInvalidDataMsg(&info->msgBuf,
                           "invalidate json", NULL);
    return -1;
  }
}

static int32_t smlParseJSONStringExt(SSmlHandle *info, cJSON *root, SSmlLineInfo *elements) {
  int32_t ret = TSDB_CODE_SUCCESS;

  cJSON *metricJson = NULL;
  cJSON *tsJson = NULL;
  cJSON *valueJson = NULL;
  cJSON *tagsJson = NULL;

  cJSON **marks[OTD_JSON_FIELDS_NUM] = {&metricJson, &tsJson, &valueJson, &tagsJson};
  ret = smlGetJsonElements(root, marks);
  if (unlikely(ret != TSDB_CODE_SUCCESS)) {
    return ret;
  }

  // Parse metric
  ret = smlParseMetricFromJSON(info, metricJson, elements);
  if (unlikely(ret != TSDB_CODE_SUCCESS)) {
    uError("OTD:0x%" PRIx64 " Unable to parse metric from JSON payload", info->id);
    return ret;
  }

  // Parse metric value
  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN};
  ret = smlParseValueFromJSON(valueJson, &kv);
  if (unlikely(ret)) {
    uError("OTD:0x%" PRIx64 " Unable to parse metric value from JSON payload", info->id);
    return ret;
  }

  // Parse tags
  ret = smlParseTagsFromJSONExt(info, tagsJson, elements);
  if (unlikely(ret)) {
    uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
    return ret;
  }

  if(unlikely(info->reRun)){
    return TSDB_CODE_SUCCESS;
  }

  // Parse timestamp
  // notice!!! put ts back to tag to ensure get meta->precision
  int64_t ts = smlParseTSFromJSON(info, tsJson);
  if (unlikely(ts < 0)) {
    uError("OTD:0x%" PRIx64 " Unable to parse timestamp from JSON payload", info->id);
    return TSDB_CODE_INVALID_TIMESTAMP;
  }
  SSmlKv kvTs = { .key = TS, .keyLen = TS_LEN, .type = TSDB_DATA_TYPE_TIMESTAMP, .i = ts, .length = (size_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};

  if(info->dataFormat){
    ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kvTs, 0);
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 1);
    }
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildRow(info->currTableDataCtx);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
      return ret;
    }
  }else{
    if(elements->colArray == NULL){
      elements->colArray = taosArrayInit(16, sizeof(SSmlKv));
    }
    taosArrayPush(elements->colArray, &kvTs);
    taosArrayPush(elements->colArray, &kv);
  }
  info->preLine = *elements;

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseJSONExt(SSmlHandle *info, char *payload) {
  int32_t payloadNum = 0;
  int32_t ret = TSDB_CODE_SUCCESS;

  if (unlikely(payload == NULL)) {
    uError("SML:0x%" PRIx64 " empty JSON Payload", info->id);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  info->root = cJSON_Parse(payload);
  if (unlikely(info->root == NULL)) {
    uError("SML:0x%" PRIx64 " parse json failed:%s", info->id, payload);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  // multiple data points must be sent in JSON array
  if (cJSON_IsArray(info->root)) {
    payloadNum = cJSON_GetArraySize(info->root);
  } else if (cJSON_IsObject(info->root)) {
    payloadNum = 1;
  } else {
    uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  info->lineNum = payloadNum;
  info->dataFormat = true;
  if (unlikely(info->lines != NULL)) {
    taosMemoryFree(info->lines);
    info->lines = NULL;
  }
  ret = smlClearForRerun(info);
wmmhello's avatar
wmmhello 已提交
1060 1061 1062
  if(ret != TSDB_CODE_SUCCESS){
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  cJSON *head = (payloadNum == 1 && cJSON_IsObject(info->root)) ? info->root : info->root->child;

  int cnt = 0;
  cJSON *dataPoint = head;
  while (dataPoint) {
    if(info->dataFormat) {
      SSmlLineInfo element = {0};
      ret = smlParseJSONStringExt(info, dataPoint, &element);
    }else{
      ret = smlParseJSONStringExt(info, dataPoint, info->lines + cnt);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
      return ret;
    }

    if(unlikely(info->reRun)){
      cnt = 0;
      dataPoint = head;
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
      if(ret != TSDB_CODE_SUCCESS){
        return ret;
      }
      continue;
    }
    cnt++;
    dataPoint = dataPoint->next;
  }

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1096 1097
int32_t smlParseJSON(SSmlHandle *info, char *payload) {
  int32_t payloadNum = 1 << 15;
1098 1099 1100
  int32_t ret = TSDB_CODE_SUCCESS;

  int cnt = 0;
wmmhello's avatar
wmmhello 已提交
1101 1102
  char *dataPointStart = payload;
  while (1) {
1103 1104
    if(info->dataFormat) {
      SSmlLineInfo element = {0};
wmmhello's avatar
wmmhello 已提交
1105
      ret = smlParseJSONString(info, &dataPointStart, &element);
1106
    }else{
wmmhello's avatar
wmmhello 已提交
1107 1108 1109 1110 1111
      if(cnt >= payloadNum){
        payloadNum = payloadNum << 1;
        void* tmp = taosMemoryRealloc(info->lines, payloadNum * sizeof(SSmlLineInfo));
        if(tmp != NULL){
          info->lines = (SSmlLineInfo*)tmp;
wmmhello's avatar
wmmhello 已提交
1112
          memset(info->lines + cnt, 0, (payloadNum - cnt) * sizeof(SSmlLineInfo));
wmmhello's avatar
wmmhello 已提交
1113 1114
        }
      }
wmmhello's avatar
wmmhello 已提交
1115
      ret = smlParseJSONString(info, &dataPointStart, info->lines + cnt);
1116 1117 1118
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
wmmhello's avatar
wmmhello 已提交
1119
      return smlParseJSONExt(info, payload);
1120 1121 1122
    }

    if(unlikely(info->reRun)){
1123
      cnt = 0;
wmmhello's avatar
wmmhello 已提交
1124
      dataPointStart = payload;
1125 1126 1127 1128 1129 1130 1131
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
      if(ret != TSDB_CODE_SUCCESS){
        return ret;
      }
      continue;
    }
wmmhello's avatar
wmmhello 已提交
1132 1133

    if(*dataPointStart == '\0') break;
1134
    cnt++;
1135
  }
wmmhello's avatar
wmmhello 已提交
1136
  info->lineNum = cnt;
1137 1138

  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1139
}