All files / src/lib/db instance.ts

100% Statements 9/9
75% Branches 3/4
100% Functions 1/1
100% Lines 9/9

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                                  9x     9x       9x 8x           1x 1x   1x           1x             1x    
/**
 * Instance identifier for telemetry.
 *
 * Generates and persists a unique identifier for this CLI installation.
 * Uses UUIDv7 for time-sortable, unique identifiers.
 */
 
import { uuidv7 } from "uuidv7";
import { getDatabase } from "./index.js";
 
/**
 * Get the instance ID, generating one if it doesn't exist.
 *
 * The instance ID is generated once on first access and persisted
 * in the database. It identifies this CLI installation for telemetry.
 */
export function getInstanceId(): string {
  const db = getDatabase();
 
  // Try to get existing instance ID
  const existingRow = db
    .query("SELECT instance_id FROM instance_info WHERE id = 1")
    .get() as { instance_id: string } | undefined;
 
  if (existingRow) {
    return existingRow.instance_id;
  }
 
  // Generate and store new instance ID
  // Use INSERT OR IGNORE to handle race condition when multiple CLI processes
  // start simultaneously - only the first insert succeeds
  const instanceId = uuidv7();
  const now = Date.now();
 
  db.query(`
    INSERT OR IGNORE INTO instance_info (id, instance_id, created_at)
    VALUES (1, ?, ?)
  `).run(instanceId, now);
 
  // Re-fetch to get the actual stored value (may differ if another process won the race)
  const row = db
    .query("SELECT instance_id FROM instance_info WHERE id = 1")
    .get() as { instance_id: string } | undefined;
 
  // If re-fetch fails (readonly DB, concurrent corruption), fall back to
  // the generated ID. It won't be persisted, but the CLI can still
  // function for this invocation — instance ID is only used for telemetry.
  return row?.instance_id ?? instanceId;
}