indexTfile.c 34.4 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */

dengyihao's avatar
dengyihao 已提交
15
#include "indexTfile.h"
16
#include "index.h"
dengyihao's avatar
dengyihao 已提交
17 18 19 20
#include "indexComm.h"
#include "indexFst.h"
#include "indexFstCountingWriter.h"
#include "indexUtil.h"
dengyihao's avatar
dengyihao 已提交
21
#include "taosdef.h"
22
#include "taoserror.h"
dengyihao's avatar
dengyihao 已提交
23
#include "tcoding.h"
dengyihao's avatar
dengyihao 已提交
24
#include "tcompare.h"
dengyihao's avatar
dengyihao 已提交
25

dengyihao's avatar
dengyihao 已提交
26 27
const static uint64_t tfileMagicNumber = 0xdb4775248b80fb57ull;

dengyihao's avatar
dengyihao 已提交
28 29 30 31 32 33 34
typedef struct TFileFstIter {
  FstStreamBuilder* fb;
  StreamWithState*  st;
  AutomationCtx*    ctx;
  TFileReader*      rdr;
} TFileFstIter;

dengyihao's avatar
dengyihao 已提交
35 36
#define TF_TABLE_TATOAL_SIZE(sz) (sizeof(sz) + sz * sizeof(uint64_t))

dengyihao's avatar
dengyihao 已提交
37
static int  tfileUidCompare(const void* a, const void* b);
dengyihao's avatar
dengyihao 已提交
38
static int  tfileStrCompare(const void* a, const void* b);
dengyihao's avatar
dengyihao 已提交
39 40
static int  tfileValueCompare(const void* a, const void* b, const void* param);
static void tfileSerialTableIdsToBuf(char* buf, SArray* tableIds);
dengyihao's avatar
dengyihao 已提交
41

dengyihao's avatar
dengyihao 已提交
42
static int tfileWriteHeader(TFileWriter* writer);
dengyihao's avatar
dengyihao 已提交
43
static int tfileWriteFstOffset(TFileWriter* tw, int32_t offset);
dengyihao's avatar
dengyihao 已提交
44
static int tfileWriteData(TFileWriter* write, TFileValue* tval);
dengyihao's avatar
dengyihao 已提交
45
static int tfileWriteFooter(TFileWriter* write);
dengyihao's avatar
dengyihao 已提交
46

dengyihao's avatar
dengyihao 已提交
47
// handle file corrupt later
dengyihao's avatar
dengyihao 已提交
48 49
static int tfileReaderLoadHeader(TFileReader* reader);
static int tfileReaderLoadFst(TFileReader* reader);
dengyihao's avatar
dengyihao 已提交
50
static int tfileReaderVerify(TFileReader* reader);
dengyihao's avatar
dengyihao 已提交
51
static int tfileReaderLoadTableIds(TFileReader* reader, int32_t offset, SArray* result);
dengyihao's avatar
dengyihao 已提交
52

dengyihao's avatar
dengyihao 已提交
53 54 55 56 57 58 59
static SArray* tfileGetFileList(const char* path);
static int     tfileRmExpireFile(SArray* result);
static void    tfileDestroyFileName(void* elem);
static int     tfileCompare(const void* a, const void* b);
static int     tfileParseFileName(const char* filename, uint64_t* suid, char* col, int* version);
static void    tfileGenFileName(char* filename, uint64_t suid, const char* col, int version);
static void    tfileGenFileFullName(char* fullname, const char* path, uint64_t suid, const char* col, int32_t version);
dengyihao's avatar
dengyihao 已提交
60 61 62 63 64 65 66
/*
 * search from  tfile
 */
static int32_t tfSearchTerm(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchPrefix(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchSuffix(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchRegex(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
dengyihao's avatar
dengyihao 已提交
67 68 69 70
static int32_t tfSearchLessThan(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchLessEqual(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchGreaterThan(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchGreaterEqual(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
dengyihao's avatar
dengyihao 已提交
71 72
static int32_t tfSearchRange(void* reader, SIndexTerm* tem, SIdxTempResult* tr);

dengyihao's avatar
dengyihao 已提交
73 74
static int32_t tfSearchCompareFunc(void* reader, SIndexTerm* tem, SIdxTempResult* tr, RangeType ctype);

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
static int32_t tfSearchTerm_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchPrefix_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchSuffix_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchRegex_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchLessThan_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchLessEqual_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchGreaterThan_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchGreaterEqual_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);
static int32_t tfSearchRange_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr);

static int32_t tfSearchCompareFunc_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr, RangeType ctype);

static int32_t (*tfSearch[][QUERY_MAX])(void* reader, SIndexTerm* tem, SIdxTempResult* tr) = {
    {tfSearchTerm, tfSearchPrefix, tfSearchSuffix, tfSearchRegex, tfSearchLessThan, tfSearchLessEqual,
     tfSearchGreaterThan, tfSearchGreaterEqual, tfSearchRange},
    {tfSearchTerm_JSON, tfSearchPrefix_JSON, tfSearchSuffix_JSON, tfSearchRegex_JSON, tfSearchLessThan_JSON,
     tfSearchLessEqual_JSON, tfSearchGreaterThan_JSON, tfSearchGreaterEqual_JSON, tfSearchRange_JSON}};
dengyihao's avatar
dengyihao 已提交
92

dengyihao's avatar
dengyihao 已提交
93
TFileCache* tfileCacheCreate(const char* path) {
wafwerar's avatar
wafwerar 已提交
94
  TFileCache* tcache = taosMemoryCalloc(1, sizeof(TFileCache));
dengyihao's avatar
dengyihao 已提交
95 96 97
  if (tcache == NULL) {
    return NULL;
  }
98 99 100 101

  tcache->tableCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
  tcache->capacity = 64;

dengyihao's avatar
dengyihao 已提交
102
  SArray* files = tfileGetFileList(path);
dengyihao's avatar
dengyihao 已提交
103
  for (size_t i = 0; i < taosArrayGetSize(files); i++) {
dengyihao's avatar
dengyihao 已提交
104
    char* file = taosArrayGetP(files, i);
dengyihao's avatar
dengyihao 已提交
105

dengyihao's avatar
dengyihao 已提交
106
    WriterCtx* wc = writerCtxCreate(TFile, file, true, 1024 * 1024 * 64);
107
    if (wc == NULL) {
dengyihao's avatar
dengyihao 已提交
108
      indexError("failed to open index:%s", file);
109
      goto End;
dengyihao's avatar
dengyihao 已提交
110
    }
dengyihao's avatar
dengyihao 已提交
111

dengyihao's avatar
dengyihao 已提交
112
    TFileReader* reader = tfileReaderCreate(wc);
dengyihao's avatar
dengyihao 已提交
113 114 115 116
    if (reader == NULL) {
      indexInfo("skip invalid file: %s", file);
      continue;
    }
dengyihao's avatar
dengyihao 已提交
117
    TFileHeader* header = &reader->header;
dengyihao's avatar
dengyihao 已提交
118
    ICacheKey    key = {.suid = header->suid, .colName = header->colName, .nColName = (int32_t)strlen(header->colName)};
dengyihao's avatar
dengyihao 已提交
119

dengyihao's avatar
dengyihao 已提交
120
    char    buf[128] = {0};
dengyihao's avatar
dengyihao 已提交
121 122 123
    int32_t sz = indexSerialCacheKey(&key, buf);
    assert(sz < sizeof(buf));
    taosHashPut(tcache->tableCache, buf, sz, &reader, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
124
    tfileReaderRef(reader);
dengyihao's avatar
dengyihao 已提交
125
  }
dengyihao's avatar
dengyihao 已提交
126
  taosArrayDestroyEx(files, tfileDestroyFileName);
dengyihao's avatar
dengyihao 已提交
127
  return tcache;
dengyihao's avatar
dengyihao 已提交
128
End:
129
  tfileCacheDestroy(tcache);
dengyihao's avatar
dengyihao 已提交
130
  taosArrayDestroyEx(files, tfileDestroyFileName);
131
  return NULL;
dengyihao's avatar
dengyihao 已提交
132
}
dengyihao's avatar
dengyihao 已提交
133
void tfileCacheDestroy(TFileCache* tcache) {
dengyihao's avatar
dengyihao 已提交
134 135 136
  if (tcache == NULL) {
    return;
  }
137
  // free table cache
dengyihao's avatar
dengyihao 已提交
138
  TFileReader** reader = taosHashIterate(tcache->tableCache, NULL);
139
  while (reader) {
dengyihao's avatar
dengyihao 已提交
140
    TFileReader* p = *reader;
141 142
    indexInfo("drop table cache suid: %" PRIu64 ", colName: %s, colType: %d", p->header.suid, p->header.colName,
              p->header.colType);
dengyihao's avatar
dengyihao 已提交
143
    tfileReaderUnRef(p);
144 145 146
    reader = taosHashIterate(tcache->tableCache, reader);
  }
  taosHashCleanup(tcache->tableCache);
wafwerar's avatar
wafwerar 已提交
147
  taosMemoryFree(tcache);
dengyihao's avatar
dengyihao 已提交
148 149
}

dengyihao's avatar
dengyihao 已提交
150 151 152 153
TFileReader* tfileCacheGet(TFileCache* tcache, ICacheKey* key) {
  char    buf[128] = {0};
  int32_t sz = indexSerialCacheKey(key, buf);
  assert(sz < sizeof(buf));
154
  indexInfo("Try to get key: %s", buf);
dengyihao's avatar
dengyihao 已提交
155
  TFileReader** reader = taosHashGet(tcache->tableCache, buf, sz);
156 157
  if (reader == NULL || *reader == NULL) {
    indexInfo("failed to  get key: %s", buf);
dengyihao's avatar
dengyihao 已提交
158 159
    return NULL;
  }
160
  indexInfo("Get key: %s file: %s", buf, (*reader)->ctx->file.buf);
161
  tfileReaderRef(*reader);
dengyihao's avatar
dengyihao 已提交
162

163
  return *reader;
dengyihao's avatar
dengyihao 已提交
164
}
dengyihao's avatar
dengyihao 已提交
165 166 167
void tfileCachePut(TFileCache* tcache, ICacheKey* key, TFileReader* reader) {
  char    buf[128] = {0};
  int32_t sz = indexSerialCacheKey(key, buf);
dengyihao's avatar
dengyihao 已提交
168
  // remove last version index reader
dengyihao's avatar
dengyihao 已提交
169
  TFileReader** p = taosHashGet(tcache->tableCache, buf, sz);
170
  if (p != NULL && *p != NULL) {
dengyihao's avatar
dengyihao 已提交
171
    TFileReader* oldReader = *p;
dengyihao's avatar
dengyihao 已提交
172
    taosHashRemove(tcache->tableCache, buf, sz);
173
    indexInfo("found %s, remove file %s", buf, oldReader->ctx->file.buf);
dengyihao's avatar
dengyihao 已提交
174
    oldReader->remove = true;
dengyihao's avatar
dengyihao 已提交
175
    tfileReaderUnRef(oldReader);
dengyihao's avatar
dengyihao 已提交
176
  }
dengyihao's avatar
dengyihao 已提交
177
  taosHashPut(tcache->tableCache, buf, sz, &reader, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
178
  tfileReaderRef(reader);
dengyihao's avatar
dengyihao 已提交
179
  return;
180
}
dengyihao's avatar
dengyihao 已提交
181
TFileReader* tfileReaderCreate(WriterCtx* ctx) {
wafwerar's avatar
wafwerar 已提交
182
  TFileReader* reader = taosMemoryCalloc(1, sizeof(TFileReader));
dengyihao's avatar
dengyihao 已提交
183 184 185
  if (reader == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
186
  reader->ctx = ctx;
dengyihao's avatar
dengyihao 已提交
187 188

  if (0 != tfileReaderVerify(reader)) {
dengyihao's avatar
dengyihao 已提交
189
    indexError("invalid tfile, suid: %" PRIu64 ", colName: %s", reader->header.suid, reader->header.colName);
dengyihao's avatar
dengyihao 已提交
190
    tfileReaderDestroy(reader);
dengyihao's avatar
dengyihao 已提交
191 192 193
    return NULL;
  }
  // T_REF_INC(reader);
dengyihao's avatar
dengyihao 已提交
194
  if (0 != tfileReaderLoadHeader(reader)) {
195 196
    indexError("failed to load index header, suid: %" PRIu64 ", colName: %s", reader->header.suid,
               reader->header.colName);
dengyihao's avatar
dengyihao 已提交
197
    tfileReaderDestroy(reader);
dengyihao's avatar
dengyihao 已提交
198 199 200 201
    return NULL;
  }

  if (0 != tfileReaderLoadFst(reader)) {
dengyihao's avatar
dengyihao 已提交
202 203
    indexError("failed to load index fst, suid: %" PRIu64 ", colName: %s, errno: %d", reader->header.suid,
               reader->header.colName, errno);
dengyihao's avatar
dengyihao 已提交
204 205 206
    tfileReaderDestroy(reader);
    return NULL;
  }
207
  reader->remove = false;
dengyihao's avatar
dengyihao 已提交
208

209
  return reader;
dengyihao's avatar
dengyihao 已提交
210
}
dengyihao's avatar
dengyihao 已提交
211
void tfileReaderDestroy(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
212 213 214
  if (reader == NULL) {
    return;
  }
215
  // T_REF_INC(reader);
dengyihao's avatar
dengyihao 已提交
216
  fstDestroy(reader->fst);
dengyihao's avatar
dengyihao 已提交
217
  writerCtxDestroy(reader->ctx, reader->remove);
wafwerar's avatar
wafwerar 已提交
218
  taosMemoryFree(reader);
dengyihao's avatar
dengyihao 已提交
219
}
dengyihao's avatar
dengyihao 已提交
220 221 222 223
static int32_t tfSearchTerm(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
224

dengyihao's avatar
dengyihao 已提交
225 226 227 228 229 230 231 232
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  uint64_t offset;
  if (fstGet(((TFileReader*)reader)->fst, &key, &offset)) {
    int64_t et = taosGetTimestampUs();
    int64_t cost = et - st;
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, found table info in tindex, time cost: %" PRIu64 "us",
              tem->suid, tem->colName, tem->colVal, cost);
dengyihao's avatar
dengyihao 已提交
233

dengyihao's avatar
dengyihao 已提交
234
    ret = tfileReaderLoadTableIds((TFileReader*)reader, (int32_t)offset, tr->total);
dengyihao's avatar
dengyihao 已提交
235 236 237 238 239 240 241
    cost = taosGetTimestampUs() - et;
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, load all table info, time cost: %" PRIu64 "us", tem->suid,
              tem->colName, tem->colVal, cost);
  }
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
242

dengyihao's avatar
dengyihao 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
static int32_t tfSearchPrefix(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  bool     hasJson = INDEX_TYPE_CONTAIN_EXTERN_TYPE(tem->colType, TSDB_DATA_TYPE_JSON);
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  if (hasJson) {
    p = indexPackJsonData(tem);
    sz = strlen(p);
  }

  SArray* offsets = taosArrayInit(16, sizeof(uint64_t));

  AutomationCtx*         ctx = automCtxCreate((void*)p, AUTOMATION_PREFIX);
  FstStreamBuilder*      sb = fstSearch(((TFileReader*)reader)->fst, ctx);
  StreamWithState*       st = streamBuilderIntoStream(sb);
  StreamWithStateResult* rt = NULL;
  while ((rt = streamWithStateNextWith(st, NULL)) != NULL) {
    taosArrayPush(offsets, &(rt->out.out));
    swsResultDestroy(rt);
  }
  streamWithStateDestroy(st);
  fstStreamBuilderDestroy(sb);

  int32_t ret = 0;
  for (int i = 0; i < taosArrayGetSize(offsets); i++) {
    uint64_t offset = *(uint64_t*)taosArrayGet(offsets, i);
    ret = tfileReaderLoadTableIds((TFileReader*)reader, offset, tr->total);
    if (ret != 0) {
      indexError("failed to find target tablelist");
      return TSDB_CODE_TDB_FILE_CORRUPTED;
dengyihao's avatar
add UT  
dengyihao 已提交
272
    }
dengyihao's avatar
dengyihao 已提交
273
  }
dengyihao's avatar
dengyihao 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  if (hasJson) {
    taosMemoryFree(p);
  }
  return 0;
}
static int32_t tfSearchSuffix(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  bool hasJson = INDEX_TYPE_CONTAIN_EXTERN_TYPE(tem->colType, TSDB_DATA_TYPE_JSON);

  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  if (hasJson) {
    p = indexPackJsonData(tem);
    sz = strlen(p);
  }
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  /*impl later*/
  if (hasJson) {
    taosMemoryFree(p);
  }
  fstSliceDestroy(&key);
  return 0;
}
static int32_t tfSearchRegex(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  bool hasJson = INDEX_TYPE_CONTAIN_EXTERN_TYPE(tem->colType, TSDB_DATA_TYPE_JSON);

  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  if (hasJson) {
    p = indexPackJsonData(tem);
    sz = strlen(p);
  }
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  /*impl later*/

  if (hasJson) {
    taosMemoryFree(p);
  }
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
318 319

static int32_t tfSearchCompareFunc(void* reader, SIndexTerm* tem, SIdxTempResult* tr, RangeType type) {
320 321 322 323
  int                  ret = 0;
  char*                p = tem->colVal;
  int                  skip = 0;
  _cache_range_compare cmpFn = indexGetCompare(type);
dengyihao's avatar
dengyihao 已提交
324

dengyihao's avatar
dengyihao 已提交
325 326 327 328 329
  SArray* offsets = taosArrayInit(16, sizeof(uint64_t));

  AutomationCtx*    ctx = automCtxCreate((void*)p, AUTOMATION_ALWAYS);
  FstStreamBuilder* sb = fstSearch(((TFileReader*)reader)->fst, ctx);

dengyihao's avatar
dengyihao 已提交
330
  FstSlice h = fstSliceCreate((uint8_t*)p, skip);
dengyihao's avatar
dengyihao 已提交
331 332 333 334 335 336
  fstStreamBuilderSetRange(sb, &h, type);
  fstSliceDestroy(&h);

  StreamWithState*       st = streamBuilderIntoStream(sb);
  StreamWithStateResult* rt = NULL;
  while ((rt = streamWithStateNextWith(st, NULL)) != NULL) {
337 338
    FstSlice* s = &rt->data;
    char*     ch = (char*)fstSliceData(s, NULL);
339 340 341 342 343 344
    // if (0 != strncmp(ch, tem->colName, tem->nColName)) {
    //  swsResultDestroy(rt);
    //  break;
    //}

    TExeCond cond = cmpFn(ch, p, tem->colType);
345 346 347 348 349 350 351
    if (MATCH == cond) {
      tfileReaderLoadTableIds((TFileReader*)reader, rt->out.out, tr->total);
    } else if (CONTINUE == cond) {
    } else if (BREAK == cond) {
      swsResultDestroy(rt);
      break;
    }
dengyihao's avatar
dengyihao 已提交
352 353 354 355 356 357
    swsResultDestroy(rt);
  }
  streamWithStateDestroy(st);
  fstStreamBuilderDestroy(sb);
  return TSDB_CODE_SUCCESS;
}
dengyihao's avatar
dengyihao 已提交
358
static int32_t tfSearchLessThan(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
dengyihao's avatar
dengyihao 已提交
359
  return tfSearchCompareFunc(reader, tem, tr, LT);
dengyihao's avatar
dengyihao 已提交
360 361
}
static int32_t tfSearchLessEqual(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
dengyihao's avatar
dengyihao 已提交
362
  return tfSearchCompareFunc(reader, tem, tr, LE);
dengyihao's avatar
dengyihao 已提交
363 364
}
static int32_t tfSearchGreaterThan(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
dengyihao's avatar
dengyihao 已提交
365
  return tfSearchCompareFunc(reader, tem, tr, GT);
dengyihao's avatar
dengyihao 已提交
366 367
}
static int32_t tfSearchGreaterEqual(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
dengyihao's avatar
dengyihao 已提交
368
  return tfSearchCompareFunc(reader, tem, tr, GE);
dengyihao's avatar
dengyihao 已提交
369
}
dengyihao's avatar
dengyihao 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
static int32_t tfSearchRange(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  bool     hasJson = INDEX_TYPE_CONTAIN_EXTERN_TYPE(tem->colType, TSDB_DATA_TYPE_JSON);
  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  if (hasJson) {
    p = indexPackJsonData(tem);
    sz = strlen(p);
  }
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  // uint64_t offset;
  // if (fstGet(((TFileReader*)reader)->fst, &key, &offset)) {
  //  int64_t et = taosGetTimestampUs();
  //  int64_t cost = et - st;
  //  indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, found table info in tindex, time cost: %" PRIu64 "us",
  //            tem->suid, tem->colName, tem->colVal, cost);
dengyihao's avatar
dengyihao 已提交
387

dengyihao's avatar
dengyihao 已提交
388 389 390 391 392 393 394 395 396 397 398
  //  ret = tfileReaderLoadTableIds((TFileReader*)reader, offset, tr->total);
  //  cost = taosGetTimestampUs() - et;
  //  indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, load all table info, time cost: %" PRIu64 "us", tem->suid,
  //            tem->colName, tem->colVal, cost);
  //}
  if (hasJson) {
    taosMemoryFree(p);
  }
  fstSliceDestroy(&key);
  return 0;
}
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
static int32_t tfSearchTerm_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  int   ret = 0;
  char* p = indexPackJsonData(tem);
  int   sz = strlen(p);

  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  uint64_t offset;
  if (fstGet(((TFileReader*)reader)->fst, &key, &offset)) {
    int64_t et = taosGetTimestampUs();
    int64_t cost = et - st;
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, found table info in tindex, time cost: %" PRIu64 "us",
              tem->suid, tem->colName, tem->colVal, cost);

    ret = tfileReaderLoadTableIds((TFileReader*)reader, offset, tr->total);
    cost = taosGetTimestampUs() - et;
dengyihao's avatar
dengyihao 已提交
415 416 417
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, load all table info, offset: %" PRIu64
              ", size: %d, time cost: %" PRIu64 "us",
              tem->suid, tem->colName, tem->colVal, offset, (int)taosArrayGetSize(tr->total), cost);
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  }
  fstSliceDestroy(&key);
  return 0;
  // deprecate api
  return TSDB_CODE_SUCCESS;
}
static int32_t tfSearchPrefix_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  // impl later
  return TSDB_CODE_SUCCESS;
}
static int32_t tfSearchSuffix_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  // impl later
  return TSDB_CODE_SUCCESS;
}
static int32_t tfSearchRegex_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  // impl later
  return TSDB_CODE_SUCCESS;
}
static int32_t tfSearchLessThan_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  return tfSearchCompareFunc_JSON(reader, tem, tr, LT);
}
static int32_t tfSearchLessEqual_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  return tfSearchCompareFunc_JSON(reader, tem, tr, LE);
}
static int32_t tfSearchGreaterThan_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  return tfSearchCompareFunc_JSON(reader, tem, tr, GT);
}
static int32_t tfSearchGreaterEqual_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  return tfSearchCompareFunc_JSON(reader, tem, tr, GE);
}
static int32_t tfSearchRange_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr) {
  // impl later
  return TSDB_CODE_SUCCESS;
}

static int32_t tfSearchCompareFunc_JSON(void* reader, SIndexTerm* tem, SIdxTempResult* tr, RangeType ctype) {
  int ret = 0;
  int skip = 0;

  char* p = indexPackJsonDataPrefix(tem, &skip);

  _cache_range_compare cmpFn = indexGetCompare(ctype);

  SArray* offsets = taosArrayInit(16, sizeof(uint64_t));
dengyihao's avatar
dengyihao 已提交
462

463 464 465
  AutomationCtx*    ctx = automCtxCreate((void*)p, AUTOMATION_PREFIX);
  FstStreamBuilder* sb = fstSearch(((TFileReader*)reader)->fst, ctx);

466 467 468
  // FstSlice h = fstSliceCreate((uint8_t*)p, skip);
  // fstStreamBuilderSetRange(sb, &h, ctype);
  // fstSliceDestroy(&h);
469 470 471 472 473

  StreamWithState*       st = streamBuilderIntoStream(sb);
  StreamWithStateResult* rt = NULL;
  while ((rt = streamWithStateNextWith(st, NULL)) != NULL) {
    FstSlice* s = &rt->data;
474

dengyihao's avatar
dengyihao 已提交
475 476
    int32_t sz = 0;
    char*   ch = (char*)fstSliceData(s, &sz);
dengyihao's avatar
dengyihao 已提交
477 478
    char*   tmp = taosMemoryCalloc(1, sz + 1);
    memcpy(tmp, ch, sz);
dengyihao's avatar
dengyihao 已提交
479

dengyihao's avatar
dengyihao 已提交
480
    if (0 != strncmp(tmp, p, skip)) {
481
      swsResultDestroy(rt);
dengyihao's avatar
dengyihao 已提交
482
      taosMemoryFree(tmp);
483 484 485
      break;
    }

dengyihao's avatar
dengyihao 已提交
486
    TExeCond cond = cmpFn(tmp + skip, tem->colVal, INDEX_TYPE_GET_TYPE(tem->colType));
487 488 489 490 491 492 493
    if (MATCH == cond) {
      tfileReaderLoadTableIds((TFileReader*)reader, rt->out.out, tr->total);
    } else if (CONTINUE == cond) {
    } else if (BREAK == cond) {
      swsResultDestroy(rt);
      break;
    }
dengyihao's avatar
dengyihao 已提交
494
    taosMemoryFree(tmp);
495 496 497 498 499 500
    swsResultDestroy(rt);
  }
  streamWithStateDestroy(st);
  fstStreamBuilderDestroy(sb);
  return TSDB_CODE_SUCCESS;
}
dengyihao's avatar
dengyihao 已提交
501 502 503
int tfileReaderSearch(TFileReader* reader, SIndexTermQuery* query, SIdxTempResult* tr) {
  SIndexTerm*     term = query->term;
  EIndexQueryType qtype = query->qType;
dengyihao's avatar
dengyihao 已提交
504
  int             ret = 0;
505
  if (INDEX_TYPE_CONTAIN_EXTERN_TYPE(term->colType, TSDB_DATA_TYPE_JSON)) {
dengyihao's avatar
dengyihao 已提交
506
    ret = tfSearch[1][qtype](reader, term, tr);
dengyihao's avatar
dengyihao 已提交
507
  } else {
dengyihao's avatar
dengyihao 已提交
508
    ret = tfSearch[0][qtype](reader, term, tr);
dengyihao's avatar
dengyihao 已提交
509
  }
510

dengyihao's avatar
dengyihao 已提交
511
  tfileReaderUnRef(reader);
dengyihao's avatar
dengyihao 已提交
512
  return ret;
dengyihao's avatar
dengyihao 已提交
513 514
}

dengyihao's avatar
dengyihao 已提交
515 516
TFileWriter* tfileWriterOpen(char* path, uint64_t suid, int32_t version, const char* colName, uint8_t colType) {
  char fullname[256] = {0};
dengyihao's avatar
dengyihao 已提交
517
  tfileGenFileFullName(fullname, path, suid, colName, version);
dengyihao's avatar
dengyihao 已提交
518
  // indexInfo("open write file name %s", fullname);
dengyihao's avatar
dengyihao 已提交
519
  WriterCtx* wcx = writerCtxCreate(TFile, fullname, false, 1024 * 1024 * 64);
dengyihao's avatar
dengyihao 已提交
520 521 522
  if (wcx == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
523 524 525 526 527 528 529 530 531

  TFileHeader tfh = {0};
  tfh.suid = suid;
  tfh.version = version;
  memcpy(tfh.colName, colName, strlen(colName));
  tfh.colType = colType;

  return tfileWriterCreate(wcx, &tfh);
}
dengyihao's avatar
dengyihao 已提交
532 533
TFileReader* tfileReaderOpen(char* path, uint64_t suid, int32_t version, const char* colName) {
  char fullname[256] = {0};
dengyihao's avatar
dengyihao 已提交
534 535
  tfileGenFileFullName(fullname, path, suid, colName, version);

dengyihao's avatar
dengyihao 已提交
536
  WriterCtx* wc = writerCtxCreate(TFile, fullname, true, 1024 * 1024 * 1024);
dengyihao's avatar
dengyihao 已提交
537
  if (wc == NULL) {
538 539
    terrno = TAOS_SYSTEM_ERROR(errno);
    indexError("failed to open readonly file: %s, reason: %s", fullname, terrstr());
dengyihao's avatar
dengyihao 已提交
540 541
    return NULL;
  }
542
  indexTrace("open read file name:%s, file size: %d", wc->file.buf, wc->file.size);
dengyihao's avatar
dengyihao 已提交
543

dengyihao's avatar
dengyihao 已提交
544
  TFileReader* reader = tfileReaderCreate(wc);
dengyihao's avatar
dengyihao 已提交
545 546
  return reader;
}
dengyihao's avatar
dengyihao 已提交
547
TFileWriter* tfileWriterCreate(WriterCtx* ctx, TFileHeader* header) {
wafwerar's avatar
wafwerar 已提交
548
  TFileWriter* tw = taosMemoryCalloc(1, sizeof(TFileWriter));
dengyihao's avatar
dengyihao 已提交
549
  if (tw == NULL) {
dengyihao's avatar
dengyihao 已提交
550
    indexError("index: %" PRIu64 " failed to alloc TFilerWriter", header->suid);
dengyihao's avatar
dengyihao 已提交
551 552
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
553 554
  tw->ctx = ctx;
  tw->header = *header;
dengyihao's avatar
dengyihao 已提交
555
  tfileWriteHeader(tw);
dengyihao's avatar
dengyihao 已提交
556 557
  return tw;
}
dengyihao's avatar
dengyihao 已提交
558

dengyihao's avatar
dengyihao 已提交
559
int tfileWriterPut(TFileWriter* tw, void* data, bool order) {
dengyihao's avatar
dengyihao 已提交
560
  // sort by coltype and write to tindex
dengyihao's avatar
dengyihao 已提交
561 562
  if (order == false) {
    __compar_fn_t fn;
dengyihao's avatar
dengyihao 已提交
563 564

    int8_t colType = tw->header.colType;
dengyihao's avatar
add UT  
dengyihao 已提交
565
    colType = INDEX_TYPE_GET_TYPE(colType);
dengyihao's avatar
dengyihao 已提交
566 567 568 569 570 571
    if (colType == TSDB_DATA_TYPE_BINARY || colType == TSDB_DATA_TYPE_NCHAR) {
      fn = tfileStrCompare;
    } else {
      fn = getComparFunc(colType, 0);
    }
    taosArraySortPWithExt((SArray*)(data), tfileValueCompare, &fn);
dengyihao's avatar
dengyihao 已提交
572
  }
dengyihao's avatar
dengyihao 已提交
573

dengyihao's avatar
dengyihao 已提交
574
  int32_t bufLimit = 64 * 4096, offset = 0;
wafwerar's avatar
wafwerar 已提交
575
  // char*   buf = taosMemoryCalloc(1, sizeof(char) * bufLimit);
dengyihao's avatar
dengyihao 已提交
576
  // char*   p = buf;
dengyihao's avatar
dengyihao 已提交
577
  int32_t sz = taosArrayGetSize((SArray*)data);
dengyihao's avatar
dengyihao 已提交
578 579 580 581 582
  int32_t fstOffset = tw->offset;

  // ugly code, refactor later
  for (size_t i = 0; i < sz; i++) {
    TFileValue* v = taosArrayGetP((SArray*)data, i);
dengyihao's avatar
dengyihao 已提交
583 584
    taosArraySort(v->tableId, tfileUidCompare);
    taosArrayRemoveDuplicate(v->tableId, tfileUidCompare, NULL);
dengyihao's avatar
dengyihao 已提交
585
    int32_t tbsz = taosArrayGetSize(v->tableId);
dengyihao's avatar
dengyihao 已提交
586
    fstOffset += TF_TABLE_TATOAL_SIZE(tbsz);
dengyihao's avatar
dengyihao 已提交
587 588 589
  }
  tfileWriteFstOffset(tw, fstOffset);

dengyihao's avatar
dengyihao 已提交
590 591 592 593 594 595 596
  for (size_t i = 0; i < sz; i++) {
    TFileValue* v = taosArrayGetP((SArray*)data, i);

    int32_t tbsz = taosArrayGetSize(v->tableId);
    // check buf has enough space or not
    int32_t ttsz = TF_TABLE_TATOAL_SIZE(tbsz);

wafwerar's avatar
wafwerar 已提交
597
    char* buf = taosMemoryCalloc(1, ttsz * sizeof(char));
dengyihao's avatar
dengyihao 已提交
598
    char* p = buf;
dengyihao's avatar
dengyihao 已提交
599
    tfileSerialTableIdsToBuf(p, v->tableId);
dengyihao's avatar
dengyihao 已提交
600
    tw->ctx->write(tw->ctx, buf, ttsz);
dengyihao's avatar
dengyihao 已提交
601 602
    v->offset = tw->offset;
    tw->offset += ttsz;
wafwerar's avatar
wafwerar 已提交
603
    taosMemoryFree(buf);
dengyihao's avatar
dengyihao 已提交
604
  }
dengyihao's avatar
dengyihao 已提交
605

dengyihao's avatar
dengyihao 已提交
606 607
  tw->fb = fstBuilderCreate(tw->ctx, 0);
  if (tw->fb == NULL) {
dengyihao's avatar
dengyihao 已提交
608
    tfileWriterClose(tw);
dengyihao's avatar
dengyihao 已提交
609 610
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
611 612

  // write data
dengyihao's avatar
dengyihao 已提交
613 614 615
  for (size_t i = 0; i < sz; i++) {
    // TODO, fst batch write later
    TFileValue* v = taosArrayGetP((SArray*)data, i);
dengyihao's avatar
dengyihao 已提交
616 617 618 619
    if (tfileWriteData(tw, v) != 0) {
      indexError("failed to write data: %s, offset: %d len: %d", v->colVal, v->offset,
                 (int)taosArrayGetSize(v->tableId));
    } else {
dengyihao's avatar
dengyihao 已提交
620 621
      // indexInfo("success to write data: %s, offset: %d len: %d", v->colVal, v->offset,
      //          (int)taosArrayGetSize(v->tableId));
dengyihao's avatar
dengyihao 已提交
622 623

      // indexInfo("tfile write data size: %d", tw->ctx->size(tw->ctx));
dengyihao's avatar
dengyihao 已提交
624 625
    }
  }
626

dengyihao's avatar
dengyihao 已提交
627 628 629
  fstBuilderFinish(tw->fb);
  fstBuilderDestroy(tw->fb);
  tw->fb = NULL;
dengyihao's avatar
dengyihao 已提交
630 631

  tfileWriteFooter(tw);
dengyihao's avatar
dengyihao 已提交
632 633
  return 0;
}
dengyihao's avatar
dengyihao 已提交
634
void tfileWriterClose(TFileWriter* tw) {
dengyihao's avatar
dengyihao 已提交
635 636 637
  if (tw == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
638
  writerCtxDestroy(tw->ctx, false);
wafwerar's avatar
wafwerar 已提交
639
  taosMemoryFree(tw);
dengyihao's avatar
dengyihao 已提交
640
}
dengyihao's avatar
dengyihao 已提交
641
void tfileWriterDestroy(TFileWriter* tw) {
dengyihao's avatar
dengyihao 已提交
642 643 644
  if (tw == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
645
  writerCtxDestroy(tw->ctx, false);
wafwerar's avatar
wafwerar 已提交
646
  taosMemoryFree(tw);
dengyihao's avatar
dengyihao 已提交
647
}
dengyihao's avatar
dengyihao 已提交
648

dengyihao's avatar
dengyihao 已提交
649
IndexTFile* indexTFileCreate(const char* path) {
dengyihao's avatar
dengyihao 已提交
650
  TFileCache* cache = tfileCacheCreate(path);
dengyihao's avatar
dengyihao 已提交
651 652 653
  if (cache == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
654

wafwerar's avatar
wafwerar 已提交
655
  IndexTFile* tfile = taosMemoryCalloc(1, sizeof(IndexTFile));
dengyihao's avatar
dengyihao 已提交
656 657 658 659
  if (tfile == NULL) {
    tfileCacheDestroy(cache);
    return NULL;
  }
660

dengyihao's avatar
dengyihao 已提交
661
  tfile->cache = cache;
dengyihao's avatar
dengyihao 已提交
662 663
  return tfile;
}
664
void indexTFileDestroy(IndexTFile* tfile) {
dengyihao's avatar
dengyihao 已提交
665 666 667
  if (tfile == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
668
  tfileCacheDestroy(tfile->cache);
wafwerar's avatar
wafwerar 已提交
669
  taosMemoryFree(tfile);
dengyihao's avatar
dengyihao 已提交
670
}
dengyihao's avatar
dengyihao 已提交
671

dengyihao's avatar
dengyihao 已提交
672
int indexTFileSearch(void* tfile, SIndexTermQuery* query, SIdxTempResult* result) {
dengyihao's avatar
dengyihao 已提交
673
  int ret = -1;
dengyihao's avatar
dengyihao 已提交
674 675 676
  if (tfile == NULL) {
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
677

dengyihao's avatar
add UT  
dengyihao 已提交
678
  int64_t     st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
679
  IndexTFile* pTfile = tfile;
680

dengyihao's avatar
dengyihao 已提交
681 682
  SIndexTerm* term = query->term;
  ICacheKey key = {.suid = term->suid, .colType = term->colType, .colName = term->colName, .nColName = term->nColName};
683
  TFileReader* reader = tfileCacheGet(pTfile->cache, &key);
dengyihao's avatar
dengyihao 已提交
684 685 686
  if (reader == NULL) {
    return 0;
  }
dengyihao's avatar
add UT  
dengyihao 已提交
687 688
  int64_t cost = taosGetTimestampUs() - st;
  indexInfo("index tfile stage 1 cost: %" PRId64 "", cost);
dengyihao's avatar
dengyihao 已提交
689

dengyihao's avatar
dengyihao 已提交
690
  return tfileReaderSearch(reader, query, result);
dengyihao's avatar
dengyihao 已提交
691
}
dengyihao's avatar
dengyihao 已提交
692
int indexTFilePut(void* tfile, SIndexTerm* term, uint64_t uid) {
693 694
  // TFileWriterOpt wOpt = {.suid = term->suid, .colType = term->colType, .colName = term->colName, .nColName =
  // term->nColName, .version = 1};
dengyihao's avatar
dengyihao 已提交
695

696 697
  return 0;
}
dengyihao's avatar
dengyihao 已提交
698 699 700 701 702 703 704 705 706
static bool tfileIteratorNext(Iterate* iiter) {
  IterateValue* iv = &iiter->val;
  iterateValueDestroy(iv, false);

  char*    colVal = NULL;
  uint64_t offset = 0;

  TFileFstIter*          tIter = iiter->iter;
  StreamWithStateResult* rt = streamWithStateNextWith(tIter->st, NULL);
dengyihao's avatar
dengyihao 已提交
707 708 709
  if (rt == NULL) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
710 711 712

  int32_t sz = 0;
  char*   ch = (char*)fstSliceData(&rt->data, &sz);
wafwerar's avatar
wafwerar 已提交
713
  colVal = taosMemoryCalloc(1, sz + 1);
dengyihao's avatar
dengyihao 已提交
714 715 716 717 718
  memcpy(colVal, ch, sz);

  offset = (uint64_t)(rt->out.out);
  swsResultDestroy(rt);
  // set up iterate value
dengyihao's avatar
dengyihao 已提交
719 720 721
  if (tfileReaderLoadTableIds(tIter->rdr, offset, iv->val) != 0) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
722

dengyihao's avatar
dengyihao 已提交
723
  iv->ver = 0;
724
  iv->type = ADD_VALUE;  // value in tfile always ADD_VALUE
dengyihao's avatar
dengyihao 已提交
725
  iv->colVal = colVal;
dengyihao's avatar
dengyihao 已提交
726
  return true;
dengyihao's avatar
dengyihao 已提交
727 728 729
  // std::string key(ch, sz);
}

730
static IterateValue* tifileIterateGetValue(Iterate* iter) { return &iter->val; }
dengyihao's avatar
dengyihao 已提交
731 732

static TFileFstIter* tfileFstIteratorCreate(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
733 734
  TFileFstIter* iter = taosMemoryCalloc(1, sizeof(TFileFstIter));
  if (iter == NULL) {
dengyihao's avatar
dengyihao 已提交
735 736
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
737

dengyihao's avatar
dengyihao 已提交
738 739 740 741 742
  iter->ctx = automCtxCreate(NULL, AUTOMATION_ALWAYS);
  iter->fb = fstSearch(reader->fst, iter->ctx);
  iter->st = streamBuilderIntoStream(iter->fb);
  iter->rdr = reader;
  return iter;
dengyihao's avatar
dengyihao 已提交
743 744 745
}

Iterate* tfileIteratorCreate(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
746 747 748
  if (reader == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
749

wafwerar's avatar
wafwerar 已提交
750
  Iterate* iter = taosMemoryCalloc(1, sizeof(Iterate));
dengyihao's avatar
dengyihao 已提交
751
  iter->iter = tfileFstIteratorCreate(reader);
752
  if (iter->iter == NULL) {
wafwerar's avatar
wafwerar 已提交
753
    taosMemoryFree(iter);
754 755
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
756 757
  iter->next = tfileIteratorNext;
  iter->getValue = tifileIterateGetValue;
dengyihao's avatar
dengyihao 已提交
758
  iter->val.val = taosArrayInit(1, sizeof(uint64_t));
759
  iter->val.colVal = NULL;
dengyihao's avatar
dengyihao 已提交
760 761 762
  return iter;
}
void tfileIteratorDestroy(Iterate* iter) {
dengyihao's avatar
dengyihao 已提交
763 764 765
  if (iter == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
766

dengyihao's avatar
dengyihao 已提交
767 768 769 770 771 772 773
  IterateValue* iv = &iter->val;
  iterateValueDestroy(iv, true);

  TFileFstIter* tIter = iter->iter;
  streamWithStateDestroy(tIter->st);
  fstStreamBuilderDestroy(tIter->fb);
  automCtxDestroy(tIter->ctx);
wafwerar's avatar
wafwerar 已提交
774
  taosMemoryFree(tIter);
dengyihao's avatar
dengyihao 已提交
775

wafwerar's avatar
wafwerar 已提交
776
  taosMemoryFree(iter);
dengyihao's avatar
dengyihao 已提交
777 778
}

dengyihao's avatar
dengyihao 已提交
779
TFileReader* tfileGetReaderByCol(IndexTFile* tf, uint64_t suid, char* colName) {
dengyihao's avatar
dengyihao 已提交
780 781 782
  if (tf == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
783
  ICacheKey key = {.suid = suid, .colType = TSDB_DATA_TYPE_BINARY, .colName = colName, .nColName = strlen(colName)};
dengyihao's avatar
dengyihao 已提交
784 785
  return tfileCacheGet(tf->cache, &key);
}
dengyihao's avatar
dengyihao 已提交
786

dengyihao's avatar
dengyihao 已提交
787 788 789 790 791
static int tfileUidCompare(const void* a, const void* b) {
  uint64_t l = *(uint64_t*)a;
  uint64_t r = *(uint64_t*)b;
  return l - r;
}
dengyihao's avatar
dengyihao 已提交
792 793
static int tfileStrCompare(const void* a, const void* b) {
  int ret = strcmp((char*)a, (char*)b);
dengyihao's avatar
dengyihao 已提交
794 795 796
  if (ret == 0) {
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
797 798 799
  return ret < 0 ? -1 : 1;
}

dengyihao's avatar
dengyihao 已提交
800 801 802 803 804 805 806 807
static int tfileValueCompare(const void* a, const void* b, const void* param) {
  __compar_fn_t fn = *(__compar_fn_t*)param;

  TFileValue* av = (TFileValue*)a;
  TFileValue* bv = (TFileValue*)b;

  return fn(av->colVal, bv->colVal);
}
dengyihao's avatar
dengyihao 已提交
808 809

TFileValue* tfileValueCreate(char* val) {
wafwerar's avatar
wafwerar 已提交
810
  TFileValue* tf = taosMemoryCalloc(1, sizeof(TFileValue));
dengyihao's avatar
dengyihao 已提交
811 812 813
  if (tf == NULL) {
    return NULL;
  }
814
  tf->colVal = tstrdup(val);
dengyihao's avatar
dengyihao 已提交
815 816 817 818
  tf->tableId = taosArrayInit(32, sizeof(uint64_t));
  return tf;
}
int tfileValuePush(TFileValue* tf, uint64_t val) {
dengyihao's avatar
dengyihao 已提交
819 820 821
  if (tf == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
822 823 824 825 826
  taosArrayPush(tf->tableId, &val);
  return 0;
}
void tfileValueDestroy(TFileValue* tf) {
  taosArrayDestroy(tf->tableId);
wafwerar's avatar
wafwerar 已提交
827 828
  taosMemoryFree(tf->colVal);
  taosMemoryFree(tf);
dengyihao's avatar
dengyihao 已提交
829
}
dengyihao's avatar
dengyihao 已提交
830 831 832 833 834
static void tfileSerialTableIdsToBuf(char* buf, SArray* ids) {
  int sz = taosArrayGetSize(ids);
  SERIALIZE_VAR_TO_BUF(buf, sz, int32_t);
  for (size_t i = 0; i < sz; i++) {
    uint64_t* v = taosArrayGet(ids, i);
dengyihao's avatar
dengyihao 已提交
835 836 837 838 839 840 841
    SERIALIZE_VAR_TO_BUF(buf, *v, uint64_t);
  }
}

static int tfileWriteFstOffset(TFileWriter* tw, int32_t offset) {
  int32_t fstOffset = offset + sizeof(tw->header.fstOffset);
  tw->header.fstOffset = fstOffset;
dengyihao's avatar
dengyihao 已提交
842

dengyihao's avatar
dengyihao 已提交
843 844 845
  if (sizeof(fstOffset) != tw->ctx->write(tw->ctx, (char*)&fstOffset, sizeof(fstOffset))) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
846
  indexInfo("tfile write fst offset: %d", tw->ctx->size(tw->ctx));
dengyihao's avatar
dengyihao 已提交
847
  tw->offset += sizeof(fstOffset);
dengyihao's avatar
dengyihao 已提交
848 849 850
  return 0;
}
static int tfileWriteHeader(TFileWriter* writer) {
dengyihao's avatar
dengyihao 已提交
851
  char buf[TFILE_HEADER_NO_FST] = {0};
dengyihao's avatar
dengyihao 已提交
852 853 854 855

  TFileHeader* header = &writer->header;
  memcpy(buf, (char*)header, sizeof(buf));

dengyihao's avatar
dengyihao 已提交
856
  indexInfo("tfile pre write header size: %d", writer->ctx->size(writer->ctx));
dengyihao's avatar
dengyihao 已提交
857
  int nwrite = writer->ctx->write(writer->ctx, buf, sizeof(buf));
dengyihao's avatar
dengyihao 已提交
858 859 860
  if (sizeof(buf) != nwrite) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
861 862

  indexInfo("tfile after write header size: %d", writer->ctx->size(writer->ctx));
dengyihao's avatar
dengyihao 已提交
863 864 865 866 867 868
  writer->offset = nwrite;
  return 0;
}
static int tfileWriteData(TFileWriter* write, TFileValue* tval) {
  TFileHeader* header = &write->header;
  uint8_t      colType = header->colType;
dengyihao's avatar
add UT  
dengyihao 已提交
869 870

  colType = INDEX_TYPE_GET_TYPE(colType);
871 872
  FstSlice key = fstSliceCreate((uint8_t*)(tval->colVal), (size_t)strlen(tval->colVal));
  if (fstBuilderInsert(write->fb, key, tval->offset)) {
dengyihao's avatar
dengyihao 已提交
873
    fstSliceDestroy(&key);
874
    return 0;
dengyihao's avatar
dengyihao 已提交
875
  }
876 877 878 879 880 881 882 883 884 885 886 887 888
  return -1;

  // if (colType == TSDB_DATA_TYPE_BINARY || colType == TSDB_DATA_TYPE_NCHAR) {
  //  FstSlice key = fstSliceCreate((uint8_t*)(tval->colVal), (size_t)strlen(tval->colVal));
  //  if (fstBuilderInsert(write->fb, key, tval->offset)) {
  //    fstSliceDestroy(&key);
  //    return 0;
  //  }
  //  fstSliceDestroy(&key);
  //  return -1;
  //} else {
  //  // handle other type later
  //}
dengyihao's avatar
dengyihao 已提交
889
}
dengyihao's avatar
dengyihao 已提交
890 891 892 893
static int tfileWriteFooter(TFileWriter* write) {
  char  buf[sizeof(tfileMagicNumber) + 1] = {0};
  void* pBuf = (void*)buf;
  taosEncodeFixedU64((void**)(void*)&pBuf, tfileMagicNumber);
dengyihao's avatar
dengyihao 已提交
894
  int nwrite = write->ctx->write(write->ctx, buf, (int32_t)strlen(buf));
dengyihao's avatar
dengyihao 已提交
895 896

  indexInfo("tfile write footer size: %d", write->ctx->size(write->ctx));
dengyihao's avatar
dengyihao 已提交
897 898 899
  assert(nwrite == sizeof(tfileMagicNumber));
  return nwrite;
}
dengyihao's avatar
dengyihao 已提交
900
static int tfileReaderLoadHeader(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
901
  // TODO simple tfile header later
dengyihao's avatar
dengyihao 已提交
902
  char buf[TFILE_HEADER_SIZE] = {0};
dengyihao's avatar
dengyihao 已提交
903

dengyihao's avatar
dengyihao 已提交
904
  int64_t nread = reader->ctx->readFrom(reader->ctx, buf, sizeof(buf), 0);
dengyihao's avatar
dengyihao 已提交
905
  if (nread == -1) {
dengyihao's avatar
dengyihao 已提交
906 907
    indexError("actual Read: %d, to read: %d, errno: %d, filename: %s", (int)(nread), (int)sizeof(buf), errno,
               reader->ctx->file.buf);
dengyihao's avatar
dengyihao 已提交
908
  } else {
dengyihao's avatar
dengyihao 已提交
909
    indexInfo("actual Read: %d, to read: %d, filename: %s", (int)(nread), (int)sizeof(buf), reader->ctx->file.buf);
dengyihao's avatar
dengyihao 已提交
910 911
  }
  // assert(nread == sizeof(buf));
dengyihao's avatar
dengyihao 已提交
912
  memcpy(&reader->header, buf, sizeof(buf));
dengyihao's avatar
dengyihao 已提交
913

dengyihao's avatar
dengyihao 已提交
914 915
  return 0;
}
dengyihao's avatar
dengyihao 已提交
916
static int tfileReaderLoadFst(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
917 918
  WriterCtx* ctx = reader->ctx;
  int        size = ctx->size(ctx);
dengyihao's avatar
dengyihao 已提交
919

dengyihao's avatar
dengyihao 已提交
920 921
  // current load fst into memory, refactor it later
  int   fstSize = size - reader->header.fstOffset - sizeof(tfileMagicNumber);
wafwerar's avatar
wafwerar 已提交
922
  char* buf = taosMemoryCalloc(1, fstSize);
dengyihao's avatar
dengyihao 已提交
923 924 925
  if (buf == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
926

dengyihao's avatar
dengyihao 已提交
927
  int64_t ts = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
928
  int32_t nread = ctx->readFrom(ctx, buf, fstSize, reader->header.fstOffset);
dengyihao's avatar
dengyihao 已提交
929
  int64_t cost = taosGetTimestampUs() - ts;
dengyihao's avatar
dengyihao 已提交
930
  indexInfo("nread = %d, and fst offset=%d, fst size: %d, filename: %s, file size: %d, time cost: %" PRId64 "us", nread,
dengyihao's avatar
dengyihao 已提交
931
            reader->header.fstOffset, fstSize, ctx->file.buf, ctx->file.size, cost);
dengyihao's avatar
dengyihao 已提交
932
  // we assuse fst size less than FST_MAX_SIZE
dengyihao's avatar
dengyihao 已提交
933
  assert(nread > 0 && nread <= fstSize);
dengyihao's avatar
dengyihao 已提交
934 935 936

  FstSlice st = fstSliceCreate((uint8_t*)buf, nread);
  reader->fst = fstCreate(&st);
wafwerar's avatar
wafwerar 已提交
937
  taosMemoryFree(buf);
dengyihao's avatar
dengyihao 已提交
938 939
  fstSliceDestroy(&st);

dengyihao's avatar
dengyihao 已提交
940
  return reader->fst != NULL ? 0 : -1;
dengyihao's avatar
dengyihao 已提交
941
}
dengyihao's avatar
dengyihao 已提交
942
static int tfileReaderLoadTableIds(TFileReader* reader, int32_t offset, SArray* result) {
dengyihao's avatar
dengyihao 已提交
943
  // TODO(yihao): opt later
dengyihao's avatar
dengyihao 已提交
944
  WriterCtx* ctx = reader->ctx;
945
  // add block cache
dengyihao's avatar
dengyihao 已提交
946
  char    block[4096] = {0};
947
  int32_t nread = ctx->readFrom(ctx, block, sizeof(block), offset);
dengyihao's avatar
dengyihao 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961
  assert(nread >= sizeof(uint32_t));

  char*   p = block;
  int32_t nid = *(int32_t*)p;
  p += sizeof(nid);

  while (nid > 0) {
    int32_t left = block + sizeof(block) - p;
    if (left >= sizeof(uint64_t)) {
      taosArrayPush(result, (uint64_t*)p);
      p += sizeof(uint64_t);
    } else {
      char buf[sizeof(uint64_t)] = {0};
      memcpy(buf, p, left);
dengyihao's avatar
dengyihao 已提交
962

dengyihao's avatar
dengyihao 已提交
963 964 965 966
      memset(block, 0, sizeof(block));
      offset += sizeof(block);
      nread = ctx->readFrom(ctx, block, sizeof(block), offset);
      memcpy(buf + left, block, sizeof(uint64_t) - left);
dengyihao's avatar
dengyihao 已提交
967

dengyihao's avatar
dengyihao 已提交
968 969 970 971
      taosArrayPush(result, (uint64_t*)buf);
      p = block + sizeof(uint64_t) - left;
    }
    nid -= 1;
dengyihao's avatar
dengyihao 已提交
972
  }
dengyihao's avatar
dengyihao 已提交
973 974
  return 0;
}
dengyihao's avatar
dengyihao 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
static int tfileReaderVerify(TFileReader* reader) {
  // just validate header and Footer, file corrupted also shuild be verified later
  WriterCtx* ctx = reader->ctx;

  uint64_t tMagicNumber = 0;

  char buf[sizeof(tMagicNumber) + 1] = {0};
  int  size = ctx->size(ctx);

  if (size < sizeof(tMagicNumber) || size <= sizeof(reader->header)) {
    return -1;
  } else if (ctx->readFrom(ctx, buf, sizeof(tMagicNumber), size - sizeof(tMagicNumber)) != sizeof(tMagicNumber)) {
    return -1;
  }

  taosDecodeFixedU64(buf, &tMagicNumber);
  return tMagicNumber == tfileMagicNumber ? 0 : -1;
}

dengyihao's avatar
dengyihao 已提交
994
void tfileReaderRef(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
995 996 997
  if (reader == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
998 999 1000 1001
  int ref = T_REF_INC(reader);
  UNUSED(ref);
}

dengyihao's avatar
dengyihao 已提交
1002
void tfileReaderUnRef(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
1003 1004 1005
  if (reader == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1006
  int ref = T_REF_DEC(reader);
1007
  if (ref == 0) {
dengyihao's avatar
dengyihao 已提交
1008
    // do nothing
1009 1010
    tfileReaderDestroy(reader);
  }
dengyihao's avatar
dengyihao 已提交
1011
}
dengyihao's avatar
dengyihao 已提交
1012

dengyihao's avatar
dengyihao 已提交
1013
static SArray* tfileGetFileList(const char* path) {
dengyihao's avatar
dengyihao 已提交
1014 1015 1016
  char     buf[128] = {0};
  uint64_t suid;
  uint32_t version;
dengyihao's avatar
dengyihao 已提交
1017
  SArray*  files = taosArrayInit(4, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
1018

wafwerar's avatar
wafwerar 已提交
1019 1020
  TdDirPtr pDir = taosOpenDir(path);
  if (NULL == pDir) {
dengyihao's avatar
dengyihao 已提交
1021 1022
    return NULL;
  }
wafwerar's avatar
wafwerar 已提交
1023 1024 1025
  TdDirEntryPtr pDirEntry;
  while ((pDirEntry = taosReadDir(pDir)) != NULL) {
    char* file = taosGetDirEntryName(pDirEntry);
dengyihao's avatar
dengyihao 已提交
1026 1027 1028
    if (0 != tfileParseFileName(file, &suid, buf, &version)) {
      continue;
    }
dengyihao's avatar
dengyihao 已提交
1029 1030

    size_t len = strlen(path) + 1 + strlen(file) + 1;
wafwerar's avatar
wafwerar 已提交
1031
    char*  buf = taosMemoryCalloc(1, len);
dengyihao's avatar
dengyihao 已提交
1032
    sprintf(buf, "%s/%s", path, file);
dengyihao's avatar
dengyihao 已提交
1033
    taosArrayPush(files, &buf);
dengyihao's avatar
dengyihao 已提交
1034
  }
wafwerar's avatar
wafwerar 已提交
1035
  taosCloseDir(&pDir);
dengyihao's avatar
dengyihao 已提交
1036 1037 1038 1039 1040

  taosArraySort(files, tfileCompare);
  tfileRmExpireFile(files);

  return files;
dengyihao's avatar
dengyihao 已提交
1041
}
dengyihao's avatar
dengyihao 已提交
1042 1043 1044 1045
static int tfileRmExpireFile(SArray* result) {
  // TODO(yihao): remove expire tindex after restart
  return 0;
}
dengyihao's avatar
dengyihao 已提交
1046 1047
static void tfileDestroyFileName(void* elem) {
  char* p = *(char**)elem;
wafwerar's avatar
wafwerar 已提交
1048
  taosMemoryFree(p);
dengyihao's avatar
dengyihao 已提交
1049 1050
}
static int tfileCompare(const void* a, const void* b) {
dengyihao's avatar
dengyihao 已提交
1051 1052 1053
  const char* as = *(char**)a;
  const char* bs = *(char**)b;
  return strcmp(as, bs);
dengyihao's avatar
dengyihao 已提交
1054
}
dengyihao's avatar
dengyihao 已提交
1055 1056 1057

static int tfileParseFileName(const char* filename, uint64_t* suid, char* col, int* version) {
  if (3 == sscanf(filename, "%" PRIu64 "-%[^-]-%d.tindex", suid, col, version)) {
dengyihao's avatar
dengyihao 已提交
1058 1059 1060 1061 1062
    // read suid & colid & version  success
    return 0;
  }
  return -1;
}
dengyihao's avatar
dengyihao 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
// tfile name suid-colId-version.tindex
static void tfileGenFileName(char* filename, uint64_t suid, const char* col, int version) {
  sprintf(filename, "%" PRIu64 "-%s-%d.tindex", suid, col, version);
  return;
}
static void tfileGenFileFullName(char* fullname, const char* path, uint64_t suid, const char* col, int32_t version) {
  char filename[128] = {0};
  tfileGenFileName(filename, suid, col, version);
  sprintf(fullname, "%s/%s", path, filename);
}