|
| 1 | +/* |
| 2 | + * Copyright 2025 the original author or authors. |
| 3 | + * <p> |
| 4 | + * Licensed under the Moderne Source Available License (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * <p> |
| 8 | + * https://docs.moderne.io/licensing/moderne-source-available-license |
| 9 | + * <p> |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +import * as fs from 'fs'; |
| 17 | +import * as rpc from "vscode-jsonrpc/node"; |
| 18 | +import {Cursor, isSourceFile, SourceFile} from "../../tree"; |
| 19 | + |
| 20 | +const CSV_HEADER = 'request,target,durationMs,memoryUsedBytes,memoryMaxBytes'; |
| 21 | + |
| 22 | +/** |
| 23 | + * Extracts the sourcePath from a tree object, either directly from a SourceFile |
| 24 | + * or by finding the nearest SourceFile via a cursor. |
| 25 | + * |
| 26 | + * @param tree The tree object to extract sourcePath from |
| 27 | + * @param cursor Optional cursor to find the nearest SourceFile |
| 28 | + * @returns The sourcePath or empty string if not found |
| 29 | + */ |
| 30 | +export function extractSourcePath(tree: any, cursor?: Cursor): string { |
| 31 | + if (isSourceFile(tree)) { |
| 32 | + return (tree as SourceFile).sourcePath || ''; |
| 33 | + } |
| 34 | + |
| 35 | + if (cursor) { |
| 36 | + const sourceFile = cursor.firstEnclosing(t => isSourceFile(t)); |
| 37 | + if (sourceFile) { |
| 38 | + return (sourceFile as SourceFile).sourcePath || ''; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return ''; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Initializes the metrics CSV file with a header if it doesn't already exist or is empty. |
| 47 | + * If the file already contains the correct header, this function is a no-op. |
| 48 | + * |
| 49 | + * @param metricsCsv The path to the CSV file for recording metrics |
| 50 | + * @param logger Optional logger for warnings |
| 51 | + */ |
| 52 | +export function initializeMetricsCsv(metricsCsv?: string, logger?: rpc.Logger): void { |
| 53 | + if (!metricsCsv) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + try { |
| 58 | + // Check if file exists and has content |
| 59 | + if (fs.existsSync(metricsCsv)) { |
| 60 | + const content = fs.readFileSync(metricsCsv, 'utf8'); |
| 61 | + const firstLine = content.split('\n')[0]; |
| 62 | + |
| 63 | + // If file already has the correct header, skip initialization |
| 64 | + if (firstLine.trim() === CSV_HEADER) { |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + // File exists but has incorrect header - warn and reset |
| 69 | + if (firstLine.trim()) { |
| 70 | + logger?.warn(`Metrics CSV file ${metricsCsv} has incorrect header. Expected '${CSV_HEADER}' but found '${firstLine.trim()}'. Resetting file.`); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + // Write header to new or empty file (overwrites existing file with incorrect header) |
| 75 | + fs.writeFileSync(metricsCsv, CSV_HEADER + '\n'); |
| 76 | + } catch (err) { |
| 77 | + console.error('Failed to initialize metrics CSV:', err); |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Internal function to wrap a handler with metrics recording. |
| 83 | + */ |
| 84 | +async function wrapWithMetrics<R>( |
| 85 | + handler: () => Promise<R>, |
| 86 | + target: { target: string }, |
| 87 | + request: string, |
| 88 | + metricsCsv?: string |
| 89 | +): Promise<R> { |
| 90 | + if (!metricsCsv) { |
| 91 | + // No metrics recording requested, just execute the handler |
| 92 | + return handler(); |
| 93 | + } |
| 94 | + |
| 95 | + const startTime = Date.now(); |
| 96 | + |
| 97 | + try { |
| 98 | + const result = await handler(); |
| 99 | + recordMetrics(metricsCsv, target.target, request, startTime); |
| 100 | + return result; |
| 101 | + } catch (error) { |
| 102 | + recordMetrics(metricsCsv, target.target, request, startTime); |
| 103 | + throw error; |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/** |
| 108 | + * Wraps an RPC request handler to record performance metrics to a CSV file. |
| 109 | + * |
| 110 | + * @param request The request type name (e.g., "Visit", "GetObject") |
| 111 | + * @param target A mutable object containing the target identifier for metrics |
| 112 | + * @param metricsCsv Optional path to the CSV file for recording metrics |
| 113 | + * @returns A function that wraps a request handler with metrics recording |
| 114 | + */ |
| 115 | +export function withMetrics<P, R>( |
| 116 | + request: string, |
| 117 | + target: { target: string }, |
| 118 | + metricsCsv?: string |
| 119 | +): (handler: (request: P) => Promise<R>) => (request: P) => Promise<R> { |
| 120 | + return (handler: (requestParam: P) => Promise<R>) => { |
| 121 | + return async (requestParam: P): Promise<R> => { |
| 122 | + return wrapWithMetrics(() => handler(requestParam), target, request, metricsCsv); |
| 123 | + }; |
| 124 | + }; |
| 125 | +} |
| 126 | + |
| 127 | +/** |
| 128 | + * Wraps an RPC request handler without parameters (RequestType0) to record performance metrics. |
| 129 | + * |
| 130 | + * @param request The request type name (e.g., "GetLanguages", "GetRecipes") |
| 131 | + * @param target A mutable object containing the target identifier for metrics |
| 132 | + * @param metricsCsv Optional path to the CSV file for recording metrics |
| 133 | + * @returns A function that wraps a request handler with metrics recording |
| 134 | + */ |
| 135 | +export function withMetrics0<R>( |
| 136 | + request: string, |
| 137 | + target: { target: string }, |
| 138 | + metricsCsv?: string |
| 139 | +): (handler: () => Promise<R>) => (token: any) => Promise<R> { |
| 140 | + return (handler: () => Promise<R>) => { |
| 141 | + return async (_: any): Promise<R> => { |
| 142 | + return wrapWithMetrics(handler, target, request, metricsCsv); |
| 143 | + }; |
| 144 | + }; |
| 145 | +} |
| 146 | + |
| 147 | +function recordMetrics( |
| 148 | + metricsCsv: string, |
| 149 | + target: string, |
| 150 | + request: string, |
| 151 | + startTime: number |
| 152 | +): void { |
| 153 | + const endTime = Date.now(); |
| 154 | + const memEnd = process.memoryUsage(); |
| 155 | + const durationMs = endTime - startTime; |
| 156 | + |
| 157 | + const memoryUsedBytes = memEnd.heapUsed; |
| 158 | + const memoryMaxBytes = memEnd.heapTotal; |
| 159 | + |
| 160 | + const csvRow = `${request},${target},${durationMs},${memoryUsedBytes},${memoryMaxBytes}\n`; |
| 161 | + |
| 162 | + try { |
| 163 | + fs.appendFileSync(metricsCsv, csvRow); |
| 164 | + } catch (err) { |
| 165 | + console.error('Failed to write metrics to CSV:', err); |
| 166 | + } |
| 167 | +} |
0 commit comments