queryAnalytics.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { PanelData, LoadingState, DataSourceApi, CoreApp, urlUtil } from '@grafana/data';
  2. import { reportMetaAnalytics, MetaAnalyticsEventName, DataRequestEventPayload } from '@grafana/runtime';
  3. import { getDashboardSrv } from '../../dashboard/services/DashboardSrv';
  4. export function emitDataRequestEvent(datasource: DataSourceApi) {
  5. let done = false;
  6. return (data: PanelData) => {
  7. if (!data.request || done || data.request.app === CoreApp.Explore) {
  8. return;
  9. }
  10. const params = urlUtil.getUrlSearchParams();
  11. if (params.editPanel != null) {
  12. return;
  13. }
  14. if (data.state !== LoadingState.Done && data.state !== LoadingState.Error) {
  15. return;
  16. }
  17. const queryCacheStatus: { [key: string]: boolean } = {};
  18. for (let i = 0; i < data.series.length; i++) {
  19. const refId = data.series[i].refId;
  20. if (refId && !queryCacheStatus[refId]) {
  21. queryCacheStatus[refId] = data.series[i].meta?.isCachedResponse ?? false;
  22. }
  23. }
  24. const totalQueries = Object.keys(queryCacheStatus).length;
  25. const cachedQueries = Object.values(queryCacheStatus).filter((val) => val === true).length;
  26. const eventData: DataRequestEventPayload = {
  27. eventName: MetaAnalyticsEventName.DataRequest,
  28. datasourceName: datasource.name,
  29. datasourceId: datasource.id,
  30. datasourceType: datasource.type,
  31. panelId: data.request.panelId,
  32. dashboardId: data.request.dashboardId,
  33. dataSize: 0,
  34. duration: data.request.endTime! - data.request.startTime,
  35. totalQueries,
  36. cachedQueries,
  37. };
  38. // enrich with dashboard info
  39. const dashboard = getDashboardSrv().getCurrent();
  40. if (dashboard) {
  41. eventData.dashboardId = dashboard.id;
  42. eventData.dashboardName = dashboard.title;
  43. eventData.dashboardUid = dashboard.uid;
  44. eventData.folderName = dashboard.meta.folderTitle;
  45. }
  46. if (data.series && data.series.length > 0) {
  47. // estimate size
  48. eventData.dataSize = data.series.length;
  49. }
  50. if (data.error) {
  51. eventData.error = data.error.message;
  52. }
  53. reportMetaAnalytics(eventData);
  54. // this done check is to make sure we do not double emit events in case
  55. // there are multiple responses with done state
  56. done = true;
  57. };
  58. }