job-queue-stress-test.plugin.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Injectable, OnModuleInit } from '@nestjs/common';
  2. import { Args, Mutation, Resolver } from '@nestjs/graphql';
  3. import { JobQueue, JobQueueService, Logger, PluginCommonModule, VendurePlugin } from '@vendure/core';
  4. import gql from 'graphql-tag';
  5. @Injectable()
  6. class TestQueueService implements OnModuleInit {
  7. private jobQueue: JobQueue<{ message: string }>;
  8. constructor(private jobQueueService: JobQueueService) {}
  9. async onModuleInit() {
  10. this.jobQueue = await this.jobQueueService.createQueue({
  11. name: 'test-queue',
  12. process: async job => {
  13. // Process the job here
  14. Logger.info(`Processing job with message: ${job.data.message}`, 'TestQueueService');
  15. if (Math.random() < 0.2) {
  16. throw new Error('Random failure occurred while processing job');
  17. }
  18. return { processed: true, message: job.data.message };
  19. },
  20. });
  21. }
  22. addJob(message: string) {
  23. return this.jobQueue.add({ message });
  24. }
  25. async generateJobs(count: number) {
  26. const jobs = [];
  27. for (let i = 0; i < count; i++) {
  28. jobs.push(this.addJob(`Test job ${i + 1}`));
  29. // await new Promise(resolve => setTimeout(resolve, 100));
  30. }
  31. return Promise.all(jobs);
  32. }
  33. }
  34. @Resolver()
  35. class TestQueueResolver {
  36. constructor(private testQueueService: TestQueueService) {}
  37. @Mutation()
  38. async generateTestJobs(@Args() args: { jobCount: number }) {
  39. const jobs = await this.testQueueService.generateJobs(args.jobCount);
  40. return {
  41. success: true,
  42. jobCount: jobs.length,
  43. };
  44. }
  45. }
  46. /**
  47. * This plugin can create a large number of jobs in the job queue, which we
  48. * can then use to stress test the job queue's ability to return lists of jobs.
  49. */
  50. @VendurePlugin({
  51. imports: [PluginCommonModule],
  52. providers: [TestQueueService],
  53. adminApiExtensions: {
  54. schema: gql`
  55. extend type Mutation {
  56. generateTestJobs(jobCount: Int!): GenerateTestJobsResult!
  57. }
  58. type GenerateTestJobsResult {
  59. success: Boolean!
  60. jobCount: Int!
  61. }
  62. `,
  63. resolvers: [TestQueueResolver],
  64. },
  65. })
  66. export class JobQueueStressTestPlugin {}