mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-04 01:53:28 +01:00
fix(preview): anonymize form previews on a worker, trace slow ones to their project
A user's backtracking term made each anonymize-form preview block the API's event loop for ~1.2 s and fail with a 500. One per keystroke, 45 of them froze every request for about a minute (12:59 UTC, 2026-11-30). - Previews run on their own worker pool (1 worker by default). A preview that runs past its deadline (3 s) terminates its worker and answers 422 anonymization_timeout; the form explains the term is too slow. - One preview per user: a newer edit, or the client leaving, stops the older preview (409 preview_superseded, logged at info). - Slow (>=500 ms) or failed previews log an anonymization_preview record with the project's repoId, input bytes and term count. - Heartbeats carry the interval's worst event-loop delay (loopMaxMs, loopP99Ms); a delay of 1 s or more logs event_loop_blocked at warn. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
049195439a
commit
fc14b2c3ae
16 files changed
+385
-73
No files matched your search
@@ -0,0 +1,23 @@
|
||||
import { anonymizationErrorCode } from "./anonymization-errors";
|
||||
import config from "../config";
|
||||
import { parentPort } from "worker_threads";
|
||||
import { ContentAnonimizer } from "./anonymize-utils";
|
||||
|
||||
// Anonymizes the form's preview snippets off the API's main thread. A term
|
||||
// that backtracks only stalls this worker; the pool terminates it on its
|
||||
// deadline. Only outputs or a fixed error code cross the boundary.
|
||||
parentPort!.on("message", ({ id, contents, options, context }: {
|
||||
id: number; contents: string[]; options: ConstructorParameters<typeof ContentAnonimizer>[0];
|
||||
context: { mask: string; hostname: string };
|
||||
}) => {
|
||||
try {
|
||||
config.ANONYMIZATION_MASK = context.mask;
|
||||
config.APP_HOSTNAME = context.hostname;
|
||||
const outputs = contents.map(content => new ContentAnonimizer(options).anonymize(content));
|
||||
parentPort!.postMessage({ id, outputs });
|
||||
} catch (error) {
|
||||
parentPort!.postMessage({ id, error: anonymizationErrorCode(error) });
|
||||
}
|
||||
});
|
||||
// Startup (module loading) does not count against a preview's deadline.
|
||||
parentPort!.postMessage({ ready: true });
|
||||
@@ -376,6 +376,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"removeWaiting",
|
||||
"reserveSpool"
|
||||
],
|
||||
"src/core/anonymization-preview.worker.ts": [
|
||||
"<anonymous>"
|
||||
],
|
||||
"build/core/anonymization-preview.worker.js": [
|
||||
"<anonymous>"
|
||||
],
|
||||
"src/core/anonymization.worker.ts": [
|
||||
"<anonymous>"
|
||||
],
|
||||
@@ -1474,6 +1480,38 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"normalizePreserveFiles",
|
||||
"parsePattern"
|
||||
],
|
||||
"src/core/preview-anonymizer.ts": [
|
||||
"<anonymous>",
|
||||
"anonymizePreview",
|
||||
"finish",
|
||||
"forget",
|
||||
"getPreviewPoolStats",
|
||||
"onAbort",
|
||||
"onError",
|
||||
"onExit",
|
||||
"onMessage",
|
||||
"previewError",
|
||||
"pump",
|
||||
"release",
|
||||
"settle",
|
||||
"spawn"
|
||||
],
|
||||
"build/core/preview-anonymizer.js": [
|
||||
"<anonymous>",
|
||||
"anonymizePreview",
|
||||
"finish",
|
||||
"forget",
|
||||
"getPreviewPoolStats",
|
||||
"onAbort",
|
||||
"onError",
|
||||
"onExit",
|
||||
"onMessage",
|
||||
"previewError",
|
||||
"pump",
|
||||
"release",
|
||||
"settle",
|
||||
"spawn"
|
||||
],
|
||||
"src/core/process-monitoring.ts": [
|
||||
"<anonymous>",
|
||||
"installFatalErrorLogging",
|
||||
@@ -2563,10 +2601,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"sendCsv"
|
||||
],
|
||||
"src/server/routes/anonymize-preview.ts": [
|
||||
"<anonymous>"
|
||||
"<anonymous>",
|
||||
"traceSlow"
|
||||
],
|
||||
"build/server/routes/anonymize-preview.js": [
|
||||
"<anonymous>"
|
||||
"<anonymous>",
|
||||
"traceSlow"
|
||||
],
|
||||
"src/server/routes/auth-utils.ts": [
|
||||
"<anonymous>",
|
||||
@@ -3107,4 +3147,4 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
};
|
||||
export const LOG_ERROR_TYPES = ["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","HttpError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"];
|
||||
export const LOG_ROUTES = ["/","other","/dashboard","/anonymize","/healthcheck","/api/healthcheck","/api","/api/download","/api/stat","/api/stat/history","/api/options","/api/message","/api/user","/api/user/quota","/api/user/dashboard","/api/repo","/api/anonymize-preview","/api/admin/overview","/api/admin/performance","/api/admin/errors","/api/admin/errors/stats","/api/admin/queues","/api/admin/queues/metrics","/github/app/webhook","/api/repo/:repoId","/api/repo/:repoId/file/:path","/api/repo/:repoId/files","/api/repo/:repoId/files/counts","/api/repo/:repoId/files/search","/api/repo/:repoId/zip","/api/repo/:repoId/options","/api/repo/:repoId/refresh","/api/repo/:repoId/coauthors","/api/repo/:repoId/extend","/api/repo/:owner/:repo","/api/repo/:owner/:repo/tree","/api/repo/:owner/:repo/file","/api/repo/:owner/:repo/readme","/api/repo/:owner/:repo/branches","/w/:repoId/:path","/r/:repoId/:path","/api/pr/:id/:path","/api/gist/:id/:path","/assets/:path","/github/:action","/api/admin/:action","/api/user/:action","/api/repo/:id/file/:path","/api/repo/:id/files/counts","/api/repo/:id/files/search","/api/repo/:id/files","/api/repo/:id/zip","/api/repo/:id","/viewer/:id/:path","/api/billing","/api/billing/draft","/api/billing/draft/:id","/api/billing/checkout","/api/billing/portal","/api/billing/refresh","/api/billing/webhook","/api/conferences/plans","/profile","/conference/:id"];
|
||||
export const LOG_THROWN_ERROR_CODES = ["another_login_required","billing_address_missing","billing_already_paid","billing_busy","billing_checkout_disabled","billing_checkout_in_progress","billing_city_missing","billing_country_missing","billing_customer_mismatch","billing_draft_not_found","billing_email_missing","billing_invalid_conference","billing_invalid_draft","billing_invalid_purchase","billing_invalid_repository_size","billing_invalid_review_window","billing_missing","billing_name_missing","billing_plan_change_not_supported","billing_plan_unavailable","billing_price_misconfigured","billing_recovery_required","billing_review_window_locked","billing_subscription_exists","billing_unavailable","billing_zip_missing","branch_not_found","branch_not_specified","cache_busy","cache_miss","cannot_coauthor_self","commit_not_found","commit_not_specified","conf_end_date_invalid","conf_end_date_missing","conf_id_missing","conf_id_used","conf_name_missing","conf_not_activated","conf_not_found","conf_start_date_invalid","conf_start_date_missing","conference_not_found","conference_payment_required","connection_changed","download_not_enabled","expiration_limit_reached","file_listing_too_large","file_not_accessible","file_not_found","file_not_supported","file_too_big","folder_not_supported","gistId_already_used","gistId_not_specified","gist_expired","gist_not_available","gist_not_found","gist_not_ready","github_app_access_required","github_app_authorization_cancelled","github_app_disabled","github_app_permissions_invalid","github_app_reconnect_required","github_app_refresh_busy","github_grant_revocation_failed","github_identity_mismatch","github_oauth_required","github_rate_limit_exceeded","github_unavailable","github_user_not_found","invalid_auth_state","invalid_billing_expiration","invalid_commit_format","invalid_connection","invalid_cursor","invalid_file_path","invalid_gistId","invalid_github_path","invalid_path","invalid_plan","invalid_preserve_files_format","invalid_project_name","invalid_pullRequestId","invalid_repo","invalid_repoId","invalid_request","invalid_settings","invalid_sort","invalid_status","invalid_terms_format","invalid_token_id","invalid_token_options","is_removed","not_authorized","not_connected","not_owner","oauth_resources_remaining","options_not_provided","page_not_activated","page_not_supported_on_different_branch","path_not_defined","path_not_specified","pullRequestId_already_used","pullRequestId_is_not_a_number","pullRequestId_not_specified","pull_request_expired","pull_request_not_available","pull_request_not_found","pull_request_not_ready","quota_exceeded","quota_repository_limit","quota_storage_limit","rate_limited","readme_not_available","repoId_already_used","repoId_not_defined","repoUrl_not_defined","repo_access_limited","repo_empty","repo_not_accessible","repo_not_found","repo_saml_enforcement","repository_archived","repository_busy","repository_changed","repository_expired","repository_job_cancelled","repository_not_accessible","repository_not_ready","repository_not_specified","repository_tree_incomplete","repository_tree_too_large","s3_config_not_provided","source_not_provided","storage_delete_failed","storage_write_size_mismatch","streamer_route_not_found","streamer_unexpected_response","streamer_unreachable","streamer_upstream_error","submodule_not_available","subscription_required_for_never_expiration","sync_failed","terms_not_specified","token_expired","token_limit_reached","unable_to_connect_user","unable_to_download","upstream_error","user_banned","user_not_found","username_not_defined","zip_not_available","zip_unsafe_entry_path"];
|
||||
export const LOG_THROWN_ERROR_CODES = ["anonymization_timeout","anonymization_worker_failed","another_login_required","billing_address_missing","billing_already_paid","billing_busy","billing_checkout_disabled","billing_checkout_in_progress","billing_city_missing","billing_country_missing","billing_customer_mismatch","billing_draft_not_found","billing_email_missing","billing_invalid_conference","billing_invalid_draft","billing_invalid_purchase","billing_invalid_repository_size","billing_invalid_review_window","billing_missing","billing_name_missing","billing_plan_change_not_supported","billing_plan_unavailable","billing_price_misconfigured","billing_recovery_required","billing_review_window_locked","billing_subscription_exists","billing_unavailable","billing_zip_missing","branch_not_found","branch_not_specified","cache_busy","cache_miss","cannot_coauthor_self","commit_not_found","commit_not_specified","conf_end_date_invalid","conf_end_date_missing","conf_id_missing","conf_id_used","conf_name_missing","conf_not_activated","conf_not_found","conf_start_date_invalid","conf_start_date_missing","conference_not_found","conference_payment_required","connection_changed","download_not_enabled","expiration_limit_reached","file_listing_too_large","file_not_accessible","file_not_found","file_not_supported","file_too_big","folder_not_supported","gistId_already_used","gistId_not_specified","gist_expired","gist_not_available","gist_not_found","gist_not_ready","github_app_access_required","github_app_authorization_cancelled","github_app_disabled","github_app_permissions_invalid","github_app_reconnect_required","github_app_refresh_busy","github_grant_revocation_failed","github_identity_mismatch","github_oauth_required","github_rate_limit_exceeded","github_unavailable","github_user_not_found","invalid_auth_state","invalid_billing_expiration","invalid_commit_format","invalid_connection","invalid_cursor","invalid_file_path","invalid_gistId","invalid_github_path","invalid_path","invalid_plan","invalid_preserve_files_format","invalid_project_name","invalid_pullRequestId","invalid_repo","invalid_repoId","invalid_request","invalid_settings","invalid_sort","invalid_status","invalid_terms_format","invalid_token_id","invalid_token_options","is_removed","not_authorized","not_connected","not_owner","oauth_resources_remaining","options_not_provided","page_not_activated","page_not_supported_on_different_branch","path_not_defined","path_not_specified","preview_busy","preview_superseded","pullRequestId_already_used","pullRequestId_is_not_a_number","pullRequestId_not_specified","pull_request_expired","pull_request_not_available","pull_request_not_found","pull_request_not_ready","quota_exceeded","quota_repository_limit","quota_storage_limit","rate_limited","readme_not_available","repoId_already_used","repoId_not_defined","repoUrl_not_defined","repo_access_limited","repo_empty","repo_not_accessible","repo_not_found","repo_saml_enforcement","repository_archived","repository_busy","repository_changed","repository_expired","repository_job_cancelled","repository_not_accessible","repository_not_ready","repository_not_specified","repository_tree_incomplete","repository_tree_too_large","s3_config_not_provided","source_not_provided","storage_delete_failed","storage_write_size_mismatch","streamer_route_not_found","streamer_unexpected_response","streamer_unreachable","streamer_upstream_error","submodule_not_available","subscription_required_for_never_expiration","sync_failed","terms_not_specified","token_expired","token_limit_reached","unable_to_connect_user","unable_to_download","upstream_error","user_banned","user_not_found","username_not_defined","zip_not_available","zip_unsafe_entry_path"];
|
||||
@@ -30,7 +30,7 @@ const UPSTREAM_HOSTS = ["github.com", "api.github.com", "codeload.github.com", "
|
||||
const UPSTREAM_ENDPOINT = new RegExp(`^/(?:(?:${UPSTREAM_ENDPOINT_SEGMENTS.join("|")}|\\{owner\\}|\\{repo\\}|\\{id\\}|\\*)(?:/|$)){0,8}$`);
|
||||
export const LOG_NUMBERS = ["memoryUsedBytes", "memoryFileCacheBytes", "memoryWorkingSetBytes", "memoryWorkingSetRatio", "quotaUsedRepositories", "quotaRepositoryLimit", "quotaUsedBytes", "quotaRequestedBytes", "quotaProjectedBytes", "quotaStorageLimit", "restartMs", "exitCode","droppedLogsInterval","expectedBytes", "measuredMs", "unattributedMs", "overlapMs","status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond",
|
||||
"attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed",
|
||||
"oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus"];
|
||||
"oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus", "inputBytes", "termCount", "loopMaxMs", "loopP99Ms"];
|
||||
export const LOG_STAGES = ["transfer", "database","repository", "credential_resolution", "upstream", "cache_lookup", "cache_fill", "worker_wait", "anonymize", "streamer_headers"];
|
||||
export function logRecord(level: string, module: string, args: unknown[]) {
|
||||
const context = logContext.getStore() || {};
|
||||
|
||||
@@ -119,7 +119,9 @@ export const LOG_EVENTS: Record<string, string> = {
|
||||
"waiting for rate limit gate": "waiting_for_rate_limit_gate",
|
||||
"webhook processing failed": "webhook_processing_failed",
|
||||
"write failed": "write_failed",
|
||||
"zip stream failed": "zip_stream_failed"
|
||||
"zip stream failed": "zip_stream_failed",
|
||||
"anonymization preview": "anonymization_preview",
|
||||
"event loop blocked": "event_loop_blocked"
|
||||
};
|
||||
|
||||
// Literal path segments allowed in an external endpoint label (see githubEndpoint).
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Worker } from "worker_threads";
|
||||
import { existsSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { AsyncResource } from "async_hooks";
|
||||
import config from "../config";
|
||||
import AnonymousError from "./AnonymousError";
|
||||
import { startStage } from "./request-monitoring";
|
||||
|
||||
/**
|
||||
* The anonymize form previews on every edit. Running it on the API's main
|
||||
* thread let one slow term (a backtracking regex on a long README) block every
|
||||
* request for its full deadline, once per keystroke. Previews now run on their
|
||||
* own workers, at most one per user: a newer preview replaces the older one.
|
||||
*/
|
||||
export type PreviewOptions = {
|
||||
image?: boolean; link?: boolean; terms?: string[];
|
||||
repoName?: string; branchName?: string; repoId?: string;
|
||||
};
|
||||
|
||||
const MAX_WORKERS = Math.min(2, Math.max(1, Number(process.env.PREVIEW_WORKERS) || 1));
|
||||
const MAX_WAITING = 8;
|
||||
export const PREVIEW_DEADLINE_MS = Math.max(500, Number(process.env.PREVIEW_DEADLINE_MS) || 3000);
|
||||
|
||||
type Job = {
|
||||
id: number; owner: string; contents: string[]; options: PreviewOptions;
|
||||
resolve: (outputs: string[]) => void; reject: (error: Error) => void;
|
||||
waitingDone: ReturnType<typeof startStage>; transformDone: () => ReturnType<typeof startStage>;
|
||||
cancel?: (code: string) => void;
|
||||
};
|
||||
|
||||
let nextId = 1;
|
||||
let running = 0;
|
||||
const waiting: Job[] = [];
|
||||
const idle: Worker[] = [];
|
||||
const byOwner = new Map<string, Job>();
|
||||
const ready = new WeakSet<Worker>();
|
||||
|
||||
function previewError(code: string): AnonymousError {
|
||||
switch (code) {
|
||||
case "anonymization_deadline_exceeded": return new AnonymousError("anonymization_timeout", { httpStatus: 422 });
|
||||
case "preview_superseded": return new AnonymousError("preview_superseded", { httpStatus: 409 });
|
||||
case "preview_cancelled": return new AnonymousError("preview_superseded", { httpStatus: 409 });
|
||||
case "preview_busy": return new AnonymousError("preview_busy", { httpStatus: 429 });
|
||||
default: return new AnonymousError("anonymization_worker_failed", { httpStatus: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function spawn(): Worker {
|
||||
const compiled = join(__dirname, "anonymization-preview.worker.js");
|
||||
return new Worker(existsSync(compiled) ? compiled : join(__dirname, "anonymization-preview.worker.ts"), {
|
||||
execArgv: existsSync(compiled) ? [] : ["-r", require.resolve("ts-node/register/transpile-only")],
|
||||
resourceLimits: { maxOldGenerationSizeMb: 256 },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Anonymize preview snippets for `owner` (the signed-in user). Rejects with a
|
||||
* coded AnonymousError; `signal` aborts when the client goes away.
|
||||
*/
|
||||
export function anonymizePreview(owner: string, contents: string[], options: PreviewOptions,
|
||||
signal?: AbortSignal): Promise<string[]> {
|
||||
// A newer edit makes the older preview useless: stop it, even mid-regex.
|
||||
byOwner.get(owner)?.cancel?.("preview_superseded");
|
||||
if (waiting.length >= MAX_WAITING) return Promise.reject(previewError("preview_busy"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const job: Job = {
|
||||
id: nextId++, owner, contents, options, resolve, reject,
|
||||
waitingDone: startStage("worker_wait"),
|
||||
transformDone: AsyncResource.bind(() => startStage("anonymize")),
|
||||
};
|
||||
byOwner.set(owner, job);
|
||||
const forget = () => { if (byOwner.get(owner) === job) byOwner.delete(owner); };
|
||||
job.cancel = code => {
|
||||
const index = waiting.indexOf(job);
|
||||
if (index < 0) return;
|
||||
waiting.splice(index, 1);
|
||||
job.waitingDone(true);
|
||||
forget();
|
||||
reject(previewError(code));
|
||||
};
|
||||
const onAbort = () => job.cancel?.("preview_cancelled");
|
||||
if (signal?.aborted) { job.waitingDone(true); forget(); return reject(previewError("preview_cancelled")); }
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
const settle = (fn: () => void) => { signal?.removeEventListener("abort", onAbort); forget(); fn(); };
|
||||
job.resolve = outputs => settle(() => resolve(outputs));
|
||||
job.reject = error => settle(() => reject(error));
|
||||
waiting.push(job);
|
||||
pump();
|
||||
});
|
||||
}
|
||||
|
||||
function pump() {
|
||||
while (waiting.length && running < MAX_WORKERS) {
|
||||
const job = waiting.shift()!;
|
||||
job.waitingDone();
|
||||
const transformDone = job.transformDone();
|
||||
running++;
|
||||
let worker: Worker;
|
||||
try { worker = idle.pop() || spawn(); }
|
||||
catch { running--; transformDone(true); job.reject(previewError("anonymization_worker_failed")); continue; }
|
||||
worker.ref();
|
||||
let finished = false;
|
||||
const finish = (error?: string, outputs?: string[]) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
transformDone(!!error);
|
||||
clearTimeout(deadline);
|
||||
worker.removeListener("message", onMessage);
|
||||
worker.removeListener("error", onError);
|
||||
worker.removeListener("exit", onExit);
|
||||
job.cancel = undefined;
|
||||
const release = () => { running--; pump(); };
|
||||
// A worker stopped mid-regex cannot be reused.
|
||||
if (error) void worker.terminate().then(release, release);
|
||||
else { idle.push(worker); worker.unref(); release(); }
|
||||
if (error) job.reject(previewError(error)); else job.resolve(outputs!);
|
||||
};
|
||||
const onMessage = (result: { id?: number; ready?: boolean; outputs?: string[]; error?: string }) => {
|
||||
if (result.ready) { ready.add(worker); return start(); }
|
||||
if (result.id === job.id) finish(result.error, result.outputs);
|
||||
};
|
||||
const onError = () => finish("anonymization_worker_failed");
|
||||
const onExit = () => finish("anonymization_worker_exited");
|
||||
// Terminating the worker is the only way to stop a regex that never yields.
|
||||
let deadline: NodeJS.Timeout | undefined;
|
||||
const start = () => {
|
||||
if (finished || deadline) return;
|
||||
deadline = setTimeout(() => finish("anonymization_deadline_exceeded"), PREVIEW_DEADLINE_MS);
|
||||
worker.postMessage({ id: job.id, contents: job.contents, options: job.options,
|
||||
context: { mask: config.ANONYMIZATION_MASK, hostname: config.APP_HOSTNAME } });
|
||||
};
|
||||
job.cancel = code => finish(code);
|
||||
worker.on("message", onMessage);
|
||||
worker.once("error", onError);
|
||||
worker.once("exit", onExit);
|
||||
if (ready.has(worker)) start();
|
||||
}
|
||||
}
|
||||
|
||||
export function getPreviewPoolStats() {
|
||||
return { running, waiting: waiting.length, idle: idle.length, maxWorkers: MAX_WORKERS, maxWaiting: MAX_WAITING };
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { logMemory } from "./log-memory";
|
||||
import { createLogger, serializeError, reportOutputDrops } from "./logger";
|
||||
import { installExternalRequestLogging } from "./external-request-logging";
|
||||
import { monitorEventLoopDelay } from "perf_hooks";
|
||||
import { activeRequestCount } from "./request-monitoring";
|
||||
|
||||
/** Observe fatal errors without overriding Node's default exit behavior. */
|
||||
export function installFatalErrorLogging(service: "api" | "streamer") {
|
||||
@@ -10,11 +12,19 @@ export function installFatalErrorLogging(service: "api" | "streamer") {
|
||||
});
|
||||
logger.info("process started", { service });
|
||||
installExternalRequestLogging();
|
||||
// A blocked event loop delays every request at once (synchronous regex,
|
||||
// JSON of a huge body, GC). Record the worst delay of each interval, and
|
||||
// warn when it was long enough for users to notice.
|
||||
const loop = monitorEventLoopDelay({ resolution: 20 });
|
||||
loop.enable();
|
||||
const heartbeat = setInterval(() => {
|
||||
const loopMaxMs = Math.round(loop.max / 1e6), loopP99Ms = Math.round(loop.percentile(99) / 1e6);
|
||||
loop.reset();
|
||||
if (loopMaxMs >= 1000) logger.warn("event loop blocked", { service, loopMaxMs, loopP99Ms, activeRequests: activeRequestCount() });
|
||||
void logMemory().then(memory => reportOutputDrops(drops => logger.info("process heartbeat", {
|
||||
service, uptime: process.uptime(), ...memory, ...drops })));
|
||||
service, uptime: process.uptime(), loopMaxMs, loopP99Ms, ...memory, ...drops })));
|
||||
}, 30000);
|
||||
heartbeat.unref();
|
||||
process.on("uncaughtExceptionMonitor", report);
|
||||
return () => { clearInterval(heartbeat); process.removeListener("uncaughtExceptionMonitor", report); };
|
||||
return () => { clearInterval(heartbeat); loop.disable(); process.removeListener("uncaughtExceptionMonitor", report); };
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
import * as express from "express";
|
||||
import { isPreservedPath, normalizePreserveFiles } from "../../core/preserve-files";
|
||||
import { isSafeSourcePath } from "../../core/source-file-list";
|
||||
import { ContentAnonimizer } from "../../core/anonymize-utils";
|
||||
import { anonymizePreview } from "../../core/preview-anonymizer";
|
||||
import { setLogContext, validProjectId } from "../../core/log-context";
|
||||
import { createLogger } from "../../core/logger";
|
||||
import AnonymousError from "../../core/AnonymousError";
|
||||
|
||||
const logger = createLogger("preview");
|
||||
import { handleError } from "./route-utils";
|
||||
import { ensureAuthenticated } from "./connection";
|
||||
|
||||
@@ -57,19 +62,38 @@ router.post("/", async (req: express.Request, res: express.Response) => {
|
||||
// Image/link options and self-link rewriting still apply.
|
||||
const terms = isPreservedPath(opt.filePath, preserveFiles) ? [] : opt.terms;
|
||||
res.set("Cache-Control", "private, no-store");
|
||||
// Construct one anonymizer per snippet so the wasAnonymized flag is per
|
||||
// input. ContentAnonimizer is cheap to instantiate.
|
||||
const outputs = inputs.map((content) => {
|
||||
const a = new ContentAnonimizer({
|
||||
// Trace the preview to its project: the form sends the anonymized ID it
|
||||
// will create or update, and the size of what it asked to anonymize.
|
||||
if (typeof opt.repoId === "string" && validProjectId(opt.repoId)) setLogContext({ repoId: opt.repoId });
|
||||
const trace = { inputBytes: inputs.reduce((sum, value) => sum + Buffer.byteLength(value), 0),
|
||||
termCount: Array.isArray(terms) ? terms.length : 0, startedAt: Date.now() };
|
||||
// The client gives up on a preview it no longer shows; stop its worker.
|
||||
const aborted = new AbortController();
|
||||
res.once("close", () => { if (!res.writableFinished) aborted.abort(); });
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const owner = String((req.user as any)?.user?._id || req.ip);
|
||||
// Slow or failed previews record what was asked, so a stalled form can be
|
||||
// traced to its project and to the size of its input and term list.
|
||||
const traceSlow = (code?: string) => {
|
||||
const ms = Date.now() - trace.startedAt;
|
||||
if (code === "preview_superseded") return;
|
||||
if (code || ms >= 500) logger.info("anonymization preview", { inputBytes: trace.inputBytes, termCount: trace.termCount, ms, code });
|
||||
};
|
||||
let outputs: string[];
|
||||
try {
|
||||
outputs = await anonymizePreview(owner, inputs, {
|
||||
terms: Array.isArray(terms) ? terms : [],
|
||||
image: opt.image,
|
||||
link: opt.link,
|
||||
repoName: opt.repoName,
|
||||
branchName: opt.branchName,
|
||||
repoId: opt.repoId,
|
||||
});
|
||||
return a.anonymize(content);
|
||||
});
|
||||
}, aborted.signal);
|
||||
} catch (error) {
|
||||
traceSlow(error instanceof AnonymousError ? error.message : "anonymization_worker_failed");
|
||||
throw error;
|
||||
}
|
||||
traceSlow();
|
||||
|
||||
if (single) {
|
||||
return res.json({ content: outputs[0] });
|
||||
|
||||
@@ -242,6 +242,8 @@ export const EXPECTED_CLIENT_ERRORS: ReadonlySet<string> = new Set([
|
||||
"gist_not_found", "gist_expired", "gist_not_ready",
|
||||
"pull_request_not_found", "pull_request_expired", "pull_request_not_ready",
|
||||
"conf_not_found", "conference_not_found", "repoId_already_used", "invalid_repoId",
|
||||
// A newer keystroke replaced this anonymize-form preview.
|
||||
"preview_superseded",
|
||||
]);
|
||||
|
||||
export type ErrorLogOptions = {
|
||||
|
||||
Reference in new issue
Block a user