All files / src/lib/formatters semantic-display.ts

94.11% Statements 240/255
82.18% Branches 226/275
100% Functions 35/35
94.09% Lines 239/254

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                            15x                               15x 15x 15x     15x           15x                                                           2682x 3136x 141x 141x 141x       2541x                           57x 436x 436x 45x           12x                             26x 2x   24x             6x   18x 2x   16x     2x   14x         14x 1x   13x 1x   12x 1x   11x     11x 1x   10x                     53x 53x 53x 53x 53x 53x   53x 42x     11x 53x       53x                         57x 57x           57x   57x 57x   57x 53x     4x                   42x 42x 42x     42x   42x 36x     6x   6x                   36x 36x 36x   36x   36x 36x           36x                   32x       4x         36x 36x   36x                   32x 32x 32x           32x 30x     2x                         28x 28x 28x 28x 28x 28x   28x 26x       2x   28x                   26x 26x       26x         26x 26x 26x   26x 24x     2x                             23x 23x 23x 23x 23x 23x 23x       23x 23x 23x   23x                       21x     2x                                       17x       17x 17x   17x 15x     2x                         30x 30x 30x         30x 30x 30x   30x     30x 28x     2x                   24x 24x 24x         24x   24x 23x     1x                           21x 21x 21x 21x 21x 21x   21x 19x     2x                   19x 19x 19x 19x 19x 19x   19x 17x     2x                   15x 15x           15x 13x       2x       15x             15x             13x 13x 12x   1x               53x 53x         53x 44x   9x 6x   3x             42x         42x 42x 42x   42x 1x   41x 2x   39x     39x 3x   36x       77x 77x 77x 74x   3x 2x   1x                       6x 6x                               6x 6x 4x 4x   2x 2x 2x 6x                 8x             30x 1x   29x       53x 52x   1x       1x     1x             27x       156x       333x         258x 194x 64x 3x 61x           1x     258x 258x 62x   196x 194x   2x               153x         45x 45x 45x 27x     27x 27x     27x 27x   45x                   19x 19x 19x 19x    
/**
 * OTel semantic attribute rendering for local dev server output.
 *
 * Ported from sentry-mcp's trace-semantic-display.ts (PR #981) and adapted
 * for raw Sentry envelope items. Renders span/transaction labels from
 * OpenTelemetry semantic attributes before falling back to Sentry op/name.
 *
 * Covers: GenAI, MCP, HTTP, database, GraphQL, RPC/cloud, messaging,
 * FaaS, object stores, CloudEvents, CICD, feature flags, process,
 * exception, and error attributes.
 */
 
import { logger } from "../logger.js";
 
const log = logger.withTag("semantic-display");
 
/** Display result from semantic rendering. */
export type SemanticSpanDisplay = {
  /** Primary label for the span/transaction. */
  label: string;
  /** Additional metadata tokens shown after the label. */
  metadata: string[];
};
 
/** A function that attempts to render semantic display for an item. */
type SpanDisplayFormatter = (
  attrs: AttributeSource,
  fallbackLabel: string
) => SemanticSpanDisplay | null;
 
const SPAN_LABEL_MAX_LENGTH = 120;
const SPAN_METADATA_MAX_LENGTH = 64;
const SPAN_ATTRIBUTE_MAX_LENGTH = 2048;
 
/** Matches a URL scheme prefix like `https://` or `ftp://`. */
const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
 
/**
 * Ordered list of semantic formatters. The first match wins.
 * MCP before HTTP so `tools/call` isn't masked by transport-level `POST /mcp`.
 */
const SEMANTIC_SPAN_FORMATTERS: SpanDisplayFormatter[] = [
  formatMcpSpanDisplay,
  formatGenAiSpanDisplay,
  formatHttpSpanDisplay,
  formatDatabaseSpanDisplay,
  formatGraphqlSpanDisplay,
  formatObjectStoreSpanDisplay,
  formatRpcSpanDisplay,
  formatMessagingSpanDisplay,
  formatCloudEventsSpanDisplay,
  formatFaasSpanDisplay,
  formatCicdSpanDisplay,
  formatFeatureFlagSpanDisplay,
  formatProcessSpanDisplay,
  formatExceptionSpanDisplay,
  formatErrorSpanDisplay,
];
 
/**
 * Abstraction over attribute sources. In raw envelopes, attributes live in
 * `contexts.trace.data` or individual span `data` objects.
 */
export type AttributeSource = Record<string, unknown>;
 
/** Look up an attribute value by trying multiple keys in order. */
function getAttr(
  attrs: AttributeSource,
  keys: string[],
  maxLength = SPAN_METADATA_MAX_LENGTH
): string | undefined {
  for (const key of keys) {
    if (Object.hasOwn(attrs, key)) {
      const value = formatDisplayPart(attrs[key], maxLength);
      Eif (value) {
        return value;
      }
    }
  }
  return;
}
 
/**
 * Build a semantic display for a transaction or span from its attributes.
 *
 * @param attrs - Merged attribute object from the envelope item
 * @param fallbackLabel - The transaction name or span description to use as fallback
 * @returns A SemanticSpanDisplay with label and metadata, or the fallback
 */
export function formatSemanticSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay {
  for (const formatter of SEMANTIC_SPAN_FORMATTERS) {
    const result = formatter(attrs, fallbackLabel);
    if (result) {
      return {
        label: truncate(result.label, SPAN_LABEL_MAX_LENGTH) || "unnamed",
        metadata: dedupeMetadata(result.metadata),
      };
    }
  }
  return { label: fallbackLabel, metadata: [] };
}
 
/**
 * Derive a semantic op category from attributes for the `[op]` display.
 * Returns undefined if no semantic category is detected (falls back to trace.op).
 *
 * Only domains with a natural one-word op category are included.
 * CloudEvents, CICD, FeatureFlag, Exception, and Error are intentionally
 * omitted — they should preserve the original trace.op.
 * HTTP also returns undefined to keep the SDK-assigned op (e.g. `http.client`).
 * S3 is checked before RPC since S3 spans carry `rpc.method` but should
 * be tagged as `s3` rather than `rpc`.
 */
export function inferSemanticOp(attrs: AttributeSource): string | undefined {
  if (getAttr(attrs, ["mcp.method.name"])) {
    return "mcp";
  }
  if (
    getAttr(attrs, [
      "gen_ai.operation.name",
      "gen_ai.tool.name",
      "gen_ai.agent.name",
    ])
  ) {
    return "gen_ai";
  }
  if (getAttr(attrs, ["http.request.method", "http.response.status_code"])) {
    return;
  }
  if (
    getAttr(attrs, ["db.system.name", "db.query.summary", "db.operation.name"])
  ) {
    return "db";
  }
  Iif (getAttr(attrs, ["graphql.operation.type"])) {
    return "graphql";
  }
  // Check S3/object store before RPC — S3 spans carry rpc.method but should
  // be displayed as object store operations, not generic RPC.
  if (getAttr(attrs, ["aws.s3.bucket", "aws.s3.key"])) {
    return "s3";
  }
  if (getAttr(attrs, ["rpc.system.name", "rpc.service"])) {
    return "rpc";
  }
  if (getAttr(attrs, ["messaging.system", "messaging.operation.name"])) {
    return "messaging";
  }
  Iif (getAttr(attrs, ["faas.trigger", "faas.invoked_name"])) {
    return "faas";
  }
  if (getAttr(attrs, ["process.executable.name", "process.command"])) {
    return "process";
  }
  return;
}
 
// ---------------------------------------------------------------------------
// Semantic formatters — each returns null if the span doesn't match
// ---------------------------------------------------------------------------
 
function formatGenAiSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const operation = getAttr(attrs, ["gen_ai.operation.name"]);
  const toolName = getAttr(attrs, ["gen_ai.tool.name"]);
  const agentName = getAttr(attrs, ["gen_ai.agent.name"]);
  const model = getGenAiModelIdentifier(attrs);
  const dataSourceId = getAttr(attrs, ["gen_ai.data_source.id"]);
  const errorType = getErrorType(attrs);
 
  if (!(operation || toolName || agentName || model || dataSourceId)) {
    return null;
  }
 
  const subject = toolName ?? agentName ?? model ?? dataSourceId;
  const label = operation
    ? formatOperationLabel(operation, subject)
    : subject || fallbackLabel;
 
  return {
    label,
    metadata: compactStrings([
      subject === model ? undefined : model,
      errorType,
    ]),
  };
}
 
function formatMcpSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const method = getAttr(attrs, ["mcp.method.name"]);
  const resourceUri = getAttr(
    attrs,
    ["mcp.resource.uri"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
  const target =
    getAttr(attrs, ["gen_ai.tool.name", "gen_ai.prompt.name"]) ??
    formatResourceTarget(resourceUri);
  const statusCode = getAttr(attrs, ["rpc.response.status_code"]);
  const errorType = getErrorType(attrs);
 
  if (!(method || resourceUri)) {
    return null;
  }
 
  return {
    label: joinParts([method, target]) || fallbackLabel,
    metadata: compactStrings([statusCode, errorType]),
  };
}
 
function formatHttpSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const method = getAttr(attrs, ["http.request.method"])?.toUpperCase();
  const statusCode = getAttr(attrs, ["http.response.status_code"]);
  const target = getHttpTarget(attrs, {
    includeServerTarget: Boolean(method || statusCode),
  });
  const errorType = getErrorType(attrs);
 
  if (!(method || target || statusCode)) {
    return null;
  }
 
  const label = formatHttpLabel({ method, target, fallbackLabel });
 
  return {
    label: label || fallbackLabel,
    metadata: compactStrings([statusCode, errorType]),
  };
}
 
function formatDatabaseSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const dbSystem = getAttr(attrs, ["db.system.name"]);
  const querySummary = getAttr(attrs, ["db.query.summary"]);
  const operationName = getAttr(attrs, ["db.operation.name"]);
  const target =
    getAttr(attrs, ["db.collection.name", "db.namespace"]) ??
    getServerTarget(attrs);
  const storedProcedure = getAttr(attrs, ["db.stored_procedure.name"]);
  const queryText = getAttr(
    attrs,
    ["db.query.text"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
 
  if (
    !(
      dbSystem ||
      querySummary ||
      operationName ||
      target ||
      storedProcedure ||
      queryText
    )
  ) {
    return null;
  }
 
  const label =
    querySummary ??
    (storedProcedure ? `CALL ${storedProcedure}` : undefined) ??
    (joinParts([operationName, target]) || undefined) ??
    formatDbQueryText(queryText) ??
    fallbackLabel;
  const statusCode = getAttr(attrs, ["db.response.status_code"]);
  const errorType = getErrorType(attrs);
 
  return {
    label,
    metadata: compactStrings([dbSystem, statusCode, errorType]),
  };
}
 
function formatGraphqlSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const operationType = getAttr(attrs, ["graphql.operation.type"]);
  const operationName = getAttr(attrs, ["graphql.operation.name"]);
  const document = getAttr(
    attrs,
    ["graphql.document"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
 
  if (!(operationType || operationName || document)) {
    return null;
  }
 
  return {
    label:
      joinParts([operationType, operationName]) ||
      truncate(document, SPAN_LABEL_MAX_LENGTH) ||
      fallbackLabel,
    metadata: [],
  };
}
 
function formatRpcSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const rpcSystem = getAttr(attrs, ["rpc.system.name"]);
  const service = getAttr(attrs, ["rpc.service"]);
  const method = getAttr(attrs, ["rpc.method"]);
  const statusCode = getAttr(attrs, ["rpc.response.status_code"]);
  const region = getAttr(attrs, ["cloud.region"]);
  const errorType = getErrorType(attrs);
 
  if (!(rpcSystem || service || method || statusCode)) {
    return null;
  }
 
  const methodLabel =
    service && method ? `${service}/${method}` : method || service;
 
  return {
    label: methodLabel || fallbackLabel,
    metadata: compactStrings([rpcSystem, statusCode, region, errorType]),
  };
}
 
function formatMessagingSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const messagingSystem = getAttr(attrs, ["messaging.system"]);
  const operation = getAttr(attrs, [
    "messaging.operation.name",
    "messaging.operation.type",
  ]);
  const destination = getAttr(attrs, [
    "messaging.destination.template",
    "messaging.destination.name",
    "messaging.destination.subscription.name",
  ]);
  const consumerGroup = getAttr(attrs, ["messaging.consumer.group.name"]);
  const messageCount = getAttr(attrs, ["messaging.batch.message_count"]);
  const errorType = getErrorType(attrs);
 
  if (!(messagingSystem || operation || destination)) {
    return null;
  }
 
  return {
    label: joinParts([operation, destination]) || fallbackLabel,
    metadata: compactStrings([
      messagingSystem,
      consumerGroup,
      messageCount ? `messages:${messageCount}` : undefined,
      errorType,
    ]),
  };
}
 
function formatFaasSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const trigger = getAttr(attrs, ["faas.trigger"]);
  const name = getAttr(attrs, ["faas.invoked_name", "faas.name"]);
  const provider = getAttr(attrs, ["faas.invoked_provider"]);
  const region = getAttr(attrs, ["faas.invoked_region"]);
  const coldStart = getAttr(attrs, ["faas.coldstart"]);
  const documentOperation = getAttr(attrs, ["faas.document.operation"]);
  const documentTarget = getAttr(attrs, [
    "faas.document.collection",
    "faas.document.name",
  ]);
  const cron = getAttr(attrs, ["faas.cron"]);
  const errorType = getErrorType(attrs);
  const isColdStart = coldStart === "true";
 
  if (
    !(
      trigger ||
      name ||
      provider ||
      region ||
      isColdStart ||
      documentOperation ||
      documentTarget ||
      cron
    )
  ) {
    return null;
  }
 
  return {
    label:
      joinParts([
        trigger,
        name,
        joinParts([documentOperation, documentTarget]) || cron,
      ]) || fallbackLabel,
    metadata: compactStrings([
      provider,
      region,
      isColdStart ? "coldstart" : undefined,
      errorType,
    ]),
  };
}
 
function formatProcessSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const command = getAttr(attrs, [
    "process.executable.name",
    "process.command",
  ]);
  const exitCode = getAttr(attrs, ["process.exit.code"]);
  const errorType = getErrorType(attrs);
 
  if (!(command || exitCode)) {
    return null;
  }
 
  return {
    label: command || fallbackLabel,
    metadata: compactStrings([
      exitCode ? `exit:${exitCode}` : undefined,
      errorType,
    ]),
  };
}
 
function formatObjectStoreSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const bucket = getAttr(attrs, ["aws.s3.bucket"]);
  const key = getAttr(attrs, ["aws.s3.key"], SPAN_ATTRIBUTE_MAX_LENGTH);
  const copySource = getAttr(
    attrs,
    ["aws.s3.copy_source"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
  const operation = getAttr(attrs, ["rpc.method"]);
  const region = getAttr(attrs, ["cloud.region"]);
  const errorType = getErrorType(attrs);
  const target =
    formatObjectStoreTarget(bucket, key) ??
    truncate(copySource, SPAN_LABEL_MAX_LENGTH);
 
  if (!(bucket || key || copySource)) {
    return null;
  }
 
  return {
    label: joinParts([operation, target]) || fallbackLabel,
    metadata: compactStrings([region, errorType]),
  };
}
 
function formatCloudEventsSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const eventType = getAttr(attrs, ["cloudevents.event_type"]);
  const eventSubject = getAttr(attrs, ["cloudevents.event_subject"]);
  const eventSource = getAttr(
    attrs,
    ["cloudevents.event_source"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
  const specVersion = getAttr(attrs, ["cloudevents.event_spec_version"]);
 
  if (!(eventType || eventSubject || eventSource || specVersion)) {
    return null;
  }
 
  return {
    label:
      joinParts([
        eventType,
        eventSubject ?? formatResourceTarget(eventSource),
      ]) || fallbackLabel,
    metadata: specVersion ? [`cloudevents:${specVersion}`] : [],
  };
}
 
function formatCicdSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const action = getAttr(attrs, ["cicd.pipeline.action.name"]);
  const pipeline = getAttr(attrs, ["cicd.pipeline.name"]);
  const pipelineResult = getAttr(attrs, ["cicd.pipeline.result"]);
  const taskName = getAttr(attrs, ["cicd.pipeline.task.name"]);
  const taskResult = getAttr(attrs, ["cicd.pipeline.task.run.result"]);
  const errorType = getErrorType(attrs);
 
  if (!(action || pipeline || pipelineResult || taskName || taskResult)) {
    return null;
  }
 
  return {
    label: joinParts([action, pipeline]) || taskName || fallbackLabel,
    metadata: compactStrings([pipelineResult, taskResult, errorType]),
  };
}
 
function formatFeatureFlagSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const flagKey = getAttr(attrs, ["feature_flag.key"]);
  const variant = getAttr(attrs, ["feature_flag.result.variant"]);
  const value = getAttr(attrs, ["feature_flag.result.value"]);
  const provider = getAttr(attrs, ["feature_flag.provider.name"]);
  const reason = getAttr(attrs, ["feature_flag.result.reason"]);
  const errorType = getErrorType(attrs);
 
  if (!(flagKey || variant || value || provider || reason)) {
    return null;
  }
 
  return {
    label: joinParts([flagKey, variant ?? value]) || fallbackLabel,
    metadata: compactStrings([provider, reason, errorType]),
  };
}
 
function formatExceptionSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const exceptionType = getAttr(attrs, ["exception.type"]);
  const exceptionMessage = getAttr(
    attrs,
    ["exception.message"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
 
  if (!(exceptionType || exceptionMessage)) {
    return null;
  }
 
  const label =
    fallbackLabel === "unnamed"
      ? exceptionType || exceptionMessage || fallbackLabel
      : fallbackLabel;
  const metadata =
    fallbackLabel === "unnamed"
      ? []
      : compactStrings([
          exceptionType,
          exceptionType ? undefined : exceptionMessage,
        ]);
 
  return { label, metadata };
}
 
function formatErrorSpanDisplay(
  attrs: AttributeSource,
  fallbackLabel: string
): SemanticSpanDisplay | null {
  const errorType = getErrorType(attrs);
  if (!errorType) {
    return null;
  }
  return { label: fallbackLabel, metadata: [errorType] };
}
 
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
 
function getGenAiModelIdentifier(attrs: AttributeSource): string | undefined {
  const provider = getAttr(attrs, ["gen_ai.provider.name"]);
  const model = getAttr(attrs, [
    "gen_ai.response.model",
    "gen_ai.request.model",
  ]);
 
  if (!model) {
    return provider;
  }
  if (!provider || model.includes("/")) {
    return model;
  }
  return `${provider}/${model}`;
}
 
function getHttpTarget(
  attrs: AttributeSource,
  { includeServerTarget = false }: { includeServerTarget?: boolean } = {}
): string | undefined {
  const route = getAttr(
    attrs,
    ["http.route", "url.template"],
    SPAN_ATTRIBUTE_MAX_LENGTH
  );
  const fullUrl = getAttr(attrs, ["url.full"], SPAN_ATTRIBUTE_MAX_LENGTH);
  const path = getAttr(attrs, ["url.path"], SPAN_ATTRIBUTE_MAX_LENGTH);
  const serverTarget = getServerTarget(attrs);
 
  if (route) {
    return formatHttpTarget(route);
  }
  if (fullUrl) {
    return formatHttpTarget(fullUrl);
  }
  Iif (path) {
    return formatHttpTarget(path);
  }
  if (includeServerTarget && serverTarget) {
    return formatHttpTarget(serverTarget);
  }
  return;
}
 
function getServerTarget(attrs: AttributeSource): string | undefined {
  const address = getAttr(attrs, ["server.address"]);
  const port = getAttr(attrs, ["server.port"]);
  if (!address) {
    return;
  }
  if (!port || address.includes(":")) {
    return address;
  }
  return `${address}:${port}`;
}
 
function formatHttpLabel({
  method,
  target,
  fallbackLabel,
}: {
  method?: string;
  target?: string;
  fallbackLabel: string;
}): string {
  Eif (method && target) {
    return joinParts([method, target]);
  }
  if (target) {
    return target;
  }
 
  const normalized = fallbackLabel.toUpperCase();
  if (method && normalized !== method && fallbackLabel !== "unnamed") {
    return normalized.startsWith(`${method} `)
      ? fallbackLabel
      : joinParts([method, fallbackLabel]);
  }
  return method || fallbackLabel;
}
 
function formatHttpTarget(value: string): string {
  const trimmed = value.trim();
  if (!URL_SCHEME_RE.test(trimmed)) {
    const noFragment = trimmed.split("#")[0] ?? trimmed;
    return noFragment.split("?")[0] ?? noFragment;
  }
  try {
    const url = new URL(trimmed);
    const path = url.pathname === "/" ? "" : url.pathname;
    return `${url.host}${path}`;
  } catch (error) {
    log.debug("Failed to parse URL for HTTP target display", error);
    const noFragment = trimmed.split("#")[0] ?? trimmed;
    return noFragment.split("?")[0] ?? noFragment;
  }
}
 
function formatOperationLabel(operation: string, subject?: string): string {
  return subject ? `${operation} ${subject}` : operation;
}
 
function formatObjectStoreTarget(
  bucket?: string,
  key?: string
): string | undefined {
  if (bucket && key) {
    return truncate(`${bucket}/${key}`, SPAN_LABEL_MAX_LENGTH);
  }
  return bucket ?? truncate(key, SPAN_LABEL_MAX_LENGTH);
}
 
function formatResourceTarget(value?: string): string | undefined {
  if (!value) {
    return;
  }
  return truncate(value.split("?")[0], SPAN_LABEL_MAX_LENGTH);
}
 
function formatDbQueryText(value?: string): string | undefined {
  Iif (!value) {
    return;
  }
  return truncate(
    value.replace(/'([^']|'')*'/g, "?").replace(/\b\d+(\.\d+)?\b/g, "?"),
    SPAN_LABEL_MAX_LENGTH
  );
}
 
function joinParts(values: Array<string | undefined>): string {
  return compactStrings(values).join(" ");
}
 
function compactStrings(values: Array<string | undefined>): string[] {
  return values.filter((v): v is string => Boolean(v));
}
 
function getErrorType(attrs: AttributeSource): string | undefined {
  return getAttr(attrs, ["error.type"]);
}
 
function truncate(value: unknown, maxLength: number): string | undefined {
  let text: string | undefined;
  if (typeof value === "string") {
    text = value;
  } else if (typeof value === "number" || typeof value === "boolean") {
    text = String(value);
  } else if (
    Array.isArray(value) &&
    value.length === 1 &&
    typeof value[0] === "string"
  ) {
    // OTel multi-value attributes are arrays; render single-element ones.
    text = value[0];
  }
 
  const normalized = text?.replace(/\s+/g, " ").trim();
  if (!normalized) {
    return;
  }
  if (normalized.length <= maxLength) {
    return normalized;
  }
  return `${normalized.slice(0, maxLength - 3)}...`;
}
 
/** Format a display part, same as truncate but exported for tests. */
export function formatDisplayPart(
  value: unknown,
  maxLength: number
): string | undefined {
  return truncate(value, maxLength);
}
 
/** Deduplicate metadata entries case-insensitively. Values are already truncated by `getAttr`. */
function dedupeMetadata(values: string[]): string[] {
  const result: string[] = [];
  const seen = new Set<string>();
  for (const v of values) {
    Iif (!v) {
      continue;
    }
    const key = v.toLowerCase();
    Iif (seen.has(key)) {
      continue;
    }
    seen.add(key);
    result.push(v);
  }
  return result;
}
 
/**
 * Merge attribute sources from a raw envelope transaction item.
 * Transaction-level attributes live in `contexts.trace.data`.
 */
export function mergeTransactionAttributes(
  event: Record<string, unknown>
): AttributeSource {
  const contexts = event.contexts as Record<string, unknown> | undefined;
  const trace = contexts?.trace as Record<string, unknown> | undefined;
  const data = trace?.data as Record<string, unknown> | undefined;
  return data ?? {};
}