-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_queue.js
More file actions
166 lines (140 loc) · 3.89 KB
/
Copy pathtask_queue.js
File metadata and controls
166 lines (140 loc) · 3.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
* Simple Task Queue with Concurrency Control
* Prevents memory leaks from unbounded process spawning
*
* Problem: Unlimited concurrent spawn = OOM at scale
* Solution: Queue with max concurrency limit
* Benefit: Stable memory, no process leak
*/
const { spawn } = require('child_process');
class TaskQueue {
constructor(maxConcurrency = 4) {
this.maxConcurrency = maxConcurrency;
this.activeCount = 0;
this.queue = [];
this.stats = {
totalProcessed: 0,
totalQueued: 0,
totalErrors: 0,
peakActive: 0,
peakQueueSize: 0
};
}
/**
* Execute a Python process with concurrency control
* If at max concurrency, queues the request
*/
async execute(args, timeout = 30000) {
return new Promise((resolve, reject) => {
const task = { args, timeout, resolve, reject, createdAt: Date.now() };
if (this.activeCount < this.maxConcurrency) {
this._executeTask(task);
} else {
this.queue.push(task);
this.stats.totalQueued++;
if (this.queue.length > this.stats.peakQueueSize) {
this.stats.peakQueueSize = this.queue.length;
}
// Log queue buildup if large
if (this.queue.length % 5 === 0) {
console.log(`[TaskQueue] Queue size: ${this.queue.length}, Active: ${this.activeCount}`);
}
}
});
}
/**
* Execute a single task (spawns Python process)
*/
_executeTask(task) {
this.activeCount++;
if (this.activeCount > this.stats.peakActive) {
this.stats.peakActive = this.activeCount;
}
const python = spawn('python3', task.args, {
stdio: ['pipe', 'pipe', 'pipe']
});
let output = '';
let errorOutput = '';
let completed = false;
// Handle stdout
python.stdout.on('data', (chunk) => {
output += chunk.toString();
});
// Handle stderr
python.stderr.on('data', (chunk) => {
errorOutput += chunk.toString();
});
// Timeout handler
const timeoutHandle = setTimeout(() => {
if (!completed) {
completed = true;
python.kill();
this._taskComplete(task, new Error('Process timeout'), null);
}
}, task.timeout);
// Process close handler
python.on('close', (code) => {
clearTimeout(timeoutHandle);
if (!completed) {
completed = true;
if (code === 0) {
this._taskComplete(task, null, output.trim());
} else {
const error = new Error(errorOutput.trim() || `Process exited with code ${code}`);
this._taskComplete(task, error, null);
}
}
});
// Process error handler
python.on('error', (error) => {
clearTimeout(timeoutHandle);
if (!completed) {
completed = true;
this._taskComplete(task, error, null);
}
});
}
/**
* Handle task completion and process next queued task
*/
_taskComplete(task, error, output) {
this.activeCount--;
this.stats.totalProcessed++;
if (error) {
this.stats.totalErrors++;
task.reject(error);
} else {
task.resolve(output);
}
// Process next queued task if any
if (this.queue.length > 0) {
const nextTask = this.queue.shift();
this._executeTask(nextTask);
}
}
/**
* Get queue statistics
*/
getStats() {
return {
...this.stats,
activeProcesses: this.activeCount,
queuedTasks: this.queue.length,
maxConcurrency: this.maxConcurrency,
utilizationPercent: Math.round((this.activeCount / this.maxConcurrency) * 100)
};
}
/**
* Clear queue (reject all pending tasks)
*/
clearQueue(reason = 'Queue cleared') {
const count = this.queue.length;
const error = new Error(reason);
for (const task of this.queue) {
task.reject(error);
}
this.queue = [];
return count;
}
}
module.exports = TaskQueue;