Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 161x 161x 3x 24x 201x 201x 19x 201x 201x 504x 2x 502x 502x 502x 301x 301x 201x 201x 201x 390x 390x 390x 390x 297x 297x 297x 221x 76x 337x 337x 299x 38x 16x 16x 16x 12x 12x 11x 11x 1x 13x 12x 12x 2x 11x 11x 2x 2x 1x 10x 26x 14x 13x 39x 1x 38x 38x 38x 24x 24x 14x 14x 14x 14x 1x 1x 13x 13x 39x 39x 13x 2x 2x 11x 1x 1x 10x 10x 10x 34x 34x 34x 34x 34x | /**
* Cached DSN detection results storage (per directory).
*
* Supports two cache modes:
* 1. Single DSN cache (original) - Used by detectDsn()
* 2. Full detection cache (v4) - Used by detectAllDsns() with mtime validation
*/
import { stat } from "node:fs/promises";
import { join } from "node:path";
import type {
CachedDsnEntry,
DetectedDsn,
ResolvedProjectInfo,
} from "../dsn/types.js";
import { recordCacheHit } from "../telemetry.js";
import { getDatabase, maybeCleanupCaches } from "./index.js";
import { safeParseJson } from "./json.js";
import { runUpsert, touchCacheEntry } from "./utils.js";
/** Cache TTL in milliseconds (24 hours) */
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
/**
* Module-level flag to disable DSN cache reads.
* When true, getCachedDsn() and getCachedDetection() return undefined.
* Cache writes still proceed so the re-scanned result gets stored.
*/
let dsnCacheDisabled = false;
/**
* Disable DSN cache reads for this invocation.
* Called when `--fresh` is set to force a full re-scan.
*/
export function disableDsnCache(): void {
dsnCacheDisabled = true;
}
/**
* Re-enable DSN cache reads after `disableDsnCache()` was called.
* Only needed in tests to prevent one test's `--fresh` flag from
* leaking into subsequent tests.
*/
export function enableDsnCache(): void {
dsnCacheDisabled = false;
}
/** Row type matching the dsn_cache table schema (including v4 columns) */
type DsnCacheRow = {
directory: string;
dsn: string;
project_id: string;
org_id: string | null;
source: string;
source_path: string | null;
resolved_org_slug: string | null;
resolved_org_name: string | null;
resolved_project_slug: string | null;
resolved_project_name: string | null;
// v4 columns for full detection caching
fingerprint: string | null;
all_dsns_json: string | null;
source_mtimes_json: string | null;
dir_mtimes_json: string | null;
root_dir_mtime: number | null;
ttl_expires_at: number | null;
cached_at: number;
last_accessed: number;
};
/** Full detection cache entry (v4) */
export type CachedDetection = {
/** Pre-computed fingerprint for alias validation */
fingerprint: string;
/** All detected DSNs */
allDsns: DetectedDsn[];
/** Map of source file paths to their mtimes (files only) */
sourceMtimes: Record<string, number>;
/** Map of scanned directory paths to their mtimes (for detecting new files) */
dirMtimes: Record<string, number>;
/** mtime of the project root directory */
rootDirMtime: number;
/** When the cache expires (TTL) */
ttlExpiresAt: number;
};
/** Input for storing a full detection result */
export type DetectionCacheEntry = {
/** Pre-computed fingerprint */
fingerprint: string;
/** All detected DSNs */
allDsns: DetectedDsn[];
/** Map of source file paths to their mtimes (files only) */
sourceMtimes: Record<string, number>;
/** Map of scanned directory paths to their mtimes (for detecting new files) */
dirMtimes: Record<string, number>;
/** mtime of the project root directory */
rootDirMtime: number;
};
function rowToCachedDsnEntry(row: DsnCacheRow): CachedDsnEntry {
const entry: CachedDsnEntry = {
dsn: row.dsn,
projectId: row.project_id,
orgId: row.org_id ?? undefined,
source: row.source as CachedDsnEntry["source"],
sourcePath: row.source_path ?? undefined,
cachedAt: row.cached_at,
};
if (row.resolved_org_slug && row.resolved_project_slug) {
entry.resolved = {
orgSlug: row.resolved_org_slug,
orgName: row.resolved_org_name ?? "",
projectSlug: row.resolved_project_slug,
projectName: row.resolved_project_name ?? "",
};
}
// Parse allResolved from all_dsns_json for inferred sources
Iif (row.source === "inferred" && row.all_dsns_json) {
try {
entry.allResolved = JSON.parse(
row.all_dsns_json
) as CachedDsnEntry["allResolved"];
} catch {
// Ignore parse errors, allResolved will be undefined
}
}
return entry;
}
export function getCachedDsn(directory: string): CachedDsnEntry | undefined {
if (dsnCacheDisabled) {
return;
}
const db = getDatabase();
const row = db
.query("SELECT * FROM dsn_cache WHERE directory = ?")
.get(directory) as DsnCacheRow | undefined;
if (!row) {
recordCacheHit("dsn", false);
return;
}
recordCacheHit("dsn", true);
touchCacheEntry("dsn_cache", "directory", directory);
return rowToCachedDsnEntry(row);
}
export function setCachedDsn(
directory: string,
entry: Omit<CachedDsnEntry, "cachedAt">
): void {
const db = getDatabase();
const now = Date.now();
runUpsert(
db,
"dsn_cache",
{
directory,
dsn: entry.dsn,
project_id: entry.projectId,
org_id: entry.orgId ?? null,
source: entry.source,
source_path: entry.sourcePath ?? null,
resolved_org_slug: entry.resolved?.orgSlug ?? null,
resolved_org_name: entry.resolved?.orgName ?? null,
resolved_project_slug: entry.resolved?.projectSlug ?? null,
resolved_project_name: entry.resolved?.projectName ?? null,
// Store allResolved in all_dsns_json for inferred sources
all_dsns_json: entry.allResolved
? JSON.stringify(entry.allResolved)
: null,
cached_at: now,
last_accessed: now,
},
["directory"]
);
maybeCleanupCaches();
}
/** Update resolved org/project info after API resolution. */
export function updateCachedResolution(
directory: string,
resolved: ResolvedProjectInfo
): void {
const db = getDatabase();
const exists = db
.query("SELECT 1 FROM dsn_cache WHERE directory = ?")
.get(directory);
if (!exists) {
return;
}
db.query(`
UPDATE dsn_cache SET
resolved_org_slug = ?,
resolved_org_name = ?,
resolved_project_slug = ?,
resolved_project_name = ?,
last_accessed = ?
WHERE directory = ?
`).run(
resolved.orgSlug,
resolved.orgName,
resolved.projectSlug,
resolved.projectName,
Date.now(),
directory
);
}
export function clearDsnCache(directory?: string): void {
const db = getDatabase();
if (directory) {
db.query("DELETE FROM dsn_cache WHERE directory = ?").run(directory);
} else {
db.query("DELETE FROM dsn_cache").run();
}
}
// =============================================================================
// Full Detection Cache (v4) - mtime-based validation
// =============================================================================
/**
* Validate a single directory mtime.
* @returns True if mtime matches, false if changed or missing
*/
async function validateDirMtime(
fullPath: string,
cachedMtime: number
): Promise<boolean> {
try {
const stats = await stat(fullPath);
return Math.floor(stats.mtimeMs) === cachedMtime;
} catch {
return false;
}
}
/**
* Validate a single file mtime.
* @returns True if mtime matches, false if changed or missing
*/
async function validateFileMtime(
fullPath: string,
cachedMtime: number
): Promise<boolean> {
try {
const stats = await stat(fullPath);
Iif (!stats.isFile()) {
return false;
}
return Math.floor(stats.mtimeMs) === cachedMtime;
} catch {
return false;
}
}
/**
* Validate that cached source file mtimes still match.
*
* @param projectRoot - Project root directory
* @param sourceMtimes - Map of relative file paths to cached mtimes
* @returns True if all file mtimes match, false if any changed or missing
*/
async function validateSourceMtimes(
projectRoot: string,
sourceMtimes: Record<string, number>
): Promise<boolean> {
for (const [relativePath, cachedMtime] of Object.entries(sourceMtimes)) {
const fullPath = join(projectRoot, relativePath);
if (!(await validateFileMtime(fullPath, cachedMtime))) {
return false;
}
}
return true;
}
/**
* Validate that cached directory mtimes still match.
* Used to detect when new files are added to scanned directories.
*
* @param projectRoot - Project root directory
* @param dirMtimes - Map of relative directory paths to cached mtimes
* @returns True if all directory mtimes match, false if any changed
*/
async function validateDirMtimes(
projectRoot: string,
dirMtimes: Record<string, number>
): Promise<boolean> {
for (const [relativePath, cachedMtime] of Object.entries(dirMtimes)) {
const fullPath = join(projectRoot, relativePath);
if (!(await validateDirMtime(fullPath, cachedMtime))) {
return false;
}
}
return true;
}
/** Type guard: value is a plain object with all-numeric values (mtimes record). */
function isMtimesRecord(value: unknown): value is Record<string, number> {
return (
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
Object.values(value as Record<string, unknown>).every(
(v) => typeof v === "number"
)
);
}
/** Type guard: value is an array (used for the cached DSN list). */
function isArray(value: unknown): value is DetectedDsn[] {
return Array.isArray(value);
}
/**
* Get cached full detection result if valid.
*
* Validation checks (in order):
* 1. Cache entry exists with full detection data
* 2. TTL not expired (24h max age)
* 3. Project root directory mtime unchanged (no new files)
* 4. All source file mtimes unchanged
*
* @param projectRoot - Project root directory
* @returns Cached detection or undefined if not cached/invalid
*/
export async function getCachedDetection(
projectRoot: string
): Promise<CachedDetection | undefined> {
if (dsnCacheDisabled) {
return;
}
const db = getDatabase();
const row = db
.query("SELECT * FROM dsn_cache WHERE directory = ?")
.get(projectRoot) as DsnCacheRow | undefined;
if (!row) {
recordCacheHit("dsn-detection", false);
return;
}
// Check if full detection data exists (v4 columns)
Iif (
!(row.fingerprint && row.all_dsns_json && row.source_mtimes_json) ||
row.root_dir_mtime === null ||
row.ttl_expires_at === null
) {
// Old cache entry without full detection data
recordCacheHit("dsn-detection", false);
return;
}
const now = Date.now();
// Check TTL expiration
Iif (now > row.ttl_expires_at) {
recordCacheHit("dsn-detection", false);
return;
}
// Check project root directory mtime
if (!(await validateDirMtime(projectRoot, row.root_dir_mtime))) {
recordCacheHit("dsn-detection", false);
return;
}
// Parse all cached JSON columns up front, validating their shape. Corruption
// (partial write, manual edit, schema drift) — including a structurally wrong
// value like an object where an array is expected — is treated as a cache miss
// so detection re-runs from scratch instead of crashing downstream.
const sourceMtimes = safeParseJson(row.source_mtimes_json, isMtimesRecord);
const dirMtimes = row.dir_mtimes_json
? safeParseJson(row.dir_mtimes_json, isMtimesRecord)
: {};
const allDsns = safeParseJson(row.all_dsns_json, isArray);
Iif (sourceMtimes === undefined || dirMtimes === undefined || !allDsns) {
recordCacheHit("dsn-detection", false);
return;
}
if (!(await validateSourceMtimes(projectRoot, sourceMtimes))) {
recordCacheHit("dsn-detection", false);
return;
}
if (!(await validateDirMtimes(projectRoot, dirMtimes))) {
recordCacheHit("dsn-detection", false);
return;
}
recordCacheHit("dsn-detection", true);
// Cache is valid - update last access time
touchCacheEntry("dsn_cache", "directory", projectRoot);
return {
fingerprint: row.fingerprint,
allDsns,
sourceMtimes,
dirMtimes,
rootDirMtime: row.root_dir_mtime,
ttlExpiresAt: row.ttl_expires_at,
};
}
/**
* Store full detection result in cache.
*
* This updates the existing cache entry (if any) with full detection data.
* The primary DSN from allDsns[0] is used for the single-DSN fields.
*
* @param projectRoot - Project root directory
* @param entry - Detection result to cache
*/
export function setCachedDetection(
projectRoot: string,
entry: DetectionCacheEntry
): void {
const db = getDatabase();
const now = Date.now();
// Use primary DSN for backwards-compatible single-DSN fields
const primaryDsn = entry.allDsns[0];
runUpsert(
db,
"dsn_cache",
{
directory: projectRoot,
// Single-DSN fields (for backwards compatibility)
dsn: primaryDsn?.raw ?? "",
project_id: primaryDsn?.projectId ?? "",
org_id: primaryDsn?.orgId ?? null,
source: primaryDsn?.source ?? "code",
source_path: primaryDsn?.sourcePath ?? null,
resolved_org_slug: null,
resolved_org_name: null,
resolved_project_slug: null,
resolved_project_name: null,
// Full detection fields (v4)
fingerprint: entry.fingerprint,
all_dsns_json: JSON.stringify(entry.allDsns),
source_mtimes_json: JSON.stringify(entry.sourceMtimes),
dir_mtimes_json: JSON.stringify(entry.dirMtimes),
root_dir_mtime: entry.rootDirMtime,
ttl_expires_at: now + CACHE_TTL_MS,
// Timestamps
cached_at: now,
last_accessed: now,
},
["directory"]
);
maybeCleanupCaches();
}
|