@solidxai/core 0.1.10-beta.3 → 0.1.10-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/controllers/action-metadata.controller.js +1 -1
  2. package/dist/controllers/action-metadata.controller.js.map +1 -1
  3. package/dist/controllers/facebook-authentication.controller.js +1 -1
  4. package/dist/controllers/facebook-authentication.controller.js.map +1 -1
  5. package/dist/controllers/google-authentication.controller.js +1 -1
  6. package/dist/controllers/google-authentication.controller.js.map +1 -1
  7. package/dist/controllers/menu-item-metadata.controller.js +1 -1
  8. package/dist/controllers/menu-item-metadata.controller.js.map +1 -1
  9. package/dist/controllers/microsoft-authentication.controller.js +1 -1
  10. package/dist/controllers/microsoft-authentication.controller.js.map +1 -1
  11. package/dist/controllers/mq-message-queue.controller.js +1 -1
  12. package/dist/controllers/mq-message-queue.controller.js.map +1 -1
  13. package/dist/controllers/mq-message.controller.js +1 -1
  14. package/dist/controllers/mq-message.controller.js.map +1 -1
  15. package/dist/controllers/view-metadata.controller.js +1 -1
  16. package/dist/controllers/view-metadata.controller.js.map +1 -1
  17. package/dist/entities/chatter-message-details.entity.d.ts.map +1 -1
  18. package/dist/entities/chatter-message-details.entity.js +0 -1
  19. package/dist/entities/chatter-message-details.entity.js.map +1 -1
  20. package/dist/helpers/field-crud-managers/BigIntFieldCrudManager.js.map +1 -1
  21. package/dist/helpers/field-crud-managers/SelectionDynamicFieldCrudManager.js.map +1 -1
  22. package/dist/helpers/module-metadata-helper.service.js.map +1 -1
  23. package/dist/jobs/database/chatter-queue-subscriber-database.service.d.ts.map +1 -1
  24. package/dist/jobs/database/chatter-queue-subscriber-database.service.js +3 -3
  25. package/dist/jobs/database/chatter-queue-subscriber-database.service.js.map +1 -1
  26. package/dist/jobs/database/trigger-mcp-client-subscriber-database.service.js.map +1 -1
  27. package/dist/jobs/rabbitmq/chatter-queue-subscriber.service.d.ts.map +1 -1
  28. package/dist/jobs/rabbitmq/chatter-queue-subscriber.service.js +3 -3
  29. package/dist/jobs/rabbitmq/chatter-queue-subscriber.service.js.map +1 -1
  30. package/dist/jobs/redis/chatter-queue-subscriber-redis.service.d.ts.map +1 -1
  31. package/dist/jobs/redis/chatter-queue-subscriber-redis.service.js +3 -3
  32. package/dist/jobs/redis/chatter-queue-subscriber-redis.service.js.map +1 -1
  33. package/dist/repository/security-rule.repository.js.map +1 -1
  34. package/dist/seeders/module-metadata-seeder.service.js.map +1 -1
  35. package/dist/seeders/permission-metadata-seeder.service.js.map +1 -1
  36. package/dist/seeders/seed-data/solid-core-metadata.json +13 -2
  37. package/dist/services/authentication.service.d.ts.map +1 -1
  38. package/dist/services/authentication.service.js +5 -5
  39. package/dist/services/authentication.service.js.map +1 -1
  40. package/dist/services/chatter-message.service.d.ts +6 -3
  41. package/dist/services/chatter-message.service.d.ts.map +1 -1
  42. package/dist/services/chatter-message.service.js +23 -35
  43. package/dist/services/chatter-message.service.js.map +1 -1
  44. package/dist/services/crud.service.js.map +1 -1
  45. package/dist/services/csv.service.js.map +1 -1
  46. package/dist/services/dashboard.service.js.map +1 -1
  47. package/dist/services/database/database-bootstrap.service.js.map +1 -1
  48. package/dist/services/excel.service.js.map +1 -1
  49. package/dist/services/export-transaction.service.js.map +1 -1
  50. package/dist/services/field-metadata.service.js.map +1 -1
  51. package/dist/services/fixtures.service.js.map +1 -1
  52. package/dist/services/import-transaction.service.js.map +1 -1
  53. package/dist/services/list-of-values.service.js.map +1 -1
  54. package/dist/services/model-metadata.service.d.ts.map +1 -1
  55. package/dist/services/model-metadata.service.js +3 -13
  56. package/dist/services/model-metadata.service.js.map +1 -1
  57. package/dist/services/module-metadata.service.js.map +1 -1
  58. package/dist/services/queues/database-publisher.service.js +3 -3
  59. package/dist/services/queues/database-publisher.service.js.map +1 -1
  60. package/dist/services/queues/database-subscriber.service.js.map +1 -1
  61. package/dist/services/queues/rabbitmq-publisher.service.js +3 -3
  62. package/dist/services/queues/rabbitmq-publisher.service.js.map +1 -1
  63. package/dist/services/queues/rabbitmq-subscriber.service.js.map +1 -1
  64. package/dist/services/queues/redis-publisher.service.d.ts.map +1 -1
  65. package/dist/services/queues/redis-publisher.service.js +4 -1
  66. package/dist/services/queues/redis-publisher.service.js.map +1 -1
  67. package/dist/services/queues/redis-subscriber.service.js.map +1 -1
  68. package/dist/services/role-metadata.service.js.map +1 -1
  69. package/dist/services/scheduled-jobs/scheduler.service.js.map +1 -1
  70. package/dist/services/settings/default-settings-provider.service.d.ts +58 -8
  71. package/dist/services/settings/default-settings-provider.service.d.ts.map +1 -1
  72. package/dist/services/settings/default-settings-provider.service.js +21 -4
  73. package/dist/services/settings/default-settings-provider.service.js.map +1 -1
  74. package/dist/services/sms/TwilioSMSService.js.map +1 -1
  75. package/dist/services/solid-introspect.service.js.map +1 -1
  76. package/dist/services/user-activity-history.service.js.map +1 -1
  77. package/dist/services/view-metadata.service.d.ts.map +1 -1
  78. package/dist/services/view-metadata.service.js +17 -2
  79. package/dist/services/view-metadata.service.js.map +1 -1
  80. package/dist/subscribers/computed-entity-field.subscriber.js.map +1 -1
  81. package/dist/subscribers/security-rule.subscriber.d.ts.map +1 -1
  82. package/dist/subscribers/security-rule.subscriber.js.map +1 -1
  83. package/dist/subscribers/view-metadata.subscriber.js.map +1 -1
  84. package/dist/testing/core/testing-engine.js.map +1 -1
  85. package/dist/testing/reporter/webhook-reporter.js.map +1 -1
  86. package/dist-tests/api/authenticate.spec.js +119 -0
  87. package/dist-tests/api/authenticate.spec.js.map +1 -0
  88. package/dist-tests/api/crud-service.findOne.cityMaster.spec.js +97 -0
  89. package/dist-tests/api/crud-service.findOne.cityMaster.spec.js.map +1 -0
  90. package/dist-tests/api/ping.spec.js +21 -0
  91. package/dist-tests/api/ping.spec.js.map +1 -0
  92. package/dist-tests/helpers/auth.js +41 -0
  93. package/dist-tests/helpers/auth.js.map +1 -0
  94. package/dist-tests/helpers/env.js +11 -0
  95. package/dist-tests/helpers/env.js.map +1 -0
  96. package/docs/grouping-enhancements.md +89 -0
  97. package/docs/java-spring/README.md +3 -0
  98. package/docs/java-spring/solid-core-module-deep-dive-report.md +1317 -0
  99. package/docs/seed-changes.md +65 -0
  100. package/docs/test-data-workflow.md +200 -0
  101. package/docs/type-declaration-import-issue.md +24 -0
  102. package/package.json +1 -1
  103. package/src/controllers/action-metadata.controller.ts +1 -1
  104. package/src/controllers/facebook-authentication.controller.ts +1 -1
  105. package/src/controllers/google-authentication.controller.ts +1 -1
  106. package/src/controllers/menu-item-metadata.controller.ts +1 -1
  107. package/src/controllers/microsoft-authentication.controller.ts +1 -1
  108. package/src/controllers/mq-message-queue.controller.ts +1 -1
  109. package/src/controllers/mq-message.controller.ts +1 -1
  110. package/src/controllers/view-metadata.controller.ts +1 -1
  111. package/src/entities/chatter-message-details.entity.ts +1 -2
  112. package/src/helpers/field-crud-managers/BigIntFieldCrudManager.ts +1 -1
  113. package/src/helpers/field-crud-managers/SelectionDynamicFieldCrudManager.ts +1 -1
  114. package/src/helpers/module-metadata-helper.service.ts +1 -1
  115. package/src/jobs/database/chatter-queue-subscriber-database.service.ts +4 -2
  116. package/src/jobs/database/trigger-mcp-client-subscriber-database.service.ts +1 -1
  117. package/src/jobs/rabbitmq/chatter-queue-subscriber.service.ts +4 -2
  118. package/src/jobs/redis/chatter-queue-subscriber-redis.service.ts +10 -3
  119. package/src/repository/security-rule.repository.ts +1 -1
  120. package/src/seeders/module-metadata-seeder.service.ts +4 -4
  121. package/src/seeders/permission-metadata-seeder.service.ts +1 -1
  122. package/src/seeders/seed-data/solid-core-metadata.json +13 -2
  123. package/src/services/authentication.service.ts +19 -31
  124. package/src/services/chatter-message.service.ts +28 -38
  125. package/src/services/crud.service.ts +1 -1
  126. package/src/services/csv.service.ts +1 -1
  127. package/src/services/dashboard.service.ts +1 -1
  128. package/src/services/database/database-bootstrap.service.ts +1 -1
  129. package/src/services/excel.service.ts +1 -1
  130. package/src/services/export-transaction.service.ts +2 -2
  131. package/src/services/field-metadata.service.ts +1 -1
  132. package/src/services/fixtures.service.ts +2 -2
  133. package/src/services/import-transaction.service.ts +2 -2
  134. package/src/services/list-of-values.service.ts +1 -1
  135. package/src/services/model-metadata.service.ts +22 -21
  136. package/src/services/module-metadata.service.ts +7 -7
  137. package/src/services/queues/database-publisher.service.ts +4 -4
  138. package/src/services/queues/database-subscriber.service.ts +1 -1
  139. package/src/services/queues/rabbitmq-publisher.service.ts +7 -7
  140. package/src/services/queues/rabbitmq-subscriber.service.ts +8 -8
  141. package/src/services/queues/redis-publisher.service.ts +7 -4
  142. package/src/services/queues/redis-subscriber.service.ts +4 -4
  143. package/src/services/role-metadata.service.ts +1 -1
  144. package/src/services/scheduled-jobs/scheduler.service.ts +5 -5
  145. package/src/services/settings/default-settings-provider.service.ts +21 -4
  146. package/src/services/sms/TwilioSMSService.ts +2 -2
  147. package/src/services/solid-introspect.service.ts +2 -2
  148. package/src/services/user-activity-history.service.ts +1 -1
  149. package/src/services/view-metadata.service.ts +25 -8
  150. package/src/subscribers/computed-entity-field.subscriber.ts +1 -1
  151. package/src/subscribers/security-rule.subscriber.ts +8 -8
  152. package/src/subscribers/view-metadata.subscriber.ts +1 -1
  153. package/src/testing/core/testing-engine.ts +2 -2
  154. package/src/testing/reporter/webhook-reporter.ts +1 -1
  155. package/.claude/settings.local.json +0 -15
  156. package/src/services/1.js +0 -6
@@ -1 +1 @@
1
- {"version":3,"file":"module-metadata.service.js","sourceRoot":"","sources":["../../src/services/module-metadata.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAgH;AAChH,6CAAmD;AACnD,oGAAyG;AAEzG,qCAAwE;AAExE,+EAAoE;AAEpE,4DAAoD;AAEpD,gDAAkC;AAClC,2CAA6B;AAC7B,gEAA8D;AAC9D,qGAAuF;AACvF,8FAAyF;AACzF,yFAAqF;AACrF,sGAAiG;AACjG,iCAAoD;AAGpD,oEAGsC;AACtC,8DAA0D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e;QACZ,gCAAc;QAEJ,oEAA+B;QAEnC,6CAAoB;QAC3B,8BAAa;QACC,4DAA2B;GAlBhE,qBAAqB,CA6bjC","sourcesContent":["import { BadRequestException, forwardRef, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';\nimport { InjectDataSource } from '@nestjs/typeorm';\nimport { DEFAULT_MEDIA_FILE_STORAGE_DIR } from \"src/services/settings/default-settings-provider.service\";\nimport type { SolidCoreSetting } from \"src/services/settings/default-settings-provider.service\";\nimport { DataSource, EntityManager, SelectQueryBuilder } from 'typeorm';\nimport { CreateModuleMetadataDto } from '../dtos/create-module-metadata.dto';\nimport { ModuleMetadata } from '../entities/module-metadata.entity';\n\nimport { classify } from '../helpers/string.helper';\nimport { ConfigService } from '@nestjs/config';\nimport * as fs from 'fs/promises'; // Use the Promise-based version of fs for async/await\nimport * as path from 'path'; // To handle file paths\nimport { ERROR_MESSAGES } from 'src/constants/error-messages';\nimport { DisallowInProduction } from 'src/decorators/disallow-in-production.decorator';\nimport { ModuleMetadataHelperService } from 'src/helpers/module-metadata-helper.service';\nimport { ModuleMetadataRepository } from 'src/repository/module-metadata.repository';\nimport { PermissionMetadataSeederService } from 'src/seeders/permission-metadata-seeder.service';\nimport { DiskFileService } from 'src/services/file';\nimport { BasicFilterDto } from '../dtos/basic-filters.dto';\nimport { UpdateModuleMetadataDto } from '../dtos/update-module-metadata.dto';\nimport {\n ADD_MODULE_COMMAND,\n SchematicService,\n} from '../helpers/schematic.service';\nimport { SolidRegistry } from '../helpers/solid-registry';\nimport { CodeGenerationOptions, ModuleMetadataConfiguration } from '../interfaces';\nimport { CrudHelperService } from './crud-helper.service';\nimport { ModelMetadataService } from './model-metadata.service';\nimport { SettingService } from './setting.service';\n\n@Injectable()\nexport class ModuleMetadataService {\n private readonly logger = new Logger(ModuleMetadataService.name);\n\n constructor(\n @InjectDataSource()\n private readonly dataSource: DataSource,\n // @InjectRepository(ModuleMetadata)\n // private readonly moduleMetadataRepo: Repository<ModuleMetadata>,\n private readonly moduleMetadataRepo: ModuleMetadataRepository,\n private readonly crudHelperService: CrudHelperService,\n private readonly schematicService: SchematicService,\n private readonly fileService: DiskFileService,\n private readonly settingService: SettingService,\n\n private readonly permissionsSeederService: PermissionMetadataSeederService,\n @Inject(forwardRef(() => ModelMetadataService))\n private readonly modelMetadataService: ModelMetadataService,\n private readonly solidRegistry: SolidRegistry,\n private readonly moduleMetadataHelperService: ModuleMetadataHelperService,\n ) { }\n\n async findMany(basicFilterDto: BasicFilterDto) {\n const alias = 'moduleMetadata';\n // Extract the required keys from the input query\n let { limit, offset } = basicFilterDto;\n\n // Create above query on pincode table using query builder\n var qb: SelectQueryBuilder<ModuleMetadata> = await this.moduleMetadataRepo.createSecurityRuleAwareQueryBuilder(alias)\n qb = await this.crudHelperService.buildFilterQuery(qb, basicFilterDto, alias);\n\n // Get the records and the count\n const [entities, count] = await qb.getManyAndCount();\n\n const currentPage = Math.floor(offset / limit) + 1;\n const totalPages = Math.ceil(count / limit);\n\n const nextPage = currentPage < totalPages ? currentPage + 1 : null;\n const prevPage = currentPage > 1 ? currentPage - 1 : null;\n\n const r = {\n meta: {\n totalRecords: count,\n currentPage: currentPage,\n nextPage: nextPage,\n prevPage: prevPage,\n totalPages: totalPages,\n perPage: +limit,\n },\n records: entities\n };\n return r\n }\n\n async find(basicFilterDto: BasicFilterDto) {\n return this.findMany(basicFilterDto);\n }\n\n async findOneByUserKey(name: string, relations = {}) {\n if (!name) {\n throw new BadRequestException(ERROR_MESSAGES.ENTITY_NAME_REQUIRED);\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n name: name,\n },\n relations: relations,\n });\n return entity;\n }\n\n async findOne(id: number, relations = {}) {\n if (!id) {\n throw new BadRequestException(ERROR_MESSAGES.ENTITY_ID_REQUIRED);\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n id: id,\n },\n relations: relations,\n });\n if (!entity) {\n throw new NotFoundException(ERROR_MESSAGES.ENTITY_NOT_FOUND());\n }\n return entity;\n }\n\n async create(createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.createInDB(manager, createDto, files);\n await this.createInFile(module);\n return module\n });\n } catch (error) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n\n async createInDB(manager: EntityManager, createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n if (files.length > 0) {\n const fileStoragePath = this.getFullFilePathForDisk(this.getFileName(files[0]));\n this.fileService.copy(files[0].path, fileStoragePath);\n this.fileService.delete(files[0].path);\n createDto.menuIconUrl = fileStoragePath;\n }\n const moduleMetadata = this.moduleMetadataRepo.create(createDto);\n return manager.save(moduleMetadata); // Use the provided manager to perform DB operations\n }\n\n async createInFile(module: ModuleMetadata) {\n try {\n // Prepare the metadata JSON structure\n\n const moduleMetaDataJson: ModuleMetadataConfiguration = {\n moduleMetadata: {\n name: module?.name,\n displayName: module?.displayName,\n description: module?.description,\n defaultDataSource: module?.defaultDataSource,\n menuIconUrl: module?.menuIconUrl,\n menuSequenceNumber: module?.menuSequenceNumber,\n isSystem: module?.isSystem,\n models: [],\n },\n roles: [],\n users: [],\n actions: [\n {\n displayName: `${module?.name} Home`,\n name: `${module?.name}-home-action`,\n type: \"custom\",\n domain: \"\",\n context: \"\",\n customComponent: `/admin/core/${module?.name}/home`,\n customIsModal: true,\n serverEndpoint: \"\",\n viewUserKey: \"\",\n moduleUserKey: module?.name,\n modelUserKey: \"\"\n }\n ],\n menus: [\n {\n displayName: \"Home\",\n name: `${module?.name}-home-menu`,\n sequenceNumber: 1,\n actionUserKey: `${module?.name}-home-action`,\n moduleUserKey: module?.name,\n parentMenuItemUserKey: \"\",\n iconName : \"home\"\n }\n ],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n securityRules: [],\n };\n\n // Convert the object to JSON string\n const metadataJson = JSON.stringify(moduleMetaDataJson, null, 2);\n\n // Create the folder path inside 'module-metadata'\n const folderPath = path.resolve(process.cwd(), 'module-metadata', module.name);\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Ensure the folder exists\n await fs.mkdir(folderPath, { recursive: true });\n\n // Write the JSON to the file\n await fs.writeFile(filePath, metadataJson);\n\n } catch (error) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error(ERROR_MESSAGES.FILE_WRITE_FAILED); // Trigger rollback\n }\n }\n\n async update(id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.updateInDB(manager, id, updateModuleMetadataDto, files);\n await this.updateInFile(module);\n return module\n });\n } catch (error) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n\n async updateInDB(manager: EntityManager, id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n\n const module = await this.moduleMetadataRepo.preload({\n id,\n ...updateModuleMetadataDto,\n });\n\n if (!module) {\n throw new NotFoundException(ERROR_MESSAGES.MODULE_ID_NOT_FOUND(id));\n }\n if (files.length > 0) {\n\n const fileStoragePath = this.getFullFilePathForDisk(this.getFileName(files[0]));\n this.fileService.copy(files[0].path, fileStoragePath);\n this.fileService.delete(files[0].path);\n module.menuIconUrl = fileStoragePath;\n }\n return manager.save(ModuleMetadata, module);\n }\n\n async updateInFile(module: ModuleMetadata) {\n try {\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Read the existing JSON file\n let metaData;\n try {\n metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);\n\n } catch (error) {\n metaData = {\n moduleMetadata: {\n name: null,\n displayName: null,\n description: null,\n defaultDataSource: null,\n menuIconUrl: null,\n menuSequenceNumber: null,\n isSystem: null,\n models: [],\n },\n roles: [],\n users: [],\n actions: [],\n menus: [],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n };\n }\n\n metaData.moduleMetadata.name = module?.name;\n metaData.moduleMetadata.displayName = module?.displayName;\n metaData.moduleMetadata.description = module?.description;\n metaData.moduleMetadata.defaultDataSource = module?.defaultDataSource;\n metaData.moduleMetadata.menuIconUrl = module?.menuIconUrl;\n metaData.moduleMetadata.menuSequenceNumber = module?.menuSequenceNumber;\n metaData.moduleMetadata.isSystem = module?.isSystem;\n\n // Write the JSON to the file\n const updatedContent = JSON.stringify(metaData, null, 2);\n await fs.writeFile(filePath, updatedContent);\n\n } catch (error) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error(ERROR_MESSAGES.FILE_WRITE_FAILED); // Trigger rollback\n }\n }\n\n async upsert(updateModuleMetadataDto: UpdateModuleMetadataDto) {\n this.logger.debug(`Module Upsert called for : ${updateModuleMetadataDto.name}`);\n // First check if module already exists using name\n const existingModuleMetadata = await this.moduleMetadataRepo.findOne({\n where: {\n name: updateModuleMetadataDto.name\n }\n })\n const { models, ...restUpdateModuleMetadataDto } = updateModuleMetadataDto;\n // if found\n if (existingModuleMetadata) {\n const updatedModuleMetadata = { ...existingModuleMetadata, ...restUpdateModuleMetadataDto };\n return this.moduleMetadataRepo.save(updatedModuleMetadata);\n }\n // if not found - create new \n else {\n const moduleMetadata = this.moduleMetadataRepo.create(restUpdateModuleMetadataDto);\n return this.moduleMetadataRepo.save(moduleMetadata);\n }\n }\n\n async removeByName(name: string) {\n const entity = await this.findOneByUserKey(name);\n if (entity) {\n await this.moduleMetadataRepo.remove(entity);\n }\n }\n\n @DisallowInProduction()\n async remove(id: number) {\n const entity = await this.findOne(id);\n await this.cleanupOnDelete(entity.id);\n const r = await this.moduleMetadataRepo.remove(entity);\n return r\n }\n\n async cleanupOnDelete(moduleEntityId: number) {\n const moduleEntity = await this.moduleMetadataRepo.findOne({\n where: {\n // @ts-ignore\n id: moduleEntityId,\n }\n });\n\n if (!moduleEntity) {\n this.logger.log(`Invalid moduleEntityId: ${moduleEntityId} unable to resolve model metadata`);\n return;\n }\n if (moduleEntity.id !== moduleEntityId) {\n this.logger.log(`Invalid moduleEntityId: ${moduleEntityId} unable to resolve model metadata id ${moduleEntity.id} not matching with the one passed as argument ${moduleEntityId}`);\n return;\n }\n\n this.logger.log(`Cleaning up for module: ${moduleEntity.name}.`);\n\n const modulePath = await this.moduleMetadataHelperService.getModulePath(moduleEntity.name);\n if (modulePath) {\n\n this.logger.log(`Module path: ${modulePath}`);\n\n // Metadata file to be deleted\n const moduleMetadataPAth = await this.moduleMetadataHelperService.getModuleMetadataFolderPath(moduleEntity.name)\n this.logger.log(`About to delete module metadata path: ${moduleMetadataPAth}`);\n\n try {\n await fs.rm(modulePath, { recursive: true, force: true });\n await fs.rm(moduleMetadataPAth, { recursive: true, force: true });\n this.logger.log(`Deleted file: ${moduleMetadataPAth}`);\n } catch (error) {\n this.logger.error(`Error deleting file: ${moduleMetadataPAth}`, error);\n throw new Error(ERROR_MESSAGES.FILE_DELETE_FAILED); // Trigger rollback\n }\n }\n await this.dataSource.query(\n `CALL cleanup_module_metadata($1, $2)`,\n [moduleEntity.name, true],\n );\n }\n\n async deleteMany(ids: number[]): Promise<any> {\n if (!ids || ids.length === 0) {\n throw new Error(ERROR_MESSAGES.DELETE_IDS_REQUIRED);\n }\n const removedEntities = [];\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n //@ts-ignore\n id: id,\n }\n });\n // if (!entity) {\n // throw new Error(`Entity with id ${id} not found`);\n // }\n removedEntities.push(await this.moduleMetadataRepo.remove(entity));\n }\n\n return removedEntities\n }\n\n async refreshPermission() {\n await this.permissionsSeederService.seed();\n return true\n }\n\n @DisallowInProduction()\n async generateCode(options: CodeGenerationOptions): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException(ERROR_MESSAGES.MODEL_REQUIRED_FOR_CODE_GENERATION);\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n // Check if the module exists\n if (!module) {\n throw new NotFoundException(ERROR_MESSAGES.MODULE_ID_NOT_FOUND(options.moduleId));\n }\n\n // Check if the module name already exists and is loaded\n const moduleInstance = this.solidRegistry.getModule(`${classify(module.name)}Module`);\n\n if (!moduleInstance) {\n const addModuleOutput = await this.generateAddModuleCode(options);\n const refreshModuleOutput = await this.generateRefreshModuleCode(options);\n return `${addModuleOutput}\\n${refreshModuleOutput}`;\n } else {\n return await this.generateRefreshModuleCode(options);\n }\n }\n\n private async generateAddModuleCode(options: CodeGenerationOptions = { dryRun: false }): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException(ERROR_MESSAGES.MODEL_REQUIRED_FOR_CODE_GENERATION);\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n //Generate the module\n const output = await this.schematicService.executeSchematicCommand(\n ADD_MODULE_COMMAND,\n { module: module.name },\n options.dryRun ?? false\n );\n this.logger.debug(`Schematic output : ${output}`);\n return output;\n }\n\n private async generateRefreshModuleCode(options: CodeGenerationOptions): Promise<string> {\n const query = {\n relations: { models: { fields: true } },\n };\n const module = options.moduleId ? await this.findOne(options.moduleId, query.relations) : await this.findOneByUserKey(options.moduleUserKey, query.relations);\n const outputLines = []\n for (const model of module.models) {\n const codeGenerationOptions = {\n modelId: model.id,\n dryRun: options.dryRun,\n };\n const output = await this.modelMetadataService.handleGenerateCode(codeGenerationOptions);\n this.logger.debug(`Schematic output : ${output}`);\n outputLines.push(output)\n }\n return outputLines.join('\\n');\n }\n\n private getFullFilePathForDisk(fileName: string): string {\n const base = this.settingService.getConfigValue<SolidCoreSetting>(\"fileStorageDir\")\n || DEFAULT_MEDIA_FILE_STORAGE_DIR;\n if (path.isAbsolute(fileName) || fileName.startsWith(`${base}/`)) {\n return fileName;\n }\n return `${base}/${fileName}`;\n }\n\n private getFileName(file: Express.Multer.File): string {\n return `${file.filename}-${file.originalname}`;\n }\n\n}\n"]}
1
+ {"version":3,"file":"module-metadata.service.js","sourceRoot":"","sources":["../../src/services/module-metadata.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAgH;AAChH,6CAAmD;AACnD,oGAAyG;AAEzG,qCAAwE;AAExE,+EAAoE;AAEpE,4DAAoD;AAEpD,gDAAkC;AAClC,2CAA6B;AAC7B,gEAA8D;AAC9D,qGAAuF;AACvF,8FAAyF;AACzF,yFAAqF;AACrF,sGAAiG;AACjG,iCAAoD;AAGpD,oEAGsC;AACtC,8DAA0D;AAE1D,+DAA0D;AAC1D,qEAAgE;AAChE,uDAAmD;AAG5C,IAAM,qBAAqB,6BAA3B,MAAM,qBAAqB;IAGhC,YAEE,UAAuC,EAGtB,kBAA4C,EAC5C,iBAAoC,EACpC,gBAAkC,EAClC,WAA4B,EAC5B,cAA8B,EAE9B,wBAAyD,EAE1E,oBAA2D,EAC1C,aAA4B,EAC5B,2BAAwD;QAbxD,eAAU,GAAV,UAAU,CAAY;QAGtB,uBAAkB,GAAlB,kBAAkB,CAA0B;QAC5C,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,gBAAW,GAAX,WAAW,CAAiB;QAC5B,mBAAc,GAAd,cAAc,CAAgB;QAE9B,6BAAwB,GAAxB,wBAAwB,CAAiC;QAEzD,yBAAoB,GAApB,oBAAoB,CAAsB;QAC1C,kBAAa,GAAb,aAAa,CAAe;QAC5B,gCAA2B,GAA3B,2BAA2B,CAA6B;QAjB1D,WAAM,GAAG,IAAI,eAAM,CAAC,uBAAqB,CAAC,IAAI,CAAC,CAAC;IAkB7D,CAAC;IAEL,KAAK,CAAC,QAAQ,CAAC,cAA8B;QAC3C,MAAM,KAAK,GAAG,gB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CAAC;IAEO,WAAW,CAAC,IAAyB;QAC3C,OAAO,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;IACjD,CAAC;CAEF,CAAA;AA7bY,sDAAqB;AAyS1B;IADL,IAAA,uDAAoB,GAAE;;;;mDAMtB;AAyEK;IADL,IAAA,uDAAoB,GAAE;;;;yDAsBtB;gCA5YU,qBAAqB;IADjC,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,0BAAgB,GAAE,CAAA;IAWlB,WAAA,IAAA,eAAM,EAAC,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,6CAAoB,CAAC,CAAC,CAAA;qCAVlB,oBAAU;QAGF,qDAAwB;QACzB,uCAAiB;QAClB,oCAAgB;QACrB,sBAAe;QACZ,gCAAc;QAEJ,oEAA+B;QAEnC,6CAAoB;QAC3B,8BAAa;QACC,4DAA2B;GAlBhE,qBAAqB,CA6bjC","sourcesContent":["import { BadRequestException, forwardRef, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';\nimport { InjectDataSource } from '@nestjs/typeorm';\nimport { DEFAULT_MEDIA_FILE_STORAGE_DIR } from \"src/services/settings/default-settings-provider.service\";\nimport type { SolidCoreSetting } from \"src/services/settings/default-settings-provider.service\";\nimport { DataSource, EntityManager, SelectQueryBuilder } from 'typeorm';\nimport { CreateModuleMetadataDto } from '../dtos/create-module-metadata.dto';\nimport { ModuleMetadata } from '../entities/module-metadata.entity';\n\nimport { classify } from '../helpers/string.helper';\nimport { ConfigService } from '@nestjs/config';\nimport * as fs from 'fs/promises'; // Use the Promise-based version of fs for async/await\nimport * as path from 'path'; // To handle file paths\nimport { ERROR_MESSAGES } from 'src/constants/error-messages';\nimport { DisallowInProduction } from 'src/decorators/disallow-in-production.decorator';\nimport { ModuleMetadataHelperService } from 'src/helpers/module-metadata-helper.service';\nimport { ModuleMetadataRepository } from 'src/repository/module-metadata.repository';\nimport { PermissionMetadataSeederService } from 'src/seeders/permission-metadata-seeder.service';\nimport { DiskFileService } from 'src/services/file';\nimport { BasicFilterDto } from '../dtos/basic-filters.dto';\nimport { UpdateModuleMetadataDto } from '../dtos/update-module-metadata.dto';\nimport {\n ADD_MODULE_COMMAND,\n SchematicService,\n} from '../helpers/schematic.service';\nimport { SolidRegistry } from '../helpers/solid-registry';\nimport { CodeGenerationOptions, ModuleMetadataConfiguration } from '../interfaces';\nimport { CrudHelperService } from './crud-helper.service';\nimport { ModelMetadataService } from './model-metadata.service';\nimport { SettingService } from './setting.service';\n\n@Injectable()\nexport class ModuleMetadataService {\n private readonly logger = new Logger(ModuleMetadataService.name);\n\n constructor(\n @InjectDataSource()\n private readonly dataSource: DataSource,\n // @InjectRepository(ModuleMetadata)\n // private readonly moduleMetadataRepo: Repository<ModuleMetadata>,\n private readonly moduleMetadataRepo: ModuleMetadataRepository,\n private readonly crudHelperService: CrudHelperService,\n private readonly schematicService: SchematicService,\n private readonly fileService: DiskFileService,\n private readonly settingService: SettingService,\n\n private readonly permissionsSeederService: PermissionMetadataSeederService,\n @Inject(forwardRef(() => ModelMetadataService))\n private readonly modelMetadataService: ModelMetadataService,\n private readonly solidRegistry: SolidRegistry,\n private readonly moduleMetadataHelperService: ModuleMetadataHelperService,\n ) { }\n\n async findMany(basicFilterDto: BasicFilterDto) {\n const alias = 'moduleMetadata';\n // Extract the required keys from the input query\n let { limit, offset } = basicFilterDto;\n\n // Create above query on pincode table using query builder\n var qb: SelectQueryBuilder<ModuleMetadata> = await this.moduleMetadataRepo.createSecurityRuleAwareQueryBuilder(alias)\n qb = await this.crudHelperService.buildFilterQuery(qb, basicFilterDto, alias);\n\n // Get the records and the count\n const [entities, count] = await qb.getManyAndCount();\n\n const currentPage = Math.floor(offset / limit) + 1;\n const totalPages = Math.ceil(count / limit);\n\n const nextPage = currentPage < totalPages ? currentPage + 1 : null;\n const prevPage = currentPage > 1 ? currentPage - 1 : null;\n\n const r = {\n meta: {\n totalRecords: count,\n currentPage: currentPage,\n nextPage: nextPage,\n prevPage: prevPage,\n totalPages: totalPages,\n perPage: +limit,\n },\n records: entities\n };\n return r\n }\n\n async find(basicFilterDto: BasicFilterDto) {\n return this.findMany(basicFilterDto);\n }\n\n async findOneByUserKey(name: string, relations = {}) {\n if (!name) {\n throw new BadRequestException(ERROR_MESSAGES.ENTITY_NAME_REQUIRED);\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n name: name,\n },\n relations: relations,\n });\n return entity;\n }\n\n async findOne(id: number, relations = {}) {\n if (!id) {\n throw new BadRequestException(ERROR_MESSAGES.ENTITY_ID_REQUIRED);\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n id: id,\n },\n relations: relations,\n });\n if (!entity) {\n throw new NotFoundException(ERROR_MESSAGES.ENTITY_NOT_FOUND());\n }\n return entity;\n }\n\n async create(createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.createInDB(manager, createDto, files);\n await this.createInFile(module);\n return module\n });\n } catch (error: any) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n\n async createInDB(manager: EntityManager, createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n if (files.length > 0) {\n const fileStoragePath = this.getFullFilePathForDisk(this.getFileName(files[0]));\n this.fileService.copy(files[0].path, fileStoragePath);\n this.fileService.delete(files[0].path);\n createDto.menuIconUrl = fileStoragePath;\n }\n const moduleMetadata = this.moduleMetadataRepo.create(createDto);\n return manager.save(moduleMetadata); // Use the provided manager to perform DB operations\n }\n\n async createInFile(module: ModuleMetadata) {\n try {\n // Prepare the metadata JSON structure\n\n const moduleMetaDataJson: ModuleMetadataConfiguration = {\n moduleMetadata: {\n name: module?.name,\n displayName: module?.displayName,\n description: module?.description,\n defaultDataSource: module?.defaultDataSource,\n menuIconUrl: module?.menuIconUrl,\n menuSequenceNumber: module?.menuSequenceNumber,\n isSystem: module?.isSystem,\n models: [],\n },\n roles: [],\n users: [],\n actions: [\n {\n displayName: `${module?.name} Home`,\n name: `${module?.name}-home-action`,\n type: \"custom\",\n domain: \"\",\n context: \"\",\n customComponent: `/admin/core/${module?.name}/home`,\n customIsModal: true,\n serverEndpoint: \"\",\n viewUserKey: \"\",\n moduleUserKey: module?.name,\n modelUserKey: \"\"\n }\n ],\n menus: [\n {\n displayName: \"Home\",\n name: `${module?.name}-home-menu`,\n sequenceNumber: 1,\n actionUserKey: `${module?.name}-home-action`,\n moduleUserKey: module?.name,\n parentMenuItemUserKey: \"\",\n iconName: \"home\"\n }\n ],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n securityRules: [],\n };\n\n // Convert the object to JSON string\n const metadataJson = JSON.stringify(moduleMetaDataJson, null, 2);\n\n // Create the folder path inside 'module-metadata'\n const folderPath = path.resolve(process.cwd(), 'module-metadata', module.name);\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Ensure the folder exists\n await fs.mkdir(folderPath, { recursive: true });\n\n // Write the JSON to the file\n await fs.writeFile(filePath, metadataJson);\n\n } catch (error: any) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error(ERROR_MESSAGES.FILE_WRITE_FAILED); // Trigger rollback\n }\n }\n\n async update(id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.updateInDB(manager, id, updateModuleMetadataDto, files);\n await this.updateInFile(module);\n return module\n });\n } catch (error: any) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n\n async updateInDB(manager: EntityManager, id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n\n const module = await this.moduleMetadataRepo.preload({\n id,\n ...updateModuleMetadataDto,\n });\n\n if (!module) {\n throw new NotFoundException(ERROR_MESSAGES.MODULE_ID_NOT_FOUND(id));\n }\n if (files.length > 0) {\n\n const fileStoragePath = this.getFullFilePathForDisk(this.getFileName(files[0]));\n this.fileService.copy(files[0].path, fileStoragePath);\n this.fileService.delete(files[0].path);\n module.menuIconUrl = fileStoragePath;\n }\n return manager.save(ModuleMetadata, module);\n }\n\n async updateInFile(module: ModuleMetadata) {\n try {\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Read the existing JSON file\n let metaData;\n try {\n metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);\n\n } catch (error: any) {\n metaData = {\n moduleMetadata: {\n name: null,\n displayName: null,\n description: null,\n defaultDataSource: null,\n menuIconUrl: null,\n menuSequenceNumber: null,\n isSystem: null,\n models: [],\n },\n roles: [],\n users: [],\n actions: [],\n menus: [],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n };\n }\n\n metaData.moduleMetadata.name = module?.name;\n metaData.moduleMetadata.displayName = module?.displayName;\n metaData.moduleMetadata.description = module?.description;\n metaData.moduleMetadata.defaultDataSource = module?.defaultDataSource;\n metaData.moduleMetadata.menuIconUrl = module?.menuIconUrl;\n metaData.moduleMetadata.menuSequenceNumber = module?.menuSequenceNumber;\n metaData.moduleMetadata.isSystem = module?.isSystem;\n\n // Write the JSON to the file\n const updatedContent = JSON.stringify(metaData, null, 2);\n await fs.writeFile(filePath, updatedContent);\n\n } catch (error: any) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error(ERROR_MESSAGES.FILE_WRITE_FAILED); // Trigger rollback\n }\n }\n\n async upsert(updateModuleMetadataDto: UpdateModuleMetadataDto) {\n this.logger.debug(`Module Upsert called for : ${updateModuleMetadataDto.name}`);\n // First check if module already exists using name\n const existingModuleMetadata = await this.moduleMetadataRepo.findOne({\n where: {\n name: updateModuleMetadataDto.name\n }\n })\n const { models, ...restUpdateModuleMetadataDto } = updateModuleMetadataDto;\n // if found\n if (existingModuleMetadata) {\n const updatedModuleMetadata = { ...existingModuleMetadata, ...restUpdateModuleMetadataDto };\n return this.moduleMetadataRepo.save(updatedModuleMetadata);\n }\n // if not found - create new \n else {\n const moduleMetadata = this.moduleMetadataRepo.create(restUpdateModuleMetadataDto);\n return this.moduleMetadataRepo.save(moduleMetadata);\n }\n }\n\n async removeByName(name: string) {\n const entity = await this.findOneByUserKey(name);\n if (entity) {\n await this.moduleMetadataRepo.remove(entity);\n }\n }\n\n @DisallowInProduction()\n async remove(id: number) {\n const entity = await this.findOne(id);\n await this.cleanupOnDelete(entity.id);\n const r = await this.moduleMetadataRepo.remove(entity);\n return r\n }\n\n async cleanupOnDelete(moduleEntityId: number) {\n const moduleEntity = await this.moduleMetadataRepo.findOne({\n where: {\n // @ts-ignore\n id: moduleEntityId,\n }\n });\n\n if (!moduleEntity) {\n this.logger.log(`Invalid moduleEntityId: ${moduleEntityId} unable to resolve model metadata`);\n return;\n }\n if (moduleEntity.id !== moduleEntityId) {\n this.logger.log(`Invalid moduleEntityId: ${moduleEntityId} unable to resolve model metadata id ${moduleEntity.id} not matching with the one passed as argument ${moduleEntityId}`);\n return;\n }\n\n this.logger.log(`Cleaning up for module: ${moduleEntity.name}.`);\n\n const modulePath = await this.moduleMetadataHelperService.getModulePath(moduleEntity.name);\n if (modulePath) {\n\n this.logger.log(`Module path: ${modulePath}`);\n\n // Metadata file to be deleted\n const moduleMetadataPAth = await this.moduleMetadataHelperService.getModuleMetadataFolderPath(moduleEntity.name)\n this.logger.log(`About to delete module metadata path: ${moduleMetadataPAth}`);\n\n try {\n await fs.rm(modulePath, { recursive: true, force: true });\n await fs.rm(moduleMetadataPAth, { recursive: true, force: true });\n this.logger.log(`Deleted file: ${moduleMetadataPAth}`);\n } catch (error: any) {\n this.logger.error(`Error deleting file: ${moduleMetadataPAth}`, error);\n throw new Error(ERROR_MESSAGES.FILE_DELETE_FAILED); // Trigger rollback\n }\n }\n await this.dataSource.query(\n `CALL cleanup_module_metadata($1, $2)`,\n [moduleEntity.name, true],\n );\n }\n\n async deleteMany(ids: number[]): Promise<any> {\n if (!ids || ids.length === 0) {\n throw new Error(ERROR_MESSAGES.DELETE_IDS_REQUIRED);\n }\n const removedEntities = [];\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n //@ts-ignore\n id: id,\n }\n });\n // if (!entity) {\n // throw new Error(`Entity with id ${id} not found`);\n // }\n removedEntities.push(await this.moduleMetadataRepo.remove(entity));\n }\n\n return removedEntities\n }\n\n async refreshPermission() {\n await this.permissionsSeederService.seed();\n return true\n }\n\n @DisallowInProduction()\n async generateCode(options: CodeGenerationOptions): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException(ERROR_MESSAGES.MODEL_REQUIRED_FOR_CODE_GENERATION);\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n // Check if the module exists\n if (!module) {\n throw new NotFoundException(ERROR_MESSAGES.MODULE_ID_NOT_FOUND(options.moduleId));\n }\n\n // Check if the module name already exists and is loaded\n const moduleInstance = this.solidRegistry.getModule(`${classify(module.name)}Module`);\n\n if (!moduleInstance) {\n const addModuleOutput = await this.generateAddModuleCode(options);\n const refreshModuleOutput = await this.generateRefreshModuleCode(options);\n return `${addModuleOutput}\\n${refreshModuleOutput}`;\n } else {\n return await this.generateRefreshModuleCode(options);\n }\n }\n\n private async generateAddModuleCode(options: CodeGenerationOptions = { dryRun: false }): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException(ERROR_MESSAGES.MODEL_REQUIRED_FOR_CODE_GENERATION);\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n //Generate the module\n const output = await this.schematicService.executeSchematicCommand(\n ADD_MODULE_COMMAND,\n { module: module.name },\n options.dryRun ?? false\n );\n this.logger.debug(`Schematic output : ${output}`);\n return output;\n }\n\n private async generateRefreshModuleCode(options: CodeGenerationOptions): Promise<string> {\n const query = {\n relations: { models: { fields: true } },\n };\n const module = options.moduleId ? await this.findOne(options.moduleId, query.relations) : await this.findOneByUserKey(options.moduleUserKey, query.relations);\n const outputLines = []\n for (const model of module.models) {\n const codeGenerationOptions = {\n modelId: model.id,\n dryRun: options.dryRun,\n };\n const output = await this.modelMetadataService.handleGenerateCode(codeGenerationOptions);\n this.logger.debug(`Schematic output : ${output}`);\n outputLines.push(output)\n }\n return outputLines.join('\\n');\n }\n\n private getFullFilePathForDisk(fileName: string): string {\n const base = this.settingService.getConfigValue<SolidCoreSetting>(\"fileStorageDir\")\n || DEFAULT_MEDIA_FILE_STORAGE_DIR;\n if (path.isAbsolute(fileName) || fileName.startsWith(`${base}/`)) {\n return fileName;\n }\n return `${base}/${fileName}`;\n }\n\n private getFileName(file: Express.Multer.File): string {\n return `${file.filename}-${file.originalname}`;\n }\n\n}\n"]}
@@ -9,9 +9,9 @@ class DatabasePublisher {
9
9
  this.mqMessageService = mqMessageService;
10
10
  this.mqMessageQueueService = mqMessageQueueService;
11
11
  this.logger = new common_1.Logger(DatabasePublisher.name);
12
- this.serviceRole = process.env.QUEUES_SERVICE_ROLE;
13
- if (!this.serviceRole) {
14
- this.logger.debug('Queue service Role is not defined in the environment variables');
12
+ this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';
13
+ if (!process.env.QUEUES_SERVICE_ROLE) {
14
+ this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting DatabasePublisher service role to "both".');
15
15
  }
16
16
  }
17
17
  async publish(message) {
@@ -1 +1 @@
1
- {"version":3,"file":"database-publisher.service.js","sourceRoot":"","sources":["../../../src/services/queues/database-publisher.service.ts"],"names":[],"mappings":";;;AAAA,2CAAwC;AACxC,+BAAoC;AAKpC,qCAAoD;AAEpD,MAAsB,iBAAiB;IAKnC,YACuB,gBAAkC,EAClC,qBAA4C;QAD5C,qBAAgB,GAAhB,gBAA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AAC,iBAAiB,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;QAG3D,OAAO,OAAO,CAAC,SAAS,CAAC;IAC7B,CAAC;IAEO,KAAK,CAAC,iBAAiB,CAAC,SAAiB,EAAE,OAAwB;QAEvE,IAAI,CAAC;YAED,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;YAGhF,MAAM,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;gBAC/B,aAAa,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,IAAI;gBAClC,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,UAAU,EAAE,OAAO,CAAC,UAAU;gBAC9B,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,KAAK,EAAE,SAAS;gBAChB,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;gBACvC,cAAc,EAAE,OAAO,CAAC,cAAc;gBACtC,YAAY,EAAE,OAAO,CAAC,YAAY;gBAClC,gBAAgB,EAAE,cAAc,CAAC,EAAE;aACtC,CAAC,CAAC;QACP,CAAC;QACD,OAAO,KAAK,EAAE,CAAC;YACX,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;IAEL,CAAC;CACJ;AAzED,8CAyEC","sourcesContent":["import { Logger } from '@nestjs/common';\nimport { v4 as uuidv4 } from 'uuid';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueuePublisher } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { buildNamespacedQueueName } from './common';\n\nexport abstract class DatabasePublisher<T> implements QueuePublisher<T> {\n private readonly logger = new Logger(DatabasePublisher.name);\n private readonly url: string;\n private readonly serviceRole: string;\n\n constructor(\n protected readonly mqMessageService: MqMessageService,\n protected readonly mqMessageQueueService: MqMessageQueueService,\n ) {\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE;\n if (!this.serviceRole) {\n this.logger.debug('Queue service Role is not defined in the environment variables');\n }\n // this.logger.debug(`DatabasePublisher instance created with options: ${JSON.stringify(this.options())}`);\n }\n\n abstract options(): QueuesModuleOptions;\n\n async publish(message: QueueMessage<T>): Promise<string> {\n if (!this.serviceRole) {\n this.logger.error('Queue service Role is not defined in the environment variables');\n throw new Error('Queue service Role is not defined in the environment variables');\n }\n if (this.serviceRole === 'subscriber') {\n this.logger.error('Queue service Role is subscriber, cannot publish messages');\n throw new Error('Queue service Role is subscriber, cannot publish messages');\n }\n\n this.logger.debug(`DatabasePublisher publishing with options: ${JSON.stringify(this.options())}`);\n\n const options = this.options();\n\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n\n // generate a new message id \n message.messageId = uuidv4();\n\n // Save the message to the DB so that we can then change its status in the subscriber...\n await this.persistToDatabase(namespacedQueueName, message);\n\n // return the newly created message id.\n return message.messageId;\n }\n\n private async persistToDatabase(queueName: string, message: QueueMessage<T>) {\n // make an entry in the relevant database table, generate a unique id earlier.\n try {\n // 1. resolve the queue first\n const mqMessageQueue = await this.mqMessageQueueService.resolveQueue(queueName);\n\n // 2. Next create an entry in the mqMessage table. \n await this.mqMessageService.create({\n messageBroker: this.options().type,\n messageId: message.messageId,\n retryCount: message.retryCount,\n retryInterval: message.retryInterval,\n stage: 'pending',\n startedAt: new Date(),\n input: JSON.stringify(message, null, 2),\n parentEntityId: message.parentEntityId,\n parentEntity: message.parentEntity,\n mqMessageQueueId: mqMessageQueue.id,\n });\n }\n catch (error) {\n this.logger.error(error.message, error.stack);\n }\n\n }\n}\n"]}
1
+ {"version":3,"file":"database-publisher.service.js","sourceRoot":"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";\nimport { QueueMessage, QueuePublisher } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { buildNamespacedQueueName } from './common';\n\nexport abstract class DatabasePublisher<T> implements QueuePublisher<T> {\n private readonly logger = new Logger(DatabasePublisher.name);\n private readonly url: string;\n private readonly serviceRole: string;\n\n constructor(\n protected readonly mqMessageService: MqMessageService,\n protected readonly mqMessageQueueService: MqMessageQueueService,\n ) {\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';\n if (!process.env.QUEUES_SERVICE_ROLE) {\n this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting DatabasePublisher service role to \"both\".');\n }\n // this.logger.debug(`DatabasePublisher instance created with options: ${JSON.stringify(this.options())}`);\n }\n\n abstract options(): QueuesModuleOptions;\n\n async publish(message: QueueMessage<T>): Promise<string> {\n if (!this.serviceRole) {\n this.logger.error('Queue service Role is not defined in the environment variables');\n throw new Error('Queue service Role is not defined in the environment variables');\n }\n if (this.serviceRole === 'subscriber') {\n this.logger.error('Queue service Role is subscriber, cannot publish messages');\n throw new Error('Queue service Role is subscriber, cannot publish messages');\n }\n\n this.logger.debug(`DatabasePublisher publishing with options: ${JSON.stringify(this.options())}`);\n\n const options = this.options();\n\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n\n // generate a new message id \n message.messageId = uuidv4();\n\n // Save the message to the DB so that we can then change its status in the subscriber...\n await this.persistToDatabase(namespacedQueueName, message);\n\n // return the newly created message id.\n return message.messageId;\n }\n\n private async persistToDatabase(queueName: string, message: QueueMessage<T>) {\n // make an entry in the relevant database table, generate a unique id earlier.\n try {\n // 1. resolve the queue first\n const mqMessageQueue = await this.mqMessageQueueService.resolveQueue(queueName);\n\n // 2. Next create an entry in the mqMessage table. \n await this.mqMessageService.create({\n messageBroker: this.options().type,\n messageId: message.messageId,\n retryCount: message.retryCount,\n retryInterval: message.retryInterval,\n stage: 'pending',\n startedAt: new Date(),\n input: JSON.stringify(message, null, 2),\n parentEntityId: message.parentEntityId,\n parentEntity: message.parentEntity,\n mqMessageQueueId: mqMessageQueue.id,\n });\n }\n catch (error: any) {\n this.logger.error(error.message, error.stack);\n }\n\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"database-subscriber.service.js","sourceRoot":"","sources":["../../../src/services/queues/database-subscriber.service.ts"],"names":[],"mappings":";;;AAAA,2CAAsD;AAMtD,qCAAoD;AAEpD,MAAsB,kBAAkB;IAKpC,YACuB,gBAAkC,EAClC,qBAA4C,EAC5C,MAAqB;QAFrB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,0BAAqB,GAArB,qBAAqB,CAAuB;QAC5C,WAAM,GAAN,MAAM,CAAe;QAExC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,MAAM,CAAC;QAC7D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2FAA2F,CAAC,CAAC;QACnH,CAAC;IAEL,CAAC;IAED,IAAc,aAAa;QACvB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACjC,CAAC;IAED,IAAc,MAAM;QAChB,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YACxB,IAAI,CAAC,eAAe,GAAG,IAAI,eAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAMO,KAAK,CAAC,WAAW,CAAC,SAAiB;QAEvC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,SAAS,CAAC,CAAC;QAC1E,IAAI,CAAC,GAAG,EAAE,CAAC;YACP,OAAO;QACX,CAAC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esContent":["import { Logger, OnModuleInit } from '@nestjs/common';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueueSubscriber } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { PollerService } from '../poller.service';\nimport { buildNamespacedQueueName } from './common';\n\nexport abstract class DatabaseSubscriber<T> implements OnModuleInit, QueueSubscriber<T> {\n private _loggerInstance?: Logger;\n private readonly url: string;\n private readonly serviceRole: string;\n\n constructor(\n protected readonly mqMessageService: MqMessageService,\n protected readonly mqMessageQueueService: MqMessageQueueService,\n protected readonly poller: PollerService,\n ) {\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';\n if (!process.env.QUEUES_SERVICE_ROLE) {\n this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting DatabaseSubscriber service role to \"both\".');\n }\n // this.logger.debug(`DatabaseSubscriber instance created with options: ${JSON.stringify(this.options())}`);\n }\n\n protected get loggerContext(): string {\n return this.constructor.name;\n }\n\n protected get logger(): Logger {\n if (!this._loggerInstance) {\n this._loggerInstance = new Logger(this.loggerContext);\n }\n return this._loggerInstance;\n }\n\n abstract subscribe(message: QueueMessage<T>): Promise<any>;\n\n abstract options(): QueuesModuleOptions;\n\n private async processNext(queueName: string) {\n // this.logger.debug(`#### DatabaseSubscriber processing next message from queue: ${queueName}`);\n const job = await this.mqMessageService.lockNextPendingMessage(queueName);\n if (!job) {\n return;\n }\n\n const messageContentString = job.input.toString();\n // this.logger.debug(`DatabaseSubscriber Received raw message: ${messageContentString}`);\n\n let message: QueueMessage<T> = null;\n\n try {\n message = JSON.parse(messageContentString) as QueueMessage<T>;\n\n // this is the first time we are receiving the message so we set the currentRetry to 0\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n if (!message.currentRetry) message.currentRetry = 0;\n\n await this.processMessage(message);\n }\n catch (error: any) {\n this.logger.error(`Error processing message: ${error.message}`);\n\n // if an error occurs then if retryCount is set we start retrying. \n if (message) {\n if (message.currentRetry < message.retryCount) {\n await this.updateStatusInDatabase('retrying', message);\n\n message.currentRetry++;\n this.logger.warn(`Retrying message (${message.currentRetry}/${message.retryCount}) after ${message.retryInterval}ms`);\n setTimeout(() => {\n this.retryMessage(message);\n }, message.retryInterval);\n } else {\n // Discard the message after max retries\n await this.updateStatusInDatabase('failed', message, error.message, '');\n this.logger.error(`Message failed after ${message.retryCount} attempts: ${error.message}`);\n }\n }\n }\n // this.logger.debug(`#### DatabaseSubscriber finished processing message from queue: ${queueName}`);\n }\n\n async onModuleInit(): Promise<void> {\n // Not using SettingService here as that will necessitate all implementors of DatabaseSubscriber to also inject SettingService which is not ideal. \n // Instead we directly read the environment variables here.\n const defaultBroker = process.env.QUEUES_DEFAULT_BROKER || 'database';\n const solidCliRunning = process.env.SOLID_CLI_RUNNING || \"false\";\n const queueNameRegex = (process.env.QUEUES_QUEUE_NAME_REGEX_TO_ENABLE || '').trim();\n const roleAllowed = ['both', 'subscriber'].includes(this.serviceRole);\n\n if (!roleAllowed) {\n this.logger.log(`DatabaseSubscriber is disabled because QUEUES_SERVICE_ROLE is \"${this.serviceRole}\". Expected \"both\" or \"subscriber\".`);\n return;\n }\n\n // we will start subscriber only if the current service role is subscriber. \n if (defaultBroker === 'database' && solidCliRunning === \"false\") {\n const options = this.options();\n const queueName = options.queueName;\n\n if (queueNameRegex && queueNameRegex !== \"all\") {\n try {\n const regex = new RegExp(queueNameRegex);\n if (!regex.test(queueName)) {\n this.logger.log(`DatabaseSubscriber for queue ${queueName} is disabled because it does not match QUEUES_QUEUE_NAME_REGEX_TO_ENABLE=${queueNameRegex}`);\n return;\n }\n } catch (error) {\n this.logger.error(`Invalid QUEUES_QUEUE_NAME_REGEX_TO_ENABLE regex \"${queueNameRegex}\". Subscriber for queue ${queueName} will not start.`);\n return;\n }\n }\n\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n this.poller.start(namespacedQueueName, (q) => this.processNext(q), {\n baseDelayMs: 1000,\n maxDelayMs: 30_000,\n timeoutPerIterationMs: 5 * 60_000,\n jitter: true,\n });\n\n this.logger.log(`DatabaseSubscriber ready to consume messages: ${JSON.stringify(this.options())}`);\n }\n }\n\n onModuleDestroy() {\n const options = this.options();\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n this.poller.stop(namespacedQueueName);\n }\n\n /**\n * Abstract method for message processing logic.\n */\n protected async processMessage(message: QueueMessage<T>): Promise<void> {\n await this.updateStatusInDatabase('started', message);\n\n // Capture the results of handling the task.\n const result = await this.subscribe(message);\n\n // TODO: Update the database to indicate that the task is finished.\n await this.updateStatusInDatabase('succeeded', message, '', result ? JSON.stringify(result, null, 2) : '');\n }\n\n /**\n * Retry the message by invoking the processing logic again.\n */\n private async retryMessage(message: QueueMessage<T>) {\n try {\n await this.processMessage(message);\n } catch (error: any) {\n if (message.currentRetry < message.retryCount) {\n await this.updateStatusInDatabase('retrying', message);\n\n message.currentRetry++;\n this.logger.warn(`Retrying message (${message.currentRetry}/${message.retryCount}) after ${message.retryInterval}ms: ${error.message}`);\n setTimeout(() => {\n this.retryMessage(message);\n }, message.retryInterval);\n } else {\n this.logger.error(`Message failed after ${message.retryCount} attempts: ${error.message}`);\n\n // TODO: Store the error in the database and update the status accordingly.\n await this.updateStatusInDatabase('failed', message, error.message, '');\n\n }\n }\n }\n\n private async updateStatusInDatabase(stage: string, message: QueueMessage<T>, error: string = '', result: string = '') {\n try {\n this.logger.debug(`Updating message status in database: ${stage} for messageId: ${message.messageId}`);\n\n // 1. resolve the queue first\n const mqMessage = await this.mqMessageService.repo.findOne({\n where: {\n messageId: message.messageId,\n }\n });\n\n if (mqMessage) {\n this.logger.debug(`Found message in database: ${JSON.stringify(mqMessage.messageId)}`);\n this.logger.debug(`Updating message status in database: ${stage} for messageId: ${mqMessage.id}`);\n\n const updatedFields = {\n stage: stage\n };\n if (stage === 'failed' || stage === 'succeeded') {\n updatedFields['finishedAt'] = new Date();\n updatedFields['elapsedMillis'] = updatedFields['finishedAt'].getTime() - mqMessage.startedAt.getTime();\n }\n if (stage === 'succeeded') {\n updatedFields['output'] = result;\n }\n if (stage === 'failed') {\n updatedFields['error'] = error;\n }\n await this.mqMessageService.repo.update(mqMessage.id, updatedFields);\n this.logger.debug(`Message status updated to ${stage} for messageId: ${mqMessage.id}`);\n }\n }\n catch (error: any) {\n this.logger.error(error.message, error.stack);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"database-subscriber.service.js","sourceRoot":"","sources":["../../../src/services/queues/database-subscriber.service.ts"],"names":[],"mappings":";;;AAAA,2CAAsD;AAMtD,qCAAoD;AAEpD,MAAsB,kBAAkB;IAKpC,YACuB,gBAAkC,EAClC,qBAA4C,EAC5C,MAAqB;QAFrB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,0BAAqB,GAArB,qBAAqB,CAAuB;QAC5C,WAAM,GAAN,MAAM,CAAe;QAExC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,MAAM,CAAC;QAC7D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2FAA2F,CAAC,CAAC;QACnH,CAAC;IAEL,CAAC;IAED,IAAc,aAAa;QACvB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACjC,CAAC;IAED,IAAc,MAAM;QAChB,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YACxB,IAAI,CAAC,eAAe,GAAG,IAAI,eAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAMO,KAAK,CAAC,WAAW,CAAC,SAAiB;QAEvC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,SAAS,CAAC,CAAC;QAC1E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AAC;QAClD,CAAC;IACL,CAAC;CACJ;AAzMD,gDAyMC","sourcesContent":["import { Logger, OnModuleInit } from '@nestjs/common';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueueSubscriber } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { PollerService } from '../poller.service';\nimport { buildNamespacedQueueName } from './common';\n\nexport abstract class DatabaseSubscriber<T> implements OnModuleInit, QueueSubscriber<T> {\n private _loggerInstance?: Logger;\n private readonly url: string;\n private readonly serviceRole: string;\n\n constructor(\n protected readonly mqMessageService: MqMessageService,\n protected readonly mqMessageQueueService: MqMessageQueueService,\n protected readonly poller: PollerService,\n ) {\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';\n if (!process.env.QUEUES_SERVICE_ROLE) {\n this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting DatabaseSubscriber service role to \"both\".');\n }\n // this.logger.debug(`DatabaseSubscriber instance created with options: ${JSON.stringify(this.options())}`);\n }\n\n protected get loggerContext(): string {\n return this.constructor.name;\n }\n\n protected get logger(): Logger {\n if (!this._loggerInstance) {\n this._loggerInstance = new Logger(this.loggerContext);\n }\n return this._loggerInstance;\n }\n\n abstract subscribe(message: QueueMessage<T>): Promise<any>;\n\n abstract options(): QueuesModuleOptions;\n\n private async processNext(queueName: string) {\n // this.logger.debug(`#### DatabaseSubscriber processing next message from queue: ${queueName}`);\n const job = await this.mqMessageService.lockNextPendingMessage(queueName);\n if (!job) {\n return;\n }\n\n const messageContentString = job.input.toString();\n // this.logger.debug(`DatabaseSubscriber Received raw message: ${messageContentString}`);\n\n let message: QueueMessage<T> = null;\n\n try {\n message = JSON.parse(messageContentString) as QueueMessage<T>;\n\n // this is the first time we are receiving the message so we set the currentRetry to 0\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n if (!message.currentRetry) message.currentRetry = 0;\n\n await this.processMessage(message);\n }\n catch (error: any) {\n this.logger.error(`Error processing message: ${error.message}`);\n\n // if an error occurs then if retryCount is set we start retrying. \n if (message) {\n if (message.currentRetry < message.retryCount) {\n await this.updateStatusInDatabase('retrying', message);\n\n message.currentRetry++;\n this.logger.warn(`Retrying message (${message.currentRetry}/${message.retryCount}) after ${message.retryInterval}ms`);\n setTimeout(() => {\n this.retryMessage(message);\n }, message.retryInterval);\n } else {\n // Discard the message after max retries\n await this.updateStatusInDatabase('failed', message, error.message, '');\n this.logger.error(`Message failed after ${message.retryCount} attempts: ${error.message}`);\n }\n }\n }\n // this.logger.debug(`#### DatabaseSubscriber finished processing message from queue: ${queueName}`);\n }\n\n async onModuleInit(): Promise<void> {\n // Not using SettingService here as that will necessitate all implementors of DatabaseSubscriber to also inject SettingService which is not ideal. \n // Instead we directly read the environment variables here.\n const defaultBroker = process.env.QUEUES_DEFAULT_BROKER || 'database';\n const solidCliRunning = process.env.SOLID_CLI_RUNNING || \"false\";\n const queueNameRegex = (process.env.QUEUES_QUEUE_NAME_REGEX_TO_ENABLE || '').trim();\n const roleAllowed = ['both', 'subscriber'].includes(this.serviceRole);\n\n if (!roleAllowed) {\n this.logger.log(`DatabaseSubscriber is disabled because QUEUES_SERVICE_ROLE is \"${this.serviceRole}\". Expected \"both\" or \"subscriber\".`);\n return;\n }\n\n // we will start subscriber only if the current service role is subscriber. \n if (defaultBroker === 'database' && solidCliRunning === \"false\") {\n const options = this.options();\n const queueName = options.queueName;\n\n if (queueNameRegex && queueNameRegex !== \"all\") {\n try {\n const regex = new RegExp(queueNameRegex);\n if (!regex.test(queueName)) {\n this.logger.log(`DatabaseSubscriber for queue ${queueName} is disabled because it does not match QUEUES_QUEUE_NAME_REGEX_TO_ENABLE=${queueNameRegex}`);\n return;\n }\n } catch (error: any) {\n this.logger.error(`Invalid QUEUES_QUEUE_NAME_REGEX_TO_ENABLE regex \"${queueNameRegex}\". Subscriber for queue ${queueName} will not start.`);\n return;\n }\n }\n\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n this.poller.start(namespacedQueueName, (q) => this.processNext(q), {\n baseDelayMs: 1000,\n maxDelayMs: 30_000,\n timeoutPerIterationMs: 5 * 60_000,\n jitter: true,\n });\n\n this.logger.log(`DatabaseSubscriber ready to consume messages: ${JSON.stringify(this.options())}`);\n }\n }\n\n onModuleDestroy() {\n const options = this.options();\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n this.poller.stop(namespacedQueueName);\n }\n\n /**\n * Abstract method for message processing logic.\n */\n protected async processMessage(message: QueueMessage<T>): Promise<void> {\n await this.updateStatusInDatabase('started', message);\n\n // Capture the results of handling the task.\n const result = await this.subscribe(message);\n\n // TODO: Update the database to indicate that the task is finished.\n await this.updateStatusInDatabase('succeeded', message, '', result ? JSON.stringify(result, null, 2) : '');\n }\n\n /**\n * Retry the message by invoking the processing logic again.\n */\n private async retryMessage(message: QueueMessage<T>) {\n try {\n await this.processMessage(message);\n } catch (error: any) {\n if (message.currentRetry < message.retryCount) {\n await this.updateStatusInDatabase('retrying', message);\n\n message.currentRetry++;\n this.logger.warn(`Retrying message (${message.currentRetry}/${message.retryCount}) after ${message.retryInterval}ms: ${error.message}`);\n setTimeout(() => {\n this.retryMessage(message);\n }, message.retryInterval);\n } else {\n this.logger.error(`Message failed after ${message.retryCount} attempts: ${error.message}`);\n\n // TODO: Store the error in the database and update the status accordingly.\n await this.updateStatusInDatabase('failed', message, error.message, '');\n\n }\n }\n }\n\n private async updateStatusInDatabase(stage: string, message: QueueMessage<T>, error: string = '', result: string = '') {\n try {\n this.logger.debug(`Updating message status in database: ${stage} for messageId: ${message.messageId}`);\n\n // 1. resolve the queue first\n const mqMessage = await this.mqMessageService.repo.findOne({\n where: {\n messageId: message.messageId,\n }\n });\n\n if (mqMessage) {\n this.logger.debug(`Found message in database: ${JSON.stringify(mqMessage.messageId)}`);\n this.logger.debug(`Updating message status in database: ${stage} for messageId: ${mqMessage.id}`);\n\n const updatedFields = {\n stage: stage\n };\n if (stage === 'failed' || stage === 'succeeded') {\n updatedFields['finishedAt'] = new Date();\n updatedFields['elapsedMillis'] = updatedFields['finishedAt'].getTime() - mqMessage.startedAt.getTime();\n }\n if (stage === 'succeeded') {\n updatedFields['output'] = result;\n }\n if (stage === 'failed') {\n updatedFields['error'] = error;\n }\n await this.mqMessageService.repo.update(mqMessage.id, updatedFields);\n this.logger.debug(`Message status updated to ${stage} for messageId: ${mqMessage.id}`);\n }\n }\n catch (error: any) {\n this.logger.error(error.message, error.stack);\n }\n }\n}\n"]}
@@ -47,12 +47,12 @@ class RabbitMqPublisher {
47
47
  this.channel = null;
48
48
  this.connectingPromise = null;
49
49
  this.url = process.env.QUEUES_RABBIT_MQ_URL;
50
- this.serviceRole = process.env.QUEUES_SERVICE_ROLE;
50
+ this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';
51
51
  if (!this.url) {
52
52
  this.logger.debug('RabbitMqPublisher url is not defined in the environment variables');
53
53
  }
54
- if (!this.serviceRole) {
55
- this.logger.debug('Queue service Role is not defined in the environment variables');
54
+ if (!process.env.QUEUES_SERVICE_ROLE) {
55
+ this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting RabbitMqPublisher service role to "both".');
56
56
  }
57
57
  }
58
58
  shouldPersistToDatabase() {
@@ -1 +1 @@
1
- {"version":3,"file":"rabbitmq-publisher.service.js","sourceRoot":"","sources":["../../../src/services/queues/rabbitmq-publisher.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAyD;AACzD,8CAAgC;AAChC,+BAAoC;AAKpC,qCAAoD;AAEpD,MAAsB,iBAAiB;IAUnC,YACuB,gBAAkC,EAClC,qBAA4C;QAD5C,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,0BAAqB,GAArB,qBAAqB,CAAuB;QAXlD,WAAM,GAAG,IAAI,eAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;QAKrD,eAAU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,IAAI,EAAE;gBACrB,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;gBACvC,cAAc,EAAE,OAAO,CAAC,cAAc;gBACtC,YAAY,EAAE,OAAO,CAAC,YAAY;gBAClC,gBAAgB,EAAE,cAAc,CAAC,EAAE;aACtC,CAAC,CAAC;QACP,CAAC;QACD,OAAO,KAAK,EAAE,CAAC;YACX,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;IAEL,CAAC;CACJ;AA9ND,8CA8NC","sourcesContent":["import { Logger, OnModuleDestroy } from '@nestjs/common';\nimport * as amqp from 'amqplib';\nimport { v4 as uuidv4 } from 'uuid';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueuePublisher } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { buildNamespacedQueueName } from './common';\n\nexport abstract class RabbitMqPublisher<T> implements OnModuleDestroy, QueuePublisher<T> {\n private readonly logger = new Logger(RabbitMqPublisher.name);\n private readonly url: string;\n private readonly serviceRole: string;\n\n // Maintain connection...\n private connection: amqp.Connection | null = null;\n private channel: amqp.Channel | null = null;\n private connectingPromise: Promise<void> | null = null;\n\n constructor(\n protected readonly mqMessageService: MqMessageService,\n protected readonly mqMessageQueueService: MqMessageQueueService,\n ) {\n this.url = process.env.QUEUES_RABBIT_MQ_URL;\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE;\n if (!this.url) {\n this.logger.debug('RabbitMqPublisher url is not defined in the environment variables');\n }\n if (!this.serviceRole) {\n this.logger.debug('Queue service Role is not defined in the environment variables');\n }\n // this.logger.debug(`RabbitMqPublisher instance created with options: ${JSON.stringify(this.options())} and url: ${this.url}`);\n }\n\n abstract options(): QueuesModuleOptions;\n\n protected shouldPersistToDatabase(): boolean {\n return this.options().persistToDatabase ?? true;\n }\n\n private async ensureConnectionAndChannel(): Promise<amqp.Channel> {\n if (this.channel) {\n return this.channel;\n }\n\n // If another call is already connecting, wait for it\n if (this.connectingPromise) {\n await this.connectingPromise;\n if (this.channel) return this.channel;\n }\n\n this.connectingPromise = (async () => {\n const url = new URL(this.url);\n\n const conn = await amqp.connect({\n protocol: url.protocol.replace(':', ''), // \"amqps\"\n hostname: url.hostname,\n port: parseInt(url.port),\n username: url.username,\n // Node's URL already decodes percent-encoding; decodeURIComponent is not needed\n // But without it does not seem to be working...\n password: decodeURIComponent(url.password),\n frameMax: 131072,\n });\n\n conn.on('error', (err) => {\n this.logger.error(`RabbitMQ connection error: ${err.message}`, err.stack);\n });\n\n conn.on('close', () => {\n this.logger.warn('RabbitMQ connection closed, resetting');\n this.connection = null;\n this.channel = null;\n });\n\n const channel = await conn.createChannel();\n\n channel.on('return', (msg) => {\n const content = msg.content?.toString?.() ?? '';\n this.logger.warn(\n `RabbitMqPublisher message returned from exchange ${msg.fields.exchange} with routingKey ${msg.fields.routingKey}: ${content}`,\n );\n });\n\n const options = this.options();\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n const exchangeName = `${namespacedQueueName}.exchange`;\n const routingKey = `${namespacedQueueName}.routing-key`;\n\n await channel.assertExchange(exchangeName, 'direct', {});\n const queue = await channel.assertQueue(namespacedQueueName, {});\n await channel.bindQueue(queue.queue, exchangeName, routingKey);\n\n this.connection = conn;\n this.channel = channel;\n })();\n\n try {\n await this.connectingPromise;\n } finally {\n this.connectingPromise = null;\n }\n\n if (!this.channel) {\n throw new Error('Failed to initialize RabbitMQ channel');\n }\n\n return this.channel;\n }\n\n // Nest will call this for every subclass instance, because they inherit the method\n async onModuleDestroy(): Promise<void> {\n await this.closeConnectionAndChannel();\n }\n\n private async closeConnectionAndChannel(): Promise<void> {\n if (this.channel) {\n try {\n await this.channel.close();\n } catch (err) {\n this.logger.warn(\n `RabbitMqPublisher error closing channel: ${(err as Error).message}`,\n );\n } finally {\n this.channel = null;\n }\n }\n\n if (this.connection) {\n try {\n await this.connection.close();\n } catch (err) {\n this.logger.warn(\n `RabbitMqPublisher error closing connection: ${(err as Error).message}`,\n );\n } finally {\n this.connection = null;\n }\n }\n }\n\n async publish(message: QueueMessage<T>): Promise<string> {\n if (!this.url) {\n this.logger.error('RabbitMqPublisher url is not defined in the environment variables');\n throw new Error('RabbitMqPublisher url is not defined in the environment variables');\n }\n if (!this.serviceRole) {\n this.logger.error('Queue service Role is not defined in the environment variables');\n throw new Error('Queue service Role is not defined in the environment variables');\n }\n if (this.serviceRole === 'subscriber') {\n this.logger.error('Queue service Role is subscriber, cannot publish messages');\n throw new Error('Queue service Role is subscriber, cannot publish messages');\n }\n\n const channel = await this.ensureConnectionAndChannel();\n // this.logger.debug(`RabbitMqPublisher publisher channel created options: ${JSON.stringify(this.options())} and url: ${url}`);\n\n const options = this.options();\n\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n\n const exchangeName = `${namespacedQueueName}.exchange`;\n const routingKey = `${namespacedQueueName}.routing-key`;\n\n // Set default values for retry. \n // by default there are no retries.\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n\n // generate a new message id \n message.messageId = uuidv4();\n\n // Save the message to the DB so that we can then change its status in the subscriber...\n if (this.shouldPersistToDatabase()) {\n await this.persistToDatabase(namespacedQueueName, message);\n }\n\n // wait for the channel to confirm \n try {\n // Publish the message\n // const publishStatus = channel.publish(exchangeName, routingKey, Buffer.from(JSON.stringify(message)));\n const publishStatus = channel.publish(exchangeName, routingKey, Buffer.from(JSON.stringify(message)), { mandatory: true });\n // this.logger.debug(`RabbitMqPublisher publish status: ${JSON.stringify(publishStatus)}`);\n // if (!publishStatus) {\n // this.logger.warn('RabbitMqPublisher Message buffering failed!');\n // }\n // await channel.waitForConfirms();\n // this.logger.debug('RabbitMqPublisher Message published successfully');\n } catch (err) {\n this.logger.error(`RabbitMqPublisher Message publish failed: ${JSON.stringify(err)}`);\n if (err instanceof Error) {\n this.logger.error(`RabbitMqPublisher Error stack: ${err.stack}`);\n }\n }\n finally {\n }\n // this.logger.debug(`Sent message: ${JSON.stringify(message)}`);\n\n // return the newly created message id.\n return message.messageId;\n }\n\n private async persistToDatabase(queueName: string, message: QueueMessage<T>) {\n\n // make an entry in the relevant database table, generate a unique id earlier.\n try {\n // 1. resolve the queue first\n const mqMessageQueue = await this.mqMessageQueueService.resolveQueue(queueName);\n\n // 2. Next create an entry in the mqMessage table. \n await this.mqMessageService.create({\n messageBroker: this.options().type,\n messageId: message.messageId,\n retryCount: message.retryCount,\n retryInterval: message.retryInterval,\n stage: 'pending',\n startedAt: new Date(),\n input: JSON.stringify(message, null, 2),\n parentEntityId: message.parentEntityId,\n parentEntity: message.parentEntity,\n mqMessageQueueId: mqMessageQueue.id,\n });\n }\n catch (error) {\n this.logger.error(error.message, error.stack);\n }\n\n }\n}\n"]}
1
+ {"version":3,"file":"rabbitmq-publisher.service.js","sourceRoot":"","sources":["../../../src/services/queues/rabbitmq-publisher.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAyD;AACzD,8CAAgC;AAChC,+BAAoC;AAKpC,qCAAoD;AAEpD,MAAsB,iBAAiB;IAUnC,YACuB,gBAAkC,EAClC,qBAA4C;QAD5C,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,0BAAqB,GAArB,qBAAqB,CAAuB;QAXlD,WAAM,GAAG,IAAI,eAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;QAKrD,eAAU,GAA2B,IAAI,CAAC;QAC1C,YAAO,GAAwB,IAAI,CAAC;QACpC,sBAAiB,GAAyB,IAAI,CAAC;QAMnD,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC;QAC5C,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,I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E,cAAc,CAAC,EAAE;aACtC,CAAC,CAAC;QACP,CAAC;QACD,OAAO,KAAU,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;IAEL,CAAC;CACJ;AA9ND,8CA8NC","sourcesContent":["import { Logger, OnModuleDestroy } from '@nestjs/common';\nimport * as amqp from 'amqplib';\nimport { v4 as uuidv4 } from 'uuid';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueuePublisher } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { buildNamespacedQueueName } from './common';\n\nexport abstract class RabbitMqPublisher<T> implements OnModuleDestroy, QueuePublisher<T> {\n private readonly logger = new Logger(RabbitMqPublisher.name);\n private readonly url: string;\n private readonly serviceRole: string;\n\n // Maintain connection...\n private connection: amqp.Connection | null = null;\n private channel: amqp.Channel | null = null;\n private connectingPromise: Promise<void> | null = null;\n\n constructor(\n protected readonly mqMessageService: MqMessageService,\n protected readonly mqMessageQueueService: MqMessageQueueService,\n ) {\n this.url = process.env.QUEUES_RABBIT_MQ_URL;\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';\n if (!this.url) {\n this.logger.debug('RabbitMqPublisher url is not defined in the environment variables');\n }\n if (!process.env.QUEUES_SERVICE_ROLE) {\n this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting RabbitMqPublisher service role to \"both\".');\n }\n // this.logger.debug(`RabbitMqPublisher instance created with options: ${JSON.stringify(this.options())} and url: ${this.url}`);\n }\n\n abstract options(): QueuesModuleOptions;\n\n protected shouldPersistToDatabase(): boolean {\n return this.options().persistToDatabase ?? true;\n }\n\n private async ensureConnectionAndChannel(): Promise<amqp.Channel> {\n if (this.channel) {\n return this.channel;\n }\n\n // If another call is already connecting, wait for it\n if (this.connectingPromise) {\n await this.connectingPromise;\n if (this.channel) return this.channel;\n }\n\n this.connectingPromise = (async () => {\n const url = new URL(this.url);\n\n const conn = await amqp.connect({\n protocol: url.protocol.replace(':', ''), // \"amqps\"\n hostname: url.hostname,\n port: parseInt(url.port),\n username: url.username,\n // Node's URL already decodes percent-encoding; decodeURIComponent is not needed\n // But without it does not seem to be working...\n password: decodeURIComponent(url.password),\n frameMax: 131072,\n });\n\n conn.on('error', (err) => {\n this.logger.error(`RabbitMQ connection error: ${err.message}`, err.stack);\n });\n\n conn.on('close', () => {\n this.logger.warn('RabbitMQ connection closed, resetting');\n this.connection = null;\n this.channel = null;\n });\n\n const channel = await conn.createChannel();\n\n channel.on('return', (msg) => {\n const content = msg.content?.toString?.() ?? '';\n this.logger.warn(\n `RabbitMqPublisher message returned from exchange ${msg.fields.exchange} with routingKey ${msg.fields.routingKey}: ${content}`,\n );\n });\n\n const options = this.options();\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n const exchangeName = `${namespacedQueueName}.exchange`;\n const routingKey = `${namespacedQueueName}.routing-key`;\n\n await channel.assertExchange(exchangeName, 'direct', {});\n const queue = await channel.assertQueue(namespacedQueueName, {});\n await channel.bindQueue(queue.queue, exchangeName, routingKey);\n\n this.connection = conn;\n this.channel = channel;\n })();\n\n try {\n await this.connectingPromise;\n } finally {\n this.connectingPromise = null;\n }\n\n if (!this.channel) {\n throw new Error('Failed to initialize RabbitMQ channel');\n }\n\n return this.channel;\n }\n\n // Nest will call this for every subclass instance, because they inherit the method\n async onModuleDestroy(): Promise<void> {\n await this.closeConnectionAndChannel();\n }\n\n private async closeConnectionAndChannel(): Promise<void> {\n if (this.channel) {\n try {\n await this.channel.close();\n } catch (err: any) {\n this.logger.warn(\n `RabbitMqPublisher error closing channel: ${(err as Error).message}`,\n );\n } finally {\n this.channel = null;\n }\n }\n\n if (this.connection) {\n try {\n await this.connection.close();\n } catch (err: any) {\n this.logger.warn(\n `RabbitMqPublisher error closing connection: ${(err as Error).message}`,\n );\n } finally {\n this.connection = null;\n }\n }\n }\n\n async publish(message: QueueMessage<T>): Promise<string> {\n if (!this.url) {\n this.logger.error('RabbitMqPublisher url is not defined in the environment variables');\n throw new Error('RabbitMqPublisher url is not defined in the environment variables');\n }\n if (!this.serviceRole) {\n this.logger.error('Queue service Role is not defined in the environment variables');\n throw new Error('Queue service Role is not defined in the environment variables');\n }\n if (this.serviceRole === 'subscriber') {\n this.logger.error('Queue service Role is subscriber, cannot publish messages');\n throw new Error('Queue service Role is subscriber, cannot publish messages');\n }\n\n const channel = await this.ensureConnectionAndChannel();\n // this.logger.debug(`RabbitMqPublisher publisher channel created options: ${JSON.stringify(this.options())} and url: ${url}`);\n\n const options = this.options();\n\n const queueName = options.queueName;\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n\n const exchangeName = `${namespacedQueueName}.exchange`;\n const routingKey = `${namespacedQueueName}.routing-key`;\n\n // Set default values for retry. \n // by default there are no retries.\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n\n // generate a new message id \n message.messageId = uuidv4();\n\n // Save the message to the DB so that we can then change its status in the subscriber...\n if (this.shouldPersistToDatabase()) {\n await this.persistToDatabase(namespacedQueueName, message);\n }\n\n // wait for the channel to confirm \n try {\n // Publish the message\n // const publishStatus = channel.publish(exchangeName, routingKey, Buffer.from(JSON.stringify(message)));\n const publishStatus = channel.publish(exchangeName, routingKey, Buffer.from(JSON.stringify(message)), { mandatory: true });\n // this.logger.debug(`RabbitMqPublisher publish status: ${JSON.stringify(publishStatus)}`);\n // if (!publishStatus) {\n // this.logger.warn('RabbitMqPublisher Message buffering failed!');\n // }\n // await channel.waitForConfirms();\n // this.logger.debug('RabbitMqPublisher Message published successfully');\n } catch (err: any) {\n this.logger.error(`RabbitMqPublisher Message publish failed: ${JSON.stringify(err)}`);\n if (err instanceof Error) {\n this.logger.error(`RabbitMqPublisher Error stack: ${err.stack}`);\n }\n }\n finally {\n }\n // this.logger.debug(`Sent message: ${JSON.stringify(message)}`);\n\n // return the newly created message id.\n return message.messageId;\n }\n\n private async persistToDatabase(queueName: string, message: QueueMessage<T>) {\n\n // make an entry in the relevant database table, generate a unique id earlier.\n try {\n // 1. resolve the queue first\n const mqMessageQueue = await this.mqMessageQueueService.resolveQueue(queueName);\n\n // 2. Next create an entry in the mqMessage table. \n await this.mqMessageService.create({\n messageBroker: this.options().type,\n messageId: message.messageId,\n retryCount: message.retryCount,\n retryInterval: message.retryInterval,\n stage: 'pending',\n startedAt: new Date(),\n input: JSON.stringify(message, null, 2),\n parentEntityId: message.parentEntityId,\n parentEntity: message.parentEntity,\n mqMessageQueueId: mqMessageQueue.id,\n });\n }\n catch (error: any) {\n this.logger.error(error.message, error.stack);\n }\n\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"rabbitmq-subscriber.service.js","sourceRoot":"","sources":["../../../src/services/queues/rabbitmq-subscriber.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAsD;AACtD,8CAAgC;AAKhC,qCAAoD;AAEpD,MAAM,8BAA+B,SAAQ,KAAK;IAC9C,YACa,SAAiB,EACjB,SAAiB,EACjB,SAAiB;QAE1B,KAAK,CAAC,yCAAyC,SAAS,gBAAgB,SAAS,kBAAkB,SAAS,EAAE,CAAC,CAAC;QAJvG,cAAS,GAAT,SAAS,CAAQ;QACjB,cAAS,GAAT,SAAS,CAAQ;QACjB,cAAS,GAAT,SAAS,CAAQ;QAG1B,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;IACjD,CAAC;CACJ;AAGD,MAAsB,kBAAkB;IAWpC,YAA+B,gBAAkC,EAAqB,qBAA4C;QAAnG,qBAAgB,GAAhB,gBAAgB,CAAkB;QAAqB,0BAAqB,GAArB,qBAAqB,CAAuB;QAP1H,eAAU,GAA2B,IAAI,CAAC;QAC1C,YAAO,GAAwB,IAAI,CAAC;QACpC,gBAAW,GAAkB,IAAI,CAAC;QACl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AC,aAAa,CAAC,CAAC;YAChC,CAAC;QACL,CAAC;IACL,CAAC;CAEJ;AAleD,gDAkeC","sourcesContent":["import { Logger, OnModuleInit } from '@nestjs/common';\nimport * as amqp from 'amqplib';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueueSubscriber } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { buildNamespacedQueueName } from './common';\n\nclass ConsumerProcessingTimeoutError extends Error {\n constructor(\n readonly queueName: string,\n readonly messageId: string,\n readonly timeoutMs: number,\n ) {\n super(`Subscriber processing timed out after ${timeoutMs}ms for queue ${queueName} and messageId ${messageId}`);\n this.name = 'ConsumerProcessingTimeoutError';\n }\n}\n\n\nexport abstract class RabbitMqSubscriber<T> implements OnModuleInit, QueueSubscriber<T> { // TODO This can be made a generic type for better type visibility\n private _loggerInstance?: Logger;\n private readonly url: string;\n private readonly serviceRole: string;\n private connection: amqp.Connection | null = null;\n private channel: amqp.Channel | null = null;\n private consumerTag: string | null = null;\n private reconnectPromise: Promise<void> | null = null;\n private reconnectAttempt = 0;\n private stopping = false;\n\n constructor(protected readonly mqMessageService: MqMessageService, protected readonly mqMessageQueueService: MqMessageQueueService) {\n this.url = process.env.QUEUES_RABBIT_MQ_URL;\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';\n if (!this.url) {\n this.logger.debug('RabbitMqPublisher url is not defined in the environment variables');\n }\n if (!process.env.QUEUES_SERVICE_ROLE) {\n this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting RabbitMqSubscriber service role to \"both\".');\n }\n // this.logger.debug(`RabbitMqSubscriber instance created with options: ${JSON.stringify(this.options())} and url: ${this.url}`);\n }\n\n protected get loggerContext(): string {\n return this.constructor.name;\n }\n\n protected get logger(): Logger {\n if (!this._loggerInstance) {\n this._loggerInstance = new Logger(this.loggerContext);\n }\n return this._loggerInstance;\n }\n\n abstract subscribe(message: QueueMessage<T>): Promise<any>;\n\n abstract options(): QueuesModuleOptions;\n\n protected shouldPersistToDatabase(): boolean {\n return this.options().persistToDatabase ?? true;\n }\n\n async establishConnection(): Promise<amqp.Connection> {\n\n const url = new URL(this.url);\n\n // this.logger.debug(`user: ${url.username}`);\n // // just for local debug, don’t log in prod\n // this.logger.debug(`pass: ${url.password}`);\n // this.logger.debug(`path (vhost): ${url.pathname}`);\n\n const connection = await amqp.connect({\n protocol: url.protocol.replace(':', ''),\n hostname: url.hostname,\n port: parseInt(url.port),\n username: url.username,\n password: decodeURIComponent(url.password),\n frameMax: 131072,\n heartbeat: 30,\n });\n\n return connection\n }\n\n async onModuleInit(): Promise<void> {\n // Not using SettingService here as that will necessitate all implementors of RabbitMqSubscriber to also inject SettingService which is not ideal. \n // Instead we directly read the environment variables here.\n const defaultBroker = process.env.QUEUES_DEFAULT_BROKER || 'database';\n const solidCliRunning = process.env.SOLID_CLI_RUNNING || \"false\";\n const queueNameRegex = (process.env.QUEUES_QUEUE_NAME_REGEX_TO_ENABLE || '').trim();\n const roleAllowed = ['both', 'subscriber'].includes(this.serviceRole);\n\n if (!roleAllowed) {\n this.logger.log(`RabbitMqSubscriber is disabled because QUEUES_SERVICE_ROLE is \"${this.serviceRole}\". Expected \"both\" or \"subscriber\".`);\n return;\n }\n\n // we will start subscriber only if the current service role is subscriber. \n if (this.url && solidCliRunning === \"false\" && defaultBroker === 'rabbitmq') {\n const options = this.options();\n const queueName = options.queueName;\n\n if (queueNameRegex && queueNameRegex !== \"all\") {\n try {\n const regex = new RegExp(queueNameRegex);\n if (!regex.test(queueName)) {\n this.logger.log(`RabbitMqSubscriber for queue ${queueName} is disabled because it does not match QUEUES_QUEUE_NAME_REGEX_TO_ENABLE=${queueNameRegex}`);\n return;\n }\n } catch (error) {\n this.logger.error(`Invalid QUEUES_QUEUE_NAME_REGEX_TO_ENABLE regex \"${queueNameRegex}\". Subscriber for queue ${queueName} will not start.`);\n return;\n }\n }\n\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n try {\n await this.connectAndConsume(namespacedQueueName);\n } catch (err) {\n this.logger.error(`Failed to connect to RabbitMQ for queue ${namespacedQueueName}: ${(err as Error).message}`, (err as Error).stack);\n this.triggerReconnect(namespacedQueueName, 'initial connection failure');\n }\n\n this.logger.log(`RabbitMqSubscriber ready to consume messages: ${JSON.stringify(options)} and url: ${this.url}`);\n }\n }\n\n private async connectAndConsume(queueName: string): Promise<void> {\n await this.cleanup();\n this.logger.log(`RabbitMqSubscriber in connectAndConsume for queue: ${queueName} and url: ${this.url}`);\n\n const options = this.options();\n const prefetch = options.prefetch ?? 1;\n if (prefetch < 1) {\n throw new Error(`RabbitMqSubscriber prefetch must be >= 1 for queue ${queueName}`);\n }\n const processingTimeoutMs = this.resolveProcessingTimeoutMs();\n if (processingTimeoutMs > 0) {\n this.logger.log(`RabbitMqSubscriber using processing timeout ${processingTimeoutMs}ms for queue ${queueName}`);\n }\n\n let connection: amqp.Connection;\n try {\n connection = await this.establishConnection();\n } catch (err) {\n this.logger.error(`Failed to connect to RabbitMQ for queue ${queueName}: ${(err as Error).message}`, (err as Error).stack);\n throw err;\n }\n\n this.connection = connection;\n\n connection.on('error', (err) => {\n if (connection !== this.connection) return;\n this.logger.error(`RabbitMqSubscriber connection error for queue ${queueName}: ${(err as Error).message}`);\n });\n\n connection.on('close', () => {\n if (connection !== this.connection) return;\n this.logger.warn(`RabbitMqSubscriber connection closed for queue ${queueName}`);\n this.triggerReconnect(queueName, 'connection closed');\n });\n\n const channel = await connection.createChannel();\n this.channel = channel;\n\n channel.on('error', (err) => {\n if (channel !== this.channel) return;\n this.logger.error(`RabbitMqSubscriber channel error for queue ${queueName}: ${(err as Error).message}`);\n });\n\n channel.on('close', () => {\n if (channel !== this.channel) return;\n this.logger.warn(`RabbitMqSubscriber channel closed for queue ${queueName}`);\n this.triggerReconnect(queueName, 'channel closed');\n });\n\n // Process one message at a time per consumer to avoid parallel work on the same subscriber instance.\n await channel.prefetch(prefetch);\n\n // Use a direct exchange with a stable routing key so retry DLX can route back to the main queue.\n const exchangeName = `${queueName}.exchange`;\n const routingKey = `${queueName}.routing-key`;\n const retryQueue = `${queueName}.retry`;\n const failedQueue = `${queueName}.failed`;\n\n await channel.assertExchange(exchangeName, 'direct', {});\n await channel.assertQueue(queueName, {});\n await channel.bindQueue(queueName, exchangeName, routingKey);\n\n // Retry queue uses DLX to route expired messages back to the main exchange/routing key.\n await channel.assertQueue(retryQueue, {\n arguments: {\n 'x-dead-letter-exchange': exchangeName,\n 'x-dead-letter-routing-key': routingKey,\n }\n });\n\n await channel.assertQueue(failedQueue, {});\n\n const consumeResult = await channel.consume(\n queueName,\n async (rawMessage) => {\n if (!rawMessage) {\n return;\n }\n\n let message: QueueMessage<T> = null;\n\n try {\n const messageContentString = rawMessage.content.toString();\n message = JSON.parse(messageContentString) as QueueMessage<T>;\n this.logger.debug(`rabbitmq subscriber received message with id: ${message.messageId} for queue ${queueName}`);\n } catch (error) {\n this.logger.error(`Invalid JSON message on queue ${queueName}: ${(error as Error).message}`);\n await this.publishToFailedQueue(queueName, rawMessage.content, channel, error);\n channel.ack(rawMessage);\n return;\n }\n\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n if (!message.currentRetry) message.currentRetry = 0;\n\n try {\n await this.processMessage(message, rawMessage, channel, queueName);\n } catch (error) {\n await this.handleProcessingError(message, rawMessage, channel, error, queueName);\n }\n },\n // Explicit ack enables reliable processing and retry routing.\n { noAck: false },\n );\n\n this.consumerTag = consumeResult.consumerTag;\n }\n\n // Retry flow: update DB -> increment retry -> send to retry queue with per-message expiration -> ack original.\n private async handleProcessingError(message: QueueMessage<T>, rawMessage: amqp.ConsumeMessage, channel: amqp.Channel, error: any, queueName: string): Promise<void> {\n const errorMessage = (error as Error)?.message || String(error);\n this.logger.error(`Error processing message on queue ${queueName}: ${errorMessage}`, (error as Error)?.stack);\n\n if (message.currentRetry < message.retryCount) {\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('retrying', message);\n }\n\n message.currentRetry++;\n const retryQueue = `${queueName}.retry`;\n const payload = Buffer.from(JSON.stringify(message));\n\n // Per-message expiration keeps the message in the retry queue until TTL, then DLX routes it back.\n channel.sendToQueue(retryQueue, payload, {\n expiration: String(message.retryInterval || 1000),\n headers: {\n 'x-error': errorMessage,\n }\n });\n\n channel.ack(rawMessage);\n this.logger.warn(`Retrying message (${message.currentRetry}/${message.retryCount}) after ${message.retryInterval}ms on queue ${queueName}`);\n return;\n }\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('failed', message, errorMessage, '');\n }\n channel.ack(rawMessage);\n await this.publishToFailedQueue(queueName, Buffer.from(JSON.stringify(message)), channel, error);\n this.logger.error(`Message failed after ${message.retryCount} attempts on queue ${queueName}: ${errorMessage}`);\n }\n\n private async publishToFailedQueue(queueName: string, payload: Buffer | string, channel: amqp.Channel, error?: any): Promise<void> {\n const failedQueue = `${queueName}.failed`;\n const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);\n const errorMessage = (error as Error)?.message || String(error || '');\n\n try {\n channel.sendToQueue(failedQueue, body, errorMessage ? {\n headers: { 'x-error': errorMessage }\n } : undefined);\n } catch (err) {\n this.logger.error(`Failed to publish to failed queue ${failedQueue}: ${(err as Error).message}`);\n }\n }\n\n private triggerReconnect(queueName: string, reason: string) {\n if (this.stopping) return;\n if (this.reconnectPromise) return;\n\n this.reconnectPromise = this.reconnectLoop(queueName, reason)\n .finally(() => {\n this.reconnectPromise = null;\n });\n }\n\n // Reconnect with backoff to avoid hammering the broker during outages.\n private async reconnectLoop(queueName: string, reason: string): Promise<void> {\n this.logger.warn(`RabbitMqSubscriber reconnecting for queue ${queueName}: ${reason}`);\n\n while (!this.stopping) {\n try {\n await this.connectAndConsume(queueName);\n this.reconnectAttempt = 0;\n this.logger.log(`RabbitMqSubscriber reconnected for queue ${queueName}`);\n return;\n } catch (err) {\n this.reconnectAttempt += 1;\n const delay = this.backoff();\n this.logger.warn(`RabbitMqSubscriber reconnect failed for queue ${queueName}; retrying in ${delay}ms`);\n await this.sleep(delay);\n }\n }\n }\n\n private async cleanup(): Promise<void> {\n const channel = this.channel;\n const connection = this.connection;\n const consumerTag = this.consumerTag;\n\n this.channel = null;\n this.connection = null;\n this.consumerTag = null;\n\n if (channel) {\n try {\n if (consumerTag) {\n await channel.cancel(consumerTag);\n }\n } catch (_) {\n // ignore\n }\n\n try {\n await channel.close();\n } catch (_) {\n // ignore\n }\n }\n\n if (connection) {\n try {\n await connection.close();\n } catch (_) {\n // ignore\n }\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n // Exponential backoff with jitter, capped to 30s.\n private backoff(): number {\n const baseMs = 1000;\n const maxMs = 30_000;\n const exp = Math.min(maxMs, baseMs * Math.pow(2, this.reconnectAttempt));\n const jitter = Math.floor(Math.random() * (exp * 0.2));\n return Math.min(maxMs, exp + jitter);\n }\n\n /**\n * Abstract method for message processing logic.\n */\n protected async processMessage(message: QueueMessage<T>, rawMessage, channel, queueName: string): Promise<void> {\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('started', message);\n }\n\n // Capture the results of handling the task.\n const result = await this.subscribeWithTimeout(message, queueName);\n\n // Ack the message. \n channel.ack(rawMessage);\n\n // Persist success output and timing.\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('succeeded', message, '', result ? JSON.stringify(result, null, 2) : '');\n }\n\n }\n\n private async updateStatusInDatabase(stage: string, message: QueueMessage<T>, error: string = '', result: string = '') {\n\n // Update the existing message record by messageId; creation happens upstream.\n try {\n // 1. resolve the queue first\n const mqMessage = await this.mqMessageService.repo.findOne({\n where: {\n messageId: message.messageId,\n }\n });\n\n if (mqMessage) {\n const updatedFields = {\n stage: stage\n };\n if (stage === 'failed' || stage === 'succeeded') {\n updatedFields['finishedAt'] = new Date();\n updatedFields['elapsedMillis'] = updatedFields['finishedAt'].getTime() - mqMessage.startedAt.getTime();\n }\n if (stage === 'succeeded') {\n updatedFields['output'] = result;\n }\n if (stage === 'failed') {\n updatedFields['error'] = error;\n }\n await this.mqMessageService.repo.update(mqMessage.id, updatedFields);\n }\n }\n catch (error: any) {\n this.logger.error(error.message, error.stack);\n }\n\n }\n\n private resolveProcessingTimeoutMs(): number {\n // Broker-side delivery-ack timeout (ms). If not provided, assume RabbitMQ default\n // behavior used in this project: 30 minutes.\n // Example (RabbitMQ broker):\n // - Broker ack timeout: 30m => 1,800,000ms (QUEUES_RABBITMQ_CONSUMER_ACK_TIMEOUT_MS)\n // - App soft timeout should be slightly lower, e.g. 29m30s => 1,770,000ms\n // (QUEUES_RABBITMQ_SUBSCRIBER_PROCESSING_TIMEOUT_MS), so application code fails first,\n // records DB state/error, and avoids broker-forced channel close as primary failure signal.\n const brokerTimeoutMs = this.parsePositiveInt(process.env.QUEUES_RABBITMQ_CONSUMER_ACK_TIMEOUT_MS, 30 * 60 * 1000);\n\n // Soft timeout should fire *before* broker timeout so we can fail explicitly,\n // persist status/error, and avoid broker-forced channel closure as primary signal.\n // Keep at least 1s to avoid zero/negative values when broker timeout is very small.\n const defaultSoftTimeoutMs = Math.max(1_000, brokerTimeoutMs - 30_000);\n\n // Final timeout precedence:\n // 1) QUEUES_RABBITMQ_SUBSCRIBER_PROCESSING_TIMEOUT_MS (if valid positive int)\n // 2) Derived defaultSoftTimeoutMs (broker timeout - 30s)\n return this.parsePositiveInt(process.env.QUEUES_RABBITMQ_SUBSCRIBER_PROCESSING_TIMEOUT_MS, defaultSoftTimeoutMs);\n }\n\n private parsePositiveInt(value: string | undefined, fallback: number): number {\n // Shared env parsing helper:\n // - missing/invalid/non-positive => fallback\n // - valid positive integer => parsed value\n if (!value) return fallback;\n const parsed = Number.parseInt(value, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n }\n\n private async subscribeWithTimeout(message: QueueMessage<T>, queueName: string): Promise<any> {\n const timeoutMs = this.resolveProcessingTimeoutMs();\n const messageId = message?.messageId || 'unknown';\n\n // Allow an escape hatch: non-positive timeout means run without a soft timeout.\n if (timeoutMs <= 0) {\n return this.subscribe(message);\n }\n\n let timedOut = false;\n let timeoutHandle: NodeJS.Timeout | null = null;\n\n // Main subscriber work promise.\n // If timeout has already fired, suppress rethrow to avoid unhandled rejection noise\n // (the timeout error is already the authoritative failure we track).\n const subscribePromise = Promise.resolve()\n .then(() => this.subscribe(message))\n .catch((error) => {\n if (timedOut) {\n this.logger.error(\n `Subscriber promise rejected after timeout for queue ${queueName} and messageId ${messageId}: ${(error as Error)?.message || String(error)}`,\n (error as Error)?.stack,\n );\n return undefined;\n }\n throw error;\n });\n\n // Timeout promise rejects after timeoutMs with an explicit domain-specific error.\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutHandle = setTimeout(() => {\n timedOut = true;\n reject(new ConsumerProcessingTimeoutError(queueName, messageId, timeoutMs));\n }, timeoutMs);\n });\n\n try {\n // Promise.race settles as soon as the *first* promise settles.\n // - If subscribePromise resolves/rejects first, we use that outcome.\n // - If timeoutPromise rejects first, we fail fast with timeout error.\n // This ensures we mark DB status via normal error handling before broker ack-timeout.\n return await Promise.race([subscribePromise, timeoutPromise]);\n } catch (error) {\n const errorMessage = (error as Error)?.message || String(error);\n this.logger.error(\n `Subscriber execution failed for queue ${queueName} and messageId ${messageId}: ${errorMessage}`,\n (error as Error)?.stack,\n );\n throw error;\n } finally {\n // Always clear timer once race settles to avoid timer leaks.\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n }\n }\n\n}\n"]}
1
+ {"version":3,"file":"rabbitmq-subscriber.service.js","sourceRoot":"","sources":["../../../src/services/queues/rabbitmq-subscriber.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAsD;AACtD,8CAAgC;AAKhC,qCAAoD;AAEpD,MAAM,8BAA+B,SAAQ,KAAK;IAC9C,YACa,SAAiB,EACjB,SAAiB,EACjB,SAAi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EAAE,SAAS,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC;YAKD,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,cAAc,CAAC,CAAC,CAAC;QAClE,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YAClB,MAAM,YAAY,GAAI,KAAe,EAAE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;YAChE,IAAI,CAAC,MAAM,CAAC,KAAK,CACb,yCAAyC,SAAS,kBAAkB,SAAS,KAAK,YAAY,EAAE,EAC/F,KAAe,EAAE,KAAK,CAC1B,CAAC;YACF,MAAM,KAAK,CAAC;QAChB,CAAC;gBAAS,CAAC;YAEP,IAAI,aAAa,EAAE,CAAC;gBAChB,YAAY,CAAC,aAAa,CAAC,CAAC;YAChC,CAAC;QACL,CAAC;IACL,CAAC;CAEJ;AAleD,gDAkeC","sourcesContent":["import { Logger, OnModuleInit } from '@nestjs/common';\nimport * as amqp from 'amqplib';\nimport { QueuesModuleOptions } from \"../../interfaces\";\nimport { QueueMessage, QueueSubscriber } from '../../interfaces/mq';\nimport { MqMessageQueueService } from '../mq-message-queue.service';\nimport { MqMessageService } from '../mq-message.service';\nimport { buildNamespacedQueueName } from './common';\n\nclass ConsumerProcessingTimeoutError extends Error {\n constructor(\n readonly queueName: string,\n readonly messageId: string,\n readonly timeoutMs: number,\n ) {\n super(`Subscriber processing timed out after ${timeoutMs}ms for queue ${queueName} and messageId ${messageId}`);\n this.name = 'ConsumerProcessingTimeoutError';\n }\n}\n\n\nexport abstract class RabbitMqSubscriber<T> implements OnModuleInit, QueueSubscriber<T> { // TODO This can be made a generic type for better type visibility\n private _loggerInstance?: Logger;\n private readonly url: string;\n private readonly serviceRole: string;\n private connection: amqp.Connection | null = null;\n private channel: amqp.Channel | null = null;\n private consumerTag: string | null = null;\n private reconnectPromise: Promise<void> | null = null;\n private reconnectAttempt = 0;\n private stopping = false;\n\n constructor(protected readonly mqMessageService: MqMessageService, protected readonly mqMessageQueueService: MqMessageQueueService) {\n this.url = process.env.QUEUES_RABBIT_MQ_URL;\n this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';\n if (!this.url) {\n this.logger.debug('RabbitMqPublisher url is not defined in the environment variables');\n }\n if (!process.env.QUEUES_SERVICE_ROLE) {\n this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting RabbitMqSubscriber service role to \"both\".');\n }\n // this.logger.debug(`RabbitMqSubscriber instance created with options: ${JSON.stringify(this.options())} and url: ${this.url}`);\n }\n\n protected get loggerContext(): string {\n return this.constructor.name;\n }\n\n protected get logger(): Logger {\n if (!this._loggerInstance) {\n this._loggerInstance = new Logger(this.loggerContext);\n }\n return this._loggerInstance;\n }\n\n abstract subscribe(message: QueueMessage<T>): Promise<any>;\n\n abstract options(): QueuesModuleOptions;\n\n protected shouldPersistToDatabase(): boolean {\n return this.options().persistToDatabase ?? true;\n }\n\n async establishConnection(): Promise<amqp.Connection> {\n\n const url = new URL(this.url);\n\n // this.logger.debug(`user: ${url.username}`);\n // // just for local debug, don’t log in prod\n // this.logger.debug(`pass: ${url.password}`);\n // this.logger.debug(`path (vhost): ${url.pathname}`);\n\n const connection = await amqp.connect({\n protocol: url.protocol.replace(':', ''),\n hostname: url.hostname,\n port: parseInt(url.port),\n username: url.username,\n password: decodeURIComponent(url.password),\n frameMax: 131072,\n heartbeat: 30,\n });\n\n return connection\n }\n\n async onModuleInit(): Promise<void> {\n // Not using SettingService here as that will necessitate all implementors of RabbitMqSubscriber to also inject SettingService which is not ideal. \n // Instead we directly read the environment variables here.\n const defaultBroker = process.env.QUEUES_DEFAULT_BROKER || 'database';\n const solidCliRunning = process.env.SOLID_CLI_RUNNING || \"false\";\n const queueNameRegex = (process.env.QUEUES_QUEUE_NAME_REGEX_TO_ENABLE || '').trim();\n const roleAllowed = ['both', 'subscriber'].includes(this.serviceRole);\n\n if (!roleAllowed) {\n this.logger.log(`RabbitMqSubscriber is disabled because QUEUES_SERVICE_ROLE is \"${this.serviceRole}\". Expected \"both\" or \"subscriber\".`);\n return;\n }\n\n // we will start subscriber only if the current service role is subscriber. \n if (this.url && solidCliRunning === \"false\" && defaultBroker === 'rabbitmq') {\n const options = this.options();\n const queueName = options.queueName;\n\n if (queueNameRegex && queueNameRegex !== \"all\") {\n try {\n const regex = new RegExp(queueNameRegex);\n if (!regex.test(queueName)) {\n this.logger.log(`RabbitMqSubscriber for queue ${queueName} is disabled because it does not match QUEUES_QUEUE_NAME_REGEX_TO_ENABLE=${queueNameRegex}`);\n return;\n }\n } catch (error: any) {\n this.logger.error(`Invalid QUEUES_QUEUE_NAME_REGEX_TO_ENABLE regex \"${queueNameRegex}\". Subscriber for queue ${queueName} will not start.`);\n return;\n }\n }\n\n const namespacedQueueName = buildNamespacedQueueName(queueName);\n try {\n await this.connectAndConsume(namespacedQueueName);\n } catch (err: any) {\n this.logger.error(`Failed to connect to RabbitMQ for queue ${namespacedQueueName}: ${(err as Error).message}`, (err as Error).stack);\n this.triggerReconnect(namespacedQueueName, 'initial connection failure');\n }\n\n this.logger.log(`RabbitMqSubscriber ready to consume messages: ${JSON.stringify(options)} and url: ${this.url}`);\n }\n }\n\n private async connectAndConsume(queueName: string): Promise<void> {\n await this.cleanup();\n this.logger.log(`RabbitMqSubscriber in connectAndConsume for queue: ${queueName} and url: ${this.url}`);\n\n const options = this.options();\n const prefetch = options.prefetch ?? 1;\n if (prefetch < 1) {\n throw new Error(`RabbitMqSubscriber prefetch must be >= 1 for queue ${queueName}`);\n }\n const processingTimeoutMs = this.resolveProcessingTimeoutMs();\n if (processingTimeoutMs > 0) {\n this.logger.log(`RabbitMqSubscriber using processing timeout ${processingTimeoutMs}ms for queue ${queueName}`);\n }\n\n let connection: amqp.Connection;\n try {\n connection = await this.establishConnection();\n } catch (err: any) {\n this.logger.error(`Failed to connect to RabbitMQ for queue ${queueName}: ${(err as Error).message}`, (err as Error).stack);\n throw err;\n }\n\n this.connection = connection;\n\n connection.on('error', (err) => {\n if (connection !== this.connection) return;\n this.logger.error(`RabbitMqSubscriber connection error for queue ${queueName}: ${(err as Error).message}`);\n });\n\n connection.on('close', () => {\n if (connection !== this.connection) return;\n this.logger.warn(`RabbitMqSubscriber connection closed for queue ${queueName}`);\n this.triggerReconnect(queueName, 'connection closed');\n });\n\n const channel = await connection.createChannel();\n this.channel = channel;\n\n channel.on('error', (err) => {\n if (channel !== this.channel) return;\n this.logger.error(`RabbitMqSubscriber channel error for queue ${queueName}: ${(err as Error).message}`);\n });\n\n channel.on('close', () => {\n if (channel !== this.channel) return;\n this.logger.warn(`RabbitMqSubscriber channel closed for queue ${queueName}`);\n this.triggerReconnect(queueName, 'channel closed');\n });\n\n // Process one message at a time per consumer to avoid parallel work on the same subscriber instance.\n await channel.prefetch(prefetch);\n\n // Use a direct exchange with a stable routing key so retry DLX can route back to the main queue.\n const exchangeName = `${queueName}.exchange`;\n const routingKey = `${queueName}.routing-key`;\n const retryQueue = `${queueName}.retry`;\n const failedQueue = `${queueName}.failed`;\n\n await channel.assertExchange(exchangeName, 'direct', {});\n await channel.assertQueue(queueName, {});\n await channel.bindQueue(queueName, exchangeName, routingKey);\n\n // Retry queue uses DLX to route expired messages back to the main exchange/routing key.\n await channel.assertQueue(retryQueue, {\n arguments: {\n 'x-dead-letter-exchange': exchangeName,\n 'x-dead-letter-routing-key': routingKey,\n }\n });\n\n await channel.assertQueue(failedQueue, {});\n\n const consumeResult = await channel.consume(\n queueName,\n async (rawMessage) => {\n if (!rawMessage) {\n return;\n }\n\n let message: QueueMessage<T> = null;\n\n try {\n const messageContentString = rawMessage.content.toString();\n message = JSON.parse(messageContentString) as QueueMessage<T>;\n this.logger.debug(`rabbitmq subscriber received message with id: ${message.messageId} for queue ${queueName}`);\n } catch (error: any) {\n this.logger.error(`Invalid JSON message on queue ${queueName}: ${(error as Error).message}`);\n await this.publishToFailedQueue(queueName, rawMessage.content, channel, error);\n channel.ack(rawMessage);\n return;\n }\n\n if (!message.retryCount) message.retryCount = 0;\n if (!message.retryInterval) message.retryInterval = 1000;\n if (!message.currentRetry) message.currentRetry = 0;\n\n try {\n await this.processMessage(message, rawMessage, channel, queueName);\n } catch (error: any) {\n await this.handleProcessingError(message, rawMessage, channel, error, queueName);\n }\n },\n // Explicit ack enables reliable processing and retry routing.\n { noAck: false },\n );\n\n this.consumerTag = consumeResult.consumerTag;\n }\n\n // Retry flow: update DB -> increment retry -> send to retry queue with per-message expiration -> ack original.\n private async handleProcessingError(message: QueueMessage<T>, rawMessage: amqp.ConsumeMessage, channel: amqp.Channel, error: any, queueName: string): Promise<void> {\n const errorMessage = (error as Error)?.message || String(error);\n this.logger.error(`Error processing message on queue ${queueName}: ${errorMessage}`, (error as Error)?.stack);\n\n if (message.currentRetry < message.retryCount) {\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('retrying', message);\n }\n\n message.currentRetry++;\n const retryQueue = `${queueName}.retry`;\n const payload = Buffer.from(JSON.stringify(message));\n\n // Per-message expiration keeps the message in the retry queue until TTL, then DLX routes it back.\n channel.sendToQueue(retryQueue, payload, {\n expiration: String(message.retryInterval || 1000),\n headers: {\n 'x-error': errorMessage,\n }\n });\n\n channel.ack(rawMessage);\n this.logger.warn(`Retrying message (${message.currentRetry}/${message.retryCount}) after ${message.retryInterval}ms on queue ${queueName}`);\n return;\n }\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('failed', message, errorMessage, '');\n }\n channel.ack(rawMessage);\n await this.publishToFailedQueue(queueName, Buffer.from(JSON.stringify(message)), channel, error);\n this.logger.error(`Message failed after ${message.retryCount} attempts on queue ${queueName}: ${errorMessage}`);\n }\n\n private async publishToFailedQueue(queueName: string, payload: Buffer | string, channel: amqp.Channel, error?: any): Promise<void> {\n const failedQueue = `${queueName}.failed`;\n const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);\n const errorMessage = (error as Error)?.message || String(error || '');\n\n try {\n channel.sendToQueue(failedQueue, body, errorMessage ? {\n headers: { 'x-error': errorMessage }\n } : undefined);\n } catch (err: any) {\n this.logger.error(`Failed to publish to failed queue ${failedQueue}: ${(err as Error).message}`);\n }\n }\n\n private triggerReconnect(queueName: string, reason: string) {\n if (this.stopping) return;\n if (this.reconnectPromise) return;\n\n this.reconnectPromise = this.reconnectLoop(queueName, reason)\n .finally(() => {\n this.reconnectPromise = null;\n });\n }\n\n // Reconnect with backoff to avoid hammering the broker during outages.\n private async reconnectLoop(queueName: string, reason: string): Promise<void> {\n this.logger.warn(`RabbitMqSubscriber reconnecting for queue ${queueName}: ${reason}`);\n\n while (!this.stopping) {\n try {\n await this.connectAndConsume(queueName);\n this.reconnectAttempt = 0;\n this.logger.log(`RabbitMqSubscriber reconnected for queue ${queueName}`);\n return;\n } catch (err: any) {\n this.reconnectAttempt += 1;\n const delay = this.backoff();\n this.logger.warn(`RabbitMqSubscriber reconnect failed for queue ${queueName}; retrying in ${delay}ms`);\n await this.sleep(delay);\n }\n }\n }\n\n private async cleanup(): Promise<void> {\n const channel = this.channel;\n const connection = this.connection;\n const consumerTag = this.consumerTag;\n\n this.channel = null;\n this.connection = null;\n this.consumerTag = null;\n\n if (channel) {\n try {\n if (consumerTag) {\n await channel.cancel(consumerTag);\n }\n } catch (_) {\n // ignore\n }\n\n try {\n await channel.close();\n } catch (_) {\n // ignore\n }\n }\n\n if (connection) {\n try {\n await connection.close();\n } catch (_) {\n // ignore\n }\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n // Exponential backoff with jitter, capped to 30s.\n private backoff(): number {\n const baseMs = 1000;\n const maxMs = 30_000;\n const exp = Math.min(maxMs, baseMs * Math.pow(2, this.reconnectAttempt));\n const jitter = Math.floor(Math.random() * (exp * 0.2));\n return Math.min(maxMs, exp + jitter);\n }\n\n /**\n * Abstract method for message processing logic.\n */\n protected async processMessage(message: QueueMessage<T>, rawMessage, channel, queueName: string): Promise<void> {\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('started', message);\n }\n\n // Capture the results of handling the task.\n const result = await this.subscribeWithTimeout(message, queueName);\n\n // Ack the message. \n channel.ack(rawMessage);\n\n // Persist success output and timing.\n if (this.shouldPersistToDatabase()) {\n await this.updateStatusInDatabase('succeeded', message, '', result ? JSON.stringify(result, null, 2) : '');\n }\n\n }\n\n private async updateStatusInDatabase(stage: string, message: QueueMessage<T>, error: string = '', result: string = '') {\n\n // Update the existing message record by messageId; creation happens upstream.\n try {\n // 1. resolve the queue first\n const mqMessage = await this.mqMessageService.repo.findOne({\n where: {\n messageId: message.messageId,\n }\n });\n\n if (mqMessage) {\n const updatedFields = {\n stage: stage\n };\n if (stage === 'failed' || stage === 'succeeded') {\n updatedFields['finishedAt'] = new Date();\n updatedFields['elapsedMillis'] = updatedFields['finishedAt'].getTime() - mqMessage.startedAt.getTime();\n }\n if (stage === 'succeeded') {\n updatedFields['output'] = result;\n }\n if (stage === 'failed') {\n updatedFields['error'] = error;\n }\n await this.mqMessageService.repo.update(mqMessage.id, updatedFields);\n }\n }\n catch (error: any) {\n this.logger.error(error.message, error.stack);\n }\n\n }\n\n private resolveProcessingTimeoutMs(): number {\n // Broker-side delivery-ack timeout (ms). If not provided, assume RabbitMQ default\n // behavior used in this project: 30 minutes.\n // Example (RabbitMQ broker):\n // - Broker ack timeout: 30m => 1,800,000ms (QUEUES_RABBITMQ_CONSUMER_ACK_TIMEOUT_MS)\n // - App soft timeout should be slightly lower, e.g. 29m30s => 1,770,000ms\n // (QUEUES_RABBITMQ_SUBSCRIBER_PROCESSING_TIMEOUT_MS), so application code fails first,\n // records DB state/error, and avoids broker-forced channel close as primary failure signal.\n const brokerTimeoutMs = this.parsePositiveInt(process.env.QUEUES_RABBITMQ_CONSUMER_ACK_TIMEOUT_MS, 30 * 60 * 1000);\n\n // Soft timeout should fire *before* broker timeout so we can fail explicitly,\n // persist status/error, and avoid broker-forced channel closure as primary signal.\n // Keep at least 1s to avoid zero/negative values when broker timeout is very small.\n const defaultSoftTimeoutMs = Math.max(1_000, brokerTimeoutMs - 30_000);\n\n // Final timeout precedence:\n // 1) QUEUES_RABBITMQ_SUBSCRIBER_PROCESSING_TIMEOUT_MS (if valid positive int)\n // 2) Derived defaultSoftTimeoutMs (broker timeout - 30s)\n return this.parsePositiveInt(process.env.QUEUES_RABBITMQ_SUBSCRIBER_PROCESSING_TIMEOUT_MS, defaultSoftTimeoutMs);\n }\n\n private parsePositiveInt(value: string | undefined, fallback: number): number {\n // Shared env parsing helper:\n // - missing/invalid/non-positive => fallback\n // - valid positive integer => parsed value\n if (!value) return fallback;\n const parsed = Number.parseInt(value, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n }\n\n private async subscribeWithTimeout(message: QueueMessage<T>, queueName: string): Promise<any> {\n const timeoutMs = this.resolveProcessingTimeoutMs();\n const messageId = message?.messageId || 'unknown';\n\n // Allow an escape hatch: non-positive timeout means run without a soft timeout.\n if (timeoutMs <= 0) {\n return this.subscribe(message);\n }\n\n let timedOut = false;\n let timeoutHandle: NodeJS.Timeout | null = null;\n\n // Main subscriber work promise.\n // If timeout has already fired, suppress rethrow to avoid unhandled rejection noise\n // (the timeout error is already the authoritative failure we track).\n const subscribePromise = Promise.resolve()\n .then(() => this.subscribe(message))\n .catch((error) => {\n if (timedOut) {\n this.logger.error(\n `Subscriber promise rejected after timeout for queue ${queueName} and messageId ${messageId}: ${(error as Error)?.message || String(error)}`,\n (error as Error)?.stack,\n );\n return undefined;\n }\n throw error;\n });\n\n // Timeout promise rejects after timeoutMs with an explicit domain-specific error.\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutHandle = setTimeout(() => {\n timedOut = true;\n reject(new ConsumerProcessingTimeoutError(queueName, messageId, timeoutMs));\n }, timeoutMs);\n });\n\n try {\n // Promise.race settles as soon as the *first* promise settles.\n // - If subscribePromise resolves/rejects first, we use that outcome.\n // - If timeoutPromise rejects first, we fail fast with timeout error.\n // This ensures we mark DB status via normal error handling before broker ack-timeout.\n return await Promise.race([subscribePromise, timeoutPromise]);\n } catch (error: any) {\n const errorMessage = (error as Error)?.message || String(error);\n this.logger.error(\n `Subscriber execution failed for queue ${queueName} and messageId ${messageId}: ${errorMessage}`,\n (error as Error)?.stack,\n );\n throw error;\n } finally {\n // Always clear timer once race settles to avoid timer leaks.\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n }\n }\n\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"redis-publisher.service.d.ts","sourceRoot":"","sources":["../../../src/services/queues/redis-publisher.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAGzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAGzD,8BAAsB,cAAc,CAAC,CAAC,CAAE,YAAW,eAAe,EAAE,cAAc,CAAC,CAAC,CAAC;IAM7E,SAAS,CAAC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB;IACrD,SAAS,CAAC,QAAQ,CAAC,qBAAqB,EAAE,qBAAqB;IANnE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;IAC1D,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,MAAM,CAAsB;gBAGb,gBAAgB,EAAE,gBAAgB,EAClC,qBAAqB,EAAE,qBAAqB;IAQnE,QAAQ,CAAC,OAAO,IAAI,mBAAmB;IAEvC,OAAO,CAAC,SAAS;IAUX,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAOhC,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;YA+B1C,iBAAiB;CAmBlC"}
1
+ {"version":3,"file":"redis-publisher.service.d.ts","sourceRoot":"","sources":["../../../src/services/queues/redis-publisher.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAGzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAGzD,8BAAsB,cAAc,CAAC,CAAC,CAAE,YAAW,eAAe,EAAE,cAAc,CAAC,CAAC,CAAC;IAM7E,SAAS,CAAC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB;IACrD,SAAS,CAAC,QAAQ,CAAC,qBAAqB,EAAE,qBAAqB;IANnE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;IAC1D,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,MAAM,CAAsB;gBAGb,gBAAgB,EAAE,gBAAgB,EAClC,qBAAqB,EAAE,qBAAqB;IAWnE,QAAQ,CAAC,OAAO,IAAI,mBAAmB;IAEvC,OAAO,CAAC,SAAS;IAUX,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAOhC,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;YA+B1C,iBAAiB;CAmBlC"}
@@ -14,7 +14,10 @@ class RedisPublisher {
14
14
  this.mqMessageQueueService = mqMessageQueueService;
15
15
  this.logger = new common_1.Logger(RedisPublisher.name);
16
16
  this.client = null;
17
- this.serviceRole = process.env.QUEUES_SERVICE_ROLE;
17
+ this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';
18
+ if (!process.env.QUEUES_SERVICE_ROLE) {
19
+ this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting RedisPublisher service role to "both".');
20
+ }
18
21
  if (!process.env.QUEUES_REDIS_URL) {
19
22
  this.logger.debug('RedisPublisher: QUEUES_REDIS_URL is not defined in the environment variables');
20
23
  }