PdfJsMetrics.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { v4 as uuid } from 'uuid'
  2. import { sendMBSampled } from '../../../infrastructure/event-tracking'
  3. const pdfJsMetrics = {
  4. id: uuid(),
  5. epoch: Date.now(),
  6. totalBandwidth: 0,
  7. }
  8. const SAMPLING_RATE = 0.01
  9. export function trackPdfDownload(response) {
  10. const { serviceWorkerMetrics, stats, timings } = response
  11. const t0 = performance.now()
  12. let bandwidth = 0
  13. function firstRenderDone({ timePDFFetched, timePDFRendered }) {
  14. const latencyFetch = timePDFFetched - t0
  15. // The renderer does not yield in case the browser tab is hidden.
  16. // It will yield when the browser tab is visible again.
  17. // This will skew our performance metrics for rendering!
  18. const latencyRender = timePDFRendered - timePDFFetched
  19. done({ latencyFetch, latencyRender })
  20. }
  21. function updateConsumedBandwidth(bytes) {
  22. pdfJsMetrics.totalBandwidth += bytes - bandwidth
  23. bandwidth = bytes
  24. }
  25. let done
  26. const onFirstRenderDone = new Promise(resolve => {
  27. done = resolve
  28. })
  29. // Submit latency along with compile context.
  30. onFirstRenderDone.then(({ latencyFetch, latencyRender }) => {
  31. submitCompileMetrics({
  32. latencyFetch,
  33. latencyRender,
  34. stats,
  35. timings,
  36. })
  37. })
  38. // Submit bandwidth counter separate from compile context.
  39. submitPDFBandwidth({ pdfJsMetrics, serviceWorkerMetrics })
  40. return {
  41. firstRenderDone,
  42. updateConsumedBandwidth,
  43. }
  44. }
  45. function submitCompileMetrics(metrics) {
  46. sl_console.log('/event/compile-metrics', JSON.stringify(metrics))
  47. sendMBSampled('compile-metrics', metrics, SAMPLING_RATE)
  48. }
  49. function submitPDFBandwidth(metrics) {
  50. sl_console.log('/event/pdf-bandwidth', JSON.stringify(metrics))
  51. sendMBSampled('pdf-bandwidth', metrics, SAMPLING_RATE)
  52. }