All files / modules/70-pipeline/components/LogsContent useLogsContent.tsx

82.09% Statements 55/67
68.42% Branches 13/19
83.33% Functions 10/12
84.62% Lines 55/65

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              33x 33x 33x     33x 33x 33x 33x 33x   33x   33x 33x 33x                 33x 25x 25x 25x 25x 25x 25x 25x     25x 25x     1x 1x           1x         1x   1x 1x                               1x 1x 1x                       1x       1x 1x                         25x   9x 7x           9x 2x 2x           25x 19x 5x   5x   2x 1x                   25x 14x             25x 9x   9x 7x     7x 7x         25x    
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { Reducer } from 'react'
import { useParams } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
 
import type { ExecutionPathProps } from '@common/interfaces/RouteInterfaces'
import { PQueue } from '@common/utils/PQueue'
import { useGetToken, logBlobPromise } from 'services/logs'
import SessionToken from 'framework/utils/SessionToken'
import { useExecutionContext } from '@pipeline/context/ExecutionContext'
import { useDeepCompareEffect } from '@common/hooks'
 
import { useLogsStream } from './useLogsStream'
import type { ActionType, State, Action } from './LogsState/types'
import { reducer } from './LogsState'
import { useActionCreator, UseActionCreatorReturn } from './LogsState/actions'
import { getDefaultReducerState, logsCache } from './LogsState/utils'
 
type LogsReducer = Reducer<State, Action<ActionType>>
 
export interface UseLogsContentReturn {
  state: State
  actions: UseActionCreatorReturn
}
 
export function useLogsContent(): UseLogsContentReturn {
  const requestQueue = React.useRef(new PQueue())
  const { accountId } = useParams<ExecutionPathProps>()
  const [state, dispatch] = React.useReducer<LogsReducer>(reducer, getDefaultReducerState())
  const actions = useActionCreator(dispatch)
  const { logsToken, setLogsToken } = useExecutionContext()
  const { data: tokenData } = useGetToken({ queryParams: { accountID: accountId }, lazy: !!logsToken })
  const { log: streamData, startStream, closeStream, key: streamKey } = useLogsStream()
 
  // need to save token in a ref due to scoping issues
  const logsTokenRef = React.useRef('')
  const timerRef = React.useRef<null | number>(null)
 
  function getBlobData(id: string): void {
    requestQueue.current.add(async (signal: AbortSignal) => {
      Iif (logsCache.has(id)) {
        actions.updateSectionData({ data: defaultTo(logsCache.get(id), ''), id })
        return
      }
 
      // if token is not found, schedule the call for later
      Iif (!logsTokenRef.current) {
        timerRef.current = window.setTimeout(() => getBlobData(id), 300)
        return
      }
 
      actions.fetchingSectionData(id)
 
      try {
        const data = (await logBlobPromise(
          {
            queryParams: {
              accountID: accountId,
              'X-Harness-Token': '',
              key: id
            },
            requestOptions: {
              headers: {
                'X-Harness-Token': logsTokenRef.current
              }
            }
          },
          signal
        )) as unknown
 
        Eif (typeof data === 'string') {
          logsCache.set(id, data)
          actions.updateSectionData({ id, data })
        } else {
          actions.resetSection(id)
        }
      } catch (e) {
        actions.resetSection(id)
      }
    })
  }
 
  function getStream(logKey: string): void {
    // if token is not found, schedule the call for later
    Iif (!logsTokenRef.current) {
      timerRef.current = window.setTimeout(() => getStream(logKey), 300)
      return
    }
    actions.fetchingSectionData(logKey)
    startStream({
      queryParams: {
        accountId,
        key: encodeURIComponent(logKey)
      },
      headers: {
        'X-Harness-Token': logsTokenRef.current,
        Authorization: SessionToken.getToken()
      },
      key: logKey
    })
  }
 
  React.useEffect(() => {
    // use the existing token if present
    if (logsToken) {
      logsTokenRef.current = logsToken
    }
 
    // if `logsToken` is not present, `tokenData` is fetched
    // as we set the lazy flag based on it's presence
    /* istanbul ignore else */
    if (tokenData) {
      setLogsToken(tokenData)
      logsTokenRef.current = tokenData
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tokenData, logsToken])
 
  // This fetches data for sections
  useDeepCompareEffect(() => {
    state.logKeys.forEach(logKey => {
      const section = state.dataMap[logKey]
      /* istanbul ignore else */
      if (section && section.status === 'LOADING') {
        /* istanbul ignore else */
        if (section.dataSource === 'blob') {
          getBlobData(logKey)
        } else if (section.dataSource === 'stream') {
          getStream(logKey)
        }
      }
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.selectedStep, state.dataMap])
 
  // fetch data for stream
  React.useEffect(() => {
    Iif (streamData) {
      actions.updateSectionData({ data: streamData, id: streamKey })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [streamData, streamKey, state.selectedStep])
 
  // on unmount
  React.useEffect(() => {
    const queue = requestQueue.current
 
    return () => {
      Iif (timerRef.current) {
        window.clearTimeout(timerRef.current)
      }
      queue.cancel()
      closeStream()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  return { state, actions }
}