metrics-telemetry-privacy.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
  2. import { buildLocalRuntimeMetricsClient } from '../../src/runtime/host-metrics.js';
  3. import type { MetricsClient } from '../../src/common/metrics.js';
  4. const clients: MetricsClient[] = [];
  5. const fetchRequest = vi.fn<typeof fetch>();
  6. beforeEach(() => {
  7. vi.stubEnv('__MAVIS_RUNTIME_MANAGED', '1');
  8. vi.stubEnv('MAVIS_BUILD_ENV', 'prod');
  9. vi.stubEnv('MAVIS_REGION', 'en');
  10. vi.stubEnv('MCODE_DISABLE_TELEMETRY', '');
  11. vi.stubEnv('DO_NOT_TRACK', '');
  12. fetchRequest.mockReset().mockResolvedValue(new Response('{}', { status: 200 }));
  13. vi.stubGlobal('fetch', fetchRequest);
  14. });
  15. afterEach(async () => {
  16. for (const client of clients.splice(0)) await client.close();
  17. vi.unstubAllGlobals();
  18. vi.unstubAllEnvs();
  19. });
  20. function fixture(metrics?: boolean) {
  21. const client = buildLocalRuntimeMetricsClient({
  22. runtimeOwnerKind: 'tui',
  23. appVersion: '0.4.12',
  24. readTelemetryEnabled: () => metrics,
  25. });
  26. clients.push(client);
  27. return client;
  28. }
  29. describe('automatic runtime metrics consent', () => {
  30. it.each([undefined, false])('does not send production metrics without an explicit opt-in (%s)', async (enabled) => {
  31. const client = fixture(enabled);
  32. client.counter('started_total', 1);
  33. await client.flush();
  34. expect(fetchRequest).not.toHaveBeenCalled();
  35. });
  36. it('sends metrics only after the metrics opt-in', async () => {
  37. const client = fixture(true);
  38. client.counter('started_total', 1);
  39. await client.flush();
  40. expect(fetchRequest).toHaveBeenCalledOnce();
  41. expect(String(fetchRequest.mock.calls[0]![0])).toBe('https://agent.minimax.io/matrix/api/v1/metrics/batch');
  42. });
  43. it.each(['MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('%s overrides the metrics opt-in', async (key) => {
  44. vi.stubEnv(key, '1');
  45. const client = fixture(true);
  46. client.counter('started_total', 1);
  47. await client.flush();
  48. expect(fetchRequest).not.toHaveBeenCalled();
  49. });
  50. });