hash
stringlengths
40
40
date
stringdate
2017-08-30 22:37:25
2025-03-22 03:08:47
author
stringclasses
173 values
commit_message
stringlengths
15
151
is_merge
bool
1 class
masked_commit_message
stringlengths
6
126
type
stringclasses
17 values
git_diff
stringlengths
182
1.51M
1808c18daf07f5cce8b6d460e59617da1e9944b1
2022-04-26 05:01:31
Scott Cooper
fix(alerts): Encode combined-rule string cursor (#33856)
false
Encode combined-rule string cursor (#33856)
fix
diff --git a/src/sentry/api/paginator.py b/src/sentry/api/paginator.py index ee08f09f0e0398..b41f4b3b7143b0 100644 --- a/src/sentry/api/paginator.py +++ b/src/sentry/api/paginator.py @@ -2,6 +2,7 @@ import functools import math from datetime import datetime +from urllib.parse import quote, unquote from django.core.exceptions import ObjectDoesNotExist from django.db import connections @@ -579,12 +580,15 @@ def key_from_item(self, item): return self.model_key_map.get(type(item))[0] def _prep_value(self, item, key, for_prev): + """ + Formats values for use in the cursor + """ value = getattr(item, key) value_type = type(value) if isinstance(value, float): return math.floor(value) if self._is_asc(for_prev) else math.ceil(value) elif value_type is str and self.case_insensitive: - return value.lower() + return quote(value.lower()) return value def get_item_key(self, item, for_prev=False): @@ -604,6 +608,8 @@ def value_from_cursor(self, cursor): value = cursor.value if isinstance(value, float): return math.floor(value) if self._is_asc(cursor.is_prev) else math.ceil(value) + if isinstance(value, str): + return unquote(value) return value def _is_asc(self, is_prev): diff --git a/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py b/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py index 682f0eb424b6ec..a063266a0b8971 100644 --- a/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py +++ b/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py @@ -480,6 +480,62 @@ def test_limit_as_1_with_paging_sort_name(self): assert result[0]["id"] == str(self.issue_rule.id) assert result[0]["type"] == "rule" + def test_limit_as_1_with_paging_sort_name_urlencode(self): + self.org = self.create_organization(owner=self.user, name="Rowdy Tiger") + self.team = self.create_team( + organization=self.org, name="Mariachi Band", members=[self.user] + ) + self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal") + self.login_as(self.user) + alert_rule = self.create_alert_rule( + name="!1?", + organization=self.org, + projects=[self.project], + date_added=before_now(minutes=6).replace(tzinfo=pytz.UTC), + owner=self.team.actor.get_actor_tuple(), + ) + alert_rule1 = self.create_alert_rule( + name="!1?zz", + organization=self.org, + projects=[self.project], + date_added=before_now(minutes=6).replace(tzinfo=pytz.UTC), + owner=self.team.actor.get_actor_tuple(), + ) + + # Test Limit as 1, no cursor: + url = f"/api/0/organizations/{self.org.slug}/combined-rules/" + with self.feature(["organizations:incidents", "organizations:performance-view"]): + request_data = {"per_page": "1", "project": self.project.id, "sort": "name", "asc": 1} + response = self.client.get( + path=url, + data=request_data, + content_type="application/json", + ) + assert response.status_code == 200, response.content + result = json.loads(response.content) + assert len(result) == 1 + self.assert_alert_rule_serialized(alert_rule, result[0], skip_dates=True) + links = requests.utils.parse_header_links( + response.get("link").rstrip(">").replace(">,<", ",<") + ) + next_cursor = links[1]["cursor"] + # Cursor should have the title encoded + assert next_cursor == "%211%3Fzz:0:0" + + with self.feature(["organizations:incidents", "organizations:performance-view"]): + request_data = { + "cursor": next_cursor, + "per_page": "1", + "project": self.project.id, + "sort": "name", + "asc": 1, + } + response = self.client.get(path=url, data=request_data, content_type="application/json") + assert response.status_code == 200 + result = json.loads(response.content) + assert len(result) == 1 + assert result[0]["id"] == str(alert_rule1.id) + def test_limit_as_1_with_paging(self): self.setup_project_and_rules()
41f334e1331c948bdef5e9a01b0b992a08692775
2023-10-04 04:00:05
Pierre Massat
feat(spans): Handle span schema v1 from Relay (#57284)
false
Handle span schema v1 from Relay (#57284)
feat
diff --git a/src/sentry/spans/consumers/process/factory.py b/src/sentry/spans/consumers/process/factory.py index 91f5027001b13d..a50247f63cf1b3 100644 --- a/src/sentry/spans/consumers/process/factory.py +++ b/src/sentry/spans/consumers/process/factory.py @@ -33,11 +33,9 @@ "span.status": "status", "span.status_code": "status_code", "span.system": "system", - "transaction": "transaction", - "transaction.method": "transaction.method", - "transaction.op": "transaction.op", } -SPAN_SCHEMA_VERSION = 1 +SPAN_SCHEMA_V1 = 1 +SPAN_SCHEMA_VERSION = SPAN_SCHEMA_V1 DEFAULT_SPAN_RETENTION_DAYS = 90 @@ -54,20 +52,13 @@ def get_organization(project_id: int) -> Tuple[Organization, int]: return organization.id, retention_days -def _build_snuba_span(relay_span: Mapping[str, Any]) -> MutableMapping[str, Any]: - organization_id, retention_days = get_organization( - relay_span["project_id"], - ) - span_data: Mapping[str, Any] = relay_span.get("data", {}) - +def _process_relay_span_v0(relay_span: Mapping[str, Any]) -> MutableMapping[str, Any]: snuba_span: MutableMapping[str, Any] = {} snuba_span["event_id"] = relay_span["event_id"] snuba_span["exclusive_time_ms"] = int(relay_span.get("exclusive_time", 0)) snuba_span["is_segment"] = relay_span.get("is_segment", False) - snuba_span["organization_id"] = organization_id snuba_span["parent_span_id"] = relay_span.get("parent_span_id", "0") snuba_span["project_id"] = relay_span["project_id"] - snuba_span["retention_days"] = retention_days snuba_span["segment_id"] = relay_span.get("segment_id", "0") snuba_span["span_id"] = relay_span.get("span_id", "0") snuba_span["tags"] = { @@ -87,11 +78,12 @@ def _build_snuba_span(relay_span: Mapping[str, Any]) -> MutableMapping[str, Any] 0, ) - sentry_tags: MutableMapping[str, Any] = {} - - if span_data: + sentry_tags: dict[str, Any] = relay_span.get("sentry_tags", {}) or {} + if sentry_tags: for relay_tag, snuba_tag in TAG_MAPPING.items(): - tag_value = span_data.get(relay_tag) + if relay_tag not in sentry_tags: + continue + tag_value = sentry_tags.pop(relay_tag) if snuba_tag == "group": if tag_value is None: metrics.incr("spans.missing_group") @@ -100,9 +92,17 @@ def _build_snuba_span(relay_span: Mapping[str, Any]) -> MutableMapping[str, Any] # Test if the value is valid hexadecimal. _ = int(tag_value, 16) # If valid, set the raw value to the tag. - sentry_tags["group"] = tag_value + sentry_tags[snuba_tag] = tag_value except ValueError: metrics.incr("spans.invalid_group") + elif snuba_tag == "status_code": + try: + # Test if the value is a valid integer. + _ = int(tag_value) + # If valid, set the raw value to the tag. + sentry_tags[snuba_tag] = tag_value + except ValueError: + metrics.incr("spans.invalid_status_code") elif tag_value is not None: sentry_tags[snuba_tag] = tag_value @@ -112,17 +112,20 @@ def _build_snuba_span(relay_span: Mapping[str, Any]) -> MutableMapping[str, Any] if "status" not in sentry_tags and (status := relay_span.get("status", "")) is not None: sentry_tags["status"] = status - if "status_code" in sentry_tags: - sentry_tags["status_code"] = sentry_tags["status_code"] + snuba_span["sentry_tags"] = sentry_tags - snuba_span["sentry_tags"] = {k: str(v) for k, v in sentry_tags.items()} + _process_group_raw(snuba_span, sentry_tags.get("transaction", "")) + + return snuba_span + +def _process_group_raw(snuba_span: MutableMapping[str, Any], transaction: str) -> None: grouping_config = load_span_grouping_config() snuba_span["span_grouping_config"] = {"id": grouping_config.id} if snuba_span["is_segment"]: group_raw = grouping_config.strategy.get_transaction_span_group( - {"transaction": span_data.get("transaction", "")}, + {"transaction": transaction}, ) else: # Build a span with only necessary values filled. @@ -148,8 +151,6 @@ def _build_snuba_span(relay_span: Mapping[str, Any]) -> MutableMapping[str, Any] snuba_span["group_raw"] = "0" metrics.incr("spans.invalid_group_raw") - return snuba_span - def _format_event_id(payload: Mapping[str, Any]) -> str: event_id = payload.get("event_id") @@ -158,12 +159,36 @@ def _format_event_id(payload: Mapping[str, Any]) -> str: return "" +def _deserialize_payload(payload: bytes) -> Mapping[str, Any]: + # We're migrating the payload from being encoded in msgpack to JSON. + # This for backward compatibility while we transition. + try: + return msgpack.unpackb(payload) + except msgpack.FormatError: + return json.loads(payload, use_rapid_json=True) + + def _process_message(message: Message[KafkaPayload]) -> KafkaPayload: - payload = msgpack.unpackb(message.payload.value) + payload = _deserialize_payload(message.payload.value) relay_span = payload["span"] relay_span["project_id"] = payload["project_id"] relay_span["event_id"] = _format_event_id(payload) - snuba_span = _build_snuba_span(relay_span) + + organization_id = payload.get("organization_id") + retention_days = payload.get("retention_days") + + if not organization_id or not retention_days: + organization_id, retention_days = get_organization( + relay_span["project_id"], + ) + + if "sentry_tags" not in relay_span and "data" in relay_span: + relay_span["sentry_tags"] = relay_span.pop("data") + + relay_span["organization_id"] = organization_id + relay_span["retention_days"] = retention_days + + snuba_span = _process_relay_span_v0(relay_span) snuba_payload = json.dumps(snuba_span).encode("utf-8") return KafkaPayload(key=None, value=snuba_payload, headers=[]) diff --git a/tests/sentry/spans/test_spans_process_consumer.py b/tests/sentry/spans/test_spans_process_consumer.py index 02ee6045c19bbb..8082a92575961b 100644 --- a/tests/sentry/spans/test_spans_process_consumer.py +++ b/tests/sentry/spans/test_spans_process_consumer.py @@ -7,7 +7,10 @@ from arroyo.types import BrokerValue, Message, Partition, Topic from sentry.receivers import create_default_projects -from sentry.spans.consumers.process.factory import ProcessSpansStrategyFactory, _build_snuba_span +from sentry.spans.consumers.process.factory import ( + ProcessSpansStrategyFactory, + _process_relay_span_v0, +) from sentry.testutils.pytest.fixtures import django_db_all @@ -76,7 +79,7 @@ def test_ingest_span(request): def test_null_tags_and_data(): relay_span: Dict[str, Any] = { - "data": None, + "sentry_tags": None, "description": "f1323e9063f91b5745a7d33e580f9f92.jpg (56 KB)", "event_id": "3f0bba60b0a7471abe18732abe6506c2", "exclusive_time": 8.635998, @@ -94,7 +97,7 @@ def test_null_tags_and_data(): "trace_id": "3f0bba60b0a7471abe18732abe6506c2", "type": "trace", } - snuba_span = _build_snuba_span(relay_span) + snuba_span = _process_relay_span_v0(relay_span) assert "tags" in snuba_span and len(snuba_span["tags"]) == 0 @@ -102,26 +105,26 @@ def test_null_tags_and_data(): "none_tag": None, "false_value": False, } - snuba_span = _build_snuba_span(relay_span) + snuba_span = _process_relay_span_v0(relay_span) assert all([v is not None for v in snuba_span["tags"].values()]) assert "false_value" in snuba_span["tags"] assert "sentry_tags" in snuba_span and len(snuba_span["sentry_tags"]) == 2 - relay_span["data"] = { + relay_span["sentry_tags"] = { "span.description": "", "span.system": None, } - snuba_span = _build_snuba_span(relay_span) + snuba_span = _process_relay_span_v0(relay_span) assert all([v is not None for v in snuba_span["sentry_tags"].values()]) assert "description" in snuba_span["sentry_tags"] - relay_span["data"] = { - "status_code": "undefined", - "group": "[Filtered]", + relay_span["sentry_tags"] = { + "span.status_code": "undefined", + "span.group": "[Filtered]", } - snuba_span = _build_snuba_span(relay_span) + snuba_span = _process_relay_span_v0(relay_span) - assert snuba_span["sentry_tags"].get("group") is None - assert snuba_span["sentry_tags"].get("status_code") is None + assert "group" not in snuba_span["sentry_tags"] + assert "status_code" not in snuba_span["sentry_tags"]
58f0949a678b5792a59649e725e3abecba2563fd
2022-10-26 23:36:17
NisanthanNanthakumar
feat(commit-context): Retry task with exponential backoff (#40559)
false
Retry task with exponential backoff (#40559)
feat
diff --git a/src/sentry/tasks/commit_context.py b/src/sentry/tasks/commit_context.py index 298dfb8f5449e9..1afcaa64fb46d7 100644 --- a/src/sentry/tasks/commit_context.py +++ b/src/sentry/tasks/commit_context.py @@ -9,6 +9,7 @@ from sentry.locks import locks from sentry.models import Commit, CommitAuthor, Project, RepositoryProjectPathConfig from sentry.models.groupowner import GroupOwner, GroupOwnerType +from sentry.shared_integrations.exceptions import ApiError from sentry.tasks.base import instrumented_task from sentry.utils import metrics from sentry.utils.event_frames import munged_filename_and_frames @@ -24,8 +25,11 @@ @instrumented_task( name="sentry.tasks.process_commit_context", queue="group_owners.process_commit_context", - default_retry_delay=5, + autoretry_for=(ApiError,), max_retries=5, + retry_backoff=True, + retry_backoff_max=60 * 60 * 3, # 3 hours + retry_jitter=False, ) def process_commit_context( event_id, event_platform, event_frames, group_id, project_id, sdk_name=None, **kwargs
e60aa964d31f80674fd876afbd4f0f5e0bbe38e7
2021-07-14 10:35:17
Evan Purkhiser
fix(cache): Add query string (#27396)
false
Add query string (#27396)
fix
diff --git a/src/sentry/templates/sentry/layout.html b/src/sentry/templates/sentry/layout.html index 8c965ec652d7dd..aa53fa27a828df 100644 --- a/src/sentry/templates/sentry/layout.html +++ b/src/sentry/templates/sentry/layout.html @@ -54,7 +54,7 @@ {% block scripts %} {% block scripts_main_entrypoint %} - {% unversioned_asset_url "sentry" "entrypoints/app.js" as asset_url %} + {% unversioned_asset_url "sentry" "entrypoints/app.js?invalidCache=1" as asset_url %} {% script src=asset_url data-entry="true" %}{% endscript %} {% endblock %}
89401668cf68f8275ac36d18c35633e55d2495dc
2024-08-06 04:54:14
Cathy Teng
chore(azure): remove base_url param from get_client (#75543)
false
remove base_url param from get_client (#75543)
chore
diff --git a/src/sentry/integrations/vsts/integration.py b/src/sentry/integrations/vsts/integration.py index 61bb98e9d9356b..44dd5f010aaa38 100644 --- a/src/sentry/integrations/vsts/integration.py +++ b/src/sentry/integrations/vsts/integration.py @@ -163,9 +163,8 @@ def has_repo_access(self, repo: RpcRepository) -> bool: return False return True - def get_client(self, base_url: str | None = None) -> VstsApiClient: - if base_url is None: - base_url = self.instance + def get_client(self) -> VstsApiClient: + base_url = self.instance if SiloMode.get_current_mode() != SiloMode.REGION: if self.default_identity is None: self.default_identity = self.get_default_identity() diff --git a/src/sentry/integrations/vsts/issues.py b/src/sentry/integrations/vsts/issues.py index 1c64ec5ad889a2..52eae3dd1d6055 100644 --- a/src/sentry/integrations/vsts/issues.py +++ b/src/sentry/integrations/vsts/issues.py @@ -32,13 +32,13 @@ def get_persisted_default_config_fields(self) -> Sequence[str]: def create_default_repo_choice(self, default_repo: str) -> tuple[str, str]: # default_repo should be the project_id - project = self.get_client(base_url=self.instance).get_project(default_repo) + project = self.get_client().get_project(default_repo) return (project["id"], project["name"]) def get_project_choices( self, group: Optional["Group"] = None, **kwargs: Any ) -> tuple[str | None, Sequence[tuple[str, str]]]: - client = self.get_client(base_url=self.instance) + client = self.get_client() try: projects = client.get_projects() except (ApiError, ApiUnauthorized, KeyError) as e: @@ -78,7 +78,7 @@ def get_project_choices( def get_work_item_choices( self, project: str, group: Optional["Group"] = None ) -> tuple[str | None, Sequence[tuple[str, str]]]: - client = self.get_client(base_url=self.instance) + client = self.get_client() try: item_categories = client.get_work_item_categories(project)["value"] except (ApiError, ApiUnauthorized, KeyError) as e: @@ -172,7 +172,7 @@ def create_issue(self, data: Mapping[str, str], **kwargs: Any) -> Mapping[str, A if project_id is None: raise ValueError("Azure DevOps expects project") - client = self.get_client(base_url=self.instance) + client = self.get_client() title = data["title"] description = data["description"] @@ -199,7 +199,7 @@ def create_issue(self, data: Mapping[str, str], **kwargs: Any) -> Mapping[str, A } def get_issue(self, issue_id: int, **kwargs: Any) -> Mapping[str, Any]: - client = self.get_client(base_url=self.instance) + client = self.get_client() work_item = client.get_work_item(issue_id) return { "key": str(work_item["id"]), @@ -219,7 +219,7 @@ def sync_assignee_outbound( assign: bool = True, **kwargs: Any, ) -> None: - client = self.get_client(base_url=self.instance) + client = self.get_client() assignee = None if user and assign is True: @@ -264,7 +264,7 @@ def sync_assignee_outbound( def sync_status_outbound( self, external_issue: "ExternalIssue", is_resolved: bool, project_id: int, **kwargs: Any ) -> None: - client = self.get_client(self.instance) + client = self.get_client() work_item = client.get_work_item(external_issue.key) # For some reason, vsts doesn't include the project id # in the work item response. @@ -324,7 +324,7 @@ def get_resolve_sync_action(self, data: Mapping[str, Any]) -> ResolveSyncAction: ) def _get_done_statuses(self, project: str) -> set[str]: - client = self.get_client(base_url=self.instance) + client = self.get_client() try: all_states = client.get_work_item_states(project)["value"] except ApiError as err: @@ -341,9 +341,7 @@ def get_issue_display_name(self, external_issue: "ExternalIssue") -> str: def create_comment(self, issue_id: int, user_id: int, group_note: Activity) -> Response: comment = group_note.data["text"] quoted_comment = self.create_comment_attribution(user_id, comment) - return self.get_client(base_url=self.instance).update_work_item( - issue_id, comment=quoted_comment - ) + return self.get_client().update_work_item(issue_id, comment=quoted_comment) def create_comment_attribution(self, user_id: int, comment_text: str) -> str: # VSTS uses markdown or xml diff --git a/src/sentry/integrations/vsts/repository.py b/src/sentry/integrations/vsts/repository.py index ba30693bb7edcf..2af5fedd57054d 100644 --- a/src/sentry/integrations/vsts/repository.py +++ b/src/sentry/integrations/vsts/repository.py @@ -23,8 +23,7 @@ def get_repository_data( self, organization: Organization, config: MutableMapping[str, Any] ) -> Mapping[str, str]: installation = self.get_installation(config.get("installation"), organization.id) - instance = installation.instance - client = installation.get_client(base_url=instance) + client = installation.get_client() repo_id = config["identifier"] @@ -34,7 +33,7 @@ def get_repository_data( raise installation.raise_error(e) config.update( { - "instance": instance, + "instance": installation.instance, "project": repo["project"]["name"], "name": repo["name"], "external_id": str(repo["id"]), @@ -76,18 +75,7 @@ def zip_commit_data( self, repo: Repository, commit_list: Sequence[Commit], organization_id: int ) -> Sequence[Commit]: installation = self.get_installation(repo.integration_id, organization_id) - instance = repo.config["instance"] - if installation.instance != instance: - logger.info( - "integrations.vsts.mismatched_instance", - extra={ - "repo_instance": instance, - "installation_instance": installation.instance, - "org_integration_id": repo.integration_id, - "repo_id": repo.id, - }, - ) - client = installation.get_client(base_url=instance) + client = installation.get_client() n = 0 for commit in commit_list: # Azure will truncate commit comments to only the first line. @@ -113,18 +101,7 @@ def compare_commits( ) -> Sequence[Mapping[str, str]]: """TODO(mgaeta): This function is kinda a mess.""" installation = self.get_installation(repo.integration_id, repo.organization_id) - instance = repo.config["instance"] - if installation.instance != instance: - logger.info( - "integrations.vsts.mismatched_instance", - extra={ - "repo_instance": instance, - "installation_instance": installation.instance, - "org_integration_id": repo.integration_id, - "repo_id": repo.id, - }, - ) - client = installation.get_client(base_url=instance) + client = installation.get_client() try: if start_sha is None: diff --git a/src/sentry/integrations/vsts/tasks/subscription_check.py b/src/sentry/integrations/vsts/tasks/subscription_check.py index 20d6e5d1f9b4b4..6bcbe8f415d86e 100644 --- a/src/sentry/integrations/vsts/tasks/subscription_check.py +++ b/src/sentry/integrations/vsts/tasks/subscription_check.py @@ -25,7 +25,7 @@ def vsts_subscription_check(integration_id: int, organization_id: int) -> None: installation = integration.get_installation(organization_id=organization_id) assert isinstance(installation, VstsIntegration), installation try: - client = installation.get_client(base_url=installation.instance) + client = installation.get_client() except ObjectDoesNotExist: return diff --git a/tests/sentry/integrations/vsts/test_client.py b/tests/sentry/integrations/vsts/test_client.py index 4e4ca5fe0005c2..765c190ee962ba 100644 --- a/tests/sentry/integrations/vsts/test_client.py +++ b/tests/sentry/integrations/vsts/test_client.py @@ -47,7 +47,7 @@ def test_refreshes_expired_token(self): self._stub_vsts() # Make a request with expired token - installation.get_client(base_url=self.vsts_base_url).get_projects() + installation.get_client().get_projects() # Second to last request, before the Projects request, was to refresh # the Access Token. @@ -91,7 +91,7 @@ def test_does_not_refresh_valid_tokens(self): self._stub_vsts() # Make a request - installation.get_client(base_url=self.vsts_base_url).get_projects() + installation.get_client().get_projects() assert len(responses.calls) == 1 assert ( responses.calls[0].request.url @@ -122,7 +122,7 @@ def request_callback(request): callback=request_callback, ) - projects = installation.get_client(base_url=self.vsts_base_url).get_projects() + projects = installation.get_client().get_projects() assert len(projects) == 220 @responses.activate @@ -150,7 +150,7 @@ def test_simple(self): external_id="albertos-apples", ) - client = installation.get_client(base_url=self.vsts_base_url) + client = installation.get_client() responses.calls.reset() assert repo.external_id is not None @@ -206,7 +206,7 @@ def test_check_file(self): external_id="albertos-apples", ) - client = installation.get_client(base_url=self.vsts_base_url) + client = installation.get_client() path = "src/sentry/integrations/vsts/client.py" version = "master" @@ -239,7 +239,7 @@ def test_check_no_file(self): external_id="albertos-apples", ) - client = installation.get_client(base_url=self.vsts_base_url) + client = installation.get_client() path = "src/sentry/integrations/vsts/client.py" version = "master"
a918666674adcd4eedc6c8869564cf7de8b03f1c
2023-12-15 00:37:31
Lyn Nagara
perf: Arroyo 2.15.2 and reusable multiprocessing pools (#61221)
false
Arroyo 2.15.2 and reusable multiprocessing pools (#61221)
perf
diff --git a/requirements-base.txt b/requirements-base.txt index 5d2bc21dff1bdf..2e3918024561db 100644 --- a/requirements-base.txt +++ b/requirements-base.txt @@ -62,8 +62,7 @@ requests>=2.25.1 rfc3339-validator>=0.1.2 rfc3986-validator>=0.1.1 # [end] jsonschema format validators -sentry-arroyo>=2.14.25 -sentry-kafka-schemas>=0.1.38 +sentry-arroyo>=2.15.2 sentry-kafka-schemas>=0.1.38 sentry-redis-tools>=0.1.7 sentry-relay>=0.8.39 diff --git a/requirements-dev-frozen.txt b/requirements-dev-frozen.txt index 347f7b541db3cc..72f8df000d3cc1 100644 --- a/requirements-dev-frozen.txt +++ b/requirements-dev-frozen.txt @@ -171,7 +171,7 @@ rfc3986-validator==0.1.1 rsa==4.8 s3transfer==0.6.1 selenium==4.16.0 -sentry-arroyo==2.14.25 +sentry-arroyo==2.15.2 sentry-cli==2.16.0 sentry-forked-django-stubs==4.2.7.post1 sentry-forked-djangorestframework-stubs==3.14.5.post1 diff --git a/requirements-frozen.txt b/requirements-frozen.txt index 7348a0f3d594d4..791190a3c1d2d1 100644 --- a/requirements-frozen.txt +++ b/requirements-frozen.txt @@ -118,7 +118,7 @@ rfc3339-validator==0.1.2 rfc3986-validator==0.1.1 rsa==4.8 s3transfer==0.6.1 -sentry-arroyo==2.14.25 +sentry-arroyo==2.15.2 sentry-kafka-schemas==0.1.38 sentry-redis-tools==0.1.7 sentry-relay==0.8.39 diff --git a/src/sentry/eventstream/kafka/dispatch.py b/src/sentry/eventstream/kafka/dispatch.py index 6cf3fb84427df3..145c15b08552fd 100644 --- a/src/sentry/eventstream/kafka/dispatch.py +++ b/src/sentry/eventstream/kafka/dispatch.py @@ -91,5 +91,6 @@ def _get_task_kwargs_and_dispatch(message: Message[KafkaPayload]) -> None: class EventPostProcessForwarderStrategyFactory(PostProcessForwarderStrategyFactory): - def _dispatch_function(self, message: Message[KafkaPayload]) -> None: + @staticmethod + def _dispatch_function(message: Message[KafkaPayload]) -> None: return _get_task_kwargs_and_dispatch(message) diff --git a/src/sentry/ingest/consumer/factory.py b/src/sentry/ingest/consumer/factory.py index 64a98d5931c750..1f97ee31da9d46 100644 --- a/src/sentry/ingest/consumer/factory.py +++ b/src/sentry/ingest/consumer/factory.py @@ -20,7 +20,7 @@ from sentry.ingest.types import ConsumerType from sentry.processing.backpressure.arroyo import HealthChecker, create_backpressure_step from sentry.utils import kafka_config -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing from .attachment_event import decode_and_process_chunks, process_attachments_and_events from .simple_event import process_simple_event_message @@ -42,14 +42,16 @@ def maybe_multiprocess_step( mp: MultiProcessConfig | None, function: Callable[[Message[TInput]], TOutput], next_step: ProcessingStrategy[FilteredPayload | TOutput], + pool: Optional[MultiprocessingPool], ) -> ProcessingStrategy[FilteredPayload | TInput]: if mp is not None: + assert pool is not None return RunTaskWithMultiprocessing( function=function, next_step=next_step, - num_processes=mp.num_processes, max_batch_size=mp.max_batch_size, max_batch_time=mp.max_batch_time, + pool=pool, input_block_size=mp.input_block_size, output_block_size=mp.output_block_size, ) @@ -74,6 +76,12 @@ def __init__( self.is_attachment_topic = consumer_type == ConsumerType.Attachments self.multi_process = None + self._pool = MultiprocessingPool(num_processes) + + # XXX: Attachment topic has two multiprocessing strategies chained together so we use + # two pools. + if self.is_attachment_topic: + self._attachments_pool = MultiprocessingPool(num_processes) if num_processes > 1: self.multi_process = MultiProcessConfig( num_processes, max_batch_size, max_batch_time, input_block_size, output_block_size @@ -91,7 +99,9 @@ def create_with_partitions( final_step = CommitOffsets(commit) if not self.is_attachment_topic: - next_step = maybe_multiprocess_step(mp, process_simple_event_message, final_step) + next_step = maybe_multiprocess_step( + mp, process_simple_event_message, final_step, self._pool + ) return create_backpressure_step(health_checker=self.health_checker, next_step=next_step) # The `attachments` topic is a bit different, as it allows multiple event types: @@ -104,7 +114,9 @@ def create_with_partitions( # are being handled in a step before the event depending on them is processed in a # later step. - step_2 = maybe_multiprocess_step(mp, process_attachments_and_events, final_step) + step_2 = maybe_multiprocess_step( + mp, process_attachments_and_events, final_step, self._attachments_pool + ) # This `FilterStep` will skip over processing `None` (aka already handled attachment chunks) # in the second step. We filter this here explicitly, # to avoid arroyo from needlessly dispatching `None` messages. @@ -113,10 +125,16 @@ def create_with_partitions( # As the steps are defined (and types inferred) in reverse order, we would get a type error here, # as `step_1` outputs an `| None`, but the `filter_step` does not mention that in its type, # as it is inferred from the `step_2` input type which does not mention `| None`. - step_1 = maybe_multiprocess_step(mp, decode_and_process_chunks, filter_step) # type:ignore + step_1 = maybe_multiprocess_step( + mp, decode_and_process_chunks, filter_step, self._pool # type:ignore + ) return create_backpressure_step(health_checker=self.health_checker, next_step=step_1) + def shutdown(self) -> None: + self._pool.close() + self._attachments_pool.close() + def get_ingest_consumer( consumer_type: str, diff --git a/src/sentry/issues/run.py b/src/sentry/issues/run.py index 2fae362dad13e9..794e35f4cfd0ae 100644 --- a/src/sentry/issues/run.py +++ b/src/sentry/issues/run.py @@ -13,7 +13,7 @@ ) from arroyo.types import Commit, Message, Partition -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing from sentry.utils.kafka_config import get_topic_definition logger = logging.getLogger(__name__) @@ -95,9 +95,9 @@ def __init__( super().__init__() self.max_batch_size = max_batch_size self.max_batch_time = max_batch_time - self.num_processes = num_processes self.input_block_size = input_block_size self.output_block_size = output_block_size + self.pool = MultiprocessingPool(num_processes) def create_with_partitions( self, @@ -107,13 +107,16 @@ def create_with_partitions( return RunTaskWithMultiprocessing( function=process_message, next_step=CommitOffsets(commit), - num_processes=self.num_processes, max_batch_size=self.max_batch_size, max_batch_time=self.max_batch_time, + pool=self.pool, input_block_size=self.input_block_size, output_block_size=self.output_block_size, ) + def shutdown(self) -> None: + self.pool.close() + def process_message(message: Message[KafkaPayload]) -> None: from sentry.issues.occurrence_consumer import ( diff --git a/src/sentry/post_process_forwarder/post_process_forwarder.py b/src/sentry/post_process_forwarder/post_process_forwarder.py index 908fca933ca4df..39c17d7c292258 100644 --- a/src/sentry/post_process_forwarder/post_process_forwarder.py +++ b/src/sentry/post_process_forwarder/post_process_forwarder.py @@ -11,14 +11,15 @@ ) from arroyo.types import Commit, Message, Partition -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing logger = logging.getLogger(__name__) class PostProcessForwarderStrategyFactory(ProcessingStrategyFactory[KafkaPayload], ABC): + @staticmethod @abstractmethod - def _dispatch_function(self, message: Message[KafkaPayload]) -> None: + def _dispatch_function(message: Message[KafkaPayload]) -> None: raise NotImplementedError() def __init__( @@ -32,13 +33,13 @@ def __init__( concurrency: int, ) -> None: self.mode = mode - self.num_processes = num_processes self.input_block_size = input_block_size self.output_block_size = output_block_size self.max_batch_size = max_batch_size self.max_batch_time = max_batch_time self.concurrency = concurrency self.max_pending_futures = concurrency + 1000 + self.pool = MultiprocessingPool(num_processes) def create_with_partitions( self, @@ -58,11 +59,14 @@ def create_with_partitions( return RunTaskWithMultiprocessing( function=self._dispatch_function, next_step=CommitOffsets(commit), - num_processes=self.num_processes, max_batch_size=self.max_batch_size, max_batch_time=self.max_batch_time, + pool=self.pool, input_block_size=self.input_block_size, output_block_size=self.output_block_size, ) else: raise ValueError(f"Invalid mode {self.mode}") + + def shutdown(self) -> None: + self.pool.close() diff --git a/src/sentry/replays/consumers/recording.py b/src/sentry/replays/consumers/recording.py index 8ba3ee7fdebf85..c92d20b2f5eaca 100644 --- a/src/sentry/replays/consumers/recording.py +++ b/src/sentry/replays/consumers/recording.py @@ -15,7 +15,7 @@ from sentry_sdk.tracing import Span from sentry.replays.usecases.ingest import ingest_recording -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing logger = logging.getLogger(__name__) @@ -60,6 +60,7 @@ def __init__( self.output_block_size = output_block_size self.use_processes = self.num_processes > 1 self.force_synchronous = force_synchronous + self.pool = MultiprocessingPool(num_processes) if self.use_processes else None def create_with_partitions( self, @@ -72,12 +73,13 @@ def create_with_partitions( next_step=CommitOffsets(commit), ) elif self.use_processes: + assert self.pool is not None return RunTaskWithMultiprocessing( function=process_message, next_step=CommitOffsets(commit), - num_processes=self.num_processes, max_batch_size=self.max_batch_size, max_batch_time=self.max_batch_time, + pool=self.pool, input_block_size=self.input_block_size, output_block_size=self.output_block_size, ) @@ -93,6 +95,10 @@ def create_with_partitions( ), ) + def shutdown(self) -> None: + if self.pool: + self.pool.close() + def initialize_threaded_context(message: Message[KafkaPayload]) -> MessageContext: """Initialize a Sentry transaction and unpack the message.""" diff --git a/src/sentry/sentry_metrics/consumers/indexer/parallel.py b/src/sentry/sentry_metrics/consumers/indexer/parallel.py index b025d5d1542a93..5531ebc07f31ed 100644 --- a/src/sentry/sentry_metrics/consumers/indexer/parallel.py +++ b/src/sentry/sentry_metrics/consumers/indexer/parallel.py @@ -25,7 +25,7 @@ RoutingProducerStep, ) from sentry.sentry_metrics.consumers.indexer.slicing_router import SlicingRouter -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing logger = logging.getLogger(__name__) @@ -137,11 +137,20 @@ def __init__( self.__max_parallel_batch_size = max_parallel_batch_size self.__max_parallel_batch_time = max_parallel_batch_time - self.__processes = processes - self.__input_block_size = input_block_size self.__output_block_size = output_block_size self.__slicing_router = slicing_router + self.__pool = MultiprocessingPool( + num_processes=processes, + # It is absolutely crucial that we pass a function reference here + # where the function lives in a module that does not depend on + # Django settings. `sentry.sentry_metrics.configuration` fulfills + # that requirement, but if you were to create a wrapper function in + # this module, and pass that function here, it would attempt to + # pull in a bunch of modules that try to read django settings at + # import time + initializer=functools.partial(initialize_subprocess_state, self.config), + ) def create_with_partitions( self, @@ -153,23 +162,16 @@ def create_with_partitions( commit=commit, slicing_router=self.__slicing_router, ) + parallel_strategy = RunTaskWithMultiprocessing( function=MessageProcessor(self.config).process_messages, next_step=Unbatcher(next_step=producer), - num_processes=self.__processes, + pool=self.__pool, max_batch_size=self.__max_parallel_batch_size, # This is in seconds max_batch_time=self.__max_parallel_batch_time / 1000, input_block_size=self.__input_block_size, output_block_size=self.__output_block_size, - # It is absolutely crucial that we pass a function reference here - # where the function lives in a module that does not depend on - # Django settings. `sentry.sentry_metrics.configuration` fulfills - # that requirement, but if you were to create a wrapper function in - # this module, and pass that function here, it would attempt to - # pull in a bunch of modules that try to read django settings at - # import time - initializer=functools.partial(initialize_subprocess_state, self.config), ) strategy = BatchMessages( @@ -178,6 +180,9 @@ def create_with_partitions( return strategy + def shutdown(self) -> None: + self.__pool.close() + def get_metrics_producer_strategy( config: MetricsIngestConfiguration, diff --git a/src/sentry/snuba/query_subscriptions/run.py b/src/sentry/snuba/query_subscriptions/run.py index b09139186cd083..c943f9c1ff67b8 100644 --- a/src/sentry/snuba/query_subscriptions/run.py +++ b/src/sentry/snuba/query_subscriptions/run.py @@ -20,7 +20,7 @@ from sentry.snuba.dataset import Dataset from sentry.snuba.query_subscriptions.constants import dataset_to_logical_topic, topic_to_dataset -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing logger = logging.getLogger(__name__) @@ -41,10 +41,10 @@ def __init__( self.logical_topic = dataset_to_logical_topic[self.dataset] self.max_batch_size = max_batch_size self.max_batch_time = max_batch_time - self.num_processes = num_processes self.input_block_size = input_block_size self.output_block_size = output_block_size self.multi_proc = multi_proc + self.pool = MultiprocessingPool(num_processes) def create_with_partitions( self, @@ -56,15 +56,18 @@ def create_with_partitions( return RunTaskWithMultiprocessing( function=callable, next_step=CommitOffsets(commit), - num_processes=self.num_processes, max_batch_size=self.max_batch_size, max_batch_time=self.max_batch_time, + pool=self.pool, input_block_size=self.input_block_size, output_block_size=self.output_block_size, ) else: return RunTask(callable, CommitOffsets(commit)) + def shutdown(self) -> None: + self.pool.close() + def process_message( dataset: Dataset, topic: str, logical_topic: str, message: Message[KafkaPayload] @@ -118,7 +121,6 @@ def get_query_subscription_consumer( output_block_size: Optional[int], multi_proc: bool = False, ) -> StreamProcessor[KafkaPayload]: - from sentry.utils import kafka_config cluster_name = kafka_config.get_topic_definition(topic)["cluster"] diff --git a/src/sentry/spans/consumers/process/factory.py b/src/sentry/spans/consumers/process/factory.py index a0f2c923aefc7b..073012d0ef4a2f 100644 --- a/src/sentry/spans/consumers/process/factory.py +++ b/src/sentry/spans/consumers/process/factory.py @@ -19,7 +19,7 @@ from sentry.spans.grouping.api import load_span_grouping_config from sentry.spans.grouping.strategy.base import Span from sentry.utils import metrics -from sentry.utils.arroyo import RunTaskWithMultiprocessing +from sentry.utils.arroyo import MultiprocessingPool, RunTaskWithMultiprocessing from sentry.utils.kafka_config import get_kafka_producer_cluster_options, get_topic_definition INGEST_SPAN_SCHEMA: Codec[IngestSpanMessage] = get_codec("ingest-spans") @@ -163,7 +163,6 @@ def __init__( ): super().__init__() - self.__num_processes = num_processes self.__max_batch_size = max_batch_size self.__max_batch_time = max_batch_time self.__input_block_size = input_block_size @@ -179,6 +178,7 @@ def __init__( ) ) self.__output_topic = Topic(name=output_topic) + self.__pool = MultiprocessingPool(num_processes) def create_with_partitions( self, @@ -192,9 +192,9 @@ def create_with_partitions( max_buffer_size=100000, ) return RunTaskWithMultiprocessing( - num_processes=self.__num_processes, max_batch_size=self.__max_batch_size, max_batch_time=self.__max_batch_time, + pool=self.__pool, input_block_size=self.__input_block_size, output_block_size=self.__output_block_size, function=process_message, @@ -203,3 +203,4 @@ def create_with_partitions( def shutdown(self) -> None: self.__producer.close() + self.__pool.close() diff --git a/src/sentry/utils/arroyo.py b/src/sentry/utils/arroyo.py index 374ee066b2191b..6c038cad45b424 100644 --- a/src/sentry/utils/arroyo.py +++ b/src/sentry/utils/arroyo.py @@ -4,12 +4,16 @@ from functools import partial from typing import Any, Callable, Mapping, Optional, Union +from arroyo.processing.strategies.run_task_with_multiprocessing import ( + MultiprocessingPool as ArroyoMultiprocessingPool, +) from arroyo.processing.strategies.run_task_with_multiprocessing import ( RunTaskWithMultiprocessing as ArroyoRunTaskWithMultiprocessing, ) from arroyo.processing.strategies.run_task_with_multiprocessing import TResult from arroyo.types import TStrategyPayload from arroyo.utils.metrics import Metrics +from django.conf import settings from sentry.metrics.base import MetricsBackend @@ -126,21 +130,44 @@ def initialize_arroyo_main() -> None: configure_metrics(metrics_wrapper) +class MultiprocessingPool: + def __init__( + self, num_processes: int, initializer: Optional[Callable[[], None]] = None + ) -> None: + self.__initializer = initializer + if settings.KAFKA_CONSUMER_FORCE_DISABLE_MULTIPROCESSING: + self.__pool = None + else: + self.__pool = ArroyoMultiprocessingPool( + num_processes, _get_arroyo_subprocess_initializer(initializer) + ) + + @property + def initializer(self) -> Optional[Callable[[], None]]: + return self.__initializer + + @property + def pool(self) -> Optional[ArroyoMultiprocessingPool]: + return self.__pool + + def close(self) -> None: + if self.__pool is not None: + self.__pool.close() + + class RunTaskWithMultiprocessing(ArroyoRunTaskWithMultiprocessing[TStrategyPayload, TResult]): """ - A variant of arroyo's RunTaskWithMultiprocessing that initializes Sentry - for you, and ensures global metric tags in the subprocess are inherited - from the main process. + A variant of arroyo's RunTaskWithMultiprocessing that can switch between + multiprocessing and non-multiprocessing mode based on the + `KAFKA_CONSUMER_FORCE_DISABLE_MULTIPROCESSING` setting. """ def __new__( cls, *, - initializer: Optional[Callable[[], None]] = None, + pool: MultiprocessingPool, **kwargs: Any, ) -> RunTaskWithMultiprocessing: - from django.conf import settings - if settings.KAFKA_CONSUMER_FORCE_DISABLE_MULTIPROCESSING: from arroyo.processing.strategies.run_task import RunTask @@ -150,11 +177,11 @@ def __new__( kwargs.pop("max_batch_size", None) kwargs.pop("max_batch_time", None) - if initializer is not None: - initializer() + if pool.initializer is not None: + pool.initializer() # Assert that initializer can be pickled and loaded again from subprocesses. - pickle.loads(pickle.dumps(initializer)) + pickle.loads(pickle.dumps(pool.initializer)) pickle.loads(pickle.dumps(kwargs["function"])) return RunTask(**kwargs) # type: ignore[return-value] @@ -163,6 +190,8 @@ def __new__( RunTaskWithMultiprocessing as ArroyoRunTaskWithMultiprocessing, ) + assert pool.pool is not None + return ArroyoRunTaskWithMultiprocessing( # type: ignore[return-value] - initializer=_get_arroyo_subprocess_initializer(initializer), **kwargs + pool=pool.pool, **kwargs ) diff --git a/tests/sentry/replays/consumers/test_recording.py b/tests/sentry/replays/consumers/test_recording.py index 7316f8ebb41c16..d00dbfe1950f33 100644 --- a/tests/sentry/replays/consumers/test_recording.py +++ b/tests/sentry/replays/consumers/test_recording.py @@ -42,6 +42,7 @@ def _commit(offsets: Mapping[Partition, int], force: bool = False) -> None: # Clean up after ourselves by terminating the processing pool spawned by the above call. task.terminate() + factory.shutdown() class RecordingTestCaseMixin(TransactionTestCase): diff --git a/tests/sentry/sentry_metrics/test_last_seen_updater.py b/tests/sentry/sentry_metrics/test_last_seen_updater.py index 2997c00b12363b..c485d9e44988b7 100644 --- a/tests/sentry/sentry_metrics/test_last_seen_updater.py +++ b/tests/sentry/sentry_metrics/test_last_seen_updater.py @@ -131,7 +131,8 @@ def test_basic_flow(self): # we can't use fixtures with unittest.TestCase commit = Mock() message = kafka_message(headerless_kafka_payload(mixed_payload())) - processing_strategy = self.processing_factory().create_with_partitions( + factory = self.processing_factory() + processing_strategy = factory.create_with_partitions( commit, {Partition(Topic("fake-topic"), 0): 0} ) processing_strategy.submit(message) @@ -145,12 +146,14 @@ def test_basic_flow(self): # without doing a bunch of mocking around time objects, stale_item.last_seen # should be approximately equal to timezone.now() but they won't be perfectly equal assert (timezone.now() - stale_item.last_seen) < timedelta(seconds=30) + factory.shutdown() def test_message_processes_after_bad_message(self): commit = Mock() ok_message = kafka_message(headerless_kafka_payload(mixed_payload())) bad_message = kafka_message(headerless_kafka_payload(bad_payload())) - processing_strategy = self.processing_factory().create_with_partitions( + factory = self.processing_factory() + processing_strategy = factory.create_with_partitions( commit, {Partition(Topic("fake-topic"), 0): 0} ) processing_strategy.submit(bad_message) @@ -160,6 +163,7 @@ def test_message_processes_after_bad_message(self): stale_item = self.table.objects.get(id=self.stale_id) assert stale_item.last_seen > self.stale_last_seen + factory.shutdown() class TestFilterMethod: diff --git a/tests/sentry/sentry_metrics/test_parallel_indexer.py b/tests/sentry/sentry_metrics/test_parallel_indexer.py index 628249fa510acc..31769b7388dc2b 100644 --- a/tests/sentry/sentry_metrics/test_parallel_indexer.py +++ b/tests/sentry/sentry_metrics/test_parallel_indexer.py @@ -77,3 +77,5 @@ def test_basic(request, settings, force_disable_multiprocessing): strategy.submit(message=message) strategy.close() strategy.join() + # Close the multiprocessing pool + processing_factory.shutdown()
ce63acc7883cc0301a5c216e5231d1ab11e81e60
2022-03-09 05:28:28
Scott Cooper
deps(ui): Remove babel-eslint (#32438)
false
Remove babel-eslint (#32438)
deps
diff --git a/package.json b/package.json index 72806356ef3de8..848d7f64a0c753 100644 --- a/package.json +++ b/package.json @@ -160,7 +160,6 @@ "@storybook/theming": "6.3.13", "@types/node": "^17.0.18", "@visual-snapshot/jest": "5.0.0", - "babel-eslint": "^10.1.0", "babel-gettext-extractor": "^4.1.3", "babel-jest": "27.5.1", "babel-plugin-dynamic-import-node": "^2.2.0", diff --git a/yarn.lock b/yarn.lock index 8b94e7bc2e4fd8..56264ba7ee24e7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -438,7 +438,7 @@ chalk "^2.0.0" js-tokens "^4.0.0" -"@babel/parser@^7.1.0", "@babel/parser@^7.12.11", "@babel/parser@^7.12.7", "@babel/parser@^7.14.7", "@babel/parser@^7.15.5", "@babel/parser@^7.16.7", "@babel/parser@^7.17.3", "@babel/parser@^7.7.0": +"@babel/parser@^7.1.0", "@babel/parser@^7.12.11", "@babel/parser@^7.12.7", "@babel/parser@^7.14.7", "@babel/parser@^7.15.5", "@babel/parser@^7.16.7", "@babel/parser@^7.17.3": version "7.17.3" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.17.3.tgz#b07702b982990bf6fdc1da5049a23fece4c5c3d0" integrity sha512-7yJPvPV+ESz2IUTPbOL+YkIGyCqOyNIzdguKQuJGnH7bg1WTIifuM21YqokFt/THWh1AkCRn9IgoykTRCBVpzA== @@ -1237,7 +1237,7 @@ "@babel/parser" "^7.16.7" "@babel/types" "^7.16.7" -"@babel/traverse@^7.12.11", "@babel/traverse@^7.12.9", "@babel/traverse@^7.13.0", "@babel/traverse@^7.15.4", "@babel/traverse@^7.16.7", "@babel/traverse@^7.17.0", "@babel/traverse@^7.17.3", "@babel/traverse@^7.7.0", "@babel/traverse@^7.7.2": +"@babel/traverse@^7.12.11", "@babel/traverse@^7.12.9", "@babel/traverse@^7.13.0", "@babel/traverse@^7.15.4", "@babel/traverse@^7.16.7", "@babel/traverse@^7.17.0", "@babel/traverse@^7.17.3", "@babel/traverse@^7.7.2": version "7.17.3" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.17.3.tgz#0ae0f15b27d9a92ba1f2263358ea7c4e7db47b57" integrity sha512-5irClVky7TxRWIRtxlh2WPUUOLhcPN06AGgaQSB8AEwuyEBgJVuJ5imdHm5zxk8w0QS5T+tDfnDxAlhWjpb7cw== @@ -1253,7 +1253,7 @@ debug "^4.1.0" globals "^11.1.0" -"@babel/types@^7.0.0", "@babel/types@^7.12.11", "@babel/types@^7.12.7", "@babel/types@^7.14.5", "@babel/types@^7.14.9", "@babel/types@^7.15.4", "@babel/types@^7.15.6", "@babel/types@^7.16.7", "@babel/types@^7.17.0", "@babel/types@^7.3.0", "@babel/types@^7.3.3", "@babel/types@^7.4.4", "@babel/types@^7.7.0": +"@babel/types@^7.0.0", "@babel/types@^7.12.11", "@babel/types@^7.12.7", "@babel/types@^7.14.5", "@babel/types@^7.14.9", "@babel/types@^7.15.4", "@babel/types@^7.15.6", "@babel/types@^7.16.7", "@babel/types@^7.17.0", "@babel/types@^7.3.0", "@babel/types@^7.3.3", "@babel/types@^7.4.4": version "7.17.0" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.17.0.tgz#a826e368bccb6b3d84acd76acad5c0d87342390b" integrity sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw== @@ -5450,18 +5450,6 @@ axe-core@^4.2.0: resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-4.2.3.tgz#2a3afc332f0031b42f602f4a3de03c211ca98f72" integrity sha512-pXnVMfJKSIWU2Ml4JHP7pZEPIrgBO1Fd3WGx+fPBsS+KRGhE4vxooD8XBGWbQOIVSZsVK7pUDBBkCicNu80yzQ== -babel-eslint@^10.1.0: - version "10.1.0" - resolved "https://registry.yarnpkg.com/babel-eslint/-/babel-eslint-10.1.0.tgz#6968e568a910b78fb3779cdd8b6ac2f479943232" - integrity sha512-ifWaTHQ0ce+448CYop8AdrQiBsGrnC+bMgfyKFdi6EsPLTAWG+QfyDeM6OH+FmWnKvEq5NnBMLvlBUPKQZoDSg== - dependencies: - "@babel/code-frame" "^7.0.0" - "@babel/parser" "^7.7.0" - "@babel/traverse" "^7.7.0" - "@babel/types" "^7.7.0" - eslint-visitor-keys "^1.0.0" - resolve "^1.12.0" - babel-gettext-extractor@^4.1.3: version "4.1.3" resolved "https://registry.yarnpkg.com/babel-gettext-extractor/-/babel-gettext-extractor-4.1.3.tgz#7d3343b9c9875cf6d25f1526f9de05598bd61f83"
b3f633423d6c753c99bbf0d8e476c85e138b071e
2023-07-18 00:45:22
Alberto Leal
chore(hybrid-cloud): Add tags to debug Identity service (#52997)
false
Add tags to debug Identity service (#52997)
chore
diff --git a/src/sentry/integrations/base.py b/src/sentry/integrations/base.py index 9fd32c0235a981..c611b49c40a6c9 100644 --- a/src/sentry/integrations/base.py +++ b/src/sentry/integrations/base.py @@ -41,6 +41,7 @@ UnsupportedResponseType, ) from sentry.utils.audit import create_audit_entry +from sentry.utils.sdk import configure_scope if TYPE_CHECKING: from sentry.services.hybrid_cloud.integration import RpcOrganizationIntegration @@ -364,6 +365,10 @@ def get_default_identity(self) -> RpcIdentity: filter={"id": self.org_integration.default_auth_id} ) if identity is None: + with configure_scope() as scope: + scope.set_tag("integration_provider", self.model.get_provider().name) + scope.set_tag("org_integration_id", self.org_integration.id) + scope.set_tag("default_auth_id", self.org_integration.default_auth_id) raise Identity.DoesNotExist return identity
1e506d7b19a6f139af422bd11a7b6d87b03d2194
2024-10-17 04:10:38
Michael Sun
chore(issue-stream): age -> first seen, seen -> last seen (#79139)
false
age -> first seen, seen -> last seen (#79139)
chore
diff --git a/static/app/components/stream/group.tsx b/static/app/components/stream/group.tsx index 52e3631c269587..b443e2fa6575ed 100644 --- a/static/app/components/stream/group.tsx +++ b/static/app/components/stream/group.tsx @@ -139,7 +139,7 @@ function GroupTimestamp({date, label}: {date: string | null; label: string}) { aria-label={label} tooltipPrefix={label} date={date} - suffix="" + suffix="ago" unitStyle="extraShort" /> ); @@ -892,7 +892,7 @@ const ChartWrapper = styled('div')<{margin: boolean; narrowGroups: boolean}>` `; const NarrowChartWrapper = styled('div')<{breakpoint: string}>` - width: 200px; + width: 175px; align-self: center; margin-right: ${space(2)}; @@ -904,7 +904,7 @@ const NarrowChartWrapper = styled('div')<{breakpoint: string}>` const TimestampWrapper = styled('div')<{breakpoint: string}>` display: flex; align-self: center; - width: 60px; + width: 75px; margin-right: ${space(2)}; @media (max-width: ${p => p.breakpoint}) { diff --git a/static/app/views/issueList/actions/headers.tsx b/static/app/views/issueList/actions/headers.tsx index c806fefcb9e531..f495544da1e5f5 100644 --- a/static/app/views/issueList/actions/headers.tsx +++ b/static/app/views/issueList/actions/headers.tsx @@ -85,11 +85,11 @@ function Headers({ {organization.features.includes('issue-stream-table-layout') ? ( <Fragment> <TimestampLabel breakpoint={COLUMN_BREAKPOINTS.AGE}> - {t('Age')} + {t('First Seen')} <HeaderDivider /> </TimestampLabel> <TimestampLabel breakpoint={COLUMN_BREAKPOINTS.SEEN}> - {t('Seen')} + {t('Last Seen')} <HeaderDivider /> </TimestampLabel> </Fragment> @@ -143,7 +143,7 @@ const GraphHeaderWrapper = styled('div')<{isSavedSearchesOpen?: boolean}>` `; const NarrowGraphLabel = styled(IssueStreamHeaderLabel)` - width: 200px; + width: 175px; flex: 1; display: flex; justify-content: space-between; @@ -182,7 +182,7 @@ const GraphToggle = styled('a')<{active: boolean}>` `; const TimestampLabel = styled(IssueStreamHeaderLabel)` - width: 60px; + width: 75px; display: flex; flex-direction: row; justify-content: space-between;
ee9eb9d38a10dbc02327cbe15b1276344bc9b04a
2021-07-01 03:13:41
Robin Rendle
fix(ui): reduced size of important tags (#26805)
false
reduced size of important tags (#26805)
fix
diff --git a/static/app/components/events/contextSummary/contextSummary.tsx b/static/app/components/events/contextSummary/contextSummary.tsx index 817d7069250105..570c13632fdb56 100644 --- a/static/app/components/events/contextSummary/contextSummary.tsx +++ b/static/app/components/events/contextSummary/contextSummary.tsx @@ -98,13 +98,9 @@ class ContextSummary extends React.Component<Props> { export default ContextSummary; const Wrapper = styled('div')` - border-top: 1px solid ${p => p.theme.innerBorder}; - @media (min-width: ${p => p.theme.breakpoints[0]}) { - display: grid; - grid-auto-flow: column; - grid-auto-columns: minmax(0, auto); - grid-gap: ${space(4)}; - padding: 25px ${space(4)} 25px 40px; + display: flex; + gap: ${space(3)}; + margin-bottom: ${space(2)}; } `; diff --git a/static/app/components/events/contextSummary/contextSummaryUser.tsx b/static/app/components/events/contextSummary/contextSummaryUser.tsx index a47034d4ed171a..1518802759597a 100644 --- a/static/app/components/events/contextSummary/contextSummaryUser.tsx +++ b/static/app/components/events/contextSummary/contextSummaryUser.tsx @@ -97,7 +97,7 @@ const ContextSummaryUser = ({data}: Props) => { const icon = userTitle ? ( <UserAvatar user={user as AvatarUser} - size={48} + size={32} className="context-item-icon" gravatar={false} /> diff --git a/static/app/components/events/contextSummary/item.tsx b/static/app/components/events/contextSummary/item.tsx index d7d985009412ce..c4b326ea8334db 100644 --- a/static/app/components/events/contextSummary/item.tsx +++ b/static/app/components/events/contextSummary/item.tsx @@ -20,21 +20,23 @@ const Item = ({children, icon, className}: Props) => ( export default Item; const Details = styled('div')` + display: flex; + flex-direction: column; + justify-content: center; max-width: 100%; min-height: 48px; `; const Wrapper = styled('div')` border-top: 1px solid ${p => p.theme.innerBorder}; - padding: ${space(2)} 0 ${space(2)} 64px; + padding: 4px 0 4px 40px; display: flex; + margin-right: ${space(3)}; align-items: center; position: relative; - min-height: 67px; @media (min-width: ${p => p.theme.breakpoints[0]}) { border: 0; - padding: ${space(0.5)} 0px 0px 64px; - min-height: 48px; + padding: 0px 0px 0px 42px; } `; diff --git a/static/app/components/events/eventDataSection.tsx b/static/app/components/events/eventDataSection.tsx index 9f40df331d91ba..2106529205271e 100644 --- a/static/app/components/events/eventDataSection.tsx +++ b/static/app/components/events/eventDataSection.tsx @@ -132,7 +132,7 @@ const SectionHeader = styled('div')<{isCentered?: boolean}>` display: flex; flex-wrap: wrap; align-items: center; - margin-bottom: ${space(2)}; + margin-bottom: ${space(1)}; > * { margin-bottom: ${space(0.5)}; diff --git a/static/app/components/events/eventEntries.tsx b/static/app/components/events/eventEntries.tsx index b733afb4349326..b213eb3be93d6d 100644 --- a/static/app/components/events/eventEntries.tsx +++ b/static/app/components/events/eventEntries.tsx @@ -373,15 +373,17 @@ class EventEntries extends Component<Props, State> { includeBorder={!hasErrors} /> )} - {hasContext && showTagSummary && <EventContextSummary event={event} />} {showTagSummary && ( - <EventTags - event={event} - organization={organization as Organization} - projectId={project.slug} - location={location} - hasQueryFeature={hasQueryFeature} - /> + <StyledEventDataSection title={t('Tags')} type="tags"> + {hasContext && <EventContextSummary event={event} />} + <EventTags + event={event} + organization={organization as Organization} + projectId={project.slug} + location={location} + hasQueryFeature={hasQueryFeature} + /> + </StyledEventDataSection> )} {this.renderEntries(event)} {hasContext && <EventContexts group={group} event={event} />} @@ -455,6 +457,10 @@ const StyledEventUserFeedback = styled(EventUserFeedback)<StyledEventUserFeedbac margin: 0; `; +const StyledEventDataSection = styled(EventDataSection)` + margin-bottom: ${space(2)}; +`; + // TODO(ts): any required due to our use of SharedViewOrganization export default withOrganization<any>(withApi(EventEntries)); export {BorderlessEventEntries}; diff --git a/static/app/components/events/eventTags/eventTags.tsx b/static/app/components/events/eventTags/eventTags.tsx index fc5244897f6d5e..b50f656f1ed2d7 100644 --- a/static/app/components/events/eventTags/eventTags.tsx +++ b/static/app/components/events/eventTags/eventTags.tsx @@ -1,11 +1,7 @@ -import styled from '@emotion/styled'; import {Location} from 'history'; import isEmpty from 'lodash/isEmpty'; -import EventDataSection from 'app/components/events/eventDataSection'; import Pills from 'app/components/pills'; -import {t} from 'app/locale'; -import space from 'app/styles/space'; import {Organization} from 'app/types'; import {Event} from 'app/types/event'; import {defined, generateQueryWithTag} from 'app/utils'; @@ -36,29 +32,21 @@ const EventTags = ({ const releasesPath = `/organizations/${orgSlug}/releases/`; return ( - <StyledEventDataSection title={t('Tags')} type="tags"> - <Pills> - {tags.map((tag, index) => ( - <EventTagsPill - key={!defined(tag.key) ? `tag-pill-${index}` : tag.key} - tag={tag} - projectId={projectId} - organization={organization} - query={generateQueryWithTag(location.query, tag)} - streamPath={streamPath} - releasesPath={releasesPath} - hasQueryFeature={hasQueryFeature} - /> - ))} - </Pills> - </StyledEventDataSection> + <Pills> + {tags.map((tag, index) => ( + <EventTagsPill + key={!defined(tag.key) ? `tag-pill-${index}` : tag.key} + tag={tag} + projectId={projectId} + organization={organization} + query={generateQueryWithTag(location.query, tag)} + streamPath={streamPath} + releasesPath={releasesPath} + hasQueryFeature={hasQueryFeature} + /> + ))} + </Pills> ); }; export default EventTags; - -const StyledEventDataSection = styled(EventDataSection)` - @media (min-width: ${p => p.theme.breakpoints[1]}) { - margin-bottom: ${space(3)}; - } -`; diff --git a/static/less/group-detail.less b/static/less/group-detail.less index 57b53342774b85..acdbed93a15975 100644 --- a/static/less/group-detail.less +++ b/static/less/group-detail.less @@ -161,28 +161,23 @@ .context-item-icon { position: absolute; left: 0; - top: 0; - width: 48px; - height: 48px; + width: 36px; + height: 36px; background-repeat: no-repeat; - background-position: center; + background-position: center 2px; background-image: url(~sentry-logos/logo-unknown.svg); - background-size: 48px 48px; + background-size: 30px 32px; // magic number here because some logos are slightly cut off when at 32 x 32 } &:first-child { border: 0; } - h3, - p { - margin: 0 0 4px; - } - h3 { .truncate; font-size: 16px; line-height: 1.2; + margin-bottom: 0; } p { @@ -280,13 +275,12 @@ &.watchos { .context-item-icon { background-image: url(~sentry-logos/logo-apple.svg); - top: -2px; + background-position: center 0; } } &.android .context-item-icon { background-image: url(~sentry-logos/logo-android.svg); - top: -1px; } &.windows .context-item-icon { @@ -1407,12 +1401,7 @@ ul.crumbs { flex-direction: column; margin-top: 0; padding: 0; - - .context-item { - .context-item-icon { - top: 9px; - } - } + margin-bottom: 20px; } .context {
b4ab5c562b98fb5f67432b96191c166b341255a6
2021-12-15 13:14:41
Evan Purkhiser
ref(js): Remove UNSAFE_componentWillReceiveProps (#30663)
false
Remove UNSAFE_componentWillReceiveProps (#30663)
ref
diff --git a/static/app/components/asyncComponent.tsx b/static/app/components/asyncComponent.tsx index 50b610a4da625f..497a0ae12654e8 100644 --- a/static/app/components/asyncComponent.tsx +++ b/static/app/components/asyncComponent.tsx @@ -114,9 +114,6 @@ export default class AsyncComponent< } } - // Compatibility shim for child classes that call super on this hook. - UNSAFE_componentWillReceiveProps(_newProps: P, _newContext: any) {} - componentDidUpdate(prevProps: P, prevContext: any) { const isRouterInContext = !!prevContext.router; const isLocationInProps = prevProps.location !== undefined;
e7edc43f4df1038056846b87b142dd09b79cc2b6
2024-07-10 02:28:12
Abdullah Khan
feat(new-trace): Updated logic for routing upon event id click from discover (#73971)
false
Updated logic for routing upon event id click from discover (#73971)
feat
diff --git a/static/app/views/discover/table/tableView.tsx b/static/app/views/discover/table/tableView.tsx index 1ca24dd81810cc..3104c8c3703008 100644 --- a/static/app/views/discover/table/tableView.tsx +++ b/static/app/views/discover/table/tableView.tsx @@ -190,13 +190,7 @@ function TableView(props: TableViewProps) { let target; - if (dataRow.trace === null || dataRow.trace === undefined) { - if (dataRow['event.type'] === 'transaction') { - throw new Error( - 'Transaction event should always have a trace associated with it.' - ); - } - + if (dataRow['event.type'] !== 'transaction') { const project = dataRow.project || dataRow['project.name']; target = { // NOTE: This uses a legacy redirect for project event to the issue group event link @@ -207,6 +201,12 @@ function TableView(props: TableViewProps) { query: {...location.query, referrer: 'discover-events-table'}, }; } else { + if (!dataRow.trace) { + throw new Error( + 'Transaction event should always have a trace associated with it.' + ); + } + target = generateLinkToEventInTraceView({ traceSlug: dataRow.trace, eventId: dataRow.id, @@ -321,13 +321,7 @@ function TableView(props: TableViewProps) { if (columnKey === 'id') { let target; - if (dataRow.trace === null || dataRow.trace === undefined) { - if (dataRow['event.type'] === 'transaction') { - throw new Error( - 'Transaction event should always have a trace associated with it.' - ); - } - + if (dataRow['event.type'] !== 'transaction') { const project = dataRow.project || dataRow['project.name']; target = { @@ -339,6 +333,12 @@ function TableView(props: TableViewProps) { query: {...location.query, referrer: 'discover-events-table'}, }; } else { + if (!dataRow.trace) { + throw new Error( + 'Transaction event should always have a trace associated with it.' + ); + } + target = generateLinkToEventInTraceView({ traceSlug: dataRow.trace?.toString(), eventId: dataRow.id,
46f14ab3435c0f82a1eba339d9c8e96d8867edd1
2020-12-01 00:59:59
k-fish
ref(ts): Convert worldMapChart to typescript (#22148)
false
Convert worldMapChart to typescript (#22148)
ref
diff --git a/src/sentry/static/sentry/app/components/charts/baseChart.tsx b/src/sentry/static/sentry/app/components/charts/baseChart.tsx index d39a65daca34e4..5084cd3a4d137b 100644 --- a/src/sentry/static/sentry/app/components/charts/baseChart.tsx +++ b/src/sentry/static/sentry/app/components/charts/baseChart.tsx @@ -74,7 +74,7 @@ type Props = { /** * Must be explicitly `null` to disable yAxis */ - yAxis?: EChartOption.YAxis; + yAxis?: EChartOption.YAxis | null; /** * Pass `true` to have 2 y-axes with default properties. Can pass an array of * objects to customize yAxis properties diff --git a/src/sentry/static/sentry/app/components/charts/worldMapChart.tsx b/src/sentry/static/sentry/app/components/charts/worldMapChart.tsx new file mode 100644 index 00000000000000..839affae790037 --- /dev/null +++ b/src/sentry/static/sentry/app/components/charts/worldMapChart.tsx @@ -0,0 +1,155 @@ +import React from 'react'; +import echarts, {EChartOption} from 'echarts'; +import {withTheme} from 'emotion-theming'; +import max from 'lodash/max'; + +import {Series, SeriesDataUnit} from 'app/types/echarts'; +import theme from 'app/utils/theme'; + +import VisualMap from './components/visualMap'; +import MapSeries from './series/mapSeries'; +import BaseChart from './baseChart'; + +type ChartProps = React.ComponentProps<typeof BaseChart>; + +type MapChartSeriesDataUnit = Omit<SeriesDataUnit, 'name' | 'itemStyle'> & { + // Docs for map itemStyle differ from Series data unit. See https://echarts.apache.org/en/option.html#series-map.data.itemStyle + itemStyle: EChartOption.SeriesMap.DataObject['itemStyle']; + name?: string; +}; + +type MapChartSeries = Omit<Series, 'data'> & { + data: MapChartSeriesDataUnit[]; +}; + +type Props = Omit<ChartProps, 'series'> & { + series: MapChartSeries[]; + seriesOptions?: EChartOption.SeriesMap; +}; + +type JSONResult = Record<string, any>; + +type State = { + countryToCodeMap: JSONResult | null; + map: JSONResult | null; + codeToCountryMap: JSONResult | null; +}; + +class WorldMapChart extends React.Component<Props, State> { + state: State = { + countryToCodeMap: null, + map: null, + codeToCountryMap: null, + }; + + async componentDidMount() { + const [countryToCodeMap, worldMap] = await Promise.all([ + import(/* webpackChunkName: "countryCodesMap" */ 'app/data/countryCodesMap'), + import(/* webpackChunkName: "worldMapGeoJson" */ 'app/data/world.json'), + ]); + + echarts.registerMap('sentryWorld', worldMap.default); + + // eslint-disable-next-line + this.setState({ + countryToCodeMap: countryToCodeMap.default, + map: worldMap.default, + codeToCountryMap: Object.fromEntries( + Object.entries(countryToCodeMap.default).map(([country, code]) => [code, country]) + ), + }); + } + + render() { + const {countryToCodeMap, map} = this.state; + + if (countryToCodeMap === null || map === null) { + return null; + } + + const {series, seriesOptions, ...props} = this.props; + const processedSeries = series.map(({seriesName, data, ...options}) => + MapSeries({ + ...seriesOptions, + ...options, + map: 'sentryWorld', + name: seriesName, + nameMap: this.state.countryToCodeMap ?? undefined, + aspectScale: 0.85, + zoom: 1.3, + center: [10.97, 9.71], + itemStyle: { + areaColor: theme.gray200, + borderColor: theme.backgroundSecondary, + emphasis: { + areaColor: theme.orange300, + }, + } as any, // TODO(ts): Echarts types aren't correct for these colors as they don't allow for basic strings + label: { + emphasis: { + show: false, + }, + }, + data, + }) + ); + + // TODO(billy): + // For absolute values, we want min/max to based on min/max of series + // Otherwise it should be 0-100 + const maxValue = max(series.map(({data}) => max(data.map(({value}) => value)))) || 1; + + const tooltipFormatter: EChartOption.Tooltip.Formatter = ( + format: EChartOption.Tooltip.Format | EChartOption.Tooltip.Format[] + ) => { + const {marker, name, value} = Array.isArray(format) ? format[0] : format; + // If value is NaN, don't show anything because we won't have a country code either + if (isNaN(value as number)) { + return ''; + } + + // `value` should be a number + const formattedValue = typeof value === 'number' ? value.toLocaleString() : ''; + const countryOrCode = this.state.codeToCountryMap?.[name as string] || name; + + return [ + `<div class="tooltip-series tooltip-series-solo"> + <div><span class="tooltip-label">${marker} <strong>${countryOrCode}</strong></span> ${formattedValue}</div> + </div>`, + '<div class="tooltip-arrow"></div>', + ].join(''); + }; + + return ( + <BaseChart + options={{ + backgroundColor: theme.backgroundSecondary, + visualMap: [ + VisualMap({ + left: 'right', + min: 0, + max: maxValue, + inRange: { + color: [theme.purple200, theme.purple300], + }, + text: ['High', 'Low'], + + // Whether show handles, which can be dragged to adjust "selected range". + // False because the handles are pretty ugly + calculable: false, + }), + ], + }} + {...props} + yAxis={null} + xAxis={null} + series={processedSeries} + tooltip={{ + formatter: tooltipFormatter, + }} + /> + ); + } +} + +export default withTheme(WorldMapChart);
99a54175bd3951a325bc0630573164aff88ab0ba
2022-04-21 05:44:20
Zhixing Zhang
fix(onboarding): Fix analytics & layout for mobile (#33815)
false
Fix analytics & layout for mobile (#33815)
fix
diff --git a/static/app/utils/analytics/growthAnalyticsEvents.tsx b/static/app/utils/analytics/growthAnalyticsEvents.tsx index d8e40aeafc2fe0..689a970fbdb649 100644 --- a/static/app/utils/analytics/growthAnalyticsEvents.tsx +++ b/static/app/utils/analytics/growthAnalyticsEvents.tsx @@ -60,7 +60,7 @@ export type GrowthEventParameters = { 'growth.onboarding_load_choose_platform': {}; 'growth.onboarding_quick_start_cta': SampleEventParam; 'growth.onboarding_set_up_your_project': PlatformParam; - 'growth.onboarding_set_up_your_projects': {platforms: string}; + 'growth.onboarding_set_up_your_projects': {platform_count: number; platforms: string}; 'growth.onboarding_start_onboarding': { source?: string; }; diff --git a/static/app/views/onboarding/components/stepHeading.tsx b/static/app/views/onboarding/components/stepHeading.tsx index 8162d2fc2d696f..b8202e8005f49f 100644 --- a/static/app/views/onboarding/components/stepHeading.tsx +++ b/static/app/views/onboarding/components/stepHeading.tsx @@ -8,7 +8,7 @@ const StepHeading = styled(motion.h2)<{step: number}>` margin-left: calc(-${space(2)} - 30px); position: relative; display: inline-grid; - grid-template-columns: max-content max-content; + grid-template-columns: max-content auto; gap: ${space(2)}; align-items: center; diff --git a/static/app/views/onboarding/targetedOnboarding/components/createProjectsFooter.tsx b/static/app/views/onboarding/targetedOnboarding/components/createProjectsFooter.tsx index 62d2f77c0c55bc..7e02e73fe6f198 100644 --- a/static/app/views/onboarding/targetedOnboarding/components/createProjectsFooter.tsx +++ b/static/app/views/onboarding/targetedOnboarding/components/createProjectsFooter.tsx @@ -71,6 +71,7 @@ export default function CreateProjectsFooter({ responses.map(ProjectActions.createSuccess); trackAdvancedAnalyticsEvent('growth.onboarding_set_up_your_projects', { platforms: platforms.join(','), + platform_count: platforms.length, organization, }); clearIndicators(); @@ -120,6 +121,10 @@ const SelectionWrapper = styled(motion.div)` flex-direction: column; justify-content: center; align-items: center; + + @media (max-width: ${p => p.theme.breakpoints[0]}) { + display: none; + } `; SelectionWrapper.defaultProps = { diff --git a/static/app/views/onboarding/targetedOnboarding/components/firstEventFooter.tsx b/static/app/views/onboarding/targetedOnboarding/components/firstEventFooter.tsx index 31bce4da76e680..f3ff1a4f219d05 100644 --- a/static/app/views/onboarding/targetedOnboarding/components/firstEventFooter.tsx +++ b/static/app/views/onboarding/targetedOnboarding/components/firstEventFooter.tsx @@ -39,7 +39,7 @@ export default function FirstEventFooter({ const getSecondaryCta = () => { // if hasn't sent first event, allow skiping. // if last, no secondary cta - if (!hasFirstEvent || !isLast) { + if (!hasFirstEvent && !isLast) { return <Button onClick={onClickSetupLater}>{t('Next Platform')}</Button>; } return null; diff --git a/static/app/views/onboarding/targetedOnboarding/onboarding.tsx b/static/app/views/onboarding/targetedOnboarding/onboarding.tsx index 40491be93077c6..ff721fc0b98ed2 100644 --- a/static/app/views/onboarding/targetedOnboarding/onboarding.tsx +++ b/static/app/views/onboarding/targetedOnboarding/onboarding.tsx @@ -262,6 +262,9 @@ const StyledStepper = styled(Stepper)` margin-left: auto; margin-right: auto; align-self: center; + @media (max-width: ${p => p.theme.breakpoints[1]}) { + display: none; + } `; interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> { diff --git a/static/app/views/onboarding/targetedOnboarding/platform.tsx b/static/app/views/onboarding/targetedOnboarding/platform.tsx index b3067fe7d5994d..bfeceece97ce92 100644 --- a/static/app/views/onboarding/targetedOnboarding/platform.tsx +++ b/static/app/views/onboarding/targetedOnboarding/platform.tsx @@ -45,8 +45,8 @@ function OnboardingPlatform(props: StepProps) { > <p> {tct( - `Variety is the spice of application monitoring. Sentry SDKs integrate - with most languages and platforms your developer heart desires. + `Variety is the spice of application monitoring. + Get started by selecting platforms for your Front End, Back End and/or Mobile applications. [link:View the full list].`, {link: <ExternalLink href="https://docs.sentry.io/platforms/" />} )} diff --git a/static/app/views/onboarding/targetedOnboarding/welcome.tsx b/static/app/views/onboarding/targetedOnboarding/welcome.tsx index d266df6bbdee84..4fb7e9197e1602 100644 --- a/static/app/views/onboarding/targetedOnboarding/welcome.tsx +++ b/static/app/views/onboarding/targetedOnboarding/welcome.tsx @@ -53,7 +53,7 @@ function TargetedOnboardingWelcome({organization, ...props}: StepProps) { organization, source, }); - }); + }, []); const onComplete = () => { trackAdvancedAnalyticsEvent('growth.onboarding_clicked_instrument_app', { diff --git a/static/app/views/onboarding/welcome.tsx b/static/app/views/onboarding/welcome.tsx index a895763abc36ee..26fc59dc491529 100644 --- a/static/app/views/onboarding/welcome.tsx +++ b/static/app/views/onboarding/welcome.tsx @@ -53,7 +53,7 @@ function TargetedOnboardingWelcome({organization, ...props}: StepProps) { organization, source, }); - }); + }, []); const onComplete = () => { trackAdvancedAnalyticsEvent('growth.onboarding_clicked_instrument_app', {
a58c0a53a14b1d1f92f2ec008983b6973e5f4fa4
2024-11-20 03:59:00
Malachi Willey
chore(rollback): Add prompt configs for rollback dismissals (#81007)
false
Add prompt configs for rollback dismissals (#81007)
chore
diff --git a/src/sentry/utils/prompts.py b/src/sentry/utils/prompts.py index a5c7814b2ac592..d89886fd24f525 100644 --- a/src/sentry/utils/prompts.py +++ b/src/sentry/utils/prompts.py @@ -22,6 +22,8 @@ "issue_feature_flags_inline_onboarding": {"required_fields": ["organization_id", "project_id"]}, "issue_feedback_hidden": {"required_fields": ["organization_id", "project_id"]}, "issue_views_add_view_banner": {"required_fields": ["organization_id"]}, + "rollback_2024_sidebar": {"required_fields": ["organization_id"]}, + "rollback_2024_dropdown": {"required_fields": ["organization_id"]}, }
e2badba1483dc2abe863db8db927c5e8ead9aa66
2024-10-01 04:46:24
Scott Cooper
fix(issues): Fix Verison -> Version (#78358)
false
Fix Verison -> Version (#78358)
fix
diff --git a/static/app/types/release.tsx b/static/app/types/release.tsx index 9ef101f5bdcc8b..9e6f80cd468bda 100644 --- a/static/app/types/release.tsx +++ b/static/app/types/release.tsx @@ -40,7 +40,7 @@ interface RawVersion { raw: string; } -export interface SemverVerison extends RawVersion { +export interface SemverVersion extends RawVersion { buildCode: string | null; components: number; major: number; @@ -53,7 +53,7 @@ export type VersionInfo = { buildHash: string | null; description: string; package: string | null; - version: RawVersion | SemverVerison; + version: RawVersion | SemverVersion; }; export interface BaseRelease { diff --git a/static/app/views/releases/utils/index.tsx b/static/app/views/releases/utils/index.tsx index d5ea20418eed84..5c67b1a5be0514 100644 --- a/static/app/views/releases/utils/index.tsx +++ b/static/app/views/releases/utils/index.tsx @@ -11,7 +11,7 @@ import {PAGE_URL_PARAM, URL_PARAM} from 'sentry/constants/pageFilters'; import {desktop, mobile} from 'sentry/data/platformCategories'; import {t, tct} from 'sentry/locale'; import type {PlatformKey} from 'sentry/types/project'; -import type {Release, SemverVerison, VersionInfo} from 'sentry/types/release'; +import type {Release, SemverVersion, VersionInfo} from 'sentry/types/release'; import {ReleaseStatus} from 'sentry/types/release'; import {defined} from 'sentry/utils'; import {MutableSearch} from 'sentry/utils/tokenizeSearch'; @@ -250,6 +250,6 @@ export function searchReleaseVersion(version: string): string { export function isVersionInfoSemver( versionInfo: VersionInfo['version'] -): versionInfo is SemverVerison { +): versionInfo is SemverVersion { return versionInfo.hasOwnProperty('components'); }
f8aef1fdc315b93d1232c89c01ac22e90e522e68
2018-03-01 07:11:40
David Cramer
ref(committers): Redesign suspected commits
false
Redesign suspected commits
ref
diff --git a/src/sentry/api/endpoints/event_file_committers.py b/src/sentry/api/endpoints/event_file_committers.py index 9bb40fe3face79..7bca5ec79bc2b6 100644 --- a/src/sentry/api/endpoints/event_file_committers.py +++ b/src/sentry/api/endpoints/event_file_committers.py @@ -89,10 +89,6 @@ def _get_commits_committer(self, commits, author_id): committer_commit_list = [ serialize(commit) for commit in commits if commit.author.id == author_id ] - - # filter out the author data - for c in committer_commit_list: - del c['author'] return committer_commit_list def _get_committers(self, annotated_frames, commits): diff --git a/src/sentry/static/sentry/app/components/activity/item.jsx b/src/sentry/static/sentry/app/components/activity/item.jsx index bc457273aa179c..62f7375bff8ff4 100644 --- a/src/sentry/static/sentry/app/components/activity/item.jsx +++ b/src/sentry/static/sentry/app/components/activity/item.jsx @@ -3,9 +3,9 @@ import React from 'react'; import {Link} from 'react-router'; import marked from 'marked'; -import CommitLink from '../../views/releases/commitLink'; import PullRequestLink from '../../views/releases/pullRequestLink'; +import CommitLink from '../../components/commitLink'; import Duration from '../../components/duration'; import Avatar from '../../components/avatar'; import IssueLink from '../../components/issueLink'; diff --git a/src/sentry/static/sentry/app/views/releases/commitLink.jsx b/src/sentry/static/sentry/app/components/commitLink.jsx similarity index 96% rename from src/sentry/static/sentry/app/views/releases/commitLink.jsx rename to src/sentry/static/sentry/app/components/commitLink.jsx index 2cbfeaa9d80fb4..8b0526f3dd218c 100644 --- a/src/sentry/static/sentry/app/views/releases/commitLink.jsx +++ b/src/sentry/static/sentry/app/components/commitLink.jsx @@ -1,7 +1,7 @@ import PropTypes from 'prop-types'; import React from 'react'; -import InlineSvg from '../../components/inlineSvg'; +import InlineSvg from './inlineSvg'; class CommitLink extends React.Component { static propTypes = { diff --git a/src/sentry/static/sentry/app/components/events/eventCause.jsx b/src/sentry/static/sentry/app/components/events/eventCause.jsx index 7d03afcdf0f6e0..c2be76afa76dc0 100644 --- a/src/sentry/static/sentry/app/components/events/eventCause.jsx +++ b/src/sentry/static/sentry/app/components/events/eventCause.jsx @@ -1,34 +1,63 @@ +import idx from 'idx'; import PropTypes from 'prop-types'; import React from 'react'; import createReactClass from 'create-react-class'; -import ReactDOMServer from 'react-dom/server'; import moment from 'moment'; import Avatar from '../avatar'; -import TooltipMixin from '../../mixins/tooltip'; import ApiMixin from '../../mixins/apiMixin'; import GroupState from '../../mixins/groupState'; import TimeSince from '../timeSince'; -import {assignTo} from '../../actionCreators/group'; +import CommitLink from '../commitLink'; +import {t} from '../../locale'; + +class Commit extends React.Component { + static propTypes = { + commit: PropTypes.object, + }; + + renderMessage = message => { + if (!message) { + return t('No message provided'); + } + + let firstLine = message.split(/\n/)[0]; + + return firstLine; + }; + + render() { + let {id, dateCreated, message, author, repository} = this.props.commit; + return ( + <li className="list-group-item" key={id}> + <div className="row row-center-vertically"> + <div className="col-xs-10 list-group-avatar"> + <Avatar user={author} /> + <h5 className="truncate">{this.renderMessage(message)}</h5> + <p> + <strong>{idx(author, _ => _.name) || t('Unknown author')}</strong> committed{' '} + <TimeSince date={dateCreated} /> + </p> + </div> + <div className="col-xs-2 align-right"> + <CommitLink commitId={id} repository={repository} /> + </div> + </div> + </li> + ); + } +} export default createReactClass({ displayName: 'EventCause', propTypes: { - event: PropTypes.object, + event: PropTypes.object.isRequired, + orgId: PropTypes.string.isRequired, + projectId: PropTypes.string.isRequired, }, - mixins: [ - ApiMixin, - GroupState, - TooltipMixin({ - selector: '.tip', - html: true, - container: 'body', - template: - '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner tooltip-owners"></div></div>', - }), - ], + mixins: [ApiMixin, GroupState], getInitialState() { return {committers: undefined}; @@ -50,21 +79,12 @@ export default createReactClass({ } }, - componentDidUpdate(_, nextState) { - //this shallow equality should be OK because it's being mutated fetchData as a new object - if (this.state.owners !== nextState.owners) { - this.removeTooltips(); - this.attachTooltips(); - } - }, - fetchData(event) { // TODO(dcramer): this API request happens twice, and we need a store for it if (!event) return; - let org = this.getOrganization(); - let project = this.getProject(); this.api.request( - `/projects/${org.slug}/${project.slug}/events/${event.id}/committers/`, + `/projects/${this.props.orgId}/${this.props + .projectId}/events/${event.id}/committers/`, { success: (data, _, jqXHR) => { this.setState(data); @@ -78,57 +98,6 @@ export default createReactClass({ ); }, - assignTo(member) { - if (member.id !== undefined) { - assignTo({id: this.props.event.groupID, member}); - } - }, - - renderCommitter(owner) { - let {author, commits} = owner; - return ( - <span - key={author.id || author.email} - className="avatar-grid-item tip" - onClick={() => this.assignTo(author)} - title={ReactDOMServer.renderToStaticMarkup( - <div> - {author.id ? ( - <div className="tooltip-owners-name">{author.name}</div> - ) : ( - <div className="tooltip-owners-unknown"> - <p className="tooltip-owners-unknown-email"> - <span className="icon icon-circle-cross" /> - <strong>{author.email}</strong> - </p> - <p> - Sorry, we don't recognize this member. Make sure to link alternative - emails in Account Settings. - </p> - <hr /> - </div> - )} - <ul className="tooltip-owners-commits"> - {commits.slice(0, 6).map(c => { - return ( - <li key={c.id} className="tooltip-owners-commit"> - {c.message} - <span className="tooltip-owners-date"> - {' '} - - {moment(c.dateCreated).fromNow()} - </span> - </li> - ); - })} - </ul> - </div> - )} - > - <Avatar user={author} /> - </span> - ); - }, - render() { if (!(this.state.committers && this.state.committers.length)) { return null; @@ -149,42 +118,18 @@ export default createReactClass({ return firstSeen - a[0] - (firstSeen - b[0]); }); if (!commitsWithAge.length) return null; - - let probablyTheCommit = commitsWithAge[0][1]; - let commitBits = probablyTheCommit.message.split('\n'); - let subject = commitBits[0]; - let message = - commitBits.length > 1 - ? commitBits - .slice(1) - .join('\n') - .replace(/^\s+|\s+$/g, '') - : null; return ( <div className="box"> <div className="box-header"> - <h3>Likely Culprit</h3> - </div> - <div style={{fontSize: '0.8em', fontWeight: 'bold', marginBottom: 10}}> - {subject} - </div> - {!!message && ( - <pre - style={{marginBottom: 10, background: 'none', padding: 0, fontSize: '0.8em'}} - > - {message} - </pre> - )} - <div style={{marginBottom: 20, fontSize: '0.7em', color: '#999', lineHeight: 1}}> - {!!probablyTheCommit.author ? ( - <strong>{probablyTheCommit.author.name}</strong> - ) : ( - <strong> - <em>Unknown Author</em> - </strong> - )}{' '} - committed <TimeSince date={probablyTheCommit.dateCreated} /> + <h3> + {t('Suspect Commits')} ({commitsWithAge.length}) + </h3> </div> + <ul className="list-group list-group-lg commit-list"> + {commitsWithAge.map(([age, commit]) => { + return <Commit key={commit.id} commit={commit} />; + })} + </ul> </div> ); }, diff --git a/src/sentry/static/sentry/app/components/events/eventEntries.jsx b/src/sentry/static/sentry/app/components/events/eventEntries.jsx index 41af0cdaf5816a..99542fa48dd37e 100644 --- a/src/sentry/static/sentry/app/components/events/eventEntries.jsx +++ b/src/sentry/static/sentry/app/components/events/eventEntries.jsx @@ -4,6 +4,7 @@ import React from 'react'; import createReactClass from 'create-react-class'; import {logException} from '../../utils/logging'; +import EventCause from './eventCause'; import EventContexts from './contexts'; import EventContextSummary from './contextSummary'; import EventDataSection from './eventDataSection'; @@ -15,6 +16,7 @@ import EventSdk from './sdk'; import EventDevice from './device'; import EventUserReport from './userReport'; import SentryTypes from '../../proptypes'; +import GroupState from '../../mixins/groupState'; import utils from '../../utils'; import {t} from '../../locale'; @@ -53,6 +55,8 @@ const EventEntries = createReactClass({ isShare: PropTypes.bool, }, + mixins: [GroupState], + getDefaultProps() { return { isShare: false, @@ -67,7 +71,8 @@ const EventEntries = createReactClass({ render() { let {group, isShare, project, event, orgId} = this.props; - + let organization = this.getOrganization(); + let features = organization ? new Set(organization.features) : new Set(); let entries = event.entries.map((entry, entryIdx) => { try { let Component = this.interfaces[entry.type]; @@ -115,6 +120,13 @@ const EventEntries = createReactClass({ return ( <div className="entries"> + {!utils.objectIsEmpty(event.errors) && ( + <EventErrors group={group} event={event} /> + )}{' '} + {!isShare && + features.has('suggested-commits') && ( + <EventCause event={event} orgId={orgId} projectId={project.slug} /> + )} {event.userReport && ( <EventUserReport report={event.userReport} @@ -123,9 +135,6 @@ const EventEntries = createReactClass({ issueId={group.id} /> )} - {!utils.objectIsEmpty(event.errors) && ( - <EventErrors group={group} event={event} /> - )} {!utils.objectIsEmpty(event.sdk) && event.sdk.upstream.isNewer && ( <div className="alert-block alert-info box"> diff --git a/src/sentry/static/sentry/app/views/groupActivity/index.jsx b/src/sentry/static/sentry/app/views/groupActivity/index.jsx index 0e95bbf10a2e54..d353bce034ea6d 100644 --- a/src/sentry/static/sentry/app/views/groupActivity/index.jsx +++ b/src/sentry/static/sentry/app/views/groupActivity/index.jsx @@ -6,9 +6,9 @@ import createReactClass from 'create-react-class'; import ApiMixin from '../../mixins/apiMixin'; import GroupState from '../../mixins/groupState'; -import CommitLink from '../../views/releases/commitLink'; import PullRequestLink from '../../views/releases/pullRequestLink'; +import CommitLink from '../../components/commitLink'; import Duration from '../../components/duration'; import Avatar from '../../components/avatar'; import TimeSince from '../../components/timeSince'; diff --git a/src/sentry/static/sentry/app/views/groupEventDetails.jsx b/src/sentry/static/sentry/app/views/groupEventDetails.jsx index a9fa0076d03a78..ff0f654cf59552 100644 --- a/src/sentry/static/sentry/app/views/groupEventDetails.jsx +++ b/src/sentry/static/sentry/app/views/groupEventDetails.jsx @@ -2,7 +2,6 @@ import React from 'react'; import createReactClass from 'create-react-class'; import ApiMixin from '../mixins/apiMixin'; import EventEntries from '../components/events/eventEntries'; -import EventCause from '../components/events/eventCause'; import GroupEventToolbar from './groupDetails/eventToolbar'; import GroupSidebar from '../components/group/sidebar'; import GroupState from '../mixins/groupState'; @@ -13,6 +12,7 @@ import ResolutionBox from '../components/resolutionBox'; const GroupEventDetails = createReactClass({ displayName: 'GroupEventDetails', + mixins: [ApiMixin, GroupState], getInitialState() { @@ -76,7 +76,6 @@ const GroupEventDetails = createReactClass({ let group = this.getGroup(); let evt = this.state.event; let params = this.props.params; - let features = new Set(this.getOrganization().features); return ( <div> @@ -100,14 +99,6 @@ const GroupEventDetails = createReactClass({ )} </div> )} - {features.has('suggested-commits') && ( - <EventCause - group={group} - event={evt} - orgId={params.orgId} - project={this.getProject()} - /> - )} {this.state.loading ? ( <LoadingIndicator /> ) : this.state.error ? ( diff --git a/src/sentry/static/sentry/app/views/releases/releaseCommits.jsx b/src/sentry/static/sentry/app/views/releases/releaseCommits.jsx index d7a70bca434cd7..089c55a034bc7d 100644 --- a/src/sentry/static/sentry/app/views/releases/releaseCommits.jsx +++ b/src/sentry/static/sentry/app/views/releases/releaseCommits.jsx @@ -11,7 +11,7 @@ import DropdownLink from '../../components/dropdownLink'; import MenuItem from '../../components/menuItem'; import ApiMixin from '../../mixins/apiMixin'; -import CommitLink from './commitLink'; +import CommitLink from '../../components/commitLink'; import {t} from '../../locale';
d6e4080aa770c45feb39b51295982e0137c18807
2023-06-08 23:41:03
Cathy Teng
feat(github-comments): PR comment workflow (#50506)
false
PR comment workflow (#50506)
feat
diff --git a/src/sentry/tasks/integrations/github/pr_comment.py b/src/sentry/tasks/integrations/github/pr_comment.py index a69f644008de1b..d2d06bc6e56c93 100644 --- a/src/sentry/tasks/integrations/github/pr_comment.py +++ b/src/sentry/tasks/integrations/github/pr_comment.py @@ -1,3 +1,4 @@ +import logging from dataclasses import dataclass from datetime import datetime, timedelta from typing import List @@ -6,9 +7,15 @@ from snuba_sdk import Column, Condition, Direction, Entity, Function, Op, OrderBy, Query from snuba_sdk import Request as SnubaRequest +from sentry import features from sentry.models import Group, GroupOwnerType, Project +from sentry.models.organization import Organization +from sentry.models.repository import Repository +from sentry.services.hybrid_cloud.integration import integration_service from sentry.utils.snuba import Dataset, raw_snql_query +logger = logging.getLogger(__name__) + @dataclass class PullRequestIssue: @@ -100,3 +107,49 @@ def get_comment_contents(issue_list: List[int]) -> List[PullRequestIssue]: PullRequestIssue(title=issue.title, subtitle=issue.message, url=issue.get_absolute_url()) for issue in issues ] + + +def comment_workflow(): + pr_list = pr_to_issue_query() + for (gh_repo_id, pr_key, org_id, issue_list) in pr_list: + try: + organization = Organization.objects.get_from_cache(id=org_id) + except Organization.DoesNotExist: + logger.error("github.pr_comment.org_missing") + continue + + # currently only posts new comments + if not features.has("organizations:pr-comment-bot", organization): + # or pr.summary_comment_meta is None: + continue + + try: + project = Group.objects.get_from_cache(id=issue_list[0]).project + except Group.DoesNotExist: + logger.error("github.pr_comment.group_missing", extra={"organization_id": org_id}) + continue + + top_5_issues = get_top_5_issues_by_count(issue_list, project) + issue_comment_contents = get_comment_contents([issue["group_id"] for issue in top_5_issues]) + + try: + repo = Repository.objects.get(id=gh_repo_id) + except Repository.DoesNotExist: + logger.error("github.pr_comment.repo_missing", extra={"organization_id": org_id}) + continue + + integration = integration_service.get_integration(integration_id=repo.integration_id) + if not integration: + logger.error("github.pr_comment.integration_missing", extra={"organization_id": org_id}) + continue + + installation = integration_service.get_installation( + integration=integration, organization_id=org_id + ) + + # GitHubAppsClient (GithubClientMixin) + client = installation.get_client() + + comment_body = format_comment(issue_comment_contents) + + client.create_comment(repo=repo.name, issue_id=pr_key, data={"body": comment_body}) diff --git a/tests/sentry/tasks/integrations/github/test_pr_comment.py b/tests/sentry/tasks/integrations/github/test_pr_comment.py index bdc9f8f2e47663..66b6b08bb33fee 100644 --- a/tests/sentry/tasks/integrations/github/test_pr_comment.py +++ b/tests/sentry/tasks/integrations/github/test_pr_comment.py @@ -1,15 +1,27 @@ -from sentry.models import Commit, GroupOwner, GroupOwnerType, PullRequest +from datetime import timedelta +from unittest.mock import patch + +import responses +from django.utils import timezone + +from sentry.integrations.github.integration import GitHubIntegrationProvider +from sentry.models import Commit, Group, GroupOwner, GroupOwnerType, PullRequest +from sentry.models.repository import Repository +from sentry.snuba.sessions_v2 import isoformat_z from sentry.tasks.integrations.github import pr_comment from sentry.tasks.integrations.github.pr_comment import ( PullRequestIssue, get_comment_contents, get_top_5_issues_by_count, ) -from sentry.testutils import SnubaTestCase, TestCase +from sentry.testutils import IntegrationTestCase, SnubaTestCase, TestCase +from sentry.testutils.helpers import with_feature from sentry.testutils.helpers.datetime import before_now, iso_format -class GithubCommentTestCase(TestCase): +class GithubCommentTestCase(IntegrationTestCase): + provider = GitHubIntegrationProvider + def setUp(self): super().setUp() self.another_integration = self.create_integration( @@ -90,7 +102,11 @@ def add_pr_to_commit(self, commit: Commit, date_added=None): def add_groupowner_to_commit(self, commit: Commit, project, user): event = self.store_event( - data={"fingerprint": [f"issue{self.fingerprint}"]}, project_id=project.id + data={ + "message": f"issue{self.fingerprint}", + "fingerprint": [f"issue{self.fingerprint}"], + }, + project_id=project.id, ) self.fingerprint += 1 groupowner = GroupOwner.objects.create( @@ -292,3 +308,121 @@ def test_format_comment(self): formatted_comment = pr_comment.format_comment(issues) expected_comment = "## Suspect Issues\nThis pull request has been deployed and Sentry has observed the following issues:\n\n- ‼️ **TypeError** `sentry.tasks.derive_code_mappings.derive_code_m...` [View Issue](https://sentry.sentry.io/issues/)\n- ‼️ **KafkaException** `query_subscription_consumer_process_message` [View Issue](https://sentry.sentry.io/stats/)\n\n<sub>Did you find this useful? React with a 👍 or 👎</sub>" assert formatted_comment == expected_comment + + +class TestCommentWorkflow(GithubCommentTestCase): + base_url = "https://api.github.com" + + def setUp(self): + super().setUp() + self.installation_id = "github:1" + self.user_id = "user_1" + self.app_id = "app_1" + self.access_token = "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx" + self.expires_at = isoformat_z(timezone.now() + timedelta(days=365)) + + def create_pr_issues(self): + commit_1 = self.add_commit_to_repo(self.gh_repo, self.user, self.project) + self.add_pr_to_commit(commit_1) + self.add_groupowner_to_commit(commit_1, self.project, self.user) + self.add_groupowner_to_commit(commit_1, self.another_org_project, self.another_org_user) + + @patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count") + @patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1") + @with_feature("organizations:pr-comment-bot") + @responses.activate + def test_comment_workflow(self, get_jwt, mock_issues): + self.create_pr_issues() + + groups = [g.id for g in Group.objects.all()] + mock_issues.return_value = [ + {"group_id": g.id, "event_count": 10} for g in Group.objects.all() + ] + + responses.add( + responses.POST, + self.base_url + f"/app/installations/{self.installation_id}/access_tokens", + json={"token": self.access_token, "expires_at": self.expires_at}, + ) + responses.add( + responses.POST, + self.base_url + "/repos/getsentry/sentry/issues/1/comments", + json={}, + ) + + pr_comment.comment_workflow() + + assert ( + responses.calls[1].request.body + == f'{{"body": "## Suspect Issues\\nThis pull request has been deployed and Sentry has observed the following issues:\\n\\n- \\u203c\\ufe0f **issue1** `issue1` [View Issue](http://testserver/organizations/foo/issues/{groups[0]}/)\\n- \\u203c\\ufe0f **issue2** `issue2` [View Issue](http://testserver/organizations/foobar/issues/{groups[1]}/)\\n\\n<sub>Did you find this useful? React with a \\ud83d\\udc4d or \\ud83d\\udc4e</sub>"}}'.encode() + ) + + @patch( + "sentry.tasks.integrations.github.pr_comment.pr_to_issue_query", + return_value=[(0, 0, 0, [])], + ) + @patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count") + def test_comment_workflow_missing_org(self, mock_issues, mock_issue_query): + pr_comment.comment_workflow() + + assert not mock_issues.called + + @patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count") + def test_comment_workflow_missing_feature_flag(self, mock_issues): + self.create_pr_issues() + + pr_comment.comment_workflow() + + assert not mock_issues.called + + @patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count") + @patch("sentry.models.Group.objects.get_from_cache") + @with_feature("organizations:pr-comment-bot") + def test_comment_workflow_missing_group(self, mock_group, mock_issues): + self.create_pr_issues() + + mock_group.side_effect = Group.DoesNotExist + + pr_comment.comment_workflow() + + assert not mock_issues.called + + @patch( + "sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count", + ) + @patch("sentry.models.Repository.objects") + @patch("sentry.tasks.integrations.github.pr_comment.format_comment") + @with_feature("organizations:pr-comment-bot") + def test_comment_workflow_missing_repo(self, mock_format_comment, mock_repository, mock_issues): + self.create_pr_issues() + + mock_repository.get.side_effect = Repository.DoesNotExist + pr_comment.comment_workflow() + + mock_issues.return_value = [ + {"group_id": g.id, "event_count": 10} for g in Group.objects.all() + ] + + assert mock_issues.called + assert not mock_format_comment.called + + @patch( + "sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count", + ) + @patch("sentry.tasks.integrations.github.pr_comment.format_comment") + @with_feature("organizations:pr-comment-bot") + def test_comment_workflow_missing_integration(self, mock_format_comment, mock_issues): + self.create_pr_issues() + + # invalid integration id + self.gh_repo.integration_id = 0 + self.gh_repo.save() + + mock_issues.return_value = [ + {"group_id": g.id, "event_count": 10} for g in Group.objects.all() + ] + + pr_comment.comment_workflow() + + assert mock_issues.called + assert not mock_format_comment.called
a345807d94fa296eb035a987a1c64146cf21d2ee
2023-02-28 20:30:17
Colton Allen
bug(replays): Fix 500 error when marshaling tags field (#45097)
false
Fix 500 error when marshaling tags field (#45097)
bug
diff --git a/src/sentry/replays/query.py b/src/sentry/replays/query.py index 128a0b810efbab..365be895354075 100644 --- a/src/sentry/replays/query.py +++ b/src/sentry/replays/query.py @@ -558,7 +558,7 @@ def _activity_score(): "browser": ["browser_name", "browser_version"], "device": ["device_name", "device_brand", "device_family", "device_model"], "sdk": ["sdk_name", "sdk_version"], - "tags": ["tags.key", "tags.value"], + "tags": ["tk", "tv"], # Nested fields. Useful for selecting searchable fields. "user.id": ["user_id"], "user.email": ["user_email"], diff --git a/tests/sentry/replays/test_organization_replay_index.py b/tests/sentry/replays/test_organization_replay_index.py index 8462a4ef1cb096..a906360c0d1c24 100644 --- a/tests/sentry/replays/test_organization_replay_index.py +++ b/tests/sentry/replays/test_organization_replay_index.py @@ -157,6 +157,48 @@ def test_get_replays_browse_screen_fields(self): assert "ip" in response_data["data"][0]["user"] assert "display_name" in response_data["data"][0]["user"] + def test_get_replays_tags_field(self): + """Test replay response with fields requested in production.""" + project = self.create_project(teams=[self.team]) + + replay1_id = uuid.uuid4().hex + seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=22) + seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=5) + self.store_replays( + mock_replay( + seq1_timestamp, + project.id, + replay1_id, + urls=[ + "http://localhost:3000/", + "http://localhost:3000/login", + ], + tags={"test": "hello", "other": "hello"}, + ) + ) + self.store_replays( + mock_replay( + seq2_timestamp, + project.id, + replay1_id, + urls=["http://localhost:3000/"], + tags={"test": "world", "other": "hello"}, + ) + ) + + with self.feature(REPLAYS_FEATURES): + response = self.client.get(self.url + "?field=tags") + assert response.status_code == 200 + + response_data = response.json() + assert "data" in response_data + assert len(response_data["data"]) == 1 + + assert len(response_data["data"][0]) == 1 + assert "tags" in response_data["data"][0] + assert response_data["data"][0]["tags"]["test"] == ["world", "hello"] + assert response_data["data"][0]["tags"]["other"] == ["hello"] + def test_get_replays_minimum_field_set(self): """Test replay response with fields requested in production.""" project = self.create_project(teams=[self.team])
b0bdef0a2359f76074ba711f252faec9ee64585b
2022-11-16 23:14:22
Jonas
feat(profiling): add inline indicator to tooltip (#41397)
false
add inline indicator to tooltip (#41397)
feat
diff --git a/static/app/components/profiling/FlamegraphTooltip/flamegraphTooltip.tsx b/static/app/components/profiling/FlamegraphTooltip/flamegraphTooltip.tsx index 60a85754b02182..3418f48cc5a652 100644 --- a/static/app/components/profiling/FlamegraphTooltip/flamegraphTooltip.tsx +++ b/static/app/components/profiling/FlamegraphTooltip/flamegraphTooltip.tsx @@ -2,6 +2,7 @@ import {Fragment} from 'react'; import styled from '@emotion/styled'; import {vec2} from 'gl-matrix'; +import {IconLightning} from 'sentry/icons'; import {t} from 'sentry/locale'; import space from 'sentry/styles/space'; import {defined} from 'sentry/utils'; @@ -22,6 +23,19 @@ export function formatWeightToProfileDuration( return `(${Math.round((frame.totalWeight / flamegraph.profile.duration) * 100)}%)`; } +function formatFileNameAndLineColumn(frame: FlamegraphFrame): string | null { + if (!frame.frame.file) { + return '<unknown file>'; + } + if (typeof frame.frame.line === 'number' && typeof frame.frame.column === 'number') { + return `${frame.frame.file}:${frame.frame.line}:${frame.frame.column}`; + } + if (typeof frame.frame.line === 'number') { + return `${frame.frame.file}:${frame.frame.line}`; + } + return `${frame.frame.file}:<unknown line>`; +} + export interface FlamegraphTooltipProps { canvasBounds: Rect; configSpaceCursor: vec2; @@ -52,21 +66,47 @@ export function FlamegraphTooltip(props: FlamegraphTooltipProps) { )}{' '} {props.frame.frame.name} </FlamegraphTooltipFrameMainInfo> - {defined(props.frame.frame.file) && ( - <FlamegraphTooltipTimelineInfo> - {props.frame.frame.file}:{props.frame.frame.line ?? t('<unknown line>')} - </FlamegraphTooltipTimelineInfo> - )} + <FlamegraphTooltipTimelineInfo> + {defined(props.frame.frame.file) && ( + <Fragment> + {t('source')}:{formatFileNameAndLineColumn(props.frame)} + </Fragment> + )} + </FlamegraphTooltipTimelineInfo> <FlamegraphTooltipTimelineInfo> {props.flamegraphRenderer.flamegraph.timelineFormatter(props.frame.start)}{' '} {' \u2014 '} {props.flamegraphRenderer.flamegraph.timelineFormatter(props.frame.end)} + {props.frame.frame.inline ? ( + <FlamegraphInlineIndicator> + <IconLightning width={10} /> + {t('inline frame')} + </FlamegraphInlineIndicator> + ) : ( + '' + )} </FlamegraphTooltipTimelineInfo> </Fragment> </BoundTooltip> ); } +const FlamegraphInlineIndicator = styled('span')` + border: 1px solid ${p => p.theme.border}; + border-radius: ${p => p.theme.borderRadius}; + font-size: ${p => p.theme.fontSizeExtraSmall}; + padding: ${space(0.25)} ${space(0.25)}; + line-height: 12px; + margin: 0 ${space(0.5)}; + align-self: flex-end; + + svg { + width: 10px; + height: 10px; + transform: translateY(1px); + } +`; + export const FlamegraphTooltipTimelineInfo = styled('div')` color: ${p => p.theme.subText}; `; diff --git a/static/app/types/profiling.d.ts b/static/app/types/profiling.d.ts index 20b49e1c0420f5..75715ae947a926 100644 --- a/static/app/types/profiling.d.ts +++ b/static/app/types/profiling.d.ts @@ -120,6 +120,7 @@ declare namespace Profiling { image?: string; resource?: string; threadId?: number; + inline?: boolean; // nodejs only columnNumber?: number; diff --git a/static/app/utils/profiling/frame.tsx b/static/app/utils/profiling/frame.tsx index d1a6b7951f9753..fb7603272f43a3 100644 --- a/static/app/utils/profiling/frame.tsx +++ b/static/app/utils/profiling/frame.tsx @@ -12,6 +12,7 @@ export class Frame extends WeightedNode { readonly image?: string; readonly resource?: string; readonly threadId?: number; + readonly inline?: boolean; static Root = new Frame( { @@ -34,6 +35,7 @@ export class Frame extends WeightedNode { this.is_application = !!frameInfo.is_application; this.image = frameInfo.image; this.threadId = frameInfo.threadId; + this.inline = frameInfo.inline || false; // We are remapping some of the keys as they differ between platforms. // This is a temporary solution until we adopt a unified format.
dc214d2b860ce83215ef3fca245163491577e3cd
2023-11-28 22:05:30
Kev
fix(perf): Add offset back to tag faceting (#60545)
false
Add offset back to tag faceting (#60545)
fix
diff --git a/src/sentry/api/endpoints/organization_events_facets_performance.py b/src/sentry/api/endpoints/organization_events_facets_performance.py index df1ad471798f96..2f672e88f047bc 100644 --- a/src/sentry/api/endpoints/organization_events_facets_performance.py +++ b/src/sentry/api/endpoints/organization_events_facets_performance.py @@ -408,6 +408,7 @@ def query_facet_performance( sample_rate=sample_rate, turbo=sample_rate is not None, limit=limit, + offset=offset, limitby=["tags_key", tag_key_limit] if not tag_key else None, ) translated_aggregate_column = tag_query.resolve_column(aggregate_column) diff --git a/tests/snuba/api/endpoints/test_organization_events_facets_performance.py b/tests/snuba/api/endpoints/test_organization_events_facets_performance.py index 0d52e9190a67c2..71a8c409098b9e 100644 --- a/tests/snuba/api/endpoints/test_organization_events_facets_performance.py +++ b/tests/snuba/api/endpoints/test_organization_events_facets_performance.py @@ -271,3 +271,39 @@ def test_aggregate_zero(self): assert data[0]["comparison"] == 0 assert data[0]["tags_key"] == "color" assert data[0]["tags_value"] == "purple" + + def test_cursor(self): + self.store_transaction(tags=[["third_tag", "good"]], duration=1000) + self.store_transaction(tags=[["third_tag", "bad"]], duration=10000) + + request = { + "aggregateColumn": "transaction.duration", + "sort": "-frequency", + "per_page": 2, + "cursor": "0:0:0", + } + + response = self.do_request(request) + assert response.status_code == 200, response.content + data = response.data["data"] + assert len(data) == 2 + assert data[0]["tags_key"] == "color" + assert data[0]["count"] == 5 + assert data[1]["tags_key"] == "many" + assert data[1]["count"] == 1 + + request["cursor"] = "0:2:0" + response = self.do_request(request) + assert response.status_code == 200, response.content + data = response.data["data"] + # Only 1 key in this page + assert len(data) == 1 + assert data[0]["tags_key"] == "third_tag" + assert data[0]["count"] == 1 + + request["cursor"] = "0:4:0" + response = self.do_request(request) + assert response.status_code == 200, response.content + data = response.data["data"] + # 0 keys, past all 3 tag keys stored. + assert len(data) == 0
8d42c3aa73fa6985c08e6573ea6a8422f67f5bc5
2021-04-16 13:25:19
Evan Purkhiser
fix(u2fa): Don't try and send so much data (#25312)
false
Don't try and send so much data (#25312)
fix
diff --git a/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.tsx b/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.tsx index 03e583a3b88819..f540ca7928d7bd 100644 --- a/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.tsx +++ b/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.tsx @@ -254,7 +254,7 @@ class AccountSecurityEnroll extends AsyncView<Props, State> { // Handle u2f device tap handleU2fTap = async (tapData: any) => { - const data = {...tapData, ...Object.fromEntries(this.formModel.fields.toJSON())}; + const data = {deviceName: this.formModel.getValue('deviceName'), ...tapData}; this.setState({loading: true});
f64a9765bbfff0d97b2e94569c1a8bc3b0fc767c
2024-03-06 01:51:05
Seiji Chew
fix(staff): Set access by calling parent method before checking staff (#66266)
false
Set access by calling parent method before checking staff (#66266)
fix
diff --git a/src/sentry/api/permissions.py b/src/sentry/api/permissions.py index afba82240fecaf..333fb579833cc6 100644 --- a/src/sentry/api/permissions.py +++ b/src/sentry/api/permissions.py @@ -78,16 +78,36 @@ class (that is not StaffPermission) require this mixin because staff does not gi staff_allowed_methods = {"GET", "POST", "PUT", "DELETE"} def has_permission(self, request, *args, **kwargs) -> bool: - # Check for staff before calling super to avoid catching exceptions from super - if request.method in self.staff_allowed_methods and is_active_staff(request): + """ + Calls the parent class's has_permission method. If it returns False or + raises an exception and the method is allowed by the mixin, we then check + if the request is from an active staff. Raised exceptions are not caught + if the request is not allowed by the mixin or from an active staff. + """ + try: + if super().has_permission(request, *args, **kwargs): + return True + except Exception: + if not (request.method in self.staff_allowed_methods and is_active_staff(request)): + raise return True - return super().has_permission(request, *args, **kwargs) + return request.method in self.staff_allowed_methods and is_active_staff(request) def has_object_permission(self, request, *args, **kwargs) -> bool: - # Check for staff before calling super to avoid catching exceptions from super - if request.method in self.staff_allowed_methods and is_active_staff(request): + """ + Calls the parent class's has_object_permission method. If it returns False or + raises an exception and the method is allowed by the mixin, we then check + if the request is from an active staff. Raised exceptions are not caught + if the request is not allowed by the mixin or from an active staff. + """ + try: + if super().has_object_permission(request, *args, **kwargs): + return True + except Exception: + if not (request.method in self.staff_allowed_methods and is_active_staff(request)): + raise return True - return super().has_object_permission(request, *args, **kwargs) + return request.method in self.staff_allowed_methods and is_active_staff(request) def is_not_2fa_compliant(self, request, *args, **kwargs) -> bool: return super().is_not_2fa_compliant(request, *args, **kwargs) and not is_active_staff(
88cc7c6bb28de86749dd80bcce1dff50badaf675
2023-02-23 21:54:00
Tony Xiao
chore(profiling): Add alias for profile.id (#45001)
false
Add alias for profile.id (#45001)
chore
diff --git a/src/sentry/search/events/datasets/profiles.py b/src/sentry/search/events/datasets/profiles.py index 3103b6137fccf9..75ffe3063e2d25 100644 --- a/src/sentry/search/events/datasets/profiles.py +++ b/src/sentry/search/events/datasets/profiles.py @@ -65,6 +65,7 @@ class Column: Column(alias="project.id", column="project_id", kind=Kind.INTEGER), Column(alias="trace.transaction", column="transaction_id", kind=Kind.STRING), Column(alias="id", column="profile_id", kind=Kind.STRING), + Column(alias="profile.id", column="profile_id", kind=Kind.STRING), Column(alias="timestamp", column="received", kind=Kind.DATE), Column(alias="device.arch", column="architecture", kind=Kind.STRING), Column(alias="device.classification", column="device_classification", kind=Kind.STRING),
cae3d9d9ca6c34a3159ce043dd59ec58fd60610e
2023-01-26 04:08:02
Cathy Teng
ref(hybrid-cloud): test for both urls in MonitorCheckinDetails (#43690)
false
test for both urls in MonitorCheckinDetails (#43690)
ref
diff --git a/tests/sentry/api/endpoints/test_monitor_checkin_details.py b/tests/sentry/api/endpoints/test_monitor_checkin_details.py index 3b7c7ed1fd4556..939f1d6e69c6fc 100644 --- a/tests/sentry/api/endpoints/test_monitor_checkin_details.py +++ b/tests/sentry/api/endpoints/test_monitor_checkin_details.py @@ -1,5 +1,6 @@ from datetime import timedelta +from django.urls import reverse from django.utils import timezone from sentry.models import CheckInStatus, Monitor, MonitorCheckIn, MonitorStatus, MonitorType @@ -10,14 +11,24 @@ @region_silo_test(stable=True) class UpdateMonitorCheckInTest(APITestCase): endpoint = "sentry-api-0-monitor-check-in-details" - method = "put" + endpoint_with_org = "sentry-api-0-monitor-check-in-details-with-org" def setUp(self): super().setUp() self.login_as(self.user) + self.latest = lambda: None + self.latest.guid = "latest" + + def _get_path_functions(self): + return ( + lambda monitor, checkin: reverse(self.endpoint, args=[monitor.guid, checkin.guid]), + lambda monitor, checkin: reverse( + self.endpoint_with_org, args=[self.organization.slug, monitor.guid, checkin.guid] + ), + ) - def test_noop_in_progerss(self): - monitor = Monitor.objects.create( + def _create_monitor(self): + return Monitor.objects.create( organization_id=self.organization.id, project_id=self.project.id, next_checkin=timezone.now() - timedelta(minutes=1), @@ -25,122 +36,113 @@ def test_noop_in_progerss(self): config={"schedule": "* * * * *"}, date_added=timezone.now() - timedelta(minutes=1), ) - checkin = MonitorCheckIn.objects.create( - monitor=monitor, - project_id=self.project.id, - date_added=monitor.date_added, - status=CheckInStatus.IN_PROGRESS, - ) - self.get_success_response(monitor.guid, checkin.guid) + def test_noop_in_progress(self): + for path_func in self._get_path_functions(): + monitor = self._create_monitor() + checkin = MonitorCheckIn.objects.create( + monitor=monitor, + project_id=self.project.id, + date_added=monitor.date_added, + status=CheckInStatus.IN_PROGRESS, + ) - checkin = MonitorCheckIn.objects.get(id=checkin.id) - assert checkin.status == CheckInStatus.IN_PROGRESS - assert checkin.date_updated > checkin.date_added + path = path_func(monitor, checkin) + resp = self.client.put(path) + assert resp.status_code == 200, resp.content + + checkin = MonitorCheckIn.objects.get(id=checkin.id) + assert checkin.status == CheckInStatus.IN_PROGRESS + assert checkin.date_updated > checkin.date_added def test_passing(self): - monitor = Monitor.objects.create( - organization_id=self.organization.id, - project_id=self.project.id, - next_checkin=timezone.now() - timedelta(minutes=1), - type=MonitorType.CRON_JOB, - config={"schedule": "* * * * *"}, - date_added=timezone.now() - timedelta(minutes=1), - ) - checkin = MonitorCheckIn.objects.create( - monitor=monitor, project_id=self.project.id, date_added=monitor.date_added - ) + for path_func in self._get_path_functions(): + monitor = self._create_monitor() + checkin = MonitorCheckIn.objects.create( + monitor=monitor, project_id=self.project.id, date_added=monitor.date_added + ) - self.get_success_response(monitor.guid, checkin.guid, status="ok") + path = path_func(monitor, checkin) + resp = self.client.put(path, data={"status": "ok"}) + assert resp.status_code == 200, resp.content - checkin = MonitorCheckIn.objects.get(id=checkin.id) - assert checkin.status == CheckInStatus.OK + checkin = MonitorCheckIn.objects.get(id=checkin.id) + assert checkin.status == CheckInStatus.OK - monitor = Monitor.objects.get(id=monitor.id) - assert monitor.next_checkin > checkin.date_added - assert monitor.status == MonitorStatus.OK - assert monitor.last_checkin > checkin.date_added + monitor = Monitor.objects.get(id=monitor.id) + assert monitor.next_checkin > checkin.date_added + assert monitor.status == MonitorStatus.OK + assert monitor.last_checkin > checkin.date_added def test_failing(self): - monitor = Monitor.objects.create( - organization_id=self.organization.id, - project_id=self.project.id, - next_checkin=timezone.now() - timedelta(minutes=1), - type=MonitorType.CRON_JOB, - config={"schedule": "* * * * *"}, - date_added=timezone.now() - timedelta(minutes=1), - ) - checkin = MonitorCheckIn.objects.create( - monitor=monitor, project_id=self.project.id, date_added=monitor.date_added - ) + for path_func in self._get_path_functions(): + monitor = self._create_monitor() + checkin = MonitorCheckIn.objects.create( + monitor=monitor, project_id=self.project.id, date_added=monitor.date_added + ) - self.get_success_response(monitor.guid, checkin.guid, status="error") + path = path_func(monitor, checkin) + resp = self.client.put(path, data={"status": "error"}) + assert resp.status_code == 200, resp.content - checkin = MonitorCheckIn.objects.get(id=checkin.id) - assert checkin.status == CheckInStatus.ERROR + checkin = MonitorCheckIn.objects.get(id=checkin.id) + assert checkin.status == CheckInStatus.ERROR - monitor = Monitor.objects.get(id=monitor.id) - assert monitor.next_checkin > checkin.date_added - assert monitor.status == MonitorStatus.ERROR - assert monitor.last_checkin > checkin.date_added + monitor = Monitor.objects.get(id=monitor.id) + assert monitor.next_checkin > checkin.date_added + assert monitor.status == MonitorStatus.ERROR + assert monitor.last_checkin > checkin.date_added def test_latest_returns_last_unfinished(self): - monitor = Monitor.objects.create( - organization_id=self.organization.id, - project_id=self.project.id, - next_checkin=timezone.now() - timedelta(minutes=1), - type=MonitorType.CRON_JOB, - config={"schedule": "* * * * *"}, - date_added=timezone.now() - timedelta(minutes=1), - ) - checkin = MonitorCheckIn.objects.create( - monitor=monitor, - project_id=self.project.id, - date_added=monitor.date_added - timedelta(minutes=2), - status=CheckInStatus.IN_PROGRESS, - ) - checkin2 = MonitorCheckIn.objects.create( - monitor=monitor, - project_id=self.project.id, - date_added=monitor.date_added - timedelta(minutes=1), - status=CheckInStatus.IN_PROGRESS, - ) - checkin3 = MonitorCheckIn.objects.create( - monitor=monitor, - project_id=self.project.id, - date_added=monitor.date_added, - status=CheckInStatus.OK, - ) - self.get_success_response(monitor.guid, "latest", status="ok") - - checkin = MonitorCheckIn.objects.get(id=checkin.id) - assert checkin.status == CheckInStatus.IN_PROGRESS - - checkin2 = MonitorCheckIn.objects.get(id=checkin2.id) - assert checkin2.status == CheckInStatus.OK - - checkin3 = MonitorCheckIn.objects.get(id=checkin3.id) - assert checkin3.status == CheckInStatus.OK - - monitor = Monitor.objects.get(id=monitor.id) - assert monitor.next_checkin > checkin2.date_added - assert monitor.status == MonitorStatus.OK - assert monitor.last_checkin > checkin2.date_added + for path_func in self._get_path_functions(): + monitor = self._create_monitor() + checkin = MonitorCheckIn.objects.create( + monitor=monitor, + project_id=self.project.id, + date_added=monitor.date_added - timedelta(minutes=2), + status=CheckInStatus.IN_PROGRESS, + ) + checkin2 = MonitorCheckIn.objects.create( + monitor=monitor, + project_id=self.project.id, + date_added=monitor.date_added - timedelta(minutes=1), + status=CheckInStatus.IN_PROGRESS, + ) + checkin3 = MonitorCheckIn.objects.create( + monitor=monitor, + project_id=self.project.id, + date_added=monitor.date_added, + status=CheckInStatus.OK, + ) + + path = path_func(monitor, self.latest) + resp = self.client.put(path, data={"status": "ok"}) + assert resp.status_code == 200, resp.content + + checkin = MonitorCheckIn.objects.get(id=checkin.id) + assert checkin.status == CheckInStatus.IN_PROGRESS + + checkin2 = MonitorCheckIn.objects.get(id=checkin2.id) + assert checkin2.status == CheckInStatus.OK + + checkin3 = MonitorCheckIn.objects.get(id=checkin3.id) + assert checkin3.status == CheckInStatus.OK + + monitor = Monitor.objects.get(id=monitor.id) + assert monitor.next_checkin > checkin2.date_added + assert monitor.status == MonitorStatus.OK + assert monitor.last_checkin > checkin2.date_added def test_latest_with_no_unfinished_checkin(self): - monitor = Monitor.objects.create( - organization_id=self.organization.id, - project_id=self.project.id, - next_checkin=timezone.now() - timedelta(minutes=1), - type=MonitorType.CRON_JOB, - config={"schedule": "* * * * *"}, - date_added=timezone.now() - timedelta(minutes=1), - ) - MonitorCheckIn.objects.create( - monitor=monitor, - project_id=self.project.id, - date_added=monitor.date_added, - status=CheckInStatus.OK, - ) - - self.get_error_response(monitor.guid, "latest", status="ok") + for path_func in self._get_path_functions(): + monitor = self._create_monitor() + MonitorCheckIn.objects.create( + monitor=monitor, + project_id=self.project.id, + date_added=monitor.date_added, + status=CheckInStatus.OK, + ) + + path = path_func(monitor, self.latest) + resp = self.client.put(path, data={"status": "ok"}) + assert resp.status_code == 404, resp.content
fb83c3185d9ae3fe760795ad701441979267004e
2024-12-11 03:15:56
Athena Moghaddam
fix(oauth): only remove the related tokens (#81677)
false
only remove the related tokens (#81677)
fix
diff --git a/src/sentry/api/endpoints/api_authorizations.py b/src/sentry/api/endpoints/api_authorizations.py index c8daaad0b88755..3013e0dca904b1 100644 --- a/src/sentry/api/endpoints/api_authorizations.py +++ b/src/sentry/api/endpoints/api_authorizations.py @@ -50,7 +50,9 @@ def delete(self, request: Request) -> Response: with outbox_context(transaction.atomic(using=router.db_for_write(ApiToken)), flush=False): for token in ApiToken.objects.filter( - user_id=request.user.id, application=auth.application_id + user_id=request.user.id, + application=auth.application_id, + scoping_organization_id=auth.organization_id, ): token.delete() diff --git a/tests/sentry/api/endpoints/test_api_authorizations.py b/tests/sentry/api/endpoints/test_api_authorizations.py index 0f5b7a73fb7dc8..da1034b0de1ebc 100644 --- a/tests/sentry/api/endpoints/test_api_authorizations.py +++ b/tests/sentry/api/endpoints/test_api_authorizations.py @@ -51,3 +51,29 @@ def test_simple(self): self.get_success_response(authorization=auth.id, status_code=204) assert not ApiAuthorization.objects.filter(id=auth.id).exists() assert not ApiToken.objects.filter(id=token.id).exists() + + def test_with_org(self): + org1 = self.organization + org2 = self.create_organization(owner=self.user, slug="test-org-2") + app_with_org = ApiApplication.objects.create( + name="test-app", owner=self.user, requires_org_level_access=True + ) + org1_auth = ApiAuthorization.objects.create( + application=app_with_org, user=self.user, organization_id=org1.id + ) + org2_auth = ApiAuthorization.objects.create( + application=app_with_org, user=self.user, organization_id=org2.id + ) + org1_token = ApiToken.objects.create( + application=app_with_org, user=self.user, scoping_organization_id=org1.id + ) + org2_token = ApiToken.objects.create( + application=app_with_org, user=self.user, scoping_organization_id=org2.id + ) + + self.get_success_response(authorization=org1_auth.id, status_code=204) + assert not ApiAuthorization.objects.filter(id=org1_auth.id).exists() + assert not ApiToken.objects.filter(id=org1_token.id).exists() + + assert ApiAuthorization.objects.filter(id=org2_auth.id).exists() + assert ApiToken.objects.filter(id=org2_token.id).exists()
94f16caa057db2db4480f4d21df659408576bb3d
2021-04-01 04:52:50
Evan Purkhiser
ref(charts): Refactor + Add discover chartcuterie types (#24874)
false
Refactor + Add discover chartcuterie types (#24874)
ref
diff --git a/config/webpack.chartcuterie.config.js b/config/webpack.chartcuterie.config.js index 48a0ed28e84a33..1fb4b31eaddaa3 100644 --- a/config/webpack.chartcuterie.config.js +++ b/config/webpack.chartcuterie.config.js @@ -21,7 +21,7 @@ const config = { target: 'node', entry: { - config: 'app/chartcuterieConfig', + config: 'app/chartcuterie/config', }, module: { diff --git a/docs-ui/components/charts-chartcuterie.stories.js b/docs-ui/components/charts-chartcuterie.stories.js index 0539ab876939a0..acef13d082daad 100644 --- a/docs-ui/components/charts-chartcuterie.stories.js +++ b/docs-ui/components/charts-chartcuterie.stories.js @@ -3,7 +3,8 @@ import styled from '@emotion/styled'; import echarts from 'echarts/lib/echarts'; import ReactEchartsCore from 'echarts-for-react/lib/core'; -import config, {ChartType} from 'app/chartcuterieConfig'; +import config from 'app/chartcuterie/config'; +import {ChartType} from 'app/chartcuterie/types'; import {getDimensionValue} from 'app/components/charts/utils'; import space from 'app/styles/space'; @@ -55,7 +56,134 @@ export const _SlackDiscoverTotalPeriod = () => { width: getDimensionValue(width), }} opts={{height, width, renderer: 'canvas'}} - option={getOption(data)} + option={getOption({seriesName: 'count()', stats: {data}})} + /> + </Container> + ); +}; + +export const _SlackDiscoverTotalDaily = () => { + const data = [ + [1615852800, [{count: 2426486}]], + [1615939200, [{count: 18837228}]], + [1616025600, [{count: 14662530}]], + [1616112000, [{count: 15102981}]], + [1616198400, [{count: 7759228}]], + [1616284800, [{count: 7216556}]], + [1616371200, [{count: 16976035}]], + [1616457600, [{count: 17240832}]], + [1616544000, [{count: 16814701}]], + [1616630400, [{count: 17480989}]], + [1616716800, [{count: 15387478}]], + [1616803200, [{count: 8467454}]], + [1616889600, [{count: 6382678}]], + [1616976000, [{count: 16842851}]], + [1617062400, [{count: 12959057}]], + ]; + + const {height, width, getOption} = renderConfig.get( + ChartType.SLACK_DISCOVER_TOTAL_DAILY + ); + + return ( + <Container> + <ReactEchartsCore + echarts={echarts} + style={{ + height: getDimensionValue(height), + width: getDimensionValue(width), + }} + opts={{height, width, renderer: 'canvas'}} + option={getOption({seriesName: 'count()', stats: {data}})} + /> + </Container> + ); +}; + +export const _SlackDiscoverTop5 = () => { + const stats = { + 'ludic-science,1st event': { + data: [ + [1615877940, [{count: 0}]], + [1615878000, [{count: 0}]], + [1615878060, [{count: 0}]], + [1615878120, [{count: 0}]], + [1615878180, [{count: 1}]], + [1615878240, [{count: 1}]], + [1615878300, [{count: 1}]], + [1615878360, [{count: 1}]], + [1615878420, [{count: 1}]], + [1615878480, [{count: 1}]], + [1615878540, [{count: 1}]], + [1615878600, [{count: 1}]], + [1615878660, [{count: 1}]], + [1615878720, [{count: 1}]], + [1615878780, [{count: 1}]], + [1615878840, [{count: 1}]], + [1615878900, [{count: 1}]], + [1615878960, [{count: 1}]], + [1615879020, [{count: 1}]], + [1615879080, [{count: 1}]], + [1615879140, [{count: 1}]], + [1615879200, [{count: 1}]], + [1615879260, [{count: 1}]], + [1615879320, [{count: 1}]], + [1615879380, [{count: 0}]], + [1615879440, [{count: 0}]], + [1615879500, [{count: 0}]], + [1615879560, [{count: 0}]], + [1615879620, [{count: 0}]], + ], + order: 0, + }, + 'ludic-science,2nd event': { + data: [ + [1615877940, [{count: 0}]], + [1615878000, [{count: 0}]], + [1615878060, [{count: 0}]], + [1615878120, [{count: 0}]], + [1615878180, [{count: 1}]], + [1615878240, [{count: 1}]], + [1615878300, [{count: 1}]], + [1615878360, [{count: 1}]], + [1615878420, [{count: 1}]], + [1615878480, [{count: 1}]], + [1615878540, [{count: 1}]], + [1615878600, [{count: 1}]], + [1615878660, [{count: 1}]], + [1615878720, [{count: 1}]], + [1615878780, [{count: 1}]], + [1615878840, [{count: 1}]], + [1615878900, [{count: 1}]], + [1615878960, [{count: 1}]], + [1615879020, [{count: 1}]], + [1615879080, [{count: 1}]], + [1615879140, [{count: 1}]], + [1615879200, [{count: 1}]], + [1615879260, [{count: 1}]], + [1615879320, [{count: 1}]], + [1615879380, [{count: 0}]], + [1615879440, [{count: 0}]], + [1615879500, [{count: 0}]], + [1615879560, [{count: 0}]], + [1615879620, [{count: 0}]], + ], + order: 1, + }, + }; + + const {height, width, getOption} = renderConfig.get(ChartType.SLACK_DISCOVER_TOP5); + + return ( + <Container> + <ReactEchartsCore + echarts={echarts} + style={{ + height: getDimensionValue(height), + width: getDimensionValue(width), + }} + opts={{height, width, renderer: 'canvas'}} + option={getOption({stats})} /> </Container> ); diff --git a/src/sentry/charts/types.py b/src/sentry/charts/types.py index 7b9119534be085..4679d3e78212a2 100644 --- a/src/sentry/charts/types.py +++ b/src/sentry/charts/types.py @@ -8,7 +8,10 @@ class ChartType(Enum): This directly maps to the chartcuterie configuration [0] in the frontend code. Be sure to keep these in sync when adding or removing types. - [0]: app/chartcuterieConfig.tsx. + [0]: app/chartcuterie/config.tsx. """ SLACK_DISCOVER_TOTAL_PERIOD = "slack:discover.totalPeriod" + SLACK_DISCOVER_TOTAL_DAILY = "slack:discover.totalDaily" + SLACK_DISCOVER_TOP5_PERIOD = "slack:discover.top5Period" + SLACK_DISCOVER_TOP5_DAILY = "slack:discover.top5Daily" diff --git a/src/sentry/static/sentry/app/chartcuterie/config.tsx b/src/sentry/static/sentry/app/chartcuterie/config.tsx new file mode 100644 index 00000000000000..084a13a8c1533b --- /dev/null +++ b/src/sentry/static/sentry/app/chartcuterie/config.tsx @@ -0,0 +1,35 @@ +/* global process */ + +/** + * This module is used to define the look and feels for charts rendered via the + * backend chart rendering service Chartcuterie. + * + * Be careful what you import into this file, as it will end up being bundled + * into the configuration file loaded by the service. + */ + +import {discoverCharts} from './discover'; +import {ChartcuterieConfig, ChartType, RenderConfig, RenderDescriptor} from './types'; + +/** + * All registered style descriptors + */ +const renderConfig: RenderConfig<ChartType> = new Map(); + +/** + * Chartcuterie configuration object + */ +const config: ChartcuterieConfig = { + version: process.env.COMMIT_SHA!, + renderConfig, +}; + +/** + * Register a style descriptor + */ +const register = (renderDescriptor: RenderDescriptor<ChartType>) => + renderConfig.set(renderDescriptor.key, renderDescriptor); + +discoverCharts.forEach(register); + +export default config; diff --git a/src/sentry/static/sentry/app/chartcuterie/discover.tsx b/src/sentry/static/sentry/app/chartcuterie/discover.tsx new file mode 100644 index 00000000000000..be84064c27b175 --- /dev/null +++ b/src/sentry/static/sentry/app/chartcuterie/discover.tsx @@ -0,0 +1,131 @@ +import XAxis from 'app/components/charts/components/xAxis'; +import AreaSeries from 'app/components/charts/series/areaSeries'; +import BarSeries from 'app/components/charts/series/barSeries'; +import {EventsStats} from 'app/types'; +import {lightTheme as theme} from 'app/utils/theme'; + +import {slackChartDefaults, slackChartSize} from './slack'; +import {ChartType, RenderDescriptor} from './types'; + +const discoverxAxis = XAxis({ + theme, + boundaryGap: true, + splitNumber: 3, + isGroupedByDate: true, + axisLabel: {fontSize: 11}, +}); + +export const discoverCharts: RenderDescriptor<ChartType>[] = []; + +discoverCharts.push({ + key: ChartType.SLACK_DISCOVER_TOTAL_PERIOD, + getOption: (data: {seriesName: string; stats: EventsStats}) => { + const color = theme.charts.getColorPalette(data.stats.data.length - 2); + + const areaSeries = AreaSeries({ + name: data.seriesName, + data: data.stats.data.map(([timestamp, countsForTimestamp]) => [ + timestamp * 1000, + countsForTimestamp.reduce((acc, {count}) => acc + count, 0), + ]), + lineStyle: {color: color?.[0], opacity: 1, width: 0.4}, + areaStyle: {color: color?.[0], opacity: 1}, + }); + + return { + ...slackChartDefaults, + useUTC: true, + color, + series: [areaSeries], + }; + }, + ...slackChartSize, +}); + +discoverCharts.push({ + key: ChartType.SLACK_DISCOVER_TOTAL_DAILY, + getOption: (data: {seriesName: string; stats: EventsStats}) => { + const color = theme.charts.getColorPalette(data.stats.data.length - 2); + + const barSeries = BarSeries({ + name: data.seriesName, + data: data.stats.data.map(([timestamp, countsForTimestamp]) => ({ + value: [ + timestamp * 1000, + countsForTimestamp.reduce((acc, {count}) => acc + count, 0), + ], + })), + itemStyle: {color: color?.[0], opacity: 1}, + }); + + return { + ...slackChartDefaults, + xAxis: discoverxAxis, + useUTC: true, + color, + series: [barSeries], + }; + }, + ...slackChartSize, +}); + +discoverCharts.push({ + key: ChartType.SLACK_DISCOVER_TOP5_PERIOD, + getOption: (data: {stats: Record<string, EventsStats>}) => { + const stats = Object.values(data.stats); + const color = theme.charts.getColorPalette(stats.length - 2); + + const series = stats + .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) + .map((topSeries, i) => + AreaSeries({ + stack: 'area', + data: topSeries.data.map(([timestamp, countsForTimestamp]) => [ + timestamp * 1000, + countsForTimestamp.reduce((acc, {count}) => acc + count, 0), + ]), + lineStyle: {color: color?.[i], opacity: 1, width: 0.4}, + areaStyle: {color: color?.[i], opacity: 1}, + }) + ); + + return { + ...slackChartDefaults, + xAxis: discoverxAxis, + useUTC: true, + color, + series, + }; + }, + ...slackChartSize, +}); + +discoverCharts.push({ + key: ChartType.SLACK_DISCOVER_TOP5_DAILY, + getOption: (data: {stats: Record<string, EventsStats>}) => { + const stats = Object.values(data.stats); + const color = theme.charts.getColorPalette(stats.length - 2); + + const series = stats + .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) + .map((topSeries, i) => + BarSeries({ + stack: 'area', + data: topSeries.data.map(([timestamp, countsForTimestamp]) => [ + timestamp * 1000, + countsForTimestamp.reduce((acc, {count}) => acc + count, 0), + ]), + itemStyle: {color: color?.[i], opacity: 1}, + }) + ); + + return { + ...slackChartDefaults, + xAxis: discoverxAxis, + useUTC: true, + color, + series, + }; + }, + ...slackChartSize, +}); diff --git a/src/sentry/static/sentry/app/chartcuterie/slack.tsx b/src/sentry/static/sentry/app/chartcuterie/slack.tsx new file mode 100644 index 00000000000000..42a5a685c1e645 --- /dev/null +++ b/src/sentry/static/sentry/app/chartcuterie/slack.tsx @@ -0,0 +1,24 @@ +import Grid from 'app/components/charts/components/grid'; +import Legend from 'app/components/charts/components/legend'; +import XAxis from 'app/components/charts/components/xAxis'; +import YAxis from 'app/components/charts/components/yAxis'; +import {lightTheme as theme} from 'app/utils/theme'; + +/** + * Size configuration for SLACK_* type charts + */ +export const slackChartSize = { + height: 150, + width: 450, +}; + +/** + * Default echarts option config for slack charts + */ +export const slackChartDefaults = { + grid: Grid({left: 5, right: 5, bottom: 5}), + backgroundColor: theme.background, + legend: Legend({theme, itemHeight: 6, top: 2, right: 10}), + yAxis: YAxis({theme, splitNumber: 3, axisLabel: {fontSize: 11}}), + xAxis: XAxis({theme, nameGap: 5, isGroupedByDate: true, axisLabel: {fontSize: 11}}), +}; diff --git a/src/sentry/static/sentry/app/types/chartcuterie.tsx b/src/sentry/static/sentry/app/chartcuterie/types.tsx similarity index 82% rename from src/sentry/static/sentry/app/types/chartcuterie.tsx rename to src/sentry/static/sentry/app/chartcuterie/types.tsx index b80514010a58fa..b81da6f1563f28 100644 --- a/src/sentry/static/sentry/app/types/chartcuterie.tsx +++ b/src/sentry/static/sentry/app/chartcuterie/types.tsx @@ -1,11 +1,25 @@ +import {EChartOption} from 'echarts'; + +/** + * Defines the keys which may be passed into the chartcuterie chart rendering + * service. + * + * When adding or removing from this list, please also update the + * sentry/charts/types.py file + */ +export enum ChartType { + SLACK_DISCOVER_TOTAL_PERIOD = 'slack:discover.totalPeriod', + SLACK_DISCOVER_TOTAL_DAILY = 'slack:discover.totalDaily', + SLACK_DISCOVER_TOP5_PERIOD = 'slack:discover.top5Period', + SLACK_DISCOVER_TOP5_DAILY = 'slack:discover.top5Daily', +} + /** * XXX(epurkhiser): These are copied directly over from chartucterie to avoid * installing the package, which has some system-level dependencies we would * prefer not to install with sentry. */ -import {EChartOption} from 'echarts'; - export type RenderOption = Omit<EChartOption, 'animation' | 'tooltip' | 'toolbox'>; /** diff --git a/src/sentry/static/sentry/app/chartcuterieConfig.tsx b/src/sentry/static/sentry/app/chartcuterieConfig.tsx deleted file mode 100644 index 6443dfd7e8e074..00000000000000 --- a/src/sentry/static/sentry/app/chartcuterieConfig.tsx +++ /dev/null @@ -1,102 +0,0 @@ -/* global process */ - -/** - * This module is used to define the look and feels for charts rendered via the - * backend chart rendering service Chartcuterie. - * - * Be careful what you import into this file, as it will end up being bundled - * into the configuration file loaded by the service. - */ - -import Grid from 'app/components/charts/components/grid'; -import Legend from 'app/components/charts/components/legend'; -import XAxis from 'app/components/charts/components/xAxis'; -import YAxis from 'app/components/charts/components/yAxis'; -import AreaSeries from 'app/components/charts/series/areaSeries'; -import {getColorPalette} from 'app/components/charts/utils'; -import {EventsStatsData} from 'app/types'; -import type { - ChartcuterieConfig, - RenderConfig, - RenderDescriptor, -} from 'app/types/chartcuterie'; -import {lightTheme as theme} from 'app/utils/theme'; - -/** - * Defines the keys which may be passed into the chartcuterie chart rendering - * service. - * - * When adding or removing from this list, please also update the - * sentry/charts/types.py file - */ -export enum ChartType { - SLACK_DISCOVER_TOTAL_PERIOD = 'slack:discover.totalPeriod', -} - -/** - * All registered style descriptors - */ -const renderConfig: RenderConfig<ChartType> = new Map(); - -/** - * Register a style descriptor - */ -const register = (renderDescriptor: RenderDescriptor<ChartType>) => - renderConfig.set(renderDescriptor.key, renderDescriptor); - -/** - * Slack unfurls for discover using the Total Period view - */ -register({ - key: ChartType.SLACK_DISCOVER_TOTAL_PERIOD, - height: 150, - width: 450, - getOption: (data: {seriesName: string; series: EventsStatsData}) => { - const color = getColorPalette(theme, data.series.length); - - const series = data.series.map(([timestamp, countsForTimestamp]) => ({ - name: timestamp * 1000, - value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0), - })); - - return { - useUTC: true, - color, - backgroundColor: theme.background, - grid: Grid({left: 5, right: 5, bottom: 5}), - legend: Legend({theme, itemHeight: 6, top: 2, right: 10}), - yAxis: YAxis({ - theme, - splitNumber: 3, - axisLabel: {fontSize: 11}, - }), - xAxis: XAxis({ - theme, - isGroupedByDate: true, - axisLabel: {fontSize: 11}, - }), - series: [ - AreaSeries({ - name: data.seriesName, - data: series.map(({name, value}) => [name, value]), - lineStyle: { - color: color?.[0], - opacity: 1, - width: 0.4, - }, - areaStyle: { - color: color?.[0], - opacity: 1.0, - }, - }), - ], - }; - }, -}); - -const config: ChartcuterieConfig = { - version: process.env.COMMIT_SHA!, - renderConfig, -}; - -export default config; diff --git a/src/sentry/static/sentry/app/components/charts/baseChart.tsx b/src/sentry/static/sentry/app/components/charts/baseChart.tsx index fbdb7fe62414fe..9d7d4791bb07b7 100644 --- a/src/sentry/static/sentry/app/components/charts/baseChart.tsx +++ b/src/sentry/static/sentry/app/components/charts/baseChart.tsx @@ -29,7 +29,7 @@ import Tooltip from './components/tooltip'; import XAxis from './components/xAxis'; import YAxis from './components/yAxis'; import LineSeries from './series/lineSeries'; -import {getColorPalette, getDimensionValue} from './utils'; +import {getDimensionValue} from './utils'; // TODO(ts): What is the series type? EChartOption.Series's data cannot have // `onClick` since it's typically an array. @@ -355,11 +355,15 @@ function BaseChartUnwrapped({ }) : undefined; + const color = + colors || + (series.length ? theme.charts.getColorPalette(series.length) : theme.charts.colors); + const chartOption = { ...options, animation: IS_ACCEPTANCE_TEST ? false : options.animation ?? true, useUTC: utc, - color: colors || getColorPalette(theme, series?.length), + color, grid: Array.isArray(grid) ? grid.map(Grid) : Grid(grid), tooltip: tooltipOrNone, legend: legend ? Legend({theme, ...legend}) : undefined, diff --git a/src/sentry/static/sentry/app/components/charts/utils.tsx b/src/sentry/static/sentry/app/components/charts/utils.tsx index 26752f2a1b2f3d..5b1567df59f6b8 100644 --- a/src/sentry/static/sentry/app/components/charts/utils.tsx +++ b/src/sentry/static/sentry/app/components/charts/utils.tsx @@ -7,7 +7,6 @@ import {EventsStats, GlobalSelection, MultiSeriesEventsStats} from 'app/types'; import {escape} from 'app/utils'; import {parsePeriodToHours} from 'app/utils/dates'; import {decodeList} from 'app/utils/queryString'; -import {Theme} from 'app/utils/theme'; const DEFAULT_TRUNCATE_LENGTH = 80; @@ -140,15 +139,3 @@ export const getDimensionValue = (dimension?: number | string | null) => { return dimension; }; - -/** - * Constructs the color palette for a chart given the Theme and optionally a - * series length - */ -export function getColorPalette(theme: Theme, seriesLength?: number | null) { - const palette = seriesLength - ? theme.charts.getColorPalette(seriesLength) - : theme.charts.colors; - - return (palette as unknown) as string[]; -} diff --git a/src/sentry/static/sentry/app/constants/chartPalette.tsx b/src/sentry/static/sentry/app/constants/chartPalette.tsx index 88bbddbe011f04..dd9aa18d6ae478 100644 --- a/src/sentry/static/sentry/app/constants/chartPalette.tsx +++ b/src/sentry/static/sentry/app/constants/chartPalette.tsx @@ -176,6 +176,6 @@ export const CHART_PALETTE = [ '#f4aa27', '#f2b712', ], -] as const; +] as string[][]; export default CHART_PALETTE; diff --git a/src/sentry/static/sentry/app/utils/theme.tsx b/src/sentry/static/sentry/app/utils/theme.tsx index bdb688774285e4..e2fe4dd84fa51e 100644 --- a/src/sentry/static/sentry/app/utils/theme.tsx +++ b/src/sentry/static/sentry/app/utils/theme.tsx @@ -500,7 +500,7 @@ const commonTheme = { // We have an array that maps `number + 1` --> list of `number` colors getColorPalette: (length: number) => - CHART_PALETTE[Math.min(CHART_PALETTE.length - 1, length + 1)], + CHART_PALETTE[Math.min(CHART_PALETTE.length - 1, length + 1)] as string[], previousPeriod: colors.gray200, symbolSize: 6, diff --git a/src/sentry/web/frontend/debug/debug_chart_renderer.py b/src/sentry/web/frontend/debug/debug_chart_renderer.py index d9ece1822ee528..1012db820b278e 100644 --- a/src/sentry/web/frontend/debug/debug_chart_renderer.py +++ b/src/sentry/web/frontend/debug/debug_chart_renderer.py @@ -4,29 +4,127 @@ from sentry.charts.types import ChartType from sentry.web.helpers import render_to_response -discover_total = { +discover_total_period = { "seriesName": "Discover total period", - "series": [ - [1616168400, [{"count": 0}]], - [1616168700, [{"count": 12}]], - [1616169000, [{"count": 13}]], - [1616169300, [{"count": 9}]], - [1616169600, [{"count": 12}]], - [1616169900, [{"count": 21}]], - [1616170200, [{"count": 11}]], - [1616170500, [{"count": 22}]], - [1616170800, [{"count": 18}]], - [1616171100, [{"count": 15}]], - [1616171400, [{"count": 14}]], - [1616171700, [{"count": 31}]], - [1616172000, [{"count": 18}]], - [1616172300, [{"count": 13}]], - [1616172600, [{"count": 17}]], - [1616172900, [{"count": 9}]], - [1616173200, [{"count": 9}]], - [1616173500, [{"count": 13}]], - [1616173800, [{"count": 11}]], - ], + "stats": { + "data": [ + [1616168400, [{"count": 0}]], + [1616168700, [{"count": 12}]], + [1616169000, [{"count": 13}]], + [1616169300, [{"count": 9}]], + [1616169600, [{"count": 12}]], + [1616169900, [{"count": 21}]], + [1616170200, [{"count": 11}]], + [1616170500, [{"count": 22}]], + [1616170800, [{"count": 18}]], + [1616171100, [{"count": 15}]], + [1616171400, [{"count": 14}]], + [1616171700, [{"count": 31}]], + [1616172000, [{"count": 18}]], + [1616172300, [{"count": 13}]], + [1616172600, [{"count": 17}]], + [1616172900, [{"count": 9}]], + [1616173200, [{"count": 9}]], + [1616173500, [{"count": 13}]], + [1616173800, [{"count": 11}]], + ], + }, +} + +discover_total_daily = { + "seriesName": "Discover total daily", + "stats": { + "data": [ + [1615852800, [{"count": 2426486}]], + [1615939200, [{"count": 18837228}]], + [1616025600, [{"count": 14662530}]], + [1616112000, [{"count": 15102981}]], + [1616198400, [{"count": 7759228}]], + [1616284800, [{"count": 7216556}]], + [1616371200, [{"count": 16976035}]], + [1616457600, [{"count": 17240832}]], + [1616544000, [{"count": 16814701}]], + [1616630400, [{"count": 17480989}]], + [1616716800, [{"count": 15387478}]], + [1616803200, [{"count": 8467454}]], + [1616889600, [{"count": 6382678}]], + [1616976000, [{"count": 16842851}]], + [1617062400, [{"count": 12959057}]], + ], + }, +} + +discover_top5 = { + "stats": { + "ludic-science,1st event": { + "data": [ + [1615877940, [{"count": 0}]], + [1615878000, [{"count": 0}]], + [1615878060, [{"count": 0}]], + [1615878120, [{"count": 0}]], + [1615878180, [{"count": 1}]], + [1615878240, [{"count": 1}]], + [1615878300, [{"count": 1}]], + [1615878360, [{"count": 1}]], + [1615878420, [{"count": 1}]], + [1615878480, [{"count": 1}]], + [1615878540, [{"count": 1}]], + [1615878600, [{"count": 3}]], + [1615878660, [{"count": 1}]], + [1615878720, [{"count": 1}]], + [1615878780, [{"count": 1}]], + [1615878840, [{"count": 1}]], + [1615878900, [{"count": 1}]], + [1615878960, [{"count": 1}]], + [1615879020, [{"count": 1}]], + [1615879080, [{"count": 1}]], + [1615879140, [{"count": 1}]], + [1615879200, [{"count": 1}]], + [1615879260, [{"count": 1}]], + [1615879320, [{"count": 1}]], + [1615879380, [{"count": 0}]], + [1615879440, [{"count": 0}]], + [1615879500, [{"count": 0}]], + [1615879560, [{"count": 0}]], + [1615879620, [{"count": 0}]], + ], + "order": 0, + }, + "ludic-science,2nd event": { + "data": [ + [1615877940, [{"count": 0}]], + [1615878000, [{"count": 0}]], + [1615878060, [{"count": 0}]], + [1615878120, [{"count": 0}]], + [1615878180, [{"count": 1}]], + [1615878240, [{"count": 1}]], + [1615878300, [{"count": 1}]], + [1615878360, [{"count": 1}]], + [1615878420, [{"count": 1}]], + [1615878480, [{"count": 1}]], + [1615878540, [{"count": 1}]], + [1615878600, [{"count": 5}]], + [1615878660, [{"count": 3}]], + [1615878720, [{"count": 2}]], + [1615878780, [{"count": 1}]], + [1615878840, [{"count": 1}]], + [1615878900, [{"count": 1}]], + [1615878960, [{"count": 1}]], + [1615879020, [{"count": 1}]], + [1615879080, [{"count": 1}]], + [1615879140, [{"count": 1}]], + [1615879200, [{"count": 1}]], + [1615879260, [{"count": 1}]], + [1615879320, [{"count": 1}]], + [1615879380, [{"count": 0}]], + [1615879440, [{"count": 0}]], + [1615879500, [{"count": 0}]], + [1615879560, [{"count": 0}]], + [1615879620, [{"count": 0}]], + ], + "order": 1, + }, + } } @@ -34,7 +132,9 @@ class DebugChartRendererView(View): def get(self, request): charts = [] - url = generate_chart(ChartType.SLACK_DISCOVER_TOTAL_PERIOD, discover_total) - charts.append(url) + charts.append(generate_chart(ChartType.SLACK_DISCOVER_TOTAL_PERIOD, discover_total_period)) + charts.append(generate_chart(ChartType.SLACK_DISCOVER_TOTAL_DAILY, discover_total_daily)) + charts.append(generate_chart(ChartType.SLACK_DISCOVER_TOP5_PERIOD, discover_top5)) + charts.append(generate_chart(ChartType.SLACK_DISCOVER_TOP5_DAILY, discover_top5)) return render_to_response("sentry/debug/chart-renderer.html", context={"charts": charts}) diff --git a/tests/chartcuterie/test_chart_renderer.py b/tests/chartcuterie/test_chart_renderer.py index a90c32894c698d..24cde0ed04af17 100644 --- a/tests/chartcuterie/test_chart_renderer.py +++ b/tests/chartcuterie/test_chart_renderer.py @@ -12,7 +12,7 @@ def test_debug_renders(self): self.browser.get("debug/chart-renderer/") images = self.browser.elements(selector="img") - assert len(images) == 1 + assert len(images) > 0 for image in images: src = image.get_attribute("src")
4869488440eef0e50b328aece83b6e1e140eb1cf
2021-02-25 04:26:55
Dora
fix(copy): replace stack with group (#24078)
false
replace stack with group (#24078)
fix
diff --git a/src/sentry/static/sentry/app/views/eventsV2/table/columnEditModal.tsx b/src/sentry/static/sentry/app/views/eventsV2/table/columnEditModal.tsx index dd71579b5c112f..ce01edb2781307 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/table/columnEditModal.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/table/columnEditModal.tsx @@ -77,7 +77,7 @@ class ColumnEditModal extends React.Component<Props, State> { <Body> <Instruction> {tct( - 'To stack events, add [functionLink: functions] f(x) that may take in additional parameters. [tagFieldLink: Tag and field] columns will help you view more details about the events (i.e. title).', + 'To group events, add [functionLink: functions] f(x) that may take in additional parameters. [tagFieldLink: Tag and field] columns will help you view more details about the events (i.e. title).', { functionLink: ( <ExternalLink href="https://docs.sentry.io/product/discover-queries/query-builder/#filter-by-table-columns" /> diff --git a/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx b/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx index ffe9a1c52b3050..e107148508ad20 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx @@ -127,8 +127,8 @@ class TableView extends React.Component<TableViewProps> { }; return [ - <Tooltip key={`eventlink${rowIndex}`} title={t('Open Stack')}> - <Link to={target} data-test-id="open-stack"> + <Tooltip key={`eventlink${rowIndex}`} title={t('Open Group')}> + <Link to={target} data-test-id="open-group"> <StyledIcon size="sm" /> </Link> </Tooltip>, diff --git a/tests/acceptance/test_organization_events_v2.py b/tests/acceptance/test_organization_events_v2.py index 85a37d43bcb652..76f30e3c0d5eee 100644 --- a/tests/acceptance/test_organization_events_v2.py +++ b/tests/acceptance/test_organization_events_v2.py @@ -350,7 +350,7 @@ def test_event_detail_view_from_errors_view(self, mock_now): self.wait_until_loaded() # Open the stack - self.browser.element('[data-test-id="open-stack"]').click() + self.browser.element('[data-test-id="open-group"]').click() self.wait_until_loaded() # View Event @@ -384,7 +384,7 @@ def test_event_detail_view_from_transactions_query(self, mock_now): self.wait_until_loaded() # Open the stack - self.browser.elements('[data-test-id="open-stack"]')[0].click() + self.browser.elements('[data-test-id="open-group"]')[0].click() self.wait_until_loaded() # View Event @@ -417,7 +417,7 @@ def test_transaction_event_detail_view_ops_filtering(self, mock_now): self.wait_until_loaded() # Open the stack - self.browser.elements('[data-test-id="open-stack"]')[0].click() + self.browser.elements('[data-test-id="open-group"]')[0].click() self.wait_until_loaded() # View Event
88755b98f9ed5022b4c0c2832f24b2646aee6a51
2023-06-26 11:58:38
Riccardo Busetti
feat(sourcemaps): Implement missing chunks functionality for artifact bundles (#51251)
false
Implement missing chunks functionality for artifact bundles (#51251)
feat
diff --git a/src/sentry/api/endpoints/organization_artifactbundle_assemble.py b/src/sentry/api/endpoints/organization_artifactbundle_assemble.py index f20d210766dd88..382eae91633fb3 100644 --- a/src/sentry/api/endpoints/organization_artifactbundle_assemble.py +++ b/src/sentry/api/endpoints/organization_artifactbundle_assemble.py @@ -2,11 +2,12 @@ from rest_framework.request import Request from rest_framework.response import Response +from sentry import options from sentry.api.base import region_silo_endpoint from sentry.api.bases.organization import OrganizationReleasesBaseEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.constants import ObjectStatus -from sentry.models import Project +from sentry.models import FileBlobOwner, Project from sentry.tasks.assemble import ( AssembleTask, ChunkFileState, @@ -16,8 +17,25 @@ from sentry.utils import json +class OrganizationArtifactBundleAssembleMixin: + @classmethod + def find_missing_chunks(cls, organization, chunks): + """ + Returns a list of chunks which are missing for an org. + """ + owned = set( + FileBlobOwner.objects.filter( + blob__checksum__in=chunks, organization_id=organization.id + ).values_list("blob__checksum", flat=True) + ) + + return list(set(chunks) - owned) + + @region_silo_endpoint -class OrganizationArtifactBundleAssembleEndpoint(OrganizationReleasesBaseEndpoint): +class OrganizationArtifactBundleAssembleEndpoint( + OrganizationReleasesBaseEndpoint, OrganizationArtifactBundleAssembleMixin +): def post(self, request: Request, organization) -> Response: """ Assembles an artifact bundle and stores the debug ids in the database. @@ -63,10 +81,29 @@ def post(self, request: Request, organization) -> Response: checksum = data.get("checksum") chunks = data.get("chunks", []) - state, detail = get_assemble_status(AssembleTask.ARTIFACTS, organization.id, checksum) + # We want to put the missing chunks functionality behind an option in order to cut it off in case of CLI + # regressions for our users. + if options.get("sourcemaps.artifact_bundles.assemble_with_missing_chunks"): + # We check if all requested chunks have been uploaded. + missing_chunks = self.find_missing_chunks(organization, chunks) + # In case there are some missing chunks, we will tell the client which chunks we require. + if missing_chunks: + return Response( + { + "state": ChunkFileState.NOT_FOUND, + "missingChunks": missing_chunks, + } + ) + + # We want to check the current state of the assemble status. + state, detail = get_assemble_status(AssembleTask.ARTIFACT_BUNDLE, organization.id, checksum) if state == ChunkFileState.OK: return Response({"state": state, "detail": None, "missingChunks": []}, status=200) elif state is not None: + # In case we have some state into the cache, we will not perform any assembly task again and rather we will + # return. This might cause issues with CLI because it might have uploaded the same bundle chunks two times + # in a row but only the first call the assemble started the assembly task, all subsequent calls will get + # an assemble status. return Response({"state": state, "detail": detail, "missingChunks": []}) # There is neither a known file nor a cached state, so we will @@ -76,7 +113,7 @@ def post(self, request: Request, organization) -> Response: return Response({"state": ChunkFileState.NOT_FOUND, "missingChunks": []}, status=200) set_assemble_status( - AssembleTask.ARTIFACTS, organization.id, checksum, ChunkFileState.CREATED + AssembleTask.ARTIFACT_BUNDLE, organization.id, checksum, ChunkFileState.CREATED ) from sentry.tasks.assemble import assemble_artifacts diff --git a/src/sentry/api/endpoints/organization_release_assemble.py b/src/sentry/api/endpoints/organization_release_assemble.py index e49c091c2368fc..5e66f0cda885df 100644 --- a/src/sentry/api/endpoints/organization_release_assemble.py +++ b/src/sentry/api/endpoints/organization_release_assemble.py @@ -57,7 +57,7 @@ def post(self, request: Request, organization, version) -> Response: checksum = data.get("checksum", None) chunks = data.get("chunks", []) - state, detail = get_assemble_status(AssembleTask.ARTIFACTS, organization.id, checksum) + state, detail = get_assemble_status(AssembleTask.RELEASE_BUNDLE, organization.id, checksum) if state == ChunkFileState.OK: return Response({"state": state, "detail": None, "missingChunks": []}, status=200) elif state is not None: @@ -70,7 +70,7 @@ def post(self, request: Request, organization, version) -> Response: return Response({"state": ChunkFileState.NOT_FOUND, "missingChunks": []}, status=200) set_assemble_status( - AssembleTask.ARTIFACTS, organization.id, checksum, ChunkFileState.CREATED + AssembleTask.RELEASE_BUNDLE, organization.id, checksum, ChunkFileState.CREATED ) from sentry.tasks.assemble import assemble_artifacts diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py index 05195f95eef9c7..9808da4a6e3fe9 100644 --- a/src/sentry/options/defaults.py +++ b/src/sentry/options/defaults.py @@ -1346,3 +1346,11 @@ default=0.5, flags=FLAG_AUTOMATOR_MODIFIABLE, ) + +# Control whether the artifact bundles assemble endpoint support the missing chunks check the enables the CLI to only +# upload missing chunks instead of the entire bundle again. +register( + "sourcemaps.artifact_bundles.assemble_with_missing_chunks", + default=False, + flags=FLAG_AUTOMATOR_MODIFIABLE, +) diff --git a/src/sentry/tasks/assemble.py b/src/sentry/tasks/assemble.py index 2af39b79f7a63e..9ed95fb61c586c 100644 --- a/src/sentry/tasks/assemble.py +++ b/src/sentry/tasks/assemble.py @@ -43,7 +43,8 @@ class ChunkFileState: class AssembleTask: DIF = "project.dsym" # Debug file upload - ARTIFACTS = "organization.artifacts" # Release file upload + RELEASE_BUNDLE = "organization.artifacts" # Release file upload + ARTIFACT_BUNDLE = "organization.artifact_bundle" # Artifact bundle upload def _get_cache_key(task, scope, checksum): @@ -491,11 +492,16 @@ def assemble_artifacts( if project_ids is None: project_ids = [] + # We want to evaluate the type of assemble task given the input parameters. + assemble_task = ( + AssembleTask.ARTIFACT_BUNDLE if upload_as_artifact_bundle else AssembleTask.RELEASE_BUNDLE + ) + try: organization = Organization.objects.get_from_cache(pk=org_id) bind_organization_context(organization) - set_assemble_status(AssembleTask.ARTIFACTS, org_id, checksum, ChunkFileState.ASSEMBLING) + set_assemble_status(assemble_task, org_id, checksum, ChunkFileState.ASSEMBLING) archive_name = "bundle-artifacts" if upload_as_artifact_bundle else "release-artifacts" archive_filename = f"{archive_name}-{uuid.uuid4().hex}.zip" @@ -503,7 +509,7 @@ def assemble_artifacts( # Assemble the chunks into a temporary file rv = assemble_file( - AssembleTask.ARTIFACTS, + assemble_task, organization, archive_filename, checksum, @@ -520,8 +526,6 @@ def assemble_artifacts( bundle, temp_file = rv try: - # TODO(iambriccardo): Once the new lookup PR is merged it would be better if we generalize the archive - # handling class. archive = ReleaseArchive(temp_file) except Exception: raise AssembleArtifactsError("failed to open release manifest") @@ -537,20 +541,18 @@ def assemble_artifacts( # Count files extracted, to compare them to release files endpoint metrics.incr("tasks.assemble.extracted_files", amount=archive.artifact_count) except AssembleArtifactsError as e: - set_assemble_status( - AssembleTask.ARTIFACTS, org_id, checksum, ChunkFileState.ERROR, detail=str(e) - ) + set_assemble_status(assemble_task, org_id, checksum, ChunkFileState.ERROR, detail=str(e)) except Exception: logger.error("failed to assemble release bundle", exc_info=True) set_assemble_status( - AssembleTask.ARTIFACTS, + assemble_task, org_id, checksum, ChunkFileState.ERROR, detail="internal server error", ) else: - set_assemble_status(AssembleTask.ARTIFACTS, org_id, checksum, ChunkFileState.OK) + set_assemble_status(assemble_task, org_id, checksum, ChunkFileState.OK) def assemble_file(task, org_or_project, name, checksum, chunks, file_type): diff --git a/tests/sentry/api/endpoints/test_organization_artifactbundle_assemble.py b/tests/sentry/api/endpoints/test_organization_artifactbundle_assemble.py index e11a61c76b50fd..e1669e27b14701 100644 --- a/tests/sentry/api/endpoints/test_organization_artifactbundle_assemble.py +++ b/tests/sentry/api/endpoints/test_organization_artifactbundle_assemble.py @@ -247,12 +247,58 @@ def test_assemble_with_version_and_dist(self, mock_assemble_artifacts): } ) + def test_assemble_with_missing_chunks(self): + with self.options({"sourcemaps.artifact_bundles.assemble_with_missing_chunks": True}): + dist = "android" + bundle_file = self.create_artifact_bundle_zip( + org=self.organization.slug, release=self.release.version + ) + total_checksum = sha1(bundle_file).hexdigest() + + # We try to upload with all the checksums missing. + response = self.client.post( + self.url, + data={ + "checksum": total_checksum, + "chunks": [total_checksum], + "projects": [self.project.slug], + "version": self.release.version, + "dist": dist, + }, + HTTP_AUTHORIZATION=f"Bearer {self.token.token}", + ) + + assert response.status_code == 200, response.content + assert response.data["state"] == ChunkFileState.NOT_FOUND + assert set(response.data["missingChunks"]) == {total_checksum} + + # We store the blobs into the database. + blob1 = FileBlob.from_file(ContentFile(bundle_file)) + FileBlobOwner.objects.get_or_create(organization_id=self.organization.id, blob=blob1) + + # We make the request again after the file have been uploaded. + response = self.client.post( + self.url, + data={ + "checksum": total_checksum, + "chunks": [total_checksum], + "projects": [self.project.slug], + "version": self.release.version, + "dist": dist, + }, + HTTP_AUTHORIZATION=f"Bearer {self.token.token}", + ) + + assert response.status_code == 200, response.content + assert response.data["state"] == ChunkFileState.CREATED + def test_assemble_response(self): bundle_file = self.create_artifact_bundle_zip( org=self.organization.slug, release=self.release.version ) total_checksum = sha1(bundle_file).hexdigest() blob1 = FileBlob.from_file(ContentFile(bundle_file)) + FileBlobOwner.objects.get_or_create(organization_id=self.organization.id, blob=blob1) assemble_artifacts( org_id=self.organization.id, @@ -273,30 +319,4 @@ def test_assemble_response(self): ) assert response.status_code == 200, response.content - assert response.data["state"] == ChunkFileState.OK - - def test_dif_error_response(self): - bundle_file = b"invalid" - total_checksum = sha1(bundle_file).hexdigest() - blob1 = FileBlob.from_file(ContentFile(bundle_file)) - - assemble_artifacts( - org_id=self.organization.id, - version=self.release.version, - checksum=total_checksum, - chunks=[blob1.checksum], - upload_as_artifact_bundle=False, - ) - - response = self.client.post( - self.url, - data={ - "checksum": total_checksum, - "chunks": [blob1.checksum], - "projects": [self.project.slug], - }, - HTTP_AUTHORIZATION=f"Bearer {self.token.token}", - ) - - assert response.status_code == 200, response.content - assert response.data["state"] == ChunkFileState.ERROR + assert response.data["state"] == ChunkFileState.CREATED diff --git a/tests/sentry/tasks/test_assemble.py b/tests/sentry/tasks/test_assemble.py index eaa8ca348c41d6..3cfe55e7bd9cd8 100644 --- a/tests/sentry/tasks/test_assemble.py +++ b/tests/sentry/tasks/test_assemble.py @@ -229,7 +229,7 @@ def test_artifacts_with_debug_ids(self): assert self.release.count_artifacts() == 0 status, details = get_assemble_status( - AssembleTask.ARTIFACTS, self.organization.id, total_checksum + AssembleTask.ARTIFACT_BUNDLE, self.organization.id, total_checksum ) assert status == ChunkFileState.OK assert details is None @@ -567,7 +567,7 @@ def test_artifacts_without_debug_ids(self): assert self.release.count_artifacts() == 2 status, details = get_assemble_status( - AssembleTask.ARTIFACTS, self.organization.id, total_checksum + AssembleTask.RELEASE_BUNDLE, self.organization.id, total_checksum ) assert status == ChunkFileState.OK assert details is None @@ -605,7 +605,7 @@ def test_artifacts_invalid_org(self): ) status, details = get_assemble_status( - AssembleTask.ARTIFACTS, self.organization.id, total_checksum + AssembleTask.RELEASE_BUNDLE, self.organization.id, total_checksum ) assert status == ChunkFileState.ERROR @@ -623,7 +623,7 @@ def test_artifacts_invalid_release(self): ) status, details = get_assemble_status( - AssembleTask.ARTIFACTS, self.organization.id, total_checksum + AssembleTask.RELEASE_BUNDLE, self.organization.id, total_checksum ) assert status == ChunkFileState.ERROR @@ -641,7 +641,7 @@ def test_artifacts_invalid_zip(self): ) status, details = get_assemble_status( - AssembleTask.ARTIFACTS, self.organization.id, total_checksum + AssembleTask.RELEASE_BUNDLE, self.organization.id, total_checksum ) assert status == ChunkFileState.ERROR @@ -669,6 +669,6 @@ def test_failing_update(self, _): # Status is still OK: status, details = get_assemble_status( - AssembleTask.ARTIFACTS, self.organization.id, total_checksum + AssembleTask.RELEASE_BUNDLE, self.organization.id, total_checksum ) assert status == ChunkFileState.OK
b52daf02588c65c05ffffb55820401d2b2424187
2022-02-03 06:19:09
Kelly Carino
feat(ui): Change Alert chart from Line Chart to Area Chart [WIP] (#31546)
false
Change Alert chart from Line Chart to Area Chart [WIP] (#31546)
feat
diff --git a/static/app/views/alerts/rules/details/metricChart.tsx b/static/app/views/alerts/rules/details/metricChart.tsx index 49360774b0834a..0ad59f96320a81 100644 --- a/static/app/views/alerts/rules/details/metricChart.tsx +++ b/static/app/views/alerts/rules/details/metricChart.tsx @@ -10,11 +10,11 @@ import momentTimezone from 'moment-timezone'; import {Client} from 'sentry/api'; import Feature from 'sentry/components/acl/feature'; import Button from 'sentry/components/button'; +import AreaChart, {AreaChartSeries} from 'sentry/components/charts/areaChart'; import ChartZoom from 'sentry/components/charts/chartZoom'; import MarkArea from 'sentry/components/charts/components/markArea'; import MarkLine from 'sentry/components/charts/components/markLine'; import EventsRequest from 'sentry/components/charts/eventsRequest'; -import LineChart, {LineChartSeries} from 'sentry/components/charts/lineChart'; import LineSeries from 'sentry/components/charts/series/lineSeries'; import SessionsRequest from 'sentry/components/charts/sessionsRequest'; import {HeaderTitleLegend, SectionHeading} from 'sentry/components/charts/styles'; @@ -26,6 +26,7 @@ import { import {Panel, PanelBody, PanelFooter} from 'sentry/components/panels'; import Placeholder from 'sentry/components/placeholder'; import Truncate from 'sentry/components/truncate'; +import CHART_PALETTE from 'sentry/constants/chartPalette'; import {IconCheckmark, IconFire, IconWarning} from 'sentry/icons'; import {t} from 'sentry/locale'; import ConfigStore from 'sentry/stores/configStore'; @@ -86,7 +87,7 @@ function formatTooltipDate(date: moment.MomentInput, format: string): string { return momentTimezone.tz(date, timezone).format(format); } -function createThresholdSeries(lineColor: string, threshold: number): LineChartSeries { +function createThresholdSeries(lineColor: string, threshold: number): AreaChartSeries { return { seriesName: 'Threshold Line', type: 'line', @@ -107,7 +108,7 @@ function createStatusAreaSeries( startTime: number, endTime: number, yPosition: number -): LineChartSeries { +): AreaChartSeries { return { seriesName: '', type: 'line', @@ -126,10 +127,10 @@ function createIncidentSeries( lineColor: string, incidentTimestamp: number, incident: Incident, - dataPoint?: LineChartSeries['data'][0], + dataPoint?: AreaChartSeries['data'][0], seriesName?: string, aggregate?: string -): LineChartSeries { +): AreaChartSeries { const formatter = ({value, marker}: any) => { const time = formatTooltipDate(moment(value), 'MMM D, YYYY LT'); return [ @@ -231,7 +232,7 @@ class MetricChart extends React.PureComponent<Props, State> { } }; - getRuleChangeSeries = (data: LineChartSeries[]): LineSeriesOption[] => { + getRuleChangeSeries = (data: AreaChartSeries[]): LineSeriesOption[] => { const {dateModified} = this.props.rule || {}; if (!data.length || !data[0].data.length || !dateModified) { @@ -349,10 +350,12 @@ class MetricChart extends React.PureComponent<Props, State> { const criticalTrigger = rule.triggers.find(({label}) => label === 'critical'); const warningTrigger = rule.triggers.find(({label}) => label === 'warning'); - const series: LineChartSeries[] = [...timeseriesData]; + const series: AreaChartSeries[] = [...timeseriesData]; const areaSeries: any[] = []; - // Ensure series data appears above incident lines - series[0].z = 100; + // Ensure series data appears below incident/mark lines + series[0].z = 1; + series[0].color = CHART_PALETTE[0][0]; + const dataArr = timeseriesData[0].data; const maxSeriesValue = dataArr.reduce( (currMax, coord) => Math.max(currMax, coord.value), @@ -559,7 +562,7 @@ class MetricChart extends React.PureComponent<Props, State> { onZoom={zoomArgs => handleZoom(zoomArgs.start, zoomArgs.end)} > {zoomRenderProps => ( - <LineChart + <AreaChart {...zoomRenderProps} isGroupedByDate showTimeInTooltip
ecb96b2288c9fa816032b5f0d2eb1101601ba957
2023-05-30 23:27:12
Vu Luong
ref(documentTitle): Use em-dashes not hyphens (#49888)
false
Use em-dashes not hyphens (#49888)
ref
diff --git a/static/app/components/sentryDocumentTitle.spec.tsx b/static/app/components/sentryDocumentTitle.spec.tsx index 6e34aeddc8877b..ec7b58422ad62d 100644 --- a/static/app/components/sentryDocumentTitle.spec.tsx +++ b/static/app/components/sentryDocumentTitle.spec.tsx @@ -5,24 +5,24 @@ import SentryDocumentTitle from './sentryDocumentTitle'; describe('SentryDocumentTitle', () => { it('sets the docuemnt title', () => { render(<SentryDocumentTitle title="This is a test" />); - expect(document.title).toBe('This is a test - Sentry'); + expect(document.title).toBe('This is a test — Sentry'); }); it('adds a organization slug', () => { render(<SentryDocumentTitle orgSlug="org" title="This is a test" />); - expect(document.title).toBe('This is a test - org - Sentry'); + expect(document.title).toBe('This is a test — org — Sentry'); }); it('adds a project slug', () => { render(<SentryDocumentTitle projectSlug="project" title="This is a test" />); - expect(document.title).toBe('This is a test - project - Sentry'); + expect(document.title).toBe('This is a test — project — Sentry'); }); it('adds a organization and project slug', () => { render( <SentryDocumentTitle orgSlug="org" projectSlug="project" title="This is a test" /> ); - expect(document.title).toBe('This is a test - org - project - Sentry'); + expect(document.title).toBe('This is a test — org — project — Sentry'); }); it('sets the title without suffix', () => { @@ -37,12 +37,12 @@ describe('SentryDocumentTitle', () => { </SentryDocumentTitle> ); - expect(document.title).toBe('child title - Sentry'); + expect(document.title).toBe('child title — Sentry'); rerender( <SentryDocumentTitle title="This is a test">new Content</SentryDocumentTitle> ); - expect(document.title).toBe('This is a test - Sentry'); + expect(document.title).toBe('This is a test — Sentry'); }); }); diff --git a/static/app/components/sentryDocumentTitle.tsx b/static/app/components/sentryDocumentTitle.tsx index 6cff80ae59740d..ac6efdd8ff09e0 100644 --- a/static/app/components/sentryDocumentTitle.tsx +++ b/static/app/components/sentryDocumentTitle.tsx @@ -40,15 +40,15 @@ function SentryDocumentTitle({ const pageTitle = useMemo(() => { if (orgSlug && projectSlug) { - return `${title} - ${orgSlug} - ${projectSlug}`; + return `${title} — ${orgSlug} — ${projectSlug}`; } if (orgSlug) { - return `${title} - ${orgSlug}`; + return `${title} — ${orgSlug}`; } if (projectSlug) { - return `${title} - ${projectSlug}`; + return `${title} — ${projectSlug}`; } return title; @@ -60,7 +60,7 @@ function SentryDocumentTitle({ } if (pageTitle !== '') { - return `${pageTitle} - Sentry`; + return `${pageTitle} — Sentry`; } return DEFAULT_PAGE_TITLE; diff --git a/static/app/views/discover/eventDetails/index.tsx b/static/app/views/discover/eventDetails/index.tsx index a50bbe77557719..9f19acf5b9ecbf 100644 --- a/static/app/views/discover/eventDetails/index.tsx +++ b/static/app/views/discover/eventDetails/index.tsx @@ -33,7 +33,7 @@ function EventDetails({organization, location, params}: Props) { return ( <SentryDocumentTitle - title={documentTitle.join(' - ')} + title={documentTitle.join(' — ')} orgSlug={organization.slug} projectSlug={projectSlug} > diff --git a/static/app/views/discover/utils.tsx b/static/app/views/discover/utils.tsx index b6ce011ceb6809..77880149a9fb51 100644 --- a/static/app/views/discover/utils.tsx +++ b/static/app/views/discover/utils.tsx @@ -154,7 +154,7 @@ export function generateTitle({ titles.reverse(); - return titles.join(' - '); + return titles.join(' — '); } export function getPrebuiltQueries(organization: Organization) { diff --git a/static/app/views/issueDetails/groupDetails.tsx b/static/app/views/issueDetails/groupDetails.tsx index be16e713b37e79..8af66e60ac27ff 100644 --- a/static/app/views/issueDetails/groupDetails.tsx +++ b/static/app/views/issueDetails/groupDetails.tsx @@ -753,13 +753,13 @@ function GroupDetails(props: GroupDetailsProps) { const {title} = getTitle(group, organization?.features); const message = getMessage(group); - const eventDetails = `${organization.slug} - ${group.project.slug}`; + const eventDetails = `${organization.slug} — ${group.project.slug}`; if (title && message) { - return `${title}: ${message} - ${eventDetails}`; + return `${title}: ${message} — ${eventDetails}`; } - return `${title || message || defaultTitle} - ${eventDetails}`; + return `${title || message || defaultTitle} — ${eventDetails}`; }; return ( diff --git a/static/app/views/monitors/details.tsx b/static/app/views/monitors/details.tsx index 5fb5fbc3b01ff1..561bda5f16c83c 100644 --- a/static/app/views/monitors/details.tsx +++ b/static/app/views/monitors/details.tsx @@ -80,7 +80,7 @@ function MonitorDetails({params, location}: Props) { ); return ( - <SentryDocumentTitle title={`Crons - ${monitor.name}`}> + <SentryDocumentTitle title={`Crons — ${monitor.name}`}> <Layout.Page> <MonitorHeader monitor={monitor} orgId={organization.slug} onUpdate={onUpdate} /> <Layout.Body> diff --git a/static/app/views/monitors/monitors.tsx b/static/app/views/monitors/monitors.tsx index b18bf9a5188c79..5aab68e3d0c623 100644 --- a/static/app/views/monitors/monitors.tsx +++ b/static/app/views/monitors/monitors.tsx @@ -116,7 +116,7 @@ export default function Monitors({location}: RouteComponentProps<{}, {}>) { ); return ( - <SentryDocumentTitle title={`Crons - ${organization.slug}`}> + <SentryDocumentTitle title={`Crons — ${organization.slug}`}> <Layout.Page> <Layout.Header> <Layout.HeaderContent> diff --git a/static/app/views/performance/traceDetails/index.tsx b/static/app/views/performance/traceDetails/index.tsx index f1587377c56d06..40f7f7bd300321 100644 --- a/static/app/views/performance/traceDetails/index.tsx +++ b/static/app/views/performance/traceDetails/index.tsx @@ -27,7 +27,7 @@ type Props = RouteComponentProps<{traceSlug: string}, {}> & { class TraceSummary extends Component<Props> { getDocumentTitle(): string { - return [t('Trace Details'), t('Performance')].join(' - '); + return [t('Trace Details'), t('Performance')].join(' — '); } getTraceSlug(): string { diff --git a/static/app/views/performance/transactionDetails/content.tsx b/static/app/views/performance/transactionDetails/content.tsx index 08a1a4cbfa0d45..b5227249fc32cf 100644 --- a/static/app/views/performance/transactionDetails/content.tsx +++ b/static/app/views/performance/transactionDetails/content.tsx @@ -349,7 +349,7 @@ class EventDetailsContent extends AsyncComponent<Props, State> { return ( <SentryDocumentTitle - title={t('Performance - Event Details')} + title={t('Performance — Event Details')} orgSlug={organization.slug} > {super.renderComponent() as React.ReactChild} diff --git a/static/app/views/performance/trends/index.tsx b/static/app/views/performance/trends/index.tsx index 1107dc823d77b0..c3e444b69571d0 100644 --- a/static/app/views/performance/trends/index.tsx +++ b/static/app/views/performance/trends/index.tsx @@ -58,7 +58,7 @@ class TrendsSummary extends Component<Props, State> { }; getDocumentTitle(): string { - return [t('Trends'), t('Performance')].join(' - '); + return [t('Trends'), t('Performance')].join(' — '); } setError = (error: string | undefined) => { diff --git a/static/app/views/performance/vitalDetail/index.tsx b/static/app/views/performance/vitalDetail/index.tsx index 528728d805e6a6..9144bf573f47c7 100644 --- a/static/app/views/performance/vitalDetail/index.tsx +++ b/static/app/views/performance/vitalDetail/index.tsx @@ -88,10 +88,10 @@ class VitalDetail extends Component<Props, State> { const hasTransactionName = typeof name === 'string' && String(name).trim().length > 0; if (hasTransactionName) { - return [String(name).trim(), t('Performance')].join(' - '); + return [String(name).trim(), t('Performance')].join(' — '); } - return [t('Vital Detail'), t('Performance')].join(' - '); + return [t('Vital Detail'), t('Performance')].join(' — '); } render() { diff --git a/static/app/views/replays/detail/page.tsx b/static/app/views/replays/detail/page.tsx index 8db445947ba5d9..012a3933f71a7f 100644 --- a/static/app/views/replays/detail/page.tsx +++ b/static/app/views/replays/detail/page.tsx @@ -34,8 +34,8 @@ function Page({ replayErrors, }: Props) { const title = replayRecord - ? `${replayRecord.id} - Session Replay - ${orgSlug}` - : `Session Replay - ${orgSlug}`; + ? `${replayRecord.id} — Session Replay — ${orgSlug}` + : `Session Replay — ${orgSlug}`; const header = ( <Header> diff --git a/static/app/views/replays/list/container.tsx b/static/app/views/replays/list/container.tsx index 9ac6ec89eda606..bc053ce8fcdc9d 100644 --- a/static/app/views/replays/list/container.tsx +++ b/static/app/views/replays/list/container.tsx @@ -13,7 +13,7 @@ function ReplaysListContainer() { const {slug: orgSlug} = useOrganization(); return ( - <SentryDocumentTitle title={`Session Replay - ${orgSlug}`}> + <SentryDocumentTitle title={`Session Replay — ${orgSlug}`}> <Layout.Header> <Layout.HeaderContent> <Layout.Title>
448060a476e5242f5ada9fdfd0e9fcd9eb1d6253
2024-09-04 00:34:58
Michelle Zhang
feat(replay): add mobile platforms to onboarding sidebar (#76709)
false
add mobile platforms to onboarding sidebar (#76709)
feat
diff --git a/static/app/components/feedback/feedbackOnboarding/sidebar.tsx b/static/app/components/feedback/feedbackOnboarding/sidebar.tsx index 53d92c695348c7..8b74094841eb2f 100644 --- a/static/app/components/feedback/feedbackOnboarding/sidebar.tsx +++ b/static/app/components/feedback/feedbackOnboarding/sidebar.tsx @@ -334,6 +334,7 @@ function OnboardingContent({currentProject}: {currentProject: Project}) { ) { return 'feedbackOnboardingNpm'; } + // TODO: update this when we add feedback to the loader return 'replayOnboardingJsLoader'; } diff --git a/static/app/components/onboarding/gettingStartedDoc/types.ts b/static/app/components/onboarding/gettingStartedDoc/types.ts index 32c1a68f1a7462..85f652824410b3 100644 --- a/static/app/components/onboarding/gettingStartedDoc/types.ts +++ b/static/app/components/onboarding/gettingStartedDoc/types.ts @@ -94,8 +94,8 @@ export interface Docs<PlatformOptions extends BasePlatformOptions = BasePlatform feedbackOnboardingCrashApi?: OnboardingConfig<PlatformOptions>; feedbackOnboardingNpm?: OnboardingConfig<PlatformOptions>; platformOptions?: PlatformOptions; + replayOnboarding?: OnboardingConfig<PlatformOptions>; replayOnboardingJsLoader?: OnboardingConfig<PlatformOptions>; - replayOnboardingNpm?: OnboardingConfig<PlatformOptions>; } export type ConfigType = @@ -103,6 +103,6 @@ export type ConfigType = | 'feedbackOnboardingNpm' | 'feedbackOnboardingCrashApi' | 'crashReportOnboarding' - | 'replayOnboardingNpm' + | 'replayOnboarding' | 'replayOnboardingJsLoader' | 'customMetricsOnboarding'; diff --git a/static/app/components/onboarding/gettingStartedDoc/utils/index.tsx b/static/app/components/onboarding/gettingStartedDoc/utils/index.tsx index 86800ed50cb94b..58705c2b13899c 100644 --- a/static/app/components/onboarding/gettingStartedDoc/utils/index.tsx +++ b/static/app/components/onboarding/gettingStartedDoc/utils/index.tsx @@ -75,7 +75,7 @@ export function MobileBetaBanner({link}: {link: string}) { return ( <Alert type="info" showIcon> {tct( - `Currently, Mobile Replay is in beta. You can [link:read our docs] to learn how to set it up for your project.`, + `Currently, Mobile Replay is in beta. To learn more, you can [link:read our docs].`, { link: <ExternalLink href={link} />, } diff --git a/static/app/components/onboarding/gettingStartedDoc/utils/replayOnboarding.tsx b/static/app/components/onboarding/gettingStartedDoc/utils/replayOnboarding.tsx index e58e2524dc86d5..a36c849868e7b2 100644 --- a/static/app/components/onboarding/gettingStartedDoc/utils/replayOnboarding.tsx +++ b/static/app/components/onboarding/gettingStartedDoc/utils/replayOnboarding.tsx @@ -2,6 +2,14 @@ import ExternalLink from 'sentry/components/links/externalLink'; import type {DocsParams} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {tct} from 'sentry/locale'; +export const getReplayMobileConfigureDescription = ({link}: {link: string}) => + tct( + 'The SDK aggressively redacts all text and images. We plan to add fine controls for redacting, but currently, we just allow either on or off. Learn more about configuring Session Replay by reading the [link:configuration docs].', + { + link: <ExternalLink href={link} />, + } + ); + export const getReplayConfigureDescription = ({link}: {link: string}) => tct( 'Add the following to your SDK config. There are several privacy and sampling options available, all of which can be set using the [code:integrations] constructor. Learn more about configuring Session Replay by reading the [link:configuration docs].', diff --git a/static/app/components/replaysOnboarding/replayOnboardingLayout.tsx b/static/app/components/replaysOnboarding/replayOnboardingLayout.tsx index 7e45ac2832670a..57cf68b4336390 100644 --- a/static/app/components/replaysOnboarding/replayOnboardingLayout.tsx +++ b/static/app/components/replaysOnboarding/replayOnboardingLayout.tsx @@ -8,6 +8,7 @@ import type {DocsParams} from 'sentry/components/onboarding/gettingStartedDoc/ty import {useSourcePackageRegistries} from 'sentry/components/onboarding/gettingStartedDoc/useSourcePackageRegistries'; import {useUrlPlatformOptions} from 'sentry/components/onboarding/platformOptionsControl'; import ReplayConfigToggle from 'sentry/components/replaysOnboarding/replayConfigToggle'; +import {space} from 'sentry/styles/space'; import useOrganization from 'sentry/utils/useOrganization'; export function ReplayOnboardingLayout({ @@ -18,14 +19,15 @@ export function ReplayOnboardingLayout({ projectSlug, newOrg, configType = 'onboarding', -}: OnboardingLayoutProps) { + hideMaskBlockToggles, +}: OnboardingLayoutProps & {hideMaskBlockToggles?: boolean}) { const organization = useOrganization(); const {isPending: isLoadingRegistry, data: registryData} = useSourcePackageRegistries(organization); const selectedOptions = useUrlPlatformOptions(docsConfig.platformOptions); const [mask, setMask] = useState(true); const [block, setBlock] = useState(true); - const {steps} = useMemo(() => { + const {introduction, steps} = useMemo(() => { const doc = docsConfig[configType] ?? docsConfig.onboarding; const docParams: DocsParams<any> = { @@ -78,6 +80,7 @@ export function ReplayOnboardingLayout({ return ( <AuthTokenGeneratorProvider projectSlug={projectSlug}> <Wrapper> + {introduction && <Introduction>{introduction}</Introduction>} <Steps> {steps.map(step => step.type === StepType.CONFIGURE ? ( @@ -85,7 +88,7 @@ export function ReplayOnboardingLayout({ key={step.title ?? step.type} {...{ ...step, - codeHeader: ( + codeHeader: hideMaskBlockToggles ? null : ( <ReplayConfigToggle blockToggle={block} maskToggle={mask} @@ -124,3 +127,9 @@ const Wrapper = styled('div')` } } `; + +const Introduction = styled('div')` + display: flex; + flex-direction: column; + margin: 0 0 ${space(2)} 0; +`; diff --git a/static/app/components/replaysOnboarding/sidebar.tsx b/static/app/components/replaysOnboarding/sidebar.tsx index 197afc11420f69..2aba0ac973649d 100644 --- a/static/app/components/replaysOnboarding/sidebar.tsx +++ b/static/app/components/replaysOnboarding/sidebar.tsx @@ -10,7 +10,6 @@ import {CompactSelect} from 'sentry/components/compactSelect'; import RadioGroup from 'sentry/components/forms/controls/radioGroup'; import IdBadge from 'sentry/components/idBadge'; import LoadingIndicator from 'sentry/components/loadingIndicator'; -import {MobileBetaBanner} from 'sentry/components/onboarding/gettingStartedDoc/utils'; import useCurrentProjectState from 'sentry/components/onboarding/gettingStartedDoc/utils/useCurrentProjectState'; import {useLoadGettingStarted} from 'sentry/components/onboarding/gettingStartedDoc/utils/useLoadGettingStarted'; import {PlatformOptionDropdown} from 'sentry/components/replaysOnboarding/platformOptionDropdown'; @@ -21,10 +20,10 @@ import type {CommonSidebarProps} from 'sentry/components/sidebar/types'; import {SidebarPanelKey} from 'sentry/components/sidebar/types'; import TextOverflow from 'sentry/components/textOverflow'; import { - backend, replayBackendPlatforms, replayFrontendPlatforms, replayJsLoaderInstructionsPlatformList, + replayMobilePlatforms, replayOnboardingPlatforms, replayPlatforms, } from 'sentry/data/platformCategories'; @@ -162,6 +161,8 @@ function OnboardingContent({ currentProject: Project; hasDocs: boolean; }) { + const organization = useOrganization(); + const jsFrameworkSelectOptions = replayJsFrameworkOptions().map(platform => { return { value: platform.id, @@ -175,40 +176,29 @@ function OnboardingContent({ }; }); - const organization = useOrganization(); const [jsFramework, setJsFramework] = useState<{ value: PlatformKey; label?: ReactNode; textValue?: string; }>(jsFrameworkSelectOptions[0]); - const defaultTab = - currentProject.platform && backend.includes(currentProject.platform) - ? 'jsLoader' - : 'npm'; - - const {getParamValue: setupMode, setParamValue: setSetupMode} = useUrlParams( - 'mode', - defaultTab - ); - - const showJsFrameworkInstructions = - currentProject.platform && - replayBackendPlatforms.includes(currentProject.platform) && - setupMode() === 'npm'; - + const backendPlatform = + currentProject.platform && replayBackendPlatforms.includes(currentProject.platform); + const mobilePlatform = + currentProject.platform && replayMobilePlatforms.includes(currentProject.platform); const npmOnlyFramework = currentProject.platform && replayFrontendPlatforms .filter((p): p is PlatformKey => p !== 'javascript') .includes(currentProject.platform); - const showRadioButtons = - currentProject.platform && - replayJsLoaderInstructionsPlatformList.includes(currentProject.platform); + const defaultTab = backendPlatform ? 'jsLoader' : 'npm'; + const {getParamValue: setupMode, setParamValue: setSetupMode} = useUrlParams( + 'mode', + defaultTab + ); - const backendPlatforms = - currentProject.platform && replayBackendPlatforms.includes(currentProject.platform); + const showJsFrameworkInstructions = backendPlatform && setupMode() === 'npm'; const currentPlatform = currentProject.platform ? platforms.find(p => p.id === currentProject.platform) ?? otherPlatform @@ -240,6 +230,10 @@ function OnboardingContent({ productType: 'replay', }); + const showRadioButtons = + currentProject.platform && + replayJsLoaderInstructionsPlatformList.includes(currentProject.platform); + const radioButtons = ( <Header> {showRadioButtons ? ( @@ -248,7 +242,7 @@ function OnboardingContent({ choices={[ [ 'npm', - backendPlatforms ? ( + backendPlatform ? ( <PlatformSelect key="platform-select"> {tct('I use [platformSelect]', { platformSelect: ( @@ -283,6 +277,7 @@ function OnboardingContent({ onChange={setSetupMode} /> ) : ( + !mobilePlatform && docs?.platformOptions && !isProjKeysLoading && ( <PlatformSelect> @@ -306,22 +301,6 @@ function OnboardingContent({ ); } - // TODO: remove once we have mobile replay onboarding - if (['android', 'react-native'].includes(currentPlatform.language)) { - return ( - <MobileBetaBanner - link={`https://docs.sentry.io/platforms/${currentPlatform.language}/session-replay/`} - /> - ); - } - if (currentPlatform.language === 'apple') { - return ( - <MobileBetaBanner - link={`https://docs.sentry.io/platforms/apple/guides/ios/session-replay/`} - /> - ); - } - const doesNotSupportReplay = currentProject.platform ? !replayPlatforms.includes(currentProject.platform) : true; @@ -375,6 +354,7 @@ function OnboardingContent({ <Fragment> {radioButtons} <ReplayOnboardingLayout + hideMaskBlockToggles={mobilePlatform} docsConfig={docs} dsn={dsn} activeProductSelection={[]} @@ -384,8 +364,9 @@ function OnboardingContent({ configType={ setupMode() === 'npm' || // switched to NPM option (!setupMode() && defaultTab === 'npm') || // default value for FE frameworks when ?mode={...} in URL is not set yet - npmOnlyFramework // even if '?mode=jsLoader', only show npm instructions for FE frameworks - ? 'replayOnboardingNpm' + npmOnlyFramework || + mobilePlatform // even if '?mode=jsLoader', only show npm/default instructions for FE frameworks & mobile platforms + ? 'replayOnboarding' : 'replayOnboardingJsLoader' } /> diff --git a/static/app/data/platformCategories.tsx b/static/app/data/platformCategories.tsx index 3faf9fcf73a581..b30c69a502dfa1 100644 --- a/static/app/data/platformCategories.tsx +++ b/static/app/data/platformCategories.tsx @@ -475,6 +475,7 @@ export const replayPlatforms: readonly PlatformKey[] = [ export const replayOnboardingPlatforms: readonly PlatformKey[] = [ ...replayFrontendPlatforms.filter(p => !['javascript-backbone'].includes(p)), ...replayBackendPlatforms, + ...replayMobilePlatforms, ]; // These are the supported replay platforms that can also be set up using the JS loader. diff --git a/static/app/gettingStartedDocs/android/android.tsx b/static/app/gettingStartedDocs/android/android.tsx index 0d75105a393fa5..7854d5925e8c25 100644 --- a/static/app/gettingStartedDocs/android/android.tsx +++ b/static/app/gettingStartedDocs/android/android.tsx @@ -10,7 +10,9 @@ import type { DocsParams, OnboardingConfig, } from 'sentry/components/onboarding/gettingStartedDoc/types'; +import {MobileBetaBanner} from 'sentry/components/onboarding/gettingStartedDoc/utils'; import {getAndroidMetricsOnboarding} from 'sentry/components/onboarding/gettingStartedDoc/utils/metricsOnboarding'; +import {getReplayMobileConfigureDescription} from 'sentry/components/onboarding/gettingStartedDoc/utils/replayOnboarding'; import {feedbackOnboardingCrashApiJava} from 'sentry/gettingStartedDocs/java/java'; import {t, tct} from 'sentry/locale'; import {getPackageVersion} from 'sentry/utils/gettingStartedDocs/getPackageVersion'; @@ -93,6 +95,24 @@ val breakWorld = Button(this).apply { addContentView(breakWorld, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))`; +const getReplaySetupSnippetKotlin = (params: Params) => ` +SentryAndroid.init(context) { options -> + options.dsn = "${params.dsn.public}" + options.isDebug = true + + // Currently under experimental options: + options.experimental.sessionReplay.errorSampleRate = 1.0 + options.experimental.sessionReplay.sessionSampleRate = 1.0 +}`; + +const getReplaySetupSnippetXml = () => ` +<meta-data android:name="io.sentry.session-replay.error-sample-rate" android:value="1.0" /> +<meta-data android:name="io.sentry.session-replay.session-sample-rate" android:value="1.0" />`; + +const getReplayConfigurationSnippet = () => ` +options.experimental.sessionReplay.redactAllText = true +options.experimental.sessionReplay.redactAllImages = true`; + const onboarding: OnboardingConfig<PlatformOptions> = { install: params => isAutoInstall(params) @@ -283,12 +303,145 @@ const onboarding: OnboardingConfig<PlatformOptions> = { ], }; +const replayOnboarding: OnboardingConfig<PlatformOptions> = { + introduction: () => ( + <MobileBetaBanner link="https://docs.sentry.io/platforms/android/session-replay/" /> + ), + install: (params: Params) => [ + { + type: StepType.INSTALL, + description: tct( + "Make sure your Sentry Android SDK version is at least 7.12.0. The easiest way to update through the Sentry Android Gradle plugin to your app module's [code:build.gradle] file.", + {code: <code />} + ), + configurations: [ + { + code: [ + { + label: 'Groovy', + value: 'groovy', + language: 'groovy', + filename: 'app/build.gradle', + code: `plugins { + id "com.android.application" + id "io.sentry.android.gradle" version "${getPackageVersion( + params, + 'sentry.java.android.gradle-plugin', + '4.11.0' + )}" +}`, + }, + { + label: 'Kotlin', + value: 'kotlin', + language: 'kotlin', + filename: 'app/build.gradle.kts', + code: `plugins { + id("com.android.application") + id("io.sentry.android.gradle") version "${getPackageVersion( + params, + 'sentry.java.android.gradle-plugin', + '4.11.0' + )}" +}`, + }, + ], + }, + { + description: tct( + 'If you have the SDK installed without the Sentry Gradle Plugin, you can update the version directly in the [code:build.gradle] through:', + {code: <code />} + ), + }, + { + code: [ + { + label: 'Groovy', + value: 'groovy', + language: 'groovy', + filename: 'app/build.gradle', + code: `dependencies { + implementation 'io.sentry:sentry-android:${getPackageVersion( + params, + 'sentry.java.android', + '7.14.0' + )}' +}`, + }, + { + label: 'Kotlin', + value: 'kotlin', + language: 'kotlin', + filename: 'app/build.gradle.kts', + code: `dependencies { + implementation("io.sentry:sentry-android:${getPackageVersion( + params, + 'sentry.java.android', + '7.14.0' + )}") +}`, + }, + ], + }, + { + description: t( + 'To set up the integration, add the following to your Sentry initialization:' + ), + }, + { + code: [ + { + label: 'Kotlin', + value: 'kotlin', + language: 'kotlin', + code: getReplaySetupSnippetKotlin(params), + }, + { + label: 'XML', + value: 'xml', + language: 'xml', + filename: 'AndroidManifest.xml', + code: getReplaySetupSnippetXml(), + }, + ], + }, + ], + }, + ], + configure: () => [ + { + type: StepType.CONFIGURE, + description: getReplayMobileConfigureDescription({ + link: 'https://docs.sentry.io/platforms/android/session-replay/#privacy', + }), + configurations: [ + { + description: t( + 'The following code is the default configuration, which masks and blocks everything.' + ), + code: [ + { + label: 'Kotlin', + value: 'kotlin', + language: 'kotlin', + code: getReplayConfigurationSnippet(), + }, + ], + }, + ], + }, + ], + verify: () => [], + nextSteps: () => [], +}; + const docs: Docs<PlatformOptions> = { onboarding, feedbackOnboardingCrashApi: feedbackOnboardingCrashApiJava, crashReportOnboarding: feedbackOnboardingCrashApiJava, customMetricsOnboarding: getAndroidMetricsOnboarding(), platformOptions, + replayOnboarding, }; export default docs; diff --git a/static/app/gettingStartedDocs/apple/ios.tsx b/static/app/gettingStartedDocs/apple/ios.tsx index 98e0cf409b9b2b..a1eb9d10f85742 100644 --- a/static/app/gettingStartedDocs/apple/ios.tsx +++ b/static/app/gettingStartedDocs/apple/ios.tsx @@ -9,7 +9,9 @@ import type { DocsParams, OnboardingConfig, } from 'sentry/components/onboarding/gettingStartedDoc/types'; +import {MobileBetaBanner} from 'sentry/components/onboarding/gettingStartedDoc/utils'; import {metricTagsExplanation} from 'sentry/components/onboarding/gettingStartedDoc/utils/metricsOnboarding'; +import {getReplayMobileConfigureDescription} from 'sentry/components/onboarding/gettingStartedDoc/utils/replayOnboarding'; import {appleFeedbackOnboarding} from 'sentry/gettingStartedDocs/apple/macos'; import {t, tct} from 'sentry/locale'; import {getPackageVersion} from 'sentry/utils/gettingStartedDocs/getPackageVersion'; @@ -244,6 +246,20 @@ const getVerifyMetricsSnippetObjC = () => ` tags: @{ @"screen" : @"login" } ];`; +const getReplaySetupSnippet = (params: Params) => ` +SentrySDK.start(configureOptions: { options in + options.dsn = "${params.dsn.public}" + options.debug = true + + // Currently under experimental options: + options.experimental.sessionReplay.onErrorSampleRate = 1.0 + options.experimental.sessionReplay.sessionSampleRate = 1.0 +})`; + +const getReplayConfigurationSnippet = () => ` +options.experimental.sessionReplay.redactAllText = true +options.experimental.sessionReplay.redactAllImages = true`; + const onboarding: OnboardingConfig<PlatformOptions> = { install: params => isAutoInstall(params) @@ -615,12 +631,99 @@ const metricsOnboarding: OnboardingConfig<PlatformOptions> = { ], }; +const replayOnboarding: OnboardingConfig<PlatformOptions> = { + introduction: () => ( + <MobileBetaBanner link="https://docs.sentry.io/platforms/android/session-replay/" /> + ), + install: (params: Params) => [ + { + type: StepType.INSTALL, + description: t( + 'Make sure your Sentry Cocoa SDK version is at least 8.31.1. If you already have the SDK installed, you can update it to the latest version with:' + ), + configurations: [ + { + code: [ + { + label: 'SPM', + value: 'spm', + language: 'swift', + code: `.package(url: "https://github.com/getsentry/sentry-cocoa", from: "${getPackageVersion( + params, + 'sentry.cocoa', + '8.36.0' + )}"),`, + }, + { + label: 'CocoaPods', + value: 'cocoapods', + language: 'ruby', + code: `pod update`, + }, + { + label: 'Carthage', + value: 'carthage', + language: 'swift', + code: `github "getsentry/sentry-cocoa" "${getPackageVersion( + params, + 'sentry.cocoa', + '8.36.0' + )}"`, + }, + ], + }, + { + description: t( + 'To set up the integration, add the following to your Sentry initialization:' + ), + }, + { + code: [ + { + label: 'Swift', + value: 'swift', + language: 'swift', + code: getReplaySetupSnippet(params), + }, + ], + }, + ], + }, + ], + configure: () => [ + { + type: StepType.CONFIGURE, + description: getReplayMobileConfigureDescription({ + link: 'https://docs.sentry.io/platforms/apple/guides/ios/session-replay/#privacy', + }), + configurations: [ + { + description: t( + 'The following code is the default configuration, which masks and blocks everything.' + ), + code: [ + { + label: 'Swift', + value: 'swift', + language: 'swift', + code: getReplayConfigurationSnippet(), + }, + ], + }, + ], + }, + ], + verify: () => [], + nextSteps: () => [], +}; + const docs: Docs<PlatformOptions> = { onboarding, feedbackOnboardingCrashApi: appleFeedbackOnboarding, crashReportOnboarding: appleFeedbackOnboarding, customMetricsOnboarding: metricsOnboarding, platformOptions, + replayOnboarding, }; export default docs; diff --git a/static/app/gettingStartedDocs/capacitor/capacitor.tsx b/static/app/gettingStartedDocs/capacitor/capacitor.tsx index 022e901b22c663..dae7338fa95083 100644 --- a/static/app/gettingStartedDocs/capacitor/capacitor.tsx +++ b/static/app/gettingStartedDocs/capacitor/capacitor.tsx @@ -487,7 +487,7 @@ const docs: Docs<PlatformOptions> = { onboarding, platformOptions, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/electron/electron.tsx b/static/app/gettingStartedDocs/electron/electron.tsx index d773f64488b041..0c34d3f8fa170c 100644 --- a/static/app/gettingStartedDocs/electron/electron.tsx +++ b/static/app/gettingStartedDocs/electron/electron.tsx @@ -363,7 +363,7 @@ init({ const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding, crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/angular.tsx b/static/app/gettingStartedDocs/javascript/angular.tsx index 29074a1914f20d..8d008c35ffe293 100644 --- a/static/app/gettingStartedDocs/javascript/angular.tsx +++ b/static/app/gettingStartedDocs/javascript/angular.tsx @@ -375,7 +375,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/astro.tsx b/static/app/gettingStartedDocs/javascript/astro.tsx index 6df7b83d0190e3..6a17a79be4ddfb 100644 --- a/static/app/gettingStartedDocs/javascript/astro.tsx +++ b/static/app/gettingStartedDocs/javascript/astro.tsx @@ -377,7 +377,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/ember.tsx b/static/app/gettingStartedDocs/javascript/ember.tsx index aaf60a79c8ca4a..3afb07d333c5bf 100644 --- a/static/app/gettingStartedDocs/javascript/ember.tsx +++ b/static/app/gettingStartedDocs/javascript/ember.tsx @@ -288,7 +288,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/gatsby.tsx b/static/app/gettingStartedDocs/javascript/gatsby.tsx index 6bbd61954fb865..f1ff44995249b4 100644 --- a/static/app/gettingStartedDocs/javascript/gatsby.tsx +++ b/static/app/gettingStartedDocs/javascript/gatsby.tsx @@ -322,7 +322,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/javascript.tsx b/static/app/gettingStartedDocs/javascript/javascript.tsx index b2f332d583fdb8..f412e4039a712b 100644 --- a/static/app/gettingStartedDocs/javascript/javascript.tsx +++ b/static/app/gettingStartedDocs/javascript/javascript.tsx @@ -289,7 +289,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, replayOnboardingJsLoader, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, diff --git a/static/app/gettingStartedDocs/javascript/nextjs.tsx b/static/app/gettingStartedDocs/javascript/nextjs.tsx index 195dec3cc92f20..3e80a4b93e1076 100644 --- a/static/app/gettingStartedDocs/javascript/nextjs.tsx +++ b/static/app/gettingStartedDocs/javascript/nextjs.tsx @@ -285,7 +285,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({ getInstallConfig: getManualInstallConfig, }), diff --git a/static/app/gettingStartedDocs/javascript/react.tsx b/static/app/gettingStartedDocs/javascript/react.tsx index e5b23ac8b612ed..86e24f76408779 100644 --- a/static/app/gettingStartedDocs/javascript/react.tsx +++ b/static/app/gettingStartedDocs/javascript/react.tsx @@ -314,7 +314,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/remix.tsx b/static/app/gettingStartedDocs/javascript/remix.tsx index 6e8529f6cf97c8..cf4285161bc6ef 100644 --- a/static/app/gettingStartedDocs/javascript/remix.tsx +++ b/static/app/gettingStartedDocs/javascript/remix.tsx @@ -232,7 +232,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/solid.tsx b/static/app/gettingStartedDocs/javascript/solid.tsx index 357750b5a40448..a9f60529b73208 100644 --- a/static/app/gettingStartedDocs/javascript/solid.tsx +++ b/static/app/gettingStartedDocs/javascript/solid.tsx @@ -314,7 +314,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/solidstart.tsx b/static/app/gettingStartedDocs/javascript/solidstart.tsx index cef5ca1d90e49a..b4713991c9cacf 100644 --- a/static/app/gettingStartedDocs/javascript/solidstart.tsx +++ b/static/app/gettingStartedDocs/javascript/solidstart.tsx @@ -472,7 +472,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/svelte.tsx b/static/app/gettingStartedDocs/javascript/svelte.tsx index 571f8de71db8a9..4aa5902e1463b2 100644 --- a/static/app/gettingStartedDocs/javascript/svelte.tsx +++ b/static/app/gettingStartedDocs/javascript/svelte.tsx @@ -311,7 +311,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/sveltekit.tsx b/static/app/gettingStartedDocs/javascript/sveltekit.tsx index d838be59c457b0..689e2139bcdb99 100644 --- a/static/app/gettingStartedDocs/javascript/sveltekit.tsx +++ b/static/app/gettingStartedDocs/javascript/sveltekit.tsx @@ -208,7 +208,7 @@ const crashReportOnboarding: OnboardingConfig = { const docs: Docs = { onboarding, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/javascript/vue.tsx b/static/app/gettingStartedDocs/javascript/vue.tsx index 9ae2313cd04cdc..4c2631c045d99f 100644 --- a/static/app/gettingStartedDocs/javascript/vue.tsx +++ b/static/app/gettingStartedDocs/javascript/vue.tsx @@ -384,7 +384,7 @@ const docs: Docs<PlatformOptions> = { onboarding, platformOptions, feedbackOnboardingNpm: feedbackOnboarding, - replayOnboardingNpm: replayOnboarding, + replayOnboarding, customMetricsOnboarding: getJSMetricsOnboarding({getInstallConfig}), crashReportOnboarding, }; diff --git a/static/app/gettingStartedDocs/react-native/react-native.tsx b/static/app/gettingStartedDocs/react-native/react-native.tsx index eab3fd8cd56286..dfb36d6bbda007 100644 --- a/static/app/gettingStartedDocs/react-native/react-native.tsx +++ b/static/app/gettingStartedDocs/react-native/react-native.tsx @@ -9,11 +9,13 @@ import type { DocsParams, OnboardingConfig, } from 'sentry/components/onboarding/gettingStartedDoc/types'; +import {MobileBetaBanner} from 'sentry/components/onboarding/gettingStartedDoc/utils'; import { getCrashReportApiIntroduction, getCrashReportInstallDescription, } from 'sentry/components/onboarding/gettingStartedDoc/utils/feedbackOnboarding'; import {getReactNativeMetricsOnboarding} from 'sentry/components/onboarding/gettingStartedDoc/utils/metricsOnboarding'; +import {getReplayMobileConfigureDescription} from 'sentry/components/onboarding/gettingStartedDoc/utils/replayOnboarding'; import {t, tct} from 'sentry/locale'; type Params = DocsParams; @@ -72,6 +74,27 @@ shopCheckout() { } }`; +const getReplaySetupSnippet = (params: Params) => ` +import * as Sentry from '@sentry/react-native'; + +Sentry.init({ + dsn: "${params.dsn.public}", + _experiments: { + replaysSessionSampleRate: 1.0, + replaysOnErrorSampleRate: 1.0, + }, + integrations: [ + Sentry.mobileReplayIntegration(), + ], +});`; + +const getReplayConfigurationSnippet = () => ` +Sentry.mobileReplayIntegration({ + maskAllText: true, + maskAllImages: true, + maskAllVectors: true, +}),`; + const onboarding: OnboardingConfig = { install: () => [ { @@ -381,11 +404,90 @@ const getInstallConfig = () => [ }, ]; +const replayOnboarding: OnboardingConfig = { + introduction: () => ( + <MobileBetaBanner link="https://docs.sentry.io/platforms/react-native/session-replay/" /> + ), + install: (params: Params) => [ + { + type: StepType.INSTALL, + description: t( + 'Make sure your Sentry React Native SDK version is at least 5.26.0. If you already have the SDK installed, you can update it to the latest version with:' + ), + configurations: [ + { + code: [ + { + label: 'npm', + value: 'npm', + language: 'bash', + code: `npm install @sentry/react-native --save`, + }, + { + label: 'yarn', + value: 'yarn', + language: 'bash', + code: `yarn add @sentry/react-native`, + }, + { + label: 'pnpm', + value: 'pnpm', + language: 'bash', + code: `pnpm add @sentry/react-native`, + }, + ], + }, + { + description: t( + 'To set up the integration, add the following to your Sentry initialization:' + ), + }, + { + code: [ + { + label: 'JavaScript', + value: 'javascript', + language: 'javascript', + code: getReplaySetupSnippet(params), + }, + ], + }, + ], + }, + ], + configure: () => [ + { + type: StepType.CONFIGURE, + description: getReplayMobileConfigureDescription({ + link: 'https://docs.sentry.io/platforms/react-native/session-replay/#privacy', + }), + configurations: [ + { + description: t( + 'The following code is the default configuration, which masks and blocks everything.' + ), + code: [ + { + label: 'JavaScript', + value: 'javascript', + language: 'javascript', + code: getReplayConfigurationSnippet(), + }, + ], + }, + ], + }, + ], + verify: () => [], + nextSteps: () => [], +}; + const docs: Docs = { onboarding, feedbackOnboardingCrashApi, crashReportOnboarding: feedbackOnboardingCrashApi, customMetricsOnboarding: getReactNativeMetricsOnboarding({getInstallConfig}), + replayOnboarding, }; export default docs;
bb749f0132e1b7768a1d1af97a28eedf98c9546e
2023-12-15 04:52:57
Snigdha Sharma
fix(severity): Add is_new to high severity condition (#61810)
false
Add is_new to high severity condition (#61810)
fix
diff --git a/src/sentry/rules/conditions/high_priority_issue.py b/src/sentry/rules/conditions/high_priority_issue.py index 5b946af8af984c..1c551e026d1bf4 100644 --- a/src/sentry/rules/conditions/high_priority_issue.py +++ b/src/sentry/rules/conditions/high_priority_issue.py @@ -17,8 +17,8 @@ class HighPriorityIssueCondition(EventCondition): id = "sentry.rules.conditions.high_priority_issue.HighPriorityIssueCondition" label = "Sentry marks an issue as high priority" - def is_high_severity(self, state: EventState, group: Optional[Group]) -> bool: - if not group: + def is_new_high_severity(self, state: EventState, group: Optional[Group]) -> bool: + if not group or not state.is_new: return False try: @@ -32,10 +32,10 @@ def passes(self, event: GroupEvent, state: EventState) -> bool: if not has_high_priority_issue_alerts(self.project): return False - is_high_severity = self.is_high_severity(state, event.group) + is_new_high_severity = self.is_new_high_severity(state, event.group) is_escalating = state.has_reappeared or state.has_escalated - return is_high_severity or is_escalating + return is_new_high_severity or is_escalating def get_activity( self, start: datetime, end: datetime, limit: int diff --git a/tests/sentry/rules/conditions/test_high_severity_issue.py b/tests/sentry/rules/conditions/test_high_priority_issue.py similarity index 62% rename from tests/sentry/rules/conditions/test_high_severity_issue.py rename to tests/sentry/rules/conditions/test_high_priority_issue.py index e1022880952ca0..2e17892560de57 100644 --- a/tests/sentry/rules/conditions/test_high_severity_issue.py +++ b/tests/sentry/rules/conditions/test_high_priority_issue.py @@ -19,10 +19,13 @@ def test_applies_correctly(self): self.assertPasses(rule, event, has_reappeared=True, has_escalated=False) self.assertPasses(rule, event, has_reappeared=False, has_escalated=True) self.assertDoesNotPass(rule, event, has_reappeared=False, has_escalated=False) + self.assertDoesNotPass(rule, event, is_new=False, has_reappeared=False, has_escalated=False) event.group.data["metadata"] = {"severity": "0.7"} - self.assertPasses(rule, event, has_reappeared=False, has_escalated=False) + self.assertPasses(rule, event, is_new=True, has_reappeared=False, has_escalated=False) + self.assertDoesNotPass(rule, event, is_new=False, has_reappeared=False, has_escalated=False) event.group.data["metadata"] = {"severity": "0.0"} - self.assertPasses(rule, event, has_reappeared=False, has_escalated=True) - self.assertDoesNotPass(rule, event, has_reappeared=False, has_escalated=False) + self.assertPasses(rule, event, is_new=False, has_reappeared=False, has_escalated=True) + self.assertPasses(rule, event, is_new=False, has_reappeared=False, has_escalated=True) + self.assertDoesNotPass(rule, event, is_new=True, has_reappeared=False, has_escalated=False)
ff310643e96d28be5c449d66c7282bc4d56067a9
2022-12-22 00:31:23
Dameli Ushbayeva
chore(perf-issues): Remove frontend perf issue feature flag (#42556)
false
Remove frontend perf issue feature flag (#42556)
chore
diff --git a/static/app/components/events/eventEntries.spec.tsx b/static/app/components/events/eventEntries.spec.tsx index c16dfd50d26015..0f814107c03eeb 100644 --- a/static/app/components/events/eventEntries.spec.tsx +++ b/static/app/components/events/eventEntries.spec.tsx @@ -6,9 +6,7 @@ import EventEntries from 'sentry/components/events/eventEntries'; import {Group, IssueCategory} from 'sentry/types'; import {EntryType, Event} from 'sentry/types/event'; -const {organization, project} = initializeData({ - features: ['performance-issues'], -}); +const {organization, project} = initializeData(); const api = new MockApiClient(); diff --git a/static/app/components/events/eventEntries.tsx b/static/app/components/events/eventEntries.tsx index 334aeacb5e9a82..b0d8e526fa8f71 100644 --- a/static/app/components/events/eventEntries.tsx +++ b/static/app/components/events/eventEntries.tsx @@ -463,10 +463,7 @@ function Entries({ return null; } - if ( - group?.issueCategory === IssueCategory.PERFORMANCE && - organization.features?.includes('performance-issues') - ) { + if (group?.issueCategory === IssueCategory.PERFORMANCE) { injectResourcesEntry(definedEvent); } diff --git a/static/app/components/events/eventEntry.tsx b/static/app/components/events/eventEntry.tsx index 1b2964c4e9cb7d..bd3a9e31940811 100644 --- a/static/app/components/events/eventEntry.tsx +++ b/static/app/components/events/eventEntry.tsx @@ -152,10 +152,7 @@ function EventEntry({entry, projectSlug, event, organization, group, isShare}: P return null; } - if ( - group?.issueCategory === IssueCategory.PERFORMANCE && - organization?.features?.includes('performance-issues') - ) { + if (group?.issueCategory === IssueCategory.PERFORMANCE) { return ( <SpanEvidenceSection issueType={group?.issueType} diff --git a/static/app/components/events/interfaces/performance/spanEvidence.spec.tsx b/static/app/components/events/interfaces/performance/spanEvidence.spec.tsx index 3f507697d8ce49..74cb1650080604 100644 --- a/static/app/components/events/interfaces/performance/spanEvidence.spec.tsx +++ b/static/app/components/events/interfaces/performance/spanEvidence.spec.tsx @@ -11,9 +11,7 @@ import {IssueType} from 'sentry/types'; import {SpanEvidenceSection} from './spanEvidence'; -const {organization} = initializeData({ - features: ['performance-issues'], -}); +const {organization} = initializeData(); describe('spanEvidence', () => { it('renders and highlights the correct data in the span evidence section', () => { diff --git a/static/app/views/admin/adminSettings.tsx b/static/app/views/admin/adminSettings.tsx index 67b6e115f2f65f..309e5c2126b0f2 100644 --- a/static/app/views/admin/adminSettings.tsx +++ b/static/app/views/admin/adminSettings.tsx @@ -17,12 +17,6 @@ const optionsAvailable = [ 'auth.user-rate-limit', 'api.rate-limit.org-create', 'beacon.anonymous', - 'performance.issues.all.problem-detection', - 'performance.issues.all.problem-creation', - 'performance.issues.all.early-adopter-rollout', - 'performance.issues.all.general-availability-rollout', - 'performance.issues.all.post-process-group-early-adopter-rollout', - 'performance.issues.all.post-process-group-ga-rollout', 'performance.issues.n_plus_one_db.problem-creation', 'performance.issues.n_plus_one_db_ext.problem-creation', 'performance.issues.n_plus_one_db.count_threshold', @@ -100,15 +94,6 @@ export default class AdminSettings extends AsyncView<{}, State> { </Panel> <Feature features={['organizations:performance-issues-dev']}> - <Panel> - <PanelHeader>Performance Issues - All</PanelHeader> - {fields['performance.issues.all.problem-detection']} - {fields['performance.issues.all.problem-creation']} - {fields['performance.issues.all.early-adopter-rollout']} - {fields['performance.issues.all.general-availability-rollout']} - {fields['performance.issues.all.post-process-group-early-adopter-rollout']} - {fields['performance.issues.all.post-process-group-ga-rollout']} - </Panel> <Panel> <PanelHeader>Performance Issues - Detectors</PanelHeader> {fields['performance.issues.n_plus_one_db.problem-creation']} diff --git a/static/app/views/issueList/actions/index.tsx b/static/app/views/issueList/actions/index.tsx index e38a460b026e63..3478567649160d 100644 --- a/static/app/views/issueList/actions/index.tsx +++ b/static/app/views/issueList/actions/index.tsx @@ -90,13 +90,9 @@ function IssueListActions({ SelectedGroupStore.deselectAll(); } - // TODO: Remove this when merging/deleting performance issues is supported + // TODO: Remove issue.category:error filter when merging/deleting performance issues is supported // This silently avoids performance issues for bulk actions - const queryExcludingPerformanceIssues = organization.features.includes( - 'performance-issues' - ) - ? `${query ?? ''} issue.category:error` - : query; + const queryExcludingPerformanceIssues = `${query ?? ''} issue.category:error`; function handleDelete() { actionSelectedGroups(itemIds => { diff --git a/static/app/views/issueList/actions/utils.tsx b/static/app/views/issueList/actions/utils.tsx index af43c692a4df99..2dbaa640cd5e1c 100644 --- a/static/app/views/issueList/actions/utils.tsx +++ b/static/app/views/issueList/actions/utils.tsx @@ -43,14 +43,13 @@ function getBulkConfirmMessage(action: string, queryCount: number) { function PerformanceIssueAlert({ allInQuerySelected, - organization, children, }: { allInQuerySelected: boolean; children: string; organization: Organization; }) { - if (!allInQuerySelected || !organization.features.includes('performance-issues')) { + if (!allInQuerySelected) { return null; }
4862dc2da45c2c0721030d2562eab5b61dbf7a24
2024-10-25 02:02:58
Tony Xiao
fix(profiling): Pass start/end timestamps for standalone profile chunks (#79714)
false
Pass start/end timestamps for standalone profile chunks (#79714)
fix
diff --git a/src/sentry/profiles/flamegraph.py b/src/sentry/profiles/flamegraph.py index 27cf08f616a624..4fcbc80d0bba42 100644 --- a/src/sentry/profiles/flamegraph.py +++ b/src/sentry/profiles/flamegraph.py @@ -251,8 +251,8 @@ def get_chunks_from_spans_metadata( for row in data: intervals = [ { - "start": str(int(datetime.fromisoformat(el["start"]).timestamp() * 10**9)), - "end": str(int(datetime.fromisoformat(el["end"]).timestamp() * 10**9)), + "start": str(int(datetime.fromisoformat(el["start"]).timestamp() * 1e9)), + "end": str(int(datetime.fromisoformat(el["end"]).timestamp() * 1e9)), "active_thread_id": el["active_thread_id"], } for el in spans[row["profiler_id"]] @@ -684,6 +684,10 @@ def get_profile_candidates_from_profiles(self) -> ProfileCandidates: "project_id": row["project_id"], "profiler_id": row["profiler_id"], "chunk_id": row["chunk_id"], + "start": str( + int(datetime.fromisoformat(row["start_timestamp"]).timestamp() * 1e9) + ), + "end": str(int(datetime.fromisoformat(row["end_timestamp"]).timestamp() * 1e9)), } for row in continuous_profile_results["data"] ] diff --git a/tests/sentry/api/endpoints/test_organization_profiling_profiles.py b/tests/sentry/api/endpoints/test_organization_profiling_profiles.py index a4f68c9aec6a1a..d5b6fda6133132 100644 --- a/tests/sentry/api/endpoints/test_organization_profiling_profiles.py +++ b/tests/sentry/api/endpoints/test_organization_profiling_profiles.py @@ -704,6 +704,8 @@ def test_queries_profile_candidates_from_profiles_with_continuous_profiles_witho "project_id": self.project.id, "profiler_id": profiler_id, "chunk_id": chunk["chunk_id"], + "start": str(int((start_timestamp - buffer).timestamp() * 1e9)), + "end": str(int((finish_timestamp + buffer).timestamp() * 1e9)), }, ], },
8caa42e2eea1d68ce05c4947cb2f39fa756ba1e3
2020-06-18 01:42:20
k-fish
fix(discover): Fix race condition when updating date range (#19398)
false
Fix race condition when updating date range (#19398)
fix
diff --git a/src/sentry/static/sentry/app/components/charts/eventsRequest.tsx b/src/sentry/static/sentry/app/components/charts/eventsRequest.tsx index 08cdaa4183dfbf..2a72a0c2e097e6 100644 --- a/src/sentry/static/sentry/app/components/charts/eventsRequest.tsx +++ b/src/sentry/static/sentry/app/components/charts/eventsRequest.tsx @@ -245,6 +245,7 @@ class EventsRequest extends React.PureComponent<EventsRequestProps, EventsReques })); try { + api.clear(); timeseriesData = await doEventsRequest(api, props); } catch (resp) { if (resp && resp.responseJSON && resp.responseJSON.detail) { diff --git a/src/sentry/static/sentry/app/views/eventsV2/results.tsx b/src/sentry/static/sentry/app/views/eventsV2/results.tsx index 9fdc637fca052f..ca8e6f6052ec74 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/results.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/results.tsx @@ -81,18 +81,21 @@ class Results extends React.Component<Props, State> { componentDidUpdate(prevProps: Props, prevState: State) { const {api, location, organization, selection} = this.props; const {eventView} = this.state; - if ( - !isEqual(prevProps.selection.projects, selection.projects) || - !isEqual(prevProps.selection.datetime, selection.datetime) - ) { - loadOrganizationTags(api, organization.slug, selection); - } this.checkEventView(); const currentQuery = eventView.getEventsAPIPayload(location); const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location); if (!isAPIPayloadSimilar(currentQuery, prevQuery)) { + api.clear(); this.fetchTotalCount(); + if ( + !isEqual(prevQuery.statsPeriod, currentQuery.statsPeriod) || + !isEqual(prevQuery.start, currentQuery.start) || + !isEqual(prevQuery.end, currentQuery.end) || + !isEqual(prevQuery.project, currentQuery.project) + ) { + loadOrganizationTags(api, organization.slug, selection); + } } } @@ -254,7 +257,7 @@ class Results extends React.Component<Props, State> { }; render() { - const {organization, location, router, api} = this.props; + const {organization, location, router} = this.props; const {eventView, error, errorCode, totalValues, showTags} = this.state; const query = decodeScalar(location.query.query) || ''; const title = this.getDocumentTitle(); @@ -280,7 +283,6 @@ class Results extends React.Component<Props, State> { onSearch={this.handleSearch} /> <ResultsChart - api={api} router={router} organization={organization} eventView={eventView} diff --git a/src/sentry/static/sentry/app/views/eventsV2/resultsChart.tsx b/src/sentry/static/sentry/app/views/eventsV2/resultsChart.tsx index 3f0ca2a2845131..4f5bf81b8e6c7c 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/resultsChart.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/resultsChart.tsx @@ -14,6 +14,7 @@ import getDynamicText from 'app/utils/getDynamicText'; import EventView from 'app/utils/discover/eventView'; import {DisplayModes} from 'app/utils/discover/types'; import {decodeScalar} from 'app/utils/queryString'; +import withApi from 'app/utils/withApi'; import ChartFooter from './chartFooter'; @@ -167,7 +168,7 @@ class ResultsChartContainer extends React.Component<ContainerProps> { } } -export default ResultsChartContainer; +export default withApi(ResultsChartContainer); export const StyledPanel = styled(Panel)` @media (min-width: ${p => p.theme.breakpoints[1]}) { diff --git a/src/sentry/static/sentry/app/views/eventsV2/table/index.tsx b/src/sentry/static/sentry/app/views/eventsV2/table/index.tsx index 9f453a3a4d8336..458c5ab1615e26 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/table/index.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/table/index.tsx @@ -92,6 +92,7 @@ class Table extends React.PureComponent<TableProps, TableState> { this.setState({isLoading: true, tableFetchID}); metric.mark({name: `discover-events-start-${apiPayload.query}`}); + this.props.api.clear(); this.props.api .requestPromise(url, { method: 'GET', diff --git a/tests/js/spec/components/charts/eventsRequest.spec.jsx b/tests/js/spec/components/charts/eventsRequest.spec.jsx index c89e3fc39ba4f4..badfe69208344d 100644 --- a/tests/js/spec/components/charts/eventsRequest.spec.jsx +++ b/tests/js/spec/components/charts/eventsRequest.spec.jsx @@ -18,7 +18,7 @@ describe('EventsRequest', function() { const organization = TestStubs.Organization(); const mock = jest.fn(() => null); const DEFAULTS = { - api: {}, + api: new MockApiClient(), projects: [parseInt(project.id, 10)], environments: [], period: '24h',
fda135bd7b395b01dd937cf78afee0a49b9974f6
2023-11-28 20:07:45
anthony sottile
ref: upgrade reportlab to 4.0.7 (#60620)
false
upgrade reportlab to 4.0.7 (#60620)
ref
diff --git a/requirements-dev-frozen.txt b/requirements-dev-frozen.txt index 7737ca9704f6c8..6c343d91d9e122 100644 --- a/requirements-dev-frozen.txt +++ b/requirements-dev-frozen.txt @@ -160,7 +160,7 @@ rb==1.10.0 redis==3.4.1 redis-py-cluster==2.1.0 regex==2022.9.13 -reportlab==3.6.13 +reportlab==4.0.7 requests==2.31.0 requests-oauthlib==1.2.0 responses==0.23.1 diff --git a/requirements-frozen.txt b/requirements-frozen.txt index ba7c3c3de1bf3c..ebde085b31ba42 100644 --- a/requirements-frozen.txt +++ b/requirements-frozen.txt @@ -106,7 +106,7 @@ rb==1.10.0 redis==3.4.1 redis-py-cluster==2.1.0 regex==2022.9.13 -reportlab==3.6.13 +reportlab==4.0.7 requests==2.31.0 requests-oauthlib==1.2.0 rfc3339-validator==0.1.2 diff --git a/requirements-getsentry.txt b/requirements-getsentry.txt index 4c33ababea24db..66f6cc7c7424ea 100644 --- a/requirements-getsentry.txt +++ b/requirements-getsentry.txt @@ -10,5 +10,5 @@ Avalara==20.9.0 PlanOut==0.6.0 pycountry==17.5.14 pyvat==1.3.15 -reportlab==3.6.13 +reportlab==4.0.7 stripe==3.1.0
08ded59f543aac0a451660309131d52a2a636584
2021-03-27 01:16:48
dependabot[bot]
build(deps): bump pyyaml from 5.3 to 5.4 (#24720)
false
bump pyyaml from 5.3 to 5.4 (#24720)
build
diff --git a/requirements-base.txt b/requirements-base.txt index 4ade69ca34321b..bbd65221729b7c 100644 --- a/requirements-base.txt +++ b/requirements-base.txt @@ -38,7 +38,7 @@ python-dateutil==2.8.1 python-memcached==1.59 python-u2flib-server==5.0.0 python3-saml==1.4.1 -PyYAML==5.3 +PyYAML==5.4 rb==1.9.0 redis-py-cluster==2.1.0 redis==3.4.1
dfbef30c7f7d6729a335bbc80431cd02f662a67e
2022-07-23 04:25:03
Taylan Gocmen
feat(mep): Surface to users in alerts when metrics for performance will be sampled (#36991)
false
Surface to users in alerts when metrics for performance will be sampled (#36991)
feat
diff --git a/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx b/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx index b28c1e52abca40..e970116cd964c5 100644 --- a/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx +++ b/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx @@ -8,11 +8,13 @@ import pick from 'lodash/pick'; import {addErrorMessage} from 'sentry/actionCreators/indicator'; import {Client} from 'sentry/api'; import Feature from 'sentry/components/acl/feature'; +import Alert from 'sentry/components/alert'; import SearchBar from 'sentry/components/events/searchBar'; import FormField from 'sentry/components/forms/formField'; import SelectControl from 'sentry/components/forms/selectControl'; import SelectField from 'sentry/components/forms/selectField'; import IdBadge from 'sentry/components/idBadge'; +import ExternalLink from 'sentry/components/links/externalLink'; import ListItem from 'sentry/components/list/listItem'; import {Panel, PanelBody} from 'sentry/components/panels'; import Tooltip from 'sentry/components/tooltip'; @@ -67,6 +69,7 @@ type Props = { project: Project; projects: Project[]; router: InjectedRouter; + showMEPAlertBanner: boolean; thresholdChart: React.ReactNode; timeWindow: number; allowChangeEventTypes?: boolean; @@ -495,6 +498,7 @@ class RuleConditionsForm extends PureComponent<Props, State> { allowChangeEventTypes, hasAlertWizardV3, dataset, + showMEPAlertBanner, } = this.props; const {environments} = this.state; @@ -522,6 +526,21 @@ class RuleConditionsForm extends PureComponent<Props, State> { <ChartPanel> <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody> </ChartPanel> + {showMEPAlertBanner && + organization.features.includes('metrics-performance-alerts') && ( + <AlertContainer> + <Alert type="info" showIcon> + {tct( + 'Filtering by these conditions automatically switch you to indexed events. [link:Learn more].', + { + link: ( + <ExternalLink href="https://docs.sentry.io/product/sentry-basics/search/" /> + ), + } + )} + </Alert> + </AlertContainer> + )} {hasAlertWizardV3 && this.renderInterval()} <StyledListItem>{t('Filter events')}</StyledListItem> <FormRow @@ -627,7 +646,11 @@ const StyledListTitle = styled('div')` `; const ChartPanel = styled(Panel)` - margin-bottom: ${space(4)}; + margin-bottom: ${space(1)}; +`; + +const AlertContainer = styled('div')` + margin-bottom: ${space(2)}; `; const StyledPanelBody = styled(PanelBody)` diff --git a/static/app/views/alerts/rules/metric/ruleForm.tsx b/static/app/views/alerts/rules/metric/ruleForm.tsx index e1c58be69fc0c2..c02765ecadf89a 100644 --- a/static/app/views/alerts/rules/metric/ruleForm.tsx +++ b/static/app/views/alerts/rules/metric/ruleForm.tsx @@ -101,16 +101,17 @@ type State = { // Needed for TriggersChart dataset: Dataset; environment: string | null; + eventTypes: EventTypes[]; project: Project; query: string; resolveThreshold: UnsavedMetricRule['resolveThreshold']; + showMEPAlertBanner: boolean; thresholdPeriod: UnsavedMetricRule['thresholdPeriod']; thresholdType: UnsavedMetricRule['thresholdType']; timeWindow: number; triggerErrors: Map<number, {[fieldName: string]: string}>; triggers: Trigger[]; comparisonDelta?: number; - eventTypes?: EventTypes[]; selectedPresetId?: string; uuid?: string; } & AsyncComponent['state']; @@ -129,6 +130,13 @@ class RuleFormContainer extends AsyncComponent<Props, State> { return this.props.organization.features.includes('alert-wizard-v3'); } + get chartQuery(): string { + const {query, eventTypes, dataset} = this.state; + const eventTypeFilter = getEventTypeFilter(this.state.dataset, eventTypes); + const queryWithTypeFilter = `${query} ${eventTypeFilter}`.trim(); + return isCrashFreeAlert(dataset) ? query : queryWithTypeFilter; + } + componentDidMount() { const {organization} = this.props; const {project} = this.state; @@ -154,7 +162,13 @@ class RuleFormContainer extends AsyncComponent<Props, State> { getDefaultState(): State { const {rule, location} = this.props; const triggersClone = [...rule.triggers]; - const {aggregate, eventTypes: _eventTypes, dataset, name} = location?.query ?? {}; + const { + aggregate, + eventTypes: _eventTypes, + dataset, + name, + showMEPAlertBanner, + } = location?.query ?? {}; const eventTypes = typeof _eventTypes === 'string' ? [_eventTypes] : _eventTypes; // Warning trigger is removed if it is blank when saving @@ -168,7 +182,7 @@ class RuleFormContainer extends AsyncComponent<Props, State> { name: name ?? rule.name ?? '', aggregate: aggregate ?? rule.aggregate, dataset: dataset ?? rule.dataset, - eventTypes: eventTypes ?? rule.eventTypes, + eventTypes: eventTypes ?? rule.eventTypes ?? [], query: rule.query ?? '', timeWindow: rule.timeWindow, environment: rule.environment || null, @@ -184,6 +198,7 @@ class RuleFormContainer extends AsyncComponent<Props, State> { : AlertRuleComparisonType.COUNT, project: this.props.project, owner: rule.owner, + showMEPAlertBanner: showMEPAlertBanner ?? false, }; } @@ -729,18 +744,23 @@ class RuleFormContainer extends AsyncComponent<Props, State> { }; handleMEPAlertDataset = data => { - if (!data) { + const {organization} = this.props; + const {dataset, showMEPAlertBanner} = this.state; + const {isMetricsData} = data ?? {}; + + if ( + isMetricsData === undefined || + !organization.features.includes('metrics-performance-alerts') + ) { return; } - const {isMetricsData} = data; - - if (isMetricsData === undefined) { - return; + if (isMetricsData && dataset === Dataset.TRANSACTIONS) { + this.setState({dataset: Dataset.GENERIC_METRICS, showMEPAlertBanner: false}); } - if (isMetricsData && this.state.dataset === Dataset.TRANSACTIONS) { - this.setState({dataset: Dataset.GENERIC_METRICS}); + if (!isMetricsData && dataset === Dataset.GENERIC_METRICS && !showMEPAlertBanner) { + this.setState({dataset: Dataset.TRANSACTIONS, showMEPAlertBanner: true}); } }; @@ -775,16 +795,14 @@ class RuleFormContainer extends AsyncComponent<Props, State> { eventTypes, dataset, selectedPresetId, + showMEPAlertBanner, } = this.state; - const eventTypeFilter = getEventTypeFilter(this.state.dataset, eventTypes); - const queryWithTypeFilter = `${query} ${eventTypeFilter}`.trim(); - const chartProps = { organization, projects: [project], triggers, - query: isCrashFreeAlert(dataset) ? query : queryWithTypeFilter, + query: this.chartQuery, aggregate, dataset, newAlertOrQuery: !ruleId || query !== rule.query, @@ -967,6 +985,7 @@ class RuleFormContainer extends AsyncComponent<Props, State> { this.handleFieldChange('timeWindow', value) } disableProjectSelector={disableProjectSelector} + showMEPAlertBanner={showMEPAlertBanner} /> {!this.hasAlertWizardV3 && thresholdTypeForm(disabled)} <AlertListItem> diff --git a/static/app/views/alerts/rules/metric/wizardField.tsx b/static/app/views/alerts/rules/metric/wizardField.tsx index 6e3aa3108cf146..14a67e6c78b2fe 100644 --- a/static/app/views/alerts/rules/metric/wizardField.tsx +++ b/static/app/views/alerts/rules/metric/wizardField.tsx @@ -190,7 +190,8 @@ export default function WizardField({ return ( <FormField {...fieldProps}> - {({onChange, value: aggregate, model, disabled}) => { + {({onChange, model, disabled}) => { + const aggregate = model.getValue('aggregate'); const dataset: Dataset = model.getValue('dataset'); const eventTypes = [...(model.getValue('eventTypes') ?? [])]; diff --git a/static/app/views/alerts/utils/index.tsx b/static/app/views/alerts/utils/index.tsx index af3010fdd40d0d..5e9a23586bfa05 100644 --- a/static/app/views/alerts/utils/index.tsx +++ b/static/app/views/alerts/utils/index.tsx @@ -69,8 +69,8 @@ export function convertDatasetEventTypesToSource( dataset: Dataset, eventTypes: EventTypes[] ) { - // transactions only has one datasource option regardless of event type - if (dataset === Dataset.TRANSACTIONS) { + // transactions and generic_metrics only have one datasource option regardless of event type + if (dataset === Dataset.TRANSACTIONS || dataset === Dataset.GENERIC_METRICS) { return Datasource.TRANSACTION; } // if no event type was provided use the default datasource
80e8d6ad9a29c5c96ffa8b8f626031080c07a78c
2020-04-01 00:28:53
Megan Heskett
fix(teams): Fix access request error (#17963)
false
Fix access request error (#17963)
fix
diff --git a/src/sentry/api/endpoints/organization_member_team_details.py b/src/sentry/api/endpoints/organization_member_team_details.py index 4241151436193f..27816f6582f996 100644 --- a/src/sentry/api/endpoints/organization_member_team_details.py +++ b/src/sentry/api/endpoints/organization_member_team_details.py @@ -111,12 +111,16 @@ def _get_member(self, request, organization, member_id): return queryset.select_related("user").get() def _create_access_request(self, request, team, member): + omt, created = OrganizationAccessRequest.objects.get_or_create(team=team, member=member) + + if not created: + return + requester = request.user if request.user != member.user else None - omt, created = OrganizationAccessRequest.objects.get_or_create( - team=team, member=member, requester=requester - ) - if created: - omt.send_request_email() + if requester: + omt.update(requester=requester) + + omt.send_request_email() def post(self, request, organization, member_id, team_slug): """ diff --git a/tests/sentry/api/endpoints/test_organization_member_team_details.py b/tests/sentry/api/endpoints/test_organization_member_team_details.py index e130265cb8a000..ef8fcf189baa57 100644 --- a/tests/sentry/api/endpoints/test_organization_member_team_details.py +++ b/tests/sentry/api/endpoints/test_organization_member_team_details.py @@ -213,7 +213,6 @@ def test_member_must_request_access_to_join_team(self): team=self.team, organizationmember=self.member ).exists() - # access request created assert OrganizationAccessRequest.objects.filter( team=self.team, member=self.member, requester=None ).exists() @@ -227,7 +226,6 @@ def test_admin_must_request_access_to_join_team(self): team=self.team, organizationmember=self.admin ).exists() - # access request created assert OrganizationAccessRequest.objects.filter( team=self.team, member=self.admin, requester=None ).exists() @@ -241,7 +239,6 @@ def test_team_member_must_request_access_to_add_member_to_team(self): team=self.team, organizationmember=self.member ).exists() - # access request created assert OrganizationAccessRequest.objects.filter( team=self.team, member=self.member, requester=self.team_member.user ).exists() @@ -256,11 +253,26 @@ def test_admin_must_request_access_to_add_member_to_team(self): team=self.team, organizationmember=self.member ).exists() - # access request created assert OrganizationAccessRequest.objects.filter( team=self.team, member=self.member, requester=self.admin.user ).exists() + def test_multiple_of_the_same_access_request(self): + self.login_as(self.member.user) + resp = self.get_response(self.org.slug, self.admin.id, self.team.slug) + assert resp.status_code == 202 + + self.login_as(self.team_member.user) + resp = self.get_response(self.org.slug, self.admin.id, self.team.slug) + assert resp.status_code == 202 + + assert not OrganizationMemberTeam.objects.filter( + team=self.team, organizationmember=self.admin + ).exists() + + oar = OrganizationAccessRequest.objects.get(team=self.team, member=self.admin) + assert oar.requester == self.member.user + class DeleteOrganizationMemberTeamTest(MemberTeamFixtures): endpoint = "sentry-api-0-organization-member-team-details"
468c7a8b028f35f1a37b6b2c77b12697d6606377
2019-10-29 05:49:30
Billy Vong
feat(ui): Fix XSS in markdown (#15302)
false
Fix XSS in markdown (#15302)
feat
diff --git a/package.json b/package.json index 5892bde8593950..244309910deb7b 100644 --- a/package.json +++ b/package.json @@ -58,6 +58,7 @@ "crypto-js": "3.1.5", "css-loader": "^2.0.1", "diff": "^3.5.0", + "dompurify": "^2.0.7", "echarts": "4.2.1", "echarts-for-react": "2.0.14", "emotion": "9.2.12", diff --git a/src/sentry/static/sentry/app/utils/marked.jsx b/src/sentry/static/sentry/app/utils/marked.jsx index f6a90334daaf72..c071afd3615740 100644 --- a/src/sentry/static/sentry/app/utils/marked.jsx +++ b/src/sentry/static/sentry/app/utils/marked.jsx @@ -1,4 +1,5 @@ import marked from 'marked'; +import dompurify from 'dompurify'; function isSafeHref(href, pattern) { try { @@ -18,7 +19,7 @@ function Renderer() { } Object.assign(Renderer.prototype, marked.Renderer.prototype); -// Anythign except javascript, vbscript, data protocols +// Only https and mailto, (e.g. no javascript, vbscript, data protocols) const safeLinkPattern = /^(https?:|mailto:)/i; Renderer.prototype.link = function(href, title, text) { @@ -32,7 +33,7 @@ Renderer.prototype.link = function(href, title, text) { out += ' title="' + title + '"'; } out += '>' + text + '</a>'; - return out; + return dompurify.sanitize(out); }; // Only allow http(s) for image tags @@ -49,7 +50,7 @@ Renderer.prototype.image = function(href, title, text) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; - return out; + return dompurify.sanitize(out); }; marked.setOptions({ diff --git a/tests/js/spec/utils/marked.spec.jsx b/tests/js/spec/utils/marked.spec.jsx index 4891d798f057f1..4d706fb235e281 100644 --- a/tests/js/spec/utils/marked.spec.jsx +++ b/tests/js/spec/utils/marked.spec.jsx @@ -30,9 +30,9 @@ describe('marked', function() { it('normal images get rendered as html', function() { for (const test of [ - ['![](http://example.com)', '<img src="http://example.com" alt="">'], - ['![x](http://example.com)', '<img src="http://example.com" alt="x">'], - ['![x](https://example.com)', '<img src="https://example.com" alt="x">'], + ['![](http://example.com)', '<img alt="" src="http://example.com">'], + ['![x](http://example.com)', '<img alt="x" src="http://example.com">'], + ['![x](https://example.com)', '<img alt="x" src="https://example.com">'], ]) { expectMarkdown(test); } @@ -43,4 +43,15 @@ describe('marked', function() { expectMarkdown(test); } }); + + it('escapes XSS and removes invalid attributes on img', function() { + [ + [ + `[test](http://example.com\""#><img/onerror='alert\(location\)'/src=>) +![test](http://example.com"/onerror='alert\(location\)'/)`, + `<a href="http://example.com"><img src="">"&gt;test</a> +<img alt="test" src="http://example.com">`, + ], + ].forEach(expectMarkdown); + }); }); diff --git a/yarn.lock b/yarn.lock index 35c13906a47d39..b140af839b8d38 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5433,6 +5433,11 @@ domhandler@^2.3.0: dependencies: domelementtype "1" +dompurify@^2.0.7: + version "2.0.7" + resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-2.0.7.tgz#f8266ad38fe1602fb5b3222f31eedbf5c16c4fd5" + integrity sha512-S3O0lk6rFJtO01ZTzMollCOGg+WAtCwS3U5E2WSDY/x/sy7q70RjEC4Dmrih5/UqzLLB9XoKJ8KqwBxaNvBu4A== + [email protected]: version "1.0.8" resolved "https://registry.yarnpkg.com/domready/-/domready-1.0.8.tgz#91f252e597b65af77e745ae24dd0185d5e26d58c"
b9b847d12b518442c9bc63b0c868ac9717ad1f5d
2024-11-15 23:27:53
Evan Purkhiser
feat(crons): Add `system_incidents.use_decisions` option (#80828)
false
Add `system_incidents.use_decisions` option (#80828)
feat
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py index 25556ffdbb49bf..f3a0ff94125cf0 100644 --- a/src/sentry/options/defaults.py +++ b/src/sentry/options/defaults.py @@ -2021,6 +2021,15 @@ flags=FLAG_BOOL | FLAG_AUTOMATOR_MODIFIABLE, ) +# Enables the the crons incident occurrence consumer to consider the clock-tick +# decision made based on volume metrics to determine if a incident occurrence +# should be processed, delayed, or dropped entirely. +register( + "crons.system_incidents.use_decisions", + default=False, + flags=FLAG_BOOL | FLAG_AUTOMATOR_MODIFIABLE, +) + # The threshold that the tick metric must surpass for a tick to be determined # as anomalous. This value should be negative, since we will only determine an # incident based on a decrease in volume.
27670b27c0322400c4074a8c8328768f28574ffe
2025-03-20 01:58:42
Malachi Willey
chore(nav): Convert release version link to new route structure (#87439)
false
Convert release version link to new route structure (#87439)
chore
diff --git a/static/app/components/version.tsx b/static/app/components/version.tsx index 16aa5a3e115cd2..d98e272f85ce13 100644 --- a/static/app/components/version.tsx +++ b/static/app/components/version.tsx @@ -9,6 +9,7 @@ import type {Organization} from 'sentry/types/organization'; import {useLocation} from 'sentry/utils/useLocation'; import {formatVersion} from 'sentry/utils/versions/formatVersion'; import withOrganization from 'sentry/utils/withOrganization'; +import {makeReleasesPathname} from 'sentry/views/releases/utils/pathnames'; type Props = { /** @@ -80,9 +81,10 @@ function Version({ if (anchor && organization?.slug) { const props = { to: { - pathname: `/organizations/${organization?.slug}/releases/${encodeURIComponent( - version - )}/`, + pathname: makeReleasesPathname({ + path: `/${encodeURIComponent(version)}/`, + organization, + }), query: releaseDetailProjectId ? {project: releaseDetailProjectId} : undefined, }, className,
f8250bfe999d07e48e4bf7092546c9410ebdc431
2024-03-15 14:20:59
Alexander Tarasov
fix: disallow inviting Admin user if team-level roles are enabled (#66836)
false
disallow inviting Admin user if team-level roles are enabled (#66836)
fix
diff --git a/src/sentry/api/endpoints/organization_member/index.py b/src/sentry/api/endpoints/organization_member/index.py index b705a4be29d6f6..460092e568bef5 100644 --- a/src/sentry/api/endpoints/organization_member/index.py +++ b/src/sentry/api/endpoints/organization_member/index.py @@ -137,10 +137,15 @@ def validate_role(self, role): return self.validate_orgRole(role) def validate_orgRole(self, role): - if role not in {r.id for r in self.context["allowed_roles"]}: + role_obj = next((r for r in self.context["allowed_roles"] if r.id == role), None) + if role_obj is None: raise serializers.ValidationError( "You do not have permission to set that org-level role" ) + if not self.context.get("allow_retired_roles", True) and role_obj.is_retired: + raise serializers.ValidationError( + f"The role '{role}' is deprecated and may no longer be assigned." + ) return role def validate_teams(self, teams): @@ -332,6 +337,7 @@ def post(self, request: Request, organization) -> Response: "organization": organization, "allowed_roles": allowed_roles, "allow_existing_invite_request": True, + "allow_retired_roles": not features.has("organizations:team-roles", organization), }, ) diff --git a/static/app/components/roleSelectControl.tsx b/static/app/components/roleSelectControl.tsx index 09b7d98a2562f2..83d7ae96e2992c 100644 --- a/static/app/components/roleSelectControl.tsx +++ b/static/app/components/roleSelectControl.tsx @@ -24,15 +24,17 @@ type Props = Omit<ControlProps<OptionType>, 'onChange' | 'value'> & { function RoleSelectControl({roles, disableUnallowed, ...props}: Props) { return ( <SelectControl - options={roles?.map( - (r: MemberRole) => - ({ - value: r.id, - label: r.name, - disabled: (disableUnallowed && !r.allowed) || r.isRetired, - details: <Details>{r.desc}</Details>, - }) as OptionType - )} + options={roles + ?.filter(r => !r.isRetired) + .map( + (r: MemberRole) => + ({ + value: r.id, + label: r.name, + disabled: disableUnallowed && !r.allowed, + details: <Details>{r.desc}</Details>, + }) as OptionType + )} showDividers {...props} /> diff --git a/tests/sentry/api/endpoints/test_organization_member_index.py b/tests/sentry/api/endpoints/test_organization_member_index.py index 7353e565ee0c8a..6618bd0b856887 100644 --- a/tests/sentry/api/endpoints/test_organization_member_index.py +++ b/tests/sentry/api/endpoints/test_organization_member_index.py @@ -476,6 +476,26 @@ def test_invalid_user_for_direct_add(self): assert member.role == "manager" self.assert_org_member_mapping(org_member=member) + @with_feature({"organizations:team-roles": False}) + def test_can_invite_retired_role_without_flag(self): + data = {"email": "[email protected]", "role": "admin", "teams": [self.team.slug]} + + with self.settings(SENTRY_ENABLE_INVITES=True): + self.get_success_response(self.organization.slug, method="post", **data) + + @with_feature("organizations:team-roles") + def test_cannot_invite_retired_role_with_flag(self): + data = {"email": "[email protected]", "role": "admin", "teams": [self.team.slug]} + + with self.settings(SENTRY_ENABLE_INVITES=True): + response = self.get_error_response( + self.organization.slug, method="post", **data, status_code=400 + ) + assert ( + response.data["role"][0] + == "The role 'admin' is deprecated and may no longer be assigned." + ) + @region_silo_test class OrganizationMemberPermissionRoleTest(OrganizationMemberListTestBase, HybridCloudTestMixin):
ddc21f379a98f397856cba18c8962d3dd71ccaec
2020-10-08 19:36:59
Priscila Oliveira
ref(u2f-container): Convert U2fContainer to Typescript (#21217)
false
Convert U2fContainer to Typescript (#21217)
ref
diff --git a/src/sentry/static/sentry/app/components/u2f/u2fContainer.jsx b/src/sentry/static/sentry/app/components/u2f/u2fContainer.jsx deleted file mode 100644 index 9195defc1a7289..00000000000000 --- a/src/sentry/static/sentry/app/components/u2f/u2fContainer.jsx +++ /dev/null @@ -1,54 +0,0 @@ -import React from 'react'; - -import {Client} from 'app/api'; - -import U2fSign from './u2fsign'; - -class U2fContainer extends React.Component { - constructor(props) { - super(props); - this.state = { - authenticators: null, - }; - this.api = new Client(); - } - - componentDidMount() { - this.api - .requestPromise('/authenticators/') - .then(resp => { - this.setState({ - authenticators: resp || [], - }); - }) - .catch(() => { - // ignore errors - }); - } - - componentWillUnmount() { - this.api.clear(); - this.api = null; - } - - render() { - const {className, authenticators} = this.state; - if (authenticators && authenticators.length) { - return ( - <div className={className}> - {authenticators.map(({id, ...other}) => { - if (id === 'u2f' && other.challenge) { - return <U2fSign key={id} {...this.props} challengeData={other.challenge} />; - } - - return null; - })} - </div> - ); - } - - return null; - } -} - -export default U2fContainer; diff --git a/src/sentry/static/sentry/app/components/u2f/u2fContainer.tsx b/src/sentry/static/sentry/app/components/u2f/u2fContainer.tsx new file mode 100644 index 00000000000000..c115a4c623349a --- /dev/null +++ b/src/sentry/static/sentry/app/components/u2f/u2fContainer.tsx @@ -0,0 +1,57 @@ +import React from 'react'; + +import withApi from 'app/utils/withApi'; +import {Client} from 'app/api'; +import {Authenticator} from 'app/types'; + +import U2fSign from './u2fsign'; + +type Props = { + api: Client; + className?: string; +}; +type State = { + authenticators: Array<Authenticator>; +}; + +class U2fContainer extends React.Component<Props, State> { + state: State = { + authenticators: [], + }; + componentDidMount() { + this.getAuthenticators(); + } + + async getAuthenticators() { + const {api} = this.props; + + try { + const authenticators = await api.requestPromise('/authenticators/'); + this.setState({authenticators: authenticators ?? []}); + } catch { + // ignore errors + } + } + + render() { + const {className} = this.props; + const {authenticators} = this.state; + + if (!authenticators.length) { + return null; + } + + return ( + <div className={className}> + {authenticators.map(({id, ...other}) => { + if (id === 'u2f' && other.challenge) { + return <U2fSign key={id} {...this.props} challengeData={other.challenge} />; + } + return null; + })} + </div> + ); + } +} + +export default withApi(U2fContainer); diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx index ee86b8c200020b..efc35813044589 100644 --- a/src/sentry/static/sentry/app/types/index.tsx +++ b/src/sentry/static/sentry/app/types/index.tsx @@ -620,6 +620,8 @@ export type Authenticator = { * Description of the authenticator */ description: string; + + challenge?: Record<string, any>; } & Partial<EnrolledAuthenticator>; export type EnrolledAuthenticator = {
71afd8568b32a49d0adc8ef7d7682a62adbdb637
2022-10-27 22:00:31
William Mak
feat(mep): Remove dynamic sampling fro metric decision (#40612)
false
Remove dynamic sampling fro metric decision (#40612)
feat
diff --git a/src/sentry/api/endpoints/organization_metrics_meta.py b/src/sentry/api/endpoints/organization_metrics_meta.py index db17797546b1ea..90412a8df34ac2 100644 --- a/src/sentry/api/endpoints/organization_metrics_meta.py +++ b/src/sentry/api/endpoints/organization_metrics_meta.py @@ -25,7 +25,6 @@ def get(self, request: Request, organization) -> Response: data = { "incompatible_projects": [], "compatible_projects": [], - "dynamic_sampling_projects": [], } try: # This will be used on the perf homepage and contains preset queries, allow global views @@ -33,21 +32,6 @@ def get(self, request: Request, organization) -> Response: except NoProjects: return Response(data) original_project_ids = params["project_id"].copy() - for project in params["project_objects"]: - dynamic_sampling = project.get_option("sentry:dynamic_sampling") - if dynamic_sampling is not None: - data["dynamic_sampling_projects"].append(project.id) - if len(data["dynamic_sampling_projects"]) > 50: - break - - # None of the projects had DS rules, nothing is compat the sum & compat projects list is useless - if len(data["dynamic_sampling_projects"]) == 0: - return Response(data) - data["dynamic_sampling_projects"].sort() - - # Save ourselves some work, only query the projects that have DS rules - data["compatible_projects"] = params["project_id"] - params["project_id"] = data["dynamic_sampling_projects"] with self.handle_query_errors(): count_has_txn = "count_has_transaction_name()" diff --git a/tests/snuba/api/endpoints/test_organization_metrics_meta.py b/tests/snuba/api/endpoints/test_organization_metrics_meta.py index 64ad73318d200b..aea966df9beb30 100644 --- a/tests/snuba/api/endpoints/test_organization_metrics_meta.py +++ b/tests/snuba/api/endpoints/test_organization_metrics_meta.py @@ -18,7 +18,6 @@ def setUp(self): "organizations:performance-use-metrics": True, } self.login_as(user=self.user) - self.project.update_option("sentry:dynamic_sampling", "something-it-doesn't-matter") # Don't create any txn on this, don't set its DS rules, it shouldn't show up anywhere self.bad_project = self.create_project() @@ -34,9 +33,10 @@ def test_unparameterized_transactions(self): response = self.client.get(url, format="json") assert response.status_code == 200, response.content - assert response.data["incompatible_projects"] == [self.project.id, self.bad_project.id] + self.assertCountEqual( + response.data["incompatible_projects"], [self.project.id, self.bad_project.id] + ) assert response.data["compatible_projects"] == [] - assert response.data["dynamic_sampling_projects"] == [self.project.id] def test_null_transaction(self): # Make current project incompatible @@ -48,9 +48,10 @@ def test_null_transaction(self): response = self.client.get(url, format="json") assert response.status_code == 200, response.content - assert response.data["incompatible_projects"] == [self.project.id, self.bad_project.id] + self.assertCountEqual( + response.data["incompatible_projects"], [self.project.id, self.bad_project.id] + ) assert response.data["compatible_projects"] == [] - assert response.data["dynamic_sampling_projects"] == [self.project.id] def test_no_transaction(self): # Make current project incompatible by having nothing @@ -61,9 +62,10 @@ def test_no_transaction(self): response = self.client.get(url, format="json") assert response.status_code == 200, response.content - assert response.data["incompatible_projects"] == [self.project.id, self.bad_project.id] + self.assertCountEqual( + response.data["incompatible_projects"], [self.project.id, self.bad_project.id] + ) assert response.data["compatible_projects"] == [] - assert response.data["dynamic_sampling_projects"] == [self.project.id] def test_has_transaction(self): self.store_transaction_metric( @@ -78,14 +80,10 @@ def test_has_transaction(self): assert response.status_code == 200, response.content assert response.data["incompatible_projects"] == [self.bad_project.id] assert response.data["compatible_projects"] == [self.project.id] - assert response.data["dynamic_sampling_projects"] == [self.project.id] def test_multiple_projects(self): project2 = self.create_project() - project2.update_option("sentry:dynamic_sampling", "something-it-doesn't-matter") project3 = self.create_project() - project3.update_option("sentry:dynamic_sampling", "something-it-doesn't-matter") - # Not setting DS, it shouldn't show up project4 = self.create_project() self.store_transaction_metric( 1, tags={"transaction": "foo_transaction"}, timestamp=self.min_ago @@ -116,27 +114,10 @@ def test_multiple_projects(self): response = self.client.get(url, format="json") assert response.status_code == 200, response.content - assert response.data["incompatible_projects"] == sorted( - [project2.id, project3.id, project4.id, self.bad_project.id] + self.assertCountEqual( + response.data["incompatible_projects"], [project2.id, project3.id, self.bad_project.id] ) - assert response.data["compatible_projects"] == [self.project.id] - assert response.data["dynamic_sampling_projects"] == [ - self.project.id, - project2.id, - project3.id, - ] - - def test_no_ds(self): - url = reverse( - "sentry-api-0-organization-metrics-compatibility", - kwargs={"organization_slug": self.project.organization.slug}, - ) - response = self.client.get(url, data={"project": [self.bad_project.id]}, format="json") - - assert response.status_code == 200, response.content - assert response.data["dynamic_sampling_projects"] == [] - assert response.data["incompatible_projects"] == [] - assert response.data["compatible_projects"] == [] + self.assertCountEqual(response.data["compatible_projects"], [self.project.id, project4.id]) @region_silo_test @@ -149,7 +130,6 @@ def setUp(self): "organizations:performance-use-metrics": True, } self.login_as(user=self.user) - self.project.update_option("sentry:dynamic_sampling", "something-it-doesn't-matter") # Don't create any txn on this, don't set its DS rules, it shouldn't show up anywhere self.create_project() @@ -213,9 +193,7 @@ def test_has_transaction(self): def test_multiple_projects(self): project2 = self.create_project() - project2.update_option("sentry:dynamic_sampling", "something-it-doesn't-matter") project3 = self.create_project() - project3.update_option("sentry:dynamic_sampling", "something-it-doesn't-matter") # Not setting DS, it shouldn't show up project4 = self.create_project() self.store_transaction_metric(
9874a712f1b4f3ef2f31d7ec2c480dc6ac188f25
2024-09-18 21:35:55
Dominik Buszowiecki
feat(insights): move geo selector to beta (#77705)
false
move geo selector to beta (#77705)
feat
diff --git a/static/app/views/insights/browser/webVitals/views/pageOverview.tsx b/static/app/views/insights/browser/webVitals/views/pageOverview.tsx index f8fb6bed4dc5a5..dffe9459fee836 100644 --- a/static/app/views/insights/browser/webVitals/views/pageOverview.tsx +++ b/static/app/views/insights/browser/webVitals/views/pageOverview.tsx @@ -38,7 +38,6 @@ import decodeBrowserTypes from 'sentry/views/insights/browser/webVitals/utils/qu import {ModulePageProviders} from 'sentry/views/insights/common/components/modulePageProviders'; import {useModuleBreadcrumbs} from 'sentry/views/insights/common/utils/useModuleBreadcrumbs'; import {useModuleURL} from 'sentry/views/insights/common/utils/useModuleURL'; -import SubregionSelector from 'sentry/views/insights/common/views/spans/selectors/subregionSelector'; import {SpanIndexedField, type SubregionCode} from 'sentry/views/insights/types'; import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils'; @@ -197,7 +196,6 @@ export function PageOverview() { <DatePageFilter /> </PageFilterBar> <BrowserTypeSelector /> - <SubregionSelector /> </TopMenuContainer> <Flex> <PerformanceScoreBreakdownChart diff --git a/static/app/views/insights/browser/webVitals/views/webVitalsLandingPage.tsx b/static/app/views/insights/browser/webVitals/views/webVitalsLandingPage.tsx index 776f98e8994a72..d8cb7485b4c3a8 100644 --- a/static/app/views/insights/browser/webVitals/views/webVitalsLandingPage.tsx +++ b/static/app/views/insights/browser/webVitals/views/webVitalsLandingPage.tsx @@ -35,7 +35,6 @@ import {ModulePageFilterBar} from 'sentry/views/insights/common/components/modul import {ModulePageProviders} from 'sentry/views/insights/common/components/modulePageProviders'; import {ModulesOnboarding} from 'sentry/views/insights/common/components/modulesOnboarding'; import {useModuleBreadcrumbs} from 'sentry/views/insights/common/utils/useModuleBreadcrumbs'; -import SubregionSelector from 'sentry/views/insights/common/views/spans/selectors/subregionSelector'; import { type InsightLandingProps, ModuleName, @@ -102,7 +101,6 @@ export function WebVitalsLandingPage({disableHeader}: InsightLandingProps) { extraFilters={ <Fragment> <BrowserTypeSelector /> - <SubregionSelector /> </Fragment> } /> diff --git a/static/app/views/insights/common/views/spans/selectors/subregionSelector.tsx b/static/app/views/insights/common/views/spans/selectors/subregionSelector.tsx index 22c803d7a13267..962d99c7d6ae75 100644 --- a/static/app/views/insights/common/views/spans/selectors/subregionSelector.tsx +++ b/static/app/views/insights/common/views/spans/selectors/subregionSelector.tsx @@ -66,7 +66,7 @@ export default function SubregionSelector({size}: Props) { triggerProps={{ prefix: ( <Fragment> - <StyledFeatureBadge type="experimental" /> + <StyledFeatureBadge type="beta" /> {t('Geo region')} </Fragment> ),
3da5a26f6c19bb3c471c6e552dfc9429aca54908
2021-02-15 16:38:25
Matej Minar
feat(ui): Refresh ProGuard settings UI (#23835)
false
Refresh ProGuard settings UI (#23835)
feat
diff --git a/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.tsx b/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.tsx index 212656c4f37b9c..28c0f722942862 100644 --- a/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.tsx +++ b/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.tsx @@ -101,15 +101,15 @@ export default function getConfiguration({ path: `${pathPrefix}/debug-symbols/`, title: t('Debug Files'), }, - { - path: `${pathPrefix}/source-maps/`, - title: t('Source Maps'), - }, { path: `${pathPrefix}/proguard/`, title: t('ProGuard'), show: () => !!organization?.features?.includes('android-mappings'), }, + { + path: `${pathPrefix}/source-maps/`, + title: t('Source Maps'), + }, ], }, { diff --git a/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguard.tsx b/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguard.tsx index 890aef723d470d..7890189f9a3b16 100644 --- a/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguard.tsx +++ b/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguard.tsx @@ -2,20 +2,19 @@ import React from 'react'; import {RouteComponentProps} from 'react-router'; import styled from '@emotion/styled'; -import Checkbox from 'app/components/checkbox'; +import ExternalLink from 'app/components/links/externalLink'; import Pagination from 'app/components/pagination'; import {PanelTable} from 'app/components/panels'; import SearchBar from 'app/components/searchBar'; -import {t} from 'app/locale'; -import space from 'app/styles/space'; +import {t, tct} from 'app/locale'; import {Organization, Project} from 'app/types'; import {DebugFile} from 'app/types/debugFiles'; import routeTitleGen from 'app/utils/routeTitle'; import AsyncView from 'app/views/asyncView'; import SettingsPageHeader from 'app/views/settings/components/settingsPageHeader'; import TextBlock from 'app/views/settings/components/text/textBlock'; -// TODO(android-mappings): use own components once we decide how this should look like -import DebugFileRow from 'app/views/settings/projectDebugFiles/debugFileRow'; + +import ProjectProguardRow from './projectProguardRow'; type Props = RouteComponentProps<{orgId: string; projectId: string}, {}> & { organization: Organization; @@ -24,7 +23,6 @@ type Props = RouteComponentProps<{orgId: string; projectId: string}, {}> & { type State = AsyncView['state'] & { mappings: DebugFile[]; - showDetails: boolean; }; class ProjectProguard extends AsyncView<Props, State> { @@ -38,7 +36,6 @@ class ProjectProguard extends AsyncView<Props, State> { return { ...super.getDefaultState(), mappings: [], - showDetails: false, }; } @@ -101,7 +98,7 @@ class ProjectProguard extends AsyncView<Props, State> { } renderMappings() { - const {mappings, showDetails} = this.state; + const {mappings} = this.state; const {organization, params} = this.props; const {orgId, projectId} = params; @@ -115,12 +112,11 @@ class ProjectProguard extends AsyncView<Props, State> { }/projects/${orgId}/${projectId}/files/dsyms/?id=${encodeURIComponent(mapping.id)}`; return ( - <DebugFileRow - debugFile={mapping} - showDetails={showDetails} + <ProjectProguardRow + mapping={mapping} downloadUrl={downloadUrl} - downloadRole={organization.debugFilesRole} onDelete={this.handleDelete} + downloadRole={organization.debugFilesRole} key={mapping.id} /> ); @@ -128,45 +124,38 @@ class ProjectProguard extends AsyncView<Props, State> { } renderBody() { - const {loading, showDetails, mappings, mappingsPageLinks} = this.state; + const {loading, mappings, mappingsPageLinks} = this.state; return ( <React.Fragment> - <SettingsPageHeader title={t('ProGuard Mappings')} /> - - <TextBlock> - {t( - `ProGuard mapping files are used to convert minified classes, methods and field names into a human readable format.` - )} - </TextBlock> - - <Wrapper> - <TextBlock noMargin>{t('Uploaded mappings')}:</TextBlock> - - <Filters> - <Label> - <Checkbox - checked={showDetails} - onChange={e => { - this.setState({showDetails: (e.target as HTMLInputElement).checked}); - }} - /> - {t('show details')} - </Label> - + <SettingsPageHeader + title={t('ProGuard Mappings')} + action={ <SearchBar - placeholder={t('Search mappings')} + placeholder={t('Filter mappings')} onSearch={this.handleSearch} query={this.getQuery()} + width="280px" /> - </Filters> - </Wrapper> + } + /> + + <TextBlock> + {tct( + `ProGuard mapping files are used to convert minified classes, methods and field names into a human readable format. To learn more about proguard mapping files, [link: read the docs].`, + { + link: ( + <ExternalLink href="https://docs.sentry.io/platforms/android/proguard/" /> + ), + } + )} + </TextBlock> <StyledPanelTable headers={[ - t('Debug ID'), - t('Information'), - <Actions key="actions">{t('Actions')}</Actions>, + t('Mapping'), + <SizeColumn key="size">{t('File Size')}</SizeColumn>, + '', ]} emptyMessage={this.getEmptyMessage()} isEmpty={mappings?.length === 0} @@ -181,45 +170,11 @@ class ProjectProguard extends AsyncView<Props, State> { } const StyledPanelTable = styled(PanelTable)` - grid-template-columns: 37% 1fr auto; + grid-template-columns: minmax(220px, 1fr) max-content 120px; `; -const Actions = styled('div')` +const SizeColumn = styled('div')` text-align: right; `; -const Wrapper = styled('div')` - display: grid; - grid-template-columns: auto 1fr; - grid-gap: ${space(4)}; - align-items: center; - margin-top: ${space(4)}; - margin-bottom: ${space(1)}; - @media (max-width: ${p => p.theme.breakpoints[0]}) { - display: block; - } -`; - -const Filters = styled('div')` - display: grid; - grid-template-columns: min-content minmax(200px, 400px); - align-items: center; - justify-content: flex-end; - grid-gap: ${space(2)}; - @media (max-width: ${p => p.theme.breakpoints[0]}) { - grid-template-columns: min-content 1fr; - } -`; - -const Label = styled('label')` - font-weight: normal; - display: flex; - margin-bottom: 0; - white-space: nowrap; - input { - margin-top: 0; - margin-right: ${space(1)}; - } -`; - export default ProjectProguard; diff --git a/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguardRow.tsx b/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguardRow.tsx new file mode 100644 index 00000000000000..0569811acde34e --- /dev/null +++ b/src/sentry/static/sentry/app/views/settings/projectProguard/projectProguardRow.tsx @@ -0,0 +1,122 @@ +import React from 'react'; +import styled from '@emotion/styled'; + +import Access from 'app/components/acl/access'; +import Role from 'app/components/acl/role'; +import Button from 'app/components/button'; +import ButtonBar from 'app/components/buttonBar'; +import Confirm from 'app/components/confirm'; +import FileSize from 'app/components/fileSize'; +import TimeSince from 'app/components/timeSince'; +import Tooltip from 'app/components/tooltip'; +import {IconClock, IconDelete, IconDownload} from 'app/icons'; +import {t} from 'app/locale'; +import space from 'app/styles/space'; +import {DebugFile} from 'app/types/debugFiles'; + +type Props = { + mapping: DebugFile; + onDelete: (id: string) => void; + downloadUrl: string; + downloadRole: string; +}; + +const ProjectProguardRow = ({mapping, onDelete, downloadUrl, downloadRole}: Props) => { + const {id, debugId, uuid, size, dateCreated} = mapping; + + const handleDeleteClick = () => { + onDelete(id); + }; + + return ( + <React.Fragment> + <NameColumn> + <Name>{debugId || uuid || `(${t('empty')})`}</Name> + <TimeWrapper> + <IconClock size="sm" /> + <TimeSince date={dateCreated} /> + </TimeWrapper> + </NameColumn> + <SizeColumn> + <FileSize bytes={size} /> + </SizeColumn> + <ActionsColumn> + <ButtonBar gap={0.5}> + <Role role={downloadRole}> + {({hasRole}) => ( + <Tooltip + title={t('You do not have permission to download mappings.')} + disabled={hasRole} + > + <Button + size="small" + icon={<IconDownload size="sm" />} + disabled={!hasRole} + href={downloadUrl} + title={t('Download Mapping')} + /> + </Tooltip> + )} + </Role> + + <Access access={['project:releases']}> + {({hasAccess}) => ( + <Tooltip + disabled={hasAccess} + title={t('You do not have permission to delete mappings.')} + > + <Confirm + message={t('Are you sure you want to remove this mapping?')} + onConfirm={handleDeleteClick} + disabled={!hasAccess} + > + <Button + size="small" + icon={<IconDelete size="sm" />} + title={t('Remove Mapping')} + label={t('Remove Mapping')} + disabled={!hasAccess} + /> + </Confirm> + </Tooltip> + )} + </Access> + </ButtonBar> + </ActionsColumn> + </React.Fragment> + ); +}; + +const NameColumn = styled('div')` + display: flex; + flex-direction: column; + align-items: flex-start; + justify-content: center; +`; + +const SizeColumn = styled('div')` + display: flex; + justify-content: flex-end; + text-align: right; + align-items: center; +`; + +const ActionsColumn = styled(SizeColumn)``; + +const Name = styled('div')` + padding-right: ${space(4)}; + overflow-wrap: break-word; + word-break: break-all; +`; + +const TimeWrapper = styled('div')` + display: grid; + grid-gap: ${space(0.5)}; + grid-template-columns: min-content 1fr; + font-size: ${p => p.theme.fontSizeMedium}; + align-items: center; + color: ${p => p.theme.subText}; + margin-top: ${space(1)}; +`; + +export default ProjectProguardRow;
fdce530c5baaba2d57a094e7a66cc91f81c3cb24
2024-04-09 23:38:40
Armen Zambrano G
chore(codeowners): Regroup files for the Issues team (#68497)
false
Regroup files for the Issues team (#68497)
chore
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 9304b08c3b972c..e96a8eb1ad6465 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -151,14 +151,11 @@ yarn.lock @getsentry/owners-js-de /src/sentry/tasks/deletion/hybrid_cloud.py @getsentry/hybrid-cloud ## End of Hybrid Cloud -## Workflow +## Alerts & Notifications /static/app/views/settings/projectAlerts/ @getsentry/alerts-notifications /static/app/views/alerts/ @getsentry/alerts-notifications -/static/app/views/issueDetails/ @getsentry/issues -/static/app/views/projects/ @getsentry/issues -/static/app/views/projectDetail/ @getsentry/issues /static/app/views/releases/ @getsentry/alerts-notifications -/static/app/views/organizationStats/teamInsights/ @getsentry/issues + /static/app/views/settings/account/notifications/ @getsentry/alerts-notifications /src/sentry/templates/sentry/emails/incidents/ @getsentry/alerts-notifications @@ -166,22 +163,13 @@ yarn.lock @getsentry/owners-js-de /tests/sentry/incidents/ @getsentry/alerts-notifications /tests/acceptance/test_incidents.py @getsentry/alerts-notifications -/src/sentry/api/helpers/events.py @getsentry/issues -/src/sentry/api/helpers/group_index/ @getsentry/issues - /src/sentry/snuba/models.py @getsentry/alerts-notifications /src/sentry/snuba/query_subscriptions/ @getsentry/alerts-notifications /src/sentry/snuba/subscriptions.py @getsentry/alerts-notifications /tests/snuba/incidents/ @getsentry/alerts-notifications /tests/sentry/snuba/test_query_subscription_consumer.py @getsentry/alerts-notifications /tests/sentry/snuba/test_subscriptions.py @getsentry/alerts-notifications -/tests/sentry/snuba/test_tasks.py @getsentry/issues -/src/sentry/api/issue_search.py @getsentry/issues -/tests/sentry/api/test_issue_search.py @getsentry/issues - -/src/sentry/tasks/auto_remove_inbox.py @getsentry/issues -/src/sentry/tasks/auto_resolve_issues.py @getsentry/issues -## Endof Workflow +## Endof Alerts & Notifications ## Performance @@ -312,17 +300,14 @@ static/app/components/events/eventStatisticalDetector/ @getse /src/sentry/api/serializers/models/alert_rule.py @getsentry/alerts-notifications /static/app/views/organizationIntegrations @getsentry/product-owners-settings-integrations -/static/app/views/settings/project/projectOwnership/ @getsentry/issues /src/sentry/digests/ @getsentry/alerts-notifications /src/sentry/identity/ @getsentry/enterprise /src/sentry/integrations/ @getsentry/product-owners-settings-integrations /src/sentry/mail/ @getsentry/alerts-notifications -/src/sentry/mediators/ @getsentry/issues /src/sentry/notifications/ @getsentry/alerts-notifications /src/sentry/pipeline/ @getsentry/ecosystem /src/sentry/plugins/ @getsentry/ecosystem -/src/sentry/ratelimits/ @getsentry/issues /src/sentry/shared_integrations/ @getsentry/ecosystem /src/sentry/models/externalactor.py @getsentry/ecosystem @@ -330,9 +315,6 @@ static/app/components/events/eventStatisticalDetector/ @getse /src/sentry/models/identity.py @getsentry/enterprise /src/sentry/models/integrations/ @getsentry/product-owners-settings-integrations -/src/sentry/tasks/codeowners/ @getsentry/issues -/src/sentry/tasks/commits.py @getsentry/issues -/src/sentry/tasks/commit_context.py @getsentry/issues /src/sentry/tasks/digests.py @getsentry/alerts-notifications /src/sentry/tasks/email.py @getsentry/alerts-notifications /src/sentry/tasks/integrations/ @getsentry/ecosystem @@ -340,7 +322,7 @@ static/app/components/events/eventStatisticalDetector/ @getse /src/sentry/tasks/weekly_reports.py @getsentry/alerts-notifications /src/sentry_plugins/ @getsentry/product-owners-settings-integrations -*code_mappings*.py @getsentry/issues + # To find matching files -> find . -name "*sentry_app*.py" *sentry_app*.py @getsentry/product-owners-settings-integrations @@ -348,8 +330,6 @@ static/app/components/events/eventStatisticalDetector/ @getse *doc_integration*.py @getsentry/ecosystem *docintegration*.py @getsentry/ecosystem -/src/sentry/middleware/ratelimit.py @getsentry/issues -/src/sentry/middleware/access_log.py @getsentry/issues ## End of Integrations @@ -480,24 +460,43 @@ static/app/components/events/eventStatisticalDetector/ @getse ## Issues -**/issues/** @getsentry/issues -/src/sentry/api/helpers/source_map_helper.py @getsentry/issues -/src/sentry/api/helpers/actionable_items_helper.py @getsentry/issues -/src/sentry/event_manager.py @getsentry/issues -/src/sentry/grouping/ @getsentry/issues -/src/sentry/tasks/post_process.py @getsentry/issues -/src/sentry/tasks/unmerge.py @getsentry/issues -/src/sentry/search/snuba/ @getsentry/issues -/tests/sentry/event_manager/ @getsentry/issues -/tests/sentry/grouping/ @getsentry/issues -/tests/sentry/search/ @getsentry/issues -/tests/sentry/tasks/test_post_process.py @getsentry/issues -/tests/snuba/search/ @getsentry/issues -/static/app/views/issueList @getsentry/issues -/static/app/views/issueList @getsentry/issues +**/issues/** @getsentry/issues +*code_mappings*.py @getsentry/issues +/src/sentry/api/helpers/events.py @getsentry/issues +/src/sentry/api/helpers/group_index/ @getsentry/issues +/src/sentry/api/helpers/source_map_helper.py @getsentry/issues +/src/sentry/api/helpers/actionable_items_helper.py @getsentry/issues +/src/sentry/api/issue_search.py @getsentry/issues +/src/sentry/event_manager.py @getsentry/issues +/src/sentry/grouping/ @getsentry/issues +/src/sentry/mediators/ @getsentry/issues +/src/sentry/middleware/ratelimit.py @getsentry/issues +/src/sentry/middleware/access_log.py @getsentry/issues +/src/sentry/ratelimits/ @getsentry/issues +/src/sentry/tasks/auto_remove_inbox.py @getsentry/issues +/src/sentry/tasks/auto_resolve_issues.py @getsentry/issues +/src/sentry/tasks/codeowners/ @getsentry/issues +/src/sentry/tasks/commits.py @getsentry/issues +/src/sentry/tasks/commit_context.py @getsentry/issues +/src/sentry/tasks/post_process.py @getsentry/issues +/src/sentry/tasks/unmerge.py @getsentry/issues +/src/sentry/search/snuba/ @getsentry/issues +/static/app/views/issueList @getsentry/issues +/static/app/views/issueDetails/ @getsentry/issues +/static/app/views/organizationStats/teamInsights/ @getsentry/issues +/static/app/views/projects/ @getsentry/issues +/static/app/views/projectDetail/ @getsentry/issues +/static/app/views/settings/project/projectOwnership/ @getsentry/issues /static/app/components/events/interfaces/crashContent/exception/actionableItems.tsx @getsentry/issues -/static/app/utils/analytics.tsx @getsentry/issues -/static/app/utils/routeAnalytics/ @getsentry/issues +/static/app/utils/analytics.tsx @getsentry/issues +/static/app/utils/routeAnalytics/ @getsentry/issues +/tests/sentry/api/test_issue_search.py @getsentry/issues +/tests/sentry/event_manager/ @getsentry/issues +/tests/sentry/grouping/ @getsentry/issues +/tests/sentry/search/ @getsentry/issues +/tests/sentry/snuba/test_tasks.py @getsentry/issues +/tests/sentry/tasks/test_post_process.py @getsentry/issues +/tests/snuba/search/ @getsentry/issues ## End of Issues ## Billing
9dfe35cf44e9e35166443112ae40a513f7a105f7
2023-03-09 21:52:47
Elias Hussary
feat(profiling): add aggregateFlamegraph to profileSummary (#45458)
false
add aggregateFlamegraph to profileSummary (#45458)
feat
diff --git a/static/app/components/profiling/aggregateFlamegraphPanel.tsx b/static/app/components/profiling/aggregateFlamegraphPanel.tsx new file mode 100644 index 00000000000000..a478bbb4e9b27b --- /dev/null +++ b/static/app/components/profiling/aggregateFlamegraphPanel.tsx @@ -0,0 +1,29 @@ +import {Panel} from 'sentry/components/panels'; +import {AggregateFlamegraph} from 'sentry/components/profiling/flamegraph/aggregateFlamegraph'; +import {FlamegraphStateProvider} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/flamegraphContextProvider'; +import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/flamegraphThemeProvider'; +import {useAggregateFlamegraphQuery} from 'sentry/utils/profiling/hooks/useAggregateFlamegraphQuery'; +import {ProfileGroupProvider} from 'sentry/views/profiling/profileGroupProvider'; + +export function AggregateFlamegraphPanel({transaction}: {transaction: string}) { + const query = useAggregateFlamegraphQuery({transaction}); + + return ( + <ProfileGroupProvider type="flamegraph" input={query.data ?? null} traceID=""> + <FlamegraphStateProvider + initialState={{ + preferences: { + sorting: 'alphabetical', + view: 'bottom up', + }, + }} + > + <FlamegraphThemeProvider> + <Panel> + <AggregateFlamegraph /> + </Panel> + </FlamegraphThemeProvider> + </FlamegraphStateProvider> + </ProfileGroupProvider> + ); +} diff --git a/static/app/components/profiling/flamegraph/aggregateFlamegraph.tsx b/static/app/components/profiling/flamegraph/aggregateFlamegraph.tsx new file mode 100644 index 00000000000000..d275345fdeeddb --- /dev/null +++ b/static/app/components/profiling/flamegraph/aggregateFlamegraph.tsx @@ -0,0 +1,413 @@ +import {ReactElement, useEffect, useLayoutEffect, useMemo, useState} from 'react'; +import styled from '@emotion/styled'; +import * as Sentry from '@sentry/react'; +import {mat3, vec2} from 'gl-matrix'; + +import {Button} from 'sentry/components/button'; +import {FlamegraphZoomView} from 'sentry/components/profiling/flamegraph/flamegraphZoomView'; +import {Flex} from 'sentry/components/profiling/flex'; +import {t} from 'sentry/locale'; +import {space} from 'sentry/styles/space'; +import {defined} from 'sentry/utils'; +import { + CanvasPoolManager, + useCanvasScheduler, +} from 'sentry/utils/profiling/canvasScheduler'; +import {CanvasView} from 'sentry/utils/profiling/canvasView'; +import {Flamegraph as FlamegraphModel} from 'sentry/utils/profiling/flamegraph'; +import {FlamegraphProfiles} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/reducers/flamegraphProfiles'; +import {useFlamegraphPreferences} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphPreferences'; +import {useFlamegraphProfiles} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphProfiles'; +import {useDispatchFlamegraphState} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphState'; +import {useFlamegraphZoomPosition} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphZoomPosition'; +import { + useFlamegraphTheme, + useMutateFlamegraphTheme, +} from 'sentry/utils/profiling/flamegraph/useFlamegraphTheme'; +import {FlamegraphCanvas} from 'sentry/utils/profiling/flamegraphCanvas'; +import {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame'; +import { + computeConfigViewWithStrategy, + computeMinZoomConfigViewForFrames, + Rect, + useResizeCanvasObserver, +} from 'sentry/utils/profiling/gl/utils'; +import {FlamegraphRendererWebGL} from 'sentry/utils/profiling/renderers/flamegraphRendererWebGL'; +import {useDevicePixelRatio} from 'sentry/utils/useDevicePixelRatio'; +import {useMemoWithPrevious} from 'sentry/utils/useMemoWithPrevious'; +import {useProfileGroup} from 'sentry/views/profiling/profileGroupProvider'; + +type FlamegraphCandidate = { + frame: FlamegraphFrame; + threadId: number; + isActiveThread?: boolean; // this is the thread referred to by the active profile index +}; + +function findLongestMatchingFrame( + flamegraph: FlamegraphModel, + focusFrame: FlamegraphProfiles['highlightFrames'] +): FlamegraphFrame | null { + if (focusFrame === null) { + return null; + } + + let longestFrame: FlamegraphFrame | null = null; + + const frames: FlamegraphFrame[] = [...flamegraph.root.children]; + while (frames.length > 0) { + const frame = frames.pop()!; + if ( + focusFrame.name === frame.frame.name && + focusFrame.package === frame.frame.image && + (longestFrame?.node?.totalWeight || 0) < frame.node.totalWeight + ) { + longestFrame = frame; + } + + if (longestFrame && longestFrame.node.totalWeight < frame.node.totalWeight) { + for (let i = 0; i < frame.children.length; i++) { + frames.push(frame.children[i]); + } + } + } + + return longestFrame; +} + +const LOADING_OR_FALLBACK_FLAMEGRAPH = FlamegraphModel.Empty(); + +export function AggregateFlamegraph(): ReactElement { + const devicePixelRatio = useDevicePixelRatio(); + const dispatch = useDispatchFlamegraphState(); + + const profileGroup = useProfileGroup(); + + const flamegraphTheme = useFlamegraphTheme(); + const setFlamegraphThemeMutation = useMutateFlamegraphTheme(); + const position = useFlamegraphZoomPosition(); + const profiles = useFlamegraphProfiles(); + const {colorCoding, sorting, view} = useFlamegraphPreferences(); + const {threadId, highlightFrames} = profiles; + + const [flamegraphCanvasRef, setFlamegraphCanvasRef] = + useState<HTMLCanvasElement | null>(null); + const [flamegraphOverlayCanvasRef, setFlamegraphOverlayCanvasRef] = + useState<HTMLCanvasElement | null>(null); + + const canvasPoolManager = useMemo(() => new CanvasPoolManager(), []); + const scheduler = useCanvasScheduler(canvasPoolManager); + + const profile = useMemo(() => { + return profileGroup.profiles.find(p => p.threadId === threadId); + }, [profileGroup, threadId]); + + const flamegraph = useMemo(() => { + if (typeof threadId !== 'number') { + return LOADING_OR_FALLBACK_FLAMEGRAPH; + } + + // This could happen if threadId was initialized from query string, but for some + // reason the profile was removed from the list of profiles. + if (!profile) { + return LOADING_OR_FALLBACK_FLAMEGRAPH; + } + + const transaction = Sentry.startTransaction({ + op: 'import', + name: 'flamegraph.constructor', + }); + + transaction.setTag('sorting', sorting.split(' ').join('_')); + transaction.setTag('view', view.split(' ').join('_')); + + const newFlamegraph = new FlamegraphModel(profile, threadId, { + inverted: view === 'bottom up', + sort: sorting, + configSpace: undefined, + }); + transaction.finish(); + + return newFlamegraph; + }, [profile, sorting, threadId, view]); + + const flamegraphCanvas = useMemo(() => { + if (!flamegraphCanvasRef) { + return null; + } + const yOrigin = flamegraphTheme.SIZES.TIMELINE_HEIGHT * devicePixelRatio; + return new FlamegraphCanvas(flamegraphCanvasRef, vec2.fromValues(0, yOrigin)); + }, [devicePixelRatio, flamegraphCanvasRef, flamegraphTheme]); + + const flamegraphView = useMemoWithPrevious<CanvasView<FlamegraphModel> | null>( + previousView => { + if (!flamegraphCanvas) { + return null; + } + + const newView = new CanvasView({ + canvas: flamegraphCanvas, + model: flamegraph, + options: { + inverted: flamegraph.inverted, + minWidth: flamegraph.profile.minFrameDuration, + barHeight: flamegraphTheme.SIZES.BAR_HEIGHT, + depthOffset: flamegraphTheme.SIZES.FLAMEGRAPH_DEPTH_OFFSET, + configSpaceTransform: undefined, + }, + }); + + if (defined(highlightFrames)) { + const frames = flamegraph.findAllMatchingFrames( + highlightFrames.name, + highlightFrames.package + ); + + if (frames.length > 0) { + const rectFrames = frames.map( + f => new Rect(f.start, f.depth, f.end - f.start, 1) + ); + const newConfigView = computeMinZoomConfigViewForFrames( + newView.configView, + rectFrames + ); + newView.setConfigView(newConfigView); + return newView; + } + } + + // Because we render empty flamechart while we fetch the data, we need to make sure + // to have some heuristic when the data is fetched to determine if we should + // initialize the config view to the full view or a predefined value + else if ( + !defined(highlightFrames) && + position.view && + !position.view.isEmpty() && + previousView?.model === LOADING_OR_FALLBACK_FLAMEGRAPH + ) { + // We allow min width to be initialize to lower than view.minWidth because + // there is a chance that user zoomed into a span duration which may have been updated + // after the model was loaded (see L320) + newView.setConfigView(position.view, {width: {min: 0}}); + } + + return newView; + }, + + // We skip position.view dependency because it will go into an infinite loop + // eslint-disable-next-line react-hooks/exhaustive-deps + [flamegraph, flamegraphCanvas, flamegraphTheme] + ); + + useEffect(() => { + const canvasHeight = flamegraphCanvas?.logicalSpace.height; + if (!canvasHeight) { + return; + } + + setFlamegraphThemeMutation(theme => { + const flamegraphFitTo = canvasHeight / flamegraph.depth; + const minReadableRatio = 0.8; // this is quite small + const fitToRatio = flamegraphFitTo / theme.SIZES.BAR_HEIGHT; + + theme.SIZES.BAR_HEIGHT = + theme.SIZES.BAR_HEIGHT * Math.max(minReadableRatio, fitToRatio); + theme.SIZES.BAR_FONT_SIZE = + theme.SIZES.BAR_FONT_SIZE * Math.max(minReadableRatio, fitToRatio); + return theme; + }); + + // We skip `flamegraphCanvas` as it causes an infinite loop + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [flamegraph, setFlamegraphThemeMutation]); + + // Uses a useLayoutEffect to ensure that these top level/global listeners are added before + // any of the children components effects actually run. This way we do not lose events + // when we register/unregister these top level listeners. + useLayoutEffect(() => { + if (!flamegraphCanvas || !flamegraphView) { + return undefined; + } + + // This code below manages the synchronization of the config views between spans and flamegraph + // We do so by listening to the config view change event and then updating the other views accordingly which + // allows us to keep the X axis in sync between the two views but keep the Y axis independent + const onConfigViewChange = (rect: Rect, sourceConfigViewChange: CanvasView<any>) => { + if (sourceConfigViewChange === flamegraphView) { + flamegraphView.setConfigView(rect.withHeight(flamegraphView.configView.height)); + } + + canvasPoolManager.draw(); + }; + + const onTransformConfigView = ( + mat: mat3, + sourceTransformConfigView: CanvasView<any> + ) => { + if (sourceTransformConfigView === flamegraphView) { + flamegraphView.transformConfigView(mat); + } + + canvasPoolManager.draw(); + }; + + const onResetZoom = () => { + flamegraphView.resetConfigView(flamegraphCanvas); + + canvasPoolManager.draw(); + }; + + const onZoomIntoFrame = (frame: FlamegraphFrame, strategy: 'min' | 'exact') => { + const newConfigView = computeConfigViewWithStrategy( + strategy, + flamegraphView.configView, + new Rect(frame.start, frame.depth, frame.end - frame.start, 1) + ).transformRect(flamegraphView.configSpaceTransform); + + flamegraphView.setConfigView(newConfigView); + + canvasPoolManager.draw(); + }; + + scheduler.on('set config view', onConfigViewChange); + scheduler.on('transform config view', onTransformConfigView); + scheduler.on('reset zoom', onResetZoom); + scheduler.on('zoom at frame', onZoomIntoFrame); + + return () => { + scheduler.off('set config view', onConfigViewChange); + scheduler.off('transform config view', onTransformConfigView); + scheduler.off('reset zoom', onResetZoom); + scheduler.off('zoom at frame', onZoomIntoFrame); + }; + }, [canvasPoolManager, flamegraphCanvas, flamegraphView, scheduler]); + + const flamegraphCanvases = useMemo(() => { + return [flamegraphCanvasRef, flamegraphOverlayCanvasRef]; + }, [flamegraphCanvasRef, flamegraphOverlayCanvasRef]); + + const flamegraphCanvasBounds = useResizeCanvasObserver( + flamegraphCanvases, + canvasPoolManager, + flamegraphCanvas, + flamegraphView + ); + + const flamegraphRenderer = useMemo(() => { + if (!flamegraphCanvasRef) { + return null; + } + + return new FlamegraphRendererWebGL(flamegraphCanvasRef, flamegraph, flamegraphTheme, { + colorCoding, + draw_border: true, + }); + }, [colorCoding, flamegraph, flamegraphCanvasRef, flamegraphTheme]); + + useEffect(() => { + if (defined(profiles.threadId)) { + return; + } + const threadID = + typeof profileGroup.activeProfileIndex === 'number' + ? profileGroup.profiles[profileGroup.activeProfileIndex]?.threadId + : null; + + // if the state has a highlight frame specified, then we want to jump to the + // thread containing it, highlight the frames on the thread, and change the + // view so it's obvious where it is + if (highlightFrames) { + const candidate = profileGroup.profiles.reduce<FlamegraphCandidate | null>( + (prevCandidate, currentProfile) => { + // if the previous candidate is the active thread, it always takes priority + if (prevCandidate?.isActiveThread) { + return prevCandidate; + } + + const graph = new FlamegraphModel(currentProfile, currentProfile.threadId, { + inverted: false, + sort: sorting, + configSpace: undefined, + }); + + const frame = findLongestMatchingFrame(graph, highlightFrames); + + if (!defined(frame)) { + return prevCandidate; + } + + const newScore = frame.node.totalWeight || 0; + const oldScore = prevCandidate?.frame?.node?.totalWeight || 0; + + // if we find the frame on the active thread, it always takes priority + if (newScore > 0 && currentProfile.threadId === threadID) { + return { + frame, + threadId: currentProfile.threadId, + isActiveThread: true, + }; + } + + return newScore <= oldScore + ? prevCandidate + : { + frame, + threadId: currentProfile.threadId, + }; + }, + null + ); + + if (defined(candidate)) { + dispatch({ + type: 'set thread id', + payload: candidate.threadId, + }); + return; + } + } + + // fall back case, when we finally load the active profile index from the profile, + // make sure we update the thread id so that it is show first + if (defined(threadID)) { + dispatch({ + type: 'set thread id', + payload: threadID, + }); + } + }, [profileGroup, highlightFrames, profiles.threadId, dispatch, sorting]); + + return ( + <Flex h={500} column> + <FlamegraphZoomView + canvasBounds={flamegraphCanvasBounds} + canvasPoolManager={canvasPoolManager} + flamegraph={flamegraph} + flamegraphRenderer={flamegraphRenderer} + flamegraphCanvas={flamegraphCanvas} + flamegraphCanvasRef={flamegraphCanvasRef} + flamegraphOverlayCanvasRef={flamegraphOverlayCanvasRef} + flamegraphView={flamegraphView} + setFlamegraphCanvasRef={setFlamegraphCanvasRef} + setFlamegraphOverlayCanvasRef={setFlamegraphOverlayCanvasRef} + disablePanX + disableZoom + disableGrid + /> + <AggregateFlamegraphToolbar> + <Button size="xs" onClick={() => scheduler.dispatch('reset zoom')}> + {t('Reset Zoom')} + </Button> + </AggregateFlamegraphToolbar> + </Flex> + ); +} + +const AggregateFlamegraphToolbar = styled('div')` + position: absolute; + left: 0; + top: 0; + padding: ${space(1)}; + padding-left: ${space(1)}; + background-color: rgba(255, 255, 255, 0.6); + width: 100%; +`; diff --git a/static/app/components/profiling/flamegraph/flamegraphZoomView.tsx b/static/app/components/profiling/flamegraph/flamegraphZoomView.tsx index 103f7bec857bcd..1a9bf2753aecb3 100644 --- a/static/app/components/profiling/flamegraph/flamegraphZoomView.tsx +++ b/static/app/components/profiling/flamegraph/flamegraphZoomView.tsx @@ -69,6 +69,9 @@ interface FlamegraphZoomViewProps { setFlamegraphOverlayCanvasRef: React.Dispatch< React.SetStateAction<HTMLCanvasElement | null> >; + disableGrid?: boolean; + disablePanX?: boolean; + disableZoom?: boolean; } function FlamegraphZoomView({ @@ -82,6 +85,9 @@ function FlamegraphZoomView({ flamegraphView, setFlamegraphCanvasRef, setFlamegraphOverlayCanvasRef, + disablePanX = false, + disableZoom = false, + disableGrid = false, }: FlamegraphZoomViewProps): React.ReactElement { const flamegraphTheme = useFlamegraphTheme(); const profileGroup = useProfileGroup(); @@ -112,7 +118,7 @@ function FlamegraphZoomView({ }, [flamegraph, flamegraphOverlayCanvasRef, flamegraphTheme]); const gridRenderer: GridRenderer | null = useMemo(() => { - if (!flamegraphOverlayCanvasRef) { + if (!flamegraphOverlayCanvasRef || disableGrid) { return null; } return new GridRenderer( @@ -120,7 +126,7 @@ function FlamegraphZoomView({ flamegraphTheme, flamegraph.formatter ); - }, [flamegraphOverlayCanvasRef, flamegraph, flamegraphTheme]); + }, [flamegraphOverlayCanvasRef, flamegraph, flamegraphTheme, disableGrid]); const sampleTickRenderer: SampleTickRenderer | null = useMemo(() => { if (!isInternalFlamegraphDebugModeEnabled) { @@ -506,12 +512,14 @@ function FlamegraphZoomView({ const onWheelCenterZoom = useWheelCenterZoom( flamegraphCanvas, flamegraphView, - canvasPoolManager + canvasPoolManager, + disableZoom ); const onCanvasScroll = useCanvasScroll( flamegraphCanvas, flamegraphView, - canvasPoolManager + canvasPoolManager, + disablePanX ); useCanvasZoomOrScroll({ @@ -657,6 +665,7 @@ const CanvasContainer = styled('div')` display: flex; flex-direction: column; height: 100%; + width: 100%; position: relative; `; diff --git a/static/app/components/profiling/flamegraph/interactions/useCanvasScroll.tsx b/static/app/components/profiling/flamegraph/interactions/useCanvasScroll.tsx index 8611b46e4833f6..2849bac55cde80 100644 --- a/static/app/components/profiling/flamegraph/interactions/useCanvasScroll.tsx +++ b/static/app/components/profiling/flamegraph/interactions/useCanvasScroll.tsx @@ -8,7 +8,8 @@ import {getTranslationMatrixFromPhysicalSpace} from 'sentry/utils/profiling/gl/u export function useCanvasScroll( canvas: FlamegraphCanvas | null, view: CanvasView<any> | null, - canvasPoolManager: CanvasPoolManager + canvasPoolManager: CanvasPoolManager, + disablePanX: boolean = false ) { const onCanvasScroll = useCallback( (evt: WheelEvent) => { @@ -17,11 +18,16 @@ export function useCanvasScroll( } canvasPoolManager.dispatch('transform config view', [ - getTranslationMatrixFromPhysicalSpace(evt.deltaX, evt.deltaY, view, canvas), + getTranslationMatrixFromPhysicalSpace( + disablePanX ? 0 : evt.deltaX, + evt.deltaY, + view, + canvas + ), view, ]); }, - [canvas, view, canvasPoolManager] + [canvas, view, canvasPoolManager, disablePanX] ); return onCanvasScroll; diff --git a/static/app/components/profiling/flamegraph/interactions/useWheelCenterZoom.tsx b/static/app/components/profiling/flamegraph/interactions/useWheelCenterZoom.tsx index 2597c5a97ccb3e..3a75cdbb7c71ee 100644 --- a/static/app/components/profiling/flamegraph/interactions/useWheelCenterZoom.tsx +++ b/static/app/components/profiling/flamegraph/interactions/useWheelCenterZoom.tsx @@ -9,11 +9,12 @@ import {getCenterScaleMatrixFromMousePosition} from 'sentry/utils/profiling/gl/u export function useWheelCenterZoom( canvas: FlamegraphCanvas | null, view: CanvasView<any> | null, - canvasPoolManager: CanvasPoolManager + canvasPoolManager: CanvasPoolManager, + disable: boolean = false ) { const zoom = useCallback( (evt: WheelEvent) => { - if (!canvas || !view) { + if (!canvas || !view || disable) { return; } @@ -28,7 +29,7 @@ export function useWheelCenterZoom( view, ]); }, - [canvas, view, canvasPoolManager] + [canvas, view, canvasPoolManager, disable] ); return zoom; diff --git a/static/app/utils/profiling/flamegraph/flamegraphThemeProvider.tsx b/static/app/utils/profiling/flamegraph/flamegraphThemeProvider.tsx index fffd242a5fcb73..5e7ef06c3886a0 100644 --- a/static/app/utils/profiling/flamegraph/flamegraphThemeProvider.tsx +++ b/static/app/utils/profiling/flamegraph/flamegraphThemeProvider.tsx @@ -1,4 +1,5 @@ -import {createContext} from 'react'; +import {createContext, useCallback, useMemo, useState} from 'react'; +import cloneDeep from 'lodash/cloneDeep'; import ConfigStore from 'sentry/stores/configStore'; import {useLegacyStore} from 'sentry/stores/useLegacyStore'; @@ -10,6 +11,15 @@ import { export const FlamegraphThemeContext = createContext<FlamegraphTheme | null>(null); +type FlamegraphThemeMutationCallback = ( + theme: FlamegraphTheme, + colorMode?: 'light' | 'dark' +) => FlamegraphTheme; + +export const FlamegraphThemeMutationContext = createContext< + ((cb: FlamegraphThemeMutationCallback) => void) | null +>(null); + interface FlamegraphThemeProviderProps { children: React.ReactNode; } @@ -17,15 +27,30 @@ interface FlamegraphThemeProviderProps { function FlamegraphThemeProvider( props: FlamegraphThemeProviderProps ): React.ReactElement { - const {theme} = useLegacyStore(ConfigStore); + const {theme: colorMode} = useLegacyStore(ConfigStore); + + const [mutation, setMutation] = useState<FlamegraphThemeMutationCallback | null>(null); + + const addModifier = useCallback((cb: FlamegraphThemeMutationCallback) => { + setMutation(() => cb); + }, []); - const activeFlamegraphTheme = - theme === 'light' ? LightFlamegraphTheme : DarkFlamegraphTheme; + const activeFlamegraphTheme = useMemo(() => { + const flamegraphTheme = + colorMode === 'light' ? LightFlamegraphTheme : DarkFlamegraphTheme; + if (!mutation) { + return flamegraphTheme; + } + const clonedTheme = cloneDeep(flamegraphTheme); + return mutation(clonedTheme, colorMode); + }, [mutation, colorMode]); return ( - <FlamegraphThemeContext.Provider value={activeFlamegraphTheme}> - {props.children} - </FlamegraphThemeContext.Provider> + <FlamegraphThemeMutationContext.Provider value={addModifier}> + <FlamegraphThemeContext.Provider value={activeFlamegraphTheme}> + {props.children} + </FlamegraphThemeContext.Provider> + </FlamegraphThemeMutationContext.Provider> ); } diff --git a/static/app/utils/profiling/flamegraph/useFlamegraphTheme.ts b/static/app/utils/profiling/flamegraph/useFlamegraphTheme.ts index 7c7f2f954afcdf..b81a6fc304b33d 100644 --- a/static/app/utils/profiling/flamegraph/useFlamegraphTheme.ts +++ b/static/app/utils/profiling/flamegraph/useFlamegraphTheme.ts @@ -1,7 +1,10 @@ import {useContext} from 'react'; import {FlamegraphTheme} from './flamegraphTheme'; -import {FlamegraphThemeContext} from './flamegraphThemeProvider'; +import { + FlamegraphThemeContext, + FlamegraphThemeMutationContext, +} from './flamegraphThemeProvider'; export function useFlamegraphTheme(): FlamegraphTheme { const ctx = useContext(FlamegraphThemeContext); @@ -12,3 +15,13 @@ export function useFlamegraphTheme(): FlamegraphTheme { return ctx; } + +export function useMutateFlamegraphTheme() { + const ctx = useContext(FlamegraphThemeMutationContext); + if (!ctx) { + throw new Error( + 'useMutateFlamegraphTheme was called outside of FlamegraphThemeProvider' + ); + } + return ctx; +} diff --git a/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts b/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts new file mode 100644 index 00000000000000..50f7b2ae63585e --- /dev/null +++ b/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts @@ -0,0 +1,32 @@ +import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; +import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam'; +import {useQuery} from 'sentry/utils/queryClient'; +import {MutableSearch} from 'sentry/utils/tokenizeSearch'; +import useOrganization from 'sentry/utils/useOrganization'; +import usePageFilters from 'sentry/utils/usePageFilters'; + +export function useAggregateFlamegraphQuery({transaction}: {transaction: string}) { + const {selection} = usePageFilters(); + const organization = useOrganization(); + const project = useCurrentProjectFromRouteParam(); + const url = `/projects/${organization.slug}/${project?.slug}/profiling/flamegraph/`; + const conditions = new MutableSearch([]); + conditions.setFilterValues('transaction_name', [transaction]); + + return useQuery<Profiling.ProfileInput>( + [ + url, + { + query: { + query: conditions.formatString(), + ...normalizeDateTimeParams(selection.datetime), + }, + }, + ], + { + staleTime: 0, + retry: false, + enabled: Boolean(organization?.slug && project?.slug && selection.datetime), + } + ); +} diff --git a/static/app/views/profiling/landing/profileCharts.tsx b/static/app/views/profiling/landing/profileCharts.tsx index 46e5c0a9a12572..9bdafcb096b2f6 100644 --- a/static/app/views/profiling/landing/profileCharts.tsx +++ b/static/app/views/profiling/landing/profileCharts.tsx @@ -17,6 +17,7 @@ import useRouter from 'sentry/utils/useRouter'; interface ProfileChartsProps { query: string; + compact?: boolean; hideCount?: boolean; selection?: PageFilters; } @@ -26,7 +27,12 @@ interface ProfileChartsProps { // cover it up. const SERIES_ORDER = ['count()', 'p99()', 'p95()', 'p75()'] as const; -export function ProfileCharts({query, selection, hideCount}: ProfileChartsProps) { +export function ProfileCharts({ + query, + selection, + hideCount, + compact = false, +}: ProfileChartsProps) { const router = useRouter(); const theme = useTheme(); @@ -102,12 +108,12 @@ export function ProfileCharts({query, selection, hideCount}: ProfileChartsProps) <StyledPanel> <TitleContainer> {!hideCount && ( - <StyledHeaderTitle>{t('Profiles by Count')}</StyledHeaderTitle> + <StyledHeaderTitle compact>{t('Profiles by Count')}</StyledHeaderTitle> )} - <StyledHeaderTitle>{t('Profiles by Percentiles')}</StyledHeaderTitle> + <StyledHeaderTitle compact>{t('Profiles by Percentiles')}</StyledHeaderTitle> </TitleContainer> <AreaChart - height={300} + height={compact ? 150 : 300} series={series} grid={[ { @@ -192,7 +198,8 @@ const TitleContainer = styled('div')` flex-direction: row; `; -const StyledHeaderTitle = styled(HeaderTitle)` +const StyledHeaderTitle = styled(HeaderTitle)<{compact?: boolean}>` flex-grow: 1; margin-left: ${space(2)}; + font-size: ${p => (p.compact ? p.theme.fontSizeSmall : undefined)}; `; diff --git a/static/app/views/profiling/profileSummary/content.tsx b/static/app/views/profiling/profileSummary/content.tsx index d66e92a97aca73..b0de03b2d954c3 100644 --- a/static/app/views/profiling/profileSummary/content.tsx +++ b/static/app/views/profiling/profileSummary/content.tsx @@ -6,6 +6,7 @@ import {Location} from 'history'; import {CompactSelect} from 'sentry/components/compactSelect'; import * as Layout from 'sentry/components/layouts/thirds'; import Pagination from 'sentry/components/pagination'; +import {AggregateFlamegraphPanel} from 'sentry/components/profiling/aggregateFlamegraphPanel'; import {ProfileEventsTable} from 'sentry/components/profiling/profileEventsTable'; import {SuspectFunctionsTable} from 'sentry/components/profiling/suspectFunctions/suspectFunctionsTable'; import {mobile} from 'sentry/data/platformCategories'; @@ -17,6 +18,7 @@ import { useProfileEvents, } from 'sentry/utils/profiling/hooks/useProfileEvents'; import {decodeScalar} from 'sentry/utils/queryString'; +import useOrganization from 'sentry/utils/useOrganization'; import {ProfileCharts} from 'sentry/views/profiling/landing/profileCharts'; interface ProfileSummaryContentProps { @@ -28,6 +30,7 @@ interface ProfileSummaryContentProps { } function ProfileSummaryContent(props: ProfileSummaryContentProps) { + const organization = useOrganization(); const fields = useMemo( () => getProfilesTableFields(props.project.platform), [props.project] @@ -66,10 +69,21 @@ function ProfileSummaryContent(props: ProfileSummaryContentProps) { [props.location] ); + const isAggregateFlamegraphEnabled = organization.features.includes( + 'profiling-aggregate-flamegraph' + ); + return ( <Fragment> <Layout.Main fullWidth> - <ProfileCharts query={props.query} hideCount /> + <ProfileCharts + query={props.query} + hideCount + compact={isAggregateFlamegraphEnabled} + /> + {isAggregateFlamegraphEnabled && ( + <AggregateFlamegraphPanel transaction={props.transaction} /> + )} <TableHeader> <CompactSelect triggerProps={{prefix: t('Filter'), size: 'xs'}}
c014779f3d0c8f7ccd9c87ee2458d24ee99196d6
2023-02-01 20:28:06
Pierre Massat
ref(profiling): Remove code producing to Kafka as it's handled by vroom (#43907)
false
Remove code producing to Kafka as it's handled by vroom (#43907)
ref
diff --git a/src/sentry/profiles/task.py b/src/sentry/profiles/task.py index e3d5dd83bcb4bf..db00c3fa950994 100644 --- a/src/sentry/profiles/task.py +++ b/src/sentry/profiles/task.py @@ -6,8 +6,6 @@ from typing import Any, List, Mapping, MutableMapping, Optional, Tuple import sentry_sdk -from arroyo.backends.kafka.consumer import KafkaPayload, KafkaProducer -from arroyo.types import Topic from django.conf import settings from django.utils import timezone from pytz import UTC @@ -22,14 +20,12 @@ from sentry.signals import first_profile_received from sentry.tasks.base import instrumented_task from sentry.tasks.symbolication import RetrySymbolication -from sentry.utils import json, kafka_config, metrics +from sentry.utils import metrics from sentry.utils.outcomes import Outcome, track_outcome Profile = MutableMapping[str, Any] CallTrees = Mapping[str, List[Any]] -_profiles_kafka_producer = None - class VroomTimeout(Exception): pass @@ -130,8 +126,7 @@ def process_profile_task( ) return - success, produce_to_kafka = _insert_vroom_profile(profile=profile) - if not success: + if not _insert_vroom_profile(profile=profile): _track_outcome( profile=profile, project=project, @@ -140,33 +135,6 @@ def process_profile_task( ) return - if produce_to_kafka: - _initialize_producer() - - try: - _insert_eventstream_call_tree(profile=profile) - except Exception as e: - sentry_sdk.capture_exception(e) - _track_outcome( - profile=profile, - project=project, - outcome=Outcome.INVALID, - reason="failed-to-produce-functions", - ) - return - - try: - _insert_eventstream_profile(profile=profile) - except Exception as e: - sentry_sdk.capture_exception(e) - _track_outcome( - profile=profile, - project=project, - outcome=Outcome.INVALID, - reason="failed-to-produce-metadata", - ) - return - _track_outcome(profile=profile, project=project, outcome=Outcome.ACCEPTED) @@ -186,7 +154,7 @@ def _should_deobfuscate(profile: Profile) -> bool: @metrics.wraps("process_profile.normalize") def _normalize(profile: Profile, organization: Organization) -> None: - profile["retention_days"] = quotas.get_event_retention(organization=organization) + profile["retention_days"] = quotas.get_event_retention(organization=organization) or 90 if profile["platform"] in {"cocoa", "android"}: classification_options = dict() @@ -527,113 +495,8 @@ def _track_outcome( ) [email protected]("process_profile.initialize_producer") -def _initialize_producer() -> None: - global _profiles_kafka_producer - - if _profiles_kafka_producer is None: - config = settings.KAFKA_TOPICS[settings.KAFKA_PROFILES] - _profiles_kafka_producer = KafkaProducer( - kafka_config.get_kafka_producer_cluster_options(config["cluster"]), - ) - - [email protected]("process_profile.insert_eventstream.profile") -def _insert_eventstream_profile(profile: Profile) -> None: - """ - TODO: This function directly publishes the profile to kafka. - We'll want to look into the existing eventstream abstraction - so we can take advantage of nodestore at some point for single - profile access. - """ - - # just a guard as this should always be initialized already - if _profiles_kafka_producer is None: - return - - f = _profiles_kafka_producer.produce( - Topic(name="processed-profiles"), - KafkaPayload(key=None, value=json.dumps(profile).encode("utf-8"), headers=[]), - ) - f.exception() - - [email protected]("process_profile.insert_eventstream.call_tree") -def _insert_eventstream_call_tree(profile: Profile) -> None: - # just a guard as this should always be initialized already - if _profiles_kafka_producer is None: - return - - # call_trees is empty because of an error earlier, skip aggregation - if not profile.get("call_trees"): - return - - try: - if "version" in profile: - event = _get_event_instance_for_sample(profile) - else: - event = _get_event_instance_for_legacy(profile) - except Exception as e: - sentry_sdk.capture_exception(e) - return - finally: - # Assumes that the call tree is inserted into the - # event stream before the profile is inserted into - # the event stream. - # - # After inserting the call tree, we no longer need - # it, but if we don't delete it here, it will be - # inserted in the profile payload making it larger - # and slower. - del profile["call_trees"] - - f = _profiles_kafka_producer.produce( - Topic(name="profiles-call-tree"), - KafkaPayload(key=None, value=json.dumps(event).encode("utf-8"), headers=[]), - ) - f.exception() - - [email protected]("process_profile.get_event_instance") -def _get_event_instance_for_sample(profile: Profile) -> Any: - return { - "call_trees": profile["call_trees"], - "environment": profile.get("environment"), - "os_name": profile["os"]["name"], - "os_version": profile["os"]["version"], - "platform": profile["platform"], - "profile_id": profile["event_id"], - "project_id": profile["project_id"], - "release": profile["release"], - "retention_days": profile["retention_days"], - "timestamp": profile["received"], - "transaction_name": profile["transactions"][0]["name"], - } - - [email protected]("process_profile.get_event_instance") -def _get_event_instance_for_legacy(profile: Profile) -> Any: - return { - "call_trees": profile["call_trees"], - "environment": profile.get("environment"), - "os_name": profile["device_os_name"], - "os_version": profile["device_os_version"], - "platform": profile["platform"], - "profile_id": profile["profile_id"], - "project_id": profile["project_id"], - "release": f"{profile['version_name']} ({profile['version_code']})" - if profile["version_code"] - else profile["version_name"], - "retention_days": profile["retention_days"], - "timestamp": profile["received"], - "transaction_name": profile["transaction_name"], - } - - @metrics.wraps("process_profile.insert_vroom_profile") -def _insert_vroom_profile(profile: Profile) -> Tuple[bool, bool]: - original_timestamp = profile["received"] - +def _insert_vroom_profile(profile: Profile) -> bool: try: profile["received"] = ( datetime.utcfromtimestamp(profile["received"]).replace(tzinfo=timezone.utc).isoformat() @@ -642,11 +505,7 @@ def _insert_vroom_profile(profile: Profile) -> Tuple[bool, bool]: response = get_from_profiling_service(method="POST", path="/profile", json_data=profile) if response.status == 204: - profile["call_trees"] = {} - return True, False - elif response.status == 200: - profile["call_trees"] = json.loads(response.data, use_rapid_json=True)["call_trees"] - return True, True + return True elif response.status == 429: raise VroomTimeout else: @@ -655,10 +514,7 @@ def _insert_vroom_profile(profile: Profile) -> Tuple[bool, bool]: tags={"platform": profile["platform"], "reason": "bad status"}, sample_rate=1.0, ) - return False, False - except RecursionError as e: - sentry_sdk.capture_exception(e) - return True, True + return False except VroomTimeout: raise except Exception as e: @@ -668,10 +524,4 @@ def _insert_vroom_profile(profile: Profile) -> Tuple[bool, bool]: tags={"platform": profile["platform"], "reason": "encountered error"}, sample_rate=1.0, ) - return False, False - finally: - profile["received"] = original_timestamp - - # remove keys we don't need anymore for snuba - for k in {"profile", "debug_meta"}: - profile.pop(k, None) + return False
772b0f8ed685ba5d157737c7ca28dfba0860730e
2022-06-01 01:35:06
Stephen Cefali
fix(onboarding): change setup to set up (#35146)
false
change setup to set up (#35146)
fix
diff --git a/static/app/views/onboarding/targetedOnboarding/welcome.tsx b/static/app/views/onboarding/targetedOnboarding/welcome.tsx index a9faa20e4f3c52..d67b73cccaf278 100644 --- a/static/app/views/onboarding/targetedOnboarding/welcome.tsx +++ b/static/app/views/onboarding/targetedOnboarding/welcome.tsx @@ -55,7 +55,7 @@ function TargetedOnboardingWelcome({organization, ...props}: StepProps) { organization, source, }); - }, []); + }); const onComplete = () => { trackAdvancedAnalyticsEvent('growth.onboarding_clicked_instrument_app', { @@ -112,7 +112,7 @@ function TargetedOnboardingWelcome({organization, ...props}: StepProps) { </ActionItem> <ActionItem {...fadeAway}> <InnerAction - title={t('Setup my team')} + title={t('Set up my team')} subText={tct( 'Invite [friends] coworkers. You shouldn’t have to fix what you didn’t break', {friends: <Strike>{t('friends')}</Strike>}
e64603d1f5225be86d9e6d624c2821504158d706
2024-03-29 11:16:31
Jonas
fix(trace): fix error on autogrouped icon (#67846)
false
fix error on autogrouped icon (#67846)
fix
diff --git a/static/app/views/performance/newTraceDetails/trace.tsx b/static/app/views/performance/newTraceDetails/trace.tsx index 9e350976b24dab..2a670def46f185 100644 --- a/static/app/views/performance/newTraceDetails/trace.tsx +++ b/static/app/views/performance/newTraceDetails/trace.tsx @@ -2129,11 +2129,6 @@ const TraceStylingWrapper = styled('div')` > div { height: 100%; } - - .TraceError { - top: -1px; - transform: translate(-50%, 0); - } } svg {
cf7da1ddd906ba6ee97a7f46d92b3457ee4e49bc
2018-10-05 05:05:24
Evan Purkhiser
ref(ui): Remove fake sidebar during load (#10026)
false
Remove fake sidebar during load (#10026)
ref
diff --git a/src/sentry/static/sentry/app/views/onboarding/onboarding.less b/src/sentry/static/sentry/app/views/onboarding/onboarding.less index 7018c193535540..bfb0904a709358 100644 --- a/src/sentry/static/sentry/app/views/onboarding/onboarding.less +++ b/src/sentry/static/sentry/app/views/onboarding/onboarding.less @@ -2,7 +2,6 @@ .onboarding-container { margin-left: @onboarding-sidebar-width; - margin-left: @onboarding-sidebar-width - @sidebar-width; max-width: 800px + @onboarding-sidebar-width; margin-top: 30px; diff --git a/src/sentry/static/sentry/less/layout.less b/src/sentry/static/sentry/less/layout.less index 183e8247605272..a1c6c2c6682e23 100644 --- a/src/sentry/static/sentry/less/layout.less +++ b/src/sentry/static/sentry/less/layout.less @@ -10,15 +10,8 @@ body { color: @gray-darker; -webkit-font-smoothing: antialiased; overflow-x: hidden; - padding-left: @sidebar-width; min-height: 100vh; - // Fake sidebar rendering until actual sidebar is loaded - - background-image: linear-gradient(@header-bg-color, @header-bg-color); - background-size: @sidebar-width; - background-repeat: repeat-y; - &.new-settings { overflow-y: scroll; background-image: none;
9515db7ed4eb78595e5903be239fae01a8ebfacc
2018-05-04 23:21:53
David Cramer
feat(api): Include email address in assignedTo
false
Include email address in assignedTo
feat
diff --git a/src/sentry/api/serializers/models/actor.py b/src/sentry/api/serializers/models/actor.py index e2427d52e89e61..3937d1fd575fd2 100644 --- a/src/sentry/api/serializers/models/actor.py +++ b/src/sentry/api/serializers/models/actor.py @@ -11,14 +11,17 @@ def serialize(self, obj, attrs, *args, **kwargs): if isinstance(obj, User): actor_type = 'user' name = obj.get_display_name() + context = {'email': obj.email} elif isinstance(obj, Team): actor_type = 'team' name = obj.slug + context = {} else: raise AssertionError('Invalid type to assign to: %r' % type(obj)) - return { + context.update({ 'type': actor_type, 'id': six.text_type(obj.id), 'name': name, - } + }) + return context
196a8daa264c4836881b7847c65b25a7d96be915
2024-10-18 01:00:23
Priscila Oliveira
ref(alerts): Add query_type to analytics tracking code (#79280)
false
Add query_type to analytics tracking code (#79280)
ref
diff --git a/src/sentry/analytics/events/alert_created.py b/src/sentry/analytics/events/alert_created.py index d9f743dcdac9d3..c00ac0b2f4038b 100644 --- a/src/sentry/analytics/events/alert_created.py +++ b/src/sentry/analytics/events/alert_created.py @@ -15,6 +15,7 @@ class AlertCreatedEvent(analytics.Event): analytics.Attribute("alert_rule_ui_component", required=False), analytics.Attribute("duplicate_rule", required=False), analytics.Attribute("wizard_v3", required=False), + analytics.Attribute("query_type", required=False), ) diff --git a/src/sentry/incidents/endpoints/organization_alert_rule_index.py b/src/sentry/incidents/endpoints/organization_alert_rule_index.py index 092c7fc6320b01..e7bae6fd35570a 100644 --- a/src/sentry/incidents/endpoints/organization_alert_rule_index.py +++ b/src/sentry/incidents/endpoints/organization_alert_rule_index.py @@ -54,6 +54,7 @@ from sentry.sentry_apps.services.app import app_service from sentry.signals import alert_rule_created from sentry.snuba.dataset import Dataset +from sentry.snuba.models import SnubaQuery from sentry.uptime.models import ( ProjectUptimeSubscription, ProjectUptimeSubscriptionMode, @@ -159,9 +160,16 @@ def create_metric_alert( is_api_token=request.auth is not None, duplicate_rule=duplicate_rule, wizard_v3=wizard_v3, + query_type=self.get_query_type_description(data.get("queryType", None)), ) return Response(serialize(alert_rule, request.user), status=status.HTTP_201_CREATED) + def get_query_type_description(self, value): + try: + return SnubaQuery.Type(value).name + except ValueError: + return "Unknown" + @region_silo_endpoint class OrganizationCombinedRuleIndexEndpoint(OrganizationEndpoint): diff --git a/src/sentry/receivers/features.py b/src/sentry/receivers/features.py index c4183c08389911..7eb48ad9971717 100644 --- a/src/sentry/receivers/features.py +++ b/src/sentry/receivers/features.py @@ -306,6 +306,7 @@ def record_alert_rule_created( alert_rule_ui_component=None, duplicate_rule=None, wizard_v3=None, + query_type=None, **kwargs, ): # NOTE: This intentionally does not fire for the default issue alert rule @@ -334,6 +335,7 @@ def record_alert_rule_created( alert_rule_ui_component=alert_rule_ui_component, duplicate_rule=duplicate_rule, wizard_v3=wizard_v3, + query_type=query_type, ) diff --git a/src/sentry/signals.py b/src/sentry/signals.py index 979ebefab65ada..abce0805ba6cde 100644 --- a/src/sentry/signals.py +++ b/src/sentry/signals.py @@ -135,7 +135,7 @@ def _log_robust_failure(self, receiver: object, err: Exception) -> None: inbound_filter_toggled = BetterSignal() # ["project"] sso_enabled = BetterSignal() # ["organization_id", "user_id", "provider"] data_scrubber_enabled = BetterSignal() # ["organization"] -# ["project", "rule", "user", "rule_type", "is_api_token", "duplicate_rule", "wizard_v3"] +# ["project", "rule", "user", "rule_type", "is_api_token", "duplicate_rule", "wizard_v3", "query_type"] alert_rule_created = BetterSignal() alert_rule_edited = BetterSignal() # ["project", "rule", "user", "rule_type", "is_api_token"] repo_linked = BetterSignal() # ["repo", "user"] diff --git a/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py b/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py index bf124c85aa2204..c6b9d675a301dc 100644 --- a/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py +++ b/tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py @@ -1317,6 +1317,21 @@ def test_post_rule_over_256_char_name(self): ) assert resp.data["name"][0] == "Ensure this field has no more than 256 characters." + @patch("sentry.analytics.record") + def test_performance_alert(self, record_analytics): + valid_alert_rule = { + **self.alert_rule_dict, + "queryType": 1, + "dataset": "transactions", + "eventTypes": ["transaction"], + } + with self.feature(["organizations:incidents", "organizations:performance-view"]): + resp = self.get_response(self.organization.slug, **valid_alert_rule) + assert resp.status_code == 201 + assert self.analytics_called_with_args( + record_analytics, "alert.created", query_type="PERFORMANCE" + ) + @freeze_time() class AlertRuleCreateEndpointTestCrashRateAlert(AlertRuleIndexBase):
34848a5acac27033a520917cef1364ea810da0da
2024-12-18 00:22:15
Josh Callender
ref(workflow_engine): Add constraint to `DataSource.type` on pre_save signal (#82116)
false
Add constraint to `DataSource.type` on pre_save signal (#82116)
ref
diff --git a/src/sentry/workflow_engine/models/data_source.py b/src/sentry/workflow_engine/models/data_source.py index 320a01709a290e..0ebf62f600ddd4 100644 --- a/src/sentry/workflow_engine/models/data_source.py +++ b/src/sentry/workflow_engine/models/data_source.py @@ -3,6 +3,8 @@ from typing import Generic, TypeVar from django.db import models +from django.db.models.signals import pre_save +from django.dispatch import receiver from sentry.backup.scopes import RelocationScope from sentry.db.models import ( @@ -11,6 +13,7 @@ FlexibleForeignKey, region_silo_model, ) +from sentry.utils.registry import NoRegistrationExistsError from sentry.workflow_engine.models.data_source_detector import DataSourceDetector from sentry.workflow_engine.registry import data_source_type_registry from sentry.workflow_engine.types import DataSourceTypeHandler @@ -33,7 +36,7 @@ class DataSource(DefaultFieldsModel): # Should this be a string so we can support UUID / ints? query_id = BoundedBigIntegerField() - # TODO - Add a type here + # This is a dynamic field, depending on the type in the data_source_type_registry type = models.TextField() detectors = models.ManyToManyField("workflow_engine.Detector", through=DataSourceDetector) @@ -49,3 +52,19 @@ def type_handler(self) -> builtins.type[DataSourceTypeHandler]: if not handler: raise ValueError(f"Unknown data source type: {self.type}") return handler + + +@receiver(pre_save, sender=DataSource) +def ensure_type_handler_registered(sender, instance: DataSource, **kwargs): + """ + Ensure that the type of the data source is valid and registered in the data_source_type_registry + """ + data_source_type = instance.type + + if not data_source_type: + raise ValueError(f"No group type found with type {instance.type}") + + try: + data_source_type_registry.get(data_source_type) + except NoRegistrationExistsError: + raise ValueError(f"No data source type found with type {data_source_type}") diff --git a/tests/sentry/workflow_engine/models/test_data_source.py b/tests/sentry/workflow_engine/models/test_data_source.py new file mode 100644 index 00000000000000..f55c2b4f81b1de --- /dev/null +++ b/tests/sentry/workflow_engine/models/test_data_source.py @@ -0,0 +1,20 @@ +from unittest import mock + +import pytest + +from sentry.workflow_engine.registry import data_source_type_registry +from tests.sentry.workflow_engine.test_base import BaseWorkflowTest + + +class DataSourceTest(BaseWorkflowTest): + def test_invalid_data_source_type(self): + with pytest.raises(ValueError): + self.create_data_source(type="invalid_type") + + def test_data_source_valid_type(self): + # Make sure the mock was registered in test_base + assert isinstance(data_source_type_registry.get("test"), mock.Mock) + + data_source = self.create_data_source(type="test") + assert data_source is not None + assert data_source.type == "test" diff --git a/tests/sentry/workflow_engine/processors/test_data_sources.py b/tests/sentry/workflow_engine/processors/test_data_sources.py index 2e655b67007085..f57274f87a7f8d 100644 --- a/tests/sentry/workflow_engine/processors/test_data_sources.py +++ b/tests/sentry/workflow_engine/processors/test_data_sources.py @@ -1,7 +1,10 @@ +from unittest import mock + from sentry.snuba.models import SnubaQuery from sentry.testutils.cases import TestCase from sentry.workflow_engine.models import DataPacket from sentry.workflow_engine.processors import process_data_sources +from sentry.workflow_engine.registry import data_source_type_registry class TestProcessDataSources(TestCase): @@ -16,6 +19,9 @@ def create_snuba_query(self, **kwargs): ) def setUp(self): + # check that test_base registers the data_source_type_registry + assert isinstance(data_source_type_registry.get("test"), mock.Mock) + self.query = self.create_snuba_query() self.query_two = self.create_snuba_query() diff --git a/tests/sentry/workflow_engine/test_base.py b/tests/sentry/workflow_engine/test_base.py index f91fd33c657ad8..ea8686d550a67e 100644 --- a/tests/sentry/workflow_engine/test_base.py +++ b/tests/sentry/workflow_engine/test_base.py @@ -1,4 +1,5 @@ from datetime import UTC, datetime +from unittest import mock from uuid import uuid4 from sentry.eventstore.models import Event, GroupEvent @@ -8,6 +9,7 @@ from sentry.snuba.models import SnubaQuery from sentry.testutils.cases import TestCase from sentry.testutils.factories import EventType +from sentry.utils.registry import AlreadyRegisteredError from sentry.workflow_engine.models import ( Action, DataConditionGroup, @@ -18,9 +20,17 @@ Workflow, ) from sentry.workflow_engine.models.data_condition import Condition +from sentry.workflow_engine.registry import data_source_type_registry from sentry.workflow_engine.types import DetectorPriorityLevel from tests.sentry.issues.test_utils import OccurrenceTestMixin +try: + type_mock = mock.Mock() + data_source_type_registry.register("test")(type_mock) +except AlreadyRegisteredError: + # Ensure "test" is mocked for tests, but don't fail if already registered here. + pass + class BaseWorkflowTest(TestCase, OccurrenceTestMixin): def create_snuba_query(self, **kwargs):
7215bc36ee063e4bc394e725f02f67bdb301654c
2023-06-13 15:32:28
Pierre Massat
feat(backpressure): Check for healthiness at a regular interval (#50517)
false
Check for healthiness at a regular interval (#50517)
feat
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py index ea51eeeba4928a..2a550de55afc8e 100644 --- a/src/sentry/options/defaults.py +++ b/src/sentry/options/defaults.py @@ -1311,6 +1311,11 @@ ) # Enables checking queue health in consumers for backpressure management. register("backpressure.monitor_queues.enable_check", default=False, flags=FLAG_AUTOMATOR_MODIFIABLE) +register( + "backpressure.monitor_queues.check_interval_in_seconds", + default=5, + flags=FLAG_AUTOMATOR_MODIFIABLE, +) register( "backpressure.monitor_queues.unhealthy_threshold", default=1000, flags=FLAG_AUTOMATOR_MODIFIABLE ) diff --git a/src/sentry/profiles/consumers/process/factory.py b/src/sentry/profiles/consumers/process/factory.py index 88117c98a5145e..7ac4b359b52798 100644 --- a/src/sentry/profiles/consumers/process/factory.py +++ b/src/sentry/profiles/consumers/process/factory.py @@ -1,28 +1,44 @@ +from time import time from typing import Mapping from arroyo.backends.kafka.consumer import KafkaPayload -from arroyo.processing.strategies.abstract import ( - MessageRejected, - ProcessingStrategy, - ProcessingStrategyFactory, -) +from arroyo.processing.strategies.abstract import ProcessingStrategy, ProcessingStrategyFactory from arroyo.processing.strategies.commit import CommitOffsets from arroyo.processing.strategies.run_task import RunTask from arroyo.types import Commit, Message, Partition +from sentry import options from sentry.monitoring.queues import is_queue_healthy, monitor_queues +from sentry.processing.backpressure.arroyo import HealthChecker, create_backpressure_step from sentry.profiles.task import process_profile_task def process_message(message: Message[KafkaPayload]) -> None: - if not is_queue_healthy("profiles.process"): - raise MessageRejected() process_profile_task.s(payload=message.payload.value).apply_async() +class ProfilesHealthChecker(HealthChecker): + def __init__(self): + self.last_check: float = 0 + # Queue is healthy by default + self.is_queue_healthy = True + + def is_healthy(self) -> bool: + now = time() + # Check queue health if it's been more than the interval + if now - self.last_check >= options.get( + "backpressure.monitor_queues.check_interval_in_seconds" + ): + self.is_queue_healthy = is_queue_healthy("profiles.process") + # We don't count the time it took to check as part of the interval + self.last_check = now + return self.is_queue_healthy + + class ProcessProfileStrategyFactory(ProcessingStrategyFactory[KafkaPayload]): def __init__(self) -> None: super().__init__() + self.health_checker = ProfilesHealthChecker() monitor_queues() def create_with_partitions( @@ -30,7 +46,11 @@ def create_with_partitions( commit: Commit, partitions: Mapping[Partition, int], ) -> ProcessingStrategy[KafkaPayload]: - return RunTask( + next_step = RunTask( function=process_message, next_step=CommitOffsets(commit), ) + return create_backpressure_step( + health_checker=self.health_checker, + next_step=next_step, + ) diff --git a/tests/sentry/monitoring/test_queues.py b/tests/sentry/monitoring/test_queues.py index 514c1b7fbce2a6..ada55ef6bf689b 100644 --- a/tests/sentry/monitoring/test_queues.py +++ b/tests/sentry/monitoring/test_queues.py @@ -51,6 +51,7 @@ def test_backpressure_unhealthy(self): with self.options( { "backpressure.monitor_queues.enable_check": True, + "backpressure.monitor_queues.check_interval_in_seconds": 0, "backpressure.monitor_queues.unhealthy_threshold": 0, "backpressure.monitor_queues.strike_threshold": 1, } @@ -67,6 +68,7 @@ def test_backpressure_healthy(self, process_profile_task): with self.options( { "backpressure.monitor_queues.enable_check": True, + "backpressure.monitor_queues.check_interval_in_seconds": 0, "backpressure.monitor_queues.unhealthy_threshold": 1000, "backpressure.monitor_queues.strike_threshold": 1, }
3d6453596fe7d7c62dfd9620f255a6a76de8942d
2024-07-03 14:13:04
Ogi
feat(metrics): limit number of specs during creation (#73627)
false
limit number of specs during creation (#73627)
feat
diff --git a/src/sentry/api/endpoints/project_metrics_extraction_rules.py b/src/sentry/api/endpoints/project_metrics_extraction_rules.py index f6ae38110a9504..4b19a6f4e2e5b3 100644 --- a/src/sentry/api/endpoints/project_metrics_extraction_rules.py +++ b/src/sentry/api/endpoints/project_metrics_extraction_rules.py @@ -1,9 +1,11 @@ +import logging + import sentry_sdk from django.db import router, transaction from rest_framework.request import Request from rest_framework.response import Response -from sentry import features +from sentry import features, options from sentry.api.api_owners import ApiOwner from sentry.api.api_publish_status import ApiPublishStatus from sentry.api.base import region_silo_endpoint @@ -21,6 +23,12 @@ ) from sentry.tasks.relay import schedule_invalidate_project_config +logger = logging.getLogger("sentry.metric_extraction_rules") + + +class MetricsExtractionRuleValidationError(ValueError): + pass + @region_silo_endpoint class ProjectMetricsExtractionRulesEndpoint(ProjectEndpoint): @@ -66,11 +74,7 @@ def get(self, request: Request, project: Project) -> Response: if not self.has_feature(project.organization, request): return Response(status=404) - try: - configs = SpanAttributeExtractionRuleConfig.objects.filter(project=project) - - except Exception as e: - return Response(status=500, data={"detail": str(e)}) + configs = SpanAttributeExtractionRuleConfig.objects.filter(project=project) # TODO(metrics): do real pagination using the database return self.paginate( @@ -104,22 +108,27 @@ def post(self, request: Request, project: Project) -> Response: configs.append( SpanAttributeExtractionRuleConfig.from_dict(obj, request.user.id, project) ) + + validate_number_of_extracted_metrics(project) + schedule_invalidate_project_config( project_id=project.id, trigger="span_attribute_extraction_configs" ) - except Exception: - sentry_sdk.capture_exception() - return Response( - status=400, + persisted_config = serialize( + configs, + request.user, + SpanAttributeExtractionRuleConfigSerializer(), ) + return Response(data=persisted_config, status=200) - persisted_config = serialize( - configs, - request.user, - SpanAttributeExtractionRuleConfigSerializer(), - ) - return Response(data=persisted_config, status=200) + except MetricsExtractionRuleValidationError as e: + logger.warning("Failed to update extraction rule", exc_info=True) + return Response(status=400, data={"detail": str(e)}) + + except Exception: + logger.exception("Failed to update extraction rule") + return Response(status=400) def put(self, request: Request, project: Project) -> Response: """PUT to modify an existing extraction rule.""" @@ -160,18 +169,38 @@ def put(self, request: Request, project: Project) -> Response: "created_by_id": request.user.id, }, ) + + validate_number_of_extracted_metrics(project) + schedule_invalidate_project_config( project_id=project.id, trigger="span_attribute_extraction_configs" ) + persisted_config = serialize( + configs, + request.user, + SpanAttributeExtractionRuleConfigSerializer(), + ) + + return Response(data=persisted_config, status=200) + + except MetricsExtractionRuleValidationError as e: + logger.warning("Failed to update extraction rule", exc_info=True) + return Response(status=400, data={"detail": str(e)}) + except Exception: - sentry_sdk.capture_exception() - return Response(status=400) + logger.exception("Failed to update extraction rule") + return Response(status=400, data={"detail": "Failed to update extraction rule."}) - persisted_config = serialize( - configs, - request.user, - SpanAttributeExtractionRuleConfigSerializer(), - ) - return Response(data=persisted_config, status=200) +def validate_number_of_extracted_metrics(project: Project): + all_configs = SpanAttributeExtractionRuleConfig.objects.filter(project=project) + + total_metrics = sum(config.number_of_extracted_metrics for config in all_configs) + + max_specs = options.get("metric_extraction.max_span_attribute_specs") + + if total_metrics > max_specs: + raise MetricsExtractionRuleValidationError( + f"Total number of rules exceeds the limit of {max_specs}." + ) diff --git a/src/sentry/sentry_metrics/models/metricsextractionrules.py b/src/sentry/sentry_metrics/models/metricsextractionrules.py index c2720957e1c210..21bfa006888f06 100644 --- a/src/sentry/sentry_metrics/models/metricsextractionrules.py +++ b/src/sentry/sentry_metrics/models/metricsextractionrules.py @@ -101,3 +101,9 @@ def generate_rules(self): rules.append(rule) return rules + + @property + def number_of_extracted_metrics(self): + metric_types = len(MetricsExtractionRule.infer_types(self.aggregates)) + + return self.conditions.count() * metric_types diff --git a/tests/sentry/api/endpoints/test_project_metrics_extraction_rules.py b/tests/sentry/api/endpoints/test_project_metrics_extraction_rules.py index 14dc7a6c1ac23d..af02e6d70a759f 100644 --- a/tests/sentry/api/endpoints/test_project_metrics_extraction_rules.py +++ b/tests/sentry/api/endpoints/test_project_metrics_extraction_rules.py @@ -5,7 +5,7 @@ from sentry.models.apitoken import ApiToken from sentry.silo.base import SiloMode from sentry.testutils.cases import APITestCase -from sentry.testutils.helpers import with_feature +from sentry.testutils.helpers import override_options, with_feature from sentry.testutils.pytest.fixtures import django_db_all from sentry.testutils.silo import assume_test_silo_mode @@ -379,12 +379,13 @@ def test_option_hides_endpoints(self): @django_db_all @with_feature("organizations:custom-metrics-extraction-rule") + @override_options({"metric_extraction.max_span_attribute_specs": 5000}) def test_get_pagination(self): json_payload = { "metricsExtractionRules": [ { "spanAttribute": f"count_clicks_{i:04d}", - "aggregates": ["count", "p50", "p75", "p95", "p99"], + "aggregates": ["count"], "unit": "none", "tags": ["tag1", "tag2", "tag3"], "conditions": [ @@ -629,3 +630,33 @@ def test_post_transaction(self): ) assert response.status_code == 200 assert len(response.data) == 0 + + @django_db_all + @with_feature("organizations:custom-metrics-extraction-rule") + @override_options({"metric_extraction.max_span_attribute_specs": 1}) + def test_specs_over_limit(self): + + new_rule = { + "metricsExtractionRules": [ + { + "spanAttribute": "my_span_attribute", + "aggregates": ["count"], + "unit": None, + "tags": ["tag1", "tag2", "tag3"], + "conditions": [ + {"id": str(uuid.uuid4()), "value": "foo:bar"}, + {"id": str(uuid.uuid4()), "value": "baz:faz"}, + ], + } + ] + } + + response = self.get_response( + self.organization.slug, + self.project.slug, + method="post", + **new_rule, + ) + + assert response.status_code == 400 + assert response.data["detail"] == "Total number of rules exceeds the limit of 1."
e13e984e97088a7f1c04908ab4aa8812cddd1b04
2024-09-18 02:15:27
Ryan Albrecht
fix(replay): Allow replay player instances to be interactable/scrollable again (#77647)
false
Allow replay player instances to be interactable/scrollable again (#77647)
fix
diff --git a/static/app/components/replays/player/replayPlayer.tsx b/static/app/components/replays/player/replayPlayer.tsx index 82dcc849b046c2..62bca2fe895691 100644 --- a/static/app/components/replays/player/replayPlayer.tsx +++ b/static/app/components/replays/player/replayPlayer.tsx @@ -95,7 +95,6 @@ export default function ReplayPlayer({offsetMs, ...props}: Props) { return ( <div {...props} - data-inspectable={props['data-inspectable']} css={[baseReplayerCss, sentryReplayerCss, props.css]} ref={mountPointRef} /> diff --git a/static/app/components/replays/player/styles.tsx b/static/app/components/replays/player/styles.tsx index 02a32c09c7ffa0..a19bb907758972 100644 --- a/static/app/components/replays/player/styles.tsx +++ b/static/app/components/replays/player/styles.tsx @@ -18,9 +18,7 @@ export const baseReplayerCss = css` .replayer-wrapper > iframe { border: none; background: white; - } - &[data-inspectable='true'] .replayer-wrapper > iframe { /* Set pointer-events to make it easier to right-click & inspect */ pointer-events: initial !important; } diff --git a/static/app/components/replays/replayPlayer.tsx b/static/app/components/replays/replayPlayer.tsx index 92a911caa066c6..c76fb517addf64 100644 --- a/static/app/components/replays/replayPlayer.tsx +++ b/static/app/components/replays/replayPlayer.tsx @@ -182,13 +182,10 @@ const PositionedLoadingIndicator = styled(LoadingIndicator)` position: absolute; `; -// Base styles, to make the Replayer instance work -const PlayerRoot = styled(BasePlayerRoot)` +const SentryPlayerRoot = styled(BasePlayerRoot)` + /* Base styles, to make the Replayer instance work */ ${baseReplayerCss} -`; - -// Sentry-specific styles for the player. -const SentryPlayerRoot = styled(PlayerRoot)` + /* Sentry-specific styles for the player */ ${p => sentryReplayerCss(p.theme)} `;
df1788e165e4a80a7d7d0bc082750109fb55b183
2023-11-29 05:25:24
Lyn Nagara
ref: Remove deprecated consumer entrypoints (#60721)
false
Remove deprecated consumer entrypoints (#60721)
ref
diff --git a/src/sentry/profiles/consumers/__init__.py b/src/sentry/profiles/consumers/__init__.py index f7e9bd84eb7f8f..e69de29bb2d1d6 100644 --- a/src/sentry/profiles/consumers/__init__.py +++ b/src/sentry/profiles/consumers/__init__.py @@ -1,55 +0,0 @@ -from __future__ import annotations - -from typing import Any, MutableMapping - -from arroyo import Topic -from arroyo.backends.kafka.configuration import build_kafka_consumer_configuration -from arroyo.backends.kafka.consumer import KafkaConsumer, KafkaPayload -from arroyo.commit import ONCE_PER_SECOND -from arroyo.processing.processor import StreamProcessor - -from sentry.profiles.consumers.process.factory import ProcessProfileStrategyFactory -from sentry.utils import kafka_config - - -def get_profiles_process_consumer( - topic: str, - group_id: str, - auto_offset_reset: str, - strict_offset_reset: bool, - force_topic: str | None, - force_cluster: str | None, -) -> StreamProcessor[KafkaPayload]: - topic = force_topic or topic - consumer_config = get_config( - topic, - group_id, - auto_offset_reset=auto_offset_reset, - strict_offset_reset=strict_offset_reset, - force_cluster=force_cluster, - ) - consumer = KafkaConsumer(consumer_config) - return StreamProcessor( - consumer=consumer, - topic=Topic(topic), - processor_factory=ProcessProfileStrategyFactory(), - commit_policy=ONCE_PER_SECOND, - ) - - -def get_config( - topic: str, - group_id: str, - auto_offset_reset: str, - strict_offset_reset: bool, - force_cluster: str | None, -) -> MutableMapping[str, Any]: - cluster_name: str = force_cluster or kafka_config.get_topic_definition(topic)["cluster"] - return build_kafka_consumer_configuration( - kafka_config.get_kafka_consumer_cluster_options( - cluster_name, - ), - group_id=group_id, - auto_offset_reset=auto_offset_reset, - strict_offset_reset=strict_offset_reset, - ) diff --git a/src/sentry/runner/commands/run.py b/src/sentry/runner/commands/run.py index a620ca6b08a5fa..7024c88ec863cb 100644 --- a/src/sentry/runner/commands/run.py +++ b/src/sentry/runner/commands/run.py @@ -505,57 +505,6 @@ def occurrences_ingest_consumer(**options): run_processor_with_signals(consumer) [email protected]("ingest-metrics-parallel-consumer") -@log_options() -@kafka_options("ingest-metrics-consumer", allow_force_cluster=False) -@strict_offset_reset_option() -@configuration [email protected]( - "--processes", - default=1, - type=int, -) [email protected]("--input-block-size", type=int, default=DEFAULT_BLOCK_SIZE) [email protected]("--output-block-size", type=int, default=DEFAULT_BLOCK_SIZE) [email protected]("--ingest-profile", required=True) [email protected]("--indexer-db", default="postgres") [email protected]("max_msg_batch_size", "--max-msg-batch-size", type=int, default=50) [email protected]("max_msg_batch_time", "--max-msg-batch-time-ms", type=int, default=10000) [email protected]("max_parallel_batch_size", "--max-parallel-batch-size", type=int, default=50) [email protected]("max_parallel_batch_time", "--max-parallel-batch-time-ms", type=int, default=10000) [email protected]("--group-instance-id", type=str, default=None) -def metrics_parallel_consumer(**options): - from sentry.sentry_metrics.consumers.indexer.parallel import get_parallel_metrics_consumer - - streamer = get_parallel_metrics_consumer(**options) - - from arroyo import configure_metrics - - from sentry.utils.arroyo import MetricsWrapper - from sentry.utils.metrics import backend - - metrics_wrapper = MetricsWrapper(backend, name="sentry_metrics.indexer") - configure_metrics(metrics_wrapper) - - run_processor_with_signals(streamer) - - [email protected]("ingest-profiles") -@log_options() [email protected]("--topic", default="profiles", help="Topic to get profiles data from.") -@kafka_options("ingest-profiles") -@strict_offset_reset_option() -@configuration -def profiles_consumer(**options): - from sentry.consumers import print_deprecation_warning - - print_deprecation_warning("ingest-profiles", options["group_id"]) - from sentry.profiles.consumers import get_profiles_process_consumer - - consumer = get_profiles_process_consumer(**options) - run_processor_with_signals(consumer) - - @run.command("consumer") @log_options() @click.argument( @@ -735,28 +684,6 @@ def monitors_consumer(**options): run_processor_with_signals(consumer) [email protected]("indexer-last-seen-updater") -@log_options() -@configuration -@kafka_options( - "indexer-last-seen-updater-consumer", - allow_force_cluster=False, - include_batching_options=True, - default_max_batch_size=100, -) -@strict_offset_reset_option() [email protected]("--ingest-profile", required=True) [email protected]("--indexer-db", default="postgres") -def last_seen_updater(**options): - from sentry.sentry_metrics.consumers.last_seen_updater import get_last_seen_updater - from sentry.utils.metrics import global_tags - - config, consumer = get_last_seen_updater(**options) - - with global_tags(_all_threads=True, pipeline=config.internal_metrics_tag): - run_processor_with_signals(consumer) - - @run.command("backpressure-monitor") @log_options() @configuration diff --git a/src/sentry/sentry_metrics/consumers/indexer/common.py b/src/sentry/sentry_metrics/consumers/indexer/common.py index 211eb39d41a488..a18f10139c8f9f 100644 --- a/src/sentry/sentry_metrics/consumers/indexer/common.py +++ b/src/sentry/sentry_metrics/consumers/indexer/common.py @@ -1,11 +1,10 @@ import logging import time from dataclasses import dataclass -from typing import Any, List, Mapping, MutableMapping, MutableSequence, NamedTuple, Optional, Union +from typing import List, Mapping, MutableSequence, NamedTuple, Optional, Union from arroyo import Partition from arroyo.backends.kafka import KafkaPayload -from arroyo.backends.kafka.configuration import build_kafka_consumer_configuration from arroyo.dlq import InvalidMessage from arroyo.processing.strategies import MessageRejected from arroyo.processing.strategies import ProcessingStrategy @@ -14,7 +13,7 @@ from sentry.sentry_metrics.consumers.indexer.routing_producer import RoutingPayload from sentry.sentry_metrics.use_case_id_registry import UseCaseID -from sentry.utils import kafka_config, metrics +from sentry.utils import metrics class BrokerMeta(NamedTuple): @@ -36,29 +35,6 @@ class IndexerOutputMessageBatch: cogs_data: Mapping[UseCaseID, int] -def get_config( - topic: str, - group_id: str, - auto_offset_reset: str, - strict_offset_reset: bool, - group_instance_id: Optional[str] = None, -) -> MutableMapping[Any, Any]: - cluster_name: str = kafka_config.get_topic_definition(topic)["cluster"] - consumer_config: MutableMapping[str, Any] = build_kafka_consumer_configuration( - kafka_config.get_kafka_consumer_cluster_options( - cluster_name, - ), - group_id=group_id, - auto_offset_reset=auto_offset_reset, - strict_offset_reset=strict_offset_reset, - queued_max_messages_kbytes=DEFAULT_QUEUED_MAX_MESSAGE_KBYTES, - queued_min_messages=DEFAULT_QUEUED_MIN_MESSAGES, - ) - if group_instance_id is not None: - consumer_config["group.instance.id"] = str(group_instance_id) - return consumer_config - - class MetricsBatchBuilder: """ Batches up individual messages - type: Message[KafkaPayload] - into a diff --git a/src/sentry/sentry_metrics/consumers/indexer/parallel.py b/src/sentry/sentry_metrics/consumers/indexer/parallel.py index 403eb70fecf88b..39d57683fc5797 100644 --- a/src/sentry/sentry_metrics/consumers/indexer/parallel.py +++ b/src/sentry/sentry_metrics/consumers/indexer/parallel.py @@ -5,25 +5,19 @@ from collections import deque from typing import Any, Deque, Mapping, Optional, Union, cast -from arroyo.backends.kafka import KafkaConsumer, KafkaPayload -from arroyo.commit import ONCE_PER_SECOND +from arroyo.backends.kafka import KafkaPayload from arroyo.dlq import InvalidMessage -from arroyo.processing import StreamProcessor from arroyo.processing.strategies import MessageRejected from arroyo.processing.strategies import ProcessingStrategy from arroyo.processing.strategies import ProcessingStrategy as ProcessingStep from arroyo.processing.strategies import ProcessingStrategyFactory -from arroyo.types import Commit, FilteredPayload, Message, Partition, Topic +from arroyo.types import Commit, FilteredPayload, Message, Partition from sentry.sentry_metrics.configuration import ( MetricsIngestConfiguration, initialize_subprocess_state, ) -from sentry.sentry_metrics.consumers.indexer.common import ( - BatchMessages, - IndexerOutputMessageBatch, - get_config, -) +from sentry.sentry_metrics.consumers.indexer.common import BatchMessages, IndexerOutputMessageBatch from sentry.sentry_metrics.consumers.indexer.multiprocess import SimpleProduceStep from sentry.sentry_metrics.consumers.indexer.processing import MessageProcessor from sentry.sentry_metrics.consumers.indexer.routing_producer import ( @@ -33,9 +27,6 @@ from sentry.sentry_metrics.consumers.indexer.slicing_router import SlicingRouter from sentry.utils.arroyo import RunTaskWithMultiprocessing -# from usageaccountant import UsageAccumulator, UsageUnit - - logger = logging.getLogger(__name__) @@ -205,49 +196,3 @@ def get_metrics_producer_strategy( commit_function=commit, output_topic=config.output_topic, ) - - -def get_parallel_metrics_consumer( - max_msg_batch_size: int, - max_msg_batch_time: float, - max_parallel_batch_size: int, - max_parallel_batch_time: float, - processes: int, - input_block_size: int, - output_block_size: int, - group_id: str, - auto_offset_reset: str, - strict_offset_reset: bool, - ingest_profile: str, - indexer_db: str, - group_instance_id: Optional[str], -) -> StreamProcessor[KafkaPayload]: - processing_factory = MetricsConsumerStrategyFactory( - max_msg_batch_size=max_msg_batch_size, - max_msg_batch_time=max_msg_batch_time, - max_parallel_batch_size=max_parallel_batch_size, - max_parallel_batch_time=max_parallel_batch_time, - processes=processes, - input_block_size=input_block_size, - output_block_size=output_block_size, - ingest_profile=ingest_profile, - indexer_db=indexer_db, - ) - - return StreamProcessor( - KafkaConsumer( - get_config( - processing_factory.config.input_topic, - group_id, - auto_offset_reset=auto_offset_reset, - strict_offset_reset=strict_offset_reset, - group_instance_id=group_instance_id, - ) - ), - Topic(processing_factory.config.input_topic), - processing_factory, - ONCE_PER_SECOND, - # We drop any in flight messages in processing step prior to produce. - # The SimpleProduceStep has a hardcoded join timeout of 5 seconds. - join_timeout=0.0, - ) diff --git a/src/sentry/sentry_metrics/consumers/last_seen_updater.py b/src/sentry/sentry_metrics/consumers/last_seen_updater.py index a9b392b1a79551..521da8bd88ebc5 100644 --- a/src/sentry/sentry_metrics/consumers/last_seen_updater.py +++ b/src/sentry/sentry_metrics/consumers/last_seen_updater.py @@ -2,22 +2,19 @@ import functools from abc import abstractmethod from datetime import timedelta -from typing import Any, Callable, Mapping, Optional, Set, Tuple +from typing import Any, Callable, Mapping, Optional, Set import rapidjson -from arroyo.backends.kafka import KafkaConsumer, KafkaPayload -from arroyo.commit import IMMEDIATE, ONCE_PER_SECOND -from arroyo.processing import StreamProcessor +from arroyo.backends.kafka import KafkaPayload +from arroyo.commit import ONCE_PER_SECOND from arroyo.processing.strategies import ProcessingStrategy, ProcessingStrategyFactory from arroyo.processing.strategies.commit import CommitOffsets from arroyo.processing.strategies.filter import FilterStep from arroyo.processing.strategies.reduce import Reduce from arroyo.processing.strategies.run_task import RunTask -from arroyo.types import BaseValue, Commit, Message, Partition, Topic +from arroyo.types import BaseValue, Commit, Message, Partition from django.utils import timezone -from sentry.sentry_metrics.configuration import MetricsIngestConfiguration -from sentry.sentry_metrics.consumers.indexer.common import get_config from sentry.sentry_metrics.consumers.indexer.multiprocess import logger from sentry.sentry_metrics.indexer.base import FetchType from sentry.sentry_metrics.indexer.postgres.models import TABLE_MAPPING, IndexerTable @@ -157,41 +154,3 @@ def do_update(message: Message[Set[int]]) -> None: transform_step = RunTask(retrieve_db_read_keys, collect_step) return FilterStep(self.__should_accept, transform_step, commit_policy=ONCE_PER_SECOND) - - -def get_last_seen_updater( - group_id: str, - max_batch_size: int, - max_batch_time: float, - auto_offset_reset: str, - strict_offset_reset: bool, - ingest_profile: str, - indexer_db: str, -) -> Tuple[MetricsIngestConfiguration, StreamProcessor[KafkaPayload]]: - """ - The last_seen updater uses output from the metrics indexer to update the - last_seen field in the sentry_stringindexer and sentry_perfstringindexer database - tables. This enables us to do deletions of tag keys/values that haven't been - accessed over the past N days (generally, 90). - """ - - processing_factory = LastSeenUpdaterStrategyFactory( - ingest_profile=ingest_profile, - indexer_db=indexer_db, - max_batch_size=max_batch_size, - max_batch_time=max_batch_time, - ) - - return processing_factory.config, StreamProcessor( - KafkaConsumer( - get_config( - processing_factory.config.output_topic, - group_id, - auto_offset_reset=auto_offset_reset, - strict_offset_reset=strict_offset_reset, - ) - ), - Topic(processing_factory.config.output_topic), - processing_factory, - IMMEDIATE, - )
fe56965b715278969e392464a91a1251abff2130
2022-11-01 23:27:14
Malachi Willey
feat(js): Add useSyncedLocalStorageState hook (#40694)
false
Add useSyncedLocalStorageState hook (#40694)
feat
diff --git a/static/app/utils/useSyncedLocalStorageState.spec.tsx b/static/app/utils/useSyncedLocalStorageState.spec.tsx new file mode 100644 index 00000000000000..cd1e29b9f50d6c --- /dev/null +++ b/static/app/utils/useSyncedLocalStorageState.spec.tsx @@ -0,0 +1,51 @@ +import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary'; + +import localStorageWrapper from 'sentry/utils/localStorage'; +import {useSyncedLocalStorageState} from 'sentry/utils/useSyncedLocalStorageState'; + +describe('useSyncedLocalStorageState', function () { + beforeEach(() => { + localStorageWrapper.clear(); + }); + + const Toggle = () => { + const [value, setValue] = useSyncedLocalStorageState<boolean>('key', false); + + return <button onClick={() => setValue(!value)}>{value ? 'On' : 'Off'}</button>; + }; + + const Text = () => { + const [value] = useSyncedLocalStorageState<boolean>('key', false); + + return <div>{value ? 'Value is on' : 'Value is off'}</div>; + }; + + it('responds to changes in multiple components', async function () { + localStorageWrapper.setItem('key', 'true'); + + const TestComponent = () => { + return ( + <div> + <Toggle /> + <Text /> + </div> + ); + }; + + render(<TestComponent />); + + // Both components should be 'On' initially due to setItem above + expect(screen.getByRole('button', {name: 'On'})).toBeInTheDocument(); + expect(screen.getByText('Value is on')).toBeInTheDocument(); + + // After clicking the button, they both should be 'Off' + userEvent.click(screen.getByRole('button')); + expect(screen.getByRole('button', {name: 'Off'})).toBeInTheDocument(); + expect(screen.getByText('Value is off')).toBeInTheDocument(); + + // localStorage should eventually have the value of false + await waitFor(() => { + expect(localStorageWrapper.getItem('key')).toBe('false'); + }); + }); +}); diff --git a/static/app/utils/useSyncedLocalStorageState.tsx b/static/app/utils/useSyncedLocalStorageState.tsx new file mode 100644 index 00000000000000..6b6b890369b188 --- /dev/null +++ b/static/app/utils/useSyncedLocalStorageState.tsx @@ -0,0 +1,62 @@ +import {useCallback, useEffect} from 'react'; + +import {useLocalStorageState} from 'sentry/utils/useLocalStorageState'; + +type SyncedLocalStorageEvent<S> = CustomEvent<{key: string; value: S}>; + +const SYNCED_STORAGE_EVENT = 'synced-local-storage'; + +function isCustomEvent(event: Event): event is CustomEvent { + return 'detail' in event; +} + +function isSyncedLocalStorageEvent<S>( + event: Event, + key: string +): event is SyncedLocalStorageEvent<S> { + return ( + isCustomEvent(event) && + event.type === SYNCED_STORAGE_EVENT && + event.detail.key === key + ); +} + +/** + * Same as `useLocalStorageState`, but notifies and reacts to state changes. + * Use this you want to access local storage state from multiple components + * on the same page. + */ +export function useSyncedLocalStorageState<S>( + key: string, + initialState: S | ((value?: unknown, rawValue?: unknown) => S) +): [S, (value: S) => void] { + const [value, setValue] = useLocalStorageState(key, initialState); + + const setValueAndNotify = useCallback( + newValue => { + setValue(newValue); + + // We use a custom event to notify all consumers of this hook + window.dispatchEvent( + new CustomEvent(SYNCED_STORAGE_EVENT, {detail: {key, value: newValue}}) + ); + }, + [key, setValue] + ); + + useEffect(() => { + const handleNewSyncedLocalStorageEvent = (event: Event) => { + if (isSyncedLocalStorageEvent<S>(event, key)) { + setValue(event.detail.value); + } + }; + + window.addEventListener(SYNCED_STORAGE_EVENT, handleNewSyncedLocalStorageEvent); + + return () => { + window.removeEventListener(SYNCED_STORAGE_EVENT, handleNewSyncedLocalStorageEvent); + }; + }, [key, setValue, value]); + + return [value, setValueAndNotify]; +}
855563342c602c99c063e7c1f78209432f5146cd
2018-08-01 00:33:56
Matt Robenolt
fix: convert bin/lint to argparse
false
convert bin/lint to argparse
fix
diff --git a/bin/lint b/bin/lint index ac95274e7bee51..2afa70e7a3241c 100755 --- a/bin/lint +++ b/bin/lint @@ -1,7 +1,6 @@ #!/usr/bin/env python from __future__ import absolute_import -import click import os import sys @@ -9,12 +8,6 @@ import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, 'src')) [email protected]() [email protected]('files', nargs=-1) [email protected]('--js', default=None, is_flag=True) [email protected]('--python', default=None, is_flag=True) [email protected]('--format', default=False, is_flag=True) [email protected]('--parseable', default=False, is_flag=True) def run(files, js, python, format, parseable): from sentry.lint import engine @@ -29,10 +22,16 @@ def run(files, js, python, format, parseable): if not files: files = None - results = engine.run(files, js=js, py=python, format=format, parseable=parseable) - if results: - raise click.Abort + return engine.run(files, js=js, py=python, format=format, parseable=parseable) if __name__ == '__main__': - run() + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument('files', nargs='*') + parser.add_argument('--js', default=None, action='store_true') + parser.add_argument('--python', default=None, action='store_true') + parser.add_argument('--format', action='store_true') + parser.add_argument('--parseable', action='store_true') + sys.exit(run(**vars(parser.parse_args())))
0499229de5e6b1a6a2cf86faacd5fdf87b66eef6
2021-05-05 00:44:44
k-fish
fix(perf): Fix ops breakdown span duration header alignment (#25861)
false
Fix ops breakdown span duration header alignment (#25861)
fix
diff --git a/static/app/components/discover/transactionsList.tsx b/static/app/components/discover/transactionsList.tsx index 9fcf3d05781656..cb8e80303f78e5 100644 --- a/static/app/components/discover/transactionsList.tsx +++ b/static/app/components/discover/transactionsList.tsx @@ -19,7 +19,12 @@ import {Organization} from 'app/types'; import DiscoverQuery, {TableData, TableDataRow} from 'app/utils/discover/discoverQuery'; import EventView, {MetaType} from 'app/utils/discover/eventView'; import {getFieldRenderer} from 'app/utils/discover/fieldRenderers'; -import {fieldAlignment, getAggregateAlias, Sort} from 'app/utils/discover/fields'; +import { + Alignments, + fieldAlignment, + getAggregateAlias, + Sort, +} from 'app/utils/discover/fields'; import {generateEventSlug} from 'app/utils/discover/urls'; import {getDuration} from 'app/utils/formatters'; import BaselineQuery, { @@ -32,6 +37,7 @@ import CellAction, {Actions} from 'app/views/eventsV2/table/cellAction'; import {TableColumn} from 'app/views/eventsV2/table/types'; import {decodeColumnOrder} from 'app/views/eventsV2/utils'; import {GridCell, GridCellNumber} from 'app/views/performance/styles'; +import {spanOperationBreakdownSingleColumns} from 'app/views/performance/transactionSummary/filter'; import { TrendChangeType, TrendsDataEvents, @@ -410,7 +416,13 @@ class TransactionsTable extends React.PureComponent<TableProps> { const headers = tableTitles.map((title, index) => { const column = columnOrder[index]; - const align = fieldAlignment(column.name, column.type, tableMeta); + + const isIndividualSpanColumn = !!spanOperationBreakdownSingleColumns.find( + c => c === column.name + ); + const align: Alignments = isIndividualSpanColumn + ? 'left' + : fieldAlignment(column.name, column.type, tableMeta); if (column.key === 'span_ops_breakdown.relative') { return ( diff --git a/static/app/views/performance/transactionSummary/filter.tsx b/static/app/views/performance/transactionSummary/filter.tsx index d8e62117591ca5..9f8ae680290275 100644 --- a/static/app/views/performance/transactionSummary/filter.tsx +++ b/static/app/views/performance/transactionSummary/filter.tsx @@ -33,6 +33,8 @@ const OPTIONS: SpanOperationBreakdownFilter[] = [ SpanOperationBreakdownFilter.Resource, ]; +export const spanOperationBreakdownSingleColumns = OPTIONS.map(o => `spans.${o}`); + type Props = { organization: OrganizationSummary; currentFilter: SpanOperationBreakdownFilter;
7acb006023c3affec838ec85481365accf1aec0b
2024-03-21 03:35:44
Pierre Massat
feat(profiles): Emit profile duration outcomes (#67380)
false
Emit profile duration outcomes (#67380)
feat
diff --git a/src/sentry/profiles/task.py b/src/sentry/profiles/task.py index 86c53714c608a8..618580d68e8e61 100644 --- a/src/sentry/profiles/task.py +++ b/src/sentry/profiles/task.py @@ -156,6 +156,10 @@ def process_profile_task( return with metrics.timer("process_profile.track_outcome.accepted"): + try: + _track_duration_outcome(profile=profile, project=project) + except Exception as e: + sentry_sdk.capture_exception(e) _track_outcome(profile=profile, project=project, outcome=Outcome.ACCEPTED) @@ -771,9 +775,9 @@ def _deobfuscate(profile: Profile, project: Project) -> None: method["class_name"] = new_frame.class_name method["name"] = new_frame.method method["data"] = { - "deobfuscation_status": "deobfuscated" - if method.get("signature", None) - else "partial" + "deobfuscation_status": ( + "deobfuscated" if method.get("signature", None) else "partial" + ) } if new_frame.file: @@ -794,9 +798,9 @@ def _deobfuscate(profile: Profile, project: Project) -> None: "class_name": new_frame.class_name, "data": {"deobfuscation_status": "deobfuscated"}, "name": new_frame.method, - "source_file": method["source_file"] - if bottom_class == new_frame.class_name - else "", + "source_file": ( + method["source_file"] if bottom_class == new_frame.class_name else "" + ), "source_line": new_frame.line, } for new_frame in reversed(mapped) @@ -922,3 +926,65 @@ def get_metrics_dsn(project_id: int) -> str: project_id=project_id, use_case=UseCase.PROFILING.value ) return project_key.get_dsn(public=True) + + [email protected]("process_profile.track_outcome") +def _track_duration_outcome( + profile: Profile, + project: Project, +) -> None: + duration_ms = _calculate_profile_duration_ms(profile) + if duration_ms <= 0: + return + track_outcome( + org_id=project.organization_id, + project_id=project.id, + key_id=None, + outcome=Outcome.ACCEPTED, + timestamp=datetime.now(timezone.utc), + category=DataCategory.PROFILE_DURATION, + quantity=duration_ms, + ) + + +def _calculate_profile_duration_ms(profile: Profile) -> int: + version = profile.get("version") + if version: + if version == "1": + return _calculate_duration_for_sample_format_v1(profile) + elif version == "2": + return _calculate_duration_for_sample_format_v2(profile) + else: + platform = profile["platform"] + if platform == "android": + return _calculate_duration_for_android_format(profile) + return 0 + + +def _calculate_duration_for_sample_format_v1(profile: Profile) -> int: + start_ns = int(profile["transaction"].get("relative_start_ns", 0)) + end_ns = int(profile["transaction"].get("relative_end_ns", 0)) + duration_ns = end_ns - start_ns + # try another method to determine the duration in case it's negative or 0. + if duration_ns <= 0: + samples = sorted(profile["profile"]["samples"], key=lambda s: s["elapsed_since_start_ns"]) + if len(samples) < 2: + return 0 + first, last = samples[0], samples[-1] + first_ns = int(first["elapsed_since_start_ns"]) + last_ns = int(last["elapsed_since_start_ns"]) + duration_ns = last_ns - first_ns + duration_ms = int(duration_ns * 1e-6) + return min(duration_ms, 30000) + + +def _calculate_duration_for_sample_format_v2(profile: Profile) -> int: + samples = sorted(profile["profile"]["samples"], key=lambda s: s["timestamp"]) + if len(samples) < 2: + return 0 + first, last = samples[0], samples[-1] + return int((last["timestamp"] - first["timestamp"]) * 1e3) + + +def _calculate_duration_for_android_format(profile: Profile) -> int: + return int(profile["duration_ns"] * 1e-6) diff --git a/tests/sentry/profiles/test_task.py b/tests/sentry/profiles/test_task.py index 112584f2a977bd..e0a40a331ce001 100644 --- a/tests/sentry/profiles/test_task.py +++ b/tests/sentry/profiles/test_task.py @@ -8,7 +8,12 @@ from sentry.lang.javascript.processing import _handles_frame as is_valid_javascript_frame from sentry.models.project import Project -from sentry.profiles.task import _deobfuscate, _normalize, _process_symbolicator_results_for_sample +from sentry.profiles.task import ( + _calculate_profile_duration_ms, + _deobfuscate, + _normalize, + _process_symbolicator_results_for_sample, +) from sentry.testutils.factories import Factories, get_fixture_path from sentry.testutils.pytest.fixtures import django_db_all from sentry.utils import json @@ -116,6 +121,156 @@ def android_profile(): return load_profile("valid_android_profile.json") [email protected] +def sample_v1_profile(): + return json.loads( + """{ + "event_id": "41fed0925670468bb0457f61a74688ec", + "version": "1", + "os": { + "name": "iOS", + "version": "16.0", + "build_number": "19H253" + }, + "device": { + "architecture": "arm64e", + "is_emulator": false, + "locale": "en_US", + "manufacturer": "Apple", + "model": "iPhone14,3" + }, + "timestamp": "2022-09-01T09:45:00.000Z", + "profile": { + "samples": [ + { + "stack_id": 0, + "thread_id": "1", + "queue_address": "0x0000000102adc700", + "elapsed_since_start_ns": "10500500" + }, + { + "stack_id": 1, + "thread_id": "1", + "queue_address": "0x0000000102adc700", + "elapsed_since_start_ns": "20500500" + }, + { + "stack_id": 0, + "thread_id": "1", + "queue_address": "0x0000000102adc700", + "elapsed_since_start_ns": "30500500" + }, + { + "stack_id": 1, + "thread_id": "1", + "queue_address": "0x0000000102adc700", + "elapsed_since_start_ns": "35500500" + } + ], + "stacks": [[0], [1]], + "frames": [ + {"instruction_addr": "0xa722447ffffffffc"}, + {"instruction_addr": "0x442e4b81f5031e58"} + ], + "thread_metadata": { + "1": {"priority": 31}, + "2": {} + }, + "queue_metadata": { + "0x0000000102adc700": {"label": "com.apple.main-thread"}, + "0x000000016d8fb180": {"label": "com.apple.network.connections"} + } + }, + "release": "0.1 (199)", + "platform": "cocoa", + "debug_meta": { + "images": [ + { + "debug_id": "32420279-25E2-34E6-8BC7-8A006A8F2425", + "image_addr": "0x000000010258c000", + "code_file": "/private/var/containers/Bundle/Application/C3511752-DD67-4FE8-9DA2-ACE18ADFAA61/TrendingMovies.app/TrendingMovies", + "type": "macho", + "image_size": 1720320, + "image_vmaddr": "0x0000000100000000" + } + ] + }, + "transaction": { + "name": "example_ios_movies_sources.MoviesViewController", + "trace_id": "4b25bc58f14243d8b208d1e22a054164", + "id": "30976f2ddbe04ac9b6bffe6e35d4710c", + "active_thread_id": "259", + "relative_start_ns": "500500", + "relative_end_ns": "50500500" + } +}""" + ) + + [email protected] +def sample_v1_profile_without_transaction_timestamps(sample_v1_profile): + for key in {"relative_start_ns", "relative_end_ns"}: + del sample_v1_profile["transaction"][key] + return sample_v1_profile + + [email protected] +def sample_v2_profile(): + return json.loads( + """{ + "event_id": "41fed0925670468bb0457f61a74688ec", + "version": "2", + "profile": { + "samples": [ + { + "stack_id": 0, + "thread_id": "1", + "timestamp": 1710958503.629 + }, + { + "stack_id": 1, + "thread_id": "1", + "timestamp": 1710958504.629 + }, + { + "stack_id": 0, + "thread_id": "1", + "timestamp": 1710958505.629 + }, + { + "stack_id": 1, + "thread_id": "1", + "timestamp": 1710958506.629 + } + ], + "stacks": [[0], [1]], + "frames": [ + {"instruction_addr": "0xa722447ffffffffc"}, + {"instruction_addr": "0x442e4b81f5031e58"} + ], + "thread_metadata": { + "1": {"priority": 31}, + "2": {} + } + }, + "release": "0.1 (199)", + "platform": "cocoa", + "debug_meta": { + "images": [ + { + "debug_id": "32420279-25E2-34E6-8BC7-8A006A8F2425", + "image_addr": "0x000000010258c000", + "code_file": "/private/var/containers/Bundle/Application/C3511752-DD67-4FE8-9DA2-ACE18ADFAA61/TrendingMovies.app/TrendingMovies", + "type": "macho", + "image_size": 1720320, + "image_vmaddr": "0x0000000100000000" + } + ] + } +}""" + ) + + @pytest.fixture def proguard_file_basic(project): return load_proguard(project, PROGUARD_UUID, PROGUARD_SOURCE) @@ -460,3 +615,17 @@ def test_decode_signature(project, android_profile): assert frames[0]["signature"] == "()" assert frames[1]["signature"] == "(): boolean" + + +@django_db_all [email protected]( + "profile, duration_ms", + [ + ("sample_v1_profile", 50), + ("sample_v2_profile", 3000), + ("android_profile", 2020), + ("sample_v1_profile_without_transaction_timestamps", 25), + ], +) +def test_calculate_profile_duration(profile, duration_ms, request): + assert _calculate_profile_duration_ms(request.getfixturevalue(profile)) == duration_ms
cd366b73095db67e38c8afc9d1b5988607c5a87b
2023-11-08 21:12:52
Ogi
fix(ddm): enhance mri parsing (#59611)
false
enhance mri parsing (#59611)
fix
diff --git a/static/app/utils/metrics.spec.tsx b/static/app/utils/metrics.spec.tsx index c99a909dc5747e..54efa713a834d5 100644 --- a/static/app/utils/metrics.spec.tsx +++ b/static/app/utils/metrics.spec.tsx @@ -1,6 +1,11 @@ import {formatMetricsUsingUnitAndOp, parseMRI} from 'sentry/utils/metrics'; describe('parseMRI', () => { + it('should handle falsy values', () => { + expect(parseMRI('')).toEqual(null); + expect(parseMRI(undefined)).toEqual(null); + }); + it('should parse MRI with name, unit, and mri (custom use case)', () => { const mri = 'd:custom/sentry.events.symbolicator.query_task@second'; const expectedResult = { @@ -13,11 +18,11 @@ describe('parseMRI', () => { }); it('should parse MRI with name, unit, and cleanMRI (transactions use case)', () => { - const mri = 'd:transactions/sentry.events.symbolicator.query_task@milisecond'; + const mri = 'g:transactions/gauge@milisecond'; const expectedResult = { - name: 'sentry.events.symbolicator.query_task', + name: 'gauge', unit: 'milisecond', - mri: 'd:transactions/sentry.events.symbolicator.query_task@milisecond', + mri: 'g:transactions/gauge@milisecond', useCase: 'transactions', }; expect(parseMRI(mri)).toEqual(expectedResult); @@ -35,16 +40,28 @@ describe('parseMRI', () => { }); it('should extract MRI from nested operations', () => { - const mri = 'd:custom/sentry.events.symbolicator.query_task@second'; + const mri = 'd:custom/foobar@none'; const expectedResult = { - name: 'sentry.events.symbolicator.query_task', - unit: 'second', - mri: 'd:custom/sentry.events.symbolicator.query_task@second', + name: 'foobar', + unit: 'none', + mri: 'd:custom/foobar@none', useCase: 'custom', }; expect(parseMRI(`sum(avg(${mri}))`)).toEqual(expectedResult); }); + + it('should extract MRI from nested operations (set)', () => { + const mri = 's:custom/foobar@none'; + + const expectedResult = { + name: 'foobar', + unit: 'none', + mri: 's:custom/foobar@none', + useCase: 'custom', + }; + expect(parseMRI(`count_unique(${mri})`)).toEqual(expectedResult); + }); }); describe('formatMetricsUsingUnitAndOp', () => { diff --git a/static/app/utils/metrics.tsx b/static/app/utils/metrics.tsx index 76b2db348e4268..fdb40b14028e1c 100644 --- a/static/app/utils/metrics.tsx +++ b/static/app/utils/metrics.tsx @@ -68,7 +68,7 @@ type MetricTag = { export function useMetricsTags(mri: string, projects: PageFilters['projects']) { const {slug} = useOrganization(); - const {useCase} = parseMRI(mri); + const useCase = getUseCaseFromMRI(mri); return useApiQuery<MetricTag[]>( [ `/organizations/${slug}/metrics/tags/`, @@ -86,7 +86,7 @@ export function useMetricsTagValues( projects: PageFilters['projects'] ) { const {slug} = useOrganization(); - const {useCase} = parseMRI(mri); + const useCase = getUseCaseFromMRI(mri); return useApiQuery<MetricTag[]>( [ `/organizations/${slug}/metrics/tags/${tag}/`, @@ -136,7 +136,7 @@ export function useMetricsData({ groupBy, }: MetricsQuery) { const {slug, features} = useOrganization(); - const {useCase} = parseMRI(mri); + const useCase = getUseCaseFromMRI(mri); const field = op ? `${op}(${mri})` : mri; const interval = getMetricsInterval(datetime, mri); @@ -248,7 +248,7 @@ function getMetricsInterval(dateTimeObj: DateTimeObject, mri: string) { } const diffInMinutes = getDiffInMinutes(dateTimeObj); - const {useCase} = parseMRI(mri); + const useCase = getUseCaseFromMRI(mri); if (diffInMinutes <= 60 && useCase === 'custom') { return '10s'; @@ -280,8 +280,12 @@ export function getReadableMetricType(type) { const noUnit = 'none'; -export function parseMRI(mri: string) { - const cleanMRI = mri.match(/d:[\w/.@]+/)?.[0] ?? mri; +export function parseMRI(mri?: string) { + if (!mri) { + return null; + } + + const cleanMRI = mri.match(/[cdegs]:[\w/.@]+/)?.[0] ?? mri; const name = cleanMRI.match(/^[a-z]:\w+\/(.+)(?:@\w+)$/)?.[1] ?? mri; const unit = cleanMRI.split('@').pop() ?? noUnit; @@ -296,7 +300,7 @@ export function parseMRI(mri: string) { }; } -function getUseCaseFromMRI(mri?: string): UseCase { +export function getUseCaseFromMRI(mri?: string): UseCase { if (mri?.includes('custom/')) { return 'custom'; } diff --git a/static/app/views/ddm/queryBuilder.tsx b/static/app/views/ddm/queryBuilder.tsx index 028461753e8bbd..016aff47a0f4fc 100644 --- a/static/app/views/ddm/queryBuilder.tsx +++ b/static/app/views/ddm/queryBuilder.tsx @@ -12,10 +12,10 @@ import {MetricsTag, SavedSearchType, TagCollection} from 'sentry/types'; import { defaultMetricDisplayType, getReadableMetricType, + getUseCaseFromMRI, isAllowedOp, MetricDisplayType, MetricsQuery, - parseMRI, useMetricsMeta, useMetricsTags, } from 'sentry/utils/metrics'; @@ -195,7 +195,7 @@ function MetricSearchBar({tags, mri, disabled, onChange, query}: MetricSearchBar // TODO(ddm): try to use useApiQuery here const getTagValues = useCallback( async tag => { - const {useCase} = parseMRI(mri); + const useCase = getUseCaseFromMRI(mri); const tagsValues = await api.requestPromise( `/organizations/${org.slug}/metrics/tags/${tag.key}/`, { diff --git a/static/app/views/ddm/summaryTable.tsx b/static/app/views/ddm/summaryTable.tsx index a663ac3c9c2a20..ca1b23d2f2f85d 100644 --- a/static/app/views/ddm/summaryTable.tsx +++ b/static/app/views/ddm/summaryTable.tsx @@ -103,7 +103,9 @@ export function SummaryTable({ const rows = series .map(s => { - const {name} = parseMRI(s.seriesName); + const parsed = parseMRI(s.seriesName); + const name = parsed?.name ?? s.seriesName; + return { ...s, ...getValues(s.data), diff --git a/static/app/views/ddm/widget.tsx b/static/app/views/ddm/widget.tsx index 51df8fbdc2e533..8381e3a2579284 100644 --- a/static/app/views/ddm/widget.tsx +++ b/static/app/views/ddm/widget.tsx @@ -250,7 +250,8 @@ function MetricWidgetBody({ function getChartSeries(data: MetricsData, {focusedSeries, groupBy, hoveredLegend}) { // this assumes that all series have the same unit - const {unit} = parseMRI(Object.keys(data.groups[0]?.series ?? {})[0]); + const parsed = parseMRI(Object.keys(data.groups[0]?.series ?? {})[0]); + const unit = parsed?.unit ?? ''; const series = data.groups.map(g => { return { @@ -290,9 +291,10 @@ function getSeriesName( groupBy: MetricsQuery['groupBy'] ) { if (isOnlyGroup && !groupBy?.length) { - const mri = Object.keys(group.series)?.[0] ?? '(none)'; - const {name} = parseMRI(mri); - return name; + const mri = Object.keys(group.series)?.[0]; + const parsed = parseMRI(mri); + + return parsed?.name ?? '(none)'; } return Object.entries(group.by)
d73bf7e33cfbb608f3c0c2972139d22bb132ed12
2023-11-10 05:41:06
Vu Luong
fix(selectControl): Fix `menuPortal` styles (#59764)
false
Fix `menuPortal` styles (#59764)
fix
diff --git a/static/app/components/forms/controls/selectControl.tsx b/static/app/components/forms/controls/selectControl.tsx index 20047d8893635c..9849597970afec 100644 --- a/static/app/components/forms/controls/selectControl.tsx +++ b/static/app/components/forms/controls/selectControl.tsx @@ -115,6 +115,10 @@ export interface ControlProps<OptionType extends OptionTypeBase = GeneralSelectV * Set to true to prefix selected values with content */ inFieldLabel?: string; + /** + * Whether this selector is being rendered inside a modal. If true, the menu will have a higher z-index. + */ + isInsideModal?: boolean; /** * Maximum width of the menu component. Menu item labels that overflow the * menu's boundaries will automatically be truncated. @@ -167,7 +171,7 @@ function SelectControl<OptionType extends GeneralSelectValue = GeneralSelectValu props: WrappedControlProps<OptionType> ) { const theme = useTheme(); - const {size, maxMenuWidth} = props; + const {size, maxMenuWidth, isInsideModal} = props; // TODO(epurkhiser): The loading indicator should probably also be our loading // indicator. @@ -216,27 +220,17 @@ function SelectControl<OptionType extends GeneralSelectValue = GeneralSelectValu ...provided, zIndex: theme.zIndex.dropdown, background: theme.backgroundElevated, - border: `1px solid ${theme.border}`, borderRadius: theme.borderRadius, - boxShadow: theme.dropShadowHeavy, + boxShadow: `${theme.dropShadowHeavy}, 0 0 0 1px ${theme.translucentBorder}`, width: 'auto', minWidth: '100%', maxWidth: maxMenuWidth ?? 'auto', }), - menuPortal: () => ({ + menuPortal: provided => ({ + ...provided, maxWidth: maxMenuWidth ?? '24rem', - zIndex: theme.zIndex.dropdown, - width: '90%', - position: 'fixed', - left: '50%', - top: '50%', - transform: 'translate(-50%, -50%)', - background: theme.backgroundElevated, - border: `1px solid ${theme.border}`, - borderRadius: theme.borderRadius, - boxShadow: theme.dropShadowHeavy, - overflow: 'hidden', + zIndex: isInsideModal ? theme.zIndex.modal + 1 : theme.zIndex.dropdown, }), option: provided => ({
a07b26c120c4b2dfc651c0695fd2204b63e66ad9
2023-07-10 18:32:56
Jan Michael Auer
feat(on-demand-metrics): Add more supported fields (#52514)
false
Add more supported fields (#52514)
feat
diff --git a/src/sentry/snuba/metrics/extraction.py b/src/sentry/snuba/metrics/extraction.py index e2fb399fb9fe07..d773e17651af35 100644 --- a/src/sentry/snuba/metrics/extraction.py +++ b/src/sentry/snuba/metrics/extraction.py @@ -36,37 +36,43 @@ RuleCondition = Union["LogicalRuleCondition", "ComparingRuleCondition", "NotRuleCondition"] -# Maps from Discover's field names to event protocol paths. -# See Relay's ``FieldValueProvider`` for supported fields. +# Maps from Discover's field names to event protocol paths. See Relay's +# ``FieldValueProvider`` for supported fields. All fields need to be prefixed +# with "event.". _SEARCH_TO_PROTOCOL_FIELDS = { # Top-level fields - "release": "event.release", - "dist": "event.dist", - "environment": "event.environment", - "transaction": "event.transaction", - "platform": "event.platform", - # User - "user.email": "event.user.email", - "user.id": "event.user.id", - "user.ip_address": "event.user.ip_address", - "user.name": "event.user.name", - "user.segment": "event.user.segment", + "release": "release", + "dist": "dist", + "environment": "environment", + "transaction": "transaction", + "platform": "platform", + # Top-level structures ("interfaces") + "user.email": "user.email", + "user.id": "user.id", + "user.ip_address": "user.ip_address", + "user.name": "user.name", + "user.segment": "user.segment", + "geo.city": "user.geo.city", + "geo.country_code": "user.geo.country_code", + "geo.region": "user.geo.region", + "geo.subdivision": "user.geo.subdivision", + "http.method": "request.method", # Subset of context fields - "device.name": "event.contexts.device.name", - "device.family": "event.contexts.device.family", - "os.name": "event.contexts.os.name", - "os.version": "event.contexts.os.version", - "transaction.op": "event.contexts.trace.op", + "device.name": "contexts.device.name", + "device.family": "contexts.device.family", + "os.name": "contexts.os.name", + "os.version": "contexts.os.version", + "browser.name": "contexts.browser.name", + "browser.version": "contexts.browser.version", + "transaction.op": "contexts.trace.op", + "transaction.status": "contexts.trace.status", + "http.status_code": "contexts.response.status_code", # Computed fields - "transaction.duration": "event.duration", - "release.build": "event.release.build", - "release.package": "event.release.package", - "release.version": "event.release.version.short", + "transaction.duration": "duration", + "release.build": "release.build", + "release.package": "release.package", + "release.version": "release.version.short", # Tags, measurements, and breakdowns are mapped by the converter - # TODO: Required but yet unsupported by Relay - # "geo.country_code": None, - # "transaction.status": None, - # "http.method": None, } # Maps from Discover's syntax to Relay rule condition operators. @@ -256,7 +262,7 @@ def _map_field_name(search_key: str) -> str: """ # Map known fields using a static mapping. if field := _SEARCH_TO_PROTOCOL_FIELDS.get(search_key): - return field + return f"event.{field}" # Measurements support generic access. if search_key.startswith("measurements."):
320406d1f54e6174340ac46ae063a6a405fc4ccd
2023-03-13 14:38:24
Michal Kuffa
feat(redis): Make feature adoption cache redis-cluster compatible (#45517)
false
Make feature adoption cache redis-cluster compatible (#45517)
feat
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index df4b33bc094680..ba86f32a288e89 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -3115,3 +3115,8 @@ def build_cdc_postgres_init_db_volume(settings): # Temporary allowlist for specially configured organizations to use the direct-storage # driver. SENTRY_REPLAYS_STORAGE_ALLOWLIST = [] + +SENTRY_FEATURE_ADOPTION_CACHE_OPTIONS = { + "path": "sentry.models.featureadoption.FeatureAdoptionRedisBackend", + "options": {"cluster": "default"}, +} diff --git a/src/sentry/models/featureadoption.py b/src/sentry/models/featureadoption.py index d46a83a6c2004f..8513cd2e77cccc 100644 --- a/src/sentry/models/featureadoption.py +++ b/src/sentry/models/featureadoption.py @@ -1,5 +1,7 @@ import logging +from typing import cast +from django.conf import settings from django.db import IntegrityError, models, transaction from django.utils import timezone @@ -13,7 +15,8 @@ region_silo_only_model, sane_repr, ) -from sentry.utils import redis +from sentry.utils.redis import get_dynamic_cluster_from_options +from sentry.utils.services import build_instance_from_options logger = logging.getLogger(__name__) @@ -114,38 +117,56 @@ manager.add(92, "metric_alert_rules", "Metric Alert Rules", "web", prerequisite=["first_event"]) -class FeatureAdoptionManager(BaseManager): - def in_cache(self, organization_id, feature_id): - org_key = FEATURE_ADOPTION_REDIS_KEY.format(organization_id) - feature_matches = [] - with redis.clusters.get("default").map() as client: - feature_matches.append(client.sismember(org_key, feature_id)) +class FeatureAdoptionRedisBackend: + def __init__(self, key_tpl=FEATURE_ADOPTION_REDIS_KEY, **options): + self.key_tpl = key_tpl + self.is_redis_cluster, self.cluster, _config = get_dynamic_cluster_from_options( + "SENTRY_FEATURE_ADOPTION_CACHE_OPTIONS", options + ) - return any([p.value for p in feature_matches]) + def get_client(self, key): + # WARN: Carefully as this works only for single key operations. + if self.is_redis_cluster: + return self.cluster + else: + return self.cluster.get_local_client_for_key(key) - def set_cache(self, organization_id, feature_id): - org_key = FEATURE_ADOPTION_REDIS_KEY.format(organization_id) - with redis.clusters.get("default").map() as client: - client.sadd(org_key, feature_id) - return True + def in_cache(self, organization_id, feature_id): + org_key = self.key_tpl.format(organization_id) + return self.get_client(org_key).sismember(org_key, feature_id) def get_all_cache(self, organization_id): - org_key = FEATURE_ADOPTION_REDIS_KEY.format(organization_id) - result = [] - with redis.clusters.get("default").map() as client: - result.append(client.smembers(org_key)) - - return {int(x) for x in set.union(*(p.value for p in result))} + org_key = self.key_tpl.format(organization_id) + return {int(v) for v in self.get_client(org_key).smembers(org_key)} def bulk_set_cache(self, organization_id, *args): if not args: return False - org_key = FEATURE_ADOPTION_REDIS_KEY.format(organization_id) - with redis.clusters.get("default").map() as client: - client.sadd(org_key, *args) + org_key = self.key_tpl.format(organization_id) + self.get_client(org_key).sadd(org_key, *args) return True + +class FeatureAdoptionManager(BaseManager): + + cache_backend: FeatureAdoptionRedisBackend = cast( + FeatureAdoptionRedisBackend, + build_instance_from_options(settings.SENTRY_FEATURE_ADOPTION_CACHE_OPTIONS), + ) + + def in_cache(self, organization_id, feature_id): + return self.cache_backend.in_cache(organization_id, feature_id) + + def set_cache(self, organization_id, feature_id): + return self.bulk_set_cache(organization_id, feature_id) + + def get_all_cache(self, organization_id): + return self.cache_backend.get_all_cache(organization_id) + + def bulk_set_cache(self, organization_id, *args): + return self.cache_backend.bulk_set_cache(organization_id, *args) + def record(self, organization_id, feature_slug, **kwargs): try: feature_id = manager.get_by_slug(feature_slug).id diff --git a/tests/sentry/models/test_featureadoption.py b/tests/sentry/models/test_featureadoption.py new file mode 100644 index 00000000000000..5f3084c50768b2 --- /dev/null +++ b/tests/sentry/models/test_featureadoption.py @@ -0,0 +1,28 @@ +from sentry.models.featureadoption import FeatureAdoptionRedisBackend +from sentry.testutils import TestCase +from sentry.utils.redis import redis_clusters + + +class TestFeatureAdoptionRedisCache(TestCase): + def setUp(self): + self.cache = FeatureAdoptionRedisBackend(cluster="default") + self.org_id = 1234 + + def test_in_cache(self): + assert not self.cache.in_cache(self.org_id, 90) + self.cache.bulk_set_cache(self.org_id, 90) + assert self.cache.in_cache(self.org_id, 90) + + def test_get_all_cache(self): + fids = {70, 71, 72, 90, 91, 92} + self.cache.bulk_set_cache(self.org_id, *fids) + assert self.cache.get_all_cache(self.org_id) == fids + + +class TestFeatureAdoptionRedisClusterCache(TestFeatureAdoptionRedisCache): + def setUp(self): + # TODO: Once we have properly redis-cluster setup in tests and CI use that For now that's + # the simplest way to test non redis-blaster compatibility. + self.cache = FeatureAdoptionRedisBackend() + self.cache.is_redis_cluster, self.cache.cluster = True, redis_clusters.get("default") + self.org_id = 1234
f5b0cc2929f076bbd9ad5b5a322fb0519eb044c9
2024-04-03 00:30:47
Malachi Willey
feat(autofix): Add setup modal (#68013)
false
Add setup modal (#68013)
feat
diff --git a/static/app/components/events/autofix/autofixBanner.spec.tsx b/static/app/components/events/autofix/autofixBanner.spec.tsx index fc9889a4b88ec1..eef7941d2c4ddc 100644 --- a/static/app/components/events/autofix/autofixBanner.spec.tsx +++ b/static/app/components/events/autofix/autofixBanner.spec.tsx @@ -18,10 +18,16 @@ describe('AutofixBanner', () => { jest.resetAllMocks(); }); + const defaultProps = { + groupId: '1', + hasSuccessfulSetup: true, + triggerAutofix: jest.fn(), + }; + it('shows PII check for sentry employee users', () => { mockIsSentryEmployee(true); - render(<AutofixBanner triggerAutofix={() => {}} />); + render(<AutofixBanner {...defaultProps} />); expect( screen.getByText( 'By clicking the button above, you confirm that there is no PII in this event.' @@ -32,7 +38,7 @@ describe('AutofixBanner', () => { it('does not show PII check for non sentry employee users', () => { mockIsSentryEmployee(false); - render(<AutofixBanner triggerAutofix={() => {}} />); + render(<AutofixBanner {...defaultProps} />); expect( screen.queryByText( 'By clicking the button above, you confirm that there is no PII in this event.' @@ -43,7 +49,7 @@ describe('AutofixBanner', () => { it('can run without instructions', async () => { const mockTriggerAutofix = jest.fn(); - render(<AutofixBanner triggerAutofix={mockTriggerAutofix} />); + render(<AutofixBanner {...defaultProps} triggerAutofix={mockTriggerAutofix} />); renderGlobalModal(); await userEvent.click(screen.getByRole('button', {name: 'Gimme Fix'})); @@ -53,7 +59,7 @@ describe('AutofixBanner', () => { it('can provide instructions', async () => { const mockTriggerAutofix = jest.fn(); - render(<AutofixBanner triggerAutofix={mockTriggerAutofix} />); + render(<AutofixBanner {...defaultProps} triggerAutofix={mockTriggerAutofix} />); renderGlobalModal(); await userEvent.click(screen.getByRole('button', {name: 'Give Instructions'})); diff --git a/static/app/components/events/autofix/autofixBanner.tsx b/static/app/components/events/autofix/autofixBanner.tsx index 3c6739eed9711c..1edb76d4cf6ce1 100644 --- a/static/app/components/events/autofix/autofixBanner.tsx +++ b/static/app/components/events/autofix/autofixBanner.tsx @@ -8,6 +8,7 @@ import bannerStars from 'sentry-images/spot/ai-suggestion-banner-stars.svg'; import {openModal} from 'sentry/actionCreators/modal'; import {Button} from 'sentry/components/button'; import {AutofixInstructionsModal} from 'sentry/components/events/autofix/autofixInstructionsModal'; +import {AutofixSetupModal} from 'sentry/components/modals/autofixSetupModal'; import Panel from 'sentry/components/panels/panel'; import PanelBody from 'sentry/components/panels/panelBody'; import {t} from 'sentry/locale'; @@ -15,10 +16,12 @@ import {space} from 'sentry/styles/space'; import {useIsSentryEmployee} from 'sentry/utils/useIsSentryEmployee'; type Props = { + groupId: string; + hasSuccessfulSetup: boolean; triggerAutofix: (value: string) => void; }; -export function AutofixBanner({triggerAutofix}: Props) { +export function AutofixBanner({groupId, triggerAutofix, hasSuccessfulSetup}: Props) { const isSentryEmployee = useIsSentryEmployee(); const onClickGiveInstructions = () => { openModal(deps => ( @@ -39,14 +42,29 @@ export function AutofixBanner({triggerAutofix}: Props) { <SubTitle>{t('You might get lucky, but then again, maybe not...')}</SubTitle> </div> <ContextArea> - <Button onClick={() => triggerAutofix('')} size="sm"> - {t('Gimme Fix')} - </Button> - <Button onClick={onClickGiveInstructions} size="sm"> - {t('Give Instructions')} - </Button> + {hasSuccessfulSetup ? ( + <Fragment> + <Button onClick={() => triggerAutofix('')} size="sm"> + {t('Gimme Fix')} + </Button> + <Button onClick={onClickGiveInstructions} size="sm"> + {t('Give Instructions')} + </Button> + </Fragment> + ) : ( + <Button + analyticsEventKey="autofix.setup_clicked" + analyticsEventName="Autofix: Setup Clicked" + onClick={() => { + openModal(deps => <AutofixSetupModal {...deps} groupId={groupId} />); + }} + size="sm" + > + Setup Autofix + </Button> + )} </ContextArea> - {isSentryEmployee && ( + {isSentryEmployee && hasSuccessfulSetup && ( <Fragment> <Separator /> <PiiMessage> @@ -96,6 +114,7 @@ const ContextArea = styled('div')` const IllustrationContainer = styled('div')` display: none; + pointer-events: none; @media (min-width: ${p => p.theme.breakpoints.xlarge}) { display: block; @@ -110,12 +129,11 @@ const IllustrationContainer = styled('div')` `; const Sentaur = styled('img')` - height: 125px; + height: 110px; position: absolute; bottom: 0; right: 185px; z-index: 1; - pointer-events: none; `; const Background = styled('img')` @@ -128,9 +146,9 @@ const Background = styled('img')` const Stars = styled('img')` pointer-events: none; position: absolute; - right: -140px; + right: -120px; bottom: 40px; - height: 120px; + height: 90px; `; const Separator = styled('hr')` diff --git a/static/app/components/events/autofix/index.spec.tsx b/static/app/components/events/autofix/index.spec.tsx index 2f6498c8bd2b8c..c73f2410a48dc0 100644 --- a/static/app/components/events/autofix/index.spec.tsx +++ b/static/app/components/events/autofix/index.spec.tsx @@ -13,11 +13,18 @@ const group = GroupFixture(); const event = EventFixture(); describe('AiAutofix', () => { - beforeAll(() => { + beforeEach(() => { MockApiClient.addMockResponse({ url: `/issues/${group.id}/ai-autofix/`, body: null, }); + MockApiClient.addMockResponse({ + url: `/issues/${group.id}/autofix/setup/`, + body: { + genAIConsent: {ok: true}, + integration: {ok: true}, + }, + }); }); it('renders the Banner component when autofixData is null', () => { diff --git a/static/app/components/events/autofix/index.tsx b/static/app/components/events/autofix/index.tsx index 65feffdc187cc6..5b57a350ce4c79 100644 --- a/static/app/components/events/autofix/index.tsx +++ b/static/app/components/events/autofix/index.tsx @@ -3,6 +3,7 @@ import {AutofixBanner} from 'sentry/components/events/autofix/autofixBanner'; import {AutofixCard} from 'sentry/components/events/autofix/autofixCard'; import type {GroupWithAutofix} from 'sentry/components/events/autofix/types'; import {useAiAutofix} from 'sentry/components/events/autofix/useAutofix'; +import {useAutofixSetup} from 'sentry/components/events/autofix/useAutofixSetup'; import type {Event} from 'sentry/types'; interface Props { @@ -13,13 +14,21 @@ interface Props { export function Autofix({event, group}: Props) { const {autofixData, triggerAutofix, reset} = useAiAutofix(group, event); + const {hasSuccessfulSetup} = useAutofixSetup({ + groupId: group.id, + }); + return ( <ErrorBoundary mini> <div> {autofixData ? ( <AutofixCard data={autofixData} onRetry={reset} /> ) : ( - <AutofixBanner triggerAutofix={triggerAutofix} /> + <AutofixBanner + groupId={group.id} + triggerAutofix={triggerAutofix} + hasSuccessfulSetup={hasSuccessfulSetup} + /> )} </div> </ErrorBoundary> diff --git a/static/app/components/events/autofix/useAutofixSetup.tsx b/static/app/components/events/autofix/useAutofixSetup.tsx new file mode 100644 index 00000000000000..d32eed02e057c1 --- /dev/null +++ b/static/app/components/events/autofix/useAutofixSetup.tsx @@ -0,0 +1,33 @@ +import {useApiQuery, type UseApiQueryOptions} from 'sentry/utils/queryClient'; +import type RequestError from 'sentry/utils/requestError/requestError'; + +export type AutofixSetupResponse = { + genAIConsent: { + ok: boolean; + }; + integration: { + ok: boolean; + reason: string | null; + }; + subprocessorConsent: { + ok: boolean; + }; +}; + +export function useAutofixSetup( + {groupId}: {groupId: string}, + options: Omit<UseApiQueryOptions<AutofixSetupResponse, RequestError>, 'staleTime'> = {} +) { + const queryData = useApiQuery<AutofixSetupResponse>( + [`/issues/${groupId}/autofix/setup/`], + {enabled: Boolean(groupId), staleTime: 0, retry: false, ...options} + ); + + return { + ...queryData, + hasSuccessfulSetup: Boolean( + // TODO: Add other checks here when we can actually configure them + queryData.data?.integration.ok + ), + }; +} diff --git a/static/app/components/guidedSteps/guidedSteps.spec.tsx b/static/app/components/guidedSteps/guidedSteps.spec.tsx index 4d3d629b6dcc91..c060919044c8f3 100644 --- a/static/app/components/guidedSteps/guidedSteps.spec.tsx +++ b/static/app/components/guidedSteps/guidedSteps.spec.tsx @@ -6,15 +6,15 @@ describe('GuidedSteps', function () { it('can navigate through steps and shows previous ones as completed', async function () { render( <GuidedSteps> - <GuidedSteps.Step title="Step 1 Title"> + <GuidedSteps.Step stepKey="step-1" title="Step 1 Title"> This is the first step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 2 Title"> + <GuidedSteps.Step stepKey="step-2" title="Step 2 Title"> This is the second step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 3 Title"> + <GuidedSteps.Step stepKey="step-3" title="Step 3 Title"> This is the third step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> @@ -40,15 +40,15 @@ describe('GuidedSteps', function () { it('starts at the first incomplete step', function () { render( <GuidedSteps> - <GuidedSteps.Step title="Step 1 Title" isCompleted> + <GuidedSteps.Step stepKey="step-1" title="Step 1 Title" isCompleted> This is the first step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 2 Title" isCompleted={false}> + <GuidedSteps.Step stepKey="step-2" title="Step 2 Title" isCompleted={false}> This is the second step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 3 Title" isCompleted={false}> + <GuidedSteps.Step stepKey="step-3" title="Step 3 Title" isCompleted={false}> This is the third step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> diff --git a/static/app/components/guidedSteps/guidedSteps.stories.tsx b/static/app/components/guidedSteps/guidedSteps.stories.tsx index 0e4600a9539a65..1347ed9fc369a7 100644 --- a/static/app/components/guidedSteps/guidedSteps.stories.tsx +++ b/static/app/components/guidedSteps/guidedSteps.stories.tsx @@ -23,15 +23,15 @@ export default storyBook(GuidedSteps, story => { </p> <SizingWindow display="block"> <GuidedSteps> - <GuidedSteps.Step title="Step 1 Title"> + <GuidedSteps.Step title="Step 1 Title" stepKey="step-1"> This is the first step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 2 Title"> + <GuidedSteps.Step title="Step 2 Title" stepKey="step-2"> This is the second step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 3 Title"> + <GuidedSteps.Step title="Step 3 Title" stepKey="step-3"> This is the third step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> @@ -61,15 +61,15 @@ export default storyBook(GuidedSteps, story => { </p> <SizingWindow display="block"> <GuidedSteps> - <GuidedSteps.Step title="Step 1 Title"> + <GuidedSteps.Step title="Step 1 Title" stepKey="step-1"> This is the first step. <SkipToLastButton /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 2 Title"> + <GuidedSteps.Step title="Step 2 Title" stepKey="step-2"> This is the second step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 3 Title"> + <GuidedSteps.Step title="Step 3 Title" stepKey="step-3"> This is the third step. <GuidedSteps.StepButtons /> </GuidedSteps.Step> @@ -90,17 +90,17 @@ export default storyBook(GuidedSteps, story => { </p> <SizingWindow display="block"> <GuidedSteps> - <GuidedSteps.Step title="Step 1 Title" isCompleted> + <GuidedSteps.Step title="Step 1 Title" stepKey="step-1" isCompleted> Congrats, you finished the first step! <GuidedSteps.StepButtons /> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 2 Title" isCompleted={false}> + <GuidedSteps.Step title="Step 2 Title" stepKey="step-2" isCompleted={false}> You haven't completed the second step yet, here's how you do it. <GuidedSteps.ButtonWrapper> <GuidedSteps.BackButton /> </GuidedSteps.ButtonWrapper> </GuidedSteps.Step> - <GuidedSteps.Step title="Step 3 Title" isCompleted={false}> + <GuidedSteps.Step title="Step 3 Title" stepKey="step-3" isCompleted={false}> You haven't completed the third step yet, here's how you do it. <GuidedSteps.ButtonWrapper> <GuidedSteps.BackButton /> diff --git a/static/app/components/guidedSteps/guidedSteps.tsx b/static/app/components/guidedSteps/guidedSteps.tsx index fe3845c7b7a4c3..75871e456537e6 100644 --- a/static/app/components/guidedSteps/guidedSteps.tsx +++ b/static/app/components/guidedSteps/guidedSteps.tsx @@ -1,13 +1,14 @@ import { - Children, createContext, - isValidElement, useCallback, useContext, + useEffect, useMemo, + useRef, useState, } from 'react'; import styled from '@emotion/styled'; +import orderBy from 'lodash/orderBy'; import {type BaseButtonProps, Button} from 'sentry/components/button'; import {IconCheckmark} from 'sentry/icons'; @@ -22,46 +23,111 @@ type GuidedStepsProps = { interface GuidedStepsContextState { currentStep: number; + getStepNumber: (stepKey: string) => number; + registerStep: (step: RegisterStepInfo) => void; setCurrentStep: (step: number) => void; totalSteps: number; } interface StepProps { children: React.ReactNode; + stepKey: string; title: string; isCompleted?: boolean; - stepNumber?: number; } +type RegisterStepInfo = Pick<StepProps, 'stepKey' | 'isCompleted'>; +type RegisteredSteps = {[key: string]: {stepNumber: number; isCompleted?: boolean}}; + const GuidedStepsContext = createContext<GuidedStepsContextState>({ currentStep: 0, setCurrentStep: () => {}, totalSteps: 0, + registerStep: () => 0, + getStepNumber: () => 0, }); export function useGuidedStepsContext() { return useContext(GuidedStepsContext); } -function Step({ - stepNumber = 1, - title, - children, - isCompleted: completedOverride, -}: StepProps) { - const {currentStep} = useGuidedStepsContext(); +function useGuidedStepsContentValue({ + onStepChange, +}: Pick<GuidedStepsProps, 'onStepChange'>): GuidedStepsContextState { + const registeredStepsRef = useRef<RegisteredSteps>({}); + const [totalSteps, setTotalSteps] = useState<number>(0); + const [currentStep, setCurrentStep] = useState<number>(1); + + // Steps are registered on initial render to determine the step order and which step to start on. + // This allows Steps to be wrapped in other components, but does require that they exist on first + // render and that step order does not change. + const registerStep = useCallback((props: RegisterStepInfo) => { + if (registeredStepsRef.current[props.stepKey]) { + return; + } + const numRegisteredSteps = Object.keys(registeredStepsRef.current).length + 1; + registeredStepsRef.current[props.stepKey] = { + isCompleted: props.isCompleted, + stepNumber: numRegisteredSteps, + }; + setTotalSteps(numRegisteredSteps); + }, []); + + const getStepNumber = useCallback((stepKey: string) => { + return registeredStepsRef.current[stepKey]?.stepNumber ?? 1; + }, []); + + // On initial load, set the current step to the first incomplete step + useEffect(() => { + const firstIncompleteStep = orderBy( + Object.values(registeredStepsRef.current), + 'stepNumber' + ).find(step => step.isCompleted !== true); + + setCurrentStep(firstIncompleteStep?.stepNumber ?? 1); + }, []); + + const handleSetCurrentStep = useCallback( + (step: number) => { + setCurrentStep(step); + onStepChange?.(step); + }, + [onStepChange] + ); + + return useMemo( + () => ({ + currentStep, + setCurrentStep: handleSetCurrentStep, + totalSteps, + registerStep, + getStepNumber, + }), + [currentStep, getStepNumber, handleSetCurrentStep, registerStep, totalSteps] + ); +} + +function Step(props: StepProps) { + const {currentStep, registerStep, getStepNumber} = useGuidedStepsContext(); + const stepNumber = getStepNumber(props.stepKey); const isActive = currentStep === stepNumber; - const isCompleted = completedOverride ?? currentStep > stepNumber; + const isCompleted = props.isCompleted ?? currentStep > stepNumber; + + useEffect(() => { + registerStep({isCompleted: props.isCompleted, stepKey: props.stepKey}); + }, [props.isCompleted, props.stepKey, registerStep]); return ( <StepWrapper data-test-id={`guided-step-${stepNumber}`}> <StepNumber isActive={isActive}>{stepNumber}</StepNumber> <div> <StepHeading isActive={isActive}> - {title} + {props.title} {isCompleted && <StepDoneIcon isActive={isActive} size="sm" />} </StepHeading> - {isActive && <ChildrenWrapper isActive={isActive}>{children}</ChildrenWrapper>} + {isActive && ( + <ChildrenWrapper isActive={isActive}>{props.children}</ChildrenWrapper> + )} </div> </StepWrapper> ); @@ -105,44 +171,11 @@ function StepButtons() { } export function GuidedSteps({className, children, onStepChange}: GuidedStepsProps) { - const [currentStep, setCurrentStep] = useState<number>(() => { - // If `isCompleted` has been passed in, we should start at the first incomplete step - const firstIncompleteStepIndex = Children.toArray(children).findIndex(child => - isValidElement(child) ? child.props.isCompleted !== true : false - ); - - return Math.max(1, firstIncompleteStepIndex + 1); - }); - - const totalSteps = Children.count(children); - const handleSetCurrentStep = useCallback( - (step: number) => { - setCurrentStep(step); - onStepChange?.(step); - }, - [onStepChange] - ); - - const value = useMemo( - () => ({ - currentStep, - setCurrentStep: handleSetCurrentStep, - totalSteps, - }), - [currentStep, handleSetCurrentStep, totalSteps] - ); + const value = useGuidedStepsContentValue({onStepChange}); return ( <GuidedStepsContext.Provider value={value}> - <StepsWrapper className={className}> - {Children.map(children, (child, index) => { - if (!child) { - return null; - } - - return <Step stepNumber={index + 1} {...child.props} />; - })} - </StepsWrapper> + <StepsWrapper className={className}>{children}</StepsWrapper> </GuidedStepsContext.Provider> ); } @@ -212,6 +245,10 @@ const StepDoneIcon = styled(IconCheckmark, { const ChildrenWrapper = styled('div')<{isActive: boolean}>` color: ${p => (p.isActive ? p.theme.textColor : p.theme.subText)}; + + p { + margin-bottom: ${space(1)}; + } `; GuidedSteps.Step = Step; diff --git a/static/app/components/modals/autofixSetupModal.spec.tsx b/static/app/components/modals/autofixSetupModal.spec.tsx new file mode 100644 index 00000000000000..138dd9527e59d3 --- /dev/null +++ b/static/app/components/modals/autofixSetupModal.spec.tsx @@ -0,0 +1,83 @@ +import {act, renderGlobalModal, screen, userEvent} from 'sentry-test/reactTestingLibrary'; + +import {openModal} from 'sentry/actionCreators/modal'; +import {AutofixSetupModal} from 'sentry/components/modals/autofixSetupModal'; + +describe('AutofixSetupModal', function () { + it('renders the integration setup instructions', async function () { + MockApiClient.addMockResponse({ + url: '/issues/1/autofix/setup/', + body: { + genAIConsent: {ok: true}, + integration: {ok: false}, + }, + }); + + const closeModal = jest.fn(); + + renderGlobalModal(); + + act(() => { + openModal(modalProps => <AutofixSetupModal {...modalProps} groupId="1" />, { + onClose: closeModal, + }); + }); + + expect(await screen.findByText('Install the GitHub Integration')).toBeInTheDocument(); + expect( + screen.getByText(/Install the GitHub integration by navigating to/) + ).toBeInTheDocument(); + }); + + it('displays successful integration text when it is installed', async function () { + MockApiClient.addMockResponse({ + url: '/issues/1/autofix/setup/', + body: { + genAIConsent: {ok: false}, + integration: {ok: true}, + }, + }); + + const closeModal = jest.fn(); + + renderGlobalModal(); + + act(() => { + openModal(modalProps => <AutofixSetupModal {...modalProps} groupId="1" />, { + onClose: closeModal, + }); + }); + + expect( + await screen.findByText(/The GitHub integration is already installed/) + ).toBeInTheDocument(); + }); + + it('shows success text when steps are done', async function () { + MockApiClient.addMockResponse({ + url: '/issues/1/autofix/setup/', + body: { + genAIConsent: {ok: true}, + integration: {ok: true}, + }, + }); + + const closeModal = jest.fn(); + + renderGlobalModal(); + + act(() => { + openModal(modalProps => <AutofixSetupModal {...modalProps} groupId="1" />, { + onClose: closeModal, + }); + }); + + expect( + await screen.findByText("You've successfully configured Autofix!") + ).toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', {name: "Let's go"})); + + expect(closeModal).toHaveBeenCalled(); + }); +}); diff --git a/static/app/components/modals/autofixSetupModal.tsx b/static/app/components/modals/autofixSetupModal.tsx new file mode 100644 index 00000000000000..cd046fff8a4a65 --- /dev/null +++ b/static/app/components/modals/autofixSetupModal.tsx @@ -0,0 +1,199 @@ +import {Fragment} from 'react'; +import styled from '@emotion/styled'; + +import type {ModalRenderProps} from 'sentry/actionCreators/modal'; +import {Button} from 'sentry/components/button'; +import { + type AutofixSetupResponse, + useAutofixSetup, +} from 'sentry/components/events/autofix/useAutofixSetup'; +import {GuidedSteps} from 'sentry/components/guidedSteps/guidedSteps'; +import HookOrDefault from 'sentry/components/hookOrDefault'; +import ExternalLink from 'sentry/components/links/externalLink'; +import LoadingError from 'sentry/components/loadingError'; +import LoadingIndicator from 'sentry/components/loadingIndicator'; +import {IconCheckmark} from 'sentry/icons'; +import {t, tct} from 'sentry/locale'; +import {space} from 'sentry/styles/space'; + +interface AutofixSetupModalProps extends ModalRenderProps { + groupId: string; +} + +const ConsentStep = HookOrDefault({ + hookName: 'component:autofix-setup-step-consent', + defaultComponent: null, +}); + +function AutofixIntegrationStep({autofixSetup}: {autofixSetup: AutofixSetupResponse}) { + if (autofixSetup.integration.ok) { + return ( + <Fragment> + {tct('The GitHub integration is already installed, [link: view in settings].', { + link: <ExternalLink href={`/settings/integrations/github/`} />, + })} + <GuidedSteps.StepButtons /> + </Fragment> + ); + } + + if (autofixSetup.integration.reason === 'integration_inactive') { + return ( + <Fragment> + <p> + {tct( + 'The GitHub integration has been installed but is not active. Navigate to the [integration settings page] and enable it to continue.', + { + link: <ExternalLink href={`/settings/integrations/github/`} />, + } + )} + </p> + <p> + {tct( + 'Once enabled, come back to this page. For more information related to installing the GitHub integration, read the [link:documentation].', + { + link: ( + <ExternalLink href="https://docs.sentry.io/product/integrations/source-code-mgmt/github/" /> + ), + } + )} + </p> + <GuidedSteps.StepButtons /> + </Fragment> + ); + } + + if (autofixSetup.integration.reason === 'integration_no_code_mappings') { + return ( + <Fragment> + <p> + {tct( + 'You have an active GitHub installation, but no linked repositories. Add repositories to the integration on the [integration settings page].', + { + link: <ExternalLink href={`/settings/integrations/github/`} />, + } + )} + </p> + <p> + {tct( + 'Once added, come back to this page. For more information related to installing the GitHub integration, read the [link:documentation].', + { + link: ( + <ExternalLink href="https://docs.sentry.io/product/integrations/source-code-mgmt/github/" /> + ), + } + )} + </p> + <GuidedSteps.StepButtons /> + </Fragment> + ); + } + + return ( + <Fragment> + <p> + {tct( + 'Install the GitHub integration by navigating to the [link:integration settings page] and clicking the "Install" button. Follow the steps provided.', + { + link: <ExternalLink href={`/settings/integrations/github/`} />, + } + )} + </p> + <p> + {tct( + 'Once installed, come back to this page. For more information related to installing the GitHub integration, read the [link:documentation].', + { + link: ( + <ExternalLink href="https://docs.sentry.io/product/integrations/source-code-mgmt/github/" /> + ), + } + )} + </p> + <GuidedSteps.StepButtons /> + </Fragment> + ); +} + +function AutofixSetupSteps({autofixSetup}: {autofixSetup: AutofixSetupResponse}) { + return ( + <GuidedSteps> + <ConsentStep hasConsented={autofixSetup.genAIConsent.ok} /> + <GuidedSteps.Step + stepKey="integration" + title={t('Install the GitHub Integration')} + isCompleted={autofixSetup.integration.ok} + > + <AutofixIntegrationStep autofixSetup={autofixSetup} /> + </GuidedSteps.Step> + </GuidedSteps> + ); +} + +function AutofixSetupContent({ + groupId, + closeModal, +}: { + closeModal: () => void; + groupId: string; +}) { + const {data, isLoading, isError} = useAutofixSetup( + {groupId}, + // Want to check setup status whenever the user comes back to the tab + {refetchOnWindowFocus: true} + ); + + if (isLoading) { + return <LoadingIndicator />; + } + + if (isError) { + return <LoadingError message={t('Failed to fetch Autofix setup progress.')} />; + } + + if (data.genAIConsent.ok && data.integration.ok) { + return ( + <AutofixSetupDone> + <DoneIcon size="xxl" isCircled /> + <p>{t("You've successfully configured Autofix!")}</p> + <Button onClick={closeModal} priority="primary"> + {t("Let's go")} + </Button> + </AutofixSetupDone> + ); + } + + return <AutofixSetupSteps autofixSetup={data} />; +} + +export function AutofixSetupModal({ + Header, + Body, + groupId, + closeModal, +}: AutofixSetupModalProps) { + return ( + <Fragment> + <Header closeButton> + <h3>{t('Configure Autofix')}</h3> + </Header> + <Body> + <AutofixSetupContent groupId={groupId} closeModal={closeModal} /> + </Body> + </Fragment> + ); +} + +const AutofixSetupDone = styled('div')` + position: relative; + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + padding: 40px; + font-size: ${p => p.theme.fontSizeLarge}; +`; + +const DoneIcon = styled(IconCheckmark)` + color: ${p => p.theme.success}; + margin-bottom: ${space(4)}; +`; diff --git a/static/app/types/hooks.tsx b/static/app/types/hooks.tsx index 6a9906925d08a2..f643edf41bf4bb 100644 --- a/static/app/types/hooks.tsx +++ b/static/app/types/hooks.tsx @@ -67,6 +67,7 @@ export type RouteHooks = { * Component specific hooks for DateRange and SelectorItems * These components have plan specific overrides in getsentry */ +type AutofixSetupConsentStepProps = {hasConsented: boolean}; type DateRangeProps = React.ComponentProps<typeof DateRange>; type SelectorItemsProps = React.ComponentProps<typeof SelectorItems>; @@ -180,6 +181,7 @@ export type PartnershipAgreementProps = { * Component wrapping hooks */ export type ComponentHooks = { + 'component:autofix-setup-step-consent': () => React.ComponentType<AutofixSetupConsentStepProps> | null; 'component:codecov-integration-settings-link': () => React.ComponentType<CodecovLinkProps>; 'component:confirm-account-close': () => React.ComponentType<AttemptCloseAttemptProps>; 'component:crons-list-page-header': () => React.ComponentType<CronsBillingBannerProps>;
61ae1ef9de33d2724ab3caa98a5bd265df897d89
2024-05-10 04:44:33
Tillman Elser
ref(seer): separate out all seer connections (#69961)
false
separate out all seer connections (#69961)
ref
diff --git a/src/sentry/api/endpoints/organization_transaction_anomaly_detection.py b/src/sentry/api/endpoints/organization_transaction_anomaly_detection.py index 486f783f1477fd..7acf5f06e3ddf4 100644 --- a/src/sentry/api/endpoints/organization_transaction_anomaly_detection.py +++ b/src/sentry/api/endpoints/organization_transaction_anomaly_detection.py @@ -16,12 +16,12 @@ from sentry.snuba.metrics_enhanced_performance import timeseries_query ads_connection_pool = connection_from_url( - settings.ANOMALY_DETECTION_URL, + settings.SEER_ANOMALY_DETECTION_URL, retries=Retry( total=5, status_forcelist=[408, 429, 502, 503, 504], ), - timeout=settings.ANOMALY_DETECTION_TIMEOUT, + timeout=settings.SEER_ANOMALY_DETECTION_TIMEOUT, ) MappedParams = namedtuple("MappedParams", ["query_start", "query_end", "granularity"]) diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 7921750f3c33cd..e9f5149e8f941b 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -3668,15 +3668,24 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]: # constraints instead of setting the column to not null. ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = False -ANOMALY_DETECTION_URL = "http://127.0.0.1:9091" -ANOMALY_DETECTION_TIMEOUT = 30 +SEER_DEFAULT_URL = "http://127.0.0.1:9091" # for local development +SEER_DEFAULT_TIMEOUT = 5 -# TODO: Once this moves to its own service, this URL will need to be updated -SEVERITY_DETECTION_URL = ANOMALY_DETECTION_URL -SEVERITY_DETECTION_TIMEOUT = 0.3 # 300 milliseconds -SEVERITY_DETECTION_RETRIES = 1 +SEER_BREAKPOINT_DETECTION_URL = SEER_DEFAULT_URL # for local development, these share a URL +SEER_BREAKPOINT_DETECTION_TIMEOUT = 5 + +SEER_SEVERITY_URL = SEER_DEFAULT_URL # for local development, these share a URL +SEER_SEVERITY_TIMEOUT = 0.3 # 300 milliseconds +SEER_SEVERITY_RETRIES = 1 + +SEER_AUTOFIX_URL = SEER_DEFAULT_URL # for local development, these share a URL + +SEER_GROUPING_URL = SEER_DEFAULT_URL # for local development, these share a URL +SEER_GROUPING_TIMEOUT = 1 + +SEER_ANOMALY_DETECTION_URL = SEER_DEFAULT_URL # for local development, these share a URL +SEER_ANOMALY_DETECTION_TIMEOUT = 5 -SEER_AUTOFIX_URL = ANOMALY_DETECTION_URL # In local development this is the same as ANOMALY_DETECTION_URL, for prod check getsentry. # This is the URL to the profiling service SENTRY_VROOM = os.getenv("VROOM", "http://127.0.0.1:8085") diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py index 4e3e8cb8ed32b8..32e441e3775ca4 100644 --- a/src/sentry/event_manager.py +++ b/src/sentry/event_manager.py @@ -31,7 +31,7 @@ tsdb, ) from sentry.attachments import CachedAttachment, MissingAttachmentChunks, attachment_cache -from sentry.conf.server import SEVERITY_DETECTION_RETRIES +from sentry.conf.server import SEER_SEVERITY_RETRIES from sentry.constants import ( DEFAULT_STORE_NORMALIZER_ARGS, LOG_LEVELS_MAP, @@ -2220,8 +2220,8 @@ def _process_existing_aggregate( severity_connection_pool = connection_from_url( - settings.SEVERITY_DETECTION_URL, - timeout=settings.SEVERITY_DETECTION_TIMEOUT, # Defaults to 300 milliseconds + settings.SEER_SEVERITY_URL, + timeout=settings.SEER_SEVERITY_TIMEOUT, # Defaults to 300 milliseconds ) @@ -2432,7 +2432,7 @@ def _get_severity_score(event: Event) -> tuple[float, str]: with metrics.timer(op): timeout = options.get( "issues.severity.seer-timout", - settings.SEVERITY_DETECTION_TIMEOUT / 1000, + settings.SEER_SEVERITY_TIMEOUT / 1000, ) response = severity_connection_pool.urlopen( "POST", @@ -2448,8 +2448,8 @@ def _get_severity_score(event: Event) -> tuple[float, str]: except MaxRetryError as e: logger.warning( "Unable to get severity score from microservice after %s retr%s. Got MaxRetryError caused by: %s.", - SEVERITY_DETECTION_RETRIES, - "ies" if SEVERITY_DETECTION_RETRIES > 1 else "y", + SEER_SEVERITY_RETRIES, + "ies" if SEER_SEVERITY_RETRIES > 1 else "y", repr(e.reason), extra=logger_data, ) diff --git a/src/sentry/seer/utils.py b/src/sentry/seer/utils.py index 3842a02dcbb027..6e5b83089034ae 100644 --- a/src/sentry/seer/utils.py +++ b/src/sentry/seer/utils.py @@ -47,27 +47,27 @@ class BreakpointResponse(TypedDict): data: list[BreakpointData] -seer_connection_pool = connection_from_url( - settings.ANOMALY_DETECTION_URL, +seer_grouping_connection_pool = connection_from_url( + settings.SEER_GROUPING_URL, retries=Retry( total=5, status_forcelist=[408, 429, 502, 503, 504], ), - timeout=settings.ANOMALY_DETECTION_TIMEOUT, + timeout=settings.SEER_GROUPING_TIMEOUT, ) -seer_staging_connection_pool = connection_from_url( - settings.SEER_AUTOFIX_URL, +seer_breakpoint_connection_pool = connection_from_url( + settings.SEER_BREAKPOINT_DETECTION_URL, retries=Retry( total=5, status_forcelist=[408, 429, 502, 503, 504], ), - timeout=settings.ANOMALY_DETECTION_TIMEOUT, + timeout=settings.SEER_BREAKPOINT_DETECTION_TIMEOUT, ) def detect_breakpoints(breakpoint_request) -> BreakpointResponse: - response = seer_connection_pool.urlopen( + response = seer_breakpoint_connection_pool.urlopen( "POST", "/trends/breakpoint-detector", body=json.dumps(breakpoint_request), @@ -178,7 +178,7 @@ def get_similar_issues_embeddings( similar_issues_request: SimilarIssuesEmbeddingsRequest, ) -> list[SeerSimilarIssueData]: """Request similar issues data from seer and normalize the results.""" - response = seer_staging_connection_pool.urlopen( + response = seer_grouping_connection_pool.urlopen( "POST", SEER_SIMILAR_ISSUES_URL, body=json.dumps(similar_issues_request), diff --git a/tests/sentry/api/endpoints/test_group_similar_issues_embeddings.py b/tests/sentry/api/endpoints/test_group_similar_issues_embeddings.py index c02c59c2a1ae5c..bba58fe4c7c401 100644 --- a/tests/sentry/api/endpoints/test_group_similar_issues_embeddings.py +++ b/tests/sentry/api/endpoints/test_group_similar_issues_embeddings.py @@ -695,7 +695,7 @@ def test_no_feature_flag(self): # TODO: Remove once switch is complete @with_feature("projects:similarity-embeddings") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") @mock.patch("sentry.api.endpoints.group_similar_issues_embeddings.logger") def test_simple_only_group_id_returned(self, mock_logger, mock_seer_request): seer_return_value: SimilarIssuesEmbeddingsResponse = { @@ -742,7 +742,7 @@ def test_simple_only_group_id_returned(self, mock_logger, mock_seer_request): ) @with_feature("projects:similarity-embeddings") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") @mock.patch("sentry.api.endpoints.group_similar_issues_embeddings.logger") def test_simple_only_hash_returned(self, mock_logger, mock_seer_request): seer_return_value: SimilarIssuesEmbeddingsResponse = { @@ -790,7 +790,7 @@ def test_simple_only_hash_returned(self, mock_logger, mock_seer_request): # TODO: Remove once switch is complete @with_feature("projects:similarity-embeddings") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") @mock.patch("sentry.api.endpoints.group_similar_issues_embeddings.logger") def test_simple_group_id_and_hash_returned(self, mock_logger, mock_seer_request): seer_return_value: SimilarIssuesEmbeddingsResponse = { @@ -839,7 +839,7 @@ def test_simple_group_id_and_hash_returned(self, mock_logger, mock_seer_request) @with_feature("projects:similarity-embeddings") @mock.patch("sentry.analytics.record") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_multiple(self, mock_seer_request, mock_record): over_threshold_group_event = save_new_event({"message": "Maisey is silly"}, self.project) under_threshold_group_event = save_new_event({"message": "Charlie is goofy"}, self.project) @@ -899,7 +899,7 @@ def test_multiple(self, mock_seer_request, mock_record): @with_feature("projects:similarity-embeddings") @mock.patch("sentry.seer.utils.logger") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_incomplete_return_data(self, mock_seer_request, mock_logger): # Two suggested groups, one with valid data, one missing both parent group id and parent hash. # We should log the second and return the first. @@ -946,7 +946,7 @@ def test_incomplete_return_data(self, mock_seer_request, mock_logger): @with_feature("projects:similarity-embeddings") @mock.patch("sentry.seer.utils.logger") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_nonexistent_group(self, mock_seer_request, mock_logger): """ The seer API can return groups that do not exist if they have been deleted/merged. @@ -1000,7 +1000,7 @@ def test_nonexistent_group(self, mock_seer_request, mock_logger): @with_feature("projects:similarity-embeddings") @mock.patch("sentry.analytics.record") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_empty_seer_return(self, mock_seer_request, mock_record): mock_seer_request.return_value = HTTPResponse([]) response = self.client.get(self.path) @@ -1070,7 +1070,7 @@ def test_no_exception(self): assert response.data == [] @with_feature("projects:similarity-embeddings") - @mock.patch("sentry.seer.utils.seer_staging_connection_pool.urlopen") + @mock.patch("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_no_optional_params(self, mock_seer_request): """ Test that optional parameters, k and threshold, can not be included. diff --git a/tests/sentry/seer/test_utils.py b/tests/sentry/seer/test_utils.py index a6ef47c970e381..3e23bf6813421c 100644 --- a/tests/sentry/seer/test_utils.py +++ b/tests/sentry/seer/test_utils.py @@ -18,7 +18,7 @@ from sentry.utils.types import NonNone [email protected]("sentry.seer.utils.seer_connection_pool.urlopen") [email protected]("sentry.seer.utils.seer_breakpoint_connection_pool.urlopen") def test_detect_breakpoints(mock_urlopen): data = { "data": [ @@ -50,7 +50,7 @@ def test_detect_breakpoints(mock_urlopen): ], ) @mock.patch("sentry_sdk.capture_exception") [email protected]("sentry.seer.utils.seer_connection_pool.urlopen") [email protected]("sentry.seer.utils.seer_breakpoint_connection_pool.urlopen") def test_detect_breakpoints_errors(mock_urlopen, mock_capture_exception, body, status): mock_urlopen.return_value = HTTPResponse(body, status=status) @@ -60,7 +60,7 @@ def test_detect_breakpoints_errors(mock_urlopen, mock_capture_exception, body, s # TODO: Remove once switch is complete @django_db_all [email protected]("sentry.seer.utils.seer_staging_connection_pool.urlopen") [email protected]("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_simple_similar_issues_embeddings_only_group_id_returned( mock_seer_request, default_project ): @@ -89,7 +89,7 @@ def test_simple_similar_issues_embeddings_only_group_id_returned( @django_db_all [email protected]("sentry.seer.utils.seer_staging_connection_pool.urlopen") [email protected]("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_simple_similar_issues_embeddings_only_hash_returned(mock_seer_request, default_project): """Test that valid responses are decoded and returned.""" event = save_new_event({"message": "Dogs are great!"}, default_project) @@ -125,7 +125,7 @@ def test_simple_similar_issues_embeddings_only_hash_returned(mock_seer_request, # TODO: Remove once switch is complete @django_db_all [email protected]("sentry.seer.utils.seer_staging_connection_pool.urlopen") [email protected]("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_simple_similar_issues_embeddings_both_returned(mock_seer_request, default_project): """Test that valid responses are decoded and returned.""" event = save_new_event({"message": "Dogs are great!"}, default_project) @@ -154,7 +154,7 @@ def test_simple_similar_issues_embeddings_both_returned(mock_seer_request, defau @django_db_all [email protected]("sentry.seer.utils.seer_staging_connection_pool.urlopen") [email protected]("sentry.seer.utils.seer_grouping_connection_pool.urlopen") def test_empty_similar_issues_embeddings(mock_seer_request, default_project): """Test that empty responses are returned.""" event = save_new_event({"message": "Dogs are great!"}, default_project)
765034443370d2d9e3ff5f367b7d395cdab1e447
2021-04-09 19:37:24
Tony
fix(trace-view): Do not persist the absolute date (#25052)
false
Do not persist the absolute date (#25052)
fix
diff --git a/src/sentry/static/sentry/app/components/organizations/globalSelectionHeader/getParams.tsx b/src/sentry/static/sentry/app/components/organizations/globalSelectionHeader/getParams.tsx index 916835cf7f15ae..773f015191910a 100644 --- a/src/sentry/static/sentry/app/components/organizations/globalSelectionHeader/getParams.tsx +++ b/src/sentry/static/sentry/app/components/organizations/globalSelectionHeader/getParams.tsx @@ -129,6 +129,8 @@ type ParsedParams = { }; type InputParams = { + pageStart?: Date | ParamValue; + pageEnd?: Date | ParamValue; start?: Date | ParamValue; end?: Date | ParamValue; period?: ParamValue; @@ -140,6 +142,7 @@ type InputParams = { type GetParamsOptions = { allowEmptyPeriod?: boolean; allowAbsoluteDatetime?: boolean; + allowAbsolutePageDatetime?: boolean; defaultStatsPeriod?: string; }; export function getParams( @@ -147,16 +150,34 @@ export function getParams( { allowEmptyPeriod = false, allowAbsoluteDatetime = true, + allowAbsolutePageDatetime = false, defaultStatsPeriod = DEFAULT_STATS_PERIOD, }: GetParamsOptions = {} ): ParsedParams { - const {start, end, period, statsPeriod, utc, ...otherParams} = params; + const { + pageStart, + pageEnd, + start, + end, + period, + statsPeriod, + utc, + ...otherParams + } = params; // `statsPeriod` takes precedence for now let coercedPeriod = getStatsPeriodValue(statsPeriod) || getStatsPeriodValue(period); - const dateTimeStart = allowAbsoluteDatetime ? getDateTimeString(start) : null; - const dateTimeEnd = allowAbsoluteDatetime ? getDateTimeString(end) : null; + const dateTimeStart = allowAbsoluteDatetime + ? allowAbsolutePageDatetime + ? getDateTimeString(pageStart) ?? getDateTimeString(start) + : getDateTimeString(start) + : null; + const dateTimeEnd = allowAbsoluteDatetime + ? allowAbsolutePageDatetime + ? getDateTimeString(pageEnd) ?? getDateTimeString(end) + : getDateTimeString(end) + : null; if (!(dateTimeStart && dateTimeEnd)) { if (!coercedPeriod && !allowEmptyPeriod) { diff --git a/src/sentry/static/sentry/app/constants/globalSelectionHeader.tsx b/src/sentry/static/sentry/app/constants/globalSelectionHeader.tsx index 2b23eb98cc021a..3747f4f56836c7 100644 --- a/src/sentry/static/sentry/app/constants/globalSelectionHeader.tsx +++ b/src/sentry/static/sentry/app/constants/globalSelectionHeader.tsx @@ -7,6 +7,11 @@ export const URL_PARAM = { ENVIRONMENT: 'environment', }; +export const PAGE_URL_PARAM = { + PAGE_START: 'pageStart', + PAGE_END: 'pageEnd', +}; + export const DATE_TIME = { START: 'start', END: 'end', diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx b/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx index b5b08b0172a886..d9b2870b1b9289 100644 --- a/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx +++ b/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx @@ -63,9 +63,7 @@ type Props = { organization: Organization; params: Params; traceSlug: string; - start: string | undefined; - end: string | undefined; - statsPeriod: string | undefined; + dateSelected: boolean; isLoading: boolean; error: string | null; traces: TraceFullDetailed[] | null; @@ -509,9 +507,9 @@ class TraceDetailsContent extends React.Component<Props, State> { } renderContent() { - const {start, end, statsPeriod, isLoading, error, traces} = this.props; + const {dateSelected, isLoading, error, traces} = this.props; - if (!statsPeriod && (!start || !end)) { + if (!dateSelected) { return this.renderTraceRequiresDateRangeSelection(); } else if (isLoading) { return this.renderTraceLoading(); diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/index.tsx b/src/sentry/static/sentry/app/views/performance/traceDetails/index.tsx index fc6d9588171b42..a2c18fedc5f8e4 100644 --- a/src/sentry/static/sentry/app/views/performance/traceDetails/index.tsx +++ b/src/sentry/static/sentry/app/views/performance/traceDetails/index.tsx @@ -35,10 +35,13 @@ class TraceSummary extends React.Component<Props> { renderContent() { const {location, organization, params} = this.props; const traceSlug = this.getTraceSlug(); - const queryParams = getParams(location.query); + const queryParams = getParams(location.query, { + allowAbsolutePageDatetime: true, + }); const start = decodeScalar(queryParams.start); const end = decodeScalar(queryParams.end); const statsPeriod = decodeScalar(queryParams.statsPeriod); + const dateSelected = Boolean(statsPeriod || (start && end)); const content = ({ isLoading, @@ -54,16 +57,14 @@ class TraceSummary extends React.Component<Props> { organization={organization} params={params} traceSlug={traceSlug} - start={start} - end={end} - statsPeriod={statsPeriod} + dateSelected={dateSelected} isLoading={isLoading} error={error} traces={traces} /> ); - if (!statsPeriod && (!start || !end)) { + if (!dateSelected) { return content({ isLoading: false, error: 'date selection not specified', diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/transactionDetail.tsx b/src/sentry/static/sentry/app/views/performance/traceDetails/transactionDetail.tsx index 624f97d9388cb6..174886fb47271a 100644 --- a/src/sentry/static/sentry/app/views/performance/traceDetails/transactionDetail.tsx +++ b/src/sentry/static/sentry/app/views/performance/traceDetails/transactionDetail.tsx @@ -1,13 +1,14 @@ import React from 'react'; import styled from '@emotion/styled'; import {Location} from 'history'; +import omit from 'lodash/omit'; import Alert from 'app/components/alert'; import Button from 'app/components/button'; import DateTime from 'app/components/dateTime'; import {getTraceDateTimeRange} from 'app/components/events/interfaces/spans/utils'; import Link from 'app/components/links/link'; -import {ALL_ACCESS_PROJECTS} from 'app/constants/globalSelectionHeader'; +import {ALL_ACCESS_PROJECTS, PAGE_URL_PARAM} from 'app/constants/globalSelectionHeader'; import {IconWarning} from 'app/icons'; import {t, tct} from 'app/locale'; import space from 'app/styles/space'; @@ -131,7 +132,7 @@ class TransactionDetail extends React.Component<Props> { organization, eventSlug, transaction.transaction, - location.query + omit(location.query, Object.values(PAGE_URL_PARAM)) ); return ( @@ -147,7 +148,7 @@ class TransactionDetail extends React.Component<Props> { const target = transactionSummaryRouteWithQuery({ orgSlug: organization.slug, transaction: transaction.transaction, - query: location.query, + query: omit(location.query, Object.values(PAGE_URL_PARAM)), projectID: String(transaction.project_id), }); diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/utils.tsx b/src/sentry/static/sentry/app/views/performance/traceDetails/utils.tsx index 9abc57ed8e6a20..a66a3adfff833a 100644 --- a/src/sentry/static/sentry/app/views/performance/traceDetails/utils.tsx +++ b/src/sentry/static/sentry/app/views/performance/traceDetails/utils.tsx @@ -1,5 +1,6 @@ import {LocationDescriptor, Query} from 'history'; +import {PAGE_URL_PARAM} from 'app/constants/globalSelectionHeader'; import {OrganizationSummary} from 'app/types'; import {TraceFullDetailed} from 'app/utils/performance/quickTrace/types'; import {reduceTrace} from 'app/utils/performance/quickTrace/utils'; @@ -12,9 +13,15 @@ export function getTraceDetailsUrl( dateSelection, query: Query ): LocationDescriptor { + const {start, end, statsPeriod} = dateSelection; return { pathname: `/organizations/${organization.slug}/performance/trace/${traceSlug}/`, - query: {...query, ...dateSelection}, + query: { + ...query, + statsPeriod, + [PAGE_URL_PARAM.PAGE_START]: start, + [PAGE_URL_PARAM.PAGE_END]: end, + }, }; } diff --git a/tests/js/spec/components/organizations/getParams.spec.jsx b/tests/js/spec/components/organizations/getParams.spec.jsx index a8486dd6cfae90..b63f1f4756e159 100644 --- a/tests/js/spec/components/organizations/getParams.spec.jsx +++ b/tests/js/spec/components/organizations/getParams.spec.jsx @@ -129,6 +129,20 @@ describe('getParams', function () { ).toEqual({statsPeriod: '14d'}); }); + it('should use pageStart and pageEnd to override start and end', function () { + expect( + getParams( + { + pageStart: '2021-10-23T04:28:49+0000', + pageEnd: '2021-10-26T02:56:17+0000', + start: '2019-10-23T04:28:49+0000', + end: '2019-10-26T02:56:17+0000', + }, + {allowAbsolutePageDatetime: true} + ) + ).toEqual({start: '2021-10-23T04:28:49.000', end: '2021-10-26T02:56:17.000'}); + }); + it('does not return default statsPeriod if `allowEmptyPeriod` option is passed', function () { expect(getParams({}, {allowEmptyPeriod: true})).toEqual({}); });
5e45dbc028c69e85502394efa452adf5220c44b2
2023-09-20 22:20:01
Abdkhan14
feat(trace-view-load-more): Added ui for loading longer traces. (#56476)
false
Added ui for loading longer traces. (#56476)
feat
diff --git a/static/app/utils/performance/quickTrace/traceFullQuery.tsx b/static/app/utils/performance/quickTrace/traceFullQuery.tsx index ee0728d9a9bd38..ffcb0b2ab1d532 100644 --- a/static/app/utils/performance/quickTrace/traceFullQuery.tsx +++ b/static/app/utils/performance/quickTrace/traceFullQuery.tsx @@ -19,6 +19,7 @@ import { type AdditionalQueryProps = { detailed?: boolean; eventId?: string; + limit?: number; }; type TraceFullQueryChildrenProps<T> = BaseTraceChildrenProps & @@ -38,6 +39,7 @@ type QueryProps<T> = Omit<TraceRequestProps, 'eventView'> & function getTraceFullRequestPayload({ detailed, eventId, + limit, ...props }: DiscoverQueryProps & AdditionalQueryProps) { const additionalApiPayload: any = getTraceRequestPayload(props); @@ -45,6 +47,11 @@ function getTraceFullRequestPayload({ if (eventId) { additionalApiPayload.event_id = eventId; } + + if (limit) { + additionalApiPayload.limit = limit; + } + return additionalApiPayload; } diff --git a/static/app/views/performance/traceDetails/content.tsx b/static/app/views/performance/traceDetails/content.tsx index f491986f2a286e..5c4d40035456da 100644 --- a/static/app/views/performance/traceDetails/content.tsx +++ b/static/app/views/performance/traceDetails/content.tsx @@ -51,6 +51,7 @@ type Props = Pick<RouteComponentProps<{traceSlug: string}, {}>, 'params' | 'loca traceEventView: EventView; traceSlug: string; traces: TraceFullDetailed[] | null; + handleLimitChange?: (newLimit: number) => void; orphanErrors?: TraceError[]; }; @@ -132,7 +133,12 @@ class TraceDetailsContent extends Component<Props, State> { } renderTraceLoading() { - return <LoadingIndicator />; + return ( + <LoadingContainer> + <StyledLoadingIndicator /> + {t('Hang in there, as we build your trace view!')} + </LoadingContainer> + ); } renderTraceRequiresDateRangeSelection() { @@ -367,6 +373,7 @@ class TraceDetailsContent extends Component<Props, State> { traces={traces || []} meta={meta} orphanErrors={orphanErrors || []} + handleLimitChange={this.props.handleLimitChange} /> </VisuallyCompleteWithData> </Margin> @@ -414,6 +421,16 @@ class TraceDetailsContent extends Component<Props, State> { } } +const StyledLoadingIndicator = styled(LoadingIndicator)` + margin-bottom: 0; +`; + +const LoadingContainer = styled('div')` + font-size: ${p => p.theme.fontSizeLarge}; + color: ${p => p.theme.subText}; + text-align: center; +`; + const Margin = styled('div')` margin-top: ${space(2)}; `; diff --git a/static/app/views/performance/traceDetails/index.tsx b/static/app/views/performance/traceDetails/index.tsx index 0036eb4083c230..2525ba4c3ec461 100644 --- a/static/app/views/performance/traceDetails/index.tsx +++ b/static/app/views/performance/traceDetails/index.tsx @@ -23,6 +23,7 @@ import withApi from 'sentry/utils/withApi'; import withOrganization from 'sentry/utils/withOrganization'; import TraceDetailsContent from './content'; +import {DEFAULT_TRACE_ROWS_LIMIT} from './limitExceededMessage'; import {getTraceSplitResults} from './utils'; type Props = RouteComponentProps<{traceSlug: string}, {}> & { @@ -30,7 +31,27 @@ type Props = RouteComponentProps<{traceSlug: string}, {}> & { organization: Organization; }; +type State = { + limit: number; +}; + class TraceSummary extends Component<Props> { + state: State = { + limit: DEFAULT_TRACE_ROWS_LIMIT, + }; + + componentDidMount(): void { + const {query} = this.props.location; + + if (query.limit) { + this.setState({limit: query.limit}); + } + } + + handleLimitChange = (newLimit: number) => { + this.setState({limit: newLimit}); + }; + getDocumentTitle(): string { return [t('Trace Details'), t('Performance')].join(' — '); } @@ -104,6 +125,7 @@ class TraceSummary extends Component<Props> { orphanErrors={orphanErrors} traces={transactions ?? (traces as TraceFullDetailed[])} meta={meta} + handleLimitChange={this.handleLimitChange} /> ); }; @@ -125,6 +147,7 @@ class TraceSummary extends Component<Props> { start={start} end={end} statsPeriod={statsPeriod} + limit={this.state.limit} > {traceResults => ( <TraceMetaQuery diff --git a/static/app/views/performance/traceDetails/limitExceededMessage.tsx b/static/app/views/performance/traceDetails/limitExceededMessage.tsx index 48d719b9aefac6..0bcb14f940fbe0 100644 --- a/static/app/views/performance/traceDetails/limitExceededMessage.tsx +++ b/static/app/views/performance/traceDetails/limitExceededMessage.tsx @@ -1,3 +1,7 @@ +import {browserHistory} from 'react-router'; +import styled from '@emotion/styled'; + +import {Button} from 'sentry/components/button'; import DiscoverFeature from 'sentry/components/discover/discoverFeature'; import Link from 'sentry/components/links/link'; import {MessageRow} from 'sentry/components/performance/waterfall/messageRow'; @@ -5,6 +9,7 @@ import {t, tct} from 'sentry/locale'; import {Organization} from 'sentry/types'; import EventView from 'sentry/utils/discover/eventView'; import {TraceMeta} from 'sentry/utils/performance/quickTrace/types'; +import {useLocation} from 'sentry/utils/useLocation'; import {TraceInfo} from 'sentry/views/performance/traceDetails/types'; interface LimitExceededMessageProps { @@ -12,15 +17,22 @@ interface LimitExceededMessageProps { organization: Organization; traceEventView: EventView; traceInfo: TraceInfo; + handleLimitChange?: (newLimit: number) => void; } + +const MAX_TRACE_ROWS_LIMIT = 2000; +export const DEFAULT_TRACE_ROWS_LIMIT = 100; + function LimitExceededMessage({ traceInfo, traceEventView, organization, meta, + handleLimitChange, }: LimitExceededMessageProps) { const count = traceInfo.transactions.size + traceInfo.errors.size; const totalEvents = (meta && meta.transactions + meta.errors) ?? count; + const location = useLocation(); if (totalEvents === null || count >= totalEvents) { return null; @@ -28,22 +40,65 @@ function LimitExceededMessage({ const target = traceEventView.getResultsViewUrlTarget(organization.slug); + // Increment by by multiples of 500. + const increment = count <= 100 ? 400 : 500; + const currentLimit = location.query.limit + ? Number(location.query.limit) + : DEFAULT_TRACE_ROWS_LIMIT; // TODO Abdullah Khan: Use count when extra orphan row bug is fixed. + + const discoverLink = ( + <DiscoverFeature> + {({hasFeature}) => ( + <StyledLink disabled={!hasFeature} to={target}> + {t('open in Discover')} + </StyledLink> + )} + </DiscoverFeature> + ); + + const limitExceededMessage = tct( + 'Limited to a view of [count] rows. To view the full list, [discover].', + { + count, + discover: discoverLink, + } + ); + + const loadBiggerTraceMessage = tct( + 'Click [loadMore:here] to build a view with more rows or to view the full list, [discover].', + { + loadMore: ( + <Button + priority="link" + onClick={() => { + const newLimit = currentLimit + increment; + if (handleLimitChange) { + handleLimitChange(newLimit); + } + browserHistory.push({ + pathname: location.pathname, + query: {...location.query, limit: newLimit}, + }); + }} + aria-label={t('Load more')} + /> + ), + discover: discoverLink, + } + ); + return ( <MessageRow> - {tct('Limited to a view of [count] rows. To view the full list, [discover].', { - count, - discover: ( - <DiscoverFeature> - {({hasFeature}) => ( - <Link disabled={!hasFeature} to={target}> - {t('Open in Discover')} - </Link> - )} - </DiscoverFeature> - ), - })} + {organization.features.includes('trace-view-load-more') && + count < MAX_TRACE_ROWS_LIMIT + ? loadBiggerTraceMessage + : limitExceededMessage} </MessageRow> ); } +const StyledLink = styled(Link)` + margin-left: 0; +`; + export default LimitExceededMessage; diff --git a/static/app/views/performance/traceDetails/traceView.tsx b/static/app/views/performance/traceDetails/traceView.tsx index 96323b1ebdb3a4..550993000f82ed 100644 --- a/static/app/views/performance/traceDetails/traceView.tsx +++ b/static/app/views/performance/traceDetails/traceView.tsx @@ -58,6 +58,7 @@ type Props = Pick<RouteComponentProps<{}, {}>, 'location'> & { traceSlug: string; traces: TraceFullDetailed[]; filteredEventIds?: Set<string>; + handleLimitChange?: (newLimit: number) => void; orphanErrors?: TraceError[]; traceInfo?: TraceInfo; }; @@ -139,6 +140,7 @@ export default function TraceView({ traceEventView, filteredEventIds, orphanErrors, + handleLimitChange, ...props }: Props) { const sentryTransaction = Sentry.getCurrentHub().getScope()?.getTransaction(); @@ -454,6 +456,7 @@ export default function TraceView({ organization={organization} traceEventView={traceEventView} meta={meta} + handleLimitChange={handleLimitChange} /> </TraceViewContainer> </StyledTracePanel> diff --git a/static/app/views/performance/traceDetails/utils.tsx b/static/app/views/performance/traceDetails/utils.tsx index a694065b4c2ef7..37a119af374eb3 100644 --- a/static/app/views/performance/traceDetails/utils.tsx +++ b/static/app/views/performance/traceDetails/utils.tsx @@ -11,6 +11,7 @@ import { } from 'sentry/utils/performance/quickTrace/types'; import {isTraceSplitResult, reduceTrace} from 'sentry/utils/performance/quickTrace/utils'; +import {DEFAULT_TRACE_ROWS_LIMIT} from './limitExceededMessage'; import {TraceInfo} from './types'; export function getTraceDetailsUrl( @@ -20,14 +21,21 @@ export function getTraceDetailsUrl( query: Query ): LocationDescriptor { const {start, end, statsPeriod} = dateSelection; + + const queryParams = { + ...query, + statsPeriod, + [PAGE_URL_PARAM.PAGE_START]: start, + [PAGE_URL_PARAM.PAGE_END]: end, + }; + + if (organization.features.includes('trace-view-load-more')) { + queryParams.limit = DEFAULT_TRACE_ROWS_LIMIT; + } + return { pathname: `/organizations/${organization.slug}/performance/trace/${traceSlug}/`, - query: { - ...query, - statsPeriod, - [PAGE_URL_PARAM.PAGE_START]: start, - [PAGE_URL_PARAM.PAGE_END]: end, - }, + query: queryParams, }; }
c8cd8ea0d1bc8ed196ad690b3ea9c372b6ef82d0
2021-03-24 02:33:17
MeredithAnya
ref(stacktrace-link): GA stacktrace link to am1 plans (#24398)
false
GA stacktrace link to am1 plans (#24398)
ref
diff --git a/src/sentry/api/endpoints/project_repo_path_parsing.py b/src/sentry/api/endpoints/project_repo_path_parsing.py index f2a850719e3be8..4a1df502093499 100644 --- a/src/sentry/api/endpoints/project_repo_path_parsing.py +++ b/src/sentry/api/endpoints/project_repo_path_parsing.py @@ -3,6 +3,7 @@ from sentry import integrations from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers.rest_framework.base import CamelSnakeSerializer +from sentry.integrations import IntegrationFeatures from sentry.models import Integration, Repository from sentry.utils.compat import filter, map @@ -40,8 +41,9 @@ def __init__(self, *args, **kwargs): @property def providers(self): - # TODO: use feature flag in the future - providers = filter(lambda x: x.has_stacktrace_linking, list(integrations.all())) + providers = filter( + lambda x: x.has_feature(IntegrationFeatures.STACKTRACE_LINK), list(integrations.all()) + ) return map(lambda x: x.key, providers) @property diff --git a/src/sentry/api/endpoints/project_stacktrace_link.py b/src/sentry/api/endpoints/project_stacktrace_link.py index 41547496fc08d4..e2572c11bc4811 100644 --- a/src/sentry/api/endpoints/project_stacktrace_link.py +++ b/src/sentry/api/endpoints/project_stacktrace_link.py @@ -2,6 +2,7 @@ from sentry import analytics from sentry.api.bases.project import ProjectEndpoint +from sentry.integrations import IntegrationFeatures from sentry.models import Integration, RepositoryProjectPathConfig from sentry.api.serializers import serialize from sentry.utils.compat import filter @@ -51,7 +52,9 @@ def get(self, request, project): # no longer feature gated and is added as an IntegrationFeature result["integrations"] = [ serialize(i, request.user) - for i in filter(lambda i: i.get_provider().has_stacktrace_linking, integrations) + for i in filter( + lambda i: i.has_feature(IntegrationFeatures.STACKTRACE_LINK), integrations + ) ] # xxx(meredith): if there are ever any changes to this query, make diff --git a/src/sentry/api/serializers/models/integration.py b/src/sentry/api/serializers/models/integration.py index 252538209f7abc..f77a97fcc30129 100644 --- a/src/sentry/api/serializers/models/integration.py +++ b/src/sentry/api/serializers/models/integration.py @@ -1,7 +1,6 @@ import logging from collections import defaultdict -from sentry import features from sentry.api.serializers import Serializer, register, serialize from sentry.models import ( ExternalIssue, @@ -130,7 +129,7 @@ def serialize(self, obj, attrs, user, organization): metadata = obj.metadata metadata = metadata and metadata._asdict() or None - output = { + return { "key": obj.key, "slug": obj.key, "name": obj.name, @@ -144,17 +143,6 @@ def serialize(self, obj, attrs, user, organization): ), } - # until we GA the stack trace linking feature to everyone it's easier to - # control whether we show the feature this way - if obj.has_stacktrace_linking: - feature_flag_name = "organizations:integrations-stacktrace-link" - has_stacktrace_linking = features.has(feature_flag_name, organization, actor=user) - if has_stacktrace_linking: - # only putting the field in if it's true to minimize test changes - output["hasStacktraceLinking"] = True - - return output - class IntegrationIssueConfigSerializer(IntegrationSerializer): def __init__(self, group, action, params=None): diff --git a/src/sentry/integrations/base.py b/src/sentry/integrations/base.py index b1bb32ce12139d..23dc29e0b8949f 100644 --- a/src/sentry/integrations/base.py +++ b/src/sentry/integrations/base.py @@ -96,6 +96,7 @@ class IntegrationFeatures(Enum): MOBILE = "mobile" SERVERLESS = "serverless" TICKET_RULES = "ticket-rules" + STACKTRACE_LINK = "stacktrace-link" # features currently only existing on plugins: DATA_FORWARDING = "data-forwarding" @@ -162,10 +163,6 @@ class is just a descriptor for how that object functions, and what behavior # if this is hidden without the feature flag requires_feature_flag = False - # whether this integration can be used for stacktrace linking - # will eventually be replaced with a feature flag - has_stacktrace_linking = False - @classmethod def get_installation(cls, model, organization_id, **kwargs): if cls.integration_cls is None: diff --git a/src/sentry/integrations/example/integration.py b/src/sentry/integrations/example/integration.py index 2475f57d5bdee8..6d9711a97c3db4 100644 --- a/src/sentry/integrations/example/integration.py +++ b/src/sentry/integrations/example/integration.py @@ -158,9 +158,14 @@ class ExampleIntegrationProvider(IntegrationProvider): metadata = metadata integration_cls = ExampleIntegration - has_stacktrace_linking = True - features = frozenset([IntegrationFeatures.COMMITS, IntegrationFeatures.ISSUE_BASIC]) + features = frozenset( + [ + IntegrationFeatures.COMMITS, + IntegrationFeatures.ISSUE_BASIC, + IntegrationFeatures.STACKTRACE_LINK, + ] + ) def get_pipeline_views(self): return [ExampleSetupView()] diff --git a/src/sentry/integrations/github/integration.py b/src/sentry/integrations/github/integration.py index 4ebe0ae2f89003..dd595700d479c0 100644 --- a/src/sentry/integrations/github/integration.py +++ b/src/sentry/integrations/github/integration.py @@ -48,6 +48,13 @@ """, IntegrationFeatures.ISSUE_BASIC, ), + FeatureDescription( + """ + Link your Sentry stack traces back to your GitHub source code with stack + trace linking. + """, + IntegrationFeatures.STACKTRACE_LINK, + ), ] @@ -147,10 +154,15 @@ class GitHubIntegrationProvider(IntegrationProvider): name = "GitHub" metadata = metadata integration_cls = GitHubIntegration - features = frozenset([IntegrationFeatures.COMMITS, IntegrationFeatures.ISSUE_BASIC]) + features = frozenset( + [ + IntegrationFeatures.COMMITS, + IntegrationFeatures.ISSUE_BASIC, + IntegrationFeatures.STACKTRACE_LINK, + ] + ) setup_dialog_config = {"width": 1030, "height": 1000} - has_stacktrace_linking = True def post_install(self, integration, organization, extra=None): repo_ids = Repository.objects.filter( diff --git a/src/sentry/integrations/github_enterprise/integration.py b/src/sentry/integrations/github_enterprise/integration.py index 79a89c7d4715b2..c1f902a52aa023 100644 --- a/src/sentry/integrations/github_enterprise/integration.py +++ b/src/sentry/integrations/github_enterprise/integration.py @@ -254,7 +254,7 @@ class GitHubEnterpriseIntegrationProvider(GitHubIntegrationProvider): name = "GitHub Enterprise" metadata = metadata integration_cls = GitHubEnterpriseIntegration - has_stacktrace_linking = False + features = frozenset([IntegrationFeatures.COMMITS, IntegrationFeatures.ISSUE_BASIC]) def _make_identity_pipeline_view(self): """ diff --git a/src/sentry/integrations/gitlab/integration.py b/src/sentry/integrations/gitlab/integration.py index 569011751c5ba9..db39b8aa4afd62 100644 --- a/src/sentry/integrations/gitlab/integration.py +++ b/src/sentry/integrations/gitlab/integration.py @@ -54,6 +54,13 @@ """, IntegrationFeatures.ISSUE_BASIC, ), + FeatureDescription( + """ + Link your Sentry stack traces back to your GitLab source code with stack + trace linking. + """, + IntegrationFeatures.STACKTRACE_LINK, + ), ] metadata = IntegrationMetadata( @@ -246,9 +253,14 @@ class GitlabIntegrationProvider(IntegrationProvider): integration_cls = GitlabIntegration needs_default_identity = True - has_stacktrace_linking = True - features = frozenset([IntegrationFeatures.ISSUE_BASIC, IntegrationFeatures.COMMITS]) + features = frozenset( + [ + IntegrationFeatures.ISSUE_BASIC, + IntegrationFeatures.COMMITS, + IntegrationFeatures.STACKTRACE_LINK, + ] + ) setup_dialog_config = {"width": 1030, "height": 1000} diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx index f47faf12d4d993..e041d5ebeb65d1 100644 --- a/src/sentry/static/sentry/app/types/index.tsx +++ b/src/sentry/static/sentry/app/types/index.tsx @@ -1158,7 +1158,6 @@ export type IntegrationProvider = BaseIntegrationProvider & { source_url: string; aspects: IntegrationAspects; }; - hasStacktraceLinking?: boolean; // TODO: Remove when we GA the feature }; export type IntegrationFeature = { diff --git a/src/sentry/static/sentry/app/views/settings/organizationIntegrations/configureIntegration.tsx b/src/sentry/static/sentry/app/views/settings/organizationIntegrations/configureIntegration.tsx index ebbd85ee9023b3..ff5468bd5beae5 100644 --- a/src/sentry/static/sentry/app/views/settings/organizationIntegrations/configureIntegration.tsx +++ b/src/sentry/static/sentry/app/views/settings/organizationIntegrations/configureIntegration.tsx @@ -78,7 +78,10 @@ class ConfigureIntegration extends AsyncView<Props, State> { } hasStacktraceLinking(provider: IntegrationProvider) { - return !!provider.hasStacktraceLinking; + return ( + provider.features.includes('stacktrace-link') && + this.props.organization.features.includes('integrations-stacktrace-link') + ); } onTabChange = (value: Tab) => { diff --git a/tests/sentry/api/endpoints/test_organization_integration_repository_project_path_configs.py b/tests/sentry/api/endpoints/test_organization_integration_repository_project_path_configs.py index 0329d37aa7a8af..97d58415e99a4c 100644 --- a/tests/sentry/api/endpoints/test_organization_integration_repository_project_path_configs.py +++ b/tests/sentry/api/endpoints/test_organization_integration_repository_project_path_configs.py @@ -66,7 +66,7 @@ def test_basic_get_with_integrationId(self): "repoName": self.repo1.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "GitHub", "canDisable": False, "key": "github", @@ -87,7 +87,7 @@ def test_basic_get_with_integrationId(self): "repoName": self.repo1.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "GitHub", "canDisable": False, "key": "github", @@ -123,7 +123,7 @@ def test_basic_get_with_projectId(self): "repoName": self.repo1.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "GitHub", "canDisable": False, "key": "github", @@ -185,7 +185,7 @@ def test_basic_post_with_valid_integrationId(self): "repoName": self.repo1.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "GitHub", "canDisable": False, "key": "github", diff --git a/tests/sentry/api/endpoints/test_project_stacktrace_link.py b/tests/sentry/api/endpoints/test_project_stacktrace_link.py index bd5e65acb01b49..5aeb0c11baffe2 100644 --- a/tests/sentry/api/endpoints/test_project_stacktrace_link.py +++ b/tests/sentry/api/endpoints/test_project_stacktrace_link.py @@ -86,7 +86,7 @@ def test_file_not_found_error(self): "repoName": self.repo.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "Example", "canDisable": False, "key": "example", @@ -121,7 +121,7 @@ def test_stack_root_mismatch_error(self): "repoName": self.repo.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "Example", "canDisable": False, "key": "example", @@ -154,7 +154,7 @@ def test_config_and_source_url(self): "repoName": self.repo.name, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "Example", "canDisable": False, "key": "example", @@ -177,7 +177,7 @@ def _serialized_integration(self): "accountType": None, "provider": { "aspects": {}, - "features": ["commits", "issue-basic"], + "features": ["commits", "issue-basic", "stacktrace-link"], "name": "Example", "canDisable": False, "key": "example",
c50e7d1a634b732882e93a9faae7961bd7da8b84
2020-06-17 20:13:34
Burak Yigit Kaya
meta(codeowners): Add releases as the codeowner for release action (#19404)
false
Add releases as the codeowner for release action (#19404)
meta
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 69fc13e0d5c870..c63650189d5b48 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -29,9 +29,10 @@ /src/sentry/net/ @getsentry/security # Build & Releases -/docker @getsentry/releases -setup.py @getsentry/releases -setup.cfg @getsentry/releases +/.github/workflows/release.yml @getsentry/releases +/docker @getsentry/releases +setup.py @getsentry/releases +setup.cfg @getsentry/releases # TODO: owners-build (for travis / gha) requirements*.txt @getsentry/owners-python-build pyproject.toml @getsentry/owners-python-build
4064c2486613eded64b00ab46f38d7d1e1891efa
2025-03-13 15:09:56
ArthurKnaus
feat(laravel-insights): Add user option for new overview (#86882)
false
Add user option for new overview (#86882)
feat
diff --git a/src/sentry/users/api/endpoints/user_details.py b/src/sentry/users/api/endpoints/user_details.py index fe760dc4f525f9..6c8f5ef0ccdb13 100644 --- a/src/sentry/users/api/endpoints/user_details.py +++ b/src/sentry/users/api/endpoints/user_details.py @@ -39,6 +39,14 @@ TIMEZONE_CHOICES = get_timezone_choices() +def validate_prefers_specialized_project_overview(value: dict[str, bool] | None) -> None: + invalid_entries = [key for key, value_ in (value or {}).items() if not isinstance(value_, bool)] + if len(invalid_entries) > 0: + raise ValidationError( + f"The enabled values {', '.join(invalid_entries)} should be booleans." + ) + + def validate_quick_start_display(value: dict[str, int] | None) -> None: if value is not None: for display_value in value.values(): @@ -79,6 +87,12 @@ class UserOptionsSerializer(serializers.Serializer[UserOption]): required=False, ) prefersIssueDetailsStreamlinedUI = serializers.BooleanField(required=False) + prefersSpecializedProjectOverview = serializers.JSONField( + required=False, + allow_null=True, + validators=[validate_prefers_specialized_project_overview], + help_text="Tracks whether the user prefers the new specialized project overview experience (dict of project ids to booleans)", + ) prefersStackedNavigation = serializers.BooleanField(required=False) quickStartDisplay = serializers.JSONField( @@ -250,6 +264,7 @@ def put(self, request: Request, user: User) -> Response: "defaultIssueEvent": "default_issue_event", "clock24Hours": "clock_24_hours", "prefersIssueDetailsStreamlinedUI": "prefers_issue_details_streamlined_ui", + "prefersSpecializedProjectOverview": "prefers_specialized_project_overview", "prefersStackedNavigation": "prefers_stacked_navigation", "quickStartDisplay": "quick_start_display", } @@ -258,7 +273,7 @@ def put(self, request: Request, user: User) -> Response: for key in key_map: if key in options_result: - if key == "quickStartDisplay": + if key in ("quickStartDisplay", "prefersSpecializedProjectOverview"): current_value = UserOption.objects.get_value( user=user, key=key_map.get(key, key) ) diff --git a/src/sentry/users/api/serializers/user.py b/src/sentry/users/api/serializers/user.py index 0d651969ec2181..edd460b3b23600 100644 --- a/src/sentry/users/api/serializers/user.py +++ b/src/sentry/users/api/serializers/user.py @@ -66,6 +66,7 @@ class _UserOptions(TypedDict): timezone: str clock24Hours: bool prefersIssueDetailsStreamlinedUI: bool + prefersSpecializedProjectOverview: dict[str, bool] prefersStackedNavigation: bool quickStartDisplay: dict[str, int] @@ -200,6 +201,9 @@ def serialize( "prefersIssueDetailsStreamlinedUI": options.get( "prefers_issue_details_streamlined_ui", False ), + "prefersSpecializedProjectOverview": options.get( + "prefers_specialized_project_overview", {} + ), "prefersStackedNavigation": options.get("prefers_stacked_navigation", False), "quickStartDisplay": options.get("quick_start_display") or {}, } diff --git a/src/sentry/users/models/user_option.py b/src/sentry/users/models/user_option.py index 1dcdf3b6613736..68cab181d4473b 100644 --- a/src/sentry/users/models/user_option.py +++ b/src/sentry/users/models/user_option.py @@ -165,6 +165,8 @@ class UserOption(Model): - unused - prefers_issue_details_streamlined_ui - Whether the user prefers the new issue details experience (boolean) + - prefers_specialized_project_overview + - Whether the user prefers the new specialized project overview experience (dict of project ids to booleans) - prefers_stacked_navigation - Whether the user prefers the new stacked navigation experience (boolean) - quick_start_display diff --git a/tests/sentry/users/api/endpoints/test_user_details.py b/tests/sentry/users/api/endpoints/test_user_details.py index 47e6e09c139884..bbaca929e78f45 100644 --- a/tests/sentry/users/api/endpoints/test_user_details.py +++ b/tests/sentry/users/api/endpoints/test_user_details.py @@ -118,6 +118,7 @@ def test_simple(self): "clock24Hours": True, "extra": True, "prefersIssueDetailsStreamlinedUI": True, + "prefersSpecializedProjectOverview": {"2": True}, "prefersStackedNavigation": True, "quickStartDisplay": {self.organization.id: 1}, }, @@ -140,6 +141,12 @@ def test_simple(self): user=self.user, key="prefers_issue_details_streamlined_ui" ) assert UserOption.objects.get_value(user=self.user, key="prefers_stacked_navigation") + assert ( + UserOption.objects.get_value( + user=self.user, key="prefers_specialized_project_overview" + ).get("2") + is True + ) assert ( UserOption.objects.get_value(user=self.user, key="quick_start_display").get( str(self.organization.id) @@ -211,6 +218,42 @@ def test_cannot_change_username_to_non_verified(self): assert user.email == "[email protected]" assert user.username == "[email protected]" + def test_saving_specialized_project_overview_option(self): + self.get_success_response( + "me", + options={"prefersSpecializedProjectOverview": {"1": False, "2": False}}, + ) + + options = UserOption.objects.get_value( + user=self.user, key="prefers_specialized_project_overview" + ) + assert options.get("1") is False + assert options.get("2") is False + + # Test updating project 1 to True + self.get_success_response( + "me", + options={"prefersSpecializedProjectOverview": {"1": True}}, + ) + options = UserOption.objects.get_value( + user=self.user, key="prefers_specialized_project_overview" + ) + assert options.get("1") is True + # Project 2 should not be affected + assert options.get("2") is False + + # Enabled value is not a boolean + self.get_error_response( + "me", + options={"prefersSpecializedProjectOverview": {"1": "True"}}, + status_code=400, + ) + self.get_error_response( + "me", + options={"prefersSpecializedProjectOverview": {"1": 1}}, + status_code=400, + ) + def test_saving_quick_start_display_option(self): org1_id = str(self.organization.id) org2_id = str(self.create_organization().id)
5f830db52d77af2331c8437c48b5128653f97b99
2023-07-20 06:24:03
Evan Purkhiser
ref(ts): Convert organizationMembersWrapper.spec to tsx (#53241)
false
Convert organizationMembersWrapper.spec to tsx (#53241)
ref
null
a11a24eff4679abc30771d5fda4374e83e8fc6d0
2022-09-14 03:57:36
Evan Purkhiser
feat(perf-issues): Add n_plus_one to FieldKey.ISSUE_TYPE values (#38752)
false
Add n_plus_one to FieldKey.ISSUE_TYPE values (#38752)
feat
diff --git a/static/app/stores/tagStore.tsx b/static/app/stores/tagStore.tsx index f9ec22974858fe..12a00fc395089c 100644 --- a/static/app/stores/tagStore.tsx +++ b/static/app/stores/tagStore.tsx @@ -84,7 +84,7 @@ const storeConfig: TagStoreDefinition = { [FieldKey.ISSUE_TYPE]: { key: FieldKey.ISSUE_TYPE, name: 'Issue Type', - values: [], + values: ['performance_n_plus_one_db_queries'], predefined: true, }, [FieldKey.LAST_SEEN]: {
a8945183cc962ae360b6e32f6609f101b76668e4
2022-02-24 01:21:06
Taylan Gocmen
feat(ui): Alert wizard v3 (#31821)
false
Alert wizard v3 (#31821)
feat
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 78bab9e542d5f5..f644a195d11e48 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -928,6 +928,8 @@ def create_partitioned_queues(name): "organizations:alert-rule-ui-component": False, # Enable issue alert status page "organizations:alert-rule-status-page": False, + # Alert wizard redesign version 3 + "organizations:alert-wizard-v3": False, "organizations:api-keys": False, # Enable multiple Apple app-store-connect sources per project. "organizations:app-store-connect-multiple": False, diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index c5905d198fc6c0..e22594a1615c1a 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -55,6 +55,7 @@ default_manager.add("organizations:alert-filters", OrganizationFeature) default_manager.add("organizations:alert-rule-ui-component", OrganizationFeature, True) default_manager.add("organizations:alert-rule-status-page", OrganizationFeature, True) +default_manager.add("organizations:alert-wizard-v3", OrganizationFeature, True) default_manager.add("organizations:api-keys", OrganizationFeature) default_manager.add("organizations:app-store-connect-multiple", OrganizationFeature, False) default_manager.add("organizations:boolean-search", OrganizationFeature) diff --git a/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx b/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx index dc02c66381ea76..bd610db10668a5 100644 --- a/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx +++ b/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx @@ -1,4 +1,5 @@ import * as React from 'react'; +import {Fragment} from 'react'; import styled from '@emotion/styled'; import pick from 'lodash/pick'; @@ -52,6 +53,7 @@ type Props = { comparisonType: AlertRuleComparisonType; dataset: Dataset; disabled: boolean; + hasAlertWizardV3: boolean; onComparisonDeltaChange: (value: number) => void; onComparisonTypeChange: (value: AlertRuleComparisonType) => void; onFilterSearch: (query: string) => void; @@ -139,19 +141,134 @@ class RuleConditionsForm extends React.PureComponent<Props, State> { return undefined; } - render() { + renderInterval() { const { organization, + dataset, disabled, - onFilterSearch, - allowChangeEventTypes, alertType, + hasAlertWizardV3, timeWindow, - comparisonType, comparisonDelta, + comparisonType, + onComparisonTypeChange, onTimeWindowChange, onComparisonDeltaChange, - onComparisonTypeChange, + } = this.props; + + const formElemBaseStyle = { + padding: `${space(0.5)}`, + border: 'none', + }; + + const {labelText, timeWindowText} = getFunctionHelpText(alertType); + const intervalLabelText = hasAlertWizardV3 ? t('Define your metric') : labelText; + + return ( + <Fragment> + {dataset !== Dataset.SESSIONS && ( + <Feature features={['organizations:change-alerts']} organization={organization}> + <StyledListItem>{t('Select threshold type')}</StyledListItem> + <FormRow> + <RadioGroup + style={{flex: 1}} + disabled={disabled} + choices={[ + [AlertRuleComparisonType.COUNT, 'Count'], + [AlertRuleComparisonType.CHANGE, 'Percent Change'], + ]} + value={comparisonType} + label={t('Threshold Type')} + onChange={onComparisonTypeChange} + /> + </FormRow> + </Feature> + )} + <StyledListItem> + <StyledListTitle> + <div>{intervalLabelText}</div> + <Tooltip + title={t( + 'Time window over which the metric is evaluated. Alerts are evaluated every minute regardless of this value.' + )} + > + <IconQuestion size="sm" color="gray200" /> + </Tooltip> + </StyledListTitle> + </StyledListItem> + <FormRow> + {timeWindowText && ( + <MetricField + name="aggregate" + help={null} + organization={organization} + disabled={disabled} + style={{ + ...formElemBaseStyle, + }} + inline={false} + flexibleControlStateSize + columnWidth={200} + alertType={alertType} + required + /> + )} + {timeWindowText && <FormRowText>{timeWindowText}</FormRowText>} + <SelectControl + name="timeWindow" + styles={{ + control: (provided: {[x: string]: string | number | boolean}) => ({ + ...provided, + minWidth: 130, + maxWidth: 300, + }), + }} + options={this.timeWindowOptions} + required + isDisabled={disabled} + value={timeWindow} + onChange={({value}) => onTimeWindowChange(value)} + inline={false} + flexibleControlStateSize + /> + <Feature features={['organizations:change-alerts']} organization={organization}> + {comparisonType === AlertRuleComparisonType.CHANGE && ( + <ComparisonContainer> + {t(' compared to ')} + <SelectControl + name="comparisonDelta" + styles={{ + container: (provided: {[x: string]: string | number | boolean}) => ({ + ...provided, + marginLeft: space(1), + }), + control: (provided: {[x: string]: string | number | boolean}) => ({ + ...provided, + minWidth: 500, + maxWidth: 1000, + }), + }} + value={comparisonDelta} + onChange={({value}) => onComparisonDeltaChange(value)} + options={COMPARISON_DELTA_OPTIONS} + required={comparisonType === AlertRuleComparisonType.CHANGE} + /> + </ComparisonContainer> + )} + </Feature> + </FormRow> + </Fragment> + ); + } + + render() { + const { + organization, + disabled, + onFilterSearch, + allowChangeEventTypes, + alertType, + hasAlertWizardV3, dataset, } = this.props; const {environments} = this.state; @@ -214,13 +331,12 @@ class RuleConditionsForm extends React.PureComponent<Props, State> { border: 'none', }; - const {labelText: intervalLabelText, timeWindowText} = getFunctionHelpText(alertType); - return ( <React.Fragment> <ChartPanel> <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody> </ChartPanel> + {hasAlertWizardV3 && this.renderInterval()} <StyledListItem>{t('Filter events')}</StyledListItem> <FormRow> <SelectField @@ -356,97 +472,7 @@ class RuleConditionsForm extends React.PureComponent<Props, State> { )} </FormField> </FormRow> - {dataset !== Dataset.SESSIONS && ( - <Feature features={['organizations:change-alerts']} organization={organization}> - <StyledListItem>{t('Select threshold type')}</StyledListItem> - <FormRow> - <RadioGroup - style={{flex: 1}} - disabled={disabled} - choices={[ - [AlertRuleComparisonType.COUNT, 'Count'], - [AlertRuleComparisonType.CHANGE, 'Percent Change'], - ]} - value={comparisonType} - label={t('Threshold Type')} - onChange={onComparisonTypeChange} - /> - </FormRow> - </Feature> - )} - <StyledListItem> - <StyledListTitle> - <div>{intervalLabelText}</div> - <Tooltip - title={t( - 'Time window over which the metric is evaluated. Alerts are evaluated every minute regardless of this value.' - )} - > - <IconQuestion size="sm" color="gray200" /> - </Tooltip> - </StyledListTitle> - </StyledListItem> - <FormRow> - {timeWindowText && ( - <MetricField - name="aggregate" - help={null} - organization={organization} - disabled={disabled} - style={{ - ...formElemBaseStyle, - }} - inline={false} - flexibleControlStateSize - columnWidth={200} - alertType={alertType} - required - /> - )} - {timeWindowText && <FormRowText>{timeWindowText}</FormRowText>} - <SelectControl - name="timeWindow" - styles={{ - control: (provided: {[x: string]: string | number | boolean}) => ({ - ...provided, - minWidth: 130, - maxWidth: 300, - }), - }} - options={this.timeWindowOptions} - required - isDisabled={disabled} - value={timeWindow} - onChange={({value}) => onTimeWindowChange(value)} - inline={false} - flexibleControlStateSize - /> - <Feature features={['organizations:change-alerts']} organization={organization}> - {comparisonType === AlertRuleComparisonType.CHANGE && ( - <ComparisonContainer> - {t(' compared to ')} - <SelectControl - name="comparisonDelta" - styles={{ - container: (provided: {[x: string]: string | number | boolean}) => ({ - ...provided, - marginLeft: space(1), - }), - control: (provided: {[x: string]: string | number | boolean}) => ({ - ...provided, - minWidth: 500, - maxWidth: 1000, - }), - }} - value={comparisonDelta} - onChange={({value}) => onComparisonDeltaChange(value)} - options={COMPARISON_DELTA_OPTIONS} - required={comparisonType === AlertRuleComparisonType.CHANGE} - /> - </ComparisonContainer> - )} - </Feature> - </FormRow> + {!hasAlertWizardV3 && this.renderInterval()} </React.Fragment> ); } diff --git a/static/app/views/alerts/incidentRules/ruleForm/index.tsx b/static/app/views/alerts/incidentRules/ruleForm/index.tsx index 64724783489b2b..b2674e88a3a874 100644 --- a/static/app/views/alerts/incidentRules/ruleForm/index.tsx +++ b/static/app/views/alerts/incidentRules/ruleForm/index.tsx @@ -719,8 +719,15 @@ class RuleFormContainer extends AsyncComponent<Props, State> { /> ); + const hasAlertWizardV3 = + Boolean(isCustomMetric) && organization.features.includes('alert-wizard-v3'); + const ruleNameOwnerForm = (hasAccess: boolean) => ( - <RuleNameOwnerForm disabled={!hasAccess || !canEdit} project={project} /> + <RuleNameOwnerForm + disabled={!hasAccess || !canEdit} + project={project} + hasAlertWizardV3={hasAlertWizardV3} + /> ); return ( @@ -775,6 +782,7 @@ class RuleFormContainer extends AsyncComponent<Props, State> { onFilterSearch={this.handleFilterUpdate} allowChangeEventTypes={isCustomMetric || dataset === Dataset.ERRORS} alertType={isCustomMetric ? 'custom' : alertType} + hasAlertWizardV3={hasAlertWizardV3} dataset={dataset} timeWindow={timeWindow} comparisonType={comparisonType} @@ -787,7 +795,6 @@ class RuleFormContainer extends AsyncComponent<Props, State> { /> <AlertListItem>{t('Set thresholds to trigger alert')}</AlertListItem> {triggerForm(hasAccess)} - <StyledListItem>{t('Add a rule name and team')}</StyledListItem> {ruleNameOwnerForm(hasAccess)} </List> </Form> diff --git a/static/app/views/alerts/incidentRules/ruleNameOwnerForm.tsx b/static/app/views/alerts/incidentRules/ruleNameOwnerForm.tsx index 6188a3866846fc..700ae51bc2fd55 100644 --- a/static/app/views/alerts/incidentRules/ruleNameOwnerForm.tsx +++ b/static/app/views/alerts/incidentRules/ruleNameOwnerForm.tsx @@ -1,61 +1,87 @@ -import {PureComponent} from 'react'; +import {Fragment} from 'react'; +import * as React from 'react'; +import styled from '@emotion/styled'; import FormField from 'sentry/components/forms/formField'; import TeamSelector from 'sentry/components/forms/teamSelector'; import TextField from 'sentry/components/forms/textField'; +import ListItem from 'sentry/components/list/listItem'; import {Panel, PanelBody} from 'sentry/components/panels'; import {t} from 'sentry/locale'; +import space from 'sentry/styles/space'; import {Project, Team} from 'sentry/types'; type Props = { disabled: boolean; + hasAlertWizardV3: boolean; project: Project; }; -class RuleNameOwnerForm extends PureComponent<Props> { - render() { - const {disabled, project} = this.props; - return ( - <Panel> - <PanelBody> - <TextField +export default function RuleNameOwnerForm({disabled, project, hasAlertWizardV3}: Props) { + const renderRuleName = () => ( + <TextField + disabled={disabled} + name="name" + label={t('Rule Name')} + help={t('Add a name so it’s easy to find later.')} + placeholder={t('Something really bad happened')} + required + /> + ); + + const renderTeamSelect = () => ( + <FormField + name="owner" + label={t('Team')} + help={t('The team that can edit this alert.')} + disabled={disabled} + > + {({model}) => { + const owner = model.getValue('owner'); + const ownerId = owner && owner.split(':')[1]; + return ( + <TeamSelector + value={ownerId} + project={project} + onChange={({value}) => { + const ownerValue = value && `team:${value}`; + model.setValue('owner', ownerValue); + }} + teamFilter={(team: Team) => team.isMember || team.id === ownerId} + useId + includeUnassigned disabled={disabled} - name="name" - label={t('Rule Name')} - help={t('Add a name so it’s easy to find later.')} - placeholder={t('Something really bad happened')} - required /> + ); + }} + </FormField> + ); - <FormField - name="owner" - label={t('Team')} - help={t('The team that can edit this alert.')} - disabled={disabled} - > - {({model}) => { - const owner = model.getValue('owner'); - const ownerId = owner && owner.split(':')[1]; - return ( - <TeamSelector - value={ownerId} - project={project} - onChange={({value}) => { - const ownerValue = value && `team:${value}`; - model.setValue('owner', ownerValue); - }} - teamFilter={(team: Team) => team.isMember || team.id === ownerId} - useId - includeUnassigned - disabled={disabled} - /> - ); - }} - </FormField> + return hasAlertWizardV3 ? ( + <Fragment> + <StyledListItem>{t('Add a name')}</StyledListItem> + <Panel> + <PanelBody>{renderRuleName()}</PanelBody> + </Panel> + <StyledListItem>{t('Assign this alert')}</StyledListItem> + <Panel> + <PanelBody>{renderTeamSelect()}</PanelBody> + </Panel> + </Fragment> + ) : ( + <Fragment> + <StyledListItem>{t('Add a rule name and team')}</StyledListItem> + <Panel> + <PanelBody> + {renderRuleName()} + {renderTeamSelect()} </PanelBody> </Panel> - ); - } + </Fragment> + ); } -export default RuleNameOwnerForm; +const StyledListItem = styled(ListItem)` + margin: ${space(2)} 0 ${space(1)} 0; + font-size: ${p => p.theme.fontSizeExtraLarge}; +`;
02cafe756953d73e27de32445d98a4c8014d0c71
2021-08-24 22:58:31
Leander Rodrigues
ref(ui): Add option to GlobalModal to prevent click outs from closing them (#28123)
false
Add option to GlobalModal to prevent click outs from closing them (#28123)
ref
diff --git a/static/app/components/globalModal/index.tsx b/static/app/components/globalModal/index.tsx index 702258b2404c53..6b7fe6174259c2 100644 --- a/static/app/components/globalModal/index.tsx +++ b/static/app/components/globalModal/index.tsx @@ -32,6 +32,12 @@ type ModalOptions = { * Set to true (the default) to show a translucent backdrop */ backdrop?: 'static' | boolean; + /** + * Set to `false` to disable the ability to click outside the modal to + * close it. This is useful for modals containing user input which will + * disappear on an accidental click. Defaults to `true`. + */ + allowClickClose?: boolean; }; type ModalRenderProps = { @@ -152,10 +158,13 @@ function GlobalModal({visible = false, options = {}, children, onClose}: Props) // Default to enabled backdrop const backdrop = options.backdrop ?? true; + // Default to enabled click close + const allowClickClose = options.allowClickClose ?? true; + // Only close when we directly click outside of the modal. const containerRef = React.useRef<HTMLDivElement>(null); const clickClose = (e: React.MouseEvent) => - containerRef.current === e.target && closeModal(); + containerRef.current === e.target && allowClickClose && closeModal(); return ReactDOM.createPortal( <React.Fragment> diff --git a/static/app/components/group/externalIssueActions.tsx b/static/app/components/group/externalIssueActions.tsx index 401ac77590cefe..c9de4b377d555f 100644 --- a/static/app/components/group/externalIssueActions.tsx +++ b/static/app/components/group/externalIssueActions.tsx @@ -65,9 +65,10 @@ const ExternalIssueActions = ({configurations, group, onChange, api}: Props) => }; const doOpenModal = (integration: GroupIntegration) => - openModal(deps => ( - <ExternalIssueForm {...deps} {...{group, onChange, integration}} /> - )); + openModal( + deps => <ExternalIssueForm {...deps} {...{group, onChange, integration}} />, + {allowClickClose: false} + ); return ( <Fragment> diff --git a/static/app/components/group/sentryAppExternalIssueActions.tsx b/static/app/components/group/sentryAppExternalIssueActions.tsx index d6454cf8cf27ac..4a887e5fc36275 100644 --- a/static/app/components/group/sentryAppExternalIssueActions.tsx +++ b/static/app/components/group/sentryAppExternalIssueActions.tsx @@ -69,13 +69,16 @@ class SentryAppExternalIssueActions extends React.Component<Props, State> { ); e?.preventDefault(); - openModal(deps => ( - <SentryAppExternalIssueModal - {...deps} - {...{group, event, sentryAppComponent, sentryAppInstallation}} - onSubmitSuccess={this.onSubmitSuccess} - /> - )); + openModal( + deps => ( + <SentryAppExternalIssueModal + {...deps} + {...{group, event, sentryAppComponent, sentryAppInstallation}} + onSubmitSuccess={this.onSubmitSuccess} + /> + ), + {allowClickClose: false} + ); }; deleteIssue = () => { diff --git a/static/app/views/organizationIntegrations/pluginDetailedView.tsx b/static/app/views/organizationIntegrations/pluginDetailedView.tsx index b708a8a5ef6250..4b7806cff4629b 100644 --- a/static/app/views/organizationIntegrations/pluginDetailedView.tsx +++ b/static/app/views/organizationIntegrations/pluginDetailedView.tsx @@ -116,7 +116,7 @@ class PluginDetailedView extends AbstractIntegrationDetailedView< }} /> ), - {} + {allowClickClose: false} ); }; diff --git a/tests/js/spec/components/globalModal.spec.jsx b/tests/js/spec/components/globalModal.spec.jsx index ec1f0d42b44c38..9368f8e4a8a590 100644 --- a/tests/js/spec/components/globalModal.spec.jsx +++ b/tests/js/spec/components/globalModal.spec.jsx @@ -66,4 +66,35 @@ describe('GlobalModal', function () { wrapper.update(); expect(closeSpy).toHaveBeenCalled(); }); + + it('calls ignores click out when the allowClickClose option is false', async function () { + const wrapper = mountWithTheme( + <div id="outside-test"> + <GlobalModal /> + </div> + ); + + openModal( + ({Header}) => ( + <div id="modal-test"> + <Header closeButton>Header</Header>Hi + </div> + ), + {allowClickClose: false} + ); + + await tick(); + wrapper.update(); + expect(wrapper.find('GlobalModal').prop('visible')).toBe(true); + + wrapper.find('#outside-test').simulate('click'); + await tick(); + wrapper.update(); + expect(wrapper.find('GlobalModal').prop('visible')).toBe(true); + + wrapper.find('CloseButton').simulate('click'); + await tick(); + wrapper.update(); + expect(wrapper.find('GlobalModal').prop('visible')).toBe(false); + }); });
131d1d8a1c034f3cf11362a380ea457ed4e04a87
2024-06-19 00:59:15
Benjamin E. Coe
fix(insights): updated empty-state copy for caches / queues (#72905)
false
updated empty-state copy for caches / queues (#72905)
fix
diff --git a/static/app/views/performance/cache/cacheLandingPage.spec.tsx b/static/app/views/performance/cache/cacheLandingPage.spec.tsx index 15a485366ef649..ae82abf273b490 100644 --- a/static/app/views/performance/cache/cacheLandingPage.spec.tsx +++ b/static/app/views/performance/cache/cacheLandingPage.spec.tsx @@ -239,7 +239,7 @@ describe('CacheLandingPage', function () { await waitForElementToBeRemoved(() => screen.queryAllByTestId('loading-indicator')); expect( - screen.getByText('Start collecting Insights about your Caches!') + screen.getByText('Make sure your application’s caching is behaving properly') ).toBeInTheDocument(); }); }); diff --git a/static/app/views/performance/cache/settings.ts b/static/app/views/performance/cache/settings.ts index ddc8469d317298..0bbabb3dd92a72 100644 --- a/static/app/views/performance/cache/settings.ts +++ b/static/app/views/performance/cache/settings.ts @@ -23,7 +23,7 @@ export const MODULE_DESCRIPTION = t( export const MODULE_DOC_LINK = 'https://docs.sentry.io/product/insights/caches/'; export const ONBOARDING_CONTENT = { - title: t('Start collecting Insights about your Caches!'), - description: t('Our robot is waiting to collect your first cache hit.'), + title: t('Make sure your application’s caching is behaving properly'), + description: t('We tell you if your application is hitting cache as often as expected and whether it’s delivering the anticipated performance improvements.'), link: MODULE_DOC_LINK, }; diff --git a/static/app/views/performance/onboarding/modulesOnboarding.tsx b/static/app/views/performance/onboarding/modulesOnboarding.tsx index b178bf95fbe2cc..fac443290b7e0e 100644 --- a/static/app/views/performance/onboarding/modulesOnboarding.tsx +++ b/static/app/views/performance/onboarding/modulesOnboarding.tsx @@ -54,13 +54,12 @@ function ModulesOnboardingPanel({children}: {children: React.ReactNode}) { } const PerfImage = styled('img')` - -webkit-transform: scaleX(-1); - transform: scaleX(-1); - width: 600px; + width: 260px; user-select: none; position: absolute; bottom: 0; right: 0; + padding-right: ${space(1)}; `; const Container = styled('div')` @@ -72,5 +71,6 @@ const Container = styled('div')` const ContentContainer = styled('div')` position: relative; + width: 70%; z-index: 1; `; diff --git a/static/app/views/performance/queues/settings.ts b/static/app/views/performance/queues/settings.ts index 8313d159954138..5bfc195dc5e18e 100644 --- a/static/app/views/performance/queues/settings.ts +++ b/static/app/views/performance/queues/settings.ts @@ -47,8 +47,8 @@ export const MODULE_DOC_LINK = 'https://docs.sentry.io/product/insights/queue-monitoring/'; export const ONBOARDING_CONTENT = { - title: t('Start collecting Insights about your Queues!'), - description: t('Our robot is waiting for your first background job to complete.'), + title: t('Make sure your jobs complete without errors'), + description: t('Track the behavior of background jobs at each step in their processing, allowing you to see whether jobs are completing on time and making it easy to debug when they are failing.'), link: MODULE_DOC_LINK, }; diff --git a/static/images/spot/performance-waiting-for-span.svg b/static/images/spot/performance-waiting-for-span.svg index 988485542201d3..d423a25a532188 100644 --- a/static/images/spot/performance-waiting-for-span.svg +++ b/static/images/spot/performance-waiting-for-span.svg @@ -1 +1,2 @@ -<svg id="Waiting_For_Events" data-name="Waiting For Events" xmlns="http://www.w3.org/2000/svg" width="646.4" height="147.3"><defs><style>.cls-1{fill:none;stroke:#3f2b56;stroke-linecap:round;stroke-linejoin:round}.cls-5{fill:#b39ed3}.cls-8{fill:#3f2b56}.cls-9{fill:#5e468c}</style></defs><path transform="matrix(1,0.1,-0.1,1,8.6,-17.7)" style="fill: #fca9cb" d="M 4.5 174.4 l 541.9 -3.6 l 23.6 -101.3 L -19.3 56.8 l 24 117.6 z"/><path d="M 245.8 97.4 v 6.4 c -0.6 15.6 -36.6 27.4 -115.6 30.2 c -45.5 1.6 -111.8 -7.5 -111.8 -22.5 V 105 s -2 -11 36 -18 c 38.4 -7 104.2 -13.3 149.4 -7 c 43.5 6.1 42 17.3 42 17.3 Z" style="fill: #e7e1ec"/><path transform="matrix(1,0,0,1,0,0)" class="cls-5" d="M 178.8 71.9 c 0.8 3.3 0.3 7.8 -1.5 13 l 10.1 7.9 l 1.2 1 l 0.2 0.6 l -2.3 11.2 l 3.2 0.5 l 5.4 -7.7 h 6.3 l 14 5.7 l 2.4 -2 l -9.2 -6.4 v -1.1 l 13.5 1.6 l 0.5 -3.7 l -13.2 -3 l 6.2 -2.2 l -0.5 -2.5 l -11.3 1.1 h -1 l -1.3 -0.8 l -22.7 -13.2 Z M 123.9 69.8 a 8.7 8.7 0 0 0 -8.8 -1.3 c -4.7 1.8 -6.1 6.7 -6.3 11.4 l -0.8 0.1 c -12.4 1 -26 2.5 -38.7 4.5 l -1 14.3 s 6 6 6.8 6.7 l 4.5 3.4 l -2 3.2 l -5.3 -2 a 31 31 0 0 1 -3.3 -2.4 l -2.4 1.9 v 9 l -3.9 0.4 l -1.7 -8.8 h -2.4 l -4.7 8.2 l -3.5 -0.4 l 1.8 -8.7 l -2 -0.5 l -8.7 3.7 l -1.1 -2.8 l 7 -4.3 l 3 -4 l 5 -16.9 l -22 -17.8 s -1.4 -1.1 -1.6 -3.5 c -0.2 -3.2 1.8 -4.6 1.8 -4.6 l 12.3 -10.9 l 14.4 9.6 c -1 -12 -6 -17 -6 -17 l 20.4 -17.9 l 10 5.7 c -0.9 -7.5 -3.9 -11.1 -3.9 -11.1 L 98.2 1.7 C 100 0 101.5 0.6 101.5 0.6 l 1.2 0.3 l 1.5 0.5 c 1.5 0.5 2.1 3 2.1 3 L 133 66.8"/><path class="cls-9" d="M 96.5 81 C 94 58 84.8 45 84.8 45 L 80.1 52 a 72.6 72.6 0 0 1 9.4 29.7 l 7 -0.7 Z"/><path d="M 96.5 14.2 s -1.6 4.7 -1.7 7.6 c -0.2 4.1 4 4.1 3.7 0.2 c -0.2 -1.9 -2 -7.8 -2 -7.8 Z" style="fill: #f6f6f8"/><path class="cls-5" d="M 122.7 42.9 L 151 64.7 c 4.9 0.2 10 1.1 14.8 3.1 c 0 0 1.5 -1.3 3.3 -1.6 L 120.6 38 l 2.1 4.9 Z"/><path d="M 99.4 104 l 38.5 12 l 39 -5 l -3.6 -25 l 3 1 s 2.5 -6.1 2.7 -9.7 s 0.5 -9.3 -4.4 -11.3 s -8.8 1.3 -8.8 1.3 s -6.6 -3.5 -19 -3 s -23 5 -23 5 s -3.4 -3.5 -9.4 -1 s -6.1 10.8 -4.7 19.8 l -9.2 6.4 l -1.1 9.5 l 38.5 12 l 39 -5 l -5 -34.9 l -8 -1.5 l -1 -0.1" style="fill: #e1557a"/><path class="cls-9" d="M 54.4 40.3 l 12.5 7 l -3.7 12 l -3 -2 c -0.8 -12 -5.8 -17 -5.8 -17 M 71.8 50.1 l 1.4 0.8 s 8.2 11 8.3 28.5 l -11.8 -0.2 l 0.6 -7.9 l 3 -4 l -2.5 -3.2 l 1 -14 Z M 80.8 17 l 9.1 4.8 s 6 7.2 12.2 22.8 c 6.7 16.8 7.8 29.4 7.8 29.4 s -1.2 3.2 -1 6 l -5.2 0.4 C 99.8 46 85.9 28.9 85.9 28.9 l -1.3 -0.8 S 84 20.8 80.8 17 Z M 126.7 68.7 l -24.4 -57.1 l -3.1 6 l -1 2.3 s 0.2 1 0.3 2.6 l 1.2 2.4 s 10.7 17.6 16.2 43.4 c 0 0 4 -1.6 8 1.5 l 2.8 -1 Z"/><path d="M 109.7 88.6 l 0.5 2.2 s 13.5 1.6 22.3 -6.8 l -2.3 -5.6 l 5.6 1 l 2 37 l -38.4 -12 l 1.1 -9.4 l 9.2 -6.4 Z" style="fill: #b23f70"/><path class="cls-1" d="M 245.8 97.4 c 2.2 14.2 -36.6 27.4 -115.6 30.2 c -45.5 1.6 -111.8 -7.4 -111.8 -22.5 v 6.4 c 0 15 66.3 24 111.8 22.5 c 79 -2.8 115.7 -16 115.6 -30.2 v -6.4 Z M 69.3 84.5 a 584.1 584.1 0 0 1 39.5 -4.6"/><path class="cls-1" d="M 190.6 78.7 c 36.2 3 54 11 55.2 18.7 c 2.2 14.2 -36.6 27.4 -115.6 30.2 c -45.5 1.6 -111.8 -7.4 -111.8 -22.5 c 0 -8 15.7 -13.9 36.3 -18"/><path class="cls-1" d="M 68.2 98.8 s 6 6 6.9 6.7 l 4.5 3.4 l -2 3.2 l -5.3 -2 a 31 31 0 0 1 -3.3 -2.4 l -2.4 1.9 v 9 l -3.9 0.4 l -1.7 -8.8 h -2.4 l -4.7 8.2 l -3.5 -0.4 l 1.8 -8.7 l -2 -0.5 l -8.7 3.7 l -1.1 -2.8 l 7 -4.3 l 3 -4 l 20.3 -66.7 M 72.9 35.5 l -4.5 61 M 132.5 84 s -7.7 8.3 -22.3 6.8 c 0 0 -5.3 -18.3 4.9 -22.3 C 126.7 64 132.5 84 132.5 84 Z"/><path class="cls-1" d="M 123.9 69.8 c 6 -2.5 26.2 -9.5 43.9 -1.2"/><path class="cls-1" d="M 165.8 67.8 a 9.2 9.2 0 0 1 8.3 -1.5 c 6 2 6.5 10.3 2.3 21.2 l -3 -1 M 136.5 75.3 l -7.2 1.2 M 156.3 74.5 c -5 -0.3 -9.5 -0.1 -13.4 0.1"/><path class="cls-1" d="M 109.7 88.6 l -9.2 6.4 l -1.1 9.5 l 38.5 12 l 39 -5 l -5 -34.9 l -8 -1.5 l -1 -0.1 M 136 81.8 l 1.9 34.6 M 171.9 76.6 l -36.1 2.8 M 136.3 76.6 l 0.9 -7.6 l 5.1 -0.2 l 0.8 7.7"/><path class="cls-1" d="M 156.3 75.8 l 0.8 -8.1 l 5.1 0.1 l 0.8 7.7 M 109.5 87.5 s 13.6 1 21.7 -7.2 M 172.7 82.1 l 4.9 1.9"/><path class="cls-8" d="M 112.8 80 c 0.5 0 1.3 0.2 1.4 2 c 0 0.9 -0.5 1.7 -1.2 1.6 c -0.7 0 -1.3 -0.7 -1.3 -1.8 c 0 -0.9 0.4 -1.8 1 -1.8 Z"/><path class="cls-1" d="M 113 81.8 s -4 4.8 -5.4 13 s 2.8 9.7 4.1 9.9 s 4 0 4.2 -2.3 s -4.2 -2.6 -6.8 -1.5 s -5.2 3.4 -5.3 7.4 c 0 4 3.5 5.3 5.5 4.6 c 1.7 -0.7 1.7 -3 -0.9 -4 s -6 -0.2 -7 3 s 0.9 5.5 2.7 6.5 s 5.3 0.8 5.4 -1.4 s -6 -1.9 -6.2 1.8 s 2.2 5.9 6.2 5.8 s 6 -4.5 4.6 -5.5 c -1.6 -1 -3.7 1.2 -4 4 c 0 2.5 0.4 5.6 4 6 c 3.5 0.4 7 -2 7.5 -4.3 c 0.6 -2.7 -2 -4 -3.4 -2.3 c -1.3 1.4 -1.1 4.4 2 7.2 c 3 2.8 8.5 -0.6 9.1 -2.9 s 0.1 -3.9 -1.4 -3.9 s -2.3 2.1 -2 3.7 s 2 5.4 5.7 5.5 c 3.5 0 5.8 -1.8 6.3 -4 c 0.6 -2.7 -0.4 -5.4 -2.2 -5 c -2 0.3 -1.7 3.9 0 5.9 s 4.2 2.4 5.8 2 c 3 -0.4 5.1 -4 4.5 -7.4 s -3.7 -3.1 -3.6 -1 s 1.5 5.1 5.7 5.7 s 5 -4.2 4.7 -6.6 s -2.2 -4.7 -3.7 -3.7 s 1 6.4 5.8 5.5 c 5 -1 4.2 -10.4 -0.2 -13.8 c -4 -3 -6 -0.6 -5.4 1.2 c 0.9 2.7 6.7 3.6 7.4 -1.8 c 1 -6 -2.8 -10 -10.5 -11"/><path class="cls-8" d="M 142.4 97.6 a 3.2 3.2 0 1 1 6.3 1 c -0.3 1.6 -1.6 3 -3.5 2.8 c -1.8 -0.2 -3.1 -1.8 -2.8 -3.8 Z"/><path class="cls-1" d="M 163.4 108.8 l -0.6 -7.1 l 6.2 -0.5 l 0.8 6.8 l -6.4 0.8 z"/><path class="cls-1" d="M 165.8 105.4 s 1.7 -0.1 3 1.2 c 2 2 3.7 5.9 5.9 8.2 c 0.7 0.8 4.6 2 4.6 2 l -11.7 5.4 l 11.4 0.8 c 1.4 0.1 3 0.5 3 2.8 v 21 M 188.8 94.4 l -2.3 11.2 l 3.2 0.5 l 5.4 -7.7 h 6.3 l 13.9 5.7 l 2.5 -2 l -9.2 -6.4 v -1.1 l 11.7 1.3 M 222.2 95.7 l 0.4 -3.2 l -13.2 -3 l 6.2 -2.2 l -0.5 -2.5 l -11.3 1.1 M 169.1 66.2 L 120.6 38 M 201.5 85.1 l -22.7 -13.2 M 177.3 85 l 10.1 7.8 M 122.7 42.9 L 151 64.7 M 133 66.8 L 106.2 4.4 s -0.6 -2.5 -2.1 -3 l -1.5 -0.5 l -1.2 -0.3 s -1.5 -0.6 -3.3 1 L 80.8 17 s 3 3.6 3.8 11.1 l -10 -5.7 l -20.2 17.9 s 5 5 5.9 17 l -14.4 -9.6 l -12.3 10.9 s -2 1.4 -1.8 4.6 a 4.8 4.8 0 0 0 1.7 3.5 l 22 17.8 M 85.9 28.9 l -12.7 22"/><path class="cls-1" d="M 106.2 3.9 s -0.7 -2 -3 -1.9 s -3.3 2.4 -3.3 2.4 l -10 17.4 M 84.6 28.1 l 1.3 0.8 s 14 17.2 17.8 51.5"/><path class="cls-1" d="M 80.8 17 l 9.1 4.8 s 6 7.2 12.2 22.8 c 6.7 16.8 7.8 29.4 7.8 29.4 M 71.8 50.1 l 1.4 0.8 s 8.2 11 8.3 28.5 l -11.8 -0.2 M 54.4 40.3 l 12.5 7 M 63.2 59.2 l -2.9 -1.9"/><path class="cls-1" d="M 70.8 64.1 l 2.4 3.1 l -2.9 4.1 M 89.5 81.8 s -1 -16.3 -9.4 -29.7 l 4.7 -7.2 S 94 57.9 96.5 81 M 96.5 14.2 s -1.6 4.7 -1.7 7.6 c -0.2 4.1 4 4.1 3.7 0.2 c -0.2 -1.9 -2 -7.8 -2 -7.8 Z M 99.2 17.7 l 3.1 -6.1 l 24.4 57.1 M 99.7 25 s 10.7 17.5 16.2 43.3 M 135.8 79.4 l -2.3 -0.4"/><path class="cls-8" d="M 142.9 74.6 v 1 l 13.4 -0.5 v -0.6 s -5.3 -0.4 -13.4 0.1 Z M 136.4 76 h -4.9 s 3 -0.7 5 -0.7 l -0.1 0.8 Z M 172 77.8 l 3.8 9.5 l -2.5 -0.8 l -1.3 -8.7 z M 122.3 38.9 l 3.1 6 l -2.7 -2 l -2.1 -4.9 l 1.7 0.9 z M 72.9 36.2 l 1.3 13 l -1 1.7 l -1.4 -0.8 l 1.1 -13.9 z M 193.8 100.3 l 7.1 -1.9 h -5.8 l -1.3 1.9 z M 66.6 109.6 l 5.7 0.5 l -3.3 -2.4 l -2.4 1.9 z M 101.2 13.7 l 2.2 0.5 l -1.1 -2.6 l -1.1 2.1 z"/><path class="cls-8" d="M 142.4 70 l 1.6 4.6 h -1.1 l -0.5 -4.6 z M 162.4 69.6 l 1.9 5.6 l -1.3 -0.2 l -0.6 -5.4 z M 112.8 80 c 0.5 0 1.3 0.2 1.4 2 c 0 0.9 -0.5 1.7 -1.2 1.6 c -0.7 0 -1.3 -0.7 -1.3 -1.8 c 0 -0.9 0.4 -1.8 1 -1.8 Z"/><path class="cls-8" d="M 142.9 74.6 v 1 l 13.4 -0.5 v -0.6 s -5.3 -0.4 -13.4 0.1 Z M 136.4 76 h -4.9 s 3 -0.7 5 -0.7 l -0.1 0.8 Z M 172 77.8 l 3.8 9.5 l -2.5 -0.8 l -1.3 -8.7 z M 122.3 38.9 l 3.1 6 l -2.7 -2 l -2.1 -4.9 l 1.7 0.9 z M 72.9 36.2 l 1.3 13 l -1 1.7 l -1.4 -0.8 l 1.1 -13.9 z M 193.8 100.3 l 7.1 -1.9 h -5.8 l -1.3 1.9 z M 66.6 109.6 l 5.7 0.5 l -3.3 -2.4 l -2.4 1.9 z M 101.2 13.7 l 2.2 0.5 l -1.1 -2.6 l -1.1 2.1 z"/><path class="cls-1" d="M 77.9 77.1 l -6.1 -3.9"/></svg> +<?xml version="1.0" encoding="UTF-8"?> +<svg xmlns="http://www.w3.org/2000/svg" data-name="Waiting For Events" viewBox="0 0 246.43 147.336" width="2400" height="1434.1463414634"><path fill="#fca9cb" d="M9.517 132.253l215.438-3.714 9.49-106.722L0 8.487l9.517 123.766z"/><path fill="#e7e1ec" d="M245.846 97.433v6.36c-.667 15.64-36.676 27.392-115.6 30.177-45.5 1.606-111.885-7.428-111.885-22.516v-6.36S16.465 94.04 54.378 87.126c38.471-7.014 104.247-13.376 149.429-7.012 43.504 6.128 42.04 17.318 42.04 17.318z"/><path fill="#b39ed3" d="M178.836 71.883c.763 3.322.221 7.83-1.539 13.074l10.122 7.805 1.204.982.136.662-2.254 11.21 3.229.487 5.36-7.676h6.337l13.89 5.666 2.436-2.01-9.199-6.336.061-1.158 13.452 1.562.499-3.694-13.22-2.924 6.275-2.254-.487-2.498-11.332 1.158h-.958l-1.356-.853-22.656-13.203zM123.856 69.791c-2.407-1.78-5.323-2.577-8.753-1.253-4.685 1.809-6.104 6.666-6.262 11.384l-.879.073c-12.39 1.058-25.938 2.523-38.669 4.491L68.241 98.76s6.024 6.125 6.84 6.738l4.493 3.37-2.042 3.266s-4.594-1.837-5.207-2.042-3.37-2.348-3.37-2.348l-2.33 1.838v9.086l-3.897.307-1.736-8.78h-2.348l-4.696 8.167-3.573-.408 1.837-8.679-2.042-.51-8.678 3.777-1.123-2.858 7.045-4.288 2.96-4.084 5.118-16.766-22.018-17.857s-1.503-1.098-1.645-3.534c-.183-3.13 1.767-4.569 1.767-4.569l12.35-10.876 14.335 9.554c-.915-11.984-5.902-16.981-5.902-16.981l20.303-17.884 9.94 5.738c-.79-7.573-3.788-11.16-3.788-11.16a10496.51 10496.51 0 0 0 17.337-15.29c1.828-1.645 3.297-1.1 3.297-1.1l1.272.308 1.462.487c1.462.487 2.132 3.046 2.132 3.046l26.58 62.394"/><path fill="#5e468c" d="M96.528 81.062c-2.521-23.163-11.724-36.19-11.724-36.19l-4.658 7.252c8.278 13.348 9.316 29.695 9.316 29.695l7.066-.757z"/><path fill="#f6f6f8" d="M96.528 14.2s-1.621 4.748-1.751 7.571c-.193 4.171 4.107 4.171 3.722.193-.18-1.857-1.97-7.765-1.97-7.765z"/><path fill="#b39ed3" d="M122.71 42.87l28.302 21.842c4.855.192 9.916 1.097 14.838 3.086 0 0 1.496-1.262 3.25-1.588l-48.482-28.252 2.092 4.911z"/><path fill="#e1557a" d="M99.38 104.476l38.49 11.945 39.103-5.002-3.653-24.91 3.04 1.02s2.477-6.137 2.639-9.717.458-9.325-4.406-11.338-8.743 1.324-8.743 1.324-6.663-3.463-19.128-3.063-22.869 5.06-22.869 5.06-3.46-3.449-9.45-.95-6.149 10.783-4.722 19.756l-9.178 6.38-1.123 9.495 38.49 11.946 39.103-5.003-5.105-34.815-7.964-1.531c-.307-.035-.613-.07-.918-.102"/><path fill="#5e468c" d="M54.378 40.282l12.475 7.038-3.632 11.902-2.94-1.96c-.916-11.983-5.903-16.98-5.903-16.98M71.848 50.139l1.381.779s8.2 10.963 8.264 28.512l-11.8-.235.585-7.887 2.95-4.065-2.418-3.112 1.038-13.992zM80.834 16.977l9.093 4.84s5.947 7.226 12.165 22.735c6.742 16.813 7.837 29.413 7.837 29.413s-1.251 3.227-1.088 5.957l-5.15.45c-3.845-34.28-17.808-51.508-17.808-51.508l-1.26-.728s-.61-7.327-3.789-11.159zM126.687 68.718l-24.402-57.15-3.08 6.096-1.099 2.227s.332 1.033.417 2.628l1.195 2.405s10.652 17.578 16.147 43.356c0 0 4.063-1.626 7.989 1.515l2.833-1.077z"/><path fill="#b23f70" d="M109.681 88.6l.521 2.195s13.527 1.578 22.257-6.84l-2.218-5.568 5.587.974 2.042 37.06-38.49-11.945 1.123-9.495 9.178-6.38z"/><g><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M245.846 97.433c2.137 14.153-36.676 27.391-115.6 30.177-45.5 1.606-111.885-7.428-111.885-22.517v6.36c0 15.089 66.386 24.123 111.886 22.517 78.923-2.785 115.683-15.942 115.6-30.177v-6.36zM69.287 84.486c12.73-1.968 26.285-3.433 38.675-4.49l.871-.074"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M190.585 78.73c36.194 2.902 54.09 10.941 55.261 18.703 2.137 14.153-36.676 27.391-115.6 30.177-45.5 1.606-111.885-7.428-111.885-22.517 0-8.02 15.705-13.86 36.364-18.037"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M68.241 98.759s6.024 6.125 6.84 6.738l4.493 3.37-2.042 3.266s-4.594-1.837-5.207-2.042-3.37-2.348-3.37-2.348l-2.33 1.838v9.086l-3.897.307-1.736-8.78h-2.348l-4.696 8.167-3.573-.408 1.837-8.679-2.042-.51-8.678 3.777-1.123-2.858 7.045-4.288 2.96-4.084 20.318-66.566M72.938 35.459l-4.526 60.993M132.46 83.955s-7.658 8.372-22.258 6.84c0 0-5.28-18.327 4.9-22.257 11.64-4.492 17.357 15.417 17.357 15.417zM123.853 69.795c6.052-2.474 26.212-9.458 43.931-1.154"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M165.85 67.797c1.871-1.3 4.86-2.659 8.264-1.505 6.024 2.042 6.534 10.312 2.246 21.236 0 0-1.246-.4-3.04-1.019M136.48 75.296a88.58 88.58 0 0 0-7.133 1.235M156.35 74.464a112.574 112.574 0 0 0-13.471.177"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M109.681 88.6l-9.178 6.381-1.123 9.495 38.49 11.945 39.103-5.002-5.105-34.815-7.963-1.531c-.308-.036-.614-.07-.92-.102M135.964 81.819l1.906 34.602M171.868 76.604l-36.04 2.757M136.339 76.604l.816-7.555 5.105-.204.817 7.657"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M156.35 75.787l.714-8.065 5.105.102.817 7.657M109.475 87.528s13.633.954 21.678-7.18M172.673 82.095l4.92 1.951"/><path fill="#3f2b56" d="M112.793 79.995c.484-.018 1.3.161 1.37 2.044.032.856-.453 1.612-1.21 1.604-.677-.008-1.214-.732-1.213-1.824 0-.906.326-1.797 1.053-1.824z"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M112.952 81.819s-3.865 4.781-5.31 12.915 2.804 9.77 4.098 9.962 3.892.097 4.133-2.262-4.187-2.647-6.738-1.54-5.198 3.417-5.294 7.412c-.097 3.994 3.465 5.342 5.438 4.572 1.759-.686 1.733-2.984-.866-3.946s-5.968-.241-7.027 2.983.867 5.487 2.695 6.498 5.294.818 5.439-1.396-6.016-1.877-6.209 1.78 2.166 5.872 6.209 5.824 6.034-4.53 4.62-5.486c-1.636-1.107-3.754 1.203-3.946 3.898-.182 2.545.289 5.631 3.898 6.064 3.552.426 7.075-2.021 7.556-4.331.547-2.623-1.973-3.899-3.417-2.31-1.352 1.487-1.155 4.475 1.925 7.267 3.08 2.791 8.519-.578 9.193-2.888s.048-3.898-1.444-3.898-2.31 2.07-2.021 3.706 1.973 5.342 5.727 5.438c3.464.09 5.755-1.822 6.257-3.898.673-2.792-.337-5.439-2.214-5.102-2.04.366-1.637 3.899 0 5.92s4.235 2.358 5.871 2.07c2.91-.514 5.102-3.995 4.476-7.46s-3.658-3.129-3.561-.963 1.443 5.102 5.63 5.68 5.006-4.188 4.765-6.643-2.214-4.668-3.706-3.705.953 6.46 5.728 5.486c4.957-1.01 4.235-10.396-.193-13.765-3.882-2.953-6.003-.604-5.39 1.204.914 2.695 6.69 3.561 7.46-1.781.874-6.069-2.84-10.107-10.492-11.021"/><path fill="#3f2b56" d="M142.428 97.631c.365-2.13 2.216-3.05 3.754-2.701 2.204.499 2.732 2.506 2.525 3.656-.298 1.652-1.596 3.076-3.54 2.815-1.78-.239-3.076-1.8-2.739-3.77z"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M163.372 108.79l-.605-7.137 6.277-.414.733 6.787-6.405.764z"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M165.762 105.413s1.748-.14 3.11 1.202c1.926 1.897 3.586 5.844 5.779 8.174.751.799 4.621 1.936 4.621 1.936l-11.63 5.48s9.902.733 11.368.829 3.027.446 3.059 2.74 0 21.062 0 21.062M188.76 94.406l-2.255 11.21 3.229.487 5.36-7.676h6.337l13.89 5.666 2.436-2.01-9.199-6.336.061-1.158 11.697 1.34M222.204 95.686l.366-3.229-13.22-2.924 6.275-2.254-.487-2.498-11.332 1.157M169.1 66.21l-48.482-28.252M201.492 85.086l-22.657-13.203M177.297 84.957l10.122 7.805M122.71 42.869l28.303 21.822M132.913 66.82L106.334 4.428s-.67-2.558-2.132-3.046L102.74.894l-1.272-.307s-1.47-.546-3.297 1.099c-.605.544-7.876 6.955-17.337 15.291 0 0 2.998 3.586 3.788 11.159l-9.94-5.738-20.303 17.884s4.986 4.997 5.902 16.98L45.945 47.71l-12.35 10.875s-1.95 1.44-1.766 4.57c.142 2.435 1.645 3.533 1.645 3.533l22.018 17.857M85.883 28.864L73.229 50.918"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M106.157 3.882s-.695-1.92-2.918-1.87-3.334 2.415-3.334 2.415l-9.978 17.39M84.622 28.136l1.261.728s13.963 17.228 17.809 51.508"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M80.834 16.977l9.093 4.84s5.947 7.226 12.165 22.735c6.742 16.813 7.837 29.413 7.837 29.413M71.848 50.139l1.381.779s8.2 10.963 8.264 28.512l-11.8-.235M54.378 40.282l12.475 7.038M63.221 59.222l-2.94-1.959"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M70.81 64.131l2.419 3.112-2.951 4.065M89.463 81.819s-1.04-16.347-9.317-29.695l4.658-7.251S94.007 57.9 96.53 81.062M96.528 14.2s-1.621 4.748-1.751 7.571c-.193 4.171 4.107 4.171 3.722.193-.18-1.857-1.97-7.765-1.97-7.765zM99.204 17.664l3.08-6.096 24.403 57.15M99.718 24.924s10.652 17.578 16.147 43.356M135.828 79.361l-2.329-.342"/><path fill="#3f2b56" d="M142.879 74.64l.1.941 13.37-.47v-.647s-5.347-.344-13.47.177zM136.398 76.06l-4.901.035s3.09-.792 4.983-.799l-.082.764zM172.045 77.812l3.764 9.537-2.489-.84-1.275-8.697zM122.3 38.938l3.1 6.005-2.69-2.074-2.092-4.911 1.682.98zM72.882 36.202l1.322 13.017-.975 1.699-1.38-.78 1.033-13.936zM193.819 100.255l7.081-1.828h-5.805l-1.276 1.828zM66.626 109.58l5.699.511-3.37-2.348-2.33 1.838zM101.19 13.733l2.218.466-1.123-2.631-1.094 2.165z"/><path fill="#3f2b56" d="M142.384 70.003l1.644 4.638h-1.15l-.494-4.638zM162.37 69.584l1.897 5.587-1.281-.2-.616-5.388zM112.793 79.995c.484-.018 1.3.161 1.37 2.044.032.856-.453 1.612-1.21 1.604-.677-.008-1.214-.732-1.213-1.824 0-.906.326-1.797 1.053-1.824z"/><path fill="#3f2b56" d="M142.879 74.64l.1.941 13.37-.47v-.647s-5.347-.344-13.47.177zM136.398 76.06l-4.901.035s3.09-.792 4.983-.799l-.082.764zM172.045 77.812l3.764 9.537-2.489-.84-1.275-8.697zM122.3 38.938l3.1 6.005-2.69-2.074-2.092-4.911 1.682.98zM72.882 36.202l1.322 13.017-.975 1.699-1.38-.78 1.033-13.936zM193.819 100.255l7.081-1.828h-5.805l-1.276 1.828zM66.626 109.58l5.699.511-3.37-2.348-2.33 1.838zM101.19 13.733l2.218.466-1.123-2.631-1.094 2.165z"/><path fill="none" stroke="#3f2b56" stroke-linecap="round" stroke-linejoin="round" d="M77.886 77.12l-6.133-3.928"/></g></svg>
65e8ab1aa52477401addab5d7b86ccf0dbe98a52
2024-02-14 05:50:09
Nar Saynorath
fix(app-start): Pass along device class consistently to event samples (#65106)
false
Pass along device class consistently to event samples (#65106)
fix
diff --git a/static/app/views/starfish/views/appStartup/screenSummary/eventSamples.tsx b/static/app/views/starfish/views/appStartup/screenSummary/eventSamples.tsx index 22cc64f7e2b35a..9a5e0328b3b571 100644 --- a/static/app/views/starfish/views/appStartup/screenSummary/eventSamples.tsx +++ b/static/app/views/starfish/views/appStartup/screenSummary/eventSamples.tsx @@ -60,20 +60,13 @@ export function EventSamples({ 'OR', 'span.description:"Warm Start"', ')', + ...(deviceClass ? [`${SpanMetricsField.DEVICE_CLASS}:${deviceClass}`] : []), // TODO: Add this back in once we have the ability to filter by start type // `${SpanMetricsField.APP_START_TYPE}:${ // startType || `[${COLD_START_TYPE},${WARM_START_TYPE}]` // }`, ]); - if (deviceClass) { - if (deviceClass === 'Unknown') { - searchQuery.addFilterValue('!has', 'device.class'); - } else { - searchQuery.addFilterValue('device.class', deviceClass); - } - } - const sort = fromSorts(decodeScalar(location.query[sortKey]))[0] ?? DEFAULT_SORT; const columnNameMap = {
872051efc11e24ced24580210b5eda3b61a28bf0
2019-07-19 22:41:10
Evan Purkhiser
ref(templates): Remove unused org_selector block (#14078)
false
Remove unused org_selector block (#14078)
ref
diff --git a/src/sentry/templates/sentry/bases/forceauth_modal.html b/src/sentry/templates/sentry/bases/forceauth_modal.html index cca9ff71f66a68..7f844efb71c0dd 100644 --- a/src/sentry/templates/sentry/bases/forceauth_modal.html +++ b/src/sentry/templates/sentry/bases/forceauth_modal.html @@ -3,7 +3,6 @@ {% load i18n %} {% block wrapperclass %}{{ block.super }} narrow hide-sidebar{% endblock %} -{% block org_selector %}{% endblock %} {% block account_nav %}{% endblock %} {% block global_sidebar %}{% endblock %}
4041b4258e62178c4314980811245391be4e28d5
2022-04-07 02:56:56
Gilbert Szeto
ref(workflow): Deprecate transferring a project to a team (#33355)
false
Deprecate transferring a project to a team (#33355)
ref
diff --git a/src/sentry/api/endpoints/accept_project_transfer.py b/src/sentry/api/endpoints/accept_project_transfer.py index f5cd4a3764d2cb..c1664ba319b6d8 100644 --- a/src/sentry/api/endpoints/accept_project_transfer.py +++ b/src/sentry/api/endpoints/accept_project_transfer.py @@ -18,8 +18,8 @@ OrganizationMember, OrganizationStatus, Project, - Team, ) +from sentry.utils import metrics from sentry.utils.signing import unsign @@ -97,58 +97,30 @@ def post(self, request: Request) -> Response: transaction_id = data["transaction_id"] org_slug = request.data.get("organization") + # DEPRECATED team_id = request.data.get("team") - if org_slug is not None and team_id is not None: - return Response( - {"detail": "Choose either a team or an organization, not both"}, status=400 - ) - - if org_slug is None and team_id is None: - return Response( - {"detail": "Choose either a team or an organization to transfer the project to"}, - status=400, - ) - - if team_id: - try: - team = Team.objects.get(id=team_id) - except Team.DoesNotExist: - return Response({"detail": "Invalid team"}, status=400) - - # check if user is an owner of the team's org - is_team_org_owner = OrganizationMember.objects.filter( - user__is_active=True, - user=request.user, - role=roles.get_top_dog().id, - organization_id=team.organization_id, - ).exists() - - if not is_team_org_owner: - return Response({"detail": "Invalid team"}, status=400) - from sentry.utils import metrics - + if org_slug is None and team_id is not None: metrics.incr("accept_project_transfer.post.to_team") - project.transfer_to(team=team) - - if org_slug: - try: - organization = Organization.objects.get(slug=org_slug) - except Organization.DoesNotExist: - return Response({"detail": "Invalid organization"}, status=400) - - # check if user is an owner of the organization - is_org_owner = OrganizationMember.objects.filter( - user__is_active=True, - user=request.user, - role=roles.get_top_dog().id, - organization_id=organization.id, - ).exists() - - if not is_org_owner: - return Response({"detail": "Invalid organization"}, status=400) - - project.transfer_to(organization=organization) + return Response({"detail": "Cannot transfer projects to a team."}, status=400) + + try: + organization = Organization.objects.get(slug=org_slug) + except Organization.DoesNotExist: + return Response({"detail": "Invalid organization"}, status=400) + + # check if user is an owner of the organization + is_org_owner = OrganizationMember.objects.filter( + user__is_active=True, + user=request.user, + role=roles.get_top_dog().id, + organization_id=organization.id, + ).exists() + + if not is_org_owner: + return Response({"detail": "Invalid organization"}, status=400) + + project.transfer_to(organization=organization) self.create_audit_entry( request=request, diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py index bff1e336656d63..904b913ba6a0fa 100644 --- a/src/sentry/models/project.py +++ b/src/sentry/models/project.py @@ -262,11 +262,7 @@ def get_audit_log_data(self): def get_full_name(self): return self.slug - def transfer_to(self, team=None, organization=None): - # NOTE: this will only work properly if the new team is in a different - # org than the existing one, which is currently the only use case in - # production - # TODO(jess): refactor this to make it an org transfer only + def transfer_to(self, organization): from sentry.incidents.models import AlertRule from sentry.models import ( Environment, @@ -278,9 +274,6 @@ def transfer_to(self, team=None, organization=None): ) from sentry.models.actor import ACTOR_TYPES - if organization is None: - organization = team.organization - old_org_id = self.organization_id org_changed = old_org_id != organization.id @@ -326,10 +319,6 @@ def transfer_to(self, team=None, organization=None): environment_id=Environment.get_or_create(self, environment_names[environment_id]).id ) - # ensure this actually exists in case from team was null - if team is not None: - self.add_team(team) - # Remove alert owners not in new org alert_rules = AlertRule.objects.fetch_for_project(self).filter(owner_id__isnull=False) rules = Rule.objects.filter(owner_id__isnull=False, project=self) diff --git a/tests/sentry/api/endpoints/test_accept_project_transfer.py b/tests/sentry/api/endpoints/test_accept_project_transfer.py index 49af3d63094efa..7014bff3e81fe9 100644 --- a/tests/sentry/api/endpoints/test_accept_project_transfer.py +++ b/tests/sentry/api/endpoints/test_accept_project_transfer.py @@ -74,7 +74,7 @@ def test_returns_org_options_with_signed_link(self): assert self.from_organization.slug in org_slugs assert self.to_organization.slug in org_slugs - def test_transfers_project_to_correct_team(self): + def test_transfers_project_to_team_deprecated(self): self.login_as(self.owner) url_data = sign( actor_id=self.member.user_id, @@ -84,11 +84,11 @@ def test_transfers_project_to_correct_team(self): transaction_id=self.transaction_id, ) - resp = self.client.post(self.path, data={"team": self.to_team.id, "data": url_data}) - assert resp.status_code == 204 - p = Project.objects.get(id=self.project.id) - assert p.organization_id == self.to_organization.id - assert p.teams.first() == self.to_team + resp = self.client.post( + self.path, data={"team": self.to_team.id, "organization": None, "data": url_data} + ) + assert resp.status_code == 400 + assert resp.data == {"detail": "Cannot transfer projects to a team."} def test_non_owner_cannot_transfer_project(self): rando_user = self.create_user(email="[email protected]", is_superuser=False) @@ -103,24 +103,13 @@ def test_non_owner_cannot_transfer_project(self): transaction_id=self.transaction_id, ) - resp = self.client.post(self.path, data={"team": self.to_team.id, "data": url_data}) + resp = self.client.post( + self.path, data={"organization": self.to_organization.slug, "data": url_data} + ) assert resp.status_code == 400 p = Project.objects.get(id=self.project.id) assert p.organization_id == self.from_organization.id - - def test_cannot_transfer_project_twice_from_same_org(self): - self.login_as(self.owner) - url_data = sign( - actor_id=self.member.user_id, - from_organization_id=self.from_organization.id, - project_id=self.project.id, - user_id=self.owner.id, - transaction_id=self.transaction_id, - ) - - resp = self.client.post(self.path, data={"team": self.to_team.id, "data": url_data}) - resp = self.client.get(self.path + "?" + urlencode({"data": url_data})) - assert resp.status_code == 400 + assert p.organization_id != rando_org.id def test_transfers_project_to_correct_organization(self): self.login_as(self.owner) @@ -139,7 +128,7 @@ def test_transfers_project_to_correct_organization(self): p = Project.objects.get(id=self.project.id) assert p.organization_id == self.to_organization.id - def test_errors_when_team_and_org_provided(self): + def test_use_org_when_team_and_org_provided(self): self.login_as(self.owner) url_data = sign( actor_id=self.member.user_id, @@ -157,7 +146,6 @@ def test_errors_when_team_and_org_provided(self): "data": url_data, }, ) - assert resp.status_code == 400 - assert resp.data == {"detail": "Choose either a team or an organization, not both"} + assert resp.status_code == 204 p = Project.objects.get(id=self.project.id) - assert p.organization_id == self.from_organization.id + assert p.organization_id == self.to_organization.id diff --git a/tests/sentry/models/test_project.py b/tests/sentry/models/test_project.py index f2ffadfade4a0d..d6e4188f432d17 100644 --- a/tests/sentry/models/test_project.py +++ b/tests/sentry/models/test_project.py @@ -42,89 +42,6 @@ def test_inactive_global_member(self): assert list(project.member_set.all()) == [] - def test_transfer_to_team(self): - from_org = self.create_organization() - from_team = self.create_team(organization=from_org) - to_org = self.create_organization() - to_team = self.create_team(organization=to_org) - - project = self.create_project(teams=[from_team]) - - rule = Rule.objects.create( - project=project, - environment_id=Environment.get_or_create(project, "production").id, - label="Golden Rule", - data={}, - ) - - project.transfer_to(team=to_team) - - project = Project.objects.get(id=project.id) - - assert project.teams.count() == 1 - assert project.teams.first() == to_team - assert project.organization_id == to_org.id - - updated_rule = project.rule_set.get(label="Golden Rule") - assert updated_rule.id == rule.id - assert updated_rule.environment_id != rule.environment_id - assert updated_rule.environment_id == Environment.get_or_create(project, "production").id - - def test_transfer_to_team_slug_collision(self): - from_org = self.create_organization() - from_team = self.create_team(organization=from_org) - project = self.create_project(teams=[from_team], slug="matt") - to_org = self.create_organization() - to_team = self.create_team(organization=to_org) - # conflicting project slug - self.create_project(teams=[to_team], slug="matt") - - assert Project.objects.filter(organization=to_org).count() == 1 - - project.transfer_to(team=to_team) - - project = Project.objects.get(id=project.id) - - assert project.teams.count() == 1 - assert project.teams.first() == to_team - assert project.organization_id == to_org.id - assert project.slug != "matt" - assert Project.objects.filter(organization=to_org).count() == 2 - assert Project.objects.filter(organization=from_org).count() == 0 - - def test_transfer_to_team_releases(self): - from_org = self.create_organization() - from_team = self.create_team(organization=from_org) - to_org = self.create_organization() - to_team = self.create_team(organization=to_org) - - project = self.create_project(teams=[from_team]) - - environment = Environment.get_or_create(project, "production") - release = Release.get_or_create(project=project, version="1.0") - - ReleaseProjectEnvironment.objects.create( - project=project, release=release, environment=environment - ) - - assert ReleaseProjectEnvironment.objects.filter( - project=project, release=release, environment=environment - ).exists() - assert ReleaseProject.objects.filter(project=project, release=release).exists() - - project.transfer_to(team=to_team) - - project = Project.objects.get(id=project.id) - - assert project.teams.count() == 1 - assert project.teams.first() == to_team - assert project.organization_id == to_org.id - - assert not ReleaseProjectEnvironment.objects.filter( - project=project, release=release, environment=environment - ).exists() - assert not ReleaseProject.objects.filter(project=project, release=release).exists() - def test_transfer_to_organization(self): from_org = self.create_organization() team = self.create_team(organization=from_org)
fca7c9a4de328d324956a6bb3f79024075ee3c2c
2022-10-13 08:53:49
Evan Purkhiser
ref(js): Move FieldSeparator into fields/separatorField (#39958)
false
Move FieldSeparator into fields/separatorField (#39958)
ref
diff --git a/static/app/components/forms/fieldFromConfig.tsx b/static/app/components/forms/fieldFromConfig.tsx index 10b60a504c8aae..6ab21b7e275f4a 100644 --- a/static/app/components/forms/fieldFromConfig.tsx +++ b/static/app/components/forms/fieldFromConfig.tsx @@ -1,5 +1,5 @@ import {FieldProps} from 'sentry/components/forms/field'; -import FieldSeparator from 'sentry/components/forms/fieldSeparator'; +import SeparatorField from 'sentry/components/forms/fields/separatorField'; import {Field} from 'sentry/components/forms/type'; import {Scope} from 'sentry/types'; @@ -48,7 +48,7 @@ function FieldFromConfig(props: FieldFromConfigProps): React.ReactElement | null switch (field.type) { case 'separator': - return <FieldSeparator />; + return <SeparatorField />; case 'secret': return <InputField {...(componentProps as InputFieldProps)} type="password" />; case 'range': diff --git a/static/app/components/forms/fieldSeparator.tsx b/static/app/components/forms/fieldSeparator.tsx deleted file mode 100644 index 5daa174c640aab..00000000000000 --- a/static/app/components/forms/fieldSeparator.tsx +++ /dev/null @@ -1,3 +0,0 @@ -export default function FieldSeparator() { - return <hr />; -} diff --git a/static/app/components/forms/fields/blankField.tsx b/static/app/components/forms/fields/blankField.tsx index 7a79b453792054..6902d650d9228f 100644 --- a/static/app/components/forms/fields/blankField.tsx +++ b/static/app/components/forms/fields/blankField.tsx @@ -1,7 +1,7 @@ import Field, {FieldProps} from 'sentry/components/forms/field'; /** - * This class is meant to hook into `fieldFromConfig`. Like the FieldSeparator + * This class is meant to hook into `fieldFromConfig`. Like the SeparatorField * class, this doesn't have any fields of its own and is just meant to make * forms more flexible. */ diff --git a/static/app/components/forms/fields/separatorField.tsx b/static/app/components/forms/fields/separatorField.tsx new file mode 100644 index 00000000000000..a6701a9fde1d6f --- /dev/null +++ b/static/app/components/forms/fields/separatorField.tsx @@ -0,0 +1,5 @@ +function SeparatorField() { + return <hr />; +} + +export default SeparatorField; diff --git a/static/app/components/forms/index.tsx b/static/app/components/forms/index.tsx index 3ff935f2749b13..ac87d281a77ebd 100644 --- a/static/app/components/forms/index.tsx +++ b/static/app/components/forms/index.tsx @@ -12,10 +12,10 @@ export {default as RangeField} from './fields/rangeField'; export {default as SelectField} from './fields/selectField'; export {default as TextareaField} from './fields/textareaField'; export {default as TextField} from './fields/textField'; +export {default as SeparatorField} from './fields/separatorField'; export {default as Form} from './form'; export {default as ApiForm} from './apiForm'; export {default as JSONForm} from './jsonForm'; export {default as FormPanel} from './formPanel'; export {default as FieldFromConfig} from './fieldFromConfig'; -export {default as FieldSeparator} from './fieldSeparator';
8a9f0ad73d075a8fe5d94bbe913d9c885054b0bf
2023-12-06 00:23:43
Colton Allen
fix(replays): Parse timestamp retaining UTC timezone (#61157)
false
Parse timestamp retaining UTC timezone (#61157)
fix
diff --git a/src/sentry/replays/usecases/segment.py b/src/sentry/replays/usecases/segment.py index eb70db19c77eeb..2c0abf7800158e 100644 --- a/src/sentry/replays/usecases/segment.py +++ b/src/sentry/replays/usecases/segment.py @@ -1,6 +1,6 @@ from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Any, Mapping from snuba_sdk import Column, Condition, Entity, Granularity, Op, Query, Request @@ -16,12 +16,8 @@ def query_segment_storage_meta_by_timestamp( replay_id: str, timestamp: float, ) -> Mapping[str, Any]: - # These timestamps do not specify a timezone. They are presumed UTC but we can not verify. - # Since these times originate from the same place it is enough to treat them relatively. We - # ignore the issue of timezone and utilize the replay's internal consistency. - # - # This means calls to the server's internal clock are prohibited. - end = datetime.fromtimestamp(timestamp + 1) + # Timestamps must be in UTC. + end = datetime.fromtimestamp(timestamp + 1, tz=timezone.utc) # For safety look back one additional hour. start = end - timedelta(hours=REPLAY_DURATION_HOURS + 1)
197f40a3a50add367ca25dbfcb32cf07ce7d3cad
2018-04-03 00:18:50
Jess MacQueen
feat(ui): Add style prop to Field component
false
Add style prop to Field component
feat
diff --git a/src/sentry/static/sentry/app/views/settings/components/forms/field/index.jsx b/src/sentry/static/sentry/app/views/settings/components/forms/field/index.jsx index bd9f4309de71c4..8bf4603f83d558 100644 --- a/src/sentry/static/sentry/app/views/settings/components/forms/field/index.jsx +++ b/src/sentry/static/sentry/app/views/settings/components/forms/field/index.jsx @@ -81,6 +81,9 @@ class Field extends React.Component { * The Control component */ children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), + + /** Inline style */ + style: PropTypes.object, }; static defaultProps = { @@ -106,6 +109,7 @@ class Field extends React.Component { id, p, children, + style, } = this.props; let isDisabled = typeof disabled === 'function' ? disabled(this.props) : disabled; let isVisible = typeof visible === 'function' ? visible(this.props) : visible; @@ -139,6 +143,7 @@ class Field extends React.Component { inline={inline} highlighted={highlighted} hasControlState={!flexibleControlStateSize} + style={style} > <FieldDescription inline={inline} htmlFor={id}> {label && (
2ead6c8f03fc07e0272005788dee82fac267bd41
2024-05-16 20:53:16
Kevin Liu
ref(insights): remove outdated starfish.panel.open in favor of new analytics (#71020)
false
remove outdated starfish.panel.open in favor of new analytics (#71020)
ref
diff --git a/static/app/utils/analytics/starfishAnalyticsEvents.tsx b/static/app/utils/analytics/starfishAnalyticsEvents.tsx index 1eeaab5b625ef8..218733799c88cc 100644 --- a/static/app/utils/analytics/starfishAnalyticsEvents.tsx +++ b/static/app/utils/analytics/starfishAnalyticsEvents.tsx @@ -12,7 +12,6 @@ export type StarfishEventParameters = { 'starfish.pageview': { route: string; }; - 'starfish.panel.open': {}; 'starfish.request': { duration: number; statusCode?: string; @@ -44,7 +43,6 @@ export type StarfishEventKey = keyof StarfishEventParameters; export const starfishEventMap: Record<keyof StarfishEventParameters, string> = { 'starfish.chart.zoom': 'Starfish: Chart Zoomed', 'starfish.pageview': 'Starfish: Page Viewed', - 'starfish.panel.open': 'Starfish: Slide Over Panel Opened', 'starfish.request': 'Starfish: API Request Completed', 'starfish.samples.loaded': 'Starfish: Samples Loaded', 'starfish.web_service_view.endpoint_list.endpoint.clicked': diff --git a/static/app/views/performance/mobile/components/spanSamplesPanel.tsx b/static/app/views/performance/mobile/components/spanSamplesPanel.tsx index 3267741b4b2fee..c1995dcd550d6a 100644 --- a/static/app/views/performance/mobile/components/spanSamplesPanel.tsx +++ b/static/app/views/performance/mobile/components/spanSamplesPanel.tsx @@ -63,7 +63,6 @@ export function SpanSamplesPanel({ const onOpenDetailPanel = useCallback(() => { if (query.transaction) { - trackAnalytics('starfish.panel.open', {organization}); trackAnalytics('performance_views.sample_spans.opened', { organization, source: moduleName, diff --git a/static/app/views/starfish/views/spanSummaryPage/sampleList/index.tsx b/static/app/views/starfish/views/spanSummaryPage/sampleList/index.tsx index 72675ef3a8ef07..5dd9ab2df55f60 100644 --- a/static/app/views/starfish/views/spanSummaryPage/sampleList/index.tsx +++ b/static/app/views/starfish/views/spanSummaryPage/sampleList/index.tsx @@ -78,7 +78,6 @@ export function SampleList({ const onOpenDetailPanel = useCallback(() => { if (query.transaction) { - trackAnalytics('starfish.panel.open', {organization}); trackAnalytics('performance_views.sample_spans.opened', { organization, source: moduleName,
9d4c4cdc17fe34a7972a4c05725db5c5f6bdf82b
2023-04-14 22:58:24
Alberto Leal
chore(hybrid-cloud): Update organization index endpoint to consume organization_service.add_organization_member (#47350)
false
Update organization index endpoint to consume organization_service.add_organization_member (#47350)
chore
diff --git a/src/sentry/api/endpoints/organization_index.py b/src/sentry/api/endpoints/organization_index.py index adba9696bfb55f..f18a1c4805af64 100644 --- a/src/sentry/api/endpoints/organization_index.py +++ b/src/sentry/api/endpoints/organization_index.py @@ -24,6 +24,7 @@ ) from sentry.search.utils import tokenize_query from sentry.services.hybrid_cloud import IDEMPOTENCY_KEY_LENGTH +from sentry.services.hybrid_cloud.organization import organization_service from sentry.services.hybrid_cloud.organization_mapping import organization_mapping_service from sentry.signals import org_setup_complete, terms_accepted @@ -204,6 +205,7 @@ def post(self, request: Request) -> Response: result = serializer.validated_data try: + with transaction.atomic(): org = Organization.objects.create(name=result["name"], slug=result.get("slug")) @@ -214,10 +216,13 @@ def post(self, request: Request) -> Response: idempotency_key=result.get("idempotencyKey", ""), region_name=settings.SENTRY_REGION or "us", ) - - om = OrganizationMember.objects.create( - organization=org, user=request.user, role=roles.get_top_dog().id + rpc_org_member = organization_service.add_organization_member( + organization_id=org.id, + default_org_role=org.default_role, + user_id=request.user.id, + role=roles.get_top_dog().id, ) + om = OrganizationMember.objects.get(id=rpc_org_member.id) if result.get("defaultTeam"): team = org.team_set.create(name=org.name) diff --git a/tests/sentry/api/endpoints/test_organization_index.py b/tests/sentry/api/endpoints/test_organization_index.py index 883d64b8b18d06..fc5e6f102b10d8 100644 --- a/tests/sentry/api/endpoints/test_organization_index.py +++ b/tests/sentry/api/endpoints/test_organization_index.py @@ -5,6 +5,7 @@ from sentry.models import Authenticator, Organization, OrganizationMember, OrganizationStatus from sentry.models.organizationmapping import OrganizationMapping from sentry.testutils import APITestCase, TwoFactorAPITestCase +from sentry.testutils.hybrid_cloud import HybridCloudTestMixin from sentry.testutils.silo import exempt_from_silo_limits, region_silo_test @@ -95,7 +96,7 @@ def test_member_id_query(self): @region_silo_test -class OrganizationsCreateTest(OrganizationIndexTest): +class OrganizationsCreateTest(OrganizationIndexTest, HybridCloudTestMixin): method = "post" def test_missing_params(self): @@ -213,6 +214,16 @@ def test_slug_already_taken(self): OrganizationMapping.objects.create(organization_id=999, slug="taken", region_name="us") self.get_error_response(slug="taken", name="TaKeN", status_code=409) + def test_add_organization_member(self): + self.login_as(user=self.user) + + response = self.get_success_response(name="org name") + + org_member = OrganizationMember.objects.get( + organization_id=response.data["id"], user=self.user + ) + self.assert_org_member_mapping(org_member=org_member) + @region_silo_test class OrganizationIndex2faTest(TwoFactorAPITestCase):
09f9b252d429102b24d151c083c44a6c6fded42e
2024-03-05 03:51:53
Kev
fix(metrics-extraction): Allow overriding split decision (#66259)
false
Allow overriding split decision (#66259)
fix
diff --git a/src/sentry/api/endpoints/organization_events.py b/src/sentry/api/endpoints/organization_events.py index 9835914df054a1..269ba4203e6779 100644 --- a/src/sentry/api/endpoints/organization_events.py +++ b/src/sentry/api/endpoints/organization_events.py @@ -324,8 +324,13 @@ def fn(offset, limit) -> dict[str, Any]: try: widget = DashboardWidget.objects.get(id=dashboard_widget_id) does_widget_have_split = widget.discover_widget_split is not None + has_override_feature = features.has( + "organizations:performance-discover-widget-split-override-save", + organization, + actor=request.user, + ) - if does_widget_have_split: + if does_widget_have_split and not has_override_feature: # This is essentially cached behaviour and we skip the check split_query = scoped_query if widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS: diff --git a/src/sentry/api/endpoints/organization_events_stats.py b/src/sentry/api/endpoints/organization_events_stats.py index 357980de4e12d4..14f0a524798798 100644 --- a/src/sentry/api/endpoints/organization_events_stats.py +++ b/src/sentry/api/endpoints/organization_events_stats.py @@ -323,8 +323,13 @@ def fn( try: widget = DashboardWidget.objects.get(id=dashboard_widget_id) does_widget_have_split = widget.discover_widget_split is not None + has_override_feature = features.has( + "organizations:performance-discover-widget-split-override-save", + organization, + actor=request.user, + ) - if does_widget_have_split: + if does_widget_have_split and not has_override_feature: # This is essentially cached behaviour and we skip the check split_query = query if widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS: diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index ff758324f77bbd..8ca7d3f38e4926 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1721,6 +1721,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]: "organizations:performance-database-view-percentiles": False, # Enable UI sending a discover split for widget "organizations:performance-discover-widget-split-ui": False, + # Enable backend overriding and always making a fresh split decision + "organizations:performance-discover-widget-split-override-save": False, # Enables updated all events tab in a performance issue "organizations:performance-issues-all-events-tab": False, # Enable compressed assets performance issue type diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index 584a970be35271..5059b89987c06b 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -176,6 +176,7 @@ default_manager.add("organizations:performance-database-view", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add("organizations:performance-db-main-thread-detector", OrganizationFeature) default_manager.add("organizations:performance-discover-widget-split-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE) +default_manager.add("organizations:performance-discover-widget-split-override-save", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add("organizations:performance-file-io-main-thread-detector", OrganizationFeature, FeatureHandlerStrategy.INTERNAL) default_manager.add("organizations:performance-issues-all-events-tab", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add("organizations:performance-issues-compressed-assets-detector", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
827e5d785e4871b9203935bb9fa309a9c91a8477
2023-09-15 21:14:33
Armen Zambrano G
feat(code_mappings): Support top level packages (#56322)
false
Support top level packages (#56322)
feat
diff --git a/src/sentry/api/endpoints/organization_derive_code_mappings.py b/src/sentry/api/endpoints/organization_derive_code_mappings.py index 957f081798f2d4..2ac27680a22245 100644 --- a/src/sentry/api/endpoints/organization_derive_code_mappings.py +++ b/src/sentry/api/endpoints/organization_derive_code_mappings.py @@ -17,6 +17,7 @@ CodeMappingTreesHelper, FrameFilename, Repo, + UnsupportedFrameFilename, create_code_mapping, ) from sentry.models import Project @@ -54,12 +55,17 @@ def get(self, request: Request, organization: Organization) -> Response: trees = installation.get_trees_for_org() trees_helper = CodeMappingTreesHelper(trees) - frame_filename = FrameFilename(stacktrace_filename) - possible_code_mappings: List[Dict[str, str]] = trees_helper.list_file_matches( - frame_filename - ) - resp_status = status.HTTP_200_OK if possible_code_mappings else status.HTTP_204_NO_CONTENT - return Response(serialize(possible_code_mappings), status=resp_status) + try: + frame_filename = FrameFilename(stacktrace_filename) + possible_code_mappings: List[Dict[str, str]] = trees_helper.list_file_matches( + frame_filename + ) + resp_status = ( + status.HTTP_200_OK if possible_code_mappings else status.HTTP_204_NO_CONTENT + ) + return Response(serialize(possible_code_mappings), status=resp_status) + except UnsupportedFrameFilename: + return Response("We do not support this case.", status=status.HTTP_400_BAD_REQUEST) def post(self, request: Request, organization: Organization) -> Response: """ diff --git a/src/sentry/integrations/utils/code_mapping.py b/src/sentry/integrations/utils/code_mapping.py index 8355345e003d7f..2a7aca1ae17779 100644 --- a/src/sentry/integrations/utils/code_mapping.py +++ b/src/sentry/integrations/utils/code_mapping.py @@ -109,7 +109,6 @@ def __init__(self, frame_file_path: str) -> None: or frame_file_path[0] in ["[", "<"] or frame_file_path.find(" ") > -1 or frame_file_path.find("\\") > -1 # Windows support - or frame_file_path.find("/") == -1 ): raise UnsupportedFrameFilename("This path is not supported.") @@ -150,12 +149,18 @@ def _straight_path_logic(self, frame_file_path: str) -> None: start_at_index = get_straight_path_prefix_end_index(frame_file_path) backslash_index = frame_file_path.find("/", start_at_index) - dir_path, self.file_name = frame_file_path.rsplit("/", 1) # foo.tsx (both) - self.root = frame_file_path[0:backslash_index] # some or .some - self.dir_path = dir_path.replace(self.root, "") # some/path/ (both) - self.file_and_dir_path = remove_straight_path_prefix( - frame_file_path - ) # some/path/foo.tsx (both) + if backslash_index > -1: + dir_path, self.file_name = frame_file_path.rsplit("/", 1) # foo.tsx (both) + self.root = frame_file_path[0:backslash_index] # some or .some + self.dir_path = dir_path.replace(self.root, "") # some/path/ (both) + self.file_and_dir_path = remove_straight_path_prefix( + frame_file_path + ) # some/path/foo.tsx (both) + else: + self.file_name = frame_file_path + self.file_and_dir_path = frame_file_path + self.root = "" + self.dir_path = "" def __repr__(self) -> str: return f"FrameFilename: {self.full_path}" diff --git a/tests/sentry/api/endpoints/test_organization_derive_code_mappings.py b/tests/sentry/api/endpoints/test_organization_derive_code_mappings.py index 5024af9024344b..21a9a5cd8b58ac 100644 --- a/tests/sentry/api/endpoints/test_organization_derive_code_mappings.py +++ b/tests/sentry/api/endpoints/test_organization_derive_code_mappings.py @@ -76,6 +76,29 @@ def test_get_start_with_backslash(self, mock_get_trees_for_org): assert response.status_code == 200, response.content assert response.data == expected_matches + @patch("sentry.integrations.github.GitHubIntegration.get_trees_for_org") + def test_get_top_level_file(self, mock_get_trees_for_org): + file = "index.php" + frame_info = FrameFilename(file) + config_data = {"stacktraceFilename": file} + expected_matches = [ + { + "filename": file, + "repo_name": "getsentry/codemap", + "repo_branch": "master", + "stacktrace_root": f"{frame_info.root}", + "source_path": _get_code_mapping_source_path(file, frame_info), + } + ] + with patch( + "sentry.integrations.utils.code_mapping.CodeMappingTreesHelper.list_file_matches", + return_value=expected_matches, + ): + response = self.client.get(self.url, data=config_data, format="json") + assert mock_get_trees_for_org.call_count == 1 + assert response.status_code == 200, response.content + assert response.data == expected_matches + @patch("sentry.integrations.github.GitHubIntegration.get_trees_for_org") def test_get_multiple_matches(self, mock_get_trees_for_org): config_data = { diff --git a/tests/sentry/integrations/utils/test_code_mapping.py b/tests/sentry/integrations/utils/test_code_mapping.py index 03598c41744a59..de2fa6fd1d9d5f 100644 --- a/tests/sentry/integrations/utils/test_code_mapping.py +++ b/tests/sentry/integrations/utils/test_code_mapping.py @@ -26,19 +26,15 @@ UNSUPPORTED_FRAME_FILENAMES = [ "async https://s1.sentry-cdn.com/_static/dist/sentry/entrypoints/app.js", - "/gtm.js", # Top source; starts with backslash "<anonymous>", "<frozen importlib._bootstrap>", "[native code]", "O$t", "async https://s1.sentry-cdn.com/_static/dist/sentry/entrypoints/app.js", - "/foo/bar/baz", # no extension + "foo/bar/baz", # no extension "README", # no extension - "ssl.py", # XXX: The following will need to be supported "C:\\Users\\Donia\\AppData\\Roaming\\Adobe\\UXP\\Plugins\\External\\452f92d2_0.13.0\\main.js", - "initialization.dart", - "backburner.js", ] @@ -79,6 +75,9 @@ def test_get_extension(): def test_buckets_logic(): stacktraces = [ + "/gtm.js", + "initialization.dart", + "backburner.js", "app://foo.js", "./app/utils/handleXhrErrorResponse.tsx", "getsentry/billing/tax/manager.py", @@ -86,6 +85,11 @@ def test_buckets_logic(): ] + UNSUPPORTED_FRAME_FILENAMES buckets = stacktrace_buckets(stacktraces) assert buckets == { + "": [ + FrameFilename("gtm.js"), + FrameFilename("initialization.dart"), + FrameFilename("backburner.js"), + ], "./app": [FrameFilename("./app/utils/handleXhrErrorResponse.tsx")], "app:": [FrameFilename("app://foo.js")], "cronscripts": [FrameFilename("/cronscripts/monitoringsync.php")], @@ -109,6 +113,14 @@ def test_frame_filename_repr(self): path = "getsentry/billing/tax/manager.py" assert FrameFilename(path).__repr__() == f"FrameFilename: {path}" + def test_frame_filename_root_level(self): + file_name = "index.php" + ff = FrameFilename(file_name) + assert ff.file_name == file_name + assert ff.root == "" + assert ff.dir_path == "" + assert ff.extension == "php" + def test_raises_unsupported(self): for filepath in UNSUPPORTED_FRAME_FILENAMES: with pytest.raises(UnsupportedFrameFilename):
f336c6b1fa426be70ec26c4f073d39e2154011a6
2024-12-06 15:32:00
Fabian Schindler
fix(dynamic-sampling): enusre that at leas one project has count (#81727)
false
enusre that at leas one project has count (#81727)
fix
diff --git a/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py b/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py index ab6a4c5c060466..a1f5115f57cc8c 100644 --- a/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py +++ b/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py @@ -401,6 +401,10 @@ def adjust_sample_rates_of_projects( projects_with_counts = { project_id: count_per_root for project_id, count_per_root, _, _ in projects_with_tx_count } + # The rebalancing will not work (or would make sense) when we have only projects with zero-counts. + if not any(projects_with_counts.values()): + return + # Since we don't mind about strong consistency, we query a replica of the main database with the possibility of # having out of date information. This is a trade-off we accept, since we work under the assumption that eventually # the projects of an org will be replicated consistently across replicas, because no org should continue to create diff --git a/tests/sentry/dynamic_sampling/tasks/test_boost_low_volume_projects.py b/tests/sentry/dynamic_sampling/tasks/test_boost_low_volume_projects.py index 58526a076e5a6c..2453ba9a97b72c 100644 --- a/tests/sentry/dynamic_sampling/tasks/test_boost_low_volume_projects.py +++ b/tests/sentry/dynamic_sampling/tasks/test_boost_low_volume_projects.py @@ -1,5 +1,6 @@ from datetime import timedelta from typing import cast +from unittest.mock import patch from django.utils import timezone @@ -183,6 +184,22 @@ def test_project_mode_sampling_with_query(self): assert get_guarded_project_sample_rate(org1, p1) == 0.2 + @with_feature(["organizations:dynamic-sampling", "organizations:dynamic-sampling-custom"]) + def test_project_mode_sampling_with_query_zero_metrics(self): + organization = self.create_organization("test-org") + project = self.create_project(organization=organization) + + organization.update_option("sentry:sampling_mode", DynamicSamplingMode.PROJECT) + project.update_option("sentry:target_sample_rate", 0.2) + + # make sure that no rebalancing is actually run + with patch( + "sentry.dynamic_sampling.models.projects_rebalancing.ProjectsRebalancingModel._run" + ) as mock_run: + with self.tasks(): + boost_low_volume_projects.delay() + assert not mock_run.called + def test_complex(self): context = TaskContext("rebalancing", 20) org1 = self.create_organization("test-org1")
c8b73ac800c02e304a3ba9be48b0783d59350c7f
2023-01-25 02:53:09
Kev
feat(perf-issues): Limit uncompressed asset detector (#43639)
false
Limit uncompressed asset detector (#43639)
feat
diff --git a/fixtures/events/performance_problems/uncompressed-assets/uncompressed-script-asset.json b/fixtures/events/performance_problems/uncompressed-assets/uncompressed-script-asset.json index 88c3b146a2a108..a0e17f00b3cf7c 100644 --- a/fixtures/events/performance_problems/uncompressed-assets/uncompressed-script-asset.json +++ b/fixtures/events/performance_problems/uncompressed-assets/uncompressed-script-asset.json @@ -44,6 +44,22 @@ "packages": [{"name": "npm:@sentry/react", "version": "7.15.0"}] }, "spans": [ + { + "timestamp": 1667330086.5292, + "start_timestamp": 1667330086.2861, + "exclusive_time": 243.100167, + "description": "https://someother.site.com/asset.js", + "op": "resource.script", + "span_id": "b66a5642da1edb52", + "parent_span_id": "a0c39078d1570b00", + "trace_id": "0102834d0bf74d388ce0b1e15329f731", + "data": { + "Decoded Body Size": 3, + "Encoded Body Size": 2, + "Transfer Size": 3 + }, + "hash": "b2978b51d54d9078" + }, { "timestamp": 1667330086.5292, "start_timestamp": 1667330086.2861, diff --git a/src/sentry/utils/performance_issues/performance_detection.py b/src/sentry/utils/performance_issues/performance_detection.py index 076b345f2f87c3..f1359e6df946bd 100644 --- a/src/sentry/utils/performance_issues/performance_detection.py +++ b/src/sentry/utils/performance_issues/performance_detection.py @@ -1607,13 +1607,14 @@ class UncompressedAssetSpanDetector(PerformanceDetector): Checks for large assets that are affecting load time. """ - __slots__ = "stored_problems" + __slots__ = ("stored_problems", "any_compression") settings_key = DetectorType.UNCOMPRESSED_ASSETS type: DetectorType = DetectorType.UNCOMPRESSED_ASSETS def init(self): self.stored_problems = {} + self.any_compression = False def visit_span(self, span: Span) -> None: op = span.get("op", None) @@ -1638,6 +1639,8 @@ def visit_span(self, span: Span) -> None: # Ignore assets that are already compressed. if encoded_body_size != decoded_body_size: + # Met criteria for a compressed span somewhere in the event. + self.any_compression = True return # Ignore assets that aren't big enough to worry about. @@ -1693,6 +1696,11 @@ def is_event_eligible(cls, event): return True return False + def on_complete(self) -> None: + if not self.any_compression: + # Must have a compressed asset in the event to emit this perf problem. + self.stored_problems = {} + # Reports metrics and creates spans for detection def report_metrics_for_detectors( diff --git a/tests/sentry/utils/performance_issues/test_uncompressed_assets_detector.py b/tests/sentry/utils/performance_issues/test_uncompressed_assets_detector.py index 252d51d1eae067..57cba62907f55a 100644 --- a/tests/sentry/utils/performance_issues/test_uncompressed_assets_detector.py +++ b/tests/sentry/utils/performance_issues/test_uncompressed_assets_detector.py @@ -25,6 +25,18 @@ def create_asset_span( return create_span("resource.script", desc=desc, duration=duration, data=data) +def create_compressed_asset_span(): + return create_asset_span( + desc="https://someothersite.example.com/app.js", + duration=1.0, + data={ + "Transfer Size": 5, + "Encoded Body Size": 4, + "Decoded Body Size": 5, + }, + ) + + @region_silo_test @pytest.mark.django_db class UncompressedAssetsDetectorTest(TestCase): @@ -50,7 +62,8 @@ def test_detects_uncompressed_asset(self): "Encoded Body Size": 1_000_000, "Decoded Body Size": 1_000_000, }, - ) + ), + create_compressed_asset_span(), ], } @@ -81,7 +94,8 @@ def test_detects_uncompressed_asset_stylesheet(self): "Encoded Body Size": 1_000_000, "Decoded Body Size": 1_000_000, }, - ) + ), + create_compressed_asset_span(), ], } @@ -110,7 +124,8 @@ def test_does_not_detect_mobile_uncompressed_asset(self): "Encoded Body Size": 1_000_000, "Decoded Body Size": 1_000_000, }, - ) + ), + create_compressed_asset_span(), ], } @@ -128,7 +143,8 @@ def test_ignores_assets_under_size(self): "Encoded Body Size": 99_999, "Decoded Body Size": 99_999, }, - ) + ), + create_compressed_asset_span(), ], } @@ -146,7 +162,8 @@ def test_ignores_compressed_assets(self): "Encoded Body Size": 101_000, "Decoded Body Size": 100_999, }, - ) + ), + create_compressed_asset_span(), ], } @@ -164,7 +181,8 @@ def test_ignores_assets_under_duration(self): "Encoded Body Size": 101_000, "Decoded Body Size": 101_000, }, - ) + ), + create_compressed_asset_span(), ], }
cb82f94dbbfd24fef39cd344cc19bafc83b279a6
2020-05-08 23:42:07
William Mak
fix(discover): Reducing interval on long queries (#18609)
false
Reducing interval on long queries (#18609)
fix
diff --git a/src/sentry/static/sentry/app/components/charts/utils.tsx b/src/sentry/static/sentry/app/components/charts/utils.tsx index 3796f995fda678..b29ade9cdaa8c1 100644 --- a/src/sentry/static/sentry/app/components/charts/utils.tsx +++ b/src/sentry/static/sentry/app/components/charts/utils.tsx @@ -8,6 +8,7 @@ import {escape} from 'app/utils'; const DEFAULT_TRUNCATE_LENGTH = 80; // In minutes +const THIRTY_DAYS = 43200; const TWENTY_FOUR_HOURS = 1440; const ONE_HOUR = 60; @@ -36,6 +37,15 @@ export function useShortInterval(datetimeObj: DateTimeObject): boolean { export function getInterval(datetimeObj: DateTimeObject, highFidelity = false) { const diffInMinutes = getDiffInMinutes(datetimeObj); + if (diffInMinutes >= THIRTY_DAYS) { + // Greater than or equal to 30 days + if (highFidelity) { + return '1h'; + } else { + return '24h'; + } + } + if (diffInMinutes > TWENTY_FOUR_HOURS) { // Greater than 24 hours if (highFidelity) {
39f46892f34b074e8d461b3cbcc08aa56d264dfb
2021-03-25 03:27:17
Tony
feat(trace-view): Add link to trace view to discover (#24689)
false
Add link to trace view to discover (#24689)
feat
diff --git a/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx b/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx index 08bca907d18e09..81a0ac3583e44c 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/table/tableView.tsx @@ -27,6 +27,7 @@ import {DisplayModes, TOP_N} from 'app/utils/discover/types'; import {eventDetailsRouteWithEventView, generateEventSlug} from 'app/utils/discover/urls'; import {stringifyQueryObject, tokenizeSearch} from 'app/utils/tokenizeSearch'; import withProjects from 'app/utils/withProjects'; +import {getTraceDetailsUrl} from 'app/views/performance/traceDetails/utils'; import {transactionSummaryRouteWithQuery} from 'app/views/performance/transactionSummary/utils'; import {getExpandedResults, pushEventViewToLocation} from '../utils'; @@ -242,6 +243,24 @@ class TableView extends React.Component<TableViewProps> { </StyledLink> </Tooltip> ); + } else if (columnKey === 'trace') { + const dateSelection = eventView.normalizeDateSelection(location); + if (dataRow.trace) { + const target = getTraceDetailsUrl( + organization, + String(dataRow.trace), + dateSelection, + {} + ); + + cell = ( + <Tooltip title={t('View Trace')}> + <StyledLink data-test-id="view-trace" to={target}> + {cell} + </StyledLink> + </Tooltip> + ); + } } return (
6cad5201201ecc76af86cb65abeb32353ec76995
2023-05-04 22:23:15
William Mak
feat(starfish): Add spans to events-stats (#48437)
false
Add spans to events-stats (#48437)
feat
diff --git a/src/sentry/api/bases/organization_events.py b/src/sentry/api/bases/organization_events.py index aeebb9f274d88b..96ad54735d6387 100644 --- a/src/sentry/api/bases/organization_events.py +++ b/src/sentry/api/bases/organization_events.py @@ -393,6 +393,7 @@ def get_event_stats_data( zerofill_results: bool = True, comparison_delta: Optional[timedelta] = None, additional_query_column: Optional[str] = None, + dataset: Optional[Any] = None, ) -> Dict[str, Any]: with self.handle_query_errors(): with sentry_sdk.start_span( @@ -514,7 +515,12 @@ def get_event_stats_data( extra_columns=extra_columns, ) serialized_result["meta"] = self.handle_results_with_meta( - request, organization, params.get("project_id", []), result.data, True + request, + organization, + params.get("project_id", []), + result.data, + True, + dataset=dataset, )["meta"] return serialized_result diff --git a/src/sentry/api/endpoints/organization_events_stats.py b/src/sentry/api/endpoints/organization_events_stats.py index de964374ff81da..f9fd422c5b7dbb 100644 --- a/src/sentry/api/endpoints/organization_events_stats.py +++ b/src/sentry/api/endpoints/organization_events_stats.py @@ -83,6 +83,7 @@ def get_features(self, organization: Organization, request: Request) -> Mapping[ "organizations:dashboards-mep", "organizations:mep-rollout-flag", "organizations:use-metrics-layer", + "organizations:starfish-view", ] batch_features = features.batch_has( feature_names, @@ -168,7 +169,9 @@ def get(self, request: Request, organization: Organization) -> Response: use_metrics_layer = batch_features.get("organizations:use-metrics-layer", False) - use_custom_dataset = use_metrics or use_profiles or use_occurrences + starfish_view = batch_features.get("organizations:starfish_view", False) + + use_custom_dataset = use_metrics or use_profiles or use_occurrences or starfish_view dataset = self.get_dataset(request) if use_custom_dataset else discover metrics_enhanced = dataset in {metrics_performance, metrics_enhanced_performance} @@ -224,6 +227,7 @@ def get_event_stats( request.GET.get("withoutZerofill") == "1" and has_chart_interpolation ), comparison_delta=comparison_delta, + dataset=discover if top_events > 0 else dataset, ), status=200, ) diff --git a/src/sentry/search/events/builder/__init__.py b/src/sentry/search/events/builder/__init__.py index fcf80b8b14e0a7..b63b3ea021aa99 100644 --- a/src/sentry/search/events/builder/__init__.py +++ b/src/sentry/search/events/builder/__init__.py @@ -22,7 +22,7 @@ SessionsV2QueryBuilder, TimeseriesSessionsV2QueryBuilder, ) -from .spans_indexed import SpansIndexedQueryBuilder # NOQA +from .spans_indexed import SpansIndexedQueryBuilder, TimeseriesSpanIndexedQueryBuilder # NOQA __all__ = [ "HistogramQueryBuilder", diff --git a/src/sentry/search/events/builder/spans_indexed.py b/src/sentry/search/events/builder/spans_indexed.py index 4acbeac2136121..cd0cf9885e52aa 100644 --- a/src/sentry/search/events/builder/spans_indexed.py +++ b/src/sentry/search/events/builder/spans_indexed.py @@ -1,6 +1,8 @@ from typing import Optional -from sentry.search.events.builder import QueryBuilder +from snuba_sdk import Column, Function + +from sentry.search.events.builder import QueryBuilder, TimeseriesQueryBuilder class SpansIndexedQueryBuilder(QueryBuilder): @@ -13,3 +15,7 @@ def get_field_type(self, field: str) -> Optional[str]: return "duration" return None + + +class TimeseriesSpanIndexedQueryBuilder(TimeseriesQueryBuilder): + time_column = Function("toStartOfHour", [Column("end_timestamp")], "time") diff --git a/src/sentry/snuba/spans_indexed.py b/src/sentry/snuba/spans_indexed.py index 32f4bf5124cc5e..134a87df654061 100644 --- a/src/sentry/snuba/spans_indexed.py +++ b/src/sentry/snuba/spans_indexed.py @@ -1,5 +1,12 @@ -from sentry.search.events.builder import SpansIndexedQueryBuilder -from sentry.utils.snuba import Dataset +from datetime import timedelta +from typing import Dict, List, Optional, Sequence + +import sentry_sdk + +from sentry.discover.arithmetic import categorize_columns +from sentry.search.events.builder import SpansIndexedQueryBuilder, TimeseriesSpanIndexedQueryBuilder +from sentry.snuba import discover +from sentry.utils.snuba import Dataset, SnubaTSResult def query( @@ -49,3 +56,57 @@ def query( result = builder.process_results(builder.run_query(referrer)) return result + + +def timeseries_query( + selected_columns: Sequence[str], + query: str, + params: Dict[str, str], + rollup: int, + referrer: str, + zerofill_results: bool = True, + allow_metric_aggregates=True, + comparison_delta: Optional[timedelta] = None, + functions_acl: Optional[List[str]] = None, + has_metrics: bool = True, + use_metrics_layer: bool = False, +) -> SnubaTSResult: + """ + High-level API for doing arbitrary user timeseries queries against events. + this API should match that of sentry.snuba.discover.timeseries_query + """ + equations, columns = categorize_columns(selected_columns) + + with sentry_sdk.start_span(op="mep", description="TimeseriesSpanIndexedQueryBuilder"): + query = TimeseriesSpanIndexedQueryBuilder( + Dataset.SpansIndexed, + params, + rollup, + query=query, + selected_columns=columns, + functions_acl=functions_acl, + ) + result = query.run_query(referrer) + with sentry_sdk.start_span(op="mep", description="query.transform_results"): + result = query.process_results(result) + result["data"] = ( + discover.zerofill( + result["data"], + params["start"], + params["end"], + rollup, + "time", + ) + if zerofill_results + else result["data"] + ) + + return SnubaTSResult( + { + "data": result["data"], + "meta": result["meta"], + }, + params["start"], + params["end"], + rollup, + )
c232d7ddeb9bec1f6dace381a1d84f95508dffab
2020-11-12 15:56:20
Evan Purkhiser
chore(ts): Convert adminRelays (#21978)
false
Convert adminRelays (#21978)
chore
diff --git a/src/sentry/static/sentry/app/views/admin/adminRelays.jsx b/src/sentry/static/sentry/app/views/admin/adminRelays.tsx similarity index 50% rename from src/sentry/static/sentry/app/views/admin/adminRelays.jsx rename to src/sentry/static/sentry/app/views/admin/adminRelays.tsx index 8924bd9322e8a1..08546998406f0c 100644 --- a/src/sentry/static/sentry/app/views/admin/adminRelays.jsx +++ b/src/sentry/static/sentry/app/views/admin/adminRelays.tsx @@ -1,59 +1,56 @@ -/* eslint-disable react/jsx-key */ -import PropTypes from 'prop-types'; import React from 'react'; import moment from 'moment'; -import createReactClass from 'create-react-class'; +import {RouteComponentProps} from 'react-router/lib/Router'; import {t} from 'app/locale'; import withApi from 'app/utils/withApi'; import ResultGrid from 'app/components/resultGrid'; import LinkWithConfirmation from 'app/components/links/linkWithConfirmation'; +import {Client} from 'app/api'; -const prettyDate = function (x) { - return moment(x).format('ll LTS'); -}; +const prettyDate = (x: string) => moment(x).format('ll LTS'); -const AdminRelays = createReactClass({ - displayName: 'GroupEventDetails', +type Props = RouteComponentProps<{}, {}> & {api: Client}; - propTypes: { - api: PropTypes.object, - }, +type State = { + loading: boolean; +}; - getInitialState() { - return { - loading: false, - }; - }, +type RelayRow = { + id: string; + relayId: string; + publicKey: string; + firstSeen: string; + lastSeen: string; +}; - onDelete(key) { - this.setState({ - loading: true, - }); +class AdminRelays extends React.Component<Props, State> { + state: State = { + loading: false, + }; + + onDelete(key: string) { + this.setState({loading: true}); this.props.api.request(`/relays/${key}/`, { method: 'DELETE', - success: () => { - this.setState({ - loading: false, - }); - }, - error: () => { - this.setState({ - loading: false, - }); - }, + success: () => this.setState({loading: false}), + error: () => this.setState({loading: false}), }); - }, + } - getRow(row) { + getRow(row: RelayRow) { return [ - <td> + <td key="id"> <strong>{row.relayId}</strong> </td>, - <td>{row.publicKey}</td>, - <td style={{textAlign: 'right'}}>{prettyDate(row.firstSeen)}</td>, - <td style={{textAlign: 'right'}}>{prettyDate(row.lastSeen)}</td>, - <td style={{textAlign: 'right'}}> + <td key="key">{row.publicKey}</td>, + <td key="firstSeen" style={{textAlign: 'right'}}> + {prettyDate(row.firstSeen)} + </td>, + <td key="lastSeen" style={{textAlign: 'right'}}> + {prettyDate(row.lastSeen)} + </td>, + <td key="tools" style={{textAlign: 'right'}}> <span className="editor-tools"> <LinkWithConfirmation className="danger" @@ -66,15 +63,21 @@ const AdminRelays = createReactClass({ </span> </td>, ]; - }, + } render() { const columns = [ - <th style={{width: 350, textAlign: 'left'}}>Relay</th>, - <th>Public Key</th>, - <th style={{width: 150, textAlign: 'right'}}>First seen</th>, - <th style={{width: 150, textAlign: 'right'}}>Last seen</th>, - <th />, + <th key="id" style={{width: 350, textAlign: 'left'}}> + Relay + </th>, + <th key="key">Public Key</th>, + <th key="firstSeen" style={{width: 150, textAlign: 'right'}}> + First seen + </th>, + <th key="lastSeen" style={{width: 150, textAlign: 'right'}}> + Last seen + </th>, + <th key="tools" />, ]; return ( @@ -97,8 +100,8 @@ const AdminRelays = createReactClass({ /> </div> ); - }, -}); + } +} export {AdminRelays};
3832a64858da825992ec23261addebefd044d4c0
2022-03-16 22:49:10
Evan Purkhiser
chore(deps): Bump react-grid-layout from 1.3.0 -> 1.3.4 (#32677)
false
Bump react-grid-layout from 1.3.0 -> 1.3.4 (#32677)
chore
diff --git a/package.json b/package.json index d10af524b33ae7..40b95a4dbcfd59 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "@types/react-date-range": "^1.1.5", "@types/react-document-title": "^2.0.5", "@types/react-dom": "~17.0.9", - "@types/react-grid-layout": "^1.3.0", + "@types/react-grid-layout": "^1.3.2", "@types/react-mentions": "4.1.2", "@types/react-router": "^3.0.22", "@types/react-select": "3.0.8", @@ -117,7 +117,7 @@ "react-date-range": "^1.3.0", "react-document-title": "2.0.3", "react-dom": "17.0.2", - "react-grid-layout": "^1.3.0", + "react-grid-layout": "^1.3.4", "react-hotkeys-hook": "^3.4.3", "react-lazyload": "^2.3.0", "react-mentions": "4.3.0", diff --git a/yarn.lock b/yarn.lock index 735a9be0733cfb..98b6378a8d3455 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4367,10 +4367,10 @@ dependencies: "@types/react" "*" -"@types/react-grid-layout@^1.3.0": - version "1.3.0" - resolved "https://registry.yarnpkg.com/@types/react-grid-layout/-/react-grid-layout-1.3.0.tgz#aa00b2b8de350aa7f6c570e69d7a0daf571de24c" - integrity sha512-Pytm7lvm4h91yN9CpdjV8IpU/hgVRHrUhDEIX593e4Mx9V14Pr3gWtj21WHzy5bDqU//jnGGVVSYJ3QVuI1NaQ== +"@types/react-grid-layout@^1.3.2": + version "1.3.2" + resolved "https://registry.yarnpkg.com/@types/react-grid-layout/-/react-grid-layout-1.3.2.tgz#9f195666a018a5ae2b773887e3b552cb4378d67f" + integrity sha512-ZzpBEOC1JTQ7MGe1h1cPKSLP4jSWuxc+yvT4TsAlEW9+EFPzAf8nxQfFd7ea9gL17Em7PbwJZAsiwfQQBUklZQ== dependencies: "@types/react" "*" @@ -13191,14 +13191,14 @@ react-fast-compare@^3.0.1, react-fast-compare@^3.2.0: resolved "https://registry.yarnpkg.com/react-fast-compare/-/react-fast-compare-3.2.0.tgz#641a9da81b6a6320f270e89724fb45a0b39e43bb" integrity sha512-rtGImPZ0YyLrscKI9xTpV8psd6I8VAtjKCzQDlzyDvqJA8XOW78TXYQwNRNd8g8JZnDu8q9Fu/1v4HPAVwVdHA== -react-grid-layout@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/react-grid-layout/-/react-grid-layout-1.3.0.tgz#ca8a3e13e62ee2162fa658b1eec4b8eec0203dbd" - integrity sha512-WqFwybAItXu0AaSt9YL8+9xE5YotIzMcCYE0Q9XBqSKNyShTxPbC0LjObV/tOWZoADNWJ+osseVfRoZsjzwWXg== +react-grid-layout@^1.3.4: + version "1.3.4" + resolved "https://registry.yarnpkg.com/react-grid-layout/-/react-grid-layout-1.3.4.tgz#4fa819be24a1ba9268aa11b82d63afc4762a32ff" + integrity sha512-sB3rNhorW77HUdOjB4JkelZTdJGQKuXLl3gNg+BI8gJkTScspL1myfZzW/EM0dLEn+1eH+xW+wNqk0oIM9o7cw== dependencies: - classnames "2.3.1" + clsx "^1.1.1" lodash.isequal "^4.0.0" - prop-types "^15.0.0" + prop-types "^15.8.1" react-draggable "^4.0.0" react-resizable "^3.0.4"
640550f807ca11e04920bd168be8ac1f2b46cd7b
2020-10-01 18:54:31
Markus Unterwaditzer
feat: Reprocessing 2.1 -- Delete old data (#21030)
false
Reprocessing 2.1 -- Delete old data (#21030)
feat
diff --git a/src/sentry/api/endpoints/event_reprocessing.py b/src/sentry/api/endpoints/event_reprocessing.py deleted file mode 100644 index 0220b869f4a469..00000000000000 --- a/src/sentry/api/endpoints/event_reprocessing.py +++ /dev/null @@ -1,33 +0,0 @@ -from __future__ import absolute_import - -import time - -from sentry import features -from sentry.api.bases.project import ProjectEndpoint -from sentry.tasks.reprocessing2 import reprocess_event - - -class EventReprocessingEndpoint(ProjectEndpoint): - def post(self, request, project, event_id): - """ - Reprocess a single event - ```````````````````````` - - Triggers reprocessing for a single event. Currently this means - duplicating the event with a new event ID and bumped timestamps. - - :pparam string organization_slug: the slug of the organization the - issues belong to. - :pparam string project_slug: the slug of the project the event - belongs to. - :pparam string event_id: the id of the event. - :auth: required - """ - if not features.has("projects:reprocessing-v2", project, actor=request.user): - return self.respond(status=404) - - start_time = time.time() - - reprocess_event.delay(project_id=project.id, event_id=event_id, start_time=start_time) - - return self.respond(status=200) diff --git a/src/sentry/api/endpoints/group_details.py b/src/sentry/api/endpoints/group_details.py index 804ff1fff1370c..78d3aa42e17a60 100644 --- a/src/sentry/api/endpoints/group_details.py +++ b/src/sentry/api/endpoints/group_details.py @@ -3,14 +3,13 @@ from datetime import timedelta import functools import logging -from uuid import uuid4 from django.utils import timezone from rest_framework.response import Response import sentry_sdk -from sentry import eventstream, tsdb, tagstore +from sentry import tsdb, tagstore from sentry.api import client from sentry.api.base import DocSection, EnvironmentMixin from sentry.api.bases import GroupEndpoint @@ -21,7 +20,6 @@ from sentry.models import ( Activity, Group, - GroupHash, GroupRelease, GroupSeen, GroupStatus, @@ -430,35 +428,14 @@ def delete(self, request, group): """ try: from sentry.utils import snuba - from sentry.tasks.deletion import delete_groups + from sentry.group_deletion import delete_group - updated = ( - Group.objects.filter(id=group.id) - .exclude( - status__in=[GroupStatus.PENDING_DELETION, GroupStatus.DELETION_IN_PROGRESS] - ) - .update(status=GroupStatus.PENDING_DELETION) - ) - if updated: - project = group.project - - eventstream_state = eventstream.start_delete_groups(group.project_id, [group.id]) - transaction_id = uuid4().hex - - GroupHash.objects.filter(project_id=group.project_id, group__id=group.id).delete() - - delete_groups.apply_async( - kwargs={ - "object_ids": [group.id], - "transaction_id": transaction_id, - "eventstream_state": eventstream_state, - }, - countdown=3600, - ) + transaction_id = delete_group(group) + if transaction_id: self.create_audit_entry( request=request, - organization_id=project.organization_id if project else None, + organization_id=group.project.organization_id if group.project else None, target_object=group.id, transaction_id=transaction_id, ) @@ -472,9 +449,11 @@ def delete(self, request, group): }, ) + # This is exclusively used for analytics, as such it should not run as part of reprocessing. issue_deleted.send_robust( group=group, user=request.user, delete_type="delete", sender=self.__class__ ) + metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 200}) return Response(status=202) except snuba.RateLimitExceeded: diff --git a/src/sentry/api/endpoints/group_reprocessing.py b/src/sentry/api/endpoints/group_reprocessing.py index c59031af5b69ef..db7c1fedd2ae27 100644 --- a/src/sentry/api/endpoints/group_reprocessing.py +++ b/src/sentry/api/endpoints/group_reprocessing.py @@ -33,7 +33,18 @@ def post(self, request, group): """ if not features.has("projects:reprocessing-v2", group.project, actor=request.user): - return self.respond(status=404) + return self.respond( + {"error": "This project does not have the reprocessing v2 feature"}, status=404, + ) - reprocess_group.delay(project_id=group.project_id, group_id=group.id) + max_events = request.data.get("maxEvents") + if max_events: + max_events = int(max_events) + + if max_events <= 0: + return self.respond({"error": "maxEvents must be at least 1"}, status=400,) + else: + max_events = None + + reprocess_group.delay(project_id=group.project_id, group_id=group.id, max_events=max_events) return self.respond(status=200) diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py index 7eb60b409af09d..e7602c074cefd2 100644 --- a/src/sentry/api/urls.py +++ b/src/sentry/api/urls.py @@ -29,7 +29,6 @@ from .endpoints.event_apple_crash_report import EventAppleCrashReportEndpoint from .endpoints.event_attachment_details import EventAttachmentDetailsEndpoint from .endpoints.event_attachments import EventAttachmentsEndpoint -from .endpoints.event_reprocessing import EventReprocessingEndpoint from .endpoints.event_file_committers import EventFileCommittersEndpoint from .endpoints.event_grouping_info import EventGroupingInfoEndpoint from .endpoints.event_owners import EventOwnersEndpoint @@ -1290,11 +1289,6 @@ EventAttachmentDetailsEndpoint.as_view(), name="sentry-api-0-event-attachment-details", ), - url( - r"^(?P<organization_slug>[^\/]+)/(?P<project_slug>[^\/]+)/events/(?P<event_id>[\w-]+)/reprocessing/$", - EventReprocessingEndpoint.as_view(), - name="sentry-api-0-event-reprocessing", - ), url( r"^(?P<organization_slug>[^\/]+)/(?P<project_slug>[^\/]+)/events/(?P<event_id>[\w-]+)/committers/$", EventFileCommittersEndpoint.as_view(), diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 167ec35593ecc2..77f587770260bc 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1990,3 +1990,5 @@ def get_sentry_sdk_config(): SENTRY_USE_UWSGI = True SENTRY_REPROCESSING_ATTACHMENT_CHUNK_SIZE = 2 ** 20 + +SENTRY_REPROCESSING_SYNC_REDIS_CLUSTER = "default" diff --git a/src/sentry/group_deletion.py b/src/sentry/group_deletion.py new file mode 100644 index 00000000000000..1ae6a4a3f2a841 --- /dev/null +++ b/src/sentry/group_deletion.py @@ -0,0 +1,36 @@ +from __future__ import absolute_import + +from uuid import uuid4 + +from sentry import eventstream + +from sentry.models.group import Group, GroupStatus +from sentry.models.grouphash import GroupHash +from sentry.tasks.deletion import delete_groups + + +def delete_group(group): + updated = ( + Group.objects.filter(id=group.id) + .exclude(status__in=[GroupStatus.PENDING_DELETION, GroupStatus.DELETION_IN_PROGRESS]) + .update(status=GroupStatus.PENDING_DELETION) + ) + + if not updated: + return + + eventstream_state = eventstream.start_delete_groups(group.project_id, [group.id]) + transaction_id = uuid4().hex + + GroupHash.objects.filter(project_id=group.project_id, group__id=group.id).delete() + + delete_groups.apply_async( + kwargs={ + "object_ids": [group.id], + "transaction_id": transaction_id, + "eventstream_state": eventstream_state, + }, + countdown=3600, + ) + + return transaction_id diff --git a/src/sentry/models/group.py b/src/sentry/models/group.py index d1dfcf00b96caa..3272fc2400cc37 100644 --- a/src/sentry/models/group.py +++ b/src/sentry/models/group.py @@ -125,6 +125,10 @@ class GroupStatus(object): DELETION_IN_PROGRESS = 4 PENDING_MERGE = 5 + # The group's events are being re-processed and after that the group will + # be deleted. In this state no new events shall be added to the group. + REPROCESSING = 6 + # TODO(dcramer): remove in 9.0 MUTED = IGNORED diff --git a/src/sentry/reprocessing2.py b/src/sentry/reprocessing2.py index 2ffc1e409f2bd6..83b4e711e27d60 100644 --- a/src/sentry/reprocessing2.py +++ b/src/sentry/reprocessing2.py @@ -10,11 +10,15 @@ from sentry import nodestore, features, eventstore from sentry.attachments import CachedAttachment, attachment_cache from sentry.models import EventAttachment +from sentry.utils import snuba from sentry.utils.cache import cache_key_for_event +from sentry.utils.redis import redis_clusters from sentry.eventstore.processing import event_processing_store logger = logging.getLogger("sentry.reprocessing") +_REDIS_SYNC_TTL = 3600 + def _generate_unprocessed_event_node_id(project_id, event_id): return hashlib.md5( @@ -68,6 +72,8 @@ def reprocess_event(project_id, event_id, start_time): with sentry_sdk.start_span(op="reprocess_events.nodestore.get"): data = nodestore.get(node_id) + if data is None: + return from sentry.event_manager import set_tag from sentry.tasks.store import preprocess_event_from_reprocessing @@ -89,11 +95,9 @@ def reprocess_event(project_id, event_id, start_time): set_tag(data, "original_group_id", event.group_id) + # XXX: reuse event IDs event_id = data["event_id"] = uuid.uuid4().hex - # XXX: Only reset received - data["timestamp"] = data["received"] = start_time - cache_key = event_processing_store.store(data) # Step 2: Copy attachments into attachment cache @@ -167,26 +171,68 @@ def is_reprocessed_event(data): def _get_original_event_id(data): from sentry.event_manager import get_tag + # XXX: Get rid of this tag once we reuse event IDs return get_tag(data, "original_event_id") -def should_save_reprocessed_event(data): - if not data: - return False +def _get_original_group_id(data): + from sentry.event_manager import get_tag + + # XXX: Have real snuba column + return get_tag(data, "original_group_id") + + +def _get_sync_redis_client(): + return redis_clusters.get(settings.SENTRY_REPROCESSING_SYNC_REDIS_CLUSTER) + + +def _get_sync_counter_key(group_id): + return "re2:count:{}".format(group_id) + + +def mark_event_reprocessed(data): + """ + This function is supposed to be unconditionally called when an event has + finished reprocessing, regardless of whether it has been saved or not. + """ + if not is_reprocessed_event(data): + return + + key = _get_sync_counter_key(_get_original_group_id(data)) + _get_sync_redis_client().decr(key) - orig_id = _get_original_event_id(data) - if not orig_id: - return True +def start_group_reprocessing(project_id, group_id, max_events=None): + from sentry.models.group import Group, GroupStatus + from sentry.models.grouphash import GroupHash + from django.db import transaction - orig_event = eventstore.get_event_by_id(project_id=data["project"], event_id=orig_id) + with transaction.atomic(): + Group.objects.filter(id=group_id).update(status=GroupStatus.REPROCESSING) + # Remove all grouphashes such that new events get sorted into a + # different group. + GroupHash.objects.filter(group_id=group_id).delete() - if not orig_event: - return True + # Get event counts of issue (for all environments etc). This was copypasted + # and simplified from groupserializer. + event_count = snuba.aliased_query( + aggregations=[["count()", "", "times_seen"]], # select + dataset=snuba.Dataset.Events, # from + conditions=[["group_id", "=", group_id], ["project_id", "=", project_id]], # where + referrer="reprocessing2.start_group_reprocessing", + )["data"][0]["times_seen"] - for prop in ("threads", "stacktrace", "exception", "debug_meta"): - old_data = orig_event.data.get(prop) - if old_data != data.get(prop): - return True + if max_events is not None: + event_count = min(event_count, max_events) + + key = _get_sync_counter_key(group_id) + _get_sync_redis_client().setex(key, _REDIS_SYNC_TTL, event_count) + + +def is_group_finished(group_id): + """ + Checks whether a group has finished reprocessing. + """ - return False + pending = int(_get_sync_redis_client().get(_get_sync_counter_key(group_id))) + return pending <= 0 diff --git a/src/sentry/static/sentry/app/components/events/errors.tsx b/src/sentry/static/sentry/app/components/events/errors.tsx index 8f6210612286cc..6eb66fb9f4b557 100644 --- a/src/sentry/static/sentry/app/components/events/errors.tsx +++ b/src/sentry/static/sentry/app/components/events/errors.tsx @@ -3,34 +3,19 @@ import React from 'react'; import styled from '@emotion/styled'; import uniqWith from 'lodash/uniqWith'; import isEqual from 'lodash/isEqual'; -import {browserHistory} from 'react-router'; - -import {openModal} from 'app/actionCreators/modal'; -import Button from 'app/components/button'; -import ButtonBar from 'app/components/buttonBar'; -import { - addErrorMessage, - addLoadingMessage, - clearIndicators, -} from 'app/actionCreators/indicator'; -import {Client} from 'app/api'; + import EventErrorItem from 'app/components/events/errorItem'; -import {Event, AvatarProject, Project} from 'app/types'; +import {Event} from 'app/types'; import {IconWarning} from 'app/icons'; import {t, tn} from 'app/locale'; import space from 'app/styles/space'; -import withApi from 'app/utils/withApi'; import {BannerContainer, BannerSummary} from './styles'; const MAX_ERRORS = 100; type Props = { - api: Client; event: Event; - orgId: string; - project: AvatarProject | Project; - issueId?: string; }; type State = { @@ -39,11 +24,7 @@ type State = { class EventErrors extends React.Component<Props, State> { static propTypes: any = { - api: PropTypes.object.isRequired, event: PropTypes.object.isRequired, - orgId: PropTypes.string.isRequired, - project: PropTypes.object.isRequired, - issueId: PropTypes.string, }; state: State = { @@ -63,109 +44,8 @@ class EventErrors extends React.Component<Props, State> { uniqueErrors = (errors: any[]) => uniqWith(errors, isEqual); - onReprocessEvent = async () => { - const {api, orgId, project, event} = this.props; - const endpoint = `/projects/${orgId}/${project.slug}/events/${event.id}/reprocessing/`; - - addLoadingMessage(t('Reprocessing event\u2026')); - - try { - await api.requestPromise(endpoint, { - method: 'POST', - }); - } catch { - clearIndicators(); - addErrorMessage( - t('Failed to start reprocessing. The event is likely too far in the past.') - ); - return; - } - - clearIndicators(); - browserHistory.push( - `/organizations/${orgId}/issues/?query=tags[original_event_id]:${event.id}` - ); - }; - - onReprocessGroup = async (issueId: string) => { - const {api, orgId} = this.props; - const endpoint = `/organizations/${orgId}/issues/${issueId}/reprocessing/`; - - addLoadingMessage(t('Reprocessing issue\u2026')); - - try { - await api.requestPromise(endpoint, { - method: 'POST', - }); - } catch { - clearIndicators(); - addErrorMessage( - t('Failed to start reprocessing. The event is likely too far in the past.') - ); - return; - } - - clearIndicators(); - browserHistory.push( - `/organizations/${orgId}/issues/?query=tags[original_group_id]:${issueId}` - ); - }; - - onReprocessStart = () => { - openModal(this.renderReprocessModal); - }; - - renderReprocessModal = ({Body, closeModal, Footer}) => { - const {issueId} = this.props; - return ( - <React.Fragment> - <Body> - <p> - {t( - 'You can choose to re-process events to see if your errors have been resolved. Keep the following limitations in mind:' - )} - </p> - - <ul> - <li> - {t( - 'Sentry will duplicate events in your project (for now) and not delete the old versions.' - )} - </li> - <li> - {t( - 'Reprocessing one or multiple events counts against your quota, but bypasses rate limits.' - )} - </li> - <li> - {t( - 'If an event is reprocessed but did not change, we will not create the new version and not bill you for it (for now).' - )} - </li> - <li> - {t( - 'If you have provided missing symbols please wait at least 1 hour before attempting to re-process. This is a limitation we will try to get rid of.' - )} - </li> - </ul> - </Body> - <Footer> - <ButtonBar gap={1}> - {issueId && ( - <Button onClick={() => this.onReprocessGroup(issueId)}> - {t('Reprocess all events in issue')} - </Button> - )} - <Button onClick={this.onReprocessEvent}>{t('Reprocess single event')}</Button> - <Button onClick={closeModal}>{t('Cancel')}</Button> - </ButtonBar> - </Footer> - </React.Fragment> - ); - }; - render() { - const {event, project} = this.props; + const {event} = this.props; // XXX: uniqueErrors is not performant with large datasets const errors = event.errors.length > MAX_ERRORS ? event.errors : this.uniqueErrors(event.errors); @@ -194,12 +74,6 @@ class EventErrors extends React.Component<Props, State> { {errors.map((error, errorIdx) => ( <EventErrorItem key={errorIdx} error={error} /> ))} - - {(project as Project)?.features?.includes('reprocessing-v2') && ( - <Button size="xsmall" onClick={this.onReprocessStart}> - {t('Try again')} - </Button> - )} </ErrorList> </StyledBanner> ); @@ -242,4 +116,4 @@ const ErrorList = styled('ul')` } `; -export default withApi<Props>(EventErrors); +export default EventErrors; diff --git a/src/sentry/static/sentry/app/components/events/eventEntries.tsx b/src/sentry/static/sentry/app/components/events/eventEntries.tsx index 7273c521864346..54ea46a52c64f6 100644 --- a/src/sentry/static/sentry/app/components/events/eventEntries.tsx +++ b/src/sentry/static/sentry/app/components/events/eventEntries.tsx @@ -212,12 +212,7 @@ class EventEntries extends React.Component<Props> { <div className={className} data-test-id="event-entries"> {hasErrors && ( <ErrorContainer> - <EventErrors - event={event} - orgId={organization.slug} - project={project} - issueId={group?.id ?? event.groupID} - /> + <EventErrors event={event} /> </ErrorContainer> )} {!isShare && diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx index cae200ff14b1e8..6fd7373062eb41 100644 --- a/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx +++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx @@ -21,13 +21,15 @@ import FeatureDisabled from 'app/components/acl/featureDisabled'; import GroupActions from 'app/actions/groupActions'; import GuideAnchor from 'app/components/assistant/guideAnchor'; import IgnoreActions from 'app/components/actions/ignore'; -import {IconDelete, IconStar} from 'app/icons'; +import {IconDelete, IconStar, IconRefresh} from 'app/icons'; import Link from 'app/components/links/link'; import LinkWithConfirmation from 'app/components/links/linkWithConfirmation'; import MenuItem from 'app/components/menuItem'; +import ReprocessingForm from 'app/views/organizationGroupDetails/reprocessingForm'; import ResolveActions from 'app/components/actions/resolve'; import SentryTypes from 'app/sentryTypes'; import ShareIssue from 'app/components/shareIssue'; +import Tooltip from 'app/components/tooltip'; import space from 'app/styles/space'; import withApi from 'app/utils/withApi'; import withOrganization from 'app/utils/withOrganization'; @@ -201,6 +203,13 @@ const GroupDetailsActions = createReactClass({ ); }, + onReprocess() { + const {group, organization} = this.props; + openModal(props => ( + <ReprocessingForm group={group} organization={organization} {...props} /> + )); + }, + onShare(shared) { const {group, project, organization} = this.props; this.setState({shareBusy: true}); @@ -264,6 +273,7 @@ const GroupDetailsActions = createReactClass({ render() { const {group, project, organization} = this.props; const orgFeatures = new Set(organization.features); + const projectFeatures = new Set(project.features); const buttonClassName = 'btn btn-default btn-sm'; let bookmarkClassName = `group-bookmark ${buttonClassName}`; @@ -298,6 +308,17 @@ const GroupDetailsActions = createReactClass({ onDelete={this.onDelete} onDiscard={this.onDiscard} /> + {projectFeatures.has('reprocessing-v2') && ( + <div className="btn-group"> + <Tooltip title={t('Reprocess this issue')}> + <div className={buttonClassName} onClick={this.onReprocess}> + <IconWrapper> + <IconRefresh isSolid size="xs" /> + </IconWrapper> + </div> + </Tooltip> + </div> + )} {orgFeatures.has('shared-issues') && ( <div className="btn-group"> <ShareIssue diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingForm.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingForm.tsx new file mode 100644 index 00000000000000..d9895862ff51f6 --- /dev/null +++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingForm.tsx @@ -0,0 +1,123 @@ +import React from 'react'; +import {browserHistory} from 'react-router'; + +import {Group, Organization} from 'app/types'; +import {t, tct} from 'app/locale'; +import {ModalRenderProps} from 'app/actionCreators/modal'; +import FeatureBadge from 'app/components/featureBadge'; +import Alert from 'app/components/alert'; +import NumberField from 'app/components/forms/numberField'; +import ApiForm from 'app/components/forms/apiForm'; +import ExternalLink from 'app/components/links/externalLink'; + +type Props = ModalRenderProps & { + group: Group; + organization: Organization; +}; + +class ReprocessingForm extends React.Component<Props> { + onSuccess = () => { + const {group, organization} = this.props; + browserHistory.push( + `/organizations/${organization.slug}/issues/?query=tags[original_group_id]:${group.id}` + ); + }; + + getEndpoint() { + const {group, organization} = this.props; + return `/organizations/${organization.slug}/issues/${group.id}/reprocessing/`; + } + + render() { + const {Header, Body, closeModal} = this.props; + + return ( + <React.Fragment> + <Header> + {t('Reprocessing')} + <FeatureBadge type="alpha" /> + </Header> + <Body> + <Alert type="warning"> + {t( + 'Reprocessing is a preview feature. Please carefully review the limitations and implications!' + )} + </Alert> + + <p> + {t( + 'You can choose to reprocess issues to apply new debug files and updated grouping configuration. While reprocessing is in preview, keep the following limitations in mind:' + )} + </p> + + <ul> + <li> + {tct( + 'Sentry [strong:creates new events and deletes this issue.] This may temporarily affect event counts in Discover and the Issue Stream.', + {strong: <strong />} + )} + </li> + <li> + {tct( + 'Depending on the number of events, [strong:reprocessing can take several minutes.] Once started, Sentry opens a view on the Issue Stream that shows the reprocessed issues.', + {strong: <strong />} + )} + </li> + <li> + {tct( + 'To reprocess Minidump crash reports, ensure [strong:storing native crash reports is enabled.] Attachment storage is required for this.', + {strong: <strong />} + )} + </li> + <li> + {tct( + "Reprocessing one or multiple events [strong:counts against your organization's quota]. Rate limits and spike protection do not apply.", + {strong: <strong />} + )} + </li> + <li> + {tct( + 'If you have uploaded missing debug files, [strong:please wait at least one hour before attempting to reprocess.]', + {strong: <strong />} + )} + </li> + <li> + {tct( + 'Reprocessed events will not trigger issue alerts, and reprocessed events will not be subject to [link:data forwarding].', + { + fwd: ( + <ExternalLink href="https://docs.sentry.io/platform-redirect/?next=/data-management/data-forwarding/" /> + ), + } + )} + </li> + </ul> + + <ApiForm + apiEndpoint={this.getEndpoint()} + apiMethod="POST" + footerClass="modal-footer" + onSubmitSuccess={this.onSuccess} + submitLabel={t('Reprocess Issue')} + submitLoadingMessage={t('Reprocessing\u2026')} + submitErrorMessage={t('Failed to reprocess. Please check your input.')} + hideErrors + onCancel={closeModal} + > + <NumberField + name="maxEvents" + label={t('Limit Number of Events')} + help={t( + 'Constrain reprocessing to a maximum number of events in this issue. The latest events will be reprocessed. Defaults to all events.' + )} + placeholder={t('All events')} + min={1} + /> + </ApiForm> + </Body> + </React.Fragment> + ); + } +} + +export default ReprocessingForm; diff --git a/src/sentry/tasks/reprocessing2.py b/src/sentry/tasks/reprocessing2.py index 641728a39ca64c..ce3348eb64a8b2 100644 --- a/src/sentry/tasks/reprocessing2.py +++ b/src/sentry/tasks/reprocessing2.py @@ -3,7 +3,6 @@ import time from sentry import eventstore -from sentry.utils.dates import to_datetime from sentry.tasks.base import instrumented_task @@ -16,25 +15,34 @@ time_limit=120, soft_time_limit=110, ) -def reprocess_group(project_id, group_id, offset=0, start_time=None): +def reprocess_group(project_id, group_id, offset=0, start_time=None, max_events=None): + from sentry.reprocessing2 import start_group_reprocessing + + start_group_reprocessing(project_id, group_id, max_events=max_events) + if start_time is None: start_time = time.time() - events = list( - eventstore.get_unfetched_events( - eventstore.Filter( - project_ids=[project_id], - group_ids=[group_id], - # XXX: received? - conditions=[["timestamp", "<", to_datetime(start_time)]], - ), - limit=GROUP_REPROCESSING_CHUNK_SIZE, - offset=offset, - referrer="reprocessing2.reprocess_group", + if max_events is not None and max_events <= 0: + events = [] + else: + limit = GROUP_REPROCESSING_CHUNK_SIZE + + if max_events is not None: + limit = min(limit, max_events) + + events = list( + eventstore.get_unfetched_events( + eventstore.Filter(project_ids=[project_id], group_ids=[group_id],), + limit=limit, + orderby=["-timestamp"], + offset=offset, + referrer="reprocessing2.reprocess_group", + ) ) - ) if not events: + wait_group_reprocessed.delay(project_id=project_id, group_id=group_id) return for event in events: @@ -42,8 +50,15 @@ def reprocess_group(project_id, group_id, offset=0, start_time=None): project_id=project_id, event_id=event.event_id, start_time=start_time, ) + if max_events is not None: + max_events -= len(events) + reprocess_group.delay( - project_id=project_id, group_id=group_id, offset=offset + len(events), start_time=start_time + project_id=project_id, + group_id=group_id, + offset=offset + len(events), + start_time=start_time, + max_events=max_events, ) @@ -57,3 +72,35 @@ def reprocess_event(project_id, event_id, start_time): from sentry.reprocessing2 import reprocess_event as reprocess_event_impl reprocess_event_impl(project_id=project_id, event_id=event_id, start_time=start_time) + + +@instrumented_task( + name="sentry.tasks.reprocessing2.wait_group_reprocessed", + queue="sleep", + time_limit=(60 * 5) + 5, + soft_time_limit=60 * 5, +) +def wait_group_reprocessed(project_id, group_id): + from sentry.reprocessing2 import is_group_finished + + if is_group_finished(group_id): + delete_old_group.delay(project_id=project_id, group_id=group_id) + else: + wait_group_reprocessed.apply_async( + kwargs={"project_id": project_id, "group_id": group_id}, countdown=60 * 5 + ) + + +@instrumented_task( + name="sentry.tasks.reprocessing2.delete_old_group", + queue="events.reprocessing.preprocess_event", + time_limit=(60 * 5) + 5, + soft_time_limit=60 * 5, +) +def delete_old_group(project_id, group_id): + from sentry.models.group import Group + from sentry.group_deletion import delete_group + + group = Group.objects.get_from_cache(id=group_id) + + delete_group(group) diff --git a/src/sentry/tasks/store.py b/src/sentry/tasks/store.py index 95793fe8a63556..37e8ff558117f7 100644 --- a/src/sentry/tasks/store.py +++ b/src/sentry/tasks/store.py @@ -706,7 +706,6 @@ def _do_save_event( set_current_project(project_id) from sentry.event_manager import EventManager, HashDiscarded - from sentry.reprocessing2 import should_save_reprocessed_event event_type = "none" @@ -753,9 +752,6 @@ def _do_save_event( return try: - if not should_save_reprocessed_event(data): - return - with metrics.timer("tasks.store.do_save_event.event_manager.save"): manager = EventManager(data) # event.project.organization is populated after this statement. @@ -776,6 +772,7 @@ def _do_save_event( event_processing_store.delete_by_key(cache_key) finally: + reprocessing2.mark_event_reprocessed(data) if cache_key: with metrics.timer("tasks.store.do_save_event.delete_attachment_cache"): attachment_cache.delete(cache_key) diff --git a/src/sentry/testutils/helpers/task_runner.py b/src/sentry/testutils/helpers/task_runner.py index f3322a11929557..fa38649a1057a5 100644 --- a/src/sentry/testutils/helpers/task_runner.py +++ b/src/sentry/testutils/helpers/task_runner.py @@ -5,6 +5,7 @@ from celery import current_app from contextlib import contextmanager from django.conf import settings +from mock import patch @contextmanager @@ -14,3 +15,29 @@ def TaskRunner(): yield current_app.conf.CELERY_ALWAYS_EAGER = False settings.CELERY_ALWAYS_EAGER = False + + +@contextmanager +def BurstTaskRunner(): + """ + A fixture for queueing up Celery tasks and working them off in bursts. + + The main interesting property is that one can run tasks at a later point in + the future, testing "concurrency" without actually spawning any kind of + worker. + """ + + queue = [] + + def apply_async(self, args=(), kwargs=(), countdown=None): + queue.append((self, args, kwargs)) + + def work(): + while queue: + self, args, kwargs = queue.pop(0) + + with patch("celery.app.task.Task.apply_async", apply_async): + self(*args, **kwargs) + + with patch("celery.app.task.Task.apply_async", apply_async): + yield work diff --git a/src/sentry/utils/pytest/fixtures.py b/src/sentry/utils/pytest/fixtures.py index f8f5cd013590cf..73aca402f8ede2 100644 --- a/src/sentry/utils/pytest/fixtures.py +++ b/src/sentry/utils/pytest/fixtures.py @@ -156,6 +156,13 @@ def task_runner(): return TaskRunner [email protected] +def burst_task_runner(): + from sentry.testutils.helpers.task_runner import BurstTaskRunner + + return BurstTaskRunner + + @pytest.fixture(scope="function") def session(): return factories.create_session() diff --git a/tests/sentry/tasks/test_reprocessing2.py b/tests/sentry/tasks/test_reprocessing2.py index 6ef51423f6a79d..888e898e71df3d 100644 --- a/tests/sentry/tasks/test_reprocessing2.py +++ b/tests/sentry/tasks/test_reprocessing2.py @@ -5,39 +5,80 @@ import uuid from sentry import eventstore +from sentry.models.group import Group from sentry.event_manager import EventManager from sentry.eventstore.processing import event_processing_store from sentry.plugins.base.v2 import Plugin2 +from sentry.reprocessing2 import is_group_finished from sentry.tasks.reprocessing2 import reprocess_group from sentry.tasks.store import preprocess_event from sentry.testutils.helpers import Feature from sentry.testutils.helpers.datetime import iso_format, before_now [email protected](autouse=True) +def reprocessing_feature(): + with Feature({"projects:reprocessing-v2": True}): + yield + + [email protected] +def process_and_save(default_project, task_runner): + def inner(data): + data.setdefault("timestamp", iso_format(before_now(seconds=1))) + mgr = EventManager(data=data, project=default_project) + mgr.normalize() + data = mgr.get_data() + event_id = data["event_id"] + cache_key = event_processing_store.store(data) + + with task_runner(): + # factories.store_event would almost be suitable for this, but let's + # actually run through stacktrace processing once + preprocess_event(start_time=time(), cache_key=cache_key, data=data) + + return event_id + + return inner + + [email protected] +def register_event_preprocessor(register_plugin): + def inner(f): + class ReprocessingTestPlugin(Plugin2): + def get_event_preprocessors(self, data): + return [f] + + def is_enabled(self, project=None): + return True + + register_plugin(globals(), ReprocessingTestPlugin) + + return inner + + @pytest.mark.django_db [email protected] @pytest.mark.parametrize("change_groups", (True, False), ids=("new_group", "same_group")) [email protected]( - "change_stacktrace", (True, False), ids=("new_stacktrace", "no_stacktrace") -) def test_basic( - task_runner, default_project, register_plugin, change_groups, reset_snuba, change_stacktrace + task_runner, + default_project, + change_groups, + reset_snuba, + process_and_save, + register_event_preprocessor, + burst_task_runner, ): # Replace this with an int and nonlocal when we have Python 3 abs_count = [] + @register_event_preprocessor def event_preprocessor(data): tags = data.setdefault("tags", []) assert all(not x or x[0] != "processing_counter" for x in tags) tags.append(("processing_counter", "x{}".format(len(abs_count)))) abs_count.append(None) - if change_stacktrace and len(abs_count) > 0: - data["exception"] = { - "values": [ - {"type": "ZeroDivisionError", "stacktrace": {"frames": [{"function": "foo"}]}} - ] - } - if change_groups: data["fingerprint"] = [uuid.uuid4().hex] else: @@ -45,26 +86,7 @@ def event_preprocessor(data): return data - class ReprocessingTestPlugin(Plugin2): - def get_event_preprocessors(self, data): - return [event_preprocessor] - - def is_enabled(self, project=None): - return True - - register_plugin(globals(), ReprocessingTestPlugin) - - mgr = EventManager( - data={ - "timestamp": iso_format(before_now(seconds=1)), - "tags": [["key1", "value"], None, ["key2", "value"]], - }, - project=default_project, - ) - mgr.normalize() - data = mgr.get_data() - event_id = data["event_id"] - cache_key = event_processing_store.store(data) + event_id = process_and_save({"tags": [["key1", "value"], None, ["key2", "value"]]}) def get_event_by_processing_counter(n): return list( @@ -76,11 +98,6 @@ def get_event_by_processing_counter(n): ) ) - with task_runner(), Feature({"projects:reprocessing-v2": True}): - # factories.store_event would almost be suitable for this, but let's - # actually run through stacktrace processing once - preprocess_event(start_time=time(), cache_key=cache_key, data=data) - event = eventstore.get_event_by_id(default_project.id, event_id) assert event.get_tag("processing_counter") == "x0" assert not event.data.get("errors") @@ -89,24 +106,101 @@ def get_event_by_processing_counter(n): old_event = event - with task_runner(), Feature({"projects:reprocessing-v2": True}): + with burst_task_runner() as burst: reprocess_group(default_project.id, event.group_id) + burst() + new_events = get_event_by_processing_counter("x1") - if not change_stacktrace: - assert not new_events + (event,) = new_events + + # Assert original data is used + assert event.get_tag("processing_counter") == "x1" + assert not event.data.get("errors") + + if change_groups: + assert event.get_hashes() != old_event.get_hashes() else: - (event,) = new_events + assert event.get_hashes() == old_event.get_hashes() - # Assert original data is used - assert event.get_tag("processing_counter") == "x1" - assert not event.data.get("errors") + assert event.group_id != old_event.group_id - if change_groups: - assert event.group_id != old_event.group_id - else: - assert event.group_id == old_event.group_id + assert event.get_tag("original_event_id") == old_event.event_id + assert int(event.get_tag("original_group_id")) == old_event.group_id + + assert not Group.objects.filter(id=old_event.group_id).exists() + assert not eventstore.get_event_by_id(default_project.id, old_event.event_id) + + assert is_group_finished(old_event.group_id) + + [email protected]_db [email protected] +def test_concurrent_events_go_into_new_group( + default_project, reset_snuba, register_event_preprocessor, process_and_save, burst_task_runner +): + @register_event_preprocessor + def event_preprocessor(data): + extra = data.setdefault("extra", {}) + extra.setdefault("processing_counter", 0) + extra["processing_counter"] += 1 + return data + + event_id = process_and_save({"message": "hello world"}) + + event = eventstore.get_event_by_id(default_project.id, event_id) + + with burst_task_runner() as burst_reprocess: + reprocess_group(default_project.id, event.group_id) + + assert not is_group_finished(event.group_id) + + event_id2 = process_and_save({"message": "hello world"}) + event2 = eventstore.get_event_by_id(default_project.id, event_id2) + assert event2.event_id != event.event_id + assert event2.group_id != event.group_id + + burst_reprocess() + + (event3,) = eventstore.get_events( + eventstore.Filter( + project_ids=[default_project.id], + conditions=[["tags[original_event_id]", "=", event_id]], + ) + ) + + assert is_group_finished(event.group_id) + + assert event2.group_id == event3.group_id + assert event.get_hashes() == event2.get_hashes() == event3.get_hashes() + + [email protected]_db [email protected] +def test_max_events( + default_project, + reset_snuba, + register_event_preprocessor, + process_and_save, + task_runner, + monkeypatch, +): + @register_event_preprocessor + def event_preprocessor(data): + extra = data.setdefault("extra", {}) + extra.setdefault("processing_counter", 0) + extra["processing_counter"] += 1 + return data + + event_id = process_and_save({"message": "hello world"}) + + event = eventstore.get_event_by_id(default_project.id, event_id) + + # Make sure it never gets called + monkeypatch.setattr("sentry.tasks.reprocessing2.reprocess_event", None) + + with task_runner(): + reprocess_group(default_project.id, event.group_id, max_events=0) - assert event.get_tag("original_event_id") == old_event.event_id - assert int(event.get_tag("original_group_id")) == old_event.group_id + assert is_group_finished(event.group_id) diff --git a/tests/symbolicator/test_minidump_full.py b/tests/symbolicator/test_minidump_full.py index db8c451efa0fbb..ad9c09cdf27cc4 100644 --- a/tests/symbolicator/test_minidump_full.py +++ b/tests/symbolicator/test_minidump_full.py @@ -1,6 +1,5 @@ from __future__ import absolute_import -import time import pytest import zipfile from sentry.utils.compat.mock import patch @@ -12,6 +11,7 @@ from sentry import eventstore from sentry.testutils import TransactionTestCase, RelayStoreHelper +from sentry.testutils.helpers.task_runner import BurstTaskRunner from sentry.models import EventAttachment from sentry.lang.native.utils import STORE_CRASH_REPORTS_ALL @@ -150,12 +150,12 @@ def test_reprocessing(self): self.upload_symbols() - from sentry.tasks.reprocessing2 import reprocess_event + from sentry.tasks.reprocessing2 import reprocess_group - with self.tasks(): - reprocess_event.delay( - project_id=self.project.id, event_id=event.event_id, start_time=time.time() - ) + with BurstTaskRunner() as burst: + reprocess_group.delay(project_id=self.project.id, group_id=event.group_id) + + burst() (new_event,) = eventstore.get_events( eventstore.Filter(
6e76922545614a1828623757fa89cc9d3849bf6e
2022-11-18 04:08:56
NisanthanNanthakumar
feat(commit-context): Add custom breadcrumbs for debugging (#41532)
false
Add custom breadcrumbs for debugging (#41532)
feat
diff --git a/src/sentry/integrations/github/client.py b/src/sentry/integrations/github/client.py index ef41e8eab037d7..0cc7f1245a1986 100644 --- a/src/sentry/integrations/github/client.py +++ b/src/sentry/integrations/github/client.py @@ -356,6 +356,12 @@ def get_blame_for_file( path="/graphql", data={"query": query}, ) + sentry_sdk.add_breadcrumb( + category="sentry.integrations.client.github", + message="get_blame_for_file query results", + level="info", + data=contents, + ) try: results: Sequence[Mapping[str, Any]] = ( contents.get("data", {}) diff --git a/src/sentry/integrations/gitlab/client.py b/src/sentry/integrations/gitlab/client.py index 40aa1b8f734bcf..5402873e05bd73 100644 --- a/src/sentry/integrations/gitlab/client.py +++ b/src/sentry/integrations/gitlab/client.py @@ -3,6 +3,7 @@ from typing import Any, Mapping, Sequence from urllib.parse import quote +import sentry_sdk from django.urls import reverse from sentry.integrations.client import ApiClient @@ -328,4 +329,10 @@ def get_blame_for_file( contents = self.get( request_path, params={"ref": ref, "range[start]": lineno, "range[end]": lineno} ) + sentry_sdk.add_breadcrumb( + category="sentry.integrations.client.gitlab", + message="get_blame_for_file query results", + level="info", + data=contents, + ) return contents