-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathTimeSeries.tsx
301 lines (247 loc) · 6.98 KB
/
TimeSeries.tsx
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
// Library
import React, {Component, RefObject, CSSProperties} from 'react'
import {isEqual} from 'lodash'
import {connect} from 'react-redux'
import {withRouter, WithRouterProps} from 'react-router'
import {fromFlux, FromFluxResult} from '@influxdata/giraffe'
// API
import {
runQuery,
RunQueryResult,
RunQuerySuccessResult,
} from 'src/shared/apis/query'
import {runStatusesQuery} from 'src/alerting/utils/statusEvents'
// Utils
import {checkQueryResult} from 'src/shared/utils/checkQueryResult'
import {getWindowVars} from 'src/variables/utils/getWindowVars'
import {buildVarsOption} from 'src/variables/utils/buildVarsOption'
import 'intersection-observer'
import {getAll} from 'src/resources/selectors'
import {getOrgIDFromBuckets} from 'src/timeMachine/actions/queries'
// Constants
import {rateLimitReached, resultTooLarge} from 'src/shared/copy/notifications'
// Actions
import {notify as notifyAction} from 'src/shared/actions/notifications'
// Types
import {
RemoteDataState,
Check,
StatusRow,
Bucket,
ResourceType,
DashboardQuery,
VariableAssignment,
AppState,
CancelBox,
} from 'src/types'
interface QueriesState {
files: string[] | null
loading: RemoteDataState
errorMessage: string
isInitialFetch: boolean
duration: number
giraffeResult: FromFluxResult
statuses: StatusRow[][]
}
interface StateProps {
queryLink: string
buckets: Bucket[]
}
interface OwnProps {
className: string
style: CSSProperties
queries: DashboardQuery[]
variables?: VariableAssignment[]
submitToken: number
implicitSubmit?: boolean
children: (r: QueriesState) => JSX.Element
check: Partial<Check>
}
interface DispatchProps {
notify: typeof notifyAction
}
type Props = StateProps & OwnProps & DispatchProps
interface State {
loading: RemoteDataState
files: string[] | null
errorMessage: string
fetchCount: number
duration: number
giraffeResult: FromFluxResult
statuses: StatusRow[][]
}
const defaultState = (): State => ({
loading: RemoteDataState.NotStarted,
files: null,
fetchCount: 0,
errorMessage: '',
duration: 0,
giraffeResult: null,
statuses: [[]],
})
class TimeSeries extends Component<Props & WithRouterProps, State> {
public static defaultProps = {
implicitSubmit: true,
className: 'time-series-container',
style: null,
}
public state: State = defaultState()
private observer: IntersectionObserver
private ref: RefObject<HTMLDivElement> = React.createRef()
private isIntersecting: boolean = false
private pendingReload: boolean = true
private pendingResults: Array<CancelBox<RunQueryResult>> = []
private pendingCheckStatuses: CancelBox<StatusRow[][]> = null
public componentDidMount() {
this.observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const {isIntersecting} = entry
if (!this.isIntersecting && isIntersecting && this.pendingReload) {
this.reload()
}
this.isIntersecting = isIntersecting
})
})
this.observer.observe(this.ref.current)
}
public componentDidUpdate(prevProps: Props) {
if (this.shouldReload(prevProps) && this.isIntersecting) {
this.reload()
}
}
public componentWillUnmount() {
this.observer && this.observer.disconnect()
}
public render() {
const {
giraffeResult,
files,
loading,
errorMessage,
fetchCount,
duration,
statuses,
} = this.state
const {className, style} = this.props
return (
<div ref={this.ref} className={className} style={style}>
{this.props.children({
giraffeResult,
files,
loading,
errorMessage,
duration,
isInitialFetch: fetchCount === 1,
statuses,
})}
</div>
)
}
private reload = async () => {
const {variables, notify, check, buckets} = this.props
const queries = this.props.queries.filter(({text}) => !!text.trim())
if (!queries.length) {
this.setState(defaultState())
return
}
this.setState({
loading: RemoteDataState.Loading,
fetchCount: this.state.fetchCount + 1,
errorMessage: '',
})
try {
const startTime = Date.now()
let errorMessage: string = ''
// Cancel any existing queries
this.pendingResults.forEach(({cancel}) => cancel())
// Issue new queries
this.pendingResults = queries.map(({text}) => {
const orgID =
getOrgIDFromBuckets(text, buckets) || this.props.params.orgID
const windowVars = getWindowVars(text, variables)
const extern = buildVarsOption([...variables, ...windowVars])
return runQuery(orgID, text, extern)
})
// Wait for new queries to complete
const results = await Promise.all(this.pendingResults.map(r => r.promise))
let statuses = [] as StatusRow[][]
if (check) {
const extern = buildVarsOption(variables)
this.pendingCheckStatuses = runStatusesQuery(
this.props.params.orgID,
check.id,
extern
)
statuses = await this.pendingCheckStatuses.promise // TODO handle errors
}
const duration = Date.now() - startTime
for (const result of results) {
if (result.type === 'UNKNOWN_ERROR') {
errorMessage = result.message
throw new Error(result.message)
}
if (result.type === 'RATE_LIMIT_ERROR') {
errorMessage = result.message
notify(rateLimitReached(result.retryAfter))
throw new Error(result.message)
}
if (result.didTruncate) {
notify(resultTooLarge(result.bytesRead))
}
checkQueryResult(result.csv)
}
const files = (results as RunQuerySuccessResult[]).map(r => r.csv)
const giraffeResult = fromFlux(files.join('\n\n'))
this.pendingReload = false
this.setState({
giraffeResult,
errorMessage,
files,
duration,
loading: RemoteDataState.Done,
statuses,
})
} catch (error) {
if (error.name === 'CancellationError') {
return
}
console.error(error)
this.setState({
errorMessage: error.message,
giraffeResult: null,
loading: RemoteDataState.Error,
statuses: [[]],
})
}
this.pendingReload = false
}
private shouldReload(prevProps: Props) {
if (prevProps.submitToken !== this.props.submitToken) {
return true
}
if (!this.props.implicitSubmit) {
return false
}
if (!isEqual(prevProps.queries, this.props.queries)) {
return true
}
if (!isEqual(prevProps.variables, this.props.variables)) {
return true
}
return false
}
}
const mstp = (state: AppState): StateProps => {
const {links} = state
return {
queryLink: links.query.self,
buckets: getAll<Bucket>(state, ResourceType.Buckets),
}
}
const mdtp: DispatchProps = {
notify: notifyAction,
}
export default connect<StateProps, {}, OwnProps>(
mstp,
mdtp
)(withRouter(TimeSeries))