cursorPoller.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import {Client, Request} from 'app/api';
  2. import parseLinkHeader from 'app/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. if (!this.timeoutId) {
  31. this.timeoutId = window.setTimeout(this.poll.bind(this), this.getDelay());
  32. }
  33. }
  34. disable() {
  35. this.active = false;
  36. if (this.timeoutId) {
  37. window.clearTimeout(this.timeoutId);
  38. this.timeoutId = null;
  39. }
  40. if (this.lastRequest) {
  41. this.lastRequest.cancel();
  42. }
  43. }
  44. poll() {
  45. this.lastRequest = this.api.request(this.pollingEndpoint, {
  46. success: (data, _, jqXHR) => {
  47. // cancel in progress operation if disabled
  48. if (!this.active) {
  49. return;
  50. }
  51. // if theres no data, nothing changes
  52. if (!data || !data.length) {
  53. this.reqsWithoutData += 1;
  54. return;
  55. }
  56. if (this.reqsWithoutData > 0) {
  57. this.reqsWithoutData -= 1;
  58. }
  59. const linksHeader = jqXHR?.getResponseHeader('Link') ?? null;
  60. const links = parseLinkHeader(linksHeader);
  61. this.pollingEndpoint = links.previous.href;
  62. this.options.success(data, linksHeader);
  63. },
  64. error: resp => {
  65. if (!resp) {
  66. return;
  67. }
  68. // If user does not have access to the endpoint, we should halt polling
  69. // These errors could mean:
  70. // * the user lost access to a project
  71. // * project was renamed
  72. // * user needs to reauth
  73. if (resp.status === 404 || resp.status === 403 || resp.status === 401) {
  74. this.disable();
  75. }
  76. },
  77. complete: () => {
  78. this.lastRequest = null;
  79. if (this.active) {
  80. this.timeoutId = window.setTimeout(this.poll.bind(this), this.getDelay());
  81. }
  82. },
  83. });
  84. }
  85. }
  86. export default CursorPoller;