Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
915 lines (834 loc) · 29.8 KB
/
Copy pathutils.ts
File metadata and controls
915 lines (834 loc) · 29.8 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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
/**
* CodeGraph Utilities
*
* Common utility functions for memory management, concurrency, batching,
* and security validation.
*
* @module utils
*
* @example
* ```typescript
* import { Mutex, processInBatches, MemoryMonitor, validatePathWithinRoot } from 'codegraph';
*
* // Use mutex for concurrent safety
* const mutex = new Mutex();
* await mutex.withLock(async () => {
* await performCriticalOperation();
* });
*
* // Process items in batches to manage memory
* const results = await processInBatches(items, 100, async (item) => {
* return await processItem(item);
* });
*
* // Monitor memory usage
* const monitor = new MemoryMonitor(512, (usage) => {
* console.warn(`Memory usage exceeded 512MB: ${usage / 1024 / 1024}MB`);
* });
* monitor.start();
* ```
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { threadId } from 'worker_threads';
// ============================================================
// SECURITY UTILITIES
// ============================================================
/**
* Sensitive system directories that should never be used as project roots.
* Checked on all platforms; non-applicable paths are harmlessly skipped.
*/
const SENSITIVE_PATHS = new Set([
'/', '/etc', '/usr', '/bin', '/sbin', '/var', '/tmp', '/dev', '/proc', '/sys',
'/root', '/boot', '/lib', '/lib64', '/opt',
'c:\\', 'c:\\windows', 'c:\\windows\\system32',
]);
/**
* Credential and config folders in the home directory. Unlike the system set,
* everything under them is refused too.
*/
const SENSITIVE_HOME_DIRS = ['.ssh', '.gnupg', '.aws', '.config'];
/**
* How long the real paths of the sensitive home folders are reused. The viewer
* re-checks its root on every file it reads, so they are not re-read per check,
* but a folder linked somewhere new while the process runs is noticed soon.
*/
const SENSITIVE_HOME_TTL_MS = 2_000;
let sensitiveHomeCache: { home: string; expires: number; trees: string[] } | undefined;
let sensitiveSystemRealPaths: Set<string> | undefined;
/**
* Config "languages" whose nodes are pure key/value DATA lifted from a config
* file (e.g. Spring `application.{yml,properties}`), not source code.
*/
export const CONFIG_LEAF_LANGUAGES: ReadonlySet<string> = new Set(['yaml', 'properties']);
/**
* A config-leaf node is a single key lifted out of a pure config/data file —
* `kind: 'constant'` in a {@link CONFIG_LEAF_LANGUAGES} language. Its on-disk
* line is `key = <value>`, and that value is routinely a secret (DB password,
* API key, JDBC URL with embedded creds). CodeGraph must surface the KEY only
* and never read/return the value, or it pushes secrets into agent context
* unbidden — the value isn't needed for resolution, and an agent that genuinely
* needs it can read the file directly. (#383)
*/
export function isConfigLeafNode(node: { kind: string; language?: string }): boolean {
return node.kind === 'constant' && !!node.language && CONFIG_LEAF_LANGUAGES.has(node.language);
}
/**
* Whether `child` is `parent` or lies under it, compared exactly as given.
*
* A root (`C:\`, `\\server\share\`, `/`) already ends with its separator, so
* none is added to it. Adding one made `C:\\` the prefix, which no path under
* the root starts with, so a project at a drive root indexed nothing (#415).
*/
function isSameOrUnder(child: string, parent: string): boolean {
if (child === parent) return true;
return child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
}
/**
* Whether `child` is `parent` itself or sits underneath it. Case-insensitive on
* Windows — NTFS is case-insensitive, and realpathSync can hand back a different
* case than the lexical root, which would otherwise false-reject a valid file.
*/
function isWithinDir(child: string, parent: string): boolean {
if (process.platform === 'win32') {
return isSameOrUnder(child.toLowerCase(), parent.toLowerCase());
}
return isSameOrUnder(child, parent);
}
/**
* The lexical half of {@link validatePathWithinRoot}, on its own.
*
* Returns the resolved absolute path when `filePath` stays inside
* `projectRoot` after `../` segments are applied, or null when it escapes.
* No filesystem access — for callers on a hot path that only need to refuse a
* lexical escape, and for which the realpath half would be both unnecessary
* and far too expensive (the existence probe in resolution's `fileExists`,
* #1631: two `realpathSync` calls per probe made it ~70x slower).
*
* This is NOT a substitute for `validatePathWithinRoot` on any path whose
* contents get served — those must keep the symlink-aware check (#527).
*/
export function lexicalPathWithinRoot(projectRoot: string, filePath: string): string | null {
const resolved = path.resolve(projectRoot, filePath);
return isWithinDir(resolved, path.resolve(projectRoot)) ? resolved : null;
}
/**
* Whether a path made relative to a root (`path.relative(root, p)`, or a
* project-relative path) leaves the root: `..` itself, a first segment of
* `..` (`../x`, or `..\x` from Windows), or an absolute path, which
* `path.relative` gives on Windows for another drive. A folder whose NAME
* starts with two dots, like `..generated/`, is inside the root:
* `startsWith('..')` took it for a way out.
*/
export function escapesRoot(rel: string): boolean {
return rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || path.isAbsolute(rel);
}
/**
* Whether a filesystem error means nothing is at the path: ENOENT, or ENOTDIR,
* which POSIX reports instead when a folder on the way is a file (Windows
* reports ENOENT for both).
*/
export function isMissingPathError(err: unknown): boolean {
const code = (err as NodeJS.ErrnoException | null)?.code;
return code === 'ENOENT' || code === 'ENOTDIR';
}
/**
* Validate that a file path stays within the project root, resolving symlinks.
*
* Two layers: a cheap lexical check that catches `../` traversal, then a
* realpath check that catches symlink escapes — an in-repo symlink whose
* logical path is inside the root but whose real target points outside it
* (issue #527). A symlink that stays within the root is still allowed, so
* legitimate in-tree symlinks keep working. Both content-serving read sinks
* (codegraph_node `includeCode`, codegraph_explore source) go through here, so
* this is the chokepoint that keeps out-of-root file contents from leaking.
*
* `allowSymlinkEscape` waives **only** the realpath-escape rejection (the
* lexical `../` guard still applies) for the INDEXING read path. The directory
* walk deliberately descends into in-root symlinks whose targets live outside
* the root (e.g. a `game/` symlink in a Dota custom-game tree, #935); discovery
* and the reader must agree, or every file the walk enumerated fails to index.
* Indexing only reads paths it just discovered, into a local index — it never
* serves them to an agent, so this does not widen the #527 leak surface. The
* content-serving sinks must never pass this flag.
*
* `readOnly` is for a caller that will only ever read what the path names, and
* changes one thing: a missing path comes straight back instead of being judged
* by its ancestors. That walk is for a caller about to create the path, which
* would follow a link out of the root on the way; a read of a missing path finds
* nothing wherever it leads, and the walk costs a `realpathSync` per missing
* folder. A path that exists is judged in full either way. Anything that may
* write must leave this off.
*
* @param projectRoot - The project root directory
* @param filePath - The (relative or absolute) file path to validate
* @param options.allowSymlinkEscape - Follow in-root symlinks out of the root
* (indexing read path only); defaults to the strict, leak-safe behavior.
* @param options.readOnly - The caller only reads the path, so a missing one
* needs no walk; defaults to the check a write needs.
* @returns The resolved absolute path (realpath when it exists), or null if it
* escapes the root. A path that does not exist yet is judged by its nearest
* existing ancestor unless `readOnly` or `allowSymlinkEscape` is set, and every
* path under a root that does not exist is null.
*/
export function validatePathWithinRoot(
projectRoot: string,
filePath: string,
options?: { allowSymlinkEscape?: boolean; readOnly?: boolean }
): string | null {
// 1. Lexical containment — cheap, catches `../` traversal. Applies even on
// the indexing read path: a crafted `../` escape is still rejected.
const resolved = lexicalPathWithinRoot(projectRoot, filePath);
if (resolved === null) {
return null;
}
const normalizedRoot = path.resolve(projectRoot);
// 2. Symlink-aware containment — resolve symlinks on both sides and re-check,
// so an in-repo symlink whose real target escapes the root is rejected.
// The indexing read path (allowSymlinkEscape) skips only this rejection so
// it stays consistent with the directory walk, which already followed the
// in-root symlink to enumerate these files (#935).
let realRoot: string;
try {
realRoot = fs.realpathSync(normalizedRoot);
} catch {
return null;
}
try {
const realResolved = fs.realpathSync(resolved);
if (options?.allowSymlinkEscape) {
return realResolved;
}
return isWithinDir(realResolved, realRoot) ? realResolved : null;
} catch (err) {
// A path under a file (ENOTDIR on POSIX) is a missing leaf too.
if (!isMissingPathError(err)) return null;
}
// Nothing to read, and with the root in place the indexing read path takes
// whatever ancestor a walk would find, so neither needs one.
if (options?.readOnly || options?.allowSymlinkEscape) return resolved;
// A missing leaf may still sit below an EXISTING symlink. Resolve the
// nearest existing ancestor before allowing a write path: otherwise
// `project/.codegraph/ui -> /outside` plus a missing `trails/` directory
// passes the lexical check and mkdir follows the symlink out of the root.
let ancestor = path.dirname(resolved);
while (isWithinDir(ancestor, normalizedRoot)) {
try {
const realAncestor = fs.realpathSync(ancestor);
return isWithinDir(realAncestor, realRoot) ? resolved : null;
} catch (err) {
if (!isMissingPathError(err)) return null;
const parent = path.dirname(ancestor);
if (parent === ancestor) return null;
ancestor = parent;
}
}
return null;
}
/**
* A path in the form the sensitive-folder check compares: lower-cased where the
* file system ignores case by default (NTFS, APFS), so `~/.SSH` is `~/.ssh`.
*/
function foldPathCase(p: string): string {
return process.platform === 'win32' || process.platform === 'darwin' ? p.toLowerCase() : p;
}
/**
* The plain spelling of a Win32 namespace path: `\\?\C:\x` and `\\.\C:\x` are
* `C:\x`, and `\\?\UNC\host\share` is `\\host\share`. `path.resolve` keeps the
* prefix, so a string comparison would never see the folder behind it. Other
* namespace paths (a `\\?\Volume{…}\` name, a device) are returned unchanged;
* the real path the caller also checks names their folder.
*/
function stripWin32NamespacePrefix(p: string): string {
if (process.platform !== 'win32') return p;
const prefix = /^[\\/]{2}[?.][\\/](UNC[\\/])?/i.exec(p);
if (!prefix) return p;
const rest = p.slice(prefix[0].length);
if (prefix[1]) return `\\\\${rest}`;
return /^[a-z]:[\\/]/i.test(rest) ? rest : p;
}
/**
* The folder a path really names: links (symlinks, junctions, a `subst` drive)
* followed, and the case and long names stored on disk. Null when it can't be
* resolved, most often because it doesn't exist; the lexical check still runs.
*/
function nativeRealPath(p: string): string | null {
try {
return fs.realpathSync.native(p);
} catch {
return null;
}
}
/**
* The system set's own real paths, folded. macOS keeps `/etc`, `/tmp` and
* `/var` under `/private`, so a project whose real path is `/private/etc` is
* `/etc`. Read once: these folders don't move.
*/
function sensitiveSystemPaths(): Set<string> {
if (!sensitiveSystemRealPaths) {
sensitiveSystemRealPaths = new Set();
for (const entry of SENSITIVE_PATHS) {
// Only this platform's entries: on Windows `/` would resolve to the root
// of the current drive and refuse every project at a drive root.
const native = process.platform === 'win32' ? /^[a-z]:\\/.test(entry) : entry.startsWith('/');
if (!native) continue;
const real = nativeRealPath(entry);
if (real) sensitiveSystemRealPaths.add(foldPathCase(real));
}
}
return sensitiveSystemRealPaths;
}
/**
* The sensitive home folders, folded: as spelled under the home directory,
* under the home's real path (a linked home), and each folder's own real path
* (a `~/.ssh` that is itself a link into a dotfiles checkout).
*/
function sensitiveHomeTrees(): string[] {
const home = os.homedir();
const now = Date.now();
if (sensitiveHomeCache && sensitiveHomeCache.home === home && now < sensitiveHomeCache.expires) {
return sensitiveHomeCache.trees;
}
const trees = new Set<string>();
const realHome = nativeRealPath(home);
for (const dir of SENSITIVE_HOME_DIRS) {
const spelled = path.join(home, dir);
trees.add(foldPathCase(spelled));
if (realHome) trees.add(foldPathCase(path.join(realHome, dir)));
const real = nativeRealPath(spelled);
if (real) trees.add(foldPathCase(real));
}
sensitiveHomeCache = { home, expires: now + SENSITIVE_HOME_TTL_MS, trees: [...trees] };
return sensitiveHomeCache.trees;
}
/**
* Validate that a path is a safe project root directory.
*
* Rejects sensitive system directories and ensures the path is
* a real, existing directory. Used at MCP and API entry points
* to prevent arbitrary directory access.
*
* The path is checked both as spelled and as the folder it really names, so a
* link to `~/.ssh`, a case variant (`~/.SSH`) or a `\\?\` spelling is refused
* like the folder itself (#1930). It is kept to one realpath per call, since the
* viewer calls this for every file it reads: the sensitive folders' own real
* paths are cached and re-read every couple of seconds.
*
* @param dirPath - The path to validate
* @returns An error message if invalid, or null if valid
*/
export function validateProjectPath(dirPath: string): string | null {
const refusal = sensitiveDirectoryRefusal(dirPath);
if (refusal) return refusal;
// Verify it's a real directory
const resolved = path.resolve(dirPath);
try {
const stats = fs.statSync(resolved);
if (!stats.isDirectory()) {
return `Path is not a directory: ${resolved}`;
}
} catch {
return `Path does not exist or is not accessible: ${resolved}`;
}
return null;
}
/**
* The sensitive-folder half of {@link validateProjectPath}: why `dirPath` is,
* or is inside, a folder CodeGraph never uses as a project, or null. Unlike
* that function it doesn't require the path to exist or be a directory, so it
* can vet a path a project root is searched for from.
*/
export function sensitiveDirectoryRefusal(dirPath: string): string | null {
const resolved = path.resolve(dirPath);
const lexical = path.resolve(stripWin32NamespacePrefix(dirPath));
const real = nativeRealPath(lexical);
const candidates = [lexical];
if (real && real !== lexical) candidates.push(real);
const named = (candidate: string): string =>
candidate === resolved ? resolved : `${resolved} (resolves to ${candidate})`;
// Block sensitive system directories
const systemPaths = sensitiveSystemPaths();
for (const candidate of candidates) {
if (
SENSITIVE_PATHS.has(candidate) ||
SENSITIVE_PATHS.has(candidate.toLowerCase()) ||
systemPaths.has(foldPathCase(candidate))
) {
return `Refusing to operate on sensitive system directory: ${named(candidate)}`;
}
}
// Also block common sensitive home subdirectories
const homeTrees = sensitiveHomeTrees();
for (const candidate of candidates) {
const folded = foldPathCase(candidate);
if (homeTrees.some((tree) => isSameOrUnder(folded, tree))) {
return `Refusing to operate on sensitive directory: ${named(candidate)}`;
}
}
return null;
}
/**
* Safely parse JSON with a fallback value.
* Prevents crashes from corrupted database metadata.
*/
export function safeJsonParse<T>(value: string, fallback: T): T {
try {
return JSON.parse(value);
} catch {
return fallback;
}
}
/**
* Clamp a numeric value to a range.
* Used to enforce sane limits on MCP tool inputs.
*/
export function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
/**
* Normalize a file path to use forward slashes.
* Fixes Windows backslash paths so glob matching works consistently.
*/
export function normalizePath(filePath: string): string {
return filePath.replace(/\\/g, '/');
}
const REGEXP_SYNTAX = /[.*+?^${}()|[\]\\]/;
/**
* Escape `text` to match itself literally inside a regular expression.
* Symbol names are not always plain words: C++'s `operator++` and
* `operator()`, Scala's `++`, a Kotlin name in backticks. Pass every name
* through this before writing it into a `new RegExp(…)` pattern, or the name
* is read as pattern syntax and may not compile at all.
*/
export function escapeRegExp(text: string): string {
// Most text here is an identifier, with nothing to escape.
return REGEXP_SYNTAX.test(text) ? text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : text;
}
/**
* An empty lock file younger than this is still being written by the process
* that created it (#2979): where hard links are missing, the lock is created
* first and the PID written a moment later. Only a crash leaves one empty for
* long, and FAT's 2 s timestamps stay well inside this.
*/
const EMPTY_LOCK_GRACE_MS = 10_000;
/**
* How many `.break` levels a takeover may climb. Each level is needed only if
* a process died inside the level above it, within a few file operations.
*/
const MAX_LOCK_BREAK_DEPTH = 3;
/** What a lock file says about its holder. */
type LockHolder =
| { state: 'free' }
| { state: 'held'; pid?: number }
| { state: 'stale' };
/**
* Cross-process file lock using a lock file with PID tracking.
*
* Prevents multiple processes (e.g., git hooks, CLI, MCP server) from
* writing to the same database simultaneously.
*/
export class FileLock {
private lockPath: string;
private held = false;
constructor(lockPath: string) {
this.lockPath = lockPath;
}
/**
* Acquire the lock. Throws if the lock is held by another live process.
*
* A free lock costs one create. A stale one, whose PID is dead or missing,
* is replaced only by the process holding `<lock>.break` (itself a
* FileLock), after reading it again there (#2979). Before, two processes
* that read the same dead PID both unlinked the lock and created their own,
* the second one deleting the first one's live lock, and both went on to
* write as the only writer.
*/
acquire(): void {
const refusal = this.tryAcquire(0);
if (refusal) {
const who = refusal.state === 'held' && refusal.pid !== undefined ? ` (PID ${refusal.pid})` : '';
throw new Error(
`CodeGraph database is locked by another process${who}. ` +
`If this is stale, run 'codegraph unlock' or delete ${this.lockPath}`
);
}
}
/** Null once the lock is ours; otherwise what kept us out. */
private tryAcquire(depth: number): LockHolder | null {
if (this.create()) return this.taken();
let holder = this.readHolder();
if (holder.state === 'free') {
// Released between our create and our read.
if (this.create()) return this.taken();
holder = this.readHolder();
}
// A long sync can hold the lock for hours. Its age says nothing about
// whether the writer is still alive; only a dead PID is stale.
if (holder.state !== 'stale') return holder;
if (depth >= MAX_LOCK_BREAK_DEPTH) return { state: 'held' };
const breaker = new FileLock(`${this.lockPath}.break`);
// Refused: a live process is replacing this stale lock right now.
const breaking = breaker.tryAcquire(depth + 1);
if (breaking) return breaking;
try {
// What we read before holding the break lock may be out of date: another
// process may have replaced the stale lock, or released its own, since.
const current = this.readHolder();
if (current.state === 'held') return current;
// Nobody else replaces a stale lock while we hold the break lock, and no
// create succeeds while the file exists, so this unlinks the stale lock.
if (current.state === 'stale') {
try { fs.unlinkSync(this.lockPath); } catch { /* gone, or the create below says who has it */ }
}
return this.create() ? this.taken() : this.readHolder();
} finally {
breaker.release();
}
}
private taken(): null {
this.held = true;
return null;
}
/**
* Create the lock file with our PID already in it, so no reader ever finds
* it empty: write a private file, then hard-link it into place, which fails
* if the lock exists. Where hard links are missing, fall back to an
* exclusive create, whose PID lands a moment later (see
* EMPTY_LOCK_GRACE_MS). False when the lock already exists.
*/
private create(): boolean {
const pid = String(process.pid);
const tmp = `${this.lockPath}.${process.pid}.${threadId}.tmp`;
try {
fs.writeFileSync(tmp, pid);
fs.linkSync(tmp, this.lockPath);
return true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;
// No hard links here (or no private file): create in place instead.
} finally {
try { fs.unlinkSync(tmp); } catch { /* never written */ }
}
try {
fs.writeFileSync(this.lockPath, pid, { flag: 'wx' });
return true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;
throw err;
}
}
private readHolder(): LockHolder {
let content: string;
try {
content = fs.readFileSync(this.lockPath, 'utf-8').trim();
} catch (err) {
// Unreadable is not proof the holder is gone: leave it to `codegraph unlock`.
return (err as NodeJS.ErrnoException).code === 'ENOENT' ? { state: 'free' } : { state: 'held' };
}
if (content === '') {
let age: number;
try {
age = Date.now() - fs.statSync(this.lockPath).mtimeMs;
} catch {
return { state: 'free' };
}
return age < EMPTY_LOCK_GRACE_MS ? { state: 'held' } : { state: 'stale' };
}
const pid = parseInt(content, 10);
// Malformed: no process owns it.
if (!(pid > 0)) return { state: 'stale' };
return this.isProcessAlive(pid) ? { state: 'held', pid } : { state: 'stale' };
}
/**
* Release the lock
*/
release(): void {
if (!this.held) return;
try {
// Only remove if we still own it (check PID)
const content = fs.readFileSync(this.lockPath, 'utf-8').trim();
if (parseInt(content, 10) === process.pid) {
fs.unlinkSync(this.lockPath);
}
} catch {
// Lock file already gone - that's fine
}
this.held = false;
}
/**
* Execute a function while holding the lock
*/
withLock<T>(fn: () => T): T {
this.acquire();
try {
return fn();
} finally {
this.release();
}
}
/**
* Execute an async function while holding the lock
*/
async withLockAsync<T>(fn: () => Promise<T>): Promise<T> {
this.acquire();
try {
return await fn();
} finally {
this.release();
}
}
/**
* Check if a process is still running
*/
private isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (err) {
// EPERM: it exists but is not ours to signal (another user's, or elevated on Windows).
return (err as NodeJS.ErrnoException).code === 'EPERM';
}
}
}
/**
* Process items in batches to manage memory
*
* @param items - Array of items to process
* @param batchSize - Number of items per batch
* @param processor - Function to process each item
* @param onBatchComplete - Optional callback after each batch
* @returns Array of results
*/
export async function processInBatches<T, R>(
items: T[],
batchSize: number,
processor: (item: T, index: number) => Promise<R>,
onBatchComplete?: (completed: number, total: number) => void
): Promise<R[]> {
const results: R[] = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, Math.min(i + batchSize, items.length));
const batchResults = await Promise.all(
batch.map((item, idx) => processor(item, i + idx))
);
results.push(...batchResults);
if (onBatchComplete) {
onBatchComplete(Math.min(i + batchSize, items.length), items.length);
}
// Allow GC between batches
if (global.gc) {
global.gc();
}
}
return results;
}
/**
* Simple mutex lock for preventing concurrent operations
*/
export class Mutex {
private locked = false;
private waitQueue: Array<() => void> = [];
/**
* Acquire the lock
*
* @returns A release function to call when done
*/
async acquire(): Promise<() => void> {
while (this.locked) {
await new Promise<void>((resolve) => {
this.waitQueue.push(resolve);
});
}
this.locked = true;
return () => {
this.locked = false;
const next = this.waitQueue.shift();
if (next) {
next();
}
};
}
/**
* Execute a function while holding the lock
*/
async withLock<T>(fn: () => Promise<T> | T): Promise<T> {
const release = await this.acquire();
try {
return await fn();
} finally {
release();
}
}
/**
* Check if the lock is currently held
*/
isLocked(): boolean {
return this.locked;
}
}
/**
* Chunked file reader for large files
*
* Reads a file in chunks to avoid loading entire file into memory.
*/
export async function* readFileInChunks(
filePath: string,
chunkSize: number = 64 * 1024
): AsyncGenerator<string, void, undefined> {
const fs = await import('fs');
const fd = fs.openSync(filePath, 'r');
const buffer = Buffer.alloc(chunkSize);
try {
let bytesRead: number;
while ((bytesRead = fs.readSync(fd, buffer, 0, chunkSize, null)) > 0) {
yield buffer.toString('utf-8', 0, bytesRead);
}
} finally {
fs.closeSync(fd);
}
}
/**
* Debounce a function
*
* @param fn - Function to debounce
* @param delay - Delay in milliseconds
* @returns Debounced function
*/
export function debounce<T extends (...args: unknown[]) => unknown>(
fn: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return (...args: Parameters<T>) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn(...args);
timeoutId = null;
}, delay);
};
}
/**
* Throttle a function
*
* @param fn - Function to throttle
* @param limit - Minimum time between calls in milliseconds
* @returns Throttled function
*/
export function throttle<T extends (...args: unknown[]) => unknown>(
fn: T,
limit: number
): (...args: Parameters<T>) => void {
let lastCall = 0;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return (...args: Parameters<T>) => {
const now = Date.now();
const remaining = limit - (now - lastCall);
if (remaining <= 0) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
lastCall = now;
fn(...args);
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
lastCall = Date.now();
timeoutId = null;
fn(...args);
}, remaining);
}
};
}
/**
* Estimate memory usage of an object (rough approximation)
*
* @param obj - Object to measure
* @returns Approximate size in bytes
*/
export function estimateSize(obj: unknown): number {
const seen = new WeakSet();
function sizeOf(value: unknown): number {
if (value === null || value === undefined) {
return 0;
}
switch (typeof value) {
case 'boolean':
return 4;
case 'number':
return 8;
case 'string':
return 2 * (value as string).length;
case 'object':
if (seen.has(value as object)) {
return 0;
}
seen.add(value as object);
if (Array.isArray(value)) {
return value.reduce((acc: number, item) => acc + sizeOf(item), 0);
}
return Object.entries(value as object).reduce(
(acc, [key, val]) => acc + sizeOf(key) + sizeOf(val),
0
);
default:
return 0;
}
}
return sizeOf(obj);
}
/**
* Memory monitor for tracking usage during operations
*/
export class MemoryMonitor {
private checkInterval: ReturnType<typeof setInterval> | null = null;
private peakUsage = 0;
private threshold: number;
private onThresholdExceeded?: (usage: number) => void;
constructor(
thresholdMB: number = 500,
onThresholdExceeded?: (usage: number) => void
) {
this.threshold = thresholdMB * 1024 * 1024;
this.onThresholdExceeded = onThresholdExceeded;
}
/**
* Start monitoring memory usage
*/
start(intervalMs: number = 1000): void {
this.stop();
this.peakUsage = 0;
this.checkInterval = setInterval(() => {
const usage = process.memoryUsage().heapUsed;
if (usage > this.peakUsage) {
this.peakUsage = usage;
}
if (usage > this.threshold && this.onThresholdExceeded) {
this.onThresholdExceeded(usage);
}
}, intervalMs);
}
/**
* Stop monitoring
*/
stop(): void {
if (this.checkInterval) {
clearInterval(this.checkInterval);
this.checkInterval = null;
}
}
/**
* Get peak memory usage in bytes
*/
getPeakUsage(): number {
return this.peakUsage;
}
/**
* Get current memory usage in bytes
*/
getCurrentUsage(): number {
return process.memoryUsage().heapUsed;
}
}