|
| 1 | +import logging |
| 2 | +from collections.abc import Sequence |
| 3 | + |
| 4 | +from sentry.issues.auto_source_code_config.code_mapping import CodeMapping |
| 5 | +from sentry.issues.auto_source_code_config.utils import PlatformConfig |
| 6 | +from sentry.models.project import Project |
| 7 | +from sentry.utils import metrics |
| 8 | + |
| 9 | +from .constants import DERIVED_ENHANCEMENTS_OPTION_KEY, METRIC_PREFIX |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +def save_in_app_stack_trace_rules( |
| 15 | + project: Project, code_mappings: Sequence[CodeMapping], platform_config: PlatformConfig |
| 16 | +) -> list[str]: |
| 17 | + """Save in app stack trace rules for a given project""" |
| 18 | + rules_from_code_mappings = set() |
| 19 | + for code_mapping in code_mappings: |
| 20 | + try: |
| 21 | + rules_from_code_mappings.add(generate_rule_for_code_mapping(code_mapping)) |
| 22 | + except ValueError: |
| 23 | + pass |
| 24 | + |
| 25 | + current_enhancements = project.get_option(DERIVED_ENHANCEMENTS_OPTION_KEY) |
| 26 | + current_rules = set(current_enhancements.split("\n")) if current_enhancements else set() |
| 27 | + |
| 28 | + united_rules = rules_from_code_mappings.union(current_rules) |
| 29 | + if not platform_config.is_dry_run_platform() and united_rules != current_rules: |
| 30 | + project.update_option(DERIVED_ENHANCEMENTS_OPTION_KEY, "\n".join(sorted(united_rules))) |
| 31 | + |
| 32 | + new_rules_added = united_rules - current_rules |
| 33 | + metrics.incr( |
| 34 | + key=f"{METRIC_PREFIX}.in_app_stack_trace_rules.created", |
| 35 | + amount=len(new_rules_added), |
| 36 | + tags={ |
| 37 | + "platform": platform_config.platform, |
| 38 | + "dry_run": platform_config.is_dry_run_platform(), |
| 39 | + }, |
| 40 | + sample_rate=1.0, |
| 41 | + ) |
| 42 | + return list(new_rules_added) |
| 43 | + |
| 44 | + |
| 45 | +# XXX: This is very Java specific. If we want to support other languages, we need to |
| 46 | +# come up with a better way to generate the rule. |
| 47 | +def generate_rule_for_code_mapping(code_mapping: CodeMapping) -> str: |
| 48 | + """Generate an in-app rule for a given code mapping""" |
| 49 | + stacktrace_root = code_mapping.stacktrace_root |
| 50 | + if stacktrace_root == "": |
| 51 | + raise ValueError("Stacktrace root is empty") |
| 52 | + |
| 53 | + parts = stacktrace_root.rstrip("/").split("/", 2) |
| 54 | + # We only want the first two parts |
| 55 | + module = ".".join(parts[:2]) |
| 56 | + |
| 57 | + if module == "": |
| 58 | + raise ValueError("Module is empty") |
| 59 | + |
| 60 | + # a/ -> a.** |
| 61 | + # x/y/ -> x.y.** |
| 62 | + # com/example/foo/bar/ -> com.example.** |
| 63 | + # uk/co/example/foo/bar/ -> uk.co.** |
| 64 | + return f"stack.module:{module}.** +app" |
0 commit comments