|
| 1 | +import { EchoBackend, EchoMeta, EchoEvent, EchoSrv } from '@grafana/runtime'; |
| 2 | +import { contextSrv } from '../context_srv'; |
| 3 | + |
| 4 | +interface EchoConfig { |
| 5 | + // How often should metrics be reported |
| 6 | + flushInterval: number; |
| 7 | + // Enables debug mode |
| 8 | + debug: boolean; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * Echo is a service for collecting events from Grafana client-app |
| 13 | + * It collects events, distributes them across registered backend and flushes once per configured interval |
| 14 | + * It's up to the registered backend to decide what to do with a given type of metric |
| 15 | + */ |
| 16 | +export class Echo implements EchoSrv { |
| 17 | + private config: EchoConfig = { |
| 18 | + flushInterval: 10000, // By default Echo flushes every 10s |
| 19 | + debug: false, |
| 20 | + }; |
| 21 | + |
| 22 | + private backends: EchoBackend[] = []; |
| 23 | + // meta data added to every event collected |
| 24 | + |
| 25 | + constructor(config?: Partial<EchoConfig>) { |
| 26 | + this.config = { |
| 27 | + ...this.config, |
| 28 | + ...config, |
| 29 | + }; |
| 30 | + setInterval(this.flush, this.config.flushInterval); |
| 31 | + } |
| 32 | + |
| 33 | + logDebug = (...msg: any) => { |
| 34 | + if (this.config.debug) { |
| 35 | + // tslint:disable-next-line |
| 36 | + // console.debug('ECHO:', ...msg); |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + flush = () => { |
| 41 | + for (const backend of this.backends) { |
| 42 | + backend.flush(); |
| 43 | + } |
| 44 | + }; |
| 45 | + |
| 46 | + addBackend = (backend: EchoBackend) => { |
| 47 | + this.logDebug('Adding backend', backend); |
| 48 | + this.backends.push(backend); |
| 49 | + }; |
| 50 | + |
| 51 | + addEvent = <T extends EchoEvent>(event: Omit<T, 'meta'>, _meta?: {}) => { |
| 52 | + const meta = this.getMeta(); |
| 53 | + const _event = { |
| 54 | + ...event, |
| 55 | + meta: { |
| 56 | + ...meta, |
| 57 | + ..._meta, |
| 58 | + }, |
| 59 | + }; |
| 60 | + |
| 61 | + for (const backend of this.backends) { |
| 62 | + if (backend.supportedEvents.length === 0 || backend.supportedEvents.indexOf(_event.type) > -1) { |
| 63 | + backend.addEvent(_event); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + this.logDebug('Adding event', _event); |
| 68 | + }; |
| 69 | + |
| 70 | + getMeta = (): EchoMeta => { |
| 71 | + return { |
| 72 | + sessionId: '', |
| 73 | + userId: contextSrv.user.id, |
| 74 | + userLogin: contextSrv.user.login, |
| 75 | + userSignedIn: contextSrv.user.isSignedIn, |
| 76 | + screenSize: { |
| 77 | + width: window.innerWidth, |
| 78 | + height: window.innerHeight, |
| 79 | + }, |
| 80 | + windowSize: { |
| 81 | + width: window.screen.width, |
| 82 | + height: window.screen.height, |
| 83 | + }, |
| 84 | + userAgent: window.navigator.userAgent, |
| 85 | + ts: performance.now(), |
| 86 | + url: window.location.href, |
| 87 | + }; |
| 88 | + }; |
| 89 | +} |
0 commit comments