diff --git a/README.md b/README.md index 256e117..6b9dee1 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,13 @@ codeant review codeant [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` diff --git a/package-lock.json b/package-lock.json index d854cad..096f305 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,12 +10,14 @@ "license": "MIT", "dependencies": { "@gitbeaker/rest": "^43.8.0", + "@keyv/sqlite": "6.1.0", "@modelcontextprotocol/sdk": "^1.29.0", "@octokit/rest": "^22.0.1", "azure-devops-node-api": "^15.1.2", "bitbucket": "^2.12.0", "commander": "^12.1.0", "ink": "^5.0.1", + "keyv": "6.1.0", "minimatch": "^10.1.1", "open": "^10.1.0", "posthog-node": "^5.28.5", @@ -28,6 +30,10 @@ }, "devDependencies": { "vitest": "^1.6.1" + }, + "optionalDependencies": { + "@keyv/sqlite": "6.1.0", + "keyv": "6.1.0" } }, "node_modules/@alcalzone/ansi-tokenize": { @@ -132,6 +138,23 @@ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", "dev": true }, + "node_modules/@keyv/sqlite": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@keyv/sqlite/-/sqlite-6.1.0.tgz", + "integrity": "sha512-298muS2rnBHP39QlH80NXmkWuwy5sLY5S0a6+d7aSQFLNrsk5q4PDCzYqKFGZFyj1Ir+yFwumPmVsZeRrKIIwQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "better-sqlite3": "^13.0.3", + "hookified": "^3.0.3" + }, + "engines": { + "node": ">= 22.19.0" + }, + "peerDependencies": { + "keyv": "^6.1.0" + } + }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.29.0", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", @@ -872,6 +895,19 @@ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz", "integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==" }, + "node_modules/better-sqlite3": { + "version": "13.2.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.2.0.tgz", + "integrity": "sha512-Z8Q/9x/uNyKxA1v4FNodyItRVRw1TeKBrmj32JhxhR0ceNcBY+wMobt/Bv7M7TzwPAXjnZRtNaEsATnUZSKWZQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "node-addon-api": "^8.0.0" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/bitbucket": { "version": "2.12.0", "resolved": "https://registry.npmjs.org/bitbucket/-/bitbucket-2.12.0.tgz", @@ -1734,6 +1770,16 @@ "node": ">=16.9.0" } }, + "node_modules/hookified": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-3.2.0.tgz", + "integrity": "sha512-l+Obd8gfynRIVdNtvFQiCsJrLaghdaxOEIGK86qynrbHUT+CMff3PF4ANjMChCMOCidNO0BNjq+qVWK8hlnoUA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=22.18.0" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -2000,6 +2046,19 @@ "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.8.tgz", "integrity": "sha512-eq/4KP6K34kwa7TcFdtvnftvHCD9KvHOGGICWwMFc4dOOKF5t4iYqnfLK8otCRCRv06FXOzGGyqE8h8ElMvvdw==" }, + "node_modules/keyv": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-6.1.0.tgz", + "integrity": "sha512-0OO64DxKOITdyQljNCcO+vc+iyaPmm3OV5eKOWRxWCp3V0QnXenpqcKfjGjycNILUJNV+erm1ose6Hsgr1fNFA==", + "license": "MIT", + "optional": true, + "dependencies": { + "hookified": "^3.0.3" + }, + "engines": { + "node": ">= 22.19.0" + } + }, "node_modules/local-pkg": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.1.tgz", @@ -2183,6 +2242,16 @@ "node": ">= 0.6" } }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", diff --git a/package.json b/package.json index b503db5..ed279db 100644 --- a/package.json +++ b/package.json @@ -69,5 +69,9 @@ }, "devDependencies": { "vitest": "^1.6.1" + }, + "optionalDependencies": { + "@keyv/sqlite": "6.1.0", + "keyv": "6.1.0" } } diff --git a/src/utils/apiCacheStore.js b/src/utils/apiCacheStore.js new file mode 100644 index 0000000..d82b306 --- /dev/null +++ b/src/utils/apiCacheStore.js @@ -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};`, + ); +} diff --git a/src/utils/fetchApi.js b/src/utils/fetchApi.js index 08b8257..da02163 100644 --- a/src/utils/fetchApi.js +++ b/src/utils/fetchApi.js @@ -1,4 +1,11 @@ +import { createHash } from 'node:crypto'; import { Agent, setGlobalDispatcher } from 'undici'; +import { + clearCachedDataForCredential, + deleteCachedData, + readCachedData, + writeCachedData, +} from './apiCacheStore.js'; import { getConfigValue } from './config.js'; import { getBaseUrl } from './baseUrl.js'; @@ -21,6 +28,58 @@ const RETRYABLE_CAUSES = new Set([ 'ENOTFOUND', ]); +const BRANCH_READ_PATHS = ['/extension/branches/all', '/extension/branches/default']; +const cacheableUrls = new Map([ + ['POST /extension/scans2/listrepos', { ttl: 300_000, valid: (data) => Array.isArray(data.repos) }], + ...BRANCH_READ_PATHS.map((path) => [`POST ${path}`, { ttl: 30_000 }]), +]); +// Scan results are selected by commit today. Until reads can identify an exact +// completed run, keep them and all status, history, and polling requests live. +let cacheGeneration = 0; +let cacheOperations = Promise.resolve(); + +function digest(value) { + return createHash('sha256').update(value).digest('hex'); +} + +function generateCacheKey(token, url, method, body, tenant) { + const scope = tenant && [tenant.organization, tenant.service, tenant.providerBaseUrl]; + return `${digest(token)}:${digest(JSON.stringify([1, url, method, body, scope]))}`; +} + +function queueCacheOperation(operation) { + const result = cacheOperations.then(operation).catch(() => undefined); + cacheOperations = result; + return result; +} + +function getCache(key) { + return queueCacheOperation(() => readCachedData(key)); +} + +function setCache(key, result, ttl, generation) { + return queueCacheOperation(() => { + if (generation !== cacheGeneration) return; + const { data, status } = result; + return writeCachedData(key, { data, status, lastSyncedAt: Date.now() }, ttl); + }); +} + +function invalidateFetchApiCache(keys) { + cacheGeneration += 1; + return queueCacheOperation(() => deleteCachedData(keys)); +} + +export function clearFetchApiCache(token) { + if (typeof token !== 'string' || !token) return; + cacheGeneration += 1; + return queueCacheOperation(() => clearCachedDataForCredential(digest(token))); +} + +function isApiError(data) { + return data?.status === 'error' || data?.success === false || Boolean(data?.error); +} + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function responseMessage(data, status) { @@ -59,7 +118,7 @@ async function parseResponse(response) { return text; } -const fetchApiResponse = async (endpoint, { +const requestApi = async (endpoint, { method = 'GET', body = null, headers = {}, @@ -67,7 +126,8 @@ const fetchApiResponse = async (endpoint, { allowHttpError = false, tenant = null, signal = undefined, -} = {}) => { + skipCache = false, +} = {}, cacheReads = false) => { const baseUrl = getBaseUrl(); const resolvedUrl = endpoint.startsWith('http') ? endpoint : `${baseUrl}${endpoint}`; const url = appendQuery(resolvedUrl, query); @@ -99,6 +159,21 @@ const fetchApiResponse = async (endpoint, { options.signal = signal; } + const path = endpoint.split('?')[0]; + const credential = typeof token === 'string' && token; + const cachePolicy = cacheReads && !skipCache && !signal?.aborted && + process.env.CODEANT_NO_CACHE !== '1' && credential && + cacheableUrls.get(`${normalizedMethod} ${path}`); + const generation = cacheGeneration; + const cacheKey = cachePolicy && generateCacheKey(token, url, normalizedMethod, options.body, tenant); + if (cacheKey) { + const cached = await getCache(cacheKey); + if (cached && generation === cacheGeneration) { + signal?.throwIfAborted(); + return { ok: true, status: cached.status, headers: {}, data: cached.data }; + } + } + // Retry transient network/cold-start failures up to 2 times. const MAX_ATTEMPTS = 3; let lastErr; @@ -120,12 +195,27 @@ const fetchApiResponse = async (endpoint, { throw error; } - return { + const result = { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data, }; + if (result.ok && !isApiError(data)) { + if (credential && normalizedMethod === 'POST' && + path === '/extension/branches/update-default' && typeof body?.repo === 'string') { + const branchBody = JSON.stringify({ repo: body.repo }); + const scopes = tenant ? [null, tenant] : [null]; + const keys = BRANCH_READ_PATHS.flatMap((readPath) => scopes.map((scope) => + generateCacheKey(token, `${baseUrl}${readPath}`, 'POST', branchBody, scope))); + await invalidateFetchApiCache(keys); + } + if (cacheKey && !signal?.aborted && data && typeof data === 'object' && + (!cachePolicy.valid || cachePolicy.valid(data))) { + await setCache(cacheKey, result, cachePolicy.ttl, generation); + } + } + return result; } catch (err) { lastErr = err; const cause = err?.cause?.code || err?.cause?.message || err?.cause || ''; @@ -142,13 +232,15 @@ const fetchApiResponse = async (endpoint, { throw lastErr; }; -const fetchApi = async (endpoint, method = 'GET', body = null) => { - const response = await fetchApiResponse(endpoint, { method, body }); +const fetchApiResponse = (endpoint, options) => requestApi(endpoint, options); + +const fetchApi = async (endpoint, method = 'GET', body = null, { skipCache, signal } = {}) => { + const response = await requestApi(endpoint, { method, body, skipCache, signal }, true); return response.data; }; -const fetchAppApi = async (endpoint, method = 'GET', body = null, tenant) => { - const response = await fetchApiResponse(endpoint, { method, body, tenant }); +const fetchAppApi = async (endpoint, method = 'GET', body = null, tenant, { skipCache, signal } = {}) => { + const response = await requestApi(endpoint, { method, body, tenant, skipCache, signal }, true); return response.data; }; diff --git a/src/utils/logout.js b/src/utils/logout.js index 6d193f4..8b1fe25 100644 --- a/src/utils/logout.js +++ b/src/utils/logout.js @@ -1,12 +1,13 @@ import { getConfigValue, setConfigValue } from './config.js'; -import { fetchApiResponse } from './fetchApi.js'; +import { clearFetchApiCache, fetchApiResponse } from './fetchApi.js'; const DEFAULT_LOGOUT_REVOCATION_TIMEOUT_MS = 3_000; export async function logoutCodeAnt({ revocationTimeoutMs = DEFAULT_LOGOUT_REVOCATION_TIMEOUT_MS, } = {}) { - const token = process.env.CODEANT_API_TOKEN?.trim() || getConfigValue('apiKeyV2'); + const environmentToken = process.env.CODEANT_API_TOKEN; + const token = environmentToken?.trim() || getConfigValue('apiKeyV2'); if (!token) return { wasLoggedIn: false, serverRevoked: false }; const controller = new AbortController(); @@ -26,6 +27,7 @@ export async function logoutCodeAnt({ clearTimeout(timeout); setConfigValue('apiKeyV2', null); delete process.env.CODEANT_API_TOKEN; + await clearFetchApiCache(environmentToken || token); } return { wasLoggedIn: true, serverRevoked, warning }; } diff --git a/tests/fetchApi.cache.test.js b/tests/fetchApi.cache.test.js new file mode 100644 index 0000000..8c244aa --- /dev/null +++ b/tests/fetchApi.cache.test.js @@ -0,0 +1,205 @@ +import { execFile } from 'node:child_process'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const exec = promisify(execFile); +const [major, minor] = process.versions.node.split('.').map(Number); +const supportsCache = (major > 22 || (major === 22 && minor >= 19)) && + await import('@keyv/sqlite').then(() => true, () => false); + +describe.skipIf(!supportsCache)('persistent fetchApi cache', () => { + let directory; + + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'codeant-fetch-cache-')); + }); + + afterEach(async () => { + await rm(directory, { recursive: true, force: true }); + }); + + async function run(script, now = 1_000_000, nodeArgs = []) { + const { stdout } = await exec(process.execPath, [...nodeArgs, '--input-type=module', '-e', ` + import assert from 'node:assert/strict'; + import { access, stat } from 'node:fs/promises'; + import { createHash } from 'node:crypto'; + import os from 'node:os'; + import { join } from 'node:path'; + import { syncBuiltinESMExports } from 'node:module'; + const { DatabaseSync } = await import('node:sqlite').catch(() => ({})); + + const directory = process.env.CODEANT_TEST_CACHE_HOME; + os.homedir = () => directory; + syncBuiltinESMExports(); + Date.now = () => ${now}; + const file = join(directory, '.codeant', 'cache', 'fetch-api.sqlite'); + const { clearFetchApiCache, fetchApi, fetchApiResponse, fetchAppApi } = + await import('./src/utils/fetchApi.js'); + const repoList = '/extension/scans2/listrepos'; + const branches = '/extension/branches/all'; + const defaultBranch = '/extension/branches/default'; + const updateBranch = '/extension/branches/update-default'; + const repo = 'acme/repo'; + let calls = 0; + globalThis.fetch = (url) => Response.json(new URL(url).pathname === repoList + ? { repos: [++calls] } : { branches: [++calls] }); + ${script} + `], { + timeout: 8_000, + env: { + ...process.env, + CODEANT_TEST_CACHE_HOME: directory, + CODEANT_API_TOKEN: 'cache-test-token', + CODEANT_API_URL: 'https://cache.test', + CODEANT_NO_CACHE: '', + }, + }); + return stdout.trim(); + } + + it.skipIf(!process.allowedNodeEnvironmentFlags.has('--no-experimental-sqlite'))( + 'uses live requests without creating a cache file when SQLite is disabled', + async () => { + await run(` + assert.deepEqual(await fetchApi(repoList, 'POST', { org: 'acme' }), { repos: [1] }); + assert.deepEqual(await fetchApi(repoList, 'POST', { org: 'acme' }), { repos: [2] }); + await assert.rejects(access(file), { code: 'ENOENT' }); + `, undefined, ['--no-experimental-sqlite']); + }, + ); + + it('reuses responses across processes and clears expired rows on first use', async () => { + await run(` + assert.deepEqual(await fetchApi(repoList, 'POST', { org: 'acme' }), { repos: [1] }); + assert.deepEqual(await fetchApi(branches, 'POST', { repo }), { branches: [2] }); + `); + await run(` + assert.deepEqual(await fetchApi(repoList, 'POST', { org: 'acme' }), { repos: [1] }); + assert.equal(calls, 0); + const db = new DatabaseSync(file); + assert.equal(db.prepare('SELECT count(*) AS count FROM fetch_api_cache').get().count, 1); + db.close(); + assert.deepEqual(await fetchApi(branches, 'POST', { repo }), { branches: [1] }); + assert.equal(calls, 1); + `, 1_031_000); + }); + + it('scopes entries to the request, tenant, credential, and API host', async () => { + await run(` + const tenant = { organization: 'acme', service: 'github', providerBaseUrl: '' }; + const read = (org, scope = tenant) => fetchAppApi(repoList, 'POST', { org }, scope); + assert.deepEqual(await read('acme'), { repos: [1] }); + assert.deepEqual(await read('acme'), { repos: [1] }); + await read('other'); + await read('acme', { ...tenant, organization: 'other' }); + await fetchAppApi(repoList + '?offset=5', 'POST', { org: 'acme' }, tenant); + process.env.CODEANT_API_URL = 'https://other.test'; + await read('acme'); + process.env.CODEANT_API_URL = 'https://cache.test'; + process.env.CODEANT_API_TOKEN = 'second-token'; + await read('acme'); + assert.equal(calls, 6); + await clearFetchApiCache('cache-test-token'); + assert.deepEqual(await read('acme'), { repos: [6] }); + process.env.CODEANT_API_TOKEN = 'cache-test-token'; + assert.deepEqual(await read('acme'), { repos: [7] }); + `); + }); + + it('evicts branch entries after a successful update and rejects an older in-flight write', async () => { + await run(` + await fetchApi(defaultBranch, 'POST', { repo }); + await fetchApi(defaultBranch, 'POST', { repo: 'acme/other' }); + let finishOlder; + let startOlder; + const started = new Promise((resolve) => { startOlder = resolve; }); + const nextFetch = globalThis.fetch; + globalThis.fetch = (url) => { + if (new URL(url).pathname !== branches || finishOlder) return nextFetch(url); + startOlder(); + return new Promise((resolve) => { finishOlder = resolve; }); + }; + const older = fetchApi(branches, 'POST', { repo }); + await started; + await fetchApi(updateBranch, 'POST', { repo, branch: 'next' }); + finishOlder(Response.json({ branches: ['old'] })); + assert.deepEqual(await older, { branches: ['old'] }); + assert.deepEqual(await fetchApi(branches, 'POST', { repo }), { branches: [4] }); + assert.deepEqual(await fetchApi(defaultBranch, 'POST', { repo }), { branches: [5] }); + assert.deepEqual(await fetchApi(defaultBranch, 'POST', { repo: 'acme/other' }), { branches: [2] }); + `); + }); + + it('bypasses raw requests, opt-outs, invalid replies, and live scan results', async () => { + await run(` + const body = { org: 'acme' }; + const read = () => fetchApi(repoList, 'POST', body); + await read(); + await fetchApiResponse(repoList, { method: 'POST', body }); + await fetchApi(repoList, 'POST', body, { skipCache: true }); + process.env.CODEANT_NO_CACHE = '1'; + await read(); + delete process.env.CODEANT_NO_CACHE; + assert.equal(calls, 4); + assert.deepEqual(await read(), { repos: [1] }); + globalThis.fetch = () => Response.json({ status: 'error', repos: [++calls] }); + const readError = () => fetchApi(repoList, 'POST', { org: 'error' }); + await readError(); + await readError(); + assert.equal(calls, 6); + + const states = ['running', 'done', 'running', undefined, 'done']; + globalThis.fetch = () => Response.json({ status: states.shift(), results: [++calls] }); + const scan = { repo, commit_id: 'same-commit', result_type: 'anti_patterns' }; + for (const status of [...states]) { + assert.equal((await fetchApi('/extension/scans2/fetch-results', 'POST', scan)).status, status); + } + assert.equal(calls, 11); + `); + }); + + it('bypasses a locked database and skips oversized entries', async () => { + await run(` + await fetchApi(repoList, 'POST', { org: 'acme' }); + const db = new DatabaseSync(file); + db.exec('BEGIN EXCLUSIVE'); + try { + assert.deepEqual(await fetchApi(repoList, 'POST', { org: 'acme' }), { repos: [2] }); + } finally { + db.exec('ROLLBACK'); + db.close(); + } + globalThis.fetch = () => Response.json({ repos: [{ id: ++calls, value: 'x'.repeat(1024 * 1024) }] }); + await fetchApi(repoList, 'POST', { org: 'large' }); + await fetchApi(repoList, 'POST', { org: 'large' }); + assert.equal(calls, 4); + `); + }); + + it('evicts earliest-expiring rows when the database reaches its size limit', async () => { + await run(` + globalThis.fetch = () => Response.json({ repos: [{ id: ++calls, value: 'x'.repeat(950_000) }] }); + let now = Date.now(); + Date.now = () => now++; + for (let i = 0; i < 68; i++) await fetchApi(repoList, 'POST', { org: String(i) }); + `); + await run(` + globalThis.fetch = () => Response.json({ repos: [{ id: ++calls, value: 'x'.repeat(950_000) }] }); + assert.equal((await fetchApi(repoList, 'POST', { org: '0' })).repos[0].id, 1); + assert.equal(calls, 0); + for (let i = 68; i < 75; i++) await fetchApi(repoList, 'POST', { org: String(i) }); + assert.ok((await stat(file)).size <= 64 * 1024 * 1024); + const db = new DatabaseSync(file); + const firstKey = createHash('sha256').update(JSON.stringify([ + 1, 'https://cache.test' + repoList, 'POST', JSON.stringify({ org: '0' }), null, + ])).digest('hex'); + assert.equal(db.prepare('SELECT 1 FROM fetch_api_cache WHERE key LIKE ?').get('%:' + firstKey), undefined); + db.close(); + assert.equal((await fetchApi(repoList, 'POST', { org: '74' })).repos[0].id, 7); + assert.equal(calls, 7); + `, 1_010_000); + }, 10_000); +}); diff --git a/tests/logout.test.js b/tests/logout.test.js index d9ec717..c5d6ae1 100644 --- a/tests/logout.test.js +++ b/tests/logout.test.js @@ -1,18 +1,20 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -const { fetchApiResponse, getConfigValue, setConfigValue } = vi.hoisted(() => ({ +const { clearFetchApiCache, fetchApiResponse, getConfigValue, setConfigValue } = vi.hoisted(() => ({ + clearFetchApiCache: vi.fn(), fetchApiResponse: vi.fn(), getConfigValue: vi.fn(), setConfigValue: vi.fn(), })); -vi.mock('../src/utils/fetchApi.js', () => ({ fetchApiResponse })); +vi.mock('../src/utils/fetchApi.js', () => ({ clearFetchApiCache, fetchApiResponse })); vi.mock('../src/utils/config.js', () => ({ getConfigValue, setConfigValue })); const { logoutCodeAnt } = await import('../src/utils/logout.js'); describe('logoutCodeAnt', () => { beforeEach(() => { + clearFetchApiCache.mockReset(); fetchApiResponse.mockReset(); getConfigValue.mockReset(); setConfigValue.mockReset(); @@ -34,6 +36,7 @@ describe('logoutCodeAnt', () => { signal: expect.any(AbortSignal), }); expect(setConfigValue).toHaveBeenCalledWith('apiKeyV2', null); + expect(clearFetchApiCache).toHaveBeenCalledWith('key'); }); it('still clears the local key and reports when revocation cannot be confirmed', async () => { @@ -45,6 +48,7 @@ describe('logoutCodeAnt', () => { expect(result.serverRevoked).toBe(false); expect(result.warning).toMatch(/could not be confirmed.*offline/); expect(setConfigValue).toHaveBeenCalledWith('apiKeyV2', null); + expect(clearFetchApiCache).toHaveBeenCalledWith('key'); }); it('bounds server revocation and still clears local authentication', async () => { @@ -68,6 +72,7 @@ describe('logoutCodeAnt', () => { }); expect(setConfigValue).toHaveBeenCalledWith('apiKeyV2', null); expect(process.env.CODEANT_API_TOKEN).toBeUndefined(); + expect(clearFetchApiCache).toHaveBeenCalledWith('environment-key'); } finally { vi.useRealTimers(); }