utils.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /**
  2. * CodeGraph Utilities
  3. *
  4. * Common utility functions for memory management, concurrency, and batching.
  5. *
  6. * @module utils
  7. *
  8. * @example
  9. * ```typescript
  10. * import { Mutex, processInBatches, MemoryMonitor } from 'codegraph';
  11. *
  12. * // Use mutex for concurrent safety
  13. * const mutex = new Mutex();
  14. * await mutex.withLock(async () => {
  15. * await performCriticalOperation();
  16. * });
  17. *
  18. * // Process items in batches to manage memory
  19. * const results = await processInBatches(items, 100, async (item) => {
  20. * return await processItem(item);
  21. * });
  22. *
  23. * // Monitor memory usage
  24. * const monitor = new MemoryMonitor(512, (usage) => {
  25. * console.warn(`Memory usage exceeded 512MB: ${usage / 1024 / 1024}MB`);
  26. * });
  27. * monitor.start();
  28. * ```
  29. */
  30. /**
  31. * Process items in batches to manage memory
  32. *
  33. * @param items - Array of items to process
  34. * @param batchSize - Number of items per batch
  35. * @param processor - Function to process each item
  36. * @param onBatchComplete - Optional callback after each batch
  37. * @returns Array of results
  38. */
  39. export async function processInBatches<T, R>(
  40. items: T[],
  41. batchSize: number,
  42. processor: (item: T, index: number) => Promise<R>,
  43. onBatchComplete?: (completed: number, total: number) => void
  44. ): Promise<R[]> {
  45. const results: R[] = [];
  46. for (let i = 0; i < items.length; i += batchSize) {
  47. const batch = items.slice(i, Math.min(i + batchSize, items.length));
  48. const batchResults = await Promise.all(
  49. batch.map((item, idx) => processor(item, i + idx))
  50. );
  51. results.push(...batchResults);
  52. if (onBatchComplete) {
  53. onBatchComplete(Math.min(i + batchSize, items.length), items.length);
  54. }
  55. // Allow GC between batches
  56. if (global.gc) {
  57. global.gc();
  58. }
  59. }
  60. return results;
  61. }
  62. /**
  63. * Simple mutex lock for preventing concurrent operations
  64. */
  65. export class Mutex {
  66. private locked = false;
  67. private waitQueue: Array<() => void> = [];
  68. /**
  69. * Acquire the lock
  70. *
  71. * @returns A release function to call when done
  72. */
  73. async acquire(): Promise<() => void> {
  74. while (this.locked) {
  75. await new Promise<void>((resolve) => {
  76. this.waitQueue.push(resolve);
  77. });
  78. }
  79. this.locked = true;
  80. return () => {
  81. this.locked = false;
  82. const next = this.waitQueue.shift();
  83. if (next) {
  84. next();
  85. }
  86. };
  87. }
  88. /**
  89. * Execute a function while holding the lock
  90. */
  91. async withLock<T>(fn: () => Promise<T> | T): Promise<T> {
  92. const release = await this.acquire();
  93. try {
  94. return await fn();
  95. } finally {
  96. release();
  97. }
  98. }
  99. /**
  100. * Check if the lock is currently held
  101. */
  102. isLocked(): boolean {
  103. return this.locked;
  104. }
  105. }
  106. /**
  107. * Chunked file reader for large files
  108. *
  109. * Reads a file in chunks to avoid loading entire file into memory.
  110. */
  111. export async function* readFileInChunks(
  112. filePath: string,
  113. chunkSize: number = 64 * 1024
  114. ): AsyncGenerator<string, void, undefined> {
  115. const fs = await import('fs');
  116. const fd = fs.openSync(filePath, 'r');
  117. const buffer = Buffer.alloc(chunkSize);
  118. try {
  119. let bytesRead: number;
  120. while ((bytesRead = fs.readSync(fd, buffer, 0, chunkSize, null)) > 0) {
  121. yield buffer.toString('utf-8', 0, bytesRead);
  122. }
  123. } finally {
  124. fs.closeSync(fd);
  125. }
  126. }
  127. /**
  128. * Debounce a function
  129. *
  130. * @param fn - Function to debounce
  131. * @param delay - Delay in milliseconds
  132. * @returns Debounced function
  133. */
  134. export function debounce<T extends (...args: unknown[]) => unknown>(
  135. fn: T,
  136. delay: number
  137. ): (...args: Parameters<T>) => void {
  138. let timeoutId: ReturnType<typeof setTimeout> | null = null;
  139. return (...args: Parameters<T>) => {
  140. if (timeoutId) {
  141. clearTimeout(timeoutId);
  142. }
  143. timeoutId = setTimeout(() => {
  144. fn(...args);
  145. timeoutId = null;
  146. }, delay);
  147. };
  148. }
  149. /**
  150. * Throttle a function
  151. *
  152. * @param fn - Function to throttle
  153. * @param limit - Minimum time between calls in milliseconds
  154. * @returns Throttled function
  155. */
  156. export function throttle<T extends (...args: unknown[]) => unknown>(
  157. fn: T,
  158. limit: number
  159. ): (...args: Parameters<T>) => void {
  160. let lastCall = 0;
  161. let timeoutId: ReturnType<typeof setTimeout> | null = null;
  162. return (...args: Parameters<T>) => {
  163. const now = Date.now();
  164. const remaining = limit - (now - lastCall);
  165. if (remaining <= 0) {
  166. if (timeoutId) {
  167. clearTimeout(timeoutId);
  168. timeoutId = null;
  169. }
  170. lastCall = now;
  171. fn(...args);
  172. } else if (!timeoutId) {
  173. timeoutId = setTimeout(() => {
  174. lastCall = Date.now();
  175. timeoutId = null;
  176. fn(...args);
  177. }, remaining);
  178. }
  179. };
  180. }
  181. /**
  182. * Estimate memory usage of an object (rough approximation)
  183. *
  184. * @param obj - Object to measure
  185. * @returns Approximate size in bytes
  186. */
  187. export function estimateSize(obj: unknown): number {
  188. const seen = new WeakSet();
  189. function sizeOf(value: unknown): number {
  190. if (value === null || value === undefined) {
  191. return 0;
  192. }
  193. switch (typeof value) {
  194. case 'boolean':
  195. return 4;
  196. case 'number':
  197. return 8;
  198. case 'string':
  199. return 2 * (value as string).length;
  200. case 'object':
  201. if (seen.has(value as object)) {
  202. return 0;
  203. }
  204. seen.add(value as object);
  205. if (Array.isArray(value)) {
  206. return value.reduce((acc: number, item) => acc + sizeOf(item), 0);
  207. }
  208. return Object.entries(value as object).reduce(
  209. (acc, [key, val]) => acc + sizeOf(key) + sizeOf(val),
  210. 0
  211. );
  212. default:
  213. return 0;
  214. }
  215. }
  216. return sizeOf(obj);
  217. }
  218. /**
  219. * Memory monitor for tracking usage during operations
  220. */
  221. export class MemoryMonitor {
  222. private checkInterval: ReturnType<typeof setInterval> | null = null;
  223. private peakUsage = 0;
  224. private threshold: number;
  225. private onThresholdExceeded?: (usage: number) => void;
  226. constructor(
  227. thresholdMB: number = 500,
  228. onThresholdExceeded?: (usage: number) => void
  229. ) {
  230. this.threshold = thresholdMB * 1024 * 1024;
  231. this.onThresholdExceeded = onThresholdExceeded;
  232. }
  233. /**
  234. * Start monitoring memory usage
  235. */
  236. start(intervalMs: number = 1000): void {
  237. this.stop();
  238. this.peakUsage = 0;
  239. this.checkInterval = setInterval(() => {
  240. const usage = process.memoryUsage().heapUsed;
  241. if (usage > this.peakUsage) {
  242. this.peakUsage = usage;
  243. }
  244. if (usage > this.threshold && this.onThresholdExceeded) {
  245. this.onThresholdExceeded(usage);
  246. }
  247. }, intervalMs);
  248. }
  249. /**
  250. * Stop monitoring
  251. */
  252. stop(): void {
  253. if (this.checkInterval) {
  254. clearInterval(this.checkInterval);
  255. this.checkInterval = null;
  256. }
  257. }
  258. /**
  259. * Get peak memory usage in bytes
  260. */
  261. getPeakUsage(): number {
  262. return this.peakUsage;
  263. }
  264. /**
  265. * Get current memory usage in bytes
  266. */
  267. getCurrentUsage(): number {
  268. return process.memoryUsage().heapUsed;
  269. }
  270. }