@omnitron-dev/testing 0.4.1 → 0.4.3
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/dist/async/deferred.d.ts +15 -0
- package/dist/async/deferred.js +35 -0
- package/dist/async/deferred.js.map +1 -0
- package/dist/async/events.d.ts +32 -0
- package/dist/async/events.js +176 -0
- package/dist/async/events.js.map +1 -0
- package/dist/async/index.d.ts +5 -0
- package/dist/async/index.js +6 -0
- package/dist/async/index.js.map +1 -0
- package/dist/async/mock-timer.d.ts +19 -0
- package/dist/async/mock-timer.js +87 -0
- package/dist/async/mock-timer.js.map +1 -0
- package/dist/async/retry.d.ts +8 -0
- package/dist/async/retry.js +36 -0
- package/dist/async/retry.js.map +1 -0
- package/dist/async/wait.d.ts +10 -0
- package/dist/async/wait.js +35 -0
- package/dist/async/wait.js.map +1 -0
- package/dist/docker/database-manager.d.ts +22 -0
- package/dist/docker/database-manager.js +97 -0
- package/dist/docker/database-manager.js.map +1 -0
- package/dist/docker/docker-test-manager.d.ts +44 -0
- package/dist/docker/docker-test-manager.js +805 -0
- package/dist/docker/docker-test-manager.js.map +1 -0
- package/dist/docker/index.d.ts +4 -0
- package/dist/docker/index.js +4 -0
- package/dist/docker/index.js.map +1 -0
- package/dist/docker/redis-manager.d.ts +12 -0
- package/dist/docker/redis-manager.js +453 -0
- package/dist/docker/redis-manager.js.map +1 -0
- package/dist/docker/types.d.ts +103 -0
- package/dist/docker/types.js +2 -0
- package/dist/docker/types.js.map +1 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +28 -0
- package/dist/errors.js.map +1 -0
- package/dist/helpers/assertions.d.ts +6 -0
- package/dist/helpers/assertions.js +37 -0
- package/dist/helpers/assertions.js.map +1 -0
- package/dist/helpers/console.d.ts +1 -0
- package/dist/helpers/console.js +23 -0
- package/dist/helpers/console.js.map +1 -0
- package/dist/helpers/index.d.ts +3 -0
- package/dist/helpers/index.js +4 -0
- package/dist/helpers/index.js.map +1 -0
- package/dist/helpers/temp-dir.d.ts +2 -0
- package/dist/helpers/temp-dir.js +13 -0
- package/dist/helpers/temp-dir.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/performance/index.d.ts +2 -0
- package/dist/performance/index.js +3 -0
- package/dist/performance/index.js.map +1 -0
- package/dist/performance/memory-detector.d.ts +9 -0
- package/dist/performance/memory-detector.js +61 -0
- package/dist/performance/memory-detector.js.map +1 -0
- package/dist/performance/perf-timer.d.ts +9 -0
- package/dist/performance/perf-timer.js +49 -0
- package/dist/performance/perf-timer.js.map +1 -0
- package/dist/titan/container-utils.d.ts +20 -0
- package/dist/titan/container-utils.js +78 -0
- package/dist/titan/container-utils.js.map +1 -0
- package/dist/titan/database/database-testing.module.d.ts +81 -0
- package/dist/titan/database/database-testing.module.js +419 -0
- package/dist/titan/database/database-testing.module.js.map +1 -0
- package/dist/titan/database/index.d.ts +3 -0
- package/dist/titan/database/index.js +4 -0
- package/dist/titan/database/index.js.map +1 -0
- package/dist/titan/database/test-utilities.d.ts +31 -0
- package/dist/titan/database/test-utilities.js +145 -0
- package/dist/titan/database/test-utilities.js.map +1 -0
- package/dist/titan/index.d.ts +14 -0
- package/dist/titan/index.js +10 -0
- package/dist/titan/index.js.map +1 -0
- package/dist/titan/nexus/index.d.ts +3 -0
- package/dist/titan/nexus/index.js +4 -0
- package/dist/titan/nexus/index.js.map +1 -0
- package/dist/titan/nexus/mock-provider.d.ts +41 -0
- package/dist/titan/nexus/mock-provider.js +127 -0
- package/dist/titan/nexus/mock-provider.js.map +1 -0
- package/dist/titan/nexus/test-container.d.ts +120 -0
- package/dist/titan/nexus/test-container.js +559 -0
- package/dist/titan/nexus/test-container.js.map +1 -0
- package/dist/titan/nexus/test-utilities.d.ts +135 -0
- package/dist/titan/nexus/test-utilities.js +484 -0
- package/dist/titan/nexus/test-utilities.js.map +1 -0
- package/dist/titan/pm/index.d.ts +4 -0
- package/dist/titan/pm/index.js +4 -0
- package/dist/titan/pm/index.js.map +1 -0
- package/dist/titan/pm/mock-process-spawner.d.ts +60 -0
- package/dist/titan/pm/mock-process-spawner.js +321 -0
- package/dist/titan/pm/mock-process-spawner.js.map +1 -0
- package/dist/titan/pm/mock-spawner.d.ts +27 -0
- package/dist/titan/pm/mock-spawner.js +99 -0
- package/dist/titan/pm/mock-spawner.js.map +1 -0
- package/dist/titan/pm/test-process-manager.d.ts +49 -0
- package/dist/titan/pm/test-process-manager.js +188 -0
- package/dist/titan/pm/test-process-manager.js.map +1 -0
- package/dist/titan/redis-test-utils.d.ts +33 -0
- package/dist/titan/redis-test-utils.js +414 -0
- package/dist/titan/redis-test-utils.js.map +1 -0
- package/dist/titan/test-application.d.ts +21 -0
- package/dist/titan/test-application.js +90 -0
- package/dist/titan/test-application.js.map +1 -0
- package/dist/titan/test-fixtures.d.ts +97 -0
- package/dist/titan/test-fixtures.js +223 -0
- package/dist/titan/test-fixtures.js.map +1 -0
- package/dist/titan/test-mocks.d.ts +29 -0
- package/dist/titan/test-mocks.js +262 -0
- package/dist/titan/test-mocks.js.map +1 -0
- package/dist/titan/test-module.d.ts +46 -0
- package/dist/titan/test-module.js +120 -0
- package/dist/titan/test-module.js.map +1 -0
- package/package.json +41 -4
- package/src/async/README.md +336 -0
- package/src/async/deferred.ts +98 -0
- package/src/async/events.ts +386 -0
- package/src/async/index.ts +48 -0
- package/src/async/mock-timer.ts +220 -0
- package/src/async/retry.ts +118 -0
- package/src/async/wait.ts +151 -0
- package/src/docker/database-manager.ts +242 -0
- package/src/docker/docker-test-manager.ts +1186 -0
- package/src/docker/index.ts +48 -0
- package/src/docker/redis-manager.ts +738 -0
- package/src/docker/types.ts +216 -0
- package/src/errors.ts +31 -0
- package/src/helpers/assertions.ts +171 -0
- package/src/helpers/console.ts +74 -0
- package/src/helpers/index.ts +15 -0
- package/src/helpers/temp-dir.ts +50 -0
- package/src/index.ts +2 -0
- package/src/performance/index.ts +11 -0
- package/src/performance/memory-detector.ts +166 -0
- package/src/performance/perf-timer.ts +146 -0
- package/src/titan/container-utils.ts +128 -0
- package/src/titan/database/database-testing.module.ts +831 -0
- package/src/titan/database/index.ts +30 -0
- package/src/titan/database/test-utilities.ts +337 -0
- package/src/titan/index.ts +147 -0
- package/src/titan/nexus/index.ts +3 -0
- package/src/titan/nexus/mock-provider.ts +189 -0
- package/src/titan/nexus/test-container.ts +887 -0
- package/src/titan/nexus/test-utilities.ts +796 -0
- package/src/titan/pm/index.ts +22 -0
- package/src/titan/pm/mock-process-spawner.ts +481 -0
- package/src/titan/pm/mock-spawner.ts +156 -0
- package/src/titan/pm/test-process-manager.ts +345 -0
- package/src/titan/redis-test-utils.ts +566 -0
- package/src/titan/test-application.ts +154 -0
- package/src/titan/test-fixtures.ts +304 -0
- package/src/titan/test-mocks.ts +336 -0
- package/src/titan/test-module.ts +232 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process Manager Testing Utilities
|
|
3
|
+
*
|
|
4
|
+
* Testing utilities for Titan Process Manager including mock spawners
|
|
5
|
+
* and test process manager with simulation capabilities.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// Export test process manager
|
|
9
|
+
export { TestProcessManager, createTestProcessManager } from './test-process-manager.js';
|
|
10
|
+
export type { ITestProcessManagerConfig, IOperationRecord } from './test-process-manager.js';
|
|
11
|
+
|
|
12
|
+
// Export mock spawner (simpler version)
|
|
13
|
+
export { MockProcessSpawner } from './mock-spawner.js';
|
|
14
|
+
|
|
15
|
+
// Export advanced mock process spawner
|
|
16
|
+
export {
|
|
17
|
+
MockWorker,
|
|
18
|
+
MockNetronClient,
|
|
19
|
+
MockWorkerHandle,
|
|
20
|
+
MockProcessSpawner as AdvancedMockProcessSpawner,
|
|
21
|
+
SimpleMockProcessSpawner,
|
|
22
|
+
} from './mock-process-spawner.js';
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mock Process Spawner for Testing
|
|
3
|
+
*
|
|
4
|
+
* Optimized mock spawner that runs processes in the same thread for fast testing.
|
|
5
|
+
* Implements the same interface as the real spawner for seamless switching.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { EventEmitter } from 'events';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { v4 as uuidv4 } from 'uuid';
|
|
11
|
+
import { Errors } from '@omnitron-dev/titan/errors';
|
|
12
|
+
import type { ProcessMethod } from '@omnitron-dev/titan/module/pm';
|
|
13
|
+
import type { ILogger } from '@omnitron-dev/titan/module/logger';
|
|
14
|
+
import type {
|
|
15
|
+
IProcessSpawner,
|
|
16
|
+
ISpawnOptions,
|
|
17
|
+
IWorkerHandle,
|
|
18
|
+
IProcessManagerConfig,
|
|
19
|
+
IProcessMetrics,
|
|
20
|
+
IHealthStatus,
|
|
21
|
+
} from '@omnitron-dev/titan/module/pm';
|
|
22
|
+
import { ProcessStatus } from '@omnitron-dev/titan/module/pm';
|
|
23
|
+
import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan/module/pm';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Mock worker that runs in the same thread
|
|
27
|
+
*/
|
|
28
|
+
export class MockWorker extends EventEmitter {
|
|
29
|
+
public readonly threadId = Math.floor(Math.random() * 10000);
|
|
30
|
+
public readonly pid = process.pid;
|
|
31
|
+
private instance: any;
|
|
32
|
+
private publicMethods = new Map<string, ProcessMethod>();
|
|
33
|
+
private _status: ProcessStatus = ProcessStatus.STARTING;
|
|
34
|
+
private metrics: IProcessMetrics = {
|
|
35
|
+
cpu: 0,
|
|
36
|
+
memory: 0,
|
|
37
|
+
requests: 0,
|
|
38
|
+
errors: 0,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
constructor(
|
|
42
|
+
public readonly id: string,
|
|
43
|
+
ProcessClass: new (...args: any[]) => any,
|
|
44
|
+
private readonly options: ISpawnOptions = {}
|
|
45
|
+
) {
|
|
46
|
+
super();
|
|
47
|
+
|
|
48
|
+
// Create instance with options
|
|
49
|
+
try {
|
|
50
|
+
this.instance = new ProcessClass(options.config || {});
|
|
51
|
+
} catch (error) {
|
|
52
|
+
// If instantiation fails, create a simple object
|
|
53
|
+
this.instance = {};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Extract and bind public methods
|
|
57
|
+
if (ProcessClass && ProcessClass.prototype) {
|
|
58
|
+
this.extractPublicMethods(ProcessClass);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Setup internal methods
|
|
62
|
+
this.setupInternalMethods();
|
|
63
|
+
|
|
64
|
+
// Emit ready immediately
|
|
65
|
+
setImmediate(() => {
|
|
66
|
+
this._status = ProcessStatus.RUNNING;
|
|
67
|
+
this.emit('message', { type: 'ready' });
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
get status(): ProcessStatus {
|
|
72
|
+
return this._status;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Extract public methods from the process class
|
|
77
|
+
*/
|
|
78
|
+
private extractPublicMethods(ProcessClass: new (...args: any[]) => any): void {
|
|
79
|
+
if (!ProcessClass || !ProcessClass.prototype) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const prototype = ProcessClass.prototype;
|
|
84
|
+
const propertyNames = Object.getOwnPropertyNames(prototype);
|
|
85
|
+
|
|
86
|
+
for (const propertyName of propertyNames) {
|
|
87
|
+
if (propertyName === 'constructor') continue;
|
|
88
|
+
|
|
89
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
|
|
90
|
+
if (!descriptor || typeof descriptor.value !== 'function') continue;
|
|
91
|
+
|
|
92
|
+
// Check if method is marked as public (supports both PM decorators and core @Method decorator)
|
|
93
|
+
const pmMetadata = Reflect.getMetadata(PROCESS_METHOD_METADATA_KEY, prototype, propertyName);
|
|
94
|
+
const corePublic = Reflect.getMetadata('public', prototype, propertyName);
|
|
95
|
+
|
|
96
|
+
if (pmMetadata?.public || corePublic) {
|
|
97
|
+
this.publicMethods.set(propertyName, descriptor.value.bind(this.instance));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Add special methods if they exist
|
|
102
|
+
const specialMethods = ['checkHealth', 'onShutdown', 'getMetrics'];
|
|
103
|
+
for (const method of specialMethods) {
|
|
104
|
+
if (typeof this.instance[method] === 'function') {
|
|
105
|
+
this.publicMethods.set(method, this.instance[method]!.bind(this.instance));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Setup internal process management methods
|
|
112
|
+
*/
|
|
113
|
+
private setupInternalMethods(): void {
|
|
114
|
+
this.publicMethods.set('__getProcessMetrics', async (): Promise<IProcessMetrics> => {
|
|
115
|
+
if (this.metrics) this.metrics.requests = (this.metrics.requests || 0) + 1;
|
|
116
|
+
return {
|
|
117
|
+
...(this.metrics || { cpu: 0, memory: 0, requests: 0, errors: 0 }),
|
|
118
|
+
cpu: Math.random() * 100,
|
|
119
|
+
memory: process.memoryUsage().heapUsed,
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
this.publicMethods.set('__getProcessHealth', async (): Promise<IHealthStatus> => {
|
|
124
|
+
if (this.publicMethods.has('checkHealth')) {
|
|
125
|
+
const result = await this.publicMethods.get('checkHealth')!();
|
|
126
|
+
// Normalize the result to IHealthStatus format
|
|
127
|
+
if (result && typeof result === 'object') {
|
|
128
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
129
|
+
const healthResult = result as any;
|
|
130
|
+
// If it already has the correct format, return as-is
|
|
131
|
+
if ('status' in healthResult && 'checks' in healthResult && 'timestamp' in healthResult) {
|
|
132
|
+
return healthResult as IHealthStatus;
|
|
133
|
+
}
|
|
134
|
+
// Convert from test format to IHealthStatus
|
|
135
|
+
const status = healthResult.status || (this._status === ProcessStatus.RUNNING ? 'healthy' : 'unhealthy');
|
|
136
|
+
return {
|
|
137
|
+
status: status as 'healthy' | 'degraded' | 'unhealthy',
|
|
138
|
+
checks: healthResult.checks || [
|
|
139
|
+
{
|
|
140
|
+
name: 'checkHealth',
|
|
141
|
+
status: status === 'healthy' ? 'pass' : 'fail',
|
|
142
|
+
message: healthResult.message,
|
|
143
|
+
details: healthResult.details,
|
|
144
|
+
},
|
|
145
|
+
],
|
|
146
|
+
timestamp: healthResult.timestamp || Date.now(),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
status: this._status === ProcessStatus.RUNNING ? 'healthy' : 'unhealthy',
|
|
153
|
+
checks: [
|
|
154
|
+
{
|
|
155
|
+
name: 'mock',
|
|
156
|
+
status: 'pass',
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
timestamp: Date.now(),
|
|
160
|
+
};
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
this.publicMethods.set('__destroy', async (): Promise<void> => {
|
|
164
|
+
await this.terminate();
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Call a method on the mock worker
|
|
170
|
+
*/
|
|
171
|
+
async callMethod(methodName: string, args: unknown[]): Promise<unknown> {
|
|
172
|
+
const method = this.publicMethods.get(methodName);
|
|
173
|
+
if (!method) {
|
|
174
|
+
if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
|
|
175
|
+
throw Errors.notFound('Method', methodName);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
try {
|
|
179
|
+
if (this.metrics) this.metrics.requests = (this.metrics.requests || 0) + 1;
|
|
180
|
+
const result = method(...args);
|
|
181
|
+
|
|
182
|
+
// If the method returns a promise, await it
|
|
183
|
+
if (result && typeof result === 'object' && 'then' in result && typeof (result as Promise<unknown>).then === 'function') {
|
|
184
|
+
return await (result as Promise<unknown>);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Return as-is for async generators and other values
|
|
188
|
+
return result;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Send message to the mock worker
|
|
197
|
+
*/
|
|
198
|
+
postMessage(message: any): void {
|
|
199
|
+
setImmediate(() => {
|
|
200
|
+
if (message.type === 'shutdown') {
|
|
201
|
+
this.terminate();
|
|
202
|
+
} else {
|
|
203
|
+
this.emit('message', { type: 'response', data: message });
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Terminate the mock worker
|
|
210
|
+
*/
|
|
211
|
+
async terminate(): Promise<void> {
|
|
212
|
+
this._status = ProcessStatus.STOPPING;
|
|
213
|
+
|
|
214
|
+
// Call onShutdown if available
|
|
215
|
+
if (this.publicMethods.has('onShutdown')) {
|
|
216
|
+
try {
|
|
217
|
+
await this.publicMethods.get('onShutdown')!();
|
|
218
|
+
} catch (error) {
|
|
219
|
+
// Ignore shutdown errors
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
this._status = ProcessStatus.STOPPED;
|
|
224
|
+
this.emit('exit', 0);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Mock Netron client for testing
|
|
230
|
+
*/
|
|
231
|
+
export class MockNetronClient {
|
|
232
|
+
private connected = false;
|
|
233
|
+
private worker: MockWorker;
|
|
234
|
+
|
|
235
|
+
constructor(
|
|
236
|
+
public readonly processId: string,
|
|
237
|
+
public readonly logger: ILogger,
|
|
238
|
+
worker: MockWorker
|
|
239
|
+
) {
|
|
240
|
+
this.worker = worker;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async start(): Promise<void> {
|
|
244
|
+
// Mock start
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async connect(url: string): Promise<void> {
|
|
248
|
+
this.connected = true;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async disconnect(): Promise<void> {
|
|
252
|
+
this.connected = false;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async stop(): Promise<void> {
|
|
256
|
+
await this.disconnect();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
isConnected(): boolean {
|
|
260
|
+
return this.connected;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async call(service: string, method: string, args: any[]): Promise<any> {
|
|
264
|
+
return this.worker.callMethod(method, args);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Add mockCall for compatibility
|
|
268
|
+
async mockCall(method: string, args: any[]): Promise<any> {
|
|
269
|
+
return this.worker.callMethod(method, args);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Mock worker handle implementation
|
|
275
|
+
*/
|
|
276
|
+
export class MockWorkerHandle implements IWorkerHandle {
|
|
277
|
+
public readonly proxy: any;
|
|
278
|
+
public readonly netronClient: MockNetronClient;
|
|
279
|
+
public readonly worker: MockWorker;
|
|
280
|
+
|
|
281
|
+
constructor(
|
|
282
|
+
public readonly id: string,
|
|
283
|
+
worker: MockWorker,
|
|
284
|
+
public readonly transportUrl: string,
|
|
285
|
+
public readonly serviceName: string,
|
|
286
|
+
public readonly serviceVersion: string,
|
|
287
|
+
private readonly logger: ILogger
|
|
288
|
+
) {
|
|
289
|
+
this.worker = worker;
|
|
290
|
+
// Create mock Netron client
|
|
291
|
+
this.netronClient = new MockNetronClient(id, logger, worker);
|
|
292
|
+
|
|
293
|
+
// Create proxy for method calls
|
|
294
|
+
this.proxy = new Proxy(
|
|
295
|
+
{},
|
|
296
|
+
{
|
|
297
|
+
get: (target, property: string | symbol) => {
|
|
298
|
+
// Handle control methods
|
|
299
|
+
if (property === '__processId') {
|
|
300
|
+
return this.id;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (property === '__destroy') {
|
|
304
|
+
return () => this.terminate();
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (property === '__getMetrics') {
|
|
308
|
+
return () => this.worker.callMethod('__getProcessMetrics', []);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (property === '__getHealth') {
|
|
312
|
+
return () => this.worker.callMethod('__getProcessHealth', []);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Handle Promise-like properties
|
|
316
|
+
if (property === 'then' || property === 'catch' || property === 'finally') {
|
|
317
|
+
return undefined;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Handle symbols
|
|
321
|
+
if (typeof property === 'symbol') {
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Convert property to string
|
|
326
|
+
const methodName = String(property);
|
|
327
|
+
|
|
328
|
+
// Check if this should be a streaming method
|
|
329
|
+
// Methods that include 'Stream' or start with 'stream' may return AsyncIterables
|
|
330
|
+
const isStreamMethod = methodName.startsWith('stream') || methodName.toLowerCase().includes('stream');
|
|
331
|
+
|
|
332
|
+
if (isStreamMethod) {
|
|
333
|
+
const workerInstance = this.worker;
|
|
334
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
335
|
+
return async (...args: any[]): Promise<any> => {
|
|
336
|
+
const result = await workerInstance.callMethod(methodName, args);
|
|
337
|
+
// If result is already an async iterable, return it directly
|
|
338
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
339
|
+
const anyResult = result as any;
|
|
340
|
+
if (anyResult && typeof anyResult[Symbol.asyncIterator] === 'function') {
|
|
341
|
+
return anyResult;
|
|
342
|
+
}
|
|
343
|
+
// If result is a sync iterable, convert to async
|
|
344
|
+
if (anyResult && typeof anyResult[Symbol.iterator] === 'function') {
|
|
345
|
+
return (async function* () {
|
|
346
|
+
yield* anyResult;
|
|
347
|
+
})();
|
|
348
|
+
}
|
|
349
|
+
// Otherwise return as normal async result
|
|
350
|
+
return result;
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Return async method wrapper
|
|
355
|
+
return async (...args: any[]) => this.worker.callMethod(methodName, args);
|
|
356
|
+
},
|
|
357
|
+
|
|
358
|
+
has: (target, property) => {
|
|
359
|
+
// Report that we have the special control methods
|
|
360
|
+
const controlMethods = ['__processId', '__destroy', '__getMetrics', '__getHealth'];
|
|
361
|
+
if (typeof property === 'string' && controlMethods.includes(property)) {
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
// All other methods are assumed to be available
|
|
365
|
+
return typeof property === 'string';
|
|
366
|
+
},
|
|
367
|
+
}
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
get status(): ProcessStatus {
|
|
372
|
+
return this.worker.status;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async terminate(): Promise<void> {
|
|
376
|
+
await this.worker.terminate();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
isAlive(): boolean {
|
|
380
|
+
return this.worker.status === ProcessStatus.RUNNING;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async send(message: any): Promise<void> {
|
|
384
|
+
this.worker.postMessage(message);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
onMessage(handler: (data: any) => void): void {
|
|
388
|
+
this.worker.on('message', handler);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Mock process spawner for testing
|
|
394
|
+
*/
|
|
395
|
+
export class MockProcessSpawner implements IProcessSpawner {
|
|
396
|
+
private workers = new Map<string, MockWorker>();
|
|
397
|
+
|
|
398
|
+
constructor(
|
|
399
|
+
private readonly logger: ILogger,
|
|
400
|
+
private readonly config: IProcessManagerConfig = {}
|
|
401
|
+
) {}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Spawn a mock process
|
|
405
|
+
*/
|
|
406
|
+
async spawn<T>(
|
|
407
|
+
processPathOrClass: string | (new (...args: any[]) => T),
|
|
408
|
+
options: ISpawnOptions = {}
|
|
409
|
+
): Promise<IWorkerHandle> {
|
|
410
|
+
const processId = options.processId || uuidv4();
|
|
411
|
+
|
|
412
|
+
let ProcessClass: new (...args: any[]) => T;
|
|
413
|
+
let serviceName: string;
|
|
414
|
+
|
|
415
|
+
if (typeof processPathOrClass === 'string') {
|
|
416
|
+
// For file paths, we need to load the module
|
|
417
|
+
// In mock spawner, we'll try to import it dynamically
|
|
418
|
+
try {
|
|
419
|
+
const module = await import(processPathOrClass);
|
|
420
|
+
if (module.default) {
|
|
421
|
+
ProcessClass = module.default;
|
|
422
|
+
} else {
|
|
423
|
+
const keys = Object.keys(module);
|
|
424
|
+
const firstKey = keys[0];
|
|
425
|
+
if (firstKey && module[firstKey]) {
|
|
426
|
+
ProcessClass = module[firstKey];
|
|
427
|
+
} else {
|
|
428
|
+
throw Errors.notFound('Default export', 'process file');
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
serviceName = options.name || path.basename(processPathOrClass, '.js');
|
|
432
|
+
} catch (error) {
|
|
433
|
+
// If import fails in test, create a simple mock class
|
|
434
|
+
ProcessClass = class MockProcess {
|
|
435
|
+
constructor() {}
|
|
436
|
+
} as any;
|
|
437
|
+
serviceName = options.name || 'MockProcess';
|
|
438
|
+
}
|
|
439
|
+
} else {
|
|
440
|
+
ProcessClass = processPathOrClass;
|
|
441
|
+
serviceName = options.name || ProcessClass.name;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const serviceVersion = options.version || '1.0.0';
|
|
445
|
+
const transportUrl = `mock://${processId}`;
|
|
446
|
+
|
|
447
|
+
// Create mock worker
|
|
448
|
+
const worker = new MockWorker(processId, ProcessClass, options);
|
|
449
|
+
this.workers.set(processId, worker);
|
|
450
|
+
|
|
451
|
+
// Create handle
|
|
452
|
+
const handle = new MockWorkerHandle(processId, worker, transportUrl, serviceName, serviceVersion, this.logger);
|
|
453
|
+
|
|
454
|
+
// Wait for ready
|
|
455
|
+
await new Promise<void>((resolve) => {
|
|
456
|
+
worker.once('message', (data) => {
|
|
457
|
+
if (data.type === 'ready') {
|
|
458
|
+
resolve();
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
return handle;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Cleanup spawner resources
|
|
468
|
+
*/
|
|
469
|
+
async cleanup(): Promise<void> {
|
|
470
|
+
// Terminate all workers
|
|
471
|
+
for (const [id, worker] of this.workers) {
|
|
472
|
+
await worker.terminate();
|
|
473
|
+
}
|
|
474
|
+
this.workers.clear();
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Export the old name for backward compatibility
|
|
480
|
+
*/
|
|
481
|
+
export { MockProcessSpawner as SimpleMockProcessSpawner };
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mock Process Spawner for Testing
|
|
3
|
+
*
|
|
4
|
+
* This spawner runs processes in the same thread for testing purposes.
|
|
5
|
+
* It maintains the same interface but doesn't actually spawn separate processes.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { EventEmitter } from 'events';
|
|
9
|
+
import { Netron } from '@omnitron-dev/titan/netron';
|
|
10
|
+
import { Errors } from '@omnitron-dev/titan/errors';
|
|
11
|
+
import type { ProcessMethod } from '@omnitron-dev/titan/module/pm';
|
|
12
|
+
import type { ILogger } from '@omnitron-dev/titan/module/logger';
|
|
13
|
+
import type { IProcessOptions, IProcessManagerConfig } from '@omnitron-dev/titan/module/pm';
|
|
14
|
+
import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan/module/pm';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Mock worker that runs in the same thread
|
|
18
|
+
*/
|
|
19
|
+
class MockWorker extends EventEmitter {
|
|
20
|
+
public threadId = Math.floor(Math.random() * 10000);
|
|
21
|
+
public pid = process.pid;
|
|
22
|
+
private instance: any;
|
|
23
|
+
private publicMethods: Map<string, ProcessMethod> = new Map();
|
|
24
|
+
|
|
25
|
+
constructor(ProcessClass: new (...args: any[]) => any) {
|
|
26
|
+
super();
|
|
27
|
+
|
|
28
|
+
// Create instance of the process class
|
|
29
|
+
this.instance = new ProcessClass();
|
|
30
|
+
|
|
31
|
+
// Extract public methods from metadata
|
|
32
|
+
const prototype = ProcessClass.prototype;
|
|
33
|
+
const propertyNames = Object.getOwnPropertyNames(prototype);
|
|
34
|
+
|
|
35
|
+
for (const propertyName of propertyNames) {
|
|
36
|
+
if (propertyName === 'constructor') continue;
|
|
37
|
+
|
|
38
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
|
|
39
|
+
if (!descriptor || typeof descriptor.value !== 'function') continue;
|
|
40
|
+
|
|
41
|
+
// Check if method is marked as public
|
|
42
|
+
const metadata = Reflect.getMetadata(PROCESS_METHOD_METADATA_KEY, prototype, propertyName);
|
|
43
|
+
if (metadata?.public) {
|
|
44
|
+
this.publicMethods.set(propertyName, descriptor.value.bind(this.instance));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Add health check method if it exists
|
|
49
|
+
if (typeof this.instance.checkHealth === 'function') {
|
|
50
|
+
this.publicMethods.set('checkHealth', this.instance.checkHealth.bind(this.instance));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Add internal methods
|
|
54
|
+
this.publicMethods.set('__getProcessMetrics', async () => ({
|
|
55
|
+
cpu: 0.1,
|
|
56
|
+
memory: process.memoryUsage().heapUsed,
|
|
57
|
+
requests: 0,
|
|
58
|
+
errors: 0,
|
|
59
|
+
uptime: process.uptime(),
|
|
60
|
+
}));
|
|
61
|
+
|
|
62
|
+
this.publicMethods.set('__getProcessHealth', async () => {
|
|
63
|
+
if (typeof this.instance.checkHealth === 'function') {
|
|
64
|
+
return await this.instance.checkHealth();
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
status: 'healthy' as const,
|
|
68
|
+
checks: [],
|
|
69
|
+
timestamp: Date.now(),
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Emit ready after a small delay
|
|
74
|
+
setImmediate(() => {
|
|
75
|
+
this.emit('message', { type: 'ready' });
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async callMethod(methodName: string, args: any[]): Promise<any> {
|
|
80
|
+
const method = this.publicMethods.get(methodName);
|
|
81
|
+
if (!method) {
|
|
82
|
+
throw Errors.notFound('Method', methodName);
|
|
83
|
+
}
|
|
84
|
+
return await method(...args);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
postMessage(message: any): void {
|
|
88
|
+
if (message.type === 'shutdown') {
|
|
89
|
+
this.emit('exit', 0);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
terminate(): Promise<number> {
|
|
94
|
+
this.emit('exit', 0);
|
|
95
|
+
return Promise.resolve(0);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Mock Process Spawner for testing
|
|
101
|
+
*/
|
|
102
|
+
export class MockProcessSpawner {
|
|
103
|
+
private mockWorkers = new Map<string, MockWorker>();
|
|
104
|
+
|
|
105
|
+
constructor(
|
|
106
|
+
private readonly logger: ILogger,
|
|
107
|
+
private readonly config: IProcessManagerConfig = {}
|
|
108
|
+
) {}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Spawn a mock process (runs in same thread)
|
|
112
|
+
*/
|
|
113
|
+
async spawn(
|
|
114
|
+
ProcessClass: new (...args: any[]) => any,
|
|
115
|
+
processId: string,
|
|
116
|
+
options: IProcessOptions
|
|
117
|
+
): Promise<{ worker: MockWorker; netron: Netron; transportUrl: string }> {
|
|
118
|
+
// Create mock worker
|
|
119
|
+
const worker = new MockWorker(ProcessClass);
|
|
120
|
+
this.mockWorkers.set(processId, worker);
|
|
121
|
+
|
|
122
|
+
// Create mock Netron that directly calls the worker
|
|
123
|
+
const netron = new Netron(this.logger as any, {
|
|
124
|
+
id: `mock-${processId}`,
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// Override Netron's call method to directly call the worker
|
|
128
|
+
(netron as any).mockCall = async (methodName: string, args: any[]) => worker.callMethod(methodName, args);
|
|
129
|
+
|
|
130
|
+
// Create a mock peer
|
|
131
|
+
(netron as any).peer = {
|
|
132
|
+
call: async (serviceName: string, methodName: string, args: any[]) => worker.callMethod(methodName, args),
|
|
133
|
+
expose: async () => {},
|
|
134
|
+
start: async () => {},
|
|
135
|
+
stop: async () => {},
|
|
136
|
+
connect: async () => {},
|
|
137
|
+
disconnect: async () => {},
|
|
138
|
+
listen: async () => {},
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const transportUrl = `mock://${processId}`;
|
|
142
|
+
|
|
143
|
+
return { worker, netron, transportUrl };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Clean up mock process
|
|
148
|
+
*/
|
|
149
|
+
async cleanup(processId: string): Promise<void> {
|
|
150
|
+
const worker = this.mockWorkers.get(processId);
|
|
151
|
+
if (worker) {
|
|
152
|
+
await worker.terminate();
|
|
153
|
+
this.mockWorkers.delete(processId);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|