@friggframework/core 2.0.0--canary.454.e2a280d.0 → 2.0.0--canary.459.51231dd.0

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 (29) hide show
  1. package/README.md +0 -28
  2. package/database/prisma.js +2 -2
  3. package/docs/PROCESS_MANAGEMENT_QUEUE_SPEC.md +517 -0
  4. package/handlers/routers/user.js +3 -1
  5. package/integrations/repositories/process-repository-factory.js +46 -0
  6. package/integrations/repositories/process-repository-interface.js +90 -0
  7. package/integrations/repositories/process-repository-mongo.js +190 -0
  8. package/integrations/repositories/process-repository-postgres.js +190 -0
  9. package/integrations/use-cases/create-process.js +128 -0
  10. package/integrations/use-cases/create-process.test.js +178 -0
  11. package/integrations/use-cases/get-process.js +87 -0
  12. package/integrations/use-cases/get-process.test.js +190 -0
  13. package/integrations/use-cases/index.js +8 -0
  14. package/integrations/use-cases/update-process-metrics.js +165 -0
  15. package/integrations/use-cases/update-process-metrics.test.js +308 -0
  16. package/integrations/use-cases/update-process-state.js +119 -0
  17. package/integrations/use-cases/update-process-state.test.js +256 -0
  18. package/modules/module.js +1 -1
  19. package/modules/use-cases/process-authorization-callback.js +2 -1
  20. package/package.json +66 -79
  21. package/prisma-mongodb/schema.prisma +64 -25
  22. package/prisma-postgresql/migrations/20251010000000_remove_unused_entity_reference_map/migration.sql +3 -0
  23. package/prisma-postgresql/schema.prisma +14 -19
  24. package/database/use-cases/run-database-migration-use-case.js +0 -137
  25. package/database/use-cases/run-database-migration-use-case.test.js +0 -310
  26. package/database/utils/prisma-runner.js +0 -313
  27. package/database/utils/prisma-runner.test.js +0 -486
  28. package/handlers/workers/db-migration.js +0 -208
  29. package/handlers/workers/db-migration.test.js +0 -437
@@ -0,0 +1,178 @@
1
+ /**
2
+ * CreateProcess Use Case Tests
3
+ *
4
+ * Tests process creation with validation and error handling.
5
+ */
6
+
7
+ const { CreateProcess } = require('./create-process');
8
+
9
+ describe('CreateProcess', () => {
10
+ let createProcessUseCase;
11
+ let mockProcessRepository;
12
+
13
+ beforeEach(() => {
14
+ mockProcessRepository = {
15
+ create: jest.fn(),
16
+ };
17
+ createProcessUseCase = new CreateProcess({
18
+ processRepository: mockProcessRepository,
19
+ });
20
+ });
21
+
22
+ describe('constructor', () => {
23
+ it('should require processRepository', () => {
24
+ expect(() => new CreateProcess({})).toThrow('processRepository is required');
25
+ });
26
+
27
+ it('should initialize with processRepository', () => {
28
+ expect(createProcessUseCase.processRepository).toBe(mockProcessRepository);
29
+ });
30
+ });
31
+
32
+ describe('execute', () => {
33
+ const validProcessData = {
34
+ userId: 'user-123',
35
+ integrationId: 'integration-456',
36
+ name: 'test-crm-contact-sync',
37
+ type: 'CRM_SYNC',
38
+ };
39
+
40
+ it('should create a process with minimal required data', async () => {
41
+ const mockCreatedProcess = { id: 'process-789', ...validProcessData };
42
+ mockProcessRepository.create.mockResolvedValue(mockCreatedProcess);
43
+
44
+ const result = await createProcessUseCase.execute(validProcessData);
45
+
46
+ expect(mockProcessRepository.create).toHaveBeenCalledWith({
47
+ userId: 'user-123',
48
+ integrationId: 'integration-456',
49
+ name: 'test-crm-contact-sync',
50
+ type: 'CRM_SYNC',
51
+ state: 'INITIALIZING',
52
+ context: {},
53
+ results: {},
54
+ childProcesses: [],
55
+ parentProcessId: null,
56
+ });
57
+ expect(result).toEqual(mockCreatedProcess);
58
+ });
59
+
60
+ it('should create a process with all optional data', async () => {
61
+ const processDataWithOptions = {
62
+ ...validProcessData,
63
+ state: 'FETCHING_TOTAL',
64
+ context: { syncType: 'INITIAL', totalRecords: 100 },
65
+ results: { aggregateData: { totalSynced: 0 } },
66
+ childProcesses: ['child-1', 'child-2'],
67
+ parentProcessId: 'parent-123',
68
+ };
69
+
70
+ const mockCreatedProcess = { id: 'process-789', ...processDataWithOptions };
71
+ mockProcessRepository.create.mockResolvedValue(mockCreatedProcess);
72
+
73
+ const result = await createProcessUseCase.execute(processDataWithOptions);
74
+
75
+ expect(mockProcessRepository.create).toHaveBeenCalledWith(processDataWithOptions);
76
+ expect(result).toEqual(mockCreatedProcess);
77
+ });
78
+
79
+ it('should throw error if userId is missing', async () => {
80
+ const invalidData = { integrationId: 'int-123', name: 'test', type: 'CRM_SYNC' };
81
+
82
+ await expect(createProcessUseCase.execute(invalidData))
83
+ .rejects.toThrow('Missing required fields for process creation: userId');
84
+ });
85
+
86
+ it('should throw error if integrationId is missing', async () => {
87
+ const invalidData = { userId: 'user-123', name: 'test', type: 'CRM_SYNC' };
88
+
89
+ await expect(createProcessUseCase.execute(invalidData))
90
+ .rejects.toThrow('Missing required fields for process creation: integrationId');
91
+ });
92
+
93
+ it('should throw error if name is missing', async () => {
94
+ const invalidData = { userId: 'user-123', integrationId: 'int-123', type: 'CRM_SYNC' };
95
+
96
+ await expect(createProcessUseCase.execute(invalidData))
97
+ .rejects.toThrow('Missing required fields for process creation: name');
98
+ });
99
+
100
+ it('should throw error if type is missing', async () => {
101
+ const invalidData = { userId: 'user-123', integrationId: 'int-123', name: 'test' };
102
+
103
+ await expect(createProcessUseCase.execute(invalidData))
104
+ .rejects.toThrow('Missing required fields for process creation: type');
105
+ });
106
+
107
+ it('should throw error if userId is not a string', async () => {
108
+ const invalidData = { ...validProcessData, userId: 123 };
109
+
110
+ await expect(createProcessUseCase.execute(invalidData))
111
+ .rejects.toThrow('userId must be a string');
112
+ });
113
+
114
+ it('should throw error if integrationId is not a string', async () => {
115
+ const invalidData = { ...validProcessData, integrationId: 456 };
116
+
117
+ await expect(createProcessUseCase.execute(invalidData))
118
+ .rejects.toThrow('integrationId must be a string');
119
+ });
120
+
121
+ it('should throw error if name is not a string', async () => {
122
+ const invalidData = { ...validProcessData, name: 789 };
123
+
124
+ await expect(createProcessUseCase.execute(invalidData))
125
+ .rejects.toThrow('name must be a string');
126
+ });
127
+
128
+ it('should throw error if type is not a string', async () => {
129
+ const invalidData = { ...validProcessData, type: 999 };
130
+
131
+ await expect(createProcessUseCase.execute(invalidData))
132
+ .rejects.toThrow('type must be a string');
133
+ });
134
+
135
+ it('should throw error if state is provided but not a string', async () => {
136
+ const invalidData = { ...validProcessData, state: 123 };
137
+
138
+ await expect(createProcessUseCase.execute(invalidData))
139
+ .rejects.toThrow('state must be a string');
140
+ });
141
+
142
+ it('should throw error if context is provided but not an object', async () => {
143
+ const invalidData = { ...validProcessData, context: 'invalid' };
144
+
145
+ await expect(createProcessUseCase.execute(invalidData))
146
+ .rejects.toThrow('context must be an object');
147
+ });
148
+
149
+ it('should throw error if results is provided but not an object', async () => {
150
+ const invalidData = { ...validProcessData, results: 'invalid' };
151
+
152
+ await expect(createProcessUseCase.execute(invalidData))
153
+ .rejects.toThrow('results must be an object');
154
+ });
155
+
156
+ it('should throw error if childProcesses is provided but not an array', async () => {
157
+ const invalidData = { ...validProcessData, childProcesses: 'invalid' };
158
+
159
+ await expect(createProcessUseCase.execute(invalidData))
160
+ .rejects.toThrow('childProcesses must be an array');
161
+ });
162
+
163
+ it('should throw error if parentProcessId is provided but not a string', async () => {
164
+ const invalidData = { ...validProcessData, parentProcessId: 123 };
165
+
166
+ await expect(createProcessUseCase.execute(invalidData))
167
+ .rejects.toThrow('parentProcessId must be a string');
168
+ });
169
+
170
+ it('should handle repository errors', async () => {
171
+ const repositoryError = new Error('Database connection failed');
172
+ mockProcessRepository.create.mockRejectedValue(repositoryError);
173
+
174
+ await expect(createProcessUseCase.execute(validProcessData))
175
+ .rejects.toThrow('Failed to create process: Database connection failed');
176
+ });
177
+ });
178
+ });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * GetProcess Use Case
3
+ *
4
+ * Retrieves a process by ID with proper error handling.
5
+ * Simple use case that delegates to repository.
6
+ *
7
+ * Design Philosophy:
8
+ * - Use cases provide consistent error handling
9
+ * - Business logic layer between controllers and repositories
10
+ * - Return null for not found vs throwing error (configurable)
11
+ *
12
+ * @example
13
+ * const getProcess = new GetProcess({ processRepository });
14
+ * const process = await getProcess.execute(processId);
15
+ * // or
16
+ * const process = await getProcess.executeOrThrow(processId);
17
+ */
18
+ class GetProcess {
19
+ /**
20
+ * @param {Object} params
21
+ * @param {ProcessRepositoryInterface} params.processRepository - Repository for process data access
22
+ */
23
+ constructor({ processRepository }) {
24
+ if (!processRepository) {
25
+ throw new Error('processRepository is required');
26
+ }
27
+ this.processRepository = processRepository;
28
+ }
29
+
30
+ /**
31
+ * Execute the use case to get a process by ID
32
+ * @param {string} processId - Process ID to retrieve
33
+ * @returns {Promise<Object|null>} Process record or null if not found
34
+ * @throws {Error} If processId is invalid
35
+ */
36
+ async execute(processId) {
37
+ // Validate input
38
+ if (!processId || typeof processId !== 'string') {
39
+ throw new Error('processId must be a non-empty string');
40
+ }
41
+
42
+ // Delegate to repository
43
+ try {
44
+ const process = await this.processRepository.findById(processId);
45
+ return process;
46
+ } catch (error) {
47
+ throw new Error(`Failed to retrieve process: ${error.message}`);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Execute and throw if process not found
53
+ * @param {string} processId - Process ID to retrieve
54
+ * @returns {Promise<Object>} Process record
55
+ * @throws {Error} If process not found or retrieval fails
56
+ */
57
+ async executeOrThrow(processId) {
58
+ const process = await this.execute(processId);
59
+
60
+ if (!process) {
61
+ throw new Error(`Process not found: ${processId}`);
62
+ }
63
+
64
+ return process;
65
+ }
66
+
67
+ /**
68
+ * Get multiple processes by IDs
69
+ * @param {string[]} processIds - Array of process IDs
70
+ * @returns {Promise<Array>} Array of process records (excludes not found)
71
+ */
72
+ async executeMany(processIds) {
73
+ if (!Array.isArray(processIds)) {
74
+ throw new Error('processIds must be an array');
75
+ }
76
+
77
+ const processes = await Promise.all(
78
+ processIds.map(id => this.execute(id))
79
+ );
80
+
81
+ // Filter out nulls (not found)
82
+ return processes.filter(p => p !== null);
83
+ }
84
+ }
85
+
86
+ module.exports = { GetProcess };
87
+
@@ -0,0 +1,190 @@
1
+ /**
2
+ * GetProcess Use Case Tests
3
+ *
4
+ * Tests process retrieval with error handling.
5
+ */
6
+
7
+ const { GetProcess } = require('./get-process');
8
+
9
+ describe('GetProcess', () => {
10
+ let getProcessUseCase;
11
+ let mockProcessRepository;
12
+
13
+ beforeEach(() => {
14
+ mockProcessRepository = {
15
+ findById: jest.fn(),
16
+ };
17
+ getProcessUseCase = new GetProcess({
18
+ processRepository: mockProcessRepository,
19
+ });
20
+ });
21
+
22
+ describe('constructor', () => {
23
+ it('should require processRepository', () => {
24
+ expect(() => new GetProcess({})).toThrow('processRepository is required');
25
+ });
26
+
27
+ it('should initialize with processRepository', () => {
28
+ expect(getProcessUseCase.processRepository).toBe(mockProcessRepository);
29
+ });
30
+ });
31
+
32
+ describe('execute', () => {
33
+ const processId = 'process-123';
34
+ const mockProcess = {
35
+ id: processId,
36
+ userId: 'user-456',
37
+ integrationId: 'integration-789',
38
+ name: 'test-sync',
39
+ type: 'CRM_SYNC',
40
+ state: 'PROCESSING_BATCHES',
41
+ context: {
42
+ syncType: 'INITIAL',
43
+ totalRecords: 1000,
44
+ processedRecords: 500,
45
+ },
46
+ results: {
47
+ aggregateData: {
48
+ totalSynced: 480,
49
+ totalFailed: 20,
50
+ duration: 120000,
51
+ recordsPerSecond: 4.17,
52
+ },
53
+ },
54
+ createdAt: new Date('2024-01-01T10:00:00Z'),
55
+ updatedAt: new Date('2024-01-01T10:02:00Z'),
56
+ };
57
+
58
+ it('should retrieve a process by ID', async () => {
59
+ mockProcessRepository.findById.mockResolvedValue(mockProcess);
60
+
61
+ const result = await getProcessUseCase.execute(processId);
62
+
63
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith(processId);
64
+ expect(result).toEqual(mockProcess);
65
+ });
66
+
67
+ it('should return null if process not found', async () => {
68
+ mockProcessRepository.findById.mockResolvedValue(null);
69
+
70
+ const result = await getProcessUseCase.execute(processId);
71
+
72
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith(processId);
73
+ expect(result).toBeNull();
74
+ });
75
+
76
+ it('should throw error if processId is missing', async () => {
77
+ await expect(getProcessUseCase.execute(''))
78
+ .rejects.toThrow('processId must be a non-empty string');
79
+ });
80
+
81
+ it('should throw error if processId is not a string', async () => {
82
+ await expect(getProcessUseCase.execute(123))
83
+ .rejects.toThrow('processId must be a non-empty string');
84
+ });
85
+
86
+ it('should handle repository errors', async () => {
87
+ const repositoryError = new Error('Database connection failed');
88
+ mockProcessRepository.findById.mockRejectedValue(repositoryError);
89
+
90
+ await expect(getProcessUseCase.execute(processId))
91
+ .rejects.toThrow('Failed to retrieve process: Database connection failed');
92
+ });
93
+ });
94
+
95
+ describe('executeOrThrow', () => {
96
+ const processId = 'process-123';
97
+ const mockProcess = {
98
+ id: processId,
99
+ userId: 'user-456',
100
+ integrationId: 'integration-789',
101
+ name: 'test-sync',
102
+ type: 'CRM_SYNC',
103
+ state: 'COMPLETED',
104
+ };
105
+
106
+ it('should return process if found', async () => {
107
+ mockProcessRepository.findById.mockResolvedValue(mockProcess);
108
+
109
+ const result = await getProcessUseCase.executeOrThrow(processId);
110
+
111
+ expect(result).toEqual(mockProcess);
112
+ });
113
+
114
+ it('should throw error if process not found', async () => {
115
+ mockProcessRepository.findById.mockResolvedValue(null);
116
+
117
+ await expect(getProcessUseCase.executeOrThrow(processId))
118
+ .rejects.toThrow('Process not found: process-123');
119
+ });
120
+
121
+ it('should propagate repository errors', async () => {
122
+ const repositoryError = new Error('Database connection failed');
123
+ mockProcessRepository.findById.mockRejectedValue(repositoryError);
124
+
125
+ await expect(getProcessUseCase.executeOrThrow(processId))
126
+ .rejects.toThrow('Failed to retrieve process: Database connection failed');
127
+ });
128
+ });
129
+
130
+ describe('executeMany', () => {
131
+ const processIds = ['process-1', 'process-2', 'process-3'];
132
+ const mockProcesses = [
133
+ { id: 'process-1', name: 'sync-1', state: 'COMPLETED' },
134
+ { id: 'process-2', name: 'sync-2', state: 'PROCESSING' },
135
+ // process-3 will not be found
136
+ ];
137
+
138
+ it('should retrieve multiple processes', async () => {
139
+ mockProcessRepository.findById
140
+ .mockResolvedValueOnce(mockProcesses[0]) // process-1 found
141
+ .mockResolvedValueOnce(mockProcesses[1]) // process-2 found
142
+ .mockResolvedValueOnce(null); // process-3 not found
143
+
144
+ const result = await getProcessUseCase.executeMany(processIds);
145
+
146
+ expect(mockProcessRepository.findById).toHaveBeenCalledTimes(3);
147
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-1');
148
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-2');
149
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-3');
150
+
151
+ // Should return only found processes
152
+ expect(result).toEqual([mockProcesses[0], mockProcesses[1]]);
153
+ });
154
+
155
+ it('should return empty array if no processes found', async () => {
156
+ mockProcessRepository.findById
157
+ .mockResolvedValueOnce(null)
158
+ .mockResolvedValueOnce(null)
159
+ .mockResolvedValueOnce(null);
160
+
161
+ const result = await getProcessUseCase.executeMany(processIds);
162
+
163
+ expect(result).toEqual([]);
164
+ });
165
+
166
+ it('should throw error if processIds is not an array', async () => {
167
+ await expect(getProcessUseCase.executeMany('not-an-array'))
168
+ .rejects.toThrow('processIds must be an array');
169
+ });
170
+
171
+ it('should handle mixed success and failure', async () => {
172
+ const repositoryError = new Error('Database error');
173
+ mockProcessRepository.findById
174
+ .mockResolvedValueOnce(mockProcesses[0]) // process-1 found
175
+ .mockRejectedValueOnce(repositoryError) // process-2 error
176
+ .mockResolvedValueOnce(null); // process-3 not found
177
+
178
+ // Should propagate the repository error
179
+ await expect(getProcessUseCase.executeMany(processIds))
180
+ .rejects.toThrow('Failed to retrieve process: Database error');
181
+ });
182
+
183
+ it('should handle empty array', async () => {
184
+ const result = await getProcessUseCase.executeMany([]);
185
+
186
+ expect(mockProcessRepository.findById).not.toHaveBeenCalled();
187
+ expect(result).toEqual([]);
188
+ });
189
+ });
190
+ });
@@ -2,10 +2,18 @@ const { GetIntegrationsForUser } = require('./get-integrations-for-user');
2
2
  const { DeleteIntegrationForUser } = require('./delete-integration-for-user');
3
3
  const { CreateIntegration } = require('./create-integration');
4
4
  const { GetIntegration } = require('./get-integration');
5
+ const { CreateProcess } = require('./create-process');
6
+ const { UpdateProcessState } = require('./update-process-state');
7
+ const { UpdateProcessMetrics } = require('./update-process-metrics');
8
+ const { GetProcess } = require('./get-process');
5
9
 
6
10
  module.exports = {
7
11
  GetIntegrationsForUser,
8
12
  DeleteIntegrationForUser,
9
13
  CreateIntegration,
10
14
  GetIntegration,
15
+ CreateProcess,
16
+ UpdateProcessState,
17
+ UpdateProcessMetrics,
18
+ GetProcess,
11
19
  };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * UpdateProcessMetrics Use Case
3
+ *
4
+ * Updates process metrics, calculates aggregates, and computes estimated completion time.
5
+ * Optionally broadcasts progress via WebSocket service if provided.
6
+ *
7
+ * Design Philosophy:
8
+ * - Metrics are cumulative (add to existing counts)
9
+ * - Performance metrics calculated automatically (duration, records/sec)
10
+ * - ETA computed based on current progress
11
+ * - Error history limited to last 100 entries
12
+ * - WebSocket broadcasting is optional (DI pattern)
13
+ *
14
+ * @example
15
+ * const updateMetrics = new UpdateProcessMetrics({ processRepository, websocketService });
16
+ * await updateMetrics.execute(processId, {
17
+ * processed: 100,
18
+ * success: 95,
19
+ * errors: 5,
20
+ * errorDetails: [{ contactId: 'abc', error: 'Missing email', timestamp: '...' }]
21
+ * });
22
+ */
23
+ class UpdateProcessMetrics {
24
+ /**
25
+ * @param {Object} params
26
+ * @param {ProcessRepositoryInterface} params.processRepository - Repository for process data access
27
+ * @param {Object} [params.websocketService] - Optional WebSocket service for progress broadcasting
28
+ */
29
+ constructor({ processRepository, websocketService }) {
30
+ if (!processRepository) {
31
+ throw new Error('processRepository is required');
32
+ }
33
+ this.processRepository = processRepository;
34
+ this.websocketService = websocketService;
35
+ }
36
+
37
+ /**
38
+ * Execute the use case to update process metrics
39
+ * @param {string} processId - Process ID to update
40
+ * @param {Object} metricsUpdate - Metrics to add/update
41
+ * @param {number} [metricsUpdate.processed=0] - Number of records processed in this batch
42
+ * @param {number} [metricsUpdate.success=0] - Number of successful records
43
+ * @param {number} [metricsUpdate.errors=0] - Number of failed records
44
+ * @param {Array} [metricsUpdate.errorDetails=[]] - Error details array
45
+ * @returns {Promise<Object>} Updated process record
46
+ * @throws {Error} If process not found or update fails
47
+ */
48
+ async execute(processId, metricsUpdate) {
49
+ // Validate inputs
50
+ if (!processId || typeof processId !== 'string') {
51
+ throw new Error('processId must be a non-empty string');
52
+ }
53
+ if (!metricsUpdate || typeof metricsUpdate !== 'object') {
54
+ throw new Error('metricsUpdate must be an object');
55
+ }
56
+
57
+ // Retrieve current process
58
+ const process = await this.processRepository.findById(processId);
59
+ if (!process) {
60
+ throw new Error(`Process not found: ${processId}`);
61
+ }
62
+
63
+ // Get current context and results
64
+ const context = process.context || {};
65
+ const results = process.results || { aggregateData: {} };
66
+
67
+ // Initialize nested objects if not present
68
+ if (!results.aggregateData) {
69
+ results.aggregateData = {};
70
+ }
71
+
72
+ // Update context counters (cumulative)
73
+ context.processedRecords = (context.processedRecords || 0) + (metricsUpdate.processed || 0);
74
+
75
+ // Update results aggregates (cumulative)
76
+ results.aggregateData.totalSynced = (results.aggregateData.totalSynced || 0) + (metricsUpdate.success || 0);
77
+ results.aggregateData.totalFailed = (results.aggregateData.totalFailed || 0) + (metricsUpdate.errors || 0);
78
+
79
+ // Append error details (limited to last 100)
80
+ if (metricsUpdate.errorDetails && metricsUpdate.errorDetails.length > 0) {
81
+ results.aggregateData.errors = [
82
+ ...(results.aggregateData.errors || []),
83
+ ...metricsUpdate.errorDetails
84
+ ].slice(-100); // Keep only last 100 errors
85
+ }
86
+
87
+ // Calculate performance metrics
88
+ const startTime = new Date(context.startTime || process.createdAt);
89
+ const elapsed = Date.now() - startTime.getTime();
90
+ results.aggregateData.duration = elapsed;
91
+
92
+ if (elapsed > 0 && context.processedRecords > 0) {
93
+ results.aggregateData.recordsPerSecond = context.processedRecords / (elapsed / 1000);
94
+ } else {
95
+ results.aggregateData.recordsPerSecond = 0;
96
+ }
97
+
98
+ // Calculate ETA if we know total
99
+ if (context.totalRecords > 0 && context.processedRecords > 0) {
100
+ const remaining = context.totalRecords - context.processedRecords;
101
+ if (results.aggregateData.recordsPerSecond > 0) {
102
+ const etaMs = (remaining / results.aggregateData.recordsPerSecond) * 1000;
103
+ const eta = new Date(Date.now() + etaMs);
104
+ context.estimatedCompletion = eta.toISOString();
105
+ }
106
+ }
107
+
108
+ // Prepare updates
109
+ const updates = {
110
+ context,
111
+ results,
112
+ };
113
+
114
+ // Persist updates
115
+ let updatedProcess;
116
+ try {
117
+ updatedProcess = await this.processRepository.update(processId, updates);
118
+ } catch (error) {
119
+ throw new Error(`Failed to update process metrics: ${error.message}`);
120
+ }
121
+
122
+ // Broadcast progress via WebSocket (if service provided)
123
+ if (this.websocketService) {
124
+ await this._broadcastProgress(updatedProcess);
125
+ }
126
+
127
+ return updatedProcess;
128
+ }
129
+
130
+ /**
131
+ * Broadcast progress update via WebSocket
132
+ * @private
133
+ * @param {Object} process - Updated process record
134
+ */
135
+ async _broadcastProgress(process) {
136
+ try {
137
+ const context = process.context || {};
138
+ const results = process.results || { aggregateData: {} };
139
+ const aggregateData = results.aggregateData || {};
140
+
141
+ await this.websocketService.broadcast({
142
+ type: 'PROCESS_PROGRESS',
143
+ data: {
144
+ processId: process.id,
145
+ processName: process.name,
146
+ processType: process.type,
147
+ state: process.state,
148
+ processed: context.processedRecords || 0,
149
+ total: context.totalRecords || 0,
150
+ successCount: aggregateData.totalSynced || 0,
151
+ errorCount: aggregateData.totalFailed || 0,
152
+ recordsPerSecond: aggregateData.recordsPerSecond || 0,
153
+ estimatedCompletion: context.estimatedCompletion || null,
154
+ timestamp: new Date().toISOString(),
155
+ }
156
+ });
157
+ } catch (error) {
158
+ // Log but don't fail the update if WebSocket broadcast fails
159
+ console.error('Failed to broadcast process progress:', error);
160
+ }
161
+ }
162
+ }
163
+
164
+ module.exports = { UpdateProcessMetrics };
165
+