sentry-instrumentation.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /* eslint-env node */
  2. import type * as Sentry from '@sentry/node';
  3. import type {Span} from '@sentry/types';
  4. import crypto from 'node:crypto';
  5. import https from 'node:https';
  6. import os from 'node:os';
  7. import type webpack from 'webpack';
  8. const {
  9. NODE_ENV,
  10. SENTRY_INSTRUMENTATION,
  11. SENTRY_WEBPACK_WEBHOOK_SECRET,
  12. GITHUB_SHA,
  13. GITHUB_REF,
  14. SENTRY_DEV_UI_PROFILING,
  15. } = process.env;
  16. const IS_CI = !!GITHUB_SHA;
  17. const PLUGIN_NAME = 'SentryInstrumentation';
  18. const GB_BYTE = 1073741824;
  19. const createSignature = function (secret: string, payload: string) {
  20. const hmac = crypto.createHmac('sha1', secret);
  21. return `sha1=${hmac.update(payload).digest('hex')}`;
  22. };
  23. const INCREMENTAL_BUILD_TXN = 'incremental-build';
  24. const INITIAL_BUILD_TXN = 'initial-build';
  25. class SentryInstrumentation {
  26. hasInitializedBuild: boolean = false;
  27. Sentry?: typeof Sentry;
  28. span?: Span;
  29. constructor() {
  30. // Only run if SENTRY_INSTRUMENTATION` is set or when in ci,
  31. // only in the javascript suite that runs webpack
  32. if (!SENTRY_INSTRUMENTATION && !SENTRY_DEV_UI_PROFILING) {
  33. return;
  34. }
  35. const sentry = require('@sentry/node') as typeof Sentry;
  36. const {nodeProfilingIntegration} = require('@sentry/profiling-node');
  37. sentry.init({
  38. dsn: 'https://3d282d186d924374800aa47006227ce9@sentry.io/2053674',
  39. environment: IS_CI ? 'ci' : 'local',
  40. tracesSampleRate: 1.0,
  41. integrations: [nodeProfilingIntegration()],
  42. profilesSampler: ({transactionContext}) => {
  43. if (transactionContext.name === INCREMENTAL_BUILD_TXN) {
  44. return 0;
  45. }
  46. return 1;
  47. },
  48. _experiments: {
  49. // 5 minutes should be plenty
  50. maxProfileDurationMs: 5 * 60 * 1000,
  51. },
  52. });
  53. if (IS_CI) {
  54. sentry.setTag('branch', GITHUB_REF);
  55. }
  56. const cpus = os.cpus();
  57. sentry.setTag('platform', os.platform());
  58. sentry.setTag('arch', os.arch());
  59. sentry.setTag(
  60. 'cpu',
  61. cpus?.length ? `${cpus[0].model} (cores: ${cpus.length})}` : 'N/A'
  62. );
  63. this.Sentry = sentry;
  64. this.span = sentry.startInactiveSpan({
  65. op: 'webpack-build',
  66. name: INITIAL_BUILD_TXN,
  67. });
  68. }
  69. /**
  70. * Measures the file sizes of assets emitted from the entrypoints
  71. */
  72. measureAssetSizes(compilation: webpack.Compilation) {
  73. if (!SENTRY_WEBPACK_WEBHOOK_SECRET) {
  74. return;
  75. }
  76. [...compilation.entrypoints].forEach(([entrypointName, entry]) =>
  77. entry.chunks.forEach(chunk =>
  78. Array.from(chunk.files)
  79. .filter(assetName => !assetName.endsWith('.map'))
  80. .forEach(assetName => {
  81. const asset = compilation.assets[assetName];
  82. const size = asset.size();
  83. const file = assetName;
  84. const body = JSON.stringify({
  85. file,
  86. entrypointName,
  87. size,
  88. commit: GITHUB_SHA,
  89. environment: IS_CI ? 'ci' : '',
  90. node_env: NODE_ENV,
  91. });
  92. const req = https.request({
  93. host: 'product-eng-webhooks-vmrqv3f7nq-uw.a.run.app',
  94. path: '/metrics/webpack/webhook',
  95. method: 'POST',
  96. headers: {
  97. 'Content-Type': 'application/json',
  98. 'Content-Length': Buffer.byteLength(body),
  99. 'x-webpack-signature': createSignature(
  100. SENTRY_WEBPACK_WEBHOOK_SECRET,
  101. body
  102. ),
  103. },
  104. });
  105. req.end(body);
  106. })
  107. )
  108. );
  109. }
  110. measureBuildTime(startTime: number, endTime: number) {
  111. if (!this.Sentry) {
  112. return;
  113. }
  114. const span = !this.hasInitializedBuild
  115. ? this.span
  116. : this.Sentry.startInactiveSpan({
  117. op: 'webpack-build',
  118. name: INCREMENTAL_BUILD_TXN,
  119. startTime,
  120. });
  121. if (!span) {
  122. return;
  123. }
  124. this.Sentry.withActiveSpan(span, () => {
  125. this.Sentry?.startInactiveSpan({
  126. op: 'build',
  127. name: 'webpack build',
  128. attributes: {
  129. os: `${os.platform()} ${os.arch()} v${os.release()}`,
  130. memory: os.freemem()
  131. ? `${os.freemem() / GB_BYTE} / ${os.totalmem() / GB_BYTE} GB (${
  132. (os.freemem() / os.totalmem()) * 100
  133. }% free)`
  134. : 'N/A',
  135. loadavg: os.loadavg(),
  136. },
  137. startTime,
  138. }).end(endTime);
  139. });
  140. span.end();
  141. }
  142. apply(compiler: webpack.Compiler) {
  143. compiler.hooks.done.tapAsync(
  144. PLUGIN_NAME,
  145. async ({compilation, startTime, endTime}, done) => {
  146. // Only record this once and only on Travis
  147. // Don't really care about asset sizes during local dev
  148. if (IS_CI && !this.hasInitializedBuild) {
  149. this.measureAssetSizes(compilation);
  150. }
  151. if (this.Sentry) {
  152. this.measureBuildTime(startTime / 1000, endTime / 1000);
  153. await this.Sentry.flush();
  154. }
  155. this.hasInitializedBuild = true;
  156. done();
  157. }
  158. );
  159. }
  160. }
  161. export default SentryInstrumentation;