Skip to content

Commit 4d3c672

Browse files
committed
cleanup promises
1 parent de4c1b1 commit 4d3c672

File tree

3 files changed

+95
-86
lines changed

3 files changed

+95
-86
lines changed

.eslintrc.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
],
2020
"no-plusplus": "off",
2121
"import/extensions": "off",
22-
"no-restricted-syntax": "off"
22+
"no-restricted-syntax": "off",
23+
"no-param-reassign": "off"
2324
}
2425
}

src/metrics/metrics-utils.ts

Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -157,47 +157,6 @@ export function percentageChange(newValue: number, oldValue: number): string {
157157
return (((newValue - oldValue) / oldValue) * 100).toFixed(1);
158158
}
159159

160-
/**
161-
* Print summary statistics
162-
* @param {TaskMetrics[]} taskMetrics Array of task metrics
163-
* @param {string} metricsDir Directory where metrics are stored
164-
*/
165-
export function printSummaryStatistics(
166-
taskMetrics: TaskMetrics[],
167-
metricsDir: string,
168-
): void {
169-
if (!taskMetrics?.length) {
170-
logger.info('No metrics to display');
171-
return;
172-
}
173-
174-
const controlTasks = taskMetrics.filter((t) => t.mode === 'control');
175-
const mcpTasks = taskMetrics.filter((t) => t.mode === 'mcp');
176-
177-
logger.info('\nExtracted Metrics Summary:');
178-
logger.info('-------------------------');
179-
logger.info(`Total tasks processed: ${taskMetrics.length}`);
180-
logger.info(`Control tasks: ${controlTasks.length}`);
181-
logger.info(`MCP tasks: ${mcpTasks.length}`);
182-
183-
logger.info('\nTask Details:');
184-
taskMetrics.forEach((task) => {
185-
logger.info(
186-
`Task ${task.taskId ?? 'unknown'} (${task.mode ?? 'unknown'}): duration=${(
187-
(task.duration ?? 0) / 1000
188-
).toFixed(
189-
1,
190-
)}s, interactions=${task.interactions ?? 0}, apiCalls=${task.apiCalls ?? 0}, tokens=${task.tokensIn ?? 0}`,
191-
);
192-
});
193-
194-
if (controlTasks.length > 0 && mcpTasks.length > 0) {
195-
printPerformanceComparison(controlTasks, mcpTasks);
196-
}
197-
198-
logger.info(`Summary file generated at: ${metricsDir}/summary.json`);
199-
}
200-
201160
/**
202161
* Print performance comparison between control and MCP tasks
203162
* @param controlTasks Control task metrics
@@ -261,6 +220,47 @@ export function printPerformanceComparison(
261220
);
262221
}
263222

223+
/**
224+
* Print summary statistics
225+
* @param {TaskMetrics[]} taskMetrics Array of task metrics
226+
* @param {string} metricsDir Directory where metrics are stored
227+
*/
228+
export function printSummaryStatistics(
229+
taskMetrics: TaskMetrics[],
230+
metricsDir: string,
231+
): void {
232+
if (!taskMetrics?.length) {
233+
logger.info('No metrics to display');
234+
return;
235+
}
236+
237+
const controlTasks = taskMetrics.filter((t) => t.mode === 'control');
238+
const mcpTasks = taskMetrics.filter((t) => t.mode === 'mcp');
239+
240+
logger.info('\nExtracted Metrics Summary:');
241+
logger.info('-------------------------');
242+
logger.info(`Total tasks processed: ${taskMetrics.length}`);
243+
logger.info(`Control tasks: ${controlTasks.length}`);
244+
logger.info(`MCP tasks: ${mcpTasks.length}`);
245+
246+
logger.info('\nTask Details:');
247+
taskMetrics.forEach((task) => {
248+
logger.info(
249+
`Task ${task.taskId ?? 'unknown'} (${task.mode ?? 'unknown'}): duration=${(
250+
(task.duration ?? 0) / 1000
251+
).toFixed(
252+
1,
253+
)}s, interactions=${task.interactions ?? 0}, apiCalls=${task.apiCalls ?? 0}, tokens=${task.tokensIn ?? 0}`,
254+
);
255+
});
256+
257+
if (controlTasks.length > 0 && mcpTasks.length > 0) {
258+
printPerformanceComparison(controlTasks, mcpTasks);
259+
}
260+
261+
logger.info(`Summary file generated at: ${metricsDir}/summary.json`);
262+
}
263+
264264
/**
265265
* Normalize a metric by ensuring all optional fields have default values
266266
* @param metric The metric to normalize

src/metrics/summary-generator.ts

Lines changed: 52 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -104,49 +104,45 @@ class SummaryGenerator {
104104

105105
const successfulWrites: string[] = [];
106106
const failedWrites: string[] = [];
107+
const tasksDir = path.join(this.metricsDir, 'tasks');
108+
try {
109+
await fs.mkdir(tasksDir, { recursive: true });
110+
} catch (mkdirError) {
111+
logger.warn(
112+
`Could not create tasks directory: ${(mkdirError as Error).message}`,
113+
);
114+
}
107115

108-
for (const metric of taskMetrics) {
109-
try {
110-
// Include directoryId in the filename for better identification
111-
// If directoryId is empty, use the startTime as a fallback
112-
const directoryId =
113-
metric.directoryId ??
114-
metric.startTime?.toString() ??
115-
Date.now().toString();
116-
const filename = `${metric.mode ?? 'unknown'}_task${metric.taskId ?? 0}_${directoryId}.json`;
117-
const tasksDir = path.join(this.metricsDir, 'tasks');
118-
119-
// Ensure tasks directory exists
116+
await Promise.all(
117+
taskMetrics.map(async (metric) => {
120118
try {
121-
await fs.mkdir(tasksDir, { recursive: true });
122-
} catch (mkdirError) {
123-
logger.warn(
124-
`Could not create tasks directory: ${(mkdirError as Error).message}`,
119+
const directoryId =
120+
metric.directoryId ??
121+
metric.startTime?.toString() ??
122+
Date.now().toString();
123+
const filename = `${metric.mode ?? 'unknown'}_task${metric.taskId ?? 0}_${directoryId}.json`;
124+
const filePath = path.join(tasksDir, filename);
125+
126+
logger.info(
127+
`Writing metric file for task ${metric.taskId} with ${metric.apiCalls ?? 0} API calls`,
125128
);
126-
}
127129

128-
const filePath = path.join(tasksDir, filename);
129-
130-
// Log the metric before writing to help debug
131-
logger.info(
132-
`Writing metric file for task ${metric.taskId} with ${metric.apiCalls ?? 0} API calls`,
133-
);
134-
135-
const payload = JSON.stringify(
136-
convertTaskMetricToFilePayload(metric),
137-
null,
138-
2,
139-
);
140-
await fs.writeFile(filePath, payload);
130+
const payload = JSON.stringify(
131+
convertTaskMetricToFilePayload(metric),
132+
null,
133+
2,
134+
);
135+
await fs.writeFile(filePath, payload);
141136

142-
successfulWrites.push(filename);
143-
} catch (error) {
144-
logger.error(
145-
`Error writing metric file for task ${metric.taskId}: ${(error as Error).message}`,
146-
);
147-
failedWrites.push(`task${metric.taskId ?? 0}`);
148-
}
149-
}
137+
successfulWrites.push(filename);
138+
} catch (error) {
139+
logger.error(
140+
`Error writing metric file for task ${metric.taskId}: ${(error as Error).message}`,
141+
);
142+
failedWrites.push(`task${metric.taskId ?? 0}`);
143+
}
144+
}),
145+
);
150146

151147
if (failedWrites.length > 0) {
152148
return {
@@ -209,21 +205,33 @@ class SummaryGenerator {
209205
const allMetrics: TaskMetrics[] = [];
210206
const failedFiles: string[] = [];
211207

212-
for (const file of metricFiles) {
208+
const readPromises = metricFiles.map(async (file) => {
213209
const filePath = path.join(this.metricsDir, 'tasks', file);
214210
try {
215211
const fileContent = await fs.readFile(filePath, 'utf8');
216212
const metric = JSON.parse(fileContent);
217-
218-
// Convert to the format expected by the summary
219-
allMetrics.push(convertFileMetricToTaskMetric(metric));
213+
return {
214+
success: true,
215+
metric: convertFileMetricToTaskMetric(metric),
216+
file,
217+
};
220218
} catch (error) {
221219
logger.error(
222220
`Error parsing metric file ${file}: ${(error as Error).message}`,
223221
);
224-
failedFiles.push(file);
222+
return { success: false, file };
225223
}
226-
}
224+
});
225+
226+
const results = await Promise.all(readPromises);
227+
228+
results.forEach((result) => {
229+
if (result.success && result.metric) {
230+
allMetrics.push(result.metric);
231+
} else {
232+
failedFiles.push(result.file);
233+
}
234+
});
227235

228236
if (allMetrics.length === 0) {
229237
return {

0 commit comments

Comments
 (0)