# All files / utils fromFlux.ts

94.28% Statements 231/245
72.85% Branches 51/70
100% Functions 22/22
93.03% Lines 187/201

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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
    146
    147
    148
    149
    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
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    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
    272
    273
    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
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    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
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    52915x

    15x
    15x
    15x

    15x
    23x
    23x
    23x
    23x

    23x
    23x

    23x
    23x
    23x
    23x
    23x
    23x

    35x
    35x

    35x
    35x

    35x
    89999x
    101x

    89898x

    35x

    35x

    33x

    33x

    33x

    33x

    279x
    279x

    279x

    279x

    279x
    168x

    279x

    279x
    718927x
    89857x
    33x
    89824x
    89822x

    718927x

    279x
    170x

    33x

    21x

    21x
    168x
    168x
    168x

    21x

    21x

    2x

    15x
    17x
    17x
    17x
    17x

    17x
    17x

    17x

    17x

    17x
    17x
    29x
    29x

    29x
    17x
    17x
    17x

    12x
    12x

    17x
    17x
    17x
    17x
    17x
    17x

    29x
    29x

    29x
    29x

    29x
    148x
    83x

    65x

    29x

    29x

    27x

    27x

    27x

    27x

    229x
    229x

    229x

    229x

    229x
    118x

    229x

    229x
    297x
    30x
    26x
    4x
    2x

    297x
    297x

    297x

    297x

    297x

    297x

    297x

    297x
    209x
    88x
    45x
    43x
    43x
    1x

    42x
    42x

    297x

    229x
    144x

    27x

    15x

    15x
    118x
    118x
    118x

    15x

    15x

    2x

    15x
    23x

    23x

    23x

    35x

    23x

    15x

    60x

    66x
    114x
    180x

    60x
    60x
    60x

    60x
    562x

    60x

    508x

    60x

    508x

    60x

    15x

    15x
    718927x

    718927x

    718927x

    718927x

    718927x

    718927x
    449344x

    269583x
    89886x

    179697x
    179697x
    1x

    179696x
    179696x

    15x

    36x
    286x
    286x

    36x
    282x
    278x

    278x
    278x

    278x

    278x

    278x
    180x
    180x

     import {csvParse, csvParseRows} from 'd3-dsv'
    import {Table, ColumnType, FluxDataType} from '../types'
    import {assert} from './assert'
    import {newTable} from './newTable'
    import {RESULT} from '../constants/columnKeys'
    export interface FromFluxResult {
      error?: Error

      // The single parsed `Table`
      table: Table

      // The union of unique group keys from all input Flux tables
      fluxGroupKeyUnion: string[]

      // All possible values of the "result" column
      resultColumnNames: string[]
    }

    type Column =
      | {
          name: string
          type: 'number'
          fluxDataType: FluxDataType
          data: Array<number | null>
        } //  parses empty numeric values as null
      | {name: string; type: 'time'; fluxDataType: FluxDataType; data: number[]}
      | {name: string; type: 'boolean'; fluxDataType: FluxDataType; data: boolean[]}
      | {name: string; type: 'string'; fluxDataType: FluxDataType; data: string[]}

    interface Columns {
      [columnKey: string]: Column
    }

    /*
      Convert a [Flux CSV response][0] to a `Table`.
      For example, given a series of Flux tables that look like this:
          column_a | column_b | column_c  <-- name
          long     | string   | long      <-- type
          ------------------------------
                 1 |      "g" |       34
                 2 |      "f" |       58
                 3 |      "c" |       21
          column_b | column_d   <-- name
          double   | boolean    <-- type
          -------------------
               1.0 |     true
               2.0 |     true
               3.0 |     true
      This function will spread them out to a single wide table that looks like
      this instead:
          column_a | column_b (string) | column_c | column_b (number) | column_d  <-- key
          column_a | column_b          | column_c | column_b          | column_d  <-- name
          number   | string            | number   | number            | bool      <-- type
          ---------------------------------------------------------------------
                 1 |               "g" |       34 |                   |
                 2 |               "f" |       58 |                   |
                 3 |                   |       21 |                   |
                   |                   |          |               1.0 |     true
                   |                   |          |               2.0 |     true
                   |                   |          |               3.0 |     true
      The `#group`, `#datatype`, and `#default` [annotations][1] are expected to be
      in the input Flux CSV.
      Values are coerced into appropriate JavaScript types based on the Flux
      `#datatype` annotation for the table
      The `Table` stores a `key` for each column which is seperate from the column
      `name`. If multiple Flux tables have the same column but with different
      types, they will be distinguished by different keys in the resulting `Table`;
      otherwise the `key` and `name` for each column in the result table will be
      identical.
      [0]: https://github.com/influxdata/flux/blob/master/docs/SPEC.md#csv
      [1]: https://github.com/influxdata/flux/blob/master/docs/SPEC.md#annotations
    */
    export const fromFlux = (fluxCSV: string): FromFluxResult => {
      const columns: Columns = {}
      const fluxGroupKeyUnion = new Set<string>()
      const resultColumnNames = new Set<string>()
      let tableLength = 0

      try {
        const chunks = splitChunks(fluxCSV)

        // declaring all nested variables here to reduce memory drain
        let tableText = ''
        let tableData: any = []
        let annotationText = ''
        let columnType: any = ''
        let columnKey = ''
        let columnDefault: any = ''

        for (const chunk of chunks) {
          const splittedChunk = chunk.split('\n')

          const tableTexts = []
          const annotationTexts = []

          splittedChunk.forEach(line => {
            if (line.startsWith('#')) {
              annotationTexts.push(line)
            } else {
              tableTexts.push(line)
            }
          })

          tableText = tableTexts.join('\n').trim()

          assert(
            !!tableText,
            'could not find annotation lines in Flux response; are `annotations` enabled in the Flux query `dialect` option?'
          )

          tableData = csvParse(tableText)

          annotationText = annotationTexts.join('\n').trim()

          assert(
            !!annotationText,
            'could not find annotation lines in Flux response; are `annotations` enabled in the Flux query `dialect` option?'
          )
          const annotationData = parseAnnotations(annotationText, tableData.columns)

          for (const columnName of tableData.columns.slice(1)) {
            columnType =
              TO_COLUMN_TYPE[annotationData.datatypeByColumnName[columnName]]

            assert(
              !!columnType,
              `encountered unknown Flux column type ${annotationData.datatypeByColumnName[columnName]}`
            )

            columnKey = `${columnName} (${columnType})`

            if (!columns[columnKey]) {
              columns[columnKey] = {
                name: columnName,
                type: columnType,
                fluxDataType: annotationData.datatypeByColumnName[columnName],
                data: [],
              } as Column
            }

            columnDefault = annotationData.defaultByColumnName[columnName]

            for (let i = 0; i < tableData.length; i++) {
              if (columnName === RESULT) {
                if (columnDefault.length) {
                  resultColumnNames.add(columnDefault)
                } else if (tableData[i][columnName].length) {
                  resultColumnNames.add(tableData[i][columnName])
                }
              }
              columns[columnKey].data[tableLength + i] = parseValue(
                tableData[i][columnName] || columnDefault,
                columnType
              )
            }

            if (annotationData.groupKey.includes(columnName)) {
              fluxGroupKeyUnion.add(columnKey)
            }
          }

          tableLength += tableData.length
        }

        resolveNames(columns, fluxGroupKeyUnion)

        const table = Object.entries(columns).reduce(
          (table, [key, {name, fluxDataType, type, data}]) => {
            data.length = tableLength
            return table.addColumn(key, fluxDataType, type, data, name)
          },
          newTable(tableLength)
        )

        const result = {
          table,
          fluxGroupKeyUnion: Array.from(fluxGroupKeyUnion),
          resultColumnNames: Array.from(resultColumnNames),
        }

        return result
      } catch (error) {
        return {
          error: error as Error,
          table: newTable(0),
          fluxGroupKeyUnion: [],
          resultColumnNames: [],
        }
      }
    }

    export const fastFromFlux = (fluxCSV: string): FromFluxResult => {
      const columns: Columns = {}
      const fluxGroupKeyUnion = new Set<string>()
      const resultColumnNames = new Set<string>()
      let tableLength = 0

      try {
        fluxCSV = fluxCSV.trimEnd()

        Iif (fluxCSV === '') {
          return {
            table: newTable(0),
            fluxGroupKeyUnion: [],
            resultColumnNames: [],
          }
        }

        // Split the response into separate chunks whenever we encounter:
        //
        // 1. A newline
        // 2. Followed by any amount of whitespace
        // 3. Followed by a newline
        // 4. Followed by a `#` character
        //
        // The last condition is [necessary][0] for handling CSV responses with
        // values containing newlines.
        //
        // [0]: https://github.com/influxdata/influxdb/issues/15017

        // finds the first non-whitespace character
        let curr = fluxCSV.search(/\S/)

        const chunks = []
        while (curr !== -1) {
          const oldVal = curr
          const nextIndex = fluxCSV
            .substring(curr, fluxCSV.length)
            .search(/\n\s*\n#/)
          if (nextIndex === -1) {
            chunks.push([oldVal, fluxCSV.length])
            curr = -1
            break
          } else {
            chunks.push([oldVal, oldVal + nextIndex])
            curr = oldVal + nextIndex + 2
          }
        }

        // declaring all nested variables here to reduce memory drain
        let tableText = ''
        let tableData: any = []
        let annotationText = ''
        let columnType: any = ''
        let columnKey = ''
        let columnDefault: any = ''

        for (const [start, end] of chunks) {
          const splittedChunk = fluxCSV.substring(start, end).split('\n')

          const tableTexts = []
          const annotationTexts = []

          splittedChunk.forEach(line => {
            if (line.startsWith('#')) {
              annotationTexts.push(line)
            } else {
              tableTexts.push(line)
            }
          })

          tableText = tableTexts.join('\n').trim()

          assert(
            !!tableText,
            'could not find annotation lines in Flux response; are `annotations` enabled in the Flux query `dialect` option?'
          )

          // TODO(ariel): csvParse is a slow operation
          tableData = csvParse(tableText)

          annotationText = annotationTexts.join('\n').trim()

          assert(
            !!annotationText,
            'could not find annotation lines in Flux response; are `annotations` enabled in the Flux query `dialect` option?'
          )
          const annotationData = parseAnnotations(annotationText, tableData.columns)

          for (const columnName of tableData.columns.slice(1)) {
            columnType =
              TO_COLUMN_TYPE[annotationData.datatypeByColumnName[columnName]]

            assert(
              !!columnType,
              `encountered unknown Flux column type ${annotationData.datatypeByColumnName[columnName]}`
            )

            columnKey = `${columnName} (${columnType})`

            if (!columns[columnKey]) {
              columns[columnKey] = {
                name: columnName,
                type: columnType,
                fluxDataType: annotationData.datatypeByColumnName[columnName],
                data: [],
              } as Column
            }

            columnDefault = annotationData.defaultByColumnName[columnName]

            for (let i = 0; i < tableData.length; i++) {
              if (columnName === RESULT) {
                if (columnDefault.length) {
                  resultColumnNames.add(columnDefault)
                } else if (tableData[i][columnName].length) {
                  resultColumnNames.add(tableData[i][columnName])
                }
              }
              const value = tableData[i][columnName] || columnDefault
              let result = null

              Iif (value === undefined) {
                result = undefined
              } else Iif (value === 'null') {
                result = null
              } else Iif (value === 'NaN') {
                result = NaN
              } else Iif (columnType === 'boolean' && value === 'true') {
                result = true
              } else Iif (columnType === 'boolean' && value === 'false') {
                result = false
              } else if (columnType === 'string') {
                result = value
              } else if (columnType === 'time') {
                result = Date.parse(value.trim())
              } else if (columnType === 'number') {
                if (value === '') {
                  result = null
                } else {
                  const parsedValue = Number(value)
                  result = parsedValue === parsedValue ? parsedValue : value
                }
              } else E{
                result = null
              }

              columns[columnKey].data[tableLength + i] = result
            }

            if (annotationData.groupKey.includes(columnName)) {
              fluxGroupKeyUnion.add(columnKey)
            }
          }

          tableLength += tableData.length
        }

        resolveNames(columns, fluxGroupKeyUnion)

        const table = Object.entries(columns).reduce(
          (table, [key, {name, fluxDataType, type, data}]) => {
            data.length = tableLength
            return table.addColumn(key, fluxDataType, type, data, name)
          },
          newTable(tableLength)
        )

        const result = {
          table,
          fluxGroupKeyUnion: Array.from(fluxGroupKeyUnion),
          resultColumnNames: Array.from(resultColumnNames),
        }

        return result
      } catch (error) {
        return {
          error: error as Error,
          table: newTable(0),
          fluxGroupKeyUnion: [],
          resultColumnNames: [],
        }
      }
    }

    /*
      A Flux CSV response can contain multiple CSV files each joined by a newline.
      This function splits up a CSV response into these individual CSV files.
      See https://github.com/influxdata/flux/blob/master/docs/SPEC.md#multiple-tables.
    */
    const splitChunks = (fluxCSV: string): string[] => {
      const trimmedResponse = fluxCSV.trim()

      Iif (trimmedResponse === '') {
        return []
      }

      // Split the response into separate chunks whenever we encounter:
      //
      // 1. A newline
      // 2. Followed by any amount of whitespace
      // 3. Followed by a newline
      // 4. Followed by a `#` character
      //
      // The last condition is [necessary][0] for handling CSV responses with
      // values containing newlines.
      //
      // [0]: https://github.com/influxdata/influxdb/issues/15017
      const chunks = trimmedResponse
        .split(/\n\s*\n#/)
        .map((s, i) => (i === 0 ? s : `#${s}`)) // Add back the `#` characters that were removed by splitting

      return chunks
    }

    const parseAnnotations = (
      annotationData: string,
      headerRow: string[]
    ): {
      groupKey: string[]
      datatypeByColumnName: {[columnName: string]: any}
      defaultByColumnName: {[columnName: string]: any}
    } => {
      const rows = csvParseRows(annotationData)

      const groupRow = rows.find(row => row[0] === '#group')
      const datatypeRow = rows.find(row => row[0] === '#datatype')
      const defaultRow = rows.find(row => row[0] === '#default')

      assert(!!groupRow, 'could not find group annotation in Flux response')
      assert(!!datatypeRow, 'could not find datatype annotation in Flux response')
      assert(!!defaultRow, 'could not find default annotation in Flux response')

      const groupKey = groupRow.reduce(
        (acc, val, i) => (val === 'true' ? [...acc, headerRow[i]] : acc),
        []
      )

      const datatypeByColumnName = datatypeRow
        .slice(1)
        .reduce((acc, val, i) => ({...acc, [headerRow[i + 1]]: val}), {})

      const defaultByColumnName = defaultRow
        .slice(1)
        .reduce((acc, val, i) => ({...acc, [headerRow[i + 1]]: val}), {})

      return {groupKey, datatypeByColumnName, defaultByColumnName}
    }

    const TO_COLUMN_TYPE: {[fluxDatatype: string]: ColumnType} = {
      boolean: 'boolean',
      unsignedLong: 'number',
      long: 'number',
      double: 'number',
      string: 'string',
      'dateTime:RFC3339': 'time',
    }

    const parseValue = (value: string | undefined, columnType: ColumnType): any => {
      Iif (value === undefined) {
        return undefined
      }

      Iif (value === 'null') {
        return null
      }

      Iif (value === 'NaN') {
        return NaN
      }

      Iif (columnType === 'boolean' && value === 'true') {
        return true
      }

      Iif (columnType === 'boolean' && value === 'false') {
        return false
      }

      if (columnType === 'string') {
        return value
      }

      if (columnType === 'time') {
        return Date.parse(value.trim())
      }

      if (columnType === 'number') {
        if (value === '') {
          return null
        }
        const parsedValue = Number(value)
        return parsedValue === parsedValue ? parsedValue : value
      }

      return null
    }

    /*
      Each column in a parsed `Table` can only have a single type, but because we
      combine columns from multiple Flux tables into a single table, we may
      encounter conflicting types for a given column during parsing.
      To avoid this issue, we seperate the concept of the column _key_ and column
      _name_ in the `Table` object, where each key is unique but each name is not
      necessarily unique. We name the keys something like "foo (int)", where "foo"
      is the name and "int" is the type.
      But since type conflicts are rare and the public API requires referencing
      columns by key, we want to avoid unwieldy keys whenever possible. So the last
      stage of parsing is to rename all column keys from the `$NAME ($TYPE)` format
      to just `$NAME` if we can do so safely. That is what this function does.
    */
    const resolveNames = (
      columns: Columns,
      fluxGroupKeyUnion: Set<string>
    ): void => {
      const colNameCounts = Object.values(columns)
        .map(col => col.name)
        .reduce((acc, name) => ({...acc, [name]: (acc[name] || 0) + 1}), {})

      const uniqueColNames = Object.entries(colNameCounts)
        .filter(([_, count]) => count === 1)
        .map(([name]) => name)

      for (const uniqueName of uniqueColNames) {
        const [columnKey, column] = Object.entries(columns).find(
          ([_, col]) => col.name === uniqueName
        )

        columns[uniqueName] = column

        delete columns[columnKey]

        if (fluxGroupKeyUnion.has(columnKey)) {
          fluxGroupKeyUnion.delete(columnKey)
          fluxGroupKeyUnion.add(uniqueName)
        }
      }
    }