crons.service.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { schedule, ScheduledTask } from 'node-cron';
  2. import { CollectionsService } from '../collections/collections.service';
  3. import {
  4. WS_EVENTS,
  5. WS_EVENTS_TYPE,
  6. checkLoading,
  7. checkIndexing,
  8. } from '../utils';
  9. import { clients } from '../socket';
  10. import { CronJobObject } from '../types';
  11. interface CronJob {
  12. id: string;
  13. clientId: string; // milvus milvusClientId
  14. task: ScheduledTask;
  15. data: CronJobObject;
  16. }
  17. import { clientCache } from '../app';
  18. const getId = (clientId: string, data: CronJobObject) => {
  19. return `${clientId}/${data.name}/${
  20. data.payload.database
  21. }/[${data.payload.collections.join('/')}]`;
  22. };
  23. export class CronsService {
  24. constructor(
  25. private collectionService: CollectionsService,
  26. private schedulerRegistry: SchedulerRegistry
  27. ) {}
  28. async toggleCronJobByName(clientId: string, data: CronJobObject) {
  29. const { name, type } = data;
  30. // define cronJob
  31. const cronJob: CronJob = this.schedulerRegistry.getCronJob(clientId, data);
  32. // if type is stop, stop cronJob
  33. if (cronJob && type === WS_EVENTS_TYPE.STOP) {
  34. return this.schedulerRegistry.deleteCronJob(clientId, data);
  35. }
  36. // switch case for different events
  37. switch (name) {
  38. // collection loading, indexing, update
  39. case WS_EVENTS.COLLECTION_UPDATE:
  40. if (type === WS_EVENTS_TYPE.START && !cronJob) {
  41. return this.execCollectionUpdateTask(clientId, data);
  42. }
  43. break;
  44. default:
  45. throw new Error('Unsupported event type');
  46. }
  47. }
  48. async execCollectionUpdateTask(clientId: string, data: CronJobObject) {
  49. console.log('execCollectionUpdateTask', clientId, data);
  50. const task = async () => {
  51. const currentJob: CronJob = this.schedulerRegistry.getCronJob(
  52. clientId,
  53. data
  54. );
  55. // if currentJob is not exist
  56. if (!currentJob) {
  57. // if client not connected, stop cron
  58. this.schedulerRegistry.deleteCronJob(clientId, data);
  59. return;
  60. }
  61. if (!clientCache.has(clientId)) {
  62. // if client not connected, stop cron
  63. this.schedulerRegistry.deleteCronJob(clientId, data);
  64. console.info('Client is not connected, stop cron.', clientId);
  65. return;
  66. }
  67. try {
  68. // get client cache data
  69. const { milvusClient } = clientCache.get(clientId);
  70. const currentDatabase = (milvusClient as any).metadata.get('dbname');
  71. // if database is not matched, return
  72. if (currentDatabase !== data.payload.database) {
  73. // if client not connected, stop cron
  74. this.schedulerRegistry.deleteCronJob(clientId, data);
  75. console.info('Database is not matched, stop cron.', clientId);
  76. return;
  77. }
  78. const collections = await this.collectionService.getAllCollections(
  79. currentJob.clientId,
  80. currentJob.data.payload.collections,
  81. currentJob.data.payload.database
  82. );
  83. // get current socket
  84. const socketClient = clients.get(currentJob.clientId);
  85. if (socketClient) {
  86. // emit event to current client, loading and indexing events are indetified as collection update
  87. socketClient.emit(WS_EVENTS.COLLECTION_UPDATE, {
  88. collections,
  89. database: currentJob.data.payload.database,
  90. });
  91. // if all collections are loaded, stop cron
  92. const LoadingOrBuildingCollections = collections.filter(v => {
  93. const isLoading = checkLoading(v);
  94. const isBuildingIndex = checkIndexing(v);
  95. return isLoading || isBuildingIndex;
  96. });
  97. if (LoadingOrBuildingCollections.length === 0) {
  98. this.schedulerRegistry.deleteCronJob(clientId, data);
  99. }
  100. }
  101. } catch (error) {
  102. if (error.message.includes('pool is draining')) {
  103. // Handle the pool draining error, possibly by logging and avoiding retry
  104. console.error(
  105. 'The pool is shutting down and cannot accept new work.'
  106. );
  107. this.schedulerRegistry.deleteCronJob(clientId, data);
  108. return;
  109. }
  110. // When user not connect milvus, stop cron
  111. this.schedulerRegistry.deleteCronJob(clientId, data);
  112. throw new Error(error);
  113. }
  114. };
  115. // every 5 seconds
  116. this.schedulerRegistry.setCronJob(clientId, '*/5 * * * * *', task, data);
  117. }
  118. }
  119. export class SchedulerRegistry {
  120. constructor(private cronJobMap: Map<string, CronJob>) {}
  121. getCronJob(clientId: string, data: CronJobObject) {
  122. const targetId = getId(clientId, data);
  123. const target = this.cronJobMap.get(targetId);
  124. return target;
  125. }
  126. deleteCronJob(clientId: string, data: CronJobObject) {
  127. const targetId = getId(clientId, data);
  128. if (this.cronJobMap.has(targetId)) {
  129. this.cronJobMap.get(targetId)?.task?.stop();
  130. this.cronJobMap.delete(targetId);
  131. }
  132. }
  133. deleteAllCronJobs(clientId: string) {
  134. // console.log('Deleting all cron jobs in service for client:', clientId);
  135. this.cronJobMap.forEach((v, k) => {
  136. if (v.clientId === clientId) {
  137. v.task.stop();
  138. this.cronJobMap.delete(k);
  139. }
  140. });
  141. }
  142. // ┌────────────── second (optional)
  143. // │ ┌──────────── minute
  144. // │ │ ┌────────── hour
  145. // │ │ │ ┌──────── day of month
  146. // │ │ │ │ ┌────── month
  147. // │ │ │ │ │ ┌──── day of week
  148. // │ │ │ │ │ │
  149. // │ │ │ │ │ │
  150. // * * * * * *
  151. // https://www.npmjs.com/package/node-cron
  152. setCronJob(
  153. clientId: string,
  154. cronExpression: string,
  155. func: () => void,
  156. data: CronJobObject
  157. ) {
  158. const target = this.getCronJob(clientId, data);
  159. if (target) {
  160. target?.task?.stop();
  161. } else {
  162. // create task id
  163. const id = getId(clientId, data);
  164. if (!this.cronJobMap.has(id)) {
  165. console.log('create task:', id);
  166. // create task
  167. const task = schedule(cronExpression, () => {
  168. console.log(
  169. `[cronExpression:${cronExpression}] ${data.name} ${id}: running a task.`
  170. );
  171. func();
  172. });
  173. // save task
  174. this.cronJobMap.set(id, {
  175. id,
  176. clientId,
  177. task,
  178. data,
  179. });
  180. }
  181. }
  182. }
  183. }