cursorPoller.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import {Client, Request} from 'sentry/api';
  2. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  3. type Options = {
  4. endpoint: string;
  5. success: (data: any, link?: string | null) => void;
  6. };
  7. const BASE_DELAY = 3000;
  8. const MAX_DELAY = 60000;
  9. class CursorPoller {
  10. constructor(options: Options) {
  11. this.options = options;
  12. this.pollingEndpoint = options.endpoint;
  13. }
  14. api = new Client();
  15. options: Options;
  16. pollingEndpoint: string;
  17. timeoutId: number | null = null;
  18. lastRequest: Request | null = null;
  19. active: boolean = true;
  20. reqsWithoutData = 0;
  21. getDelay() {
  22. const delay = BASE_DELAY * (this.reqsWithoutData + 1);
  23. return Math.min(delay, MAX_DELAY);
  24. }
  25. setEndpoint(url: string) {
  26. this.pollingEndpoint = url;
  27. }
  28. enable() {
  29. this.active = true;
  30. // Proactively clear timeout and last request
  31. if (this.timeoutId) {
  32. window.clearTimeout(this.timeoutId);
  33. }
  34. if (this.lastRequest) {
  35. this.lastRequest.cancel();
  36. }
  37. this.timeoutId = window.setTimeout(this.poll.bind(this), this.getDelay());
  38. }
  39. disable() {
  40. this.active = false;
  41. if (this.timeoutId) {
  42. window.clearTimeout(this.timeoutId);
  43. this.timeoutId = null;
  44. }
  45. if (this.lastRequest) {
  46. this.lastRequest.cancel();
  47. }
  48. }
  49. poll() {
  50. this.lastRequest = this.api.request(this.pollingEndpoint, {
  51. success: (data, _, resp) => {
  52. // cancel in progress operation if disabled
  53. if (!this.active) {
  54. return;
  55. }
  56. // if theres no data, nothing changes
  57. if (!data || !data.length) {
  58. this.reqsWithoutData += 1;
  59. return;
  60. }
  61. if (this.reqsWithoutData > 0) {
  62. this.reqsWithoutData -= 1;
  63. }
  64. const linksHeader = resp?.getResponseHeader('Link') ?? null;
  65. const links = parseLinkHeader(linksHeader);
  66. this.pollingEndpoint = links.previous.href;
  67. this.options.success(data, linksHeader);
  68. },
  69. error: resp => {
  70. if (!resp) {
  71. return;
  72. }
  73. // If user does not have access to the endpoint, we should halt polling
  74. // These errors could mean:
  75. // * the user lost access to a project
  76. // * project was renamed
  77. // * user needs to reauth
  78. if (resp.status === 404 || resp.status === 403 || resp.status === 401) {
  79. this.disable();
  80. }
  81. },
  82. complete: () => {
  83. this.lastRequest = null;
  84. if (this.active) {
  85. this.timeoutId = window.setTimeout(this.poll.bind(this), this.getDelay());
  86. }
  87. },
  88. });
  89. }
  90. }
  91. export default CursorPoller;