clientSmlJson.c 40.9 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
#define OTD_JSON_SUB_FIELDS_NUM 2

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

wmmhello's avatar
wmmhello 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
//SArray *smlJsonParseTags(char *start, char *end){
//  SArray *tags = taosArrayInit(4, sizeof(SSmlKv));
//  while(start < end){
//    SSmlKv kv = {0};
//    kv.type = TSDB_DATA_TYPE_NCHAR;
//    bool isInQuote = false;
//    while(start < end){
//      if(unlikely(!isInQuote && *start == '"')){
//        start++;
//        kv.key = start;
//        isInQuote = true;
//        continue;
//      }
//      if(unlikely(isInQuote && *start == '"')){
//        kv.keyLen = start - kv.key;
//        start++;
//        break;
//      }
//      start++;
//    }
//    bool hasColon = false;
//    while(start < end){
//      if(unlikely(!hasColon && *start == ':')){
//        start++;
//        hasColon = true;
//        continue;
//      }
//      if(unlikely(hasColon && kv.value == NULL && (*start > 32 && *start != '"'))){
//        kv.value = start;
//        start++;
//        continue;
//      }
//
//      if(unlikely(hasColon && kv.value != NULL && (*start == '"' || *start == ',' || *start == '}'))){
//        kv.length = start - kv.value;
//        taosArrayPush(tags, &kv);
//        start++;
//        break;
//      }
//      start++;
//    }
//  }
//  return tags;
//}

//static int32_t smlParseTagsFromJSON(SSmlHandle *info, SSmlLineInfo *elements) {
//  int32_t ret = TSDB_CODE_SUCCESS;
//
//  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);
//  }
//
//  SArray *tags = smlJsonParseTags(elements->tags, elements->tags + elements->tagsLen);
//  int32_t tagNum = taosArrayGetSize(tags);
//  if (tagNum == 0) {
//    uError("SML:tag is empty:%s", elements->tags)
//    taosArrayDestroy(tags);
//    return TSDB_CODE_SML_INVALID_DATA;
//  }
//  for (int32_t i = 0; i < tagNum; ++i) {
//    SSmlKv kv = *(SSmlKv*)taosArrayGet(tags, i);
//
//    if(info->dataFormat){
//      if(unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)){
//        info->dataFormat = false;
//        info->reRun      = true;
//        taosArrayDestroy(tags);
//        return TSDB_CODE_SUCCESS;
//      }
//
//      if(isSameMeasure){
//        if(unlikely(cnt >= taosArrayGetSize(preLineKV))) {
//          info->dataFormat = false;
//          info->reRun      = true;
//          taosArrayDestroy(tags);
//          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);
146 147 148 149
//           if(unlikely(NULL == tableMeta)){
//             uError("SML:0x%" PRIx64 " NULL == tableMeta", info->id);
//             return TSDB_CODE_SML_INTERNAL_ERROR;
//           }
wmmhello's avatar
wmmhello 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
//
//          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;
//          taosArrayDestroy(tags);
//          return TSDB_CODE_SUCCESS;
//        }
//      }else{
//        if(isSuperKVInit){
//          if(unlikely(cnt >= taosArrayGetSize(superKV))) {
//            info->dataFormat = false;
//            info->reRun      = true;
//            taosArrayDestroy(tags);
//            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;
//            taosArrayDestroy(tags);
//            return TSDB_CODE_SUCCESS;
//          }
//        }else{
//          taosArrayPush(superKV, &kv);
//        }
//        taosArrayPush(preLineKV, &kv);
//      }
//    }else{
//      taosArrayPush(preLineKV, &kv);
//    }
//    cnt++;
//  }
//  taosArrayDestroy(tags);
//
//  SSmlTableInfo *tinfo = (SSmlTableInfo *)nodeListGet(info->childTables, elements, POINTER_BYTES, is_same_child_table_telnet);
//  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;
//      }
//    }
//
//    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
//    *key = *elements;
//    tinfo->key = key;
//    nodeListSet(&info->childTables, key, POINTER_BYTES, tinfo, is_same_child_table_telnet);
//  }
//  if (info->dataFormat) info->currTableDataCtx = tinfo->tableDataCtx;
//
//  return ret;
//}
222

wmmhello's avatar
wmmhello 已提交
223
static char* smlJsonGetObj(char *payload){
wmmhello's avatar
wmmhello 已提交
224 225
  int  leftBracketCnt = 0;
  bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
226
  while(*payload) {
wmmhello's avatar
wmmhello 已提交
227 228 229
    if(*payload == '"' && *(payload - 1) != '\\'){
      isInQuote = !isInQuote;
    }else if (!isInQuote && unlikely(*payload == '{')) {
wmmhello's avatar
wmmhello 已提交
230 231 232 233
      leftBracketCnt++;
      payload++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
234
    else if (!isInQuote && unlikely(*payload == '}')) {
wmmhello's avatar
wmmhello 已提交
235 236 237 238 239 240
      leftBracketCnt--;
      payload++;
      if (leftBracketCnt == 0) {
        return payload;
      } else if (leftBracketCnt < 0) {
        return NULL;
241
      }
wmmhello's avatar
wmmhello 已提交
242
      continue;
243
    }
wmmhello's avatar
wmmhello 已提交
244 245 246 247 248
    payload++;
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
249
int smlJsonParseObjFirst(char **start, SSmlLineInfo *element, int8_t *offset){
wmmhello's avatar
wmmhello 已提交
250
  int index = 0;
wmmhello's avatar
wmmhello 已提交
251
  while(*(*start)){
wmmhello's avatar
wmmhello 已提交
252 253 254 255
    if((*start)[0] != '"'){
      (*start)++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
256

wmmhello's avatar
wmmhello 已提交
257 258
    if(unlikely(index >= OTD_JSON_FIELDS_NUM)) {
      uError("index >= %d, %s", OTD_JSON_FIELDS_NUM, *start)
wmmhello's avatar
wmmhello 已提交
259
      return -1;
wmmhello's avatar
wmmhello 已提交
260 261
    }

wmmhello's avatar
wmmhello 已提交
262
    char *sTmp = *start;
wmmhello's avatar
wmmhello 已提交
263
    if((*start)[1] == 'm' && (*start)[2] == 'e' && (*start)[3] == 't'
wmmhello's avatar
wmmhello 已提交
264
       && (*start)[4] == 'r' &&  (*start)[5] == 'i' && (*start)[6] == 'c' && (*start)[7] == '"'){
wmmhello's avatar
wmmhello 已提交
265

wmmhello's avatar
wmmhello 已提交
266
      (*start) += 8;
wmmhello's avatar
wmmhello 已提交
267
      bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
268 269 270
      while(*(*start)){
        if(unlikely(!isInQuote && *(*start) == '"')){
          (*start)++;
wmmhello's avatar
wmmhello 已提交
271
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
272
          element->measure = (*start);
wmmhello's avatar
wmmhello 已提交
273 274 275
          isInQuote = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
276 277
        if(unlikely(isInQuote && *(*start) == '"')){
          element->measureLen = (*start) - element->measure;
wmmhello's avatar
wmmhello 已提交
278
          (*start)++;
wmmhello's avatar
wmmhello 已提交
279 280
          break;
        }
wmmhello's avatar
wmmhello 已提交
281
        (*start)++;
wmmhello's avatar
wmmhello 已提交
282
      }
wmmhello's avatar
wmmhello 已提交
283
    }else if((*start)[1] == 't' && (*start)[2] == 'i' && (*start)[3] == 'm'
wmmhello's avatar
wmmhello 已提交
284 285
             && (*start)[4] == 'e' &&  (*start)[5] == 's' && (*start)[6] == 't'
             && (*start)[7] == 'a' &&  (*start)[8] == 'm' && (*start)[9] == 'p' && (*start)[10] == '"'){
wmmhello's avatar
wmmhello 已提交
286

wmmhello's avatar
wmmhello 已提交
287
      (*start) += 11;
wmmhello's avatar
wmmhello 已提交
288
      bool hasColon = false;
wmmhello's avatar
wmmhello 已提交
289 290 291 292
      while(*(*start)){
        if(unlikely(!hasColon && *(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
293
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
294
          element->timestamp = (*start);
wmmhello's avatar
wmmhello 已提交
295 296 297 298 299 300 301 302
          if(*(*start) == '{'){
            char* tmp = smlJsonGetObj((*start));
            if(tmp){
              element->timestampLen = tmp - (*start);
              *start = tmp;
            }
            break;
          }
wmmhello's avatar
wmmhello 已提交
303 304 305
          hasColon = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
306
        if(unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))){
wmmhello's avatar
wmmhello 已提交
307
          element->timestampLen = (*start) - element->timestamp;
wmmhello's avatar
wmmhello 已提交
308 309
          break;
        }
wmmhello's avatar
wmmhello 已提交
310
        (*start)++;
wmmhello's avatar
wmmhello 已提交
311
      }
wmmhello's avatar
wmmhello 已提交
312
    }else if((*start)[1] == 'v' && (*start)[2] == 'a' && (*start)[3] == 'l'
wmmhello's avatar
wmmhello 已提交
313
             && (*start)[4] == 'u' &&  (*start)[5] == 'e' && (*start)[6] == '"'){
wmmhello's avatar
wmmhello 已提交
314

wmmhello's avatar
wmmhello 已提交
315
      (*start) += 7;
wmmhello's avatar
wmmhello 已提交
316 317

      bool hasColon = false;
wmmhello's avatar
wmmhello 已提交
318 319 320 321
      while(*(*start)){
        if(unlikely(!hasColon && *(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
322
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
323
          element->cols = (*start);
wmmhello's avatar
wmmhello 已提交
324 325 326 327 328 329 330 331
          if(*(*start) == '{'){
            char* tmp = smlJsonGetObj((*start));
            if(tmp){
              element->colsLen = tmp - (*start);
              *start = tmp;
            }
            break;
          }
wmmhello's avatar
wmmhello 已提交
332 333 334
          hasColon = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
335
        if(unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))){
wmmhello's avatar
wmmhello 已提交
336
          element->colsLen = (*start) - element->cols;
wmmhello's avatar
wmmhello 已提交
337 338
          break;
        }
wmmhello's avatar
wmmhello 已提交
339
        (*start)++;
wmmhello's avatar
wmmhello 已提交
340
      }
wmmhello's avatar
wmmhello 已提交
341
    }else if((*start)[1] == 't' && (*start)[2] == 'a' && (*start)[3] == 'g'
wmmhello's avatar
wmmhello 已提交
342 343 344 345 346 347 348
             && (*start)[4] == 's' && (*start)[5] == '"'){
      (*start) += 6;

      while(*(*start)){
        if(unlikely(*(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
349
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
350 351 352 353 354 355
          element->tags = (*start);
          char* tmp = smlJsonGetObj((*start));
          if(tmp){
            element->tagsLen = tmp - (*start);
            *start = tmp;
          }
wmmhello's avatar
wmmhello 已提交
356 357
          break;
        }
wmmhello's avatar
wmmhello 已提交
358
        (*start)++;
wmmhello's avatar
wmmhello 已提交
359
      }
360
    }
wmmhello's avatar
wmmhello 已提交
361 362 363
    if(*(*start) == '\0'){
      break;
    }
wmmhello's avatar
wmmhello 已提交
364 365 366 367 368
    if(*(*start) == '}'){
      (*start)++;
      break;
    }
    (*start)++;
369
  }
wmmhello's avatar
wmmhello 已提交
370

wmmhello's avatar
wmmhello 已提交
371 372
  if(unlikely(index != OTD_JSON_FIELDS_NUM) || element->tags == NULL || element->cols == NULL || element->measure == NULL || element->timestamp == NULL) {
    uError("elements != %d or element parse null", OTD_JSON_FIELDS_NUM)
wmmhello's avatar
wmmhello 已提交
373 374 375
    return -1;
  }
  return 0;
376 377
}

wmmhello's avatar
wmmhello 已提交
378
int smlJsonParseObj(char **start, SSmlLineInfo *element, int8_t *offset){
wmmhello's avatar
wmmhello 已提交
379 380 381 382 383 384 385
  int index = 0;
  while(*(*start)){
    if((*start)[0] != '"'){
      (*start)++;
      continue;
    }

wmmhello's avatar
wmmhello 已提交
386 387
    if(unlikely(index >= OTD_JSON_FIELDS_NUM)) {
      uError("index >= %d, %s", OTD_JSON_FIELDS_NUM, *start)
wmmhello's avatar
wmmhello 已提交
388
      return -1;
wmmhello's avatar
wmmhello 已提交
389 390
    }

wmmhello's avatar
wmmhello 已提交
391 392 393 394 395 396
    if((*start)[1] == 'm'){
      (*start) += offset[index++];
      element->measure = *start;
      while(*(*start)){
        if(unlikely(*(*start) == '"')){
          element->measureLen = (*start) - element->measure;
wmmhello's avatar
wmmhello 已提交
397
          (*start)++;
wmmhello's avatar
wmmhello 已提交
398 399 400 401 402 403 404
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 't' && (*start)[2] == 'i'){
      (*start) += offset[index++];
      element->timestamp = *start;
wmmhello's avatar
wmmhello 已提交
405 406 407 408 409 410
      if(*(*start) == '{'){
        char* tmp = smlJsonGetObj((*start));
        if(tmp){
          element->timestampLen = tmp - (*start);
          *start = tmp;
        }
wmmhello's avatar
wmmhello 已提交
411 412 413 414 415 416 417
      }else{
        while(*(*start)){
          if(unlikely(*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)){
            element->timestampLen = (*start) - element->timestamp;
            break;
          }
          (*start)++;
wmmhello's avatar
wmmhello 已提交
418 419 420 421 422
        }
      }
    }else if((*start)[1] == 'v'){
      (*start) += offset[index++];
      element->cols = *start;
wmmhello's avatar
wmmhello 已提交
423 424 425 426 427 428
      if(*(*start) == '{'){
        char* tmp = smlJsonGetObj((*start));
        if(tmp){
          element->colsLen = tmp - (*start);
          *start = tmp;
        }
wmmhello's avatar
wmmhello 已提交
429 430 431 432 433 434 435
      }else{
        while(*(*start)){
          if(unlikely( *(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)){
            element->colsLen = (*start) - element->cols;
            break;
          }
          (*start)++;
wmmhello's avatar
wmmhello 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        }
      }
    }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;
      }
    }
    if(*(*start) == '}'){
      (*start)++;
      break;
    }
    (*start)++;
  }
wmmhello's avatar
wmmhello 已提交
453

wmmhello's avatar
wmmhello 已提交
454
  if(unlikely(index != 0 && index != OTD_JSON_FIELDS_NUM)) {
wmmhello's avatar
wmmhello 已提交
455 456 457 458
    uError("elements != %d", OTD_JSON_FIELDS_NUM)
    return -1;
  }
  return 0;
wmmhello's avatar
wmmhello 已提交
459 460
}

wmmhello's avatar
wmmhello 已提交
461 462 463 464 465 466 467 468 469 470 471 472 473 474
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){
  for (int i = 0; i < OTD_JSON_FIELDS_NUM; ++i) {
wmmhello's avatar
wmmhello 已提交
475
    cJSON *child = root->child;
wmmhello's avatar
wmmhello 已提交
476 477 478 479 480 481 482 483 484
    while(child != NULL)
    {
      if(strcasecmp(child->string, jsonName[i]) == 0){
        *marks[i] = child;
        break;
      }
      child = child->next;
    }
    if(*marks[i] == NULL){
wmmhello's avatar
wmmhello 已提交
485
      uError("smlGetJsonElements error, not find mark:%d:%s", i, jsonName[i]);
wmmhello's avatar
wmmhello 已提交
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
      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
       */

wmmhello's avatar
wmmhello 已提交
666
      char *tsDefaultJSONStrType = "binary";  // todo
wmmhello's avatar
wmmhello 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
      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;
}

wmmhello's avatar
wmmhello 已提交
685
static int32_t smlParseTagsFromJSON(SSmlHandle *info, cJSON *tags, SSmlLineInfo *elements) {
wmmhello's avatar
wmmhello 已提交
686 687 688 689 690 691
  int32_t ret = TSDB_CODE_SUCCESS;

  bool isSameMeasure = IS_SAME_SUPER_TABLE;

  int     cnt = 0;
  SArray *preLineKV = info->preLineTagKV;
wmmhello's avatar
wmmhello 已提交
692
  SArray *maxKVs = info->maxTagKVs;
wmmhello's avatar
wmmhello 已提交
693 694 695 696
  bool    isSuperKVInit = true;
  SArray *superKV = NULL;
  if(info->dataFormat){
    if(unlikely(!isSameMeasure)){
697 698 699
      SSmlSTableMeta **tmp = (SSmlSTableMeta **)taosHashGet(info->superTables, elements->measure, elements->measureLen);
      SSmlSTableMeta *sMeta = NULL;
      if(unlikely(tmp == NULL)){
wmmhello's avatar
wmmhello 已提交
700 701 702 703 704 705
        STableMeta * pTableMeta = smlGetMeta(info, elements->measure, elements->measureLen);
        if(pTableMeta == NULL){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
wmmhello's avatar
wmmhello 已提交
706 707
        sMeta = smlBuildSTableMeta(info->dataFormat);
        sMeta->tableMeta = pTableMeta;
708 709
        taosHashPut(info->superTables, elements->measure, elements->measureLen, &sMeta, POINTER_BYTES);
        tmp = &sMeta;
wmmhello's avatar
wmmhello 已提交
710
      }
711 712
      info->currSTableMeta = (*tmp)->tableMeta;
      superKV = (*tmp)->tags;
wmmhello's avatar
wmmhello 已提交
713 714 715 716

      if(unlikely(taosArrayGetSize(superKV) == 0)){
        isSuperKVInit = false;
      }
wmmhello's avatar
wmmhello 已提交
717
      taosArraySetSize(maxKVs, 0);
wmmhello's avatar
wmmhello 已提交
718 719
    }
  }else{
wmmhello's avatar
wmmhello 已提交
720
    taosArraySetSize(maxKVs, 0);
wmmhello's avatar
wmmhello 已提交
721
  }
wmmhello's avatar
wmmhello 已提交
722
  taosArraySetSize(preLineKV, 0);
wmmhello's avatar
wmmhello 已提交
723 724

  int32_t tagNum = cJSON_GetArraySize(tags);
wmmhello's avatar
wmmhello 已提交
725 726 727 728
  if(unlikely(tagNum == 0)){
    uError("SML:Tag should not be empty");
    return TSDB_CODE_TSC_INVALID_JSON;
  }
wmmhello's avatar
wmmhello 已提交
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
  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){
wmmhello's avatar
wmmhello 已提交
757
        if(unlikely(cnt >= taosArrayGetSize(maxKVs))) {
wmmhello's avatar
wmmhello 已提交
758 759 760 761
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
wmmhello's avatar
wmmhello 已提交
762 763 764
        SSmlKv *maxKV = (SSmlKv *)taosArrayGet(maxKVs, cnt);
        if(unlikely(kv.length > maxKV->length)){
          maxKV->length = kv.length;
765
          SSmlSTableMeta **tableMeta = (SSmlSTableMeta **)taosHashGet(info->superTables, elements->measure, elements->measureLen);
766 767 768 769
          if(unlikely(NULL == tableMeta)){
            uError("SML:0x%" PRIx64 " NULL == tableMeta", info->id);
            return TSDB_CODE_SML_INTERNAL_ERROR;
          }
wmmhello's avatar
wmmhello 已提交
770

771
          SSmlKv *oldKV = (SSmlKv *)taosArrayGet((*tableMeta)->tags, cnt);
wmmhello's avatar
wmmhello 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
          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;
          }
wmmhello's avatar
wmmhello 已提交
787 788 789
          SSmlKv *maxKV = (SSmlKv *)taosArrayGet(superKV, cnt);
          if(unlikely(kv.length > maxKV->length)) {
            maxKV->length = kv.length;
wmmhello's avatar
wmmhello 已提交
790
          }else{
wmmhello's avatar
wmmhello 已提交
791
            kv.length = maxKV->length;
wmmhello's avatar
wmmhello 已提交
792 793 794 795 796 797 798 799 800 801 802
          }
          info->needModifySchema = true;

          if(unlikely(!IS_SAME_KEY)){
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }
        }else{
          taosArrayPush(superKV, &kv);
        }
wmmhello's avatar
wmmhello 已提交
803
        taosArrayPush(maxKVs, &kv);
wmmhello's avatar
wmmhello 已提交
804 805
      }
    }else{
wmmhello's avatar
wmmhello 已提交
806
      taosArrayPush(maxKVs, &kv);
wmmhello's avatar
wmmhello 已提交
807
    }
wmmhello's avatar
wmmhello 已提交
808
    taosArrayPush(preLineKV, &kv);
wmmhello's avatar
wmmhello 已提交
809 810 811
    cnt++;
  }

812 813 814
  elements->measureTag = (char*)taosMemoryMalloc(elements->measureLen + elements->tagsLen);
  memcpy(elements->measureTag, elements->measure, elements->measureLen);
  memcpy(elements->measureTag + elements->measureLen, elements->tags, elements->tagsLen);
815
  elements->measureTagsLen = elements->measureLen + elements->tagsLen;
816 817 818 819

  SSmlTableInfo **tmp = (SSmlTableInfo **)taosHashGet(info->childTables, elements->measureTag, elements->measureLen + elements->tagsLen);
  SSmlTableInfo *tinfo = NULL;
  if (unlikely(tmp == NULL)) {
wmmhello's avatar
wmmhello 已提交
820 821 822 823 824 825 826
    tinfo = smlBuildTableInfo(1, elements->measure, elements->measureLen);
    if (unlikely(!tinfo)) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    tinfo->tags = taosArrayDup(preLineKV, NULL);

    smlSetCTableName(tinfo);
wmmhello's avatar
wmmhello 已提交
827
    tinfo->uid = info->uid++;
wmmhello's avatar
wmmhello 已提交
828 829 830 831 832
    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);
833
        smlDestroyTableInfo(info, tinfo);
wmmhello's avatar
wmmhello 已提交
834 835 836 837
        return TSDB_CODE_SML_INVALID_DATA;
      }
    }

838 839 840 841 842 843 844 845 846 847
//    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
//    *key = *elements;
//    if(info->parseJsonByLib){
//      key->tags = taosMemoryMalloc(elements->tagsLen + 1);
//      memcpy(key->tags, elements->tags, elements->tagsLen);
//      key->tags[elements->tagsLen] = 0;
//    }
//    tinfo->key = key;
    taosHashPut(info->childTables, elements->measureTag, elements->measureLen + elements->tagsLen, &tinfo, POINTER_BYTES);
    tmp = &tinfo;
wmmhello's avatar
wmmhello 已提交
848
  }
849
  if (info->dataFormat) info->currTableDataCtx = (*tmp)->tableDataCtx;
wmmhello's avatar
wmmhello 已提交
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

  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;

wmmhello's avatar
wmmhello 已提交
982 983 984 985 986 987 988
  int32_t size = cJSON_GetArraySize(root);
  // outmost json fields has to be exactly 4
  if (size != OTD_JSON_FIELDS_NUM) {
    uError("OTD:0x%" PRIx64 " Invalid number of JSON fields in data point %d", info->id, size);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

wmmhello's avatar
wmmhello 已提交
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  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
wmmhello's avatar
wmmhello 已提交
1011
  bool needFree = info->dataFormat;
wmmhello's avatar
wmmhello 已提交
1012 1013
  elements->tags = cJSON_PrintUnformatted(tagsJson);
  elements->tagsLen = strlen(elements->tags);
1014
  if(is_same_child_table_telnet(elements, &info->preLine) != 0) {
wmmhello's avatar
wmmhello 已提交
1015 1016 1017 1018
    ret = smlParseTagsFromJSON(info, tagsJson, elements);
    if (unlikely(ret)) {
      uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
      taosMemoryFree(elements->tags);
wmmhello's avatar
wmmhello 已提交
1019
      elements->tags = NULL;
wmmhello's avatar
wmmhello 已提交
1020 1021
      return ret;
    }
1022 1023
  }else{
    elements->measureTag = info->preLine.measureTag;
wmmhello's avatar
wmmhello 已提交
1024 1025
  }

wmmhello's avatar
wmmhello 已提交
1026
  if(needFree){
wmmhello's avatar
wmmhello 已提交
1027
    taosMemoryFree(elements->tags);
wmmhello's avatar
wmmhello 已提交
1028
    elements->tags = NULL;
wmmhello's avatar
wmmhello 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  }

  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);
    }
wmmhello's avatar
wmmhello 已提交
1052
    clearColValArray(info->currTableDataCtx->pValues);
wmmhello's avatar
wmmhello 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 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
    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 {
wmmhello's avatar
wmmhello 已提交
1090
    uError("SML:0x%" PRIx64 " Invalid JSON Payload 3:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    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 已提交
1101 1102 1103
  if(ret != TSDB_CODE_SUCCESS){
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
1104 1105

  info->parseJsonByLib = true;
wmmhello's avatar
wmmhello 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
  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)) {
wmmhello's avatar
wmmhello 已提交
1118
      uError("SML:0x%" PRIx64 " Invalid JSON Payload 2:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
      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 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
static int32_t smlParseJSONString(SSmlHandle *info, char **start, SSmlLineInfo *elements) {
  int32_t ret = TSDB_CODE_SUCCESS;

  if(info->offset[0] == 0){
    ret = smlJsonParseObjFirst(start, elements, info->offset);
  }else{
    ret = smlJsonParseObj(start, elements, info->offset);
  }

  if (ret != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_VALUE;
  }

  if(unlikely(**start == '\0' && elements->measure == NULL)) return TSDB_CODE_SUCCESS;

1154 1155 1156 1157 1158
  if (unlikely(IS_INVALID_TABLE_LEN(elements->measureLen))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "measure is empty or too large than 192", NULL);
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

wmmhello's avatar
wmmhello 已提交
1159
  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN, .value = elements->cols, .length = (size_t)elements->colsLen};
wmmhello's avatar
wmmhello 已提交
1160 1161 1162 1163 1164 1165 1166 1167

  if (unlikely(elements->colsLen == 0)) {
    uError("SML:colsLen == 0");
    return TSDB_CODE_TSC_INVALID_VALUE;
  }else if(unlikely(elements->cols[0] == '{')){
    char tmp = elements->cols[elements->colsLen];
    elements->cols[elements->colsLen] = '\0';
    cJSON* valueJson = cJSON_Parse(elements->cols);
1168 1169 1170 1171 1172
    if (unlikely(valueJson == NULL)) {
      uError("SML:0x%" PRIx64 " parse json cols failed:%s", info->id, elements->cols);
      return TSDB_CODE_TSC_INVALID_JSON;
    }
    taosArrayPush(info->tagJsonArray, &valueJson);
wmmhello's avatar
wmmhello 已提交
1173 1174 1175 1176 1177 1178 1179 1180
    ret = smlParseValueFromJSONObj(valueJson, &kv);
    if (ret != TSDB_CODE_SUCCESS) {
      uError("SML:Failed to parse value from JSON Obj:%s", elements->cols);
      elements->cols[elements->colsLen] = tmp;
      return TSDB_CODE_TSC_INVALID_VALUE;
    }
    elements->cols[elements->colsLen] = tmp;
  }else if(smlParseValue(&kv, &info->msgBuf) != TSDB_CODE_SUCCESS){
wmmhello's avatar
wmmhello 已提交
1181 1182 1183 1184 1185
    uError("SML:cols invalidate:%s", elements->cols);
    return TSDB_CODE_TSC_INVALID_VALUE;
  }

  // Parse tags
1186
  if(is_same_child_table_telnet(elements, &info->preLine) != 0){
wmmhello's avatar
wmmhello 已提交
1187 1188 1189 1190 1191
    char tmp = *(elements->tags + elements->tagsLen);
    *(elements->tags + elements->tagsLen) = 0;
    cJSON* tagsJson = cJSON_Parse(elements->tags);
    *(elements->tags + elements->tagsLen) = tmp;
    if (unlikely(tagsJson == NULL)) {
1192
      uError("SML:0x%" PRIx64 " parse json tag failed:%s", info->id, elements->tags);
wmmhello's avatar
wmmhello 已提交
1193 1194 1195
      return TSDB_CODE_TSC_INVALID_JSON;
    }

wmmhello's avatar
wmmhello 已提交
1196
    taosArrayPush(info->tagJsonArray, &tagsJson);
wmmhello's avatar
wmmhello 已提交
1197 1198 1199 1200 1201
    ret = smlParseTagsFromJSON(info, tagsJson, elements);
    if (unlikely(ret)) {
      uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
      return ret;
    }
1202 1203
  }else{
    elements->measureTag = info->preLine.measureTag;
wmmhello's avatar
wmmhello 已提交
1204 1205 1206 1207 1208 1209 1210 1211
  }

  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 已提交
1212 1213 1214
  int64_t ts = 0;
  if(unlikely(elements->timestampLen == 0)){
    uError("OTD:0x%" PRIx64 " elements->timestampLen == 0", info->id);
wmmhello's avatar
wmmhello 已提交
1215
    return TSDB_CODE_INVALID_TIMESTAMP;
wmmhello's avatar
wmmhello 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  }else if(elements->timestamp[0] == '{'){
    char tmp = elements->timestamp[elements->timestampLen];
    elements->cols[elements->timestampLen] = '\0';
    cJSON* tsJson = cJSON_Parse(elements->timestamp);
    ts = smlParseTSFromJSON(info, tsJson);
    if (unlikely(ts < 0)) {
      uError("SML:0x%" PRIx64 " Unable to parse timestamp from JSON payload:%s", info->id, elements->timestamp);
      elements->timestamp[elements->timestampLen] = tmp;
      cJSON_Delete(tsJson);
      return TSDB_CODE_INVALID_TIMESTAMP;
    }
    elements->timestamp[elements->timestampLen] = tmp;
    cJSON_Delete(tsJson);
  }else{
    ts = smlParseOpenTsdbTime(info, elements->timestamp, elements->timestampLen);
    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 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
  }
  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);
    }
wmmhello's avatar
wmmhello 已提交
1246
    clearColValArray(info->currTableDataCtx->pValues);
wmmhello's avatar
wmmhello 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    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 已提交
1263 1264
int32_t smlParseJSON(SSmlHandle *info, char *payload) {
  int32_t payloadNum = 1 << 15;
1265 1266
  int32_t ret = TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
1267
  uDebug("SML:0x%" PRIx64 "json:%s", info->id, payload);
1268
  int cnt = 0;
wmmhello's avatar
wmmhello 已提交
1269 1270
  char *dataPointStart = payload;
  while (1) {
1271 1272
    if(info->dataFormat) {
      SSmlLineInfo element = {0};
wmmhello's avatar
wmmhello 已提交
1273
      ret = smlParseJSONString(info, &dataPointStart, &element);
1274
      if(element.measureTagsLen != 0) taosMemoryFree(element.measureTag);
1275
    }else{
wmmhello's avatar
wmmhello 已提交
1276 1277 1278 1279 1280
      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 已提交
1281
          memset(info->lines + cnt, 0, (payloadNum - cnt) * sizeof(SSmlLineInfo));
wmmhello's avatar
wmmhello 已提交
1282 1283
        }
      }
wmmhello's avatar
wmmhello 已提交
1284
      ret = smlParseJSONString(info, &dataPointStart, info->lines + cnt);
wmmhello's avatar
wmmhello 已提交
1285
      if((info->lines + cnt)->measure == NULL) break;
1286 1287
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
wmmhello's avatar
wmmhello 已提交
1288
      uError("SML:0x%" PRIx64 " Invalid JSON Payload 1:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1289
      return smlParseJSONExt(info, payload);
1290 1291 1292
    }

    if(unlikely(info->reRun)){
1293
      cnt = 0;
wmmhello's avatar
wmmhello 已提交
1294
      dataPointStart = payload;
1295 1296 1297 1298 1299 1300 1301
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
      if(ret != TSDB_CODE_SUCCESS){
        return ret;
      }
      continue;
    }
wmmhello's avatar
wmmhello 已提交
1302

1303
    cnt++;
wmmhello's avatar
wmmhello 已提交
1304
    if(*dataPointStart == '\0') break;
1305
  }
wmmhello's avatar
wmmhello 已提交
1306
  info->lineNum = cnt;
1307 1308

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