hash,date,author,commit_message,is_merge,masked_commit_message,type,git_diff 561b24c72c2addbab965d04bfd689de8c7b2913b,2018-10-20 00:15:03,Evan Purkhiser,ref(ui): Make Footer component stateless (#10194),False,Make Footer component stateless (#10194),ref,"diff --git a/src/sentry/static/sentry/app/components/footer.jsx b/src/sentry/static/sentry/app/components/footer.jsx index 09d09bee382a21..a5560bf9609450 100644 --- a/src/sentry/static/sentry/app/components/footer.jsx +++ b/src/sentry/static/sentry/app/components/footer.jsx @@ -1,58 +1,44 @@ import React from 'react'; -import ConfigStore from 'app/stores/configStore'; -import HookStore from 'app/stores/hookStore'; + import {t} from 'app/locale'; +import ConfigStore from 'app/stores/configStore'; import DynamicWrapper from 'app/components/dynamicWrapper'; +import Hook from 'app/components/hook'; -class Footer extends React.Component { - constructor(props) { - super(props); - // Allow injection via getsentry et all - let hooks = []; - HookStore.get('footer').forEach(cb => { - hooks.push(cb()); - }); - - this.state = { - hooks, - }; - } - - render() { - let config = ConfigStore.getConfig(); - return ( - + ); +}; export default Footer;" 596b68cfd398e890a7fc92aa28f0181466b2d0ac,2024-06-25 05:30:47,Nathan Hsieh,fix: attach activations to incidents on trigger (#73242),False,attach activations to incidents on trigger (#73242),fix,"diff --git a/src/sentry/incidents/subscription_processor.py b/src/sentry/incidents/subscription_processor.py index 977017e8e16001..50dca818b9eb8d 100644 --- a/src/sentry/incidents/subscription_processor.py +++ b/src/sentry/incidents/subscription_processor.py @@ -630,8 +630,8 @@ def trigger_alert_threshold( if not self.active_incident: detected_at = self.calculate_event_date_from_update_date(self.last_update) activation: AlertRuleActivations | None = None - if self.alert_rule.monitor_type == AlertRuleMonitorType.ACTIVATED: - activations = list(self.subscription.alertruleactivations_set) + if self.alert_rule.monitor_type == AlertRuleMonitorType.ACTIVATED.value: + activations = list(self.subscription.alertruleactivations_set.all()) if len(activations) != 1: logger.error( ""activated alert rule subscription has unexpected activation instances"", diff --git a/tests/sentry/incidents/test_subscription_processor.py b/tests/sentry/incidents/test_subscription_processor.py index 7e9a982ec9e3bf..fd624af761baa4 100644 --- a/tests/sentry/incidents/test_subscription_processor.py +++ b/tests/sentry/incidents/test_subscription_processor.py @@ -43,6 +43,7 @@ partition, update_alert_rule_stats, ) +from sentry.incidents.utils.types import AlertRuleActivationConditionType from sentry.sentry_metrics.configuration import UseCaseKey from sentry.sentry_metrics.indexer.postgres.models import MetricsKeyIndexer from sentry.sentry_metrics.utils import resolve_tag_key, resolve_tag_value @@ -195,6 +196,10 @@ def other_project(self): def sub(self): return self.rule.snuba_query.subscriptions.filter(project=self.project).get() + @cached_property + def activated_sub(self): + return self.activated_rule.snuba_query.subscriptions.filter(project=self.project).get() + @cached_property def other_sub(self): return self.rule.snuba_query.subscriptions.filter(project=self.other_project).get() @@ -226,6 +231,40 @@ def rule(self): ) return rule + @cached_property + def activated_rule(self): + rule = self.create_alert_rule( + projects=[self.project, self.other_project], + name=""some rule"", + query="""", + aggregate=""count()"", + time_window=1, + threshold_type=AlertRuleThresholdType.ABOVE, + resolve_threshold=10, + threshold_period=1, + monitor_type=AlertRuleMonitorType.ACTIVATED, + activation_condition=AlertRuleActivationConditionType.RELEASE_CREATION, + event_types=[ + SnubaQueryEventType.EventType.ERROR, + SnubaQueryEventType.EventType.DEFAULT, + ], + ) + rule.subscribe_projects( + projects=[self.project], + monitor_type=AlertRuleMonitorType.ACTIVATED, + activation_condition=AlertRuleActivationConditionType.DEPLOY_CREATION, + activator=""testing"", + ) + # Make sure the trigger exists + trigger = create_alert_rule_trigger(rule, CRITICAL_TRIGGER_LABEL, 100) + create_alert_rule_trigger_action( + trigger, + AlertRuleTriggerAction.Type.EMAIL, + AlertRuleTriggerAction.TargetType.USER, + str(self.user.id), + ) + return rule + @cached_property def comparison_rule_above(self): rule = self.rule @@ -250,10 +289,18 @@ def comparison_rule_below(self): def trigger(self): return self.rule.alertruletrigger_set.get() + @cached_property + def activated_trigger(self): + return self.activated_rule.alertruletrigger_set.get() + @cached_property def action(self): return self.trigger.alertruletriggeraction_set.get() + @cached_property + def activated_action(self): + return self.activated_trigger.alertruletriggeraction_set.get() + def build_subscription_update(self, subscription, time_delta=None, value=EMPTY): if time_delta is not None: timestamp = timezone.now() + time_delta @@ -381,6 +428,33 @@ def test_alert(self): [(trigger.alert_threshold + 1, IncidentStatus.CRITICAL, uuid)], ) + def test_activated_alert(self): + # Verify that an alert rule that only expects a single update to be over the + # alert threshold triggers correctly + rule = self.activated_rule + trigger = self.activated_trigger + subscription = self.activated_sub + processor = self.send_update( + rule=rule, value=trigger.alert_threshold + 1, subscription=subscription + ) + self.assert_trigger_counts(processor, self.activated_trigger, 0, 0) + incident = self.assert_active_incident(rule=rule, subscription=subscription) + assert incident.date_started == ( + timezone.now().replace(microsecond=0) - timedelta(seconds=rule.snuba_query.time_window) + ) + self.assert_trigger_exists_with_status( + incident, self.activated_trigger, TriggerStatus.ACTIVE + ) + latest_activity = self.latest_activity(incident) + uuid = str(latest_activity.notification_uuid) + self.assert_actions_fired_for_incident( + incident, + [self.activated_action], + [(trigger.alert_threshold + 1, IncidentStatus.CRITICAL, uuid)], + ) + # assert that an incident was created _with_ an activation! + assert incident.activation + def test_alert_dedupe(self): # Verify that an alert rule that only expects a single update to be over the # alert threshold triggers correctly" e403432ccff3d39b2c3bf88cac39ae13912ec4d3,2021-07-22 22:56:07,Dan Fuller,perf(api): Improve performance on `OrganizationActivityEndpoint` (#27667),False,Improve performance on `OrganizationActivityEndpoint` (#27667),perf,"diff --git a/src/sentry/api/base.py b/src/sentry/api/base.py index 0c66999eafb86e..7d13edc3afe640 100644 --- a/src/sentry/api/base.py +++ b/src/sentry/api/base.py @@ -292,6 +292,15 @@ def get_per_page(self, request, default_per_page=100, max_per_page=100): return per_page + def get_cursor_from_request(self, request, cursor_cls=Cursor): + if not request.GET.get(self.cursor_name): + return + + try: + return cursor_cls.from_string(request.GET.get(self.cursor_name)) + except ValueError: + raise ParseError(detail=""Invalid cursor parameter."") + def paginate( self, request, @@ -307,12 +316,7 @@ def paginate( per_page = self.get_per_page(request, default_per_page, max_per_page) - input_cursor = None - if request.GET.get(self.cursor_name): - try: - input_cursor = cursor_cls.from_string(request.GET.get(self.cursor_name)) - except ValueError: - raise ParseError(detail=""Invalid cursor parameter."") + input_cursor = self.get_cursor_from_request(request, cursor_cls=cursor_cls) if not paginator: paginator = paginator_cls(**paginator_kwargs) diff --git a/src/sentry/api/endpoints/organization_activity.py b/src/sentry/api/endpoints/organization_activity.py index 07ae9e10feb0ce..11f9da9d2fecc1 100644 --- a/src/sentry/api/endpoints/organization_activity.py +++ b/src/sentry/api/endpoints/organization_activity.py @@ -1,3 +1,5 @@ +from functools import reduce + from sentry.api.base import EnvironmentMixin from sentry.api.bases import OrganizationMemberEndpoint from sentry.api.paginator import DateTimePaginator @@ -10,19 +12,49 @@ def get(self, request, organization, member): # There is an activity record created for both sides of the unmerge # operation, so we only need to include one of them here to avoid # showing the same entry twice. - queryset = ( - Activity.objects.filter( - project__in=list( - Project.objects.filter( - organization=organization, - teams__in=OrganizationMemberTeam.objects.filter( - organizationmember=member - ).values(""team""), - ).values_list(""id"", flat=True) - ) - ) - .exclude(type=Activity.UNMERGE_SOURCE) - .select_related(""project"", ""group"", ""user"") + base_qs = Activity.objects.exclude(type=Activity.UNMERGE_SOURCE).values_list( + ""id"", flat=True + ) + + # To make this query efficient, we have to hammer it into a weird format. This table is + # extremely large and if we are making a query across many projects, in a lot of cases + # Postgres decides that the best query plan is to iterate backwards on the datetime index. + # This means it does something close to a table scan to get the results it wants - this can + # be the case even for orgs with less than a page of activity rows, and often results in + # queries that take > 30s, which get killed by stomper. + # To convince Postgres to use the index on `(project_id, datetime)`, it basically needs to + # see queries that filter on a single project id and then order by datetime. So we replicate + # the query for every project and UNION ALL them together to get the candidate set of rows. + # Then we sort these and return the final result. Convoluted, but it improves the query a + # lot. + # To make this work well with pagination, we have to also apply the pagination queries to + # the subqueries. + cursor = self.get_cursor_from_request(request) + paginator = DateTimePaginator(base_qs, order_by=""-datetime"") + if cursor is not None and cursor.value: + cursor_value = paginator.value_from_cursor(cursor) + else: + cursor_value = 0 + base_qs = paginator.build_queryset(cursor_value, False) + + project_ids = list( + Project.objects.filter( + organization=organization, + teams__in=OrganizationMemberTeam.objects.filter(organizationmember=member).values( + ""team"" + ), + ).values_list(""id"", flat=True) + ) + + union_qs = reduce( + lambda qs1, qs2: qs1.union(qs2, all=True), + [base_qs.filter(project_id=project)[: paginator.max_limit] for project in project_ids], + ) + + # We do `select_related` here to make the unions less heavy. This way we only join these + # table for the rows we actually want. + queryset = Activity.objects.filter(id__in=union_qs[: paginator.max_limit]).select_related( + ""project"", ""group"", ""user"" ) return self.paginate( diff --git a/src/sentry/api/paginator.py b/src/sentry/api/paginator.py index c88360b9c4d4e1..0ce817dae80bdf 100644 --- a/src/sentry/api/paginator.py +++ b/src/sentry/api/paginator.py @@ -44,7 +44,7 @@ def __init__( def _is_asc(self, is_prev): return (self.desc and is_prev) or not (self.desc or is_prev) - def _build_queryset(self, value, is_prev): + def build_queryset(self, value, is_prev): queryset = self.queryset # ""asc"" controls whether or not we need to change the ORDER BY to @@ -114,7 +114,7 @@ def get_result(self, limit=100, cursor=None, count_hits=False, known_hits=None, else: cursor_value = 0 - queryset = self._build_queryset(cursor_value, cursor.is_prev) + queryset = self.build_queryset(cursor_value, cursor.is_prev) # TODO(dcramer): this does not yet work correctly for ``is_prev`` when # the key is not unique diff --git a/src/sentry/testutils/cases.py b/src/sentry/testutils/cases.py index 2b076faf204a86..1f213330e6b012 100644 --- a/src/sentry/testutils/cases.py +++ b/src/sentry/testutils/cases.py @@ -427,6 +427,14 @@ def get_error_response(self, *args, **params): return response + def get_cursor_headers(self, response): + return [ + link[""cursor""] + for link in requests.utils.parse_header_links( + response.get(""link"").rstrip("">"").replace("">,<"", "",<"") + ) + ] + class TwoFactorAPITestCase(APITestCase): @fixture diff --git a/tests/sentry/api/endpoints/test_organization_activity.py b/tests/sentry/api/endpoints/test_organization_activity.py index d0b18f3f697c9d..3761e2d48cc3ba 100644 --- a/tests/sentry/api/endpoints/test_organization_activity.py +++ b/tests/sentry/api/endpoints/test_organization_activity.py @@ -1,5 +1,6 @@ from sentry.models import Activity from sentry.testutils import APITestCase +from sentry.testutils.helpers.datetime import before_now, iso_format class OrganizationActivityTest(APITestCase): @@ -23,3 +24,44 @@ def test_simple(self): response = self.get_success_response(org.slug) assert [r[""id""] for r in response.data] == [str(activity.id)] + + def test_paginate(self): + group = self.group + org = group.organization + project_2 = self.create_project() + group_2 = self.store_event( + data={ + ""timestamp"": iso_format(before_now(minutes=1)), + ""tags"": {""group_id"": ""group-2""}, + }, + project_id=project_2.id, + ).group + + activity = Activity.objects.create( + group=group, + project=group.project, + type=Activity.NOTE, + user=self.user, + data={""text"": ""hello world""}, + ) + activity_2 = Activity.objects.create( + group=group_2, + project=group_2.project, + type=Activity.NOTE, + user=self.user, + data={""text"": ""hello world 2""}, + ) + activity_3 = Activity.objects.create( + group=group, + project=group.project, + type=Activity.NOTE, + user=self.user, + data={""text"": ""hello world 3""}, + ) + + response = self.get_success_response(org.slug, per_page=2) + assert [r[""id""] for r in response.data] == [str(activity_3.id), str(activity_2.id)] + next_cursor = self.get_cursor_headers(response)[1] + + response = self.get_success_response(org.slug, per_page=2, cursor=next_cursor) + assert [r[""id""] for r in response.data] == [str(activity.id)]" 06498c89b9a22ba0d15fa94d2c3f4c81925b8354,2020-03-19 22:42:09,Billy Vong,"fix(workflow): Change `` children to be ""primary"" w… (#17767)",False,"Change `` children to be ""primary"" w… (#17767)",fix,"diff --git a/src/sentry/static/sentry/app/views/alerts/list/index.tsx b/src/sentry/static/sentry/app/views/alerts/list/index.tsx index 6d908f3162de86..77af08b7f17ddd 100644 --- a/src/sentry/static/sentry/app/views/alerts/list/index.tsx +++ b/src/sentry/static/sentry/app/views/alerts/list/index.tsx @@ -46,6 +46,7 @@ type State = { function getQueryStatus(status: any) { return ['open', 'closed', 'all'].includes(status) ? status : DEFAULT_QUERY_STATUS; } + class IncidentsList extends AsyncComponent { getEndpoints(): [string, string, any][] { const {params, location} = this.props; @@ -200,6 +201,11 @@ class IncidentsListContainer extends React.Component { const allIncidentsQuery = omit({...query, status: 'all'}, 'cursor'); const status = getQueryStatus(query.status); + + const isOpenActive = status === 'open'; + const isClosedActive = status === 'closed'; + const isAllActive = status === 'all'; + return ( @@ -237,21 +243,24 @@ class IncidentsListContainer extends React.Component { diff --git a/tests/js/spec/views/incidents/list/index.spec.jsx b/tests/js/spec/views/incidents/list/index.spec.jsx index fcc8c35686cbb4..387ac1c29a4b50 100644 --- a/tests/js/spec/views/incidents/list/index.spec.jsx +++ b/tests/js/spec/views/incidents/list/index.spec.jsx @@ -102,10 +102,10 @@ describe('IncidentsList', function() { expect( wrapper .find('ButtonBar') - .find('a') + .find('Button') .at(0) - .hasClass('active') - ).toBe(true); + .prop('priority') + ).toBe('primary'); expect(mock).toHaveBeenCalledTimes(1); @@ -121,8 +121,8 @@ describe('IncidentsList', function() { .find('ButtonBar') .find('Button') .at(2) - .hasClass('active') - ).toBe(true); + .prop('priority') + ).toBe('primary'); expect(mock).toHaveBeenCalledTimes(2);" a67ea84967ed1ec42844720d9daf77be36ff73b0,2023-01-19 20:19:00,edwardgou-sentry,fix(discover): Make sure event.type filter for metric query is not negated (#43430),False,Make sure event.type filter for metric query is not negated (#43430),fix,"diff --git a/src/sentry/search/events/datasets/metrics.py b/src/sentry/search/events/datasets/metrics.py index d93f5fee768c80..3c7c8682786150 100644 --- a/src/sentry/search/events/datasets/metrics.py +++ b/src/sentry/search/events/datasets/metrics.py @@ -688,7 +688,8 @@ def _project_threshold_multi_if_function(self) -> SelectType: def _event_type_converter(self, search_filter: SearchFilter) -> Optional[WhereType]: """"""Not really a converter, check its transaction, error otherwise"""""" value = search_filter.value.value - if value == ""transaction"": + operator = search_filter.operator + if value == ""transaction"" and operator == ""="": return None raise IncompatibleMetricsQuery(""Can only filter event.type:transaction"") diff --git a/src/sentry/search/events/datasets/metrics_layer.py b/src/sentry/search/events/datasets/metrics_layer.py index 40f0076f6c39d5..63dcb23f3489b8 100644 --- a/src/sentry/search/events/datasets/metrics_layer.py +++ b/src/sentry/search/events/datasets/metrics_layer.py @@ -440,7 +440,8 @@ def _resolve_team_key_transaction_alias(self, _: str) -> SelectType: def _event_type_converter(self, search_filter: SearchFilter) -> Optional[WhereType]: """"""Not really a converter, check its transaction, error otherwise"""""" value = search_filter.value.value - if value == ""transaction"": + operator = search_filter.operator + if value == ""transaction"" and operator == ""="": return None raise IncompatibleMetricsQuery(""Can only filter event.type:transaction"") diff --git a/tests/sentry/search/events/builder/test_metrics.py b/tests/sentry/search/events/builder/test_metrics.py index 69f09b3faa04fb..30805d6e86c646 100644 --- a/tests/sentry/search/events/builder/test_metrics.py +++ b/tests/sentry/search/events/builder/test_metrics.py @@ -1552,6 +1552,24 @@ def test_missing_function(self): ], ) + def test_event_type_query_condition(self): + query = MetricsQueryBuilder( + self.params, + query=""event.type:transaction"", + dataset=Dataset.PerformanceMetrics, + selected_columns=[], + ) + self.assertCountEqual(query.where, self.default_conditions) + + def test_invalid_event_type_query_condition(self): + with pytest.raises(IncompatibleMetricsQuery): + MetricsQueryBuilder( + self.params, + query=""!event.type:transaction"", + dataset=Dataset.PerformanceMetrics, + selected_columns=[], + ) + class TimeseriesMetricQueryBuilderTest(MetricBuilderBaseTest): def test_get_query(self):" 555daf42dfa5936fb012e1fd94183de2fd6434bc,2020-02-25 00:31:43,Evan Purkhiser,chore(ts): Convert marked (#17174),False,Convert marked (#17174),chore,"diff --git a/package.json b/package.json index 9719eef57eba37..6f1f9186a25967 100644 --- a/package.json +++ b/package.json @@ -30,11 +30,13 @@ ""@types/clipboard"": ""^2.0.1"", ""@types/color"": ""^3.0.0"", ""@types/create-react-class"": ""^15.6.2"", + ""@types/dompurify"": ""^2.0.1"", ""@types/echarts"": ""^4.1.11"", ""@types/jest"": ""^24.0.17"", ""@types/jquery"": ""^2.0.53"", ""@types/js-cookie"": ""^2.2.2"", ""@types/lodash"": ""^4.14.134"", + ""@types/marked"": ""^0.7.2"", ""@types/moment-timezone"": ""^0.5.12"", ""@types/papaparse"": ""^4.5.11"", ""@types/react"": ""~16.9.19"", diff --git a/src/sentry/static/sentry/app/utils/marked.jsx b/src/sentry/static/sentry/app/utils/marked.jsx deleted file mode 100644 index 893579cb7b2828..00000000000000 --- a/src/sentry/static/sentry/app/utils/marked.jsx +++ /dev/null @@ -1,70 +0,0 @@ -import marked from 'marked'; // eslint-disable-line no-restricted-imports -import dompurify from 'dompurify'; - -function isSafeHref(href, pattern) { - try { - return pattern.test(decodeURIComponent(unescape(href))); - } catch (e) { - return false; - } -} - -// We need to implement our own marked Renderer to not render -// potentially malicious uris. -// This is copy/pasted from -// https://github.com/chjj/marked/blob/master/lib/marked.js#L869-L888 -// and modified. -function Renderer() { - return marked.Renderer.apply(this, arguments); -} -Object.assign(Renderer.prototype, marked.Renderer.prototype); - -// Only https and mailto, (e.g. no javascript, vbscript, data protocols) -const safeLinkPattern = /^(https?:|mailto:)/i; - -Renderer.prototype.link = function(href, title, text) { - // For a bad link, just return the plain text href - if (this.options.sanitize && !isSafeHref(href, safeLinkPattern)) { - return href; - } - - let out = ''; - return dompurify.sanitize(out); -}; - -// Only allow http(s) for image tags -const safeImagePattern = /^https?:\/\/./i; - -Renderer.prototype.image = function(href, title, text) { - // For a bad image, return an empty string - if (this.options.sanitize && !isSafeHref(href, safeImagePattern)) { - return ''; - } - - let out = '' : '>'; - return out; -}; - -marked.setOptions({ - renderer: new Renderer(), - sanitize: true, -}); - -const noParagraphRenderer = new Renderer(); -noParagraphRenderer.paragraph = s => s; - -const singleLineRenderer = (text, options) => - dompurify.sanitize(marked(text, {...options, renderer: noParagraphRenderer})); - -const sanitizedMarked = (...args) => dompurify.sanitize(marked(...args)); - -export {singleLineRenderer}; -export default sanitizedMarked; diff --git a/src/sentry/static/sentry/app/utils/marked.tsx b/src/sentry/static/sentry/app/utils/marked.tsx new file mode 100644 index 00000000000000..0c660e7d5ee106 --- /dev/null +++ b/src/sentry/static/sentry/app/utils/marked.tsx @@ -0,0 +1,59 @@ +import marked from 'marked'; // eslint-disable-line no-restricted-imports +import dompurify from 'dompurify'; + +// Only https and mailto, (e.g. no javascript, vbscript, data protocols) +const safeLinkPattern = /^(https?:|mailto:)/i; + +const safeImagePattern = /^https?:\/\/./i; + +function isSafeHref(href: string, pattern: RegExp) { + try { + return pattern.test(decodeURIComponent(unescape(href))); + } catch { + return false; + } +} + +/** + * Implementation of marked.Renderer which additonally sanitizes URLs. + */ +class SafeRenderer extends marked.Renderer { + link(href: string, title: string, text: string) { + // For a bad link, just return the plain text href + if (!isSafeHref(href, safeLinkPattern)) { + return href; + } + + const out = `${text}`; + return dompurify.sanitize(out); + } + + image(href: string, title: string, text: string) { + // For a bad image, return an empty string + if (this.options.sanitize && !isSafeHref(href, safeImagePattern)) { + return ''; + } + + return ``; + } +} + +class NoParagraphRenderer extends SafeRenderer { + paragraph(text: string) { + return text; + } +} + +marked.setOptions({ + renderer: new SafeRenderer(), + sanitize: true, +}); + +const sanitizedMarked = (...args: Parameters) => + dompurify.sanitize(marked(...args)); + +const singleLineRenderer = (text: string, options: marked.MarkedOptions = {}) => + sanitizedMarked(text, {...options, renderer: new NoParagraphRenderer()}); + +export {singleLineRenderer}; +export default sanitizedMarked; diff --git a/yarn.lock b/yarn.lock index 9a3f667ce56e5f..1a582d2f537ac5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2409,6 +2409,13 @@ dependencies: ""@types/react"" ""*"" +""@types/dompurify@^2.0.1"": + version ""2.0.1"" + resolved ""https://registry.yarnpkg.com/@types/dompurify/-/dompurify-2.0.1.tgz#0bf3a9f8ee21d81adb20b8c374ab034d6a74dbf7"" + integrity sha512-OQ16dECrRv/I//woKkVUxyVGYR94W3qp3Wy//B63awHVe3h/1/URFqP5a/V2m4k01DEvWs1+z7FWW3xfM1lH3Q== + dependencies: + ""@types/trusted-types"" ""*"" + ""@types/echarts@^4.1.11"": version ""4.4.2"" resolved ""https://registry.yarnpkg.com/@types/echarts/-/echarts-4.4.2.tgz#88be60b9b87bc65414f22d4150834538d62ac602"" @@ -2507,6 +2514,11 @@ resolved ""https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.149.tgz#1342d63d948c6062838fbf961012f74d4e638440"" integrity sha512-ijGqzZt/b7BfzcK9vTrS6MFljQRPn5BFWOx8oE0GYxribu6uV+aA9zZuXI1zc/etK9E8nrgdoF2+LgUw7+9tJQ== +""@types/marked@^0.7.2"": + version ""0.7.2"" + resolved ""https://registry.yarnpkg.com/@types/marked/-/marked-0.7.2.tgz#1393f076773b55cc7078c0fbeb86a497c69db97e"" + integrity sha512-A3EDyNaq6OCcpaOia2HQ/tu2QYt8DKuj4ExP21VU3cU3HTo2FLslvbqa2T1vux910RHvuSVqpwKnnykSFcRWOA== + ""@types/minimatch@*"": version ""3.0.3"" resolved ""https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d"" @@ -2678,6 +2690,11 @@ resolved ""https://registry.yarnpkg.com/@types/tapable/-/tapable-1.0.5.tgz#9adbc12950582aa65ead76bffdf39fe0c27a3c02"" integrity sha512-/gG2M/Imw7cQFp8PGvz/SwocNrmKFjFsm5Pb8HdbHkZ1K8pmuPzOX4VeVoiEecFCVf4CsN1r3/BRvx+6sNqwtQ== +""@types/trusted-types@*"": + version ""1.0.4"" + resolved ""https://registry.yarnpkg.com/@types/trusted-types/-/trusted-types-1.0.4.tgz#922d092c84a776a59acb0bd6785fd82b59b9bad5"" + integrity sha512-6jtHrHpmiXOXoJ31Cg9R+iEVwuEKPf0XHwFUI93eEPXx492/J2JHyafkleKE2EYzZprayk9FSjTyK1GDqcwDng== + ""@types/uglify-js@*"": version ""3.0.4"" resolved ""https://registry.yarnpkg.com/@types/uglify-js/-/uglify-js-3.0.4.tgz#96beae23df6f561862a830b4288a49e86baac082""" bf7b88cbf79ad04ea7de38e475749f585491ba55,2021-06-23 21:42:39,Burak Yigit Kaya,ci(lint): Add requirements checker (#26822),False,Add requirements checker (#26822),ci,"diff --git a/.github/file-filters.yml b/.github/file-filters.yml index 5beeccd3308cb6..f90cffa89d65ee 100644 --- a/.github/file-filters.yml +++ b/.github/file-filters.yml @@ -34,6 +34,7 @@ frontend_components_modified_lintable: backend_lintable: &backend_lintable - '**/*.py' + - 'requirements-base.txt' # Currently used in `getsentry-dispatch.yml` to dispatch backend tests on getsentry backend_dependencies: &backend_dependencies diff --git a/.github/workflows/backend-lint.yml b/.github/workflows/backend-lint.yml index d93ec40e8d3e2d..91d3f9629cedf7 100644 --- a/.github/workflows/backend-lint.yml +++ b/.github/workflows/backend-lint.yml @@ -89,6 +89,8 @@ jobs: filters: | all: - added|modified: '**/*.py' + - added|modified: 'requirements-base.txt' + - name: Run pre-commit on changed files if: steps.changes.outputs.backend == 'true' diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3a99192065da57..aed89d17d2109c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -51,6 +51,12 @@ repos: # We can't change this mock to unittest.mock until Python 3.8, # refer to the comment in this file. exclude: 'src/sentry/utils/compat/mock.py' + - id: lint-requirements + name: lint-requirements + entry: bin/lint-requirements + language: system + files: requirements-base.txt + pass_filenames: false - repo: https://github.com/sirosen/check-jsonschema rev: 0.3.0 diff --git a/bin/lint-requirements b/bin/lint-requirements new file mode 100755 index 00000000000000..cf3c619404cbfb --- /dev/null +++ b/bin/lint-requirements @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +import sys + +import requirements + + +def main(): + """""" + We cannot have non-specifier requirements if we want to publish to PyPI + due to security concerns. This check ensures we don't have/add any URL/VCS + dependencies in the base requirements file. + """""" + with open(""requirements-base.txt"") as reqs_file: + if any(not req.specifier for req in requirements.parse(reqs_file)): + print( + ""\n"".join( + [ + ""You cannot use dependencies that are not on PyPI directly."", + ""See PEP440: https://www.python.org/dev/peps/pep-0440/#direct-references"", + ] + ), + file=sys.stderr, + ) + sys.exit(1) + + +if __name__ == ""__main__"": + main() diff --git a/requirements-pre-commit.txt b/requirements-pre-commit.txt index 7a94870d5cd65a..c35bbc23608193 100644 --- a/requirements-pre-commit.txt +++ b/requirements-pre-commit.txt @@ -3,3 +3,4 @@ black==21.5b1 sentry-flake8==1.0.0 pyupgrade==2.18.3 isort==5.8.0 +requirements-parser>=0.2.0" 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) {" 6b103dd4d21f30e055d33b9e5dcad55d9dc7cfd3,2018-02-08 00:32:50,Jess MacQueen,fix(projects): Use correct team relation when getting full project name,False,Use correct team relation when getting full project name,fix,"diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py index 9a1a40f5573e1f..241f6685251ca8 100644 --- a/src/sentry/models/project.py +++ b/src/sentry/models/project.py @@ -227,8 +227,9 @@ def get_audit_log_data(self): } def get_full_name(self): - if self.team.name not in self.name: - return '%s %s' % (self.team.name, self.name) + team_name = self.teams.values_list('name', flat=True).first() + if team_name is not None and team_name not in self.name: + return '%s %s' % (team_name, self.name) return self.name def get_notification_recipients(self, user_option):" 08590747f2e04268bf57cc4d4f992bbe420e333a,2020-02-13 03:40:24,Evan Purkhiser,chore: Ignore Brewfile.lock (#16989),False,Ignore Brewfile.lock (#16989),chore,"diff --git a/.gitignore b/.gitignore index 1ac8aca08df12e..264d074e660227 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,4 @@ junit.xml package-lock.json .webpack.meta pip-wheel-metadata/ +Brewfile.lock.json" 9676933cf6a1464f87aea637989ffcaa10884b02,2022-07-08 17:15:35,Matej Minar,feat(sampling): Fix sampling prediction chart logic (#36470),False,Fix sampling prediction chart logic (#36470),feat,"diff --git a/static/app/views/settings/project/server-side-sampling/utils/projectStatsToPredictedSeries.tsx b/static/app/views/settings/project/server-side-sampling/utils/projectStatsToPredictedSeries.tsx index 5c73e0af840a2a..3b9af791a8b031 100644 --- a/static/app/views/settings/project/server-side-sampling/utils/projectStatsToPredictedSeries.tsx +++ b/static/app/views/settings/project/server-side-sampling/utils/projectStatsToPredictedSeries.tsx @@ -59,8 +59,8 @@ export function projectStatsToPredictedSeries( const total = accepted + filtered + invalid + dropped + rateLimited + clientDiscard; const newSentClient = clientRate * total; const droppedClient = total - newSentClient; - const validEvents = newSentClient - (filtered + invalid + rateLimited); - const newAccepted = serverRate * validEvents; + const validEvents = Math.max(newSentClient - (filtered + invalid + rateLimited), 0); + const newAccepted = serverRate > clientRate ? validEvents : serverRate * validEvents; const droppedServer = newSentClient - newAccepted; const name = moment(interval).valueOf();" fc8ca6f1b4a00f9c80284716ad178acc120ae238,2020-01-03 02:17:33,Stephen Cefali,feat(plugins): adds trello plugin using issuev2 (#16144),False,adds trello plugin using issuev2 (#16144),feat,"diff --git a/setup.py b/setup.py index e1d0818f4555e5..f9265ac39d36d9 100755 --- a/setup.py +++ b/setup.py @@ -112,6 +112,7 @@ def run(self): ""redmine = sentry_plugins.redmine"", ""sessionstack = sentry_plugins.sessionstack"", ""teamwork = sentry_plugins.teamwork"", + ""trello = sentry_plugins.trello"", ""twilio = sentry_plugins.twilio"", ], ""sentry.plugins"": [ @@ -136,6 +137,7 @@ def run(self): ""slack = sentry_plugins.slack.plugin:SlackPlugin"", ""splunk = sentry_plugins.splunk.plugin:SplunkPlugin"", ""teamwork = sentry_plugins.teamwork.plugin:TeamworkPlugin"", + ""trello = sentry_plugins.trello.plugin:TrelloPlugin"", ""twilio = sentry_plugins.twilio.plugin:TwilioPlugin"", ""victorops = sentry_plugins.victorops.plugin:VictorOpsPlugin"", ""vsts = sentry_plugins.vsts.plugin:VstsPlugin"", diff --git a/src/sentry_plugins/trello/Trello_Instructions.md b/src/sentry_plugins/trello/Trello_Instructions.md new file mode 100644 index 00000000000000..c663db12ea83a0 --- /dev/null +++ b/src/sentry_plugins/trello/Trello_Instructions.md @@ -0,0 +1,8 @@ +How to Setup Trello +=========================== + +1. Go to https://trello.com/app-key +2. Copy Key at top to ""Trello API Key"" field in settings form +3. Click link on page to go to token generation page +4. Press ""Allow"" on bottom right +5. Copy token to ""Trello API Token"" field and press ""Save Changes"" diff --git a/src/sentry_plugins/trello/__init__.py b/src/sentry_plugins/trello/__init__.py new file mode 100644 index 00000000000000..c3961685ab8def --- /dev/null +++ b/src/sentry_plugins/trello/__init__.py @@ -0,0 +1 @@ +from __future__ import absolute_import diff --git a/src/sentry_plugins/trello/client.py b/src/sentry_plugins/trello/client.py new file mode 100644 index 00000000000000..8c528277895122 --- /dev/null +++ b/src/sentry_plugins/trello/client.py @@ -0,0 +1,111 @@ +from __future__ import absolute_import + + +from sentry_plugins.client import ApiClient + + +ORG_BOARD_PATH = ""/organizations/%s/boards"" +MEMBER_ORG_PATH = ""/members/me/organizations"" +LISTS_OF_BOARD_PATH = ""/boards/%s/lists"" +NEW_CARD_PATH = ""/cards"" +SINGLE_CARD_PATH = ""/cards/%s"" +ADD_COMMENT_PATH = ""/cards/%s/actions/comments"" +MEMBER_BOARD_PATH = ""/members/me/boards"" +SEARCH_PATH = ""/search"" + +CARD_FIELDS = "","".join([""name"", ""shortLink"", ""idShort""]) + + +class TrelloApiClient(ApiClient): + base_url = ""https://api.trello.com/1"" + plugin_name = ""trello"" + + def __init__(self, api_key, token=None, **kwargs): + self.api_key = api_key + self.token = token + super(TrelloApiClient, self).__init__(**kwargs) + + def request(self, method=""GET"", path="""", data=None, params=None, **kwargs): + params = {} if params is None else params.copy() + params[""token""] = self.token + params[""key""] = self.api_key + return self._request(method, path, data=data, params=params, **kwargs) + + def get_organization_boards(self, org_id_or_name, fields=None): + """""" + Return boards for an organization/team + """""" + return self.request(path=ORG_BOARD_PATH % (org_id_or_name), params={""fields"": fields}) + + def get_member_boards(self, fields=None): + """""" + Return boards for a user + """""" + return self.request(path=MEMBER_BOARD_PATH, params={""fields"": fields}) + + def get_boards(self, org=None): + """""" + Return boards for an organization/team if set, otherwise return boards for user + """""" + if org: + return self.get_organization_boards(org, fields=""name"") + return self.get_member_boards(fields=""name"") + + def get_organization_list(self, fields=None): + """""" + Return organization list for user + """""" + return self.request(path=MEMBER_ORG_PATH, params={""fields"": fields}) + + def get_lists_of_board(self, board_id, fields=None): + """""" + Return the lists on a given board + """""" + return self.request(path=LISTS_OF_BOARD_PATH % (board_id), params={""fields"": fields}) + + def new_card(self, name, id_list, desc=None): + """""" + Create a Trello card + """""" + return self.request( + method=""POST"", path=NEW_CARD_PATH, data={""name"": name, ""idList"": id_list, ""desc"": desc} + ) + + def get_organization_options(self): + """""" + Return organization options to use in a Django form + """""" + organizations = self.get_organization_list(fields=""name"") + return [(org[""id""], org[""name""]) for org in organizations] + + def get_cards(self, query, org_id=None): + """""" + Return the cards matching a query, limited to an org if passed in + """""" + params = { + ""query"": query, + ""modelTypes"": ""cards"", + ""cards_limit"": 100, + ""partial"": ""true"", + ""card_fields"": CARD_FIELDS, + } + if org_id: + params[""idOrganizations""] = org_id + response = self.request(path=SEARCH_PATH, params=params) + return response[""cards""] + + def get_card(self, card_id_or_short_link): + """""" + Return a card from an ID or short link + """""" + return self.request( + path=SINGLE_CARD_PATH % card_id_or_short_link, params={""fields"": CARD_FIELDS} + ) + + def create_comment(self, card_id_or_short_link, comment): + """""" + Create a comment on a card + """""" + return self.request( + method=""POST"", path=ADD_COMMENT_PATH % card_id_or_short_link, params={""text"": comment} + ) diff --git a/src/sentry_plugins/trello/plugin.py b/src/sentry_plugins/trello/plugin.py new file mode 100644 index 00000000000000..ef57cb0b432c43 --- /dev/null +++ b/src/sentry_plugins/trello/plugin.py @@ -0,0 +1,277 @@ +from __future__ import absolute_import + +import re +from django.conf.urls import url +from rest_framework.response import Response + + +from sentry.utils.http import absolute_uri +from sentry.plugins.bases.issue2 import IssuePlugin2, IssueGroupActionEndpoint +from sentry_plugins.base import CorePluginMixin +from .client import TrelloApiClient + + +SETUP_URL = ""https://github.com/getsentry/sentry/blob/master/src/sentry_plugins/trello/Trello_Instructions.md"" # NOQA + +LABLEX_REGEX = re.compile(r""\w+/https://trello\.com/"") + + +class TrelloPlugin(CorePluginMixin, IssuePlugin2): + description = ""Create Trello cards on issues"" + slug = ""trello"" + title = ""Trello"" + conf_title = title + conf_key = ""trello"" + auth_provider = None + resource_links = [(""Trello Setup Instructions"", SETUP_URL)] + CorePluginMixin.resource_links + + def get_config(self, project, **kwargs): + """""" + Return the configuration of the plugin. + Pull the value out of our the arguments to this function or from the DB + """""" + + def get_value(field): + initial_values = kwargs.get(""initial"", {}) + return initial_values.get(field) or self.get_option(field, project) + + token_config = { + ""name"": ""token"", + ""type"": ""secret"", + ""label"": ""Trello API Token"", + ""default"": None, + } + + token_val = get_value(""token"") + if token_val: + # The token is sensitive so we should mask the value by only sending back the first 5 characters + token_config[""required""] = False + token_config[""prefix""] = token_val[:5] + token_config[""has_saved_value""] = True + else: + token_config[""required""] = True + + api_key = get_value(""key"") + + key_config = { + ""name"": ""key"", + ""type"": ""text"", + ""required"": True, + ""label"": ""Trello API Key"", + ""default"": api_key, + } + + config = [key_config, token_config] + org_value = get_value(""organization"") + include_org = kwargs.get(""add_additial_fields"", org_value) + if api_key and token_val and include_org: + trello_client = TrelloApiClient(api_key, token_val) + try: + org_options = trello_client.get_organization_options() + config.append( + { + ""name"": ""organization"", + ""label"": ""Trello Organization"", + ""choices"": org_options, + ""type"": ""select"", + ""required"": False, + ""default"": org_value, + } + ) + except Exception as e: + self.raise_error(e) + return config + + def validate_config(self, project, config, actor=None): + """""" + Make sure the configuration is valid by trying to query for the organizations with the auth + """""" + trello_client = TrelloApiClient(config[""key""], config[""token""]) + try: + trello_client.get_organization_options() + except Exception as e: + self.raise_error(e) + return config + + def get_group_urls(self): + """""" + Return the URLs and the matching views + """""" + return super(TrelloPlugin, self).get_group_urls() + [ + url( + r""^options"", + IssueGroupActionEndpoint.as_view(view_method_name=""view_options"", plugin=self), + ), + url( + r""^autocomplete"", + IssueGroupActionEndpoint.as_view(view_method_name=""view_autocomplete"", plugin=self), + ), + ] + + def is_configured(self, request, project, **kwargs): + return all(self.get_option(key, project) for key in (""token"", ""key"")) + + # used for boards and lists but not cards (shortLink used as ID for cards) + def map_to_options(self, items): + return [(item[""id""], item[""name""]) for item in items] + + def get_new_issue_fields(self, request, group, event, **kwargs): + """""" + Return the fields needed for creating a new issue + """""" + fields = super(TrelloPlugin, self).get_new_issue_fields(request, group, event, **kwargs) + client = self.get_client(group.project) + organization = self.get_option(""organization"", group.project) + + boards = client.get_boards(organization) + board_choices = self.map_to_options(boards) + + return fields + [ + { + ""name"": ""board"", + ""label"": ""Board"", + ""type"": ""select"", + ""choices"": board_choices, + ""readonly"": False, + ""required"": True, + }, + { + ""name"": ""list"", + ""depends"": [""board""], + ""label"": ""List"", + ""type"": ""select"", + ""has_autocomplete"": False, + ""required"": True, + }, + ] + + def get_link_existing_issue_fields(self, request, group, event, **kwargs): + """""" + Return the fields needed for linking to an existing issue + """""" + return [ + { + ""name"": ""issue_id"", + ""label"": ""Card"", + ""type"": ""select"", + ""has_autocomplete"": True, + ""required"": True, + }, + { + ""name"": ""comment"", + ""label"": ""Comment"", + ""default"": absolute_uri( + group.get_absolute_url(params={""referrer"": ""trello_plugin""}) + ), + ""type"": ""textarea"", + ""help"": (""Leave blank if you don't want to "" ""add a comment to the Trello card.""), + ""required"": False, + }, + ] + + def get_client(self, project): + return TrelloApiClient( + self.get_option(""key"", project), token=self.get_option(""token"", project) + ) + + def error_message_from_json(self, data): + errors = data.get(""errors"") + if errors: + return "" "".join(e[""message""] for e in errors) + return ""unknown error"" + + def create_issue(self, request, group, form_data, **kwargs): + client = self.get_client(group.project) + + try: + response = client.new_card( + id_list=form_data[""list""], name=form_data[""title""], desc=form_data[""description""] + ) + except Exception as e: + self.raise_error(e) + + return response[""shortLink""] + + def link_issue(self, request, group, form_data, **kwargs): + client = self.get_client(group.project) + + try: + card = client.get_card(form_data[""issue_id""]) + except Exception as e: + self.raise_error(e) + + comment = form_data.get(""comment"") + if comment: + try: + client.create_comment(card[""shortLink""], comment) + except Exception as e: + self.raise_error(e) + + return {""title"": card[""name""], ""id"": card[""shortLink""]} + + def get_issue_label(self, group, issue, **kwargs): + """""" + Return label of the linked issue we show in the UI from the issue string + """""" + # the old version of the plugin stores the url in the issue + if LABLEX_REGEX.search(issue): + short_issue = issue.split(""/"", 1)[0] + return ""Trello-%s"" % short_issue + return ""Trello-%s"" % issue + + def get_issue_url(self, group, issue, **kwargs): + """""" + Return label of the url of card in Trello based off the issue object or issue ID + """""" + # TODO(Steve): figure out why we sometimes get a string and sometimes a dict + if isinstance(issue, dict): + issue = issue[""id""] + # the old version of the plugin stores the url in the issue + if LABLEX_REGEX.search(issue): + return issue.split(""/"", 1)[1] + return ""https://trello.com/c/%s"" % issue + + def view_options(self, request, group, **kwargs): + """""" + Return the lists on a given Trello board + """""" + field = request.GET.get(""option_field"") + board = request.GET.get(""board"") + + results = [] + if field == ""list"" and board: + client = self.get_client(group.project) + try: + response = client.get_lists_of_board(board) + except Exception as e: + return Response( + { + ""error_type"": ""validation"", + ""errors"": [{""__all__"": self.message_from_error(e)}], + }, + status=400, + ) + else: + results = self.map_to_options(response) + + return Response({field: results}) + + def view_autocomplete(self, request, group, **kwargs): + """""" + Return the cards matching a given query and the organization of the configuration + """""" + field = request.GET.get(""autocomplete_field"") + query = request.GET.get(""autocomplete_query"") + + output = [] + if field == ""issue_id"" and query: + organization = self.get_option(""organization"", group.project) + + client = self.get_client(group.project) + cards = client.get_cards(query, organization) + output = [ + {""text"": ""(#%s) %s"" % (card[""idShort""], card[""name""]), ""id"": card[""shortLink""]} + for card in cards + ] + + return Response({field: output}) diff --git a/tests/sentry_plugins/trello/__init__.py b/tests/sentry_plugins/trello/__init__.py new file mode 100644 index 00000000000000..c3961685ab8def --- /dev/null +++ b/tests/sentry_plugins/trello/__init__.py @@ -0,0 +1 @@ +from __future__ import absolute_import diff --git a/tests/sentry_plugins/trello/test_plugin.py b/tests/sentry_plugins/trello/test_plugin.py new file mode 100644 index 00000000000000..f7bcfa2c98ea54 --- /dev/null +++ b/tests/sentry_plugins/trello/test_plugin.py @@ -0,0 +1,254 @@ +from __future__ import absolute_import + +import responses + +from exam import fixture +from django.test import RequestFactory +from sentry.testutils import PluginTestCase +from sentry.utils import json + +from sentry_plugins.trello.plugin import TrelloPlugin + + +class TrelloPluginTestBase(PluginTestCase): + @fixture + def plugin(self): + return TrelloPlugin() + + @fixture + def request(self): + return RequestFactory() + + +class TrelloPluginTest(TrelloPluginTestBase): + def test_conf_key(self): + assert self.plugin.conf_key == ""trello"" + + def test_entry_point(self): + self.assertPluginInstalled(""trello"", self.plugin) + + def test_get_issue_label(self): + group = self.create_group(message=""Hello world"", culprit=""foo.bar"") + # test new and old format + assert self.plugin.get_issue_label(group, ""rPPDb"") == ""Trello-rPPDb"" + assert ( + self.plugin.get_issue_label(group, ""5dafd/https://trello.com/c/rPPDb/75-title"") + == ""Trello-5dafd"" + ) + + def test_get_issue_url(self): + group = self.create_group(message=""Hello world"", culprit=""foo.bar"") + # test new and old format + assert self.plugin.get_issue_url(group, ""rPPDb"") == ""https://trello.com/c/rPPDb"" + assert self.plugin.get_issue_url(group, {""id"": ""rPPDb""}) == ""https://trello.com/c/rPPDb"" + assert ( + self.plugin.get_issue_url(group, ""5dafd/https://trello.com/c/rPPDb/75-title"") + == ""https://trello.com/c/rPPDb/75-title"" + ) + + def test_is_configured(self): + assert self.plugin.is_configured(None, self.project) is False + self.plugin.set_option(""token"", ""7c8951d1"", self.project) + assert self.plugin.is_configured(None, self.project) is False + self.plugin.set_option(""key"", ""39g"", self.project) + assert self.plugin.is_configured(None, self.project) is True + + +class TrelloPluginApiTests(TrelloPluginTestBase): + def setUp(self): + self.group = self.create_group(message=""Hello world"", culprit=""foo.bar"") + self.plugin.set_option(""token"", ""7c8951d1"", self.project) + self.plugin.set_option(""key"", ""39g"", self.project) + self.plugin.set_option(""organization"", ""f187"", self.project) + + self.login_as(self.user) + + def test_get_config_no_org(self): + self.plugin.unset_option(""organization"", self.project) + out = self.plugin.get_config(self.project) + assert out == [ + { + ""default"": ""39g"", + ""required"": True, + ""type"": ""text"", + ""name"": ""key"", + ""label"": ""Trello API Key"", + }, + { + ""name"": ""token"", + ""default"": None, + ""required"": False, + ""label"": ""Trello API Token"", + ""prefix"": ""7c895"", + ""type"": ""secret"", + ""has_saved_value"": True, + }, + ] + + @responses.activate + def test_get_config_include_additional(self): + self.plugin.unset_option(""organization"", self.project) + + responses.add( + responses.GET, + ""https://api.trello.com/1/members/me/organizations"", + json=[{""name"": ""team 1"", ""id"": ""2d8e""}, {""name"": ""team 2"", ""id"": ""d0cc""}], + ) + out = self.plugin.get_config(self.project, add_additial_fields=True) + assert out == [ + { + ""default"": ""39g"", + ""required"": True, + ""type"": ""text"", + ""name"": ""key"", + ""label"": ""Trello API Key"", + }, + { + ""name"": ""token"", + ""default"": None, + ""required"": False, + ""label"": ""Trello API Token"", + ""prefix"": ""7c895"", + ""type"": ""secret"", + ""has_saved_value"": True, + }, + { + ""name"": ""organization"", + ""default"": None, + ""required"": False, + ""choices"": [(""2d8e"", ""team 1""), (""d0cc"", ""team 2"")], + ""label"": ""Trello Organization"", + ""type"": ""select"", + }, + ] + + @responses.activate + def test_create_issue(self): + responses.add(responses.POST, ""https://api.trello.com/1/cards"", json={""shortLink"": ""rds43""}) + + form_data = { + ""title"": ""Hello"", + ""description"": ""Fix this."", + ""board"": ""ads23f"", + ""list"": ""23tds"", + } + request = self.make_request(user=self.user, method=""POST"") + + assert self.plugin.create_issue(request, self.group, form_data) == ""rds43"" + request = responses.calls[0].request + assert request.url == ""https://api.trello.com/1/cards?token=7c8951d1&key=39g"" + payload = json.loads(request.body) + assert payload == {""name"": ""Hello"", ""desc"": ""Fix this."", ""idList"": ""23tds""} + + @responses.activate + def test_link_issue(self): + responses.add( + responses.GET, + ""https://api.trello.com/1/cards/SstgnBIQ"", + json={""idShort"": 2, ""name"": ""MyTitle"", ""shortLink"": ""SstgnBIQ""}, + ) + responses.add( + responses.POST, ""https://api.trello.com/1/cards/SstgnBIQ/actions/comments"", json={} + ) + + form_data = {""comment"": ""please fix this"", ""issue_id"": ""SstgnBIQ""} + request = self.make_request(user=self.user, method=""POST"") + + assert self.plugin.link_issue(request, self.group, form_data) == { + ""title"": ""MyTitle"", + ""id"": ""SstgnBIQ"", + } + + request = responses.calls[0].request + assert ( + request.url + == ""https://api.trello.com/1/cards/SstgnBIQ?fields=name%2CshortLink%2CidShort&token=7c8951d1&key=39g"" + ) + + request = responses.calls[1].request + assert ( + request.url + == ""https://api.trello.com/1/cards/SstgnBIQ/actions/comments?text=please+fix+this&token=7c8951d1&key=39g"" + ) + + @responses.activate + def test_view_options(self): + responses.add( + responses.GET, + ""https://api.trello.com/1/boards/f34/lists"", + json=[{""id"": ""8f3"", ""name"": ""list 1""}, {""id"": ""j8f"", ""name"": ""list 2""}], + ) + + request = self.make_request(user=self.user, method=""GET"") + request.GET[""option_field""] = ""list"" + request.GET[""board""] = ""f34"" + + response = self.plugin.view_options(request, self.group) + assert response.data == {""list"": [(""8f3"", ""list 1""), (""j8f"", ""list 2"")]} + + request = responses.calls[0].request + assert request.url == ""https://api.trello.com/1/boards/f34/lists?token=7c8951d1&key=39g"" + + @responses.activate + def test_view_autocomplete(self): + responses.add( + responses.GET, + ""https://api.trello.com/1/search"", + json={ + ""cards"": [ + {""id"": ""4fsdafad"", ""name"": ""KeyError"", ""idShort"": 1, ""shortLink"": ""0lr""}, + {""id"": ""f4usdfa"", ""name"": ""Key Missing"", ""idShort"": 3, ""shortLink"": ""9lf""}, + ] + }, + ) + + request = self.make_request(user=self.user, method=""GET"") + request.GET[""autocomplete_field""] = ""issue_id"" + request.GET[""autocomplete_query""] = ""Key"" + + response = self.plugin.view_autocomplete(request, self.group) + assert response.data == { + ""issue_id"": [ + {""id"": ""0lr"", ""text"": ""(#1) KeyError""}, + {""id"": ""9lf"", ""text"": ""(#3) Key Missing""}, + ] + } + + request = responses.calls[0].request + assert ( + request.url + == ""https://api.trello.com/1/search?cards_limit=100&partial=true&card_fields=name%2CshortLink%2CidShort&key=39g&query=Key&modelTypes=cards&token=7c8951d1&idOrganizations=f187"" + ) + + @responses.activate + def test_view_autocomplete_no_org(self): + self.plugin.unset_option(""organization"", self.project) + + responses.add( + responses.GET, + ""https://api.trello.com/1/search"", + json={ + ""cards"": [ + {""id"": ""4fsdafad"", ""name"": ""KeyError"", ""idShort"": 1, ""shortLink"": ""0lr""}, + {""id"": ""f4usdfa"", ""name"": ""Key Missing"", ""idShort"": 3, ""shortLink"": ""9lf""}, + ] + }, + ) + + request = self.make_request(user=self.user, method=""GET"") + request.GET[""autocomplete_field""] = ""issue_id"" + request.GET[""autocomplete_query""] = ""Key"" + + response = self.plugin.view_autocomplete(request, self.group) + assert response.data == { + ""issue_id"": [ + {""id"": ""0lr"", ""text"": ""(#1) KeyError""}, + {""id"": ""9lf"", ""text"": ""(#3) Key Missing""}, + ] + } + + request = responses.calls[0].request + assert ( + request.url + == ""https://api.trello.com/1/search?cards_limit=100&partial=true&modelTypes=cards&token=7c8951d1&card_fields=name%2CshortLink%2CidShort&key=39g&query=Key"" + )" 7d1c120798916f942299dae3c96836b193f2974d,2023-05-19 22:50:57,Alberto Leal,chore(hybrid-cloud): Properly delete org member records when deleting the user account (#49433),False,Properly delete org member records when deleting the user account (#49433),chore,"diff --git a/src/sentry/api/endpoints/user_details.py b/src/sentry/api/endpoints/user_details.py index a2fb20ebf08e0d..520703ad39a122 100644 --- a/src/sentry/api/endpoints/user_details.py +++ b/src/sentry/api/endpoints/user_details.py @@ -254,9 +254,10 @@ def delete(self, request: Request, user) -> Response: ] if remaining_org_ids: - OrganizationMember.objects.filter( + for member in OrganizationMember.objects.filter( organization__in=remaining_org_ids, user_id=user.id - ).delete() + ): + member.delete() logging_data = { ""actor_id"": request.user.id, diff --git a/tests/sentry/api/endpoints/test_user_details.py b/tests/sentry/api/endpoints/test_user_details.py index 72dffa12178597..d5bcd0719d489f 100644 --- a/tests/sentry/api/endpoints/test_user_details.py +++ b/tests/sentry/api/endpoints/test_user_details.py @@ -1,5 +1,6 @@ from sentry.models import ( Organization, + OrganizationMember, OrganizationStatus, User, UserOption, @@ -7,6 +8,8 @@ UserRole, ) from sentry.testutils import APITestCase +from sentry.testutils.hybrid_cloud import HybridCloudTestMixin +from sentry.testutils.outbox import outbox_runner from sentry.testutils.silo import control_silo_test @@ -239,7 +242,7 @@ def test_superuser_with_permission_can_add_staff(self): @control_silo_test -class UserDetailsDeleteTest(UserDetailsTest): +class UserDetailsDeleteTest(UserDetailsTest, HybridCloudTestMixin): method = ""delete"" def test_close_account(self): @@ -298,7 +301,21 @@ def test_close_account_no_orgs(self): self.create_member(user=user2, organization=org_with_other_owner, role=""owner"") self.create_member(user=self.user, organization=org_as_other_owner, role=""owner"") - self.get_success_response(self.user.id, organizations=[], status_code=204) + member_records = list( + OrganizationMember.objects.filter( + organization__in=[org_with_other_owner.id, org_as_other_owner.id], + user_id=self.user.id, + ) + ) + + for member in member_records: + self.assert_org_member_mapping(org_member=member) + + with outbox_runner(): + self.get_success_response(self.user.id, organizations=[], status_code=204) + + for member in member_records: + self.assert_org_member_mapping_not_exists(org_member=member) # deletes org_single_owner even though it wasn't specified in array # because it has a single owner" 50688caa9a402ac7dc1f40b92374a1d241cb634a,2024-12-21 02:51:03,anthony sottile,ref: strptime -> fromisoformat in tests (#82488),False,strptime -> fromisoformat in tests (#82488),ref,"diff --git a/tests/sentry/api/endpoints/test_custom_rules.py b/tests/sentry/api/endpoints/test_custom_rules.py index 1c7ba791b57ed8..6c3d42ae031456 100644 --- a/tests/sentry/api/endpoints/test_custom_rules.py +++ b/tests/sentry/api/endpoints/test_custom_rules.py @@ -10,7 +10,7 @@ UnsupportedSearchQueryReason, get_rule_condition, ) -from sentry.models.dynamicsampling import CUSTOM_RULE_DATE_FORMAT, CustomDynamicSamplingRule +from sentry.models.dynamicsampling import CustomDynamicSamplingRule from sentry.testutils.cases import APITestCase, TestCase @@ -206,8 +206,8 @@ def test_create(self): data = resp.data - start_date = datetime.strptime(data[""startDate""], CUSTOM_RULE_DATE_FORMAT) - end_date = datetime.strptime(data[""endDate""], CUSTOM_RULE_DATE_FORMAT) + start_date = datetime.fromisoformat(data[""startDate""]) + end_date = datetime.fromisoformat(data[""endDate""]) assert end_date - start_date == timedelta(days=2) projects = data[""projects""] assert projects == [self.project.id] @@ -260,8 +260,8 @@ def test_updates_existing(self): data = resp.data rule_id = data[""ruleId""] - start_date = datetime.strptime(data[""startDate""], CUSTOM_RULE_DATE_FORMAT) - end_date = datetime.strptime(data[""endDate""], CUSTOM_RULE_DATE_FORMAT) + start_date = datetime.fromisoformat(data[""startDate""]) + end_date = datetime.fromisoformat(data[""endDate""]) assert end_date - start_date == timedelta(days=2) request_data = { @@ -275,8 +275,8 @@ def test_updates_existing(self): assert resp.status_code == 200 data = resp.data - start_date = datetime.strptime(data[""startDate""], CUSTOM_RULE_DATE_FORMAT) - end_date = datetime.strptime(data[""endDate""], CUSTOM_RULE_DATE_FORMAT) + start_date = datetime.fromisoformat(data[""startDate""]) + end_date = datetime.fromisoformat(data[""endDate""]) assert end_date - start_date >= timedelta(days=2) projects = data[""projects""] diff --git a/tests/sentry/api/endpoints/test_group_ai_autofix.py b/tests/sentry/api/endpoints/test_group_ai_autofix.py index 915274955569d3..568c5e13dbc92f 100644 --- a/tests/sentry/api/endpoints/test_group_ai_autofix.py +++ b/tests/sentry/api/endpoints/test_group_ai_autofix.py @@ -29,7 +29,7 @@ def test_ai_autofix_get_endpoint_with_autofix(self, mock_get_autofix_state): mock_get_autofix_state.return_value = AutofixState( run_id=123, request={""project_id"": 456, ""issue"": {""id"": 789}}, - updated_at=datetime.strptime(""2023-07-18T12:00:00Z"", ""%Y-%m-%dT%H:%M:%SZ""), + updated_at=datetime.fromisoformat(""2023-07-18T12:00:00Z""), status=AutofixStatus.PROCESSING, ) @@ -64,7 +64,7 @@ def test_ai_autofix_get_endpoint_repositories( mock_get_autofix_state.return_value = AutofixState( run_id=123, request={""project_id"": 456, ""issue"": {""id"": 789}}, - updated_at=datetime.strptime(""2023-07-18T12:00:00Z"", ""%Y-%m-%dT%H:%M:%SZ""), + updated_at=datetime.fromisoformat(""2023-07-18T12:00:00Z""), status=AutofixStatus.PROCESSING, ) diff --git a/tests/sentry/issues/test_escalating_issues_alg.py b/tests/sentry/issues/test_escalating_issues_alg.py index 80087b5aaf12e0..800e293f758308 100644 --- a/tests/sentry/issues/test_escalating_issues_alg.py +++ b/tests/sentry/issues/test_escalating_issues_alg.py @@ -1,12 +1,10 @@ from datetime import datetime -from typing import Any from sentry.issues.escalating_issues_alg import generate_issue_forecast -from sentry.tasks.weekly_escalating_forecast import GroupCount -START_TIME = datetime.strptime(""2022-07-27T00:00:00+00:00"", ""%Y-%m-%dT%H:%M:%S%f%z"") +START_TIME = datetime.fromisoformat(""2022-07-27T00:00:00+00:00"") -SEVEN_DAY_INPUT_INTERVALS: list[Any] = [ +SEVEN_DAY_INPUT_INTERVALS = [ ""2022-07-20T00:00:00+00:00"", ""2022-07-20T01:00:00+00:00"", ""2022-07-20T02:00:00+00:00"", @@ -177,7 +175,7 @@ ""2022-07-26T23:00:00+00:00"", ] -SIX_DAY_INPUT_INTERVALS: list[Any] = [ +SIX_DAY_INPUT_INTERVALS = [ ""2022-07-21T00:00:00+00:00"", ""2022-07-21T01:00:00+00:00"", ""2022-07-21T02:00:00+00:00"", @@ -324,7 +322,7 @@ ""2022-07-26T23:00:00+00:00"", ] -SEVEN_DAY_ERROR_EVENTS: list[Any] = [ +SEVEN_DAY_ERROR_EVENTS = [ 74, 532, 670, @@ -497,10 +495,10 @@ def test_spike_case() -> None: - start_time = datetime.strptime(""2022-07-27T00:00:00+00:00"", ""%Y-%m-%dT%H:%M:%S%f%z"") - data: GroupCount = {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": SEVEN_DAY_ERROR_EVENTS} - - ceilings_list = generate_issue_forecast(data, start_time) + start_time = datetime.fromisoformat(""2022-07-27T00:00:00+00:00"") + ceilings_list = generate_issue_forecast( + {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": SEVEN_DAY_ERROR_EVENTS}, start_time + ) ceilings = [x[""forecasted_value""] for x in ceilings_list] assert ceilings == [6987] * 14, ""Ceilings are incorrect"" @@ -583,20 +581,18 @@ def test_bursty_case() -> None: 7627, ] + [0] * 95 - data: GroupCount = {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": error_events} - - ceilings_list = generate_issue_forecast(data, START_TIME) + ceilings_list = generate_issue_forecast( + {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": error_events}, START_TIME + ) ceilings = [x[""forecasted_value""] for x in ceilings_list] assert ceilings == [16580] * 14, ""Ceilings are incorrect"" def test_empty_input() -> None: - error_events: list[int] = [] - - data: GroupCount = {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": error_events} - - ceilings_list = generate_issue_forecast(data, START_TIME) + ceilings_list = generate_issue_forecast( + {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": []}, START_TIME + ) ceilings = [x[""forecasted_value""] for x in ceilings_list] assert ceilings == [], ""Empty Input"" @@ -655,9 +651,9 @@ def test_less_than_week_data() -> None: 7627, ] + [0] * 95 - data: GroupCount = {""intervals"": SIX_DAY_INPUT_INTERVALS, ""data"": error_events} - - ceilings_list = generate_issue_forecast(data, START_TIME) + ceilings_list = generate_issue_forecast( + {""intervals"": SIX_DAY_INPUT_INTERVALS, ""data"": error_events}, START_TIME + ) ceilings = [x[""forecasted_value""] for x in ceilings_list] assert ceilings == [82900] * 14, ""Ceilings are incorrect"" @@ -666,18 +662,18 @@ def test_less_than_week_data() -> None: def test_low_freq_events() -> None: error_events = [6] * 168 - data: GroupCount = {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": error_events} - - ceilings_list = generate_issue_forecast(data, START_TIME) + ceilings_list = generate_issue_forecast( + {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": error_events}, START_TIME + ) ceilings = [x[""forecasted_value""] for x in ceilings_list] assert ceilings == [36] * 14, ""Ceilings are incorrect"" def test_output() -> None: - data: GroupCount = {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": SEVEN_DAY_ERROR_EVENTS} - - ceilings_list = generate_issue_forecast(data, START_TIME) + ceilings_list = generate_issue_forecast( + {""intervals"": SEVEN_DAY_INPUT_INTERVALS, ""data"": SEVEN_DAY_ERROR_EVENTS}, START_TIME + ) assert ceilings_list == [ {""forecasted_date"": ""2022-07-27"", ""forecasted_value"": 6987}," f92c32447f93fa209234d431204e409dd2bc1dd1,2024-09-16 23:20:58,Evan Purkhiser,ref(uptime): Include host_provider_id in restricted_by_provider metric (#77495),False,Include host_provider_id in restricted_by_provider metric (#77495),ref,"diff --git a/src/sentry/uptime/consumers/results_consumer.py b/src/sentry/uptime/consumers/results_consumer.py index bcc4c6905a539d..07253c48ca4771 100644 --- a/src/sentry/uptime/consumers/results_consumer.py +++ b/src/sentry/uptime/consumers/results_consumer.py @@ -267,13 +267,15 @@ def handle_result_for_project_active_mode( restricted_host_provider_ids = options.get( ""uptime.restrict-issue-creation-by-hosting-provider-id"" ) - issue_creation_restricted_by_provider = ( - project_subscription.uptime_subscription.host_provider_id - in restricted_host_provider_ids - ) + host_provider_id = project_subscription.uptime_subscription.host_provider_id + issue_creation_restricted_by_provider = host_provider_id in restricted_host_provider_ids if issue_creation_restricted_by_provider: - metrics.incr(""uptime.result_processor.restricted_by_provider"", sample_rate=1.0) + metrics.incr( + ""uptime.result_processor.restricted_by_provider"", + sample_rate=1.0, + tags={""host_provider_id"": host_provider_id}, + ) if issue_creation_flag_enabled and not issue_creation_restricted_by_provider: create_issue_platform_occurrence(result, project_subscription) diff --git a/tests/sentry/uptime/consumers/test_results_consumers.py b/tests/sentry/uptime/consumers/test_results_consumers.py index 1ec189a2937f4e..598ca481b1c0eb 100644 --- a/tests/sentry/uptime/consumers/test_results_consumers.py +++ b/tests/sentry/uptime/consumers/test_results_consumers.py @@ -148,7 +148,11 @@ def test_restricted_host_provider_id(self): self.send_result(result) metrics.incr.assert_has_calls( [ - call(""uptime.result_processor.restricted_by_provider"", sample_rate=1.0), + call( + ""uptime.result_processor.restricted_by_provider"", + sample_rate=1.0, + tags={""host_provider_id"": ""TEST""}, + ), ], any_order=True, )" 93d197337329d6e69f9d7d4a68401bdf85420388,2024-03-14 14:29:15,Jernej Strasner,ref(recap): Remove deprecated recap polling feature UI code (#66858),False,Remove deprecated recap polling feature UI code (#66858),ref,"diff --git a/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx b/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx index d4f218909403b1..c498340ecce4a1 100644 --- a/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx +++ b/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx @@ -54,22 +54,6 @@ const formGroups: JsonFormObject[] = [ formatStoreCrashReports(value, organization.storeCrashReports), ]), }, - { - name: 'recapServerUrl', - type: 'string', - placeholder: t('URL'), - label: t('Recap Server URL'), - help: t('URL to the Recap Server events should be polled from'), - visible: ({features}) => features.has('recap-server'), - }, - { - name: 'recapServerToken', - type: 'string', - placeholder: t('Token'), - label: t('Recap Server Token'), - help: t('Auth Token to the configured Recap Server'), - visible: ({features}) => features.has('recap-server'), - }, ], }, {" 9bd718fff89f945348e4327d9d63286cd323357b,2023-03-29 18:19:11,Riccardo Busetti,ref(dynamic-sampling): Simplify biases architecture (#46374),False,Simplify biases architecture (#46374),ref,"diff --git a/src/sentry/dynamic_sampling/__init__.py b/src/sentry/dynamic_sampling/__init__.py index 0fee9f3a048807..a38538672b3b56 100644 --- a/src/sentry/dynamic_sampling/__init__.py +++ b/src/sentry/dynamic_sampling/__init__.py @@ -1,11 +1,8 @@ from .rules.base import generate_rules -from .rules.biases.boost_environments_bias import ENVIRONMENT_GLOBS, BoostEnvironmentsRulesGenerator -from .rules.biases.boost_key_transactions_bias import BoostKeyTransactionsRulesGenerator -from .rules.biases.boost_latest_releases_bias import BoostLatestReleasesRulesGenerator -from .rules.biases.ignore_health_checks_bias import ( - HEALTH_CHECK_GLOBS, - IgnoreHealthChecksRulesGenerator, -) +from .rules.biases.boost_environments_bias import ENVIRONMENT_GLOBS, BoostEnvironmentsBias +from .rules.biases.boost_key_transactions_bias import BoostKeyTransactionsBias +from .rules.biases.boost_latest_releases_bias import BoostLatestReleasesBias +from .rules.biases.ignore_health_checks_bias import HEALTH_CHECK_GLOBS, IgnoreHealthChecksBias from .rules.helpers.latest_releases import ( ExtendedBoostedRelease, LatestReleaseBias, @@ -40,10 +37,10 @@ ""Platform"", ""LatestReleaseBias"", ""LatestReleaseParams"", - ""IgnoreHealthChecksRulesGenerator"", - ""BoostKeyTransactionsRulesGenerator"", - ""BoostEnvironmentsRulesGenerator"", - ""BoostLatestReleasesRulesGenerator"", + ""IgnoreHealthChecksBias"", + ""BoostKeyTransactionsBias"", + ""BoostEnvironmentsBias"", + ""BoostLatestReleasesBias"", ""LATEST_RELEASE_TTAS"", ""ENVIRONMENT_GLOBS"", ""BOOSTED_KEY_TRANSACTION_LIMIT"", diff --git a/src/sentry/dynamic_sampling/rules/base.py b/src/sentry/dynamic_sampling/rules/base.py index 9c5f7e6a7e1864..9976486d9de6f3 100644 --- a/src/sentry/dynamic_sampling/rules/base.py +++ b/src/sentry/dynamic_sampling/rules/base.py @@ -3,7 +3,7 @@ import sentry_sdk from sentry import quotas -from sentry.dynamic_sampling.rules.biases.base import Bias, BiasParams +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.combine import get_relay_biases_combinator from sentry.dynamic_sampling.rules.helpers.prioritise_project import ( get_prioritise_by_project_sample_rate, @@ -40,7 +40,7 @@ def _get_rules_of_enabled_biases( if rule_type in ALWAYS_ALLOWED_RULE_TYPES or ( rule_type.value in enabled_biases and 0.0 < base_sample_rate < 1.0 ): - rules += bias.get_rules(BiasParams(project, base_sample_rate)) + rules += bias.generate_rules(project, base_sample_rate) log_rules(project.organization.id, project.id, rules) diff --git a/src/sentry/dynamic_sampling/rules/biases/base.py b/src/sentry/dynamic_sampling/rules/biases/base.py index 1435c87e0d77b7..5f2f14a6e8e7a8 100644 --- a/src/sentry/dynamic_sampling/rules/biases/base.py +++ b/src/sentry/dynamic_sampling/rules/biases/base.py @@ -1,55 +1,19 @@ from abc import ABC, abstractmethod from collections import namedtuple -from typing import Any, Dict, List, Type +from typing import Any, Dict, List from sentry.dynamic_sampling.rules.utils import PolymorphicRule +from sentry.models import Project BiasData = Dict[str, Any] BiasParams = namedtuple(""BiasParams"", ""project base_sample_rate"") -class BiasDataProvider(ABC): - """""" - Base class representing the provider of data needed to generate a rule connected to a bias. - """""" - - @abstractmethod - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - raise NotImplementedError - - -class BiasRulesGenerator(ABC): +class Bias(ABC): """""" Base class representing the generator of rules connected to a bias. """""" - def __init__(self, data_provider: BiasDataProvider): - self.data_provider = data_provider - - def generate_bias_rules(self, bias_params: BiasParams) -> List[PolymorphicRule]: - return self._generate_bias_rules(self.data_provider.get_bias_data(bias_params)) - @abstractmethod - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: raise NotImplementedError - - -class Bias(ABC): - """""" - Base class containing business logic that automatically handles the execution flow and inter-dependencies of the - data provider and rules generator. - - The goal of this class is to abstract away the interaction between the provider and generator, in order to make - this abstractions work like a small framework. - """""" - - def __init__( - self, - data_provider_cls: Type[BiasDataProvider], - rules_generator_cls: Type[BiasRulesGenerator], - ): - self.data_provider = data_provider_cls() - self.rules_generator = rules_generator_cls(self.data_provider) - - def get_rules(self, bias_params: BiasParams) -> List[PolymorphicRule]: - return self.rules_generator.generate_bias_rules(bias_params) diff --git a/src/sentry/dynamic_sampling/rules/biases/boost_environments_bias.py b/src/sentry/dynamic_sampling/rules/biases/boost_environments_bias.py index 66cc6a56a0a315..b8441727a710cd 100644 --- a/src/sentry/dynamic_sampling/rules/biases/boost_environments_bias.py +++ b/src/sentry/dynamic_sampling/rules/biases/boost_environments_bias.py @@ -1,13 +1,8 @@ from typing import List -from sentry.dynamic_sampling.rules.biases.base import ( - Bias, - BiasData, - BiasDataProvider, - BiasParams, - BiasRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.utils import RESERVED_IDS, PolymorphicRule, RuleType +from sentry.models import Project ENVIRONMENT_GLOBS = [ ""*dev*"", @@ -17,13 +12,8 @@ ] -class BoostEnvironmentsDataProvider(BiasDataProvider): - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - return {""id"": RESERVED_IDS[RuleType.BOOST_ENVIRONMENTS_RULE]} - - -class BoostEnvironmentsRulesGenerator(BiasRulesGenerator): - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: +class BoostEnvironmentsBias(Bias): + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: return [ { ""samplingValue"": { @@ -41,11 +31,6 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: } ], }, - ""id"": bias_data[""id""], + ""id"": RESERVED_IDS[RuleType.BOOST_ENVIRONMENTS_RULE], } ] - - -class BoostEnvironmentsBias(Bias): - def __init__(self) -> None: - super().__init__(BoostEnvironmentsDataProvider, BoostEnvironmentsRulesGenerator) diff --git a/src/sentry/dynamic_sampling/rules/biases/boost_key_transactions_bias.py b/src/sentry/dynamic_sampling/rules/biases/boost_key_transactions_bias.py index c0ada32e306d37..d7c78f561edd21 100644 --- a/src/sentry/dynamic_sampling/rules/biases/boost_key_transactions_bias.py +++ b/src/sentry/dynamic_sampling/rules/biases/boost_key_transactions_bias.py @@ -1,12 +1,6 @@ from typing import List -from sentry.dynamic_sampling.rules.biases.base import ( - Bias, - BiasData, - BiasDataProvider, - BiasParams, - BiasRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.helpers.key_transactions import get_key_transactions from sentry.dynamic_sampling.rules.utils import ( KEY_TRANSACTIONS_BOOST_FACTOR, @@ -15,29 +9,20 @@ RuleType, apply_dynamic_factor, ) +from sentry.models import Project -class BoostKeyTransactionsDataProvider(BiasDataProvider): - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - return { - ""id"": RESERVED_IDS[RuleType.BOOST_KEY_TRANSACTIONS_RULE], - ""factor"": apply_dynamic_factor( - bias_params.base_sample_rate, KEY_TRANSACTIONS_BOOST_FACTOR - ), - ""keyTransactions"": get_key_transactions(bias_params.project), - } - - -class BoostKeyTransactionsRulesGenerator(BiasRulesGenerator): - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: - if len(bias_data[""keyTransactions""]) == 0: +class BoostKeyTransactionsBias(Bias): + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: + key_transactions = get_key_transactions(project) + if len(key_transactions) == 0: return [] return [ { ""samplingValue"": { ""type"": ""factor"", - ""value"": bias_data[""factor""], + ""value"": apply_dynamic_factor(base_sample_rate, KEY_TRANSACTIONS_BOOST_FACTOR), }, ""type"": ""transaction"", ""condition"": { @@ -46,16 +31,11 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: { ""op"": ""eq"", ""name"": ""event.transaction"", - ""value"": bias_data[""keyTransactions""], + ""value"": key_transactions, ""options"": {""ignoreCase"": True}, } ], }, - ""id"": bias_data[""id""], + ""id"": RESERVED_IDS[RuleType.BOOST_KEY_TRANSACTIONS_RULE], } ] - - -class BoostKeyTransactionsBias(Bias): - def __init__(self) -> None: - super().__init__(BoostKeyTransactionsDataProvider, BoostKeyTransactionsRulesGenerator) diff --git a/src/sentry/dynamic_sampling/rules/biases/boost_latest_releases_bias.py b/src/sentry/dynamic_sampling/rules/biases/boost_latest_releases_bias.py index f8a87ddeb8baa1..5c0e3faecdba4b 100644 --- a/src/sentry/dynamic_sampling/rules/biases/boost_latest_releases_bias.py +++ b/src/sentry/dynamic_sampling/rules/biases/boost_latest_releases_bias.py @@ -1,13 +1,7 @@ from datetime import datetime from typing import List, cast -from sentry.dynamic_sampling.rules.biases.base import ( - Bias, - BiasData, - BiasDataProvider, - BiasParams, - BiasRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.helpers.latest_releases import ProjectBoostedReleases from sentry.dynamic_sampling.rules.utils import ( LATEST_RELEASES_BOOST_DECAYED_FACTOR, @@ -17,28 +11,16 @@ RuleType, apply_dynamic_factor, ) +from sentry.models import Project -class BoostLatestReleasesDataProvider(BiasDataProvider): - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - return { - ""id"": RESERVED_IDS[RuleType.BOOST_LATEST_RELEASES_RULE], - ""factor"": apply_dynamic_factor( - bias_params.base_sample_rate, LATEST_RELEASES_BOOST_FACTOR - ), - ""decayedFactor"": LATEST_RELEASES_BOOST_DECAYED_FACTOR, - ""boostedReleases"": ProjectBoostedReleases( - bias_params.project.id - ).get_extended_boosted_releases(), - } - - -class BoostLatestReleasesRulesGenerator(BiasRulesGenerator): +class BoostLatestReleasesBias(Bias): datetime_format = ""%Y-%m-%dT%H:%M:%SZ"" - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: - boosted_releases = bias_data[""boostedReleases""] + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: + factor = apply_dynamic_factor(base_sample_rate, LATEST_RELEASES_BOOST_FACTOR) + boosted_releases = ProjectBoostedReleases(project.id).get_extended_boosted_releases() return cast( List[PolymorphicRule], @@ -46,7 +28,7 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: { ""samplingValue"": { ""type"": ""factor"", - ""value"": bias_data[""factor""], + ""value"": factor, }, ""type"": ""trace"", ""condition"": { @@ -67,7 +49,7 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: }, ], }, - ""id"": bias_data[""id""] + idx, + ""id"": RESERVED_IDS[RuleType.BOOST_LATEST_RELEASES_RULE] + idx, ""timeRange"": { ""start"": datetime.utcfromtimestamp(boosted_release.timestamp).strftime( self.datetime_format @@ -78,14 +60,9 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: }, ""decayingFn"": { ""type"": ""linear"", - ""decayedValue"": bias_data[""decayedFactor""], + ""decayedValue"": LATEST_RELEASES_BOOST_DECAYED_FACTOR, }, } for idx, boosted_release in enumerate(boosted_releases) ], ) - - -class BoostLatestReleasesBias(Bias): - def __init__(self) -> None: - super().__init__(BoostLatestReleasesDataProvider, BoostLatestReleasesRulesGenerator) diff --git a/src/sentry/dynamic_sampling/rules/biases/boost_rare_transactions_rule.py b/src/sentry/dynamic_sampling/rules/biases/boost_rare_transactions_rule.py index 5c3a47ce0678c4..265fdaea0895a2 100644 --- a/src/sentry/dynamic_sampling/rules/biases/boost_rare_transactions_rule.py +++ b/src/sentry/dynamic_sampling/rules/biases/boost_rare_transactions_rule.py @@ -1,31 +1,19 @@ from typing import List -from sentry.dynamic_sampling.rules.biases.base import ( - Bias, - BiasData, - BiasDataProvider, - BiasParams, - BiasRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.helpers.prioritize_transactions import ( get_transactions_resampling_rates, ) from sentry.dynamic_sampling.rules.utils import RESERVED_IDS, PolymorphicRule, Rule, RuleType +from sentry.models import Project -class RareTransactionsDataProvider(BiasDataProvider): - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - return {""project"": bias_params.project, ""sample_rate"": bias_params.base_sample_rate} - - -class RareTransactionsRulesGenerator(BiasRulesGenerator): - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: - project = bias_data[""project""] - sample_rate = bias_data[""sample_rate""] +class RareTransactionsRulesBias(Bias): + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: proj_id = project.id org_id = project.organization.id transaction_map, rate = get_transactions_resampling_rates( - org_id=org_id, proj_id=proj_id, default_rate=sample_rate + org_id=org_id, proj_id=proj_id, default_rate=base_sample_rate ) ret_val: List[Rule] = [] @@ -34,8 +22,8 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: idx = 0 for name, transaction_rate in transaction_map.items(): - if sample_rate != 0: - transaction_rate /= sample_rate + if base_sample_rate != 0: + transaction_rate /= base_sample_rate # add a rule for each rebalanced transaction ret_val.append( { @@ -59,9 +47,5 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: } ) idx += 1 - return ret_val - -class RareTransactionsRulesBias(Bias): - def __init__(self) -> None: - super().__init__(RareTransactionsDataProvider, RareTransactionsRulesGenerator) + return ret_val diff --git a/src/sentry/dynamic_sampling/rules/biases/ignore_health_checks_bias.py b/src/sentry/dynamic_sampling/rules/biases/ignore_health_checks_bias.py index f570a0d6b0ba67..db040f5563a9d9 100644 --- a/src/sentry/dynamic_sampling/rules/biases/ignore_health_checks_bias.py +++ b/src/sentry/dynamic_sampling/rules/biases/ignore_health_checks_bias.py @@ -1,18 +1,13 @@ from typing import List -from sentry.dynamic_sampling.rules.biases.base import ( - Bias, - BiasData, - BiasDataProvider, - BiasParams, - BiasRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.utils import ( IGNORE_HEALTH_CHECKS_FACTOR, RESERVED_IDS, PolymorphicRule, RuleType, ) +from sentry.models import Project # https://kubernetes.io/docs/reference/using-api/health-checks/ # Also it covers: livez, readyz @@ -27,20 +22,14 @@ ] -class IgnoreHealthChecksDataProvider(BiasDataProvider): - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - return { - ""id"": RESERVED_IDS[RuleType.IGNORE_HEALTH_CHECKS_RULE], - ""sampleRate"": bias_params.base_sample_rate / IGNORE_HEALTH_CHECKS_FACTOR, - ""healthCheckGlobs"": HEALTH_CHECK_GLOBS, - } - - -class IgnoreHealthChecksRulesGenerator(BiasRulesGenerator): - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: +class IgnoreHealthChecksBias(Bias): + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: return [ { - ""samplingValue"": {""type"": ""sampleRate"", ""value"": bias_data[""sampleRate""]}, + ""samplingValue"": { + ""type"": ""sampleRate"", + ""value"": base_sample_rate / IGNORE_HEALTH_CHECKS_FACTOR, + }, ""type"": ""transaction"", ""condition"": { ""op"": ""or"", @@ -48,15 +37,10 @@ def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: { ""op"": ""glob"", ""name"": ""event.transaction"", - ""value"": bias_data[""healthCheckGlobs""], + ""value"": HEALTH_CHECK_GLOBS, } ], }, - ""id"": bias_data[""id""], + ""id"": RESERVED_IDS[RuleType.IGNORE_HEALTH_CHECKS_RULE], } ] - - -class IgnoreHealthChecksBias(Bias): - def __init__(self) -> None: - super().__init__(IgnoreHealthChecksDataProvider, IgnoreHealthChecksRulesGenerator) diff --git a/src/sentry/dynamic_sampling/rules/biases/uniform_bias.py b/src/sentry/dynamic_sampling/rules/biases/uniform_bias.py index e5440b4be9e974..8f200a0182db33 100644 --- a/src/sentry/dynamic_sampling/rules/biases/uniform_bias.py +++ b/src/sentry/dynamic_sampling/rules/biases/uniform_bias.py @@ -1,41 +1,23 @@ from typing import List -from sentry.dynamic_sampling.rules.biases.base import ( - Bias, - BiasData, - BiasDataProvider, - BiasParams, - BiasRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.base import Bias from sentry.dynamic_sampling.rules.utils import RESERVED_IDS, PolymorphicRule, RuleType +from sentry.models import Project -class UniformDataProvider(BiasDataProvider): - def get_bias_data(self, bias_params: BiasParams) -> BiasData: - return { - ""id"": RESERVED_IDS[RuleType.UNIFORM_RULE], - ""sampleRate"": bias_params.base_sample_rate, - } - - -class UniformRulesGenerator(BiasRulesGenerator): - def _generate_bias_rules(self, bias_data: BiasData) -> List[PolymorphicRule]: +class UniformBias(Bias): + def generate_rules(self, project: Project, base_sample_rate: float) -> List[PolymorphicRule]: return [ { ""samplingValue"": { ""type"": ""sampleRate"", - ""value"": bias_data[""sampleRate""], + ""value"": base_sample_rate, }, ""type"": ""trace"", ""condition"": { ""op"": ""and"", ""inner"": [], }, - ""id"": bias_data[""id""], + ""id"": RESERVED_IDS[RuleType.UNIFORM_RULE], } ] - - -class UniformBias(Bias): - def __init__(self) -> None: - super().__init__(UniformDataProvider, UniformRulesGenerator) diff --git a/tests/sentry/dynamic_sampling/rules/biases/test_boost_environments_bias.py b/tests/sentry/dynamic_sampling/rules/biases/test_boost_environments_bias.py index 10699e8a3660e9..87c5f9fcf42206 100644 --- a/tests/sentry/dynamic_sampling/rules/biases/test_boost_environments_bias.py +++ b/tests/sentry/dynamic_sampling/rules/biases/test_boost_environments_bias.py @@ -1,23 +1,12 @@ -from unittest.mock import MagicMock, patch - import pytest from sentry.dynamic_sampling import ENVIRONMENT_GLOBS -from sentry.dynamic_sampling.rules.biases.boost_environments_bias import ( - BoostEnvironmentsRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.boost_environments_bias import BoostEnvironmentsBias @pytest.mark.django_db -@patch(""sentry.dynamic_sampling.rules.biases.boost_environments_bias.BoostEnvironmentsDataProvider"") -def test_generate_bias_rules_v2(data_provider, default_project): - rule_id = 1002 - - data_provider.get_bias_data.return_value = { - ""id"": rule_id, - } - - rules = BoostEnvironmentsRulesGenerator(data_provider).generate_bias_rules(MagicMock()) +def test_generate_bias_rules_v2(default_project): + rules = BoostEnvironmentsBias().generate_rules(project=default_project, base_sample_rate=0.1) assert rules == [ { ""condition"": { @@ -30,7 +19,7 @@ def test_generate_bias_rules_v2(data_provider, default_project): ], ""op"": ""or"", }, - ""id"": rule_id, + ""id"": 1001, ""samplingValue"": {""type"": ""sampleRate"", ""value"": 1.0}, ""type"": ""trace"", } diff --git a/tests/sentry/dynamic_sampling/rules/biases/test_boost_key_transactions_bias.py b/tests/sentry/dynamic_sampling/rules/biases/test_boost_key_transactions_bias.py index 4f9152b326c6ff..130d9a7ef274d4 100644 --- a/tests/sentry/dynamic_sampling/rules/biases/test_boost_key_transactions_bias.py +++ b/tests/sentry/dynamic_sampling/rules/biases/test_boost_key_transactions_bias.py @@ -1,28 +1,19 @@ -from unittest.mock import MagicMock, patch +from unittest.mock import patch import pytest from sentry.dynamic_sampling.rules.biases.boost_key_transactions_bias import ( - BoostKeyTransactionsRulesGenerator, + BoostKeyTransactionsBias, ) @pytest.mark.django_db -@patch( - ""sentry.dynamic_sampling.rules.biases.boost_key_transactions_bias.BoostKeyTransactionsDataProvider"" -) -def test_generate_bias_rules_v2(data_provider, default_project): - rule_id = 1002 - factor = 1.5 +@patch(""sentry.dynamic_sampling.rules.biases.boost_key_transactions_bias.get_key_transactions"") +def test_generate_bias_rules_v2(get_key_transactions, default_project): key_transactions = [""/foo"", ""/bar""] + get_key_transactions.return_value = key_transactions - data_provider.get_bias_data.return_value = { - ""id"": rule_id, - ""factor"": factor, - ""keyTransactions"": key_transactions, - } - - rules = BoostKeyTransactionsRulesGenerator(data_provider).generate_bias_rules(MagicMock()) + rules = BoostKeyTransactionsBias().generate_rules(default_project, base_sample_rate=0.0) assert rules == [ { ""condition"": { @@ -36,23 +27,18 @@ def test_generate_bias_rules_v2(data_provider, default_project): ], ""op"": ""or"", }, - ""id"": rule_id, - ""samplingValue"": {""type"": ""factor"", ""value"": factor}, + ""id"": 1003, + ""samplingValue"": {""type"": ""factor"", ""value"": 1.5}, ""type"": ""transaction"", } ] @pytest.mark.django_db -@patch( - ""sentry.dynamic_sampling.rules.biases.boost_key_transactions_bias.BoostKeyTransactionsDataProvider"" -) -def test_generate_bias_rules_with_no_key_transactions(data_provider, default_project): - data_provider.get_bias_data.return_value = { - ""id"": 1002, - ""sampleRate"": 0.8, - ""keyTransactions"": [], - } - - rules = BoostKeyTransactionsRulesGenerator(data_provider).generate_bias_rules(MagicMock()) +@patch(""sentry.dynamic_sampling.rules.biases.boost_key_transactions_bias.get_key_transactions"") +def test_generate_bias_rules_with_no_key_transactions(get_key_transactions, default_project): + key_transactions = [] + get_key_transactions.return_value = key_transactions + + rules = BoostKeyTransactionsBias().generate_rules(project=default_project, base_sample_rate=0.0) assert rules == [] diff --git a/tests/sentry/dynamic_sampling/rules/biases/test_boost_latest_releases_bias.py b/tests/sentry/dynamic_sampling/rules/biases/test_boost_latest_releases_bias.py index 7eb5973ba7164d..1e2ec602f43d32 100644 --- a/tests/sentry/dynamic_sampling/rules/biases/test_boost_latest_releases_bias.py +++ b/tests/sentry/dynamic_sampling/rules/biases/test_boost_latest_releases_bias.py @@ -1,14 +1,12 @@ from datetime import timedelta -from unittest.mock import MagicMock, patch +from unittest.mock import patch import pytest from django.utils import timezone from freezegun import freeze_time from sentry.dynamic_sampling import LATEST_RELEASE_TTAS, ExtendedBoostedRelease, Platform -from sentry.dynamic_sampling.rules.biases.boost_latest_releases_bias import ( - BoostLatestReleasesRulesGenerator, -) +from sentry.dynamic_sampling.rules.biases.boost_latest_releases_bias import BoostLatestReleasesBias ONE_DAY_AGO = timezone.now() - timedelta(days=1) MOCK_DATETIME = ONE_DAY_AGO.replace(hour=10, minute=0, second=0, microsecond=0) @@ -17,17 +15,12 @@ @freeze_time(MOCK_DATETIME) @pytest.mark.django_db @patch( - ""sentry.dynamic_sampling.rules.biases.boost_latest_releases_bias.BoostLatestReleasesDataProvider"" + ""sentry.dynamic_sampling.rules.biases.boost_latest_releases_bias.ProjectBoostedReleases.get_extended_boosted_releases"" ) -def test_generate_bias_rules_v2(data_provider, default_project): +def test_generate_bias_rules_v2(get_boosted_releases, default_project): now = timezone.now() - - factor = 1.5 - decayed_factor = 1.0 platform = ""python"" - default_project.update(platform=platform) - boosted_releases = [ ExtendedBoostedRelease( id=12345, @@ -46,15 +39,9 @@ def test_generate_bias_rules_v2(data_provider, default_project): platform=Platform(platform), ), ] + get_boosted_releases.return_value = boosted_releases - data_provider.get_bias_data.return_value = { - ""id"": 1000, - ""factor"": factor, - ""decayedFactor"": decayed_factor, - ""boostedReleases"": boosted_releases, - } - - rules = BoostLatestReleasesRulesGenerator(data_provider).generate_bias_rules(MagicMock()) + rules = BoostLatestReleasesBias().generate_rules(project=default_project, base_sample_rate=0.0) assert rules == [ { ""condition"": { @@ -64,15 +51,15 @@ def test_generate_bias_rules_v2(data_provider, default_project): ], ""op"": ""and"", }, - ""id"": 1000, - ""samplingValue"": {""type"": ""factor"", ""value"": factor}, + ""id"": 1500, + ""samplingValue"": {""type"": ""factor"", ""value"": 1.5}, ""timeRange"": { ""end"": (now + timedelta(seconds=LATEST_RELEASE_TTAS[platform])) .isoformat() .replace(""+00:00"", ""Z""), ""start"": now.isoformat().replace(""+00:00"", ""Z""), }, - ""decayingFn"": {""type"": ""linear"", ""decayedValue"": decayed_factor}, + ""decayingFn"": {""type"": ""linear"", ""decayedValue"": 1.0}, ""type"": ""trace"", }, { @@ -83,15 +70,15 @@ def test_generate_bias_rules_v2(data_provider, default_project): ], ""op"": ""and"", }, - ""id"": 1001, - ""samplingValue"": {""type"": ""factor"", ""value"": factor}, + ""id"": 1501, + ""samplingValue"": {""type"": ""factor"", ""value"": 1.5}, ""timeRange"": { ""end"": (now + timedelta(seconds=LATEST_RELEASE_TTAS[platform])) .isoformat() .replace(""+00:00"", ""Z""), ""start"": now.isoformat().replace(""+00:00"", ""Z""), }, - ""decayingFn"": {""type"": ""linear"", ""decayedValue"": decayed_factor}, + ""decayingFn"": {""type"": ""linear"", ""decayedValue"": 1.0}, ""type"": ""trace"", }, ] @@ -99,16 +86,12 @@ def test_generate_bias_rules_v2(data_provider, default_project): @pytest.mark.django_db @patch( - ""sentry.dynamic_sampling.rules.biases.boost_latest_releases_bias.BoostLatestReleasesDataProvider"" + ""sentry.dynamic_sampling.rules.biases.boost_latest_releases_bias.ProjectBoostedReleases.get_extended_boosted_releases"" ) -def test_generate_bias_rules_with_no_boosted_releases(data_provider, default_project): +def test_generate_bias_rules_with_no_boosted_releases(get_boosted_releases, default_project): default_project.update(platform=""python"") + boosted_releases = [] + get_boosted_releases.return_value = boosted_releases - data_provider.get_bias_data.return_value = { - ""id"": 1000, - ""sampleRate"": 0.7, - ""boostedReleases"": [], - } - - rules = BoostLatestReleasesRulesGenerator(data_provider).generate_bias_rules(MagicMock()) + rules = BoostLatestReleasesBias().generate_rules(project=default_project, base_sample_rate=0.0) assert rules == [] diff --git a/tests/sentry/dynamic_sampling/rules/biases/test_boost_rare_transactions_rule.py b/tests/sentry/dynamic_sampling/rules/biases/test_boost_rare_transactions_rule.py index c30517706638e5..c06a520cb8740f 100644 --- a/tests/sentry/dynamic_sampling/rules/biases/test_boost_rare_transactions_rule.py +++ b/tests/sentry/dynamic_sampling/rules/biases/test_boost_rare_transactions_rule.py @@ -1,7 +1,6 @@ from unittest.mock import MagicMock, patch from sentry.dynamic_sampling import RESERVED_IDS, RuleType -from sentry.dynamic_sampling.rules.biases.base import BiasParams from sentry.dynamic_sampling.rules.biases.boost_rare_transactions_rule import ( RareTransactionsRulesBias, ) @@ -39,12 +38,9 @@ def test_transaction_boost_known_projects(get_transactions_resampling_rates): """""" project, fake_get_trans_res_rates = _create_mocks() rate = 0.2 - get_transactions_resampling_rates.side_effect = fake_get_trans_res_rates - bias = RareTransactionsRulesBias() - rules = bias.get_rules(BiasParams(project=project, base_sample_rate=rate)) - + rules = RareTransactionsRulesBias().generate_rules(project=project, base_sample_rate=rate) expected = [ { ""samplingValue"": {""type"": ""factor"", ""value"": 0.1 / rate}, @@ -90,6 +86,5 @@ def test_transaction_boost_unknown_projects(): project, fake_get_trans_res_rates = _create_mocks() rate = 0.2 - bias = RareTransactionsRulesBias() - rules = bias.get_rules(BiasParams(project=project, base_sample_rate=rate)) + rules = RareTransactionsRulesBias().generate_rules(project=project, base_sample_rate=rate) assert rules == [] diff --git a/tests/sentry/dynamic_sampling/rules/biases/test_ignore_health_checks_bias.py b/tests/sentry/dynamic_sampling/rules/biases/test_ignore_health_checks_bias.py index 19cb0caceed9ba..da43a79dcba125 100644 --- a/tests/sentry/dynamic_sampling/rules/biases/test_ignore_health_checks_bias.py +++ b/tests/sentry/dynamic_sampling/rules/biases/test_ignore_health_checks_bias.py @@ -1,28 +1,14 @@ -from unittest.mock import MagicMock, patch - import pytest from sentry.dynamic_sampling.rules.biases.ignore_health_checks_bias import ( - IgnoreHealthChecksRulesGenerator, + HEALTH_CHECK_GLOBS, + IgnoreHealthChecksBias, ) @pytest.mark.django_db -@patch( - ""sentry.dynamic_sampling.rules.biases.ignore_health_checks_bias.IgnoreHealthChecksDataProvider"" -) -def test_generate_bias_rules_v2(data_provider, default_project): - rule_id = 1001 - sample_rate = 1.0 - health_check_globs = [""/health"", ""/healtz"", ""/*health*""] - - data_provider.get_bias_data.return_value = { - ""id"": rule_id, - ""sampleRate"": sample_rate, - ""healthCheckGlobs"": health_check_globs, - } - - rules = IgnoreHealthChecksRulesGenerator(data_provider).generate_bias_rules(MagicMock()) +def test_generate_bias_rules_v2(default_project): + rules = IgnoreHealthChecksBias().generate_rules(project=default_project, base_sample_rate=1.0) assert rules == [ { ""condition"": { @@ -30,13 +16,13 @@ def test_generate_bias_rules_v2(data_provider, default_project): { ""name"": ""event.transaction"", ""op"": ""glob"", - ""value"": health_check_globs, + ""value"": HEALTH_CHECK_GLOBS, } ], ""op"": ""or"", }, - ""id"": rule_id, - ""samplingValue"": {""type"": ""sampleRate"", ""value"": 1.0}, + ""id"": 1002, + ""samplingValue"": {""type"": ""sampleRate"", ""value"": 0.2}, ""type"": ""transaction"", } ]" 62d08012072b5f31aaea9976ec20e6bb1350b4dc,2020-06-23 16:09:59,Priscila Oliveira,fix(pii): Clear event id status (#19490),False,Clear event id status (#19490),fix,"diff --git a/src/sentry/static/sentry/app/views/settings/components/dataScrubbing/index.tsx b/src/sentry/static/sentry/app/views/settings/components/dataScrubbing/index.tsx index 345c7808dc078b..6040ac1ff58c9f 100644 --- a/src/sentry/static/sentry/app/views/settings/components/dataScrubbing/index.tsx +++ b/src/sentry/static/sentry/app/views/settings/components/dataScrubbing/index.tsx @@ -242,7 +242,7 @@ class DataScrubbing extends React.Component< this.setState(prevState => ({ showAddRuleModal, eventId: - prevState.eventId?.status === EventIdStatus.LOADED + prevState.eventId?.status !== EventIdStatus.LOADED ? {value: ''} : prevState.eventId, }));" 761fb67c7ee1fb52946961e0c17d22c17ef4f7b4,2023-03-18 00:25:58,Zach Collins,fix(hc): silo decorator can break pytest class tests. Fix it (#46000),False,silo decorator can break pytest class tests. Fix it (#46000),fix,"diff --git a/src/sentry/testutils/silo.py b/src/sentry/testutils/silo.py index 97f3cc1750ddd8..e1598143794ad4 100644 --- a/src/sentry/testutils/silo.py +++ b/src/sentry/testutils/silo.py @@ -134,7 +134,8 @@ def replacement_test_method(*args: Any, **kwargs: Any) -> None: def _call(self, decorated_obj: Any, stable: bool) -> Any: is_test_case_class = isinstance(decorated_obj, type) and issubclass(decorated_obj, TestCase) - is_function = callable(decorated_obj) + is_function = inspect.isfunction(decorated_obj) + if not (is_test_case_class or is_function): raise ValueError(""@SiloModeTest must decorate a function or TestCase class"") diff --git a/tests/sentry/api/endpoints/test_project_app_store_connect_credentials.py b/tests/sentry/api/endpoints/test_project_app_store_connect_credentials.py index 5b7fe85039f9ae..a06a3b262e8511 100644 --- a/tests/sentry/api/endpoints/test_project_app_store_connect_credentials.py +++ b/tests/sentry/api/endpoints/test_project_app_store_connect_credentials.py @@ -9,11 +9,9 @@ AppStoreUpdateCredentialsSerializer, ) from sentry.lang.native.appconnect import AppStoreConnectConfig -from sentry.testutils.silo import region_silo_test from sentry.utils import json -@region_silo_test(stable=True) class TestAppStoreUpdateCredentialsSerializer: def test_validate_secrets_magic_object_true(self): payload_json = """"""{""appconnectPrivateKey"": {""hidden-secret"": true}}"""""" @@ -83,7 +81,6 @@ def test_validate_secrets_string(self): assert data[""appconnectPrivateKey""] == ""honk"" -@region_silo_test(stable=True) class TestAppStoreConnectRefreshEndpoint: @pytest.fixture # type: ignore def config_id(self, default_project): diff --git a/tests/sentry/nodestore/django/test_backend.py b/tests/sentry/nodestore/django/test_backend.py index 55d70116851bab..b520fa0b7d338f 100644 --- a/tests/sentry/nodestore/django/test_backend.py +++ b/tests/sentry/nodestore/django/test_backend.py @@ -12,12 +12,12 @@ from sentry.utils.strings import compress -@region_silo_test(stable=True) @pytest.mark.django_db class TestDjangoNodeStorage: def setup_method(self): self.ns = DjangoNodeStorage() + @region_silo_test(stable=True) @pytest.mark.parametrize( ""node_data"", [ @@ -35,6 +35,7 @@ def test_get(self, node_data): result = self.ns.get(node.id) assert result == {""foo"": ""bar""} + @region_silo_test(stable=True) def test_get_multi(self): Node.objects.create(id=""d2502ebbd7df41ceba8d3275595cac33"", data=compress(b'{""foo"": ""bar""}')) Node.objects.create(id=""5394aa025b8e401ca6bc3ddee3130edc"", data=compress(b'{""foo"": ""baz""}')) @@ -47,24 +48,28 @@ def test_get_multi(self): ""5394aa025b8e401ca6bc3ddee3130edc"": {""foo"": ""baz""}, } + @region_silo_test(stable=True) def test_set(self): self.ns.set(""d2502ebbd7df41ceba8d3275595cac33"", {""foo"": ""bar""}) assert Node.objects.get(id=""d2502ebbd7df41ceba8d3275595cac33"").data == compress( b'{""foo"":""bar""}' ) + @region_silo_test(stable=True) def test_delete(self): node = Node.objects.create(id=""d2502ebbd7df41ceba8d3275595cac33"", data=b'{""foo"": ""bar""}') self.ns.delete(node.id) assert not Node.objects.filter(id=node.id).exists() + @region_silo_test(stable=True) def test_delete_multi(self): node = Node.objects.create(id=""d2502ebbd7df41ceba8d3275595cac33"", data=b'{""foo"": ""bar""}') self.ns.delete_multi([node.id]) assert not Node.objects.filter(id=node.id).exists() + @region_silo_test(stable=True) def test_cleanup(self): now = timezone.now() cutoff = now - timedelta(days=1)" 0ba88f70abdc7911b5a01613bcf416ec5e5e03a4,2023-02-01 04:13:31,Snigdha Sharma,ref(codecov): Set codecov tags more consistently (#43923),False,Set codecov tags more consistently (#43923),ref,"diff --git a/src/sentry/api/endpoints/project_stacktrace_link.py b/src/sentry/api/endpoints/project_stacktrace_link.py index c209e5922c1d19..00e227be6b8f03 100644 --- a/src/sentry/api/endpoints/project_stacktrace_link.py +++ b/src/sentry/api/endpoints/project_stacktrace_link.py @@ -128,8 +128,6 @@ def set_tags(scope: Scope, result: JSONData) -> None: scope.set_tag( ""stacktrace_link.auto_derived"", result[""config""][""automaticallyGenerated""] is True ) - if result.get(""codecov"") and result[""codecov""].get(""attemptedUrl""): - scope.set_tag(""codecov.attempted_url"", result[""codecov""][""attemptedUrl""]) @region_silo_endpoint @@ -271,7 +269,7 @@ def get(self, request: Request, project: Project) -> Response: ) and project.organization.flags.codecov_access ) - + scope.set_tag(""codecov.enabled"", codecov_enabled) if codecov_enabled: try: lineCoverage, codecovUrl = get_codecov_data( @@ -299,7 +297,6 @@ def get(self, request: Request, project: Project) -> Response: except Exception: logger.exception(""Something unexpected happen. Continuing execution."") # We don't expect coverage data if the integration does not exist (404) - scope.set_tag(""codecov.enabled"", True) try: set_tags(scope, result) diff --git a/src/sentry/integrations/utils/codecov.py b/src/sentry/integrations/utils/codecov.py index 06e300f8072634..444f082e59418a 100644 --- a/src/sentry/integrations/utils/codecov.py +++ b/src/sentry/integrations/utils/codecov.py @@ -28,16 +28,25 @@ def get_codecov_data( response = requests.get( url, params=params, headers={""Authorization"": f""Bearer {codecov_token}""} ) - scope.set_tag(""codecov.http_code"", response.status_code) + tags = { + ""codecov.request_url"": url, + ""codecov.request_path"": path, + ""codecov.request_branch"": branch, + ""codecov.http_code"": response.status_code, + } + response_json = response.json() files = response_json.get(""files"") line_coverage = files[0].get(""line_coverage"") if files else None coverage_found = line_coverage not in [None, [], [[]]] - scope.set_tag(""codecov.coverage_found"", coverage_found) + tags[""codecov.coverage_found""] = coverage_found + + codecov_url = response_json.get(""commit_file_url"", """") + tags[""codecov.coverage_url""] = codecov_url + for key, value in tags.items(): + scope.set_tag(key, value) response.raise_for_status() - codecov_url = response_json.get(""commit_file_url"") - scope.set_tag(""codecov.url"", codecov_url) return line_coverage, codecov_url" a190469caecf2befdfcaa18f83698787ec5eb4b5,2024-02-29 03:04:36,Jonas,fix(trace): prevent loss of zooming state when interacting with UI (#65833),False,prevent loss of zooming state when interacting with UI (#65833),fix,"diff --git a/static/app/views/performance/newTraceDetails/trace.tsx b/static/app/views/performance/newTraceDetails/trace.tsx index 8adb0845f11b48..98a3baff174967 100644 --- a/static/app/views/performance/newTraceDetails/trace.tsx +++ b/static/app/views/performance/newTraceDetails/trace.tsx @@ -4,6 +4,7 @@ import {browserHistory} from 'react-router'; import {AutoSizer, List} from 'react-virtualized'; import {type Theme, useTheme} from '@emotion/react'; import styled from '@emotion/styled'; +import * as qs from 'query-string'; import ProjectAvatar from 'sentry/components/avatar/projectAvatar'; import LoadingIndicator from 'sentry/components/loadingIndicator'; @@ -15,7 +16,6 @@ import {space} from 'sentry/styles/space'; import type {Project} from 'sentry/types'; import {getDuration} from 'sentry/utils/formatters'; import useApi from 'sentry/utils/useApi'; -import {useLocation} from 'sentry/utils/useLocation'; import useOrganization from 'sentry/utils/useOrganization'; import useProjects from 'sentry/utils/useProjects'; @@ -53,8 +53,12 @@ function Trace({trace, trace_id}: TraceProps) { const api = useApi(); const {projects} = useProjects(); const organization = useOrganization(); - const location = useLocation(); - const viewManager = useRef(null); + const viewManager = useMemo(() => { + return new VirtualizedViewManager({ + list: {width: 0.5}, + span_list: {width: 0.5}, + }); + }, []); const [clickedNode, setClickedNode] = useState | null>(null); @@ -65,47 +69,31 @@ function Trace({trace, trace_id}: TraceProps) { const treeRef = useRef(trace); treeRef.current = trace; - if (!viewManager.current) { - viewManager.current = new VirtualizedViewManager({ - list: {width: 0.5}, - span_list: {width: 0.5}, - }); - } - if ( trace.root.space && - (trace.root.space[0] !== viewManager.current.to_origin || - trace.root.space[1] !== viewManager.current.trace_space.width) + (trace.root.space[0] !== viewManager.to_origin || + trace.root.space[1] !== viewManager.trace_space.width) ) { - viewManager.current.initializeTraceSpace([ - trace.root.space[0], - 0, - trace.root.space[1], - 1, - ]); - scrollQueue.current = decodeScrollQueue(location.query.node); + viewManager.initializeTraceSpace([trace.root.space[0], 0, trace.root.space[1], 1]); + scrollQueue.current = decodeScrollQueue(qs.parse(location.search).node); } useEffect(() => { - if ( - trace.type === 'loading' || - scrollQueue.current === null || - !viewManager.current - ) { + if (trace.type === 'loading' || scrollQueue.current === null || !viewManager) { return; } - viewManager.current + viewManager .scrollToPath(trace, scrollQueue.current, () => setRender(a => (a + 1) % 2), { api, organization, }) .then(_maybeNode => { setClickedNode(_maybeNode); - viewManager.current?.onScrollEndOutOfBoundsCheck(); + viewManager.onScrollEndOutOfBoundsCheck(); scrollQueue.current = null; }); - }, [api, organization, trace, trace_id]); + }, [api, organization, trace, trace_id, viewManager]); const handleFetchChildren = useCallback( (node: TraceTreeNode, value: boolean) => { @@ -133,18 +121,15 @@ function Trace({trace, trace_id}: TraceProps) { [] ); - const onRowClick = useCallback( - (node: TraceTreeNode) => { - browserHistory.push({ - pathname: location.pathname, - query: { - ...location.query, - node: node.path, - }, - }); - }, - [location.query, location.pathname] - ); + const onRowClick = useCallback((node: TraceTreeNode) => { + browserHistory.push({ + pathname: location.pathname, + query: { + ...qs.parse(location.search), + node: node.path, + }, + }); + }, []); const projectLookup = useMemo(() => { return projects.reduce>((acc, project) => { @@ -156,7 +141,7 @@ function Trace({trace, trace_id}: TraceProps) { return ( viewManager.current?.onContainerRef(r)} + ref={r => viewManager.onContainerRef(r)} className={trace.type === 'loading' ? 'Loading' : ''} style={{ height: '70vh', @@ -166,7 +151,7 @@ function Trace({trace, trace_id}: TraceProps) { > viewManager.current?.registerDividerRef(r)} + ref={r => viewManager?.registerDividerRef(r)} /> {trace.type === 'loading' ? : null} @@ -177,9 +162,7 @@ function Trace({trace, trace_id}: TraceProps) { return (
- viewManager.current?.registerIndicatorRef(r, i, indicator) - } + ref={r => viewManager.registerIndicatorRef(r, i, indicator)} className=""TraceIndicator"" >
@@ -188,7 +171,7 @@ function Trace({trace, trace_id}: TraceProps) { }) : null} viewManager.current?.registerList(r)} + ref={r => viewManager.registerList(r)} rowHeight={24} height={height} width={width} @@ -203,7 +186,7 @@ function Trace({trace, trace_id}: TraceProps) { index={p.index} theme={theme} projects={projectLookup} - viewManager={viewManager.current!} + viewManager={viewManager!} startIndex={ (p.parent as unknown as {_rowStartIndex: number}) ._rowStartIndex ?? 0 @@ -222,7 +205,7 @@ function Trace({trace, trace_id}: TraceProps) { trace_id={trace_id} projects={projectLookup} node={treeRef.current.list[p.index]} - viewManager={viewManager.current!} + viewManager={viewManager!} clickedNode={clickedNode} onFetchChildren={handleFetchChildren} onExpandNode={handleExpandNode} @@ -335,6 +318,8 @@ function RenderRow(props: { } style={{ width: props.viewManager.columns.span_list.width * 100 + '%', + backgroundColor: + props.index % 2 === 0 ? props.theme.backgroundSecondary : undefined, }} > {isParentAutogroupedNode(props.node) ? ( @@ -423,6 +408,8 @@ function RenderRow(props: { className=""TraceRightColumn"" style={{ width: props.viewManager.columns.span_list.width * 100 + '%', + backgroundColor: + props.index % 2 === 0 ? props.theme.backgroundSecondary : undefined, }} > {' '} @@ -701,6 +694,8 @@ function RenderRow(props: { className=""TraceRightColumn"" style={{ width: props.viewManager.columns.span_list.width * 100 + '%', + backgroundColor: + props.index % 2 === 0 ? props.theme.backgroundSecondary : undefined, }} > {/* @TODO: figure out what to do with trace errors */}{' '} @@ -774,6 +769,8 @@ function RenderPlaceholderRow(props: { className=""TraceRightColumn"" style={{ width: props.viewManager.columns.span_list.width * 100 + '%', + backgroundColor: + props.index % 2 === 0 ? props.theme.backgroundSecondary : undefined, }} > p.theme.fontSizeSmall}; - &:nth-of-type(odd) { - .TraceRightColumn { - background-color: ${p => p.theme.backgroundSecondary}; - } - } - &:hover { background-color: ${p => p.theme.backgroundSecondary}; } diff --git a/static/app/views/performance/newTraceDetails/virtualizedViewManager.tsx b/static/app/views/performance/newTraceDetails/virtualizedViewManager.tsx index c888bbbd21ce56..5df7a37816783b 100644 --- a/static/app/views/performance/newTraceDetails/virtualizedViewManager.tsx +++ b/static/app/views/performance/newTraceDetails/virtualizedViewManager.tsx @@ -461,6 +461,10 @@ export class VirtualizedViewManager { if (span_list?.children?.[0]) { (span_list.children[0] as HTMLElement).style.pointerEvents = 'none'; } + const span_text = this.span_text[i]; + if (span_text) { + span_text.ref.style.pointerEvents = 'none'; + } } } @@ -472,6 +476,10 @@ export class VirtualizedViewManager { if (span_list?.children?.[0]) { (span_list.children[0] as HTMLElement).style.pointerEvents = 'auto'; } + const span_text = this.span_text[i]; + if (span_text) { + span_text.ref.style.pointerEvents = 'auto'; + } } }" 20a52093bfab434484f4620b732485e6479d4122,2024-06-21 02:42:32,Josh Ferge,fix(projects): turn off degraded symbolication fetching in project se… (#73078),False,turn off degraded symbolication fetching in project se… (#73078),fix,"diff --git a/src/sentry/api/serializers/models/project.py b/src/sentry/api/serializers/models/project.py index d8680e0f375e17..7ea107389de45f 100644 --- a/src/sentry/api/serializers/models/project.py +++ b/src/sentry/api/serializers/models/project.py @@ -27,7 +27,6 @@ from sentry.ingest.inbound_filters import FilterTypes from sentry.issues.highlights import get_highlight_preset_for_project from sentry.lang.native.sources import parse_sources, redact_source_secrets -from sentry.lang.native.symbolicator import SymbolicatorPlatform from sentry.lang.native.utils import convert_crashreport_count from sentry.models.environment import EnvironmentProject from sentry.models.options.project_option import OPTION_KEYS, ProjectOption @@ -42,7 +41,6 @@ from sentry.release_health.base import CurrentAndPreviousCrashFreeRate from sentry.roles import organization_roles from sentry.snuba import discover -from sentry.tasks.symbolication import should_demote_symbolication STATUS_LABELS = { ObjectStatus.ACTIVE: ""active"", @@ -694,10 +692,9 @@ def get_attrs( if not self._collapse(LATEST_DEPLOYS_KEY): attrs[item][""deploys""] = deploys_by_project.get(item.id) # check if the project is in LPQ for any platform - attrs[item][""symbolication_degraded""] = any( - should_demote_symbolication(platform, project_id=item.id) - for platform in SymbolicatorPlatform - ) + # XXX(joshferge): determine if the frontend needs this flag at all + # removing redis call as was causing problematic latency issues + attrs[item][""symbolication_degraded""] = False return attrs" b57329cf400e7d44b390044a02c6983770e15c91,2025-01-03 02:16:49,Michelle Zhang,ref(flags): don't show flag legend if no lines to show (#82826),False,don't show flag legend if no lines to show (#82826),ref,"diff --git a/static/app/views/issueDetails/streamline/hooks/useFlagSeries.tsx b/static/app/views/issueDetails/streamline/hooks/useFlagSeries.tsx index 095c6661cc3a51..13fca675343fb1 100644 --- a/static/app/views/issueDetails/streamline/hooks/useFlagSeries.tsx +++ b/static/app/views/issueDetails/streamline/hooks/useFlagSeries.tsx @@ -39,6 +39,14 @@ export default function useFlagSeries({query = {}, event}: FlagSeriesProps) { evaluatedFlagNames?.includes(f.name) ); + if (!intersectionFlags.length) { + return { + seriesName: t('Feature Flags'), + markLine: {}, + data: [], + }; + } + // create a markline series using hydrated flag data const markLine = MarkLine({ animation: false," cf9d4a890055cd08402ec6fdc5f337b3971c13fc,2024-06-13 19:12:40,anthony sottile,ref: fix typing of sentry.models.groupsubscription (#72591),False,fix typing of sentry.models.groupsubscription (#72591),ref,"diff --git a/pyproject.toml b/pyproject.toml index 00fee83a679699..1154df28067415 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -565,6 +565,7 @@ module = [ ""sentry.mediators.sentry_app_installations.installation_notifier"", ""sentry.migrations.*"", ""sentry.models.eventattachment"", + ""sentry.models.groupsubscription"", ""sentry.nodestore.base"", ""sentry.nodestore.bigtable.backend"", ""sentry.nodestore.django.backend"", diff --git a/src/sentry/models/groupsubscription.py b/src/sentry/models/groupsubscription.py index 1de9d6e841c70f..5b8743b8424faa 100644 --- a/src/sentry/models/groupsubscription.py +++ b/src/sentry/models/groupsubscription.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Iterable, Mapping, Sequence +from collections.abc import Iterable from typing import TYPE_CHECKING, ClassVar from django.conf import settings @@ -201,9 +201,9 @@ def get_participants(self, group: Group) -> ParticipantMap: if user.id not in providers_by_recipient: continue - subscription_option = subscriptions_by_user_id.get(user.id, {}) + subscription_option = subscriptions_by_user_id.get(user.id) if not subscription_option and has_team_workflow: - subscription_option = subscriptions_by_team_id.get(user.id, {}) + subscription_option = subscriptions_by_team_id.get(user.id) for provider_str, val in providers_by_recipient[user.id].items(): value = NotificationSettingsOptionEnum(val) @@ -237,7 +237,7 @@ def get_possible_team_actors(self, group: Group) -> list[Actor]: def get_subscriptions_by_team_id( self, group: Group, possible_team_actors: list[Actor] - ) -> Mapping[int, int]: + ) -> dict[int, GroupSubscription]: active_and_disabled_team_subscriptions = self.filter( group=group, team_id__in=[t.id for t in possible_team_actors] ) @@ -247,24 +247,28 @@ def get_subscriptions_by_team_id( } @staticmethod - def get_participating_user_ids(group: Group) -> Sequence[int]: + def get_participating_user_ids(group: Group) -> list[int]: """"""Return the list of user ids participating in this issue."""""" - return list( - GroupSubscription.objects.filter(group=group, is_active=True, team=None).values_list( - ""user_id"", flat=True - ) - ) + return [ + user_id + for user_id in GroupSubscription.objects.filter( + group=group, is_active=True, team=None + ).values_list(""user_id"", flat=True) + if user_id is not None + ] @staticmethod - def get_participating_team_ids(group: Group) -> Sequence[int]: + def get_participating_team_ids(group: Group) -> list[int]: """"""Return the list of team ids participating in this issue."""""" - return list( - GroupSubscription.objects.filter(group=group, is_active=True, user_id=None).values_list( - ""team_id"", flat=True - ) - ) + return [ + team_id + for team_id in GroupSubscription.objects.filter( + group=group, is_active=True, user_id=None + ).values_list(""team_id"", flat=True) + if team_id is not None + ] @region_silo_model" d7cc9b622b699240cc31a838909bb2a5c233732b,2021-11-11 02:31:20,Dan Fuller,feat(issue_search): Add `regressed_in_release` search term to issue search (#29890),False,Add `regressed_in_release` search term to issue search (#29890),feat,"diff --git a/src/sentry/api/issue_search.py b/src/sentry/api/issue_search.py index 04e00b41136a52..de06e996f93ffd 100644 --- a/src/sentry/api/issue_search.py +++ b/src/sentry/api/issue_search.py @@ -101,6 +101,7 @@ def convert_status_value(value, projects, user, environments): ""first_release"": convert_first_release_value, ""release"": convert_release_value, ""status"": convert_status_value, + ""regressed_in_release"": convert_first_release_value, } diff --git a/src/sentry/search/snuba/backend.py b/src/sentry/search/snuba/backend.py index a18a450ff1f2ff..c8575889d8e9ff 100644 --- a/src/sentry/search/snuba/backend.py +++ b/src/sentry/search/snuba/backend.py @@ -2,6 +2,7 @@ from abc import ABCMeta, abstractmethod from collections import defaultdict from datetime import timedelta +from typing import Sequence from django.db.models import Q from django.utils import timezone @@ -13,6 +14,8 @@ Group, GroupAssignee, GroupEnvironment, + GroupHistory, + GroupHistoryStatus, GroupLink, GroupOwner, GroupStatus, @@ -20,6 +23,7 @@ OrganizationMember, OrganizationMemberTeam, PlatformExternalIssue, + Project, Release, Team, User, @@ -246,6 +250,19 @@ def assigned_or_suggested_filter(owners, projects, field_filter=""id""): return query +def regressed_in_release_filter(versions: Sequence[str], projects: Sequence[Project]) -> Q: + release_ids = Release.objects.filter( + organization_id=projects[0].organization_id, version__in=versions + ).values_list(""id"", flat=True) + return Q( + id__in=GroupHistory.objects.filter( + release_id__in=release_ids, + status=GroupHistoryStatus.REGRESSED, + project__in=projects, + ).values_list(""group_id"", flat=True), + ) + + class Condition: """"""\ Adds a single filter to a ``QuerySet`` object. Used with @@ -466,6 +483,9 @@ def _get_queryset_conditions(self, projects, environments, search_filters): ""assigned_or_suggested"": QCallbackCondition( functools.partial(assigned_or_suggested_filter, projects=projects) ), + ""regressed_in_release"": QCallbackCondition( + functools.partial(regressed_in_release_filter, projects=projects) + ), } if environments is not None: diff --git a/src/sentry/search/snuba/executors.py b/src/sentry/search/snuba/executors.py index 03d232323df051..17945370e9e880 100644 --- a/src/sentry/search/snuba/executors.py +++ b/src/sentry/search/snuba/executors.py @@ -271,6 +271,7 @@ class PostgresSnubaQueryExecutor(AbstractQueryExecutor): ""subscribed_by"", ""first_release"", ""first_seen"", + ""regressed_in_release"", } sort_strategies = { ""date"": ""last_seen"", @@ -431,6 +432,7 @@ def query( max_time = options.get(""snuba.search.max-total-chunk-time-seconds"") time_start = time.time() + more_results = False # Do smaller searches in chunks until we have enough results # to answer the query (or hit the end of possible results). We do diff --git a/tests/snuba/api/endpoints/test_organization_group_index.py b/tests/snuba/api/endpoints/test_organization_group_index.py index 44b5ad4d774b9c..bcdd78e6fd8c10 100644 --- a/tests/snuba/api/endpoints/test_organization_group_index.py +++ b/tests/snuba/api/endpoints/test_organization_group_index.py @@ -37,7 +37,7 @@ add_group_to_inbox, remove_group_from_inbox, ) -from sentry.models.grouphistory import GroupHistoryStatus +from sentry.models.grouphistory import GroupHistoryStatus, record_group_history from sentry.search.events.constants import ( RELEASE_STAGE_ALIAS, SEMVER_ALIAS, @@ -628,6 +628,22 @@ def test_lookup_by_release_wildcard(self): assert len(issues) == 1 assert int(issues[0][""id""]) == event.group.id + def test_lookup_by_regressed_in_release(self): + self.login_as(self.user) + project = self.project + release = self.create_release() + event = self.store_event( + data={ + ""timestamp"": iso_format(before_now(seconds=1)), + ""tags"": {""sentry:release"": release.version}, + }, + project_id=project.id, + ) + record_group_history(event.group, GroupHistoryStatus.REGRESSED, release=release) + response = self.get_valid_response(query=f""regressed_in_release:{release.version}"") + issues = json.loads(response.content) + assert [int(issue[""id""]) for issue in issues] == [event.group.id] + def test_pending_delete_pending_merge_excluded(self): events = [] for i in ""abcd"": diff --git a/tests/snuba/search/test_backend.py b/tests/snuba/search/test_backend.py index e969591c224dd2..576101c93b9faf 100644 --- a/tests/snuba/search/test_backend.py +++ b/tests/snuba/search/test_backend.py @@ -16,9 +16,11 @@ GroupAssignee, GroupBookmark, GroupEnvironment, + GroupHistoryStatus, GroupStatus, GroupSubscription, Integration, + record_group_history, ) from sentry.models.groupowner import GroupOwner from sentry.search.snuba.backend import ( @@ -1393,6 +1395,50 @@ def test_hits_estimate(self): assert third_results.hits > 10 assert third_results.results != second_results.results + def test_regressed_in_release(self): + # expect no groups within the results since there are no releases + results = self.make_query(search_filter_query=""regressed_in_release:fake"") + assert set(results) == set() + + # expect no groups even though there is a release; since no group regressed in this release + release_1 = self.create_release() + + results = self.make_query(search_filter_query=""regressed_in_release:%s"" % release_1.version) + assert set(results) == set() + + # Create a new event so that we get a group in this release + group = self.store_event( + data={ + ""release"": release_1.version, + }, + project_id=self.project.id, + ).group + + # # Should still be no group since we didn't regress in this release + results = self.make_query(search_filter_query=""regressed_in_release:%s"" % release_1.version) + assert set(results) == set() + + record_group_history(group, GroupHistoryStatus.REGRESSED, release=release_1) + results = self.make_query(search_filter_query=""regressed_in_release:%s"" % release_1.version) + assert set(results) == {group} + + # Make sure this works correctly with multiple releases + release_2 = self.create_release() + group_2 = self.store_event( + data={ + ""fingerprint"": [""put-me-in-group9001""], + ""event_id"": ""a"" * 32, + ""release"": release_2.version, + }, + project_id=self.project.id, + ).group + record_group_history(group_2, GroupHistoryStatus.REGRESSED, release=release_2) + + results = self.make_query(search_filter_query=""regressed_in_release:%s"" % release_1.version) + assert set(results) == {group} + results = self.make_query(search_filter_query=""regressed_in_release:%s"" % release_2.version) + assert set(results) == {group_2} + def test_first_release(self): # expect no groups within the results since there are no releases" 3f7ca6a5a7bd904ed66f5ed074182a89fe55bd8b,2025-02-19 19:06:21,anthony sottile,ref: create release deploy directly in heroku plugin (#85374),False,create release deploy directly in heroku plugin (#85374),ref,"diff --git a/src/sentry/api/endpoints/release_deploys.py b/src/sentry/api/endpoints/release_deploys.py index fc24cb06e0c5d0..387e136a17a41f 100644 --- a/src/sentry/api/endpoints/release_deploys.py +++ b/src/sentry/api/endpoints/release_deploys.py @@ -15,6 +15,7 @@ from sentry.api.serializers.rest_framework.project import ProjectField from sentry.models.deploy import Deploy from sentry.models.environment import Environment +from sentry.models.organization import Organization from sentry.models.release import Release from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment from sentry.signals import deploy_created @@ -38,6 +39,56 @@ def validate_environment(self, value): return value +def create_deploy( + organization: Organization, release: Release, serializer: DeploySerializer +) -> Deploy: + result = serializer.validated_data + release_projects = list(release.projects.all()) + projects = result.get(""projects"", release_projects) + invalid_projects = {project.slug for project in projects} - { + project.slug for project in release_projects + } + if len(invalid_projects) > 0: + raise ParameterValidationError( + f""Invalid projects ({', '.join(invalid_projects)}) for release {release.version}"" + ) + + env = Environment.objects.get_or_create( + name=result[""environment""], organization_id=organization.id + )[0] + for project in projects: + env.add_project(project) + + deploy = Deploy.objects.create( + organization_id=organization.id, + release=release, + environment_id=env.id, + date_finished=result.get(""dateFinished"", timezone.now()), + date_started=result.get(""dateStarted""), + name=result.get(""name""), + url=result.get(""url""), + ) + deploy_created.send_robust(deploy=deploy, sender=create_deploy) + + # XXX(dcramer): this has a race for most recent deploy, but + # should be unlikely to hit in the real world + Release.objects.filter(id=release.id).update( + total_deploys=F(""total_deploys"") + 1, last_deploy_id=deploy.id + ) + + for project in projects: + ReleaseProjectEnvironment.objects.create_or_update( + release=release, + environment=env, + project=project, + values={""last_deploy_id"": deploy.id}, + ) + + Deploy.notify_if_ready(deploy.id) + + return deploy + + @region_silo_endpoint class ReleaseDeploysEndpoint(OrganizationReleasesBaseEndpoint): publish_status = { @@ -143,49 +194,7 @@ def post(self, request: Request, organization, version) -> Response: ) if serializer.is_valid(): - result = serializer.validated_data - release_projects = list(release.projects.all()) - projects = result.get(""projects"", release_projects) - invalid_projects = {project.slug for project in projects} - { - project.slug for project in release_projects - } - if len(invalid_projects) > 0: - raise ParameterValidationError( - f""Invalid projects ({', '.join(invalid_projects)}) for release {release.version}"" - ) - - env = Environment.objects.get_or_create( - name=result[""environment""], organization_id=organization.id - )[0] - for project in projects: - env.add_project(project) - - deploy = Deploy.objects.create( - organization_id=organization.id, - release=release, - environment_id=env.id, - date_finished=result.get(""dateFinished"", timezone.now()), - date_started=result.get(""dateStarted""), - name=result.get(""name""), - url=result.get(""url""), - ) - deploy_created.send_robust(deploy=deploy, sender=self.__class__) - - # XXX(dcramer): this has a race for most recent deploy, but - # should be unlikely to hit in the real world - Release.objects.filter(id=release.id).update( - total_deploys=F(""total_deploys"") + 1, last_deploy_id=deploy.id - ) - - for project in projects: - ReleaseProjectEnvironment.objects.create_or_update( - release=release, - environment=env, - project=project, - values={""last_deploy_id"": deploy.id}, - ) - - Deploy.notify_if_ready(deploy.id) + deploy = create_deploy(organization, release, serializer) return Response(serialize(deploy, request.user), status=201) diff --git a/src/sentry/shared_integrations/client/__init__.py b/src/sentry/shared_integrations/client/__init__.py index 8450aec3428a94..1083f97dfaa2fa 100644 --- a/src/sentry/shared_integrations/client/__init__.py +++ b/src/sentry/shared_integrations/client/__init__.py @@ -1,9 +1,4 @@ -__all__ = ( - ""BaseApiClient"", - ""BaseInternalApiClient"", - ""BaseApiResponse"", -) - from ..response import BaseApiResponse from .base import BaseApiClient -from .internal import BaseInternalApiClient + +__all__ = (""BaseApiClient"", ""BaseApiResponse"") diff --git a/src/sentry/shared_integrations/client/internal.py b/src/sentry/shared_integrations/client/internal.py deleted file mode 100644 index 37899d29655204..00000000000000 --- a/src/sentry/shared_integrations/client/internal.py +++ /dev/null @@ -1,28 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from requests.models import Response - -from sentry.api.client import ApiClient -from sentry.shared_integrations.track_response import TrackResponseMixin -from sentry.utils import metrics - - -class BaseInternalApiClient(ApiClient, TrackResponseMixin): - integration_type: str | None = None - - log_path: str | None = None - - metrics_prefix: str | None = None - - def request(self, *args: Any, **kwargs: Any) -> Response: - metrics.incr( - f""{self.metrics_prefix}.http_request"", - sample_rate=1.0, - tags={str(self.integration_type): self.name}, - ) - - resp: Response = ApiClient.request(self, *args, **kwargs) - self.track_response_data(resp.status_code, None, resp) - return resp diff --git a/src/sentry_plugins/client.py b/src/sentry_plugins/client.py index f293bd60799c83..a0044e07a6d758 100644 --- a/src/sentry_plugins/client.py +++ b/src/sentry_plugins/client.py @@ -6,7 +6,6 @@ from requests import PreparedRequest, Response from sentry.shared_integrations.client.base import BaseApiClient -from sentry.shared_integrations.client.internal import BaseInternalApiClient from sentry.shared_integrations.exceptions import ApiUnauthorized from sentry.users.services.usersocialauth.service import usersocialauth_service @@ -103,13 +102,3 @@ def _request(self, method, path, **kwargs): usersocialauth_service.refresh_token(filter={""id"": self.auth.id}) kwargs = self.bind_auth(**kwargs) return ApiClient._request(self, method, path, **kwargs) - - -class InternalApiClient(BaseInternalApiClient): - integration_type = ""plugin"" - - metrics_prefix = ""sentry-plugins"" - - log_path = ""sentry.plugins.client"" - - plugin_name = ""undefined"" diff --git a/src/sentry_plugins/heroku/client.py b/src/sentry_plugins/heroku/client.py deleted file mode 100644 index 9b4546b504d04d..00000000000000 --- a/src/sentry_plugins/heroku/client.py +++ /dev/null @@ -1,8 +0,0 @@ -from sentry_plugins.client import InternalApiClient - - -class HerokuApiClient(InternalApiClient): - plugin_name = ""heroku"" - - def __init__(self): - super().__init__() diff --git a/src/sentry_plugins/heroku/plugin.py b/src/sentry_plugins/heroku/plugin.py index f853c6eeff108e..654af7e1f71b06 100644 --- a/src/sentry_plugins/heroku/plugin.py +++ b/src/sentry_plugins/heroku/plugin.py @@ -7,6 +7,7 @@ from django.http import HttpRequest, HttpResponse +from sentry.api.endpoints.release_deploys import DeploySerializer, create_deploy from sentry.auth.services.auth.model import AuthenticatedToken from sentry.integrations.base import FeatureDescription, IntegrationFeatures from sentry.models.apikey import ApiKey @@ -19,8 +20,6 @@ from sentry_plugins.base import CorePluginMixin from sentry_plugins.utils import get_secret_field_config -from .client import HerokuApiClient - logger = logging.getLogger(""sentry.plugins.heroku"") @@ -33,9 +32,6 @@ def get_auth(self) -> AuthenticatedToken | None: except ApiKey.DoesNotExist: return None - def get_client(self): - return HerokuApiClient() - def is_valid_signature(self, body, heroku_hmac): secret = ProjectOption.objects.get_value(project=self.project, key=""heroku:webhook_secret"") if secret is None: @@ -129,11 +125,12 @@ def set_refs(self, release, **values): fetch=True, ) # create deploy associated with release via ReleaseDeploysEndpoint - endpoint = ( - f""/organizations/{self.project.organization.slug}/releases/{release.version}/deploys/"" + serializer = DeploySerializer( + data={""environment"": deploy_project_option}, + context={""organization"": self.project.organization}, ) - client = self.get_client() - client.post(endpoint, data={""environment"": deploy_project_option}, auth=self.get_auth()) + assert serializer.is_valid() + create_deploy(self.project.organization, release, serializer) class HerokuPlugin(CorePluginMixin, ReleaseTrackingPlugin):" 4eee8e1537b7d90a82d73b287218fa7b3caeeb0b,2022-11-22 21:22:44,David Wang,feat(monitors): Add label to status in header (#41542),False,Add label to status in header (#41542),feat,"diff --git a/static/app/views/monitors/monitorHeader.tsx b/static/app/views/monitors/monitorHeader.tsx index c9ae46642da539..b7830426b5cabb 100644 --- a/static/app/views/monitors/monitorHeader.tsx +++ b/static/app/views/monitors/monitorHeader.tsx @@ -10,9 +10,18 @@ import space from 'sentry/styles/space'; import MonitorHeaderActions from './monitorHeaderActions'; import MonitorIcon from './monitorIcon'; +import {Status} from './types'; type Props = React.ComponentProps; +const statusToLabel: Record = { + ok: t('Ok'), + error: t('Failed'), + disabled: t('Disabled'), + active: t('Active'), + missed_checkin: t('Missed'), +}; + const MonitorHeader = ({monitor, orgId, onUpdate}: Props) => { const crumbs = [ { @@ -49,7 +58,10 @@ const MonitorHeader = ({monitor, orgId, onUpdate}: Props) => { {t('Status')}
{monitor.lastCheckIn && }
{monitor.nextCheckIn && }
- + + + {statusToLabel[monitor.status]} + @@ -80,6 +92,16 @@ const MonitorStats = styled('div')` const MonitorStatLabel = styled(SectionHeading)` text-transform: uppercase; font-size: ${p => p.theme.fontSizeSmall}; + text-align: center; +`; + +const MonitorStatus = styled('div')` + display: flex; + align-items: center; +`; + +const MonitorStatusLabel = styled('div')` + margin-left: ${space(1)}; `; export default MonitorHeader;" 0f01b902ad075743ecafb7f08d64bfe10a4ee093,2023-02-01 00:54:29,Nar Saynorath,feat(view-hierarchy): Render wireframe (#43864),False,Render wireframe (#43864),feat,"diff --git a/static/app/components/events/viewHierarchy/detailsPanel.tsx b/static/app/components/events/viewHierarchy/detailsPanel.tsx index 181f82ea8a04ec..9a7095c83d8dc0 100644 --- a/static/app/components/events/viewHierarchy/detailsPanel.tsx +++ b/static/app/components/events/viewHierarchy/detailsPanel.tsx @@ -36,11 +36,6 @@ const Title = styled('header')` `; const Container = styled('div')` - margin-top: ${space(1)}; - border: 1px solid ${p => p.theme.gray100}; - border-radius: ${p => p.theme.borderRadius}; padding: ${space(1.5)}; padding-bottom: 0; - max-height: 400px; - overflow: auto; `; diff --git a/static/app/components/events/viewHierarchy/index.tsx b/static/app/components/events/viewHierarchy/index.tsx index bc8a10145f7127..05eee45e05a082 100644 --- a/static/app/components/events/viewHierarchy/index.tsx +++ b/static/app/components/events/viewHierarchy/index.tsx @@ -2,6 +2,7 @@ import {Fragment, useMemo, useState} from 'react'; import styled from '@emotion/styled'; import {Node} from 'sentry/components/events/viewHierarchy/node'; +import {Wireframe} from 'sentry/components/events/viewHierarchy/wireframe'; import space from 'sentry/styles/space'; import {defined} from 'sentry/utils'; import { @@ -110,34 +111,71 @@ function ViewHierarchy({viewHierarchy}: ViewHierarchyProps) { return ( - - - - - - {renderedItems} - - - - {defined(selectedNode) && ( - - )} + + + + + + + + {renderedItems} + + + + {defined(selectedNode) && ( + + + + )} + + + + + ); } export {ViewHierarchy}; +const Content = styled('div')` + display: flex; + flex-direction: row; + gap: ${space(1)}; + max-height: 700px; +`; + +const Left = styled('div')` + width: 40%; + display: flex; + gap: ${space(1)}; + flex-direction: column; + resize: both; +`; + +const Right = styled('div')` + width: 60%; + border: 1px solid ${p => p.theme.gray100}; + border-radius: ${p => p.theme.borderRadius}; + overflow: hidden; +`; + const TreeContainer = styled('div')` position: relative; - height: 400px; + height: 70%; overflow: hidden; - overflow-y: auto; background-color: ${p => p.theme.background}; border: 1px solid ${p => p.theme.gray100}; border-radius: ${p => p.theme.borderRadius}; `; +const DetailsContainer = styled('div')` + max-height: 30%; + border: 1px solid ${p => p.theme.gray100}; + border-radius: ${p => p.theme.borderRadius}; + overflow: auto; +`; + const ScrollContainer = styled('div')` padding: ${space(1.5)}; `; diff --git a/static/app/components/events/viewHierarchy/useMousePan.tsx b/static/app/components/events/viewHierarchy/useMousePan.tsx new file mode 100644 index 00000000000000..d7f0c03c0e613c --- /dev/null +++ b/static/app/components/events/viewHierarchy/useMousePan.tsx @@ -0,0 +1,62 @@ +import {MouseEventHandler, useState} from 'react'; + +import {defined} from 'sentry/utils'; + +type UseMousePanProps = { + initialXOffset: number; + initialYOffset: number; +}; + +export function useMousePan({initialXOffset, initialYOffset}: UseMousePanProps) { + const [dragStartCoords, setDragStartCoords] = useState<{x: number; y: number} | null>( + null + ); + const [xOffset, setXOffset] = useState(initialXOffset); + const [yOffset, setYOffset] = useState(initialYOffset); + + const handlePanStart: MouseEventHandler = e => { + e.preventDefault(); + e.stopPropagation(); + + setDragStartCoords({ + x: e.clientX - xOffset, + y: e.clientY - yOffset, + }); + }; + + const handlePanStop: MouseEventHandler = e => { + e.preventDefault(); + e.stopPropagation(); + + setDragStartCoords(null); + }; + + const handlePanMove: MouseEventHandler = e => { + if (!defined(dragStartCoords)) { + return; + } + + const {x, y} = dragStartCoords; + + e.preventDefault(); + e.stopPropagation(); + + const mouseX = e.clientX - xOffset; + const mouseY = e.clientY - yOffset; + + const dx = mouseX - x; + const dy = mouseY - y; + + setXOffset(xOffset + dx); + setYOffset(yOffset + dy); + }; + + return { + handlePanStart, + handlePanStop, + handlePanMove, + isDragging: defined(dragStartCoords), + xOffset, + yOffset, + }; +} diff --git a/static/app/components/events/viewHierarchy/wireframe.spec.tsx b/static/app/components/events/viewHierarchy/wireframe.spec.tsx new file mode 100644 index 00000000000000..3f43345a886839 --- /dev/null +++ b/static/app/components/events/viewHierarchy/wireframe.spec.tsx @@ -0,0 +1,44 @@ +import {ViewHierarchyWindow} from 'sentry/components/events/viewHierarchy'; +import {getCoordinates} from 'sentry/components/events/viewHierarchy/wireframe'; + +const MOCK_HIERARCHY = [ + { + x: 0, + y: 0, + width: 10, + height: 10, + children: [ + { + x: 10, + y: 5, + width: 10, + height: 10, + children: [ + { + x: 2, + y: 2, + width: 5, + height: 5, + }, + ], + }, + ], + }, + {x: 10, y: 0, width: 20, height: 20}, +] as ViewHierarchyWindow[]; + +describe('View Hierarchy Wireframe', function () { + it('properly calculates coordinates', function () { + const actual = getCoordinates(MOCK_HIERARCHY); + + // One array for each root + expect(actual).toEqual([ + [ + {x: 0, y: 0, width: 10, height: 10}, + {x: 10, y: 5, width: 10, height: 10}, + {x: 12, y: 7, width: 5, height: 5}, + ], + [{x: 10, y: 0, width: 20, height: 20}], + ]); + }); +}); diff --git a/static/app/components/events/viewHierarchy/wireframe.tsx b/static/app/components/events/viewHierarchy/wireframe.tsx new file mode 100644 index 00000000000000..38bd02749843ac --- /dev/null +++ b/static/app/components/events/viewHierarchy/wireframe.tsx @@ -0,0 +1,145 @@ +import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import styled from '@emotion/styled'; +import {useResizeObserver} from '@react-aria/utils'; + +import {ViewHierarchyWindow} from 'sentry/components/events/viewHierarchy'; +import {useMousePan} from 'sentry/components/events/viewHierarchy/useMousePan'; + +const RECT_FILL_ALPHA = 0.005; +const RECT_OUTLINE_ALPHA = 1; + +type Rect = Pick; + +export function getCoordinates(hierarchies: ViewHierarchyWindow[]) { + return hierarchies.map(hierarchy => { + const newHierarchy: Rect[] = []; + + const nodesToProcess = [hierarchy]; + while (nodesToProcess.length) { + const node = nodesToProcess.pop()!; + + // Fetch coordinates off the current node + newHierarchy.push({ + x: node.x ?? 0, + y: node.y ?? 0, + width: node.width ?? 0, + height: node.height ?? 0, + }); + + if ((node.children ?? []).length !== 0) { + // Update the children's coords relative to the parent + const newChildren = + node.children?.map(child => ({ + ...child, + x: (child.x ?? 0) + (node.x ?? 0), + y: (child.y ?? 0) + (node.y ?? 0), + })) ?? []; + + nodesToProcess.push(...newChildren); + } + } + + return newHierarchy; + }); +} + +function Wireframe({hierarchy}) { + const containerRef = useRef(null); + const canvasRef = useRef(null); + const coordinates = useMemo(() => getCoordinates(hierarchy), [hierarchy]); + + const [dimensions, setDimensions] = useState({width: 0, height: 0}); + + const {handlePanMove, handlePanStart, handlePanStop, isDragging, xOffset, yOffset} = + useMousePan({initialXOffset: 20, initialYOffset: 20}); + + const draw = useCallback( + (context: CanvasRenderingContext2D) => { + // Make areas with more overlayed elements darker + context.globalCompositeOperation = 'overlay'; + + coordinates.forEach(hierarchyCoords => { + hierarchyCoords.forEach(({x, y, width, height}) => { + // Prepare rectangles for drawing + context.fillStyle = 'rgb(88, 74, 192)'; + context.strokeStyle = 'black'; + context.lineWidth = 1; + context.rect(x + xOffset, y + yOffset, width, height); + + // Draw the rectangles + context.globalAlpha = RECT_FILL_ALPHA; + context.fill(); + + // Draw the outlines + context.globalAlpha = RECT_OUTLINE_ALPHA; + context.stroke(); + }); + }); + }, + [coordinates, xOffset, yOffset] + ); + + useEffect(() => { + const container = containerRef.current; + const canvas = canvasRef.current; + if (!canvas || !container) { + return; + } + + canvas.width = dimensions.width || container.clientWidth; + canvas.height = dimensions.height || container.clientHeight; + + const context = canvas.getContext('2d'); + if (context) { + draw(context); + } + }, [dimensions.height, dimensions.width, draw]); + + useResizeObserver({ + ref: containerRef, + onResize: () => { + if (!containerRef.current) { + return; + } + + const {clientWidth, clientHeight} = containerRef.current; + const needsResize = + dimensions.width !== clientWidth || dimensions.height !== clientHeight; + + if (needsResize) { + setDimensions({ + width: clientWidth ?? 0, + height: clientHeight ?? 0, + }); + } + }, + }); + + return ( + + + + ); +} + +export {Wireframe}; + +// This container wraps the canvas so we can stretch it to fit +// the space we want and then read the width and height +// to resize the canvas +const Container = styled('div')` + height: 100%; + width: 100%; +`; + +const StyledCanvas = styled('canvas')<{isDragging: boolean}>` + background-color: ${p => p.theme.surface100}; + cursor: ${p => (p.isDragging ? 'grabbing' : 'grab')}; +`;" df68174849305992310a845885197e72ab968b1f,2023-08-15 22:38:23,Chloe,fix(sentryapp): sentryapp disabled email new subject line (#54734),False,sentryapp disabled email new subject line (#54734),fix,"diff --git a/src/sentry/integrations/notify_disable.py b/src/sentry/integrations/notify_disable.py index 81d7dc80d89ff8..209420999f6b8e 100644 --- a/src/sentry/integrations/notify_disable.py +++ b/src/sentry/integrations/notify_disable.py @@ -36,6 +36,10 @@ def get_subject(integration_name: str) -> str: return f""Action required: re-authenticate or fix your {integration_name} integration"" +def get_sentry_app_subject(integration_name: str) -> str: + return f""Action required: Fix your {integration_name} integration"" + + def notify_disable( organization: Organization, integration_name: str, @@ -52,15 +56,17 @@ def notify_disable( ) referrer = ( - ""?referrer=disabled-sentry-app/"" + ""?referrer=disabled-sentry-app"" if ""sentry-app"" in redis_key - else ""?referrer=disabled-integration/"" + else ""?referrer=disabled-integration"" ) for user in organization.get_owners(): msg = MessageBuilder( - subject=get_subject(integration_name.title()), + subject=get_sentry_app_subject(integration_name.title()) + if ""sentry-app"" in redis_key + else get_subject(integration_name.title()), context={ ""integration_name"": integration_name.title(), ""integration_link"": f""{integration_link}{referrer}"", diff --git a/src/sentry/templates/sentry/integrations/sentry-app-notify-disable.html b/src/sentry/templates/sentry/integrations/sentry-app-notify-disable.html index e8da26449321df..a6c44a12e7c412 100644 --- a/src/sentry/templates/sentry/integrations/sentry-app-notify-disable.html +++ b/src/sentry/templates/sentry/integrations/sentry-app-notify-disable.html @@ -8,7 +8,7 @@

We’ve received multiple request errors from your webhook: {{webhook_url}} for the custom {{ integration_name }} integration, and have unsubscribed the webhook from receiving events.

- To continue using your custom integration, please fix your webhook: {{webhook_url}} and re-enable the webhook subscriptions here. + To continue using your custom integration, please fix your webhook and re-enable the webhook subscriptions here.

diff --git a/tests/sentry/integrations/slack/test_disable.py b/tests/sentry/integrations/slack/test_disable.py index 814ac0661737e3..7b4ea6524b09c5 100644 --- a/tests/sentry/integrations/slack/test_disable.py +++ b/tests/sentry/integrations/slack/test_disable.py @@ -89,7 +89,7 @@ def test_email(self): ) assert ( self.organization.absolute_url( - f""/settings/{self.organization.slug}/integrations/{self.integration.provider}/?referrer=disabled-integration/"" + f""/settings/{self.organization.slug}/integrations/{self.integration.provider}/?referrer=disabled-integration"" ) in msg.body ) diff --git a/tests/sentry/tasks/test_sentry_apps.py b/tests/sentry/tasks/test_sentry_apps.py index 82676fe5acf5bc..0863aef32b22a2 100644 --- a/tests/sentry/tasks/test_sentry_apps.py +++ b/tests/sentry/tasks/test_sentry_apps.py @@ -912,10 +912,7 @@ def test_notify_disabled_email(self): ) assert len(mail.outbox) == 1 msg = mail.outbox[0] - assert ( - msg.subject - == f""Action required: re-authenticate or fix your {self.sentry_app.name} integration"" - ) + assert msg.subject == f""Action required: Fix your {self.sentry_app.name} integration"" assert ( self.organization.absolute_url( f""/settings/{self.organization.slug}/developer-settings/{self.sentry_app.slug}""" 361836737b7413dbac89b1cbcfae4493ee56d4b5,2024-07-25 03:29:41,anthony sottile,ref: copy signature of _request to plugin api client (#74899),False,copy signature of _request to plugin api client (#74899),ref,"diff --git a/src/sentry_plugins/client.py b/src/sentry_plugins/client.py index 8b2feea7202fe4..ddd4908de346b1 100644 --- a/src/sentry_plugins/client.py +++ b/src/sentry_plugins/client.py @@ -1,4 +1,12 @@ -from sentry.shared_integrations.client import BaseApiClient, BaseInternalApiClient +from __future__ import annotations + +from collections.abc import Mapping +from typing import Literal, overload + +from requests import PreparedRequest, Response + +from sentry.shared_integrations.client.base import BaseApiClient, BaseApiResponseX +from sentry.shared_integrations.client.internal import BaseInternalApiClient from sentry.shared_integrations.exceptions import ApiUnauthorized from sentry.users.services.usersocialauth.service import usersocialauth_service @@ -36,6 +44,44 @@ def bind_auth(self, **kwargs): kwargs[""headers""][""Authorization""] = f""Bearer {token}"" return kwargs + @overload + def _request( + self, + method: str, + path: str, + headers: Mapping[str, str] | None = None, + data: Mapping[str, str] | None = None, + params: Mapping[str, str] | None = None, + auth: tuple[str, str] | str | None = None, + json: bool = True, + allow_text: bool | None = None, + allow_redirects: bool | None = None, + timeout: int | None = None, + ignore_webhook_errors: bool = False, + prepared_request: PreparedRequest | None = None, + raw_response: Literal[True] = ..., + ) -> Response: + ... + + @overload + def _request( + self, + method: str, + path: str, + headers: Mapping[str, str] | None = None, + data: Mapping[str, str] | None = None, + params: Mapping[str, str] | None = None, + auth: str | None = None, + json: bool = True, + allow_text: bool | None = None, + allow_redirects: bool | None = None, + timeout: int | None = None, + ignore_webhook_errors: bool = False, + prepared_request: PreparedRequest | None = None, + raw_response: bool = ..., + ) -> BaseApiResponseX: + ... + def _request(self, method, path, **kwargs): headers = kwargs.setdefault(""headers"", {}) headers.setdefault(""Accept"", ""application/json, application/xml"")" 39a914d5ead67c7747aea0e1ab148c9f3de12160,2020-08-19 03:08:08,Tony,feat(discover): Add y axis to discover queries (#20270),False,Add y axis to discover queries (#20270),feat,"diff --git a/src/sentry/static/sentry/app/views/eventsV2/miniGraph.tsx b/src/sentry/static/sentry/app/views/eventsV2/miniGraph.tsx index 0193d67888d97f..4e4a6e1dbe77ea 100644 --- a/src/sentry/static/sentry/app/views/eventsV2/miniGraph.tsx +++ b/src/sentry/static/sentry/app/views/eventsV2/miniGraph.tsx @@ -13,6 +13,7 @@ import {getUtcToLocalDateObject} from 'app/utils/dates'; import LoadingIndicator from 'app/components/loadingIndicator'; import LoadingContainer from 'app/components/loading/loadingContainer'; import {IconWarning} from 'app/icons'; +import {formatAbbreviatedNumber} from 'app/utils/formatters'; import theme from 'app/utils/theme'; import EventView from 'app/utils/discover/eventView'; @@ -124,7 +125,24 @@ class MiniGraph extends React.Component { }, }} yAxis={{ - show: false, + show: true, + axisLine: { + show: false, + }, + axisLabel: { + color: theme.gray400, + fontFamily: theme.text.family, + fontSize: 12, + formatter: formatAbbreviatedNumber, + inside: true, + showMinLabel: false, + showMaxLabel: false, + }, + splitNumber: 3, + splitLine: { + show: false, + }, + zlevel: theme.zIndex.header, }} tooltip={{ show: false," bf5ce8c7f9d98c7683e8fb08b5d1c29761fe59ea,2022-08-16 03:13:20,Jesus Padron,fix: remove from url (#37808),False,remove from url (#37808),fix,"diff --git a/static/app/components/replays/breadcrumbs/utils.tsx b/static/app/components/replays/breadcrumbs/utils.tsx index 51cca2f78dc805..1bc1f172cb1f78 100644 --- a/static/app/components/replays/breadcrumbs/utils.tsx +++ b/static/app/components/replays/breadcrumbs/utils.tsx @@ -6,9 +6,7 @@ import {BreadcrumbType, Crumb} from 'sentry/types/breadcrumbs'; export function getDescription(crumb: Crumb) { switch (crumb.type) { case BreadcrumbType.NAVIGATION: - return `${crumb.data?.from ? `${crumb.data?.from} => ` : ''}${ - crumb.data?.to ?? '' - }`; + return `${crumb.data?.to ?? ''}`; case BreadcrumbType.DEFAULT: return JSON.stringify(crumb.data); default:" 31ec465e4fc2b9a6930455a4d3ec13a7e8002f4c,2024-11-07 23:34:20,Scott Cooper,feat(issues): Use a dropdown to toggle new issue details (#80356),False,Use a dropdown to toggle new issue details (#80356),feat,"diff --git a/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx b/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx index 3c40e302f1fe03..40e0e71c905e3d 100644 --- a/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx +++ b/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx @@ -14,6 +14,11 @@ jest.mock('sentry/utils/useNavigate', () => ({ })); jest.mock('sentry/utils/analytics'); +const mockFeedbackForm = jest.fn(); +jest.mock('sentry/utils/useFeedbackForm', () => ({ + useFeedbackForm: () => mockFeedbackForm(), +})); + describe('NewIssueExperienceButton', function () { const organization = OrganizationFixture({features: ['issue-details-streamline']}); const user = UserFixture(); @@ -22,6 +27,7 @@ describe('NewIssueExperienceButton', function () { beforeEach(() => { ConfigStore.init(); + jest.clearAllMocks(); }); it('does not appear by default', function () { @@ -124,4 +130,44 @@ describe('NewIssueExperienceButton', function () { ); expect(trackAnalytics).toHaveBeenCalledTimes(2); }); + + it('can switch back to the old UI via dropdown', async function () { + const mockFormCallback = jest.fn(); + mockFeedbackForm.mockReturnValue(mockFormCallback); + const mockChangeUserSettings = MockApiClient.addMockResponse({ + url: '/users/me/', + method: 'PUT', + }); + + render(, {organization}); + await userEvent.click( + screen.getByRole('button', { + name: 'Switch to the new issue experience', + }) + ); + + expect( + screen.getByRole('button', { + name: 'Switch issue experience', + }) + ).toBeInTheDocument(); + + const dropdownButton = screen.getByRole('button', { + name: 'Switch issue experience', + }); + await userEvent.click(dropdownButton); + + await userEvent.click( + await screen.findByRole('menuitemradio', {name: 'Give feedback on new UI'}) + ); + expect(mockFeedbackForm).toHaveBeenCalled(); + + await userEvent.click(dropdownButton); + await userEvent.click( + screen.getByRole('menuitemradio', { + name: 'Switch to the old issue experience', + }) + ); + expect(mockChangeUserSettings).toHaveBeenCalledTimes(2); + }); }); diff --git a/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx b/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx index 9246e95dac66bd..ae1b02701ac248 100644 --- a/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx +++ b/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx @@ -1,7 +1,9 @@ +import {useCallback} from 'react'; import styled from '@emotion/styled'; import {Button} from 'sentry/components/button'; -import ButtonBar from 'sentry/components/buttonBar'; +import DropdownButton from 'sentry/components/dropdownButton'; +import {DropdownMenu} from 'sentry/components/dropdownMenu'; import {IconLab} from 'sentry/icons'; import {t} from 'sentry/locale'; import {trackAnalytics} from 'sentry/utils/analytics'; @@ -21,57 +23,81 @@ export function NewIssueExperienceButton() { const openForm = useFeedbackForm(); const {mutate} = useMutateUserOptions(); + const handleToggle = useCallback(() => { + mutate({['prefersIssueDetailsStreamlinedUI']: !hasStreamlinedUI}); + trackAnalytics('issue_details.streamline_ui_toggle', { + isEnabled: !hasStreamlinedUI, + organization: organization, + }); + navigate({ + ...location, + query: {...location.query, streamline: hasStreamlinedUI ? '0' : '1'}, + }); + }, [mutate, organization, hasStreamlinedUI, location, navigate]); + if (!hasStreamlinedUIFlag) { return null; } - const feedbackButton = openForm ? ( - - ) : null; - - const label = hasStreamlinedUI - ? t('Switch to the old issue experience') - : t('Switch to the new issue experience'); + if (!openForm || !hasStreamlinedUI) { + const label = hasStreamlinedUI + ? t('Switch to the old issue experience') + : t('Switch to the new issue experience'); - return ( - + return ( } title={label} aria-label={label} - onClick={() => { - mutate({['prefersIssueDetailsStreamlinedUI']: !hasStreamlinedUI}); - trackAnalytics('issue_details.streamline_ui_toggle', { - isEnabled: !hasStreamlinedUI, - organization: organization, - }); - navigate({ - ...location, - query: {...location.query, streamline: hasStreamlinedUI ? '0' : '1'}, - }); - }} + onClick={handleToggle} /> - {hasStreamlinedUI && feedbackButton} - + ); + } + + return ( + ( + + {/* Passing icon as child to avoid extra icon margin */} + + + )} + items={[ + { + key: 'switch-to-old-ui', + label: t('Switch to the old issue experience'), + onAction: handleToggle, + }, + { + key: 'give-feedback', + label: t('Give feedback on new UI'), + hidden: !openForm, + onAction: () => { + openForm({ + messagePlaceholder: t('How can we make this new UI work for you?'), + }); + }, + }, + ]} + position=""bottom-end"" + /> ); } +const StyledDropdownButton = styled(DropdownButton)<{enabled: boolean}>` + color: ${p => (p.enabled ? p.theme.button.primary.background : 'inherit')}; + :hover { + color: ${p => (p.enabled ? p.theme.button.primary.background : 'inherit')}; + } +`; + const StyledButton = styled(Button)<{enabled: boolean}>` color: ${p => (p.enabled ? p.theme.button.primary.background : 'inherit')}; :hover {" 1a31ce74b8753cddb45c0e6d2bd6e20c2bff1653,2020-10-09 20:52:25,Priscila Oliveira,ref(ts): Convert CrashContent to Typescript (#21227),False,Convert CrashContent to Typescript (#21227),ref,"diff --git a/src/sentry/static/sentry/app/components/events/interfaces/crashContent.jsx b/src/sentry/static/sentry/app/components/events/interfaces/crashContent.jsx deleted file mode 100644 index 969c82a270170a..00000000000000 --- a/src/sentry/static/sentry/app/components/events/interfaces/crashContent.jsx +++ /dev/null @@ -1,73 +0,0 @@ -import PropTypes from 'prop-types'; -import React from 'react'; - -import ErrorBoundary from 'app/components/errorBoundary'; -import ExceptionContent from 'app/components/events/interfaces/exceptionContent'; -import RawExceptionContent from 'app/components/events/interfaces/rawExceptionContent'; -import SentryTypes from 'app/sentryTypes'; -import StacktraceContent from 'app/components/events/interfaces/stacktraceContent'; -import rawStacktraceContent from 'app/components/events/interfaces/rawStacktraceContent'; - -class CrashContent extends React.Component { - static propTypes = { - event: SentryTypes.Event.isRequired, - stackView: PropTypes.string.isRequired, - projectId: PropTypes.string.isRequired, - newestFirst: PropTypes.bool.isRequired, - stackType: PropTypes.string, - exception: PropTypes.object, - stacktrace: PropTypes.object, - }; - - renderException = () => { - const {event, stackView, stackType, newestFirst, exception, projectId} = this.props; - return stackView === 'raw' ? ( - - ) : ( - - ); - }; - - renderStacktrace = () => { - const {event, stackView, newestFirst, stacktrace} = this.props; - return stackView === 'raw' ? ( -

-        {rawStacktraceContent(stacktrace, event.platform)}
-      
- ) : ( - - ); - }; - - render() { - if (this.props.exception) { - return {this.renderException()}; - } - if (this.props.stacktrace) { - return {this.renderStacktrace()}; - } - return null; - } -} - -export default CrashContent; diff --git a/src/sentry/static/sentry/app/components/events/interfaces/crashContent/exception.tsx b/src/sentry/static/sentry/app/components/events/interfaces/crashContent/exception.tsx new file mode 100644 index 00000000000000..8e755c97ee25d2 --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/interfaces/crashContent/exception.tsx @@ -0,0 +1,54 @@ +import React from 'react'; + +import ErrorBoundary from 'app/components/errorBoundary'; +import RawExceptionContent from 'app/components/events/interfaces/rawExceptionContent'; +import ExceptionContent from 'app/components/events/interfaces/exceptionContent'; +import {STACK_VIEW, STACK_TYPE} from 'app/types/stacktrace'; +import {PlatformType, Project, ExceptionType, Event} from 'app/types'; + +type Props = { + stackView: STACK_VIEW; + stackType: STACK_TYPE; + projectId: Project['id']; + exception: { + excOmitted: any | null; + hasSystemFrames: boolean; + values: Array; + }; + event: Event; + newestFirst: boolean; + platform: PlatformType; +}; + +const Exception = ({ + stackView, + stackType, + projectId, + exception, + event, + newestFirst, + platform = 'other', +}: Props) => ( + + {stackView === STACK_VIEW.RAW ? ( + + ) : ( + + )} + +); + +export default Exception; diff --git a/src/sentry/static/sentry/app/components/events/interfaces/crashContent/index.tsx b/src/sentry/static/sentry/app/components/events/interfaces/crashContent/index.tsx new file mode 100644 index 00000000000000..c56dd6fadc657b --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/interfaces/crashContent/index.tsx @@ -0,0 +1,70 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +import SentryTypes from 'app/sentryTypes'; +import {PlatformType} from 'app/types'; + +import Exception from './exception'; +import Stacktrace from './stacktrace'; + +type ExceptionProps = React.ComponentProps; +type StacktraceProps = React.ComponentProps; +type Props = Pick< + ExceptionProps, + 'stackType' | 'stackView' | 'projectId' | 'event' | 'newestFirst' +> & { + exception?: ExceptionProps['exception']; + stacktrace?: StacktraceProps['stacktrace']; +}; + +const CrashContent = ({ + event, + stackView, + stackType, + newestFirst, + projectId, + exception, + stacktrace, +}: Props) => { + const platform = (event.platform ?? 'other') as PlatformType; + + if (exception) { + return ( + + ); + } + + if (stacktrace) { + return ( + + ); + } + + return null; +}; + +CrashContent.propTypes = { + event: SentryTypes.Event.isRequired, + stackView: PropTypes.string.isRequired, + projectId: PropTypes.string.isRequired, + newestFirst: PropTypes.bool.isRequired, + stackType: PropTypes.string, + exception: PropTypes.object, + stacktrace: PropTypes.object, +}; + +export default CrashContent; diff --git a/src/sentry/static/sentry/app/components/events/interfaces/crashContent/stacktrace.tsx b/src/sentry/static/sentry/app/components/events/interfaces/crashContent/stacktrace.tsx new file mode 100644 index 00000000000000..7e22d6d41b4bc2 --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/interfaces/crashContent/stacktrace.tsx @@ -0,0 +1,36 @@ +import React from 'react'; + +import ErrorBoundary from 'app/components/errorBoundary'; +import StacktraceContent from 'app/components/events/interfaces/stacktraceContent'; +import rawStacktraceContent from 'app/components/events/interfaces/rawStacktraceContent'; +import {STACK_VIEW, StacktraceType} from 'app/types/stacktrace'; +import {PlatformType, Event} from 'app/types'; + +type Props = { + stackView: STACK_VIEW; + stacktrace: StacktraceType; + event: Event; + newestFirst: boolean; + platform: PlatformType; +}; + +const Stacktrace = ({stackView, stacktrace, event, newestFirst, platform}: Props) => ( + + {stackView === STACK_VIEW.RAW ? ( +
+        {rawStacktraceContent(stacktrace, event.platform)}
+      
+ ) : ( + + )} +
+); + +export default Stacktrace; diff --git a/src/sentry/static/sentry/app/components/events/interfaces/exceptionStacktraceContent.tsx b/src/sentry/static/sentry/app/components/events/interfaces/exceptionStacktraceContent.tsx index bc25f70df1191c..c29606ac4c6a87 100644 --- a/src/sentry/static/sentry/app/components/events/interfaces/exceptionStacktraceContent.tsx +++ b/src/sentry/static/sentry/app/components/events/interfaces/exceptionStacktraceContent.tsx @@ -5,15 +5,15 @@ import StacktraceContent from 'app/components/events/interfaces/stacktraceConten import {Panel} from 'app/components/panels'; import {IconWarning} from 'app/icons'; import EmptyMessage from 'app/views/settings/components/emptyMessage'; -import {Stacktrace, STACK_VIEW} from 'app/types/stacktrace'; +import {StacktraceType, STACK_VIEW} from 'app/types/stacktrace'; import {PlatformType, Event} from 'app/types'; type Props = { stackView: STACK_VIEW; - data: Stacktrace | null; + data: StacktraceType | null; event: Event; platform: PlatformType; - stacktrace: Stacktrace; + stacktrace: StacktraceType; chainedException: boolean; expandFirstFrame?: boolean; newestFirst?: boolean; diff --git a/src/sentry/static/sentry/app/components/events/interfaces/stacktraceContent.tsx b/src/sentry/static/sentry/app/components/events/interfaces/stacktraceContent.tsx index 702cf66eb5517e..debb2c8f614779 100644 --- a/src/sentry/static/sentry/app/components/events/interfaces/stacktraceContent.tsx +++ b/src/sentry/static/sentry/app/components/events/interfaces/stacktraceContent.tsx @@ -5,11 +5,11 @@ import Line from 'app/components/events/interfaces/frame/line'; import {t} from 'app/locale'; import SentryTypes from 'app/sentryTypes'; import {parseAddress, getImageRange} from 'app/components/events/interfaces/utils'; -import {Stacktrace} from 'app/types/stacktrace'; +import {StacktraceType} from 'app/types/stacktrace'; import {PlatformType, Event} from 'app/types'; type Props = { - data: Stacktrace; + data: StacktraceType; includeSystemFrames: boolean; platform: PlatformType; event: Event; diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx index 64e3728d347f09..648e3dbd6624a6 100644 --- a/src/sentry/static/sentry/app/types/index.tsx +++ b/src/sentry/static/sentry/app/types/index.tsx @@ -13,7 +13,7 @@ import {Props as AlertProps} from 'app/components/alert'; import {Query as DiscoverQuery} from 'app/views/discover/types'; import {SymbolicatorStatus} from 'app/components/events/interfaces/types'; -import {Stacktrace, RawStacktrace, Mechanism} from './stacktrace'; +import {StacktraceType, RawStacktrace, Mechanism} from './stacktrace'; declare global { interface Window { @@ -1537,7 +1537,7 @@ export type FilesByRepository = { export type ExceptionType = { type: string; value: string; - stacktrace: Stacktrace; + stacktrace: StacktraceType; rawStacktrace: RawStacktrace; mechanism: Mechanism | null; module: string | null; diff --git a/src/sentry/static/sentry/app/types/stacktrace.tsx b/src/sentry/static/sentry/app/types/stacktrace.tsx index 49cfa847541cde..ef0233cef9e6a5 100644 --- a/src/sentry/static/sentry/app/types/stacktrace.tsx +++ b/src/sentry/static/sentry/app/types/stacktrace.tsx @@ -11,14 +11,14 @@ export enum STACK_TYPE { MINIFIED = 'minified', } -export type Stacktrace = { +export type StacktraceType = { frames: Array; hasSystemFrames: boolean; registers: Record | null; framesOmitted: any; }; -export type RawStacktrace = Stacktrace | null; +export type RawStacktrace = StacktraceType | null; type MechanismMeta = { errno?: {" 842d5a71661be15212592af1b5919984adf0f4f8,2024-05-21 22:15:51,Scott Cooper,fix(stories): Reduce scroll bars on stories (#71202),False,Reduce scroll bars on stories (#71202),fix,"diff --git a/static/app/views/stories/index.tsx b/static/app/views/stories/index.tsx index c64317e89fcfa8..2297a90f37ad55 100644 --- a/static/app/views/stories/index.tsx +++ b/static/app/views/stories/index.tsx @@ -104,7 +104,7 @@ const Main = styled(VerticalScroll)` padding: var(--stories-grid-space); overflow-x: hidden; - overflow-y: scroll; + overflow-y: auto; position: relative; `; diff --git a/static/app/views/stories/storyFile.tsx b/static/app/views/stories/storyFile.tsx index 83b511523141e7..475d9702aaff95 100644 --- a/static/app/views/stories/storyFile.tsx +++ b/static/app/views/stories/storyFile.tsx @@ -78,7 +78,6 @@ const FlexColumn = styled('section')` `; const StoryArea = styled('div')` - overflow: scroll; display: flex; flex-direction: column; gap: ${space(4)};" 473fb208059fa77fc8cd441cf468cd1960de266c,2022-09-17 03:18:08,Evan Purkhiser,ref(ui): Add per value context support in KeyValueList (#38977),False,Add per value context support in KeyValueList (#38977),ref,"diff --git a/static/app/components/events/interfaces/keyValueList/index.tsx b/static/app/components/events/interfaces/keyValueList/index.tsx index 8cf10ef2de49c1..3f1395a1358235 100644 --- a/static/app/components/events/interfaces/keyValueList/index.tsx +++ b/static/app/components/events/interfaces/keyValueList/index.tsx @@ -42,7 +42,16 @@ function KeyValueList({ subjectIcon, subjectDataTestId, actionButton, + isContextData: valueIsContextData, }) => { + const valueProps = { + isContextData: valueIsContextData || isContextData, + meta, + subjectIcon, + value, + raw, + }; + return ( @@ -52,23 +61,11 @@ function KeyValueList({ {actionButton ? ( - + {actionButton} ) : ( - + )} diff --git a/static/app/types/group.tsx b/static/app/types/group.tsx index 2205e16227a2ad..d1700b2817f039 100644 --- a/static/app/types/group.tsx +++ b/static/app/types/group.tsx @@ -608,6 +608,7 @@ export type KeyValueListData = { key: string; subject: string; actionButton?: React.ReactNode; + isContextData?: boolean; meta?: Meta; subjectDataTestId?: string; subjectIcon?: React.ReactNode;" 27bc41551b7b6534b6a04d1a44eb3a265795382b,2023-10-12 01:55:16,Colton Allen,feat(replays): Add accessibility-issues blueprint (#57160),False,Add accessibility-issues blueprint (#57160),feat,"diff --git a/src/sentry/replays/blueprints/api.md b/src/sentry/replays/blueprints/api.md index 6c9bdd6dd3d3ab..03712fad6e86ee 100644 --- a/src/sentry/replays/blueprints/api.md +++ b/src/sentry/replays/blueprints/api.md @@ -240,6 +240,94 @@ Deletes a replay instance. - Response 204 +## Replay Accessibility Issues [/projects///replays//accessibility-issues] + +This resource does not accept any URI parameters and is not paginated. Responses are ingested whole. + +### Fetch Replay Accessibility Issues [GET] + +Retrieve a collection of accessibility issues. + +**Attributes** + +Issue Type: + +| Column | Type | Description | +| --------- | ---------------------- | --------------------------------------------------- | +| elements | array[IssueElement] | Array of elements matching the accessibility issue. | +| help | string | - | +| help_url | string | - | +| id | string | - | +| impact | Optional[enum[string]] | One of: 'minor', 'moderate', 'serious', 'critical' | +| timestamp | number | - | + +IssueElement Type: + +| Column | Type | Description | +| ------------ | ------------------------------ | --------------------------------------------------- | +| alternatives | array[IssueElementAlternative] | Array of solutions which could solve the problem. | +| element | string | Array of elements matching the accessibility issue. | +| target | array[string] | Array of elements matching the accessibility issue. | + +IssueElementAlternative Type: + +| Column | Type | Description | +| ------- | ------ | ------------------------------------- | +| id | string | String ID of the accessibility issue. | +| message | string | Message explaining the problem. | + +- Response 200 + + - Headers + + - X-Hits=1 + + - Body + + ```json + { + ""data"": [ + [ + { + ""elements"": [ + { + ""alternatives"": [ + { + ""id"": ""button-has-visible-text"", + ""message"": ""Element does not have inner text that is visible to screen readers"" + }, + { + ""id"": ""aria-label"", + ""message"": ""aria-label attribute does not exist or is empty"" + }, + { + ""id"": ""aria-labelledby"", + ""message"": ""aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty"" + }, + { + ""id"": ""non-empty-title"", + ""message"": ""Element has no title attribute"" + }, + { + ""id"": ""presentational-role"", + ""message"": ""Element's default semantics were not overridden with role=\""none\"" or role=\""presentation\"""" + } + ], + ""element"": ""
- {hasIssueAlertOptionsEnabled ? t('Name') : t('Assign a Team')} + {hasIssueAlertOptionsEnabled ? t('Team') : t('Assign a Team')} { {({registerScrollFn, scrollToHash}) => { if (!isGapSpan(span)) { - registerScrollFn(`#span-${span.span_id}`, this.scrollIntoView); + registerScrollFn(spanTargetHash(span.span_id), this.scrollIntoView); } if (!this.state.showDetail || !isVisible) { diff --git a/static/app/components/events/interfaces/spans/utils.tsx b/static/app/components/events/interfaces/spans/utils.tsx index d76dc29502805e..91f1f6a4301b09 100644 --- a/static/app/components/events/interfaces/spans/utils.tsx +++ b/static/app/components/events/interfaces/spans/utils.tsx @@ -615,7 +615,7 @@ export function scrollToSpan( // because it will be hidden behind the minimap e.preventDefault(); - const hash = `#span-${spanId}`; + const hash = spanTargetHash(spanId); scrollToHash(hash); @@ -629,3 +629,7 @@ export function scrollToSpan( }); }; } + +export function spanTargetHash(spanId: string): string { + return `#span-${spanId}`; +} diff --git a/static/app/utils/performance/suspectSpans/suspectSpansQuery.tsx b/static/app/utils/performance/suspectSpans/suspectSpansQuery.tsx index ef68e2cdb62005..5d7046b94ee908 100644 --- a/static/app/utils/performance/suspectSpans/suspectSpansQuery.tsx +++ b/static/app/utils/performance/suspectSpans/suspectSpansQuery.tsx @@ -1,6 +1,7 @@ import {ReactNode} from 'react'; import omit from 'lodash/omit'; +import {defined} from 'sentry/utils'; import GenericDiscoverQuery, { DiscoverQueryProps, GenericChildrenProps, @@ -10,7 +11,8 @@ import withApi from 'sentry/utils/withApi'; import {SuspectSpans} from './types'; type SuspectSpansProps = { - spanOps: string[]; + perSuspect?: number; + spanOps?: string[]; }; type RequestProps = DiscoverQueryProps & SuspectSpansProps; @@ -24,7 +26,14 @@ type Props = RequestProps & { }; function getSuspectSpanPayload(props: RequestProps) { - const payload = {spanOp: props.spanOps}; + const {perSuspect, spanOps} = props; + const payload = {perSuspect, spanOp: spanOps}; + if (!defined(payload.perSuspect)) { + delete payload.perSuspect; + } + if (!defined(payload.spanOp)) { + delete payload.spanOp; + } const additionalPayload = omit(props.eventView.getEventsAPIPayload(props.location), [ 'field', ]); diff --git a/static/app/views/performance/transactionSummary/pageLayout.tsx b/static/app/views/performance/transactionSummary/pageLayout.tsx index cfb25b07f19080..a80be3a108ab72 100644 --- a/static/app/views/performance/transactionSummary/pageLayout.tsx +++ b/static/app/views/performance/transactionSummary/pageLayout.tsx @@ -30,6 +30,7 @@ export type ChildProps = { organization: Organization; projects: Project[]; eventView: EventView; + projectId: string; transactionName: string; setError: Dispatch>; // These are used to trigger a reload when the threshold/metric changes. @@ -149,6 +150,7 @@ function PageLayout(props: Props) { organization={organization} projects={projects} eventView={eventView} + projectId={projectId} transactionName={transactionName} setError={setError} transactionThreshold={transactionThreshold} diff --git a/static/app/views/performance/transactionSummary/transactionOverview/content.tsx b/static/app/views/performance/transactionSummary/transactionOverview/content.tsx index a875a7806d0c40..6f18ccc293de0c 100644 --- a/static/app/views/performance/transactionSummary/transactionOverview/content.tsx +++ b/static/app/views/performance/transactionSummary/transactionOverview/content.tsx @@ -4,6 +4,7 @@ import styled from '@emotion/styled'; import {Location} from 'history'; import omit from 'lodash/omit'; +import Feature from 'sentry/components/acl/feature'; import TransactionsList, { DropdownOption, } from 'sentry/components/discover/transactionsList'; @@ -54,12 +55,14 @@ import TransactionSummaryCharts from './charts'; import RelatedIssues from './relatedIssues'; import SidebarCharts from './sidebarCharts'; import StatusBreakdown from './statusBreakdown'; +import SuspectSpans from './suspectSpans'; import {TagExplorer} from './tagExplorer'; import UserStats from './userStats'; type Props = { location: Location; eventView: EventView; + projectId: string; transactionName: string; organization: Organization; isLoading: boolean; @@ -187,6 +190,7 @@ class SummaryContent extends React.Component { render() { let {eventView} = this.props; const { + projectId, transactionName, location, organization, @@ -351,6 +355,18 @@ class SummaryContent extends React.Component { })} forceLoading={isLoading} /> + + + ; + +type SuspectSpanTableDataRow = Record; + +const SUSPECT_SPANS_TABLE_COLUMN_ORDER: SuspectSpanTableColumn[] = [ + { + key: 'op', + name: t('Operation'), + width: COL_WIDTH_UNDEFINED, + }, + { + key: 'description', + name: t('Description'), + width: COL_WIDTH_UNDEFINED, + }, + { + key: 'p75ExclusiveTime', + name: t('P75 Exclusive Time'), + width: COL_WIDTH_UNDEFINED, + }, + { + key: 'count', + name: t('Total Occurrences'), + width: COL_WIDTH_UNDEFINED, + }, + { + key: 'sumExclusiveTime', + name: t('Total Exclusive Time'), + width: COL_WIDTH_UNDEFINED, + }, + { + key: 'id', + name: t('Example Transaction'), + width: COL_WIDTH_UNDEFINED, + }, +]; + +const SPANS_CURSOR_NAME = 'spansCursor'; + +type Props = { + location: Location; + organization: Organization; + eventView: EventView; + projectId: string; + transactionName: string; +}; + +export default function SuspectSpans(props: Props) { + const {location, organization, eventView, projectId, transactionName} = props; + const sort = getSuspectSpanSortFromLocation(location, 'spanSort'); + const cursor = decodeScalar(location.query?.[SPANS_CURSOR_NAME]); + + const sortedEventView = eventView + .withColumns( + [...Object.values(SpanSortOthers), ...Object.values(SpanSortPercentiles)].map( + field => ({kind: 'field', field}) + ) + ) + .withSorts([{kind: 'desc', field: sort.field}]); + const sortColumn: GridColumnSortBy = { + key: sort.field as SuspectSpanTableColumnKeys, + width: COL_WIDTH_UNDEFINED, + order: 'desc', + }; + + return ( + + {({suspectSpans, isLoading, pageLinks}) => { + const data = (suspectSpans ?? []).map(suspectSpan => { + const example = suspectSpan.examples[0]; + return { + project: suspectSpan.project, + op: suspectSpan.op, + description: example?.description ?? null, + p75ExclusiveTime: suspectSpan.p75ExclusiveTime, + count: suspectSpan.frequency, + sumExclusiveTime: suspectSpan.sumExclusiveTime, + id: example?.id ?? null, + spans: example?.spans, + }; + }); + + return ( + + + + + ); + }} + + ); +} + +const SUSPECT_SPANS_TABLE_COLUMN_TYPE: Omit< + Record, + 'spans' +> = { + op: 'string', + description: 'string', + p75ExclusiveTime: 'duration', + count: 'integer', + sumExclusiveTime: 'duration', + id: 'string', +}; + +function renderHeadCellWithMeta( + location: Location, + sortColumn: GridColumnSortBy +) { + return (column: SuspectSpanTableColumn, _index: number): ReactNode => { + const columnType = SUSPECT_SPANS_TABLE_COLUMN_TYPE[column.key]; + const align = fieldAlignment(column.key, columnType); + + const canSort = columnType === 'integer' || columnType === 'duration'; + const direction = + canSort && column.key === sortColumn.key ? sortColumn.order : undefined; + + function generateSortLink() { + return { + ...location, + query: { + ...location.query, + spanSort: column.key, + [SPANS_CURSOR_NAME]: undefined, + }, + }; + } + + return ( + + ); + }; +} + +function renderBodyCellWithMeta({ + location, + organization, + transactionName, +}: { + location: Location; + organization: Organization; + transactionName: string; +}) { + return ( + column: SuspectSpanTableColumn, + dataRow: SuspectSpanTableDataRow + ): ReactNode => { + const fieldRenderer = getFieldRenderer(column.key, SUSPECT_SPANS_TABLE_COLUMN_TYPE); + const rendered = fieldRenderer(dataRow, {location, organization}); + + if (column.key === 'id') { + if (defined(dataRow.id)) { + const worstSpan = dataRow.spans?.length + ? dataRow.spans.reduce((worst, span) => + worst.exclusiveTime >= span.exclusiveTime ? worst : span + ) + : null; + + const target = generateTransactionLink(transactionName)( + organization, + dataRow, + location.query, + worstSpan.id + ); + + return {rendered}; + } + + return emptyValue; + } + + return rendered; + }; +} + +type HeaderProps = { + location: Location; + organization: Organization; + projectId: string; + transactionName: string; + pageLinks: string | null; +}; + +function SuspectSpansHeader(props: HeaderProps) { + const {location, organization, projectId, transactionName, pageLinks} = props; + + const viewAllTarget = spansRouteWithQuery({ + orgSlug: organization.slug, + transaction: transactionName, + projectID: projectId, + query: location.query, + }); + + const handleCursor: CursorHandler = (cursor, pathname, query) => { + browserHistory.push({ + pathname, + query: {...query, [SPANS_CURSOR_NAME]: cursor}, + }); + }; + + return ( +
+
+ {t('Suspect Spans')} + +
+ + +
+ ); +} + +const Header = styled('div')` + display: grid; + grid-template-columns: 1fr auto auto; + margin-bottom: ${space(1)}; +`; + +const StyledPagination = styled(Pagination)` + margin: 0 0 0 ${space(1)}; +`; + +const EmptyValueContainer = styled('span')` + color: ${p => p.theme.gray300}; +`; +const emptyValue = {t('n/a')}; diff --git a/static/app/views/performance/transactionSummary/transactionSpans/suspectSpanCard.tsx b/static/app/views/performance/transactionSummary/transactionSpans/suspectSpanCard.tsx index 1e933d72af008b..0b5eecdc38b785 100644 --- a/static/app/views/performance/transactionSummary/transactionSpans/suspectSpanCard.tsx +++ b/static/app/views/performance/transactionSummary/transactionSpans/suspectSpanCard.tsx @@ -39,32 +39,35 @@ import {getSuspectSpanSortFromEventView} from './utils'; const SPANS_TABLE_COLUMN_ORDER: SuspectSpanTableColumn[] = [ { key: 'id', - name: 'Example Transaction', + name: t('Example Transaction'), width: COL_WIDTH_UNDEFINED, }, { key: 'timestamp', - name: 'Timestamp', + name: t('Timestamp'), width: COL_WIDTH_UNDEFINED, }, { key: 'spanDuration', - name: 'Span Duration', + name: t('Span Duration'), width: COL_WIDTH_UNDEFINED, }, { key: 'occurrences', - name: 'Occurrences', + name: t('Occurrences'), width: COL_WIDTH_UNDEFINED, }, { key: 'cumulativeDuration', - name: 'Cumulative Duration', + name: t('Cumulative Duration'), width: COL_WIDTH_UNDEFINED, }, ]; -const SPANS_TABLE_COLUMN_TYPE: Partial> = { +const SPANS_TABLE_COLUMN_TYPE: Omit< + Record, + 'spans' | 'transactionDuration' +> = { id: 'string', timestamp: 'date', spanDuration: 'duration', @@ -296,8 +299,12 @@ function renderBodyCellWithMeta( worst.exclusiveTime >= span.exclusiveTime ? worst : span ) : null; - const hash = worstSpan ? `#span-${worstSpan.id}` : undefined; - const target = generateTransactionLink(organization, dataRow, location.query, hash); + const target = generateTransactionLink( + organization, + dataRow, + location.query, + worstSpan.id + ); rendered = {rendered}; } diff --git a/static/app/views/performance/transactionSummary/transactionSpans/utils.tsx b/static/app/views/performance/transactionSummary/transactionSpans/utils.tsx index 9c3cbc03294889..1b96f8ef99f34d 100644 --- a/static/app/views/performance/transactionSummary/transactionSpans/utils.tsx +++ b/static/app/views/performance/transactionSummary/transactionSpans/utils.tsx @@ -82,8 +82,11 @@ function getSuspectSpanSort(sort: string): SpanSortOption { return SPAN_SORT_OPTIONS.find(option => option.field === DEFAULT_SORT)!; } -export function getSuspectSpanSortFromLocation(location: Location): SpanSortOption { - const sort = decodeScalar(location?.query?.sort) ?? DEFAULT_SORT; +export function getSuspectSpanSortFromLocation( + location: Location, + sortKey: string = 'sort' +): SpanSortOption { + const sort = decodeScalar(location?.query?.[sortKey]) ?? DEFAULT_SORT; return getSuspectSpanSort(sort); } diff --git a/static/app/views/performance/transactionSummary/utils.tsx b/static/app/views/performance/transactionSummary/utils.tsx index a6988baad94a5a..0bdec28d577a96 100644 --- a/static/app/views/performance/transactionSummary/utils.tsx +++ b/static/app/views/performance/transactionSummary/utils.tsx @@ -103,7 +103,7 @@ export function generateTransactionLink(transactionName: string) { organization: Organization, tableRow: TableDataRow, query: Query, - hash?: string + spanId?: string ): LocationDescriptor => { const eventSlug = generateEventSlug(tableRow); return getTransactionDetailsUrl( @@ -111,7 +111,7 @@ export function generateTransactionLink(transactionName: string) { eventSlug, transactionName, query, - hash + spanId ); }; } diff --git a/static/app/views/performance/utils.tsx b/static/app/views/performance/utils.tsx index 92d061797f8024..38591dc3b09f00 100644 --- a/static/app/views/performance/utils.tsx +++ b/static/app/views/performance/utils.tsx @@ -2,6 +2,7 @@ import {browserHistory} from 'react-router'; import {Location, LocationDescriptor, Query} from 'history'; import Duration from 'sentry/components/duration'; +import {spanTargetHash} from 'sentry/components/events/interfaces/spans/utils'; import {ALL_ACCESS_PROJECTS} from 'sentry/constants/globalSelectionHeader'; import {backend, frontend, mobile} from 'sentry/data/platformCategories'; import { @@ -225,8 +226,9 @@ export function getTransactionDetailsUrl( eventSlug: string, transaction: string, query: Query, - hash?: string + spanId?: string ): LocationDescriptor { + const hash = defined(spanId) ? spanTargetHash(spanId) : undefined; const target = { pathname: `/organizations/${organization.slug}/performance/${eventSlug}/`, query: { diff --git a/tests/js/sentry-test/performance/initializePerformanceData.ts b/tests/js/sentry-test/performance/initializePerformanceData.ts index fc747a290e431d..d51acf1bc08d36 100644 --- a/tests/js/sentry-test/performance/initializePerformanceData.ts +++ b/tests/js/sentry-test/performance/initializePerformanceData.ts @@ -1,7 +1,13 @@ import {initializeOrg} from 'sentry-test/initializeOrg'; import {Project} from 'sentry/types'; +import {defined} from 'sentry/utils'; import EventView from 'sentry/utils/discover/eventView'; +import { + ExampleSpan, + ExampleTransaction, + SuspectSpan, +} from 'sentry/utils/performance/suspectSpans/types'; export function initializeData(settings?: { query?: {}; @@ -39,3 +45,106 @@ export function initializeData(settings?: { return {...initialData, location, eventView}; } + +export const SAMPLE_SPANS = [ + { + op: 'op1', + group: 'aaaaaaaaaaaaaaaa', + examples: [ + { + id: 'abababababababab', + description: 'span-1', + spans: [{id: 'ababab11'}, {id: 'ababab22'}], + }, + { + id: 'acacacacacacacac', + description: 'span-2', + spans: [{id: 'acacac11'}, {id: 'acacac22'}], + }, + ], + }, + { + op: 'op2', + group: 'bbbbbbbbbbbbbbbb', + examples: [ + { + id: 'bcbcbcbcbcbcbcbc', + description: 'span-3', + spans: [{id: 'bcbcbc11'}, {id: 'bcbcbc11'}], + }, + { + id: 'bdbdbdbdbdbdbdbd', + description: 'span-4', + spans: [{id: 'bdbdbd11'}, {id: 'bdbdbd22'}], + }, + ], + }, +]; + +type SpanOpt = { + id: string; +}; + +type ExampleOpt = { + id: string; + description: string; + spans: SpanOpt[]; +}; + +type SuspectOpt = { + op: string; + group: string; + examples: ExampleOpt[]; +}; + +function makeSpan(opt: SpanOpt): ExampleSpan { + const {id} = opt; + return { + id, + startTimestamp: 10100, + finishTimestamp: 10200, + exclusiveTime: 100, + }; +} + +function makeExample(opt: ExampleOpt): ExampleTransaction { + const {id, description, spans} = opt; + return { + id, + description, + startTimestamp: 10000, + finishTimestamp: 12000, + nonOverlappingExclusiveTime: 2000, + spans: spans.map(makeSpan), + }; +} + +function makeSuspectSpan(opt: SuspectOpt): SuspectSpan { + const {op, group, examples} = opt; + return { + projectId: 1, + project: 'bar', + transaction: 'transaction-1', + op, + group, + frequency: 1, + count: 1, + sumExclusiveTime: 1, + p50ExclusiveTime: 1, + p75ExclusiveTime: 1, + p95ExclusiveTime: 1, + p99ExclusiveTime: 1, + examples: examples.map(makeExample), + }; +} + +export function generateSuspectSpansResponse(opts?: {examples?: number}) { + const {examples} = opts ?? {}; + return SAMPLE_SPANS.map(sampleSpan => { + const span = {...sampleSpan}; + if (defined(examples)) { + span.examples = span.examples.slice(0, examples); + } + return makeSuspectSpan(span); + }); +} diff --git a/tests/js/spec/utils/performance/suspectSpans/suspectSpansQuery.spec.tsx b/tests/js/spec/utils/performance/suspectSpans/suspectSpansQuery.spec.tsx index a46eae28fa036b..69af8c6f956b13 100644 --- a/tests/js/spec/utils/performance/suspectSpans/suspectSpansQuery.spec.tsx +++ b/tests/js/spec/utils/performance/suspectSpans/suspectSpansQuery.spec.tsx @@ -66,4 +66,26 @@ describe('SuspectSpansQuery', function () { expect(getMock).toHaveBeenCalledTimes(1); }); + + it('fetches data with the right per suspect param', async function () { + const getMock = MockApiClient.addMockResponse({ + url: '/organizations/test-org/events-spans-performance/', + // just asserting that the data is being fetched, no need for actual data here + body: [], + match: [MockApiClient.matchQuery({perSuspect: 1})], + }); + + mountWithTheme( + + {() => null} + + ); + + expect(getMock).toHaveBeenCalledTimes(1); + }); }); diff --git a/tests/js/spec/views/performance/transactionSpans/index.spec.tsx b/tests/js/spec/views/performance/transactionSpans/index.spec.tsx index a3c738c2326b3f..2f3743cc5bd935 100644 --- a/tests/js/spec/views/performance/transactionSpans/index.spec.tsx +++ b/tests/js/spec/views/performance/transactionSpans/index.spec.tsx @@ -1,13 +1,12 @@ import {initializeOrg} from 'sentry-test/initializeOrg'; +import { + generateSuspectSpansResponse, + SAMPLE_SPANS, +} from 'sentry-test/performance/initializePerformanceData'; import {act, mountWithTheme, screen, within} from 'sentry-test/reactTestingLibrary'; import ProjectsStore from 'sentry/stores/projectsStore'; import {getShortEventId} from 'sentry/utils/events'; -import { - ExampleSpan, - ExampleTransaction, - SuspectSpan, -} from 'sentry/utils/performance/suspectSpans/types'; import TransactionSpans from 'sentry/views/performance/transactionSummary/transactionSpans'; import { SpanSortOthers, @@ -36,98 +35,6 @@ function initializeData({query} = {query: {}}) { return initialData; } -type SpanOpt = { - id: string; -}; - -type ExampleOpt = { - id: string; - description: string; - spans: SpanOpt[]; -}; - -type SuspectOpt = { - op: string; - group: string; - examples: ExampleOpt[]; -}; - -function makeSpan(opt: SpanOpt): ExampleSpan { - const {id} = opt; - return { - id, - startTimestamp: 10100, - finishTimestamp: 10200, - exclusiveTime: 100, - }; -} - -function makeExample(opt: ExampleOpt): ExampleTransaction { - const {id, description, spans} = opt; - return { - id, - description, - startTimestamp: 10000, - finishTimestamp: 12000, - nonOverlappingExclusiveTime: 2000, - spans: spans.map(makeSpan), - }; -} - -export function makeSuspectSpan(opt: SuspectOpt): SuspectSpan { - const {op, group, examples} = opt; - return { - projectId: 1, - project: 'bar', - transaction: 'transaction-1', - op, - group, - frequency: 1, - count: 1, - sumExclusiveTime: 1, - p50ExclusiveTime: 1, - p75ExclusiveTime: 1, - p95ExclusiveTime: 1, - p99ExclusiveTime: 1, - examples: examples.map(makeExample), - }; -} - -const spans = [ - { - op: 'op1', - group: 'aaaaaaaaaaaaaaaa', - examples: [ - { - id: 'abababababababab', - description: 'span-1', - spans: [{id: 'ababab11'}, {id: 'ababab22'}], - }, - { - id: 'acacacacacacacac', - description: 'span-2', - spans: [{id: 'acacac11'}, {id: 'acacac22'}], - }, - ], - }, - { - op: 'op2', - group: 'bbbbbbbbbbbbbbbb', - examples: [ - { - id: 'bcbcbcbcbcbcbcbc', - description: 'span-3', - spans: [{id: 'bcbcbc11'}, {id: 'bcbcbc11'}], - }, - { - id: 'bdbdbdbdbdbdbdbd', - description: 'span-4', - spans: [{id: 'bdbdbd11'}, {id: 'bdbdbd22'}], - }, - ], - }, -]; - describe('Performance > Transaction Spans', function () { let eventsV2Mock; let eventsSpanOpsMock; @@ -192,7 +99,7 @@ describe('Performance > Transaction Spans', function () { beforeEach(function () { eventsSpansPerformanceMock = MockApiClient.addMockResponse({ url: '/organizations/org-slug/events-spans-performance/', - body: spans.map(makeSuspectSpan), + body: generateSuspectSpansResponse(), }); }); @@ -221,7 +128,7 @@ describe('Performance > Transaction Spans', function () { await within(card).findByText('Total Cumulative Duration') ).toBeInTheDocument(); - for (const example of spans[i].examples) { + for (const example of SAMPLE_SPANS[i].examples) { expect( await within(card).findByText(getShortEventId(example.id)) ).toBeInTheDocument(); diff --git a/tests/js/spec/views/performance/transactionSummary.spec.jsx b/tests/js/spec/views/performance/transactionSummary.spec.jsx index 74cc0665939b45..97b7b7e58ab200 100644 --- a/tests/js/spec/views/performance/transactionSummary.spec.jsx +++ b/tests/js/spec/views/performance/transactionSummary.spec.jsx @@ -559,6 +559,28 @@ describe('Performance > TransactionSummary', function () { expect(issueGet).toHaveBeenCalled(); }); + it('renders the suspect spans table if the feature is enabled', async function () { + MockApiClient.addMockResponse({ + url: '/organizations/org-slug/events-spans-performance/', + body: [], + }); + + const initialData = initializeData({ + features: ['performance-suspect-spans-view'], + }); + const wrapper = mountWithTheme( + , + initialData.routerContext + ); + await tick(); + wrapper.update(); + + expect(wrapper.find('SuspectSpans')).toHaveLength(1); + }); + it('adds search condition on transaction status when clicking on status breakdown', async function () { const initialData = initializeData(); const wrapper = mountWithTheme( diff --git a/tests/js/spec/views/performance/transactionSummary/content.spec.tsx b/tests/js/spec/views/performance/transactionSummary/content.spec.tsx index 40bdf1860fe959..79e9cdb65022be 100644 --- a/tests/js/spec/views/performance/transactionSummary/content.spec.tsx +++ b/tests/js/spec/views/performance/transactionSummary/content.spec.tsx @@ -5,11 +5,11 @@ import EventView from 'sentry/utils/discover/eventView'; import {SpanOperationBreakdownFilter} from 'sentry/views/performance/transactionSummary/filter'; import SummaryContent from 'sentry/views/performance/transactionSummary/transactionOverview/content'; -function initialize(projects, query, additionalFeatures: string[] = []) { +function initialize(project, query, additionalFeatures: string[] = []) { const features = ['transaction-event', 'performance-view', ...additionalFeatures]; const organization = TestStubs.Organization({ features, - projects, + projects: [project], }); const initialOrgData = { organization, @@ -18,7 +18,7 @@ function initialize(projects, query, additionalFeatures: string[] = []) { query: {...query}, }, }, - project: 1, + project: parseInt(project.id, 10), projects: [], }; const initialData = initializeOrg(initialOrgData); @@ -95,14 +95,14 @@ describe('Transaction Summary Content', function () { }); it('Basic Rendering', async function () { - const projects = [TestStubs.Project()]; + const project = TestStubs.Project(); const { organization, location, eventView, spanOperationBreakdownFilter, transactionName, - } = initialize(projects, {}); + } = initialize(project, {}); const routerContext = TestStubs.routerContext([{organization}]); const wrapper = mountWithTheme( @@ -110,6 +110,7 @@ describe('Transaction Summary Content', function () { location={location} organization={organization} eventView={eventView} + projectId={project.id} transactionName={transactionName} isLoading={false} totalValues={null} @@ -140,14 +141,14 @@ describe('Transaction Summary Content', function () { }); it('Renders with generatePerformanceTransactionEventsView instead when feature flagged', async function () { - const projects = [TestStubs.Project()]; + const project = TestStubs.Project(); const { organization, location, eventView, spanOperationBreakdownFilter, transactionName, - } = initialize(projects, {}, ['performance-events-page']); + } = initialize(project, {}, ['performance-events-page']); const routerContext = TestStubs.routerContext([{organization}]); const wrapper = mountWithTheme( @@ -155,6 +156,7 @@ describe('Transaction Summary Content', function () { location={location} organization={organization} eventView={eventView} + projectId={project.id} transactionName={transactionName} isLoading={false} totalValues={null} @@ -185,14 +187,14 @@ describe('Transaction Summary Content', function () { }); it('Renders TransactionSummaryCharts withoutZerofill when feature flagged', async function () { - const projects = [TestStubs.Project()]; + const project = TestStubs.Project(); const { organization, location, eventView, spanOperationBreakdownFilter, transactionName, - } = initialize(projects, {}, [ + } = initialize(project, {}, [ 'performance-events-page', 'performance-chart-interpolation', ]); @@ -203,6 +205,7 @@ describe('Transaction Summary Content', function () { location={location} organization={organization} eventView={eventView} + projectId={project.id} transactionName={transactionName} isLoading={false} totalValues={null} diff --git a/tests/js/spec/views/performance/transactionSummary/suspectSpans.spec.tsx b/tests/js/spec/views/performance/transactionSummary/suspectSpans.spec.tsx new file mode 100644 index 00000000000000..0414a835e471d6 --- /dev/null +++ b/tests/js/spec/views/performance/transactionSummary/suspectSpans.spec.tsx @@ -0,0 +1,98 @@ +import {initializeOrg} from 'sentry-test/initializeOrg'; +import {generateSuspectSpansResponse} from 'sentry-test/performance/initializePerformanceData'; +import { + act, + mountWithTheme, + screen, + // waitForElementToBeRemoved, +} from 'sentry-test/reactTestingLibrary'; + +import ProjectsStore from 'sentry/stores/projectsStore'; +import EventView from 'sentry/utils/discover/eventView'; +import SuspectSpans from 'sentry/views/performance/transactionSummary/transactionOverview/suspectSpans'; + +function initializeData({query} = {query: {}}) { + const features = ['performance-view', 'performance-suspect-spans-view']; + const organization = TestStubs.Organization({ + features, + projects: [TestStubs.Project()], + }); + const initialData = initializeOrg({ + organization, + router: { + location: { + query: { + transaction: 'Test Transaction', + project: '1', + ...query, + }, + }, + }, + }); + act(() => void ProjectsStore.loadInitialData(initialData.organization.projects)); + return { + ...initialData, + eventView: EventView.fromLocation(initialData.router.location), + }; +} + +describe('SuspectSpans', function () { + describe('With Span Data', function () { + beforeEach(function () { + MockApiClient.addMockResponse({ + url: '/organizations/org-slug/events-spans-performance/', + body: generateSuspectSpansResponse({ + examples: 1, + }), + }); + }); + + it('renders basic UI elements', async function () { + const initialData = initializeData(); + mountWithTheme( + , + {context: initialData.routerContext} + ); + + expect(await screen.findByText('Suspect Spans')).toBeInTheDocument(); + expect(await screen.findByText('View All Spans')).toBeInTheDocument(); + expect(await screen.findByText('Operation')).toBeInTheDocument(); + expect(await screen.findByText('Description')).toBeInTheDocument(); + expect(await screen.findByText('P75 Exclusive Time')).toBeInTheDocument(); + expect(await screen.findByText('Total Occurrences')).toBeInTheDocument(); + expect(await screen.findByText('Total Exclusive Time')).toBeInTheDocument(); + expect(await screen.findByText('Example Transaction')).toBeInTheDocument(); + }); + + // Due to the createHref being stubbed out (see link below), + // the anchors all have an empty href so we can't actually + // test this. + // + // https://github.com/getsentry/sentry/blob/28a2337ae902785d4d3e914c0ba484fa883cc17a/tests/js/setup.ts#L162 + // + // it('allows sorting by some columns', async function () { + // const initialData = initializeData(); + // mountWithTheme( + // , + // {context: initialData.routerContext} + // ); + + // await waitForElementToBeRemoved(() => screen.getByTestId('loading-indicator')); + // expect(screen.getByText('P75 Exclusive Time')).toHaveAttribute('href', null); + // expect(screen.getByText('Total Occurrences')).toHaveAttribute('href', null); + // expect(screen.getByText('Total Exclusive Time')).toHaveAttribute('href', null); + // }); + }); +});" 7fcea93972e47c343fa2851ce19236ca58bdfd45,2023-12-15 03:06:18,Ryan Albrecht,ref(replay-count): Refactor replay-count JS helpers to remove custom react context (#61660),False,Refactor replay-count JS helpers to remove custom react context (#61660),ref,"diff --git a/static/app/components/feedback/feedbackItem/feedbackItem.tsx b/static/app/components/feedback/feedbackItem/feedbackItem.tsx index 8f02fd91770fe5..1c988c25a1e469 100644 --- a/static/app/components/feedback/feedbackItem/feedbackItem.tsx +++ b/static/app/components/feedback/feedbackItem/feedbackItem.tsx @@ -29,7 +29,7 @@ import {space} from 'sentry/styles/space'; import type {Event, Group} from 'sentry/types'; import {GroupStatus} from 'sentry/types'; import type {FeedbackIssue} from 'sentry/utils/feedback/types'; -import {useReplayCountForFeedbacks} from 'sentry/utils/replayCount/replayCountForFeedbacks'; +import useReplayCountForFeedbacks from 'sentry/utils/replayCount/useReplayCountForFeedbacks'; import useCopyToClipboard from 'sentry/utils/useCopyToClipboard'; import useOrganization from 'sentry/utils/useOrganization'; import {normalizeUrl} from 'sentry/utils/withDomainRequired'; diff --git a/static/app/components/feedback/list/feedbackListItem.tsx b/static/app/components/feedback/list/feedbackListItem.tsx index 5e00f28e676a7d..261d285410594f 100644 --- a/static/app/components/feedback/list/feedbackListItem.tsx +++ b/static/app/components/feedback/list/feedbackListItem.tsx @@ -23,7 +23,7 @@ import {Group} from 'sentry/types/group'; import {trackAnalytics} from 'sentry/utils/analytics'; import {FeedbackIssue} from 'sentry/utils/feedback/types'; import {decodeScalar} from 'sentry/utils/queryString'; -import {useReplayCountForFeedbacks} from 'sentry/utils/replayCount/replayCountForFeedbacks'; +import useReplayCountForFeedbacks from 'sentry/utils/replayCount/useReplayCountForFeedbacks'; import {darkTheme, lightTheme} from 'sentry/utils/theme'; import useLocationQuery from 'sentry/utils/url/useLocationQuery'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/utils/api/useAggregatedQueryKeys.tsx b/static/app/utils/api/useAggregatedQueryKeys.tsx index d33db2bd733b5a..e41a0165d8733d 100644 --- a/static/app/utils/api/useAggregatedQueryKeys.tsx +++ b/static/app/utils/api/useAggregatedQueryKeys.tsx @@ -1,6 +1,8 @@ import {useCallback, useRef, useState} from 'react'; +import first from 'lodash/first'; import {ApiResult} from 'sentry/api'; +import {defined} from 'sentry/utils'; import {ApiQueryKey, fetchDataQuery, useQueryClient} from 'sentry/utils/queryClient'; import useApi from 'sentry/utils/useApi'; @@ -8,24 +10,29 @@ const BUFFER_WAIT_MS = 20; interface Props { /** - * Default data that goes into `useState` - */ - defaultData: Data; - - /** - * The queryKey reducer/generator. + * The queryKey reducer * * Takes the buffered ""aggregates"" and outputs an ApiQueryKey + * + * The returned key must have a stable url in the first index of the returned + * array. This is used as a cache id. */ - genQueryKey: (ids: ReadonlyArray) => ApiQueryKey; + getQueryKey: (ids: ReadonlyArray) => ApiQueryKey; /** * Data reducer, to integrate new requests with the previous state */ - reducer: (prev: Data, result: ApiResult) => Data; + responseReducer: (prev: undefined | Data, result: ApiResult) => Data; + + /** + * Maximun number of items to keep in the buffer before flushing + * + * Default: 50 + */ + bufferLimit?: number; /** - * Callback should an error happen while fetching or reducing the data + * Optional callback, should an error happen while fetching or reducing the data */ onError?: (error: Error) => void; } @@ -44,58 +51,98 @@ interface Props { * multiple ids. * * How it works: - * - The hook returns a method called `buffer(aggregates: Array)` and the + * - This hook returns a method called `buffer(aggregates: Array)` and the * value `data`. * - You will implement the props `getQueryKey(aggregates: Array)` which * takes the unique list of `aggregates` that have been passed into `buffer()`. - * Your `getQueryKey()` function will be invoked after `buffer()` has stopped - * being called for BUFFER_WAIT_MS, this is a debounce mechanic. - * - The new queryKey will be used to fetch some data - * - You will implement `reducer(prev: Data, result: ApiResult)` which combines - * `defaultData` with the data that was fetched with the queryKey. + * The returned queryKey must have a stable url as the first array item. + * - After after `buffer()` has stopped being called for BUFFER_WAIT_MS, or if + * bufferLimit items are queued, then `getQueryKey()` function will be called. + * - The new queryKey will be used to fetch some data. + * - You will implement `responseReducer(prev: Data, result: ApiResult)` which + * combines `defaultData` with the data that was fetched with the queryKey. */ export default function useAggregatedQueryKeys({ - defaultData, - genQueryKey, - reducer, + getQueryKey, onError, + responseReducer, + bufferLimit = 50, }: Props) { const api = useApi({persistInFlight: true}); const queryClient = useQueryClient(); + const cache = queryClient.getQueryCache(); - const buffered = useRef>(new Set()); - const inFlight = useRef>(new Set()); - const done = useRef>(new Set()); - const timer = useRef(null); + const key = first(getQueryKey([])); - const [data, setData] = useState(defaultData); + const [data, setData] = useState(() => + cache + .findAll({queryKey: [key]}) + .map(({queryKey}) => queryClient.getQueryData(queryKey)) + .filter(defined) + .reduce(responseReducer, undefined) + ); + + const timer = useRef(null); const fetchData = useCallback(async () => { - const aggregates = Array.from(buffered.current); + const allQueuedQueries = cache.findAll({ + queryKey: ['aggregate', key, 'queued'], + }); - buffered.current.clear(); - aggregates.forEach(id => inFlight.current.add(id)); + const selectedQueuedQueries = allQueuedQueries.slice(0, bufferLimit); + if (!selectedQueuedQueries.length) { + return; + } + + const queuedAggregates = selectedQueuedQueries.map( + ({queryKey}) => queryKey[3] as QueryKeyAggregate + ); try { - const result = await queryClient.fetchQuery({ - queryKey: genQueryKey(aggregates), + queryClient.removeQueries({ + queryKey: ['aggregate', key, 'queued'], + predicate: ({queryKey}) => + queuedAggregates.includes(queryKey[3] as QueryKeyAggregate), + }); + selectedQueuedQueries.forEach(({queryKey}) => { + const inFlightQueryKey = ['aggregate', key, 'inFlight', queryKey[3]]; + queryClient.setQueryData(inFlightQueryKey, true); + }); + + const promise = queryClient.fetchQuery({ + queryKey: getQueryKey(queuedAggregates), queryFn: fetchDataQuery(api), }); - setData(reducer(data, result)); + if (allQueuedQueries.length > selectedQueuedQueries.length) { + fetchData(); + } - aggregates.forEach(id => { - inFlight.current.delete(id); - done.current.add(id); + setData(responseReducer(data, await promise)); + + queryClient.removeQueries({ + queryKey: ['aggregate', key, 'inFlight'], + predicate: ({queryKey}) => + queuedAggregates.includes(queryKey[3] as QueryKeyAggregate), }); - } catch (error) { - aggregates.forEach(id => { - inFlight.current.delete(id); - buffered.current.add(id); + selectedQueuedQueries.forEach(({queryKey}) => { + const doneQueryKey = ['aggregate', key, 'done', queryKey[3]]; + queryClient.setQueryData(doneQueryKey, true); }); + } catch (error) { onError?.(error); } - }, [api, data, genQueryKey, queryClient, reducer, onError]); + }, [ + api, + bufferLimit, + cache, + data, + getQueryKey, + key, + onError, + queryClient, + responseReducer, + ]); const clearTimer = useCallback(() => { if (timer.current) { @@ -114,22 +161,27 @@ export default function useAggregatedQueryKeys({ const buffer = useCallback( (aggregates: ReadonlyArray) => { - let needsTimer = false; - for (const aggregate of aggregates) { - if ( - !buffered.current.has(aggregate) && - !inFlight.current.has(aggregate) && - !done.current.has(aggregate) - ) { - buffered.current.add(aggregate); - needsTimer = true; + const foundQueries = cache.findAll({ + queryKey: ['aggregate', key], + predicate: ({queryKey}) => aggregates.includes(queryKey[3] as QueryKeyAggregate), + }); + const foundAggregates = foundQueries.map(({queryKey}) => queryKey[3]); + + const newCacheKeys = aggregates + .filter(aggregate => !foundAggregates.includes(aggregate)) + .map(aggregate => ['aggregate', key, 'queued', aggregate]) + .map(queryKey => queryClient.setQueryData(queryKey, true)); + + if (newCacheKeys.length) { + if (foundQueries.length + newCacheKeys.length >= bufferLimit) { + clearTimer(); + fetchData(); + } else { + setTimer(); } } - if (needsTimer) { - setTimer(); - } }, - [setTimer] + [bufferLimit, cache, clearTimer, fetchData, key, queryClient, setTimer] ); return {data, buffer}; diff --git a/static/app/utils/replayCount/replayCountCache.tsx b/static/app/utils/replayCount/replayCountCache.tsx deleted file mode 100644 index 8fc461f41244b8..00000000000000 --- a/static/app/utils/replayCount/replayCountCache.tsx +++ /dev/null @@ -1,164 +0,0 @@ -import {createContext, ReactNode, useCallback, useContext, useMemo} from 'react'; - -import {ApiResult} from 'sentry/api'; -import {Organization} from 'sentry/types'; -import {defined} from 'sentry/utils'; -import useAggregatedQueryKeys from 'sentry/utils/api/useAggregatedQueryKeys'; -import {ApiQueryKey, useQueryClient} from 'sentry/utils/queryClient'; -import useOrganization from 'sentry/utils/useOrganization'; - -interface QueryKeyGenProps { - dataSource: string; - fieldName: string; - organization: Organization; - statsPeriod: string; -} - -interface Props { - children: ReactNode; - queryKeyGenProps: QueryKeyGenProps; -} - -type CountValue = undefined | number; -type ExistsValue = undefined | boolean; -type CountState = Record; -type ExistsState = Record; - -interface TContext { - getMany: (ids: readonly string[]) => CountState; - getOne: (id: string) => CountValue; - hasMany: (ids: readonly string[]) => ExistsState; - hasOne: (id: string) => ExistsValue; -} - -const DEFAULT_CONTEXT: TContext = { - getMany: () => ({}), - getOne: () => undefined, - hasMany: () => ({}), - hasOne: () => undefined, -}; - -const ReplayCacheCountContext = createContext(DEFAULT_CONTEXT); - -function queryKeyGen({ - dataSource, - fieldName, - organization, - statsPeriod, -}: QueryKeyGenProps) { - return (ids: readonly string[]): ApiQueryKey => [ - `/organizations/${organization.slug}/replay-count/`, - { - query: { - data_source: dataSource, - project: -1, - statsPeriod, - query: `${fieldName}:[${ids.join(',')}]`, - }, - }, - ]; -} - -function filterKeysInList(obj: Record, list: readonly string[]) { - return Object.fromEntries(Object.entries(obj).filter(([key, _value]) => key in list)); -} - -function boolIfDefined(val: undefined | unknown) { - return val === undefined ? undefined : Boolean(val); -} - -function mapToBool(obj: Record): Record { - return Object.fromEntries( - Object.entries(obj).map(([key, value]) => [key, Boolean(value)]) - ); -} - -function reducer(data: CountState, response: ApiResult) { - const [newData] = response; - return {...data, ...newData}; -} - -function useDefaultData() { - const organization = useOrganization(); - const queryClient = useQueryClient(); - - return useMemo(() => { - const cache = queryClient.getQueryCache(); - const queries = cache.findAll({ - predicate: ({queryKey}) => { - const url = queryKey[0]; - return url === `/organizations/${organization.slug}/replay-count/`; - }, - }); - const allQueryData = queries - .map(({queryKey}) => queryClient.getQueryData(queryKey)) - .filter(defined); - return allQueryData.reduce(reducer, {}); - }, [organization, queryClient]); -} - -/** - * Base ReactContext for fetching and reducing data from /replay-count/ - * - * Don't use this directly! - * Import one of the configured helpers instead: - * - `` & `useReplayExists()` - * - `` & `useReplayCountForIssues()` - * - `` & `useReplayCountForTransactions()` - * - `` & `useReplayCountForFeedbacks()` - * - * @private - */ -export function ReplayCountCache({children, queryKeyGenProps}: Props) { - const defaultData = useDefaultData(); - const cache = useAggregatedQueryKeys({ - genQueryKey: queryKeyGen(queryKeyGenProps), - reducer, - defaultData, - }); - - const getMany = useCallback( - (ids: readonly string[]) => { - cache.buffer(ids); - return filterKeysInList(cache.data, ids); - }, - [cache] - ); - - const getOne = useCallback( - (id: string) => { - cache.buffer([id]); - return cache.data[id]; - }, - [cache] - ); - - const hasMany = useCallback( - (ids: readonly string[]) => mapToBool(getMany(ids)), - [getMany] - ); - - const hasOne = useCallback((id: string) => boolIfDefined(getOne(id)), [getOne]); - - return ( - - {children} - - ); -} - -/** - * Base ReactContext for fetching and reducing data from /replay-count/ - * - * Don't use this directly! - * Import one of the configured helpers instead: - * - `` & `useReplayExists()` - * - `` & `useReplayCountForIssues()` - * - `` & `useReplayCountForTransactions()` - * - `` & `useReplayCountForFeedbacks()` - * - * @private - */ -export function useReplayCount() { - return useContext(ReplayCacheCountContext); -} diff --git a/static/app/utils/replayCount/replayCountForFeedbacks.tsx b/static/app/utils/replayCount/replayCountForFeedbacks.tsx deleted file mode 100644 index 2597b661a1432f..00000000000000 --- a/static/app/utils/replayCount/replayCountForFeedbacks.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import {ReactNode} from 'react'; - -import { - ReplayCountCache, - useReplayCount, -} from 'sentry/utils/replayCount/replayCountCache'; -import useOrganization from 'sentry/utils/useOrganization'; - -interface Props { - children: ReactNode; -} - -/** - * React context for whether feedback(s) have a replay assiciated or not. - * - * You can query & read from the context via `useReplayCountForFeedbacks()`. - */ -export function ReplayCountForFeedbacks({children}: Props) { - const organization = useOrganization(); - - return ( - - {children} - - ); -} - -/** - * Query results for whether a Feedback has replays associated. - */ -export function useReplayCountForFeedbacks() { - const {hasOne, hasMany} = useReplayCount(); - - return { - feedbackHasReplay: hasOne, - feedbacksHaveReplay: hasMany, - }; -} diff --git a/static/app/utils/replayCount/replayCountForIssues.tsx b/static/app/utils/replayCount/replayCountForIssues.tsx deleted file mode 100644 index 1bfff5fb617d0c..00000000000000 --- a/static/app/utils/replayCount/replayCountForIssues.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import {ReactNode} from 'react'; - -import { - ReplayCountCache, - useReplayCount, -} from 'sentry/utils/replayCount/replayCountCache'; -import useOrganization from 'sentry/utils/useOrganization'; - -interface Props { - children: ReactNode; -} - -/** - * React context for whether issue(s)/group(s) have a replay assiciated or not. - * - * You can query & read from the context via `useReplayCountForIssues()`. - */ -export function ReplayCountForIssues({children}: Props) { - const organization = useOrganization(); - - return ( - - {children} - - ); -} - -/** - * Query results for whether an Issue/Group has replays associated. - */ -export function useReplayCountForIssues() { - const {getOne, getMany, hasOne, hasMany} = useReplayCount(); - - return { - getReplayCountForIssue: getOne, - getReplayCountForIssues: getMany, - issueHasReplay: hasOne, - issuesHaveReplay: hasMany, - }; -} diff --git a/static/app/utils/replayCount/replayCountForTransactions.tsx b/static/app/utils/replayCount/replayCountForTransactions.tsx deleted file mode 100644 index d657fe2f2cebd1..00000000000000 --- a/static/app/utils/replayCount/replayCountForTransactions.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import {ReactNode} from 'react'; - -import { - ReplayCountCache, - useReplayCount, -} from 'sentry/utils/replayCount/replayCountCache'; -import useOrganization from 'sentry/utils/useOrganization'; - -interface Props { - children: ReactNode; -} - -/** - * React context for whether transactions(s) have a replay assiciated or not. - * - * You can query & read from the context via `useReplayCountForTransactions()`. - */ -export function ReplayCountForTransactions({children}: Props) { - const organization = useOrganization(); - - return ( - - {children} - - ); -} - -/** - * Query results for whether a Transaction has replays associated. - */ -export function useReplayCountForTransactions() { - const {getOne, getMany, hasOne, hasMany} = useReplayCount(); - - return { - getReplayCountForTransaction: getOne, - getReplayCountForTransactions: getMany, - transactionHasReplay: hasOne, - transactionsHaveReplay: hasMany, - }; -} diff --git a/static/app/utils/replayCount/replayExists.tsx b/static/app/utils/replayCount/replayExists.tsx deleted file mode 100644 index 1018796c8ec229..00000000000000 --- a/static/app/utils/replayCount/replayExists.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import {ReactNode} from 'react'; - -import { - ReplayCountCache, - useReplayCount, -} from 'sentry/utils/replayCount/replayCountCache'; -import useOrganization from 'sentry/utils/useOrganization'; - -interface Props { - children: ReactNode; -} - -/** - * React context for whether replay(s) exist or not. - * - * You can query & read from the context via `useReplayExists()`. - */ -export function ReplayExists({children}: Props) { - const organization = useOrganization(); - - return ( - - {children} - - ); -} - -/** - * Query results for whether a given replayId exists in the database (not deleted, etc) - */ -export function useReplayExists() { - const {hasOne, hasMany} = useReplayCount(); - - return { - replayExists: hasOne, - replaysExist: hasMany, - }; -} diff --git a/static/app/utils/replayCount/useReplayCount.tsx b/static/app/utils/replayCount/useReplayCount.tsx new file mode 100644 index 00000000000000..958352cad9c03e --- /dev/null +++ b/static/app/utils/replayCount/useReplayCount.tsx @@ -0,0 +1,98 @@ +import {useCallback} from 'react'; + +import {ApiResult} from 'sentry/api'; +import {Organization} from 'sentry/types'; +import useAggregatedQueryKeys from 'sentry/utils/api/useAggregatedQueryKeys'; +import {ApiQueryKey} from 'sentry/utils/queryClient'; + +interface Props { + bufferLimit: number; + dataSource: string; + fieldName: string; + organization: Organization; + statsPeriod: string; +} + +type CountValue = undefined | number; +type CountState = Record; + +function filterKeysInList(obj: Record, list: readonly string[]) { + return Object.fromEntries(Object.entries(obj).filter(([key, _value]) => key in list)); +} + +function boolIfDefined(val: undefined | unknown) { + return val === undefined ? undefined : Boolean(val); +} + +function mapToBool(obj: Record): Record { + return Object.fromEntries( + Object.entries(obj).map(([key, value]) => [key, Boolean(value)]) + ); +} + +/** + * Base hook for fetching and reducing data from /replay-count/ + * + * Don't use this directly! + * Import one of the configured helpers instead: + * - `useReplayExists()` + * - `useReplayCountForIssues()` + * - `useReplayCountForTransactions()` + * - `useReplayCountForFeedbacks()` + * + * @private + */ +export default function useReplayCount({ + bufferLimit, + dataSource, + fieldName, + organization, + statsPeriod, +}: Props) { + const cache = useAggregatedQueryKeys({ + bufferLimit, + getQueryKey: useCallback( + (ids: readonly string[]): ApiQueryKey => [ + `/organizations/${organization.slug}/replay-count/`, + { + query: { + data_source: dataSource, + project: -1, + statsPeriod, + query: `${fieldName}:[${ids.join(',')}]`, + }, + }, + ], + [dataSource, fieldName, organization, statsPeriod] + ), + responseReducer: useCallback( + (data: undefined | CountState, response: ApiResult) => ({...data, ...response[0]}), + [] + ), + }); + + const getMany = useCallback( + (ids: readonly string[]) => { + cache.buffer(ids); + return filterKeysInList(cache.data ?? {}, ids); + }, + [cache] + ); + + const getOne = useCallback( + (id: string) => { + cache.buffer([id]); + return cache.data?.[id]; + }, + [cache] + ); + + const hasMany = useCallback( + (ids: readonly string[]) => mapToBool(getMany(ids)), + [getMany] + ); + + const hasOne = useCallback((id: string) => boolIfDefined(getOne(id)), [getOne]); + + return {getOne, getMany, hasOne, hasMany}; +} diff --git a/static/app/utils/replayCount/useReplayCountForFeedbacks.tsx b/static/app/utils/replayCount/useReplayCountForFeedbacks.tsx new file mode 100644 index 00000000000000..e1c32fe996d76b --- /dev/null +++ b/static/app/utils/replayCount/useReplayCountForFeedbacks.tsx @@ -0,0 +1,21 @@ +import useReplayCount from 'sentry/utils/replayCount/useReplayCount'; +import useOrganization from 'sentry/utils/useOrganization'; + +/** + * Query results for whether a Feedback has replays associated. + */ +export default function useReplayCountForFeedbacks() { + const organization = useOrganization(); + const {hasOne, hasMany} = useReplayCount({ + bufferLimit: 25, + dataSource: 'search_issues', + fieldName: 'issue.id', + organization, + statsPeriod: '90d', + }); + + return { + feedbackHasReplay: hasOne, + feedbacksHaveReplay: hasMany, + }; +} diff --git a/static/app/utils/replayCount/useReplayCountForIssues.tsx b/static/app/utils/replayCount/useReplayCountForIssues.tsx new file mode 100644 index 00000000000000..eb6c1769e46572 --- /dev/null +++ b/static/app/utils/replayCount/useReplayCountForIssues.tsx @@ -0,0 +1,23 @@ +import useReplayCount from 'sentry/utils/replayCount/useReplayCount'; +import useOrganization from 'sentry/utils/useOrganization'; + +/** + * Query results for whether an Issue/Group has replays associated. + */ +export default function useReplayCountForIssues() { + const organization = useOrganization(); + const {getOne, getMany, hasOne, hasMany} = useReplayCount({ + bufferLimit: 25, + dataSource: 'discover', + fieldName: 'issue.id', + organization, + statsPeriod: '90d', + }); + + return { + getReplayCountForIssue: getOne, + getReplayCountForIssues: getMany, + issueHasReplay: hasOne, + issuesHaveReplay: hasMany, + }; +} diff --git a/static/app/utils/replayCount/useReplayCountForTransactions.tsx b/static/app/utils/replayCount/useReplayCountForTransactions.tsx new file mode 100644 index 00000000000000..819ac22efdec42 --- /dev/null +++ b/static/app/utils/replayCount/useReplayCountForTransactions.tsx @@ -0,0 +1,23 @@ +import useReplayCount from 'sentry/utils/replayCount/useReplayCount'; +import useOrganization from 'sentry/utils/useOrganization'; + +/** + * Query results for whether a Transaction has replays associated. + */ +export default function useReplayCountForTransactions() { + const organization = useOrganization(); + const {getOne, getMany, hasOne, hasMany} = useReplayCount({ + bufferLimit: 25, + dataSource: 'discover', + fieldName: 'transaction', + organization, + statsPeriod: '90d', + }); + + return { + getReplayCountForTransaction: getOne, + getReplayCountForTransactions: getMany, + transactionHasReplay: hasOne, + transactionsHaveReplay: hasMany, + }; +} diff --git a/static/app/utils/replayCount/useReplayExists.tsx b/static/app/utils/replayCount/useReplayExists.tsx new file mode 100644 index 00000000000000..802bfb060fac58 --- /dev/null +++ b/static/app/utils/replayCount/useReplayExists.tsx @@ -0,0 +1,21 @@ +import useReplayCount from 'sentry/utils/replayCount/useReplayCount'; +import useOrganization from 'sentry/utils/useOrganization'; + +/** + * Query results for whether a given replayId exists in the database (not deleted, etc) + */ +export default function useReplayExists() { + const organization = useOrganization(); + const {hasOne, hasMany} = useReplayCount({ + bufferLimit: 100, + dataSource: 'discover', + fieldName: 'replay_id', + organization, + statsPeriod: '90d', + }); + + return { + replayExists: hasOne, + replaysExist: hasMany, + }; +} diff --git a/static/app/views/feedback/feedbackListPage.tsx b/static/app/views/feedback/feedbackListPage.tsx index dc7d26e78e5302..50ea2dfb9856c2 100644 --- a/static/app/views/feedback/feedbackListPage.tsx +++ b/static/app/views/feedback/feedbackListPage.tsx @@ -19,7 +19,6 @@ import {PageHeadingQuestionTooltip} from 'sentry/components/pageHeadingQuestionT import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import {ReplayCountForFeedbacks} from 'sentry/utils/replayCount/replayCountForFeedbacks'; import useOrganization from 'sentry/utils/useOrganization'; import FluidHeight from 'sentry/views/replays/detail/layout/fluidHeight'; @@ -36,46 +35,44 @@ export default function FeedbackListPage({}: Props) { - - - - - {t('User Feedback')} - - - - - - - - - - - - {hasSetupOneFeedback || hasSlug ? ( - - - - - - - - - - ) : ( - - - + + + + {t('User Feedback')} + - - - + docsUrl=""https://docs.sentry.io/product/user-feedback/"" + /> + + + + + + + + + + + {hasSetupOneFeedback || hasSlug ? ( + + + + + + + + + + ) : ( + + + + )} + + + " 5a712c16a280c535cd18ab416fa5dcf7e8d425fc,2024-07-11 21:49:13,Malachi Willey,feat(query-builder): Add feedback button (#74116),False,Add feedback button (#74116),feat,"diff --git a/static/app/components/feedback/widget/useFeedback.tsx b/static/app/components/feedback/widget/useFeedback.tsx index 502d8f400ff4ee..1f46ae58a8de09 100644 --- a/static/app/components/feedback/widget/useFeedback.tsx +++ b/static/app/components/feedback/widget/useFeedback.tsx @@ -8,12 +8,13 @@ import useAsyncSDKIntegrationStore from 'sentry/views/app/asyncSDKIntegrationPro export type FeedbackIntegration = NonNullable>; -export type UseFeedbackOptions = { - formTitle?: string; - messagePlaceholder?: string; -}; +export type UseFeedbackOptions = Parameters[0]; -export function useFeedback({formTitle, messagePlaceholder}: UseFeedbackOptions) { +export function useFeedback({ + formTitle, + messagePlaceholder, + tags, +}: NonNullable) { const config = useLegacyStore(ConfigStore); const {state} = useAsyncSDKIntegrationStore(); @@ -26,8 +27,9 @@ export function useFeedback({formTitle, messagePlaceholder}: UseFeedbackOptions) submitButtonLabel: t('Send Feedback'), messagePlaceholder: messagePlaceholder ?? t('What did you expect?'), formTitle: formTitle ?? t('Give Feedback'), + tags, }; - }, [config.theme, formTitle, messagePlaceholder]); + }, [config.theme, formTitle, messagePlaceholder, tags]); return {feedback, options}; } diff --git a/static/app/components/searchQueryBuilder/combobox.tsx b/static/app/components/searchQueryBuilder/combobox.tsx index e9dd6a96898da4..b67c5072292098 100644 --- a/static/app/components/searchQueryBuilder/combobox.tsx +++ b/static/app/components/searchQueryBuilder/combobox.tsx @@ -34,11 +34,14 @@ import { import {GrowingInput} from 'sentry/components/growingInput'; import LoadingIndicator from 'sentry/components/loadingIndicator'; import {Overlay} from 'sentry/components/overlay'; +import {useSearchQueryBuilder} from 'sentry/components/searchQueryBuilder/context'; import type {Token, TokenResult} from 'sentry/components/searchSyntax/parser'; +import {IconMegaphone} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; import {defined} from 'sentry/utils'; import mergeRefs from 'sentry/utils/mergeRefs'; +import {useFeedbackForm} from 'sentry/utils/useFeedbackForm'; import useOverlay from 'sentry/utils/useOverlay'; import usePrevious from 'sentry/utils/usePrevious'; @@ -273,6 +276,35 @@ function ListBoxSectionButton({ ); } +function FeedbackFooter() { + const {searchSource} = useSearchQueryBuilder(); + const openForm = useFeedbackForm(); + + if (!openForm) { + return null; + } + + return ( + + + + ); +} + function SectionedListBox>({ popoverRef, listBoxRef, @@ -344,6 +376,7 @@ function SectionedListBox>({ size=""sm"" /> + ) : null} @@ -705,10 +738,23 @@ const SectionedOverlay = styled(Overlay)` overflow: hidden; display: grid; grid-template-columns: 120px 240px; + grid-template-rows: 1fr auto; + grid-template-areas: + 'left right' + 'footer footer'; height: 400px; width: 360px; `; +const SectionedOverlayFooter = styled('div')` + display: flex; + align-items: center; + justify-content: flex-end; + grid-area: footer; + padding: ${space(1)}; + border-top: 1px solid ${p => p.theme.innerBorder}; +`; + const SectionedListBoxPane = styled('div')` overflow-y: auto; `; diff --git a/static/app/utils/useFeedbackForm.spec.tsx b/static/app/utils/useFeedbackForm.spec.tsx index a62305ffa97548..fe4cc90b2157a7 100644 --- a/static/app/utils/useFeedbackForm.spec.tsx +++ b/static/app/utils/useFeedbackForm.spec.tsx @@ -20,6 +20,7 @@ const defaultOptions = { submitButtonLabel: '', messagePlaceholder: '', formTitle: '', + tags: {}, }; describe('useFeedbackForm', function () {" 74dc91a7b6451e80aad42ed8aca658f644a35c9d,2025-01-25 00:30:36,Snigdha Sharma,feat(metric-issues): Show a more accurate last seen value (#83977),False,Show a more accurate last seen value (#83977),feat,"diff --git a/static/app/types/group.tsx b/static/app/types/group.tsx index a607bfd82a91c7..8579657062f97e 100644 --- a/static/app/types/group.tsx +++ b/static/app/types/group.tsx @@ -848,8 +848,8 @@ export interface GroupOpenPeriod { duration: string; end: string; isOpen: boolean; + lastChecked: string; start: string; - lastChecked?: string; } export interface GroupReprocessing extends BaseGroup, GroupStats { diff --git a/static/app/utils/issueTypeConfig/index.tsx b/static/app/utils/issueTypeConfig/index.tsx index 47a77522a4d57d..35ca52fe259dcb 100644 --- a/static/app/utils/issueTypeConfig/index.tsx +++ b/static/app/utils/issueTypeConfig/index.tsx @@ -65,6 +65,7 @@ const BASE_CONFIG: IssueTypeConfig = { resources: null, usesIssuePlatform: true, issueSummary: {enabled: false}, + useOpenPeriodChecks: false, }; const issueTypeConfig: Config = { diff --git a/static/app/utils/issueTypeConfig/metricIssueConfig.tsx b/static/app/utils/issueTypeConfig/metricIssueConfig.tsx index 669b1b40783fb1..4edef9985e3726 100644 --- a/static/app/utils/issueTypeConfig/metricIssueConfig.tsx +++ b/static/app/utils/issueTypeConfig/metricIssueConfig.tsx @@ -28,6 +28,7 @@ const metricIssueConfig: IssueCategoryConfigMapping = { showOpenPeriods: true, userFeedback: {enabled: false}, usesIssuePlatform: true, + useOpenPeriodChecks: true, stats: {enabled: false}, tags: {enabled: false}, tagsTab: {enabled: false}, diff --git a/static/app/utils/issueTypeConfig/types.tsx b/static/app/utils/issueTypeConfig/types.tsx index b090fd92a85d73..7a63223b104a9a 100644 --- a/static/app/utils/issueTypeConfig/types.tsx +++ b/static/app/utils/issueTypeConfig/types.tsx @@ -132,6 +132,10 @@ export type IssueTypeConfig = { * Is the Tags tab show for this issue */ tagsTab: DisabledWithReasonConfig; + /** + * Whether to use open periods for the last checked date + */ + useOpenPeriodChecks: boolean; /** * Is the User Feedback tab shown for this issue */ diff --git a/static/app/views/issueDetails/streamline/sidebar/firstLastSeenSection.tsx b/static/app/views/issueDetails/streamline/sidebar/firstLastSeenSection.tsx index efa1fac52a554a..522e3481541c05 100644 --- a/static/app/views/issueDetails/streamline/sidebar/firstLastSeenSection.tsx +++ b/static/app/views/issueDetails/streamline/sidebar/firstLastSeenSection.tsx @@ -9,6 +9,7 @@ import {space} from 'sentry/styles/space'; import type {Group} from 'sentry/types/group'; import type {Project} from 'sentry/types/project'; import type {Release} from 'sentry/types/release'; +import {getConfigForIssueType} from 'sentry/utils/issueTypeConfig'; import {useApiQuery} from 'sentry/utils/queryClient'; import useOrganization from 'sentry/utils/useOrganization'; import {useFetchAllEnvsGroupData} from 'sentry/views/issueDetails/groupSidebar'; @@ -21,6 +22,7 @@ interface GroupRelease { export default function FirstLastSeenSection({group}: {group: Group}) { const organization = useOrganization(); const {project} = group; + const issueTypeConfig = getConfigForIssueType(group, group.project); const {data: allEnvironments} = useFetchAllEnvsGroupData(organization, group); const {data: groupReleaseData} = useApiQuery( @@ -31,6 +33,14 @@ export default function FirstLastSeenSection({group}: {group: Group}) { } ); + const lastSeen = issueTypeConfig.useOpenPeriodChecks + ? group.openPeriods?.[0]?.lastChecked ?? group.lastSeen + : group.lastSeen; + + const dateGlobal = issueTypeConfig.useOpenPeriodChecks + ? lastSeen + : allEnvironments?.lastSeen ?? lastSeen; + return (
@@ -38,8 +48,8 @@ export default function FirstLastSeenSection({group}: {group: Group}) { {t('Last seen')} {group.lastSeen ? ( { stats: {enabled: false}, tags: {enabled: false}, tagsTab: {enabled: false}, + useOpenPeriodChecks: false, userFeedback: {enabled: false}, usesIssuePlatform: false, });" d870e468160e81746d2e1816a01e32e0c67528ae,2019-12-17 01:05:48,Billy Vong,fix(ui): Re-arrange `
` footer buttons (#16097),False,Re-arrange `` footer buttons (#16097),fix,"diff --git a/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx b/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx index 480e304a18f618..f595f8fd010e62 100644 --- a/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx +++ b/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx @@ -11,6 +11,7 @@ import FormModel, { FieldValue, } from 'app/views/settings/components/forms/model'; import Panel from 'app/components/panels/panel'; +import space from 'app/styles/space'; type Data = {}; @@ -219,38 +220,41 @@ export default class Form extends React.Component { style={footerStyle} saveOnBlur={saveOnBlur} > - - {() => ( - + {extraButton} + + {onCancel && ( + + {() => ( + + )} + )} - - {onCancel && ( {() => ( )} - )} - {extraButton} + )} @@ -259,7 +263,8 @@ export default class Form extends React.Component { } const StyledFooter = styled('div')<{saveOnBlur?: boolean}>` - text-align: right; + display: flex; + justify-content: flex-end; margin-top: 25px; border-top: 1px solid #e9ebec; background: none; @@ -286,4 +291,12 @@ const StyledFooter = styled('div')<{saveOnBlur?: boolean}>` `}; `; +const DefaultButtons = styled('div')` + display: grid; + grid-gap: ${space(1)}; + grid-auto-flow: column; + justify-content: flex-end; + flex: 1; +`; + export {FieldValue}; diff --git a/tests/js/spec/components/forms/__snapshots__/formField.spec.jsx.snap b/tests/js/spec/components/forms/__snapshots__/formField.spec.jsx.snap index 6b302be3a5d108..0dbe36401da66b 100644 --- a/tests/js/spec/components/forms/__snapshots__/formField.spec.jsx.snap +++ b/tests/js/spec/components/forms/__snapshots__/formField.spec.jsx.snap @@ -339,67 +339,73 @@ exports[`FormField + model renders with Form 1`] = ` saveOnBlur={false} >
- - - - - - + + + Save Changes + + + + + + + + +
+
diff --git a/tests/js/spec/components/forms/__snapshots__/tableField.spec.jsx.snap b/tests/js/spec/components/forms/__snapshots__/tableField.spec.jsx.snap index 3acd48e2510c50..61486e6b4d16a0 100644 --- a/tests/js/spec/components/forms/__snapshots__/tableField.spec.jsx.snap +++ b/tests/js/spec/components/forms/__snapshots__/tableField.spec.jsx.snap @@ -500,67 +500,73 @@ exports[`TableField renders renders with form context 1`] = ` saveOnBlur={false} >
- - - - - - + + + Save Changes + + + + + + + + +
+
" 2af25d2ad1a739968e9dcd2a2ce4efde66231096,2024-07-25 19:15:47,anthony sottile,ref: unify signature of notify(...) (#74903),False,unify signature of notify(...) (#74903),ref,"diff --git a/src/sentry/plugins/bases/notify.py b/src/sentry/plugins/bases/notify.py index 17d3319196bf0b..47bfd767c34fb7 100644 --- a/src/sentry/plugins/bases/notify.py +++ b/src/sentry/plugins/bases/notify.py @@ -10,8 +10,9 @@ from sentry.integrations.types import ExternalProviders from sentry.notifications.services.service import notifications_service from sentry.notifications.types import NotificationSettingEnum -from sentry.plugins.base import Notification, Plugin +from sentry.plugins.base import Plugin from sentry.plugins.base.configuration import react_plugin_config +from sentry.plugins.base.structs import Notification from sentry.shared_integrations.exceptions import ApiError from sentry.types.actor import Actor, ActorType @@ -51,7 +52,7 @@ def configure(self, project, request): def get_plugin_type(self): return ""notification"" - def notify(self, notification, raise_exception=False): + def notify(self, notification: Notification, raise_exception: bool = False) -> None: """""" This calls the notify_users method of the plugin. Normally this method eats the error and logs it but if we @@ -60,7 +61,7 @@ def notify(self, notification, raise_exception=False): """""" event = notification.event try: - return self.notify_users( + self.notify_users( event.group, event, triggering_rules=[r.label for r in notification.rules] ) except ( @@ -82,7 +83,6 @@ def notify(self, notification, raise_exception=False): ) if raise_exception: raise - return False def rule_notify(self, event, futures): rules = [] @@ -180,16 +180,16 @@ def should_notify(self, group, event): return True - def test_configuration(self, project): + def test_configuration(self, project) -> None: from sentry.utils.samples import create_sample_event event = create_sample_event(project, platform=""python"") notification = Notification(event=event) - return self.notify(notification, raise_exception=True) + self.notify(notification, raise_exception=True) def test_configuration_and_get_test_results(self, project): try: - test_results = self.test_configuration(project) + self.test_configuration(project) except Exception as exc: if isinstance(exc, HTTPError) and hasattr(exc.response, ""text""): test_results = f""{exc}\n{exc.response.text[:256]}"" @@ -202,7 +202,7 @@ def test_configuration_and_get_test_results(self, project): test_results = ( ""There was an internal error with the Plugin, %s"" % str(exc)[:256] ) - if not test_results: + else: test_results = ""No errors returned"" return test_results diff --git a/src/sentry_plugins/pushover/plugin.py b/src/sentry_plugins/pushover/plugin.py index fb775e343c2f38..224c73051166c2 100644 --- a/src/sentry_plugins/pushover/plugin.py +++ b/src/sentry_plugins/pushover/plugin.py @@ -1,5 +1,6 @@ from sentry.exceptions import PluginError from sentry.integrations.base import FeatureDescription, IntegrationFeatures +from sentry.plugins.base.structs import Notification from sentry.plugins.bases.notify import NotifyPlugin from sentry_plugins.base import CorePluginMixin from sentry_plugins.utils import get_secret_field_config @@ -106,7 +107,7 @@ def error_message_from_json(self, data): return "" "".join(errors) return ""unknown error"" - def notify(self, notification, **kwargs): + def notify(self, notification: Notification, raise_exception: bool = False) -> None: event = notification.event group = event.group project = group.project diff --git a/src/sentry_plugins/slack/plugin.py b/src/sentry_plugins/slack/plugin.py index 0f342ced675b50..d75a2020d7851a 100644 --- a/src/sentry_plugins/slack/plugin.py +++ b/src/sentry_plugins/slack/plugin.py @@ -3,7 +3,7 @@ from sentry import tagstore from sentry.integrations.base import FeatureDescription, IntegrationFeatures from sentry.integrations.slack.message_builder import LEVEL_TO_COLOR -from sentry.plugins.base import Notification +from sentry.plugins.base.structs import Notification from sentry.plugins.bases import notify from sentry.shared_integrations.exceptions import ApiError from sentry.utils import json diff --git a/tests/sentry/plugins/bases/test_notify.py b/tests/sentry/plugins/bases/test_notify.py index 228f6e40676b9b..208add613aae84 100644 --- a/tests/sentry/plugins/bases/test_notify.py +++ b/tests/sentry/plugins/bases/test_notify.py @@ -56,7 +56,7 @@ def test_notify_failure(self): notification = Notification(event) with mock.patch.object(DummyNotificationPlugin, ""notify_users"", side_effect=err): - assert n.notify(notification) is False + n.notify(notification) # does not raise! def test_test_configuration_and_get_test_results(self): errors = (" 542484c0cd71625e62e086f3f7c5aaf85360f724,2022-02-25 04:11:26,Marcos Gaeta,fix(plugins): Silence error (#32042),False,Silence error (#32042),fix,"diff --git a/src/sentry/plugins/bases/notify.py b/src/sentry/plugins/bases/notify.py index 43b742ade4f67c..dd3193da4e484f 100644 --- a/src/sentry/plugins/bases/notify.py +++ b/src/sentry/plugins/bases/notify.py @@ -7,7 +7,7 @@ from requests.exceptions import HTTPError, SSLError from sentry import digests, ratelimits -from sentry.exceptions import PluginError +from sentry.exceptions import InvalidIdentity, PluginError from sentry.models import NotificationSetting from sentry.plugins.base import Notification, Plugin from sentry.plugins.base.configuration import react_plugin_config @@ -62,7 +62,14 @@ def notify(self, notification, raise_exception=False): return self.notify_users( event.group, event, triggering_rules=[r.label for r in notification.rules] ) - except (SSLError, HTTPError, ApiError, PluginError, UrllibHTTPError) as err: + except ( + ApiError, + HTTPError, + InvalidIdentity, + PluginError, + SSLError, + UrllibHTTPError, + ) as err: self.logger.info( ""notification-plugin.notify-failed"", extra={" 98b71a802d1232650f3324a278222f50f50fa8e9,2024-04-16 21:58:01,Armen Zambrano G,feat(related_issues): Use new data shape from endpoint (#68985),False,Use new data shape from endpoint (#68985),feat,"diff --git a/static/app/views/issueDetails/groupRelatedIssues/index.spec.tsx b/static/app/views/issueDetails/groupRelatedIssues/index.spec.tsx index 6ed15170f32a27..34abf2bb109824 100644 --- a/static/app/views/issueDetails/groupRelatedIssues/index.spec.tsx +++ b/static/app/views/issueDetails/groupRelatedIssues/index.spec.tsx @@ -29,7 +29,14 @@ describe('Related Issues View', function () { }); relatedIssuesMock = MockApiClient.addMockResponse({ url: `/issues/${groupId}/related-issues/`, - body: {same_root_cause: [group1, group2]}, + body: { + data: [ + { + type: 'same_root_cause', + data: [group1, group2], + }, + ], + }, }); issuesInfoMock = MockApiClient.addMockResponse({ url: orgIssuesEndpoint, diff --git a/static/app/views/issueDetails/groupRelatedIssues/index.tsx b/static/app/views/issueDetails/groupRelatedIssues/index.tsx index e32880f6e9226a..76a14b03236cda 100644 --- a/static/app/views/issueDetails/groupRelatedIssues/index.tsx +++ b/static/app/views/issueDetails/groupRelatedIssues/index.tsx @@ -20,7 +20,12 @@ type RouteParams = { type Props = RouteComponentProps; type RelatedIssuesResponse = { - same_root_cause: number[]; + data: [ + { + data: number[]; + type: string; + }, + ]; }; function GroupRelatedIssues({params}: Props) { @@ -39,11 +44,13 @@ function GroupRelatedIssues({params}: Props) { staleTime: 0, }); + const sameRootCauseIssues = relatedIssues?.data + .filter(item => item.type === 'same_root_cause') + .map(item => item.data); // If the group we're looking related issues for shows up in the table, - // it will trigger a bug in getGroupReprocessingStatus because activites would be empty - const groups = relatedIssues?.same_root_cause - ?.filter(id => id.toString() !== groupId) - ?.join(','); + // it will trigger a bug in getGroupReprocessingStatus because activites would be empty, + // thus, we excude it from the list of related issues + const groups = sameRootCauseIssues?.filter(id => id.toString() !== groupId)?.join(','); return ( " a20f0cb56b4ade7998951e225bb936f5cfb1d9c0,2024-01-23 02:09:57,Seiji Chew,ref(superuser): Extract superuser exception from permission layer (#63541),False,Extract superuser exception from permission layer (#63541),ref,"diff --git a/src/sentry/api/base.py b/src/sentry/api/base.py index ac6063d4be3904..488879caacb560 100644 --- a/src/sentry/api/base.py +++ b/src/sentry/api/base.py @@ -24,6 +24,7 @@ from sentry import analytics, options, tsdb from sentry.api.api_owners import ApiOwner from sentry.api.api_publish_status import ApiPublishStatus +from sentry.api.exceptions import SuperuserRequired from sentry.apidocs.hooks import HTTP_METHOD_NAME from sentry.auth import access from sentry.models.environment import Environment @@ -48,7 +49,7 @@ UserAuthTokenAuthentication, ) from .paginator import BadPaginationError, Paginator -from .permissions import NoPermission +from .permissions import NoPermission, SuperuserPermission __all__ = [ ""Endpoint"", @@ -205,6 +206,23 @@ def build_cursor_link(self, request: Request, name: str, cursor: Cursor): def convert_args(self, request: Request, *args, **kwargs): return (args, kwargs) + def permission_denied(self, request, message=None, code=None): + """""" + Raise a specific superuser exception if the user can become superuser + and the only permission class is SuperuserPermission. Otherwise, raises + the appropriate exception according to parent DRF function. + """""" + permissions = self.get_permissions() + + can_be_superuser = request.user.is_authenticated and request.user.is_superuser + has_only_superuser_permission = len(permissions) == 1 and isinstance( + permissions[0], SuperuserPermission + ) + + if can_be_superuser and has_only_superuser_permission: + raise SuperuserRequired() + super().permission_denied(request, message, code) + def handle_exception( # type: ignore[override] self, request: Request, diff --git a/src/sentry/api/endpoints/relocations/index.py b/src/sentry/api/endpoints/relocations/index.py index bafcdb5f4facd7..56e9042972f56e 100644 --- a/src/sentry/api/endpoints/relocations/index.py +++ b/src/sentry/api/endpoints/relocations/index.py @@ -17,7 +17,6 @@ from sentry.api.api_publish_status import ApiPublishStatus from sentry.api.base import Endpoint, region_silo_endpoint from sentry.api.endpoints.relocations import ERR_FEATURE_DISABLED -from sentry.api.exceptions import SuperuserRequired from sentry.api.paginator import OffsetPaginator from sentry.api.permissions import SuperuserPermission from sentry.api.serializers import serialize @@ -89,10 +88,7 @@ def validate_new_relocation_request( request: Request, owner_username: str, org_slugs: list[str], file_size: int ) -> Response | None: # We only honor the `relocation.enabled` flag for non-superusers. - try: - is_superuser = SuperuserPermission().has_permission(request, None) - except SuperuserRequired: - is_superuser = False + is_superuser = SuperuserPermission().has_permission(request, None) if not options.get(""relocation.enabled"") and not is_superuser: return Response({""detail"": ERR_FEATURE_DISABLED}, status=status.HTTP_403_FORBIDDEN) diff --git a/src/sentry/api/permissions.py b/src/sentry/api/permissions.py index 0d48402c942f40..e8edd233ed7059 100644 --- a/src/sentry/api/permissions.py +++ b/src/sentry/api/permissions.py @@ -43,6 +43,11 @@ def has_permission(self, request: Request, view: object) -> bool: return False +class SuperuserPermission(permissions.BasePermission): + def has_permission(self, request: Request, view: object) -> bool: + return is_active_superuser(request) + + class ScopedPermission(permissions.BasePermission): """""" Permissions work depending on the type of authentication: @@ -76,15 +81,6 @@ def has_object_permission(self, request: Request, view: object, obj: Any) -> boo return False -class SuperuserPermission(permissions.BasePermission): - def has_permission(self, request: Request, view: object) -> bool: - if is_active_superuser(request): - return True - if request.user.is_authenticated and request.user.is_superuser: - raise SuperuserRequired - return False - - class SentryPermission(ScopedPermission): def is_not_2fa_compliant( self, request: Request, organization: RpcOrganization | Organization @@ -163,7 +159,6 @@ def determine_access( elif request.user.is_authenticated: # session auth needs to confirm various permissions if self.needs_sso(request, org_context.organization): - logger.info( ""access.must-sso"", extra=extra, diff --git a/tests/sentry/api/test_base.py b/tests/sentry/api/test_base.py index abaec2a4e5d458..454fe0741a2646 100644 --- a/tests/sentry/api/test_base.py +++ b/tests/sentry/api/test_base.py @@ -4,12 +4,15 @@ from django.http import HttpRequest, QueryDict, StreamingHttpResponse from django.test import override_settings from pytest import raises +from rest_framework.permissions import AllowAny from rest_framework.response import Response from sentry_sdk import Scope from sentry_sdk.utils import exc_info_from_error from sentry.api.base import Endpoint, EndpointSiloLimit +from sentry.api.exceptions import SuperuserRequired from sentry.api.paginator import GenericOffsetPaginator +from sentry.api.permissions import SuperuserPermission from sentry.models.apikey import ApiKey from sentry.services.hybrid_cloud.util import FunctionSiloLimit from sentry.silo import SiloMode @@ -33,6 +36,17 @@ def get(self, request): return Response({""ok"": True}) +class DummySuperuserPermissionEndpoint(DummyEndpoint): + permission_classes = (SuperuserPermission,) + + +class DummySuperuserOrAnyPermissionEndpoint(DummyEndpoint): + permission_classes = ( + SuperuserPermission, + AllowAny, + ) + + class DummyErroringEndpoint(Endpoint): permission_classes = () # `as_view` requires that any init args passed to it match attributes already on the @@ -82,9 +96,6 @@ def data_fn(offset, limit): ) -_dummy_endpoint = DummyEndpoint.as_view() - - class DummyPaginationStreamingEndpoint(Endpoint): permission_classes = () @@ -104,6 +115,7 @@ def data_fn(offset, limit): ) +_dummy_endpoint = DummyEndpoint.as_view() _dummy_streaming_endpoint = DummyPaginationStreamingEndpoint.as_view() @@ -575,3 +587,25 @@ def test_with_inactive_mode(self): def test_with_monolith_mode(self): self._test_active_on(SiloMode.REGION, SiloMode.MONOLITH, True) self._test_active_on(SiloMode.CONTROL, SiloMode.MONOLITH, True) + + +class SuperuserPermissionTest(APITestCase): + def setUp(self): + super().setUp() + self.request = self.make_request(user=self.user, method=""GET"") + self.superuser_permission_view = DummySuperuserPermissionEndpoint().as_view() + self.superuser_or_any_permission_view = DummySuperuserOrAnyPermissionEndpoint().as_view() + + def test_superuser_exception_raised(self): + response = self.superuser_permission_view(self.request) + response_detail = response.data[""detail""] + + assert response.status_code == SuperuserRequired.status_code + assert response_detail[""code""] == SuperuserRequired.code + assert response_detail[""message""] == SuperuserRequired.message + + @mock.patch(""sentry.api.permissions.is_active_superuser"", return_value=True) + def test_superuser_or_any_no_exception_raised(self, mock_is_active_superuser): + response = self.superuser_or_any_permission_view(self.request) + + assert response.status_code == 200, response.content" dba75433c52897c6bdbf8516b3173af43377746f,2024-03-22 04:35:45,David Wang,ref(crons): Add named route for monitor overview (#67476),False,Add named route for monitor overview (#67476),ref,"diff --git a/src/sentry/monitors/tasks/detect_broken_monitor_envs.py b/src/sentry/monitors/tasks/detect_broken_monitor_envs.py index 8d2798ea988cf3..a2a6887aaba415 100644 --- a/src/sentry/monitors/tasks/detect_broken_monitor_envs.py +++ b/src/sentry/monitors/tasks/detect_broken_monitor_envs.py @@ -44,15 +44,13 @@ def detect_broken_monitor_envs(): # TODO(davidenwang): When we want to email users, remove this filter monitorenvbrokendetection__isnull=True, ) - for open_incident in RangeQuerySetWrapper( - open_incidents_qs, - order_by=""starting_timestamp"", - step=1000, - ): + org_ids_with_open_incidents = ( + open_incidents_qs.all().values_list(""monitor__organization_id"", flat=True).distinct() + ) + + for org_id in org_ids_with_open_incidents: try: - organization = Organization.objects.get_from_cache( - id=open_incident.monitor.organization_id - ) + organization = Organization.objects.get_from_cache(id=org_id) if not features.has( ""organizations:crons-broken-monitor-detection"", organization=organization ): @@ -60,21 +58,35 @@ def detect_broken_monitor_envs(): except Organization.DoesNotExist: continue - # verify that the most recent check-ins have been failing - recent_checkins = ( - MonitorCheckIn.objects.filter(monitor_environment=open_incident.monitor_environment) - .order_by(""-date_added"") - .values(""status"")[:NUM_CONSECUTIVE_BROKEN_CHECKINS] + orgs_open_incidents = ( + open_incidents_qs.all() + .select_related(""monitor_environment"") + .filter(monitor__organization_id=org_id) ) - if len(recent_checkins) != NUM_CONSECUTIVE_BROKEN_CHECKINS or not all( - checkin[""status""] in [CheckInStatus.ERROR, CheckInStatus.TIMEOUT, CheckInStatus.MISSED] - for checkin in recent_checkins + # Query for all the broken incidents within the current org we are processing + for open_incident in RangeQuerySetWrapper( + orgs_open_incidents, + order_by=""starting_timestamp"", + step=1000, ): - continue + # Verify that the most recent check-ins have been failing + recent_checkins = ( + MonitorCheckIn.objects.filter(monitor_environment=open_incident.monitor_environment) + .order_by(""-date_added"") + .values(""status"")[:NUM_CONSECUTIVE_BROKEN_CHECKINS] + ) + if len(recent_checkins) != NUM_CONSECUTIVE_BROKEN_CHECKINS or not all( + checkin[""status""] + in [CheckInStatus.ERROR, CheckInStatus.TIMEOUT, CheckInStatus.MISSED] + for checkin in recent_checkins + ): + continue - detection, _ = MonitorEnvBrokenDetection.objects.get_or_create( - monitor_incident=open_incident, defaults={""detection_timestamp"": current_time} - ) - if not detection.user_notified_timestamp: - # TODO(davidenwang): This is where we would implement email sending logic - pass + detection, _ = MonitorEnvBrokenDetection.objects.get_or_create( + monitor_incident=open_incident, defaults={""detection_timestamp"": current_time} + ) + if not detection.user_notified_timestamp: + # Record that we need to notify users about this broken detection via email + pass + + # TODO(davidenwang): Send the emails here diff --git a/src/sentry/web/urls.py b/src/sentry/web/urls.py index f3955cc9e44ed8..8e0d92f649849e 100644 --- a/src/sentry/web/urls.py +++ b/src/sentry/web/urls.py @@ -1001,6 +1001,11 @@ react_page_view, name=""sentry-organization-replay-rage-clicks"", ), + re_path( + r""^(?P[\w_-]+)/crons/$"", + react_page_view, + name=""sentry-organization-crons"", + ), re_path( r""^(?P[\w_-]+)/crons/(?P[\w_-]+)/(?P[\w_-]+)/$"", react_page_view," 978068f65e5c0d5da6b4d5b1feb7b2e9f2bda2e7,2024-04-16 00:47:59,Catherine Lee,fix(replay): Fixes type error if same param is in url (#68851),False,Fixes type error if same param is in url (#68851),fix,"diff --git a/static/app/utils/useUrlParams.spec.tsx b/static/app/utils/useUrlParams.spec.tsx index 4a51372a4f49b8..0721f7faecbf9f 100644 --- a/static/app/utils/useUrlParams.spec.tsx +++ b/static/app/utils/useUrlParams.spec.tsx @@ -8,7 +8,7 @@ import useUrlParams from './useUrlParams'; jest.mock('react-router'); jest.mock('sentry/utils/useLocation'); -type Query = {limit: string; page: string}; +type Query = {array: string[]; limit: string; page: string}; describe('useUrlParams', () => { beforeEach(() => { @@ -16,6 +16,7 @@ describe('useUrlParams', () => { query: { page: '3', limit: '50', + array: ['first', 'second'], }, } as Location); }); @@ -25,6 +26,7 @@ describe('useUrlParams', () => { expect(result.current.getParamValue('page')).toBe('3'); expect(result.current.getParamValue('limit')).toBe('50'); + expect(result.current.getParamValue('array')).toBe('first'); expect(result.current.getParamValue('foo')).toBeUndefined(); }); @@ -54,6 +56,7 @@ describe('useUrlParams', () => { expect(browserHistory.push).toHaveBeenCalledWith({ query: { + array: ['first', 'second'], page: '4', limit: '50', }, @@ -69,6 +72,7 @@ describe('useUrlParams', () => { expect(browserHistory.push).toHaveBeenCalledWith({ query: { + array: ['first', 'second'], page: '4', limit: '50', }, diff --git a/static/app/utils/useUrlParams.tsx b/static/app/utils/useUrlParams.tsx index 19c05cd3a9214e..bc1a752b2e4635 100644 --- a/static/app/utils/useUrlParams.tsx +++ b/static/app/utils/useUrlParams.tsx @@ -20,7 +20,10 @@ function useUrlParams(defaultKey?: string, defaultValue?: string) { const getParamValue = useCallback( (key: string) => { const location = browserHistory.getCurrentLocation(); - return location.query[key] ?? defaultValue; + // location.query.key can return string[] but we expect a singular value from this function, so we return the first string (this is picked arbitrarily) if it's string[] + return Array.isArray(location.query[key]) + ? location.query[key]?.at(0) ?? defaultValue + : location.query[key] ?? defaultValue; }, [defaultValue] );" 91d472a194ea4b81618e76f9ab874d9252a015e0,2023-11-27 16:30:28,ArthurKnaus,fix(alerts): transaction metrics being available (#60584),False,transaction metrics being available (#60584),fix,"diff --git a/static/app/utils/metrics/useMetricsMeta.tsx b/static/app/utils/metrics/useMetricsMeta.tsx index 2afe9cb4a9052a..68af041238b2cc 100644 --- a/static/app/utils/metrics/useMetricsMeta.tsx +++ b/static/app/utils/metrics/useMetricsMeta.tsx @@ -34,32 +34,43 @@ export function useMetricsMeta( ]; }; + const hasSessions = enabledUseCases.includes('sessions'); + const hasTransactions = enabledUseCases.includes('transactions'); + const hasCustom = enabledUseCases.includes('custom'); + const commonOptions = { staleTime: Infinity, }; const sessionsMeta = useApiQuery(getKey('sessions'), { ...commonOptions, - enabled: enabledUseCases.includes('sessions'), + enabled: hasSessions, }); const txnsMeta = useApiQuery(getKey('transactions'), { ...commonOptions, - enabled: enabledUseCases.includes('transactions'), + enabled: hasTransactions, }); const customMeta = useApiQuery(getKey('custom'), { ...commonOptions, - enabled: enabledUseCases.includes('custom'), + enabled: hasCustom, }); const combinedMeta = useMemo>(() => { return [ - ...(sessionsMeta.data ?? []), - ...(txnsMeta.data ?? []), - ...(customMeta.data ?? []), + ...(hasSessions ? sessionsMeta.data ?? [] : []), + ...(hasTransactions ? txnsMeta.data ?? [] : []), + ...(hasCustom ? customMeta.data ?? [] : []), ].reduce((acc, metricMeta) => { return {...acc, [metricMeta.mri]: metricMeta}; }, {}); - }, [sessionsMeta.data, txnsMeta.data, customMeta.data]); + }, [ + hasSessions, + sessionsMeta.data, + hasTransactions, + txnsMeta.data, + hasCustom, + customMeta.data, + ]); return { data: combinedMeta, diff --git a/static/app/views/alerts/rules/metric/mriField.tsx b/static/app/views/alerts/rules/metric/mriField.tsx index 9f864c1e253a1f..3ea3ce7ee8421f 100644 --- a/static/app/views/alerts/rules/metric/mriField.tsx +++ b/static/app/views/alerts/rules/metric/mriField.tsx @@ -7,6 +7,7 @@ import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; import {Project} from 'sentry/types'; import { + DEFAULT_METRIC_ALERT_AGGREGATE, fieldToMri, getReadableMetricType, isAllowedOp, @@ -37,14 +38,21 @@ function MriField({aggregate, project, onChange}: Props) { useEffect(() => { // Auto-select the first mri if none of the available ones is selected - if (!selectedMriMeta && metaArr.length > 0) { + if (!selectedMriMeta) { const newSelection = metaArr[0]; - onChange( - mriToField(newSelection.mri, filterAndSortOperations(newSelection.operations)[0]), - {} - ); + if (newSelection) { + onChange( + mriToField( + newSelection.mri, + filterAndSortOperations(newSelection.operations)[0] + ), + {} + ); + } else if (aggregate !== DEFAULT_METRIC_ALERT_AGGREGATE) { + onChange(DEFAULT_METRIC_ALERT_AGGREGATE, {}); + } } - }, [metaArr, onChange, selectedMriMeta, isLoading]); + }, [metaArr, onChange, selectedMriMeta, isLoading, aggregate]); const handleMriChange = useCallback( option => { diff --git a/static/app/views/alerts/rules/metric/utils/isCustomMetricAlert.tsx b/static/app/views/alerts/rules/metric/utils/isCustomMetricAlert.tsx index e07d82ce68fb4b..dbeee480058e38 100644 --- a/static/app/views/alerts/rules/metric/utils/isCustomMetricAlert.tsx +++ b/static/app/views/alerts/rules/metric/utils/isCustomMetricAlert.tsx @@ -1,7 +1,7 @@ import {fieldToMri} from 'sentry/utils/metrics'; /** - * Currently we can tell if an alert is a crash free alert by checking the aggregate for a MRI, + * Currently we can tell if an alert is a custom metric alert by checking the aggregate for a MRI, */ export function isCustomMetricAlert(aggregate: string): boolean { return fieldToMri(aggregate).mri !== undefined;" 7bd76fd482edb25f67c39888e778fecb70bed95a,2024-01-11 05:27:38,Hubert Deng,feat(relocation): Add relocation created analytics (#62880),False,Add relocation created analytics (#62880),feat,"diff --git a/src/sentry/analytics/events/relocation_created.py b/src/sentry/analytics/events/relocation_created.py new file mode 100644 index 00000000000000..70ffd032b495b5 --- /dev/null +++ b/src/sentry/analytics/events/relocation_created.py @@ -0,0 +1,14 @@ +from sentry import analytics + + +class RelocationCreatedEvent(analytics.Event): + type = ""relocation.created"" + + attributes = ( + analytics.Attribute(""creator_id""), + analytics.Attribute(""owner_id""), + analytics.Attribute(""uuid""), + ) + + +analytics.register(RelocationCreatedEvent) diff --git a/src/sentry/analytics/events/relocation_organization_imported.py b/src/sentry/analytics/events/relocation_organization_imported.py new file mode 100644 index 00000000000000..393940911eaeda --- /dev/null +++ b/src/sentry/analytics/events/relocation_organization_imported.py @@ -0,0 +1,16 @@ +from sentry import analytics + + +class RelocationOrganizationImportedEvent(analytics.Event): + type = ""relocation.organization_imported"" + + attributes = ( + analytics.Attribute(""organization_id""), + analytics.Attribute(""relocation_uuid""), + analytics.Attribute(""owner_id""), + analytics.Attribute(""name""), + analytics.Attribute(""slug""), + ) + + +analytics.register(RelocationOrganizationImportedEvent) diff --git a/src/sentry/analytics/events/user_signup.py b/src/sentry/analytics/events/user_signup.py index 7fcd0b9c965fe0..52cb62b07f3160 100644 --- a/src/sentry/analytics/events/user_signup.py +++ b/src/sentry/analytics/events/user_signup.py @@ -12,4 +12,9 @@ class UserSignUpEvent(analytics.Event): ) +class RelocationUserSignUpEvent(UserSignUpEvent): + type = ""relocation.user_signup"" + + analytics.register(UserSignUpEvent) +analytics.register(RelocationUserSignUpEvent) diff --git a/src/sentry/api/endpoints/relocations/index.py b/src/sentry/api/endpoints/relocations/index.py index a49e8aeba95527..368d7ef965d342 100644 --- a/src/sentry/api/endpoints/relocations/index.py +++ b/src/sentry/api/endpoints/relocations/index.py @@ -12,7 +12,7 @@ from rest_framework.request import Request from rest_framework.response import Response -from sentry import options +from sentry import analytics, options from sentry.api.api_owners import ApiOwner from sentry.api.api_publish_status import ApiPublishStatus from sentry.api.base import Endpoint, region_silo_endpoint @@ -269,4 +269,10 @@ def post(self, request: Request) -> Response: ) uploading_complete.delay(relocation.uuid) + analytics.record( + ""relocation.created"", + creator_id=request.user.id, + owner_id=owner.id, + uuid=str(relocation.uuid), + ) return Response(serialize(relocation), status=status.HTTP_201_CREATED) diff --git a/src/sentry/api/endpoints/relocations/retry.py b/src/sentry/api/endpoints/relocations/retry.py index 598a8fa62c644a..c38607313222ba 100644 --- a/src/sentry/api/endpoints/relocations/retry.py +++ b/src/sentry/api/endpoints/relocations/retry.py @@ -7,6 +7,7 @@ from rest_framework.request import Request from rest_framework.response import Response +from sentry import analytics from sentry.api.api_owners import ApiOwner from sentry.api.api_publish_status import ApiPublishStatus from sentry.api.base import Endpoint, region_silo_endpoint @@ -118,4 +119,10 @@ def post(self, request: Request, relocation_uuid: str) -> Response: ) uploading_complete.delay(new_relocation.uuid) + analytics.record( + ""relocation.created"", + creator_id=request.user.id, + owner_id=owner.id, + uuid=str(new_relocation.uuid), + ) return Response(serialize(new_relocation), status=status.HTTP_201_CREATED) diff --git a/src/sentry/tasks/relocation.py b/src/sentry/tasks/relocation.py index 0988c4c9f945af..02133f4ef409c2 100644 --- a/src/sentry/tasks/relocation.py +++ b/src/sentry/tasks/relocation.py @@ -15,7 +15,9 @@ from django.db import router, transaction from google.cloud.devtools.cloudbuild_v1 import Build from google.cloud.devtools.cloudbuild_v1 import CloudBuildClient as CloudBuildClient +from sentry_sdk import capture_exception +from sentry import analytics from sentry.api.serializers.rest_framework.base import camel_to_snake_case, convert_dict_key_case from sentry.backup.dependencies import NormalizedModelName, get_model from sentry.backup.exports import export_in_config_scope, export_in_user_scope @@ -1085,7 +1087,6 @@ def postprocessing(uuid: str) -> None: user_id=relocation.owner_id, role=""owner"", ) - # Last, but certainly not least: trigger signals, so that interested subscribers in eg: # getsentry can do whatever postprocessing they need to. If even a single one fails, we fail # the entire task. @@ -1093,6 +1094,18 @@ def postprocessing(uuid: str) -> None: if isinstance(result, Exception): raise result + for org in imported_orgs: + try: + analytics.record( + ""relocation.organization_imported"", + organization_id=org.id, + relocation_uuid=str(relocation.uuid), + slug=org.slug, + owner_id=relocation.owner_id, + ) + except Exception as e: + capture_exception(e) + notifying_users.apply_async(args=[uuid]) diff --git a/tests/sentry/api/endpoints/relocations/test_index.py b/tests/sentry/api/endpoints/relocations/test_index.py index 7ad672f8609f04..5629c79930cc7a 100644 --- a/tests/sentry/api/endpoints/relocations/test_index.py +++ b/tests/sentry/api/endpoints/relocations/test_index.py @@ -2,7 +2,7 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Tuple -from unittest.mock import patch +from unittest.mock import Mock, call, patch from uuid import UUID from django.core.files.uploadedfile import SimpleUploadedFile @@ -232,6 +232,7 @@ def test_bad_no_superuser(self): @region_silo_test +@patch(""sentry.analytics.record"") class PostRelocationsTest(APITestCase): endpoint = ""sentry-api-0-relocations-index"" @@ -257,7 +258,11 @@ def tmp_keys(self, tmp_dir: str) -> Tuple[Path, Path]: return (tmp_priv_key_path, tmp_pub_key_path) @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_good_simple(self, uploading_complete_mock): + def test_good_simple( + self, + uploading_complete_mock: Mock, + analytics_record_mock: Mock, + ): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -307,8 +312,20 @@ def test_good_simple(self, uploading_complete_mock): assert uploading_complete_mock.call_count == 1 + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_good_with_valid_autopause_option(self, uploading_complete_mock): + def test_good_with_valid_autopause_option( + self, + uploading_complete_mock: Mock, + analytics_record_mock: Mock, + ): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: @@ -345,8 +362,20 @@ def test_good_with_valid_autopause_option(self, uploading_complete_mock): assert uploading_complete_mock.call_count == 1 + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_good_with_invalid_autopause_option(self, uploading_complete_mock): + def test_good_with_invalid_autopause_option( + self, + uploading_complete_mock: Mock, + analytics_record_mock: Mock, + ): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: @@ -382,9 +411,18 @@ def test_good_with_invalid_autopause_option(self, uploading_complete_mock): assert response.data[""scheduledPauseAtStep""] is None assert uploading_complete_mock.call_count == 1 + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_good_with_superuser_when_feature_disabled(self, uploading_complete_mock): + def test_good_with_superuser_when_feature_disabled( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock + ): self.login_as(user=self.superuser, superuser=True) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -433,7 +471,15 @@ def test_good_with_superuser_when_feature_disabled(self, uploading_complete_mock assert uploading_complete_mock.call_count == 1 - def test_bad_without_superuser_when_feature_disabled(self): + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + + def test_bad_without_superuser_when_feature_disabled(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -460,7 +506,9 @@ def test_bad_without_superuser_when_feature_disabled(self): assert response.data.get(""detail"") is not None assert response.data.get(""detail"") == ERR_FEATURE_DISABLED - def test_bad_expired_superuser_when_feature_disabled(self): + assert analytics_record_mock.call_count == 0 + + def test_bad_expired_superuser_when_feature_disabled(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=True) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -487,6 +535,8 @@ def test_bad_expired_superuser_when_feature_disabled(self): assert response.data.get(""detail"") is not None assert response.data.get(""detail"") == ERR_FEATURE_DISABLED + assert analytics_record_mock.call_count == 0 + # pytest parametrize does not work in TestCase subclasses, so hack around this for org_slugs, expected in [ (""testing,foo,"", [""testing"", ""foo""]), @@ -497,7 +547,11 @@ def test_bad_expired_superuser_when_feature_disabled(self): @patch(""sentry.tasks.relocation.uploading_complete.delay"") def test_good_valid_org_slugs( - self, uploading_complete_mock, org_slugs=org_slugs, expected=expected + self, + uploading_complete_mock: Mock, + analytics_record_mock: Mock, + org_slugs=org_slugs, + expected=expected, ): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() @@ -532,6 +586,14 @@ def test_good_valid_org_slugs( assert Relocation.objects.get(owner_id=self.owner.id).want_org_slugs == expected assert uploading_complete_mock.call_count == 1 + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + for org_slugs, invalid_org_slug in [ ("",,"", """"), (""testing,,foo"", """"), @@ -541,7 +603,11 @@ def test_good_valid_org_slugs( @patch(""sentry.tasks.relocation.uploading_complete.delay"") def test_bad_invalid_org_slugs( - self, uploading_complete_mock, org_slugs=org_slugs, invalid_org_slug=invalid_org_slug + self, + analytics_record_mock: Mock, + uploading_complete_mock: Mock, + org_slugs=org_slugs, + invalid_org_slug=invalid_org_slug, ): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() @@ -579,7 +645,9 @@ def test_bad_invalid_org_slugs( assert RelocationFile.objects.count() == relocation_file_count assert uploading_complete_mock.call_count == 0 - def test_good_relocation_for_same_owner_already_completed(self): + assert analytics_record_mock.call_count == 0 + + def test_good_relocation_for_same_owner_already_completed(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) Relocation.objects.create( creator_id=self.superuser.id, @@ -628,7 +696,15 @@ def test_good_relocation_for_same_owner_already_completed(self): assert Relocation.objects.count() == relocation_count + 1 assert RelocationFile.objects.count() == relocation_file_count + 1 - def test_bad_missing_file(self): + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + + def test_bad_missing_file(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -651,7 +727,9 @@ def test_bad_missing_file(self): assert response.data.get(""file"") is not None assert response.data.get(""file"")[0].code == ""required"" - def test_bad_missing_orgs(self): + analytics_record_mock.assert_not_called() + + def test_bad_missing_orgs(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -682,7 +760,9 @@ def test_bad_missing_orgs(self): assert response.data.get(""orgs"") is not None assert response.data.get(""orgs"")[0].code == ""required"" - def test_bad_missing_owner(self): + analytics_record_mock.assert_not_called() + + def test_bad_missing_owner(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -713,7 +793,9 @@ def test_bad_missing_owner(self): assert response.data.get(""owner"") is not None assert response.data.get(""owner"")[0].code == ""required"" - def test_bad_nonexistent_owner(self): + analytics_record_mock.assert_not_called() + + def test_bad_nonexistent_owner(self, analytics_record_mock: Mock): self.login_as(user=self.superuser, superuser=True) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -747,7 +829,9 @@ def test_bad_nonexistent_owner(self): owner_username=""doesnotexist"" ) - def test_bad_owner_not_self(self): + analytics_record_mock.assert_not_called() + + def test_bad_owner_not_self(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) with tempfile.TemporaryDirectory() as tmp_dir: (_, tmp_pub_key_path) = self.tmp_keys(tmp_dir) @@ -779,12 +863,16 @@ def test_bad_owner_not_self(self): assert response.data.get(""detail"") is not None assert response.data.get(""detail"") == ERR_INVALID_OWNER.substitute(creator_username=""owner"") + analytics_record_mock.assert_not_called() + for stat in [ Relocation.Status.IN_PROGRESS, Relocation.Status.PAUSE, ]: - def test_bad_relocation_for_same_owner_already_active(self, stat=stat): + def test_bad_relocation_for_same_owner_already_active( + self, analytics_record_mock: Mock, stat=stat + ): self.login_as(user=self.owner, superuser=False) Relocation.objects.create( creator_id=self.superuser.id, @@ -822,7 +910,9 @@ def test_bad_relocation_for_same_owner_already_active(self, stat=stat): assert response.status_code == status.HTTP_409_CONFLICT - def test_bad_throttle_if_daily_limit_reached(self): + analytics_record_mock.assert_not_called() + + def test_bad_throttle_if_daily_limit_reached(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -883,7 +973,15 @@ def test_bad_throttle_if_daily_limit_reached(self): assert Relocation.objects.count() == relocation_count + 1 assert RelocationFile.objects.count() == relocation_file_count + 1 - def test_good_no_throttle_for_superuser(self): + assert analytics_record_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(initial_response.data[""creatorId""]), + owner_id=int(initial_response.data[""ownerId""]), + uuid=initial_response.data[""uuid""], + ) + + def test_good_no_throttle_for_superuser(self, analytics_record_mock: Mock): self.login_as(user=self.superuser, superuser=True) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -942,7 +1040,25 @@ def test_good_no_throttle_for_superuser(self): assert Relocation.objects.count() == relocation_count + 2 assert RelocationFile.objects.count() == relocation_file_count + 2 - def test_good_no_throttle_different_bucket_relocations(self): + assert analytics_record_mock.call_count == 2 + analytics_record_mock.assert_has_calls( + [ + call( + ""relocation.created"", + creator_id=int(initial_response.data[""creatorId""]), + owner_id=int(initial_response.data[""ownerId""]), + uuid=initial_response.data[""uuid""], + ), + call( + ""relocation.created"", + creator_id=int(throttled_response.data[""creatorId""]), + owner_id=int(throttled_response.data[""ownerId""]), + uuid=throttled_response.data[""uuid""], + ), + ] + ) + + def test_good_no_throttle_different_bucket_relocations(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -1003,7 +1119,25 @@ def test_good_no_throttle_different_bucket_relocations(self): assert Relocation.objects.count() == relocation_count + 2 assert RelocationFile.objects.count() == relocation_file_count + 2 - def test_good_no_throttle_relocation_over_multiple_days(self): + assert analytics_record_mock.call_count == 2 + analytics_record_mock.assert_has_calls( + [ + call( + ""relocation.created"", + creator_id=int(initial_response.data[""creatorId""]), + owner_id=int(initial_response.data[""ownerId""]), + uuid=initial_response.data[""uuid""], + ), + call( + ""relocation.created"", + creator_id=int(unthrottled_response.data[""creatorId""]), + owner_id=int(unthrottled_response.data[""ownerId""]), + uuid=unthrottled_response.data[""uuid""], + ), + ] + ) + + def test_good_no_throttle_relocation_over_multiple_days(self, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -1066,7 +1200,26 @@ def test_good_no_throttle_relocation_over_multiple_days(self): assert Relocation.objects.count() == relocation_count + 2 assert RelocationFile.objects.count() == relocation_file_count + 2 - def test_bad_no_auth(self): + assert analytics_record_mock.call_count == 2 + + analytics_record_mock.assert_has_calls( + [ + call( + ""relocation.created"", + creator_id=int(initial_response.data[""creatorId""]), + owner_id=int(initial_response.data[""ownerId""]), + uuid=initial_response.data[""uuid""], + ), + call( + ""relocation.created"", + creator_id=int(unthrottled_response.data[""creatorId""]), + owner_id=int(unthrottled_response.data[""ownerId""]), + uuid=unthrottled_response.data[""uuid""], + ), + ] + ) + + def test_bad_no_auth(self, analytics_record_mock: Mock): relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -1096,3 +1249,5 @@ def test_bad_no_auth(self): assert response.status_code == status.HTTP_401_UNAUTHORIZED assert Relocation.objects.count() == relocation_count assert RelocationFile.objects.count() == relocation_file_count + + analytics_record_mock.assert_not_called() diff --git a/tests/sentry/api/endpoints/relocations/test_retry.py b/tests/sentry/api/endpoints/relocations/test_retry.py index 705efbf427095f..6314e9846f5e49 100644 --- a/tests/sentry/api/endpoints/relocations/test_retry.py +++ b/tests/sentry/api/endpoints/relocations/test_retry.py @@ -1,7 +1,7 @@ from datetime import datetime, timezone from functools import lru_cache from io import BytesIO -from unittest.mock import patch +from unittest.mock import Mock, patch from uuid import uuid4 from rest_framework import status @@ -42,6 +42,7 @@ def get_test_tarball() -> BytesIO: @region_silo_test +@patch(""sentry.analytics.record"") class RetryRelocationTest(APITestCase): endpoint = ""sentry-api-0-relocations-retry"" @@ -85,7 +86,7 @@ def setUp(self): ) @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_good_simple(self, uploading_complete_mock): + def test_good_simple(self, uploading_complete_mock: Mock, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -124,8 +125,17 @@ def test_good_simple(self, uploading_complete_mock): assert uploading_complete_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_good_with_superuser_when_feature_disabled(self, uploading_complete_mock): + def test_good_with_superuser_when_feature_disabled( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock + ): self.login_as(user=self.superuser, superuser=True) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -154,8 +164,17 @@ def test_good_with_superuser_when_feature_disabled(self, uploading_complete_mock assert uploading_complete_mock.call_count == 1 + analytics_record_mock.assert_called_with( + ""relocation.created"", + creator_id=int(response.data[""creatorId""]), + owner_id=int(response.data[""ownerId""]), + uuid=response.data[""uuid""], + ) + @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_without_superuser_when_feature_disabled(self, uploading_complete_mock): + def test_bad_without_superuser_when_feature_disabled( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock + ): self.login_as(user=self.owner, superuser=False) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -179,7 +198,9 @@ def test_bad_without_superuser_when_feature_disabled(self, uploading_complete_mo assert uploading_complete_mock.call_count == 0 @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_expired_superuser_when_feature_disabled(self, uploading_complete_mock): + def test_bad_expired_superuser_when_feature_disabled( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock + ): self.login_as(user=self.owner, superuser=True) relocation_count = Relocation.objects.count() relocation_file_count = RelocationFile.objects.count() @@ -201,9 +222,12 @@ def test_bad_expired_superuser_when_feature_disabled(self, uploading_complete_mo assert File.objects.count() == file_count assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_relocation_not_found(self, uploading_complete_mock): + def test_bad_relocation_not_found( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock + ): self.login_as(user=self.owner, superuser=False) with self.options({""relocation.enabled"": True, ""relocation.daily-limit.small"": 2}): @@ -212,9 +236,12 @@ def test_bad_relocation_not_found(self, uploading_complete_mock): assert response.status_code == status.HTTP_404_NOT_FOUND assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_relocation_file_not_found(self, uploading_complete_mock): + def test_bad_relocation_file_not_found( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock + ): self.login_as(user=self.owner, superuser=False) RelocationFile.objects.all().delete() @@ -225,9 +252,10 @@ def test_bad_relocation_file_not_found(self, uploading_complete_mock): assert response.data.get(""detail"") == ERR_FILE_NO_LONGER_EXISTS assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_file_not_found(self, uploading_complete_mock): + def test_bad_file_not_found(self, uploading_complete_mock: Mock, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) File.objects.all().delete() @@ -240,7 +268,7 @@ def test_bad_file_not_found(self, uploading_complete_mock): assert uploading_complete_mock.call_count == 0 @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_owner_not_found(self, uploading_complete_mock): + def test_bad_owner_not_found(self, uploading_complete_mock: Mock, analytics_record_mock: Mock): self.login_as(user=self.superuser, superuser=True) with assume_test_silo_mode(SiloMode.CONTROL): User.objects.filter(id=self.owner.id).delete() @@ -252,9 +280,10 @@ def test_bad_owner_not_found(self, uploading_complete_mock): assert response.data.get(""detail"") == ERR_OWNER_NO_LONGER_EXISTS assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_throttled(self, uploading_complete_mock): + def test_bad_throttled(self, uploading_complete_mock: Mock, analytics_record_mock: Mock): self.login_as(user=self.owner, superuser=False) with self.options({""relocation.enabled"": True, ""relocation.daily-limit.small"": 1}): @@ -264,6 +293,7 @@ def test_bad_throttled(self, uploading_complete_mock): assert response.data.get(""detail"") == ERR_THROTTLED_RELOCATION assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() for stat in [ Relocation.Status.IN_PROGRESS, @@ -271,7 +301,9 @@ def test_bad_throttled(self, uploading_complete_mock): ]: @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_relocation_still_ongoing(self, uploading_complete_mock, stat=stat): + def test_bad_relocation_still_ongoing( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock, stat=stat + ): self.login_as(user=self.owner, superuser=False) self.relocation.status = stat.value self.relocation.latest_notified = Relocation.EmailKind.STARTED.value @@ -288,6 +320,7 @@ def test_bad_relocation_still_ongoing(self, uploading_complete_mock, stat=stat): ) assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() for stat in [ Relocation.Status.IN_PROGRESS, @@ -295,7 +328,9 @@ def test_bad_relocation_still_ongoing(self, uploading_complete_mock, stat=stat): ]: @patch(""sentry.tasks.relocation.uploading_complete.delay"") - def test_bad_owner_has_another_active_relocation(self, uploading_complete_mock, stat=stat): + def test_bad_owner_has_another_active_relocation( + self, uploading_complete_mock: Mock, analytics_record_mock: Mock, stat=stat + ): self.login_as(user=self.owner, superuser=False) Relocation.objects.create( date_added=TEST_DATE_ADDED, @@ -321,3 +356,4 @@ def test_bad_owner_has_another_active_relocation(self, uploading_complete_mock, assert response.data.get(""detail"") == ERR_DUPLICATE_RELOCATION assert uploading_complete_mock.call_count == 0 + analytics_record_mock.assert_not_called() diff --git a/tests/sentry/tasks/test_relocation.py b/tests/sentry/tasks/test_relocation.py index 564547da944402..46431317b47db0 100644 --- a/tests/sentry/tasks/test_relocation.py +++ b/tests/sentry/tasks/test_relocation.py @@ -1668,6 +1668,7 @@ def test_pause( @patch(""sentry.utils.relocation.MessageBuilder"") @patch(""sentry.signals.relocated.send_robust"") @patch(""sentry.tasks.relocation.notifying_users.apply_async"") +@patch(""sentry.analytics.record"") class PostprocessingTest(RelocationTaskTestCase): def setUp(self): RelocationTaskTestCase.setUp(self) @@ -1701,6 +1702,7 @@ def noop_relocated_signal_receiver(sender, **kwargs) -> None: def test_success( self, + analytics_record_mock: Mock, notifying_users_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, @@ -1731,8 +1733,19 @@ def test_success( organization_id=self.imported_org_id, user_id=self.owner.id ).exists() + relocation = Relocation.objects.get(uuid=self.uuid) + + analytics_record_mock.assert_called_with( + ""relocation.organization_imported"", + organization_id=self.imported_org_id, + relocation_uuid=str(relocation.uuid), + slug=self.imported_org_slug, + owner_id=self.owner.id, + ) + def test_pause( self, + analytics_record_mock: Mock, notifying_users_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, @@ -1752,8 +1765,11 @@ def test_pause( assert relocation.scheduled_pause_at_step is None assert relocation.latest_task == OrderedTask.POSTPROCESSING.name + analytics_record_mock.assert_not_called() + def test_retry_if_attempts_left( self, + analytics_record_mock: Mock, notifying_users_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, @@ -1778,8 +1794,12 @@ def test_retry_if_attempts_left( assert relocation.latest_notified != Relocation.EmailKind.FAILED.value assert not relocation.failure_reason + # Technically this should be called, but since we're mocking out the `send_robust` function, it won't + analytics_record_mock.assert_not_called() + def test_fail_if_no_attempts_left( self, + analytics_record_mock: Mock, notifying_users_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, @@ -1809,6 +1829,7 @@ def test_fail_if_no_attempts_left( assert relocation.status == Relocation.Status.FAILURE.value assert relocation.latest_notified == Relocation.EmailKind.FAILED.value assert relocation.failure_reason == ERR_POSTPROCESSING_INTERNAL + analytics_record_mock.assert_not_called() @region_silo_test @@ -2062,6 +2083,7 @@ def test_success(self): ) @patch(""sentry.utils.relocation.MessageBuilder"") @patch(""sentry.signals.relocated.send_robust"") +@patch(""sentry.analytics.record"") class EndToEndTest(RelocationTaskTestCase, TransactionTestCase): def setUp(self): RelocationTaskTestCase.setUp(self) @@ -2144,8 +2166,25 @@ def assert_failure_database_state(self, org_count: int): with assume_test_silo_mode(SiloMode.CONTROL): assert ControlImportChunk.objects.filter(import_uuid=self.uuid).count() == 0 + def assert_success_analytics_record(self, analytics_record_mock: Mock): + imported_orgs = RegionImportChunk.objects.get( + import_uuid=self.uuid, model=""sentry.organization"" + ) + + imported_org_id: int = next(iter(imported_orgs.inserted_map.values())) + imported_org_slug: str = next(iter(imported_orgs.inserted_identifiers.values())) + + analytics_record_mock.assert_called_with( + ""relocation.organization_imported"", + organization_id=imported_org_id, + relocation_uuid=str(self.uuid), + slug=imported_org_slug, + owner_id=self.owner.id, + ) + def test_valid_no_retries( self, + analytics_record_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, fake_cloudbuild_client: FakeCloudBuildClient, @@ -2184,9 +2223,11 @@ def test_valid_no_retries( assert not relocation.failure_reason self.assert_success_database_state(org_count) + self.assert_success_analytics_record(analytics_record_mock) def test_valid_max_retries( self, + analytics_record_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, fake_cloudbuild_client: FakeCloudBuildClient, @@ -2227,9 +2268,11 @@ def test_valid_max_retries( assert not relocation.failure_reason self.assert_success_database_state(org_count) + self.assert_success_analytics_record(analytics_record_mock) def test_invalid_no_retries( self, + analytics_record_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, fake_cloudbuild_client: FakeCloudBuildClient, @@ -2269,9 +2312,11 @@ def test_invalid_no_retries( assert relocation.failure_reason self.assert_failure_database_state(org_count) + analytics_record_mock.assert_not_called() def test_invalid_max_retries( self, + analytics_record_mock: Mock, relocated_signal_mock: Mock, fake_message_builder: Mock, fake_cloudbuild_client: FakeCloudBuildClient, @@ -2313,3 +2358,4 @@ def test_invalid_max_retries( assert relocation.failure_reason self.assert_failure_database_state(org_count) + analytics_record_mock.assert_not_called()" 9b1c0d9f5ae2777991fb054740939b6b6daf7ec3,2024-04-15 20:06:48,Yagiz Nizipli,chore: update biome to v1.7.0 (#68892),False,update biome to v1.7.0 (#68892),chore,"diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f4390dec6b9740..69e0e15a086f10 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -135,7 +135,7 @@ repos: hooks: - id: biome-check name: biome (javascript, typescript, json) - additional_dependencies: ['@biomejs/biome@1.6.0'] + additional_dependencies: ['@biomejs/biome@1.7.0'] - repo: https://github.com/pre-commit/mirrors-prettier rev: 'v3.1.0' # Use the sha or tag you want to point at hooks: diff --git a/biome.json b/biome.json index 76c2090d1d18a6..23b5c42e67a036 100644 --- a/biome.json +++ b/biome.json @@ -72,7 +72,8 @@ ""static/app/data/world.json"", ""**/*.sourcemap.js"", ""**/*.min.js"", - ""fixtures"" + ""fixtures"", + "".devenv"" ] }, ""formatter"": { diff --git a/package.json b/package.json index d0857cef4b6c5d..ded9058ed852e9 100644 --- a/package.json +++ b/package.json @@ -177,7 +177,7 @@ ""zxcvbn"": ""^4.4.2"" }, ""devDependencies"": { - ""@biomejs/biome"": ""^1.6.0"", + ""@biomejs/biome"": ""^1.7.0"", ""@codecov/webpack-plugin"": ""^0.0.1-beta.6"", ""@pmmmwh/react-refresh-webpack-plugin"": ""0.5.10"", ""@sentry/jest-environment"": ""^4.0.0"", diff --git a/yarn.lock b/yarn.lock index 442924fd9ad11e..69ae3c07ef5338 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1185,59 +1185,59 @@ resolved ""https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39"" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== -""@biomejs/biome@^1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/biome/-/biome-1.6.0.tgz#b0f3bcc93451a7de74288af30f62f80aa74b1283"" - integrity sha512-hvP8K1+CV8qc9eNdXtPwzScVxFSHB448CPKSqX6+8IW8G7bbhBVKGC80BowExJN5+vu+kzsj4xkWa780MAOlJw== +""@biomejs/biome@^1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/biome/-/biome-1.7.0.tgz#b12973c41b0a9c62374807b988cf984b20d85f44"" + integrity sha512-mejiRhnAq6UrXtYvjWJUKdstcT58n0/FfKemFf3d2Ou0HxOdS88HQmWtQ/UgyZvOEPD572YbFTb6IheyROpqkw== optionalDependencies: - ""@biomejs/cli-darwin-arm64"" ""1.6.0"" - ""@biomejs/cli-darwin-x64"" ""1.6.0"" - ""@biomejs/cli-linux-arm64"" ""1.6.0"" - ""@biomejs/cli-linux-arm64-musl"" ""1.6.0"" - ""@biomejs/cli-linux-x64"" ""1.6.0"" - ""@biomejs/cli-linux-x64-musl"" ""1.6.0"" - ""@biomejs/cli-win32-arm64"" ""1.6.0"" - ""@biomejs/cli-win32-x64"" ""1.6.0"" - -""@biomejs/cli-darwin-arm64@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-1.6.0.tgz#60f3620ccb2aac618afd9cd119291afa69d4aabf"" - integrity sha512-K1Fjqye5pt+Ua+seC7V/2bFjfnqOaEOcQbBQSiiefB/VPNOb6lA5NFIfJ1PskTA3JrMXE1k7iqKQn56qrKFS6A== + ""@biomejs/cli-darwin-arm64"" ""1.7.0"" + ""@biomejs/cli-darwin-x64"" ""1.7.0"" + ""@biomejs/cli-linux-arm64"" ""1.7.0"" + ""@biomejs/cli-linux-arm64-musl"" ""1.7.0"" + ""@biomejs/cli-linux-x64"" ""1.7.0"" + ""@biomejs/cli-linux-x64-musl"" ""1.7.0"" + ""@biomejs/cli-win32-arm64"" ""1.7.0"" + ""@biomejs/cli-win32-x64"" ""1.7.0"" + +""@biomejs/cli-darwin-arm64@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-1.7.0.tgz#a247f1c4cf3f0366e1f0ccbfc8cb226f1237b354"" + integrity sha512-12TaeaKHU4SAZt0fQJ2bYk1jUb4foope7LmgDE5p3c0uMxd3mFkg1k7G721T+K6UHYULcSOQDsNNM8DhYi8Irg== -""@biomejs/cli-darwin-x64@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.6.0.tgz#dd3a0d66ff22f800bb13df33cb4dacf191eefe78"" - integrity sha512-CjEALu6vN9RbcfhaBDoj481mesUIsUjxgQn+/kiMCea+Paypqslhez1I7OwRBJnkzz+Pa+PXdABd7S30eyy6+Q== +""@biomejs/cli-darwin-x64@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.7.0.tgz#ab4b3826ca76229e5e6cda468855c24efbc85dc5"" + integrity sha512-6Qq1BSIB0cpp0cQNqO/+EiUV7FE3jMpF6w7+AgIBXp0oJxUWb2Ff0RDZdO9bfzkimXD58j0vGpNHMGnCcjDV2Q== -""@biomejs/cli-linux-arm64-musl@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.6.0.tgz#cf2b171757f4f2062076ca323f2f23c1753208e9"" - integrity sha512-prww6AUuJ+IO/GziN3WjtGM/DNOVuPFxqWrK97wKTZygEDdA+o1qHUN2HeCkSyk084xnzbMSbls5xscAKAn43A== +""@biomejs/cli-linux-arm64-musl@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.7.0.tgz#8a479f3a1be968dc685b8c0e60e32521732e9867"" + integrity sha512-pwIY80nU7SAxrVVZ6HD9ah1pruwh9ZqlSR0Nvbg4ZJqQa0POhiB+RJx7+/1Ml2mTZdrl8kb/YiwQpD16uwb5wg== -""@biomejs/cli-linux-arm64@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.6.0.tgz#a7f2761d8566b2fdc78e09fc0d85cf1fccce602e"" - integrity sha512-32LVrC7dAgQT39YZ0ieO/VzzpAflozs9mW5K0oKNef7S4ocCdk89E98eXApxOdei0JTf3vfseDCl1AUIp6MwJw== +""@biomejs/cli-linux-arm64@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.7.0.tgz#c1edaa4ddc071400bddec6cf180f9248958b66cb"" + integrity sha512-GwSci7xBJ2j1CrdDXDUVXnUtrvypEz/xmiYPpFeVdlX5p95eXx+7FekPPbJfhGGw5WKSsKZ+V8AAlbN+kUwJWw== -""@biomejs/cli-linux-x64-musl@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.6.0.tgz#95e17927d498af868cca32e3be79132ddeb3036f"" - integrity sha512-NwitWeUKCy8G/rr+rgHPYirnrsOjJEJBWODdaRzweeFNcJjvO6de6AmNdSJzsewzLEaxjOWyoXU03MdzbGz/6Q== +""@biomejs/cli-linux-x64-musl@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.7.0.tgz#ff37c3306d719120139cefd4ab2e10912c0414f2"" + integrity sha512-KzCA0mW4LSbCd7XZWaEJvTOTTBjfJoVEXkfq1fsXxww1HB+ww5PGMbhbIcbYCsj2CTJUifeD5hOkyuBVppU1xQ== -""@biomejs/cli-linux-x64@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-x64/-/cli-linux-x64-1.6.0.tgz#bcab0e71981a5601d85ea3ef09454b262764b776"" - integrity sha512-b6mWu9Cu4w5B3K46wq9SlxKEZEEL6II/6HFNAuZ4YL8mOeQ0FTMU+wNMJFKkmkSE2zvim3xwW3PknmbLKbe3Mg== +""@biomejs/cli-linux-x64@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-linux-x64/-/cli-linux-x64-1.7.0.tgz#c2de603cbfeaa1db268b396adc280df1b540386f"" + integrity sha512-1y+odKQsyHcw0JCGRuqhbx7Y6jxOVSh4lGIVDdJxW1b55yD22DY1kcMEfhUte6f95OIc2uqfkwtiI6xQAiZJdw== -""@biomejs/cli-win32-arm64@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.6.0.tgz#af94814be3c15ae4d201c01708a4ef79378cad36"" - integrity sha512-DlNOL6mG+76iZS1gL/UiuMme7jnt+auzo2+u0aUq6UXYsb75juchwlnVLy2UV5CQjVBRB8+RM+KVoXRZ8NlBjQ== +""@biomejs/cli-win32-arm64@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.7.0.tgz#feb48c1a8a3522083b4924f194b5febe06fd94fe"" + integrity sha512-AvLDUYZBpOUFgS/mni4VruIoVV3uSGbKSkZQBPXsHgL0w4KttLll3NBrVanmWxOHsom6C6ocHLyfAY8HUc8TXg== -""@biomejs/cli-win32-x64@1.6.0"": - version ""1.6.0"" - resolved ""https://registry.yarnpkg.com/@biomejs/cli-win32-x64/-/cli-win32-x64-1.6.0.tgz#a90b549170864eff030a6b7e395f48ead5193170"" - integrity sha512-sXBcXIOGuG8/XcHqmnkhLIs0oy6Dp+TkH4Alr4WH/P8mNsp5GcStI/ZwbEiEoxA0P3Fi+oUppQ6srxaY2rSCHg== +""@biomejs/cli-win32-x64@1.7.0"": + version ""1.7.0"" + resolved ""https://registry.yarnpkg.com/@biomejs/cli-win32-x64/-/cli-win32-x64-1.7.0.tgz#cc95cde067bd692339e6b7b92d049c25c023c2b4"" + integrity sha512-Pylm00BAAuLVb40IH9PC17432BTsY8K4pSUvhvgR1eaalnMaD6ug9SYJTTzKDbT6r24MPAGCTiSZERyhGkGzFQ== ""@codecov/bundler-plugin-core@^0.0.1-beta.6"": version ""0.0.1-beta.6""" 9588b119b17cbcdb18f71115285298277f111829,2022-07-13 21:03:37,Tony Xiao,tests(discover): Improve stability of events geo tests (#36619),False,Improve stability of events geo tests (#36619),tests,"diff --git a/tests/snuba/api/endpoints/test_organization_events_geo.py b/tests/snuba/api/endpoints/test_organization_events_geo.py index eb50f1a64d41e4..a4ef3f5acae7ff 100644 --- a/tests/snuba/api/endpoints/test_organization_events_geo.py +++ b/tests/snuba/api/endpoints/test_organization_events_geo.py @@ -7,7 +7,7 @@ class OrganizationEventsGeoEndpointTest(APITestCase, SnubaTestCase): def setUp(self): super().setUp() - self.min_ago = iso_format(before_now(minutes=1)) + self.ten_mins_ago = iso_format(before_now(minutes=10)) self.features = {} def do_request(self, query, features=None): @@ -51,18 +51,18 @@ def test_require_aggregate_field(self): def test_happy_path(self): other_project = self.create_project() self.store_event( - data={""event_id"": ""a"" * 32, ""environment"": ""staging"", ""timestamp"": self.min_ago}, + data={""event_id"": ""a"" * 32, ""environment"": ""staging"", ""timestamp"": self.ten_mins_ago}, project_id=self.project.id, ) self.store_event( - data={""event_id"": ""b"" * 32, ""environment"": ""staging"", ""timestamp"": self.min_ago}, + data={""event_id"": ""b"" * 32, ""environment"": ""staging"", ""timestamp"": self.ten_mins_ago}, project_id=other_project.id, ) self.store_event( data={ ""event_id"": ""c"" * 32, ""environment"": ""production"", - ""timestamp"": self.min_ago, + ""timestamp"": self.ten_mins_ago, ""user"": { ""email"": ""foo@example.com"", ""id"": ""123"", @@ -92,7 +92,7 @@ def test_only_use_last_field(self): data={ ""event_id"": ""a"" * 32, ""environment"": ""staging"", - ""timestamp"": self.min_ago, + ""timestamp"": self.ten_mins_ago, ""user"": { ""email"": ""foo@example.com"", ""id"": ""123"", @@ -120,7 +120,7 @@ def get_mock_data(index, geo): return { ""event_id"": str(index) * 32, ""environment"": ""staging"", - ""timestamp"": self.min_ago, + ""timestamp"": self.ten_mins_ago, ""user"": { ""email"": ""foo@example.com"", ""id"": ""123""," 3183b13afc2fed76d686571f1dd88f4eaf78341c,2022-10-04 00:28:44,Malachi Willey,ref(ui): Make stack trace tooltip generic for more issue types (#39483),False,Make stack trace tooltip generic for more issue types (#39483),ref,"diff --git a/static/app/components/eventOrGroupHeader.spec.tsx b/static/app/components/eventOrGroupHeader.spec.tsx index 22e3975f3e1a78..2e43cd54c5f984 100644 --- a/static/app/components/eventOrGroupHeader.spec.tsx +++ b/static/app/components/eventOrGroupHeader.spec.tsx @@ -4,6 +4,7 @@ import {textWithMarkupMatcher} from 'sentry-test/utils'; import EventOrGroupHeader from 'sentry/components/eventOrGroupHeader'; import {EventOrGroupType} from 'sentry/types'; +import {OrganizationContext} from 'sentry/views/organizationContext'; const group = TestStubs.Group({ level: 'error', @@ -39,7 +40,9 @@ describe('EventOrGroupHeader', function () { describe('Group', function () { it('renders with `type = error`', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); @@ -47,14 +50,16 @@ describe('EventOrGroupHeader', function () { it('renders with `type = csp`', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); @@ -62,18 +67,20 @@ describe('EventOrGroupHeader', function () { it('renders with `type = default`', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); @@ -81,14 +88,16 @@ describe('EventOrGroupHeader', function () { it('renders metadata values in message for error events', function () { render( - + + + ); expect(screen.getByText('metadata value')).toBeInTheDocument(); @@ -96,18 +105,20 @@ describe('EventOrGroupHeader', function () { it('renders location', function () { render( - + + + ); expect( @@ -119,87 +130,97 @@ describe('EventOrGroupHeader', function () { describe('Event', function () { it('renders with `type = error`', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); }); it('renders with `type = csp`', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); }); it('renders with `type = default`', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); }); it('hides level tag', function () { const {container} = render( - + + + ); expect(container).toSnapshot(); }); it('keeps sort in link when query has sort', function () { render( - + + + ); expect(screen.getByRole('link')).toHaveAttribute( @@ -210,18 +231,20 @@ describe('EventOrGroupHeader', function () { it('lack of project adds allp parameter', function () { render( - + + + ); expect(screen.getByRole('link')).toHaveAttribute( diff --git a/static/app/components/eventOrGroupTitle.tsx b/static/app/components/eventOrGroupTitle.tsx index fe855ed6b772c7..de1ae892d12fbe 100644 --- a/static/app/components/eventOrGroupTitle.tsx +++ b/static/app/components/eventOrGroupTitle.tsx @@ -2,14 +2,13 @@ import {Fragment} from 'react'; import {css} from '@emotion/react'; import styled from '@emotion/styled'; -import ProjectsStore from 'sentry/stores/projectsStore'; -import {BaseGroup, GroupTombstone, IssueCategory, Organization} from 'sentry/types'; +import {BaseGroup, GroupTombstone, Organization} from 'sentry/types'; import {Event} from 'sentry/types/event'; import {getTitle} from 'sentry/utils/events'; import withOrganization from 'sentry/utils/withOrganization'; import EventTitleTreeLabel from './eventTitleTreeLabel'; -import {StackTracePreview} from './stacktracePreview'; +import GroupPreviewTooltip from './groupPreviewTooltip'; type Props = { data: Event | BaseGroup | GroupTombstone; @@ -33,28 +32,22 @@ function EventOrGroupTitle({ const groupingIssueCategory = (data as BaseGroup)?.issueCategory; const hasGroupingTreeUI = !!organization?.features.includes('grouping-tree-ui'); - const hasGroupingStacktraceUI = !!organization?.features.includes( - 'grouping-stacktrace-ui' - ); const {id, eventID, groupID, projectID} = event; const {title, subtitle, treeLabel} = getTitle(event, organization?.features, grouping); return ( - {withStackTracePreview && groupingIssueCategory === IssueCategory.ERROR ? ( - - {treeLabel ? : title} - + {treeLabel ? : title ?? ''} + ) : treeLabel ? ( ) : ( @@ -85,21 +78,6 @@ const Subtitle = styled('em')` font-style: normal; `; -const StyledStacktracePreview = styled(StackTracePreview)<{ - hasGroupingStacktraceUI: boolean; -}>` - ${p => - p.hasGroupingStacktraceUI && - css` - display: inline-flex; - overflow: hidden; - height: 100%; - > span:first-child { - ${p.theme.overflowEllipsis} - } - `} -`; - const Wrapper = styled('span')<{hasGroupingTreeUI: boolean}>` font-size: ${p => p.theme.fontSizeLarge}; ${p => diff --git a/static/app/components/groupPreviewTooltip/index.tsx b/static/app/components/groupPreviewTooltip/index.tsx new file mode 100644 index 00000000000000..226d1814534bf6 --- /dev/null +++ b/static/app/components/groupPreviewTooltip/index.tsx @@ -0,0 +1,44 @@ +import {Fragment, ReactChild} from 'react'; + +import ProjectsStore from 'sentry/stores/projectsStore'; +import {IssueCategory} from 'sentry/types'; + +import {StackTracePreview} from './stackTracePreview'; + +type GroupPreviewTooltipProps = { + children: ReactChild; + groupId: string; + issueCategory: IssueCategory; + // we need eventId only when hovering over Event, not Group + // (different API call is made to get the stack trace then) + eventId?: string; + groupingCurrentLevel?: number; + projectId?: string; +}; + +const GroupPreviewTooltip = ({ + children, + eventId, + groupId, + groupingCurrentLevel, + issueCategory, + projectId, +}: GroupPreviewTooltipProps) => { + switch (issueCategory) { + case IssueCategory.ERROR: + return ( + + {children} + + ); + default: + return {children}; + } +}; + +export default GroupPreviewTooltip; diff --git a/static/app/components/stackTracePreview.spec.tsx b/static/app/components/groupPreviewTooltip/stackTracePreview.spec.tsx similarity index 78% rename from static/app/components/stackTracePreview.spec.tsx rename to static/app/components/groupPreviewTooltip/stackTracePreview.spec.tsx index fbfe3185f1d289..93009616c96cd1 100644 --- a/static/app/components/stackTracePreview.spec.tsx +++ b/static/app/components/groupPreviewTooltip/stackTracePreview.spec.tsx @@ -1,13 +1,14 @@ import {initializeOrg} from 'sentry-test/initializeOrg'; import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary'; -import {StackTracePreview} from 'sentry/components/stacktracePreview'; -import {EventError} from 'sentry/types'; +import {EventError, Organization} from 'sentry/types'; import {EntryType, Event, ExceptionType, ExceptionValue, Frame} from 'sentry/types/event'; import useApi from 'sentry/utils/useApi'; import {OrganizationContext} from 'sentry/views/organizationContext'; import {RouteContext} from 'sentry/views/routeContext'; +import {StackTracePreview} from './stackTracePreview'; + const makeEvent = (event: Partial = {}): Event => { const evt: Event = { ...TestStubs.Event(), @@ -17,11 +18,11 @@ const makeEvent = (event: Partial = {}): Event => { return evt; }; -function TestComponent({children}: {children: React.ReactNode}) { +function TestComponent({org, children}: {children: React.ReactNode; org?: Organization}) { const {organization, router} = initializeOrg(); return ( - + { render( - + Preview Trigger @@ -66,7 +62,7 @@ describe('StackTracePreview', () => { await waitFor(() => { expect(spy.mock.calls[0][0]).toBe( - `/projects/org_slug/project_slug/events/event_id/` + `/projects/org-slug/project_slug/events/event_id/` ); }); }); @@ -82,12 +78,7 @@ describe('StackTracePreview', () => { render( - - Preview Trigger - + Preview Trigger ); @@ -111,12 +102,7 @@ describe('StackTracePreview', () => { render( - - Preview Trigger - + Preview Trigger ); @@ -136,12 +122,7 @@ describe('StackTracePreview', () => { render( - - Preview Trigger - + Preview Trigger ); @@ -214,16 +195,8 @@ describe('StackTracePreview', () => { useApi.mockReturnValue(api); render( - - - Preview Trigger - + + Preview Trigger ); diff --git a/static/app/components/stacktracePreview.tsx b/static/app/components/groupPreviewTooltip/stackTracePreview.tsx similarity index 88% rename from static/app/components/stacktracePreview.tsx rename to static/app/components/groupPreviewTooltip/stackTracePreview.tsx index fe23286b38d5fa..2de38e506af7de 100644 --- a/static/app/components/stacktracePreview.tsx +++ b/static/app/components/groupPreviewTooltip/stackTracePreview.tsx @@ -1,23 +1,24 @@ import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import {css} from '@emotion/react'; import styled from '@emotion/styled'; import StackTraceContent from 'sentry/components/events/interfaces/crashContent/stackTrace/content'; import StackTraceContentV2 from 'sentry/components/events/interfaces/crashContent/stackTrace/contentV2'; import StackTraceContentV3 from 'sentry/components/events/interfaces/crashContent/stackTrace/contentV3'; +import findBestThread from 'sentry/components/events/interfaces/threads/threadSelector/findBestThread'; +import getThreadStacktrace from 'sentry/components/events/interfaces/threads/threadSelector/getThreadStacktrace'; import {isStacktraceNewestFirst} from 'sentry/components/events/interfaces/utils'; import {Body, Hovercard} from 'sentry/components/hovercard'; import LoadingIndicator from 'sentry/components/loadingIndicator'; import {t} from 'sentry/locale'; import space from 'sentry/styles/space'; -import {Organization, PlatformType} from 'sentry/types'; +import {PlatformType} from 'sentry/types'; import {EntryType, Event} from 'sentry/types/event'; import {StacktraceType} from 'sentry/types/stacktrace'; import {defined} from 'sentry/utils'; import {isNativePlatform} from 'sentry/utils/platform'; import useApi from 'sentry/utils/useApi'; - -import findBestThread from './events/interfaces/threads/threadSelector/findBestThread'; -import getThreadStacktrace from './events/interfaces/threads/threadSelector/getThreadStacktrace'; +import useOrganization from 'sentry/utils/useOrganization'; const REQUEST_DELAY = 100; const HOVERCARD_CONTENT_DELAY = 400; @@ -100,8 +101,6 @@ function StackTracePreviewContent({ type StackTracePreviewProps = { children: React.ReactNode; issueId: string; - organization: Organization; - className?: string; eventId?: string; groupingCurrentLevel?: number; projectSlug?: string; @@ -109,6 +108,7 @@ type StackTracePreviewProps = { function StackTracePreview(props: StackTracePreviewProps): React.ReactElement { const api = useApi(); + const organization = useOrganization(); const [loadingVisible, setLoadingVisible] = useState(false); const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading'); @@ -143,7 +143,7 @@ function StackTracePreview(props: StackTracePreviewProps): React.ReactElement { try { const evt = await api.requestPromise( props.eventId && props.projectSlug - ? `/projects/${props.organization.slug}/${props.projectSlug}/events/${props.eventId}/` + ? `/projects/${organization.slug}/${props.projectSlug}/events/${props.eventId}/` : `/issues/${props.issueId}/events/latest/?collapse=stacktraceOnly` ); window.clearTimeout(loaderTimeoutRef.current); @@ -156,14 +156,7 @@ function StackTracePreview(props: StackTracePreviewProps): React.ReactElement { setStatus('error'); setLoadingVisible(false); } - }, [ - event, - api, - props.organization.slug, - props.projectSlug, - props.eventId, - props.issueId, - ]); + }, [event, api, organization.slug, props.projectSlug, props.eventId, props.issueId]); const handleMouseEnter = useCallback(() => { window.clearTimeout(delayTimeoutRef.current); @@ -185,12 +178,16 @@ function StackTracePreview(props: StackTracePreviewProps): React.ReactElement { const stacktrace = useMemo(() => (event ? getStacktrace(event) : null), [event]); + const hasGroupingStacktraceUI = organization.features.includes( + 'grouping-stacktrace-ui' + ); + return ( -
) @@ -231,12 +228,27 @@ function StackTracePreview(props: StackTracePreviewProps): React.ReactElement { > {props.children} - + ); } export {StackTracePreview}; +const Wrapper = styled('span')<{ + hasGroupingStacktraceUI: boolean; +}>` + ${p => + p.hasGroupingStacktraceUI && + css` + display: inline-flex; + overflow: hidden; + height: 100%; + > span:first-child { + ${p.theme.overflowEllipsis} + } + `} +`; + const StacktraceHovercard = styled(Hovercard)<{state: 'loading' | 'empty' | 'done'}>` /* Lower z-index to match the modals (10000 vs 10002) to allow stackTraceLinkModal be on top of stack trace preview. */ z-index: ${p => p.theme.zIndex.modal}; diff --git a/static/app/views/projectDetail/projectIssues.spec.jsx b/static/app/views/projectDetail/projectIssues.spec.jsx index 898c780ac211af..15c713428f3cd6 100644 --- a/static/app/views/projectDetail/projectIssues.spec.jsx +++ b/static/app/views/projectDetail/projectIssues.spec.jsx @@ -3,6 +3,8 @@ import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; import ProjectIssues from 'sentry/views/projectDetail/projectIssues'; +import {OrganizationContext} from '../organizationContext'; + describe('ProjectDetail > ProjectIssues', function () { let endpointMock, filteredEndpointMock; const {organization, router, routerContext} = initializeOrg({ @@ -38,18 +40,28 @@ describe('ProjectDetail > ProjectIssues', function () { url: `/organizations/org-slug/issues/?limit=5&query=error.unhandled%3Atrue%20is%3Aunresolved&sort=freq&statsPeriod=14d`, body: [TestStubs.Group(), TestStubs.Group({id: '2'})], }); - render(, { - context: routerContext, - }); + render( + + + , + { + context: routerContext, + } + ); expect(await screen.findAllByTestId('group')).toHaveLength(2); }); it('renders a link to Issues', function () { MockApiClient.warnOnMissingMocks(); - render(, { - context: routerContext, - }); + render( + + + , + { + context: routerContext, + } + ); const link = screen.getByLabelText('Open in Issues'); expect(link).toBeInTheDocument(); @@ -68,9 +80,14 @@ describe('ProjectDetail > ProjectIssues', function () { it('renders a link to Discover', function () { MockApiClient.warnOnMissingMocks(); - render(, { - context: routerContext, - }); + render( + + + , + { + context: routerContext, + } + ); const link = screen.getByLabelText('Open in Discover'); expect(link).toBeInTheDocument(); @@ -91,12 +108,14 @@ describe('ProjectDetail > ProjectIssues', function () { it('changes according to global header', function () { render( - , + + + , {context: routerContext} );" b58ec7f496fe57beaeb88bafbc6509f4216bf13e,2023-08-11 02:20:28,Scott Cooper,fix(ui): Remove unused props exports (#54582),False,Remove unused props exports (#54582),fix,"diff --git a/static/app/components/acl/access.tsx b/static/app/components/acl/access.tsx index 721b65e9f61185..f883bbe455eff3 100644 --- a/static/app/components/acl/access.tsx +++ b/static/app/components/acl/access.tsx @@ -14,7 +14,7 @@ type ChildRenderProps = { type ChildFunction = (props: ChildRenderProps) => JSX.Element; -export type Props = { +type Props = { organization: Organization; /** * List of required access levels diff --git a/static/app/views/issueDetails/allEventsTable.tsx b/static/app/views/issueDetails/allEventsTable.tsx index af4abef0e11904..f98fb93fb98909 100644 --- a/static/app/views/issueDetails/allEventsTable.tsx +++ b/static/app/views/issueDetails/allEventsTable.tsx @@ -17,7 +17,7 @@ import {useApiQuery} from 'sentry/utils/queryClient'; import {useRoutes} from 'sentry/utils/useRoutes'; import EventsTable from 'sentry/views/performance/transactionSummary/transactionEvents/eventsTable'; -export interface Props { +interface Props { group: Group; issueId: string; location: Location; diff --git a/static/app/views/settings/account/notifications/notificationSettingsByProjects.tsx b/static/app/views/settings/account/notifications/notificationSettingsByProjects.tsx index 90a7508a3cdc04..81e9c1d27ae5e4 100644 --- a/static/app/views/settings/account/notifications/notificationSettingsByProjects.tsx +++ b/static/app/views/settings/account/notifications/notificationSettingsByProjects.tsx @@ -40,7 +40,7 @@ export type NotificationSettingsByProjectsBaseProps = { onSubmitSuccess: () => void; }; -export type Props = { +type Props = { organizations: Organization[]; } & NotificationSettingsByProjectsBaseProps & DeprecatedAsyncComponent['props'] &" cffc4ff21df105f8bd5d107752cabb71c86a6db6,2024-09-09 23:44:23,Katie Byers,chore(seer grouping): Stop using `similarity-embeddings-grouping` feature flag (#77116),False,Stop using `similarity-embeddings-grouping` feature flag (#77116),chore,"diff --git a/src/sentry/api/endpoints/project_details.py b/src/sentry/api/endpoints/project_details.py index 9ab2a8419d3bae..de54f967610ed6 100644 --- a/src/sentry/api/endpoints/project_details.py +++ b/src/sentry/api/endpoints/project_details.py @@ -954,9 +954,7 @@ def delete(self, request: Request, project) -> Response: project.rename_on_pending_deletion() # Tell seer to delete all the project's grouping records - if features.has( - ""projects:similarity-embeddings-grouping"", project - ) or project.get_option(""sentry:similarity_backfill_completed""): + if project.get_option(""sentry:similarity_backfill_completed""): call_seer_delete_project_grouping_records.apply_async(args=[project.id]) return Response(status=204) diff --git a/src/sentry/grouping/ingest/seer.py b/src/sentry/grouping/ingest/seer.py index 1ff22808328b23..8b991adb1637f2 100644 --- a/src/sentry/grouping/ingest/seer.py +++ b/src/sentry/grouping/ingest/seer.py @@ -5,7 +5,7 @@ import sentry_sdk from django.conf import settings -from sentry import features, options +from sentry import options from sentry import ratelimits as ratelimiter from sentry.conf.server import SEER_SIMILARITY_MODEL_VERSION from sentry.eventstore.models import Event @@ -61,21 +61,19 @@ def should_call_seer_for_grouping(event: Event, primary_hashes: CalculatedHashes def _project_has_similarity_grouping_enabled(project: Project) -> bool: - has_seer_grouping_flag_on = features.has(""projects:similarity-embeddings-grouping"", project) - # TODO: This is a hack to get ingest to turn on for projects as soon as they're backfilled. When # the backfill script completes, we turn on this option, enabling ingest immediately rather than # forcing the project to wait until it's been manually added to a feature handler. Once all # projects have been backfilled, the option (and this check) can go away. - has_been_backfilled = project.get_option(""sentry:similarity_backfill_completed"") + has_been_backfilled = bool(project.get_option(""sentry:similarity_backfill_completed"")) metrics.incr( ""grouping.similarity.event_project_backfill_status"", sample_rate=options.get(""seer.similarity.metrics_sample_rate""), - tags={""backfilled"": bool(has_seer_grouping_flag_on or has_been_backfilled)}, + tags={""backfilled"": has_been_backfilled}, ) - return has_seer_grouping_flag_on or has_been_backfilled + return has_been_backfilled # TODO: Here we're including events with hybrid fingerprints (ones which are `{{ default }}` diff --git a/src/sentry/tasks/delete_seer_grouping_records.py b/src/sentry/tasks/delete_seer_grouping_records.py index 70b670c403b346..4deaec4d3525a5 100644 --- a/src/sentry/tasks/delete_seer_grouping_records.py +++ b/src/sentry/tasks/delete_seer_grouping_records.py @@ -1,7 +1,7 @@ import logging from typing import Any -from sentry import features, options +from sentry import options from sentry.models.group import Group from sentry.models.grouphash import GroupHash from sentry.seer.similarity.grouping_records import ( @@ -56,10 +56,7 @@ def call_delete_seer_grouping_records_by_hash( project = group.project if group else None if ( project - and ( - features.has(""projects:similarity-embeddings-grouping"", project) - or project.get_option(""sentry:similarity_backfill_completed"") - ) + and project.get_option(""sentry:similarity_backfill_completed"") and not killswitch_enabled(project.id) and not options.get(""seer.similarity-embeddings-delete-by-hash-killswitch.enabled"") ): diff --git a/tests/sentry/api/endpoints/test_project_details.py b/tests/sentry/api/endpoints/test_project_details.py index 9150a853c94923..ece879fb1ed4e0 100644 --- a/tests/sentry/api/endpoints/test_project_details.py +++ b/tests/sentry/api/endpoints/test_project_details.py @@ -1591,13 +1591,13 @@ def test_internal_project(self): model_name=""Project"", object_id=self.project.id ).exists() - @with_feature(""projects:similarity-embeddings-grouping"") @mock.patch( ""sentry.tasks.delete_seer_grouping_records.call_seer_delete_project_grouping_records.apply_async"" ) def test_delete_project_and_delete_grouping_records( self, mock_call_seer_delete_project_grouping_records ): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) self._delete_project_and_assert_deleted() mock_call_seer_delete_project_grouping_records.assert_called_with(args=[self.project.id]) diff --git a/tests/sentry/api/helpers/test_group_index.py b/tests/sentry/api/helpers/test_group_index.py index 56e6f2706e4ae8..1ad1e035d7ac1c 100644 --- a/tests/sentry/api/helpers/test_group_index.py +++ b/tests/sentry/api/helpers/test_group_index.py @@ -1,4 +1,5 @@ from datetime import UTC, datetime, timedelta +from time import time from unittest.mock import MagicMock, Mock, patch import pytest @@ -1085,7 +1086,6 @@ def test_delete_groups_simple(self, send_robust: Mock): ) assert send_robust.called - @with_feature(""projects:similarity-embeddings-grouping"") @patch( ""sentry.tasks.delete_seer_grouping_records.delete_seer_grouping_records_by_hash.apply_async"" ) @@ -1094,6 +1094,8 @@ def test_delete_groups_simple(self, send_robust: Mock): def test_delete_groups_deletes_seer_records_by_hash( self, send_robust: Mock, mock_logger: Mock, mock_delete_seer_grouping_records_by_hash ): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + groups = [self.create_group(), self.create_group()] group_ids = [group.id for group in groups] request = self.make_request(user=self.user, method=""GET"") diff --git a/tests/sentry/deletions/test_group.py b/tests/sentry/deletions/test_group.py index 50e250746f1e3d..f9f65bfe8ff083 100644 --- a/tests/sentry/deletions/test_group.py +++ b/tests/sentry/deletions/test_group.py @@ -1,3 +1,4 @@ +from time import time from unittest import mock from uuid import uuid4 @@ -16,7 +17,6 @@ from sentry.tasks.deletion.groups import delete_groups from sentry.testutils.cases import SnubaTestCase, TestCase from sentry.testutils.helpers.datetime import before_now, iso_format -from sentry.testutils.helpers.features import with_feature class DeleteGroupTest(TestCase, SnubaTestCase): @@ -170,13 +170,13 @@ def test_cleanup(self, nodestore_delete_multi, os_environ): assert nodestore_delete_multi.call_count == 0 - @with_feature(""projects:similarity-embeddings-grouping"") @mock.patch( ""sentry.tasks.delete_seer_grouping_records.delete_seer_grouping_records_by_hash.apply_async"" ) def test_delete_groups_delete_grouping_records_by_hash( self, mock_delete_seer_grouping_records_by_hash_apply_async ): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) other_event = self.store_event( data={ ""event_id"": ""d"" * 32, diff --git a/tests/sentry/event_manager/grouping/test_seer_grouping.py b/tests/sentry/event_manager/grouping/test_seer_grouping.py index 36a2bfaa60c0e9..6aef13fa8e83e2 100644 --- a/tests/sentry/event_manager/grouping/test_seer_grouping.py +++ b/tests/sentry/event_manager/grouping/test_seer_grouping.py @@ -1,4 +1,5 @@ from dataclasses import asdict +from time import time from typing import Any from unittest.mock import MagicMock, patch @@ -7,9 +8,7 @@ from sentry.models.grouphash import GroupHash from sentry.seer.similarity.types import SeerSimilarIssueData from sentry.testutils.cases import TestCase -from sentry.testutils.helpers import Feature from sentry.testutils.helpers.eventprocessing import save_new_event -from sentry.testutils.helpers.features import with_feature from sentry.testutils.pytest.mocking import capture_results from sentry.utils.types import NonNone @@ -50,45 +49,47 @@ def test_obeys_seer_similarity_flags(self): ), ): - with Feature({""projects:similarity-embeddings-grouping"": False}): - new_event = save_new_event({""message"": ""Adopt don't shop""}, self.project) - - # We checked whether to make the call, but didn't go through with it - assert should_call_seer_spy.call_count == 1 - assert get_seer_similar_issues_spy.call_count == 0 - - # No metadata stored, parent group not used (even though `should_group` is True) - assert ""seer_similarity"" not in NonNone(new_event.group).data[""metadata""] - assert ""seer_similarity"" not in new_event.data - assert new_event.group_id != existing_event.group_id - - should_call_seer_spy.reset_mock() - get_seer_similar_issues_spy.reset_mock() - - with Feature({""projects:similarity-embeddings-grouping"": True}): - new_event = save_new_event({""message"": ""Maisey is silly""}, self.project) - expected_metadata = { - ""similarity_model_version"": SEER_SIMILARITY_MODEL_VERSION, - ""results"": [asdict(seer_result_data)], - } - # In real life just filtering on group id wouldn't be enough to guarantee us a - # single, specific GroupHash record, but since the database resets before each test, - # here it's okay - expected_grouphash = GroupHash.objects.filter( - group_id=NonNone(existing_event.group_id) - ).first() - - # We checked whether to make the call, and then made it - assert should_call_seer_spy.call_count == 1 - assert get_seer_similar_issues_spy.call_count == 1 - - # Metadata returned and stored - assert get_seer_similar_issues_return_values[0][0] == expected_metadata - assert new_event.data[""seer_similarity""] == expected_metadata - - # Parent grouphash returned and parent group used - assert get_seer_similar_issues_return_values[0][1] == expected_grouphash - assert new_event.group_id == existing_event.group_id + # Project option not set + self.project.update_option(""sentry:similarity_backfill_completed"", None) + new_event = save_new_event({""message"": ""Adopt don't shop""}, self.project) + + # We checked whether to make the call, but didn't go through with it + assert should_call_seer_spy.call_count == 1 + assert get_seer_similar_issues_spy.call_count == 0 + + # No metadata stored, parent group not used (even though `should_group` is True) + assert ""seer_similarity"" not in NonNone(new_event.group).data[""metadata""] + assert ""seer_similarity"" not in new_event.data + assert new_event.group_id != existing_event.group_id + + should_call_seer_spy.reset_mock() + get_seer_similar_issues_spy.reset_mock() + + # Project option set + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + new_event = save_new_event({""message"": ""Maisey is silly""}, self.project) + expected_metadata = { + ""similarity_model_version"": SEER_SIMILARITY_MODEL_VERSION, + ""results"": [asdict(seer_result_data)], + } + # In real life just filtering on group id wouldn't be enough to guarantee us a + # single, specific GroupHash record, but since the database resets before each test, + # here it's okay + expected_grouphash = GroupHash.objects.filter( + group_id=NonNone(existing_event.group_id) + ).first() + + # We checked whether to make the call, and then made it + assert should_call_seer_spy.call_count == 1 + assert get_seer_similar_issues_spy.call_count == 1 + + # Metadata returned and stored + assert get_seer_similar_issues_return_values[0][0] == expected_metadata + assert new_event.data[""seer_similarity""] == expected_metadata + + # Parent grouphash returned and parent group used + assert get_seer_similar_issues_return_values[0][1] == expected_grouphash + assert new_event.group_id == existing_event.group_id @patch(""sentry.grouping.ingest.seer.should_call_seer_for_grouping"", return_value=True) @patch(""sentry.grouping.ingest.seer.get_seer_similar_issues"", return_value=({}, None)) @@ -159,7 +160,6 @@ def test_stores_seer_results_in_metadata(self, _): assert new_event.data[""seer_similarity""] == expected_metadata - @with_feature(""projects:similarity-embeddings-grouping"") @patch(""sentry.grouping.ingest.seer.should_call_seer_for_grouping"", return_value=True) def test_assigns_event_to_neighbor_group_if_found(self, _): for use_optimized_grouping, existing_event_message, new_event_message in [ @@ -191,7 +191,6 @@ def test_assigns_event_to_neighbor_group_if_found(self, _): mock_get_similarity_data.reset_mock() - @with_feature(""projects:similarity-embeddings-grouping"") @patch(""sentry.grouping.ingest.seer.should_call_seer_for_grouping"", return_value=True) def test_creates_new_group_if_no_neighbor_found(self, _): for use_optimized_grouping, existing_event_message, new_event_message in [ diff --git a/tests/sentry/grouping/ingest/test_seer.py b/tests/sentry/grouping/ingest/test_seer.py index 003c41e1b03fa9..3b76606dc0db40 100644 --- a/tests/sentry/grouping/ingest/test_seer.py +++ b/tests/sentry/grouping/ingest/test_seer.py @@ -1,4 +1,5 @@ from dataclasses import asdict +from time import time from unittest.mock import MagicMock, patch from sentry.conf.server import SEER_SIMILARITY_MODEL_VERSION @@ -8,9 +9,7 @@ from sentry.models.grouphash import GroupHash from sentry.seer.similarity.types import SeerSimilarIssueData from sentry.testutils.cases import TestCase -from sentry.testutils.helpers import Feature from sentry.testutils.helpers.eventprocessing import save_new_event -from sentry.testutils.helpers.features import with_feature from sentry.testutils.helpers.options import override_options from sentry.utils.types import NonNone @@ -47,23 +46,17 @@ def setUp(self): self.primary_hashes = self.event.get_hashes() def test_obeys_feature_enablement_check(self): - for grouping_flag, backfill_completed_option, expected_result in [ - (False, None, False), - (True, None, True), - (False, 11211231, True), - (True, 11211231, True), - ]: - with Feature({""projects:similarity-embeddings-grouping"": grouping_flag}): - self.project.update_option( - ""sentry:similarity_backfill_completed"", backfill_completed_option - ) - assert ( - should_call_seer_for_grouping(self.event, self.primary_hashes) - is expected_result - ), f""Case (grouping {grouping_flag}, backfill completed {backfill_completed_option}) failed."" + for backfill_completed_option, expected_result in [(None, False), (11211231, True)]: + self.project.update_option( + ""sentry:similarity_backfill_completed"", backfill_completed_option + ) + assert ( + should_call_seer_for_grouping(self.event, self.primary_hashes) is expected_result + ), f""Case {backfill_completed_option} failed."" - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_content_filter(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for content_eligibility, expected_result in [(True, True), (False, False)]: with patch( ""sentry.grouping.ingest.seer.event_content_is_seer_eligible"", @@ -74,8 +67,9 @@ def test_obeys_content_filter(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_global_seer_killswitch(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for killswitch_enabled, expected_result in [(True, False), (False, True)]: with override_options({""seer.global-killswitch.enabled"": killswitch_enabled}): assert ( @@ -83,8 +77,9 @@ def test_obeys_global_seer_killswitch(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_similarity_service_killswitch(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for killswitch_enabled, expected_result in [(True, False), (False, True)]: with override_options({""seer.similarity-killswitch.enabled"": killswitch_enabled}): assert ( @@ -92,8 +87,9 @@ def test_obeys_similarity_service_killswitch(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_project_specific_killswitch(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for blocked_projects, expected_result in [([self.project.id], False), ([], True)]: with override_options( {""seer.similarity.grouping_killswitch_projects"": blocked_projects} @@ -103,8 +99,9 @@ def test_obeys_project_specific_killswitch(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_global_ratelimit(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for ratelimit_enabled, expected_result in [(True, False), (False, True)]: with patch( ""sentry.grouping.ingest.seer.ratelimiter.backend.is_limited"", @@ -117,8 +114,9 @@ def test_obeys_global_ratelimit(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_project_ratelimit(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for ratelimit_enabled, expected_result in [(True, False), (False, True)]: with patch( ""sentry.grouping.ingest.seer.ratelimiter.backend.is_limited"", @@ -133,8 +131,9 @@ def test_obeys_project_ratelimit(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_circuit_breaker(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + for request_allowed, expected_result in [(True, True), (False, False)]: with patch( ""sentry.grouping.ingest.seer.CircuitBreaker.should_allow_request"", @@ -145,8 +144,9 @@ def test_obeys_circuit_breaker(self): is expected_result ) - @with_feature(""projects:similarity-embeddings-grouping"") def test_obeys_customized_fingerprint_check(self): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + default_fingerprint_event = Event( project_id=self.project.id, event_id=""11212012123120120415201309082013"", diff --git a/tests/sentry/tasks/test_delete_seer_grouping_records.py b/tests/sentry/tasks/test_delete_seer_grouping_records.py index 380601ef7afc33..1b637634e3ab02 100644 --- a/tests/sentry/tasks/test_delete_seer_grouping_records.py +++ b/tests/sentry/tasks/test_delete_seer_grouping_records.py @@ -1,3 +1,4 @@ +from time import time from unittest.mock import patch from sentry.models.grouphash import GroupHash @@ -7,7 +8,6 @@ delete_seer_grouping_records_by_hash, ) from sentry.testutils.cases import TestCase -from sentry.testutils.helpers.features import with_feature from sentry.testutils.pytest.fixtures import django_db_all @@ -33,9 +33,10 @@ def test_delete_seer_grouping_records_by_hash_batches( ""args"": [project_id, hashes, 100] } - @with_feature(""projects:similarity-embeddings-grouping"") @patch(""sentry.tasks.delete_seer_grouping_records.logger"") def test_call_delete_seer_grouping_records_by_hash_simple(self, mock_logger): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + group_ids, hashes = [], [] for i in range(5): group = self.create_group(project=self.project) @@ -50,12 +51,13 @@ def test_call_delete_seer_grouping_records_by_hash_simple(self, mock_logger): extra={""project_id"": self.project.id, ""hashes"": hashes}, ) - @with_feature(""projects:similarity-embeddings-grouping"") @patch(""sentry.tasks.delete_seer_grouping_records.delete_seer_grouping_records_by_hash"") @patch(""sentry.tasks.delete_seer_grouping_records.logger"") def test_call_delete_seer_grouping_records_by_hash_no_hashes( self, mock_logger, mock_delete_seer_grouping_records_by_hash ): + self.project.update_option(""sentry:similarity_backfill_completed"", int(time())) + group_ids = [] for _ in range(5): group = self.create_group(project=self.project)" d7816893f873cec1d89e35c771df1d3508c5ef7c,2021-07-29 15:19:37,Markus Unterwaditzer,fix(grouping): More categorization + instrument hash mismatch (#27781),False,More categorization + instrument hash mismatch (#27781),fix,"diff --git a/src/sentry/api/endpoints/event_grouping_info.py b/src/sentry/api/endpoints/event_grouping_info.py index 850d8bf16bbaea..38b06558fae6fd 100644 --- a/src/sentry/api/endpoints/event_grouping_info.py +++ b/src/sentry/api/endpoints/event_grouping_info.py @@ -1,10 +1,14 @@ +import logging + from django.http import HttpResponse from sentry import eventstore from sentry.api.bases.project import ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.grouping.api import GroupingConfigNotFound -from sentry.utils import json +from sentry.utils import json, metrics + +logger = logging.getLogger(__name__) class EventGroupingInfoEndpoint(ProjectEndpoint): @@ -40,11 +44,21 @@ def get(self, request, project, event_id): # Since the hashes are generated on the fly and might no # longer match the stored ones we indicate if the hash # generation caused the hash to mismatch. - d[""hashMismatch""] = ( + d[""hashMismatch""] = hash_mismatch = ( d[""hash""] is not None and d[""hash""] not in hashes.hashes and d[""hash""] not in hashes.hierarchical_hashes ) + + if hash_mismatch: + metrics.incr(""event_grouping_info.hash_mismatch"") + logger.error( + ""event_grouping_info.hash_mismatch"", + extra={""project_id"": project.id, ""event_id"": event_id}, + ) + else: + metrics.incr(""event_grouping_info.hash_match"") + d[""key""] = key rv[key] = d diff --git a/src/sentry/grouping/enhancer/enhancement-configs/mobile@2021-04-02.txt b/src/sentry/grouping/enhancer/enhancement-configs/mobile@2021-04-02.txt index f4eff46bfd8952..2c27093b5467f8 100644 --- a/src/sentry/grouping/enhancer/enhancement-configs/mobile@2021-04-02.txt +++ b/src/sentry/grouping/enhancer/enhancement-configs/mobile@2021-04-02.txt @@ -176,6 +176,7 @@ family:native function:__dynamic_cast category=indirection family:native function:boost::function* category=indirection family:native function:boost::_bi::* category=indirection family:native function:boost::detail::function::functor_manager* category=indirection +family:native function:Array.subscript.* category=indirection module:java.lang.reflect.* category=indirection module:java.lang.Class function:getMethod category=indirection module:androidx.work.impl.utils.ForceStopRunnable category=indirection @@ -246,6 +247,8 @@ module:com.lenovo.payplus.analytics.* category=telemetry package:""**/libBugly.so"" category=telemetry family:native function:dlopen category=load +family:native function:dladdr category=load +family:native function:ImageLoaderMachO::findClosestSymbol category=load family:native package:/system/lib/libnativeloader.so function:android::OpenNativeLibrary category=load module:java.lang.System function:loadLibrary category=load module:java.lang.Runtime function:loadLibrary* category=load diff --git a/tests/sentry/grouping/categorization_inputs/arraygetter.json b/tests/sentry/grouping/categorization_inputs/arraygetter.json new file mode 100644 index 00000000000000..5ccc1070a7601a --- /dev/null +++ b/tests/sentry/grouping/categorization_inputs/arraygetter.json @@ -0,0 +1,119 @@ +{ + ""event_id"": ""2d0db6a514574c2c9de0d1586f3983ec"", + ""exception"": { + ""values"": [ + { + ""mechanism"": { + ""data"": { + ""relevant_address"": ""[Filtered]"" + }, + ""handled"": false, + ""meta"": { + ""mach_exception"": { + ""code"": 18862328, + ""exception"": 6, + ""name"": ""EXC_BREAKPOINT"", + ""subcode"": 8 + }, + ""signal"": { + ""code"": 0, + ""name"": ""SIGTRAP"", + ""number"": 5 + } + }, + ""synthetic"": true, + ""type"": ""mach"" + }, + ""stacktrace"": { + ""frames"": [ + { + ""function"": ""start"", + ""package"": ""libdyld.dylib"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""function"": ""UIApplicationMain"", + ""package"": ""UIKitCore"" + }, + { + ""function"": ""-[UIApplication _run]"", + ""package"": ""UIKitCore"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""function"": ""CFRunLoopRunSpecific"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""__CFRunLoopRun"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""__CFRunLoopDoTimers"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""__CFRunLoopDoTimer"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""abs_path"": """", + ""filename"": """", + ""function"": ""closure"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""abs_path"": """", + ""filename"": """", + ""function"": ""Collection.map"" + }, + { + ""abs_path"": """", + ""filename"": """", + ""function"": ""closure"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""abs_path"": ""/Users/vagrant/git/iOS"", + ""filename"": ""iOS"", + ""function"": ""Array.subscript.getter"" + }, + { + ""abs_path"": """", + ""filename"": """", + ""function"": ""Array._getElement"" + }, + { + ""abs_path"": """", + ""filename"": """", + ""function"": ""_ArrayBuffer._nativeTypeChecked.getter"" + }, + { + ""abs_path"": """", + ""filename"": """", + ""function"": ""range"" + } + ] + }, + ""type"": ""EXC_BREAKPOINT"", + ""value"": ""Iz\t\u05a1A"" + } + ] + }, + ""platform"": ""cocoa"" +} diff --git a/tests/sentry/grouping/categorization_inputs/dladdr.json b/tests/sentry/grouping/categorization_inputs/dladdr.json new file mode 100644 index 00000000000000..cbb2fb0668f2d3 --- /dev/null +++ b/tests/sentry/grouping/categorization_inputs/dladdr.json @@ -0,0 +1,106 @@ +{ + ""event_id"": ""1fd5468193cb46c8870174d98e40e5b7"", + ""exception"": { + ""values"": [ + { + ""mechanism"": { + ""data"": { + ""relevant_address"": ""[Filtered]"" + }, + ""handled"": false, + ""meta"": { + ""mach_exception"": { + ""code"": 272, + ""exception"": 1, + ""name"": ""EXC_BAD_ACCESS"", + ""subcode"": 8 + }, + ""signal"": { + ""code"": 0, + ""code_name"": ""BUS_NOOP"", + ""name"": ""SIGBUS"", + ""number"": 10 + } + }, + ""synthetic"": true, + ""type"": ""mach"" + }, + ""stacktrace"": { + ""frames"": [ + { + ""function"": ""start"", + ""package"": ""libdyld.dylib"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""function"": ""UIApplicationMain"", + ""package"": ""UIKitCore"" + }, + { + ""function"": ""-[UIApplication _run]"", + ""package"": ""UIKitCore"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""function"": ""CFRunLoopRunSpecific"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""__CFRunLoopRun"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__"", + ""package"": ""CoreFoundation"" + }, + { + ""function"": ""_dispatch_main_queue_callback_4CF"", + ""package"": ""libdispatch.dylib"" + }, + { + ""function"": ""_dispatch_client_callout"", + ""package"": ""libdispatch.dylib"" + }, + { + ""function"": ""_dispatch_async_and_wait_invoke"", + ""package"": ""libdispatch.dylib"" + }, + { + ""function"": ""_dispatch_client_callout"", + ""package"": ""libdispatch.dylib"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""function"": ""stripped_application_code"" + }, + { + ""function"": ""-[UIApplication __beginBackgroundTaskWithExpirationHandler:]"", + ""package"": ""UIKitCore"" + }, + { + ""function"": ""dladdr"", + ""package"": ""libdyld.dylib"" + }, + { + ""function"": ""dladdr"", + ""package"": ""dyld_sim"" + }, + { + ""function"": ""ImageLoaderMachO::findClosestSymbol"", + ""package"": ""dyld_sim"" + } + ] + }, + ""type"": ""EXC_BAD_ACCESS"", + ""value"": ""Exception 1, Code 272, Subcode 8 >\nAttempted to dereference garbage pointer 0x110."" + } + ] + }, + ""platform"": ""cocoa"" +} diff --git a/tests/sentry/grouping/snapshots/test_categorization/test_categorization/arraygetter.pysnap b/tests/sentry/grouping/snapshots/test_categorization/test_categorization/arraygetter.pysnap new file mode 100644 index 00000000000000..81267007a7c109 --- /dev/null +++ b/tests/sentry/grouping/snapshots/test_categorization/test_categorization/arraygetter.pysnap @@ -0,0 +1,28 @@ +--- +created: '2021-07-27T14:49:31.351466Z' +creator: sentry +source: tests/sentry/grouping/test_categorization.py +--- + + +EXC_BREAKPOINT:Iz ֡A (thread_id:_, crashed:_) + libdyld.dylib start category=threadbase + stripped_application_code + UIKitCore UIApplicationMain category=threadbase + UIKitCore -[UIApplication _run] category=ui + stripped_application_code + CoreFoundation CFRunLoopRunSpecific category=indirection + CoreFoundation __CFRunLoopRun category=internals + CoreFoundation __CFRunLoopDoTimers category=internals + CoreFoundation __CFRunLoopDoTimer category=internals + CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ category=internals + stripped_application_code + closure category=internals + stripped_application_code + Collection.map category=internals + closure category=internals + stripped_application_code + iOS Array.subscript.getter category=indirection + Array._getElement category=internals + _ArrayBuffer._nativeTypeChecked.getter category=internals + range category=internals diff --git a/tests/sentry/grouping/snapshots/test_categorization/test_categorization/dladdr.pysnap b/tests/sentry/grouping/snapshots/test_categorization/test_categorization/dladdr.pysnap new file mode 100644 index 00000000000000..1f8384ebf864fb --- /dev/null +++ b/tests/sentry/grouping/snapshots/test_categorization/test_categorization/dladdr.pysnap @@ -0,0 +1,27 @@ +--- +created: '2021-07-27T14:43:43.231210Z' +creator: sentry +source: tests/sentry/grouping/test_categorization.py +--- + + +EXC_BAD_ACCESS:Exception 1, Code 272, Subcode 8 > +Attempted to dereference garbage pointer 0x110. (thread_id:_, crashed:_) + libdyld.dylib start category=threadbase + stripped_application_code + UIKitCore UIApplicationMain category=threadbase + UIKitCore -[UIApplication _run] category=ui + stripped_application_code + CoreFoundation CFRunLoopRunSpecific category=indirection + CoreFoundation __CFRunLoopRun category=internals + CoreFoundation __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ category=internals + libdispatch.dylib _dispatch_main_queue_callback_4CF category=internals + libdispatch.dylib _dispatch_client_callout category=threadbase + libdispatch.dylib _dispatch_async_and_wait_invoke category=internals + libdispatch.dylib _dispatch_client_callout category=threadbase + stripped_application_code + stripped_application_code + UIKitCore -[UIApplication __beginBackgroundTaskWithExpirationHandler:] category=ui + libdyld.dylib dladdr category=load + dyld_sim dladdr category=internals + dyld_sim ImageLoaderMachO::findClosestSymbol category=internals" 809109960c940b467639c3c1eea238408c47ae63,2025-02-06 21:36:02,Andrew Liu,feat(issues): add feature flags to issue stream search suggestions (#83968),False,add feature flags to issue stream search suggestions (#83968),feat,"diff --git a/static/app/actionCreators/tags.tsx b/static/app/actionCreators/tags.tsx index 58ad9a03ac3690..3b8b492c1d4159 100644 --- a/static/app/actionCreators/tags.tsx +++ b/static/app/actionCreators/tags.tsx @@ -8,13 +8,14 @@ import AlertStore from 'sentry/stores/alertStore'; import TagStore from 'sentry/stores/tagStore'; import type {PageFilters} from 'sentry/types/core'; import type {Tag, TagValue} from 'sentry/types/group'; +import type {Organization} from 'sentry/types/organization'; import { type ApiQueryKey, keepPreviousData, useApiQuery, type UseApiQueryOptions, } from 'sentry/utils/queryClient'; -import type {Dataset} from 'sentry/views/alerts/rules/metric/types'; +import {Dataset} from 'sentry/views/alerts/rules/metric/types'; const MAX_TAGS = 1000; @@ -212,6 +213,67 @@ export function fetchSpanFieldValues({ }); } +/** + * Fetch feature flag values for an organization. This is done by querying ERRORS with useFlagsBackend=1. + * This only returns feature flags and not tags. + * + * The `projectIds` argument can be used to subset projects. + */ +export function fetchFeatureFlagValues({ + api, + organization, + tagKey, + endpointParams, + projectIds, + search, + sort, +}: { + api: Client; + organization: Organization; + tagKey: string; + endpointParams?: Query; + projectIds?: string[]; + search?: string; + sort?: '-last_seen' | '-count'; +}): Promise { + if (!organization.features.includes('feature-flag-autocomplete')) { + return Promise.resolve([]); + } + + const url = `/organizations/${organization.slug}/tags/${tagKey}/values/`; + + const query: Query = { + dataset: Dataset.ERRORS, + useFlagsBackend: '1', + }; + + if (search) { + query.query = search; + } + if (projectIds) { + query.project = projectIds; + } + if (endpointParams) { + if (endpointParams.start) { + query.start = endpointParams.start; + } + if (endpointParams.end) { + query.end = endpointParams.end; + } + if (endpointParams.statsPeriod) { + query.statsPeriod = endpointParams.statsPeriod; + } + } + if (sort) { + query.sort = sort; + } + + return api.requestPromise(url, { + method: 'GET', + query, + }); +} + type FetchOrganizationTagsParams = { orgSlug: string; dataset?: Dataset; @@ -222,6 +284,7 @@ type FetchOrganizationTagsParams = { start?: string; statsPeriod?: string | null; useCache?: boolean; + useFlagsBackend?: boolean; }; export const makeFetchOrganizationTags = ({ @@ -229,6 +292,7 @@ export const makeFetchOrganizationTags = ({ dataset, projectIds, useCache = true, + useFlagsBackend = false, statsPeriod, start, end, @@ -238,6 +302,7 @@ export const makeFetchOrganizationTags = ({ query.dataset = dataset; query.useCache = useCache ? '1' : '0'; query.project = projectIds; + query.useFlagsBackend = useFlagsBackend ? '1' : '0'; if (statsPeriod) { query.statsPeriod = statsPeriod; diff --git a/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/keyDescription.tsx b/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/keyDescription.tsx index eb943c2dc78cf9..db57b669f70ffe 100644 --- a/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/keyDescription.tsx +++ b/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/keyDescription.tsx @@ -13,16 +13,24 @@ type KeyDescriptionProps = { size?: 'sm' | 'md'; }; -function ValueType({fieldDefinition}: {fieldDefinition: FieldDefinition | null}) { +function ValueType({ + fieldDefinition, + fieldKind, +}: { + fieldDefinition: FieldDefinition | null; + fieldKind?: FieldKind; +}) { + const defaultType = + fieldKind === FieldKind.FEATURE_FLAG ? FieldValueType.BOOLEAN : FieldValueType.STRING; if (!fieldDefinition) { - return toTitleCase(FieldValueType.STRING); + return toTitleCase(defaultType); } if (fieldDefinition.parameterDependentValueType) { return t('Dynamic'); } - return toTitleCase(fieldDefinition?.valueType ?? FieldValueType.STRING); + return toTitleCase(fieldDefinition?.valueType ?? defaultType); } export function KeyDescription({size = 'sm', tag}: KeyDescriptionProps) { @@ -32,7 +40,11 @@ export function KeyDescription({size = 'sm', tag}: KeyDescriptionProps) { const description = fieldDefinition?.desc ?? - (tag.kind === FieldKind.TAG ? t('A tag sent with one or more events') : null); + (tag.kind === FieldKind.TAG + ? t('A tag sent with one or more events') + : tag.kind === FieldKind.FEATURE_FLAG + ? t('A feature flag evaluated before an error event') + : null); return ( @@ -44,7 +56,7 @@ export function KeyDescription({size = 'sm', tag}: KeyDescriptionProps) { {t('Type')}
- +
diff --git a/static/app/utils/fields/index.ts b/static/app/utils/fields/index.ts index 35dd599f1d2411..2a4a5185beacef 100644 --- a/static/app/utils/fields/index.ts +++ b/static/app/utils/fields/index.ts @@ -7,6 +7,7 @@ import {CONDITIONS_ARGUMENTS, WEB_VITALS_QUALITY} from '../discover/types'; export enum FieldKind { TAG = 'tag', + FEATURE_FLAG = 'feature_flag', MEASUREMENT = 'measurement', BREAKDOWN = 'breakdown', FIELD = 'field', diff --git a/static/app/views/issueList/searchBar.tsx b/static/app/views/issueList/searchBar.tsx index c1cd9ad82a3da3..ed05969fb99895 100644 --- a/static/app/views/issueList/searchBar.tsx +++ b/static/app/views/issueList/searchBar.tsx @@ -1,14 +1,19 @@ import {useCallback, useMemo} from 'react'; import orderBy from 'lodash/orderBy'; -import {fetchTagValues} from 'sentry/actionCreators/tags'; +import {fetchFeatureFlagValues, fetchTagValues} from 'sentry/actionCreators/tags'; import { SearchQueryBuilder, type SearchQueryBuilderProps, } from 'sentry/components/searchQueryBuilder'; import type {FilterKeySection} from 'sentry/components/searchQueryBuilder/types'; import {t} from 'sentry/locale'; -import {SavedSearchType, type Tag, type TagCollection} from 'sentry/types/group'; +import { + SavedSearchType, + type Tag, + type TagCollection, + type TagValue, +} from 'sentry/types/group'; import type {Organization} from 'sentry/types/organization'; import {getUtcDateString} from 'sentry/utils/dates'; import {FieldKind} from 'sentry/utils/fields'; @@ -19,25 +24,37 @@ import {mergeAndSortTagValues} from 'sentry/views/issueDetails/utils'; import {makeGetIssueTagValues} from 'sentry/views/issueList/utils/getIssueTagValues'; import {useIssueListFilterKeys} from 'sentry/views/issueList/utils/useIssueListFilterKeys'; -const getFilterKeySections = (tags: TagCollection): FilterKeySection[] => { +const getFilterKeySections = ( + tags: TagCollection, + organization: Organization +): FilterKeySection[] => { const allTags: Tag[] = Object.values(tags).filter( tag => !EXCLUDED_TAGS.includes(tag.key) ); + const issueFields = orderBy( allTags.filter(tag => tag.kind === FieldKind.ISSUE_FIELD), ['key'] ).map(tag => tag.key); + const eventFields = orderBy( allTags.filter(tag => tag.kind === FieldKind.EVENT_FIELD), ['key'] ).map(tag => tag.key); + const eventTags = orderBy( allTags.filter(tag => tag.kind === FieldKind.TAG), ['totalValues', 'key'], ['desc', 'asc'] ).map(tag => tag.key); - return [ + const eventFeatureFlags = orderBy( + allTags.filter(tag => tag.kind === FieldKind.FEATURE_FLAG), + ['totalValues', 'key'], + ['desc', 'asc'] + ).map(tag => tag.key); + + const sections = [ { value: FieldKind.ISSUE_FIELD, label: t('Issues'), @@ -54,6 +71,16 @@ const getFilterKeySections = (tags: TagCollection): FilterKeySection[] => { children: eventTags, }, ]; + + if (organization.features.includes('feature-flag-autocomplete')) { + sections.push({ + value: FieldKind.FEATURE_FLAG, + label: t('Flags'), // Keeping this short so the tabs stay on 1 line. + children: eventFeatureFlags, + }); + } + + return sections; }; interface Props extends Partial { @@ -72,9 +99,9 @@ function IssueListSearchBar({ const {selection: pageFilters} = usePageFilters(); const filterKeys = useIssueListFilterKeys(); + // Fetches the unique values seen for a tag key and query string. Result is sorted by count. const tagValueLoader = useCallback( - async (key: string, search: string) => { - const orgSlug = organization.slug; + async (key: string, search: string): Promise => { const projectIds = pageFilters.projects.map(id => id.toString()); const endpointParams = { start: pageFilters.datetime.start @@ -88,7 +115,7 @@ function IssueListSearchBar({ const fetchTagValuesPayload = { api, - orgSlug, + orgSlug: organization.slug, tagKey: key, search, projectIds, @@ -96,6 +123,14 @@ function IssueListSearchBar({ sort: '-count' as const, }; + // For now feature flags are treated like tags, but the api query is slightly different. + if (filterKeys[key]?.kind === FieldKind.FEATURE_FLAG) { + return await fetchFeatureFlagValues({ + ...fetchTagValuesPayload, + organization, + }); + } + const [eventsDatasetValues, issuePlatformDatasetValues] = await Promise.all([ fetchTagValues({ ...fetchTagValuesPayload, @@ -115,7 +150,8 @@ function IssueListSearchBar({ }, [ api, - organization.slug, + filterKeys, + organization, pageFilters.datetime.end, pageFilters.datetime.period, pageFilters.datetime.start, @@ -129,8 +165,8 @@ function IssueListSearchBar({ ); const filterKeySections = useMemo(() => { - return getFilterKeySections(filterKeys); - }, [filterKeys]); + return getFilterKeySections(filterKeys, organization); + }, [filterKeys, organization]); return ( Promise ) { return async (tag: Tag, query: string): Promise => { + // Strip quotes for feature flags, which may be used to escape special characters in the search bar. + const charsToStrip = '""'; + const key = + tag.kind === FieldKind.FEATURE_FLAG + ? tag.key.replace(new RegExp(`^[${charsToStrip}]+|[${charsToStrip}]+$`, 'g'), '') + : tag.key; + // device.class is stored as ""numbers"" in snuba, but we want to suggest high, medium, // and low search filter values because discover maps device.class to these values. - if (isDeviceClass(tag.key)) { + if (isDeviceClass(key)) { return DEVICE_CLASS_TAG_VALUES; } - const values = await tagValueLoader(tag.key, query); + const values = await tagValueLoader(key, query); return values.map(({value}) => { // Truncate results to 5000 characters to avoid exceeding the max url query length // The message attribute for example can be 8192 characters. diff --git a/static/app/views/issueList/utils/useFetchIssueTags.tsx b/static/app/views/issueList/utils/useFetchIssueTags.tsx index 4b384a89a0e535..104be0d53ed053 100644 --- a/static/app/views/issueList/utils/useFetchIssueTags.tsx +++ b/static/app/views/issueList/utils/useFetchIssueTags.tsx @@ -38,6 +38,7 @@ type UseFetchIssueTagsParams = { projectIds: string[]; enabled?: boolean; end?: string; + includeFeatureFlags?: boolean; keepPreviousData?: boolean; start?: string; statsPeriod?: string | null; @@ -91,6 +92,7 @@ export const useFetchIssueTags = ({ keepPreviousData = false, useCache = true, enabled = true, + includeFeatureFlags = false, ...statsPeriodParams }: UseFetchIssueTagsParams) => { const {teams} = useLegacyStore(TeamStore); @@ -122,6 +124,22 @@ export const useFetchIssueTags = ({ {} ); + // For now, feature flag keys (see `flags` column of the ERRORS dataset) are exposed from the tags endpoint, + // with query param useFlagsBackend=1. This is used for issue stream search suggestions. + const featureFlagTagsQuery = useFetchOrganizationTags( + { + orgSlug: org.slug, + projectIds, + dataset: Dataset.ERRORS, + useCache, + useFlagsBackend: true, // Queries `flags` column instead of tags. Response format is the same. + enabled: enabled && includeFeatureFlags, // Only make this query if includeFeatureFlags is true. + keepPreviousData, + ...statsPeriodParams, + }, + {} + ); + const allTags = useMemo(() => { const userTeams = teams.filter(team => team.isMember).map(team => `#${team.slug}`); const usernames: string[] = members.map(getUsername); @@ -151,6 +169,7 @@ export const useFetchIssueTags = ({ const eventsTags: Tag[] = eventsTagsQuery.data || []; const issuePlatformTags: Tag[] = issuePlatformTagsQuery.data || []; + const featureFlagTags: Tag[] = featureFlagTagsQuery.data || []; const allTagsCollection: TagCollection = eventsTags.reduce( (acc, tag) => { @@ -169,6 +188,26 @@ export const useFetchIssueTags = ({ } }); + featureFlagTags.forEach(tag => { + // Double quote to escape ':' character, which is used by our search syntax. + const key = tag.key.includes(':') ? `""${tag.key}""` : tag.key; + if (allTagsCollection[key]) { + if (allTagsCollection[key]!.kind === FieldKind.FEATURE_FLAG) { + allTagsCollection[key]!.totalValues = + (allTagsCollection[key]!.totalValues ?? 0) + (tag.totalValues ?? 0); + } else { + // pass. When a feature flag collides with a custom tag, we only suggest the tag. + // The search filter will still check both columns (cond(tags) OR cond(flags)). + } + } else { + allTagsCollection[key] = { + ...tag, + kind: FieldKind.FEATURE_FLAG, + key, // Update with wrapped key. + }; + } + }); + for (const excludedTag of EXCLUDED_TAGS) { delete allTagsCollection[excludedTag]; } @@ -184,12 +223,24 @@ export const useFetchIssueTags = ({ ...renamedTags, ...additionalTags, }; - }, [eventsTagsQuery.data, issuePlatformTagsQuery.data, members, teams]); + }, [ + eventsTagsQuery.data, + issuePlatformTagsQuery.data, + featureFlagTagsQuery.data, + members, + teams, + ]); return { tags: allTags, - isLoading: eventsTagsQuery.isPending || issuePlatformTagsQuery.isPending, - isError: eventsTagsQuery.isError || issuePlatformTagsQuery.isError, + isLoading: + eventsTagsQuery.isPending || + issuePlatformTagsQuery.isPending || + featureFlagTagsQuery.isPending, + isError: + eventsTagsQuery.isError || + issuePlatformTagsQuery.isError || + featureFlagTagsQuery.isError, }; }; diff --git a/static/app/views/issueList/utils/useIssueListFilterKeys.tsx b/static/app/views/issueList/utils/useIssueListFilterKeys.tsx index bc0f933d69188b..466ffc1de63fc8 100644 --- a/static/app/views/issueList/utils/useIssueListFilterKeys.tsx +++ b/static/app/views/issueList/utils/useIssueListFilterKeys.tsx @@ -6,10 +6,15 @@ import {useFetchIssueTags} from 'sentry/views/issueList/utils/useFetchIssueTags' export function useIssueListFilterKeys() { const organization = useOrganization(); const {selection: pageFilters} = usePageFilters(); + const hasFeatureFlagSearch = organization.features.includes( + 'feature-flag-autocomplete' + ); + const {tags: issueTags} = useFetchIssueTags({ org: organization, projectIds: pageFilters.projects.map(id => id.toString()), keepPreviousData: true, + includeFeatureFlags: hasFeatureFlagSearch, start: pageFilters.datetime.start ? getUtcDateString(pageFilters.datetime.start) : undefined," bfcc91fa08edd98710347a02dd7c695a13c63191,2024-08-26 23:04:13,Richard Roggenkemper,feat(issue-details): Add support for multiple suspect commits in streamlined design (#76365),False,Add support for multiple suspect commits in streamlined design (#76365),feat,"diff --git a/static/app/components/commitRow.tsx b/static/app/components/commitRow.tsx index 9089ffcf078616..103d9ef1626bb2 100644 --- a/static/app/components/commitRow.tsx +++ b/static/app/components/commitRow.tsx @@ -309,7 +309,7 @@ const Meta = styled(TextOverflow)<{hasStreamlinedUI?: boolean}>` const StreamlinedCommitRow = styled('div')` display: flex; flex-direction: column; - padding: ${space(1)} ${space(1.5)} ${space(1.5)}; + padding: ${space(0.5)} ${space(1.5)} ${space(1.5)}; `; const MetaWrapper = styled('div')` diff --git a/static/app/components/events/suspectCommits.spec.tsx b/static/app/components/events/suspectCommits.spec.tsx index feca74803cf564..99bdea50a41042 100644 --- a/static/app/components/events/suspectCommits.spec.tsx +++ b/static/app/components/events/suspectCommits.spec.tsx @@ -1,5 +1,6 @@ import {EventFixture} from 'sentry-fixture/event'; import {GroupFixture} from 'sentry-fixture/group'; +import {LocationFixture} from 'sentry-fixture/locationFixture'; import {OrganizationFixture} from 'sentry-fixture/organization'; import {ProjectFixture} from 'sentry-fixture/project'; import {RepositoryFixture} from 'sentry-fixture/repository'; @@ -181,6 +182,7 @@ describe('SuspectCommits', function () { const project = ProjectFixture(); const event = EventFixture(); const group = GroupFixture({firstRelease: {}} as any); + const location = LocationFixture({query: {streamline: '1'}}); const committers = [ { @@ -227,7 +229,7 @@ describe('SuspectCommits', function () { method: 'GET', url: `/projects/${organization.slug}/${project.slug}/events/${event.id}/committers/`, body: { - committers, + committers: [committers[0]], }, }); }); @@ -240,7 +242,7 @@ describe('SuspectCommits', function () { eventId={event.id} group={group} />, - {organization} + {router: {location}} ); expect(await screen.findByTestId('commit-row')).toBeInTheDocument(); @@ -256,24 +258,21 @@ describe('SuspectCommits', function () { eventId={event.id} group={group} />, - {organization} + {router: {location}} ); expect(await screen.findByTestId('quick-context-commit-row')).toBeInTheDocument(); expect(screen.queryByTestId('commit-row')).not.toBeInTheDocument(); }); - it('renders correct heading for single commit', async () => { - // For this one test, undo the `beforeEach` so that we can respond with just a single commit - MockApiClient.clearMockResponses(); + it('renders multiple suspect commits', async () => { MockApiClient.addMockResponse({ method: 'GET', url: `/projects/${organization.slug}/${project.slug}/events/${event.id}/committers/`, body: { - committers: [committers[0]], + committers, }, }); - render( , - {organization} + {router: {location}} ); - - expect(await screen.findByText(/Suspect Commit/i)).toBeInTheDocument(); - expect(screen.queryByText(/Suspect Commits/i)).not.toBeInTheDocument(); + expect( + await screen.findByText('feat: Enhance suggested commits and add to alerts') + ).toBeInTheDocument(); + expect(await screen.findByText('fix: Make things less broken')).toBeInTheDocument(); + expect(await screen.findAllByTestId('commit-row')).toHaveLength(2); }); }); }); diff --git a/static/app/components/events/suspectCommits.tsx b/static/app/components/events/suspectCommits.tsx index fdd26a4dad4043..914a9f69fb99c2 100644 --- a/static/app/components/events/suspectCommits.tsx +++ b/static/app/components/events/suspectCommits.tsx @@ -4,12 +4,11 @@ import uniqBy from 'lodash/uniqBy'; import bannerIllustration from 'sentry-images/spot/alerts-empty-state.svg'; -import {Button} from 'sentry/components/button'; import type {CommitRowProps} from 'sentry/components/commitRow'; import {SuspectCommitHeader} from 'sentry/components/events/styles'; import Panel from 'sentry/components/panels/panel'; +import {ScrollCarousel} from 'sentry/components/scrollCarousel'; import {IconAdd, IconSubtract} from 'sentry/icons'; -import {IconClose} from 'sentry/icons/iconClose'; import {t, tn} from 'sentry/locale'; import {space} from 'sentry/styles/space'; import type {Group} from 'sentry/types/group'; @@ -19,7 +18,6 @@ import {trackAnalytics} from 'sentry/utils/analytics'; import {getAnalyticsDataForGroup} from 'sentry/utils/events'; import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams'; import useCommitters from 'sentry/utils/useCommitters'; -import {useLocalStorageState} from 'sentry/utils/useLocalStorageState'; import useOrganization from 'sentry/utils/useOrganization'; import {useHasStreamlinedUI} from 'sentry/views/issueDetails/utils'; @@ -41,11 +39,6 @@ export function SuspectCommits({group, eventId, project, commitRow: CommitRow}: const hasStreamlinedUI = useHasStreamlinedUI(); - const [suspectCommitDismissed, setSuspectCommitDismissed] = useLocalStorageState( - `suspect-commit-dismissed-${project.slug}-${eventId}`, - false - ); - function getUniqueCommitsWithAuthors() { // Get a list of commits with author information attached const commitsWithAuthors = committers.flatMap(({commits, author}) => @@ -93,35 +86,28 @@ export function SuspectCommits({group, eventId, project, commitRow: CommitRow}: const commitHeading = tn('Suspect Commit', 'Suspect Commits (%s)', commits.length); - const firstCommit = commits[0]; - return hasStreamlinedUI ? ( - !suspectCommitDismissed ? ( - -
- {t('Suspect Commit')} - } - onClick={() => setSuspectCommitDismissed(true)} - aria-label={t('Close Suspect Commit Banner')} - size=""zero"" - /> -
-
- handleCommitClick(firstCommit, 0)} - onPullRequestClick={() => handlePullRequestClick(firstCommit, 0)} - project={project} - /> -
- - - -
- ) : null + + + {commits.slice(0, 100).map((commit, commitIndex) => ( + + {t('Suspect Commit')} +
+ handleCommitClick(commit, commitIndex)} + onPullRequestClick={() => handlePullRequestClick(commit, commitIndex)} + project={project} + /> +
+ + + +
+ ))} +
+
) : (
@@ -170,12 +156,6 @@ const ExpandButton = styled('button')` const Title = styled('div')` font-size: ${p => p.theme.fontSizeLarge}; font-weight: bold; -`; - -const Header = styled('div')` - display: flex; - justify-content: space-between; - align-items: center; padding: 12px 12px 0 12px; `; @@ -184,6 +164,14 @@ const StreamlinedPanel = styled(Panel)` linear-gradient(to right, rgba(245, 243, 247, 0), ${p => p.theme.surface100}); overflow: hidden; margin-bottom: 0; + width: 100%; + min-width: 85%; + &:last-child { + margin-right: ${space(1.5)}; + } + &:first-child { + margin-left: ${space(1.5)}; + } `; const IllustrationContainer = styled('div')` @@ -200,6 +188,8 @@ const IllustrationContainer = styled('div')` const Illustration = styled('img')` height: 110px; `; -const DismissButton = styled(Button)` - color: ${p => p.theme.gray300}; + +const SuspectCommitWrapper = styled('div')` + margin-right: 0; + margin-left: 0; `; diff --git a/static/app/components/scrollCarousel.tsx b/static/app/components/scrollCarousel.tsx index 7950bca0ca9cdb..e8d5b0b8ca523d 100644 --- a/static/app/components/scrollCarousel.tsx +++ b/static/app/components/scrollCarousel.tsx @@ -14,6 +14,8 @@ interface ScrollCarouselProps { className?: string; 'data-test-id'?: string; gap?: ValidSize; + jumpItemCount?: number; + transparentMask?: boolean; } /** @@ -52,7 +54,13 @@ const getOffsetRect = (el: HTMLElement, relativeTo: HTMLElement) => { }; }; -export function ScrollCarousel({children, gap = 1, ...props}: ScrollCarouselProps) { +export function ScrollCarousel({ + children, + gap = 1, + transparentMask = false, + jumpItemCount = DEFAULT_JUMP_ITEM_COUNT, + ...props +}: ScrollCarouselProps) { const scrollContainerRef = useRef(null); const {visibility, childrenEls} = useRefChildrenVisibility({ children, @@ -66,22 +74,19 @@ export function ScrollCarousel({children, gap = 1, ...props}: ScrollCarouselProp const scrollLeft = useCallback(() => { const scrollIndex = visibility.findIndex(Boolean); // Clamp the scroll index to the first visible item - const clampedIndex = Math.max(scrollIndex - DEFAULT_JUMP_ITEM_COUNT, 0); + const clampedIndex = Math.max(scrollIndex - jumpItemCount, 0); // scrollIntoView scrolls the entire page on some browsers scrollContainerRef.current?.scrollTo({ behavior: 'smooth', // We don't need to do any fancy math for the left edge left: getOffsetRect(childrenEls[clampedIndex], childrenEls[0]).left, }); - }, [visibility, childrenEls]); + }, [visibility, childrenEls, jumpItemCount]); const scrollRight = useCallback(() => { const scrollIndex = visibility.findLastIndex(Boolean); // Clamp the scroll index to the last visible item - const clampedIndex = Math.min( - scrollIndex + DEFAULT_JUMP_ITEM_COUNT, - visibility.length - 1 - ); + const clampedIndex = Math.min(scrollIndex + jumpItemCount, visibility.length - 1); const targetElement = childrenEls[clampedIndex]; const targetElementRight = getOffsetRect(targetElement, childrenEls[0]).right; @@ -91,15 +96,15 @@ export function ScrollCarousel({children, gap = 1, ...props}: ScrollCarouselProp behavior: 'smooth', left: Math.max(targetElementRight - containerRight, 0), }); - }, [visibility, childrenEls]); + }, [visibility, childrenEls, jumpItemCount]); return ( {children} - {!isAtStart && } - {!isAtEnd && } + {!isAtStart && } + {!isAtEnd && } {!isAtStart && ( ` ${Mask} left: 0; - background: linear-gradient( + background: ${p => + p.transparentMask + ? `linear-gradient(to left, ${Color(p.theme.background).alpha(0).rgb().string()}, ${p.theme.background})` + : `linear-gradient( 90deg, - ${p => p.theme.background} 50%, - ${p => Color(p.theme.background).alpha(0.09).rgb().string()} 100% - ); + ${p.theme.background} 50%, + ${Color(p.theme.background).alpha(0.09).rgb().string()} 100% + )`}; `; -const RightMask = styled('div')` +const RightMask = styled('div')<{transparentMask: boolean}>` ${Mask} right: 0; - background: linear-gradient( + background: ${p => + p.transparentMask + ? 'linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1))' + : `linear-gradient( 270deg, - ${p => p.theme.background} 50%, - ${p => Color(p.theme.background).alpha(0.09).rgb().string()} 100% - ); + ${p.theme.background} 50%, + ${Color(p.theme.background).alpha(0.09).rgb().string()} 100% + )`}; `; const StyledIconChevron = styled(IconChevron)` diff --git a/static/app/views/issueDetails/groupEventDetails/groupEventDetails.tsx b/static/app/views/issueDetails/groupEventDetails/groupEventDetails.tsx index 3b3723b216c573..e13475c9feba2a 100644 --- a/static/app/views/issueDetails/groupEventDetails/groupEventDetails.tsx +++ b/static/app/views/issueDetails/groupEventDetails/groupEventDetails.tsx @@ -252,7 +252,14 @@ const GroupContent = styled(Layout.Main)` display: flex; flex-direction: column; gap: ${space(1.5)}; - padding: ${space(1.5)}; + padding-top: ${space(1.5)}; + padding-bottom: ${space(1.5)}; + box-shadow: 0 0 0 1px ${p => p.theme.translucentInnerBorder}; + + > * { + margin-right: ${space(1.5)}; + margin-left: ${space(1.5)}; + } `; const StyledLayoutSide = styled(Layout.Side)<{hasStreamlinedUi: boolean}>`" 44daccd6e50b9c29bd94053dd1acb5f9494688a2,2020-09-17 17:14:14,Matej Minar,feat: Remove artifacts-in-settings flag checks (#20778),False,Remove artifacts-in-settings flag checks (#20778),feat,"diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index 374254915cfeca..eacc4df1aeacaf 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -56,7 +56,6 @@ default_manager.add(""organizations:advanced-search"", OrganizationFeature) # NOQA default_manager.add(""organizations:android-mappings"", OrganizationFeature) # NOQA default_manager.add(""organizations:api-keys"", OrganizationFeature) # NOQA -default_manager.add(""organizations:artifacts-in-settings"", OrganizationFeature) # NOQA default_manager.add(""organizations:boolean-search"", OrganizationFeature) # NOQA default_manager.add(""organizations:related-events"", OrganizationFeature) # NOQA default_manager.add(""organizations:alert-filters"", OrganizationFeature) # NOQA @@ -98,6 +97,7 @@ default_manager.add(""organizations:usage-stats-graph"", OrganizationFeature) # NOQA default_manager.add(""organizations:dynamic-issue-counts"", OrganizationFeature) # NOQA # XXX(mark) Don't use this feature it is going away soon. +default_manager.add(""organizations:artifacts-in-settings"", OrganizationFeature) # NOQA default_manager.add(""organizations:transaction-events"", OrganizationFeature) # NOQA default_manager.add(""organizations:invite-members-rate-limits"", OrganizationFeature) # NOQA diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/overview/projectReleaseDetails.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/overview/projectReleaseDetails.tsx index e54a90a1cf5bba..dfd116f33523fe 100644 --- a/src/sentry/static/sentry/app/views/releasesV2/detail/overview/projectReleaseDetails.tsx +++ b/src/sentry/static/sentry/app/views/releasesV2/detail/overview/projectReleaseDetails.tsx @@ -9,7 +9,6 @@ import TimeSince from 'app/components/timeSince'; import DateTime from 'app/components/dateTime'; import Link from 'app/components/links/link'; import Count from 'app/components/count'; -import Feature from 'app/components/acl/feature'; import {SectionHeading, Wrapper} from './styles'; @@ -52,21 +51,19 @@ const ProjectReleaseDetails = ({release, releaseMeta, orgSlug, projectSlug}: Pro {lastEvent ? : '-'} - - - {t('Source Maps')} - - - {' '} - {tn('artifact', 'artifacts', releaseMeta.releaseFileCount)} - - - - + + {t('Source Maps')} + + + {' '} + {tn('artifact', 'artifacts', releaseMeta.releaseFileCount)} + + + 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 d4ecda65e2b7e1..e3ef9a339c6736 100644 --- a/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.tsx +++ b/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.tsx @@ -65,7 +65,6 @@ export default function getConfiguration({ { path: `${pathPrefix}/source-maps/`, title: t('Source Maps'), - show: () => organization.features?.includes('artifacts-in-settings'), }, { path: `${pathPrefix}/proguard/`, diff --git a/src/sentry/static/sentry/app/views/settings/projectSourceMaps/index.tsx b/src/sentry/static/sentry/app/views/settings/projectSourceMaps/index.tsx index 1d3ea10fa8ffa6..9abb0f193999fd 100644 --- a/src/sentry/static/sentry/app/views/settings/projectSourceMaps/index.tsx +++ b/src/sentry/static/sentry/app/views/settings/projectSourceMaps/index.tsx @@ -1,10 +1,6 @@ import React from 'react'; import {RouteComponentProps} from 'react-router/lib/Router'; -import {t} from 'app/locale'; -import {PageContent} from 'app/styles/organization'; -import Feature from 'app/components/acl/feature'; -import Alert from 'app/components/alert'; import withOrganization from 'app/utils/withOrganization'; import {Organization, Project} from 'app/types'; @@ -15,31 +11,14 @@ type RouteParams = { type Props = RouteComponentProps & { organization: Organization; project: Project; + children: React.ReactNode; }; -class ProjectSourceMapsContainer extends React.Component { - renderNoAccess() { - return ( - - {t(""You don't have access to this feature"")} - - ); - } - - render() { - const {children, project, organization} = this.props; - - return ( - - {React.isValidElement(children) && - React.cloneElement(children, {organization, project})} - - ); - } +function ProjectSourceMapsContainer(props: Props) { + const {children, organization, project} = props; + return React.isValidElement(children) + ? React.cloneElement(children, {organization, project}) + : null; } export default withOrganization(ProjectSourceMapsContainer);" 462df57e0e860d29afa0ee18a3e29216d98ed78a,2024-08-14 03:30:02,Malachi Willey,fix(query-builder): Prevent performance issues with long recent searches (#76104),False,Prevent performance issues with long recent searches (#76104),fix,"diff --git a/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/useRecentSearchFilters.tsx b/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/useRecentSearchFilters.tsx index 5b9e9f513b111b..6ac13ccf2f3b29 100644 --- a/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/useRecentSearchFilters.tsx +++ b/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/useRecentSearchFilters.tsx @@ -1,3 +1,5 @@ +import {useMemo} from 'react'; + import {useFetchRecentSearches} from 'sentry/actionCreators/savedSearches'; import {useSearchQueryBuilder} from 'sentry/components/searchQueryBuilder/context'; import type {FieldDefinitionGetter} from 'sentry/components/searchQueryBuilder/types'; @@ -6,6 +8,10 @@ import {type ParseResult, Token} from 'sentry/components/searchSyntax/parser'; import type {RecentSearch, TagCollection} from 'sentry/types/group'; const MAX_RECENT_FILTERS = 5; +const NO_FILTERS = []; + +// If the recent searches are very long, this prevents the parser from taking too long +const MAX_QUERY_PARSE_LENGTH = 500; function getFiltersFromParsedQuery(parsedQuery: ParseResult | null) { if (!parsedQuery) { @@ -26,15 +32,19 @@ function getFiltersFromQuery({ getFieldDefinition: FieldDefinitionGetter; query: string; }) { - const parsed = parseQueryBuilderValue(query, getFieldDefinition, { - filterKeys, - }); + const parsed = parseQueryBuilderValue( + query.slice(0, MAX_QUERY_PARSE_LENGTH), + getFieldDefinition, + { + filterKeys, + } + ); return getFiltersFromParsedQuery(parsed); } function getFiltersFromRecentSearches( - recentSearchesData: RecentSearch[], + recentSearchesData: RecentSearch[] | undefined, { parsedCurrentQuery, filterKeys, @@ -45,10 +55,9 @@ function getFiltersFromRecentSearches( parsedCurrentQuery: ParseResult | null; } ) { - if (!recentSearchesData.length) { - return []; + if (!recentSearchesData?.length) { + return NO_FILTERS; } - const filtersInCurrentQuery = getFiltersFromParsedQuery(parsedCurrentQuery); const filterCounts: {[filter: string]: number} = recentSearchesData @@ -86,11 +95,15 @@ export function useRecentSearchFilters() { } ); - const filters = getFiltersFromRecentSearches(recentSearchesData ?? [], { - parsedCurrentQuery: parsedQuery, - filterKeys, - getFieldDefinition, - }); + const filters = useMemo( + () => + getFiltersFromRecentSearches(recentSearchesData, { + parsedCurrentQuery: parsedQuery, + filterKeys, + getFieldDefinition, + }), + [filterKeys, getFieldDefinition, parsedQuery, recentSearchesData] + ); return filters; }" 704138ef7220e3b33fae225b0eabd202f32d7a65,2022-10-11 03:44:11,Evan Purkhiser,test(js): Convert IssueListOverview (polling) to RTL (#39825),False,Convert IssueListOverview (polling) to RTL (#39825),test,"diff --git a/static/app/views/issueList/header.tsx b/static/app/views/issueList/header.tsx index 1256ea60f3fc15..18f21cd0c91aea 100644 --- a/static/app/views/issueList/header.tsx +++ b/static/app/views/issueList/header.tsx @@ -73,6 +73,10 @@ function IssueListHeader({ selectedProjectIds.includes(Number(id)) ); + const realtimeTitle = realtimeActive + ? t('Pause real-time updates') + : t('Enable real-time updates'); + return ( @@ -82,12 +86,10 @@ function IssueListHeader({ -
- - ); - }) - : No available auth methods} - - ); - }, - - renderBody() { - let orgFeatures = new Set(this.getOrganization().features); - if (!orgFeatures.has('integrations-v3')) { - return ( -
- {t(""Nothing to see here. You don't have access to this feature yet."")} -
- ); + let {success, data} = event.data; + if (success) { + let itemList = this.state.itemList; + itemList.push(data); + this.setState({ + itemList: sortArray(itemList, item => item.name) + }); + } else { + IndicatorStore.add(t('An error occurred: %s.', data.detail), 'error', { + duration: 5000 + }); } + this.dialog = null; + }; + + getEndpoints() { + let {orgId} = this.props.params; + return [ + ['itemList', `/organizations/${orgId}/integrations/`, {query: {status: ''}}], + ['config', `/organizations/${orgId}/config/integrations/`] + ]; + } - if (this.state.loading) return ; + deleteIntegration = integration => { + // eslint-disable-next-line no-alert + if (!confirm(t('Are you sure you want to remove this integration?'))) return; - let error = this.state.error; - if (error) { - if (error.error_type === 'auth') { - let authUrl = error.auth_url; - if (authUrl.indexOf('?') === -1) { - authUrl += '?next=' + encodeURIComponent(document.location.pathname); - } else { - authUrl += '&next=' + encodeURIComponent(document.location.pathname); + let indicator = IndicatorStore.add(t('Saving changes..')); + this.api.request( + `/organizations/${this.props.params.orgId}/integrations/${integration.id}/`, + { + method: 'DELETE', + success: () => { + this.setState({ + itemList: this.state.itemList.filter(item => item.id !== integration.id) + }); + }, + error: () => { + IndicatorStore.add(t('An error occurred.'), 'error', { + duration: 3000 + }); + }, + complete: () => { + IndicatorStore.remove(indicator); } - return ( -
-
- {'You need to associate an identity with ' + - error.title + - ' before you can create issues with this service.'} -
- - Associate Identity - -
- ); - } else { - return ( -
-

- {error.message - ? error.message - : tct( - 'An unknown error occurred. Need help with this? [link:Contact support]', - { - link: - } - )} -

-
- ); } + ); + }; + + launchAddIntegration = integration => { + let url = `${integration.setupUri}?callback=${this.dialogCallbackName}&init=1`; + let name = 'sentryAddIntegration'; + let width = 400; + let height = 400; + + // this attempts to center the dialog + let screenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left; + let screenTop = window.screenTop != undefined ? window.screenTop : screen.top; + let innerWidth = window.innerWidth + ? window.innerWidth + : document.documentElement.clientWidth + ? document.documentElement.clientWidth + : screen.width; + let innerHeight = window.innerHeight + ? window.innerHeight + : document.documentElement.clientHeight + ? document.documentElement.clientHeight + : screen.height; + let left = innerWidth / 2 - width / 2 + screenLeft; + let top = innerHeight / 2 - height / 2 + screenTop; + + this.dialog = window.open( + url, + name, + `scrollbars=yes, width=${width}, height=${height}, top=${top}, left=${left}` + ); + window.focus && this.dialog.focus(); + this.dialog.onclose = () => { + this.dialog && document.location.refresh(); + }; + }; + + getStatusLabel(integration) { + switch (integration.status) { + case 'pending_deletion': + return 'Deletion Queued'; + case 'deletion_in_progress': + return 'Deletion in Progress'; + case 'hidden': + return 'Disabled'; + default: + return null; } + } - let {ingtegrationList} = this.state; - return ( -
- {ingtegrationList.map(this.renderProvider)} -
- ); - }, + getTitle() { + return 'Integrations'; + } + + renderBody() { + let itemList = this.state.itemList; - render() { return ( - {this.renderBody()} +
+

+ {t('Integrations')} +

+ {itemList.length > 0 + ?
+ + + {itemList.map(integration => { + return ( + + + + + ); + })} + +
+ + {integration.name} + — + {integration.provider.name} + + + +
+
+ :
+
+

+ {t('Sentry is better with friends')} +

+

+ {t( + 'Integrations allow you to pull in things like repository data or sync with an external issue tracker.' + )} +

+

+ + Learn more + +

+
} ); } -}); - -export default OrganizationIntegrations; +} diff --git a/src/sentry/utils/pytest/sentry.py b/src/sentry/utils/pytest/sentry.py index 9338ef35e4e765..bd4d8009d8caf6 100644 --- a/src/sentry/utils/pytest/sentry.py +++ b/src/sentry/utils/pytest/sentry.py @@ -144,6 +144,10 @@ def pytest_configure(config): plugins.register(TestIssuePlugin2) + from sentry import integrations + from sentry.integrations.example import ExampleIntegration + integrations.register(ExampleIntegration) + from sentry.plugins import bindings from sentry.plugins.providers.dummy import DummyRepositoryProvider diff --git a/src/sentry/web/frontend/base.py b/src/sentry/web/frontend/base.py index 04d7d0643c4ea2..00a8a74da64dc3 100644 --- a/src/sentry/web/frontend/base.py +++ b/src/sentry/web/frontend/base.py @@ -6,9 +6,9 @@ from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect -from django.utils.decorators import method_decorator -from django.views.decorators.csrf import csrf_protect +from django.middleware.csrf import CsrfViewMiddleware from django.views.generic import View +from django.views.decorators.csrf import csrf_exempt from sudo.views import redirect_to_sudo from sentry import roles @@ -155,15 +155,26 @@ class BaseView(View, OrganizationMixin): # TODO(dcramer): change sudo so it can be required only on POST sudo_required = False - def __init__(self, auth_required=None, sudo_required=None, *args, **kwargs): + csrf_protect = True + + def __init__(self, auth_required=None, sudo_required=None, csrf_protect=None, + *args, **kwargs): if auth_required is not None: self.auth_required = auth_required if sudo_required is not None: self.sudo_required = sudo_required + if csrf_protect is not None: + self.csrf_protect = csrf_protect super(BaseView, self).__init__(*args, **kwargs) - @method_decorator(csrf_protect) + # we manage csrf verification ourselves + @csrf_exempt def dispatch(self, request, *args, **kwargs): + if self.csrf_protect: + response = self.test_csrf(request) + if response: + return response + if self.is_auth_required(request, *args, **kwargs): return self.handle_auth_required(request, *args, **kwargs) @@ -182,6 +193,10 @@ def dispatch(self, request, *args, **kwargs): return self.handle(request, *args, **kwargs) + def test_csrf(self, request): + middleware = CsrfViewMiddleware() + return middleware.process_view(request, self.dispatch, [request], {}) + def get_access(self, request, *args, **kwargs): return access.DEFAULT diff --git a/src/sentry/web/frontend/integration_setup.py b/src/sentry/web/frontend/integration_setup.py new file mode 100644 index 00000000000000..1c9ed27771213e --- /dev/null +++ b/src/sentry/web/frontend/integration_setup.py @@ -0,0 +1,52 @@ +from __future__ import absolute_import, print_function + +import logging + +from sentry import features +from sentry.integrations.helper import PipelineHelper +from sentry.web.frontend.base import OrganizationView + +logger = logging.getLogger('sentry.integrations') + + +class IntegrationSetupView(OrganizationView): + required_scope = 'org:integrations' + + csrf_protect = False + + def has_feature(self, request, organization): + return features.has( + 'organizations:integrations-v3', + organization=organization, + actor=request.user, + ) + + def handle(self, request, organization, provider_id): + if not self.has_feature(request, organization): + return self.redirect('/') + + if request.GET.get('init') != '1': + helper = PipelineHelper.get_for_request( + request=request, + organization=organization, + provider_id=provider_id, + ) + else: + helper = None + + if helper: + try: + return helper.current_step() + except Exception: + logging.exception('integration.setup-error') + return helper.error('an internal error occurred') + + helper = PipelineHelper.initialize( + request=request, + organization=organization, + provider_id=provider_id, + dialog=True, + ) + # we redirect the user to scrub parameters from the URL to avoid passing + # them into third parties + return self.redirect(request.path) diff --git a/src/sentry/web/urls.py b/src/sentry/web/urls.py index f29d69ce49fd38..235518e25d34e3 100644 --- a/src/sentry/web/urls.py +++ b/src/sentry/web/urls.py @@ -32,6 +32,7 @@ from sentry.web.frontend.group_plugin_action import GroupPluginActionView from sentry.web.frontend.group_tag_export import GroupTagExportView from sentry.web.frontend.home import HomeView +from sentry.web.frontend.integration_setup import IntegrationSetupView from sentry.web.frontend.mailgun_inbound_webhook import \ MailgunInboundWebhookView from sentry.web.frontend.oauth_authorize import OAuthAuthorizeView @@ -320,6 +321,10 @@ def init_all_applications(): OrganizationAuthSettingsView.as_view(), name='sentry-organization-auth-settings' ), + url( + r'^organizations/(?P[\w_-]+)/integrations/(?P[\w_-]+)/setup/$', + IntegrationSetupView.as_view() + ), url( r'^organizations/(?P[\w_-]+)/members/$', OrganizationMembersView.as_view(), diff --git a/tests/js/setup.js b/tests/js/setup.js index 2f24e42797ce39..e75bf81670e679 100644 --- a/tests/js/setup.js +++ b/tests/js/setup.js @@ -91,6 +91,26 @@ window.TestStubs = { ], ...params }; + }, + Integration: (...params) => { + return { + id: '4', + name: 'repo-name', + provider: { + id: 'github', + name: 'GitHub' + }, + ...params + }; + }, + GitHubIntegrationProvider: (...params) => { + return { + id: 'github', + name: 'GitHub', + config: [], + setupUri: '/github-integration-setup-uri/', + ...params + }; } }; diff --git a/tests/js/spec/views/__snapshots__/organizationIntegrations.spec.jsx.snap b/tests/js/spec/views/__snapshots__/organizationIntegrations.spec.jsx.snap new file mode 100644 index 00000000000000..b1a0c5652ee34b --- /dev/null +++ b/tests/js/spec/views/__snapshots__/organizationIntegrations.spec.jsx.snap @@ -0,0 +1,1762 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`OrganizationIntegrations render() with a provider renders 1`] = ` + + + +
+
+
+ +
+

+ + + + + + + + Select a project + + + + + + + + +

+
+
+
+
+ + +
+
+
+
+
+ +
+
+ Organization +
+ +
+
+ Issues +
+ +
+
+
+ Manage +
+ +
+
+
+
+
+
+ + + + Add Integration + + + + + +
+

+ Integrations +

+
+
+

+ Sentry is better with friends +

+

+ Integrations allow you to pull in things like repository data or sync with an external issue tracker. +

+

+ + Learn more + +

+
+
+
+
+
+ + + +`; + +exports[`OrganizationIntegrations render() with a provider renders with a repository 1`] = ` + + + +
+
+
+ +
+

+ + + + + + + + Select a project + + + + + + + + +

+
+
+
+
+ + +
+
+
+
+
+ +
+
+ Organization +
+ +
+
+ Issues +
+ +
+
+
+ Manage +
+ +
+
+
+
+
+
+ + + + Add Integration + + + + + +
+

+ Integrations +

+
+ + + + + + + +
+ + repo-name + + — + + GitHub + + + +
+
+
+
+
+
+
+
+
+`; + +exports[`OrganizationIntegrations render() without any providers is loading when initially rendering 1`] = ` + + +
+ +
+

+ Integrations +

+
+
+

+ Sentry is better with friends +

+

+ Integrations allow you to pull in things like repository data or sync with an external issue tracker. +

+

+ + Learn more + +

+
+ + +`; + +exports[`OrganizationIntegrations render() without any providers renders 1`] = ` + + + +
+
+
+ +
+

+ + + + + + + + Select a project + + + + + + + + +

+
+
+
+
+ + +
+
+
+
+
+ +
+
+ Organization +
+ +
+
+ Issues +
+ +
+
+
+ Manage +
+ +
+
+
+
+
+ +

+ Integrations +

+
+
+

+ Sentry is better with friends +

+

+ Integrations allow you to pull in things like repository data or sync with an external issue tracker. +

+

+ + Learn more + +

+
+
+
+
+
+ + + +`; diff --git a/tests/js/spec/views/organizationIntegrations.spec.jsx b/tests/js/spec/views/organizationIntegrations.spec.jsx new file mode 100644 index 00000000000000..2c5abf0b4d6c57 --- /dev/null +++ b/tests/js/spec/views/organizationIntegrations.spec.jsx @@ -0,0 +1,97 @@ +import React from 'react'; +import {mount, shallow} from 'enzyme'; + +import {Client} from 'app/api'; +import OrganizationIntegrations from 'app/views/organizationIntegrations'; + +const childContextTypes = { + organization: React.PropTypes.object, + location: React.PropTypes.object +}; + +describe('OrganizationIntegrations', function() { + beforeEach(function() { + Client.clearMockResponses(); + }); + + describe('render()', function() { + describe('without any providers', function() { + beforeEach(function() { + Client.addMockResponse({ + url: '/organizations/org-slug/integrations/', + body: [] + }); + Client.addMockResponse({ + url: '/organizations/org-slug/config/integrations/', + body: {providers: []} + }); + }); + + it('is loading when initially rendering', function() { + let wrapper = shallow(, { + context: { + router: TestStubs.router(), + organization: TestStubs.Organization(), + location: TestStubs.location() + }, + childContextTypes + }); + expect(wrapper).toMatchSnapshot(); + }); + + it('renders', function() { + let wrapper = mount(, { + context: { + router: TestStubs.router(), + organization: TestStubs.Organization(), + location: TestStubs.location() + }, + childContextTypes + }); + expect(wrapper.state('loading')).toBe(false); + expect(wrapper).toMatchSnapshot(); + }); + }); + + describe('with a provider', function() { + beforeEach(function() { + Client.addMockResponse({ + url: '/organizations/org-slug/config/integrations/', + body: {providers: [TestStubs.GitHubIntegrationProvider()]} + }); + }); + it('renders', function() { + Client.addMockResponse({ + url: '/organizations/org-slug/integrations/', + body: [] + }); + let wrapper = mount(, { + context: { + router: TestStubs.router(), + organization: TestStubs.Organization(), + location: TestStubs.location() + }, + childContextTypes + }); + expect(wrapper.state('loading')).toBe(false); + expect(wrapper).toMatchSnapshot(); + }); + it('renders with a repository', function() { + Client.addMockResponse({ + url: '/organizations/org-slug/integrations/', + body: [TestStubs.Integration()] + }); + let wrapper = mount(, { + context: { + router: TestStubs.router(), + organization: TestStubs.Organization(), + location: TestStubs.location() + }, + childContextTypes + }); + expect(wrapper.state('loading')).toBe(false); + expect(wrapper).toMatchSnapshot(); + }); + }); + }); +}); diff --git a/tests/sentry/api/endpoints/test_organization_config_integrations.py b/tests/sentry/api/endpoints/test_organization_config_integrations.py new file mode 100644 index 00000000000000..f25fe69e293d0d --- /dev/null +++ b/tests/sentry/api/endpoints/test_organization_config_integrations.py @@ -0,0 +1,23 @@ +from __future__ import absolute_import + +from django.core.urlresolvers import reverse + +from sentry.testutils import APITestCase + + +class OrganizationConfigIntegrationsTest(APITestCase): + def test_simple(self): + self.login_as(user=self.user) + + org = self.create_organization(owner=self.user, name='baz') + + url = reverse('sentry-api-0-organization-config-integrations', args=[org.slug]) + response = self.client.get(url) + + assert response.status_code == 200, response.content + assert len(response.data['providers']) == 1 + provider = response.data['providers'][0] + assert provider['id'] == 'example' + assert provider['name'] == 'Example' + assert provider['config'] + assert provider['setupUri'] diff --git a/tests/sentry/api/endpoints/test_organization_integration_details.py b/tests/sentry/api/endpoints/test_organization_integration_details.py new file mode 100644 index 00000000000000..d68c684a70ea74 --- /dev/null +++ b/tests/sentry/api/endpoints/test_organization_integration_details.py @@ -0,0 +1,46 @@ +from __future__ import absolute_import + +import six + +from sentry.models import Integration, OrganizationIntegration +from sentry.testutils import APITestCase + + +class OrganizationIntegrationDetailsTest(APITestCase): + def test_simple(self): + self.login_as(user=self.user) + org = self.create_organization(owner=self.user, name='baz') + integration = Integration.objects.create( + provider='example', + name='Example', + ) + integration.add_organization(org.id) + path = '/api/0/organizations/{}/integrations/{}/'.format(org.slug, integration.id) + + with self.feature('organizations:integrations-v3', True): + response = self.client.get(path, format='json') + + assert response.status_code == 200, response.content + assert response.data['id'] == six.text_type(integration.id) + + +class OrganizationIntegrationDeleteTest(APITestCase): + def test_simple(self): + self.login_as(user=self.user) + org = self.create_organization(owner=self.user, name='baz') + integration = Integration.objects.create( + provider='example', + name='Example', + ) + integration.add_organization(org.id) + path = '/api/0/organizations/{}/integrations/{}/'.format(org.slug, integration.id) + + with self.feature('organizations:integrations-v3', True): + response = self.client.delete(path, format='json') + + assert response.status_code == 204, response.content + assert Integration.objects.filter(id=integration.id).exists() + assert not OrganizationIntegration.objects.filter( + id=integration.id, + organization=org, + ).exists() diff --git a/tests/sentry/api/endpoints/test_organization_integrations.py b/tests/sentry/api/endpoints/test_organization_integrations.py index c38c364dfcb112..a1f213af040af6 100644 --- a/tests/sentry/api/endpoints/test_organization_integrations.py +++ b/tests/sentry/api/endpoints/test_organization_integrations.py @@ -2,117 +2,24 @@ import six -from django.core.urlresolvers import reverse - -from social_auth.models import UserSocialAuth -from sentry.models import Integration, OrganizationIntegration +from sentry.models import Integration from sentry.testutils import APITestCase class OrganizationIntegrationsListTest(APITestCase): def test_simple(self): self.login_as(user=self.user) - org = self.create_organization(owner=self.user, name='baz') - auth = UserSocialAuth.objects.create( - provider='dummy', - user=self.user, - uid='123456', + integration = Integration.objects.create( + provider='example', + name='Example', ) + integration.add_organization(org.id) + path = '/api/0/organizations/{}/integrations/'.format(org.slug) - url = reverse('sentry-api-0-organization-integrations', args=[org.slug]) with self.feature('organizations:integrations-v3', True): - response = self.client.get(url, format='json') + response = self.client.get(path, format='json') assert response.status_code == 200, response.content assert len(response.data) == 1 - assert response.data[0] == { - 'id': - 'dummy', - 'name': - 'Example', - 'authUrl': - '/account/settings/social/associate/dummy/', - 'auths': [ - { - 'externalId': auth.uid, - 'defaultAuthId': auth.id, - 'user': { - 'email': self.user.email - }, - 'linked': False, - 'integrationId': None, - } - ], - } - - -class OrganizationIntegrationsCreateTest(APITestCase): - def test_simple(self): - self.login_as(user=self.user) - - org = self.create_organization(owner=self.user, name='baz') - auth = UserSocialAuth.objects.create( - provider='dummy', - user=self.user, - uid='123456', - ) - - url = reverse('sentry-api-0-organization-integrations', args=[org.slug]) - with self.feature('organizations:integrations-v3', True): - response = self.client.post( - url, data={ - 'provider': 'dummy', - 'defaultAuthId': auth.id, - } - ) - - assert response.status_code == 201, response.content - - assert Integration.objects.filter(default_auth_id=auth.id).exists() - - assert response.data == { - 'id': - u'dummy', - 'name': - 'Example', - 'authUrl': - '/account/settings/social/associate/dummy/', - 'auths': [ - { - 'externalId': auth.uid, - 'defaultAuthId': auth.id, - 'user': { - 'email': self.user.email - }, - 'linked': True, - 'integrationId': - six.text_type(Integration.objects.get(default_auth_id=auth.id).id), - } - ], - } - assert OrganizationIntegration.objects.filter( - integration__default_auth_id=auth.id, - organization_id=org.id, - ).exists() - - def test_adding_bad_social_auth(self): - self.login_as(user=self.user) - user2 = self.create_user() - auth = UserSocialAuth.objects.create( - provider='dummy', - user=user2, - uid='123456', - ) - org = self.create_organization(owner=self.user, name='baz') - - url = reverse('sentry-api-0-organization-integrations', args=[org.slug]) - with self.feature('organizations:integrations-v3', True): - response = self.client.post( - url, data={ - 'provider': 'dummy', - 'defaultAuthId': auth.id, - } - ) - - assert response.status_code == 400 + assert response.data[0]['id'] == six.text_type(integration.id) diff --git a/tests/sentry/plugins/test_repository_provider.py b/tests/sentry/plugins/test_repository_provider.py index 8a26af061151ae..59fe5cea75e1c9 100644 --- a/tests/sentry/plugins/test_repository_provider.py +++ b/tests/sentry/plugins/test_repository_provider.py @@ -62,8 +62,7 @@ def test_get_auth_for_organization(self): integration = Integration.objects.create( provider='dummy', external_id='123456', - default_auth_id=usa.id, ) - integration.add_organization(org.id) + integration.add_organization(org.id, default_auth_id=usa.id) assert provider.get_auth(user, organization=org) == usa diff --git a/tests/sentry/web/frontend/test_integration_setup.py b/tests/sentry/web/frontend/test_integration_setup.py new file mode 100644 index 00000000000000..970bb73bbd1c08 --- /dev/null +++ b/tests/sentry/web/frontend/test_integration_setup.py @@ -0,0 +1,68 @@ +from __future__ import absolute_import + +import pytest + +from sentry.integrations.example import ExampleSetupView +from sentry.models import Integration, OrganizationIntegration +from sentry.testutils import AuthProviderTestCase, PermissionTestCase + + +class IntegrationSetupPermissionTest(PermissionTestCase): + def setUp(self): + super(IntegrationSetupPermissionTest, self).setUp() + self.path = '/organizations/{}/integrations/example/setup/'.format( + self.organization.slug, + ) + + def test_teamless_admin_cannot_load(self): + with self.feature('organizations:integrations-v3'): + self.assert_teamless_admin_cannot_access(self.path) + + def test_team_admin_cannot_load(self): + with self.feature('organizations:integrations-v3'): + self.assert_team_admin_cannot_access(self.path) + + # this currently redirects the user + @pytest.mark.xfail + def test_manager_can_load(self): + with self.feature('organizations:integrations-v3'): + self.assert_role_can_access(self.path, 'manager') + + # this currently redirects the user + @pytest.mark.xfail + def test_owner_can_load(self): + with self.feature('organizations:integrations-v3'): + self.assert_owner_can_access(self.path) + + +class IntegrationSetupTest(AuthProviderTestCase): + def setUp(self): + super(IntegrationSetupTest, self).setUp() + self.organization = self.create_organization(name='foo', owner=self.user) + self.login_as(self.user) + self.path = '/organizations/{}/integrations/example/setup/'.format( + self.organization.slug, + ) + + def test_basic_flow(self): + with self.feature('organizations:integrations-v3'): + resp = self.client.get(self.path + '?init=1&callback=test') + assert resp.status_code == 302 + + resp = self.client.get(self.path) + assert resp.status_code == 200 + assert ExampleSetupView.TEMPLATE in resp.content.decode('utf-8') + + resp = self.client.post(self.path, {'name': 'test'}) + + assert resp.status_code == 200 + assert 'window.opener.postMessage(' in resp.content + + integration = Integration.objects.get(provider='example') + assert integration.external_id == 'test' + assert integration.name == 'test' + assert integration.metadata == {} + assert OrganizationIntegration.objects.filter( + integration=integration, + organization=self.organization, + ).exists()" ceb2d16f942a4fe4800d570bc27e6741f0408be3,2021-10-07 22:15:08,Marcos Gaeta,ref(models): Split up Models and Managers (#29114),False,Split up Models and Managers (#29114),ref,"diff --git a/src/sentry/integrations/msteams/card_builder.py b/src/sentry/integrations/msteams/card_builder.py index 223ac7f92b6b0f..3047cbf31d71e1 100644 --- a/src/sentry/integrations/msteams/card_builder.py +++ b/src/sentry/integrations/msteams/card_builder.py @@ -1,5 +1,7 @@ +from typing import Optional + from sentry.integrations.metric_alerts import incident_attachment_info -from sentry.models import GroupAssignee, GroupStatus, Project, Team +from sentry.models import Group, GroupStatus, Project, Team, User from sentry.utils.assets import get_asset_url from sentry.utils.compat import map from sentry.utils.http import absolute_uri @@ -28,24 +30,16 @@ def generate_action_payload(action_type, event, rules, integration): } -# get the string of the assignee -# if a user, show the email address -# if a team, show the team slug prepended with a # -def get_assignee_string(group): - try: - actor = GroupAssignee.objects.get(group=group).assigned_actor() - except GroupAssignee.DoesNotExist: - return None +def get_assignee_string(group: Group) -> Optional[str]: + """"""Get a string representation of the group's assignee."""""" + assignee = group.get_assignee() + if isinstance(assignee, User): + return assignee.email - try: - assigned_actor = actor.resolve() - except assigned_actor.type.DoesNotExist: - return None + if isinstance(assignee, Team): + return f""#{assignee.slug}"" - if actor.type == Team: - return f""#{assigned_actor.slug}"" - else: - return assigned_actor.email + return None def build_welcome_card(signed_params): diff --git a/src/sentry/models/__init__.py b/src/sentry/models/__init__.py index 9c8d72276e1d64..70541b0db3d102 100644 --- a/src/sentry/models/__init__.py +++ b/src/sentry/models/__init__.py @@ -73,6 +73,7 @@ from .organizationaccessrequest import * # NOQA from .organizationavatar import * # NOQA from .organizationmember import * # NOQA +from .organizationmemberteam import * # NOQA from .organizationonboardingtask import * # NOQA from .organizationoption import * # NOQA from .platformexternalissue import * # NOQA @@ -86,6 +87,7 @@ from .projectownership import * # NOQA from .projectplatform import * # NOQA from .projectredirect import * # NOQA +from .projectteam import * # NOQA from .promptsactivity import * # NOQA from .pullrequest import * # NOQA from .rawevent import * # NOQA diff --git a/src/sentry/models/actor.py b/src/sentry/models/actor.py index 812ab4a5bdc770..c13625ebbb5c91 100644 --- a/src/sentry/models/actor.py +++ b/src/sentry/models/actor.py @@ -1,5 +1,5 @@ from collections import defaultdict, namedtuple -from typing import TYPE_CHECKING, Optional, Sequence, Type, Union +from typing import TYPE_CHECKING, Mapping, Optional, Sequence, Type, Union from django.db import models from django.db.models.signals import pre_save @@ -137,7 +137,7 @@ def resolve_many(cls, actors: Sequence[""ActorTuple""]) -> Sequence[Union[""Team"", return list(filter(None, [results.get((actor.type, actor.id)) for actor in actors])) @classmethod - def resolve_dict(cls, actor_dict): + def resolve_dict(cls, actor_dict: Mapping[int, ""Actor""]) -> Mapping[int, Union[""Team"", ""User""]]: actors_by_type = defaultdict(list) for actor in actor_dict.values(): actors_by_type[actor.type].append(actor) diff --git a/src/sentry/models/group.py b/src/sentry/models/group.py index 59f3e33aee1c2b..4b3d778fac7fe4 100644 --- a/src/sentry/models/group.py +++ b/src/sentry/models/group.py @@ -7,11 +7,11 @@ from enum import Enum from functools import reduce from operator import or_ -from typing import List, Mapping, Optional, Sequence, Set +from typing import TYPE_CHECKING, List, Mapping, Optional, Sequence, Set, Union from django.core.cache import cache from django.db import models -from django.db.models import Q +from django.db.models import Q, QuerySet from django.utils import timezone from django.utils.http import urlencode, urlquote from django.utils.translation import ugettext_lazy as _ @@ -34,6 +34,9 @@ from sentry.utils.numbers import base32_decode, base32_encode from sentry.utils.strings import strip, truncatechars +if TYPE_CHECKING: + from sentry.models import Integration, Team, User + logger = logging.getLogger(__name__) _short_id_re = re.compile(r""^(.*?)(?:[\s_-])([A-Za-z0-9]+)$"") @@ -282,10 +285,14 @@ def filter_by_event_id(self, project_ids, event_id): return Group.objects.filter(id__in=group_ids) - def get_groups_by_external_issue(self, integration, external_issue_key): + def get_groups_by_external_issue( + self, + integration: ""Integration"", + external_issue_key: str, + ) -> QuerySet: from sentry.models import ExternalIssue, GroupLink - return Group.objects.filter( + return self.filter( id__in=GroupLink.objects.filter( linked_id__in=ExternalIssue.objects.filter( key=external_issue_key, @@ -602,3 +609,18 @@ def issues_mapping(group_ids, project_ids, organization): id__in=group_ids, project_id__in=project_ids, project__organization=organization ) } + + def get_assignee(self) -> Optional[Union[""Team"", ""User""]]: + from sentry.models import GroupAssignee + + try: + group_assignee = GroupAssignee.objects.get(group=self) + except GroupAssignee.DoesNotExist: + return None + + assigned_actor = group_assignee.assigned_actor() + + try: + return assigned_actor.resolve() + except assigned_actor.type.DoesNotExist: + return None diff --git a/src/sentry/models/groupassignee.py b/src/sentry/models/groupassignee.py index ad298ed864cff8..eac217efbd8b72 100644 --- a/src/sentry/models/groupassignee.py +++ b/src/sentry/models/groupassignee.py @@ -1,42 +1,18 @@ import logging -from collections import defaultdict +from typing import TYPE_CHECKING, Optional, Union from django.conf import settings from django.db import models from django.utils import timezone from sentry.db.models import BaseManager, FlexibleForeignKey, Model, sane_repr -from sentry.models.activity import Activity from sentry.notifications.types import GroupSubscriptionReason from sentry.signals import issue_assigned from sentry.types.activity import ActivityType from sentry.utils import metrics - -def get_user_project_ids(users): - """""" - Given a list of users, return a dict where keys are user_ids - and values are a set of the project_ids the user is a member of - """""" - from sentry.models import OrganizationMemberTeam, ProjectTeam - - user_teams = list( - OrganizationMemberTeam.objects.filter( - organizationmember__user__in=users, is_active=True - ).values(""organizationmember__user"", ""team"") - ) - - # team_id to list of projects - projects_by_team = defaultdict(set) - for tp in ProjectTeam.objects.filter(team__in=[ut[""team""] for ut in user_teams]): - projects_by_team[tp.team_id].add(tp.project_id) - - # user_id to projects - projects_by_user = defaultdict(set) - for ut in user_teams: - projects_by_user[ut[""organizationmember__user""]].update(projects_by_team[ut[""team""]]) - - return projects_by_user +if TYPE_CHECKING: + from sentry.models import ActorTuple, Group, Team, User def sync_group_assignee_inbound(integration, email, external_issue_key, assign=True): @@ -46,7 +22,7 @@ def sync_group_assignee_inbound(integration, email, external_issue_key, assign=T Returns a list of groups that were successfully assigned. """""" from sentry import features - from sentry.models import Group, User, UserEmail + from sentry.models import Group, Project, User, UserEmail logger = logging.getLogger(""sentry.integrations.%s"" % integration.provider) @@ -83,7 +59,7 @@ def sync_group_assignee_inbound(integration, email, external_issue_key, assign=T ) } - projects_by_user = get_user_project_ids(list(users.values())) + projects_by_user = Project.objects.get_by_users(users) groups_assigned = [] for group in affected_groups: @@ -125,9 +101,14 @@ def sync_group_assignee_outbound(group, user_id, assign=True): class GroupAssigneeManager(BaseManager): - def assign(self, group, assigned_to, acting_user=None): + def assign( + self, + group: ""Group"", + assigned_to: Union[""Team"", ""User""], + acting_user: Optional[""User""] = None, + ): from sentry import features - from sentry.models import GroupSubscription, Team, User + from sentry.models import Activity, GroupSubscription, Team, User GroupSubscription.objects.subscribe_actor( group=group, actor=assigned_to, reason=GroupSubscriptionReason.assigned @@ -140,17 +121,17 @@ def assign(self, group, assigned_to, acting_user=None): assignee_type = ""team"" other_type = ""user"" else: - raise AssertionError(""Invalid type to assign to: %r"" % type(assigned_to)) + raise AssertionError(f""Invalid type to assign to: {type(assigned_to)}"") now = timezone.now() - assignee, created = GroupAssignee.objects.get_or_create( + assignee, created = self.get_or_create( group=group, defaults={""project"": group.project, assignee_type: assigned_to, ""date_added"": now}, ) if not created: affected = ( - GroupAssignee.objects.filter(group=group) + self.filter(group=group) .exclude(**{assignee_type: assigned_to}) .update(**{assignee_type: assigned_to, other_type: None, ""date_added"": now}) ) @@ -183,9 +164,10 @@ def assign(self, group, assigned_to, acting_user=None): def deassign(self, group, acting_user=None): from sentry import features + from sentry.models import Activity - affected = GroupAssignee.objects.filter(group=group)[:1].count() - GroupAssignee.objects.filter(group=group).delete() + affected = self.filter(group=group)[:1].count() + self.filter(group=group).delete() if affected > 0: activity = Activity.objects.create( @@ -231,7 +213,8 @@ def save(self, *args, **kwargs): ), ""Must have Team or User, not both"" super().save(*args, **kwargs) - def assigned_actor_id(self): + def assigned_actor_id(self) -> str: + # TODO(mgaeta): Create migration for GroupAssignee to use the Actor model. if self.user: return f""user:{self.user_id}"" @@ -240,7 +223,7 @@ def assigned_actor_id(self): raise NotImplementedError(""Unknown Assignee"") - def assigned_actor(self): + def assigned_actor(self) -> ""ActorTuple"": from sentry.models import ActorTuple return ActorTuple.from_actor_identifier(self.assigned_actor_id()) diff --git a/src/sentry/models/organizationmember.py b/src/sentry/models/organizationmember.py index b7f3fadb6aebf4..31979159a6055a 100644 --- a/src/sentry/models/organizationmember.py +++ b/src/sentry/models/organizationmember.py @@ -17,14 +17,7 @@ from bitfield import BitField from sentry import roles from sentry.constants import ALERTS_MEMBER_WRITE_DEFAULT, EVENTS_MEMBER_ADMIN_DEFAULT -from sentry.db.models import ( - BaseModel, - BoundedAutoField, - BoundedPositiveIntegerField, - FlexibleForeignKey, - Model, - sane_repr, -) +from sentry.db.models import BoundedPositiveIntegerField, FlexibleForeignKey, Model, sane_repr from sentry.db.models.manager import BaseManager from sentry.models.team import TeamStatus from sentry.utils.http import absolute_uri @@ -49,36 +42,6 @@ class InviteStatus(Enum): } -class OrganizationMemberTeam(BaseModel): - """""" - Identifies relationships between organization members and the teams they are on. - """""" - - __include_in_export__ = True - - id = BoundedAutoField(primary_key=True) - team = FlexibleForeignKey(""sentry.Team"") - organizationmember = FlexibleForeignKey(""sentry.OrganizationMember"") - # an inactive membership simply removes the team from the default list - # but still allows them to re-join without request - is_active = models.BooleanField(default=True) - - class Meta: - app_label = ""sentry"" - db_table = ""sentry_organizationmember_teams"" - unique_together = ((""team"", ""organizationmember""),) - - __repr__ = sane_repr(""team_id"", ""organizationmember_id"") - - def get_audit_log_data(self): - return { - ""team_slug"": self.team.slug, - ""member_id"": self.organizationmember_id, - ""email"": self.organizationmember.get_email(), - ""is_active"": self.is_active, - } - - class OrganizationMemberManager(BaseManager): def get_contactable_members_for_org(self, organization_id: int) -> QuerySet: """"""Get a list of members we can contact for an organization through email."""""" @@ -350,7 +313,7 @@ def get_avatar_type(self): return ""letter_avatar"" def get_audit_log_data(self): - from sentry.models import Team + from sentry.models import OrganizationMemberTeam, Team teams = list( Team.objects.filter( @@ -371,7 +334,7 @@ def get_audit_log_data(self): } def get_teams(self): - from sentry.models import Team + from sentry.models import OrganizationMemberTeam, Team return Team.objects.filter( status=TeamStatus.VISIBLE, diff --git a/src/sentry/models/organizationmemberteam.py b/src/sentry/models/organizationmemberteam.py new file mode 100644 index 00000000000000..8d9468027d1902 --- /dev/null +++ b/src/sentry/models/organizationmemberteam.py @@ -0,0 +1,33 @@ +from django.db import models + +from sentry.db.models import BaseModel, BoundedAutoField, FlexibleForeignKey, sane_repr + + +class OrganizationMemberTeam(BaseModel): + """""" + Identifies relationships between organization members and the teams they are on. + """""" + + __include_in_export__ = True + + id = BoundedAutoField(primary_key=True) + team = FlexibleForeignKey(""sentry.Team"") + organizationmember = FlexibleForeignKey(""sentry.OrganizationMember"") + # an inactive membership simply removes the team from the default list + # but still allows them to re-join without request + is_active = models.BooleanField(default=True) + + class Meta: + app_label = ""sentry"" + db_table = ""sentry_organizationmember_teams"" + unique_together = ((""team"", ""organizationmember""),) + + __repr__ = sane_repr(""team_id"", ""organizationmember_id"") + + def get_audit_log_data(self): + return { + ""team_slug"": self.team.slug, + ""member_id"": self.organizationmember_id, + ""email"": self.organizationmember.get_email(), + ""is_active"": self.is_active, + } diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py index 7e3aee132ad51d..454b2915c4e7e5 100644 --- a/src/sentry/models/project.py +++ b/src/sentry/models/project.py @@ -1,14 +1,14 @@ import logging import warnings from collections import defaultdict -from typing import TYPE_CHECKING, Sequence +from typing import TYPE_CHECKING, Iterable, Mapping, Sequence from uuid import uuid1 import sentry_sdk from django.conf import settings from django.db import IntegrityError, models, transaction from django.db.models import QuerySet -from django.db.models.signals import post_delete, post_save, pre_delete +from django.db.models.signals import pre_delete from django.utils import timezone from django.utils.http import urlencode from django.utils.translation import ugettext_lazy as _ @@ -26,7 +26,6 @@ sane_repr, ) from sentry.db.models.utils import slugify_instance -from sentry.tasks.code_owners import update_code_owners_schema from sentry.utils import metrics from sentry.utils.colors import get_hashed_color from sentry.utils.http import absolute_uri @@ -34,48 +33,25 @@ from sentry.utils.retries import TimedRetryPolicy if TYPE_CHECKING: - from sentry.models import Team + from sentry.models import User # TODO(dcramer): pull in enum library ProjectStatus = ObjectStatus -class ProjectTeamManager(BaseManager): - def get_for_teams_with_org_cache(self, teams: Sequence[""Team""]) -> Sequence[""ProjectTeam""]: - project_teams = ( - self.filter(team__in=teams, project__status=ProjectStatus.VISIBLE) - .order_by(""project__name"", ""project__slug"") - .select_related(""project"") - ) - - # TODO(dcramer): we should query in bulk for ones we're missing here - orgs = {i.organization_id: i.organization for i in teams} - - for project_team in project_teams: - project_team.project.set_cached_field_value( - ""organization"", orgs[project_team.project.organization_id] - ) - - return project_teams - - -class ProjectTeam(Model): - __include_in_export__ = True - - project = FlexibleForeignKey(""sentry.Project"") - team = FlexibleForeignKey(""sentry.Team"") - - objects = ProjectTeamManager() - - class Meta: - app_label = ""sentry"" - db_table = ""sentry_projectteam"" - unique_together = ((""project"", ""team""),) - - __repr__ = sane_repr(""project_id"", ""team_id"") - - class ProjectManager(BaseManager): + def get_by_users(self, users: Iterable[""User""]) -> Mapping[""User"", Iterable[""Project""]]: + """"""Given a list of users, return a mapping of each user to the projects they are a member of."""""" + project_rows = self.filter( + projectteam__team__organizationmemberteam__is_active=True, + projectteam__team__organizationmemberteam__organizationmember__user__in=users, + ).values_list(""id"", ""projectteam__team__organizationmemberteam__organizationmember__user"") + + projects_by_user_id = defaultdict(set) + for project_id, user_id in project_rows: + projects_by_user_id[user_id].add(project_id) + return projects_by_user_id + def get_for_user_ids(self, user_ids: Sequence[int]) -> QuerySet: """"""Returns the QuerySet of all projects that a set of Users have access to."""""" from sentry.models import ProjectStatus @@ -106,7 +82,7 @@ def get_for_user(self, team, user, scope=None, _skip_team_check=False): try: team = team_list[team_list.index(team)] except ValueError: - logging.info(""User does not have access to team: %s"", team.id) + logging.info(f""User does not have access to team: {team.id}"") return [] base_qs = self.filter(teams=team, status=ProjectStatus.VISIBLE) @@ -119,6 +95,8 @@ def get_for_user(self, team, user, scope=None, _skip_team_check=False): class Project(Model, PendingDeletionMixin): + from sentry.models.projectteam import ProjectTeam + """""" Projects are permission based namespaces which generally are the top level entry point for all data. @@ -347,6 +325,8 @@ def transfer_to(self, team=None, organization=None): self.add_team(team) def add_team(self, team): + from sentry.models.projectteam import ProjectTeam + try: with transaction.atomic(): ProjectTeam.objects.create(project=self, team=team) @@ -358,6 +338,7 @@ def add_team(self, team): def remove_team(self, team): from sentry.incidents.models import AlertRule from sentry.models import Rule + from sentry.models.projectteam import ProjectTeam ProjectTeam.objects.filter(project=self, team=team).delete() AlertRule.objects.fetch_for_project(self).filter(owner_id=team.actor_id).update(owner=None) @@ -373,7 +354,7 @@ def get_security_token(self): return security_token def get_lock_key(self): - return ""project_token:%s"" % self.id + return f""project_token:{self.id}"" def copy_settings_from(self, project_id): """""" @@ -388,7 +369,13 @@ def copy_settings_from(self, project_id): Returns True if the settings have successfully been copied over Returns False otherwise """""" - from sentry.models import EnvironmentProject, ProjectOption, ProjectOwnership, Rule + from sentry.models import ( + EnvironmentProject, + ProjectOption, + ProjectOwnership, + ProjectTeam, + Rule, + ) model_list = [EnvironmentProject, ProjectOwnership, ProjectTeam, Rule] @@ -437,23 +424,3 @@ def delete(self, **kwargs): pre_delete.connect(delete_pending_deletion_option, sender=Project, weak=False) -post_save.connect( - lambda instance, **kwargs: update_code_owners_schema.apply_async( - kwargs={ - ""organization"": instance.project.organization, - ""projects"": [instance.project], - } - ), - sender=ProjectTeam, - weak=False, -) -post_delete.connect( - lambda instance, **kwargs: update_code_owners_schema.apply_async( - kwargs={ - ""organization"": instance.project.organization, - ""projects"": [instance.project], - } - ), - sender=ProjectTeam, - weak=False, -) diff --git a/src/sentry/models/projectteam.py b/src/sentry/models/projectteam.py new file mode 100644 index 00000000000000..3795d44ac06ce1 --- /dev/null +++ b/src/sentry/models/projectteam.py @@ -0,0 +1,70 @@ +from typing import TYPE_CHECKING, Sequence + +from django.db.models.signals import post_delete, post_save + +from sentry.constants import ObjectStatus +from sentry.db.models import BaseManager, FlexibleForeignKey, Model, sane_repr +from sentry.tasks.code_owners import update_code_owners_schema + +if TYPE_CHECKING: + from sentry.models import Team + +# TODO(dcramer): pull in enum library +ProjectStatus = ObjectStatus + + +class ProjectTeamManager(BaseManager): + def get_for_teams_with_org_cache(self, teams: Sequence[""Team""]) -> Sequence[""ProjectTeam""]: + project_teams = ( + self.filter(team__in=teams, project__status=ProjectStatus.VISIBLE) + .order_by(""project__name"", ""project__slug"") + .select_related(""project"") + ) + + # TODO(dcramer): we should query in bulk for ones we're missing here + orgs = {i.organization_id: i.organization for i in teams} + + for project_team in project_teams: + project_team.project.set_cached_field_value( + ""organization"", orgs[project_team.project.organization_id] + ) + + return project_teams + + +class ProjectTeam(Model): + __include_in_export__ = True + + project = FlexibleForeignKey(""sentry.Project"") + team = FlexibleForeignKey(""sentry.Team"") + + objects = ProjectTeamManager() + + class Meta: + app_label = ""sentry"" + db_table = ""sentry_projectteam"" + unique_together = ((""project"", ""team""),) + + __repr__ = sane_repr(""project_id"", ""team_id"") + + +post_save.connect( + lambda instance, **kwargs: update_code_owners_schema.apply_async( + kwargs={ + ""organization"": instance.project.organization, + ""projects"": [instance.project], + } + ), + sender=ProjectTeam, + weak=False, +) +post_delete.connect( + lambda instance, **kwargs: update_code_owners_schema.apply_async( + kwargs={ + ""organization"": instance.project.organization, + ""projects"": [instance.project], + } + ), + sender=ProjectTeam, + weak=False, +) diff --git a/src/sentry/models/team.py b/src/sentry/models/team.py index 17c67120719a40..f15126f13fb28c 100644 --- a/src/sentry/models/team.py +++ b/src/sentry/models/team.py @@ -1,5 +1,6 @@ import warnings from collections import defaultdict +from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union from django.conf import settings from django.db import IntegrityError, connections, models, router, transaction @@ -18,9 +19,18 @@ from sentry.tasks.code_owners import update_code_owners_schema from sentry.utils.retries import TimedRetryPolicy +if TYPE_CHECKING: + from sentry.models import Organization, Project, User + class TeamManager(BaseManager): - def get_for_user(self, organization, user, scope=None, with_projects=False): + def get_for_user( + self, + organization: ""Organization"", + user: ""User"", + scope: Optional[str] = None, + with_projects: bool = False, + ) -> Union[Sequence[""Team""], Sequence[Tuple[""Team"", Sequence[""Project""]]]]: """""" Returns a list of all teams a user has some level of access to. """""" diff --git a/src/sentry/models/user.py b/src/sentry/models/user.py index 16ce3d8279ce32..1edcec495d8af5 100644 --- a/src/sentry/models/user.py +++ b/src/sentry/models/user.py @@ -22,7 +22,7 @@ audit_logger = logging.getLogger(""sentry.audit.user"") if TYPE_CHECKING: - from sentry.models import Organization + from sentry.models import Group, Organization, Team class UserManager(BaseManager, DjangoUserManager): @@ -41,14 +41,15 @@ def get_team_members_with_verified_email_for_projects( is_active=True, ).distinct() - def get_from_group(self, group): + def get_from_group(self, group: ""Group"") -> QuerySet: """"""Get a queryset of all users in all teams in a given Group's project."""""" return self.filter( + sentry_orgmember_set__organization=group.organization, sentry_orgmember_set__teams__in=group.project.teams.all(), is_active=True, ) - def get_from_teams(self, organization_id, teams): + def get_from_teams(self, organization_id: int, teams: Sequence[""Team""]) -> QuerySet: return self.filter( sentry_orgmember_set__organization_id=organization_id, sentry_orgmember_set__organizationmemberteam__team__in=teams, diff --git a/tests/sentry/manager/test_project_manager.py b/tests/sentry/manager/test_project_manager.py new file mode 100644 index 00000000000000..5ff61f533c57fe --- /dev/null +++ b/tests/sentry/manager/test_project_manager.py @@ -0,0 +1,64 @@ +from sentry.models import Project, User +from sentry.testutils import TestCase + + +class ProjectManagerTest(TestCase): + def test_get_for_user(self): + user = User.objects.create(username=""foo"") + org = self.create_organization() + team = self.create_team(organization=org, name=""Test"") + project = self.create_project(teams=[team], name=""foo"") + project2 = self.create_project(teams=[team], name=""baz"") + + result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=True) + assert result == [project2, project] + + result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=False) + assert result == [] + + self.create_member(organization=org, user=user, teams=[team]) + + # check again after creating member + result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=True) + assert result == [project2, project] + + result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=False) + assert result == [project2, project] + + # test with scope user doesn't have + result = Project.objects.get_for_user( + team=team, user=user, _skip_team_check=False, scope=""project:write"" + ) + assert result == [] + + # check with scope they do have + result = Project.objects.get_for_user( + team=team, user=user, _skip_team_check=False, scope=""project:read"" + ) + assert result == [project2, project] + + def test_get_by_users_empty(self): + assert Project.objects.get_by_users([]) == {} + assert Project.objects.get_by_users([self.user]) == {} + + def test_get_by_users(self): + organization = self.create_organization() + + user1 = self.create_user(""foo@example.com"") + user2 = self.create_user(""foo2@example.com"") + + team1 = self.create_team(organization=organization, name=""team_1"") + self.create_member(user=user1, organization=organization, teams=[team1]) + team2 = self.create_team(organization=organization, name=""team_2"") + self.create_member(user=user2, organization=organization, teams=[team2]) + + project1 = self.create_project(teams=[team1], name=""foo"") + project2 = self.create_project(teams=[team1, team2], name=""baz"") + self.create_project(organization=organization, name=""no_teams"") + + assert Project.objects.get_by_users({user1}) == {user1.id: {project1.id, project2.id}} + assert Project.objects.get_by_users({user2}) == {user2.id: {project2.id}} + assert Project.objects.get_by_users({user1, user2}) == { + user1.id: {project1.id, project2.id}, + user2.id: {project2.id}, + } diff --git a/tests/sentry/manager/tests.py b/tests/sentry/manager/tests.py index 479dd2fde3972d..4dd723066e8853 100644 --- a/tests/sentry/manager/tests.py +++ b/tests/sentry/manager/tests.py @@ -1,4 +1,4 @@ -from sentry.models import Group, Project, Team, User +from sentry.models import Group, Team, User from sentry.testutils import TestCase @@ -55,39 +55,3 @@ def test_with_projects(self): project2 = self.create_project(teams=[team], name=""bar"") result = Team.objects.get_for_user(organization=org, user=user, with_projects=True) assert result == [(team, [project2, project])] - - -class ProjectManagerTest(TestCase): - def test_simple(self): - user = User.objects.create(username=""foo"") - org = self.create_organization() - team = self.create_team(organization=org, name=""Test"") - project = self.create_project(teams=[team], name=""foo"") - project2 = self.create_project(teams=[team], name=""baz"") - - result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=True) - assert result == [project2, project] - - result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=False) - assert result == [] - - self.create_member(organization=org, user=user, teams=[team]) - - # check again after creating member - result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=True) - assert result == [project2, project] - - result = Project.objects.get_for_user(team=team, user=user, _skip_team_check=False) - assert result == [project2, project] - - # test with scope user doesn't have - result = Project.objects.get_for_user( - team=team, user=user, _skip_team_check=False, scope=""project:write"" - ) - assert result == [] - - # check with scope they do have - result = Project.objects.get_for_user( - team=team, user=user, _skip_team_check=False, scope=""project:read"" - ) - assert result == [project2, project]" 9b2d638481c0f7b8bd7cfc05717c48eb6b24b1b1,2021-09-13 19:10:09,Priscila Oliveira,ref(test): Convert eventOrGroupHeader test rto RTL (#28524),False,Convert eventOrGroupHeader test rto RTL (#28524),ref,"diff --git a/static/app/components/globalSelectionLink.tsx b/static/app/components/globalSelectionLink.tsx index e05d333779e1b9..e3a31f50e56e25 100644 --- a/static/app/components/globalSelectionLink.tsx +++ b/static/app/components/globalSelectionLink.tsx @@ -68,6 +68,7 @@ class GlobalSelectionLink extends React.Component { const url = (typeof to === 'string' ? to : to.pathname) + '?' + qs.stringify(queryStringObject); + return ( {this.props.children} diff --git a/static/app/types/event.tsx b/static/app/types/event.tsx index c4d970f2826e5f..76d314e161bcb0 100644 --- a/static/app/types/event.tsx +++ b/static/app/types/event.tsx @@ -184,8 +184,6 @@ type EventBase = { message: string; entries: Entry[]; errors: any[]; - previousEventID?: string; - nextEventID?: string; projectSlug: string; projectID: string; tags: EventTag[]; @@ -198,6 +196,8 @@ type EventBase = { enhancements: string; }; crashFile: IssueAttachment | null; + previousEventID?: string; + nextEventID?: string; groupID?: string; context?: Record; device?: Record; diff --git a/tests/js/spec/components/eventOrGroupHeader.spec.jsx b/tests/js/spec/components/eventOrGroupHeader.spec.jsx deleted file mode 100644 index 0813390fbb0827..00000000000000 --- a/tests/js/spec/components/eventOrGroupHeader.spec.jsx +++ /dev/null @@ -1,225 +0,0 @@ -import {mountWithTheme} from 'sentry-test/enzyme'; -import {initializeOrg} from 'sentry-test/initializeOrg'; - -import EventOrGroupHeader from 'app/components/eventOrGroupHeader'; - -const data = { - metadata: { - type: 'metadata type', - directive: 'metadata directive', - uri: 'metadata uri', - value: 'metadata value', - message: 'metadata message', - }, - culprit: 'culprit', -}; - -describe('EventOrGroupHeader', function () { - const {routerContext} = initializeOrg(); - describe('Group', function () { - const groupData = { - ...data, - level: 'error', - id: 'id', - }; - - it('renders with `type = error`', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('renders with `type = csp`', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('renders with `type = default`', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('renders metadata values in message for error events', function () { - const component = mountWithTheme( - , - routerContext - ); - const message = component.find('Message'); - expect(message.text()).toEqual('metadata value'); - }); - - it('renders location', function () { - const component = mountWithTheme( - , - routerContext - ); - const location = component.find('Location'); - expect(location.text()).toEqual('in path/to/file.swift'); - }); - }); - - describe('Event', function () { - const eventData = { - ...data, - id: 'id', - eventID: 'eventID', - groupID: 'groupID', - culprit: undefined, - }; - - it('renders with `type = error`', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('renders with `type = csp`', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('renders with `type = default`', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('hides level tag', function () { - const component = mountWithTheme( - , - routerContext - ); - - expect(component).toSnapshot(); - }); - - it('keeps sort in link when query has sort', function () { - const query = { - sort: 'freq', - }; - - const wrapper = mountWithTheme( - - ); - - expect(wrapper.find('GlobalSelectionLink').props().to.query.sort).toEqual('freq'); - }); - - it('lack of project adds allp parameter', function () { - const query = {}; - - const wrapper = mountWithTheme( - - ); - - expect(wrapper.find('GlobalSelectionLink').props().to.query._allp).toEqual(1); - }); - }); -}); diff --git a/tests/js/spec/components/eventOrGroupHeader.spec.tsx b/tests/js/spec/components/eventOrGroupHeader.spec.tsx new file mode 100644 index 00000000000000..b251a474e6aa31 --- /dev/null +++ b/tests/js/spec/components/eventOrGroupHeader.spec.tsx @@ -0,0 +1,242 @@ +import {initializeOrg} from 'sentry-test/initializeOrg'; +import {mountWithTheme} from 'sentry-test/reactTestingLibrary'; +import {findByTextContent} from 'sentry-test/utils'; + +import EventOrGroupHeader from 'app/components/eventOrGroupHeader'; +import {EventOrGroupType} from 'app/types'; + +// @ts-expect-error +const group = TestStubs.Group({ + level: 'error', + metadata: { + type: 'metadata type', + directive: 'metadata directive', + uri: 'metadata uri', + value: 'metadata value', + message: 'metadata message', + }, + culprit: 'culprit', +}); + +// @ts-expect-error +const event = TestStubs.Event({ + id: 'id', + eventID: 'eventID', + groupID: 'groupID', + culprit: undefined, + metadata: { + type: 'metadata type', + directive: 'metadata directive', + uri: 'metadata uri', + value: 'metadata value', + message: 'metadata message', + }, +}); + +describe('EventOrGroupHeader', function () { + const {organization, router, routerContext} = initializeOrg({ + router: {orgId: 'orgId'}, + } as Parameters[0]); + + describe('Group', function () { + it('renders with `type = error`', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + + expect(container).toSnapshot(); + }); + + it('renders with `type = csp`', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + + expect(container).toSnapshot(); + }); + + it('renders with `type = default`', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + + expect(container).toSnapshot(); + }); + + it('renders metadata values in message for error events', function () { + const {getByText} = mountWithTheme( + , + {context: routerContext} + ); + + expect(getByText('metadata value')).toBeTruthy(); + }); + + it('renders location', async function () { + const component = mountWithTheme( + , + {context: routerContext} + ); + + expect(await findByTextContent(component, 'in path/to/file.swift')).toBeTruthy(); + }); + }); + + describe('Event', function () { + it('renders with `type = error`', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + expect(container).toSnapshot(); + }); + + it('renders with `type = csp`', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + expect(container).toSnapshot(); + }); + + it('renders with `type = default`', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + expect(container).toSnapshot(); + }); + + it('hides level tag', function () { + const {container} = mountWithTheme( + , + {context: routerContext} + ); + expect(container).toSnapshot(); + }); + + it('keeps sort in link when query has sort', function () { + const {getByRole} = mountWithTheme( + + ); + + expect(getByRole('link')).toHaveAttribute( + 'href', + '/organizations/org-slug/issues/groupID/events/eventID/?_allp=1&sort=freq' + ); + }); + + it('lack of project adds allp parameter', function () { + const {getByRole} = mountWithTheme( + + ); + + expect(getByRole('link')).toHaveAttribute( + 'href', + '/organizations/org-slug/issues/groupID/events/eventID/?_allp=1' + ); + }); + }); +});" 9d2d6bc3c8c349421155907d3a32f4360931c417,2023-10-20 23:25:43,David Wang,ref(crons): Guard against duplicate create events (#58493),False,Guard against duplicate create events (#58493),ref,"diff --git a/src/sentry/monitors/consumers/monitor_consumer.py b/src/sentry/monitors/consumers/monitor_consumer.py index 3a93c68a37d146..b1ea5fd8c34523 100644 --- a/src/sentry/monitors/consumers/monitor_consumer.py +++ b/src/sentry/monitors/consumers/monitor_consumer.py @@ -107,7 +107,8 @@ def _ensure_monitor_with_config( ""config"": validated_config, }, ) - signal_monitor_created(project, None, True) + if created: + signal_monitor_created(project, None, True) # Update existing monitor if monitor and not created and monitor.config != validated_config:" e87c88cfba3dd9a257962937130b9f18be5ffe67,2024-09-26 22:58:15,Michael Sun,fix(issue-views): Fix bug where renaming is triggered on single click (#78215),False,Fix bug where renaming is triggered on single click (#78215),fix,"diff --git a/static/app/components/draggableTabs/draggableTabList.tsx b/static/app/components/draggableTabs/draggableTabList.tsx index 9675cc3e8c0310..b2bec19953f332 100644 --- a/static/app/components/draggableTabs/draggableTabList.tsx +++ b/static/app/components/draggableTabs/draggableTabList.tsx @@ -132,6 +132,7 @@ function Tabs({ hoveringKey, setHoveringKey, tempTabActive, + editingTabKey, }: { ariaProps: AriaTabListOptions; hoveringKey: Key | 'addView' | null; @@ -145,6 +146,7 @@ function Tabs({ tempTabActive: boolean; className?: string; disabled?: boolean; + editingTabKey?: string; onChange?: (key: string | number) => void; tabVariant?: BaseTabProps['variant']; value?: string | number; @@ -230,6 +232,7 @@ function Tabs({ dragTransition={{bounceStiffness: 400, bounceDamping: 40}} // Recovers spring behavior thats lost when using dragElastic=0 transition={{delay: -0.1}} // Skips the first few frames of the animation that make the tab appear to shrink before growing layout + drag={item.key !== editingTabKey} // Disable dragging if the tab is being edited onDrag={() => setIsDragging(true)} onDragEnd={() => setIsDragging(false)} onHoverStart={() => setHoveringKey(item.key)} @@ -331,6 +334,7 @@ function BaseDraggableTabList({ hoveringKey={hoveringKey} setHoveringKey={setHoveringKey} tempTabActive={!!tempTab} + editingTabKey={props.editingTabKey} /> { onReorder: (newOrder: Node[]) => void; className?: string; + editingTabKey?: string; hideBorder?: boolean; onAddView?: React.MouseEventHandler; outerWrapStyles?: React.CSSProperties; diff --git a/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx b/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx index 8563539549d260..94b7b3398ae538 100644 --- a/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx +++ b/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx @@ -407,6 +407,7 @@ export function DraggableTabBar({ defaultSelectedKey={initialTabKey} onAddView={handleCreateNewView} orientation=""horizontal"" + editingTabKey={editingTabKey ?? undefined} hideBorder > {allTabs.map(tab => ( diff --git a/static/app/views/issueList/groupSearchViewTabs/editableTabTitle.tsx b/static/app/views/issueList/groupSearchViewTabs/editableTabTitle.tsx index d791e1b6b06962..25e3cc5e8a3f40 100644 --- a/static/app/views/issueList/groupSearchViewTabs/editableTabTitle.tsx +++ b/static/app/views/issueList/groupSearchViewTabs/editableTabTitle.tsx @@ -76,6 +76,7 @@ function EditableTabTitle({ if (isEditing) { requestAnimationFrame(() => { inputRef.current?.focus(); + inputRef.current?.select(); }); } else { inputRef.current?.blur(); @@ -94,17 +95,22 @@ function EditableTabTitle({ value={inputValue} onChange={handleOnChange} onKeyDown={handleOnKeyDown} - onDoubleClick={() => isSelected && setIsEditing(true)} + onDoubleClick={() => setIsEditing(true)} onBlur={handleOnBlur} ref={inputRef} style={memoizedStyles} isEditing={isEditing} - onFocus={e => e.target.select()} onPointerDown={e => { e.stopPropagation(); + if (!isEditing) { + e.preventDefault(); + } }} onMouseDown={e => { e.stopPropagation(); + if (!isEditing) { + e.preventDefault(); + } }} maxLength={128} />" a24b57bcb0ae704a77450b4a6876e6722b73b63e,2024-12-02 21:49:10,George Gritsouk,"fix(insights): Link ""Highest Cache Miss Rate"" widget to module correctly (#81514)",False,"Link ""Highest Cache Miss Rate"" widget to module correctly (#81514)",fix,"diff --git a/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx b/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx index 073e5278d645c5..c7b44d49c93d88 100644 --- a/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx +++ b/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx @@ -26,7 +26,7 @@ import {useLocation} from 'sentry/utils/useLocation'; import withApi from 'sentry/utils/withApi'; import {getResourcesEventViewQuery} from 'sentry/views/insights/browser/common/queries/useResourcesQuery'; import {DEFAULT_RESOURCE_TYPES} from 'sentry/views/insights/browser/resources/settings'; -import {BASE_FILTERS, CACHE_BASE_URL} from 'sentry/views/insights/cache/settings'; +import {BASE_FILTERS} from 'sentry/views/insights/cache/settings'; import {SpanDescriptionCell} from 'sentry/views/insights/common/components/tableCells/spanDescriptionCell'; import {TimeSpentCell} from 'sentry/views/insights/common/components/tableCells/timeSpentCell'; import {STARFISH_CHART_INTERVAL_FIDELITY} from 'sentry/views/insights/common/utils/constants'; @@ -687,10 +687,13 @@ export function LineChartListWidget(props: PerformanceWidgetProps) { ); case PerformanceWidgetSetting.HIGHEST_CACHE_MISS_RATE_TRANSACTIONS: + const moduleRoute = moduleURLBuilder('cache', 'backend'); const cacheMissRate = listItem[fieldString] as any; + const target = normalizeUrl( - `${CACHE_BASE_URL}/?${qs.stringify({transaction: transaction, project: listItem['project.id']})}` + `/${moduleRoute}/?${qs.stringify({transaction: transaction, project: listItem['project.id']})}` ); + return ( " 70a90fb99aa3d55adaed19e30202d446c3a70eeb,2022-01-14 03:40:02,Scott Cooper,fix(teamStats): Fix link to alert details from triggered (#31124),False,Fix link to alert details from triggered (#31124),fix,"diff --git a/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx b/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx index 60135a9d0d2a90..b241bb6ed01c93 100644 --- a/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx +++ b/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx @@ -186,7 +186,7 @@ class TeamAlertsTriggered extends AsyncComponent {
{rule.name} " 5bb01c579fd8436f27c4838415f328a1cb3d46a0,2023-06-01 14:59:06,Francesco Novy,ref: Add feature flag for org-based auth tokens (#50064),False,Add feature flag for org-based auth tokens (#50064),ref,"diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index a49788a27a2dbe..fd3022e62716a4 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1533,6 +1533,8 @@ def SOCIAL_AUTH_DEFAULT_USERNAME(): ""organizations:js-sdk-dynamic-loader"": False, # If true certain Slack messages will be escaped to prevent rendering markdown ""organizations:slack-escape-messages"": False, + # If true, allow to create/use org access tokens + ""organizations:org-access-tokens"": False, # Adds additional filters and a new section to issue alert rules. ""projects:alert-filters"": True, # Enable functionality to specify custom inbound filters on events. diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index 993d1a9174ad48..700a7a233baebe 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -105,6 +105,7 @@ default_manager.add(""organizations:minute-resolution-sessions"", OrganizationFeature, FeatureHandlerStrategy.INTERNAL) default_manager.add(""organizations:mobile-vitals"", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add(""organizations:mobile-cpu-memory-in-transactions"", OrganizationFeature, FeatureHandlerStrategy.REMOTE) +default_manager.add(""organizations:org-access-tokens"", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add(""organizations:view-hierarchies-options-dev"", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add(""organizations:anr-improvements"", OrganizationFeature, FeatureHandlerStrategy.REMOTE) default_manager.add(""organizations:anr-analyze-frames"", OrganizationFeature, FeatureHandlerStrategy.REMOTE)" 3cdb3c6ff3246ed572b0a2730af3711aa6413293,2018-11-20 00:20:17,Billy Vong,feat(charts): Allow local/utc date formatting in charts (#10628),False,Allow local/utc date formatting in charts (#10628),feat,"diff --git a/src/sentry/static/sentry/app/components/charts/baseChart.jsx b/src/sentry/static/sentry/app/components/charts/baseChart.jsx index 1f7e73912ad2dc..02d8e0c0f18bf9 100644 --- a/src/sentry/static/sentry/app/components/charts/baseChart.jsx +++ b/src/sentry/static/sentry/app/components/charts/baseChart.jsx @@ -5,6 +5,7 @@ import React from 'react'; import ReactEchartsCore from 'echarts-for-react/lib/core'; import echarts from 'echarts/lib/echarts'; +import {DEFAULT_USE_UTC} from 'app/constants'; import SentryTypes from 'app/sentryTypes'; import theme from 'app/utils/theme'; @@ -108,6 +109,9 @@ class BaseChart extends React.Component { // How is data grouped (affects formatting of axis labels and tooltips) interval: PropTypes.oneOf(['hour', 'day']), + + // Formats dates as UTC? + utc: PropTypes.bool, }; static defaultProps = { @@ -124,6 +128,7 @@ class BaseChart extends React.Component { yAxis: {}, isGroupedByDate: false, interval: 'day', + utc: DEFAULT_USE_UTC, }; handleChartReady = (...args) => { @@ -155,6 +160,7 @@ class BaseChart extends React.Component { isGroupedByDate, interval, previousPeriod, + utc, devicePixelRatio, height, @@ -194,7 +200,9 @@ class BaseChart extends React.Component { color: colors || this.getColorPalette(), grid: Grid(grid), tooltip: - tooltip !== null ? Tooltip({interval, isGroupedByDate, ...tooltip}) : null, + tooltip !== null + ? Tooltip({interval, isGroupedByDate, utc, ...tooltip}) + : null, legend: legend ? Legend({...legend}) : null, yAxis: yAxis !== null ? YAxis(yAxis) : null, xAxis: @@ -203,6 +211,7 @@ class BaseChart extends React.Component { ...xAxis, interval, isGroupedByDate, + utc, }) : null, series: !previousPeriod diff --git a/src/sentry/static/sentry/app/components/charts/components/tooltip.jsx b/src/sentry/static/sentry/app/components/charts/components/tooltip.jsx index f3b75b6478a900..baccc2a9b2f78a 100644 --- a/src/sentry/static/sentry/app/components/charts/components/tooltip.jsx +++ b/src/sentry/static/sentry/app/components/charts/components/tooltip.jsx @@ -1,16 +1,17 @@ -import moment from 'moment'; import 'echarts/lib/component/tooltip'; + +import {getFormattedDate} from 'app/utils/dates'; import {truncationFormatter} from '../utils'; -function formatAxisLabel(value, isTimestamp) { +function formatAxisLabel(value, isTimestamp, utc) { if (!isTimestamp) { return value; } - return moment.utc(value).format('MMM D, YYYY'); + return getFormattedDate(value, 'MMM D, YYYY', utc); } -function getFormatter({filter, isGroupedByDate, truncate}) { +function getFormatter({filter, isGroupedByDate, truncate, utc}) { const getFilter = seriesParam => { const value = seriesParam.data[1]; if (typeof filter === 'function') { @@ -23,7 +24,7 @@ function getFormatter({filter, isGroupedByDate, truncate}) { return seriesParams => { const label = seriesParams.length && - formatAxisLabel(seriesParams[0].axisValueLabel, isGroupedByDate); + formatAxisLabel(seriesParams[0].axisValueLabel, isGroupedByDate, utc); return [ `
${truncationFormatter(label, truncate)}
`, seriesParams @@ -39,9 +40,9 @@ function getFormatter({filter, isGroupedByDate, truncate}) { } export default function Tooltip( - {filter, isGroupedByDate, formatter, truncate, ...props} = {} + {filter, isGroupedByDate, formatter, truncate, utc, ...props} = {} ) { - formatter = formatter || getFormatter({filter, isGroupedByDate, truncate}); + formatter = formatter || getFormatter({filter, isGroupedByDate, truncate, utc}); return { show: true, diff --git a/src/sentry/static/sentry/app/components/charts/components/xAxis.jsx b/src/sentry/static/sentry/app/components/charts/components/xAxis.jsx index eff658d2f2ef5e..d0a0e0039ddc3e 100644 --- a/src/sentry/static/sentry/app/components/charts/components/xAxis.jsx +++ b/src/sentry/static/sentry/app/components/charts/components/xAxis.jsx @@ -1,16 +1,12 @@ -import moment from 'moment'; - +import {getFormattedDate} from 'app/utils/dates'; import theme from 'app/utils/theme'; import {truncationFormatter} from '../utils'; -export default function XAxis({isGroupedByDate, interval, ...props} = {}) { +export default function XAxis({isGroupedByDate, interval, utc, ...props} = {}) { const axisLabelFormatter = value => { if (isGroupedByDate) { const format = interval === 'hour' ? 'LT' : 'MMM Do'; - return moment - .utc(value) - .local() - .format(format); + return getFormattedDate(value, format, {local: !utc}); } else if (props.truncate) { return truncationFormatter(value, props.truncate); } else { diff --git a/src/sentry/static/sentry/app/constants/index.jsx b/src/sentry/static/sentry/app/constants/index.jsx index d51d30e797df64..35009a8daf3250 100644 --- a/src/sentry/static/sentry/app/constants/index.jsx +++ b/src/sentry/static/sentry/app/constants/index.jsx @@ -63,6 +63,8 @@ export const MENU_CLOSE_DELAY = 200; export const DEFAULT_STATS_PERIOD = '14d'; +export const DEFAULT_USE_UTC = true; + export const DEFAULT_RELATIVE_PERIODS = { '24h': t('Last 24 hours'), '7d': t('Last 7 days')," 58294e415ce9b7457e4eff27b048fa8615a1f4c8,2023-09-21 05:10:15,Evan Purkhiser,ref(crons): Remove temp dual read logic in consumer (#56531),False,Remove temp dual read logic in consumer (#56531),ref,"diff --git a/src/sentry/monitors/consumers/monitor_consumer.py b/src/sentry/monitors/consumers/monitor_consumer.py index b7babd40377b9c..150a8e52565689 100644 --- a/src/sentry/monitors/consumers/monitor_consumer.py +++ b/src/sentry/monitors/consumers/monitor_consumer.py @@ -68,7 +68,6 @@ def _ensure_monitor_with_config( project: Project, monitor_slug: str, - monitor_slug_from_param: str, config: Optional[Dict], ): try: @@ -80,21 +79,6 @@ def _ensure_monitor_with_config( except Monitor.DoesNotExist: monitor = None - # XXX(epurkhiser): Temporary dual-read logic to handle some monitors - # that were created before we correctly slugified slugs on upsert in - # this consumer. - # - # Once all slugs are correctly slugified we can remove this. - if not monitor: - try: - monitor = Monitor.objects.get( - slug=monitor_slug_from_param, - project_id=project.id, - organization_id=project.organization_id, - ) - except Monitor.DoesNotExist: - pass - if not config: return monitor @@ -391,7 +375,6 @@ def update_existing_check_in( monitor = _ensure_monitor_with_config( project, monitor_slug, - params[""monitor_slug""], monitor_config, ) except MonitorLimitsExceeded: diff --git a/tests/sentry/monitors/test_monitor_consumer.py b/tests/sentry/monitors/test_monitor_consumer.py index e62eb42dc39821..51bd3d10e44d6d 100644 --- a/tests/sentry/monitors/test_monitor_consumer.py +++ b/tests/sentry/monitors/test_monitor_consumer.py @@ -480,18 +480,6 @@ def test_monitor_upsert_invalid_slug(self): monitor = Monitor.objects.get(slug=""someslugwith-weirdstuff"") assert monitor is not None - def test_monitor_upsert_temp_dual_read_invalid_slug(self): - monitor = self._create_monitor(slug=""my/monitor/invalid-slug"") - - self.send_checkin( - ""my/monitor/invalid-slug"", - monitor_config={""schedule"": {""type"": ""crontab"", ""value"": ""0 * * * *""}}, - ) - - checkin = MonitorCheckIn.objects.get(guid=self.guid) - assert checkin.status == CheckInStatus.OK - assert checkin.monitor_id == monitor.id - def test_monitor_invalid_config(self): # 6 value schedule self.send_checkin(" 53cbc7a71367d049dde86e0f6c943e871d954ffb,2024-03-27 21:49:17,Tony Xiao,chore(perf): Use p95 for trends widgets on perf landing (#67785),False,Use p95 for trends widgets on perf landing (#67785),chore,"diff --git a/static/app/views/performance/landing/widgets/components/widgetContainer.spec.tsx b/static/app/views/performance/landing/widgets/components/widgetContainer.spec.tsx index ad806e2eeb5406..7c720fd81944d9 100644 --- a/static/app/views/performance/landing/widgets/components/widgetContainer.spec.tsx +++ b/static/app/views/performance/landing/widgets/components/widgetContainer.spec.tsx @@ -253,7 +253,7 @@ describe('Performance > Widgets > WidgetContainer', function () { 'transaction.op:pageload tpm():>0.01 count_percentage():>0.25 count_percentage():<4 trend_percentage():>0% confidence():>6', sort: 'trend_percentage()', statsPeriod: '14d', - trendFunction: 'p50(transaction.duration)', + trendFunction: 'p95(transaction.duration)', trendType: 'improved', }), }) @@ -845,7 +845,7 @@ describe('Performance > Widgets > WidgetContainer', function () { 'transaction.op:pageload tpm():>0.01 count_percentage():>0.25 count_percentage():<4 trend_percentage():>0% confidence():>6', sort: 'trend_percentage()', statsPeriod: '7d', - trendFunction: 'p50(transaction.duration)', + trendFunction: 'p95(transaction.duration)', trendType: 'improved', }), }) @@ -1036,7 +1036,7 @@ describe('Performance > Widgets > WidgetContainer', function () { 'transaction.op:pageload tpm():>0.01 count_percentage():>0.25 count_percentage():<4 trend_percentage():>0% confidence():>6', sort: '-trend_percentage()', statsPeriod: '7d', - trendFunction: 'p50(transaction.duration)', + trendFunction: 'p95(transaction.duration)', trendType: 'regression', }), }) diff --git a/static/app/views/performance/landing/widgets/widgetDefinitions.tsx b/static/app/views/performance/landing/widgets/widgetDefinitions.tsx index e16d4f300f14aa..00153e5d6af291 100644 --- a/static/app/views/performance/landing/widgets/widgetDefinitions.tsx +++ b/static/app/views/performance/landing/widgets/widgetDefinitions.tsx @@ -357,7 +357,7 @@ export const WIDGET_DEFINITIONS: ({ chartColor: WIDGET_PALETTE[0], }, [PerformanceWidgetSetting.MOST_IMPROVED]: { - title: t('Most Improved'), + title: t('Most Improved (P95)'), titleTooltip: t( 'This compares the baseline (%s) of the past with the present.', 'improved' @@ -366,7 +366,7 @@ export const WIDGET_DEFINITIONS: ({ dataType: GenericPerformanceWidgetDataType.TRENDS, }, [PerformanceWidgetSetting.MOST_REGRESSED]: { - title: t('Most Regressed'), + title: t('Most Regressed (P95)'), titleTooltip: t( 'This compares the baseline (%s) of the past with the present.', 'regressed' @@ -375,7 +375,7 @@ export const WIDGET_DEFINITIONS: ({ dataType: GenericPerformanceWidgetDataType.TRENDS, }, [PerformanceWidgetSetting.MOST_CHANGED]: { - title: t('Most Changed'), + title: t('Most Changed (P95)'), titleTooltip: t( 'This compares the baseline (%s) of the past with the present.', 'changed' diff --git a/static/app/views/performance/landing/widgets/widgets/trendsWidget.tsx b/static/app/views/performance/landing/widgets/widgets/trendsWidget.tsx index 8b7846bc9baa13..5fcc5e0720f400 100644 --- a/static/app/views/performance/landing/widgets/widgets/trendsWidget.tsx +++ b/static/app/views/performance/landing/widgets/widgets/trendsWidget.tsx @@ -69,7 +69,7 @@ export function TrendsWidget(props: PerformanceWidgetProps) { ? TrendChangeType.IMPROVED : TrendChangeType.REGRESSION; const derivedTrendChangeType = withBreakpoint ? TrendChangeType.ANY : trendChangeType; - const trendFunctionField = TrendFunctionField.P50; // Setting p50 to match trends page + const trendFunctionField = TrendFunctionField.P95; const [selectedListIndex, setSelectListIndex] = useState(0); diff --git a/static/app/views/performance/trends/index.spec.tsx b/static/app/views/performance/trends/index.spec.tsx index 0c18317db3081c..383545685caa37 100644 --- a/static/app/views/performance/trends/index.spec.tsx +++ b/static/app/views/performance/trends/index.spec.tsx @@ -345,7 +345,7 @@ describe('Performance > Trends', function () { expect(summaryLink.closest('a')).toHaveAttribute( 'href', - '/organizations/org-slug/performance/summary/?display=trend&project=1&query=tpm%28%29%3A%3E0.01%20transaction.duration%3A%3E0%20transaction.duration%3A%3C15min%20count_percentage%28%29%3A%3E0.25%20count_percentage%28%29%3A%3C4%20trend_percentage%28%29%3A%3E0%25%20confidence%28%29%3A%3E6&referrer=performance-transaction-summary&statsPeriod=14d&transaction=%2Forganizations%2F%3AorgId%2Fperformance%2F&trendFunction=p50&unselectedSeries=p100%28%29&unselectedSeries=avg%28%29' + '/organizations/org-slug/performance/summary/?display=trend&project=1&query=tpm%28%29%3A%3E0.01%20transaction.duration%3A%3E0%20transaction.duration%3A%3C15min%20count_percentage%28%29%3A%3E0.25%20count_percentage%28%29%3A%3C4%20trend_percentage%28%29%3A%3E0%25%20confidence%28%29%3A%3E6&referrer=performance-transaction-summary&statsPeriod=14d&transaction=%2Forganizations%2F%3AorgId%2Fperformance%2F&trendFunction=p95&unselectedSeries=p100%28%29&unselectedSeries=avg%28%29' ); }); @@ -543,7 +543,7 @@ describe('Performance > Trends', function () { ); const trendDropdownButton = await getTrendDropdown(); - expect(trendDropdownButton).toHaveTextContent('Percentilep50'); + expect(trendDropdownButton).toHaveTextContent('Percentilep95'); }); it('sets duration as a default trend parameter for backend project if query does not specify trend parameter', async function () { diff --git a/static/app/views/performance/trends/utils.tsx b/static/app/views/performance/trends/utils.tsx index a6cbe914788e60..bff7381e3e8858 100644 --- a/static/app/views/performance/trends/utils.tsx +++ b/static/app/views/performance/trends/utils.tsx @@ -35,16 +35,10 @@ export const DEFAULT_MAX_DURATION = '15min'; export const TRENDS_FUNCTIONS: TrendFunction[] = [ { - label: 'p50', - field: TrendFunctionField.P50, - alias: 'percentile_range', - legendLabel: 'p50', - }, - { - label: 'p75', - field: TrendFunctionField.P75, + label: 'p99', + field: TrendFunctionField.P99, alias: 'percentile_range', - legendLabel: 'p75', + legendLabel: 'p99', }, { label: 'p95', @@ -53,10 +47,16 @@ export const TRENDS_FUNCTIONS: TrendFunction[] = [ legendLabel: 'p95', }, { - label: 'p99', - field: TrendFunctionField.P99, + label: 'p75', + field: TrendFunctionField.P75, alias: 'percentile_range', - legendLabel: 'p99', + legendLabel: 'p75', + }, + { + label: 'p50', + field: TrendFunctionField.P50, + alias: 'percentile_range', + legendLabel: 'p50', }, { label: 'average', @@ -156,7 +156,7 @@ export function getCurrentTrendFunction( const trendFunctionField = _trendFunctionField ?? decodeScalar(location?.query?.trendFunction); const trendFunction = TRENDS_FUNCTIONS.find(({field}) => field === trendFunctionField); - return trendFunction || TRENDS_FUNCTIONS[0]; + return trendFunction || TRENDS_FUNCTIONS[1]; } function getDefaultTrendParameter(" 8f6d6b31171d5bdd8d69cd19820d363556597069,2021-04-27 03:51:00,Dan Fuller,"feat(issue_search): Backfill saved searches to convert `me_or_none` to `[me, none]` (#25288)",False,"Backfill saved searches to convert `me_or_none` to `[me, none]` (#25288)",feat,"diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt index dd25c3b986a61c..e14f56874e65cb 100644 --- a/migrations_lockfile.txt +++ b/migrations_lockfile.txt @@ -7,5 +7,5 @@ will then be regenerated, and you should be able to merge without conflicts. jira_ac: 0001_initial nodestore: 0002_nodestore_no_dictfield -sentry: 0186_add_externalactor +sentry: 0187_backfill_me_or_none social_auth: 0001_initial diff --git a/src/sentry/migrations/0187_backfill_me_or_none.py b/src/sentry/migrations/0187_backfill_me_or_none.py new file mode 100644 index 00000000000000..ba65fe53ba0217 --- /dev/null +++ b/src/sentry/migrations/0187_backfill_me_or_none.py @@ -0,0 +1,41 @@ +# Generated by Django 1.11.29 on 2021-04-26 20:15 + +from django.db import migrations + +from sentry.utils.query import RangeQuerySetWrapperWithProgressBar + + +def backfill_me_or_none(apps, schema_editor): + SavedSearch = apps.get_model(""sentry"", ""SavedSearch"") + for saved_search in RangeQuerySetWrapperWithProgressBar(SavedSearch.objects.all()): + if "":me_or_none"" in saved_search.query: + saved_search.query = saved_search.query.replace("":me_or_none"", "":[me, none]"") + saved_search.save() + + +class Migration(migrations.Migration): + # This flag is used to mark that a migration shouldn't be automatically run in + # production. We set this to True for operations that we think are risky and want + # someone from ops to run manually and monitor. + # General advice is that if in doubt, mark your migration as `is_dangerous`. + # Some things you should always mark as dangerous: + # - Large data migrations. Typically we want these to be run manually by ops so that + # they can be monitored. Since data migrations will now hold a transaction open + # this is even more important. + # - Adding columns to highly active tables, even ones that are NULL. + is_dangerous = True + + # This flag is used to decide whether to run this migration in a transaction or not. + # By default we prefer to run in a transaction, but for migrations where you want + # to `CREATE INDEX CONCURRENTLY` this needs to be set to False. Typically you'll + # want to create an index concurrently when adding one to an existing table. + # You'll also usually want to set this to `False` if you're writing a data + # migration, since we don't want the entire migration to run in one long-running + # transaction. + atomic = False + + dependencies = [ + (""sentry"", ""0186_add_externalactor""), + ] + + operations = [migrations.RunPython(backfill_me_or_none, reverse_code=migrations.RunPython.noop)]" aaa9773454952fc152bb816e817374c179a89a11,2018-10-12 04:33:10,Lyn Nagara,fix(discover): Display error message from API if one is received (#10096),False,Display error message from API if one is received (#10096),fix,"diff --git a/src/sentry/static/sentry/app/views/organizationDiscover/result/index.jsx b/src/sentry/static/sentry/app/views/organizationDiscover/result/index.jsx index 4a8e79186af822..ded80c879e06e7 100644 --- a/src/sentry/static/sentry/app/views/organizationDiscover/result/index.jsx +++ b/src/sentry/static/sentry/app/views/organizationDiscover/result/index.jsx @@ -94,8 +94,9 @@ export default class Result extends React.Component { pathname: `/organizations/${organization.slug}/discover/saved/${savedQuery.id}/`, }); }) - .catch(() => { - addErrorMessage(t('Could not save query')); + .catch(err => { + const message = (err && err.detail) || t('Could not save query'); + addErrorMessage(message); }); };" 9ccffaf04fb6f428a66a29f6db51d555b24d2626,2024-02-02 13:49:28,anthony sottile,ref: remove sentry.db.postgres.operations (#64368),False,remove sentry.db.postgres.operations (#64368),ref,"diff --git a/src/sentry/db/postgres/base.py b/src/sentry/db/postgres/base.py index 2548708802765c..7699351b7b34c5 100644 --- a/src/sentry/db/postgres/base.py +++ b/src/sentry/db/postgres/base.py @@ -3,6 +3,7 @@ # Some of these imports are unused, but they are inherited from other engines # and should be available as part of the backend ``base.py`` namespace. from django.db.backends.postgresql.base import DatabaseWrapper as DjangoDatabaseWrapper +from django.db.backends.postgresql.operations import DatabaseOperations from sentry.utils.strings import strip_lone_surrogates @@ -13,12 +14,10 @@ capture_transaction_exceptions, more_better_error_messages, ) -from .operations import DatabaseOperations +from .schema import DatabaseSchemaEditorProxy __all__ = (""DatabaseWrapper"",) -from .schema import DatabaseSchemaEditorProxy - def remove_null(value): # In psycopg2 2.7+, behavior was introduced where a diff --git a/src/sentry/db/postgres/operations.py b/src/sentry/db/postgres/operations.py deleted file mode 100644 index c63099852e1161..00000000000000 --- a/src/sentry/db/postgres/operations.py +++ /dev/null @@ -1,7 +0,0 @@ -from django.db.backends.postgresql.operations import DatabaseOperations as DjangoDatabaseOperations - - -class DatabaseOperations(DjangoDatabaseOperations): - # Remove HOST() lookups for GenericIPAddressField - def field_cast_sql(self, db_type, internal_type): - return ""%s""" b38f59d9f6d9eedd7ce0606805df7c072addb000,2022-11-08 07:02:32,Mike Ihbe,ref(hybrid-cloud): Add user services. Start tagging some model tests as stable (#40614),False,Add user services. Start tagging some model tests as stable (#40614),ref,"diff --git a/.vscode/settings.json b/.vscode/settings.json index 300c96969dcb53..260d436796d33a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -69,7 +69,7 @@ ""python.linting.flake8Enabled"": true, // test discovery is sluggish and the UI around running // tests is often in your way and misclicked - ""python.testing.pytestEnabled"": false, + ""python.testing.pytestEnabled"": true, ""python.testing.unittestEnabled"": false, ""python.testing.nosetestsEnabled"": false, ""editor.tabSize"": 4, @@ -79,5 +79,8 @@ ""python.linting.pycodestylePath"": ""${workspaceFolder}/.venv/bin/pep8"", ""python.testing.pytestPath"": ""${workspaceFolder}/.venv/bin/pytest"", ""python.formatting.blackPath"": ""${workspaceFolder}/.venv/bin/black"", - ""python.formatting.provider"": ""black"" + ""python.formatting.provider"": ""black"", + ""python.testing.pytestArgs"": [ + ""tests"" + ] } diff --git a/src/sentry/api/fields/actor.py b/src/sentry/api/fields/actor.py index c294fa1b073467..3530d80b105b0c 100644 --- a/src/sentry/api/fields/actor.py +++ b/src/sentry/api/fields/actor.py @@ -1,7 +1,14 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + from rest_framework import serializers from sentry.models import ActorTuple, OrganizationMember, Team, User +if TYPE_CHECKING: + from sentry.services.hybrid_cloud.user import APIUser + class ActorField(serializers.Field): def to_representation(self, value): @@ -18,7 +25,7 @@ def to_internal_value(self, data): ""Could not parse actor. Format should be `type:id` where type is `team` or `user`."" ) try: - obj = actor.resolve() + obj: APIUser | Team = actor.resolve() except (Team.DoesNotExist, User.DoesNotExist): raise serializers.ValidationError(f""{actor.type.__name__} does not exist"") @@ -27,7 +34,7 @@ def to_internal_value(self, data): raise serializers.ValidationError(""Team is not a member of this organization"") elif actor.type == User: if not OrganizationMember.objects.filter( - organization=self.context[""organization""], user=obj + organization=self.context[""organization""], user_id=obj.id ).exists(): raise serializers.ValidationError(""User is not a member of this organization"") return actor diff --git a/src/sentry/api/helpers/group_index/update.py b/src/sentry/api/helpers/group_index/update.py index 718e1e23b46a7e..d0a9f122e00b74 100644 --- a/src/sentry/api/helpers/group_index/update.py +++ b/src/sentry/api/helpers/group_index/update.py @@ -37,6 +37,7 @@ GroupTombstone, Project, Release, + Team, User, UserOption, follows_semver_versioning_scheme, @@ -47,6 +48,7 @@ from sentry.models.grouphistory import record_group_history_from_activity_type from sentry.models.groupinbox import GroupInboxRemoveAction, add_group_to_inbox from sentry.notifications.types import SUBSCRIPTION_REASON_MAP, GroupSubscriptionReason +from sentry.services.hybrid_cloud.user import APIUser from sentry.signals import ( issue_ignored, issue_mark_reviewed, @@ -690,7 +692,7 @@ def update_groups( ) if assigned_actor: for group in group_list: - resolved_actor = assigned_actor.resolve() + resolved_actor: APIUser | Team = assigned_actor.resolve() assignment = GroupAssignee.objects.assign( group, resolved_actor, acting_user, extra=extra diff --git a/src/sentry/api/serializers/base.py b/src/sentry/api/serializers/base.py index a2148202429f2a..adc05cb78ad097 100644 --- a/src/sentry/api/serializers/base.py +++ b/src/sentry/api/serializers/base.py @@ -68,7 +68,6 @@ def serialize( pass else: return objects - with sentry_sdk.start_span(op=""serialize"", description=type(serializer).__name__) as span: span.set_data(""Object Count"", len(objects)) diff --git a/src/sentry/api/serializers/models/actor.py b/src/sentry/api/serializers/models/actor.py index 0375ff2eb5a054..a302c84c4a83c7 100644 --- a/src/sentry/api/serializers/models/actor.py +++ b/src/sentry/api/serializers/models/actor.py @@ -1,14 +1,13 @@ from sentry.api.serializers import Serializer -from sentry.models import Team, User class ActorSerializer(Serializer): def serialize(self, obj, attrs, user, **kwargs): - if isinstance(obj, User): + if obj.class_name() == ""User"": actor_type = ""user"" name = obj.get_display_name() context = {""email"": obj.email} - elif isinstance(obj, Team): + elif obj.class_name() == ""Team"": actor_type = ""team"" name = obj.slug context = {} diff --git a/src/sentry/api/serializers/models/group.py b/src/sentry/api/serializers/models/group.py index be93ae3d26382f..cb94afd8e73a52 100644 --- a/src/sentry/api/serializers/models/group.py +++ b/src/sentry/api/serializers/models/group.py @@ -17,6 +17,7 @@ Sequence, Tuple, TypedDict, + Union, ) import pytz @@ -52,6 +53,7 @@ Integration, NotificationSetting, SentryAppInstallationToken, + Team, User, ) from sentry.notifications.helpers import ( @@ -179,6 +181,20 @@ def __init__( self.collapse = collapse self.expand = expand + def _serialize_assigness( + self, actor_dict: Mapping[int, ActorTuple] + ) -> Mapping[int, Union[Team, Any]]: + actors_by_type: MutableMapping[Any, List[ActorTuple]] = defaultdict(list) + for actor in actor_dict.values(): + actors_by_type[actor.type].append(actor) + + resolved_actors = {} + for t, actors in actors_by_type.items(): + serializable = ActorTuple.resolve_many(actors) + resolved_actors[t] = {actor.id: actor for actor in serializable} + + return {key: resolved_actors[value.type][value.id] for key, value in actor_dict.items()} + def get_attrs( self, item_list: Sequence[Group], user: Any, **kwargs: Any ) -> MutableMapping[Group, MutableMapping[str, Any]]: @@ -205,11 +221,11 @@ def get_attrs( seen_groups = {} subscriptions = defaultdict(lambda: (False, False, None)) - assignees = { + assignees: Mapping[int, ActorTuple] = { a.group_id: a.assigned_actor() for a in GroupAssignee.objects.filter(group__in=item_list) } - resolved_assignees = ActorTuple.resolve_dict(assignees) + resolved_assignees = self._serialize_assigness(assignees) ignore_items = {g.group_id: g for g in GroupSnooze.objects.filter(group__in=item_list)} diff --git a/src/sentry/api/serializers/rest_framework/mentions.py b/src/sentry/api/serializers/rest_framework/mentions.py index 7f901d0c699221..39e01667b2042f 100644 --- a/src/sentry/api/serializers/rest_framework/mentions.py +++ b/src/sentry/api/serializers/rest_framework/mentions.py @@ -1,6 +1,11 @@ +from __future__ import annotations + +from typing import Sequence + from rest_framework import serializers from sentry.models import ActorTuple, Team, User +from sentry.services.hybrid_cloud.user import APIUser def extract_user_ids_from_mentions(organization_id, mentions): @@ -11,7 +16,7 @@ def extract_user_ids_from_mentions(organization_id, mentions): is all user ids from explicitly mentioned teams, excluding any already mentioned users. """""" - actors = ActorTuple.resolve_many(mentions) + actors: Sequence[APIUser | Team] = ActorTuple.resolve_many(mentions) actor_mentions = separate_resolved_actors(actors) mentioned_team_users = list( @@ -33,8 +38,8 @@ def separate_actors(actors): return {""users"": users, ""teams"": teams} -def separate_resolved_actors(actors): - users = [actor for actor in actors if isinstance(actor, User)] +def separate_resolved_actors(actors: Sequence[APIUser | Team]): + users = [actor for actor in actors if actor.class_name() == ""User""] teams = [actor for actor in actors if isinstance(actor, Team)] return {""users"": users, ""teams"": teams} diff --git a/src/sentry/api/validators/project_codeowners.py b/src/sentry/api/validators/project_codeowners.py index eed450820faf03..97461d06bcd395 100644 --- a/src/sentry/api/validators/project_codeowners.py +++ b/src/sentry/api/validators/project_codeowners.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, Mapping, Sequence +from typing import TYPE_CHECKING, Any, Mapping, Sequence from django.db.models import Subquery @@ -15,6 +15,9 @@ from sentry.ownership.grammar import parse_code_owners from sentry.types.integrations import ExternalProviders +if TYPE_CHECKING: + from sentry.services.hybrid_cloud.user import APIUser + def validate_association( raw_items: Sequence[UserEmail | ExternalActor], @@ -58,7 +61,7 @@ def validate_codeowners_associations( for external_actor in external_actors: type = actor_type_to_string(external_actor.actor.type) if type == ""user"": - user = external_actor.actor.resolve() + user: APIUser = external_actor.actor.resolve() organization_members_ids = OrganizationMember.objects.filter( user_id=user.id, organization_id=project.organization_id ).values_list(""id"", flat=True) diff --git a/src/sentry/digests/utils.py b/src/sentry/digests/utils.py index 178b638d5d5aa2..eb1df2aa95cc77 100644 --- a/src/sentry/digests/utils.py +++ b/src/sentry/digests/utils.py @@ -8,9 +8,10 @@ from sentry.digests import Digest, Record from sentry.eventstore.models import Event -from sentry.models import Group, Project, ProjectOwnership, Rule, Team, User +from sentry.models import Group, Project, ProjectOwnership, Rule, Team from sentry.notifications.types import ActionTargetType from sentry.notifications.utils.participants import get_send_to +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import ExternalProviders @@ -63,11 +64,14 @@ def get_digest_as_context(digest: Digest) -> Mapping[str, Any]: def get_events_by_participant( - participants_by_provider_by_event: Mapping[Event, Mapping[ExternalProviders, set[Team | User]]] -) -> Mapping[Team | User, set[Event]]: + participants_by_provider_by_event: Mapping[ + Event, Mapping[ExternalProviders, set[Team | APIUser]] + ] +) -> Mapping[Team | APIUser, set[Event]]: """"""Invert a mapping of events to participants to a mapping of participants to events."""""" output = defaultdict(set) for event, participants_by_provider in participants_by_provider_by_event.items(): + participants: set[Team | APIUser] for participants in participants_by_provider.values(): for participant in participants: output[participant].add(event) @@ -76,7 +80,9 @@ def get_events_by_participant( def get_personalized_digests( digest: Digest, - participants_by_provider_by_event: Mapping[Event, Mapping[ExternalProviders, set[Team | User]]], + participants_by_provider_by_event: Mapping[ + Event, Mapping[ExternalProviders, set[Team | APIUser]] + ], ) -> Mapping[int, Digest]: events_by_participant = get_events_by_participant(participants_by_provider_by_event) return { @@ -115,7 +121,7 @@ def get_participants_by_event( project: Project, target_type: ActionTargetType = ActionTargetType.ISSUE_OWNERS, target_identifier: int | None = None, -) -> Mapping[Event, Mapping[ExternalProviders, set[Team | User]]]: +) -> Mapping[Event, Mapping[ExternalProviders, set[Team | APIUser]]]: """""" This is probably the slowest part in sending digests because we do a lot of DB calls while we iterate over every event. It would be great if we could diff --git a/src/sentry/integrations/message_builder.py b/src/sentry/integrations/message_builder.py index b433f8b1480ec5..990b8d97c98c06 100644 --- a/src/sentry/integrations/message_builder.py +++ b/src/sentry/integrations/message_builder.py @@ -5,9 +5,10 @@ from sentry.eventstore.models import GroupEvent from sentry.integrations.slack.message_builder import SLACK_URL_FORMAT -from sentry.models import Group, Project, Rule, Team, User +from sentry.models import Group, Project, Rule, Team from sentry.notifications.notifications.base import BaseNotification from sentry.notifications.utils import get_matched_problem, get_span_evidence_value_problem +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders from sentry.types.issues import GROUP_TYPE_TO_TEXT, GroupCategory from sentry.utils.http import absolute_uri @@ -17,13 +18,13 @@ class AbstractMessageBuilder(ABC): pass -def format_actor_options(actors: Sequence[Team | User]) -> Sequence[Mapping[str, str]]: +def format_actor_options(actors: Sequence[Team | APIUser]) -> Sequence[Mapping[str, str]]: sort_func: Callable[[Mapping[str, str]], Any] = lambda actor: actor[""text""] return sorted((format_actor_option(actor) for actor in actors), key=sort_func) -def format_actor_option(actor: Team | User) -> Mapping[str, str]: - if isinstance(actor, User): +def format_actor_option(actor: Team | APIUser) -> Mapping[str, str]: + if isinstance(actor, APIUser): return {""text"": actor.get_display_name(), ""value"": f""user:{actor.id}""} if isinstance(actor, Team): return {""text"": f""#{actor.slug}"", ""value"": f""team:{actor.id}""} diff --git a/src/sentry/integrations/msteams/card_builder/issues.py b/src/sentry/integrations/msteams/card_builder/issues.py index 781057702ba1e4..aa2477e9c78260 100644 --- a/src/sentry/integrations/msteams/card_builder/issues.py +++ b/src/sentry/integrations/msteams/card_builder/issues.py @@ -207,7 +207,7 @@ def build_group_actions(self) -> ContainerBlock: teams_choices = self.get_teams_choices() assign_action = self.create_issue_action_block( - toggled=self.group.get_assignee(), + toggled=self.group.get_assignee() is not None, action=ACTION_TYPE.ASSIGN, action_title=IssueConstants.ASSIGN, reverse_action=ACTION_TYPE.UNASSIGN, diff --git a/src/sentry/integrations/notifications.py b/src/sentry/integrations/notifications.py index 4522e27398a40c..494a3645d34386 100644 --- a/src/sentry/integrations/notifications.py +++ b/src/sentry/integrations/notifications.py @@ -8,12 +8,13 @@ from sentry.constants import ObjectStatus from sentry.models import ExternalActor, Identity, Integration, Organization, Team, User from sentry.notifications.notifications.base import BaseNotification +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders def get_context( notification: BaseNotification, - recipient: Team | User, + recipient: Team | APIUser, shared_context: Mapping[str, Any], extra_context: Mapping[str, Any], ) -> Mapping[str, Any]: @@ -91,7 +92,7 @@ def get_integrations_by_channel_by_recipient( for recipient in recipients: channels_to_integrations = ( get_channel_and_integration_by_user(recipient, organization, provider) - if isinstance(recipient, User) + if recipient.class_name() == ""User"" else get_channel_and_integration_by_team(recipient, organization, provider) ) output[recipient] = channels_to_integrations diff --git a/src/sentry/integrations/slack/message_builder/issues.py b/src/sentry/integrations/slack/message_builder/issues.py index b56c0d76c13f95..9f1d94dab8b71f 100644 --- a/src/sentry/integrations/slack/message_builder/issues.py +++ b/src/sentry/integrations/slack/message_builder/issues.py @@ -33,6 +33,7 @@ from sentry.notifications.notifications.base import BaseNotification, ProjectNotification from sentry.notifications.notifications.rules import AlertRuleNotification from sentry.notifications.utils.actions import MessageAction +from sentry.services.hybrid_cloud.user import user_service from sentry.types.integrations import ExternalProviders from sentry.types.issues import GroupCategory from sentry.utils import json @@ -54,7 +55,9 @@ def build_assigned_text(identity: Identity, assignee: str) -> str | None: elif actor.type == User: try: assignee_ident = Identity.objects.get( - user=assigned_actor, idp__type=""slack"", idp__external_id=identity.idp.external_id + user_id=assigned_actor.id, + idp__type=""slack"", + idp__external_id=identity.idp.external_id, ) assignee_text = f""<@{assignee_ident.external_id}>"" except Identity.DoesNotExist: @@ -106,7 +109,7 @@ def build_tag_fields( def get_option_groups(group: Group) -> Sequence[Mapping[str, Any]]: - members = User.objects.get_from_group(group).distinct() + members = user_service.get_from_group(group) teams = group.project.teams.all() option_groups = [] diff --git a/src/sentry/integrations/utils/sync.py b/src/sentry/integrations/utils/sync.py index f3ebd7f61a66b4..aa7f049130e351 100644 --- a/src/sentry/integrations/utils/sync.py +++ b/src/sentry/integrations/utils/sync.py @@ -4,7 +4,8 @@ from typing import TYPE_CHECKING, Mapping, Sequence from sentry import features -from sentry.models import Group, GroupAssignee, Project, User +from sentry.models import Group, GroupAssignee, Project +from sentry.services.hybrid_cloud.user import user_service from sentry.tasks.integrations import sync_assignee_outbound if TYPE_CHECKING: @@ -73,7 +74,7 @@ def sync_group_assignee_inbound( GroupAssignee.objects.deassign(group) return affected_groups - users = User.objects.get_for_email(email, case_sensitive=False) + users = user_service.get_many_by_email(email) users_by_id = {user.id: user for user in users} projects_by_user = Project.objects.get_by_users(users) diff --git a/src/sentry/mail/notifications.py b/src/sentry/mail/notifications.py index e1413fa7459fa9..0668f0dfdb39ac 100644 --- a/src/sentry/mail/notifications.py +++ b/src/sentry/mail/notifications.py @@ -1,13 +1,13 @@ from __future__ import annotations import logging -from typing import Any, Iterable, Mapping, MutableMapping +from typing import TYPE_CHECKING, Any, Iterable, Mapping, MutableMapping import sentry_sdk from django.utils.encoding import force_text from sentry import options -from sentry.models import Project, ProjectOption, Team, User +from sentry.models import Project, ProjectOption, Team from sentry.notifications.notifications.active_release import ActiveReleaseIssueNotification from sentry.notifications.notifications.base import BaseNotification, ProjectNotification from sentry.notifications.notify import register_notification_provider @@ -18,6 +18,9 @@ logger = logging.getLogger(__name__) +if TYPE_CHECKING: + from sentry.services.hybrid_cloud.user import APIUser + def get_headers(notification: BaseNotification) -> Mapping[str, Any]: headers = {""X-SMTPAPI"": json.dumps({""category"": notification.metrics_key})} @@ -72,14 +75,14 @@ def get_unsubscribe_link( return signed_link -def log_message(notification: BaseNotification, recipient: Team | User) -> None: +def log_message(notification: BaseNotification, recipient: Team | APIUser) -> None: extra = notification.get_log_params(recipient) logger.info(""mail.adapter.notify.mail_user"", extra={**extra}) def get_context( notification: BaseNotification, - recipient: Team | User, + recipient: Team | APIUser, shared_context: Mapping[str, Any], extra_context: Mapping[str, Any], ) -> Mapping[str, Any]: @@ -95,7 +98,7 @@ def get_context( # TODO(mgaeta): The unsubscribe system relies on `user_id` so it doesn't # work with Teams. We should add the `actor_id` to the signed link. unsubscribe_key = notification.get_unsubscribe_key() - if isinstance(recipient, User) and unsubscribe_key: + if recipient.class_name() == ""User"" and unsubscribe_key: key, resource_id, referrer = unsubscribe_key context.update( {""unsubscribe_link"": get_unsubscribe_link(recipient.id, resource_id, key, referrer)} @@ -107,7 +110,7 @@ def get_context( @register_notification_provider(ExternalProviders.EMAIL) def send_notification_as_email( notification: BaseNotification, - recipients: Iterable[Team | User], + recipients: Iterable[Team | APIUser], shared_context: Mapping[str, Any], extra_context_by_actor_id: Mapping[int, Mapping[str, Any]] | None, ) -> None: @@ -137,7 +140,7 @@ def send_notification_as_email( def get_builder_args( notification: BaseNotification, - recipient: User, + recipient: APIUser, shared_context: Mapping[str, Any] | None = None, extra_context_by_actor_id: Mapping[int, Mapping[str, Any]] | None = None, ) -> Mapping[str, Any]: diff --git a/src/sentry/models/activity.py b/src/sentry/models/activity.py index 652051da31bea4..76c89e73597834 100644 --- a/src/sentry/models/activity.py +++ b/src/sentry/models/activity.py @@ -22,6 +22,7 @@ if TYPE_CHECKING: from sentry.models import Group, User + from sentry.services.hybrid_cloud.user import APIUser class ActivityManager(BaseManager): @@ -59,17 +60,19 @@ def create_group_activity( self, group: Group, type: ActivityType, - user: Optional[User] = None, + user: Optional[User | APIUser] = None, data: Optional[Mapping[str, Any]] = None, send_notification: bool = True, ) -> Activity: - activity = self.create( - project_id=group.project_id, - group=group, - type=type.value, - user=user, - data=data, - ) + activity_args = { + ""project_id"": group.project_id, + ""group"": group, + ""type"": type.value, + ""data"": data, + } + if user is not None: + activity_args[""user_id""] = user.id + activity = self.create(**activity_args) if send_notification: activity.send_notification() diff --git a/src/sentry/models/actor.py b/src/sentry/models/actor.py index 004aa98711bde3..1a7f81bc6370c1 100644 --- a/src/sentry/models/actor.py +++ b/src/sentry/models/actor.py @@ -1,5 +1,5 @@ from collections import defaultdict, namedtuple -from typing import TYPE_CHECKING, Mapping, Optional, Sequence, Type, Union +from typing import TYPE_CHECKING, Optional, Sequence, Type, Union from django.db import models from django.db.models.signals import pre_save @@ -8,13 +8,13 @@ from sentry.db.models import Model, region_silo_only_model if TYPE_CHECKING: - from sentry.models import Team, User - + from sentry.models import Team + from sentry.services.hybrid_cloud.user import APIUser ACTOR_TYPES = {""team"": 0, ""user"": 1} -def actor_type_to_class(type: int) -> Type[Union[""Team"", ""User""]]: +def actor_type_to_class(type: int) -> Type[Union[""Team"", ""APIUser""]]: # type will be 0 or 1 and we want to get Team or User from sentry.models import Team, User @@ -23,6 +23,36 @@ def actor_type_to_class(type: int) -> Type[Union[""Team"", ""User""]]: return ACTOR_TYPE_TO_CLASS[type] +def fetch_actor_by_actor_id(cls, actor_id: int) -> Union[""Team"", ""APIUser""]: + from sentry.models import Team, User + from sentry.services.hybrid_cloud.user import user_service + + if cls is User: + user = user_service.get_by_actor_id(actor_id) + if user is None: + raise User.DoesNotExist() + return user + if cls is Team: + return Team.objects.get(actor_id=actor_id) + + raise ValueError(f""Cls {cls} is not a valid actor type."") + + +def fetch_actor_by_id(cls, id: int) -> Union[""Team"", ""APIUser""]: + from sentry.models import Team, User + + if cls is Team: + return Team.objects.get(id=id) + + if cls is User: + from sentry.services.hybrid_cloud.user import user_service + + user = user_service.get_user(id) + if user is None: + raise User.DoesNotExist() + return user + + def actor_type_to_string(type: int) -> Optional[str]: # type will be 0 or 1 and we want to get ""team"" or ""user"" for k, v in ACTOR_TYPES.items(): @@ -46,11 +76,11 @@ class Meta: app_label = ""sentry"" db_table = ""sentry_actor"" - def resolve(self): + def resolve(self) -> Union[""Team"", ""APIUser""]: # Returns User/Team model object - return actor_type_to_class(self.type).objects.get(actor_id=self.id) + return fetch_actor_by_actor_id(actor_type_to_class(self.type), self.id) - def get_actor_tuple(self): + def get_actor_tuple(self) -> ""ActorTuple"": # Returns ActorTuple version of the Actor model. actor_type = actor_type_to_class(self.type) return ActorTuple(self.resolve().id, actor_type) @@ -108,20 +138,23 @@ def from_actor_identifier(cls, actor_identifier: Union[int, str]) -> ""ActorTuple except IndexError: raise serializers.ValidationError(""Unable to resolve actor identifier"") - def resolve(self): - return self.type.objects.select_related(""actor"").get(id=self.id) + def resolve(self) -> Union[""Team"", ""APIUser""]: + return fetch_actor_by_id(self.type, self.id) - def resolve_to_actor(self): - return self.resolve().actor + def resolve_to_actor(self) -> Actor: + return Actor.objects.get(id=self.resolve().actor_id) @classmethod - def resolve_many(cls, actors: Sequence[""ActorTuple""]) -> Sequence[Union[""Team"", ""User""]]: + def resolve_many(cls, actors: Sequence[""ActorTuple""]) -> Sequence[Union[""Team"", ""APIUser""]]: """""" Resolve multiple actors at the same time. Returns the result in the same order as the input, minus any actors we couldn't resolve. :param actors: :return: """""" + from sentry.models import User + from sentry.services.hybrid_cloud.user import user_service + if not actors: return [] @@ -131,25 +164,15 @@ def resolve_many(cls, actors: Sequence[""ActorTuple""]) -> Sequence[Union[""Team"", results = {} for type, _actors in actors_by_type.items(): - for instance in type.objects.filter(id__in=[a.id for a in _actors]): - results[(type, instance.id)] = instance + if type == User: + for instance in user_service.get_many([a.id for a in _actors]): + results[(type, instance.id)] = instance + else: + for instance in type.objects.filter(id__in=[a.id for a in _actors]): + results[(type, instance.id)] = instance return list(filter(None, [results.get((actor.type, actor.id)) for actor in actors])) - @classmethod - def resolve_dict(cls, actor_dict: Mapping[int, ""Actor""]) -> Mapping[int, Union[""Team"", ""User""]]: - actors_by_type = defaultdict(list) - for actor in actor_dict.values(): - actors_by_type[actor.type].append(actor) - - resolved_actors = {} - for type, actors in actors_by_type.items(): - resolved_actors[type] = { - actor.id: actor for actor in type.objects.filter(id__in=[a.id for a in actors]) - } - - return {key: resolved_actors[value.type][value.id] for key, value in actor_dict.items()} - def handle_actor_pre_save(instance, **kwargs): # we want to create an actor if we don't have one diff --git a/src/sentry/models/commitauthor.py b/src/sentry/models/commitauthor.py index 722e4fcc1e5cc0..3305ccc23fe97c 100644 --- a/src/sentry/models/commitauthor.py +++ b/src/sentry/models/commitauthor.py @@ -1,7 +1,13 @@ +from typing import TYPE_CHECKING, List + from django.db import models from sentry.db.models import BoundedBigIntegerField, Model, region_silo_only_model, sane_repr from sentry.db.models.manager import BaseManager +from sentry.models.organizationmember import OrganizationMember + +if TYPE_CHECKING: + from sentry.services.hybrid_cloud.user import APIUser class CommitAuthorManager(BaseManager): @@ -32,12 +38,11 @@ class Meta: __repr__ = sane_repr(""organization_id"", ""email"", ""name"") - def find_users(self): - from sentry.models import User + def find_users(self) -> List[""APIUser""]: + from sentry.services.hybrid_cloud.user import user_service - return User.objects.filter( - emails__email__iexact=self.email, - emails__is_verified=True, - sentry_orgmember_set__organization=self.organization_id, - is_active=True, - ) + users = user_service.get_many_by_email(self.email) + group_memberships = OrganizationMember.objects.filter( + organization_id=self.organization_id, + ).values_list(""user_id"", flat=True) + return list(filter(lambda u: u.id in group_memberships, users)) diff --git a/src/sentry/models/group.py b/src/sentry/models/group.py index 2671288292ce51..7fc4b30d190992 100644 --- a/src/sentry/models/group.py +++ b/src/sentry/models/group.py @@ -41,7 +41,8 @@ from sentry.utils.strings import strip, truncatechars if TYPE_CHECKING: - from sentry.models import Integration, Organization, Team, User + from sentry.models import Integration, Organization, Team + from sentry.services.hybrid_cloud.user import APIUser logger = logging.getLogger(__name__) @@ -459,7 +460,7 @@ class Meta: __repr__ = sane_repr(""project_id"") def __str__(self): - return f""({self.times_seen}) {self.error()}"" + return f""({self.times_seen}) {self.title}"" def save(self, *args, **kwargs): if not self.last_seen: @@ -652,7 +653,7 @@ def count_users_seen(self): def calculate_score(cls, times_seen, last_seen): return math.log(float(times_seen or 1)) * 600 + float(last_seen.strftime(""%s"")) - def get_assignee(self) -> Team | User | None: + def get_assignee(self) -> Team | APIUser | None: from sentry.models import GroupAssignee try: diff --git a/src/sentry/models/groupassignee.py b/src/sentry/models/groupassignee.py index dfe389f6d9a319..5fc5fd70924eb2 100644 --- a/src/sentry/models/groupassignee.py +++ b/src/sentry/models/groupassignee.py @@ -21,30 +21,34 @@ if TYPE_CHECKING: from sentry.models import ActorTuple, Group, Team, User + from sentry.services.hybrid_cloud.user import APIUser class GroupAssigneeManager(BaseManager): def assign( self, group: Group, - assigned_to: Team | User, + assigned_to: Team | APIUser, acting_user: User | None = None, create_only: bool = False, extra: Dict[str, str] | None = None, ): from sentry import features from sentry.integrations.utils import sync_group_assignee_outbound - from sentry.models import Activity, GroupSubscription, Team, User + from sentry.models import Activity, GroupSubscription, Team GroupSubscription.objects.subscribe_actor( group=group, actor=assigned_to, reason=GroupSubscriptionReason.assigned ) - if isinstance(assigned_to, User): + assigned_to_id = assigned_to.id + if assigned_to.class_name() == ""User"": assignee_type = ""user"" + assignee_type_attr = ""user_id"" other_type = ""team"" elif isinstance(assigned_to, Team): assignee_type = ""team"" + assignee_type_attr = ""team_id"" other_type = ""user"" else: raise AssertionError(f""Invalid type to assign to: {type(assigned_to)}"") @@ -52,13 +56,17 @@ def assign( now = timezone.now() assignee, created = self.get_or_create( group=group, - defaults={""project"": group.project, assignee_type: assigned_to, ""date_added"": now}, + defaults={ + ""project"": group.project, + assignee_type_attr: assigned_to_id, + ""date_added"": now, + }, ) if not created: affected = not create_only and self.filter(group=group).exclude( - **{assignee_type: assigned_to} - ).update(**{assignee_type: assigned_to, other_type: None, ""date_added"": now}) + **{assignee_type_attr: assigned_to_id} + ).update(**{assignee_type_attr: assigned_to_id, other_type: None, ""date_added"": now}) else: affected = True issue_assigned.send_robust( diff --git a/src/sentry/models/grouphistory.py b/src/sentry/models/grouphistory.py index 8a5b45d6895db8..3a5f2ac015e2f9 100644 --- a/src/sentry/models/grouphistory.py +++ b/src/sentry/models/grouphistory.py @@ -219,7 +219,7 @@ def record_group_history( group=group, project=group.project, release=release, - actor=actor.actor if actor is not None else None, + actor_id=actor.actor_id if actor is not None else None, status=status, prev_history=prev_history, prev_history_date=prev_history.date_added if prev_history else None, diff --git a/src/sentry/models/groupsubscription.py b/src/sentry/models/groupsubscription.py index 663b4ba256e36d..83f8fd00c57730 100644 --- a/src/sentry/models/groupsubscription.py +++ b/src/sentry/models/groupsubscription.py @@ -22,13 +22,14 @@ if TYPE_CHECKING: from sentry.models import Group, Team, User + from sentry.services.hybrid_cloud.user import APIUser class GroupSubscriptionManager(BaseManager): # type: ignore def subscribe( self, group: ""Group"", - user: ""User"", + user: ""APIUser"", reason: int = GroupSubscriptionReason.unknown, ) -> bool: """""" @@ -38,7 +39,11 @@ def subscribe( try: with transaction.atomic(): self.create( - user=user, group=group, project=group.project, is_active=True, reason=reason + user_id=user.id, + group=group, + project=group.project, + is_active=True, + reason=reason, ) except IntegrityError: pass @@ -47,12 +52,13 @@ def subscribe( def subscribe_actor( self, group: ""Group"", - actor: Union[""Team"", ""User""], + actor: Union[""Team"", ""User"", ""APIUser""], reason: int = GroupSubscriptionReason.unknown, ) -> Optional[bool]: from sentry.models import Team, User + from sentry.services.hybrid_cloud.user import APIUser as APIUserClass - if isinstance(actor, User): + if isinstance(actor, APIUserClass) or isinstance(actor, User): return self.subscribe(group, actor, reason) if isinstance(actor, Team): # subscribe the members of the team @@ -105,15 +111,20 @@ def bulk_subscribe( raise e return False - def get_participants(self, group: ""Group"") -> Mapping[ExternalProviders, Mapping[""User"", int]]: + def get_participants( + self, group: ""Group"" + ) -> Mapping[ExternalProviders, Mapping[""APIUser"", int]]: """""" Identify all users who are participating with a given issue. :param group: Group object """""" - from sentry.models import NotificationSetting, User + from sentry.models import NotificationSetting + from sentry.services.hybrid_cloud.user import user_service - all_possible_users = User.objects.get_from_group(group) - active_and_disabled_subscriptions = self.filter(group=group, user__in=all_possible_users) + all_possible_users = user_service.get_from_group(group) + active_and_disabled_subscriptions = self.filter( + group=group, user_id__in=[u.id for u in all_possible_users] + ) notification_settings = NotificationSetting.objects.get_for_recipient_by_parent( NotificationSettingTypes.WORKFLOW, recipients=all_possible_users, @@ -126,7 +137,9 @@ def get_participants(self, group: ""Group"") -> Mapping[ExternalProviders, Mapping notification_settings, all_possible_users ) - result: MutableMapping[ExternalProviders, MutableMapping[""User"", int]] = defaultdict(dict) + result: MutableMapping[ExternalProviders, MutableMapping[""APIUser"", int]] = defaultdict( + dict + ) for user in all_possible_users: subscription_option = subscriptions_by_user_id.get(user.id) providers = where_should_be_participating( diff --git a/src/sentry/models/options/user_option.py b/src/sentry/models/options/user_option.py index 56c4aac2b68c5b..0184c5f540aeef 100644 --- a/src/sentry/models/options/user_option.py +++ b/src/sentry/models/options/user_option.py @@ -11,6 +11,7 @@ if TYPE_CHECKING: from sentry.models import Organization, Project, User + from sentry.services.hybrid_cloud.user import APIUser option_scope_error = ""this is not a supported use case, scope to project OR organization"" @@ -19,7 +20,7 @@ class UserOptionManager(OptionManager[""User""]): def _make_key( self, - user: User, + user: User | APIUser, project: Project | None = None, organization: Organization | None = None, ) -> str: @@ -34,7 +35,9 @@ def _make_key( key: str = super()._make_key(metakey) return key - def get_value(self, user: User, key: str, default: Value | None = None, **kwargs: Any) -> Value: + def get_value( + self, user: User | APIUser, key: str, default: Value | None = None, **kwargs: Any + ) -> Value: project = kwargs.get(""project"") organization = kwargs.get(""organization"") @@ -86,7 +89,7 @@ def set_value(self, user: User, key: str, value: Value, **kwargs: Any) -> None: def get_all_values( self, - user: User, + user: User | APIUser, project: Project | None = None, organization: Organization | None = None, force_reload: bool = False, @@ -99,7 +102,7 @@ def get_all_values( if metakey not in self._option_cache or force_reload: result = { i.key: i.value - for i in self.filter(user=user, project=project, organization=organization) + for i in self.filter(user_id=user.id, project=project, organization=organization) } self._option_cache[metakey] = result diff --git a/src/sentry/models/organization.py b/src/sentry/models/organization.py index c13ac8a8664809..fb71895587ccda 100644 --- a/src/sentry/models/organization.py +++ b/src/sentry/models/organization.py @@ -29,13 +29,15 @@ ) from sentry.db.models.utils import slugify_instance from sentry.locks import locks +from sentry.models.organizationmember import OrganizationMember from sentry.roles.manager import Role from sentry.utils.http import absolute_uri from sentry.utils.retries import TimedRetryPolicy from sentry.utils.snowflake import SnowflakeIdMixin if TYPE_CHECKING: - from sentry.models import User + from sentry.services.hybrid_cloud.user import APIUser + SENTRY_USE_SNOWFLAKE = getattr(settings, ""SENTRY_USE_SNOWFLAKE"", False) @@ -250,16 +252,15 @@ def get_audit_log_data(self): ""default_role"": self.default_role, } - def get_owners(self) -> Sequence[User]: - from sentry.models import User + def get_owners(self) -> Sequence[APIUser]: + from sentry.services.hybrid_cloud.user import user_service - return User.objects.filter( - sentry_orgmember_set__role=roles.get_top_dog().id, - sentry_orgmember_set__organization=self, - is_active=True, - ) + owner_memberships = OrganizationMember.objects.filter( + role=roles.get_top_dog().id, organization=self + ).values_list(""user_id"", flat=True) + return user_service.get_many(owner_memberships) - def get_default_owner(self): + def get_default_owner(self) -> APIUser: if not hasattr(self, ""_default_owner""): self._default_owner = self.get_owners()[0] return self._default_owner @@ -271,7 +272,10 @@ def default_owner_id(self): if there is no owner. Used for analytics primarily. """""" if not hasattr(self, ""_default_owner_id""): - self._default_owner_id = self.get_owners().values_list(""id"", flat=True).first() + owners = self.get_owners() + if len(owners) == 0: + return None + self._default_owner_id = owners[0].id return self._default_owner_id def has_single_owner(self): diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py index 3b3e020e619ea6..b99b915e438393 100644 --- a/src/sentry/models/project.py +++ b/src/sentry/models/project.py @@ -52,7 +52,9 @@ def get_by_users(self, users: Iterable[User]) -> Mapping[int, Iterable[int]]: """"""Given a list of users, return a mapping of each user to the projects they are a member of."""""" project_rows = self.filter( projectteam__team__organizationmemberteam__is_active=True, - projectteam__team__organizationmemberteam__organizationmember__user__in=users, + projectteam__team__organizationmemberteam__organizationmember__user_id__in=map( + lambda u: u.id, users + ), ).values_list(""id"", ""projectteam__team__organizationmemberteam__organizationmember__user"") projects_by_user_id = defaultdict(set) @@ -336,8 +338,9 @@ def transfer_to(self, organization): rules = Rule.objects.filter(owner_id__isnull=False, project=self) for rule in list(chain(alert_rules, rules)): actor = rule.owner + is_member = False if actor.type == ACTOR_TYPES[""user""]: - is_member = organization.member_set.filter(user=actor.resolve()).exists() + is_member = organization.member_set.filter(user_id=actor.resolve().id).exists() if actor.type == ACTOR_TYPES[""team""]: is_member = actor.resolve().organization_id == organization.id if not is_member: diff --git a/src/sentry/models/projectownership.py b/src/sentry/models/projectownership.py index d1cde04799ab22..3a5ed3049f6ceb 100644 --- a/src/sentry/models/projectownership.py +++ b/src/sentry/models/projectownership.py @@ -13,7 +13,8 @@ from sentry.utils.cache import cache if TYPE_CHECKING: - from sentry.models import Team, User + from sentry.models import Team + from sentry.services.hybrid_cloud.user import APIUser READ_CACHE_DURATION = 3600 @@ -159,7 +160,7 @@ def get_issue_owners( ) -> Sequence[ Tuple[ ""Rule"", - Sequence[Union[""Team"", ""User""]], + Sequence[Union[""Team"", ""APIUser""]], Union[OwnerRuleType.OWNERSHIP_RULE.value, OwnerRuleType.CODEOWNERS.value], ] ]: diff --git a/src/sentry/models/team.py b/src/sentry/models/team.py index 5ce6509cae8f0a..d62162cf66ae38 100644 --- a/src/sentry/models/team.py +++ b/src/sentry/models/team.py @@ -164,6 +164,9 @@ class Meta: __repr__ = sane_repr(""name"", ""slug"") + def class_name(self): + return ""Team"" + def __str__(self): return f""{self.name} ({self.slug})"" diff --git a/src/sentry/models/user.py b/src/sentry/models/user.py index a727d0f855522c..0f7f3e71b353f2 100644 --- a/src/sentry/models/user.py +++ b/src/sentry/models/user.py @@ -29,7 +29,7 @@ audit_logger = logging.getLogger(""sentry.audit.user"") if TYPE_CHECKING: - from sentry.models import Group, Organization, Team + from sentry.models import Organization, Team class UserManager(BaseManager, DjangoUserManager): @@ -48,14 +48,6 @@ def get_team_members_with_verified_email_for_projects( is_active=True, ).distinct() - def get_from_group(self, group: ""Group"") -> QuerySet: - """"""Get a queryset of all users in all teams in a given Group's project."""""" - return self.filter( - sentry_orgmember_set__organization=group.organization, - sentry_orgmember_set__teams__in=group.project.teams.all(), - is_active=True, - ) - def get_from_teams(self, organization_id: int, teams: Sequence[""Team""]) -> QuerySet: return self.filter( sentry_orgmember_set__organization_id=organization_id, @@ -106,14 +98,6 @@ def get_users_with_only_one_integration_for_provider( .filter(row_count=1) ) - def get_for_email(self, email: str, case_sensitive: bool = True) -> Sequence[""User""]: - if not case_sensitive: - kwargs = dict(emails__email__iexact=email) - else: - kwargs = dict(emails__email=email) - - return self.filter(emails__is_verified=True, is_active=True, **kwargs) - @control_silo_only_model class User(BaseModel, AbstractBaseUser): @@ -205,6 +189,9 @@ class Meta: __repr__ = sane_repr(""id"") + def class_name(self): + return ""User"" + def delete(self): if self.username == ""sentry"": raise Exception('You cannot delete the ""sentry"" user as it is required by Sentry.') diff --git a/src/sentry/notifications/helpers.py b/src/sentry/notifications/helpers.py index 6f1db8e0cd9d47..57bcac70dca749 100644 --- a/src/sentry/notifications/helpers.py +++ b/src/sentry/notifications/helpers.py @@ -33,12 +33,13 @@ Team, User, ) + from sentry.services.hybrid_cloud.user import APIUser def _get_notification_setting_default( provider: ExternalProviders, type: NotificationSettingTypes, - recipient: Team | User | None = None, # not needed right now + recipient: Team | APIUser | None = None, # not needed right now ) -> NotificationSettingOptionValues: """""" In order to increase engagement, we automatically opt users into receiving @@ -55,7 +56,7 @@ def _get_notification_setting_default( def _get_default_value_by_provider( type: NotificationSettingTypes, - recipient: Team | User | None = None, + recipient: Team | APIUser | None = None, ) -> Mapping[ExternalProviders, NotificationSettingOptionValues]: return { provider: _get_notification_setting_default(provider, type, recipient) @@ -65,10 +66,10 @@ def _get_default_value_by_provider( def _get_setting_mapping_from_mapping( notification_settings_by_recipient: Mapping[ - Team | User, + Team | APIUser, Mapping[NotificationScopeType, Mapping[ExternalProviders, NotificationSettingOptionValues]], ], - recipient: Team | User, + recipient: Team | APIUser, type: NotificationSettingTypes, ) -> Mapping[ExternalProviders, NotificationSettingOptionValues]: """""" @@ -127,7 +128,7 @@ def should_be_participating( def where_should_be_participating( - recipient: Team | User, + recipient: Team | APIUser, subscription: GroupSubscription | None, notification_settings_by_recipient: Mapping[ Team | User, @@ -187,9 +188,9 @@ def get_values_by_provider_by_type( def transform_to_notification_settings_by_recipient( notification_settings: Iterable[NotificationSetting], - recipients: Iterable[Team | User], + recipients: Iterable[Team | APIUser], ) -> Mapping[ - Team | User, + Team | APIUser, Mapping[NotificationScopeType, Mapping[ExternalProviders, NotificationSettingOptionValues]], ]: """""" @@ -198,7 +199,7 @@ def transform_to_notification_settings_by_recipient( """""" actor_mapping = {recipient.actor_id: recipient for recipient in recipients} notification_settings_by_recipient: MutableMapping[ - Team | User, + Team | APIUser, MutableMapping[ NotificationScopeType, MutableMapping[ExternalProviders, NotificationSettingOptionValues], diff --git a/src/sentry/notifications/manager.py b/src/sentry/notifications/manager.py index e89c24fa4c14aa..17bc6d68fa3c3d 100644 --- a/src/sentry/notifications/manager.py +++ b/src/sentry/notifications/manager.py @@ -28,6 +28,7 @@ if TYPE_CHECKING: from sentry.models import NotificationSetting, Organization, Project, Team, User + from sentry.services.hybrid_cloud.user import APIUser REMOVE_SETTING_BATCH_SIZE = 1000 @@ -247,9 +248,9 @@ def get_for_recipient_by_parent( self, type_: NotificationSettingTypes, parent: Organization | Project, - recipients: Iterable[Team | User], + recipients: Iterable[Team | User | APIUser], ) -> QuerySet: - from sentry.models import Team, User + from sentry.models import Team """""" Find all of a project/organization's notification settings for a list of @@ -262,9 +263,9 @@ def get_for_recipient_by_parent( for recipient in recipients: if type(recipient) == Team: team_ids.add(recipient.id) - if type(recipient) == User: + if recipient.class_name() == ""User"": user_ids.add(recipient.id) - actor_ids.add(recipient.actor.id) + actor_ids.add(recipient.actor_id) # If the list would be empty, don't bother querying. if not actor_ids: @@ -291,9 +292,9 @@ def get_for_recipient_by_parent( def filter_to_accepting_recipients( self, parent: Union[Organization, Project], - recipients: Iterable[Team | User], + recipients: Iterable[Team | APIUser], type: NotificationSettingTypes = NotificationSettingTypes.ISSUE_ALERTS, - ) -> Mapping[ExternalProviders, Iterable[Team | User]]: + ) -> Mapping[ExternalProviders, Iterable[Team | APIUser]]: """""" Filters a list of teams or users down to the recipients by provider who are subscribed to alerts. We check both the project level settings and diff --git a/src/sentry/notifications/notifications/activity/assigned.py b/src/sentry/notifications/notifications/activity/assigned.py index b4a7b8c6d672cf..94627cbaee1437 100644 --- a/src/sentry/notifications/notifications/activity/assigned.py +++ b/src/sentry/notifications/notifications/activity/assigned.py @@ -5,6 +5,7 @@ from sentry.models import Activity, NotificationSetting, Organization, Team, User from sentry.notifications.types import GroupSubscriptionReason +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import ExternalProviders from .base import GroupActivityNotification @@ -77,7 +78,7 @@ def get_notification_title( def get_participants_with_group_subscription_reason( self, - ) -> Mapping[ExternalProviders, Mapping[Team | User, int]]: + ) -> Mapping[ExternalProviders, Mapping[Team | APIUser, int]]: """"""Hack to tack on the assigned team to the list of users subscribed to the group."""""" users_by_provider = super().get_participants_with_group_subscription_reason() if is_team_assignee(self.activity): @@ -92,7 +93,7 @@ def get_participants_with_group_subscription_reason( ) actors_by_provider: MutableMapping[ ExternalProviders, - MutableMapping[Team | User, int], + MutableMapping[Team | APIUser, int], ] = defaultdict(dict) actors_by_provider.update({**users_by_provider}) for provider, teams in teams_by_provider.items(): diff --git a/src/sentry/notifications/notifications/activity/base.py b/src/sentry/notifications/notifications/activity/base.py index a5af6b10a3bb28..50335b6c2ed643 100644 --- a/src/sentry/notifications/notifications/activity/base.py +++ b/src/sentry/notifications/notifications/activity/base.py @@ -14,6 +14,7 @@ from sentry.notifications.utils import send_activity_notification from sentry.notifications.utils.avatar import avatar_as_html from sentry.notifications.utils.participants import get_participants_for_group +from sentry.services.hybrid_cloud.user import APIUser, user_service from sentry.types.integrations import ExternalProviders if TYPE_CHECKING: @@ -63,7 +64,7 @@ def get_context(self) -> MutableMapping[str, Any]: @abc.abstractmethod def get_participants_with_group_subscription_reason( self, - ) -> Mapping[ExternalProviders, Mapping[Team | User, int]]: + ) -> Mapping[ExternalProviders, Mapping[Team | APIUser, int]]: pass def send(self) -> None: @@ -91,9 +92,10 @@ def get_group_link(self) -> str: def get_participants_with_group_subscription_reason( self, - ) -> Mapping[ExternalProviders, Mapping[Team | User, int]]: + ) -> Mapping[ExternalProviders, Mapping[Team | APIUser, int]]: """"""This is overridden by the activity subclasses."""""" - return get_participants_for_group(self.group, self.activity.user) + user = user_service.get_user(self.activity.user_id) + return get_participants_for_group(self.group, user) def get_unsubscribe_key(self) -> tuple[str, int, str | None] | None: return ""issue"", self.group.id, None diff --git a/src/sentry/notifications/notifications/activity/release.py b/src/sentry/notifications/notifications/activity/release.py index d566c6aea3ef5c..9d3384e2825a3b 100644 --- a/src/sentry/notifications/notifications/activity/release.py +++ b/src/sentry/notifications/notifications/activity/release.py @@ -95,7 +95,7 @@ def get_projects(self, recipient: Team | User) -> set[Project]: if not self.release: return set() - if isinstance(recipient, User): + if recipient.class_name() == ""User"": if recipient.is_superuser or self.organization.flags.allow_joinleave: # Admins can see all projects. return self.projects diff --git a/src/sentry/notifications/notifications/activity/release_summary.py b/src/sentry/notifications/notifications/activity/release_summary.py index ea965d3cd6ded2..5b29e3bc202765 100644 --- a/src/sentry/notifications/notifications/activity/release_summary.py +++ b/src/sentry/notifications/notifications/activity/release_summary.py @@ -103,7 +103,7 @@ def get_projects(self, recipient: Team | User) -> set[Project]: if not self.release: return set() - if isinstance(recipient, User): + if recipient.class_name() == ""User"": if recipient.is_superuser or self.organization.flags.allow_joinleave: # Admins can see all projects. return self.projects diff --git a/src/sentry/notifications/notifications/base.py b/src/sentry/notifications/notifications/base.py index 944974e6afced9..483e1cb00f1d0d 100644 --- a/src/sentry/notifications/notifications/base.py +++ b/src/sentry/notifications/notifications/base.py @@ -11,6 +11,7 @@ from sentry.models import Environment, NotificationSetting, Team, User from sentry.notifications.types import NotificationSettingTypes, get_notification_setting_type_name from sentry.notifications.utils.actions import MessageAction +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders from sentry.utils.http import absolute_uri from sentry.utils.safe import safe_execute @@ -85,7 +86,7 @@ def template_path(self) -> str: pass def get_recipient_context( - self, recipient: Team | User, extra_context: Mapping[str, Any] + self, recipient: Team | APIUser, extra_context: Mapping[str, Any] ) -> MutableMapping[str, Any]: # Basically a noop. return {**extra_context} @@ -112,18 +113,18 @@ def get_message_description(self, recipient: Team | User, provider: ExternalProv def get_unsubscribe_key(self) -> tuple[str, int, str | None] | None: return None - def get_log_params(self, recipient: Team | User) -> Mapping[str, Any]: + def get_log_params(self, recipient: Team | APIUser) -> Mapping[str, Any]: group = getattr(self, ""group"", None) params = { ""organization_id"": self.organization.id, ""actor_id"": recipient.actor_id, ""group_id"": group.id if group else None, } - if isinstance(recipient, User): + if recipient.class_name() == ""User"": params[""user_id""] = recipient.id return params - def get_custom_analytics_params(self, recipient: Team | User) -> Mapping[str, Any]: + def get_custom_analytics_params(self, recipient: Team | APIUser) -> Mapping[str, Any]: """""" Returns a mapping of params used to record the event associated with self.analytics_event. By default, use the log params. @@ -166,16 +167,16 @@ def record_notification_sent(self, recipient: Team | User, provider: ExternalPro ) def get_referrer( - self, provider: ExternalProviders, recipient: Optional[Team | User] = None + self, provider: ExternalProviders, recipient: Optional[Team | APIUser] = None ) -> str: # referrer needs the provider and recipient referrer = f""{self.metrics_key}-{EXTERNAL_PROVIDERS[provider]}"" if recipient: - referrer += ""-"" + recipient.__class__.__name__.lower() + referrer += ""-"" + recipient.class_name().lower() return referrer def get_sentry_query_params( - self, provider: ExternalProviders, recipient: Optional[Team | User] = None + self, provider: ExternalProviders, recipient: Optional[Team | APIUser] = None ) -> str: """""" Returns the query params that allow us to track clicks into Sentry links. @@ -184,7 +185,7 @@ def get_sentry_query_params( """""" return f""?referrer={self.get_referrer(provider, recipient)}"" - def get_settings_url(self, recipient: Team | User, provider: ExternalProviders) -> str: + def get_settings_url(self, recipient: Team | APIUser, provider: ExternalProviders) -> str: # Settings url is dependant on the provider so we know which provider is sending them into Sentry. if isinstance(recipient, Team): url_str = f""/settings/{self.organization.slug}/teams/{recipient.slug}/notifications/"" @@ -202,7 +203,7 @@ def get_settings_url(self, recipient: Team | User, provider: ExternalProviders) ) ) - def determine_recipients(self) -> Iterable[Team | User]: + def determine_recipients(self) -> Iterable[Team | APIUser]: raise NotImplementedError def get_notification_providers(self) -> Iterable[ExternalProviders]: @@ -211,7 +212,7 @@ def get_notification_providers(self) -> Iterable[ExternalProviders]: return notification_providers() - def get_participants(self) -> Mapping[ExternalProviders, Iterable[Team | User]]: + def get_participants(self) -> Mapping[ExternalProviders, Iterable[Team | APIUser]]: # need a notification_setting_type to call this function if not self.notification_setting_type: raise NotImplementedError diff --git a/src/sentry/notifications/notifications/codeowners_auto_sync.py b/src/sentry/notifications/notifications/codeowners_auto_sync.py index 0045707bc3c71e..27e5cbd3023431 100644 --- a/src/sentry/notifications/notifications/codeowners_auto_sync.py +++ b/src/sentry/notifications/notifications/codeowners_auto_sync.py @@ -5,6 +5,7 @@ from sentry.notifications.notifications.base import ProjectNotification from sentry.notifications.types import NotificationSettingTypes +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import ExternalProviders from sentry.utils.http import absolute_uri @@ -18,7 +19,7 @@ class AutoSyncNotification(ProjectNotification): notification_setting_type = NotificationSettingTypes.DEPLOY template_path = ""sentry/emails/codeowners-auto-sync-failure"" - def determine_recipients(self) -> Iterable[Team | User]: + def determine_recipients(self) -> Iterable[Team | APIUser]: return self.organization.get_owners() # type: ignore @property diff --git a/src/sentry/notifications/notifications/organization_request/base.py b/src/sentry/notifications/notifications/organization_request/base.py index 569a633a36933b..bf3432c05347b8 100644 --- a/src/sentry/notifications/notifications/organization_request/base.py +++ b/src/sentry/notifications/notifications/organization_request/base.py @@ -11,6 +11,7 @@ RoleBasedRecipientStrategy, ) from sentry.notifications.types import NotificationSettingTypes +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import ExternalProviders if TYPE_CHECKING: @@ -35,7 +36,7 @@ def reference(self) -> Model | None: def get_context(self) -> MutableMapping[str, Any]: return {} - def determine_recipients(self) -> Iterable[Team | User]: + def determine_recipients(self) -> Iterable[Team | APIUser]: return self.role_based_recipient_strategy.determine_recipients() def get_notification_title( diff --git a/src/sentry/notifications/notifications/rules.py b/src/sentry/notifications/notifications/rules.py index 26d4f7a95a1805..ac4fee693f052e 100644 --- a/src/sentry/notifications/notifications/rules.py +++ b/src/sentry/notifications/notifications/rules.py @@ -73,7 +73,7 @@ def get_recipient_context( ) -> MutableMapping[str, Any]: timezone = pytz.timezone(""UTC"") - if isinstance(recipient, User): + if recipient.class_name() == ""User"": user_tz = UserOption.objects.get_value(user=recipient, key=""timezone"", default=""UTC"") try: timezone = pytz.timezone(user_tz) diff --git a/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py b/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py index b3ba0014a1f237..bb86d51bbc464b 100644 --- a/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py +++ b/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py @@ -5,6 +5,7 @@ from sentry import roles from sentry.models import OrganizationMember +from sentry.services.hybrid_cloud.user import APIUser, user_service if TYPE_CHECKING: from sentry.models import Organization, User @@ -16,11 +17,13 @@ class RoleBasedRecipientStrategy(metaclass=ABCMeta): def __init__(self, organization: Organization): self.organization = organization - def get_member(self, user: User) -> OrganizationMember: + def get_member(self, user: APIUser) -> OrganizationMember: # cache the result + if user.class_name() != ""User"": + raise OrganizationMember.DoesNotExist() if user.id not in self.member_by_user_id: self.member_by_user_id[user.id] = OrganizationMember.objects.get( - user=user, organization=self.organization + user_id=user.id, organization=self.organization ) return self.member_by_user_id[user.id] @@ -32,15 +35,13 @@ def set_member_in_cache(self, member: OrganizationMember) -> None: def determine_recipients( self, - ) -> Iterable[User]: + ) -> Iterable[APIUser]: members = self.determine_member_recipients() # store the members in our cache for member in members: self.set_member_in_cache(member) # convert members to users - user_map: Iterable[User] = map(lambda member: member.user, members) - # convert to list from an interterator - return list(user_map) + return user_service.get_many(member.user_id for member in members) @abstractmethod def determine_member_recipients(self) -> Iterable[OrganizationMember]: diff --git a/src/sentry/notifications/notifications/user_report.py b/src/sentry/notifications/notifications/user_report.py index 701b0a9e2d232d..26f5639d1acf5e 100644 --- a/src/sentry/notifications/notifications/user_report.py +++ b/src/sentry/notifications/notifications/user_report.py @@ -10,6 +10,7 @@ from sentry.notifications.helpers import get_reason_context from sentry.notifications.notifications.base import ProjectNotification from sentry.notifications.utils import send_activity_notification +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import ExternalProviders from sentry.utils.http import absolute_uri @@ -30,7 +31,7 @@ def __init__(self, project: Project, report: Mapping[str, Any]) -> None: def get_participants_with_group_subscription_reason( self, - ) -> Mapping[ExternalProviders, Mapping[Team | User, int]]: + ) -> Mapping[ExternalProviders, Mapping[Team | APIUser, int]]: data_by_provider = GroupSubscription.objects.get_participants(group=self.group) return { provider: data diff --git a/src/sentry/notifications/notify.py b/src/sentry/notifications/notify.py index 9316520a6260d0..a9e2a84a578f92 100644 --- a/src/sentry/notifications/notify.py +++ b/src/sentry/notifications/notify.py @@ -2,11 +2,14 @@ from typing import TYPE_CHECKING, Any, Callable, Iterable, Mapping, MutableMapping, Optional, Union +from sentry.models import User from sentry.notifications.notifications.base import BaseNotification +from sentry.services.hybrid_cloud.user import APIUser +from sentry.silo.base import SiloMode from sentry.types.integrations import ExternalProviders if TYPE_CHECKING: - from sentry.models import Team, User + from sentry.models import Team # Shortcut so that types don't explode. Notifiable = Callable[ @@ -46,9 +49,28 @@ def wrapped(send_notification: Notifiable) -> Notifiable: def notify( provider: ExternalProviders, notification: Any, - recipients: Iterable[Team | User], + recipients: Iterable[Team | APIUser], shared_context: Mapping[str, Any], extra_context_by_actor_id: Mapping[int, Mapping[str, Any]] | None = None, ) -> None: """"""Send notifications to these users or team."""""" + + """""" ###################### Begin Hack ###################### + # Temporary Hybrid Cloud hack that isolates the notification subsystem from APIUser + # type changes. With this in place, we can assert that changes so far don't affect + # Notification system behavior (only possibly who receives notifications). + # This will be removed in future work. + + # Create a new list of recipients that are full Team and User objects (as opposed to APIUser) + """""" + if SiloMode.get_current_mode() == SiloMode.MONOLITH: + user_ids = [] + new_recipients = [] + for r in recipients: + if isinstance(r, APIUser): + user_ids.append(r.id) + else: + new_recipients.append(r) + recipients = new_recipients + list(User.objects.filter(id__in=user_ids)) + """""" ###################### End Hack ###################### """""" registry[provider](notification, recipients, shared_context, extra_context_by_actor_id) diff --git a/src/sentry/notifications/utils/participants.py b/src/sentry/notifications/utils/participants.py index e0331f739118d7..71869edf53d39b 100644 --- a/src/sentry/notifications/utils/participants.py +++ b/src/sentry/notifications/utils/participants.py @@ -12,6 +12,8 @@ GroupSubscription, NotificationSetting, Organization, + OrganizationMember, + OrganizationMemberTeam, Project, ProjectOwnership, Release, @@ -32,6 +34,7 @@ NotificationSettingOptionValues, NotificationSettingTypes, ) +from sentry.services.hybrid_cloud.user import APIUser, user_service from sentry.types.integrations import ExternalProviders from sentry.utils import metrics @@ -48,8 +51,8 @@ def get_providers_from_which_to_remove_user( - user: User, - participants_by_provider: Mapping[ExternalProviders, Mapping[User, int]], + user: APIUser, + participants_by_provider: Mapping[ExternalProviders, Mapping[APIUser, int]], ) -> set[ExternalProviders]: """""" Given a mapping of provider to mappings of users to why they should receive @@ -60,7 +63,7 @@ def get_providers_from_which_to_remove_user( providers = { provider for provider, participants in participants_by_provider.items() - if user in participants + if user.id in map(lambda p: int(p.id), participants) } if ( providers @@ -71,10 +74,10 @@ def get_providers_from_which_to_remove_user( def get_participants_for_group( - group: Group, user: User | None = None + group: Group, user: APIUser | None = None ) -> Mapping[ExternalProviders, Mapping[Team | User, int]]: participants_by_provider: MutableMapping[ - ExternalProviders, MutableMapping[Team | User, int] + ExternalProviders, MutableMapping[Team | APIUser, int] ] = GroupSubscription.objects.get_participants(group) if user: # Optionally remove the actor that created the activity from the recipients list. @@ -136,15 +139,15 @@ def get_participants_for_release( def split_participants_and_context( - participants_with_reasons: Mapping[Team | User, int] -) -> tuple[Iterable[Team | User], Mapping[int, Mapping[str, Any]]]: + participants_with_reasons: Mapping[Team | APIUser, int] +) -> tuple[Iterable[Team | APIUser], Mapping[int, Mapping[str, Any]]]: return participants_with_reasons.keys(), { participant.actor_id: {""reason"": reason} for participant, reason in participants_with_reasons.items() } -def get_owners(project: Project, event: Event | None = None) -> Sequence[Team | User]: +def get_owners(project: Project, event: Event | None = None) -> Sequence[Team | APIUser]: """""" Given a project and an event, decide which users and teams are the owners. @@ -163,7 +166,7 @@ def get_owners(project: Project, event: Event | None = None) -> Sequence[Team | elif owners == ProjectOwnership.Everyone: outcome = ""everyone"" - recipients = User.objects.filter(id__in=project.member_set.values_list(""user"", flat=True)) + recipients = user_service.get_from_project(project.id) else: outcome = ""match"" @@ -215,7 +218,7 @@ def determine_eligible_recipients( target_type: ActionTargetType, target_identifier: int | None = None, event: Event | None = None, -) -> Iterable[Team | User]: +) -> Iterable[Team | APIUser]: """""" Either get the individual recipient from the target type/id or the owners as determined by rules for this project and event. @@ -242,7 +245,7 @@ def determine_eligible_recipients( return set() -def get_release_committers(project: Project, event: Event) -> Sequence[User]: +def get_release_committers(project: Project, event: Event) -> Sequence[APIUser]: # get_participants_for_release seems to be the method called when deployments happen # supposedly, this logic should be fairly, close ... # why is get_participants_for_release so much more complex??? @@ -263,7 +266,7 @@ def get_release_committers(project: Project, event: Event) -> Sequence[User]: return _get_release_committers(last_release) -def _get_release_committers(release: Release) -> Sequence[User]: +def _get_release_committers(release: Release) -> Sequence[APIUser]: from sentry.api.serializers import Author, get_users_for_commits from sentry.utils.committers import _get_commits @@ -274,12 +277,9 @@ def _get_release_committers(release: Release) -> Sequence[User]: # commit_author_id : Author author_users: Mapping[str, Author] = get_users_for_commits(commits) - release_committers = list( - User.objects.filter(id__in={au[""id""] for au in author_users.values() if au.get(""id"")}) - ) - if features.has(""organizations:active-release-notifications-enable"", release.organization): - return release_committers + user_ids: set[int] = {au[""id""] for au in author_users.values() if au.get(""id"")} + return user_service.get_many(user_ids) return [] @@ -289,7 +289,7 @@ def get_send_to( target_identifier: int | None = None, event: Event | None = None, notification_type: NotificationSettingTypes = NotificationSettingTypes.ISSUE_ALERTS, -) -> Mapping[ExternalProviders, set[Team | User]]: +) -> Mapping[ExternalProviders, set[Team | APIUser]]: recipients = determine_eligible_recipients(project, target_type, target_identifier, event) return get_recipients_by_provider(project, recipients, notification_type) @@ -299,16 +299,24 @@ def get_user_from_identifier(project: Project, target_identifier: str | int | No return None try: - return ( - User.objects.filter( - id=int(target_identifier), - sentry_orgmember_set__teams__projectteam__project=project, - ) - .distinct() - .get() + ident = int(target_identifier) + except ValueError: + return None + + try: + organization_member_team = OrganizationMember.objects.get( + organization_id=project.organization_id, user_id=ident ) - except User.DoesNotExist: + except OrganizationMember.DoesNotExist: + return None + + team_ids = [t.id for t in project.teams.all()] + omt = OrganizationMemberTeam.objects.filter( + organizationmember_id=organization_member_team.id, team_id__in=team_ids + ).first() + if omt is None: return None + return user_service.get_user(ident) def get_team_from_identifier(project: Project, target_identifier: str | int | None) -> Team | None: @@ -322,11 +330,11 @@ def get_team_from_identifier(project: Project, target_identifier: str | int | No def partition_recipients( - recipients: Iterable[Team | User], -) -> tuple[Iterable[Team], Iterable[User]]: + recipients: Iterable[Team | APIUser], +) -> tuple[Iterable[Team], Iterable[APIUser]]: teams, users = set(), set() for recipient in recipients: - if isinstance(recipient, User): + if recipient.class_name() == ""User"": users.add(recipient) else: teams.add(recipient) @@ -336,24 +344,24 @@ def partition_recipients( def get_users_from_team_fall_back( teams: Iterable[Team], recipients_by_provider: Mapping[ExternalProviders, Iterable[Team | User]], -) -> Iterable[User]: +) -> Iterable[APIUser]: teams_to_fall_back = set(teams) for recipients in recipients_by_provider.values(): for recipient in recipients: teams_to_fall_back.remove(recipient) - users = set() + user_ids: set[int] = set() for team in teams_to_fall_back: # Fall back to notifying each subscribed user if there aren't team notification settings member_list = team.member_set.values_list(""user_id"", flat=True) - users |= set(User.objects.filter(id__in=member_list)) - return users + user_ids |= set(member_list) + return user_service.get_many(user_ids) def combine_recipients_by_provider( - teams_by_provider: Mapping[ExternalProviders, set[Team | User]], - users_by_provider: Mapping[ExternalProviders, set[Team | User]], -) -> Mapping[ExternalProviders, set[Team | User]]: + teams_by_provider: Mapping[ExternalProviders, set[Team | APIUser]], + users_by_provider: Mapping[ExternalProviders, set[Team | APIUser]], +) -> Mapping[ExternalProviders, set[Team | APIUser]]: """"""TODO(mgaeta): Make this more generic and move it to utils."""""" recipients_by_provider = defaultdict(set) for provider, teams in teams_by_provider.items(): @@ -367,9 +375,9 @@ def combine_recipients_by_provider( def get_recipients_by_provider( project: Project, - recipients: Iterable[Team | User], + recipients: Iterable[Team | APIUser], notification_type: NotificationSettingTypes = NotificationSettingTypes.ISSUE_ALERTS, -) -> Mapping[ExternalProviders, set[Team | User]]: +) -> Mapping[ExternalProviders, set[Team | APIUser]]: """"""Get the lists of recipients that should receive an Issue Alert by ExternalProvider."""""" teams, users = partition_recipients(recipients) diff --git a/src/sentry/ownership/grammar.py b/src/sentry/ownership/grammar.py index acc7252f7fa209..a046b9befb4c35 100644 --- a/src/sentry/ownership/grammar.py +++ b/src/sentry/ownership/grammar.py @@ -547,6 +547,8 @@ def resolve_actors(owners: Iterable[Owner], project_id: int) -> Mapping[Owner, A actors.update( { (""user"", email.lower()): ActorTuple(u_id, User) + # This will need to be broken in hybrid cloud world, querying users from region silo won't be possible + # without an explicit service call. for u_id, email in User.objects.filter( reduce(operator.or_, [Q(emails__email__iexact=o.identifier) for o in users]), # We don't require verified emails diff --git a/src/sentry/receivers/onboarding.py b/src/sentry/receivers/onboarding.py index 827a24ae7387e5..fef17466704b49 100644 --- a/src/sentry/receivers/onboarding.py +++ b/src/sentry/receivers/onboarding.py @@ -14,6 +14,7 @@ Project, ) from sentry.plugins.bases import IssueTrackingPlugin, IssueTrackingPlugin2 +from sentry.services.hybrid_cloud.user import APIUser from sentry.signals import ( alert_rule_created, event_processed, @@ -134,7 +135,7 @@ def record_first_event(project, event, **kwargs): ) try: - user = Organization.objects.get(id=project.organization_id).get_default_owner() + user: APIUser = Organization.objects.get(id=project.organization_id).get_default_owner() except IndexError: logging.getLogger(""sentry"").warning( ""Cannot record first event for organization (%s) due to missing owners"", @@ -280,7 +281,7 @@ def record_release_received(project, event, **kwargs): ) if success: try: - user = Organization.objects.get(id=project.organization_id).get_default_owner() + user: APIUser = Organization.objects.get(id=project.organization_id).get_default_owner() except IndexError: logging.getLogger(""sentry"").warning( ""Cannot record release received for organization (%s) due to missing owners"", @@ -317,7 +318,9 @@ def record_user_context_received(project, event, **kwargs): ) if success: try: - user = Organization.objects.get(id=project.organization_id).get_default_owner() + user: APIUser = Organization.objects.get( + id=project.organization_id + ).get_default_owner() except IndexError: logging.getLogger(""sentry"").warning( ""Cannot record user context received for organization (%s) due to missing owners"", @@ -351,7 +354,7 @@ def record_sourcemaps_received(project, event, **kwargs): ) if success: try: - user = Organization.objects.get(id=project.organization_id).get_default_owner() + user: APIUser = Organization.objects.get(id=project.organization_id).get_default_owner() except IndexError: logging.getLogger(""sentry"").warning( ""Cannot record sourcemaps received for organization (%s) due to missing owners"", diff --git a/src/sentry/receivers/releases.py b/src/sentry/receivers/releases.py index 9afe65323a747e..ff92667bcf9923 100644 --- a/src/sentry/receivers/releases.py +++ b/src/sentry/receivers/releases.py @@ -128,14 +128,18 @@ def resolved_in_commit(instance, created, **kwargs): user=user, group=group, reason=GroupSubscriptionReason.status_change ) - Activity.objects.create( - project_id=group.project_id, - group=group, - type=ActivityType.SET_RESOLVED_IN_COMMIT.value, - ident=instance.id, - user=acting_user, - data={""commit"": instance.id}, - ) + activity_kwargs = { + ""project_id"": group.project_id, + ""group"": group, + ""type"": ActivityType.SET_RESOLVED_IN_COMMIT.value, + ""ident"": instance.id, + ""data"": {""commit"": instance.id}, + } + if acting_user is not None: + activity_kwargs[""user_id""] = acting_user.id + + Activity.objects.create(**activity_kwargs) + Group.objects.filter(id=group.id).update( status=GroupStatus.RESOLVED, resolved_at=current_datetime ) diff --git a/src/sentry/receivers/sentry_apps.py b/src/sentry/receivers/sentry_apps.py index 6059d18afee17d..04faf219c16c3c 100644 --- a/src/sentry/receivers/sentry_apps.py +++ b/src/sentry/receivers/sentry_apps.py @@ -11,8 +11,10 @@ Organization, SentryAppInstallation, SentryFunction, + Team, User, ) +from sentry.services.hybrid_cloud.user import APIUser from sentry.signals import ( comment_created, comment_deleted, @@ -29,7 +31,7 @@ def send_issue_assigned_webhook(project, group, user, **kwargs): assignee = GroupAssignee.objects.get(group_id=group.id).assigned_actor() - actor = assignee.resolve() + actor: APIUser | Team = assignee.resolve() data = { ""assignee"": {""type"": assignee.type.__name__.lower(), ""name"": actor.name, ""id"": actor.id} diff --git a/src/sentry/services/hybrid_cloud/user.py b/src/sentry/services/hybrid_cloud/user.py new file mode 100644 index 00000000000000..99ca920af126b4 --- /dev/null +++ b/src/sentry/services/hybrid_cloud/user.py @@ -0,0 +1,174 @@ +from abc import abstractmethod +from dataclasses import dataclass, fields +from typing import Any, Iterable, List, Optional + +from sentry.api.serializers import serialize +from sentry.models import Project +from sentry.models.group import Group +from sentry.models.user import User +from sentry.services.hybrid_cloud import ( + CreateStubFromBase, + InterfaceWithLifecycle, + silo_mode_delegation, +) +from sentry.silo import SiloMode + + +@dataclass(frozen=True, eq=True) +class APIUser: + id: int = -1 + pk: int = -1 + name: str = """" + email: str = """" + username: str = """" + actor_id: int = -1 + display_name: str = """" + is_superuser: bool = False + + def get_display_name(self) -> str: # API compatibility with ORM User + return self.display_name + + def get_full_name(self) -> str: + return self.name + + def get_short_name(self) -> str: + return self.username + + def class_name(self) -> str: + return ""User"" + + +class UserService(InterfaceWithLifecycle): + @abstractmethod + def get_many_by_email(self, email: str) -> List[APIUser]: + """""" + Return a list of active users with verified emails matching the parameter + :param email: + A case insensitive email to match + :return: + """""" + pass + + @abstractmethod + def get_from_group(self, group: Group) -> List[APIUser]: + """"""Get all users in all teams in a given Group's project."""""" + pass + + @abstractmethod + def get_from_project(self, project_id: int) -> List[Group]: + """"""Get all users associated with a project identifier"""""" + pass + + @abstractmethod + def get_many(self, user_ids: Iterable[int]) -> List[APIUser]: + """""" + This method returns User objects given an iterable of IDs + :param user_ids: + A list of user IDs to fetch + :return: + """""" + pass + + def get_by_actor_id(self, actor_id: int) -> Optional[APIUser]: + """""" + This method returns a User object given an actor ID + :param actor_id: + An actor ID to fetch + :return: + """""" + pass + + def get_user(self, user_id: int) -> Optional[APIUser]: + """""" + This method returns a User object given an ID + :param user_id: + A user ID to fetch + :return: + """""" + users = self.get_many([user_id]) + if len(users) > 0: + return users[0] + else: + return None + + # NOTE: In the future if this becomes RPC, we can avoid the double serialization problem by using a special type + # with its own json serialization that allows pass through (ie, a string type that does not serialize into a string, + # but rather validates itself as valid json and renders 'as is'. Like ""unescaped json text"". + @abstractmethod + def serialize_users(self, user_ids: List[int]) -> List[Any]: + """""" + It is crucial that the returned order matches the user_ids passed in so that no introspection is required + to match the serialized user and the original user_id. + :param user_ids: + :return: + """""" + pass + + @classmethod + def serialize_user(cls, user: User) -> APIUser: + args = { + field.name: getattr(user, field.name) + for field in fields(APIUser) + if hasattr(user, field.name) + } + args[""pk""] = user.pk + args[""display_name""] = user.get_display_name() + args[""is_superuser""] = user.is_superuser + return APIUser(**args) + + +class DatabaseBackedUserService(UserService): + def get_many_by_email(self, email: str) -> List[APIUser]: + return [ + UserService.serialize_user(user) + for user in User.objects.filter( + emails__is_verified=True, is_active=True, emails__email__iexact=email + ) + ] + + def serialize_users(self, user_ids: List[int]) -> List[Any]: + result: List[Any] = [] + for user in User.objects.filter(id__in=user_ids): + result.append(serialize(user)) + return result + + def get_from_group(self, group: Group) -> List[APIUser]: + return [ + UserService.serialize_user(u) + for u in User.objects.filter( + sentry_orgmember_set__organization=group.organization, + sentry_orgmember_set__teams__in=group.project.teams.all(), + is_active=True, + ) + ] + + def get_many(self, user_ids: Iterable[int]) -> List[APIUser]: + query = User.objects.filter(id__in=user_ids) + return [UserService.serialize_user(u) for u in query] + + def get_from_project(self, project_id: int) -> List[APIUser]: + try: + project = Project.objects.get(id=project_id) + except Project.DoesNotExist: + return [] + return self.get_many(project.member_set.values_list(""user_id"", flat=True)) + + def get_by_actor_id(self, actor_id: int) -> Optional[APIUser]: + try: + return UserService.serialize_user(User.objects.get(actor_id=actor_id)) + except User.DoesNotExist: + return None + + def close(self) -> None: + pass + + +StubUserService = CreateStubFromBase(DatabaseBackedUserService) + +user_service: UserService = silo_mode_delegation( + { + SiloMode.MONOLITH: lambda: DatabaseBackedUserService(), + SiloMode.REGION: lambda: StubUserService(), + SiloMode.CONTROL: lambda: DatabaseBackedUserService(), + } +) diff --git a/src/sentry/services/hybrid_cloud/user_option.py b/src/sentry/services/hybrid_cloud/user_option.py new file mode 100644 index 00000000000000..5a16d8969daa69 --- /dev/null +++ b/src/sentry/services/hybrid_cloud/user_option.py @@ -0,0 +1,59 @@ +from abc import abstractmethod +from typing import Iterable, List, Optional + +from sentry.models.options.user_option import UserOption +from sentry.models.project import Project +from sentry.services.hybrid_cloud import ( + CreateStubFromBase, + InterfaceWithLifecycle, + silo_mode_delegation, +) +from sentry.silo import SiloMode + + +class UserOptionService(InterfaceWithLifecycle): + @abstractmethod + def get( + self, + user_ids: Iterable[int], + key: str, + project: Optional[Project], + ) -> List[UserOption]: + """""" + This method returns UserOption objects based on the passed in filters + :param user_ids: + A list of user IDs to fetch + :param project: + Filter options to a specific project + :param key: + Filter options to a specific key + :return: + """""" + pass + + +class DatabaseBackedUserOptionService(UserOptionService): + def get( + self, + user_ids: Iterable[int], + key: str, + project: Optional[Project], + ) -> List[UserOption]: + queryset = UserOption.objects.filter(user__in=user_ids, key=key) # type: ignore + if project is not None: + queryset = queryset.filter(project=project) + return list(queryset) + + def close(self) -> None: + pass + + +StubUserOptionService = CreateStubFromBase(DatabaseBackedUserOptionService) + +user_option_service: UserOptionService = silo_mode_delegation( + { + SiloMode.MONOLITH: lambda: DatabaseBackedUserOptionService(), + SiloMode.REGION: lambda: StubUserOptionService(), + SiloMode.CONTROL: lambda: DatabaseBackedUserOptionService(), + } +) diff --git a/src/sentry/tasks/integrations/sync_assignee_outbound.py b/src/sentry/tasks/integrations/sync_assignee_outbound.py index 4bd50e51692433..fe18e47e567ba1 100644 --- a/src/sentry/tasks/integrations/sync_assignee_outbound.py +++ b/src/sentry/tasks/integrations/sync_assignee_outbound.py @@ -2,6 +2,7 @@ from sentry import analytics, features from sentry.models import ExternalIssue, Integration, Organization, User +from sentry.services.hybrid_cloud.user import user_service from sentry.tasks.base import instrumented_task, retry @@ -25,16 +26,15 @@ def sync_assignee_outbound(external_issue_id: int, user_id: Optional[int], assig organization = Organization.objects.get(id=external_issue.organization_id) has_issue_sync = features.has(""organizations:integrations-issue-sync"", organization) - if not has_issue_sync: return integration = Integration.objects.get(id=external_issue.integration_id) - # Assume unassign if None. - user = User.objects.get(id=user_id) if user_id else None + user = user_service.get_user(user_id) if user_id else None installation = integration.get_installation(organization_id=external_issue.organization_id) + if installation.should_sync(""outbound_assignee""): installation.sync_assignee_outbound(external_issue, user, assign=assign) analytics.record( diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py index 35a672dc427c7b..0cc7b353543b04 100644 --- a/src/sentry/tasks/post_process.py +++ b/src/sentry/tasks/post_process.py @@ -2,7 +2,7 @@ import logging from datetime import timedelta -from typing import TYPE_CHECKING, Mapping, Optional, Sequence, Tuple, TypedDict, Union +from typing import TYPE_CHECKING, List, Mapping, Optional, Sequence, Tuple, TypedDict, Union import sentry_sdk from django.conf import settings @@ -192,6 +192,7 @@ def handle_group_owners(project, group, issue_owners): from sentry.models.groupowner import GroupOwner, GroupOwnerType, OwnerRuleType from sentry.models.team import Team from sentry.models.user import User + from sentry.services.hybrid_cloud.user import APIUser lock = locks.get(f""groupowner-bulk:{group.id}"", duration=10, name=""groupowner_bulk"") try: @@ -203,6 +204,7 @@ def handle_group_owners(project, group, issue_owners): type__in=[GroupOwnerType.OWNERSHIP_RULE.value, GroupOwnerType.CODEOWNERS.value], ) new_owners = {} + owners: Union[List[APIUser], List[Team]] for rule, owners, source in issue_owners: for owner in owners: # Can potentially have multiple rules pointing to the same owner @@ -248,7 +250,7 @@ def handle_group_owners(project, group, issue_owners): ) user_id = None team_id = None - if owner_type is User: + if owner_type is APIUser: user_id = owner_id if owner_type is Team: team_id = owner_id diff --git a/src/sentry/testutils/factories.py b/src/sentry/testutils/factories.py index 2f20d9500beb7b..9eabbbdaad1d98 100644 --- a/src/sentry/testutils/factories.py +++ b/src/sentry/testutils/factories.py @@ -1288,12 +1288,12 @@ def create_identity_provider(integration: Integration, **kwargs: Any) -> Identit @staticmethod @exempt_from_silo_limits() def create_identity( - user: User, identity_provider: IdentityProvider, external_id: str, **kwargs: Any + user: Any, identity_provider: IdentityProvider, external_id: str, **kwargs: Any ) -> Identity: return Identity.objects.create( external_id=external_id, idp=identity_provider, - user=user, + user_id=user.id, status=IdentityStatus.VALID, scopes=[], ) diff --git a/src/sentry/testutils/fixtures.py b/src/sentry/testutils/fixtures.py index 94e1dca1dc26fa..72546db1779c79 100644 --- a/src/sentry/testutils/fixtures.py +++ b/src/sentry/testutils/fixtures.py @@ -11,7 +11,7 @@ OrganizationMember, OrganizationMemberTeam, ) -from sentry.models.user import User +from sentry.services.hybrid_cloud.user import APIUser from sentry.testutils.factories import Factories from sentry.testutils.helpers.datetime import before_now, iso_format @@ -376,7 +376,7 @@ def create_slack_integration( self, organization: ""Organization"", external_id: str = ""TXXXXXXX1"", - user: User = None, + user: APIUser = None, identity_external_id: str = ""UXXXXXXX1"", **kwargs: Any, ): diff --git a/src/sentry/testutils/helpers/notifications.py b/src/sentry/testutils/helpers/notifications.py index f98f72c24f2f0d..9c24607fe28fc5 100644 --- a/src/sentry/testutils/helpers/notifications.py +++ b/src/sentry/testutils/helpers/notifications.py @@ -4,6 +4,7 @@ from sentry.models import Team, User from sentry.notifications.notifications.base import BaseNotification +from sentry.services.hybrid_cloud.user import APIUser from sentry.types.integrations import ExternalProviders @@ -15,7 +16,7 @@ class DummyNotification(BaseNotification): def get_subject(self, context: Mapping[str, Any] | None = None) -> str: pass - def determine_recipients(self) -> Iterable[Team | User]: + def determine_recipients(self) -> Iterable[Team | APIUser]: return [] def build_attachment_title(self, *args): diff --git a/src/sentry/testutils/silo.py b/src/sentry/testutils/silo.py index 55df63bc1e0003..d6cc7c6ae87ddb 100644 --- a/src/sentry/testutils/silo.py +++ b/src/sentry/testutils/silo.py @@ -11,9 +11,17 @@ from django.test import override_settings from sentry.silo import SiloMode +from sentry.testutils.region import override_regions +from sentry.types.region import Region, RegionCategory TestMethod = Callable[..., None] +region_map = [ + Region(""north_america"", 1, ""na.sentry.io"", RegionCategory.MULTI_TENANT), + Region(""europe"", 2, ""eu.sentry.io"", RegionCategory.MULTI_TENANT), + Region(""acme-single-tenant"", 3, ""acme.my.sentry.io"", RegionCategory.SINGLE_TENANT), +] + class SiloModeTest: """"""Decorate a test case that is expected to work in a given silo mode. @@ -40,7 +48,12 @@ def _create_mode_methods(self, test_method: TestMethod) -> Iterable[Tuple[str, T def method_for_mode(mode: SiloMode) -> Iterable[Tuple[str, TestMethod]]: def replacement_test_method(*args: Any, **kwargs: Any) -> None: with override_settings(SILO_MODE=mode): - test_method(*args, **kwargs) + with override_regions(region_map): + if mode == SiloMode.REGION: + with override_settings(SENTRY_REGION=""north_america""): + test_method(*args, **kwargs) + else: + test_method(*args, **kwargs) functools.update_wrapper(replacement_test_method, test_method) modified_name = f""{test_method.__name__}__in_{str(mode).lower()}_silo"" @@ -67,8 +80,14 @@ def receive_decorated_obj(f: Any) -> Any: def _mark_parameterized_by_silo_mode(self, test_method: TestMethod) -> TestMethod: def replacement_test_method(*args: Any, **kwargs: Any) -> None: - with override_settings(SILO_MODE=kwargs.pop(""silo_mode"")): - return test_method(*args, **kwargs) + silo_mode = kwargs.pop(""silo_mode"") + with override_settings(SILO_MODE=silo_mode): + with override_regions(region_map): + if silo_mode == SiloMode.REGION: + with override_settings(SENTRY_REGION=""north_america""): + test_method(*args, **kwargs) + else: + test_method(*args, **kwargs) orig_sig = inspect.signature(test_method) new_test_method = functools.update_wrapper(replacement_test_method, test_method) diff --git a/src/sentry/utils/email/manager.py b/src/sentry/utils/email/manager.py index f5beb26511e2a8..7295b6ec47df44 100644 --- a/src/sentry/utils/email/manager.py +++ b/src/sentry/utils/email/manager.py @@ -3,7 +3,9 @@ import logging from typing import Iterable, Mapping -from sentry.models import Project, User, UserEmail, UserOption +from sentry.models import Project, UserEmail +from sentry.services.hybrid_cloud.user import user_service +from sentry.services.hybrid_cloud.user_option import user_option_service from .faker import is_fake_email @@ -21,7 +23,7 @@ def get_email_addresses( results = {} if project: - queryset = UserOption.objects.filter(project=project, user__in=pending, key=""mail:email"") + queryset = user_option_service.get(user_ids=pending, project=project, key=""mail:email"") for option in (o for o in queryset if o.value and not is_fake_email(o.value)): if UserEmail.objects.filter(user=option.user, email=option.value).exists(): results[option.user_id] = option.value @@ -31,8 +33,8 @@ def get_email_addresses( option.delete() if pending: - queryset = User.objects.filter(pk__in=pending, is_active=True) - for (user_id, email) in queryset.values_list(""id"", ""email""): + users = user_service.get_many(pending) + for (user_id, email) in [(user.id, user.email) for user in users]: if email and not is_fake_email(email): results[user_id] = email pending.discard(user_id) diff --git a/tests/sentry/mail/activity/test_note.py b/tests/sentry/mail/activity/test_note.py index f967e9ca0304eb..cc21277935a576 100644 --- a/tests/sentry/mail/activity/test_note.py +++ b/tests/sentry/mail/activity/test_note.py @@ -5,6 +5,7 @@ NotificationSettingOptionValues, NotificationSettingTypes, ) +from sentry.services.hybrid_cloud.user import user_service from sentry.testutils.cases import ActivityTestCase from sentry.types.activity import ActivityType from sentry.types.integrations import ExternalProviders @@ -41,7 +42,7 @@ def test_allow_self_notifications(self): ] assert len(participants) == 1 assert participants == { - self.user: GroupSubscriptionReason.implicit, + user_service.serialize_user(self.user): GroupSubscriptionReason.implicit, } def test_disable_self_notifications(self): diff --git a/tests/sentry/migrations/test_0311_backfill_slack_settings.py b/tests/sentry/migrations/test_0311_backfill_slack_settings.py index dccb3561a29481..7f4edbbb76e327 100644 --- a/tests/sentry/migrations/test_0311_backfill_slack_settings.py +++ b/tests/sentry/migrations/test_0311_backfill_slack_settings.py @@ -3,7 +3,7 @@ from django.test.utils import override_settings from django.utils import timezone -from sentry.models import ExternalActor, Integration, NotificationSetting, Team, User +from sentry.models import ExternalActor, Integration, NotificationSetting, Team from sentry.notifications.types import ( NotificationScopeType, NotificationSettingOptionValues, @@ -20,7 +20,7 @@ def get_scope_type_from_entity(entity): - if isinstance(entity, User): + if entity.class_name() == ""User"": return NotificationScopeType.USER if isinstance(entity, Team): return NotificationScopeType.TEAM diff --git a/tests/sentry/models/test_auditlogentry.py b/tests/sentry/models/test_auditlogentry.py index 3cacc755b13794..fb524e60acf678 100644 --- a/tests/sentry/models/test_auditlogentry.py +++ b/tests/sentry/models/test_auditlogentry.py @@ -3,8 +3,10 @@ from sentry import audit_log from sentry.models import AuditLogEntry from sentry.testutils import TestCase +from sentry.testutils.silo import control_silo_test +@control_silo_test(stable=True) class AuditLogEntryTest(TestCase): def test_audit_log_entry(self): AuditLogEntry.objects.create( diff --git a/tests/sentry/models/test_commit.py b/tests/sentry/models/test_commit.py index 6a51fd8d4621cc..24319f4795e890 100644 --- a/tests/sentry/models/test_commit.py +++ b/tests/sentry/models/test_commit.py @@ -3,8 +3,10 @@ from sentry.models import Commit, Repository from sentry.testutils import TestCase +from sentry.testutils.silo import region_silo_test +@region_silo_test(stable=True) class FindReferencedGroupsTest(TestCase): def test_multiple_matches_basic(self): group = self.create_group() diff --git a/tests/sentry/models/test_commitfilechange.py b/tests/sentry/models/test_commitfilechange.py index ca7e4c8ff2b7e2..6db584b3facf35 100644 --- a/tests/sentry/models/test_commitfilechange.py +++ b/tests/sentry/models/test_commitfilechange.py @@ -1,7 +1,9 @@ from sentry.models import Commit, CommitFileChange, Repository from sentry.testutils import TestCase +from sentry.testutils.silo import region_silo_test +@region_silo_test(stable=True) class CommitFileChangeTest(TestCase): def test_get_count_for_commits(self): group = self.create_group() diff --git a/tests/sentry/models/test_debugfile.py b/tests/sentry/models/test_debugfile.py index 9caa37548c0cd7..d1d776bc4f1b2d 100644 --- a/tests/sentry/models/test_debugfile.py +++ b/tests/sentry/models/test_debugfile.py @@ -8,6 +8,7 @@ from sentry.models import DifMeta, File, ProjectDebugFile, debugfile from sentry.testutils import APITestCase, TestCase +from sentry.testutils.silo import region_silo_test # This is obviously a freely generated UUID and not the checksum UUID. # This is permissible if users want to send different UUIDs @@ -20,6 +21,7 @@ """""" +@region_silo_test(stable=True) class DebugFileTest(TestCase): def test_delete_dif(self): dif = self.create_dif_file( diff --git a/tests/sentry/models/test_deploy.py b/tests/sentry/models/test_deploy.py index 253fe53524b0ac..34461af9b07811 100644 --- a/tests/sentry/models/test_deploy.py +++ b/tests/sentry/models/test_deploy.py @@ -1,8 +1,10 @@ from sentry.models import Activity, Commit, Deploy, Environment, Release, ReleaseHeadCommit from sentry.testutils import TestCase +from sentry.testutils.silo import region_silo_test from sentry.types.activity import ActivityType +@region_silo_test(stable=True) class DeployNotifyTest(TestCase): def test_notify_if_ready_long_release(self): org = self.create_organization() diff --git a/tests/sentry/models/test_environment.py b/tests/sentry/models/test_environment.py index c24116bd03e006..986ea8151c1886 100644 --- a/tests/sentry/models/test_environment.py +++ b/tests/sentry/models/test_environment.py @@ -2,8 +2,10 @@ from sentry.models import Environment from sentry.testutils import TestCase +from sentry.testutils.silo import region_silo_test +@region_silo_test(stable=True) class GetOrCreateTest(TestCase): def test_simple(self): project = self.create_project() diff --git a/tests/sentry/models/test_eventuser.py b/tests/sentry/models/test_eventuser.py index df50ea22c89843..3d455d4600da92 100644 --- a/tests/sentry/models/test_eventuser.py +++ b/tests/sentry/models/test_eventuser.py @@ -5,7 +5,7 @@ from sentry.testutils.silo import region_silo_test -@region_silo_test +@region_silo_test(stable=True) class EventUserTestCase(TestCase): def test_build_hash(self): cases = [ diff --git a/tests/sentry/models/test_group.py b/tests/sentry/models/test_group.py index 802c4e7173a7e9..df754b0aa3be5d 100644 --- a/tests/sentry/models/test_group.py +++ b/tests/sentry/models/test_group.py @@ -20,7 +20,7 @@ from sentry.testutils.silo import region_silo_test -@region_silo_test +@region_silo_test(stable=True) class GroupTest(TestCase, SnubaTestCase): def setUp(self): super().setUp() diff --git a/tests/sentry/models/test_groupassignee.py b/tests/sentry/models/test_groupassignee.py index c76ff00dd6a566..08978374a13ec5 100644 --- a/tests/sentry/models/test_groupassignee.py +++ b/tests/sentry/models/test_groupassignee.py @@ -12,12 +12,13 @@ Integration, OrganizationIntegration, ) +from sentry.services.hybrid_cloud.user import user_service from sentry.testutils import TestCase from sentry.testutils.silo import region_silo_test from sentry.types.activity import ActivityType -@region_silo_test +@region_silo_test(stable=True) class GroupAssigneeTestCase(TestCase): def test_constraints(self): # Can't both be assigned @@ -153,7 +154,7 @@ def test_assignee_sync_outbound_assign(self, mock_sync_assignee_outbound): GroupAssignee.objects.assign(self.group, self.user) mock_sync_assignee_outbound.assert_called_with( - external_issue, self.user, assign=True + external_issue, user_service.serialize_user(self.user), assign=True ) assert GroupAssignee.objects.filter( diff --git a/tests/sentry/models/test_grouphistory.py b/tests/sentry/models/test_grouphistory.py index 39c56144a77064..651d82c165cd42 100644 --- a/tests/sentry/models/test_grouphistory.py +++ b/tests/sentry/models/test_grouphistory.py @@ -3,7 +3,7 @@ from sentry.testutils.silo import region_silo_test -@region_silo_test +@region_silo_test(stable=True) class FilterToTeamTest(TestCase): def test(self): GroupAssignee.objects.assign(self.group, self.user) diff --git a/tests/sentry/models/test_groupinbox.py b/tests/sentry/models/test_groupinbox.py index 80e598875c029c..b296603f89cd58 100644 --- a/tests/sentry/models/test_groupinbox.py +++ b/tests/sentry/models/test_groupinbox.py @@ -13,7 +13,7 @@ from sentry.types.activity import ActivityType -@region_silo_test +@region_silo_test(stable=True) class GroupInboxTestCase(TestCase): @patch(""sentry.signals.inbox_in.send_robust"") def test_add_to_inbox(self, inbox_in): diff --git a/tests/sentry/models/test_groupmeta.py b/tests/sentry/models/test_groupmeta.py index 840358498a79cf..eb9c7aac8411f4 100644 --- a/tests/sentry/models/test_groupmeta.py +++ b/tests/sentry/models/test_groupmeta.py @@ -5,7 +5,7 @@ from sentry.testutils.silo import region_silo_test -@region_silo_test +@region_silo_test(stable=True) class GroupMetaManagerTest(TestCase): def test_set_value(self): GroupMeta.objects.set_value(self.group, ""foo"", ""bar"") diff --git a/tests/sentry/models/test_grouprelease.py b/tests/sentry/models/test_grouprelease.py index 9ab9b23bda33b3..83c3ef78ed9687 100644 --- a/tests/sentry/models/test_grouprelease.py +++ b/tests/sentry/models/test_grouprelease.py @@ -4,8 +4,10 @@ from sentry.models import Environment, GroupRelease, Release from sentry.testutils import TestCase +from sentry.testutils.silo import region_silo_test +@region_silo_test(stable=True) class GetOrCreateTest(TestCase): def test_simple(self): project = self.create_project() diff --git a/tests/sentry/models/test_groupresolution.py b/tests/sentry/models/test_groupresolution.py index 480420820aa6eb..99d1b688adb4ca 100644 --- a/tests/sentry/models/test_groupresolution.py +++ b/tests/sentry/models/test_groupresolution.py @@ -7,7 +7,7 @@ from sentry.testutils.silo import region_silo_test -@region_silo_test +@region_silo_test(stable=True) class GroupResolutionTest(TestCase): def setUp(self): super().setUp() diff --git a/tests/sentry/models/test_groupsnooze.py b/tests/sentry/models/test_groupsnooze.py index 447ac89c9d7649..5278c041dec93c 100644 --- a/tests/sentry/models/test_groupsnooze.py +++ b/tests/sentry/models/test_groupsnooze.py @@ -13,7 +13,7 @@ from sentry.types.issues import GroupType -@region_silo_test +@region_silo_test(stable=True) class GroupSnoozeTest(TestCase, SnubaTestCase, PerfIssueTransactionTestMixin): sequence = itertools.count() # generates unique values, class scope doesn't matter diff --git a/tests/sentry/models/test_groupsubscription.py b/tests/sentry/models/test_groupsubscription.py index 4d7fd2d7ac9d9b..3e175410bb8048 100644 --- a/tests/sentry/models/test_groupsubscription.py +++ b/tests/sentry/models/test_groupsubscription.py @@ -6,10 +6,13 @@ NotificationSettingOptionValues, NotificationSettingTypes, ) +from sentry.services.hybrid_cloud.user import user_service from sentry.testutils import TestCase +from sentry.testutils.silo import region_silo_test from sentry.types.integrations import ExternalProviders +@region_silo_test(stable=True) class SubscribeTest(TestCase): def test_simple(self): group = self.create_group() @@ -83,6 +86,7 @@ def test_actor_team(self): GroupSubscription.objects.subscribe_actor(group=group, actor=team) +@region_silo_test class GetParticipantsTest(TestCase): def setUp(self): self.org = self.create_organization() @@ -92,6 +96,7 @@ def setUp(self): self.user = self.create_user() self.create_member(user=self.user, organization=self.org, teams=[self.team]) self.update_user_settings_always() + self.user = user_service.serialize_user(self.user) def update_user_settings_always(self): NotificationSetting.objects.update_settings( @@ -159,7 +164,7 @@ def test_simple(self): # unsubscribed GroupSubscription.objects.create( - user=self.user, group=group, project=project, is_active=False + user_id=self.user.id, group=group, project=project, is_active=False ) users = GroupSubscription.objects.get_participants(group=group) @@ -167,7 +172,7 @@ def test_simple(self): assert users == {} # not participating by default - GroupSubscription.objects.filter(user=self.user, group=group).delete() + GroupSubscription.objects.filter(user_id=self.user.id, group=group).delete() self.update_user_setting_subscribe_only() @@ -177,7 +182,7 @@ def test_simple(self): # explicitly participating GroupSubscription.objects.create( - user=self.user, + user_id=self.user.id, group=group, project=project, is_active=True, @@ -222,7 +227,7 @@ def test_no_conversations(self): # Explicit subscription, overridden by the global option. GroupSubscription.objects.create( - user=self.user, + user_id=self.user.id, group=self.group, project=self.project, is_active=True, @@ -317,7 +322,7 @@ def test_participating_only(self): }, ): subscription = GroupSubscription.objects.create( - user=self.user, + user_id=self.user.id, group=self.group, project=self.project, is_active=True, @@ -339,7 +344,7 @@ def test_participating_only(self): }, ): subscription = GroupSubscription.objects.create( - user=self.user, + user_id=self.user.id, group=self.group, project=self.project, is_active=True, @@ -363,7 +368,7 @@ def test_participating_only(self): }, ): subscription = GroupSubscription.objects.create( - user=self.user, + user_id=self.user.id, group=self.group, project=self.project, is_active=True, @@ -385,7 +390,7 @@ def test_participating_only(self): }, ): subscription = GroupSubscription.objects.create( - user=self.user, + user_id=self.user.id, group=self.group, project=self.project, is_active=True, diff --git a/tests/sentry/models/test_identity.py b/tests/sentry/models/test_identity.py index 99672a5c1be5e4..0700b340c6427e 100644 --- a/tests/sentry/models/test_identity.py +++ b/tests/sentry/models/test_identity.py @@ -2,13 +2,14 @@ from sentry.identity.providers.dummy import DummyProvider from sentry.models import Identity, IdentityProvider from sentry.testutils import TestCase -from sentry.testutils.silo import control_silo_test +from sentry.testutils.silo import exempt_from_silo_limits, region_silo_test -@control_silo_test +@region_silo_test(stable=True) class IdentityTestCase(TestCase): def test_get_provider(self): - provider_model = IdentityProvider.objects.create(type=""dummy"", external_id=""tester_id"") + with exempt_from_silo_limits(): + provider_model = IdentityProvider.objects.create(type=""dummy"", external_id=""tester_id"") register(DummyProvider) identity_model = Identity.objects.create( diff --git a/tests/sentry/models/test_organization.py b/tests/sentry/models/test_organization.py index e0f7349625df38..7cc6a566c07749 100644 --- a/tests/sentry/models/test_organization.py +++ b/tests/sentry/models/test_organization.py @@ -178,7 +178,7 @@ def test_merge_to(self): def test_get_default_owner(self): user = self.create_user(""foo@example.com"") org = self.create_organization(owner=user) - assert org.get_default_owner() == user + assert org.get_default_owner().id == user.id def test_default_owner_id(self): user = self.create_user(""foo@example.com"") diff --git a/tests/sentry/models/test_projectownership.py b/tests/sentry/models/test_projectownership.py index 0604975b6397c4..0ad2003d064914 100644 --- a/tests/sentry/models/test_projectownership.py +++ b/tests/sentry/models/test_projectownership.py @@ -1,6 +1,7 @@ from sentry.models import ActorTuple, GroupAssignee, ProjectOwnership, Repository, Team, User from sentry.models.groupowner import GroupOwner, GroupOwnerType, OwnerRuleType from sentry.ownership.grammar import Matcher, Owner, Rule, dump_schema, resolve_actors +from sentry.services.hybrid_cloud.user import UserService from sentry.testutils import TestCase from sentry.testutils.helpers.datetime import before_now, iso_format from sentry.testutils.silo import region_silo_test @@ -253,7 +254,7 @@ def test_get_issue_owners_when_codeowners_and_issueowners_exists(self): assert ProjectOwnership.get_issue_owners( self.project.id, {""stacktrace"": {""frames"": [{""filename"": ""src/foo.py""}]}} ) == [ - (rule_b, [self.user], OwnerRuleType.OWNERSHIP_RULE.value), + (rule_b, [UserService.serialize_user(self.user)], OwnerRuleType.OWNERSHIP_RULE.value), (rule_a, [self.team], OwnerRuleType.OWNERSHIP_RULE.value), ] diff --git a/tests/sentry/notifications/notifications/test_organization_request.py b/tests/sentry/notifications/notifications/test_organization_request.py index 927a84b0675b12..e67fe7619b75d3 100644 --- a/tests/sentry/notifications/notifications/test_organization_request.py +++ b/tests/sentry/notifications/notifications/test_organization_request.py @@ -4,6 +4,7 @@ RoleBasedRecipientStrategy, ) from sentry.notifications.types import NotificationSettingOptionValues, NotificationSettingTypes +from sentry.services.hybrid_cloud.user import user_service from sentry.testutils import TestCase from sentry.types.integrations import ExternalProviders @@ -27,9 +28,12 @@ def setUp(self): def test_default_to_slack(self): notification = DummyRequestNotification(self.organization, self.user) + api_user = user_service.serialize_user(self.user) + api_user_2 = user_service.serialize_user(self.user2) + assert notification.get_participants() == { - ExternalProviders.EMAIL: {self.user, self.user2}, - ExternalProviders.SLACK: {self.user, self.user2}, + ExternalProviders.EMAIL: {api_user, api_user_2}, + ExternalProviders.SLACK: {api_user, api_user_2}, } def test_turn_off_settings(self): @@ -49,7 +53,10 @@ def test_turn_off_settings(self): notification = DummyRequestNotification(self.organization, self.user) + api_user = user_service.serialize_user(self.user) + api_user_2 = user_service.serialize_user(self.user2) + assert notification.get_participants() == { - ExternalProviders.EMAIL: {self.user, self.user2}, - ExternalProviders.SLACK: {self.user, self.user2}, + ExternalProviders.EMAIL: {api_user, api_user_2}, + ExternalProviders.SLACK: {api_user, api_user_2}, } diff --git a/tests/sentry/notifications/utils/test_participants.py b/tests/sentry/notifications/utils/test_participants.py index 09a838f4a4749c..45cbb55ec7e82b 100644 --- a/tests/sentry/notifications/utils/test_participants.py +++ b/tests/sentry/notifications/utils/test_participants.py @@ -11,6 +11,7 @@ from sentry.notifications.utils.participants import get_owners, get_release_committers, get_send_to from sentry.ownership import grammar from sentry.ownership.grammar import Matcher, Owner, Rule, dump_schema +from sentry.services.hybrid_cloud.user import APIUser, UserService, user_service from sentry.testutils import TestCase from sentry.testutils.helpers.datetime import before_now, iso_format from sentry.testutils.silo import region_silo_test @@ -34,8 +35,8 @@ def test_invalid_user(self): def test_send_to_user(self): assert self.get_send_to_member() == { - ExternalProviders.EMAIL: {self.user}, - ExternalProviders.SLACK: {self.user}, + ExternalProviders.EMAIL: {user_service.serialize_user(self.user)}, + ExternalProviders.SLACK: {user_service.serialize_user(self.user)}, } NotificationSetting.objects.update_settings( @@ -46,7 +47,9 @@ def test_send_to_user(self): project=self.project, ) - assert self.get_send_to_member() == {ExternalProviders.SLACK: {self.user}} + assert self.get_send_to_member() == { + ExternalProviders.SLACK: {user_service.serialize_user(self.user)} + } def test_other_org_user(self): org_2 = self.create_organization() @@ -56,8 +59,8 @@ def test_other_org_user(self): project_2 = self.create_project(organization=org_2, teams=[team_2, team_3]) assert self.get_send_to_member(project_2, user_2.id) == { - ExternalProviders.EMAIL: {user_2}, - ExternalProviders.SLACK: {user_2}, + ExternalProviders.EMAIL: {user_service.serialize_user(user_2)}, + ExternalProviders.SLACK: {user_service.serialize_user(user_2)}, } assert self.get_send_to_member(self.project, user_2.id) == {} @@ -70,8 +73,8 @@ def test_no_project_access(self): project_2 = self.create_project(organization=org_2, teams=[team_2]) assert self.get_send_to_member(project_2, user_2.id) == { - ExternalProviders.EMAIL: {user_2}, - ExternalProviders.SLACK: {user_2}, + ExternalProviders.EMAIL: {user_service.serialize_user(user_2)}, + ExternalProviders.SLACK: {user_service.serialize_user(user_2)}, } assert self.get_send_to_member(self.project, user_3.id) == {} @@ -108,7 +111,7 @@ def test_invalid_team(self): def test_send_to_team(self): assert self.get_send_to_team() == { - ExternalProviders.EMAIL: {self.user}, + ExternalProviders.EMAIL: {user_service.serialize_user(self.user)}, } NotificationSetting.objects.update_settings( @@ -136,7 +139,9 @@ def test_send_to_team_direct(self): NotificationSettingOptionValues.NEVER, team=self.team, ) - assert self.get_send_to_team() == {ExternalProviders.EMAIL: {self.user}} + assert self.get_send_to_team() == { + ExternalProviders.EMAIL: {user_service.serialize_user(self.user)} + } def test_other_project_team(self): user_2 = self.create_user() @@ -144,8 +149,8 @@ def test_other_project_team(self): project_2 = self.create_project(organization=self.organization, teams=[team_2]) assert self.get_send_to_team(project_2, team_2.id) == { - ExternalProviders.EMAIL: {user_2}, - ExternalProviders.SLACK: {user_2}, + ExternalProviders.EMAIL: {user_service.serialize_user(user_2)}, + ExternalProviders.SLACK: {user_service.serialize_user(user_2)}, } assert self.get_send_to_team(self.project, team_2.id) == {} @@ -156,8 +161,8 @@ def test_other_org_team(self): project_2 = self.create_project(organization=org_2, teams=[team_2]) assert self.get_send_to_team(project_2, team_2.id) == { - ExternalProviders.EMAIL: {user_2}, - ExternalProviders.SLACK: {user_2}, + ExternalProviders.EMAIL: {user_service.serialize_user(user_2)}, + ExternalProviders.SLACK: {user_service.serialize_user(user_2)}, } assert self.get_send_to_team(self.project, team_2.id) == {} @@ -201,8 +206,8 @@ def test_default_committer(self, spy_get_release_committers): event.group = self.group with self.feature(""organizations:active-release-notifications-enable""): assert self.get_send_to_release_members(event) == { - ExternalProviders.EMAIL: {self.user}, - ExternalProviders.SLACK: {self.user}, + ExternalProviders.EMAIL: {user_service.serialize_user(self.user)}, + ExternalProviders.SLACK: {user_service.serialize_user(self.user)}, } assert spy_get_release_committers.call_count == 1 @@ -279,8 +284,8 @@ def test_single_user(self): event = self.store_event(""user.jsx"") assert self.get_send_to_owners(event) == { - ExternalProviders.EMAIL: {self.user}, - ExternalProviders.SLACK: {self.user}, + ExternalProviders.EMAIL: {UserService.serialize_user(self.user)}, + ExternalProviders.SLACK: {UserService.serialize_user(self.user)}, } # Make sure that disabling mail alerts works as expected @@ -293,7 +298,7 @@ def test_single_user(self): ) assert self.get_send_to_owners(event) == { - ExternalProviders.SLACK: {self.user}, + ExternalProviders.SLACK: {UserService.serialize_user(self.user)}, } def test_single_user_no_teams(self): @@ -305,8 +310,14 @@ def test_team_owners(self): event = self.store_event(""team.py"") assert self.get_send_to_owners(event) == { - ExternalProviders.EMAIL: {self.user, self.user2}, - ExternalProviders.SLACK: {self.user, self.user2}, + ExternalProviders.EMAIL: { + user_service.serialize_user(self.user), + user_service.serialize_user(self.user2), + }, + ExternalProviders.SLACK: { + user_service.serialize_user(self.user), + user_service.serialize_user(self.user2), + }, } # Make sure that disabling mail alerts works as expected @@ -318,8 +329,11 @@ def test_team_owners(self): project=self.project, ) assert self.get_send_to_owners(event) == { - ExternalProviders.EMAIL: {self.user}, - ExternalProviders.SLACK: {self.user, self.user2}, + ExternalProviders.EMAIL: {user_service.serialize_user(self.user)}, + ExternalProviders.SLACK: { + user_service.serialize_user(self.user), + user_service.serialize_user(self.user2), + }, } def test_disable_alerts_multiple_scopes(self): @@ -343,16 +357,22 @@ def test_disable_alerts_multiple_scopes(self): ) assert self.get_send_to_owners(event) == { - ExternalProviders.EMAIL: {self.user}, - ExternalProviders.SLACK: {self.user}, + ExternalProviders.EMAIL: {UserService.serialize_user(self.user)}, + ExternalProviders.SLACK: {UserService.serialize_user(self.user)}, } def test_fallthrough(self): event = self.store_event(""no_rule.cpp"") assert self.get_send_to_owners(event) == { - ExternalProviders.EMAIL: {self.user, self.user2}, - ExternalProviders.SLACK: {self.user, self.user2}, + ExternalProviders.EMAIL: { + UserService.serialize_user(self.user), + UserService.serialize_user(self.user2), + }, + ExternalProviders.SLACK: { + UserService.serialize_user(self.user), + UserService.serialize_user(self.user2), + }, } def test_without_fallthrough(self): @@ -409,11 +429,14 @@ def create_ownership( ) def assert_recipients( - self, expected: Iterable[Union[Team, User]], received: Iterable[Union[Team, User]] + self, expected: Iterable[Union[Team, User]], received: Iterable[Union[Team, APIUser]] ) -> None: assert len(expected) == len(received) for recipient in expected: - assert recipient in received + if isinstance(recipient, User): + assert UserService.serialize_user(recipient) in received + else: + assert recipient in received # If no event to match, we assume fallthrough is enabled def test_get_owners_no_event(self):" df3ae77fa1ccc0e22cb7f505c49dcf01c72fa7b7,2023-10-23 13:39:36,Luca Forstner,fix(source-map-debugger): Only show the source map debugger for frames with valid file ending (#58509),False,Only show the source map debugger for frames with valid file ending (#58509),fix,"diff --git a/static/app/components/events/interfaces/frame/deprecatedLine.tsx b/static/app/components/events/interfaces/frame/deprecatedLine.tsx index 26bc6ca453b2d9..3eed118a1aecc6 100644 --- a/static/app/components/events/interfaces/frame/deprecatedLine.tsx +++ b/static/app/components/events/interfaces/frame/deprecatedLine.tsx @@ -50,6 +50,13 @@ import { isExpandable, } from './utils'; +const VALID_SOURCE_MAP_DEBUGGER_FILE_ENDINGS = [ + '.js', + '.mjs', + '.cjs', + '.jsbundle', // React Native file ending +]; + export interface DeprecatedLineProps { data: Frame; event: Event; @@ -313,9 +320,15 @@ export class DeprecatedLine extends Component { lockAddress ); - const shouldShowSourceMapDebuggerToggle = + const frameHasValidFileEndingForSourceMapDebugger = + VALID_SOURCE_MAP_DEBUGGER_FILE_ENDINGS.some(ending => + (data.absPath || data.filename || '').endsWith(ending) + ); + + const shouldShowSourceMapDebuggerButton = !this.props.hideSourceMapDebugger && data.inApp && + frameHasValidFileEndingForSourceMapDebugger && this.props.frameSourceResolutionResults && (!this.props.frameSourceResolutionResults.frameIsResolved || !hasContextSource(data)); @@ -358,7 +371,7 @@ export class DeprecatedLine extends Component { ) : null} {this.renderShowHideToggle()} - {shouldShowSourceMapDebuggerToggle ? ( + {shouldShowSourceMapDebuggerButton ? ( { + const {meta, data} = this.props.result; + + const colName = meta[columnIndex].name; + + return ( + + {rowIndex === 0 ? ( + {colName} + ) : ( + {getDisplayValue(data[rowIndex - 1][colName])} + )} + + ); + }; + renderTable() { const {meta, data} = this.props.result; return ( - - - {meta.map(({name}, idx) => {name})} - - - {data.map((row, rowIdx) => { - return ( - - {meta.map((val, colIdx) => ( - - - {getDisplayValue(row[meta[colIdx].name])} - - - ))} - - ); - })} - - + ); } @@ -50,7 +57,7 @@ export default class Result extends React.Component { } return ( -
+
snuba query time: {timing.duration_ms}ms, {data.length} rows @@ -60,16 +67,12 @@ export default class Result extends React.Component { } } -const Summary = styled(Box)` - font-size: 12px; +const Cell = styled('div')` + overflow: scroll; + font-size: 14px; + padding: 1px; `; -const StyledTable = styled.table` - font-size: 14px; - tbody > tr > td, - thead > tr > th { - padding: 8px; - max-width: 100px; - overflow: scroll; - } +const Summary = styled(Box)` + font-size: 12px; `; diff --git a/yarn.lock b/yarn.lock index 39f4b87ac10970..88da117d6813a4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2466,6 +2466,10 @@ classnames@2.2.0: version ""2.2.0"" resolved ""https://registry.yarnpkg.com/classnames/-/classnames-2.2.0.tgz#8f61df81f356c45d18a31d83fde4dfb194ea8722"" +classnames@^2.2.3: + version ""2.2.6"" + resolved ""https://registry.yarnpkg.com/classnames/-/classnames-2.2.6.tgz#43935bffdd291f326dad0a205309b38d00f650ce"" + classnames@^2.2.4, classnames@^2.2.5: version ""2.2.5"" resolved ""https://registry.yarnpkg.com/classnames/-/classnames-2.2.5.tgz#fb3801d453467649ef3603c7d61a02bd129bde6d"" @@ -3331,14 +3335,14 @@ doctrine@^2.0.0: dependencies: esutils ""^2.0.2"" +""dom-helpers@^2.4.0 || ^3.0.0"", dom-helpers@^3.2.1: + version ""3.3.1"" + resolved ""https://registry.yarnpkg.com/dom-helpers/-/dom-helpers-3.3.1.tgz#fc1a4e15ffdf60ddde03a480a9c0fece821dd4a6"" + dom-helpers@^3.2.0: version ""3.2.1"" resolved ""https://registry.yarnpkg.com/dom-helpers/-/dom-helpers-3.2.1.tgz#3203e07fed217bd1f424b019735582fc37b2825a"" -dom-helpers@^3.2.1: - version ""3.3.1"" - resolved ""https://registry.yarnpkg.com/dom-helpers/-/dom-helpers-3.3.1.tgz#fc1a4e15ffdf60ddde03a480a9c0fece821dd4a6"" - dom-serializer@0, dom-serializer@~0.1.0: version ""0.1.0"" resolved ""https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.0.tgz#073c697546ce0780ce23be4a28e293e40bc30c82"" @@ -5779,6 +5783,10 @@ js-tokens@^3.0.0, js-tokens@^3.0.2: version ""3.0.2"" resolved ""https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b"" +""js-tokens@^3.0.0 || ^4.0.0"": + version ""4.0.0"" + resolved ""https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"" + js-yaml@^3.4.3, js-yaml@^3.7.0, js-yaml@^3.9.0, js-yaml@^3.9.1, js-yaml@~3.10.0: version ""3.10.0"" resolved ""https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.10.0.tgz#2e78441646bd4682e963f22b6e92823c309c62dc"" @@ -6280,6 +6288,12 @@ loose-envify@^1.0.0, loose-envify@^1.1.0, loose-envify@^1.2.0, loose-envify@^1.3 dependencies: js-tokens ""^3.0.0"" +loose-envify@^1.3.0: + version ""1.4.0"" + resolved ""https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"" + dependencies: + js-tokens ""^3.0.0 || ^4.0.0"" + loud-rejection@^1.0.0: version ""1.6.0"" resolved ""https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f"" @@ -8169,6 +8183,10 @@ react-lazyload@^2.3.0: version ""2.3.0"" resolved ""https://registry.yarnpkg.com/react-lazyload/-/react-lazyload-2.3.0.tgz#ccb134223012447074a96543954f44b055dc6185"" +react-lifecycles-compat@^3.0.4: + version ""3.0.4"" + resolved ""https://registry.yarnpkg.com/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz#4f1a273afdfc8f3488a8c516bfda78f872352362"" + react-mentions@^1.2.0: version ""1.2.2"" resolved ""https://registry.yarnpkg.com/react-mentions/-/react-mentions-1.2.2.tgz#db09e5ec84f3cf40d5a56bbc9fcc0f81c4c8c60b"" @@ -8326,6 +8344,17 @@ react-treebeard@^2.0.3: shallowequal ""^0.2.2"" velocity-react ""^1.3.1"" +react-virtualized@^9.20.1: + version ""9.20.1"" + resolved ""https://registry.yarnpkg.com/react-virtualized/-/react-virtualized-9.20.1.tgz#02dc08fe9070386b8c48e2ac56bce7af0208d22d"" + dependencies: + babel-runtime ""^6.26.0"" + classnames ""^2.2.3"" + dom-helpers ""^2.4.0 || ^3.0.0"" + loose-envify ""^1.3.0"" + prop-types ""^15.6.0"" + react-lifecycles-compat ""^3.0.4"" + react@16.3.2: version ""16.3.2"" resolved ""https://registry.yarnpkg.com/react/-/react-16.3.2.tgz#fdc8420398533a1e58872f59091b272ce2f91ea9""" 3682832fe266d69340cd041bde218c3ccd028dfb,2018-05-16 01:27:39,0x6a6f7368,build(travis): Spring Cleaning (#8419),False,Spring Cleaning (#8419),build,"diff --git a/.gitignore b/.gitignore index 85879037cea742..87dc41e8eecb9a 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,6 @@ test.conf pip-log.txt celerybeat-schedule sentry-package.json -/htmlcov /coverage/ /cover /build diff --git a/.travis.yml b/.travis.yml index e67d78cfd14aeb..709804f781cdbe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,19 +1,22 @@ filter_secrets: false -group: deprecated-2017Q4 + dist: trusty sudo: required +group: deprecated-2017Q4 language: python -rvm: - - 2.2 +python: 2.7 + +branches: + only: + - master + cache: + pip: true yarn: true directories: - node_modules - - $HOME/.cache/pip/wheels - $HOME/google-cloud-sdk -branches: - only: - - master + addons: apt: sources: @@ -22,29 +25,26 @@ addons: - g++-4.8 - libxmlsec1-dev chrome: stable + env: global: - - NODE_ENV=production + - NODE_ENV=development - PIP_DISABLE_PIP_VERSION_CHECK=on - SENTRY_LIGHT_BUILD=1 - SENTRY_SKIP_BACKEND_VALIDATION=1 - - TRAVIS_NODE_VERSION=8.9.1 - CXX=g++-4.8 - SOUTH_TESTS_MIGRATE=1 - - JEST_JUNIT_OUTPUT=jest.junit.xml - - DJANGO_VERSION="">=1.6,<1.7"" -install: - - 'export PATH=$PATH:~/.bin' - - nvm install $TRAVIS_NODE_VERSION - - npm install -g yarn@1.3.2 - - make travis-install-$TEST_SUITE -before_script: - - pip freeze + - DJANGO_VERSION="">=1.6.11,<1.7"" + - NPM_VERSION=""8.9.1"" + - YARN_VERSION=""1.3.2"" + script: - make travis-lint-$TEST_SUITE - make travis-test-$TEST_SUITE - make travis-scan-$TEST_SUITE + after_success: + - pip install codecov - codecov -e TEST_SUITE - npm install -g @zeus-ci/cli - zeus upload -t ""text/xml+xunit"" junit.xml @@ -55,6 +55,7 @@ after_success: - zeus upload -t ""text/plain+pycodestyle"" flake8.pycodestyle.log - zeus upload -t ""text/xml+checkstyle"" eslint.checkstyle.xml - zeus upload -t ""application/webpack-stats+json"" webpack-stats.json + after_failure: - dmesg | tail -n 100 - npm install -g @zeus-ci/cli @@ -66,7 +67,10 @@ after_failure: - zeus upload -t ""text/plain+pycodestyle"" flake8.pycodestyle.log - zeus upload -t ""text/xml+checkstyle"" eslint.checkstyle.xml - zeus upload -t ""application/webpack-stats+json"" webpack-stats.json -# each attribute in the matrix will override the global attribute + +# each job in the matrix inherits `env/global` and uses everything above, +# but custom `services`, `before_install`, `install`, and `before_script` directives +# may be defined to define and setup individual job environments with more precision. matrix: fast_finish: true include: @@ -77,51 +81,104 @@ matrix: - memcached - riak - redis-server + install: + - pip install -e "".[dev,tests,optional]"" + - python: 2.7 env: TEST_SUITE=postgres DB=postgres services: - memcached - redis-server - postgresql + install: + - pip install -e "".[dev,tests,optional]"" + before_script: + - psql -c 'create database sentry;' -U postgres + - python: 2.7 env: TEST_SUITE=network DB=postgres services: - memcached - redis-server - postgresql + install: + - pip install -e "".[dev,tests,optional]"" + before_script: + - psql -c 'create database sentry;' -U postgres + - python: 2.7 env: TEST_SUITE=mysql DB=mysql services: - memcached - mysql - redis-server + install: + - pip install -e "".[dev,tests,optional]"" + - pip install mysqlclient + before_script: + - mysql -u root -e 'create database sentry;' + - python: 2.7 env: TEST_SUITE=acceptance services: - memcached - redis-server - postgresql + install: + - pip install -e "".[dev,tests,optional]"" + - wget -N ""http://chromedriver.storage.googleapis.com/$(curl https://chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip"" -P ~/ + - unzip ~/chromedriver_linux64.zip -d ~/ + - rm ~/chromedriver_linux64.zip + - sudo install -m755 ~/chromedriver /usr/local/bin/ + before_script: + - psql -c 'create database sentry;' -U postgres + - python: 2.7 env: TEST_SUITE=js + before_install: + - nvm install ""$NPM_VERSION"" + - npm install -g ""yarn@${YARN_VERSION}"" + install: + - yarn install --pure-lockfile + - pip install $(cat requirements*.txt | grep -E 'click|pycodestyle') + - python: 2.7 env: TEST_SUITE=cli services: - postgresql - redis-server + install: + - pip install -e . + before_script: + - psql -c 'create database sentry;' -U postgres + - python: 2.7 env: TEST_SUITE=dist + - python: 2.7 - env: TEST_SUITE=postgres DJANGO_VERSION="">=1.8,<1.9"" + env: SENTRY_TAGSTORE=sentry.tagstore.v2.V2TagStorage TEST_SUITE=postgres DB=postgres services: - memcached - redis-server - postgresql + install: + - pip install -e "".[dev,tests,optional]"" + before_script: + - psql -c 'create database sentry;' -U postgres + + # django 1.8 in testing - allowed to fail - python: 2.7 - env: SENTRY_TAGSTORE=sentry.tagstore.v2.V2TagStorage TEST_SUITE=postgres DB=postgres + env: TEST_SUITE=postgres DJANGO_VERSION="">=1.8,<1.9"" services: - memcached - redis-server - postgresql + install: + - pip install -e "".[dev,tests,optional]"" + before_script: + - psql -c 'create database sentry;' -U postgres + + # snuba in testing - allowed to fail - python: 2.7 env: TEST_SUITE=snuba SENTRY_TAGSTORE=sentry.tagstore.snuba.SnubaTagStorage services: @@ -133,8 +190,12 @@ matrix: - docker run -d --name clickhouse-server -p 9000:9000 -p 9009:9009 -p 8123:8123 --ulimit nofile=262144:262144 yandex/clickhouse-server - docker run -d --env SNUBA_SETTINGS=test --env CLICKHOUSE_SERVER=clickhouse-server:9000 --name snuba -p 1218:1218 --link clickhouse-server:clickhouse-server getsentry/snuba - docker ps -a + install: + - pip install -e "".[dev,tests,optional]"" + before_script: + - psql -c 'create database sentry;' -U postgres - # Deploy 'storybook' (component & style guide) + # Deploy 'storybook' (component & style guide) - allowed to fail - language: node_js env: STORYBOOK_BUILD=1 before_install: @@ -145,15 +206,21 @@ matrix: - tar -xzf credentials.tar.gz # Use the decrypted service account credentials to authenticate the command line tool - gcloud auth activate-service-account --key-file client-secret.json + # Travis doesn't ""inherit"" steps like before_install in the build matrix, so we have to explicitly install our package managers + - nvm install ""$NPM_VERSION"" + - npm install -g ""yarn@${YARN_VERSION}"" install: - - nvm install $TRAVIS_NODE_VERSION - - make install-yarn + - yarn install --pure-lockfile - gcloud version + script: bash .travis/deploy-storybook.sh after_success: skip after_failure: skip - script: bash .travis/deploy-storybook.sh +# jobs are defined in matrix/include +# to specify which jobs are allowed to fail, match the env exactly in matrix/allow_failures allow_failures: + - python: 2.7 + env: TEST_SUITE=postgres DJANGO_VERSION="">=1.8,<1.9"" - python: 2.7 env: TEST_SUITE=snuba SENTRY_TAGSTORE=sentry.tagstore.snuba.SnubaTagStorage - language: node_js diff --git a/Makefile b/Makefile index 13e95b92d0bd14..ecc0bf72f1db3b 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,4 @@ -NPM_ROOT = ./node_modules STATIC_DIR = src/sentry/static/sentry -DJANGO_VERSION := "">=1.6,<1.7"" ifneq ""$(wildcard /usr/local/opt/libxmlsec1/lib)"" """" LDFLAGS += -L/usr/local/opt/libxmlsec1/lib @@ -10,40 +8,14 @@ ifneq ""$(wildcard /usr/local/opt/openssl/lib)"" """" endif PIP = LDFLAGS=""$(LDFLAGS)"" pip -q +WEBPACK = NODE_ENV=production ./node_modules/.bin/webpack -develop-only: update-submodules install-brew install-python install-yarn - +test: develop lint test-js test-python test-cli develop: setup-git develop-only - @echo """" - -install-yarn: - @echo ""--> Installing Node dependencies"" - @hash yarn 2> /dev/null || (echo 'Cannot continue with JavaScript dependencies. Please install yarn before proceeding. For more information refer to https://yarnpkg.com/lang/en/docs/install/'; echo 'If you are on a mac run:'; echo ' brew install yarn'; exit 1) - # Use NODE_ENV=development so that yarn installs both dependencies + devDependencies - NODE_ENV=development yarn install --pure-lockfile - -install-brew: - @hash brew 2> /dev/null && brew bundle || (echo '! Homebrew not found, skipping system dependencies.') +# Used by https://github.com/getsentry/sentry-docs/blob/master/bin/extract-docs +develop-only: update-submodules install-system-pkgs install-yarn-pkgs install-sentry-dev -install-python: - # must be executed serially - $(MAKE) install-python-base - $(MAKE) install-python-develop - -install-python-base: - @echo ""--> Installing Python dependencies"" - $(PIP) install ""setuptools>=0.9.8"" ""pip>=8.0.0"" - # order matters here, base package must install first - $(PIP) install -e . - $(PIP) install ""file://`pwd`#egg=sentry[dev]"" - -install-python-develop: - $(PIP) install ""file://`pwd`#egg=sentry[dev,tests]"" - -install-python-tests: - $(PIP) install ""file://`pwd`#egg=sentry[dev,tests,optional]"" - -dev-postgres: install-python +build: locale dev-docs: $(PIP) install -r doc-requirements.txt @@ -56,14 +28,6 @@ reset-db: @echo ""--> Applying migrations"" sentry upgrade -setup-git: - @echo ""--> Installing git hooks"" - git config branch.autosetuprebase always - cd .git/hooks && ln -sf ../../config/hooks/* ./ - @echo """" - -build: locale - clean: @echo ""--> Cleaning static cache"" rm -rf dist/* static/dist/* @@ -75,9 +39,35 @@ clean: rm -rf build/ dist/ src/sentry/assets.json @echo """" +setup-git: + @echo ""--> Installing git hooks"" + git config branch.autosetuprebase always + cd .git/hooks && ln -sf ../../config/hooks/* ./ + @echo """" + +update-submodules: + @echo ""--> Updating git submodules"" + git submodule init + git submodule update + @echo """" + +install-system-pkgs: + @echo ""--> Installing system packages (from Brewfile)"" + @command -v brew 2>&1 > /dev/null && brew bundle || (echo 'WARNING: homebrew not found or brew bundle failed - skipping system dependencies.') + +install-yarn-pkgs: + @echo ""--> Installing Yarn packages (for development)"" + @command -v yarn 2>&1 > /dev/null || (echo 'yarn not found. Please install it before proceeding.'; exit 1) + # Use NODE_ENV=development so that yarn installs both dependencies + devDependencies + NODE_ENV=development yarn install --pure-lockfile + +install-sentry-dev: + @echo ""--> Installing Sentry (for development)"" + $(PIP) install -e "".[dev,tests,optional]"" + build-js-po: mkdir -p build - SENTRY_EXTRACT_TRANSLATIONS=1 ./node_modules/.bin/webpack + SENTRY_EXTRACT_TRANSLATIONS=1 $(WEBPACK) locale: build-js-po cd src/sentry && sentry django makemessages -i static -l en @@ -94,23 +84,11 @@ update-transifex: build-js-po ./bin/find-good-catalogs src/sentry/locale/catalogs.json cd src/sentry && sentry django compilemessages -update-submodules: - @echo ""--> Updating git submodules"" - git submodule init - git submodule update - @echo """" - build-platform-assets: @echo ""--> Building platform assets"" sentry init @echo ""from sentry.utils.integrationdocs import sync_docs; sync_docs(quiet=True)"" | sentry exec -test: develop lint test-js test-python test-cli - -testloop: develop - pip install -q pytest-xdist - py.test tests -f - test-cli: @echo ""--> Testing CLI"" rm -rf test_cli @@ -123,7 +101,7 @@ test-cli: test-js: @echo ""--> Building static assets"" - @${NPM_ROOT}/.bin/webpack --profile --json > webpack-stats.json + @$(WEBPACK) --profile --json > webpack-stats.json @echo ""--> Running JavaScript tests"" @npm run test-ci @echo """" @@ -154,7 +132,7 @@ test-snuba: test-acceptance: build-platform-assets @echo ""--> Building static assets"" - @${NPM_ROOT}/.bin/webpack --display errors-only + @$(WEBPACK) --display errors-only @echo ""--> Running acceptance tests"" py.test tests/acceptance --cov . --cov-report=""xml:coverage.xml"" --junit-xml=""junit.xml"" --html=""pytest.html"" @echo """" @@ -177,68 +155,17 @@ scan-python: bin/scan @echo """" -coverage: develop - $(MAKE) test-python - coverage html - publish: python setup.py sdist bdist_wheel upload -extract-api-docs: - rm -rf api-docs/cache/* - cd api-docs; python generator.py - - -.PHONY: develop dev-postgres dev-docs setup-git build clean locale update-transifex update-submodules test testloop test-cli test-js test-styleguide test-python test-acceptance lint lint-python lint-js coverage publish scan-python - ############################ # Halt, Travis stuff below # ############################ -# Bases for all builds -travis-upgrade-pip: - python -m pip install -q ""pip>=9,<10"" -travis-setup-cassandra: - echo ""create keyspace sentry with replication = {'class' : 'SimpleStrategy', 'replication_factor': 1};"" | cqlsh --cqlversion=3.1.7 - echo 'create table nodestore (key text primary key, value blob, flags int);' | cqlsh -k sentry --cqlversion=3.1.7 -travis-install-python: - pip install -q Django${DJANGO_VERSION} - $(MAKE) travis-upgrade-pip - $(MAKE) install-python-base - $(MAKE) install-python-tests - python -m pip install -q codecov travis-noop: @echo ""nothing to do here."" -.PHONY: travis-upgrade-pip travis-setup-cassandra travis-install-python travis-noop - -travis-install-sqlite: travis-install-python -travis-install-postgres: travis-install-python dev-postgres - psql -c 'create database sentry;' -U postgres -travis-install-mysql: travis-install-python - pip install -q mysqlclient - echo 'create database sentry;' | mysql -uroot -travis-install-acceptance: install-yarn travis-install-postgres - wget -N http://chromedriver.storage.googleapis.com/$(shell curl https://chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip -P ~/ - unzip ~/chromedriver_linux64.zip -d ~/ - rm ~/chromedriver_linux64.zip - chmod +x ~/chromedriver - mkdir -p ~/.bin - mv ~/chromedriver ~/.bin/ -travis-install-network: travis-install-postgres -travis-install-snuba: travis-install-postgres -travis-install-js: - $(MAKE) travis-upgrade-pip - $(MAKE) travis-install-python install-yarn -travis-install-cli: travis-install-postgres -travis-install-dist: - $(MAKE) travis-upgrade-pip - $(MAKE) travis-install-python install-yarn -travis-install-django-18: travis-install-postgres - -.PHONY: travis-install-sqlite travis-install-postgres travis-install-js travis-install-cli travis-install-dist - # Lint steps travis-lint-sqlite: lint-python travis-lint-postgres: lint-python @@ -249,9 +176,6 @@ travis-lint-snuba: lint-python travis-lint-js: lint-js travis-lint-cli: travis-noop travis-lint-dist: travis-noop -travis-lint-django-18: travis-lint-postgres - -.PHONY: travis-lint-sqlite travis-lint-postgres travis-lint-mysql travis-lint-js travis-lint-cli travis-lint-dist # Test steps travis-test-sqlite: test-python @@ -260,16 +184,11 @@ travis-test-mysql: test-python travis-test-acceptance: test-acceptance travis-test-network: test-network travis-test-snuba: test-snuba -travis-test-js: - $(MAKE) test-js +travis-test-js: test-js travis-test-cli: test-cli travis-test-dist: SENTRY_BUILD=$(TRAVIS_COMMIT) SENTRY_LIGHT_BUILD=0 python setup.py sdist bdist_wheel @ls -lh dist/ -travis-test-django-18: travis-test-postgres - -.PHONY: travis-test-sqlite travis-test-postgres travis-test-mysql travis-test-js travis-test-cli travis-test-dist - # Scan steps travis-scan-sqlite: scan-python @@ -281,6 +200,5 @@ travis-scan-snuba: scan-python travis-scan-js: travis-noop travis-scan-cli: travis-noop travis-scan-dist: travis-noop -travis-scan-django-18: travis-noop -.PHONY: travis-scan-sqlite travis-scan-postgres travis-scan-mysql travis-scan-acceptance travis-scan-network travis-scan-snuba travis-scan-js travis-scan-cli travis-scan-dist travis-scan-django-18 +.PHONY: all develop develop-only build dev-docs test testloop reset-db clean setup-git update-submodules install-system-pkgs install-yarn-pkgs install-sentry install-sentry-dev build-js-po locale update-transifex build-platform-assets test-cli test-js test-styleguide test-python test-network test-snuba test-acceptance lint lint-python lint-js scan-python coverage publish extract-api-docs travis-noop travis-setup-cassandra travis-lint-sqlite travis-lint-postgres travis-lint-mysql travis-lint-acceptance travis-lint-network travis-lint-snuba travis-lint-js travis-lint-cli travis-lint-dist travis-test-sqlite travis-test-postgres travis-test-mysql travis-test-acceptance travis-test-network travis-test-snuba travis-test-js travis-test-cli travis-test-dist travis-scan-sqlite travis-scan-postgres travis-scan-mysql travis-scan-acceptance travis-scan-network travis-scan-snuba travis-scan-js travis-scan-cli travis-scan-dist diff --git a/setup.py b/setup.py index ea5e0c5288fb39..ae4661c3e729d4 100755 --- a/setup.py +++ b/setup.py @@ -63,24 +63,22 @@ IS_LIGHT_BUILD = os.environ.get('SENTRY_LIGHT_BUILD') == '1' # we use pip requirements files to improve Docker layer caching - - def get_requirements(env): with open('requirements-{}.txt'.format(env)) as fp: return [x.strip() for x in fp.read().split('\n') if not x.startswith('#')] - install_requires = get_requirements('base') dev_requires = get_requirements('dev') tests_require = get_requirements('test') optional_requires = get_requirements('optional') +# override django version in requirements file if DJANGO_VERSION is set DJANGO_VERSION = os.environ.get('DJANGO_VERSION') if DJANGO_VERSION: install_requires = [ - 'Django{}'.format(DJANGO_VERSION[1:-1]) - if k.startswith('Django>=') else k - for k in install_requires + 'Django{}'.format(DJANGO_VERSION) + if r.startswith('Django>=') else r + for r in install_requires ]" d3e8ca85719c706351cfba08ed307ee7884ad853,2020-02-17 14:33:21,Priscila Oliveira,ref(ui): Added tooltip - Datascrubbers v2 - Part 4 (#16975),False,Added tooltip - Datascrubbers v2 - Part 4 (#16975),ref,"diff --git a/src/sentry/static/sentry/app/components/events/contexts.jsx b/src/sentry/static/sentry/app/components/events/contexts.jsx index 536ae8c7637d08..84a3d8916de51b 100644 --- a/src/sentry/static/sentry/app/components/events/contexts.jsx +++ b/src/sentry/static/sentry/app/components/events/contexts.jsx @@ -11,7 +11,7 @@ const CONTEXT_TYPES = { app: require('app/components/events/contexts/app').default, device: require('app/components/events/contexts/device').default, os: require('app/components/events/contexts/operatingSystem/operatingSystem').default, - runtime: require('app/components/events/contexts/runtime').default, + runtime: require('app/components/events/contexts/runtime/runtime').default, user: require('app/components/events/contexts/user').default, gpu: require('app/components/events/contexts/gpu').default, }; diff --git a/src/sentry/static/sentry/app/components/events/contexts/runtime.jsx b/src/sentry/static/sentry/app/components/events/contexts/runtime.jsx deleted file mode 100644 index 01582572b61d64..00000000000000 --- a/src/sentry/static/sentry/app/components/events/contexts/runtime.jsx +++ /dev/null @@ -1,29 +0,0 @@ -import PropTypes from 'prop-types'; -import React from 'react'; - -import ContextBlock from 'app/components/events/contexts/contextBlock'; - -class RuntimeContextType extends React.Component { - static propTypes = { - alias: PropTypes.string.isRequired, - data: PropTypes.object.isRequired, - }; - - render() { - const {name, version, build, ...data} = this.props.data; - return ( - - ); - } -} - -RuntimeContextType.getTitle = () => 'Runtime'; - -export default RuntimeContextType; diff --git a/src/sentry/static/sentry/app/components/events/contexts/runtime/getRuntimeKnownData.tsx b/src/sentry/static/sentry/app/components/events/contexts/runtime/getRuntimeKnownData.tsx new file mode 100644 index 00000000000000..93d83423c097a5 --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/contexts/runtime/getRuntimeKnownData.tsx @@ -0,0 +1,30 @@ +import {KeyValueListData} from 'app/components/events/interfaces/keyValueList/types'; +import {getMeta} from 'app/components/events/meta/metaProxy'; + +import getRuntimeKnownDataDetails from './getRuntimeKnownDataDetails'; +import {RuntimeData, RuntimeKnownDataType} from './types'; + +function getRuntimeKnownData(data: RuntimeData): Array { + const knownData: Array = []; + + const dataKeys = Object.keys(data); + for (const key of dataKeys) { + const knownDataDetails = getRuntimeKnownDataDetails( + data, + key as RuntimeKnownDataType + ); + + if (key === null || !knownDataDetails) { + continue; + } + + knownData.push({ + key, + ...knownDataDetails, + meta: getMeta(data, key), + }); + } + return knownData; +} + +export default getRuntimeKnownData; diff --git a/src/sentry/static/sentry/app/components/events/contexts/runtime/getRuntimeKnownDataDetails.tsx b/src/sentry/static/sentry/app/components/events/contexts/runtime/getRuntimeKnownDataDetails.tsx new file mode 100644 index 00000000000000..d48ea44ca7da5b --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/contexts/runtime/getRuntimeKnownDataDetails.tsx @@ -0,0 +1,30 @@ +import {t} from 'app/locale'; + +import {RuntimeData, RuntimeKnownDataType} from './types'; + +type Output = { + subject: string; + value: string | null; +}; + +function getRuntimeKnownDataDetails( + data: RuntimeData, + type: RuntimeKnownDataType +): Output | undefined { + switch (type) { + case RuntimeKnownDataType.NAME: + return { + subject: t('Name'), + value: data.name, + }; + case RuntimeKnownDataType.VERSION: + return { + subject: t('Version'), + value: `${data.version}${data.build ? `(${data.build})` : ''}`, + }; + default: + return undefined; + } +} + +export default getRuntimeKnownDataDetails; diff --git a/src/sentry/static/sentry/app/components/events/contexts/runtime/runtime.tsx b/src/sentry/static/sentry/app/components/events/contexts/runtime/runtime.tsx new file mode 100644 index 00000000000000..558c8c2e1b7726 --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/contexts/runtime/runtime.tsx @@ -0,0 +1,23 @@ +import React from 'react'; + +import ContextBlock from 'app/components/events/contexts/contextBlockV2'; +import {defined} from 'app/utils'; + +import getRuntimeKnownData from './getRuntimeKnownData'; +import {RuntimeData} from './types'; + +type Props = { + data?: RuntimeData; +}; + +const Runtime = ({data}: Props) => { + if (!defined(data)) { + return null; + } + + return ; +}; + +Runtime.getTitle = () => 'Runtime'; + +export default Runtime; diff --git a/src/sentry/static/sentry/app/components/events/contexts/runtime/types.ts b/src/sentry/static/sentry/app/components/events/contexts/runtime/types.ts new file mode 100644 index 00000000000000..96404d1b1191ff --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/contexts/runtime/types.ts @@ -0,0 +1,11 @@ +export enum RuntimeKnownDataType { + NAME = 'name', + VERSION = 'version', +} + +export type RuntimeData = { + name: string; + type: string; + build: string; + version?: string; +}; diff --git a/src/sentry/static/sentry/app/components/events/interfaces/keyValueList/types.tsx b/src/sentry/static/sentry/app/components/events/interfaces/keyValueList/types.tsx new file mode 100644 index 00000000000000..f2ee78b0e2fd1d --- /dev/null +++ b/src/sentry/static/sentry/app/components/events/interfaces/keyValueList/types.tsx @@ -0,0 +1,8 @@ +import {Meta} from 'app/types'; + +export type KeyValueListData = { + key: string; + subject: React.ReactNode; + value: string | null; + meta: Meta; +};" d83804d2bbe7f9b797ececd1ee1041e7d8e60633,2019-06-11 03:43:41,Lyn Nagara,ref(sentry10): Remove Sentry 10 references from tests (#13615),False,Remove Sentry 10 references from tests (#13615),ref,"diff --git a/tests/acceptance/test_dashboard.py b/tests/acceptance/test_dashboard.py index c1df487ab2f9eb..637aa03abf26bb 100644 --- a/tests/acceptance/test_dashboard.py +++ b/tests/acceptance/test_dashboard.py @@ -58,44 +58,42 @@ def setUp(self): def test_no_issues(self): # I think no ""activity"" would be more accurate? - with self.feature('organizations:sentry10'): - self.project.update(first_event=None) - self.browser.get(self.path) - self.browser.wait_until_not('.loading-indicator') - self.browser.wait_until_test_id('awaiting-events') - self.browser.snapshot('org dash no issues') + self.project.update(first_event=None) + self.browser.get(self.path) + self.browser.wait_until_not('.loading-indicator') + self.browser.wait_until_test_id('awaiting-events') + self.browser.snapshot('org dash no issues') def test_one_issue(self): - with self.feature('organizations:sentry10'): - self.init_snuba() + self.init_snuba() - event_data = load_data('python') - event_data['event_id'] = 'd964fdbd649a4cf8bfc35d18082b6b0e' - event_data['timestamp'] = 1452683305 - event = self.store_event( - project_id=self.project.id, - data=event_data, - assert_no_errors=False - ) - event.group.update( - first_seen=datetime(2018, 1, 12, 3, 8, 25, tzinfo=timezone.utc), - last_seen=datetime(2018, 1, 13, 3, 8, 25, tzinfo=timezone.utc), - ) - GroupAssignee.objects.create( - user=self.user, - group=event.group, - project=self.project, - ) - OrganizationOnboardingTask.objects.create_or_update( - organization_id=self.project.organization_id, - task=OnboardingTask.FIRST_EVENT, - status=OnboardingTaskStatus.COMPLETE, - ) - self.project.update(first_event=timezone.now()) - self.browser.get(self.path) - self.browser.wait_until_not('.loading-indicator') - self.browser.wait_until('[data-test-id] figure') - self.browser.snapshot('org dash one issue') + event_data = load_data('python') + event_data['event_id'] = 'd964fdbd649a4cf8bfc35d18082b6b0e' + event_data['timestamp'] = 1452683305 + event = self.store_event( + project_id=self.project.id, + data=event_data, + assert_no_errors=False + ) + event.group.update( + first_seen=datetime(2018, 1, 12, 3, 8, 25, tzinfo=timezone.utc), + last_seen=datetime(2018, 1, 13, 3, 8, 25, tzinfo=timezone.utc), + ) + GroupAssignee.objects.create( + user=self.user, + group=event.group, + project=self.project, + ) + OrganizationOnboardingTask.objects.create_or_update( + organization_id=self.project.organization_id, + task=OnboardingTask.FIRST_EVENT, + status=OnboardingTaskStatus.COMPLETE, + ) + self.project.update(first_event=timezone.now()) + self.browser.get(self.path) + self.browser.wait_until_not('.loading-indicator') + self.browser.wait_until('[data-test-id] figure') + self.browser.snapshot('org dash one issue') class EmptyDashboardTest(AcceptanceTestCase): @@ -117,7 +115,6 @@ def setUp(self): self.path = u'/organizations/{}/projects/'.format(self.org.slug) def test_new_dashboard_empty(self): - with self.feature('organizations:sentry10'): - self.browser.get(self.path) - self.browser.wait_until_not('.loading-indicator') - self.browser.snapshot('new dashboard empty') + self.browser.get(self.path) + self.browser.wait_until_not('.loading-indicator') + self.browser.snapshot('new dashboard empty') diff --git a/tests/acceptance/test_emails.py b/tests/acceptance/test_emails.py index ca17031f07774d..1691d46c247d66 100644 --- a/tests/acceptance/test_emails.py +++ b/tests/acceptance/test_emails.py @@ -63,18 +63,17 @@ def build_url(self, path, format='html'): ) def test_emails(self): - with self.feature('organizations:sentry10'): - for url, name in EMAILS: - # HTML output is captured as a snapshot - self.browser.get(self.build_url(url, 'html')) - self.browser.wait_until('#preview') - self.browser.snapshot(u'{} email html'.format(name)) + for url, name in EMAILS: + # HTML output is captured as a snapshot + self.browser.get(self.build_url(url, 'html')) + self.browser.wait_until('#preview') + self.browser.snapshot(u'{} email html'.format(name)) - # Text output is asserted against static fixture files - self.browser.get(self.build_url(url, 'txt')) - self.browser.wait_until('#preview') - elem = self.browser.find_element_by_css_selector('#preview pre') - text_src = elem.get_attribute('innerHTML') + # Text output is asserted against static fixture files + self.browser.get(self.build_url(url, 'txt')) + self.browser.wait_until('#preview') + elem = self.browser.find_element_by_css_selector('#preview pre') + text_src = elem.get_attribute('innerHTML') - fixture_src = read_txt_email_fixture(name) - assert fixture_src == text_src + fixture_src = read_txt_email_fixture(name) + assert fixture_src == text_src diff --git a/tests/acceptance/test_issue_details_workflow.py b/tests/acceptance/test_issue_details_workflow.py index b4738d5a233731..99b99851932842 100644 --- a/tests/acceptance/test_issue_details_workflow.py +++ b/tests/acceptance/test_issue_details_workflow.py @@ -46,13 +46,12 @@ def test_resolve_basic(self): event = self.create_sample_event( platform='python', ) - with self.feature('organizations:sentry10'): - self.page.visit_issue(self.org.slug, event.group.id) - self.page.resolve_issue() + self.page.visit_issue(self.org.slug, event.group.id) + self.page.resolve_issue() - res = self.page.api_issue_get(event.group.id) - assert res.status_code == 200, res - assert res.data['status'] == 'resolved' + res = self.page.api_issue_get(event.group.id) + assert res.status_code == 200, res + assert res.data['status'] == 'resolved' def test_ignore_basic(self): event = self.create_sample_event( diff --git a/tests/acceptance/test_onboarding.py b/tests/acceptance/test_onboarding.py index 87f27d00632420..2dbc3dbe45192e 100644 --- a/tests/acceptance/test_onboarding.py +++ b/tests/acceptance/test_onboarding.py @@ -26,25 +26,24 @@ def setUp(self): @mock.patch('sentry.models.ProjectKey.generate_api_key', return_value='031667ea1758441f92c7995a428d2d14') def test_onboarding(self, generate_api_key): - with self.feature('organizations:sentry10'): - self.browser.get('/onboarding/%s/' % self.org.slug) - self.browser.wait_until('.onboarding-container') - self.browser.wait_until_not('.loading-indicator') - self.browser.snapshot(name='onboarding-choose-platform') + self.browser.get('/onboarding/%s/' % self.org.slug) + self.browser.wait_until('.onboarding-container') + self.browser.wait_until_not('.loading-indicator') + self.browser.snapshot(name='onboarding-choose-platform') - self.browser.click('[data-test-id=""platform-javascript-angular""]') - self.browser.click('[data-test-id=""create-project""]') + self.browser.click('[data-test-id=""platform-javascript-angular""]') + self.browser.click('[data-test-id=""create-project""]') - self.browser.wait_until('.onboarding-Configure') - self.browser.wait_until_not('.loading-indicator') + self.browser.wait_until('.onboarding-Configure') + self.browser.wait_until_not('.loading-indicator') - project = Project.objects.get(organization=self.org) - assert project.name == 'Angular' - assert project.platform == 'javascript-angular' + project = Project.objects.get(organization=self.org) + assert project.name == 'Angular' + assert project.platform == 'javascript-angular' - self.browser.snapshot(name='onboarding-configure-project') - self.browser.click('[data-test-id=""configure-done""]') - self.browser.wait_until_not('.loading-indicator') + self.browser.snapshot(name='onboarding-configure-project') + self.browser.click('[data-test-id=""configure-done""]') + self.browser.wait_until_not('.loading-indicator') - assert self.browser.element_exists('.robot') - assert self.browser.element_exists_by_test_id('install-instructions') + assert self.browser.element_exists('.robot') + assert self.browser.element_exists_by_test_id('install-instructions') diff --git a/tests/acceptance/test_organization_group_index.py b/tests/acceptance/test_organization_group_index.py index 14e6c3bad8b486..a185dac370bc42 100644 --- a/tests/acceptance/test_organization_group_index.py +++ b/tests/acceptance/test_organization_group_index.py @@ -36,19 +36,17 @@ def setUp(self): def test_with_onboarding(self): self.project.update(first_event=None) - with self.feature(['organizations:sentry10', 'organizations:discover']): - self.browser.get(self.path) - self.wait_until_loaded() - self.browser.wait_until_test_id('awaiting-events') - self.browser.snapshot('organization issues onboarding') + self.browser.get(self.path) + self.wait_until_loaded() + self.browser.wait_until_test_id('awaiting-events') + self.browser.snapshot('organization issues onboarding') def test_with_no_results(self): self.project.update(first_event=timezone.now()) - with self.feature(['organizations:sentry10', 'organizations:discover']): - self.browser.get(self.path) - self.wait_until_loaded() - self.browser.wait_until_test_id('empty-state') - self.browser.snapshot('organization issues no results') + self.browser.get(self.path) + self.wait_until_loaded() + self.browser.wait_until_test_id('empty-state') + self.browser.snapshot('organization issues no results') @patch('django.utils.timezone.now') def test_with_results(self, mock_now): @@ -71,16 +69,15 @@ def test_with_results(self, mock_now): }, project_id=self.project.id ) - with self.feature(['organizations:sentry10', 'organizations:discover']): - self.browser.get(self.path) - self.wait_until_loaded() - self.browser.wait_until('.event-issue-header') - self.browser.snapshot('organization issues with issues') + self.browser.get(self.path) + self.wait_until_loaded() + self.browser.wait_until('.event-issue-header') + self.browser.snapshot('organization issues with issues') - groups = self.browser.find_elements_by_class_name('event-issue-header') - assert len(groups) == 2 - assert 'oh snap' in groups[0].text - assert 'oh no' in groups[1].text + groups = self.browser.find_elements_by_class_name('event-issue-header') + assert len(groups) == 2 + assert 'oh snap' in groups[0].text + assert 'oh no' in groups[1].text def wait_until_loaded(self): self.browser.wait_until_not('.loading') diff --git a/tests/acceptance/test_organization_releases.py b/tests/acceptance/test_organization_releases.py index e369674f7486b9..c513b46b2b8847 100644 --- a/tests/acceptance/test_organization_releases.py +++ b/tests/acceptance/test_organization_releases.py @@ -26,23 +26,21 @@ def setUp(self): self.org.slug) def test_with_releases(self): - with self.feature('organizations:sentry10'): - release = self.create_release( - project=self.project, - version='1.0', - ) - self.create_group( - first_release=release, - project=self.project, - message='Foo bar', - ) - self.project.update(first_event=timezone.now()) - self.browser.get(self.path) - self.browser.wait_until_not('.loading') - self.browser.snapshot('organization releases with releases') + release = self.create_release( + project=self.project, + version='1.0', + ) + self.create_group( + first_release=release, + project=self.project, + message='Foo bar', + ) + self.project.update(first_event=timezone.now()) + self.browser.get(self.path) + self.browser.wait_until_not('.loading') + self.browser.snapshot('organization releases with releases') def test_with_no_releases(self): - with self.feature('organizations:sentry10'): - self.browser.get(self.path) - self.browser.wait_until_not('.loading') - self.browser.snapshot('organization releases without releases') + self.browser.get(self.path) + self.browser.wait_until_not('.loading') + self.browser.snapshot('organization releases without releases') diff --git a/tests/acceptance/test_organization_user_feedback.py b/tests/acceptance/test_organization_user_feedback.py index dd3959e8f1fd64..4c4a42bf789ac7 100644 --- a/tests/acceptance/test_organization_user_feedback.py +++ b/tests/acceptance/test_organization_user_feedback.py @@ -26,21 +26,19 @@ def setUp(self): self.project.update(first_event=timezone.now()) def test(self): - with self.feature('organizations:sentry10'): - self.create_userreport( - date_added=timezone.now(), - group=self.group, - project=self.project) - self.browser.get(self.path) - self.browser.wait_until_not('.loading-indicator') - self.browser.wait_until('[data-test-id=""user-feedback-list""]') - self.browser.snapshot('organization user feedback') + self.create_userreport( + date_added=timezone.now(), + group=self.group, + project=self.project) + self.browser.get(self.path) + self.browser.wait_until_not('.loading-indicator') + self.browser.wait_until('[data-test-id=""user-feedback-list""]') + self.browser.snapshot('organization user feedback') def test_empty(self): - with self.feature('organizations:sentry10'): - self.browser.get(self.path) - self.browser.wait_until_not('.loading-indicator') - self.browser.snapshot('organization user feedback - empty') + self.browser.get(self.path) + self.browser.wait_until_not('.loading-indicator') + self.browser.snapshot('organization user feedback - empty') def test_no_access(self): self.browser.get(self.path) diff --git a/tests/js/spec/components/sidebar/index.spec.jsx b/tests/js/spec/components/sidebar/index.spec.jsx index d987c8ce1cc0d1..8336d80afeb496 100644 --- a/tests/js/spec/components/sidebar/index.spec.jsx +++ b/tests/js/spec/components/sidebar/index.spec.jsx @@ -287,17 +287,5 @@ describe('Sidebar', function() { wrapper.update(); expect(wrapper.find('SidebarPanel')).toHaveLength(0); }); - - it('hides assigned, bookmarks, history, activity and stats for sentry10', function() { - const sentry10Org = TestStubs.Organization({features: ['sentry10']}); - wrapper = createWrapper(); - wrapper.setProps({organization: sentry10Org}); - wrapper.update(); - const labels = wrapper.find('SidebarItemLabel').map(node => node.text()); - expect(labels).toHaveLength(10); - expect(labels).not.toContain('Assigned to me'); - expect(labels).not.toContain('Bookmarked issues'); - expect(labels).not.toContain('Recently viewed'); - }); }); }); diff --git a/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx b/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx index 7319f0532c867a..8c9c2509215739 100644 --- a/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx +++ b/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx @@ -118,12 +118,8 @@ describe('OrganizationDashboard', function() { TestStubs.routerContext() ); const emptyState = wrapper.find('NoProjectMessage'); - const favorites = wrapper.find('TeamSection[data-test-id=""favorites""]'); const teamSection = wrapper.find('TeamSection'); expect(emptyState).toHaveLength(0); - // Note: we have a project that is bookmarked but there is no Favorites section - // We removed this as part of sentry 10 - expect(favorites).toHaveLength(0); expect(teamSection).toHaveLength(1); }); @@ -268,8 +264,6 @@ describe('OrganizationDashboard', function() { routerContext ); - // Favorites = ~3~0 + 6 for first team - // Note: Favorites does not exist in sentry10 expect(loadStatsSpy).toHaveBeenCalledTimes(6); expect(mock).not.toHaveBeenCalled();" d89937df87c78e47330886fde3d75d1721d46388,2021-02-20 03:38:37,MeredithAnya,ref(apm): Convert some transaction_start to SAMPLED_URL_NAMES (#23987),False,Convert some transaction_start to SAMPLED_URL_NAMES (#23987),ref,"diff --git a/src/sentry/api/endpoints/group_integration_details.py b/src/sentry/api/endpoints/group_integration_details.py index fb4a43d7a1dde5..157aa83fe11526 100644 --- a/src/sentry/api/endpoints/group_integration_details.py +++ b/src/sentry/api/endpoints/group_integration_details.py @@ -9,7 +9,6 @@ from sentry.shared_integrations.exceptions import IntegrationError, IntegrationFormError from sentry.models import Activity, ExternalIssue, GroupLink, Integration from sentry.signals import integration_issue_created, integration_issue_linked -from sentry.web.decorators import transaction_start MISSING_FEATURE_MESSAGE = ""Your organization does not have access to this feature."" @@ -42,7 +41,6 @@ def create_issue_activity(self, request, group, installation, external_issue): data=issue_information, ) - @transaction_start(""GroupIntegrationDetailsEndpoint"") def get(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({""detail"": MISSING_FEATURE_MESSAGE}, status=400) @@ -81,7 +79,6 @@ def get(self, request, group, integration_id): return Response({""detail"": str(e)}, status=400) # was thinking put for link an existing issue, post for create new issue? - @transaction_start(""GroupIntegrationDetailsEndpoint"") def put(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({""detail"": MISSING_FEATURE_MESSAGE}, status=400) @@ -170,7 +167,6 @@ def put(self, request, group, integration_id): } return Response(context, status=201) - @transaction_start(""GroupIntegrationDetailsEndpoint"") def post(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({""detail"": MISSING_FEATURE_MESSAGE}, status=400) @@ -243,7 +239,6 @@ def post(self, request, group, integration_id): } return Response(context, status=201) - @transaction_start(""GroupIntegrationDetailsEndpoint"") def delete(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({""detail"": MISSING_FEATURE_MESSAGE}, status=400) diff --git a/src/sentry/api/endpoints/organization_release_details.py b/src/sentry/api/endpoints/organization_release_details.py index 917d574576419f..c821b73e84a412 100644 --- a/src/sentry/api/endpoints/organization_release_details.py +++ b/src/sentry/api/endpoints/organization_release_details.py @@ -16,7 +16,6 @@ from sentry.snuba.sessions import STATS_PERIODS from sentry.api.endpoints.organization_releases import get_stats_period_detail from sentry.utils.sdk import configure_scope, bind_organization_context -from sentry.web.decorators import transaction_start class OrganizationReleaseSerializer(ReleaseSerializer): @@ -27,7 +26,6 @@ class OrganizationReleaseSerializer(ReleaseSerializer): class OrganizationReleaseDetailsEndpoint(OrganizationReleasesBaseEndpoint, ReleaseAnalyticsMixin): - @transaction_start(""OrganizationReleaseDetailsEndpoint.get"") def get(self, request, organization, version): """""" Retrieve an Organization's Release @@ -74,7 +72,6 @@ def get(self, request, organization, version): ) ) - @transaction_start(""OrganizationReleaseDetailsEndpoint.put"") def put(self, request, organization, version): """""" Update an Organization's Release @@ -196,7 +193,6 @@ def put(self, request, organization, version): return Response(serialize(release, request.user)) - @transaction_start(""OrganizationReleaseDetailsEndpoint.delete"") def delete(self, request, organization, version): """""" Delete an Organization's Release diff --git a/src/sentry/api/endpoints/project_release_details.py b/src/sentry/api/endpoints/project_release_details.py index 5a534a1f5fc042..559f3117242a8c 100644 --- a/src/sentry/api/endpoints/project_release_details.py +++ b/src/sentry/api/endpoints/project_release_details.py @@ -15,13 +15,11 @@ from sentry.api.endpoints.organization_releases import get_stats_period_detail from sentry.utils.sdk import configure_scope, bind_organization_context -from sentry.web.decorators import transaction_start class ProjectReleaseDetailsEndpoint(ProjectEndpoint, ReleaseAnalyticsMixin): permission_classes = (ProjectReleasePermission,) - @transaction_start(""ProjectReleaseDetailsEndpoint.get"") def get(self, request, project, version): """""" Retrieve a Project's Release @@ -65,7 +63,6 @@ def get(self, request, project, version): ) ) - @transaction_start(""ProjectReleaseDetailsEndpoint.put"") def put(self, request, project, version): """""" Update a Project's Release @@ -143,7 +140,6 @@ def put(self, request, project, version): return Response(serialize(release, request.user)) - @transaction_start(""ProjectReleaseDetailsEndpoint.delete"") def delete(self, request, project, version): """""" Delete a Project's Release diff --git a/src/sentry/api/endpoints/project_releases.py b/src/sentry/api/endpoints/project_releases.py index 223cbeaf05e774..e3d220f1fe004b 100644 --- a/src/sentry/api/endpoints/project_releases.py +++ b/src/sentry/api/endpoints/project_releases.py @@ -14,13 +14,11 @@ from sentry.plugins.interfaces.releasehook import ReleaseHook from sentry.signals import release_created from sentry.utils.sdk import configure_scope, bind_organization_context -from sentry.web.decorators import transaction_start class ProjectReleasesEndpoint(ProjectEndpoint, EnvironmentMixin): permission_classes = (ProjectReleasePermission,) - @transaction_start(""ProjectReleasesEndpoint.get"") def get(self, request, project): """""" List a Project's Releases @@ -71,7 +69,6 @@ def get(self, request, project): ), ) - @transaction_start(""ProjectReleasesEndpoint.post"") def post(self, request, project): """""" Create a New Release for a Project diff --git a/src/sentry/api/endpoints/sentry_app_authorizations.py b/src/sentry/api/endpoints/sentry_app_authorizations.py index ea4401b42f514f..480e9b876b4276 100644 --- a/src/sentry/api/endpoints/sentry_app_authorizations.py +++ b/src/sentry/api/endpoints/sentry_app_authorizations.py @@ -8,13 +8,11 @@ from sentry.coreapi import APIUnauthorized from sentry.mediators.token_exchange import GrantExchanger, Refresher, GrantTypes from sentry.api.serializers.models.apitoken import ApiTokenSerializer -from sentry.web.decorators import transaction_start logger = logging.getLogger(__name__) class SentryAppAuthorizationsEndpoint(SentryAppAuthorizationsBaseEndpoint): - @transaction_start(""SentryAppAuthorizationsEndpoint"") def post(self, request, installation): with sentry_sdk.configure_scope() as scope: scope.set_tag(""organization"", installation.organization_id) diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py index 9db350c95b4267..29e2b19b58dae4 100644 --- a/src/sentry/api/urls.py +++ b/src/sentry/api/urls.py @@ -395,7 +395,11 @@ ), url(r""^(?P[^\/]+)/attachments/$"", GroupAttachmentsEndpoint.as_view()), url(r""^(?P[^\/]+)/similar/$"", GroupSimilarIssuesEndpoint.as_view()), - url(r""^(?P[^\/]+)/external-issues/$"", GroupExternalIssuesEndpoint.as_view()), + url( + r""^(?P[^\/]+)/external-issues/$"", + GroupExternalIssuesEndpoint.as_view(), + name=""external-issues"", + ), url( r""^(?P[^\/]+)/external-issues/(?P\d+)/$"", GroupExternalIssueDetailsEndpoint.as_view(), @@ -404,6 +408,7 @@ url( r""^(?P[^\/]+)/integrations/(?P\d+)/$"", GroupIntegrationDetailsEndpoint.as_view(), + name=""integration-details"", ), url(r""^(?P[^\/]+)/current-release/$"", GroupCurrentReleaseEndpoint.as_view()), # Load plugin group urls @@ -924,7 +929,10 @@ OrganizationGroupIndexStatsEndpoint.as_view(), name=""sentry-api-0-organization-group-index-stats"", ), - url(r""^(?P[^\/]+)/(?:issues|groups)/"", include(GROUP_URLS)), + url( + r""^(?P[^\/]+)/(?:issues|groups)/"", + include(GROUP_URLS, namespace=""sentry-api-0-organization-group""), + ), url( r""^(?P[^\/]+)/integrations/$"", OrganizationIntegrationsEndpoint.as_view(), @@ -1714,7 +1722,7 @@ ), ), # Groups - url(r""^(?:issues|groups)/"", include(GROUP_URLS)), + url(r""^(?:issues|groups)/"", include(GROUP_URLS, namespace=""sentry-api-0-group"")), url( r""^issues/(?P[^\/]+)/participants/$"", GroupParticipantsEndpoint.as_view(), diff --git a/src/sentry/utils/sdk.py b/src/sentry/utils/sdk.py index 52a2404ce6fe48..a63cc2d8df0ec9 100644 --- a/src/sentry/utils/sdk.py +++ b/src/sentry/utils/sdk.py @@ -23,8 +23,17 @@ # URLs that should always be sampled SAMPLED_URL_NAMES = { + # releases ""sentry-api-0-organization-releases"", + ""sentry-api-0-organization-release-details"", + ""sentry-api-0-project-releases"", + ""sentry-api-0-project-release-details"", + # integrations ""sentry-extensions-jira-issue-hook"", + ""sentry-api-0-group-integration-details"", + # integration platform + ""sentry-api-0-group-external-issues"", + ""sentry-api-0-sentry-app-authorizations"", } UNSAFE_TAG = ""_unsafe""" aa1f4b6ec66c9b994d909a0df1b203669c1b7eae,2021-06-18 19:42:11,Tony Xiao,fix(discover): No user set for snuba params (#26673),False,No user set for snuba params (#26673),fix,"diff --git a/src/sentry/api/bases/organization_events.py b/src/sentry/api/bases/organization_events.py index 6d4a812cd1c248..6b26e21e31bfc6 100644 --- a/src/sentry/api/bases/organization_events.py +++ b/src/sentry/api/bases/organization_events.py @@ -67,6 +67,16 @@ def get_snuba_filter(self, request, organization, params=None): except InvalidSearchQuery as e: raise ParseError(detail=str(e)) + def get_team_ids(self, request, organization): + if not request.user: + return [] + + teams = get_teams(request, organization) + if not teams: + teams = Team.objects.get_for_user(organization, request.user) + + return [team.id for team in teams] + def get_snuba_params(self, request, organization, check_global_views=True): with sentry_sdk.start_span(op=""discover.endpoint"", description=""filter_params""): if ( @@ -81,10 +91,7 @@ def get_snuba_params(self, request, organization, check_global_views=True): params = self.get_filter_params(request, organization) params = self.quantize_date_params(request, params) params[""user_id""] = request.user.id if request.user else None - teams = get_teams(request, organization) - if not teams: - teams = Team.objects.get_for_user(organization, request.user) - params[""team_id""] = [team.id for team in teams] + params[""team_id""] = self.get_team_ids(request, organization) if check_global_views: has_global_views = features.has( diff --git a/tests/sentry/integrations/slack/test_unfurl.py b/tests/sentry/integrations/slack/test_unfurl.py index 9b6916f83fc93c..e81d7d55b15c9f 100644 --- a/tests/sentry/integrations/slack/test_unfurl.py +++ b/tests/sentry/integrations/slack/test_unfurl.py @@ -122,7 +122,12 @@ def test_unfurl_discover(self, mock_generate_chart): UnfurlableUrl(url=url, args=args), ] - with self.feature(""organizations:chart-unfurls""): + with self.feature( + [ + ""organizations:discover-basic"", + ""organizations:chart-unfurls"", + ] + ): unfurls = link_handlers[link_type].fn(self.request, self.integration, links) assert unfurls[url] == build_discover_attachment( @@ -165,10 +170,11 @@ def test_unfurl_discover_short_url(self, mock_generate_chart): ] with self.feature( - { - ""organizations:discover"": True, - ""organizations:chart-unfurls"": True, - } + [ + ""organizations:discover"", + ""organizations:discover-basic"", + ""organizations:chart-unfurls"", + ] ): unfurls = link_handlers[link_type].fn(self.request, self.integration, links)" 7b30d5a810da5e0edf222df19fbc10690947a373,2025-03-21 18:52:37,Nikki Kapadia,feat(schema-hints): Drawer part of content on large screens (#87494),False,Drawer part of content on large screens (#87494),feat,"diff --git a/static/app/views/explore/components/schemaHintsList.tsx b/static/app/views/explore/components/schemaHintsList.tsx index 44827442631e61..99c1c18b977425 100644 --- a/static/app/views/explore/components/schemaHintsList.tsx +++ b/static/app/views/explore/components/schemaHintsList.tsx @@ -30,6 +30,8 @@ import { } from 'sentry/views/explore/contexts/pageParamsContext'; import {SPANS_FILTER_KEY_SECTIONS} from 'sentry/views/insights/constants'; +export const SCHEMA_HINTS_DRAWER_WIDTH = '35vw'; + interface SchemaHintsListProps { numberTags: TagCollection; stringTags: TagCollection; @@ -43,6 +45,12 @@ const seeFullListTag: Tag = { kind: undefined, }; +const hideListTag: Tag = { + key: 'hideList', + name: t('Hide list'), + kind: undefined, +}; + function getTagsFromKeys(keys: string[], tags: TagCollection): Tag[] { return keys.map(key => tags[key]).filter(tag => !!tag); } @@ -58,7 +66,7 @@ function SchemaHintsList({ const setExploreQuery = useSetExploreQuery(); const location = useLocation(); - const {openDrawer, isDrawerOpen} = useDrawer(); + const {openDrawer, isDrawerOpen, closeDrawer} = useDrawer(); const functionTags = useMemo(() => { return getFunctionTags(supportedAggregates); @@ -136,7 +144,10 @@ function SchemaHintsList({ lastVisibleIndex = items.length; } - setVisibleHints([...filterTagsSorted.slice(0, lastVisibleIndex), seeFullListTag]); + setVisibleHints([ + ...filterTagsSorted.slice(0, lastVisibleIndex), + isDrawerOpen ? hideListTag : seeFullListTag, + ]); // Remove the temporary div document.body.removeChild(measureDiv); @@ -151,7 +162,7 @@ function SchemaHintsList({ } return () => resizeObserver.disconnect(); - }, [filterTagsSorted]); + }, [filterTagsSorted, isDrawerOpen]); const onHintClick = useCallback( (hint: Tag) => { @@ -165,7 +176,13 @@ function SchemaHintsList({ ), { ariaLabel: t('Schema Hints Drawer'), - drawerWidth: '35vw', + drawerWidth: SCHEMA_HINTS_DRAWER_WIDTH, + transitionProps: { + key: 'schema-hints-drawer', + type: 'tween', + duration: 0.7, + ease: 'easeOut', + }, shouldCloseOnLocationChange: newLocation => { return ( location.pathname !== newLocation.pathname || @@ -182,6 +199,13 @@ function SchemaHintsList({ return; } + if (hint.key === hideListTag.key) { + if (isDrawerOpen) { + closeDrawer(); + } + return; + } + const newSearchQuery = new MutableSearch(exploreQuery); const isBoolean = getFieldDefinition(hint.key, 'span', hint.kind)?.valueType === @@ -192,11 +216,20 @@ function SchemaHintsList({ ); setExploreQuery(newSearchQuery.formatString()); }, - [exploreQuery, setExploreQuery, isDrawerOpen, openDrawer, filterTagsSorted, location] + [ + exploreQuery, + setExploreQuery, + isDrawerOpen, + openDrawer, + filterTagsSorted, + location.pathname, + location.query, + closeDrawer, + ] ); const getHintText = (hint: Tag) => { - if (hint.key === seeFullListTag.key) { + if (hint.key === seeFullListTag.key || hint.key === hideListTag.key) { return hint.name; } diff --git a/static/app/views/explore/spans/spansTab.tsx b/static/app/views/explore/spans/spansTab.tsx index f6b280ea443552..d6f1e3797ba047 100644 --- a/static/app/views/explore/spans/spansTab.tsx +++ b/static/app/views/explore/spans/spansTab.tsx @@ -1,10 +1,12 @@ import {useMemo, useState} from 'react'; +import {useTheme} from '@emotion/react'; import styled from '@emotion/styled'; import * as Sentry from '@sentry/react'; import Feature from 'sentry/components/acl/feature'; import {getDiffInMinutes} from 'sentry/components/charts/utils'; import {Button} from 'sentry/components/core/button'; +import useDrawer from 'sentry/components/globalDrawer'; import * as Layout from 'sentry/components/layouts/thirds'; import {DatePageFilter} from 'sentry/components/organizations/datePageFilter'; import {EnvironmentPageFilter} from 'sentry/components/organizations/environmentPageFilter'; @@ -26,10 +28,13 @@ import { type AggregationKey, ALLOWED_EXPLORE_VISUALIZE_AGGREGATES, } from 'sentry/utils/fields'; +import useMedia from 'sentry/utils/useMedia'; import useOrganization from 'sentry/utils/useOrganization'; import usePageFilters from 'sentry/utils/usePageFilters'; import {ExploreCharts} from 'sentry/views/explore/charts'; -import SchemaHintsList from 'sentry/views/explore/components/schemaHintsList'; +import SchemaHintsList, { + SCHEMA_HINTS_DRAWER_WIDTH, +} from 'sentry/views/explore/components/schemaHintsList'; import { PageParamsProvider, useExploreDataset, @@ -86,6 +91,14 @@ export function SpansTabContentImpl({ const query = useExploreQuery(); const setQuery = useSetExploreQuery(); + const {isDrawerOpen: isSchemaHintsDrawerOpen} = useDrawer(); + const theme = useTheme(); + const isLargeScreen = useMedia(`(min-width: ${theme.breakpoints.xlarge})`); + const isSchemaHintsDrawerOpenOnLargeScreen = + isSchemaHintsDrawerOpen && + isLargeScreen && + organization.features.includes('traces-schema-hints'); + const toolbarExtras = [ ...(organization?.features?.includes('visibility-explore-dataset') ? ['dataset toggle' as const] @@ -172,6 +185,9 @@ export function SpansTabContentImpl({ @@ -222,7 +238,7 @@ export function SpansTabContentImpl({ )} - + ` +const Body = styled(Layout.Body)<{ + thirdColumnWidth: string; + withHints: boolean; + withToolbar: boolean; +}>` @media (min-width: ${p => p.theme.breakpoints.medium}) { display: grid; ${p => p.withToolbar - ? `grid-template-columns: 300px minmax(100px, auto);` - : `grid-template-columns: 0px minmax(100px, auto);`} + ? `grid-template-columns: 300px minmax(100px, auto) ${p.withHints ? p.thirdColumnWidth : ''};` + : `grid-template-columns: 0px minmax(100px, auto) ${p.withHints ? p.thirdColumnWidth : ''};`} grid-template-rows: auto ${p => (p.withHints ? 'auto 1fr' : '1fr')}; align-content: start; gap: ${space(2)} ${p => (p.withToolbar ? `${space(2)}` : '0px')}; @@ -373,7 +393,7 @@ const SideSection = styled('aside')<{withToolbar: boolean}>` } `; -const HintsSection = styled('div')` +const HintsSection = styled('div')<{withSchemaHintsDrawer: boolean}>` display: grid; /* This is to ensure the hints section spans all the columns */ grid-column: 1/-1; @@ -382,7 +402,8 @@ const HintsSection = styled('div')` height: fit-content; @media (min-width: ${p => p.theme.breakpoints.medium}) { - grid-template-columns: 1fr; + grid-template-columns: 1fr ${p => + p.withSchemaHintsDrawer ? SCHEMA_HINTS_DRAWER_WIDTH : '0px'}; margin-bottom: 0; margin-top: 0; }" 0670b8e24c9e8289467de507f3a8d206bbcc682d,2024-01-27 00:00:36,Malachi Willey,feat(issue-details): Apply initial design feedback to replay player (#63963),False,Apply initial design feedback to replay player (#63963),feat,"diff --git a/static/app/components/events/eventReplay/replayClipPreview.spec.tsx b/static/app/components/events/eventReplay/replayClipPreview.spec.tsx index 699157a4b17b69..b8ad63171ab838 100644 --- a/static/app/components/events/eventReplay/replayClipPreview.spec.tsx +++ b/static/app/components/events/eventReplay/replayClipPreview.spec.tsx @@ -24,7 +24,7 @@ const mockReplayId = '761104e184c64d439ee1014b72b4d83b'; const mockEventTimestampMs = new Date('2022-09-22T16:59:41Z').getTime(); -const mockButtonHref = `/organizations/${mockOrgSlug}/replays/761104e184c64d439ee1014b72b4d83b/?referrer=%2Forganizations%2F%3AorgId%2Fissues%2F%3AgroupId%2Freplays%2F&t=52&t_main=errors`; +const mockButtonHref = `/organizations/${mockOrgSlug}/replays/761104e184c64d439ee1014b72b4d83b/?referrer=%2Forganizations%2F%3AorgId%2Fissues%2F%3AgroupId%2Freplays%2F&t=57&t_main=errors`; // Get replay data with the mocked replay reader params const mockReplay = ReplayReader.factory({ @@ -170,9 +170,9 @@ describe('ReplayClipPreview', () => { // Should be two sliders, one for the scrubber and one for timeline const sliders = screen.getAllByRole('slider', {name: 'Seek slider'}); - // Replay should start at 52000ms because event happened at 62000ms - expect(sliders[0]).toHaveValue('52000'); - expect(sliders[0]).toHaveAttribute('min', '52000'); + // Replay should start at 57000ms because event happened at 62000ms + expect(sliders[0]).toHaveValue('57000'); + expect(sliders[0]).toHaveAttribute('min', '57000'); // End of range should be 5 seconds after at 67000ms expect(sliders[0]).toHaveAttribute('max', '67000'); diff --git a/static/app/components/events/eventReplay/replayClipPreview.tsx b/static/app/components/events/eventReplay/replayClipPreview.tsx index 649382739dcb37..ddbd522fdf6cdd 100644 --- a/static/app/components/events/eventReplay/replayClipPreview.tsx +++ b/static/app/components/events/eventReplay/replayClipPreview.tsx @@ -1,4 +1,4 @@ -import {ComponentProps, Fragment, useMemo, useRef, useState} from 'react'; +import {ComponentProps, useMemo, useRef, useState} from 'react'; import styled from '@emotion/styled'; import screenfull from 'screenfull'; @@ -6,6 +6,7 @@ import {Alert} from 'sentry/components/alert'; import {LinkButton} from 'sentry/components/button'; import ButtonBar from 'sentry/components/buttonBar'; import ErrorBoundary from 'sentry/components/errorBoundary'; +import Panel from 'sentry/components/panels/panel'; import Placeholder from 'sentry/components/placeholder'; import {Flex} from 'sentry/components/profiling/flex'; import MissingReplayAlert from 'sentry/components/replays/alerts/missingReplayAlert'; @@ -46,7 +47,7 @@ type Props = { fullReplayButtonProps?: Partial>; }; -const CLIP_DURATION_BEFORE_EVENT = 10_000; +const CLIP_DURATION_BEFORE_EVENT = 5_000; const CLIP_DURATION_AFTER_EVENT = 5_000; function getReplayAnalyticsStatus({ @@ -100,7 +101,7 @@ function ReplayPreviewPlayer({ }; return ( - + {isFullscreen ? ( @@ -121,7 +122,7 @@ function ReplayPreviewPlayer({ - + @@ -135,7 +136,7 @@ function ReplayPreviewPlayer({ - + ); } @@ -230,9 +231,19 @@ function ReplayClipPreview({ ); } +const PlayerPanel = styled(Panel)` + padding: ${space(3)} ${space(3)} ${space(1.5)}; + margin: 0; + display: flex; + gap: ${space(1)}; + flex-direction: column; + flex-grow: 1; + overflow: hidden; + height: 100%; +`; + const PlayerBreadcrumbContainer = styled(FluidHeight)` position: relative; - height: 100%; `; const PlayerContainer = styled(FluidHeight)` diff --git a/static/app/components/replays/replayPlayPauseButton.tsx b/static/app/components/replays/replayPlayPauseButton.tsx index 8d5cd425fbe371..643c3b524e466a 100644 --- a/static/app/components/replays/replayPlayPauseButton.tsx +++ b/static/app/components/replays/replayPlayPauseButton.tsx @@ -1,9 +1,9 @@ -import {Button} from 'sentry/components/button'; +import {BaseButtonProps, Button} from 'sentry/components/button'; import {useReplayContext} from 'sentry/components/replays/replayContext'; import {IconPause, IconPlay, IconPrevious} from 'sentry/icons'; import {t} from 'sentry/locale'; -function ReplayPlayPauseButton() { +function ReplayPlayPauseButton(props: BaseButtonProps) { const {isFinished, isPlaying, restart, togglePlayPause} = useReplayContext(); return isFinished ? ( @@ -13,6 +13,7 @@ function ReplayPlayPauseButton() { onClick={restart} aria-label={t('Restart Replay')} priority=""primary"" + {...props} /> ) : (