mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 09:03:37 +01:00
Merge remote-tracking branch 'origin/main' into fix/expected-errors-info
This commit is contained in:
commit
5509b30b1b
8 files changed
+248
-14
No files matched your search
@@ -42,7 +42,7 @@ if service == "mongodb" {
|
||||
if includes(["quota_denied", "deployment", "account_removed", "application_log", "billing_maintenance_failed", "billing_reconciliation_deferred", "billing_requires_attention", "billing_worker_failed", "blob_api_failed_falling_back_to_raw_url", "branch_not_found", "cache_removal_failed", "cache_removed", "checking_repository_status_and_unused_repositories", "cleared_lock_for_active_job", "conference_expire_failed", "content_expiration_failed", "daily_stats_snapshot_failed", "daily_stats_snapshot_stored", "download_completed", "download_start", "downloaded", "downloadfile_failed", "downloading_file", "downloading_gist", "downloading_pull_request", "downloading_via_raw_url_lfs", "duplicate_stripe_customer_requires_review", "ensuretodaysnapshot_failed", "error_log_redis_connect_failed", "expired_repository_cleanup_failed", "failed_removal_recovery_failed", "failed_to_persist_error_status", "failed_to_record_repository_removal_error", "gettoken", "github_primary_rate_limit_hit", "github_secondary_rate_limit_hit", "grant_revocation_failed", "initial_repository_status_check_failed", "job_completed", "job_failed", "job_stalled", "job_started", "lastusedat_update_failed", "login_token_failed", "login_token_req_login_failed", "logout_after_account_removal_failed", "logout_failed", "lookup_failed", "markerrorifinflight_failed", "markerrorifremoving_failed", "metadata_cleanup_complete", "metadata_cleanup_deferred", "owner_access_alert_reset_unavailable", "owner_access_email_accepted", "owner_access_email_audit_unavailable", "owner_access_email_claim_cleanup_unavailable", "owner_access_email_deferred_recovery_unavailable", "owner_access_email_delivery_failed", "owner_access_email_preparation_cleanup_unavailable", "owner_access_email_recovery_recorded", "owner_access_email_recovery_unavailable", "owner_access_email_result_reconciliation_required", "owner_access_email_unavailable", "pr_comments_404_continuing_without_them", "process_fatal_error", "process_heartbeat", "process_started", "progress", "queue_heartbeat", "queued_for_download", "rate_limit_gate_active_delaying_job_before_work", "rate_limit_gate_set", "rate_limited_delaying_job", "recover_failed", "recovered_expired_repository_cleanup", "recovered_file_from_truncated_tree", "recovered_file_invalidation_failed", "recovered_stuck_repo", "recoverstuckpreparing_failed", "recoverstuckremoving_failed", "redis_client_error", "redis_rate_limit_gate_written", "rejected_upstream_download_destination", "removal_failed", "removal_recovery_failed", "removecache_save_failed", "removed_cache_for_unused_repository", "removing_cache", "removing_repository", "repo_claimed", "repository_cache_removal_failed", "repository_expiration_failed", "repository_expired", "repository_removal_failed", "repository_removed", "request_cancelled", "request_completed", "request_slow", "requeued_failed_removal", "requeued_interrupted_removal", "reset", "retired_tree_cleanup_deferred", "retired_tree_cleanup_failed", "running_daily_stats_snapshot", "s3_body_stream_error", "send_failed", "server_started", "source_stream_failed_cache_write_discarded", "staged_tree_cleanup_failed", "staged_tree_completion_deferred", "streamer_fetch_failed", "streamer_started", "streamer_startup_failed", "streamer_zip_fetch_failed", "temporary_storage_cleanup_deferred", "token_refresh_failed_backing_off", "up_to_date", "update_queued", "verify_failed", "waiting_for_rate_limit_gate", "webhook_log", "webhook_processing_failed", "write_failed", "zip_stream_failed"], record.event) { out.event = record.event }
|
||||
if is_string(record.release) && match(string!(record.release), r'^[a-f0-9]{7,40}$') { out.release = record.release }
|
||||
if is_string(record.instance) && match(string!(record.instance), r'^[a-f0-9-]{36}$') { out.instance = record.instance }
|
||||
if includes(["repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "ABORT_ERR", "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EPIPE", "ETIMEDOUT", "billing_address_missing", "billing_city_missing", "billing_country_missing", "billing_email_missing", "billing_missing", "billing_name_missing", "billing_zip_missing", "branch_not_found", "branch_not_specified", "cache_busy", "cache_miss", "cannot_coauthor_self", "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", "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_found", "gist_not_ready", "github_app_access_required", "github_app_reconnect_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_token_invalid", "github_user_not_found", "invalid_commit_format", "invalid_cursor", "invalid_file_path", "invalid_gistId", "invalid_path", "invalid_plan", "invalid_preserve_files_format", "invalid_project_name", "invalid_pullRequestId", "invalid_repo", "invalid_repoId", "invalid_request", "invalid_settings", "invalid_signature", "invalid_sort", "invalid_status", "invalid_terms_format", "invalid_token_id", "invalid_token_options", "is_removed", "not_authorized", "not_connected", "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_found", "pull_request_not_ready", "token_refresh_failed", "anonymized_output_too_large", "anonymization_memory_budget_exceeded", "anonymization_queue_full", "anonymization_queue_timeout", "anonymization_cancelled", "anonymization_worker_exited", "anonymization_deadline_exceeded", "anonymization_spool_budget_exceeded", "anonymization_worker_failed", "anonymization_storage_full", "anonymization_io_failed", "zip_unsafe_entry_path", "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_changed", "repository_expired", "repository_job_cancelled", "repository_not_found", "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", "submodule_not_available", "terms_not_specified", "token_expired", "token_limit_reached", "unable_to_connect_user", "unable_to_download", "upstream_error", "upstream_timeout", "user_not_found", "username_not_defined", "webhook_processing_failed"], record.errorCode) { out.errorCode = record.errorCode }
|
||||
if includes(["repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "ABORT_ERR", "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EPIPE", "ETIMEDOUT", "billing_address_missing", "billing_city_missing", "billing_country_missing", "billing_email_missing", "billing_missing", "billing_name_missing", "billing_zip_missing", "branch_not_found", "branch_not_specified", "cache_busy", "cache_miss", "cannot_coauthor_self", "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", "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_found", "gist_not_ready", "github_app_access_required", "github_app_reconnect_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_token_invalid", "github_user_not_found", "invalid_commit_format", "invalid_cursor", "invalid_file_path", "invalid_gistId", "invalid_path", "invalid_plan", "invalid_preserve_files_format", "invalid_project_name", "invalid_pullRequestId", "invalid_repo", "invalid_repoId", "invalid_request", "invalid_settings", "invalid_signature", "invalid_sort", "invalid_status", "invalid_terms_format", "invalid_token_id", "invalid_token_options", "is_removed", "not_authorized", "not_connected", "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_found", "pull_request_not_ready", "token_refresh_failed", "anonymized_output_too_large", "anonymization_memory_budget_exceeded", "anonymization_queue_full", "anonymization_queue_timeout", "anonymization_cancelled", "anonymization_worker_exited", "anonymization_deadline_exceeded", "anonymization_spool_budget_exceeded", "anonymization_worker_failed", "anonymization_storage_full", "anonymization_io_failed", "zip_unsafe_entry_path", "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_changed", "repository_expired", "repository_job_cancelled", "repository_not_found", "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", "submodule_not_available", "terms_not_specified", "token_expired", "token_limit_reached", "unable_to_connect_user", "unable_to_download", "upstream_error", "upstream_timeout", "user_not_found", "username_not_defined", "webhook_processing_failed", "another_login_required", "billing_already_paid", "billing_busy", "billing_checkout_disabled", "billing_checkout_in_progress", "billing_customer_mismatch", "billing_draft_not_found", "billing_invalid_conference", "billing_invalid_draft", "billing_invalid_purchase", "billing_invalid_repository_size", "billing_invalid_review_window", "billing_plan_change_not_supported", "billing_plan_unavailable", "billing_price_misconfigured", "billing_recovery_required", "billing_review_window_locked", "billing_subscription_exists", "billing_unavailable", "conference_payment_required", "gist_not_available", "github_app_authorization_cancelled", "github_app_disabled", "github_app_permissions_invalid", "github_app_refresh_busy", "github_grant_revocation_failed", "github_oauth_required", "github_unavailable", "invalid_auth_state", "invalid_billing_expiration", "invalid_connection", "invalid_github_path", "not_owner", "oauth_resources_remaining", "pull_request_not_available", "repository_busy", "repository_not_accessible", "streamer_unreachable", "streamer_upstream_error", "subscription_required_for_never_expiration", "user_banned"], record.errorCode) { out.errorCode = record.errorCode }
|
||||
if includes(["admin", "anonymized-file", "auth", "billing", "dailyStats", "file-tree", "fs", "gh-stream", "gist", "github", "github-app-webhook", "owner-notifications", "process", "pull-request", "queue", "queue:cache", "queue:download", "queue:remove", "repository", "repository-public", "requests", "route", "route:repo", "s3", "schedule", "server", "streamer", "temporary-storage", "token-auth", "user", "zip-stream"], record.module) { out.module = record.module }
|
||||
if includes(["protocol", "credentials", "port", "host"], record.reason) { out.reason = record.reason }
|
||||
if includes(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], record.phase) { out.phase = record.phase }
|
||||
@@ -81,7 +81,7 @@ if includes(["/", "other", "/dashboard", "/anonymize", "/healthcheck", "/api/hea
|
||||
}
|
||||
}
|
||||
# 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","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","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>","anonymizationErrorCode","data"],"build/core/anonymization-errors.js":["<anonymous>","anonymizationErrorCode","data"],"src/core/anonymization-pool.ts":["<anonymous>","anonymizeOLine 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","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","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","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","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>","anonymizationErrorCode","data"],"build/core/anonymization-errors.js":["<anonymous>","anonymizationErrorCode","data"],"srLine truncated
|
||||
for_each(["errorType", "causeType"]) -> |_index, key| {
|
||||
value = get(record, [key]) ?? null
|
||||
if includes(["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"], value) { out = set!(out, [key], value) }
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
// Generate finite diagnostic allowlists from repository code, never runtime input.
|
||||
const fs = require('fs'), path = require('path'), ts = require('typescript');
|
||||
const files = {};
|
||||
// Error codes the code base throws or relays, so the logger and the collector
|
||||
// keep them as errorCode instead of dropping them as arbitrary strings.
|
||||
const codePattern = /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/;
|
||||
const errorFactories = new Set(['AnonymousError','billingError','appError']);
|
||||
const thrownCodes = new Set();
|
||||
function codeLiterals(node) {
|
||||
if (!node) return;
|
||||
if (ts.isStringLiteralLike(node)) { if (codePattern.test(node.text)) thrownCodes.add(node.text); }
|
||||
else if (ts.isConditionalExpression(node)) { codeLiterals(node.whenTrue); codeLiterals(node.whenFalse); }
|
||||
else if (ts.isBinaryExpression(node) && [ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(node.operatorToken.kind)) { codeLiterals(node.left); codeLiterals(node.right); }
|
||||
else if (ts.isParenthesizedExpression(node)) codeLiterals(node.expression);
|
||||
}
|
||||
function scan(dir) {
|
||||
for (const entry of fs.readdirSync(dir, {withFileTypes:true})) {
|
||||
const file = path.join(dir,entry.name);
|
||||
@@ -11,6 +23,11 @@ function scan(dir) {
|
||||
function visit(node) {
|
||||
if ((ts.isFunctionDeclaration(node)||ts.isMethodDeclaration(node)||ts.isFunctionExpression(node)) && node.name && ts.isIdentifier(node.name)) names.add(node.name.text);
|
||||
if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&node.initializer&&(ts.isArrowFunction(node.initializer)||ts.isFunctionExpression(node.initializer))) names.add(node.name.text);
|
||||
// new AnonymousError("code"), billingError("code"), appError("code")
|
||||
if((ts.isNewExpression(node)||ts.isCallExpression(node))&&ts.isIdentifier(node.expression)&&errorFactories.has(node.expression.text)&&node.arguments?.length) codeLiterals(node.arguments[0]);
|
||||
// Codes picked into a variable first: errCode = "streamer_unreachable"
|
||||
if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&/^(errCode|code)$/.test(node.name.text)) codeLiterals(node.initializer);
|
||||
if(ts.isBinaryExpression(node)&&node.operatorToken.kind===ts.SyntaxKind.EqualsToken&&ts.isIdentifier(node.left)&&/^(errCode|code)$/.test(node.left.text)) codeLiterals(node.right);
|
||||
ts.forEachChild(node,visit);
|
||||
}
|
||||
visit(source);
|
||||
@@ -23,7 +40,12 @@ scan('src');
|
||||
const types=['Error','TypeError','RangeError','ReferenceError','SyntaxError','URIError','EvalError','AggregateError','AnonymousError','HTTPError','RequestError','MongoServerError','MongoNetworkError','MongoServerSelectionError','ValidationError','TimeoutError','AbortError','UnknownError'];
|
||||
const vrl=fs.readFileSync('deploy/logging/sanitize.vrl','utf8');
|
||||
const routes=JSON.parse(vrl.match(/if includes\((\[.*?\]), record.route\)/)[1]);
|
||||
fs.writeFileSync('src/core/log-diagnostic-schema.ts','// Generated by scripts/generate-log-diagnostics.js; do not edit.\nexport const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = '+JSON.stringify(files,null,2)+';\nexport const LOG_ERROR_TYPES = '+JSON.stringify(types)+';\nexport const LOG_ROUTES = '+JSON.stringify(routes)+';\n');
|
||||
const codes=[...thrownCodes].sort();
|
||||
fs.writeFileSync('src/core/log-diagnostic-schema.ts','// Generated by scripts/generate-log-diagnostics.js; do not edit.\nexport const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = '+JSON.stringify(files,null,2)+';\nexport const LOG_ERROR_TYPES = '+JSON.stringify(types)+';\nexport const LOG_ROUTES = '+JSON.stringify(routes)+';\nexport const LOG_THROWN_ERROR_CODES = '+JSON.stringify(codes)+';\n');
|
||||
// The collector keeps reviewed codes too (system errnos, worker codes); only add.
|
||||
const codeList=/(if includes\()(\[.*?\])(, record\.errorCode\))/;
|
||||
const collectorCodes=JSON.parse(vrl.match(codeList)[2]);
|
||||
const mergedCodes=[...collectorCodes,...codes.filter(code=>!collectorCodes.includes(code))];
|
||||
const block=`# BEGIN GENERATED DIAGNOSTICS
|
||||
source_functions = ${JSON.stringify(files)}
|
||||
for_each(["errorType", "causeType"]) -> |_index, key| {
|
||||
@@ -43,5 +65,5 @@ for_each(["errorStack", "causeStack"]) -> |_index, key| {
|
||||
}
|
||||
}
|
||||
# END GENERATED DIAGNOSTICS`;
|
||||
const clean=vrl.replace(/# BEGIN GENERATED DIAGNOSTICS[\s\S]*?# END GENERATED DIAGNOSTICS\n?/,'');
|
||||
const clean=vrl.replace(/# BEGIN GENERATED DIAGNOSTICS[\s\S]*?# END GENERATED DIAGNOSTICS\n?/,'').replace(codeList,(_,start,_list,end)=>start+JSON.stringify(mergedCodes).replace(/","/g,'", "')+end);
|
||||
fs.writeFileSync('deploy/logging/sanitize.vrl',clean.replace('out._msg = out.event',()=>block+'\nout._msg = out.event'));
|
||||
@@ -1,4 +1,5 @@
|
||||
import { recordResponseFailure } from "./request-evidence";
|
||||
import { watchClientClose } from "./response-cancellation";
|
||||
import { createGzip } from "zlib";
|
||||
import { createHash } from "crypto";
|
||||
import { Readable, PassThrough } from "stream";
|
||||
@@ -53,12 +54,19 @@ async function sendCached(content: Readable, res: Response,
|
||||
// Install evidence before pipeline's listeners destroy the response.
|
||||
const localFailure = () => { if (!res.destroyed) recordResponseFailure(res, "unknown", "local_abort"); };
|
||||
stream.once("error", localFailure);
|
||||
if (record.encoding === "identity" && !res.req.acceptsEncodings("identity")) {
|
||||
res.setHeader("Content-Encoding", "gzip"); res.removeHeader("Content-Length");
|
||||
const gzip = createGzip();
|
||||
gzip.once("error", localFailure);
|
||||
await pipeline(stream, gzip, res);
|
||||
} else await pipeline(stream, res);
|
||||
const clientClosed = watchClientClose(res, stream);
|
||||
try {
|
||||
if (record.encoding === "identity" && !res.req.acceptsEncodings("identity")) {
|
||||
res.setHeader("Content-Encoding", "gzip"); res.removeHeader("Content-Length");
|
||||
const gzip = createGzip();
|
||||
gzip.once("error", localFailure);
|
||||
await pipeline(stream, gzip, res);
|
||||
} else await pipeline(stream, res);
|
||||
} catch (error) {
|
||||
// A visitor who stops a download is not a server fault.
|
||||
if (clientClosed()) throw Object.assign(new Error("response_cancelled"), { cause: error });
|
||||
throw error;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const decision = results.decision(key);
|
||||
|
||||
@@ -142,6 +142,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"getToken",
|
||||
"getTokenGateResetAt",
|
||||
"octokit",
|
||||
"ownerGitHubAccessRequired",
|
||||
"rateLimitDetail",
|
||||
"resolveRepositoryToken",
|
||||
"run",
|
||||
@@ -160,6 +161,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"getToken",
|
||||
"getTokenGateResetAt",
|
||||
"octokit",
|
||||
"ownerGitHubAccessRequired",
|
||||
"rateLimitDetail",
|
||||
"resolveRepositoryToken",
|
||||
"run",
|
||||
@@ -1643,6 +1645,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"admitResolvedBytes",
|
||||
"assertActive",
|
||||
"assertDownloadUrl",
|
||||
"assertHost",
|
||||
"cached",
|
||||
"confirmOwnerAccess",
|
||||
"deferredRawDownload",
|
||||
@@ -1651,6 +1654,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"downloadFile",
|
||||
"downloadFileViaRaw",
|
||||
"downloadRaw",
|
||||
"downloadViaJsDelivr",
|
||||
"downloadWithFallback",
|
||||
"fallbackToRaw",
|
||||
"fetchContent",
|
||||
@@ -1663,9 +1667,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"githubRawFileUrl",
|
||||
"iterateFiles",
|
||||
"iterateTreeBatches",
|
||||
"jsDelivrFileUrl",
|
||||
"lfsPointerGuard",
|
||||
"normalize",
|
||||
"pMap",
|
||||
"produce",
|
||||
"rejectLfsPointer",
|
||||
"resolve",
|
||||
"resolveLfsPointer",
|
||||
"stopSourceOnDestroy",
|
||||
@@ -1679,6 +1686,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"admitResolvedBytes",
|
||||
"assertActive",
|
||||
"assertDownloadUrl",
|
||||
"assertHost",
|
||||
"cached",
|
||||
"confirmOwnerAccess",
|
||||
"deferredRawDownload",
|
||||
@@ -1687,6 +1695,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"downloadFile",
|
||||
"downloadFileViaRaw",
|
||||
"downloadRaw",
|
||||
"downloadViaJsDelivr",
|
||||
"downloadWithFallback",
|
||||
"fallbackToRaw",
|
||||
"fetchContent",
|
||||
@@ -1699,9 +1708,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"githubRawFileUrl",
|
||||
"iterateFiles",
|
||||
"iterateTreeBatches",
|
||||
"jsDelivrFileUrl",
|
||||
"lfsPointerGuard",
|
||||
"normalize",
|
||||
"pMap",
|
||||
"produce",
|
||||
"rejectLfsPointer",
|
||||
"resolve",
|
||||
"resolveLfsPointer",
|
||||
"stopSourceOnDestroy",
|
||||
@@ -2927,3 +2939,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","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_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_unreachable","streamer_upstream_error","submodule_not_available","subscription_required_for_never_expiration","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"];
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ANONYMIZATION_ERRORS } from "./anonymization-errors";
|
||||
import { requestReproduction, safeReproductionPath } from "./log-reproduction";
|
||||
import { safeDiagnosticFields, errorDiagnostics } from "./log-diagnostics";
|
||||
import { LOG_ROUTES } from "./log-diagnostic-schema";
|
||||
import { LOG_ROUTES, LOG_THROWN_ERROR_CODES } from "./log-diagnostic-schema";
|
||||
import { LOG_MODULES, ERROR_CODES, LOG_EVENTS } from "./log-schema";
|
||||
import { randomUUID } from "crypto";
|
||||
import { logContext, validTraceId } from "./log-context";
|
||||
@@ -17,8 +17,9 @@ const events: Record<string, string> = {
|
||||
"process heartbeat": "process_heartbeat", "job started": "job_started", "job completed": "job_completed",
|
||||
"job failed": "job_failed", "job stalled": "job_stalled", "queue heartbeat": "queue_heartbeat",
|
||||
};
|
||||
const errorCodes = new Set([
|
||||
...ERROR_CODES, ...ANONYMIZATION_ERRORS, "zip_unsafe_entry_path",
|
||||
// LOG_THROWN_ERROR_CODES is generated from the codes the source throws.
|
||||
export const LOG_ERROR_CODES: ReadonlySet<string> = new Set([
|
||||
...ERROR_CODES, ...ANONYMIZATION_ERRORS, ...LOG_THROWN_ERROR_CODES, "zip_unsafe_entry_path",
|
||||
"repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "token_refresh_failed", "quota_exceeded", "quota_repository_limit", "quota_storage_limit", "github_rate_limit_exceeded", "github_app_reconnect_required", "github_token_invalid",
|
||||
"repository_expired", "repository_not_ready", "repository_not_found", "repository_job_cancelled",
|
||||
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE", "ABORT_ERR",
|
||||
@@ -57,7 +58,7 @@ export function logRecord(level: string, module: string, args: unknown[]) {
|
||||
}
|
||||
if (Number.isSafeInteger(context.attempt)) record.attempt = context.attempt;
|
||||
for (const key of LOG_NUMBERS) if (typeof details[key] === "number" && Number.isFinite(details[key])) record[key] = details[key];
|
||||
const code = [details.code, details.message].find(value => typeof value === "string" && errorCodes.has(value));
|
||||
const code = [details.code, details.message].find(value => typeof value === "string" && LOG_ERROR_CODES.has(value));
|
||||
if (code) record.errorCode = code;
|
||||
if (allowed(["protocol", "credentials", "port", "host"], details.reason)) record.reason = details.reason;
|
||||
if (allowed(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], details.phase)) record.phase = details.phase;
|
||||
|
||||
@@ -14,3 +14,19 @@ export function isResponseCancellation(error: unknown, response?: { destroyed?:
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* pipeline() rejects with ERR_STREAM_PREMATURE_CLOSE both when the client goes
|
||||
* away and when the source ends early. Call before piping; the returned check
|
||||
* is true only when the response closed unfinished before the source failed.
|
||||
*/
|
||||
export function watchClientClose(response: { writableFinished?: boolean; once(event: "close", listener: () => void): unknown },
|
||||
source: { readableEnded?: boolean; once(event: "close" | "error", listener: () => void): unknown }): () => boolean {
|
||||
let sourceFailed = false;
|
||||
let clientClosed = false;
|
||||
source.once("error", () => { sourceFailed = true; });
|
||||
// A source that closes without ending was cut short.
|
||||
source.once("close", () => { if (!source.readableEnded) sourceFailed = true; });
|
||||
response.once("close", () => { if (!sourceFailed && !response.writableFinished) clientClosed = true; });
|
||||
return () => clientClosed;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
const { strict: assert } = require("node:assert");
|
||||
const { promises: fs } = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { join } = require("node:path");
|
||||
const { PassThrough, Readable, Writable } = require("node:stream");
|
||||
const { pipeline } = require("node:stream/promises");
|
||||
const { setTimeout } = require("node:timers");
|
||||
const { createHash } = require("node:crypto");
|
||||
const express = require("express");
|
||||
require("ts-node/register/transpile-only");
|
||||
const config = require("../src/config").default;
|
||||
const { sharedBlobCache, closeBlobCaches } = require("../src/core/blob-cache");
|
||||
const { watchClientClose, isResponseCancellation } = require("../src/core/response-cancellation");
|
||||
const streamer = require("../src/streamer/route").default;
|
||||
|
||||
const body = Buffer.alloc(8 * 1024 * 1024, 7);
|
||||
const sha = createHash("sha1").update(`blob ${body.length}\0`).update(body).digest("hex");
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Collect the structured records a test run writes to stdout. */
|
||||
function captureLogs() {
|
||||
const records = [];
|
||||
const write = process.stdout.write;
|
||||
process.stdout.write = function (chunk, ...rest) {
|
||||
for (const line of String(chunk).split("\n")) {
|
||||
try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ }
|
||||
if (line) write.call(process.stdout, line + "\n");
|
||||
}
|
||||
const callback = rest.find((arg) => typeof arg === "function");
|
||||
if (callback) callback();
|
||||
return true;
|
||||
};
|
||||
return { records, restore: () => { process.stdout.write = write; } };
|
||||
}
|
||||
|
||||
describe("cached response cancellation", function () {
|
||||
this.timeout(15000);
|
||||
let root, old;
|
||||
beforeEach(async () => {
|
||||
old = { ...config }; closeBlobCaches();
|
||||
root = await fs.mkdtemp(join(tmpdir(), "cached-cancel-"));
|
||||
Object.assign(config, { STORAGE: "filesystem", FOLDER: root, SHARED_CACHE_ENABLED: true,
|
||||
SHARED_CACHE_PATH: join(root, "cache"), SHARED_CACHE_BYTES: 64 * 1024 ** 2,
|
||||
SHARED_CACHE_RESULT_BYTES: 32 * 1024 ** 2, SHARED_CACHE_MAX_FILE_BYTES: 16 * 1024 ** 2,
|
||||
SHARED_CACHE_FREE_BYTES: 0, BILLING_ENABLED: false });
|
||||
});
|
||||
afterEach(async () => {
|
||||
closeBlobCaches(); Object.assign(config, old);
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("does not log a client that stops a cached download as a server error", async () => {
|
||||
const seeded = await sharedBlobCache().getOrFill(`git-${sha}`, async () => Readable.from([body]), async () => `git-${sha}`, body.length);
|
||||
for await (const chunk of seeded) void chunk;
|
||||
const app = express(); app.use(express.json()); app.use("/api", streamer);
|
||||
const server = await new Promise((resolve) => { const s = app.listen(0, "127.0.0.1", () => resolve(s)); });
|
||||
const logs = captureLogs();
|
||||
try {
|
||||
await new Promise((resolve) => {
|
||||
const req = http.request({ host: "127.0.0.1", port: server.address().port, path: "/api", method: "POST",
|
||||
headers: { "content-type": "application/json" } }, (res) => {
|
||||
res.once("data", () => req.destroy());
|
||||
res.on("error", () => undefined);
|
||||
res.on("close", resolve);
|
||||
});
|
||||
req.on("error", resolve);
|
||||
req.end(JSON.stringify({ token: "", repoFullName: "owner/repo", repoId: "anon", sha, size: body.length,
|
||||
filePath: "video.bin", anonymizerOptions: { terms: [], filePath: "video.bin" } }));
|
||||
});
|
||||
await wait(300);
|
||||
} finally {
|
||||
logs.restore();
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
const faults = logs.records.filter((record) => record.severity === "error" || record.severity === "warn");
|
||||
assert.deepEqual(faults, []);
|
||||
});
|
||||
|
||||
it("names a client disconnect but keeps a source that ended early as a failure", async () => {
|
||||
const attribute = async (closeFirst) => {
|
||||
const source = new PassThrough();
|
||||
// The "late" response never acknowledges its write, like a slow socket.
|
||||
const response = new Writable({ write(_chunk, _encoding, done) { if (closeFirst !== "late") done(); } });
|
||||
const clientClosed = watchClientClose(response, source);
|
||||
const piping = pipeline(source, response);
|
||||
source.write("partial");
|
||||
if (closeFirst === "late") source.end();
|
||||
await wait(5);
|
||||
if (closeFirst !== "source") response.destroy();
|
||||
else source.destroy();
|
||||
const error = await piping.then(() => undefined, (failure) => failure);
|
||||
return { error, clientClosed: clientClosed(), cancellation: isResponseCancellation(error, response) };
|
||||
};
|
||||
const client = await attribute("client");
|
||||
assert.equal(client.error.code, "ERR_STREAM_PREMATURE_CLOSE");
|
||||
assert.equal(client.clientClosed, true);
|
||||
// The source was fully read but the response had not flushed yet.
|
||||
const late = await attribute("late");
|
||||
assert.equal(late.error.code, "ERR_STREAM_PREMATURE_CLOSE");
|
||||
assert.equal(late.clientClosed, true);
|
||||
const source = await attribute("source");
|
||||
assert.equal(source.error.code, "ERR_STREAM_PREMATURE_CLOSE");
|
||||
assert.equal(source.clientClosed, false);
|
||||
assert.equal(source.cancellation, false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
const { strict: assert } = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const ts = require("typescript");
|
||||
require("ts-node/register/transpile-only");
|
||||
const { logRecord, LOG_ERROR_CODES } = require("../src/core/log-record");
|
||||
const { serializeError } = require("../src/core/logger");
|
||||
const { billingError } = require("../src/core/billing/config");
|
||||
const { consumeFlow } = require("../src/server/routes/github-app");
|
||||
|
||||
const root = path.join(__dirname, "..");
|
||||
const vrl = fs.readFileSync(path.join(root, "deploy/logging/sanitize.vrl"), "utf8");
|
||||
const collectorCodes = new Set(JSON.parse(vrl.match(/if includes\((\[.*?\]), record\.errorCode\)/)[1]));
|
||||
|
||||
// Independent of the generator: string codes passed straight to the error
|
||||
// factories anywhere under src/.
|
||||
function thrownCodes() {
|
||||
const codes = new Map();
|
||||
const literals = (node, file) => {
|
||||
if (!node) return;
|
||||
if (ts.isStringLiteralLike(node)) { if (/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/.test(node.text)) codes.set(node.text, file); }
|
||||
else if (ts.isConditionalExpression(node)) { literals(node.whenTrue, file); literals(node.whenFalse, file); }
|
||||
else if (ts.isParenthesizedExpression(node)) literals(node.expression, file);
|
||||
};
|
||||
const walk = (dir) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const file = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) { walk(file); continue; }
|
||||
if (!file.endsWith(".ts") || file.endsWith(".d.ts")) continue;
|
||||
const source = ts.createSourceFile(file, fs.readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
|
||||
(function visit(node) {
|
||||
if ((ts.isNewExpression(node) || ts.isCallExpression(node)) && ts.isIdentifier(node.expression) &&
|
||||
["AnonymousError", "billingError", "appError"].includes(node.expression.text) && node.arguments?.length) {
|
||||
literals(node.arguments[0], path.relative(root, file));
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
})(source);
|
||||
}
|
||||
};
|
||||
walk(path.join(root, "src"));
|
||||
return codes;
|
||||
}
|
||||
|
||||
describe("thrown error codes reach the logs", () => {
|
||||
it("keeps the billing expiration and GitHub App state codes", () => {
|
||||
const billing = logRecord("warn", "route", [serializeError(billingError("invalid_billing_expiration"))]);
|
||||
assert.equal(billing.errorCode, "invalid_billing_expiration");
|
||||
let state;
|
||||
try { consumeFlow(undefined, "state"); } catch (error) { state = error; }
|
||||
assert.equal(state.message, "invalid_auth_state");
|
||||
assert.equal(logRecord("warn", "route", [serializeError(state)]).errorCode, "invalid_auth_state");
|
||||
for (const code of ["invalid_billing_expiration", "invalid_auth_state", "streamer_unreachable"]) {
|
||||
assert.ok(collectorCodes.has(code), `${code} is missing from sanitize.vrl`);
|
||||
}
|
||||
});
|
||||
|
||||
it("allowlists every code passed to an error factory", () => {
|
||||
const missing = [...thrownCodes()].filter(([code]) => !LOG_ERROR_CODES.has(code) || !collectorCodes.has(code))
|
||||
.map(([code, file]) => `${code} (${file})`);
|
||||
assert.deepEqual(missing, [], "run node scripts/generate-log-diagnostics.js");
|
||||
});
|
||||
|
||||
it("lets the collector keep every code the logger emits", () => {
|
||||
assert.deepEqual([...LOG_ERROR_CODES].filter((code) => !collectorCodes.has(code)), []);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user