mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 09:03:37 +01:00
perf(db): fix the slowest MongoDB queries from the last 24 hours
MongoDB's slow-query log (24 h, >100 ms) showed four shapes: - Admin repository search: a case-insensitive substring regex over four fields scanned all ~300k repositories, three times per page (up to 5.2 s each). Searches that are a repository ID or owner/name now match through the indexes first and only fall back to the regex otherwise. - Admin errors page owner lookup: repoId $in without the repoId index's collation was a full collection scan. It now uses the collation. - Status breakdown and home stats aggregates (~0.4 s over every repository, ~100 runs a day from admin polling): cached for a minute, and the admin overview uses the existing hourly home-stats cache. - Folder counts for large repositories (0.7-1.5 s, 400-550k index keys) are cached per tree generation, which never changes; legacy trees are keyed by commit for 5 minutes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8df674ef10
commit
24534823a3
5 files changed
+112
-35
No files matched your search
@@ -108,7 +108,7 @@ if includes(["api", "streamer"], service) {
|
||||
}
|
||||
}
|
||||
# BEGIN GENERATED DIAGNOSTICS
|
||||
source_functions = {"src/cli/index.ts":["<anonymous>","generateRandomFileName","main"],"build/cli/index.js":["<anonymous>","generateRandomFileName","main"],"src/config.ts":["<anonymous>"],"build/config.js":["<anonymous>"],"src/core/AnonymizedFile.ts":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"build/core/AnonymizedFile.js":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"src/core/AnonymousError.ts":["<anonymous>","detail","toString","url"],"build/core/AnonymousError.js":["<anonymous>","detail","toString","url"],"src/core/Conference.ts":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"build/core/Conference.js":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"src/core/Gist.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"src/core/Repository.ts":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"build/core/Repository.js":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"src/core/User.ts":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"build/core/User.js":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"src/core/anonymization-errors.ts":["<anonymous>","anonymLine truncated
|
||||
source_functions = {"src/cli/index.ts":["<anonymous>","generateRandomFileName","main"],"build/cli/index.js":["<anonymous>","generateRandomFileName","main"],"src/config.ts":["<anonymous>"],"build/config.js":["<anonymous>"],"src/core/AnonymizedFile.ts":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"build/core/AnonymizedFile.js":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"src/core/AnonymousError.ts":["<anonymous>","detail","toString","url"],"build/core/AnonymousError.js":["<anonymous>","detail","toString","url"],"src/core/Conference.ts":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"build/core/Conference.js":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"src/core/Gist.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"src/core/Repository.ts":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"build/core/Repository.js":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"src/core/User.ts":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"build/core/User.js":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"src/core/anonymization-errors.ts":["<anonymous>","anonymLine truncated
|
||||
for_each(["errorType", "causeType"]) -> |_index, key| {
|
||||
value = get(record, [key]) ?? null
|
||||
if includes(["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","HttpError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"], value) { out = set!(out, [key], value) }
|
||||
|
||||
+30
-12
@@ -4,6 +4,14 @@ import AnonymousError from "./AnonymousError";
|
||||
import FileModel from "./model/files/files.model";
|
||||
import { FILE_LISTING_LIMIT } from "./file-tree";
|
||||
import { anonymizePathCompiled, compileTerms } from "./anonymize-utils";
|
||||
import { AsyncCache } from "./async-cache";
|
||||
|
||||
// Counting a large repository's files scans its whole index range (0.5-1.5 s
|
||||
// for 400k+ files) and the tree browser asks again on every folder it opens.
|
||||
// A tree generation never changes, so its counts are cached; legacy trees are
|
||||
// keyed by commit and kept briefly.
|
||||
const generationCounts = new AsyncCache<{ _id: string; count: number }[]>(30 * 60_000, 512);
|
||||
const legacyCounts = new AsyncCache<{ _id: string; count: number }[]>(5 * 60_000, 128);
|
||||
|
||||
/** Only return the current folder and its immediate children, never a whole tree. */
|
||||
export async function folderCounts(repo: Repository, requestedPath: unknown): Promise<Record<string, number>> {
|
||||
@@ -36,18 +44,10 @@ export async function folderCounts(repo: Repository, requestedPath: unknown): Pr
|
||||
] } : { $arrayElemAt: [{ $split: ["$path", "/"] }, 0] }, count: { $sum: 1 } } },
|
||||
{ $limit: FILE_LISTING_LIMIT + 1 },
|
||||
]).option({ maxTimeMS: 2000, allowDiskUse: true });
|
||||
let rows: { _id: string; count: number }[];
|
||||
try {
|
||||
// The short planner trial can favor the size-first index despite its
|
||||
// document fetches. Legacy snapshots still use the default planner.
|
||||
rows = await aggregate().option(repo.model.treeGeneration ? { hint: "file_counts_covering" } : {}).exec();
|
||||
} catch (error) {
|
||||
// During an additive rollout the index may not be ready yet. Retry only
|
||||
// the missing-hint planning error, never timeouts or execution failures.
|
||||
if (!repo.model.treeGeneration || !(error instanceof Error) || !("code" in error) || error.code !== 2 ||
|
||||
!/hint provided does not correspond to an existing index/.test(error.message || "")) throw error;
|
||||
rows = await aggregate().exec();
|
||||
}
|
||||
const generation = repo.model.treeGeneration;
|
||||
const cache = generation ? generationCounts : legacyCounts;
|
||||
const key = JSON.stringify([repo.repoId, generation || `legacy:${repo.model.source?.commit || ""}`, originalPath]);
|
||||
const rows = await cache.get(key, () => countRows(!!generation, aggregate));
|
||||
if (rows.length > FILE_LISTING_LIMIT) throw new AnonymousError("file_listing_too_large", { httpStatus: 413 });
|
||||
const counts: Record<string, number> = Object.create(null);
|
||||
const compiled = compileTerms(repo.options.terms || []);
|
||||
@@ -61,3 +61,21 @@ export async function folderCounts(repo: Repository, requestedPath: unknown): Pr
|
||||
counts[requestedPath] = total;
|
||||
return counts;
|
||||
}
|
||||
|
||||
type CountRows = { _id: string; count: number }[];
|
||||
async function countRows(generation: boolean, aggregate: () => ReturnType<typeof FileModel.aggregate<{ _id: string; count: number }>>): Promise<CountRows> {
|
||||
try {
|
||||
// The short planner trial can favor the size-first index despite its
|
||||
// document fetches. Legacy snapshots still use the default planner.
|
||||
return await aggregate().option(generation ? { hint: "file_counts_covering" } : {}).exec();
|
||||
} catch (error) {
|
||||
// During an additive rollout the index may not be ready yet. Retry only
|
||||
// the missing-hint planning error, never timeouts or execution failures.
|
||||
if (!generation || !(error instanceof Error) || !("code" in error) || error.code !== 2 ||
|
||||
!/hint provided does not correspond to an existing index/.test(error.message || "")) throw error;
|
||||
return await aggregate().exec();
|
||||
}
|
||||
}
|
||||
|
||||
/** Test hook. */
|
||||
export function clearFolderCountCache() { generationCounts.clear(); legacyCounts.clear(); }
|
||||
@@ -969,11 +969,15 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"src/core/folder-counts.ts": [
|
||||
"<anonymous>",
|
||||
"aggregate",
|
||||
"clearFolderCountCache",
|
||||
"countRows",
|
||||
"folderCounts"
|
||||
],
|
||||
"build/core/folder-counts.js": [
|
||||
"<anonymous>",
|
||||
"aggregate",
|
||||
"clearFolderCountCache",
|
||||
"countRows",
|
||||
"folderCounts"
|
||||
],
|
||||
"src/core/github-app.ts": [
|
||||
@@ -1494,7 +1498,8 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"pump",
|
||||
"release",
|
||||
"settle",
|
||||
"spawn"
|
||||
"spawn",
|
||||
"start"
|
||||
],
|
||||
"build/core/preview-anonymizer.js": [
|
||||
"<anonymous>",
|
||||
@@ -1510,7 +1515,8 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"pump",
|
||||
"release",
|
||||
"settle",
|
||||
"spawn"
|
||||
"spawn",
|
||||
"start"
|
||||
],
|
||||
"src/core/process-monitoring.ts": [
|
||||
"<anonymous>",
|
||||
@@ -2567,9 +2573,11 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"src/server/routes/admin.ts": [
|
||||
"<anonymous>",
|
||||
"adminUserFilter",
|
||||
"cachedStatusBreakdown",
|
||||
"csvEscape",
|
||||
"dashboardCache",
|
||||
"escapeRegex",
|
||||
"exactRepositoryMatches",
|
||||
"getErrorLogClient",
|
||||
"historyRows",
|
||||
"hourKey",
|
||||
@@ -2585,9 +2593,11 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"build/server/routes/admin.js": [
|
||||
"<anonymous>",
|
||||
"adminUserFilter",
|
||||
"cachedStatusBreakdown",
|
||||
"csvEscape",
|
||||
"dashboardCache",
|
||||
"escapeRegex",
|
||||
"exactRepositoryMatches",
|
||||
"getErrorLogClient",
|
||||
"historyRows",
|
||||
"hourKey",
|
||||
|
||||
+45
-19
@@ -11,12 +11,13 @@ import { Queue, JobType } from "bullmq";
|
||||
import * as express from "express";
|
||||
import AnonymousError from "../../core/AnonymousError";
|
||||
import AnonymizedRepositoryModel from "../../core/model/anonymizedRepositories/anonymizedRepositories.model";
|
||||
import { REPOSITORY_ID_COLLATION } from "../../core/repository-id";
|
||||
import ConferenceModel from "../../core/model/conference/conferences.model";
|
||||
import UserModel from "../../core/model/users/users.model";
|
||||
import { addRemovalJob, cacheQueue, downloadQueue, removeQueue } from "../../queue";
|
||||
import { queryMetrics } from "../../queue/queueMetrics";
|
||||
import {
|
||||
computeStats,
|
||||
getCurrentStats,
|
||||
HomeStatsHistoryRow,
|
||||
mergeCurrentStatsIntoHistory,
|
||||
} from "../dailyStatsSnapshot";
|
||||
@@ -121,7 +122,9 @@ async function issueNames(repoIds: string[], userIds: string[]) {
|
||||
const users: Record<string, string> = {};
|
||||
if (AnonymizedRepositoryModel.db.readyState !== 1 || (!repoIds.length && !userIds.length)) return { repos, users };
|
||||
try {
|
||||
const found = repoIds.length ? await AnonymizedRepositoryModel.find({ repoId: { $in: repoIds.slice(0, 100) } }, { repoId: 1, owner: 1, status: 1, "source.repositoryName": 1 }).lean().maxTimeMS(2000) : [];
|
||||
const found = repoIds.length ? await AnonymizedRepositoryModel.find({ repoId: { $in: repoIds.slice(0, 100) } }, { repoId: 1, owner: 1, status: 1, "source.repositoryName": 1 })
|
||||
// The repoId index is case-insensitive; without its collation this scanned all repositories.
|
||||
.collation(REPOSITORY_ID_COLLATION).lean().maxTimeMS(2000) : [];
|
||||
const owners = [...new Set([...found.map(repo => String(repo.owner || "")).filter(id => /^[a-f0-9]{24}$/.test(id)), ...userIds.slice(0, 100)])];
|
||||
const named = owners.length ? await UserModel.find({ _id: { $in: owners } }, { username: 1 }).lean().maxTimeMS(2000) : [];
|
||||
for (const user of named) users[String(user._id)] = String(user.username);
|
||||
@@ -208,6 +211,25 @@ function pickQueue(name: string): Queue | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** IDs of repositories whose repoId or source owner/name equals the search, through their indexes. */
|
||||
export async function exactRepositoryMatches(search: string) {
|
||||
const term = search.trim();
|
||||
if (!/^[A-Za-z0-9_.-]{1,200}(?:\/[A-Za-z0-9_.-]{1,200})?$/.test(term)) return [];
|
||||
const [byId, bySource] = await Promise.all([
|
||||
term.includes("/") ? [] : AnonymizedRepositoryModel.find({ repoId: term }, { _id: 1 })
|
||||
.collation(REPOSITORY_ID_COLLATION).limit(1).lean().maxTimeMS(2000),
|
||||
AnonymizedRepositoryModel.find({ "source.repositoryName": term }, { _id: 1 }).limit(1000).lean().maxTimeMS(2000),
|
||||
]);
|
||||
return [...byId, ...bySource].map(repo => repo._id);
|
||||
}
|
||||
|
||||
// Repository counts by status sum a field over every repository (300k docs,
|
||||
// ~0.4 s). Admin pages poll them; a minute-old breakdown is fine.
|
||||
const statusBreakdownCache = new AsyncCache<{ _id: string; count: number; storage: number }[]>(60_000, 1);
|
||||
const cachedStatusBreakdown = () => statusBreakdownCache.get("all", () => AnonymizedRepositoryModel.aggregate([
|
||||
{ $group: { _id: "$status", count: { $sum: 1 }, storage: { $sum: "$size.storage" } } },
|
||||
]));
|
||||
|
||||
function escapeRegex(s: string): string {
|
||||
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
||||
}
|
||||
@@ -796,9 +818,7 @@ router.get("/overview", async (req, res) => {
|
||||
rCounts,
|
||||
cCounts,
|
||||
] = await Promise.all([
|
||||
AnonymizedRepositoryModel.aggregate([
|
||||
{ $group: { _id: "$status", count: { $sum: 1 }, storage: { $sum: "$size.storage" } } },
|
||||
]),
|
||||
cachedStatusBreakdown(),
|
||||
AnonymizedRepositoryModel.countDocuments({
|
||||
status: "error",
|
||||
statusDate: { $gte: now24h },
|
||||
@@ -880,7 +900,7 @@ router.get("/overview", async (req, res) => {
|
||||
nbPageViews: d.nbPageViews,
|
||||
nbPullRequests: d.nbPullRequests,
|
||||
}));
|
||||
history = mergeCurrentStatsIntoHistory(rows, await computeStats());
|
||||
history = mergeCurrentStatsIntoHistory(rows, await getCurrentStats());
|
||||
} catch {
|
||||
// DailyStats collection might not exist yet
|
||||
}
|
||||
@@ -943,9 +963,7 @@ router.get("/stats", async (req, res) => {
|
||||
try {
|
||||
const [statusBreakdown, recentErrors, totalUsers, totalConferences] =
|
||||
await Promise.all([
|
||||
AnonymizedRepositoryModel.aggregate([
|
||||
{ $group: { _id: "$status", count: { $sum: 1 }, storage: { $sum: "$size.storage" } } },
|
||||
]),
|
||||
cachedStatusBreakdown(),
|
||||
AnonymizedRepositoryModel.countDocuments({
|
||||
status: "error",
|
||||
statusDate: { $gte: new Date(Date.now() - 1000 * 60 * 60 * 24) },
|
||||
@@ -982,16 +1000,24 @@ router.get("/repos", async (req, res) => {
|
||||
|
||||
// multi-field search: repoId, source.repositoryName, statusMessage, conference
|
||||
if (req.query.search) {
|
||||
const escaped = escapeRegex(req.query.search as string);
|
||||
const re = { $regex: escaped, $options: "i" };
|
||||
query.push({
|
||||
$or: [
|
||||
{ repoId: re },
|
||||
{ "source.repositoryName": re },
|
||||
{ statusMessage: re },
|
||||
{ conference: re },
|
||||
],
|
||||
});
|
||||
const search = req.query.search as string;
|
||||
// Most searches are a repository ID or owner/name copied from a link or
|
||||
// the errors page. Those use the indexes; a case-insensitive substring
|
||||
// regex scans all 300k repositories (5 s, three times per page).
|
||||
const exact = await exactRepositoryMatches(search);
|
||||
if (exact.length) {
|
||||
query.push({ _id: { $in: exact } });
|
||||
} else {
|
||||
const re = { $regex: escapeRegex(search), $options: "i" };
|
||||
query.push({
|
||||
$or: [
|
||||
{ repoId: re },
|
||||
{ "source.repositoryName": re },
|
||||
{ statusMessage: re },
|
||||
{ conference: re },
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// filter by owner username
|
||||
|
||||
@@ -6,7 +6,7 @@ const Repository = require("../src/core/Repository").default;
|
||||
const Repo = require("../src/core/model/anonymizedRepositories/anonymizedRepositories.model").default;
|
||||
const File = require("../src/core/model/files/files.model").default;
|
||||
const Path = require("../src/core/model/anonymized-path").default;
|
||||
const { folderCounts } = require("../src/core/folder-counts");
|
||||
const { folderCounts, clearFolderCountCache } = require("../src/core/folder-counts");
|
||||
const { FILE_LISTING_LIMIT } = require("../src/core/file-tree");
|
||||
const uri = process.env.PERFORMANCE_MONGO_URI;
|
||||
|
||||
@@ -45,6 +45,7 @@ describe("folder count request validation", () => {
|
||||
});
|
||||
after(async () => { db.isConnected = false; await mongoose.connection.dropDatabase(); await mongoose.disconnect(); });
|
||||
beforeEach(async () => {
|
||||
clearFolderCountCache(); // Tests reuse one repository ID and generation with new files.
|
||||
await Promise.all([Repo, File, Path].map(model => model.deleteMany({})));
|
||||
repo = new Repository(await Repo.create({ repoId: "counts", owner: new mongoose.Types.ObjectId(), status: "ready",
|
||||
statusDate: new Date(), anonymizeDate: new Date(), treeGeneration: "active", source: { type: "GitHubStream", repositoryName: "fixture/repo" }, options: { terms: [] } }));
|
||||
@@ -138,6 +139,28 @@ describe("folder count request validation", () => {
|
||||
expect(await folderCounts(new Repository(await Repo.findById(repo.model._id)), "")).to.deep.equal({ "": 2, new: 2 });
|
||||
});
|
||||
|
||||
it("counts a tree generation once, then serves it from cache with the current terms", async () => {
|
||||
await insert([{ path: "src", name: "a.js", size: 1 }, { path: "src", name: "b.js", size: 1 }]);
|
||||
expect(await folderCounts(repo, "")).to.deep.equal({ "": 2, src: 2 });
|
||||
const original = File.aggregate;
|
||||
let queries = 0;
|
||||
File.aggregate = function (...args) { queries++; return original.apply(this, args); };
|
||||
try {
|
||||
repo.model.options.terms = ["src"];
|
||||
expect(await folderCounts(repo, "")).to.deep.equal({ "": 2, "XXXX-1": 2 });
|
||||
expect(queries).to.equal(0);
|
||||
} finally { File.aggregate = original; }
|
||||
});
|
||||
|
||||
it("finds admin repository searches by exact ID or source name through the indexes", async () => {
|
||||
const { exactRepositoryMatches } = require("../src/server/routes/admin");
|
||||
const ids = matches => matches.map(String);
|
||||
expect(ids(await exactRepositoryMatches("COUNTS"))).to.deep.equal([String(repo.model._id)]);
|
||||
expect(ids(await exactRepositoryMatches("fixture/repo"))).to.deep.equal([String(repo.model._id)]);
|
||||
expect(await exactRepositoryMatches("fixture")).to.deep.equal([]);
|
||||
expect(await exactRepositoryMatches("not a repo id")).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("keeps a hard bound for over-wide responses", async () => {
|
||||
for (let offset = 0; offset <= FILE_LISTING_LIMIT; offset += 500) await insert(Array.from({
|
||||
length: Math.min(500, FILE_LISTING_LIMIT + 1 - offset),
|
||||
|
||||
Reference in new issue
Block a user