Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 | 19x 19x 51x 6x 45x 6x 39x 8x 31x 14x 17x 7x 10x 19x 8x 8x 8x 8x 7x 1x 1x 1x 2x 2x 1x 1x 2x 1x 2x 8x 8x 1x 7x 7x 7x 1x 1x 1x 6x 6x 6x 6x 8x 8x 6x 6x 8x 8x 8x 3x 6x 1x 5x 2x 1x 4x 5x 4x 2x 2x 2x 2x 4x 4x 1x 3x 3x 1x 19x 19x 5x 1x 4x 4x 1x 3x 4x 4x 4x 4x 4x 1x 3x 4x 2x 2x 1x 1x 1x 1x 1x 4x 1x 4x 4x 1x 1x 1x 6x 1x 5x 10x 10x 3x 3x 1x 2x 1x 1x 1x 1x 7x 5x 9x 9x 9x 9x 6x 9x 9x 4x 4x 6x 3x 1x 1x 1x 2x 34x 34x 34x 34x 9x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 8x 3x 4x 1x 5x 3x 4x 2x 17x 16x 17x 25x 14x 1x 1x 13x 7x 7x 6x 1x 1x 7x 4x 1x 1x 4x 7x 5x 7x 16x 10x 6x 1x 5x 12x 12x 12x 12x 17x 16x | /**
* Shared utilities for issue commands
*
* Common functionality used by explain, plan, view, and other issue commands.
*/
import pLimit from "p-limit";
import {
findProjectsBySlug,
getAutofixState,
getIssue,
getIssueByShortId,
getIssueInOrg,
getSharedIssue,
ISSUE_DETAIL_COLLAPSE,
type IssueSort,
listIssuesPaginated,
listOrganizations,
ORG_FANOUT_CONCURRENCY,
triggerRootCauseAnalysis,
tryGetIssueByShortId,
} from "../../lib/api-client.js";
import { type IssueSelector, parseIssueArg } from "../../lib/arg-parsing.js";
import {
clearCachedIssueOrg,
getCachedIssueOrg,
setCachedIssueOrg,
} from "../../lib/db/issue-org-cache.js";
import { getProjectByAlias } from "../../lib/db/project-aliases.js";
import { detectAllDsns } from "../../lib/dsn/index.js";
import {
ApiError,
type AuthGuardFailure,
ContextError,
ResolutionError,
withAuthGuard,
} from "../../lib/errors.js";
import { getProgressMessage } from "../../lib/formatters/seer.js";
import { expandToFullShortId, isShortSuffix } from "../../lib/issue-id.js";
import { logger } from "../../lib/logger.js";
import { poll } from "../../lib/polling.js";
import { resolveEffectiveOrg } from "../../lib/region.js";
import {
resolveFromDsn,
resolveOrg,
resolveOrgAndProject,
} from "../../lib/resolve-target.js";
import { parseSentryUrl } from "../../lib/sentry-url-parser.js";
import { buildIssueUrl } from "../../lib/sentry-urls.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import { isAllDigits } from "../../lib/utils.js";
import type { SentryIssue } from "../../types/index.js";
import { type AutofixState, isTerminalStatus } from "../../types/seer.js";
const log = logger.withTag("issue.utils");
/** Shared positional parameter for issue ID */
export const issueIdPositional = {
kind: "tuple",
parameters: [
{
placeholder: "issue",
brief:
"Issue: @latest, @most_frequent, <org>/ID, <org>/<project>#ID, <project>-suffix, ID, or suffix",
parse: String,
},
],
} as const;
/**
* Build a command hint string for error messages.
*
* Returns context-aware hints based on the issue ID format:
* - Already contains `/` (e.g., "saber-ut/103103195") → show as-is (already has context)
* - Numeric ID (e.g., "123456789") → suggest `<org>/123456789`
* - Suffix only (e.g., "G") → suggest `<project>-G`
* - Has dash (e.g., "cli-G") → suggest `<org>/cli-G`
*
* @param command - The issue subcommand (e.g., "view", "explain")
* @param issueId - The user-provided issue ID
* @param base - Base command prefix (default: "sentry issue")
*/
export function buildCommandHint(
command: string,
issueId: string,
base = "sentry issue"
): string {
// URLs are self-contained — no enrichment needed
if (issueId.startsWith("http://") || issueId.startsWith("https://")) {
return `${base} ${command} ${issueId}`;
}
// Selectors already include the @ prefix and are self-contained
if (issueId.startsWith("@")) {
return `${base} ${command} <org>/${issueId}`;
}
// Input already contains org/project context — show as-is to avoid double-prefixing
if (issueId.includes("/")) {
return `${base} ${command} ${issueId}`;
}
// Numeric IDs always need org context - can't be combined with project
if (isAllDigits(issueId)) {
return `${base} ${command} <org>/${issueId}`;
}
// Short suffixes can be combined with project prefix
if (isShortSuffix(issueId)) {
return `${base} ${command} <project>-${issueId}`;
}
// Everything else (has dash) needs org prefix
return `${base} ${command} <org>/${issueId}`;
}
/** Default timeout in milliseconds (6 minutes) */
const DEFAULT_TIMEOUT_MS = 360_000;
/**
* Result of resolving an issue ID - includes full issue object.
* Used by view command which needs the complete issue data.
*/
export type ResolvedIssueResult = {
/** Resolved organization slug (may be undefined for numeric IDs without context) */
org: string | undefined;
/** Full issue object from API */
issue: SentryIssue;
};
/** Internal type for strict resolution (org required) */
type StrictResolvedIssue = {
/** Resolved organization slug */
org: string;
/** Full issue object from API */
issue: SentryIssue;
};
/**
* Try to resolve via alias cache.
* Returns null if the alias is not found in cache or fingerprint doesn't match.
*
* @param alias - The project alias (lowercase)
* @param suffix - The issue suffix (uppercase)
* @param cwd - Current working directory for DSN detection
*/
async function tryResolveFromAlias(
alias: string,
suffix: string,
cwd: string
): Promise<StrictResolvedIssue | null> {
// Detect DSNs to get fingerprint for validation
const detection = await detectAllDsns(cwd);
const fingerprint = detection.fingerprint;
const projectEntry = getProjectByAlias(alias, fingerprint);
if (!projectEntry) {
return null;
}
const resolvedShortId = expandToFullShortId(suffix, projectEntry.projectSlug);
const issue = await getIssueByShortId(projectEntry.orgSlug, resolvedShortId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { org: projectEntry.orgSlug, issue };
}
/**
* Fallback for when the fast shortid fan-out found no matches.
* Uses findProjectsBySlug to give a precise error ("project not found" vs
* "issue not found") and retries the issue lookup on transient failures.
*/
async function resolveProjectSearchFallback(
projectSlug: string,
suffix: string,
commandHint: string
): Promise<StrictResolvedIssue> {
const { projects } = await findProjectsBySlug(projectSlug.toLowerCase());
if (projects.length === 0) {
throw new ResolutionError(
`Project '${projectSlug}'`,
"not found",
commandHint,
["No project with this slug found in any accessible organization"]
);
}
Eif (projects.length > 1) {
const orgList = projects.map((p) => p.orgSlug).join(", ");
throw new ResolutionError(
`Project '${projectSlug}'`,
"is ambiguous",
commandHint,
[
`Found in: ${orgList}`,
`Specify the org: sentry issue ... <org>/${projectSlug}-${suffix}`,
]
);
}
// Project exists — retry the issue lookup. The fast path may have failed
// due to a transient error (5xx, timeout); retrying here either succeeds
// or propagates the real error to the user.
const matchedProject = projects[0];
const matchedOrg = matchedProject?.orgSlug;
Iif (matchedOrg && matchedProject) {
const retryShortId = expandToFullShortId(suffix, matchedProject.slug);
const issue = await getIssueByShortId(matchedOrg, retryShortId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { org: matchedOrg, issue };
}
throw new ResolutionError(
`Project '${projectSlug}'`,
"not found",
commandHint
);
}
/**
* Resolve project-search type: search for project across orgs, then fetch issue.
*
* Resolution order:
* 1. Try alias cache (fast, local)
* 2. Check DSN detection cache
* 3. Try shortid endpoint directly across all orgs (fast path)
* 4. Fall back to findProjectsBySlug for precise error messages
*
* @param projectSlug - Project slug to search for
* @param suffix - Issue suffix (uppercase)
* @param cwd - Current working directory
* @param commandHint - Hint for error messages
*/
async function resolveProjectSearch(
projectSlug: string,
suffix: string,
cwd: string,
commandHint: string
): Promise<StrictResolvedIssue> {
// 1. Try alias cache first (fast, local lookup)
const aliasResult = await tryResolveFromAlias(
projectSlug.toLowerCase(),
suffix,
cwd
);
if (aliasResult) {
return aliasResult;
}
// 2. Check if DSN detection already resolved this project.
// resolveFromDsn() reads from the DSN cache (populated by detectAllDsns
// in tryResolveFromAlias above) + project cache. This avoids the expensive
// listOrganizations() fan-out when the DSN matches the target project.
// Only catch resolveFromDsn errors — getIssueByShortId errors (e.g. 404)
// must propagate so we don't duplicate the expensive call via fallback.
let dsnTarget: Awaited<ReturnType<typeof resolveFromDsn>> | undefined;
try {
dsnTarget = await resolveFromDsn(cwd);
} catch {
// DSN resolution failed — fall through to full search
}
if (
dsnTarget &&
dsnTarget.project.toLowerCase() === projectSlug.toLowerCase()
) {
const fullShortId = expandToFullShortId(suffix, dsnTarget.project);
const issue = await getIssueByShortId(dsnTarget.org, fullShortId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { org: dsnTarget.org, issue };
}
// 3. Fast path: try resolving the short ID directly across all orgs.
// The shortid endpoint validates both project existence and issue existence
// in a single call, eliminating the separate getProject() round-trip.
// Concurrency-limited to avoid overwhelming the API for enterprise users.
const fullShortId = expandToFullShortId(suffix, projectSlug);
const orgs = await listOrganizations();
const limit = pLimit(ORG_FANOUT_CONCURRENCY);
const results = await Promise.all(
orgs.map((org) =>
limit(() =>
withAuthGuard(() =>
tryGetIssueByShortId(org.slug, fullShortId, {
collapse: ISSUE_DETAIL_COLLAPSE,
})
)
)
)
);
const successes: StrictResolvedIssue[] = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
const org = orgs[i];
if (result && org && result.ok && result.value) {
successes.push({ org: org.slug, issue: result.value });
}
}
if (successes.length === 1 && successes[0]) {
return successes[0];
}
if (successes.length > 1) {
const orgList = successes.map((s) => s.org).join(", ");
throw new ResolutionError(
`Project '${projectSlug}'`,
"is ambiguous",
commandHint,
[
`Found in: ${orgList}`,
`Specify the org: sentry issue ... <org>/${projectSlug}-${suffix}`,
]
);
}
// If every org failed with a real error (403, 5xx, network timeout),
// surface it instead of falling through to a misleading "not found".
// Only throw when ALL results are errors — if some orgs returned clean
// 404s ({ok: true, value: null}), fall through to the fallback for a
// precise error message.
const realErrors = results.filter(
(r): r is AuthGuardFailure => r !== undefined && !r.ok
);
if (realErrors.length === results.length && realErrors.length > 0) {
const firstError = realErrors[0]?.error;
Eif (firstError instanceof Error) {
throw firstError;
}
}
// 4. Fall back to findProjectsBySlug for precise error messages
// and retry the issue lookup (handles transient failures).
return resolveProjectSearchFallback(projectSlug, suffix, commandHint);
}
/**
* Resolve suffix-only type using DSN detection for project context.
*
* @param suffix - The issue suffix (uppercase)
* @param cwd - Current working directory for DSN detection
* @param commandHint - Hint for error messages
*/
async function resolveSuffixOnly(
suffix: string,
cwd: string,
commandHint: string
): Promise<StrictResolvedIssue> {
const target = await resolveOrgAndProject({ cwd });
if (!target) {
throw new ResolutionError(
`Issue suffix '${suffix}'`,
"could not be resolved without project context",
commandHint
);
}
const fullShortId = expandToFullShortId(suffix, target.project);
const issue = await getIssueByShortId(target.org, fullShortId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { org: target.org, issue };
}
/**
* Resolve explicit-org-suffix type: org provided but only suffix given.
*
* This format (`org/suffix`) is ambiguous - we have org but no project.
* We don't use DSN detection here because mixing explicit org with
* DSN-detected project (which belongs to a potentially different org)
* would be semantically wrong and confusing.
*
* @param org - Explicit organization slug
* @param suffix - Issue suffix (uppercase)
* @param commandHint - Hint for error messages
*/
function resolveExplicitOrgSuffix(
org: string,
suffix: string,
commandHint: string
): never {
throw new ResolutionError(
`Issue suffix '${suffix}'`,
"could not be resolved without project context",
commandHint,
[
`The format '${org}/${suffix}' requires a project to build the full issue ID.`,
`Use: sentry issue ... ${org}/<project>-${suffix}`,
]
);
}
/**
* Map magic selectors to Sentry issue list sort parameters.
*
* `@latest` → `"date"` (most recent `lastSeen` timestamp)
* `@most_frequent` → `"freq"` (highest event frequency)
*/
const SELECTOR_SORT_MAP: Record<IssueSelector, IssueSort> = {
"@latest": "date",
"@most_frequent": "freq",
};
/**
* Human-readable labels for selectors (used in error messages).
*/
const SELECTOR_LABELS: Record<IssueSelector, string> = {
"@latest": "most recent",
"@most_frequent": "most frequent",
};
/**
* Resolve a magic `@` selector to the top matching issue.
*
* Fetches the issue list sorted by the selector's criteria and returns
* the first result. Requires organization context (explicit or auto-detected).
*
* @param selector - The magic selector (e.g., `@latest`, `@most_frequent`)
* @param explicitOrg - Optional explicit org slug from `org/@selector` format
* @param cwd - Current working directory for context resolution
* @param commandHint - Hint for error messages
* @returns The resolved issue with org context
* @throws {ContextError} When organization cannot be resolved
* @throws {ResolutionError} When no issues match the selector
*/
async function resolveSelector(
selector: IssueSelector,
explicitOrg: string | undefined,
cwd: string,
commandHint: string
): Promise<StrictResolvedIssue> {
// Resolve org: explicit from `org/@latest` or auto-detected from DSN/defaults
let orgSlug: string;
if (explicitOrg) {
orgSlug = await resolveEffectiveOrg(explicitOrg);
} else {
const resolved = await resolveOrg({ cwd });
if (!resolved) {
throw new ContextError("Organization", commandHint);
}
orgSlug = resolved.org;
}
const sort = SELECTOR_SORT_MAP[selector];
const label = SELECTOR_LABELS[selector];
// Fetch just the top issue with the appropriate sort.
// Collapse all non-essential fields since we only need the issue identity.
const { data: issues } = await listIssuesPaginated(orgSlug, "", {
sort,
perPage: 1,
query: "is:unresolved",
collapse: ISSUE_DETAIL_COLLAPSE,
});
const issue = issues[0];
if (!issue) {
throw new ResolutionError(
`Selector '${selector}'`,
"no unresolved issues found",
`sentry issue list ${orgSlug}/ -q "is:resolved"`,
[`The ${label} issue selector only matches unresolved issues.`]
);
}
return { org: orgSlug, issue };
}
/**
* Resolve a share URL to a full issue via two-step lookup:
* 1. Call public share API to get numeric group ID
* 2. Fetch full issue details via authenticated API
*
* When the share URL includes org context (from subdomain), uses org-scoped
* endpoint for proper region routing. Otherwise falls back to the unscoped
* endpoint and extracts org from the response permalink.
*
* @param shareId - The share ID from the URL
* @param org - Optional organization slug (from share URL subdomain)
* @param baseUrl - The Sentry instance base URL
* @param cwd - Current working directory for context resolution
*/
async function resolveShareIssue(
shareId: string,
org: string | undefined,
baseUrl: string,
cwd: string
): Promise<ResolvedIssueResult> {
const shared = await getSharedIssue(baseUrl, shareId);
const groupId = shared.groupID;
// Fetch full issue via authenticated API
if (org) {
const resolvedOrg = await resolveEffectiveOrg(org);
const orgScopedIssue = await getIssueInOrg(resolvedOrg, groupId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { org: resolvedOrg, issue: orgScopedIssue };
}
// No org from URL — try env/DSN context, then the issue-id → org cache,
// then fall back to the unscoped fetch. See resolveNumericIssue for the
// full rationale behind the cache.
const resolvedOrg = await resolveOrg({ cwd });
const cachedOrg = resolvedOrg ? null : getCachedIssueOrg(groupId);
const { issue, cacheEvicted } = await fetchIssueByNumericId(
groupId,
resolvedOrg?.org,
cachedOrg
);
// When `cacheEvicted` is true, the cached org was stale (404'd) — do NOT
// let it win the `??` chain; re-derive from the permalink instead.
const effectiveCachedOrg = cacheEvicted ? null : cachedOrg;
const resolvedOrgSlug =
resolvedOrg?.org ??
effectiveCachedOrg ??
extractOrgFromPermalink(issue.permalink);
if (resolvedOrgSlug && !resolvedOrg && !effectiveCachedOrg) {
// Best-effort — a broken/read-only DB must not fail a successful lookup.
try {
setCachedIssueOrg(groupId, resolvedOrgSlug);
} catch (cacheErr) {
log.debug(
`Failed to cache issue-org mapping for ${groupId}: ${String(cacheErr)}`
);
}
}
return { org: resolvedOrgSlug, issue };
}
/**
* Options for resolving an issue ID.
*/
export type ResolveIssueOptions = {
/** User-provided issue argument (raw CLI input) */
issueArg: string;
/** Current working directory for context resolution */
cwd: string;
/** Command name for error messages (e.g., "view", "explain") */
command: string;
/** Base command prefix for error hints (default: "sentry issue") */
commandBase?: string;
};
/**
* Extract the organization slug from a Sentry issue permalink.
*
* Handles both path-based (`https://sentry.io/organizations/{org}/issues/...`)
* and subdomain-style (`https://{org}.sentry.io/issues/...`) SaaS URLs.
* Returns undefined if the permalink is missing or not a recognized format.
*
* @param permalink - Issue permalink URL from the Sentry API response
*/
function extractOrgFromPermalink(
permalink: string | undefined
): string | undefined {
if (!permalink) {
return;
}
return parseSentryUrl(permalink)?.org;
}
/**
* Result of {@link fetchIssueByNumericId}.
*
* `cacheEvicted` is true when the helper invalidated a stale `cachedOrg`
* entry after a 404 and fell through to the legacy unscoped endpoint.
* Callers MUST treat their local `cachedOrg` as stale when this flag is
* set and re-derive the org from `issue.permalink` instead — otherwise
* a stale slug leaks into downstream API calls (issue events, traces).
*/
type FetchIssueByNumericIdResult = {
issue: SentryIssue;
cacheEvicted: boolean;
};
/**
* Fetch an issue by numeric ID, preferring an org-scoped endpoint when
* the caller has explicit or cached org context. Falls back to the legacy
* unscoped `/api/0/issues/{id}/` endpoint when no org is known, and also
* when a cached org yields a 404 (stale mapping).
*
* Extracted from {@link resolveNumericIssue} to keep its cognitive
* complexity below the project's lint threshold.
*/
async function fetchIssueByNumericId(
id: string,
explicitOrg: string | undefined,
cachedOrg: string | null | undefined
): Promise<FetchIssueByNumericIdResult> {
Iif (explicitOrg) {
const issue = await getIssueInOrg(explicitOrg, id, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { issue, cacheEvicted: false };
}
if (cachedOrg) {
try {
const issue = await getIssueInOrg(cachedOrg, id, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
return { issue, cacheEvicted: false };
} catch (orgErr) {
if (orgErr instanceof ApiError && orgErr.status === 404) {
// Stale mapping (issue moved / deleted / access revoked). Evict the
// cache entry and fall through to the legacy unscoped endpoint.
clearCachedIssueOrg(id);
const issue = await getIssue(id, { collapse: ISSUE_DETAIL_COLLAPSE });
return { issue, cacheEvicted: true };
}
throw orgErr;
}
}
const issue = await getIssue(id, { collapse: ISSUE_DETAIL_COLLAPSE });
return { issue, cacheEvicted: false };
}
/**
* Resolve a bare numeric issue ID.
*
* Attempts org-scoped resolution with region routing when org context can be
* derived from the working directory (DSN / env vars / config defaults), or
* from the issue-id → org cache populated on previous runs.
* Falls back to the legacy unscoped endpoint otherwise.
* Extracts the org slug from the response permalink so callers like
* {@link resolveOrgAndIssueId} can proceed without explicit org context.
*
* Caching: after a successful permalink-based org extraction, records the
* numeric-id → org mapping so future runs skip the unscoped fallback and
* route directly via the regional API. This addresses the
* `sentry.issue.view` "Consecutive HTTP" fan-out pattern for bare numeric
* IDs (Pattern D in the Sentry issue triage).
*/
async function resolveNumericIssue(
id: string,
cwd: string,
command: string,
commandBase = "sentry issue"
): Promise<ResolvedIssueResult> {
const resolvedOrg = await resolveOrg({ cwd });
// Prefer explicit context over the cache — `resolveOrg()` already factors
// in env vars and config defaults that may point at a different org.
const cachedOrg = resolvedOrg ? null : getCachedIssueOrg(id);
try {
const { issue, cacheEvicted } = await fetchIssueByNumericId(
id,
resolvedOrg?.org,
cachedOrg
);
// When `cacheEvicted` is true, the cached org slug was stale (404'd) and
// the helper fell through to the unscoped endpoint. Do NOT let the stale
// `cachedOrg` participate in the `??` chain — re-derive from permalink.
const effectiveCachedOrg = cacheEvicted ? null : cachedOrg;
// Extract org from the response permalink as a fallback so that callers
// like resolveOrgAndIssueId (used by explain/plan) get the org slug even
// when no org context was available before the fetch.
const org =
resolvedOrg?.org ??
effectiveCachedOrg ??
extractOrgFromPermalink(issue.permalink);
// Best-effort: remember the numeric-id → org mapping so the next run
// skips the unscoped fallback. Skipped when the org came from a still-
// valid cache hit (already stored). When the cache was evicted we SHOULD
// re-write the corrected mapping derived from the permalink.
if (org && !resolvedOrg && !effectiveCachedOrg) {
// Best-effort — a broken/read-only DB must not fail a successful lookup.
try {
setCachedIssueOrg(id, org);
} catch (cacheErr) {
log.debug(
`Failed to cache issue-org mapping for ${id}: ${String(cacheErr)}`
);
}
}
return { org, issue };
} catch (err) {
if (err instanceof ApiError && err.status === 404) {
// Improve on the generic "Issue not found" message by including the ID
// and suggesting the short-ID format, since users often confuse numeric
// group IDs with short-ID suffixes. When org context is available, use
// the real org slug instead of <org> placeholder (CLI-BT, 18 users).
//
// Skip `cachedOrg` here: if the unscoped legacy endpoint 404'd too,
// the helper has already evicted the (proven-stale) cache entry, so
// suggesting the old slug in the hint would mislead the user. Only
// explicit `resolvedOrg` is worth preserving.
const orgHint = resolvedOrg?.org ?? "<org>";
const hint = `${commandBase} ${command} ${orgHint}/${id}`;
throw new ResolutionError(`Issue ${id}`, "not found", hint, [
`No issue with numeric ID ${id} found — you may not have access, or it may have been deleted.`,
`If this is a short ID suffix, try: ${commandBase} ${command} <project>-${id}`,
]);
}
throw err;
}
}
/**
* Resolve an issue ID to organization slug and full issue object.
*
* Supports all issue ID formats (now parsed by parseIssueArg in arg-parsing.ts):
* - selector: "@latest", "sentry/@most_frequent" → top issue by criteria
* - explicit: "sentry/cli-G" → org + project + suffix
* - explicit-org-suffix: "sentry/G" → org + suffix (needs DSN for project)
* - explicit-org-numeric: "sentry/123456789" → org + numeric ID
* - project-search: "cli-G" → search for project across orgs
* - suffix-only: "G" (requires DSN context)
* - numeric: "123456789" (direct fetch, no org)
*
* @param options - Resolution options
* @returns Object with org slug and full issue
* @throws {ContextError} When required context (org) is missing
* @throws {ResolutionError} When an issue or project could not be found or resolved
*/
export async function resolveIssue(
options: ResolveIssueOptions
): Promise<ResolvedIssueResult> {
const { issueArg, cwd, command, commandBase } = options;
const parsed = parseIssueArg(issueArg);
const commandHint = buildCommandHint(command, issueArg, commandBase);
let result: ResolvedIssueResult;
switch (parsed.type) {
case "numeric":
result = await resolveNumericIssue(parsed.id, cwd, command, commandBase);
break;
case "explicit": {
// Full context: org + project + suffix
const org = await resolveEffectiveOrg(parsed.org);
const fullShortId = expandToFullShortId(parsed.suffix, parsed.project);
const issue = await getIssueByShortId(org, fullShortId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
result = { org, issue };
break;
}
case "explicit-org-numeric": {
// Org + numeric ID — use org-scoped endpoint for proper region routing.
const org = await resolveEffectiveOrg(parsed.org);
try {
const issue = await getIssueInOrg(org, parsed.numericId, {
collapse: ISSUE_DETAIL_COLLAPSE,
});
result = { org, issue };
} catch (err) {
if (err instanceof ApiError && err.status === 404) {
throw new ResolutionError(
`Issue ${parsed.numericId}`,
"not found",
commandHint,
[
`No issue with numeric ID ${parsed.numericId} found in org '${org}' — you may not have access, or it may have been deleted.`,
`If this is a short ID suffix, try: sentry issue ${command} <project>-${parsed.numericId}`,
]
);
}
throw err;
}
break;
}
case "explicit-org-suffix": {
// Org + suffix only - ambiguous without project, always errors
const org = await resolveEffectiveOrg(parsed.org);
result = await resolveExplicitOrgSuffix(org, parsed.suffix, commandHint);
break;
}
case "project-search":
// Project slug + suffix - search across orgs
result = await resolveProjectSearch(
parsed.projectSlug,
parsed.suffix,
cwd,
commandHint
);
break;
case "suffix-only":
// Just suffix - need DSN for org and project
result = await resolveSuffixOnly(parsed.suffix, cwd, commandHint);
break;
case "selector":
// Magic @ selector - fetch top issue by sort criteria
result = await resolveSelector(
parsed.selector,
parsed.org,
cwd,
commandHint
);
break;
case "share":
// Share URL — resolve via public share API, then authenticated fetch
result = await resolveShareIssue(
parsed.shareId,
parsed.org,
parsed.baseUrl,
cwd
);
break;
default: {
// Exhaustive check - this should never be reached
const _exhaustive: never = parsed;
throw new Error(
`Unexpected issue arg type: ${JSON.stringify(_exhaustive)}`
);
}
}
// Set telemetry context from the resolved result
if (result.org) {
setOrgProjectContext(
[result.org],
result.issue.project?.slug ? [result.issue.project.slug] : []
);
}
return result;
}
/**
* Resolve both organization slug and numeric issue ID.
* Required for autofix endpoints that need both org and issue ID.
* This is a stricter wrapper around resolveIssue that throws if org is undefined.
*
* @param options - Resolution options
* @returns Object with org slug and numeric issue ID
* @throws {ContextError} When organization cannot be resolved
*/
export async function resolveOrgAndIssueId(
options: ResolveIssueOptions
): Promise<{ org: string; issueId: string }> {
const result = await resolveIssue(options);
if (!result.org) {
const commandHint = buildCommandHint(options.command, options.issueArg);
throw new ContextError("Organization", commandHint);
}
return { org: result.org, issueId: result.issue.id };
}
type PollAutofixOptions = {
/** Organization slug */
orgSlug: string;
/** Numeric issue ID */
issueId: string;
/** Whether to suppress progress output (JSON mode) */
json: boolean;
/** Polling interval in milliseconds (default: 1000) */
pollIntervalMs?: number;
/** Maximum time to wait in milliseconds (default: 360000 = 6 minutes) */
timeoutMs?: number;
/** Custom timeout error message */
timeoutMessage?: string;
/** Actionable hint appended to the TimeoutError (e.g., "Run the command again…").
* When omitted, defaults to a hint with the Sentry issue URL. */
timeoutHint?: string;
/** Stop polling when status is WAITING_FOR_USER_RESPONSE (default: false) */
stopOnWaitingForUser?: boolean;
};
type EnsureRootCauseOptions = {
/** Organization slug */
org: string;
/** Numeric issue ID */
issueId: string;
/** Whether to suppress progress output (JSON mode) */
json: boolean;
/** Force new analysis even if one exists */
force?: boolean;
};
/**
* Ensure root cause analysis exists for an issue.
*
* If no analysis exists (or force is true), triggers a new analysis.
* If analysis is in progress, waits for it to complete.
* If analysis failed (ERROR status), retries automatically.
*
* @param options - Configuration options
* @returns The completed autofix state with root causes
*/
export async function ensureRootCauseAnalysis(
options: EnsureRootCauseOptions
): Promise<AutofixState> {
const { org, issueId, json, force = false } = options;
// 1. Check for existing analysis (skip if --force)
let state = force ? null : await getAutofixState(org, issueId);
// Handle error status - we will retry the analysis
if (state?.status === "ERROR") {
Iif (!json) {
log.info("Previous analysis failed, retrying...");
}
state = null;
}
// 2. Trigger new analysis if none exists or forced
if (!state) {
if (!json) {
const prefix = force ? "Forcing fresh" : "Starting";
log.info(`${prefix} root cause analysis, it can take several minutes...`);
}
await triggerRootCauseAnalysis(org, issueId);
}
// 3. Poll until complete (if not already completed)
if (
!state ||
(state.status !== "COMPLETED" &&
state.status !== "WAITING_FOR_USER_RESPONSE")
) {
state = await pollAutofixState({
orgSlug: org,
issueId,
json,
stopOnWaitingForUser: true,
});
}
return state;
}
/**
* Check if polling should stop based on current state.
*
* Terminal statuses (COMPLETED, ERROR, CANCELLED) always stop polling.
* When `stopOnWaitingForUser` is true, also stops on interactive statuses:
* - `WAITING_FOR_USER_RESPONSE` — root cause analysis needs user input
* - `NEED_MORE_INFORMATION` — solution step completed, awaiting user decision
*
* @param state - Current autofix state
* @param stopOnWaitingForUser - Whether to stop on interactive statuses
* @returns True if polling should stop
*/
function shouldStopPolling(
state: AutofixState,
stopOnWaitingForUser: boolean
): boolean {
if (isTerminalStatus(state.status)) {
return true;
}
if (
stopOnWaitingForUser &&
(state.status === "WAITING_FOR_USER_RESPONSE" ||
state.status === "NEED_MORE_INFORMATION")
) {
return true;
}
return false;
}
/**
* Poll autofix state until completion or timeout.
* Uses the generic poll utility with autofix-specific configuration.
*
* @param options - Polling configuration
* @returns Final autofix state
* @throws {Error} On timeout
*/
export async function pollAutofixState(
options: PollAutofixOptions
): Promise<AutofixState> {
const {
orgSlug,
issueId,
json,
pollIntervalMs,
timeoutMs = DEFAULT_TIMEOUT_MS,
timeoutMessage = "Operation timed out after 6 minutes. Try again or check the issue in Sentry web UI.",
timeoutHint,
stopOnWaitingForUser = false,
} = options;
const issueUrl = buildIssueUrl(orgSlug, issueId);
const hint =
timeoutHint ??
"The analysis may still complete in the background.\n" +
` View in Sentry: ${issueUrl}\n` +
` Or retry: sentry issue explain ${issueId}`;
return await poll<AutofixState>({
fetchState: () => getAutofixState(orgSlug, issueId),
shouldStop: (state) => shouldStopPolling(state, stopOnWaitingForUser),
getProgressMessage,
json,
pollIntervalMs,
timeoutMs,
timeoutMessage,
timeoutHint: hint,
initialMessage: "Waiting for analysis to start...",
});
}
|