forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackend_srv.ts
603 lines (505 loc) · 20 KB
/
backend_srv.ts
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { from, lastValueFrom, MonoTypeOperatorFunction, Observable, Subject, Subscription, throwError } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
import {
catchError,
filter,
finalize,
map,
mergeMap,
retryWhen,
share,
takeUntil,
tap,
throwIfEmpty,
} from 'rxjs/operators';
import { v4 as uuidv4 } from 'uuid';
import { AppEvents, DataQueryErrorType, deprecationWarning } from '@grafana/data';
import { BackendSrv as BackendService, BackendSrvRequest, config, FetchError, FetchResponse } from '@grafana/runtime';
import appEvents from 'app/core/app_events';
import { getConfig } from 'app/core/config';
import { getSessionExpiry, hasSessionExpiry } from 'app/core/utils/auth';
import { loadUrlToken } from 'app/core/utils/urlToken';
import { getDashboardAPI } from 'app/features/dashboard/api/dashboard_api';
import { DashboardModel } from 'app/features/dashboard/state';
import { DashboardSearchItem } from 'app/features/search/types';
import { TokenRevokedModal } from 'app/features/users/TokenRevokedModal';
import { DashboardDTO, FolderDTO } from 'app/types';
import { ShowModalReactEvent } from '../../types/events';
import { isContentTypeJson, parseInitFromOptions, parseResponseBody, parseUrlFromOptions } from '../utils/fetch';
import { isDataQuery, isLocalUrl } from '../utils/query';
import { FetchQueue } from './FetchQueue';
import { FetchQueueWorker } from './FetchQueueWorker';
import { ResponseQueue } from './ResponseQueue';
import { ContextSrv, contextSrv } from './context_srv';
const CANCEL_ALL_REQUESTS_REQUEST_ID = 'cancel_all_requests_request_id';
export interface BackendSrvDependencies {
fromFetch: (input: string | Request, init?: RequestInit) => Observable<Response>;
appEvents: typeof appEvents;
contextSrv: ContextSrv;
logout: () => void;
}
export interface FolderRequestOptions {
withAccessControl?: boolean;
}
const GRAFANA_TRACEID_HEADER = 'grafana-trace-id';
export interface InspectorStream {
response: FetchResponse | FetchError;
requestId?: string;
}
export class BackendSrv implements BackendService {
private inFlightRequests: Subject<string> = new Subject<string>();
private HTTP_REQUEST_CANCELED = -1;
private noBackendCache: boolean;
private inspectorStream: Subject<InspectorStream> = new Subject<InspectorStream>();
private readonly fetchQueue: FetchQueue;
private readonly responseQueue: ResponseQueue;
private _tokenRotationInProgress?: Observable<FetchResponse> | null = null;
private deviceID?: string | null = null;
private grafanaPrefix: boolean;
private dependencies: BackendSrvDependencies = {
fromFetch: fromFetch,
appEvents: appEvents,
contextSrv: contextSrv,
logout: () => {
contextSrv.setLoggedOut();
},
};
constructor(deps?: BackendSrvDependencies) {
if (deps) {
this.dependencies = {
...this.dependencies,
...deps,
};
}
this.grafanaPrefix = false;
this.noBackendCache = false;
this.internalFetch = this.internalFetch.bind(this);
this.fetchQueue = new FetchQueue();
this.responseQueue = new ResponseQueue(this.fetchQueue, this.internalFetch);
this.initGrafanaDeviceID();
new FetchQueueWorker(this.fetchQueue, this.responseQueue, getConfig());
}
private async initGrafanaDeviceID() {
try {
const fp = await FingerprintJS.load();
const result = await fp.get();
this.deviceID = result.visitorId;
} catch (error) {
console.error(error);
}
}
async request<T = unknown>(options: BackendSrvRequest): Promise<T> {
return await lastValueFrom(this.fetch<T>(options).pipe(map((response: FetchResponse<T>) => response.data)));
}
fetch<T>(options: BackendSrvRequest): Observable<FetchResponse<T>> {
// prefix "/grafana" to options.url
if (this.grafanaPrefix) {
if (options.url.indexOf('/grafana') !== 0) {
options.url = '/grafana' + options.url;
}
}
// We need to match an entry added to the queue stream with the entry that is eventually added to the response stream
const id = uuidv4();
const fetchQueue = this.fetchQueue;
return new Observable((observer) => {
// Subscription is an object that is returned whenever you subscribe to an Observable.
// You can also use it as a container of many subscriptions and when it is unsubscribed all subscriptions within are also unsubscribed.
const subscriptions: Subscription = new Subscription();
// We're using the subscriptions.add function to add the subscription implicitly returned by this.responseQueue.getResponses<T>(id).subscribe below.
subscriptions.add(
this.responseQueue.getResponses<T>(id).subscribe((result) => {
// The one liner below can seem magical if you're not accustomed to RxJs.
// Firstly, we're subscribing to the result from the result.observable and we're passing in the outer observer object.
// By passing the outer observer object then any updates on result.observable are passed through to any subscriber of the fetch<T> function.
// Secondly, we're adding the subscription implicitly returned by result.observable.subscribe(observer).
subscriptions.add(result.observable.subscribe(observer));
})
);
// Let the fetchQueue know that this id needs to start data fetching.
this.fetchQueue.add(id, options);
// This returned function will be called whenever the returned Observable from the fetch<T> function is unsubscribed/errored/completed/canceled.
return function unsubscribe() {
// Change status to Done moved here from ResponseQueue because this unsubscribe was called before the responseQueue produced a result
fetchQueue.setDone(id);
// When subscriptions is unsubscribed all the implicitly added subscriptions above are also unsubscribed.
subscriptions.unsubscribe();
};
});
}
private internalFetch<T>(options: BackendSrvRequest): Observable<FetchResponse<T>> {
if (options.requestId) {
this.inFlightRequests.next(options.requestId);
}
options = this.parseRequestOptions(options);
const token = loadUrlToken();
if (token !== null && token !== '') {
if (config.jwtUrlLogin && config.jwtHeaderName) {
options.headers = options.headers ?? {};
options.headers[config.jwtHeaderName] = `${token}`;
}
}
if (!!this.deviceID) {
options.headers = options.headers ?? {};
options.headers['X-Grafana-Device-Id'] = `${this.deviceID}`;
}
return this.getFromFetchStream<T>(options).pipe(
this.handleStreamResponse<T>(options),
this.handleStreamError(options),
this.handleStreamCancellation(options)
);
}
resolveCancelerIfExists(requestId: string) {
this.inFlightRequests.next(requestId);
}
cancelAllInFlightRequests() {
this.inFlightRequests.next(CANCEL_ALL_REQUESTS_REQUEST_ID);
}
async datasourceRequest<T = unknown>(options: BackendSrvRequest) {
return lastValueFrom(this.fetch<T>(options));
}
private getCodeRabbitOrg(): { id: string } | null {
const selectedOrgStorage = sessionStorage.getItem('selected_org');
try {
return selectedOrgStorage ? (JSON.parse(selectedOrgStorage) as { id: string }) : null;
} catch (e) {
console.error('Failed to parse selected_org', selectedOrgStorage, 'error:', e);
sessionStorage.removeItem('selected_org');
return null;
}
}
private parseRequestOptions(options: BackendSrvRequest): BackendSrvRequest {
const orgId = this.dependencies.contextSrv.user?.orgId;
// init retry counter
options.retry = options.retry ?? 0;
if (isLocalUrl(options.url)) {
if (orgId) {
options.headers = options.headers ?? {};
options.headers['X-Grafana-Org-Id'] = orgId;
}
const codeRabbitOrg = this.getCodeRabbitOrg();
if (codeRabbitOrg) {
options.headers = options.headers ?? {};
options.headers['x-coderabbit-organization'] = codeRabbitOrg.id;
options.headers['x-tenant-id'] = sessionStorage.getItem('firebaseTenantId');
}
if (options.url.startsWith('/')) {
options.url = options.url.substring(1);
}
const codeRabbitToken = sessionStorage.getItem('accessToken');
if (codeRabbitToken) {
options.headers = options.headers ?? {};
options.headers['x-coderabbit-token'] = `Bearer ${codeRabbitToken}`;
}
if (options.headers?.Authorization) {
options.headers['X-DS-Authorization'] = options.headers.Authorization;
delete options.headers.Authorization;
}
if (this.noBackendCache) {
options.headers = options.headers ?? {};
options.headers['X-Grafana-NoCache'] = 'true';
}
}
if (options.hideFromInspector === undefined) {
// Hide all local non data query calls
options.hideFromInspector = isLocalUrl(options.url) && !isDataQuery(options.url);
}
return options;
}
private getFromFetchStream<T>(options: BackendSrvRequest): Observable<FetchResponse<T>> {
const url = parseUrlFromOptions(options);
const init = parseInitFromOptions(options);
return this.dependencies.fromFetch(url, init).pipe(
mergeMap(async (response) => {
const { status, statusText, ok, headers, url, type, redirected } = response;
const responseType = options.responseType ?? (isContentTypeJson(headers) ? 'json' : undefined);
const data = await parseResponseBody<T>(response, responseType);
const fetchResponse: FetchResponse<T> = {
status,
statusText,
ok,
data,
headers,
url,
type,
redirected,
config: options,
traceId: response.headers.get(GRAFANA_TRACEID_HEADER) ?? undefined,
};
return fetchResponse;
})
);
}
showApplicationErrorAlert(err: FetchError) {}
showSuccessAlert<T>(response: FetchResponse<T>) {
const { config } = response;
if (config.showSuccessAlert === false) {
return;
}
// if showSuccessAlert is undefined we only show alerts non GET request, non data query and local api requests
if (
config.showSuccessAlert === undefined &&
(config.method === 'GET' || isDataQuery(config.url) || !isLocalUrl(config.url))
) {
return;
}
const data: { message: string } = response.data as any;
if (data?.message) {
this.dependencies.appEvents.emit(AppEvents.alertSuccess, [data.message]);
}
}
showErrorAlert(config: BackendSrvRequest, err: FetchError) {
if (config.showErrorAlert === false) {
return;
}
// is showErrorAlert is undefined we only show alerts non data query and local api requests
if (config.showErrorAlert === undefined && (isDataQuery(config.url) || !isLocalUrl(config.url))) {
return;
}
let description = '';
let message = err.data.message;
// Sometimes we have a better error message on err.message
if (message === 'Unexpected error' && err.message) {
message = err.message;
}
if (message.length > 80) {
description = message;
message = 'Error';
}
// Validation
if (err.status === 422) {
description = err.data.message;
message = 'Validation failed';
}
this.dependencies.appEvents.emit(err.status < 500 ? AppEvents.alertWarning : AppEvents.alertError, [
message,
description,
err.data.traceID,
]);
}
/**
* Processes FetchError to ensure "data" property is an object.
*
* @see DataQueryError.data
*/
processRequestError(options: BackendSrvRequest, err: FetchError): FetchError<{ message: string; error?: string }> {
err.data = err.data ?? { message: 'Unexpected error' };
if (typeof err.data === 'string') {
err.data = {
message: err.data,
error: err.statusText,
response: err.data,
};
}
// If no message but got error string, copy to message prop
if (err.data && !err.data.message && typeof err.data.error === 'string') {
err.data.message = err.data.error;
}
// check if we should show an error alert
if (err.data.message) {
setTimeout(() => {
if (!err.isHandled) {
this.showErrorAlert(options, err);
}
}, 50);
}
this.inspectorStream.next({ response: err, requestId: options.requestId });
return err;
}
private handleStreamResponse<T>(options: BackendSrvRequest): MonoTypeOperatorFunction<FetchResponse<T>> {
return (inputStream) =>
inputStream.pipe(
map((response) => {
if (!response.ok) {
const { status, statusText, data } = response;
const fetchErrorResponse: FetchError = {
status,
statusText,
data,
config: options,
traceId: response.headers.get(GRAFANA_TRACEID_HEADER) ?? undefined,
};
throw fetchErrorResponse;
}
return response;
}),
tap((response) => {
this.showSuccessAlert(response);
this.inspectorStream.next({ response: response, requestId: options.requestId });
})
);
}
private handleStreamError<T>(options: BackendSrvRequest): MonoTypeOperatorFunction<FetchResponse<T>> {
const { isSignedIn } = this.dependencies.contextSrv.user;
return (inputStream) =>
inputStream.pipe(
retryWhen((attempts) =>
attempts.pipe(
mergeMap((error, i) => {
const firstAttempt = i === 0 && options.retry === 0;
if (error.status === 401 && isLocalUrl(options.url) && firstAttempt && isSignedIn) {
if (error.data?.error?.id === 'ERR_TOKEN_REVOKED') {
this.dependencies.appEvents.publish(
new ShowModalReactEvent({
component: TokenRevokedModal,
props: {
maxConcurrentSessions: error.data?.error?.maxConcurrentSessions,
},
})
);
return throwError(() => error);
}
let authChecker = this.loginPing();
if (hasSessionExpiry()) {
const expired = getSessionExpiry() * 1000 < Date.now();
if (expired) {
authChecker = this.rotateToken();
}
}
return from(authChecker).pipe(
catchError((err) => {
if (err.status === 401) {
this.dependencies.logout();
return throwError(err);
}
return throwError(err);
})
);
}
return throwError(error);
})
)
),
catchError((err: FetchError) => throwError(() => this.processRequestError(options, err)))
);
}
private handleStreamCancellation(options: BackendSrvRequest): MonoTypeOperatorFunction<FetchResponse> {
return (inputStream) =>
inputStream.pipe(
takeUntil(
this.inFlightRequests.pipe(
filter((requestId) => {
let cancelRequest = false;
if (options && options.requestId && options.requestId === requestId) {
// when a new requestId is started it will be published to inFlightRequests
// if a previous long running request that hasn't finished yet has the same requestId
// we need to cancel that request
cancelRequest = true;
}
if (requestId === CANCEL_ALL_REQUESTS_REQUEST_ID) {
cancelRequest = true;
}
return cancelRequest;
})
)
),
// when a request is cancelled by takeUntil it will complete without emitting anything so we use throwIfEmpty to identify this case
// in throwIfEmpty we'll then throw an cancelled error and then we'll return the correct result in the catchError or rethrow
throwIfEmpty(() => ({
type: DataQueryErrorType.Cancelled,
cancelled: true,
data: null,
status: this.HTTP_REQUEST_CANCELED,
statusText: 'Request was aborted',
config: options,
}))
);
}
getInspectorStream(): Observable<InspectorStream> {
return this.inspectorStream;
}
async get<T = any>(
url: string,
params?: BackendSrvRequest['params'],
requestId?: BackendSrvRequest['requestId'],
options?: Partial<BackendSrvRequest>
) {
return this.request<T>({ ...options, method: 'GET', url, params, requestId });
}
async delete<T = unknown>(url: string, data?: unknown, options?: Partial<BackendSrvRequest>) {
return this.request<T>({ ...options, method: 'DELETE', url, data });
}
async post<T = any>(url: string, data?: unknown, options?: Partial<BackendSrvRequest>) {
return this.request<T>({ ...options, method: 'POST', url, data });
}
async patch<T = any>(url: string, data: unknown, options?: Partial<BackendSrvRequest>) {
return this.request<T>({ ...options, method: 'PATCH', url, data });
}
async put<T = any>(url: string, data: unknown, options?: Partial<BackendSrvRequest>): Promise<T> {
return this.request<T>({ ...options, method: 'PUT', url, data });
}
withNoBackendCache(callback: () => Promise<void>) {
this.noBackendCache = true;
return callback().finally(() => {
this.noBackendCache = false;
});
}
rotateToken() {
if (this._tokenRotationInProgress) {
return this._tokenRotationInProgress;
}
this._tokenRotationInProgress = this.fetch({ url: '/api/user/auth-tokens/rotate', method: 'POST', retry: 1 }).pipe(
finalize(() => {
this._tokenRotationInProgress = null;
}),
share()
);
return this._tokenRotationInProgress;
}
loginPing() {
return this.fetch({ url: '/api/login/ping', method: 'GET', retry: 1 });
}
/** @deprecated */
search(query: Parameters<typeof this.get>[1]): Promise<DashboardSearchItem[]> {
return this.get('/api/search', query);
}
/** @deprecated */
getDashboardByUid(uid: string): Promise<DashboardDTO> {
// NOTE: When this is removed, we can also remove most instances of:
// jest.mock('app/features/live/dashboard/dashboardWatcher
deprecationWarning('backend_srv', 'getDashboardByUid(uid)', 'getDashboardAPI().getDashboardDTO(uid)');
return getDashboardAPI().getDashboardDTO(uid);
}
getDashboardByUidVersion(uid: string, version: number): Promise<DashboardDTO> {
return this.get<DashboardDTO>(`/api/dashboards/uid/${uid}/versions/${version}`);
}
validateDashboard(dashboard: DashboardModel) {
// We want to send the dashboard as a JSON string (in the JSON body payload) so we can get accurate error line numbers back
const dashboardJson = JSON.stringify(dashboard, replaceJsonNulls, 2);
return this.request<ValidateDashboardResponse>({
method: 'POST',
url: `/api/dashboards/validate`,
data: { dashboard: dashboardJson },
showSuccessAlert: false,
showErrorAlert: false,
});
}
getPublicDashboardByUid(uid: string) {
return this.get<DashboardDTO>(`/api/public/dashboards/${uid}`);
}
getFolderByUid(uid: string, options: FolderRequestOptions = {}) {
const queryParams = new URLSearchParams();
if (options.withAccessControl) {
queryParams.set('accesscontrol', 'true');
}
return this.get<FolderDTO>(`/api/folders/${uid}?${queryParams.toString()}`, undefined, undefined, {
showErrorAlert: false,
});
}
setGrafanaPrefix(prefix: boolean) {
this.grafanaPrefix = prefix;
}
}
// Used for testing and things that really need BackendSrv
export const backendSrv = new BackendSrv();
export const getBackendSrv = (): BackendSrv => backendSrv;
interface ValidateDashboardResponse {
isValid: boolean;
message?: string;
}
function replaceJsonNulls<T extends unknown>(key: string, value: T): T | undefined {
if (typeof value === 'number' && !isFinite(value)) {
return undefined;
}
return value;
}