# All files fromFlux.ts

95% Statements 133/140
71.87% Branches 23/32
100% Functions 19/19
93.75% Lines 105/112

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
    3521x

    1x
    1x

    1x

    1x
    13x
    13x
    13x
    13x

    13x
    13x

    13x
    13x
    13x
    13x
    13x
    13x

    21x
    21x

    21x
    21x

    21x
    108x
    59x

    49x

    21x

    21x

    19x
    19x

    19x

    19x

    19x

    197x
    197x

    197x

    197x

    197x
    102x

    197x

    197x
    265x
    24x

    265x

    197x
    132x

    19x

    11x

    11x
    102x
    102x
    102x

    11x

    11x

    2x

    1x
    13x

    13x

    13x

    21x

    13x

    1x

    19x

    19x
    38x
    57x

    19x
    19x
    19x

    19x
    213x

    19x

    197x

    19x

    197x

    19x

    1x

    1x
    265x

    265x

    265x

    265x

    265x

    265x
    177x

    88x
    45x

    43x
    43x
    1x

    42x
    42x

    1x

    11x
    102x
    102x

    11x
    100x
    98x

    98x
    98x

    98x

    98x

    98x
    65x
    65x

     import {csvParse, csvParseRows} from 'd3-dsv'
    import {Table, ColumnType, FluxDataType} from '../types'
    import {assert} from './assert'
    import {newTable} from './newTable'

    const RESULT_COLUMN_INDEX = 1
    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)
            }
            // if (line.startsWith('#default')) {
            //   const defaults = line.split(',')
            //   if (
            //     defaults.length >= RESULT_COLUMN_INDEX + 1 &&
            //     defaults[RESULT_COLUMN_INDEX].length
            //   ) {
            //     resultColumnNames.add(defaults[RESULT_COLUMN_INDEX])
            //   }
            // }
          })

          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)
          console.log('tableData', tableData)

          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') {
                resultColumnNames.add(tableData[i][columnName] || columnDefault)
              }
              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: [],
        }
      }
    }

    /*
      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)
        }
      }
    }