@friggframework/core 2.0.0-next.43 → 2.0.0-next.45
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.
- package/database/config.js +29 -1
- package/database/use-cases/test-encryption-use-case.js +6 -5
- package/docs/PROCESS_MANAGEMENT_QUEUE_SPEC.md +517 -0
- package/handlers/WEBHOOKS.md +653 -0
- package/handlers/backend-utils.js +118 -3
- package/handlers/integration-event-dispatcher.test.js +68 -0
- package/handlers/routers/integration-webhook-routers.js +67 -0
- package/handlers/routers/integration-webhook-routers.test.js +126 -0
- package/handlers/webhook-flow.integration.test.js +356 -0
- package/handlers/workers/integration-defined-workers.test.js +184 -0
- package/index.js +16 -0
- package/integrations/WEBHOOK-QUICKSTART.md +151 -0
- package/integrations/integration-base.js +74 -3
- package/integrations/repositories/process-repository-factory.js +46 -0
- package/integrations/repositories/process-repository-interface.js +90 -0
- package/integrations/repositories/process-repository-mongo.js +190 -0
- package/integrations/repositories/process-repository-postgres.js +217 -0
- package/integrations/tests/doubles/dummy-integration-class.js +1 -8
- package/integrations/use-cases/create-process.js +128 -0
- package/integrations/use-cases/create-process.test.js +178 -0
- package/integrations/use-cases/get-process.js +87 -0
- package/integrations/use-cases/get-process.test.js +190 -0
- package/integrations/use-cases/index.js +8 -0
- package/integrations/use-cases/update-process-metrics.js +201 -0
- package/integrations/use-cases/update-process-metrics.test.js +308 -0
- package/integrations/use-cases/update-process-state.js +119 -0
- package/integrations/use-cases/update-process-state.test.js +256 -0
- package/package.json +5 -5
- package/prisma-mongodb/schema.prisma +44 -0
- package/prisma-postgresql/schema.prisma +45 -0
- package/queues/queuer-util.js +10 -0
- package/user/repositories/user-repository-mongo.js +53 -12
- package/user/repositories/user-repository-postgres.js +53 -14
- package/user/tests/use-cases/login-user.test.js +85 -5
- package/user/tests/user-password-encryption-isolation.test.js +237 -0
- package/user/tests/user-password-hashing.test.js +235 -0
- package/user/use-cases/login-user.js +1 -1
- package/user/user.js +2 -2
|
@@ -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,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
TODO:
|
|
3
|
+
This implementation contains a race condition in the `execute` method. When multiple concurrent processes call this method on the same process record, they'll each read the current state, modify it independently, and then save - potentially overwriting each other's changes.
|
|
4
|
+
|
|
5
|
+
For example:
|
|
6
|
+
```
|
|
7
|
+
Thread 1: reads process with totalSynced=100
|
|
8
|
+
Thread 2: reads process with totalSynced=100
|
|
9
|
+
Thread 1: adds 50 → writes totalSynced=150
|
|
10
|
+
Thread 2: adds 30 → writes totalSynced=130 (overwrites Thread 1's update!)
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Consider implementing one of these patterns:
|
|
14
|
+
1. Database transactions with row locking
|
|
15
|
+
2. Optimistic concurrency control with version numbers
|
|
16
|
+
3. Atomic update operations (e.g., `$inc` in MongoDB)
|
|
17
|
+
4. A FIFO queue for process updates (as described in the PROCESS_MANAGEMENT_QUEUE_SPEC.md)
|
|
18
|
+
|
|
19
|
+
The current approach will lead to lost updates and inconsistent metrics during concurrent processing.
|
|
20
|
+
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* UpdateProcessMetrics Use Case
|
|
25
|
+
*
|
|
26
|
+
* Updates process metrics, calculates aggregates, and computes estimated completion time.
|
|
27
|
+
* Optionally broadcasts progress via WebSocket service if provided.
|
|
28
|
+
*
|
|
29
|
+
* Design Philosophy:
|
|
30
|
+
* - Metrics are cumulative (add to existing counts)
|
|
31
|
+
* - Performance metrics calculated automatically (duration, records/sec)
|
|
32
|
+
* - ETA computed based on current progress
|
|
33
|
+
* - Error history limited to last 100 entries
|
|
34
|
+
* - WebSocket broadcasting is optional (DI pattern)
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* const updateMetrics = new UpdateProcessMetrics({ processRepository, websocketService });
|
|
38
|
+
* await updateMetrics.execute(processId, {
|
|
39
|
+
* processed: 100,
|
|
40
|
+
* success: 95,
|
|
41
|
+
* errors: 5,
|
|
42
|
+
* errorDetails: [{ contactId: 'abc', error: 'Missing email', timestamp: '...' }]
|
|
43
|
+
* });
|
|
44
|
+
*/
|
|
45
|
+
class UpdateProcessMetrics {
|
|
46
|
+
/**
|
|
47
|
+
* @param {Object} params
|
|
48
|
+
* @param {ProcessRepositoryInterface} params.processRepository - Repository for process data access
|
|
49
|
+
* @param {Object} [params.websocketService] - Optional WebSocket service for progress broadcasting
|
|
50
|
+
*/
|
|
51
|
+
constructor({ processRepository, websocketService }) {
|
|
52
|
+
if (!processRepository) {
|
|
53
|
+
throw new Error('processRepository is required');
|
|
54
|
+
}
|
|
55
|
+
this.processRepository = processRepository;
|
|
56
|
+
this.websocketService = websocketService;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Execute the use case to update process metrics
|
|
61
|
+
* @param {string} processId - Process ID to update
|
|
62
|
+
* @param {Object} metricsUpdate - Metrics to add/update
|
|
63
|
+
* @param {number} [metricsUpdate.processed=0] - Number of records processed in this batch
|
|
64
|
+
* @param {number} [metricsUpdate.success=0] - Number of successful records
|
|
65
|
+
* @param {number} [metricsUpdate.errors=0] - Number of failed records
|
|
66
|
+
* @param {Array} [metricsUpdate.errorDetails=[]] - Error details array
|
|
67
|
+
* @returns {Promise<Object>} Updated process record
|
|
68
|
+
* @throws {Error} If process not found or update fails
|
|
69
|
+
*/
|
|
70
|
+
async execute(processId, metricsUpdate) {
|
|
71
|
+
// Validate inputs
|
|
72
|
+
if (!processId || typeof processId !== 'string') {
|
|
73
|
+
throw new Error('processId must be a non-empty string');
|
|
74
|
+
}
|
|
75
|
+
if (!metricsUpdate || typeof metricsUpdate !== 'object') {
|
|
76
|
+
throw new Error('metricsUpdate must be an object');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Retrieve current process
|
|
80
|
+
const process = await this.processRepository.findById(processId);
|
|
81
|
+
if (!process) {
|
|
82
|
+
throw new Error(`Process not found: ${processId}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Get current context and results
|
|
86
|
+
const context = process.context || {};
|
|
87
|
+
const results = process.results || { aggregateData: {} };
|
|
88
|
+
|
|
89
|
+
// Initialize nested objects if not present
|
|
90
|
+
if (!results.aggregateData) {
|
|
91
|
+
results.aggregateData = {};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Update context counters (cumulative)
|
|
95
|
+
context.processedRecords =
|
|
96
|
+
(context.processedRecords || 0) + (metricsUpdate.processed || 0);
|
|
97
|
+
|
|
98
|
+
// Update results aggregates (cumulative)
|
|
99
|
+
results.aggregateData.totalSynced =
|
|
100
|
+
(results.aggregateData.totalSynced || 0) +
|
|
101
|
+
(metricsUpdate.success || 0);
|
|
102
|
+
results.aggregateData.totalFailed =
|
|
103
|
+
(results.aggregateData.totalFailed || 0) +
|
|
104
|
+
(metricsUpdate.errors || 0);
|
|
105
|
+
|
|
106
|
+
// Append error details (limited to last 100)
|
|
107
|
+
if (
|
|
108
|
+
metricsUpdate.errorDetails &&
|
|
109
|
+
metricsUpdate.errorDetails.length > 0
|
|
110
|
+
) {
|
|
111
|
+
results.aggregateData.errors = [
|
|
112
|
+
...(results.aggregateData.errors || []),
|
|
113
|
+
...metricsUpdate.errorDetails,
|
|
114
|
+
].slice(-100); // Keep only last 100 errors
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Calculate performance metrics
|
|
118
|
+
const startTime = new Date(context.startTime || process.createdAt);
|
|
119
|
+
const elapsed = Date.now() - startTime.getTime();
|
|
120
|
+
results.aggregateData.duration = elapsed;
|
|
121
|
+
|
|
122
|
+
if (elapsed > 0 && context.processedRecords > 0) {
|
|
123
|
+
results.aggregateData.recordsPerSecond =
|
|
124
|
+
context.processedRecords / (elapsed / 1000);
|
|
125
|
+
} else {
|
|
126
|
+
results.aggregateData.recordsPerSecond = 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Calculate ETA if we know total
|
|
130
|
+
if (context.totalRecords > 0 && context.processedRecords > 0) {
|
|
131
|
+
const remaining = context.totalRecords - context.processedRecords;
|
|
132
|
+
if (results.aggregateData.recordsPerSecond > 0) {
|
|
133
|
+
const etaMs =
|
|
134
|
+
(remaining / results.aggregateData.recordsPerSecond) * 1000;
|
|
135
|
+
const eta = new Date(Date.now() + etaMs);
|
|
136
|
+
context.estimatedCompletion = eta.toISOString();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Prepare updates
|
|
141
|
+
const updates = {
|
|
142
|
+
context,
|
|
143
|
+
results,
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Persist updates
|
|
147
|
+
let updatedProcess;
|
|
148
|
+
try {
|
|
149
|
+
updatedProcess = await this.processRepository.update(
|
|
150
|
+
processId,
|
|
151
|
+
updates
|
|
152
|
+
);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`Failed to update process metrics: ${error.message}`
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Broadcast progress via WebSocket (if service provided)
|
|
160
|
+
if (this.websocketService) {
|
|
161
|
+
await this._broadcastProgress(updatedProcess);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return updatedProcess;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Broadcast progress update via WebSocket
|
|
169
|
+
* @private
|
|
170
|
+
* @param {Object} process - Updated process record
|
|
171
|
+
*/
|
|
172
|
+
async _broadcastProgress(process) {
|
|
173
|
+
try {
|
|
174
|
+
const context = process.context || {};
|
|
175
|
+
const results = process.results || { aggregateData: {} };
|
|
176
|
+
const aggregateData = results.aggregateData || {};
|
|
177
|
+
|
|
178
|
+
await this.websocketService.broadcast({
|
|
179
|
+
type: 'PROCESS_PROGRESS',
|
|
180
|
+
data: {
|
|
181
|
+
processId: process.id,
|
|
182
|
+
processName: process.name,
|
|
183
|
+
processType: process.type,
|
|
184
|
+
state: process.state,
|
|
185
|
+
processed: context.processedRecords || 0,
|
|
186
|
+
total: context.totalRecords || 0,
|
|
187
|
+
successCount: aggregateData.totalSynced || 0,
|
|
188
|
+
errorCount: aggregateData.totalFailed || 0,
|
|
189
|
+
recordsPerSecond: aggregateData.recordsPerSecond || 0,
|
|
190
|
+
estimatedCompletion: context.estimatedCompletion || null,
|
|
191
|
+
timestamp: new Date().toISOString(),
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
} catch (error) {
|
|
195
|
+
// Log but don't fail the update if WebSocket broadcast fails
|
|
196
|
+
console.error('Failed to broadcast process progress:', error);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = { UpdateProcessMetrics };
|