polling-job-queue-strategy.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import { JobState } from '@vendure/common/lib/generated-types';
  2. import { ID } from '@vendure/common/lib/shared-types';
  3. import { isObject } from '@vendure/common/lib/shared-utils';
  4. import { from, interval, race, Subject, Subscription } from 'rxjs';
  5. import { filter, switchMap, take, throttleTime } from 'rxjs/operators';
  6. import { Logger } from '../config/logger/vendure-logger';
  7. import { InjectableJobQueueStrategy } from './injectable-job-queue-strategy';
  8. import { Job } from './job';
  9. import { QueueNameProcessStorage } from './queue-name-process-storage';
  10. import { JobData } from './types';
  11. /**
  12. * @description
  13. * Defines the backoff strategy used when retrying failed jobs. Returns the delay in
  14. * ms that should pass before the failed job is retried.
  15. *
  16. * @docsCategory JobQueue
  17. * @docsPage types
  18. */
  19. export type BackoffStrategy = (queueName: string, attemptsMade: number, job: Job) => number;
  20. export interface PollingJobQueueStrategyConfig {
  21. /**
  22. * @description
  23. * How many jobs from a given queue to process concurrently.
  24. *
  25. * Can be set to a function which receives the queue name and returns
  26. * the concurrency limit. This is useful for limiting concurrency on
  27. * queues which have resource-intensive jobs.
  28. *
  29. * @example
  30. * ```ts
  31. * concurrency: (queueName) => {
  32. * if (queueName === 'apply-collection-filters') {
  33. * return 1;
  34. * }
  35. * return 3;
  36. * }
  37. * ```
  38. *
  39. * @default 1
  40. */
  41. concurrency?: number | ((queueName: string) => number);
  42. /**
  43. * @description
  44. * The interval in ms between polling the database for new jobs.
  45. *
  46. * @description 200
  47. */
  48. pollInterval?: number | ((queueName: string) => number);
  49. /**
  50. * @description
  51. * When a job is added to the JobQueue using `JobQueue.add()`, the calling
  52. * code may specify the number of retries in case of failure. This option allows
  53. * you to override that number and specify your own number of retries based on
  54. * the job being added.
  55. */
  56. setRetries?: (queueName: string, job: Job) => number;
  57. /**
  58. * @description
  59. * The strategy used to decide how long to wait before retrying a failed job.
  60. *
  61. * @default () => 1000
  62. */
  63. backoffStrategy?: BackoffStrategy;
  64. /**
  65. * @description
  66. * The timeout in ms which the queue will use when attempting a graceful shutdown.
  67. * That means, when the server is shut down but a job is running, the job queue will
  68. * wait for the job to complete before allowing the server to shut down. If the job
  69. * does not complete within this timeout window, the job will be forced to stop
  70. * and the server will shut down anyway.
  71. *
  72. * @since 2.2.0
  73. * @default 20_000
  74. */
  75. gracefulShutdownTimeout?: number;
  76. }
  77. const STOP_SIGNAL = Symbol('STOP_SIGNAL');
  78. class ActiveQueue<Data extends JobData<Data> = object> {
  79. private timer: any;
  80. private running = false;
  81. private activeJobs: Array<Job<Data>> = [];
  82. private errorNotifier$ = new Subject<[string, string]>();
  83. private queueStopped$ = new Subject<typeof STOP_SIGNAL>();
  84. private subscription: Subscription;
  85. private readonly pollInterval: number;
  86. private readonly concurrency: number;
  87. constructor(
  88. private readonly queueName: string,
  89. private readonly process: (job: Job<Data>) => Promise<any>,
  90. private readonly jobQueueStrategy: PollingJobQueueStrategy,
  91. ) {
  92. this.pollInterval =
  93. typeof this.jobQueueStrategy.pollInterval === 'function'
  94. ? this.jobQueueStrategy.pollInterval(queueName)
  95. : this.jobQueueStrategy.pollInterval;
  96. this.concurrency =
  97. typeof this.jobQueueStrategy.concurrency === 'function'
  98. ? this.jobQueueStrategy.concurrency(queueName)
  99. : this.jobQueueStrategy.concurrency;
  100. }
  101. start() {
  102. Logger.debug(`Starting JobQueue "${this.queueName}"`);
  103. this.subscription = this.errorNotifier$.pipe(throttleTime(3000)).subscribe(([message, stack]) => {
  104. Logger.error(message);
  105. Logger.debug(stack);
  106. });
  107. this.running = true;
  108. const runNextJobs = async () => {
  109. try {
  110. const runningJobsCount = this.activeJobs.length;
  111. for (let i = runningJobsCount; i < this.concurrency; i++) {
  112. const nextJob = await this.jobQueueStrategy.next(this.queueName);
  113. if (nextJob) {
  114. this.activeJobs.push(nextJob);
  115. await this.jobQueueStrategy.update(nextJob);
  116. const onProgress = (job: Job) => this.jobQueueStrategy.update(job);
  117. nextJob.on('progress', onProgress);
  118. const cancellationSub = interval(this.pollInterval * 5)
  119. .pipe(
  120. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  121. switchMap(() => this.jobQueueStrategy.findOne(nextJob.id!)),
  122. filter(job => job?.state === JobState.CANCELLED),
  123. take(1),
  124. )
  125. .subscribe(() => {
  126. nextJob.cancel();
  127. });
  128. const stopSignal$ = this.queueStopped$.pipe(take(1));
  129. race(from(this.process(nextJob)), stopSignal$)
  130. .toPromise()
  131. .then(
  132. result => {
  133. if (result === STOP_SIGNAL) {
  134. nextJob.defer();
  135. } else if (result instanceof Job && result.state === JobState.CANCELLED) {
  136. nextJob.cancel();
  137. } else {
  138. nextJob.complete(result);
  139. }
  140. },
  141. err => {
  142. nextJob.fail(err);
  143. },
  144. )
  145. .finally(() => {
  146. // if (!this.running && nextJob.state !== JobState.PENDING) {
  147. // return;
  148. // }
  149. nextJob.off('progress', onProgress);
  150. cancellationSub.unsubscribe();
  151. return this.onFailOrComplete(nextJob);
  152. })
  153. .catch((err: any) => {
  154. Logger.warn(`Error updating job info: ${JSON.stringify(err)}`);
  155. });
  156. }
  157. }
  158. } catch (e: any) {
  159. this.errorNotifier$.next([
  160. `Job queue "${
  161. this.queueName
  162. }" encountered an error (set log level to Debug for trace): ${JSON.stringify(e.message)}`,
  163. e.stack,
  164. ]);
  165. }
  166. if (this.running) {
  167. this.timer = setTimeout(runNextJobs, this.pollInterval);
  168. }
  169. };
  170. void runNextJobs();
  171. }
  172. async stop(stopActiveQueueTimeout = 20_000): Promise<void> {
  173. this.running = false;
  174. clearTimeout(this.timer);
  175. await this.awaitRunningJobsOrTimeout(stopActiveQueueTimeout);
  176. Logger.info(`Stopped queue: ${this.queueName}`);
  177. this.subscription.unsubscribe();
  178. // Allow any job status changes to be persisted
  179. // before we permit the application shutdown to continue.
  180. // Otherwise, the DB connection will close before our
  181. // changes are persisted.
  182. await new Promise(resolve => setTimeout(resolve, 1000));
  183. }
  184. private awaitRunningJobsOrTimeout(stopActiveQueueTimeout = 20_000): Promise<void> {
  185. const start = +new Date();
  186. let timeout: ReturnType<typeof setTimeout>;
  187. return new Promise(resolve => {
  188. let lastStatusUpdate = +new Date();
  189. const pollActiveJobs = () => {
  190. const now = +new Date();
  191. const timedOut =
  192. stopActiveQueueTimeout === undefined ? false : now - start > stopActiveQueueTimeout;
  193. if (this.activeJobs.length === 0) {
  194. clearTimeout(timeout);
  195. resolve();
  196. return;
  197. }
  198. if (timedOut) {
  199. Logger.warn(
  200. `Timed out (${stopActiveQueueTimeout}ms) waiting for ` +
  201. `${this.activeJobs.length} active jobs in queue "${this.queueName}" ` +
  202. `to complete. Forcing stop...`,
  203. );
  204. this.queueStopped$.next(STOP_SIGNAL);
  205. clearTimeout(timeout);
  206. resolve();
  207. return;
  208. }
  209. if (this.activeJobs.length > 0) {
  210. if (now - lastStatusUpdate > 2000) {
  211. Logger.info(
  212. `Stopping queue: ${this.queueName} - waiting for ${this.activeJobs.length} active jobs to complete...`,
  213. );
  214. lastStatusUpdate = now;
  215. }
  216. }
  217. timeout = setTimeout(pollActiveJobs, 200);
  218. };
  219. void pollActiveJobs();
  220. });
  221. }
  222. private async onFailOrComplete(job: Job<Data>) {
  223. await this.jobQueueStrategy.update(job);
  224. this.removeJobFromActive(job);
  225. }
  226. private removeJobFromActive(job: Job<Data>) {
  227. const index = this.activeJobs.indexOf(job);
  228. if (index !== -1) {
  229. this.activeJobs.splice(index, 1);
  230. }
  231. }
  232. }
  233. /**
  234. * @description
  235. * This class allows easier implementation of {@link JobQueueStrategy} in a polling style.
  236. * Instead of providing {@link JobQueueStrategy} `start()` you should provide a `next` method.
  237. *
  238. * This class should be extended by any strategy which does not support a push-based system
  239. * to notify on new jobs. It is used by the {@link SqlJobQueueStrategy} and {@link InMemoryJobQueueStrategy}.
  240. *
  241. * @docsCategory JobQueue
  242. */
  243. export abstract class PollingJobQueueStrategy extends InjectableJobQueueStrategy {
  244. public concurrency: number | ((queueName: string) => number);
  245. public pollInterval: number | ((queueName: string) => number);
  246. public setRetries: (queueName: string, job: Job) => number;
  247. public backOffStrategy?: BackoffStrategy;
  248. public gracefulShutdownTimeout: number;
  249. protected activeQueues = new QueueNameProcessStorage<ActiveQueue<any>>();
  250. constructor(config?: PollingJobQueueStrategyConfig);
  251. constructor(concurrency?: number, pollInterval?: number);
  252. constructor(concurrencyOrConfig?: number | PollingJobQueueStrategyConfig, maybePollInterval?: number) {
  253. super();
  254. if (concurrencyOrConfig && isObject(concurrencyOrConfig)) {
  255. this.concurrency = concurrencyOrConfig.concurrency ?? 1;
  256. this.pollInterval = concurrencyOrConfig.pollInterval ?? 200;
  257. this.backOffStrategy = concurrencyOrConfig.backoffStrategy ?? (() => 1000);
  258. this.setRetries = concurrencyOrConfig.setRetries ?? ((_, job) => job.retries);
  259. this.gracefulShutdownTimeout = concurrencyOrConfig.gracefulShutdownTimeout ?? 20_000;
  260. } else {
  261. this.concurrency = concurrencyOrConfig ?? 1;
  262. this.pollInterval = maybePollInterval ?? 200;
  263. this.setRetries = (_, job) => job.retries;
  264. this.gracefulShutdownTimeout = 20_000;
  265. }
  266. }
  267. async start<Data extends JobData<Data> = object>(
  268. queueName: string,
  269. process: (job: Job<Data>) => Promise<any>,
  270. ) {
  271. if (!this.hasInitialized) {
  272. this.started.set(queueName, process);
  273. return;
  274. }
  275. if (this.activeQueues.has(queueName, process)) {
  276. return;
  277. }
  278. const active = new ActiveQueue<Data>(queueName, process, this);
  279. active.start();
  280. this.activeQueues.set(queueName, process, active);
  281. }
  282. async stop<Data extends JobData<Data> = object>(
  283. queueName: string,
  284. process: (job: Job<Data>) => Promise<any>,
  285. ) {
  286. const active = this.activeQueues.getAndDelete(queueName, process);
  287. if (!active) {
  288. return;
  289. }
  290. await active.stop(this.gracefulShutdownTimeout);
  291. }
  292. async cancelJob(jobId: ID): Promise<Job | undefined> {
  293. const job = await this.findOne(jobId);
  294. if (job) {
  295. job.cancel();
  296. await this.update(job);
  297. return job;
  298. }
  299. }
  300. /**
  301. * @description
  302. * Should return the next job in the given queue. The implementation is
  303. * responsible for returning the correct job according to the time of
  304. * creation.
  305. */
  306. abstract next(queueName: string): Promise<Job | undefined>;
  307. /**
  308. * @description
  309. * Update the job details in the store.
  310. */
  311. abstract update(job: Job): Promise<void>;
  312. /**
  313. * @description
  314. * Returns a job by its id.
  315. */
  316. abstract findOne(id: ID): Promise<Job | undefined>;
  317. }