Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ codeant review
codeant <command> [options]
```

On Node.js 22.19 or later, the CLI can cache repository and branch listings at
`~/.codeant/cache/fetch-api.sqlite`. The cache requires Node's built-in SQLite and
the optional npm dependencies. Other installations fetch these reads live.
Repository lists expire after five minutes and branch reads after 30 seconds.
Set `CODEANT_NO_CACHE=1` to bypass the cache. Scan status, history, and
commit-based results always fetch live data.

### Commands

#### `login`
Expand Down
69 changes: 69 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,9 @@
},
"devDependencies": {
"vitest": "^1.6.1"
},
"optionalDependencies": {
"@keyv/sqlite": "6.1.0",
"keyv": "6.1.0"
}
}
124 changes: 124 additions & 0 deletions src/utils/apiCacheStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { access, mkdir, open } from 'node:fs/promises';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';

const MAX_DATABASE_BYTES = 64 * 1024 * 1024;
const MAX_ENTRY_BYTES = 1024 * 1024;
const LOCK_TIMEOUT_MS = 50;
const CLEANUP_INTERVAL_MS = 60_000;
const EVICTION_BATCH_SIZE = 64;
const TABLE = 'fetch_api_cache';

let connection;

async function openStore(file) {
const [version, minor] = process.versions.node.split('.').map(Number);
if (version < 22 || (version === 22 && minor < 19)) return;

const drivers = await Promise.all([
import('keyv'),
import('@keyv/sqlite'),
import('node:sqlite'),
]).catch(() => undefined);
if (!drivers) return;

const [{ default: Keyv }, { default: KeyvSqlite }] = drivers;
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
const handle = await open(file, 'a', 0o600);
await handle.close();

const store = new KeyvSqlite({
uri: `sqlite://${file}`,
table: TABLE,
driver: 'node:sqlite',
busyTimeout: LOCK_TIMEOUT_MS,
});
try {
const [{ page_size: pageSize }] = await store.query('PRAGMA page_size');
const pageLimit = Math.floor(MAX_DATABASE_BYTES / pageSize);
const [{ max_page_count: maxPages }] = await store.query(`PRAGMA max_page_count = ${pageLimit}`);
if (maxPages > pageLimit) throw new Error('API cache exceeds its database size limit');
await store.clearExpired();
store.clearExpiredInterval = CLEANUP_INTERVAL_MS;
const keyv = new Keyv({ store });
// Keyv forwards adapter errors and throws when there is no listener.
keyv.on('error', () => {});
return { keyv, store, pageSize, pageLimit };
} catch (error) {
await store.disconnect().catch(() => {});
throw error;
}
}

async function getStore(create = true) {
if (connection) return connection;

const file = join(homedir(), '.codeant', 'cache', 'fetch-api.sqlite');
if (!create) {
try {
await access(file);
} catch {
return;
}
}

connection ??= openStore(file).catch(() => {
connection = undefined;
});
return connection;
}

export async function readCachedData(key) {
const cache = await getStore();
return cache?.keyv.get(key);
}

export async function writeCachedData(key, entry, ttl) {
const bytes = Buffer.byteLength(JSON.stringify({ value: entry, expires: Date.now() + ttl }));
if (bytes > MAX_ENTRY_BYTES) return;

const cache = await getStore();
if (!cache) return;
const { keyv, store, pageSize, pageLimit } = cache;

// The adapter reports SQLite write errors through its event and a false return.
let full = false;
const onError = (error) => {
if (error.errcode === 13 || error.code === 'SQLITE_FULL') full = true;
};
store.on('error', onError);
try {
if (await keyv.set(key, entry, ttl) || !full) return;
} finally {
store.off('error', onError);
}

await store.clearExpired();
const [{ page_count: pages }] = await store.query('PRAGMA page_count');
const [{ freelist_count: free }] = await store.query('PRAGMA freelist_count');
// Leave two pages for SQLite's record and index overhead.
if (pageLimit - pages + free < Math.ceil(bytes / pageSize) + 2) {
await store.query(
`DELETE FROM ${TABLE} WHERE rowid IN (
SELECT rowid FROM ${TABLE} WHERE expires IS NOT NULL ORDER BY expires LIMIT ?
)`,
EVICTION_BATCH_SIZE,
);
}
await keyv.set(key, entry, ttl);
}

export async function deleteCachedData(keys) {
const cache = await getStore(false);
await cache?.keyv.deleteMany(keys);
}

export async function clearCachedDataForCredential(credential) {
const cache = await getStore(false);
// The credential fingerprint is a fixed-length hex prefix followed by ':'.
await cache?.store.query(
`DELETE FROM ${TABLE} WHERE key >= ? AND key < ?`,
`${credential}:`,
`${credential};`,
);
}
Loading