Bläddra i källkod

fix: add proper cleanup for watcher service on application shutdown

- Implement OnModuleDestroy lifecycle hook in WatcherService
- Properly close chokidar watcher and terminate validation worker on shutdown
- Clear validation callbacks map to prevent memory leaks
- Add error handling for cleanup operations
- Improves application stability during restarts
Timothy Pomeroy 3 veckor sedan
förälder
incheckning
f6454faf8c
1 ändrade filer med 24 tillägg och 2 borttagningar
  1. 24 2
      apps/service/src/watcher.service.ts

+ 24 - 2
apps/service/src/watcher.service.ts

@@ -1,4 +1,4 @@
-import { Inject, Injectable, Logger } from '@nestjs/common';
+import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
 import chokidar, { FSWatcher } from 'chokidar';
 import fs from 'fs';
 import path from 'path';
@@ -16,7 +16,7 @@ interface FileRecord {
 }
 
 @Injectable()
-export class WatcherService {
+export class WatcherService implements OnModuleDestroy {
   private watcher: FSWatcher | null = null;
   private isWatching = false;
   private lastWatches: string[] = [];
@@ -537,4 +537,26 @@ export class WatcherService {
       options: this.lastOptions,
     };
   }
+
+  async onModuleDestroy() {
+    // Clean up resources on application shutdown
+    try {
+      // Close the watcher if it's running
+      if (this.watcher && this.isWatching) {
+        await this.watcher.close();
+        this.logger.log('Watcher closed on module destroy');
+      }
+
+      // Terminate the validation worker
+      if (this.validationWorker) {
+        await this.validationWorker.terminate();
+        this.logger.log('Validation worker terminated on module destroy');
+      }
+
+      // Clear callbacks
+      this.validationCallbacks.clear();
+    } catch (error) {
+      this.logger.error(`Error during module destroy: ${error}`);
+    }
+  }
 }