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 | 11x 11x 11x 11x 11x 11x 11x 11x 11x 55x 42x 4x 38x 15x 23x 7x 7x 42x 42x 42x 29x 29x 29x 81x 29x 29x 85x 14x 29x 30x 1x 29x 29x 30x 30x 30x 30x 3x 3x 3x 1x 3x 11x 103x 66x 8x 8x 2x 66x 66x 2x 66x 66x 16x 38x 66x 66x 66x 30x 30x 66x 66x 66x 66x 66x 2x 66x 2x 2x 66x 66x 48x 8x 2x 2x 2x 2x 3x 5x 3x 2x 1x 35x 35x 8x 43x 8x 1x 7x 8x 7x 7x 7x 27x 1x 26x 26x 35x 1x 25x 25x 26x 26x 26x 33x 33x 32x 32x 1x 11x 38x 38x 37x 37x 38x 38x 11x 37x 37x 37x 4x 1x 1x 4x 4x 4x 4x 4x 1x 4x 33x 4x 1x 3x 35x 35x 38x 38x 33x 33x 33x 33x 33x 38x 38x 38x 38x 33x | /**
* sentry explore
*
* Query aggregate event data using the Sentry Explore/Events API.
* Supports arbitrary fields, aggregates, and datasets for spike analysis
* and ad-hoc event queries.
*/
import type { SentryContext } from "../context.js";
import {
isReplaySortValue,
listReplays,
queryEvents,
queryMetricsMeta,
} from "../lib/api-client.js";
import { buildProjectQuery, validateLimit } from "../lib/arg-parsing.js";
import {
advancePaginationState,
buildPaginationContextKey,
hasPreviousPage,
resolveCursor,
} from "../lib/db/pagination.js";
import { ValidationError } from "../lib/errors.js";
import { filterFields } from "../lib/formatters/json.js";
import { buildMetaColumns } from "../lib/formatters/meta-table.js";
import { CommandOutput } from "../lib/formatters/output.js";
import { formatTable } from "../lib/formatters/table.js";
import {
appendQueryHint,
appendSortHint,
buildListCommand,
LIST_MAX_LIMIT,
PERIOD_ALIASES,
paginationHint,
} from "../lib/list-command.js";
import { logger } from "../lib/logger.js";
import { resolveMetricField } from "../lib/metrics-transform.js";
import { withProgress } from "../lib/polling.js";
import {
DEFAULT_REPLAY_EXPLORE_FIELDS,
getReplayFieldValue,
getReplayRequestFields,
isSupportedReplayField,
listSupportedReplayFields,
parseReplayEnvironmentFilter,
} from "../lib/replay-search.js";
import { resolveOrgOptionalProjectFromArg } from "../lib/resolve-target.js";
import { sanitizeQuery } from "../lib/search-query.js";
import {
appendPeriodHint,
PERIOD_BRIEF,
parsePeriod,
serializeTimeRange,
type TimeRange,
timeRangeToApiParams,
} from "../lib/time-range.js";
const log = logger.withTag("explore");
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Default fields when none specified — top errors view */
const DEFAULT_FIELDS = ["title", "count()"];
/** Default dataset */
const DEFAULT_DATASET = "errors";
const DEFAULT_REPLAY_SORT = "-started_at";
/** Default time period */
const DEFAULT_PERIOD = "24h";
/** Command key for pagination cursor storage */
const PAGINATION_KEY = "explore";
/**
* Dataset aliases: user-facing name → API-level dataset name.
*
* All entries are accepted as `--dataset` values. `VALID_DATASETS` controls
* which appear in `--help` and validation error messages.
*/
const DATASET_ALIASES: Record<string, string> = {
errors: "errors",
error: "errors",
spans: "spans",
span: "spans",
metrics: "tracemetrics",
logs: "logs",
log: "logs",
replays: "replays",
replay: "replays",
// Deprecated but still functional — hidden from help
transactions: "transactions",
transaction: "transactions",
discover: "discover",
};
/**
* User-facing dataset names shown in `--help` and validation errors.
* Deprecated datasets (transactions, discover) are omitted from the display
* list but still work as `--dataset` values via `DATASET_ALIASES`.
*
* Set preserves insertion order for the join-based help/error rendering.
*/
const VALID_DATASETS = new Set([
"errors",
"spans",
"metrics",
"logs",
"replays",
]);
/**
* Reverse map from API-level dataset name → canonical user-facing name.
* Used by pagination hints so they emit `--dataset metrics` not `--dataset tracemetrics`.
*/
const API_TO_USER_DATASET = new Map(
Array.from(VALID_DATASETS, (name) => [DATASET_ALIASES[name] ?? name, name])
);
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type ExploreFlags = {
readonly field?: string[];
readonly metric?: string;
readonly agg: string;
readonly dataset: string;
readonly environment?: readonly string[];
readonly query?: string;
readonly sort?: string;
readonly period: TimeRange;
readonly limit: number;
readonly cursor?: string;
readonly json: boolean;
readonly fresh: boolean;
readonly fields?: string[];
};
/** Data yielded by the explore command for both JSON and human output */
type ExploreData = {
data: Record<string, unknown>[];
meta?: {
fields?: Record<string, string>;
units?: Record<string, string | null>;
};
hasMore: boolean;
hasPrev: boolean;
nextCursor?: string | null;
dataset: string;
org: string;
/** Project filter, when target was `org/project` */
project?: string;
/** The fields the user requested, in their original order — drives column order */
requestedFields: string[];
};
// ---------------------------------------------------------------------------
// Flag parsing
// ---------------------------------------------------------------------------
/**
* Parse and validate dataset flag value.
* Accepts canonical names and common aliases.
*/
function parseDataset(value: string): string {
const lower = value.toLowerCase();
const resolved = DATASET_ALIASES[lower];
if (!resolved) {
throw new ValidationError(
`Invalid dataset "${value}". Must be one of: ${[...VALID_DATASETS].join(", ")}`,
"dataset"
);
}
return resolved;
}
/**
* Parse --limit flag. Capped at {@link LIST_MAX_LIMIT} (1000).
* `queryEvents` auto-paginates when the limit exceeds the API's per-page cap.
*/
function parseLimit(value: string): number {
return validateLimit(value, 1, LIST_MAX_LIMIT);
}
/** Infer a Discover-style column type for a replay field (used for table alignment). */
function inferReplayFieldType(field: string): string {
if (field === "duration") {
return "duration";
}
if (field === "activity" || field.startsWith("count_")) {
return "integer";
}
return "string";
}
function buildReplayExploreResponse(
fields: string[],
replays: Awaited<ReturnType<typeof listReplays>>["data"]
): { data: Record<string, unknown>[]; meta: NonNullable<ExploreData["meta"]> } {
return {
data: replays.map((replay) =>
Object.fromEntries(
fields.map((field) => [field, getReplayFieldValue(replay, field)])
)
),
meta: {
fields: Object.fromEntries(
fields.map((field) => [field, inferReplayFieldType(field)])
),
units: Object.fromEntries(
fields.map((field) => [field, field === "duration" ? "s" : null])
),
},
};
}
// ---------------------------------------------------------------------------
// Output formatters
// ---------------------------------------------------------------------------
/**
* Determine the column order for the table.
*
* Preserves the user's `--field` order, then appends any extra fields the
* API returned that weren't in the request (rare, but possible for derived
* fields like equations). Falls back to API response keys when no requested
* fields are available.
*/
function orderFieldNames(
requestedFields: string[],
data: ExploreData
): string[] {
const apiFields = data.meta?.fields
? Object.keys(data.meta.fields)
: Object.keys(data.data[0] ?? {});
Iif (requestedFields.length === 0) {
return apiFields;
}
const apiSet = new Set(apiFields);
const ordered = requestedFields.filter((f) => apiSet.has(f));
// Append any API-returned fields that weren't requested (preserves API order)
const requestedSet = new Set(ordered);
for (const f of apiFields) {
if (!requestedSet.has(f)) {
ordered.push(f);
}
}
return ordered;
}
/** Format explore results for human-readable terminal output */
function formatExploreHuman(data: ExploreData): string {
if (data.data.length === 0) {
// Empty page mid-pagination (more or prev pages exist) vs. truly no results.
return data.hasMore || data.hasPrev
? "No results on this page."
: "No results matched the query.";
}
const fieldNames = orderFieldNames(data.requestedFields, data);
const columns = buildMetaColumns(
fieldNames,
data.meta?.fields,
data.meta?.units
);
const scope = data.project ? `${data.org}/${data.project}` : data.org;
const displayDataset = API_TO_USER_DATASET.get(data.dataset) ?? data.dataset;
const header = `Querying ${displayDataset} in ${scope}:\n\n`;
return header + formatTable(data.data, columns);
}
/** Transform explore results for JSON output */
function jsonTransformExplore(data: ExploreData, fields?: string[]): unknown {
const items =
fields && fields.length > 0
? data.data.map((row) => filterFields(row, fields))
: data.data;
const envelope: Record<string, unknown> = {
data: items,
meta: data.meta,
hasMore: data.hasMore,
hasPrev: data.hasPrev,
dataset: data.dataset,
};
if (
data.nextCursor !== null &&
data.nextCursor !== undefined &&
data.nextCursor !== ""
) {
envelope.nextCursor = data.nextCursor;
}
return envelope;
}
// ---------------------------------------------------------------------------
// Pagination hints
// ---------------------------------------------------------------------------
/** Default limit value matching the flag default for hint comparison */
const DEFAULT_LIMIT = 25;
function defaultFieldsForDataset(dataset: string): readonly string[] {
return dataset === "replays" ? DEFAULT_REPLAY_EXPLORE_FIELDS : DEFAULT_FIELDS;
}
/** Append --metric / --agg flags to hint parts */
function appendMetricHints(
parts: string[],
metric: string | undefined,
agg: string
): void {
if (metric) {
parts.push(`-m "${metric}"`);
if (agg !== "sum") {
parts.push(`--agg ${agg}`);
}
}
}
/** Append non-default --field flags to hint parts */
function appendFieldHints(
parts: string[],
rawFields: string[] | undefined,
dataset: string,
metricActive: boolean
): void {
const fields = rawFields ?? [];
const fieldList = metricActive
? fields.filter((f) => !isAggregate(f))
: fields;
const defaults = defaultFieldsForDataset(dataset).join(",");
if (fieldList.join(",") !== defaults && fieldList.length > 0) {
for (const f of fieldList) {
parts.push(`-F "${f}"`);
}
}
}
/** Append active non-default flags to a base command string */
function appendFlagHints(
base: string,
flags: Pick<
ExploreFlags,
| "dataset"
| "environment"
| "sort"
| "query"
| "period"
| "field"
| "limit"
| "metric"
| "agg"
>
): string {
const parts: string[] = [];
const defaultSort =
flags.dataset === "replays" ? DEFAULT_REPLAY_SORT : undefined;
if (flags.dataset !== DEFAULT_DATASET) {
// Emit user-facing name, not API-level name (e.g. "metrics" not "tracemetrics")
const displayDataset =
API_TO_USER_DATASET.get(flags.dataset) ?? flags.dataset;
parts.push(`--dataset ${displayDataset}`);
}
appendMetricHints(parts, flags.metric, flags.agg);
appendSortHint(parts, flags.sort, defaultSort);
appendQueryHint(parts, flags.query);
appendFieldHints(parts, flags.field, flags.dataset, !!flags.metric);
if (flags.limit !== DEFAULT_LIMIT) {
parts.push(`--limit ${flags.limit}`);
}
if (flags.environment && flags.environment.length > 0) {
for (const environment of flags.environment) {
parts.push(`-e "${environment}"`);
}
}
appendPeriodHint(parts, flags.period, DEFAULT_PERIOD);
return parts.length > 0 ? `${base} ${parts.join(" ")}` : base;
}
/**
* Detect the first aggregate function in the field list.
* Aggregates contain parentheses, e.g., `count()`, `p50(transaction.duration)`.
*/
function findFirstAggregate(fieldList: string[]): string | undefined {
return fieldList.find((f) => f.includes("(") && f.includes(")"));
}
/** True when the field looks like an aggregate call: `fn(...)`. */
function isAggregate(field: string): boolean {
return field.includes("(") && field.endsWith(")");
}
/**
* True when the aggregate uses the tracemetrics comma-separated format:
* `aggregation(value,metric_name,metric_type,unit)`.
*/
function isTracemetricsAggregate(aggregate: string): boolean {
const parenIdx = aggregate.indexOf("(");
Iif (parenIdx < 0) {
return false;
}
const inner = aggregate.slice(parenIdx + 1, -1);
return inner.startsWith("value,") && inner.split(",").length === 4;
}
/**
* Validate that aggregate fields use the tracemetrics format when querying
* the `tracemetrics` dataset. Standard aggregates like `count()` or
* `avg(measurements.fcp)` are invalid — the API requires the four-part
* comma-separated format: `aggregation(value,metric_name,metric_type,unit)`.
*/
function validateMetricsFields(fieldList: string[]): void {
const badAggs = fieldList.filter(
(f) => isAggregate(f) && !isTracemetricsAggregate(f)
);
if (badAggs.length === 0) {
return;
}
throw new ValidationError(
`Invalid metrics aggregate${badAggs.length > 1 ? "s" : ""}: ${badAggs.join(", ")}\n\n` +
"The metrics dataset requires the format: aggregation(value,metric_name,metric_type,unit)\n\n" +
"Examples:\n" +
' sentry explore my-org/ -F "sum(value,llm.token_usage,distribution,none)" --dataset metrics\n' +
' sentry explore my-org/ -F gen_ai.request.model -F "avg(value,cache.hit_rate,distribution,none)" --dataset metrics\n\n' +
"Parameters:\n" +
' - value: literal string "value"\n' +
" - metric_name: the metric name emitted by the SDK (e.g., llm.token_usage)\n" +
" - metric_type: distribution, gauge, counter, or set\n" +
" - unit: none, byte, second, millisecond, etc.",
"field"
);
}
// ---------------------------------------------------------------------------
// Dataset configuration
// ---------------------------------------------------------------------------
/**
* Dataset-specific configuration resolved before the main query loop.
*
* Centralizes all replay vs. non-replay branching so the main `func` body
* reads linearly without `dataset === "replays"` checks.
*/
type DatasetConfig = {
/** The effective sort value for pagination context and API calls. */
sort: string | undefined;
/** The API query string (with or without `project:` prefix). */
query: string | undefined;
/** Execute the dataset-specific API query. */
fetch: (params: {
cursor: string | undefined;
limit: number;
timeRange: TimeRange;
}) => Promise<{
data: { data: Record<string, unknown>[]; meta?: ExploreData["meta"] };
nextCursor?: string;
}>;
};
/**
* Resolve dataset-specific configuration: sort, query, validation, and fetch.
*
* For the `replays` dataset this validates fields, resolves replay-specific
* sort, and returns a fetch function that calls `listReplays`. For all other
* datasets it validates environment usage, resolves explore sort (spans-only),
* prepends `project:<slug>` to the query, and returns a `queryEvents` fetch.
*/
function resolveDatasetConfig(params: {
dataset: string;
fieldList: string[];
flags: ExploreFlags;
org: string;
project: string | undefined;
environment: string[] | undefined;
}): DatasetConfig {
const { dataset, fieldList, flags, org, project, environment } = params;
if (dataset === "replays") {
const unsupportedField = fieldList.find(
(field) => !isSupportedReplayField(field)
);
if (unsupportedField) {
throw new ValidationError(
`Unsupported replay field "${unsupportedField}". Supported fields include: ${listSupportedReplayFields().slice(0, 12).join(", ")}...`,
"field"
);
}
const sort = flags.sort ?? DEFAULT_REPLAY_SORT;
Iif (!isReplaySortValue(sort)) {
throw new ValidationError(
`Invalid replay sort "${sort}". Use a replay sort like ${DEFAULT_REPLAY_SORT} or -count_errors.`,
"sort"
);
}
return {
sort,
query: flags.query,
fetch: async ({ cursor, limit, timeRange }) => {
const replayResponse = await listReplays(org, {
cursor,
environment,
fields: getReplayRequestFields(fieldList),
limit,
projectSlugs: project ? [project] : undefined,
query: flags.query,
sort,
...timeRangeToApiParams(timeRange),
});
return {
data: buildReplayExploreResponse(fieldList, replayResponse.data),
nextCursor: replayResponse.nextCursor,
};
},
};
}
// Non-replay datasets
if (environment) {
throw new ValidationError(
"--environment is only supported with --dataset replays. Use environment:... inside --query for other datasets.",
"environment"
);
}
const firstAgg = findFirstAggregate(fieldList);
const rawSort = flags.sort ?? (firstAgg ? `-${firstAgg}` : undefined);
let sort: string | undefined;
if (dataset === "spans") {
sort = rawSort;
} else {
// Warn only when user explicitly passed --sort on a non-spans dataset
Iif (rawSort && flags.sort) {
log.warn(
`--sort is only supported on the spans dataset. Ignoring sort for ${dataset}.`
);
}
sort = undefined;
}
const query = buildProjectQuery(flags.query, project);
return {
sort,
query,
fetch: async ({ cursor, limit, timeRange }) =>
queryEvents(org, {
fields: fieldList,
dataset,
query,
sort,
limit,
cursor,
...timeRangeToApiParams(timeRange),
}),
};
}
/** Build the result hint string from pagination state and row count */
function buildResultHint(rowCount: number, nav: string): string | undefined {
Iif (rowCount === 0 && nav) {
return nav;
}
if (rowCount > 0) {
const countText = `Showing ${rowCount} result${rowCount === 1 ? "" : "s"}.`;
return nav ? `${countText} ${nav}` : countText;
}
return;
}
// ---------------------------------------------------------------------------
// Command definition
// ---------------------------------------------------------------------------
export const exploreCommand = buildListCommand("explore", {
docs: {
brief: "Query aggregate event data (Explore)",
fullDescription:
"Query the Sentry Explore API for aggregate event data.\n\n" +
"Supports arbitrary fields including columns (title, project),\n" +
"aggregates (count(), count_unique(user), p50(transaction.duration)),\n" +
"and equations. Results are returned as a table.\n\n" +
"Datasets:\n" +
" errors Error events (default)\n" +
" spans Span data\n" +
" metrics Custom metrics (tracemetrics format)\n" +
" logs Log entries\n" +
" replays Session replay search\n\n" +
"Targets:\n" +
" <org>/<project> Filter by project (auto-adds project:<slug> to query)\n" +
" <org>/ All projects in org\n" +
" <project> Bare slug — searches across orgs\n" +
" (omitted) Auto-detect from DSN/config\n\n" +
"Examples:\n" +
' sentry explore my-org/cli -F title -F "count()"\n' +
' sentry explore my-org/ -F title -F "count()" -F "count_unique(user)" --period 1h\n' +
' sentry explore my-org/cli -F span.op -F "p50(span.duration)" ' +
"--dataset spans\n" +
" sentry explore my-org/cli --dataset replays -F id -F user.email -F count_errors\n" +
' sentry explore -F span.op -F "count()" --dataset spans --period 1h\n' +
" sentry explore --json\n\n" +
"Metrics (auto mode — resolves type/unit automatically):\n" +
" sentry explore my-org/ -m llm.token_usage --dataset metrics\n" +
" sentry explore my-org/seer -F gen_ai.request.model -m llm.token_usage --dataset metrics --period 7d\n" +
" sentry explore my-org/ -m cache.hit_rate --agg avg --dataset metrics",
},
output: {
human: formatExploreHuman,
jsonTransform: jsonTransformExplore,
},
parameters: {
positional: {
kind: "tuple" as const,
parameters: [
{
placeholder: "target",
brief:
"Target: <org>/<project>, <org>/, or <project>. Auto-detected if omitted.",
parse: String,
optional: true as const,
},
],
},
flags: {
field: {
kind: "parsed",
parse: String,
brief:
'API field or aggregate (repeatable). E.g., title, "count()", "p50(transaction.duration)"',
variadic: true,
optional: true,
},
metric: {
kind: "parsed",
parse: String,
brief:
"Metric name for --dataset metrics. Auto-resolves type/unit via API.",
optional: true,
},
agg: {
kind: "parsed",
parse: String,
brief: "Aggregation for --metric (sum, avg, count, p50, p95, etc.)",
default: "sum",
},
dataset: {
kind: "parsed",
parse: parseDataset,
brief: `Dataset to query (${[...VALID_DATASETS].join(", ")})`,
default: DEFAULT_DATASET,
},
query: {
kind: "parsed",
parse: sanitizeQuery,
brief: "Search query (Sentry search syntax)",
optional: true,
},
sort: {
kind: "parsed",
parse: String,
brief: 'Sort field (prefix with - for desc, e.g., "-count()")',
optional: true,
},
environment: {
kind: "parsed",
parse: String,
brief:
"Replay environment filter for --dataset replays (repeatable, comma-separated)",
variadic: true,
optional: true,
},
limit: {
kind: "parsed",
parse: parseLimit,
brief: `Number of rows (1-${LIST_MAX_LIMIT})`,
default: "25",
},
period: {
kind: "parsed" as const,
parse: parsePeriod,
brief: PERIOD_BRIEF,
default: DEFAULT_PERIOD,
},
},
aliases: {
...PERIOD_ALIASES,
e: "environment",
F: "field",
m: "metric",
d: "dataset",
q: "query",
s: "sort",
n: "limit",
},
},
async *func(this: SentryContext, flags: ExploreFlags, target?: string) {
const { cwd } = this;
const { org, project } = await resolveOrgOptionalProjectFromArg(
target,
cwd,
"explore"
);
let dataset = flags.dataset;
const userSuppliedFields = flags.field && flags.field.length > 0;
let fieldList = [...defaultFieldsForDataset(dataset)];
if (userSuppliedFields) {
fieldList = flags.field;
}
const timeRange = flags.period;
const environment = parseReplayEnvironmentFilter(flags.environment);
// --metric auto mode: resolve metric name → tracemetrics aggregate
if (flags.metric) {
if (dataset !== "tracemetrics") {
log.warn("--metric implies --dataset metrics; switching dataset.");
dataset = "tracemetrics";
}
// Use the user's --period for metadata discovery so older metrics are found
const metaParams = timeRangeToApiParams(timeRange);
const metrics = await withProgress(
{
message: `Discovering metric '${flags.metric}'...`,
json: flags.json,
},
() =>
queryMetricsMeta(org, {
...metaParams,
project,
})
);
const aggField = resolveMetricField(flags.metric, flags.agg, metrics);
// Prepend any user-supplied grouping fields, then the resolved aggregate
const groupByFields = userSuppliedFields
? fieldList.filter((f) => !isAggregate(f))
: [];
fieldList = [...groupByFields, aggField];
} else if (dataset === "tracemetrics") {
if (!userSuppliedFields) {
throw new ValidationError(
"The metrics dataset requires --metric or explicit --field flags.\n\n" +
"Auto mode (recommended):\n" +
" sentry explore my-org/ -m llm.token_usage --dataset metrics\n" +
" sentry explore my-org/ -m llm.token_usage --agg avg --dataset metrics\n\n" +
"Manual mode (tracemetrics format):\n" +
' sentry explore my-org/ -F "sum(value,llm.token_usage,distribution,none)" --dataset metrics',
"field"
);
}
validateMetricsFields(fieldList);
}
const config = resolveDatasetConfig({
dataset,
fieldList,
flags,
org,
project,
environment,
});
const contextKey = buildPaginationContextKey(
"explore",
project ? `${org}/${project}` : org,
{
dataset,
env: environment?.join(","),
fields: fieldList.join(","),
q: flags.query,
sort: config.sort,
period: serializeTimeRange(timeRange),
}
);
const { cursor, direction } = resolveCursor(
flags.cursor,
PAGINATION_KEY,
contextKey
);
const { data: response, nextCursor } = await withProgress(
{
message: `Querying ${dataset} in ${project ? `${org}/${project}` : org}...`,
json: flags.json,
},
() => config.fetch({ cursor, limit: flags.limit, timeRange })
);
advancePaginationState(PAGINATION_KEY, contextKey, direction, nextCursor);
const hasPrev = hasPreviousPage(PAGINATION_KEY, contextKey);
const hasMore = !!nextCursor;
const baseTarget = project ? `${org}/${project}` : `${org}/`;
const hintFlags = { ...flags, dataset };
const nav = paginationHint({
hasPrev,
hasMore,
prevHint: appendFlagHints(
`sentry explore ${baseTarget} -c prev`,
hintFlags
),
nextHint: appendFlagHints(
`sentry explore ${baseTarget} -c next`,
hintFlags
),
});
const hint = buildResultHint(response.data.length, nav);
yield new CommandOutput({
data: response.data,
meta: response.meta,
hasMore,
hasPrev,
nextCursor,
dataset,
org,
project,
requestedFields: fieldList,
});
return { hint };
},
});
|