You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.web.ts 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { AnyAction } from 'redux';
  2. import MiddlewareRegistry from '../redux/MiddlewareRegistry';
  3. import { isEmbedded } from '../util/embedUtils';
  4. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from './actionTypes';
  5. import logger from './logger';
  6. /**
  7. * Experimental feature to monitor CPU pressure.
  8. */
  9. let pressureObserver: typeof window.PressureObserver;
  10. /**
  11. * Middleware which intercepts app actions to handle changes to the related state.
  12. *
  13. * @param {Store} store - The redux store.
  14. * @returns {Function}
  15. */
  16. MiddlewareRegistry.register(() => (next: Function) => (action: AnyAction) => {
  17. switch (action.type) {
  18. case APP_WILL_MOUNT: {
  19. // Disable it inside an iframe until Google fixes the origin trial for 3rd party sources:
  20. // https://bugs.chromium.org/p/chromium/issues/detail?id=1504167
  21. if (!isEmbedded() && 'PressureObserver' in globalThis) {
  22. pressureObserver = new window.PressureObserver(
  23. (records: typeof window.PressureRecord) => {
  24. logger.info('Compute pressure state changed:', JSON.stringify(records));
  25. if (typeof APP !== 'undefined') {
  26. APP.API.notifyComputePressureChanged(records);
  27. }
  28. },
  29. { sampleRate: 1 }
  30. );
  31. try {
  32. pressureObserver
  33. .observe('cpu')
  34. .catch((e: any) => logger.error('CPU pressure observer failed to start', e));
  35. } catch (e: any) {
  36. logger.error('CPU pressure observer failed to start', e);
  37. }
  38. }
  39. break;
  40. }
  41. case APP_WILL_UNMOUNT: {
  42. if (pressureObserver) {
  43. pressureObserver.unobserve('cpu');
  44. }
  45. break;
  46. }
  47. }
  48. return next(action);
  49. });